SLOPSHOPPER

drift-fuse

Scores each unattended turn against the task the person asked for with TypeSafe's Jev model, and after consecutive off-task turns redirects or pauses the next…

guardpromptnetwork
A shopper browsing a rack in a slop shop
README

cc-settings

cc-settings gives Claude Code and Codex the Darkroom engineering team's standards, task workflows, safety checks, and proof gates. One installer makes a new machine behave like the rest of the team without replacing personal configuration that cc-settings does not own.

The practical effect is simple: "fix this bug" gets a cause-first debugging workflow, "review my changes" stays read-only, and "ship it" must prove the real build and tests before anything is published.

New here? Install it (5 minutes), run one read-only task, then learn the daily loop. That is enough to get most of the value. Everything after that section is reference you can come back to.

Five-minute first success

1. Install the product you plan to use

Install and authenticate Claude Code, Codex CLI, or both. cc-settings configures those products; it does not install a subscription or account.

2. Install cc-settings

Any platform (Node 18+):

npx darkroom-settings

Every installer flag works: npx darkroom-settings --light --auto-update=on. bunx darkroom-settings is equivalent. The npm package is only a downloader; the configuration always installs from this repository's pinned GitHub origin.

macOS or Linux, without Node:

curl -fsSL https://raw.githubusercontent.com/darkroomengineering/cc-settings/main/setup.sh | bash

Flags go after -s --. Every setup.sh flag works remotely, with no clone or download needed:

curl -fsSL https://raw.githubusercontent.com/darkroomengineering/cc-settings/main/setup.sh | bash -s -- --light --auto-update=on

Windows PowerShell:

powershell -ExecutionPolicy Bypass -c "irm https://raw.githubusercontent.com/darkroomengineering/cc-settings/main/setup.ps1 | iex"

To pass flags remotely on Windows, invoke the downloaded script as a script block:

powershell -ExecutionPolicy Bypass -c "& ([scriptblock]::Create((irm https://raw.githubusercontent.com/darkroomengineering/cc-settings/main/setup.ps1))) --light"

The default target installs both products when codex is on PATH, and Claude Code only otherwise. --light installs a minimal beginner tier; re-run without it to get the full setup. Clone the repository only when you want a source checkout you own:

git clone https://github.com/darkroomengineering/cc-settings.git
cd cc-settings
bash setup.sh --target=both --dry-run
bash setup.sh --target=both

Review all requirements, tiers, system changes, prompts, managed paths, and undo behavior in the installation reference.

3. Restart and inspect

Restart every selected product. In Codex full installs, open /hooks and review the installed hooks once. Claude users can inspect the installed user-scope configuration from any directory:

bun ~/.claude/src/scripts/whats-on.ts

That report shows what is installed and shaping Claude user scope. It does not identify which skill handled a previous prompt or fully resolve project overrides.

4. Run one harmless task

Open a repository and say:

Explain where this project's configuration is loaded. Read only. Cite the files and lines.

The result should name its read-only scope, cite evidence, and leave the working tree unchanged. Your first session shows the expected output, background behavior, follow-up, and recovery.

The daily loop

You do not need to memorize commands. Describe the outcome in plain language and cc-settings picks the matching workflow (a "skill"). Type the skill name only when you want to force a specific one: /name in Claude Code, $name in Codex.

Most days are some path through these steps:

StepSay something likeOr pinWhat you get back
Understand"how does checkout work here?"the explore agentA read-only map with file and line citations
Fix"the login redirect loops on Safari"/fixThe named cause, a reproduction, the smallest fix, and the tests that prove it
Build"add a stats dashboard to the admin page"/buildA GO/NO-GO check, a plan, the implementation, tests, and a review
Check"review my changes"/dr-reviewFindings on the current diff by severity, with no edits
Prove"is this review-ready?"/proof-of-workThe project's real typecheck, tests, lint, and a screenshot for UI work
Ship"ship it"/shipA pushed branch, a PR in the house format, and CI watched until it settles
Pause"done for today"/handoffSaved state; "continue where we left off" resumes it in a new session

Claude Code's built-in /code-review reviews a diff without the Darkroom checklist. /dr-review applies it.

Big tasks split themselves. Work that spans several files, a long chain of tool calls, or security-sensitive code gets handed to focused agents (explore, implement, test, review, security) that run in the background and report back. You can keep talking in the main conversation while they work.

Every workflow for every situation, including audits, triage of a client repo, and adversarial verification, is in the manual. The skill guide says what each one can change and when it stops to ask.

Set up the projects you work in

cc-settings brings the team standards to every repository. Each project can add its own instructions on top.

  • Starting a new Darkroom project: say "new darkroom project" or run /dr-init. It creates the project from the satus or novus starter. The native /init is a different command that only writes a CLAUDE.md.
  • Giving a project its own instructions: put them in AGENTS.md at the project root. Claude Code and Codex both read it. Good content is what an agent cannot learn from the code: the commands to run, the environments, the traps, and the decisions that look wrong but are deliberate.
  • Existing project with a CLAUDE.md: say "migrate to agents.md" or run /cc migrate. Claude Code ignores AGENTS.md while a CLAUDE.md exists, so the two drift apart. The session banner tells you when a project needs this.
  • Planned work on GitHub: link the issue and /handoff posts progress to it, so agents read the issue and update it as they go.

Habits that change results

Small habits make the biggest difference in how well sessions go:

  1. Say the outcome, not the steps. "Fix the flaky checkout test" works better than a list of commands. Add constraints you care about ("read only", "don't touch the API").
  2. One task per session. Run /clear between unrelated tasks. Long, mixed sessions get slower, cost more, and lose track of details.
  3. Save before you stop or risk something. /handoff at the end of a day or a long session; commit before a risky refactor or migration (or use the built-in /rewind), so you can roll back.
  4. Raise effort only for hard turns. The default is tuned for everyday work. Use /effort high or /effort xhigh for hard debugging, audits, or migrations, or add ultrathink to a single message.
  5. Ask for a second opinion when it matters. "Poke holes in this" (/poke-holes) sends independent agents to find and disprove problems. Asking "what could go wrong?" before you commit to a plan gets a risk review.
  6. Read the statusline. It shows context size and usage limits. When context passes about 150K tokens, hand off or compact instead of pushing on.
  7. When something feels off, look before you guess. whats-on.ts shows what is installed and active; troubleshooting covers hook warnings and install health.

Make it better for everyone

cc-settings improves when people feed back what they learn. There are three levels, from quickest to most involved:

  1. Share a lesson. When you hit a gotcha, a convention, or a decision the team should know, say "share this" or run /share-learning. It lands in the shared team-knowledge repository, and every machine sees it right before the command or file edit it applies to.
  2. Keep a workflow that worked. When a session found a good way to do something repeatable, say "turn this session into a skill" or run /harvest. It proposes a skill, rule, or team note built from what actually happened.
  3. Look back weekly. /retro reports what you shipped, how sessions went, and quality trends, and shows which guardrails fired and whether they helped.

To change cc-settings itself, clone it and read the maintainer docs. The short version:

  • Settings live in config/ as fragments that the installer merges into ~/.claude/settings.json. Edit the fragments, never the installed file.
  • A new or reworded skill ships with an eval case in evals/; see skill authoring.
  • Run bun test, bun run typecheck, and bun run lint before pushing.
  • If you only want to suggest something, open an issue with the behavior you saw and what you expected.

Keep it current

  • Update: say "update cc-settings" or run /cc update in a session, or re-run the install command. Restart the product afterwards.
  • Auto-update (macOS): add --auto-update=on to the install command for a daily check at 10:00 local time. --auto-update=off removes it.
  • Check health: npx darkroom-settings --status reports installed versus packaged state.
  • Undo: bun src/setup.ts --rollback from a checkout restores the newest backup. The installation reference covers uninstall.

What cc-settings adds on top of a vanilla install

A fresh Claude Code or Codex install is a capable general assistant with no memory of how this team works. cc-settings installs that memory, plus the checks that make "done" mean the same thing on every machine. The same request behaves differently once it is installed:

You sayVanilla Claude Code or CodexWith cc-settings
"Fix this bug"Edits the first plausible cause and reports doneReproduces first, names the cause before the fix, keeps the change inside the bug's scope, runs the real tests afterwards
"Review my changes"May start editing while it reviewsStays read-only, checks the diff against the team checklist, reports by severity
"Ship it"Pushes whatever is in the treeRuns the repository's own type check, build, tests, and lint, opens the PR in the house style, watches CI
"Build a header component"Writes a component its wayUses the Darkroom starter conventions: CSS modules, no manual memoization, the accessibility and performance rules
git push --force origin mainRuns itA permission rule denies it; a hook blocks rm -rf and other destructive commands before they execute
bun drizzle-kit push on a project with dataRuns itA hook surfaces the team note that this command can truncate production tables
Working in a large repoReads files one at a timeDelegates to focused agents for exploration, implementation, testing, review, and security, on cheaper models
Something worth remembering for the teamLost when the session ends/share-learning posts it to the shared knowledge repo, and later sessions on every machine are reminded of it when it applies

The pieces

  • Standards. AGENTS.md holds the coding standards and guardrails every tool reads; Claude Code gets its copy as CLAUDE-FULL.md, installed as ~/.claude/CLAUDE.md. Twelve topic rules (TypeScript, React, performance, accessibility, security, git, motion, style) load only for the files they cover, and six stack profiles (Next.js, React Router, React Native, Tauri, WebGL, durable agents) add the specifics of each stack.
  • 25 skills. Named workflows selected from ordinary language or pinned with /name in Claude and $name in Codex: fix, build, review, ship, audit, poke-holes, handoff, and the rest. The skill guide lists what each one changes and when it asks.
  • 9 role agents. Planner, explorer, implementer, tester, reviewer, security reviewer, deslopper, orchestrator, and a cross-model verifier. Big work is divided instead of held in one conversation, and each role runs on the model tier its job needs.
  • 22 hooks on 16 lifecycle events. Small programs that run around tool calls, compaction, and session start or end. They block destructive commands and git hook skips, remind about docs before an install, nudge when unreviewed agent output piles up, and inject context the model would otherwise never see. Claude gets the full set; Codex gets the compatible plugin subset and asks you to review it once through /hooks.
  • Model routing. Effort pinned to medium, read-only subagents on Sonnet, planning, decisions and code-editing agents on the session model, bulk or mechanical work and one cross-model review per PR or direct push routed to Codex when the bridge is installed. The statusline shows the usage limits that drive that routing.
  • Connected tools. In Claude, four MCP servers: Context7 for current library docs, a TypeScript code map for call graphs and blast radius, Figma, and Chrome DevTools for screenshots and Lighthouse. Codex gets the Figma server only and reports a missing capability instead of faking the rest.
  • Verbatim compaction. With a TypeSafe key, long sessions compact near the 200K working ceiling by removing stale tool output that Jev scores as no longer needed, while every user and assistant message stays word for word. Without a key, native summary compaction applies. See verbatim compaction with Jev.
  • Team knowledge. A shared repository of decisions, conventions, and gotchas that every machine reads. Notes are posted with /share-learning and surface automatically before the command or file edit they apply to.
  • Ownership and rollback. The installer records what it owns, keeps a backup per product, fingerprints its hooks, and can preview, roll back, or uninstall without touching your own configuration. Read SECURITY.md if a session ever warns about hook trust.

What it leaves alone

Your login and subscription, your permission mode, your personal memory, and any setting the installer does not own. Put your own global instructions in ~/.claude/personal.md: the installed CLAUDE.md imports it, and setup never replaces it (Claude Code only). It does not grant GitHub, Figma, or browser access, and it does not make the two products identical: see Claude Code and Codex for what each host can and cannot do.

Choose where to read next

GoalStart here
Find the workflow for a specific outcomeManual
Choose a skill and understand what it can changeSkill guide
Prove the setup with a harmless first taskYour first session
Install safely and understand every side effectInstallation
Compare Claude Code and Codex behaviorHost parity
Diagnose an installed setupTroubleshooting
Understand the whole systemSystem overview
Understand why advice becomes an enforced gateThe flow
Browse every user, concept, maintainer, and history documentDocumentation index

Why the team maintains it

Written standards, workflows, and proof gates reduce per-machine drift. They also make the codebase more legible to humans: the conventions an agent needs are the same debt the team owes its engineers.

darkroom.engineering | MIT

Source 1 files
hooks/fuse.ts 309 lines
1// drift-fuse — a function-hook plugin that watches an unattended run for
2// drift from the task the person asked for. It keeps the last prompt a person
3// typed as the task contract, records what each turn did (files edited, Bash
4// commands, tool names) and, when the turn ends, asks TypeSafe's Jev model one
5// yes/no question: did this turn serve that task? Two off-task turns in a row
6// (configurable) trip the fuse. A tripped fuse redirects the next prompt that
7// no person typed (a loop wakeup, a routine, a task notification) with a
8// context line naming the drift, or drops it when `onTrip` is "pause"; a
9// prompt a person types always passes and resets the contract. Fail-open:
10// without a TYPESAFE_API_KEY, in a project that has not set
11// CC_TYPESAFE_PROJECT=1, or on any Jev failure, nothing is scored. See
12// docs/hooks-reference.md "Function hooks (early access)".
13//
14// PRIVACY: in a project that opted in, the contract prompt, the turn's file
15// paths and Bash command heads, and the head of the answer leave the machine
16// for each scored turn; in any other project nothing does. By default only
17// turns started by a non-person prompt are scored (`scope: "unattended"`);
18// `scope: "all"` scores every main-loop turn.
19//
20// Deliberately has NO runtime imports (`import type` erases), so the pure
21// functions here run under `bun test` without resolving 'claude-code'.
22import type {
23  On,
24  PluginOptions,
25  PromptOrigin,
26  PromptSubmitInput,
27  Register,
28  ToolCallInput,
29  TurnCompleteInput,
30  TurnStartInput,
31} from "claude-code";
32
33export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
34export const JEV_MODEL = "jev-latest";
35export const JEV_TIMEOUT_MS = 2500;
36export const JEV_INSTRUCTIONS =
37  "The actions and the answer of this turn serve the task the user asked for. Reading, searching, verifying, and fixing what the task directly needs all count as serving it; work on files or features the task did not ask for, or a new goal the user never stated, does not.";
38export const JEV_CRITERIA = {
39  true: "The turn stayed on the task, including its direct prerequisites and verification.",
40  false: "The turn spent its effort on something the task did not ask for.",
41} as const;
42
43const DEFAULTS = {
44  driftBelow: 0.35,
45  tripAfter: 2,
46  onTrip: "redirect",
47  scope: "unattended",
48} as const;
49
50export type FuseConfig = {
51  /** A turn whose on-task probability is below this counts as drift. */
52  driftBelow: number;
53  /** Consecutive drift turns that trip the fuse. */
54  tripAfter: number;
55  /** What a tripped fuse does to the next non-person prompt. */
56  onTrip: "redirect" | "pause";
57  /** Which main-loop turns are scored. */
58  scope: "unattended" | "all";
59};
60
61function optionNumber(options: PluginOptions, key: string, fallback: number): number {
62  const value = options[key];
63  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
64}
65
66function optionOneOf<T extends string>(options: PluginOptions, key: string, allowed: readonly T[], fallback: T): T {
67  const value = options[key];
68  return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;
69}
70
71/** Reads the plugin's `userConfig` values; anything missing takes the defaults. */
72export function resolveFuseConfig(options: PluginOptions): FuseConfig {
73  return {
74    driftBelow: optionNumber(options, "driftBelow", DEFAULTS.driftBelow),
75    tripAfter: Math.max(1, Math.floor(optionNumber(options, "tripAfter", DEFAULTS.tripAfter))),
76    onTrip: optionOneOf(options, "onTrip", ["redirect", "pause"], DEFAULTS.onTrip),
77    scope: optionOneOf(options, "scope", ["unattended", "all"], DEFAULTS.scope),
78  };
79}
80
81/** A person at a keyboard or a phone; everything else is a machine's prompt. */
82export function isPersonOrigin(origin: PromptOrigin | undefined): boolean {
83  return origin?.kind === "composer" || origin?.kind === "bridge";
84}
85
86const CONTRACT_MAX = 2000;
87
88/**
89 * Pure: the contract after a person's prompt. A prompt long enough to name a
90 * task replaces it; a short one ("fix billing", "ok", `/audit`) is appended,
91 * so a task switch in three words still reaches the judge and an
92 * acknowledgement never becomes the whole task. Pasted tool output (`<...>`)
93 * changes nothing.
94 */
95export function nextContract(contract: string, text: string): string {
96  const t = text.trim();
97  if (t.length === 0 || t.startsWith("<")) return contract;
98  if (t.length >= 20 && !t.startsWith("/")) return t.slice(0, CONTRACT_MAX);
99  const joined = contract ? `${contract}\nthen: ${t}` : t;
100  return joined.length > CONTRACT_MAX ? joined.slice(joined.length - CONTRACT_MAX) : joined;
101}
102
103const ANSWER_MAX = 1200;
104const COMMAND_MAX = 120;
105const ACTIONS_MAX = 40;
106
107/** One line per tool call, the way Jev reads it: `Edit /path`, `Bash: cmd`. */
108export function describeToolCall(event: ToolCallInput): string | undefined {
109  const e = event as unknown as { tool: string; file_path?: unknown; command?: unknown; notebook_path?: unknown };
110  const path = typeof e.file_path === "string" ? e.file_path : typeof e.notebook_path === "string" ? e.notebook_path : undefined;
111  if (path && (e.tool === "Edit" || e.tool === "Write" || e.tool === "NotebookEdit")) return `${e.tool} ${path}`;
112  if (e.tool === "Bash" && typeof e.command === "string") return `Bash: ${e.command.replace(/\s+/g, " ").slice(0, COMMAND_MAX)}`;
113  return undefined;
114}
115
116export type TurnRecord = {
117  actions: string[];
118  /** Tool calls the plugin saw, including reads it did not describe. */
119  toolCalls: number;
120};
121
122/** The state Jev scores: the contract, what the turn did, what it said. */
123export function scoringState(contract: string, turn: TurnRecord, answer: string): Record<string, string> {
124  return {
125    task: contract.slice(0, CONTRACT_MAX),
126    actions: turn.actions.length > 0 ? turn.actions.join("\n") : `(${turn.toolCalls} read-only tool calls)`,
127    answer: answer.slice(0, ANSWER_MAX),
128  };
129}
130
131/** The request body for one scoring call. */
132export function scoringRequest(state: Record<string, string>): string {
133  return JSON.stringify({
134    model: JEV_MODEL,
135    state,
136    questions: { on_task: { type: "noul", instructions: JEV_INSTRUCTIONS, criteria: JEV_CRITERIA } },
137  });
138}
139
140/** The on-task probability from a response body, or null when it is not one. */
141export function parseOnTask(text: string): number | null {
142  try {
143    const body = JSON.parse(text) as { answers?: { on_task?: { noul?: unknown } } };
144    const p = body?.answers?.on_task?.noul;
145    return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 ? p : null;
146  } catch {
147    return null;
148  }
149}
150
151export type FuseState = {
152  /** Consecutive drift turns so far. */
153  strikes: number;
154  tripped: boolean;
155};
156
157/**
158 * Pure: fold one scored turn into the fuse. A turn at or above `driftBelow`
159 * clears the strikes; one below adds a strike, and `tripAfter` strikes trip.
160 */
161export function foldTurn(state: FuseState, onTask: number, config: FuseConfig): FuseState {
162  if (onTask >= config.driftBelow) return { strikes: 0, tripped: state.tripped };
163  const strikes = state.strikes + 1;
164  return { strikes, tripped: state.tripped || strikes >= config.tripAfter };
165}
166
167/** The line a tripped fuse puts in front of the model on the next prompt. */
168export function redirectLine(contract: string, strikes: number, lastActions: readonly string[]): string {
169  const head = contract.replace(/\s+/g, " ").slice(0, 160);
170  const did = lastActions.length > 0 ? ` Last turn: ${lastActions.slice(0, 5).join("; ")}.` : "";
171  return (
172    `drift-fuse: the last ${strikes} turns drifted from the task the user asked for ("${head}").${did} ` +
173    `Return to that task, or stop and ask the user before continuing with anything else.`
174  );
175}
176
177/** The TypeSafe key the settings `env` block holds, or undefined. */
178export function settingsTypesafeKey(settings: Readonly<Record<string, unknown>>): string | undefined {
179  const env = settings.env;
180  if (!env || typeof env !== "object") return undefined;
181  const value = (env as Record<string, unknown>).TYPESAFE_API_KEY;
182  return typeof value === "string" && value.length > 0 ? value : undefined;
183}
184
185type Engine = {
186  env: { get: (name: string) => Promise<string | undefined> };
187  settings: { read: () => Promise<Readonly<Record<string, unknown>>> };
188  http: { fetch: (url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<{ ok: boolean; text: string }> };
189  clock: { sleep: (ms: number) => Promise<void> };
190};
191
192/** True when this project (or the user, globally) set CC_TYPESAFE_PROJECT=1 in
193 *  the process env or in any settings source's `env` block; `$.settings.read()`
194 *  merges the project's `.claude/settings.json` and `settings.local.json`. */
195export async function projectOptedIn($: Pick<Engine, "env" | "settings">): Promise<boolean> {
196  if ((await $.env.get("CC_TYPESAFE_PROJECT")) === "1") return true;
197  const env = (await $.settings.read()).env;
198  return !!env && typeof env === "object" && (env as Record<string, unknown>).CC_TYPESAFE_PROJECT === "1";
199}
200
201/** The key from the process env, else from settings; undefined when unset and
202 *  undefined when the project has not opted in, so nothing is scored or sent. */
203export async function typesafeKey($: Pick<Engine, "env" | "settings">): Promise<string | undefined> {
204  if (!(await projectOptedIn($))) return undefined;
205  const fromEnv = await $.env.get("TYPESAFE_API_KEY");
206  if (fromEnv) return fromEnv;
207  return settingsTypesafeKey(await $.settings.read());
208}
209
210/** One scoring call through the host; null on any failure or past the timeout. */
211export async function scoreTurn($: Engine, key: string, state: Record<string, string>): Promise<number | null> {
212  const call = $.http
213    .fetch(JEV_ENDPOINT, {
214      method: "POST",
215      headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
216      body: scoringRequest(state),
217    })
218    .then((resp) => (resp.ok ? parseOnTask(resp.text) : null))
219    .catch(() => null);
220  const late = $.clock.sleep(JEV_TIMEOUT_MS).then(() => null);
221  return Promise.race([call, late]);
222}
223
224// $ is never bound to a name: `claude plugin validate` requires every call on
225// it to read as `$.noun.event(...)` at the call site.
226export const register: Register = (on: On, options: PluginOptions) => {
227  const config = resolveFuseConfig(options);
228  let contract = "";
229  // Bumped by every person's prompt; a turn scored against an older contract
230  // than the current one is discarded (the person moved on mid-turn).
231  let contractGeneration = 0;
232  let turnContract = "";
233  let turnGeneration = 0;
234  let fuse: FuseState = { strikes: 0, tripped: false };
235  let lastActions: string[] = [];
236  // The origin of the prompt whose turn is about to start; set at
237  // prompt.submit for an idle session, read at turn.start.
238  let pendingOrigin: PromptOrigin | undefined;
239  let turnUnattended = false;
240  let turn: TurnRecord = { actions: [], toolCalls: 0 };
241
242  on("prompt.submit", ($, event: PromptSubmitInput, next) => {
243    if (isPersonOrigin(event.origin)) {
244      // A person redirecting is never drift: the contract follows them.
245      contract = nextContract(contract, event.text);
246      contractGeneration += 1;
247      fuse = { strikes: 0, tripped: false };
248      pendingOrigin = event.origin;
249      return next(event);
250    }
251    pendingOrigin = event.origin;
252    if (!fuse.tripped) return next(event);
253    const line = redirectLine(contract, fuse.strikes, lastActions);
254    fuse = { strikes: 0, tripped: false };
255    if (config.onTrip === "pause") {
256      $.ui.log(`drift-fuse: paused a ${event.origin.kind} prompt after ${config.tripAfter} off-task turns`);
257      return { drop: line };
258    }
259    $.ui.log(`drift-fuse: redirected a ${event.origin.kind} prompt after ${config.tripAfter} off-task turns`);
260    return next({ ...event, context: [...(event.context ?? []), line] });
261  });
262
263  on("turn.start", ($, event: TurnStartInput, next) => {
264    turnUnattended = !isPersonOrigin(pendingOrigin);
265    pendingOrigin = undefined;
266    turnContract = contract;
267    turnGeneration = contractGeneration;
268    turn = { actions: [], toolCalls: 0 };
269    return next(event);
270  });
271
272  on("tool.call", ($, event: ToolCallInput, next) => {
273    if (!event.agentId) {
274      turn.toolCalls += 1;
275      const line = describeToolCall(event);
276      if (line && turn.actions.length < ACTIONS_MAX) turn.actions.push(line);
277    }
278    return next(event);
279  });
280
281  on("turn.complete", async ($, event: TurnCompleteInput, next) => {
282    const scored =
283      !event.agentId && !event.isAborted && turnContract && turn.toolCalls > 0 && (config.scope === "all" || turnUnattended);
284    if (scored) {
285      try {
286        const key = await typesafeKey($);
287        if (key) {
288          const onTask = await scoreTurn($, key, scoringState(turnContract, turn, event.answer));
289          // A person's prompt during the turn replaced the contract; this
290          // turn served the old one and must not count against the new.
291          if (onTask !== null && turnGeneration === contractGeneration) {
292            const before = fuse;
293            fuse = foldTurn(fuse, onTask, config);
294            lastActions = turn.actions;
295            if (fuse.tripped && !before.tripped) {
296              $.ui.log(`drift-fuse: tripped after ${fuse.strikes} off-task turns (on-task ${onTask.toFixed(2)})`);
297            } else if (fuse.strikes > 0) {
298              $.ui.log(`drift-fuse: off-task turn ${fuse.strikes}/${config.tripAfter} (on-task ${onTask.toFixed(2)})`, { to: "debug" });
299            }
300          }
301        }
302      } catch (error) {
303        $.ui.log(`drift-fuse: skipped (${error instanceof Error ? error.message : String(error)})`, { to: "debug" });
304      }
305    }
306    return next(event);
307  });
308};
309