Keeps a ledger of what you asked for and counts it done only on evidence: claims stay pale until a read-back confirms them, bare SQL UPDATE or DELETE writes…

A Claude Code mod that keeps track of what you asked for and what was proven done, and holds risky SQL writes for your answer.
witness is a plugin of function hooks. It sits in the session beside you, keeps a ledger of your asks, and counts an ask as done only when there is evidence: a read-back of what was written, or your own words. It draws one line above the prompt with a small companion beside it.
asks n/m, where n is the number witnessed. /undone lists every ask as witnessed, pale (claimed but not proven) or open. Standing instructions ("explain as we go") are not recorded. Work that spans several sessions is listed apart as builds N and is never counted. Text you quote or paste is not read as an ask. At the end of a watch, an open ask nobody claimed carries into the next one once, shown apart as carried N.sed -i replacement), the read-back must show it: a grep that still finds the old text leaves the claim pale and the print calls it contradicted (a test run still counts as a read-back, as it shows no file text). A subagent's final report is a claim too: it stays pale until the main session reads back what the report rests on, and a report is never evidence for the confirm tool.execute_sql hold. An execute_sql UPDATE or DELETE that has no RETURNING clause is held (any MCP tool whose name ends __execute_sql, or the tools named in sqlTools), and you choose: add RETURNING, let it through once, or cancel. A headless run (claude -p) or a subagent has nobody to ask, so there the write is refused. witness never approves a call past another guard.confirm tool and must cite evidence: a tool result already in the session, or your words. It can mark an ask dropped only on your words. A close paraphrase of an ask is accepted when exactly one live ask clearly matches. If a turn calls something done without proof, the next prompt carries one short line asking the agent to confirm it./wrap writes a Witness print into the open session log: asks witnessed, pale and open, writes held, friction, notes taken, and hook or skill candidates. It then hands the print to the main session, which settles what is done and says what each open line waits on, without starting new work. The close command (default /close) writes the same print before it runs. When no session log is open at the close (the project keeps none, or the session opened without one), the whole print, notes included, is attached to the close prompt instead.body) at the right of the band, facing the line. Its colour deepens as more of the session's claims are proved. A chime of three bells hangs at its back, an hour of active work each, filling from the bottom with a half bell for thirty minutes; * barnacles on its shell are friction that recurs across sessions (a cancelled or refused write, a call that keeps failing, an MCP tool's error; never the edits of a file you are building), and /barnacles lists what they record and scrubs them off; its eye turns amber in a repository whose push would start a metered build, and the whole creature turns red while a write is held, while a write is refused by another guard (10 seconds, then the rim stays amber until your next prompt), while a statement sends back far more rows than it named (the haemorrhage), when Claude's confirm tool cites evidence that does not check out (CITATION FAILED, 10 seconds red then amber, once per burst), and when another live session wrote the same file within five minutes of your own write (COLLISION, 10 seconds red then amber, once per burst; an older shared file stays the ordinary amber overlap). Part of the shell blushes red for any other irreversible call, by who can undo its effects: the rim alone when you can undo it yourself, the rim and the walls when undoing it will not get everything back, the rim, walls and top when nobody can (a DROP or an unpinned bulk write, a force push, a sent email; a plain git push depends on whether the repo is metered), and the bubble says which and how. A blush lights as the call goes out and stays 8 seconds after it. For one moment at session start the whole creature shows red, a lamp test that proves the red works. The blush says "not checked" for effects it has no register for (builds, webhooks, triggers outside the tables you list). A ◈ gem on the shell is a hook (green) or skill (blue) candidate you have not settled yet. A candidate is only minted if nothing already covers it (the side pass is shown the repo's scripts/ and the headings of your CLAUDE.md files, and must say why nothing listed does the job) and if it recurs in at least two sessions, since one session's repeats (and one parallel message of failures) are recorded but not minted; recurring repair pairs likewise need two sessions, and a routine that works can count in two sessions through the sessions' routine heads; gems and barnacles share four cells. The bells, the barnacles and the gems wear their own inks. /wear dresses it in a costume.witness-band. A mod folded beneath the witness can return a host keyed witness-guest holding its own drawing first and what stood beneath it second; the witness lifts the guest out (never reading its words as a heads-up note) and draws it: from 104 body columns in a left column of 38.2%, with the band laid out in the rest; narrower, above the band at full width. The engine's own node stays at the band root, under no sized Box. While a guest from a mod that names its drawing with the ammonite- key prefix stands narrow, the companion wears the devil horns for that draw only.From a terminal:
claude plugin marketplace add https://github.com/iniphi/witness
claude plugin install witness@iniphi-witness
Or at the prompt of a terminal session:
/plugin install witness --marketplace iniphi/witness
Answer y to add the marketplace and choose a scope. Install it once. Two copies loaded in one session would run every hook twice.
Set these with /config or when you install. Every key is optional.
| Key | Default | What it does |
|---|---|---|
body | naut | The companion's body: naut (the nautilus, Naut) or phial (round-bottom flask). phi, the nautilus's older name, is still accepted and means the same body. |
watchHold | false | At session start, and after five idle minutes, ask before the first prompt goes through. |
ticketScript | empty | A script that prints a status ticket as JSON, as a path relative to the session folder or absolute. If it is empty and no ticket script sits beside the mod, there is no ticket, and the line shows the companion's own counts. The mod looks beside itself from the folder Claude Code reports for it, or from its own file when that is blank; if it has nowhere to look from, the line shows estate: ? rather than nothing. |
watchScript | empty | A script that reads a work board for the watch and its poll. If it is empty and none is found, no board is polled. |
writerCalls | empty | SQL functions that a SELECT calls to write, written as schema.name, where a trailing * matches any suffix (for example app.finish_task, app.log_*). These count as writes. With none listed, a SELECT is a read. |
sqlTools | mcp__*__execute_sql | The database tools whose queries the hold judges, as a comma-separated list of tool names where * matches any run of characters. The default matches any MCP tool whose name ends __execute_sql, a name several database servers share. Set it if your server names its query tool otherwise. |
tableSchemas | public | Schemas whose schema.table names in a subagent's report count as targets that report named. Add your own, for example public, app. |
person | you | How the print and the confirm tool name you. The default prints "on your words", and the model reads "the user". |
sessionsDir | .claude/sessions | Where session logs live, relative to the session folder. |
goalsHeading | ## Goals | The session log heading whose checkbox items are goals. The section ends at the next heading of the same level. |
closeCommands | /close | Commands that close a session, separated by commas. The print is written before they run. |
sonar | auto | Heartbeats between the sessions running on this machine, overlap alerts and /hand. auto turns it on only where a ticket script is found; on and off force it. It writes small files under ~/.claude/state/witness-sonar (see Footprint). |
pointInTimeRecovery | false | Whether your database can restore lost rows by a point-in-time restore. On: a DROP, TRUNCATE or unpinned bulk write blushes the rim and walls (rung 2). Off or unknown: the top too (rung 3), because unknown fails closed. |
haemorrhageRows | 25 | An UPDATE or DELETE with RETURNING that sends back more rows than it named, and more than this, turns the whole creature red (HAEMORRHAGE). Display only. |
lampTest | true | Show the whole creature red for 1.5 seconds at session start, to prove the red channel. |
effectTables | empty | Tables whose writes can reach outside the database (a trigger that calls a webhook or a build), comma-separated, * anywhere. A write to one blushes at least the rim and walls. Empty: the witness says triggers on a written table are not in effectTables. |
typedHands | auto | Whether a /hand you typed in another session starts work in the receiving session without an Enter. auto allows it only where a ticket script is found; start always; wait never. A hand is recognised by a plugin stamp that Claude Code passes on as the sender's own claim, so any installed plugin could claim it; wait is the safe choice, and is what auto gives you without a ticket script. |
/witness opens a pane in which the companion introduces itself: the creature (the compact one the band draws), a readout of what it is watching in this session, what is new in 1.3, and the commands./undone lists every ask in this watch: witnessed, pale or open./wrap ends the watch, writes the print into the session log and hands it to the main session to settle./tackle puts a prompt in the prompt box for a run over the undone asks. You read it and decide whether to send it. It never sends on its own./barnacles opens a pane with what each barnacle on the shell records, and treat and wash beside each. Treat puts the barnacle's evidence in your prompt box for Claude to propose one fix; once you accept it and it lands, Claude's treated call takes the barnacle off (only for one you put in treatment, and only after something was written). Wash takes it off with no fix, for a false alarm; wash all washes every one. Either way, the moment the same friction is recorded again it is back, unspoken, so you hear it again: the fix or the wash did not hold. When a hook or skill candidate waits, one line says so and points to /jewels. Under the barnacles the pane lists the project's repair pairs: a call that failed, the call that cured it, what changed between them and roughly what the failed attempts cost. A failure cured in two or more projects becomes one hook candidate for managed settings, named with the projects it was seen in, proposed once across every project on the machine./jewels opens a pane with every hook or skill candidate you have not settled, newest first and in full: a ◈ gem (green for a hook, blue for a skill, as on the shell), the title, why it was proposed, the evidence, when it was seen and whether it has been filed to the candidates file. Under each, take puts the candidate in your prompt box for Claude to propose how to build it (never over a draft; the gem goes off only once the box took it) and dismiss takes it off with no build; With two or more listed, calibrate all puts every listed jewel in your prompt box as one numbered batch ask (kind, title, why, evidence) for Claude to give a read on, check adversarially and bring rulings in batches; the jewels are taken only once the box took it, and never over a draft. There is no dismiss all: a bulk dismissal is permanent and skipped the calibration, so the bulk path is calibrate all. The list is read fresh from the store each time, so a candidate another session in the project proposed shows at once. Jewels are per project: another project's surface as gems on the shell when a session opens in that project, and the pane lists this project's only. With no surface to place a pane, /jewels answers with the same content as text. A new install shows at most three new jewels a day for its first week; the rest are queued ("N more queued (first-week budget)") and shown on later days, never dropped. A jewel from a single session is minted only when it names a gap (a gate that does not run, or a check rebuilt by hand that no script holds). Filing candidates at /wrap does not take a gem off; settling does. The page ends with Settled: built n, taken m, dismissed o. calibrate all settles every listed jewel as taken, so once the batch is ruled, record each ruling (1.12): /jewels taken lists the taken jewels, numbered, with their state and key; /jewels built 2 3 and /jewels dismissed 4 5 (numbers or keys) record it on top of the taken settle. Only a taken jewel is ruled, once: the same ruling again changes nothing, a ruling is never changed, and a jewel that is not taken is refused. A jewel ruled dismissed joins the dismissed shapes the generator is shown; a built one does not (it was acted on). A line you strike (...) in the candidates file dismisses that jewel at the next session start (1.14), when the jewel is still unsettled; a taken one is ruled with /jewels built or /jewels dismissed instead./reds lists this project's last 20 safelight events across sessions, newest first: when, which session, the channel (the lamp test, a blush, a hold, a refusal beneath, a haemorrhage, a failed citation, a collision), amber or red, why it lit, the fix, and how it ended. The print at /wrap and before a close carries a short Safelight section when the session had a red event. A blush that "you can undo" is amber; a refused write is whole red for 10 seconds, then amber until your next prompt, once per burst./pods (sonar on) lists the other live sessions on this machine: what each is on, when it last beat, and any file you both wrote. The one line shows pods N, with !K in the warning colour while K files overlap. When another live session rewrites a Notion page this session fetched, after the fetch, you are told once (STALE: re-read it before working from it), and the session that rewrote it is told whose read it made stale; a stale read is listed in /pods but not counted in !K. An overlap is reported after the fact, never before: each session beats and reads the others every 30 seconds, so you hear of a shared write up to about a minute after it, and two writes to one file inside that gap both land before either session is told. The sonar does not lock, block or prevent a write. It tells you where to look./hand <number|name> <what to do> (sonar on) hands work to another live session. A hand you type waits in that session's prompt box for your Enter, or, where typedHands allows it, starts that session's turn once it is idle. A hand Claude writes (its hand tool) lands in that session's prompt box and waits for your Enter; it never starts work on its own and never goes over a draft./wear razor, /wear compass, /wear horns, /wear devil dress the companion for the session; /wear none undresses it. A costume is how a later companion plugin shows which role is speaking, and another plugin can set one through the same command./dismiss command. While witness is showing a notice that can be dismissed, a 0: Dismiss button sits at its foot, bound to the 0 key. A held write is never dismissed, only answered. When more than one notice is waiting, <n/m> shows your place in the queue, and its < and > are buttons: click > for the next notice and < for the one before, without dismissing any (including Claude Code's own note). With the band focused (ctrl+x tab), Enter presses the one the focus is on. While a write is held it stays in the bubble and there is no pager. A digit typed into an empty prompt presses the band button that has it, so start a message with a word while the 0: Dismiss button shows.What it reads:
sessionsDir;ticketScript and watchScript, if they are set or found;What it writes:
~/.claude/state/witness-usage/<day>/<session>.json: the token counts the API reported for each of witness's own side passes and each model turn. Nothing is written if neither USERPROFILE nor HOME is set./wrap and at the close command.reports/witness-candidates.md when the session folder has a reports/ folder, and to .claude/witness-candidates.md otherwise.routines:<project>:<session id>: up to 60 call HEADS with a count of calls and of turns, for example git commit, an MCP tool's name, or Edit .ts. A routines slot holds no arguments, no paths, no file contents, no SQL and no prompt text; it lets a hook or skill candidate be seen to recur across two sessions. A slot untouched for a day is folded into a bounded archive (the newest 20 sessions) and deleted.~/.claude/state/witness-sonar/<day>/<session>.json, this session's heartbeat every 30 seconds, holding the folder, up to three of its open asks (one line each), the asks count, the paths of the files it wrote in the last 30 minutes, and the ids of up to 20 Notion pages it fetched (no titles or contents); and, when a hand cannot be delivered as a message, ~/.claude/state/witness-sonar/hands/<session>/<hand>.json. Nothing prunes old day folders yet. A hand that arrives as a file is never treated as typed by you: it only waits in the prompt box. Claude's writes into that folder (its file tools, and a shell command that writes) are refused in every session, so the heartbeats cannot be tampered with from inside Claude; reading them is allowed.What it sends to a model: the side passes are extract, match, candidates and barnacles. They run on Haiku at low effort. Each pass sees only what it is given: the prompt, with quoted and pasted text cut out, and short excerpts of answers and tool output. The candidates pass also sees the names and first comment line of the scripts in the session folder's scripts/, and the #/## headings of the project and user CLAUDE.md files, so it can tell what already exists. No other conversation content is sent. The only text witness adds to the main session's context is the one-line unproved-done note, the /wrap print, and a hand from another session (submitted when you typed it there, otherwise left in the prompt box for you to send).
witness's own spend is its Haiku side passes, and what witness measures is tokens. The comparison here is against new material: the input, output and cache writes the sessions produced, with cache reads left out. On the author's machine over five days of ordinary use (2026-10-07 to 2026-10-11, read at about 10:30 UTC on the last day), the sessions produced about 42 million tokens of new material (42.6 million), and witness's side passes were about 1.86 million of them: about 4.4%, or 4.6% against the sessions' own new material alone. Per session the side passes used a median of about 52,000 tokens (mean about 50,000, range 564 to 143,000, over the 37 sessions that ran one). The 2.07 billion cache reads those sessions also made are not counted. Per call, the extract pass uses about 1,250 tokens, match about 1,700, candidates about 10,000 and barnacles about 1,000.
Any dollar figure is an approximation. Priced at Anthropic's API list prices (as of 2026-10-08), the same five days come to about $0.28 for witness's side passes against about $864 for the sessions' own model turns. These are computed, not billed: no bill has been checked against either figure, so read them as a scale, not a cost. Every figure here is summed from the usage files described under Footprint, which you can read for your own machine; the author keeps monitoring them.
The usage file records every model turn's tokens beside the side passes, so a session's whole spend can be read next to witness's share. Those turn figures are the session's cost, not witness's. witness does not price the work of subagents a session spawns: their tokens are recorded only as the host reports them. Since 1.1 a subagent's final report is a claim in the ledger, pale until the main session reads back what the report rests on.
claude plugin validate <path to witness>
claude plugin test <path to witness>
The pure modules in hooks/ each have a *.test.ts beside them. hooks/register.tsx is the hooks module, the only file that calls the engine.
Issues and pull requests are welcome. witness is developed in a separate source repository and published here at each release, so the maintainer applies an accepted pull request there, with credit in the CHANGELOG, rather than merging it here.
To report a vulnerability, see SECURITY.md. Please do not open a public issue for one.
MIT. Copyright (c) 2026 Bradley Higginson. See LICENSE.
hooks/register.tsx 2808 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type {
5 Activity,
6 Ask,
7 Barnacle,
8 Beat,
9 BoardRow,
10 Blush,
11 Body,
12 Candidate,
13 Costume,
14 Friction,
15 Haemorrhage,
16 Hand,
17 Heard,
18 Hold,
19 Ledger,
20 LogBinding,
21 NoticeQueue,
22 Observed,
23 OpenFailure,
24 Overlap,
25 PodState,
26 PodWrite,
27 RepairPair,
28 SonarView,
29 Spoken,
30 Ticket,
31 UsagePass,
32 UsageRow,
33 Watch,
34 WatchInfo,
35} from '../types'
36import {
37 applyMatches,
38 applyTriage,
39 carryOver,
40 counts,
41 dropAsk,
42 extractPrompt,
43 matchPrompt,
44 MAX_PREVIOUS_CHARS,
45 mergeGoals,
46 nm,
47 paneRows,
48 parseExtraction,
49 parseGoals,
50 parseTriage,
51 parseMatch,
52 printSection,
53 resolveStates,
54 seedCarried,
55} from './asks'
56import { isIdle, touch } from './bells'
57import {
58 ESTATE_TACKLE_SKILL,
59 NO_ADAPTERS,
60 TICKET_SCRIPT,
61 WATCH_SCRIPT,
62 effectTablePattern,
63 personRef,
64 isSqlTool,
65 readConfig,
66 sqlToolPattern,
67 rootFromModuleUrl,
68 scriptCandidates,
69 sonarOn,
70 typedHandsStart,
71 writerPattern,
72} from './config'
73import type { Adapters, Config } from './config'
74import {
75 afterScrub,
76 asScrubbed,
77 frictionFrom,
78 markSpoken,
79 mergeBarnacles,
80 nextToSpeak,
81 noteFriction,
82 parseRecur,
83 realFriction,
84 recurPrompt,
85 regrown,
86 scrub,
87 stampScrub,
88 unscrub,
89} from './barnacles'
90import type { RecentCall } from './barnacles'
91import { bodyFromOption } from './body'
92import { parseCostume } from './sprites'
93import {
94 CONFIRM_TOOL,
95 REPORT_TOOLS,
96 confirmDescription,
97 confirmSchema,
98 confirmAsks,
99 confirmReport,
100 hear,
101 inputText,
102 observe,
103 parseItems,
104 trimResult,
105 unprovedNote,
106} from './evidence'
107import { writeMarks } from './content'
108import {
109 CANDIDATE_MIN_NEW_CALLS,
110 HEADS_UP,
111 INSTALLED_GUARDS,
112 MAX_SCRIPTS,
113 appendCandidates,
114 callDigest,
115 candidatesPath,
116 candidatesPrompt,
117 candidatesSection,
118 markFiled,
119 mdHeadings,
120 mergeCandidates,
121 mergeCandidatesByKey,
122 retireStrays,
123 notesSection,
124 noteHeard,
125 noteSpoken,
126 parseCandidates,
127 scriptSummary,
128 settleCandidatesIn,
129 shouldScan,
130 struckKeys,
131 sessionTag,
132 tagFriction,
133 takePrompt,
134 unsettled,
135} from './notes'
136import type { HeadingNote, ScriptNote } from './notes'
137import { asCarrySlot, carryPrefix, carrySlot, carrySlotKey, mergeCarried, ownLeftovers, takeable } from './carry'
138import {
139 archivable,
140 asFrictionList,
141 asFrictionSlot,
142 frictionPrefix,
143 frictionSlot,
144 frictionSlotKey,
145 mergeFriction,
146 ownFriction,
147 stampSession,
148} from './frictionslots'
149import {
150 asRoutineArchive,
151 asRoutineSlot,
152 foldRoutines,
153 noteRoutine,
154 routineArchivable,
155 routineSlot,
156 routinesArchiveKey,
157 routinesPrefix,
158 routinesSlotKey,
159 sharedRoutines,
160} from './routines'
161import type { LiveRoutine, RoutineSlot } from './routines'
162import {
163 FIX,
164 REDS_SLOTS,
165 asRedSlot,
166 closeRed,
167 openRed,
168 redSlot,
169 redsList,
170 redsPrefix,
171 redsSection,
172 redsSlotKey,
173 redsStale,
174} from './redlog'
175import type { OpenRed, RedChannel, RedEvent, RedHow, RedSlot } from './redlog'
176import { podsTree } from './pods'
177import { ABOUT_TITLE, aboutModel, aboutReply, versionOf } from './about'
178import type { AboutModel } from './about'
179import { aboutTree } from './aboutpane'
180import { GUEST_MIN_BODY, GUEST_OWNER_PREFIX, bandTree, barnaclesTree, beneathText, paneTree, splitBeneath } from './render'
181import { INSTALL_KEY, applyBudget, asFirstScanAt, configuredHooks, dismissedTitles } from './charter'
182import { calibrateAllText, jewelsList, jewelsPointer, jewelsText, JEWELS_TITLE } from './jewels'
183import { jewelsTree } from './jewelspane'
184import { parseRuling, ruleIn, rulingText } from './ruling'
185import { addPairs, asPairs, pairCandidates, pairsSection } from './immunity'
186import { estateCandidates } from './estate'
187import {
188 TREATED_DESCRIPTION,
189 TREATED_SCHEMA,
190 TREATED_TOOL,
191 isTreatPrompt,
192 markTreating,
193 parseTreated,
194 treatPrompt,
195 treatVerdict,
196 treatedText,
197} from './treat'
198import { age, cure, noteFailure } from './repair'
199import {
200 BEAT_MS,
201 HAND_TAG,
202 HAND_TEXT_MAX,
203 LIVE_MS,
204 beatDays,
205 beatFile,
206 beatPath,
207 findPod,
208 freshOverlaps,
209 handAction,
210 handEnvelope,
211 handFile,
212 handPath,
213 handPrompt,
214 handsDir,
215 isForgedHand,
216 isWitnessHand,
217 livePods,
218 makeBeat,
219 newcomers,
220 originLabel,
221 overlaps,
222 parseBeat,
223 parseHand,
224 parseHandArgs,
225 parseHandFile,
226 podLabel,
227 recentWrites,
228 sonarDir,
229 touchesSonar,
230 unreadHand,
231} from './sonar'
232import { bandPods, isCounted, newcomerText, overlapText, podRows } from './podview'
233import { intrusions, noteReads, recentTargets, staleReads, storeOverlaps } from './territory'
234import { needsHold, withReturning } from './sql'
235import { citationFailure, citationNotice, citationSignal, collisionKey, collisionNotice, collisionSignal, trueCollisions } from './signals'
236import type { Signal } from './signals'
237import {
238 HELPER_TIMEOUT_MS,
239 SIDE_PASS,
240 askText,
241 bindLog,
242 claimable,
243 freshAsks,
244 isCloseCommand,
245 isOpenLog,
246 isTacklePrompt,
247 isWrapReadPrompt,
248 logTouch,
249 needsOpenCheck,
250 newIds,
251 projectKey,
252 rootOf,
253 storeKeys,
254 tacklePrompt,
255 tally,
256 undone,
257 closePrintNote,
258 withPrint,
259 withoutQuoted,
260 wrapReadPrompt,
261} from './support'
262import type { LogTouch } from './support'
263import { TICKET_MS, UNAVAILABLE_TICKET, ticketFromRun } from './ticket'
264import { addUsage, turnRow, usageDir, usageFile, usagePath, usageRow } from './usage'
265import { BLUSH_HEADER, BLUSH_MS, LAMP_MS, blushFor, blushLanded, blushLevel, blushWhy, haemorrhageFrom, haemorrhageNotice } from './blush'
266import { undoOf } from './irreversible'
267import { REFUSAL_MS, REFUSAL_RED_MS, foldRefusal, refusalFrom, refusalLive, refusalNotice } from './refusal'
268import type { Refusal } from './refusal'
269import { EYE_ROW, HOLD_TEXT, buildView } from './view'
270import { dismiss, dismissable, enqueue, remove, settle, showing, step } from './notices'
271import { landedRows, parseRows, parseWatch, watchHeader, watchText } from './watch'
272import { claimLabel, classify, developByAsks, isContradicted, recordAgentTurn, recordCall, recordTurn } from './witness'
273
274const PANE = 'witness-undone'
275const BARNACLES_PANE = 'witness-barnacles'
276const JEWELS_PANE = 'witness-jewels'
277const PODS_PANE = 'witness-pods'
278// /witness (1.3.4). Written here, not imported: the engine reads a matcher's literal only in this file.
279const ABOUT_PANE = 'witness-about'
280// The model's own hand (1.2): it lands in the other pod's prompt box and waits for the person's Enter.
281const HAND_TOOL = 'mcp__witness__hand'
282const HAND_DESCRIPTION =
283 "Hand a piece of work to another live Claude Code session (a pod) on this machine. It lands in that session's prompt box and waits for the person to read it and press Enter; it never starts work there on its own. `to` is the pod's number, name or id prefix as /pods lists it."
284const HAND_SCHEMA = {
285 type: 'object',
286 properties: {
287 to: { type: 'string', description: "The pod: its number in /pods, its folder name, or the start of its session id." },
288 text: { type: 'string', description: 'What the other session should do, self-contained: it has none of this conversation.' },
289 },
290 required: ['to', 'text'],
291} as const
292const SUBAGENT_HAND = 'witness: a subagent may not hand work to another session; report to the main session instead.'
293// 1.3.5 (loop pass 1, 2026-10-11): the refusal says why a read was refused, and how to read; "use the
294// hand tool" told a session that only wanted to read nothing it could act on.
295const SONAR_FENCE =
296 "witness: the sonar's files (~/.claude/state/witness-sonar) are written by the witness alone, so a hand typed by the person can never be forged. This command writes there, or runs a word the witness cannot vouch for (an interpreter's code counts as a write). To read the heartbeats, use cat, ls or grep; to hand work to a pod, use the hand tool."
297const FORGED_HAND =
298 "witness: a hand envelope is the witness's own. Use the hand tool, or ask the person to type /hand."
299const FRAME_MS = 1_500
300const FRAME_CYCLE = [0, 0, 0, 1, 0, 0, 2, 0]
301const HOUSEKEEP_MS = 15_000
302const POLL_MS = 5 * 60_000
303const SPEAK_MS = 90_000
304const PRINT_MS = 5 * 60_000
305const RECENT_CAP = 20
306const ADD = 'Add RETURNING'
307const ONCE = 'Let through once'
308const CANCEL = 'Cancel'
309const TAKE = 'Take the watch'
310const HOLD_FAILED =
311 'witness: the hold failed, so the write was NOT sent. Re-send it naming what it touches: WITH w AS (<statement> RETURNING *) SELECT * FROM w.'
312const SUBAGENT_HELD =
313 'witness: a subagent may not send an UPDATE or DELETE that names nothing it touched (no one is there to answer the hold). Re-send it as WITH w AS (<statement> RETURNING *) SELECT * FROM w.'
314// 1.1 (ruled 2026-10-09): a subagent's report is a claim the main session reads back.
315const SUBAGENT_CONFIRM =
316 "witness: a subagent may not confirm asks. Its report is a claim the main session must read back; say what you changed, and the main session confirms on its own read-back."
317
318// Every value the band and the pane draw from, held by the host for the session
319// (they survive a hot reload; module variables do not). Declared here, not
320// imported: the engine reads a state reference only where its literals are written.
321const EMPTY_LEDGER: Ledger = { writes: [], claims: [], turns: {} }
322const EMPTY_ACTIVITY: Activity = { activeMs: 0, lastAt: null }
323const PENDING_WATCH: Watch = { state: 'pending', info: null, takenAt: null }
324
325const ledgerAtom = atom({ plugin: 'witness', key: 'ledger' } as const, EMPTY_LEDGER)
326const asksAtom = atom({ plugin: 'witness', key: 'asks' } as const, [] as Ask[])
327const activityAtom = atom({ plugin: 'witness', key: 'activity' } as const, EMPTY_ACTIVITY)
328const noticesAtom = atom({ plugin: 'witness', key: 'notices' } as const, { items: [], seen: 0 } as NoticeQueue)
329const holdAtom = atom({ plugin: 'witness', key: 'hold' } as const, null as Hold | null)
330// A write refused beneath the witness (1.4.0): the band's red and its bubble, until it lapses or the next prompt.
331const refusalAtom = atom({ plugin: 'witness', key: 'refusal' } as const, null as Refusal | null)
332// 1.13.0: a confirm citation that did not check out, and a true collision; each the refusal's red-then-amber.
333const citationAtom = atom({ plugin: 'witness', key: 'citation' } as const, null as Signal | null)
334const collisionAtom = atom({ plugin: 'witness', key: 'collision' } as const, null as Signal | null)
335// The safelight blush (1.7): part of the shell red for an irreversible call, by who can undo it.
336const blushAtom = atom({ plugin: 'witness', key: 'blush' } as const, null as Blush | null)
337// Far more rows than the statement named (1.7): the whole creature red, until it lapses or the next prompt.
338const haemorrhageAtom = atom({ plugin: 'witness', key: 'haemorrhage' } as const, null as Haemorrhage | null)
339// The lamp test (1.7): its end, epoch ms; the whole creature red until then, at session start only.
340const lampAtom = atom({ plugin: 'witness', key: 'lamp' } as const, null as number | null)
341const watchAtom = atom({ plugin: 'witness', key: 'watch' } as const, PENDING_WATCH)
342const barnaclesAtom = atom({ plugin: 'witness', key: 'barnacles' } as const, [] as Barnacle[])
343const frameAtom = atom({ plugin: 'witness', key: 'frame' } as const, 0)
344const costumeAtom = atom({ plugin: 'witness', key: 'costume' } as const, 'none' as Costume)
345// The running turn survives a mid-turn hot reload, so its later writes stay in its claim.
346const turnAtom = atom({ plugin: 'witness', key: 'turn' } as const, 'turn-0')
347// What the confirm tool checks evidence against: calls the mod saw, and Bradley's own words.
348const observedAtom = atom({ plugin: 'witness', key: 'observed' } as const, [] as Observed[])
349const heardAtom = atom({ plugin: 'witness', key: 'heard' } as const, [] as Heard[])
350// For the print (S163): what the companion said, and the hook and skill candidates.
351const spokenAtom = atom({ plugin: 'witness', key: 'spoken' } as const, [] as Spoken[])
352const candidatesAtom = atom({ plugin: 'witness', key: 'candidates' } as const, [] as Candidate[])
353const candidateScanAtom = atom({ plugin: 'witness', key: 'candidateScanAt' } as const, 0)
354// The estate ticket the one line opens with (0.3.0, folded in from estate-status).
355const ticketAtom = atom({ plugin: 'witness', key: 'ticket' } as const, null as Ticket | null)
356// What each Haiku side pass cost (0.4.0), written to this session's usage file.
357const usageAtom = atom({ plugin: 'witness', key: 'usage' } as const, [] as UsageRow[])
358// The session log this watch follows (1.1): bound by the main loop's own file calls, kept across a hot reload.
359const logAtom = atom({ plugin: 'witness', key: 'log' } as const, null as LogBinding | null)
360// The repair pairs (1.2): this project's, newest last, kept across sessions in $.store.
361const repairsAtom = atom({ plugin: 'witness', key: 'repairs' } as const, [] as RepairPair[])
362// The sonar (1.2): the other live pods, the files this pod and one of them both wrote, waiting hands.
363const EMPTY_SONAR: SonarView = { pods: [], overlaps: [], waiting: [], at: 0 }
364const sonarAtom = atom({ plugin: 'witness', key: 'sonar' } as const, EMPTY_SONAR)
365
366// The session's plain values. The engine follows `$` only into functions declared at
367// the top of this file, so the helpers read this record rather than closures. It is
368// replaced, never mutated, and lost on a hot reload (register runs again), which
369// nothing here needs to survive: what must survive is in $.state and $.store.
370type Session = {
371 body: Body
372 watchHold: boolean
373 cwd: string
374 key: string
375 interactive: boolean
376 /** Epoch ms the session started: an older session log is not this session's. */
377 startedAt: number
378 tick: number
379 recent: RecentCall[]
380 friction: Friction[]
381 /** This session's own routine heads (1.9): normalised, counted, never an argument. */
382 routines: LiveRoutine[]
383 /** This session's own safelight events (1.10.0): the red log, saved to its own slot. */
384 reds: RedEvent[]
385 rowIds: string[]
386 /** A candidate pass is in flight; the housekeeping tick must not start a second. */
387 scanning: boolean
388 /** The session's id (its transcript's name): names this session's usage file. */
389 sessionId: string
390 /** A /tackle prompt went in: the main turn it starts is recorded as `tackle`. */
391 tackleTurn: boolean
392 /** Asks a turn called done without proof, to put to Claude on the next prompt. */
393 nudge: string[]
394 /** Asks already put to Claude this session: each is put once. */
395 nudged: string[]
396 /** The end of the last main answer: an approval on the next prompt is read against it. */
397 lastAnswer: string
398 /** Notes from beneath already recorded since this load, so a redraw does not record one again. */
399 headsUp: string[]
400 /** The userConfig fields, read once per load (1.0: the core/estate split). */
401 config: Config
402 /** The configured writer calls as a pattern; null: none. */
403 writers: RegExp | null
404 /** The configured SQL tools as a pattern; null: none. */
405 sqlTools: RegExp | null
406 /** The configured effect tables as a pattern (1.7); null: none. */
407 effectTables: RegExp | null
408 /** The estate adapters found at session start; null is off. */
409 adapters: Adapters
410 /** Where usage files go; null (none written) when the home is unknown. */
411 usageDir: string | null
412 /** Failures waiting for their cure (1.2): the main session's own, lost on a reload. */
413 opens: OpenFailure[]
414 /** The sonar's folder (1.2); null when the sonar is off or the home is unknown. */
415 sonarDir: string | null
416 /** The home folder, for the shared ~/.claude places an overlap may sit in. */
417 home: string | null
418 /** The git repository's root, as the engine reads it; null outside one. */
419 root: string | null
420 /** This pod's state on the sonar: a main turn running, or between turns. */
421 podState: PodState
422 /** Pods in this repo already announced, and the overlaps already said: each said once. */
423 noticedPods: string[]
424 podOverlaps: Overlap[]
425 /** True collisions already announced (1.13.0): each (path, peer) said once. */
426 podCollisions: Overlap[]
427 /** The Notion pages this watch read, each at its latest read (1.15, the stale-canon ping). */
428 notionReads: PodWrite[]
429 /** Hands already taken (by message or by file): each taken once. */
430 handsSeen: string[]
431 /** A sonar sweep is running; the tick must not start a second. */
432 sweeping: boolean
433 /**
434 * The sonar folder the fence keeps Claude's writes out of, in EVERY session with a known home,
435 * the sonar on or off, headless included (the blind verifier's blocker, S170): a session with
436 * its own sonar off could otherwise write a hand file for a pod whose sonar is on.
437 */
438 fenceDir: string | null
439 /** The pods as last shown in the Pods pane, by session id: a /hand row number means these. */
440 podsShown: string[]
441 /** The manifest's version (1.3.4, for /witness); null when it could not be read. */
442 version: string | null
443 /** A ticket read asked for because none was showing (1.3.6) is in flight. */
444 ticketing: boolean
445}
446
447let s: Session = {
448 body: 'phi',
449 watchHold: false,
450 cwd: '',
451 key: '',
452 interactive: false,
453 startedAt: 0,
454 tick: 0,
455 recent: [],
456 friction: [],
457 routines: [],
458 reds: [],
459 rowIds: [],
460 scanning: false,
461 sessionId: '',
462 tackleTurn: false,
463 nudge: [],
464 nudged: [],
465 lastAnswer: '',
466 headsUp: [],
467 config: readConfig({}),
468 writers: writerPattern(readConfig({}).writers),
469 sqlTools: sqlToolPattern(readConfig({}).sqlTools),
470 effectTables: null,
471 adapters: NO_ADAPTERS,
472 usageDir: null,
473 opens: [],
474 sonarDir: null,
475 home: null,
476 root: null,
477 podState: 'idle',
478 noticedPods: [],
479 podOverlaps: [],
480 podCollisions: [],
481 notionReads: [],
482 handsSeen: [],
483 sweeping: false,
484 fenceDir: null,
485 podsShown: [],
486 version: null,
487 ticketing: false,
488}
489
490function setSession(patch: Partial<Session>): void {
491 s = { ...s, ...patch }
492}
493
494function isHeldSql(e: any): boolean {
495 return isSqlTool(e?.tool, s.sqlTools) && typeof e.query === 'string' && needsHold(e.query)
496}
497
498// ---- reaching out: helper script, session log, side passes, store ----
499
500async function say($: any, header: string, text: string, full: boolean, until: number | null): Promise<void> {
501 const at = await $.clock.now()
502 const id = newIds(at, 1, 'n')[0] ?? `n${at}`
503 await update($, noticesAtom, q => enqueue(q, { kind: 'own', header, text, full, until }, id, at))
504 await update($, spokenAtom, log => noteSpoken(log, { header, text, at }))
505}
506
507/** A note from beneath (Claude Code's own "Heads up"), into Notes taken once (to-do 3f23...c538). */
508async function hearBeneath($: any, text: string): Promise<void> {
509 const at = await $.clock.now()
510 await update($, spokenAtom, log => noteHeard(log, { header: HEADS_UP, text, at }))
511}
512
513/** The estate is present when its ticket script is: /tackle names /agile, the guard list is the estate's. */
514function estate(): boolean {
515 return s.adapters.ticket !== null
516}
517
518async function firstExisting($: any, paths: readonly string[]): Promise<string | null> {
519 for (const path of paths) {
520 try {
521 if ((await $.fs.exists(path)) === true) return path
522 } catch {}
523 }
524 return null
525}
526
527/**
528 * The mod's own folder: the engine's word (`$.plugin.root`), else this module's own
529 * location, which cannot be blank. Added after the estate line vanished for a morning
530 * (2026-10-09): the engine answered the lookup with nothing, the adapter read that as
531 * "no estate", and the band fell silent with no sign that it had not looked.
532 */
533function pluginRoot($: any): string {
534 let given: unknown = ''
535 try {
536 given = $.plugin.root
537 } catch {
538 given = ''
539 }
540 if (typeof given === 'string' && given !== '') return given
541 try {
542 return rootFromModuleUrl(import.meta.url)
543 } catch {
544 return ''
545 }
546}
547
548/** The manifest's version, read once at start for /witness (1.3.4); `$.plugin` names no version. */
549async function readVersion($: any, root: string): Promise<string | null> {
550 if (root === '') return null
551 try {
552 return versionOf(await $.fs.read(`${root}/.claude-plugin/plugin.json`))
553 } catch {
554 return null
555 }
556}
557
558/** What /witness says, from the session's state as it stands. */
559async function aboutNow($: any): Promise<AboutModel> {
560 const ticket: Ticket | null = await read($, ticketAtom)
561 const sonar: SonarView = await read($, sonarAtom)
562 return aboutModel({
563 body: s.body,
564 version: s.version,
565 asks: await read($, asksAtom),
566 ledger: await read($, ledgerAtom),
567 activity: await read($, activityAtom),
568 barnacles: await read($, barnaclesAtom),
569 hold: await read($, holdAtom),
570 pods: s.sonarDir === null ? null : sonar.pods.length,
571 costume: await read($, costumeAtom),
572 metered: ticket?.kind === 'ok' && ticket.warnPush,
573 })
574}
575
576/** The adapters' scripts: configured, else found in the mod's own repository; absent, off. */
577async function findAdapters($: any, cwd: string, root: string): Promise<Adapters> {
578 return {
579 ticket: await firstExisting($, scriptCandidates(s.config.ticketScript, root, cwd, TICKET_SCRIPT)),
580 watch: await firstExisting($, scriptCandidates(s.config.watchScript, root, cwd, WATCH_SCRIPT)),
581 }
582}
583
584async function homeDir($: any): Promise<string | undefined> {
585 const profile = await $.env.get('USERPROFILE').catch(() => undefined)
586 return profile ?? (await $.env.get('HOME').catch(() => undefined))
587}
588
589async function runHelper($: any, extra: string[]): Promise<{ exitCode: number; stdout: string } | null> {
590 if (s.adapters.watch === null) return null
591 try {
592 return await $.process.run(['python', s.adapters.watch, '--json', ...extra, '--project-dir', s.cwd], {
593 timeoutMs: HELPER_TIMEOUT_MS,
594 })
595 } catch {
596 return null
597 }
598}
599
600/**
601 * Every Haiku side pass goes through here, so each one's cost is recorded as the API
602 * reported it (0.4.0, S165). Recording never fails the pass it measures.
603 */
604async function complete($: any, pass: UsagePass, prompt: string): Promise<any> {
605 const r = await $.model.complete({ ...SIDE_PASS, prompt })
606 await recordUsage($, pass, r).catch(() => undefined)
607 return r
608}
609
610async function recordUsage($: any, pass: UsagePass, r: any): Promise<void> {
611 await appendUsage($, usageRow(pass, await $.clock.now(), r))
612}
613
614/** Adds one row (a side pass or a turn) and rewrites this session's usage file. */
615async function appendUsage($: any, row: UsageRow): Promise<void> {
616 await update($, usageAtom, rows => addUsage(rows, row))
617 const sessionId = s.sessionId === '' ? `session-${s.startedAt}` : s.sessionId
618 const file = usageFile({
619 sessionId,
620 repo: s.key,
621 startedAt: s.startedAt,
622 model: SIDE_PASS.model,
623 rows: await read($, usageAtom),
624 })
625 if (s.usageDir !== null) await $.fs.write(usagePath(s.usageDir, s.startedAt, sessionId), file)
626}
627
628/**
629 * The note for Claude, once per ask (Bradley, S165, option B): asks a turn called done
630 * without proof that are still unproved now. Null when there is nothing to put.
631 */
632async function takeNudge($: any): Promise<string | null> {
633 if (s.nudge.length === 0) return null
634 const pending = s.nudge
635 setSession({ nudge: [], nudged: [...s.nudged, ...pending] })
636 const asks = await read($, asksAtom)
637 const still = asks.filter(a => pending.includes(a.id) && a.state === 'claimed')
638 return still.length === 0 ? null : unprovedNote(still.map(a => ({ id: a.id, text: a.text })))
639}
640
641/** Re-reads the estate ticket; a helper that cannot run leaves it unavailable, never zeros. */
642async function refreshTicket($: any): Promise<void> {
643 if (s.adapters.ticket === null) return
644 let run: { exitCode: number; stdout: string } | null
645 try {
646 run = await $.process.run(['python', s.adapters.ticket, '--json', '--project-dir', s.cwd], {
647 timeoutMs: HELPER_TIMEOUT_MS,
648 })
649 } catch {
650 run = null
651 }
652 const ticket = ticketFromRun(run)
653 await update($, ticketAtom, () => ticket)
654}
655
656/**
657 * The session log this watch is bound to (1.1), read by its one path: no folder listing
658 * and no mtime test, so another session's log in the same repo is never followed.
659 * Unbound (a session that has not touched its log yet): null.
660 */
661async function boundLog($: any): Promise<{ path: string; text: string } | null> {
662 const bound: LogBinding | null = await read($, logAtom)
663 if (bound === null) return null
664 try {
665 if (!(await $.fs.exists(bound.path))) return null
666 const text: string = await $.fs.read(bound.path)
667 return { path: bound.path, text }
668 } catch {
669 return null
670 }
671}
672
673/** The bound log while it is open: its Goals are synced and the print is written into it. */
674async function openLog($: any): Promise<{ path: string; text: string } | null> {
675 const log = await boundLog($)
676 return log !== null && isOpenLog(log.text) ? log : null
677}
678
679/** The bound log, closed or not: the close triage lands after the close. */
680async function sessionLog($: any): Promise<{ path: string; text: string } | null> {
681 return boundLog($)
682}
683
684/**
685 * Binds the watch to the session log a main-loop file call touched (1.1). A Write of another
686 * log over a Write rebinds only once the bound log is closed, so that log is read first.
687 */
688async function bindTouch($: any, touch: LogTouch, now: number): Promise<void> {
689 const current: LogBinding | null = await read($, logAtom)
690 const open = needsOpenCheck(current, touch) ? (await openLog($)) !== null : true
691 const next = bindLog(current, touch, now, open)
692 if (next === current) return
693 await update($, logAtom, () => next)
694 // The goals' source moved: read its Goals now rather than at the next tick.
695 if (s.interactive && (current === null || current.path !== next?.path)) $.clock.after(0, () => syncGoals($, now))
696}
697
698/** What the close triage settled leaves the undone (0.8.0, a field report). */
699async function syncTriage($: any): Promise<void> {
700 const log = await sessionLog($)
701 if (log === null) return
702 const triage = parseTriage(log.text)
703 if (triage.dismissed.length + triage.todo.length === 0) return
704 await update($, asksAtom, asks => applyTriage(asks, triage))
705}
706
707/**
708 * Reads the open log's Goals into the asks ledger. Runs at session start, at every turn's
709 * end, AND on the housekeeping tick and every prompt: one long turn (S163, an hour of work
710 * with Bradley's messages arriving mid-turn) never reached a turn's end, so the log's goals
711 * never arrived and the band read 0/7 while the work landed.
712 *
713 * A goal is dated from the session's start, not from when it was synced: synced late,
714 * it would have refused every read-back made before the sync as evidence.
715 */
716async function syncGoals($: any, now: number): Promise<void> {
717 await syncTriage($).catch(() => undefined)
718 const log = await openLog($)
719 const goals = log === null ? [] : parseGoals(log.text, s.config.goalsHeading)
720 if (goals.length === 0) return
721 const ids = newIds(now, goals.length, 'g')
722 const at = s.startedAt > 0 ? s.startedAt : now
723 const ledger = await read($, ledgerAtom)
724 await update($, asksAtom, asks => resolveStates(mergeGoals(asks, goals, { at, ids }), ledger))
725}
726
727/** The Haiku pass over one of Bradley's prompts. Adds nothing to Claude's context. */
728async function extractAsks($: any, text: string, now: number, previous: string): Promise<void> {
729 const before: Ask[] = await read($, asksAtom)
730 const r = await complete($, 'extract', extractPrompt(text, before, previous))
731 if (!r.isAnswered) return
732 const found = parseExtraction(r.text, before)
733 if (found.asks.length + found.builds.length === 0) return
734 // A multi-session build is held apart from this session's asks (0.6.0).
735 const fresh = [
736 ...freshAsks(found.asks, newIds(now, found.asks.length, 'a'), now),
737 ...freshAsks(found.builds, newIds(now, found.builds.length, 'b'), now, 'build'),
738 ]
739 await update($, asksAtom, list => [...list, ...fresh])
740}
741
742/** Which open asks a "done" answer claims; they ride on that claim from here. */
743async function matchAsks($: any, claimId: string, answer: string): Promise<void> {
744 const open = claimable(await read($, asksAtom))
745 if (open.length === 0) return
746 const r = await complete($, 'match', matchPrompt(open, answer))
747 if (!r.isAnswered) return
748 const ids = parseMatch(r.text, open.length).flatMap(n => open[n - 1]?.id ?? [])
749 if (ids.length === 0) return
750 const ledger = await read($, ledgerAtom)
751 await update($, asksAtom, list => resolveStates(applyMatches(list, ids, claimId), ledger))
752 await developFromAsks($)
753}
754
755/** A claim whose matched asks are all witnessed develops (to-do 3f33...1b36); its asks follow it. */
756async function developFromAsks($: any): Promise<void> {
757 const asks: Ask[] = await read($, asksAtom)
758 await update($, ledgerAtom, l => developByAsks(l, asks))
759 const ledger = await read($, ledgerAtom)
760 await update($, asksAtom, a => resolveStates(a, ledger))
761}
762
763/** This session's own name in the store: its id, else its start time. */
764function selfId(): string {
765 return s.sessionId !== '' ? s.sessionId : `session-${s.startedAt}`
766}
767
768/**
769 * This session's leftovers into its OWN slot (1.2, ruled 2026-10-09): a live session's slot is
770 * never taken by another, and `ended` (written at session end) is what makes it takeable.
771 */
772async function saveCarry($: any, ended = false): Promise<void> {
773 const slot = carrySlot({ sessionId: selfId(), savedAt: await $.clock.now(), ended, asks: carryOver(await read($, asksAtom)) })
774 await $.store.set(carrySlotKey(s.key, selfId()), slot)
775}
776
777/**
778 * The leftovers of sessions in this project that have ended (or gone stale), each slot taken
779 * once and deleted; the older single slot, if one is still stored, read the same way.
780 */
781async function takeCarried($: any, now: number): Promise<Ask[]> {
782 const lists: Ask[][] = []
783 const all: string[] = await $.store.keys().catch(() => [])
784 for (const k of all.filter(x => x.startsWith(carryPrefix(s.key)))) {
785 const slot = asCarrySlot(await $.store.get(k))
786 if (slot === null || !takeable(slot, now, selfId())) continue
787 lists.push(slot.asks)
788 await $.store.delete(k).catch(() => undefined)
789 }
790 const legacy = await $.store.get(storeKeys(s.key).carry)
791 if (Array.isArray(legacy)) {
792 lists.push(legacy as Ask[])
793 await $.store.delete(storeKeys(s.key).carry).catch(() => undefined)
794 }
795 return mergeCarried(lists)
796}
797
798/** This session's OWN friction into its own slot (1.2, ruled 2026-10-09): never over another pod's. */
799async function saveFriction($: any): Promise<void> {
800 const slot = frictionSlot({ sessionId: selfId(), savedAt: await $.clock.now(), entries: ownFriction(s.friction, s.startedAt) })
801 await $.store.set(frictionSlotKey(s.key, selfId()), slot)
802}
803
804/**
805 * The project's friction as every pod wrote it: the archive (the old single key) and every
806 * session's slot, live or ended, merged. Slots untouched for a day are folded into the archive
807 * and deleted, so the store stays bounded.
808 */
809async function loadFriction($: any, now: number): Promise<Friction[]> {
810 const archiveKey = storeKeys(s.key).friction
811 const archive = asFrictionList(await $.store.get(archiveKey))
812 const lists: Friction[][] = [archive]
813 const folded: Friction[][] = []
814 const gone: string[] = []
815 const all: string[] = await $.store.keys().catch(() => [])
816 for (const k of all.filter(x => x.startsWith(frictionPrefix(s.key)))) {
817 const slot = asFrictionSlot(await $.store.get(k))
818 if (slot === null) continue
819 // A slot knows whose it is: entries with no session take the slot's (1.9).
820 const entries = stampSession(slot.entries, slot.sessionId)
821 lists.push(entries)
822 if (archivable(slot, now, selfId())) {
823 folded.push(entries)
824 gone.push(k)
825 }
826 }
827 if (gone.length > 0) {
828 await $.store.set(archiveKey, mergeFriction([archive, ...folded]))
829 for (const k of gone) await $.store.delete(k).catch(() => undefined)
830 }
831 return mergeFriction(lists)
832}
833
834/** This session's OWN routine heads into its own slot (1.9): never over another session's; no arguments, only heads. */
835async function saveRoutines($: any): Promise<void> {
836 if (s.routines.length === 0) return
837 const slot = routineSlot({ sessionId: selfId(), savedAt: await $.clock.now(), entries: s.routines })
838 await $.store.set(routinesSlotKey(s.key, selfId()), slot)
839}
840
841/** This session's own safelight events into its own slot (1.10.0). Never throws: the log must not cost a call. */
842async function saveReds($: any, now: number): Promise<void> {
843 try {
844 if (s.reds.length === 0 || s.key === '') return
845 await $.store.set(redsSlotKey(s.key, selfId()), redSlot({ sessionId: selfId(), savedAt: now, events: s.reds }))
846 } catch {}
847}
848
849/** A safelight event lit (1.10.0): kept in memory and saved. */
850async function logRed($: any, o: OpenRed): Promise<void> {
851 setSession({ reds: openRed(s.reds, o) })
852 await saveReds($, o.at)
853}
854
855/** An event that never showed on its own: logged and ended in one step (a refusal folded into a live burst). */
856async function logRedEnded($: any, o: OpenRed, how: RedHow): Promise<void> {
857 const next = openRed(s.reds, o)
858 const last = next[next.length - 1]
859 setSession({ reds: last === undefined ? next : closeRed(next, { id: last.id }, how, o.at) })
860 await saveReds($, o.at)
861}
862
863/** Open events of a channel ended (1.10.0). */
864async function endRed($: any, channel: RedChannel, how: RedHow, at: number): Promise<void> {
865 if (!s.reds.some((e) => e.channel === channel && e.endedAt === undefined)) return
866 setSession({ reds: closeRed(s.reds, { channel }, how, at) })
867 await saveReds($, at)
868}
869
870/**
871 * Every session's red slots, this session's included (its live events from memory). Another
872 * session's slot untouched for a week, and any beyond the newest REDS_SLOTS, is deleted (with
873 * `prune`, at a start), so the store stays bounded.
874 */
875async function loadReds($: any, now: number, prune: boolean): Promise<RedSlot[]> {
876 const found: Array<{ key: string; slot: RedSlot }> = []
877 const all: string[] = await $.store.keys().catch(() => [])
878 for (const key of all.filter((x) => x.startsWith(redsPrefix(s.key)))) {
879 const slot = asRedSlot(await $.store.get(key).catch(() => null))
880 if (slot !== null && slot.sessionId !== selfId()) found.push({ key, slot })
881 }
882 found.sort((a, b) => b.slot.savedAt - a.slot.savedAt)
883 const keep = found.filter((f, i) => i < REDS_SLOTS && !redsStale(f.slot, now, selfId()))
884 if (prune) {
885 for (const f of found.filter((x) => !keep.includes(x))) await $.store.delete(f.key).catch(() => undefined)
886 }
887 const mine: RedSlot[] = s.reds.length === 0 ? [] : [redSlot({ sessionId: selfId(), savedAt: now, events: s.reds })]
888 return [...keep.map((f) => f.slot), ...mine]
889}
890
891/**
892 * Every session's routine slots, the archive's and the live ones, one slot per session. With
893 * `fold`, slots untouched for a day are folded into the archive and deleted (at a start), so the
894 * store stays bounded. This session's own slot is left out: its live heads are in `s.routines`.
895 */
896async function loadRoutines($: any, now: number, fold: boolean): Promise<RoutineSlot[]> {
897 const archiveKey = routinesArchiveKey(s.key)
898 const archive = asRoutineArchive(await $.store.get(archiveKey))
899 const live: RoutineSlot[] = []
900 const stale: RoutineSlot[] = []
901 const gone: string[] = []
902 const all: string[] = await $.store.keys().catch(() => [])
903 for (const k of all.filter(x => x.startsWith(routinesPrefix(s.key)))) {
904 const slot = asRoutineSlot(await $.store.get(k))
905 if (slot === null || slot.sessionId === selfId()) continue
906 live.push(slot)
907 if (routineArchivable(slot, now, selfId())) {
908 stale.push(slot)
909 gone.push(k)
910 }
911 }
912 if (fold && gone.length > 0) {
913 await $.store.set(archiveKey, foldRoutines(archive, stale))
914 for (const k of gone) await $.store.delete(k).catch(() => undefined)
915 }
916 return foldRoutines(archive, live)
917}
918
919/**
920 * This session's own leftovers back, as carried (1.3.6, F9): a slot under its own id at a start, or
921 * when the id moves to a resumed one, is this conversation's previous process. No other session
922 * ever takes it (takeable), so without this a crash strands it.
923 */
924async function takeOwn($: any, now: number): Promise<void> {
925 if (s.sessionId === '') return
926 const slot = asCarrySlot(await $.store.get(carrySlotKey(s.key, s.sessionId)).catch(() => null))
927 if (slot === null || slot.asks.length === 0) return
928 const held: Ask[] = await read($, asksAtom)
929 const back = ownLeftovers(slot.asks, held)
930 if (back.length === 0) return
931 const seeded = seedCarried(back, { at: now, ids: newIds(now, back.length, 'k') })
932 await update($, asksAtom, a => [...a, ...seeded])
933}
934
935/**
936 * F9 (2026-10-11, live, after the laptop restarted): a resumed conversation's session.start runs
937 * under a fresh id, and the engine moves to the resumed id afterwards with no session.end. The
938 * witness kept the first id: a phantom pod beat on, and the conversation's own slot was stranded.
939 * The id is now read again on each prompt and sonar sweep; when it has moved, the phantom's beat is
940 * ended and its slot dropped (this process saves under the new id), and the resumed id's own
941 * leftovers come back as carried.
942 */
943async function followId($: any): Promise<void> {
944 const id: unknown = await $.session.id().catch(() => s.sessionId)
945 if (typeof id !== 'string' || id === '' || id === s.sessionId) return
946 const was = s.sessionId
947 const state = s.podState
948 const now = await $.clock.now()
949 if (was !== '') {
950 setSession({ podState: 'ended' })
951 await writeBeat($, now).catch(() => undefined)
952 await $.store.delete(carrySlotKey(s.key, was)).catch(() => undefined)
953 }
954 setSession({ sessionId: id, podState: state, noticedPods: [], podOverlaps: [], podCollisions: [], podsShown: [] })
955 await takeOwn($, now).catch(() => undefined)
956 await writeBeat($, now).catch(() => undefined)
957 // The ticket read at the start may not be the one the band now reads; read it again now.
958 if (estate()) $.clock.after(0, () => refreshTicket($))
959}
960
961/**
962 * Bradley, 2026-10-11 (a screenshot): at a session's start the band often showed neither the
963 * ticket nor `estate: ?`, so the start's read had landed nowhere the band reads, with the next one
964 * ten minutes off. A prompt that finds no ticket yet asks for one; one read in flight at a time.
965 */
966async function ticketIfMissing($: any): Promise<void> {
967 if (!estate() || s.ticketing) return
968 const ticket: Ticket | null = await read($, ticketAtom)
969 if (ticket !== null) return
970 setSession({ ticketing: true })
971 try {
972 await refreshTicket($)
973 } finally {
974 setSession({ ticketing: false })
975 }
976}
977
978/**
979 * Retires the stray subfolder slots of this repository (1.11.1, "Repo root, retire stray"): a
980 * session started in `<repo>/sub` before 1.11.1 kept its candidates under that folder. Each
981 * `candidates:<root>/<sub>` slot whose own repository root is this one is merged into this
982 * project's slot (unsettled ones `retired`, never overwriting a settled one) and deleted. Friction,
983 * barnacles, carry, repairs and scrubbed stray slots are left alone. Idempotent: a second start
984 * finds no stray slot.
985 */
986async function retireStraySlots($: any, now: number): Promise<void> {
987 const exists = (p: string): Promise<boolean> => $.fs.exists(p).then((v: unknown) => v === true)
988 const prefix = `candidates:${s.key}/`
989 const all: string[] = await $.store.keys().catch(() => [])
990 const strays: Array<{ key: string; list: Candidate[] }> = []
991 for (const k of all.filter(k => k.startsWith(prefix))) {
992 const root = await rootOf(k.slice('candidates:'.length), exists)
993 if (root === null || projectKey(root) !== s.key) continue
994 const v = await $.store.get(k).catch(() => null)
995 strays.push({ key: k, list: Array.isArray(v) ? (v as Candidate[]) : [] })
996 }
997 if (strays.length === 0) return
998 const own = storeKeys(s.key).candidates
999 const stored = await $.store.get(own)
1000 const merged = retireStrays(Array.isArray(stored) ? (stored as Candidate[]) : [], strays.map(x => x.list), now)
1001 await $.store.set(own, merged)
1002 for (const x of strays) await $.store.delete(x.key).catch(() => undefined)
1003}
1004
1005/**
1006 * Struck lines in the candidates file are dismissals (1.14.0). The file invites a strike once a
1007 * jewel is ruled, and a close's triage struck seven in 102_pm that the store never heard of, so
1008 * they came back to be graded again. Each unsettled jewel whose line is struck is settled
1009 * dismissed, through the same merge by key as a dismiss in the pane. Read from where
1010 * `fileCandidates` writes; idempotent, since a settled jewel is never struck again.
1011 */
1012async function settleStruck($: any, now: number): Promise<void> {
1013 const path = await candidatesFile($)
1014 if ((await $.fs.exists(path)) !== true) return
1015 const text: unknown = await $.fs.read(path)
1016 if (typeof text !== 'string') return
1017 const stored = await $.store.get(storeKeys(s.key).candidates)
1018 const list = Array.isArray(stored) ? (stored as Candidate[]) : []
1019 const keys = struckKeys(list, text)
1020 if (keys.length > 0) await persistCandidates($, settleCandidatesIn(list, keys, 'dismissed', now))
1021}
1022
1023async function loadStored($: any, now: number): Promise<void> {
1024 await retireStraySlots($, now).catch(() => undefined)
1025 await settleStruck($, now).catch(() => undefined)
1026 const keys = storeKeys(s.key)
1027 // Only ended sessions' leftovers (1.2): a live session's undone asks stay its own.
1028 const carried = await takeCarried($, now)
1029 if (carried.length > 0) {
1030 const seeded = seedCarried(carried, { at: now, ids: newIds(now, carried.length, 'k') })
1031 await update($, asksAtom, a => (a.length === 0 ? seeded : a))
1032 }
1033 // A slot under this session's own id at a start is its previous process (1.3.6, F9).
1034 await takeOwn($, now).catch(() => undefined)
1035 // Every pod's friction, read; this session writes only its own (1.2). Legacy third-edit
1036 // entries are dropped: a file under build is work, not friction (1.1).
1037 setSession({ friction: realFriction(await loadFriction($, now)) })
1038 // Stale routine slots are folded into the archive now; they are read again at each scan (1.9).
1039 await loadRoutines($, now, true).catch(() => undefined)
1040 // The red log (1.10.0): this session's own slot back (a resumed id), and old slots pruned.
1041 if (s.sessionId !== '') {
1042 const own = asRedSlot(await $.store.get(redsSlotKey(s.key, selfId())).catch(() => null))
1043 if (own !== null && s.reds.length === 0) setSession({ reds: own.events })
1044 }
1045 await loadReds($, now, true).catch(() => undefined)
1046 const stored = await $.store.get(keys.candidates)
1047 if (Array.isArray(stored)) await update($, candidatesAtom, () => stored as Candidate[])
1048 const pairs = asPairs(await $.store.get(keys.repairs))
1049 if (pairs.length > 0) await update($, repairsAtom, () => pairs)
1050}
1051
1052/**
1053 * The hook and skill candidate pass (S163). A Haiku side pass over this session's call
1054 * digest and the project's friction; adds nothing to Claude's context. `force` (the print)
1055 * skips the interval but still needs enough new calls to be worth reading.
1056 */
1057async function scanCandidates($: any, now: number, force: boolean): Promise<void> {
1058 if (s.scanning || !s.interactive) return
1059 const lastScanAt: number = await read($, candidateScanAtom)
1060 const observed: Observed[] = await read($, observedAtom)
1061 const newCalls = observed.filter(o => o.at > lastScanAt && !o.agent).length
1062 const due = force ? newCalls >= CANDIDATE_MIN_NEW_CALLS : shouldScan({ now, lastScanAt, newCalls })
1063 if (!due) return
1064 setSession({ scanning: true })
1065 try {
1066 await update($, candidateScanAtom, () => now)
1067 // Read fresh (1.7.1): another pod's candidates and settles are in the store, not in this atom.
1068 const existing: Candidate[] = await freshCandidates($)
1069 // The installed commands and skills, so a candidate never re-proposes one (a field report).
1070 const commands: any[] = await $.command.list().catch(() => [])
1071 const installed = commands
1072 .filter(c => c?.source === 'user' || c?.source === 'plugin')
1073 .map(c => ({ name: String(c.name), description: String(c.description ?? '') }))
1074 const guards = estate() ? INSTALLED_GUARDS : []
1075 const covered = await readCovered($)
1076 // The charter (1.11): when this machine first scanned, the dismissed shapes of every project,
1077 // and the hooks actually configured.
1078 if (asFirstScanAt(await $.store.get(INSTALL_KEY).catch(() => null)) === null) await $.store.set(INSTALL_KEY, now).catch(() => undefined)
1079 const dismissed = await readDismissed($)
1080 const hooks = await readConfiguredHooks($)
1081 // Routines seen in two or more sessions (1.9): this session's live heads beside every other slot's.
1082 const others = await loadRoutines($, now, false).catch(() => [] as RoutineSlot[])
1083 const mine = routineSlot({ sessionId: selfId(), savedAt: now, entries: s.routines })
1084 const prompt = candidatesPrompt({
1085 routines: sharedRoutines([...others, mine]),
1086 // Session tags (1.9): the pass quotes them, and parseCandidates drops evidence from one session.
1087 friction: tagFriction(s.friction, observed, selfId()),
1088 calls: callDigest(observed, undefined, sessionTag(selfId())),
1089 existing,
1090 installed,
1091 guards,
1092 dismissed,
1093 hooks,
1094 ...covered,
1095 })
1096 const r = await complete($, 'candidates', prompt)
1097 if (!r.isAnswered) return
1098 const fresh = parseCandidates(r.text, existing, now, guards)
1099 if (fresh.length === 0) return
1100 await persistCandidates($, mergeCandidates(existing, fresh))
1101 } finally {
1102 setSession({ scanning: false })
1103 }
1104}
1105
1106/** The titles of jewels dismissed in any project's candidates slot (1.11): shown to the pass, never displayed. */
1107async function readDismissed($: any): Promise<string[]> {
1108 const all: string[] = await $.store.keys().catch(() => [])
1109 const lists: Candidate[][] = []
1110 for (const k of all.filter(k => k.startsWith('candidates:'))) {
1111 const v = await $.store.get(k).catch(() => null)
1112 if (Array.isArray(v)) lists.push(v as Candidate[])
1113 }
1114 return dismissedTitles(lists)
1115}
1116
1117/** The hooks configured in the user, project and local settings files (1.11), as `event matcher: script` lines. */
1118async function readConfiguredHooks($: any): Promise<string[]> {
1119 const root = s.cwd.replace(/\\/g, '/').replace(/\/+$/, '')
1120 const paths = [
1121 ...(s.home === null ? [] : [`${s.home.replace(/\\/g, '/').replace(/\/+$/, '')}/.claude/settings.json`]),
1122 `${root}/.claude/settings.json`,
1123 `${root}/.claude/settings.local.json`,
1124 ]
1125 const texts: string[] = []
1126 for (const path of paths) {
1127 try {
1128 if ((await $.fs.exists(path).catch(() => false)) !== true) continue
1129 const text: string | null = await $.fs.read(path).catch(() => null)
1130 if (typeof text === 'string') texts.push(text)
1131 } catch {
1132 // absent or unreadable: omitted
1133 }
1134 }
1135 return configuredHooks(texts)
1136}
1137
1138/** This project's jewels split by the first-week budget (1.11): what shows, and what is queued. */
1139async function budgetedJewels($: any, own: readonly Candidate[]): Promise<{ shown: Candidate[]; queued: Candidate[] }> {
1140 const first = asFirstScanAt(await $.store.get(INSTALL_KEY).catch(() => null))
1141 return applyBudget(own, first, await $.clock.now())
1142}
1143
1144/** Script extensions whose first comment line is worth reading. */
1145const SCRIPT_EXT = /\.(py|sh|bash|ps1|js|mjs|cjs|ts|bat|cmd)$/i
1146
1147/**
1148 * What already exists, for the candidate pass's covered check (1.8): the session repo's scripts/
1149 * (names, with a first docstring or comment line) and the headings of the CLAUDE.md files Claude
1150 * Code loads. Read through the engine's fs with every failure tolerated: absent is omitted.
1151 */
1152async function readCovered($: any): Promise<{ scripts: ScriptNote[]; headings: HeadingNote[] }> {
1153 const root = s.cwd.replace(/\\/g, '/').replace(/\/+$/, '')
1154 const scripts: ScriptNote[] = []
1155 try {
1156 const entries: any[] = await $.fs.list(`${root}/scripts`).catch(() => [])
1157 const names = entries
1158 .filter(e => e?.kind === 'file' && SCRIPT_EXT.test(String(e.name)))
1159 .map(e => String(e.name))
1160 .sort()
1161 .slice(0, MAX_SCRIPTS)
1162 for (const name of names) {
1163 const text: string | null = await $.fs.read(`${root}/scripts/${name}`).catch(() => null)
1164 scripts.push({ name, summary: typeof text === 'string' ? scriptSummary(text) : '' })
1165 }
1166 } catch {
1167 // the covered check is best-effort
1168 }
1169 const headings: HeadingNote[] = []
1170 const files: Array<[string, string]> = [['CLAUDE.md', `${root}/CLAUDE.md`]]
1171 if (s.home !== null) files.push(['~/.claude/CLAUDE.md', `${s.home.replace(/\\/g, '/').replace(/\/+$/, '')}/.claude/CLAUDE.md`])
1172 for (const [label, path] of files) {
1173 try {
1174 if ((await $.fs.exists(path).catch(() => false)) !== true) continue
1175 const text: string | null = await $.fs.read(path).catch(() => null)
1176 const found = typeof text === 'string' ? mdHeadings(text) : []
1177 if (found.length > 0) headings.push({ file: label, headings: found })
1178 } catch {
1179 // absent or unreadable: omitted
1180 }
1181 }
1182 return { scripts, headings }
1183}
1184
1185/** The running candidates file: reports/ under the session folder when it has one, else .claude/. */
1186async function candidatesFile($: any): Promise<string> {
1187 const root = s.cwd.replace(/\\/g, '/').replace(/\/+$/, '')
1188 return candidatesPath(s.cwd, (await $.fs.exists(`${root}/reports`)) === true)
1189}
1190
1191/** Appends this watch's unfiled candidates to the running file, then marks them filed. */
1192async function fileCandidates($: any, now: number, source: string): Promise<void> {
1193 // Read fresh (1.7.1): what another pod filed is not filed twice, and its settles are kept.
1194 const candidates: Candidate[] = await freshCandidates($)
1195 const unfiled = candidates.filter(c => !c.filed)
1196 if (unfiled.length === 0) return
1197 const path = await candidatesFile($)
1198 const before: string = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
1199 const date = new Date(now).toISOString().slice(0, 10)
1200 await $.fs.write(path, appendCandidates(before, candidates, { date, source }))hooks/asks.ts 513 lines1// The asks ledger: Bradley's done/undone tracker. Pure functions over plain data.
2// An ask counts as done only when witnessed; a claimed-but-unwitnessed ask is pale.
3import type { Ask, Ledger } from '../types'
4import { isContradicted } from './witness'
5
6/** `dropped`: a `- [-]` line, a goal the session set aside. */
7export type Goal = { text: string; ticked: boolean; dropped?: boolean }
8/**
9 * done/total/pale count this session's asks only; `carried` the undone carried in from the
10 * last watch; `builds` the live multi-session builds.
11 */
12export type Counts = { done: number; total: number; pale: number; carried: number; builds: number }
13export type Extraction = { asks: string[]; builds: string[] }
14export type PaneRow = { id: string; marker: '[ ]' | '[~]' | '[x]'; text: string; source: Ask['source']; settled?: Ask['settled'] }
15
16export const MAX_ASK_CHARS = 90
17export const MAX_EXTRACT = 5
18export const MAX_BUILDS = 3
19/** How much of the previous answer's end the extract pass reads beside an approval. */
20export const MAX_PREVIOUS_CHARS = 800
21export const MAX_CARRIED = 30
22export const MAX_PROMPT_ASKS = 40
23export const PRINT_END = '<!-- /witness print -->'
24
25/** Every whitespace run (newlines included) becomes one space: no ask can inject a markdown line. */
26export function cleanText(text: string): string {
27 return String(text ?? '').replace(/\s+/g, ' ').trim()
28}
29
30/** The n newest entries (by `at`, later index wins a tie), kept in original order with original indices. */
31function newestEntries(asks: Ask[], n: number): Array<{ a: Ask; i: number }> {
32 const all = asks.map((a, i) => ({ a, i }))
33 if (all.length <= n) return all
34 const keep = [...all].sort((x, y) => y.a.at - x.a.at || y.i - x.i).slice(0, n)
35 return keep.sort((x, y) => x.i - y.i)
36}
37
38/** Lower-case, links and punctuation stripped, first 60 chars: the dedupe key. */
39export function normalise(text: string): string {
40 return text
41 .toLowerCase()
42 .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
43 .replace(/https?:\/\/\S+/g, ' ')
44 .replace(/[^\p{L}\p{N}\s]/gu, ' ')
45 .replace(/\s+/g, ' ')
46 .trim()
47 .slice(0, 60)
48 .trim()
49}
50
51/** First balanced {...} object in the text that parses as JSON; null on anything else. */
52export function parseJsonObject(reply: string): Record<string, unknown> | null {
53 if (typeof reply !== 'string') return null
54 const text = reply.replace(/```[a-zA-Z]*/g, ' ')
55 for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) {
56 const end = balancedEnd(text, start)
57 if (end === -1) continue
58 try {
59 const value: unknown = JSON.parse(text.slice(start, end + 1))
60 if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
61 return value as Record<string, unknown>
62 }
63 } catch {
64 // try the next opening brace
65 }
66 }
67 return null
68}
69
70function balancedEnd(text: string, start: number): number {
71 let depth = 0
72 let inString = false
73 for (let i = start; i < text.length; i++) {
74 const c = text[i]
75 if (inString) {
76 if (c === '\\') i++
77 else if (c === '"') inString = false
78 } else if (c === '"') inString = true
79 else if (c === '{') depth++
80 else if (c === '}' && --depth === 0) return i
81 }
82 return -1
83}
84
85/**
86 * `- [ ]` / `- [x]` / `- [-]` items under the goals heading (config `goalsHeading`,
87 * default `## Goals`), up to the next heading of the same level.
88 */
89export function parseGoals(markdown: string, heading = '## Goals'): Goal[] {
90 const h = /^(#+)\s+(.*\S)\s*$/.exec(heading.trim())
91 const level = h?.[1]?.length ?? 2
92 const title = (h?.[2] ?? 'Goals').toLowerCase()
93 const goals: Goal[] = []
94 let inGoals = false
95 for (const line of String(markdown ?? '').split(/\r?\n/)) {
96 const hd = /^(#+)\s+(.*?)\s*$/.exec(line)
97 if (hd !== null && hd[1]?.length === level) {
98 inGoals = (hd[2] ?? '').toLowerCase() === title
99 continue
100 }
101 if (!inGoals) continue
102 const m = /^\s*[-*]\s+\[( |x|X|-)\]\s+(.*\S)\s*$/.exec(line)
103 if (m) goals.push({ text: (m[2] ?? '').trim(), ticked: m[1] === 'x' || m[1] === 'X', dropped: m[1] === '-' })
104 }
105 return goals
106}
107
108/** Shortest dedupe key a goal edit may extend and still be the same goal. */
109const MIN_EDIT_KEY = 12
110
111/**
112 * The live ask a goal names: the same key, else (for a goal-sourced ask only) a key one
113 * extends, as when an outcome is appended to the line in place. Each ask matches once.
114 */
115function goalMatch(asks: Ask[], key: string, taken: ReadonlySet<string>): number {
116 const live = (a: Ask) => a.state !== 'dropped' && !taken.has(a.id)
117 const same = asks.findIndex((a) => live(a) && normalise(a.text) === key)
118 if (same !== -1) return same
119 return asks.findIndex((a) => {
120 if (!live(a) || a.source !== 'goal') return false
121 const old = normalise(a.text)
122 const short = old.length < key.length ? old : key
123 return short.length >= MIN_EDIT_KEY && (key.startsWith(old) || old.startsWith(key))
124 })
125}
126
127const STOP_WORDS = new Set(
128 'the a an to of and or in on for with that this it its be is are was us we our my me as at by from so then than into up out about can could should would will just also please'.split(' '),
129)
130
131/** A word's plain form: a trailing plural `s`, or `ing` / `ed` on a longer word, cut. */
132function stem(w: string): string {
133 if (w.length > 5 && /(ing|ed)$/.test(w)) return w.replace(/(ing|ed)$/, '')
134 if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss')) return w.slice(0, -1)
135 return w
136}
137
138function contentWords(text: string): Set<string> {
139 const words = text
140 .toLowerCase()
141 .replace(/[^\p{L}\p{N}\s]/gu, ' ')
142 .split(/\s+/)
143 .filter((w) => w.length > 1 && !STOP_WORDS.has(w))
144 return new Set(words.map(stem))
145}
146
147/** Shared content words a restatement needs, and their share of the shorter text. */
148export const RESTATE_SHARED = 3
149export const RESTATE_SHARE = 0.6
150
151/** Content words two texts share, and their share of the shorter text's words. */
152export function wordOverlap(a: string, b: string): { shared: number; share: number } {
153 const wa = contentWords(a)
154 const wb = contentWords(b)
155 const shared = [...wa].filter((w) => wb.has(w)).length
156 return { shared, share: shared / Math.max(1, Math.min(wa.size, wb.size)) }
157}
158
159/** Is `b` close enough to `a` to be the same request in other words? */
160export function restates(a: string, b: string): number | null {
161 const o = wordOverlap(a, b)
162 return o.shared >= RESTATE_SHARED && o.share >= RESTATE_SHARE ? o.share : null
163}
164
165/**
166 * The typed ask a goal restates (a field report: /start wrote Goals rephrasing Bradley's
167 * prompt, and each request counted twice). Most shared content words wins; -1 when none qualifies.
168 */
169function restatedAsk(asks: Ask[], text: string, taken: ReadonlySet<string>): number {
170 let best = -1
171 let bestShare = 0
172 asks.forEach((a, i) => {
173 if (a.source !== 'ask' || a.state === 'dropped' || taken.has(a.id)) return
174 const share = restates(a.text, text)
175 if (share !== null && share > bestShare) {
176 best = i
177 bestShare = share
178 }
179 })
180 return best
181}
182
183/**
184 * The log's Goals are the session's own record, so the ledger follows them:
185 * a goal rescoped in place supersedes its old ask, a `[-]` goal drops it, and a goal
186 * gone from the log is dropped unless witnessed. Asks Bradley typed are never touched.
187 * No goals at all changes nothing: a Goals section that vanished is not a ruling.
188 */
189export function mergeGoals(
190 asks: Ask[],
191 goals: Goal[],
192 opts: { at: number; ids: string[] },
193): Ask[] {
194 if (goals.length === 0) return asks.map((a) => ({ ...a }))
195 let next = asks.map((a) => ({ ...a }))
196 const named = new Set<string>()
197 let used = 0
198 for (const goal of goals) {
199 const text = cleanText(goal.text)
200 const key = normalise(text)
201 if (key === '') continue
202 const matched = goalMatch(next, key, named)
203 // A goal restating a typed ask takes that ask over: one request, one count.
204 const restated = matched === -1 && !goal.dropped ? restatedAsk(next, text, named) : -1
205 const idx = matched !== -1 ? matched : restated
206 if (idx !== -1) {
207 const found = next[idx]!
208 named.add(found.id)
209 const undone = found.state === 'open' || found.state === 'claimed'
210 const patch: Partial<Ask> = goal.dropped
211 ? undone
212 ? { state: 'dropped' }
213 : {}
214 : {
215 ...((found.source === 'goal' || idx === restated) && found.text !== text ? { text } : {}),
216 ...(found.source === 'carried' || found.source === 'build' || idx === restated
217 ? { source: 'goal' as const }
218 : {}),
219 ...(goal.ticked && found.state === 'open' ? { state: 'claimed' as const, claimId: null } : {}),
220 }
221 next = next.map((a, i) => (i === idx ? { ...a, ...patch } : a))
222 continue
223 }
224 if (goal.dropped) continue
225 const id = opts.ids[used]
226 if (id === undefined) continue
227 used++
228 named.add(id)
229 next = [
230 ...next,
231 {
232 id,
233 text,
234 source: 'goal',
235 state: goal.ticked ? 'claimed' : 'open',
236 claimId: null,
237 at: opts.at,
238 },
239 ]
240 }
241 return next.map((a) =>
242 a.source === 'goal' && !named.has(a.id) && (a.state === 'open' || a.state === 'claimed')
243 ? { ...a, state: 'dropped' }
244 : a,
245 )
246}
247
248/**
249 * `previous`: the end of the assistant's last answer, so an approval ("greenlight") can be
250 * read as the proposal it commissions. Only its last MAX_PREVIOUS_CHARS are
251 * sent, where a proposal sits, and the section is left out when there is none.
252 */
253export function extractPrompt(promptText: string, asks: Ask[], previous = ''): string {
254 const existing = newestEntries(
255 asks.filter((a) => a.state !== 'dropped'),
256 MAX_PROMPT_ASKS,
257 )
258 .map(({ a }, i) => `${i + 1}. ${cleanText(a.text)}`)
259 .join('\n')
260 const before = cleanText(previous).slice(-MAX_PREVIOUS_CHARS).trim()
261 return [
262 'You read one message a person sent to an AI coding assistant and list the asks in it, in two kinds.',
263 'asks: things the person wants the assistant to DO and finish in this session (build, fix, add, change, write, run, check and report).',
264 'builds: work the person sets for several sessions or days, a whole project, or many deliverables at once (e.g. "over the next few days", "rebuild X to a shippable standard", "build 18 apps"). Put each item in one kind only.',
265 'When the message approves a concrete proposal at the end of the assistant\'s previous message ("yes", "go ahead", "greenlight", "do it"), list that proposal as an ask, in its own terms. Never list anything from the previous message that this message does not approve.',
266 'Exclude: questions asking for information, questions whether something could or should be done ("can we also have X?", "would X be hard?") until the person asks for it, approvals that commission nothing, opinions, thanks, background context, any standing instruction about how to work, conditional ones included ("explain as we go", "always do X", "if you find a bug, report it"), the method steps of a plan rather than the work it does ("sweep first", "verify each item", "close each with a read-back"), anything the person quotes or pastes to talk about (another prompt, a list, a log) unless they ask for it to be done, and anything already in the existing list.',
267 `Write each item as an imperative of at most ${MAX_ASK_CHARS} characters, in the person's own terms. Never add a word that changes what was asked: "build an /agile ultracode" is not "build an /agile ultracode skill".`,
268 `At most ${MAX_EXTRACT} asks and ${MAX_BUILDS} builds. Use empty lists when there are none.`,
269 'Output shape: {"asks": ["imperative"], "builds": ["imperative"]}',
270 'Reply with the JSON only.',
271 '',
272 'Existing list:',
273 existing === '' ? '(none)' : existing,
274 ...(before === '' ? [] : ['', "The end of the assistant's previous message:", before]),
275 '',
276 'Message:',
277 promptText,
278 ].join('\n')
279}
280
281/** Clean texts from one list of the reply, skipping any key already seen; `seen` is extended. */
282function takeTexts(raw: unknown, seen: Set<string>, cap: number): string[] {
283 if (!Array.isArray(raw)) return []
284 const out: string[] = []
285 for (const item of raw) {
286 if (typeof item !== 'string') continue
287 const text = cleanText(item).slice(0, MAX_ASK_CHARS).trim()
288 const key = normalise(text)
289 if (key === '' || seen.has(key)) continue
290 seen.add(key)
291 out.push(text)
292 if (out.length === cap) break
293 }
294 return out
295}
296
297/** The side pass's two lists, deduped against the existing asks and across each other (asks first). */
298export function parseExtraction(reply: string, asks: Ask[] = []): Extraction {
299 const obj = parseJsonObject(reply)
300 const seen = new Set(asks.map((a) => normalise(a.text)))
301 const found = takeTexts(obj?.asks, seen, MAX_EXTRACT)
302 return { asks: found, builds: takeTexts(obj?.builds, seen, MAX_BUILDS) }
303}
304
305export function parseExtract(reply: string, asks: Ask[] = []): string[] {
306 return parseExtraction(reply, asks).asks
307}
308
309export function matchPrompt(openAsks: Ask[], answer: string): string {
310 // Numbers stay the original 1-based positions in openAsks, so parseMatch(reply, openAsks.length) maps back.
311 const list = newestEntries(openAsks, MAX_PROMPT_ASKS)
312 .map(({ a, i }) => `${i + 1}. ${cleanText(a.text)}`)
313 .join('\n')
314 return [
315 'You compare a numbered list of asks with the answer an AI assistant just gave.',
316 'List the numbers of the asks the answer claims to have COMPLETED. Leave out asks it only discusses, plans, or partly does.',
317 'Output shape: {"done": [1, 3]}',
318 'Use {"done": []} when none. Reply with the JSON only.',
319 '',
320 'Asks:',
321 list === '' ? '(none)' : list,
322 '',
323 'Answer:',
324 answer,
325 ].join('\n')
326}
327
328/** 1-based item numbers from the reply, in range, no duplicates. */
329export function parseMatch(reply: string, n: number): number[] {
330 const raw = parseJsonObject(reply)?.done
331 if (!Array.isArray(raw)) return []
332 const out: number[] = []
333 for (const v of raw) {
334 if (typeof v !== 'number' || !Number.isInteger(v)) continue
335 if (v < 1 || v > n || out.includes(v)) continue
336 out.push(v)
337 }
338 return out
339}
340
341export function applyMatches(asks: Ask[], askIds: string[], claimId: string): Ask[] {
342 return asks.map((a) =>
343 askIds.includes(a.id) && (a.state === 'open' || a.state === 'claimed')
344 ? { ...a, state: 'claimed', claimId }
345 : { ...a },
346 )
347}
348
349export function resolveStates(asks: Ask[], ledger: Ledger): Ask[] {
350 return asks.map((ask) => {
351 if (ask.state === 'dropped' || ask.state === 'witnessed') return { ...ask }
352 // Only an ask's OWN claim counts; a ticked goal with no claim stays pale until applyMatches attaches one.
353 const claimId = ask.claimId
354 const claim = claimId === null ? undefined : ledger.claims.find((c) => c.id === claimId)
355 if (claim === undefined) return { ...ask, claimId }
356 return { ...ask, claimId, state: claim.state === 'developed' ? 'witnessed' : 'claimed' }
357 })
358}
359
360/** This session's own work: not carried in from the last watch, not a multi-session build. */
361export function isSessionAsk(a: Ask): boolean {
362 return a.source !== 'carried' && a.source !== 'build'
363}
364
365/** Carried asks and builds are not Bradley's asks for this session: never in n/m. */
366export function counts(asks: Ask[]): Counts {
367 const live = asks.filter((a) => a.state !== 'dropped' && isSessionAsk(a))
368 return {
369 done: live.filter((a) => a.state === 'witnessed').length,
370 total: live.length,
371 pale: live.filter((a) => a.state === 'claimed').length,
372 carried: asks.filter((a) => a.source === 'carried' && (a.state === 'open' || a.state === 'claimed')).length,
373 builds: asks.filter((a) => a.source === 'build' && a.state !== 'dropped').length,
374 }
375}
376
377export function nm(asks: Ask[]): string {
378 const c = counts(asks)
379 return `${c.done}/${c.total}${c.pale > 0 ? ` ~${c.pale}` : ''}`
380}
381
382const ORDER: Record<string, number> = { open: 0, claimed: 1, witnessed: 2 }
383const MARKER: Record<string, PaneRow['marker']> = { open: '[ ]', claimed: '[~]', witnessed: '[x]' }
384
385/** This session's asks first (open, pale, done), then the carried ones, then the builds, each under its own heading. */
386export function paneRows(asks: Ask[]): PaneRow[] {
387 const group = (a: Ask) => (a.source === 'build' ? 2 : a.source === 'carried' ? 1 : 0)
388 return asks
389 .map((a, i) => ({ a, i }))
390 .filter(({ a }) => a.state !== 'dropped')
391 .sort((x, y) => group(x.a) - group(y.a) || (ORDER[x.a.state] ?? 0) - (ORDER[y.a.state] ?? 0) || x.i - y.i)
392 .map(({ a }) => ({
393 id: a.id,
394 marker: MARKER[a.state] ?? '[ ]',
395 text: a.text,
396 source: a.source,
397 ...(a.settled === undefined ? {} : { settled: a.settled }),
398 }))
399}
400
401export function dropAsk(asks: Ask[], id: string): Ask[] {
402 return asks.map((a) => (a.id === id ? { ...a, state: 'dropped' } : { ...a }))
403}
404
405/**
406 * What may carry (Bradley, 2026-10-08): an open ask nobody claimed, one hop only. A pale
407 * claim or a goal the log ticked stays in the print as pale and is not reopened, and a
408 * carried ask still untouched at the end is not carried again.
409 */
410function carries(a: Ask): boolean {
411 // A build is never carried: /close makes it a to-do (0.6.0); nor is what the close triage settled (0.8.0).
412 return a.state === 'open' && isSessionAsk(a) && a.settled === undefined
413}
414
415export type Triage = { dismissed: string[]; todo: string[] }
416
417/** `- dismissed: <item> - <evidence>` and `- to-do: <item> -> <url>` under `## Witness triage` (/close Step 4b). */
418export function parseTriage(markdown: string): Triage {
419 const dismissed: string[] = []
420 const todo: string[] = []
421 let inTriage = false
422 for (const line of String(markdown ?? '').split(/\r?\n/)) {
423 if (/^##\s+/.test(line)) {
424 inTriage = /^##\s+Witness triage\s*$/i.test(line)
425 continue
426 }
427 if (!inTriage) continue
428 const m = /^\s*[-*]\s+(dismissed|to-do):\s*(.*\S)\s*$/i.exec(line)
429 if (m) (m[1]!.toLowerCase() === 'dismissed' ? dismissed : todo).push((m[2] ?? '').trim())
430 }
431 return { dismissed, todo }
432}
433
434/** Does a triage line quote this ask? It opens with the ask's text (a suffix and the evidence follow). */
435function quotes(line: string, a: Ask): boolean {
436 const k = normalise(a.text)
437 const l = normalise(line)
438 return k !== '' && (l === k || (k.length >= MIN_EDIT_KEY && l.startsWith(k)))
439}
440
441/**
442 * The close triage settles what it quotes (a field report: a /tackle after /close offered
443 * the eight carried asks the triage had just dismissed with evidence). Dismissed: dropped.
444 * To-do: routed to the board, so no longer this session's undone work. Witnessed asks and
445 * anything the triage does not quote are left as they are.
446 */
447export function applyTriage(asks: Ask[], triage: Triage): Ask[] {
448 return asks.map((a): Ask => {
449 if (a.state === 'dropped' || a.state === 'witnessed' || a.settled !== undefined) return { ...a }
450 if (triage.dismissed.some((l) => quotes(l, a))) return { ...a, state: 'dropped', settled: 'dismissed' }
451 if (triage.todo.some((l) => quotes(l, a))) return { ...a, settled: 'to-do' }
452 return { ...a }
453 })
454}
455
456export function carryOver(asks: Ask[]): Ask[] {
457 return newestEntries(asks.filter(carries), MAX_CARRIED).map(({ a }) => ({ ...a }))
458}
459
460/** The same rule again at load: a store written before it may hold anything. */
461export function seedCarried(carried: Ask[], opts: { at: number; ids: string[] }): Ask[] {
462 return carried
463 .filter(carries)
464 .flatMap((a, i) => {
465 const id = opts.ids[i]
466 return id === undefined
467 ? []
468 : [{ id, text: cleanText(a.text), source: 'carried' as const, state: 'open' as const, claimId: null, at: opts.at }]
469 })
470}
471
472/** `extra`: further sections (Notes taken, candidates) placed before the closing marker. */
473export function printSection(asks: Ask[], ledger: Ledger, extra: readonly string[] = []): string {
474 const c = counts(asks)
475 const open = c.total - c.done - c.pale
476 const live = asks.filter((a) => a.state !== 'dropped')
477 const listed = (group: Ask[], tag: string) => {
478 const of = (s: Ask['state']) => group.filter((a) => a.state === s)
479 return [
480 ...of('witnessed').map((a) => `- [x] ${cleanText(a.text)}${tag}`),
481 ...of('claimed').map((a) => `- [ ] ${cleanText(a.text)}${tag} (pale: claimed, never witnessed)`),
482 ...of('open').map((a) => `- [ ] ${cleanText(a.text)}${tag}`),
483 ]
484 }
485 const items = listed(live.filter(isSessionAsk), '')
486 const carriedItems = listed(live.filter((a) => a.source === 'carried'), ' (carried)')
487 const builds = live.filter((a) => a.source === 'build').map((a) => `- ${cleanText(a.text)} (build)`)
488 // A subagent's report is labelled as one (1.1): the main session has still to read it back.
489 // A contradicted claim (1.15): a read-back showed the old text, not the new.
490 const paleClaims = ledger.claims
491 .filter((cl) => cl.state === 'pale')
492 .map((cl) => {
493 const said = isContradicted(cl, ledger.writes) ? 'contradicted' : 'pale'
494 return `- ${said} ${cl.agentId === undefined ? 'claim' : 'agent claim'}: ${cleanText(cl.text)}`
495 })
496 const lines = [
497 '## Witness print',
498 '',
499 `Asks: ${c.done} of ${c.total} witnessed, ${c.pale} pale, ${open} open.`,
500 ]
501 if (items.length > 0) lines.push('', ...items)
502 if (carriedItems.length > 0) {
503 lines.push('', `Carried in from the last watch: ${c.carried} undone, not carried again.`, '', ...carriedItems)
504 }
505 if (builds.length > 0) {
506 lines.push('', `Builds (multi-session; each becomes a to-do at /close): ${builds.length}.`, '', ...builds)
507 }
508 if (paleClaims.length > 0) lines.push('', ...paleClaims)
509 if (extra.length > 0) lines.push('', ...extra.map((l) => l.replace(/\r?\n/g, ' ')))
510 lines.push('', PRINT_END)
511 return lines.join('\n')
512}
513hooks/bells.ts 32 lines1import type { Activity } from '../types'
2
3export const BREAK_MS = 5 * 60_000
4/** Half a bell: thirty minutes of active time (1.1, Bradley's sketch of 2026-10-09). */
5export const HALF_BELL_MS = 30 * 60_000
6/** A whole bell: an hour of active time. */
7export const BELL_MS = 2 * HALF_BELL_MS
8/** Three bells on the chime, an hour each, filling from the bottom. */
9export const BELLS = 3
10export const MAX_HALVES = 2 * BELLS
11
12/** Count an interaction at `at`: a gap of five minutes or less is active time. */
13export function touch(activity: Activity, at: number): Activity {
14 const gap = activity.lastAt === null ? 0 : at - activity.lastAt
15 const counted = activity.lastAt !== null && gap >= 0 && gap <= BREAK_MS ? gap : 0
16 return { activeMs: activity.activeMs + counted, lastAt: at }
17}
18
19/** Half-bells of active time, one per thirty minutes, capped at the chime's six. */
20export function bellHalves(activity: Activity): number {
21 return Math.min(MAX_HALVES, Math.floor(activity.activeMs / HALF_BELL_MS))
22}
23
24/** Whole bells rung: one per hour of active time, capped at three. */
25export function bellsRung(activity: Activity): number {
26 return Math.floor(bellHalves(activity) / 2)
27}
28
29export function isIdle(activity: Activity, now: number): boolean {
30 return activity.lastAt !== null && now - activity.lastAt > BREAK_MS
31}
32hooks/config.ts 240 lines1// The core/estate split (1.0, ruled 2026-10-09): one source that runs in the iniphi
2// estate unchanged and in a Claude Code with no estate at all. Every estate-specific
3// input is a userConfig field, and each adapter is off when its input is absent.
4// SUPERSEDED IN PART (ruled by Bradley 2026-10-11): the 1.0 clause
5// "whose default keeps the estate working with no configuration" no longer holds. The
6// public defaults are neutral (no workspace.* names, no Supabase assumption) and the
7// estate supplies its own values through its local config (writerCalls, and sqlTools if
8// its database tool does not end in __execute_sql). Pure: register.tsx does the file
9// checks; what can be decided from plain data lives here.
10
11export const TICKET_SCRIPT = 'scripts/estate-status.py'
12export const WATCH_SCRIPT = 'scripts/witness-watch.py'
13/** No writer functions by default (neutral, 2026-10-11): a SELECT is a read unless the user lists the functions that write. */
14export const DEFAULT_WRITERS: readonly string[] = []
15/**
16 * The tools whose `query` input is SQL the hold judges. Neutral default: any MCP tool whose
17 * name ends `__execute_sql`, a convention several database servers share (not Supabase-only).
18 */
19export const DEFAULT_SQL_TOOLS = ['mcp__*__execute_sql'] as const
20/** The schemas whose tables a subagent's report may name; neutral: `public` only. */
21export const DEFAULT_TABLE_SCHEMAS = ['public'] as const
22export const DEFAULT_SESSIONS_DIR = '.claude/sessions'
23export const DEFAULT_GOALS_HEADING = '## Goals'
24export const DEFAULT_CLOSE_COMMANDS = ['/close'] as const
25export const DEFAULT_PERSON = 'you'
26/** The estate's run-a-board skill; named in /tackle only where the estate is present. */
27export const ESTATE_TACKLE_SKILL = '/agile'
28/** How far above the mod's folder a default script is looked for (mods/<mod> -> repo root). */
29export const SCRIPT_LEVELS = 3
30
31export type Config = {
32 ticketScript: string
33 watchScript: string
34 writers: readonly string[]
35 /** Tool-name patterns of the SQL tools the hold judges (`*` matches any run of characters). */
36 sqlTools: readonly string[]
37 /** Schemas whose `schema.table` names in a subagent's report count as targets it named. */
38 tableSchemas: readonly string[]
39 person: string
40 sessionsDir: string
41 goalsHeading: string
42 closeCommands: readonly string[]
43 /** The sonar (1.2): `auto` runs it where the estate is present, `on` always, `off` never. */
44 sonar: SonarSetting
45 /** Typed hands (1.3.3): `auto` starts work where the estate is present, `start` always, `wait` never. */
46 typedHands: TypedHandsSetting
47 /** The blush (1.7): the database has point-in-time recovery, so a bulk loss is rung 2, not 3. Unknown is false. */
48 pointInTimeRecovery: boolean
49 /** The haemorrhage (1.7): rows back from a statement that named fewer, above which the creature goes red. */
50 haemorrhageRows: number
51 /** The lamp test (1.7): the creature shows red for 1.5 s at session start. */
52 lampTest: boolean
53 /** Tables whose writes can reach outside the database (1.7); `*` matches any run of characters. Default none. */
54 effectTables: readonly string[]
55}
56
57export const DEFAULT_HAEMORRHAGE_ROWS = 25
58
59/** A number, or a numeric string, that is a whole count of at least 1; else the fallback. */
60export function countOf(v: unknown, fallback: number): number {
61 const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN
62 return Number.isFinite(n) && n >= 1 ? Math.trunc(n) : fallback
63}
64
65/** A boolean option, or the strings true/false; else the fallback. */
66export function flagOf(v: unknown, fallback: boolean): boolean {
67 if (typeof v === 'boolean') return v
68 if (v === 'true') return true
69 if (v === 'false') return false
70 return fallback
71}
72
73export type SonarSetting = 'auto' | 'on' | 'off'
74export type TypedHandsSetting = 'auto' | 'start' | 'wait'
75
76/** Whether this load runs the sonar: heartbeats, overlaps and hands write files under ~/.claude/state. */
77export function sonarOn(setting: SonarSetting, estate: boolean): boolean {
78 return setting === 'on' || (setting === 'auto' && estate)
79}
80
81/**
82 * Whether a hand typed in another session may start work here unattended (ruled 2026-10-09).
83 * A hand is taken on the engine's plugin stamp, which its own types call only the sender's
84 * claim, so by default (no estate) a typed hand waits for Enter like a Claude-written one.
85 */
86export function typedHandsStart(setting: TypedHandsSetting, estate: boolean): boolean {
87 return setting === 'start' || (setting === 'auto' && estate)
88}
89
90/** The adapters found at session start: null is off. */
91export type Adapters = { ticket: string | null; watch: string | null }
92
93export const NO_ADAPTERS: Adapters = { ticket: null, watch: null }
94
95const text = (v: unknown): string => (typeof v === 'string' ? v.trim() : '')
96
97/** A comma- or newline-separated list, blanks dropped. */
98export function listOf(v: unknown): string[] {
99 return text(v)
100 .split(/[,\n]/)
101 .map(x => x.trim())
102 .filter(x => x.length > 0)
103}
104
105export function readConfig(options: unknown): Config {
106 const o = (options ?? {}) as Record<string, unknown>
107 const writers = listOf(o.writerCalls)
108 const close = listOf(o.closeCommands)
109 const sqlTools = listOf(o.sqlTools)
110 const schemas = listOf(o.tableSchemas).filter(n => /^[A-Za-z_]\w*$/.test(n))
111 return {
112 ticketScript: text(o.ticketScript),
113 watchScript: text(o.watchScript),
114 writers: writers.length > 0 ? writers : [...DEFAULT_WRITERS],
115 sqlTools: sqlTools.length > 0 ? sqlTools : [...DEFAULT_SQL_TOOLS],
116 tableSchemas: schemas.length > 0 ? schemas : [...DEFAULT_TABLE_SCHEMAS],
117 person: text(o.person) || DEFAULT_PERSON,
118 sessionsDir: text(o.sessionsDir) || DEFAULT_SESSIONS_DIR,
119 goalsHeading: text(o.goalsHeading) || DEFAULT_GOALS_HEADING,
120 closeCommands: close.length > 0 ? close : [...DEFAULT_CLOSE_COMMANDS],
121 sonar: o.sonar === 'on' || o.sonar === 'off' ? o.sonar : 'auto',
122 typedHands: o.typedHands === 'start' || o.typedHands === 'wait' ? o.typedHands : 'auto',
123 pointInTimeRecovery: flagOf(o.pointInTimeRecovery, false),
124 haemorrhageRows: countOf(o.haemorrhageRows, DEFAULT_HAEMORRHAGE_ROWS),
125 lampTest: flagOf(o.lampTest, true),
126 effectTables: listOf(o.effectTables),
127 }
128}
129
130export function isAbsolute(path: string): boolean {
131 return /^([A-Za-z]:)?[\\/]/.test(path)
132}
133
134/** Forward slashes, `.` and `..` segments resolved, no trailing slash. */
135export function normalizePath(path: string): string {
136 const raw = path.replace(/\\/g, '/')
137 const lead = raw.startsWith('/') ? '/' : ''
138 const parts = raw.split('/').reduce<string[]>((acc, seg) => {
139 if (seg === '' || seg === '.') return acc
140 if (seg !== '..') return [...acc, seg]
141 const last = acc[acc.length - 1]
142 // Never above a root: `/..` and `C:/..` stay at the root; a relative path keeps its `..`.
143 if (last === undefined) return lead === '/' ? acc : [...acc, seg]
144 if (/^[A-Za-z]:$/.test(last)) return acc
145 return last === '..' ? [...acc, seg] : acc.slice(0, -1)
146 }, [])
147 return `${lead}${parts.join('/')}`
148}
149
150/** `rel` under `base`, unless `rel` is absolute. */
151export function under(base: string, rel: string): string {
152 return normalizePath(isAbsolute(rel) ? rel : `${base}/${rel}`)
153}
154
155/**
156 * The mod's folder from its hooks module's own `import.meta.url`, a second word on where
157 * the mod is for when the engine's `$.plugin.root` is blank (the estate line vanished for a
158 * morning on 2026-10-09 when it was): `file:///C:/x/mods/witness/hooks/register.tsx` gives
159 * `C:/x/mods/witness`, and so does the POSIX form. '' for anything that is not a file URL
160 * of a module under a `hooks/` folder.
161 */
162export function rootFromModuleUrl(url: unknown): string {
163 if (typeof url !== 'string' || !url.startsWith('file://')) return ''
164 const path = decodeURIComponent(url.slice('file://'.length))
165 const local = /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path
166 const m = /^(.+)\/hooks\/[^/]+$/.exec(local)
167 return m === null ? '' : normalizePath(m[1] ?? '')
168}
169
170/**
171 * Where to look for a script, in order. A configured path is the only candidate
172 * (relative to the session's folder); unset, `rel` under the mod's own folder and up
173 * to SCRIPT_LEVELS folders above it, so the mod's own repository supplies it (in the
174 * estate, <repo>/mods/witness -> <repo>/scripts). Never the session's
175 * folder by default: a repo opened is not trusted to run a script on every start.
176 */
177export function scriptCandidates(configured: string, pluginRoot: string, cwd: string, rel: string): string[] {
178 if (configured !== '') return [under(cwd, configured)]
179 if (pluginRoot === '') return []
180 return Array.from({ length: SCRIPT_LEVELS }, (_, i) => under(pluginRoot, `${'../'.repeat(i)}${rel}`))
181}
182
183const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
184
185/** `schema.name` or `name`; a trailing `*` matches any further name characters. */
186function writerSource(name: string): string {
187 const star = name.endsWith('*')
188 const parts = (star ? name.slice(0, -1) : name).split('.').map(p => escape(p.trim()))
189 return `${parts.join('\\s*\\.\\s*')}${star ? '[a-z_0-9]*' : ''}`
190}
191
192/** The pattern sql.ts matches writer calls with; null when the list is empty. */
193export function writerPattern(names: readonly string[]): RegExp | null {
194 const valid = names.filter(n => /^[A-Za-z_][\w.]*\*?$/.test(n))
195 if (valid.length === 0) return null
196 return new RegExp(`\\b(${valid.map(writerSource).join('|')})\\s*\\(`, 'gi')
197}
198
199/** The pattern a tool name must match whole to be a SQL tool; `*` anywhere is a wildcard. Null when no entry is usable. */
200export function sqlToolPattern(names: readonly string[]): RegExp | null {
201 const valid = names.filter(n => /^[\w$*-]+$/.test(n))
202 if (valid.length === 0) return null
203 return new RegExp(`^(?:${valid.map(n => n.split('*').map(escape).join('.*')).join('|')})$`)
204}
205
206/**
207 * The pattern a written table's name must match whole (lower-case) to be an effect table (1.7).
208 * `*` is a wildcard anywhere. An entry with no schema (`orders`) also matches that table in any
209 * schema. Null when the list is empty or holds nothing usable.
210 */
211export function effectTablePattern(names: readonly string[]): RegExp | null {
212 const valid = names.map(n => n.trim().toLowerCase()).filter(n => /^[\w$*.]+$/.test(n))
213 if (valid.length === 0) return null
214 const source = (n: string): string => {
215 const body = n.split('*').map(escape).join('.*')
216 return n.includes('.') ? body : `(?:[\\w$]+\\.)?${body}`
217 }
218 return new RegExp(`^(?:${valid.map(source).join('|')})$`)
219}
220
221/** Whether a tool name is one of the configured SQL tools. */
222export function isSqlTool(tool: unknown, pattern: RegExp | null): boolean {
223 return typeof tool === 'string' && pattern !== null && pattern.test(tool)
224}
225
226export function isCloseCommand(prompt: string, commands: readonly string[]): boolean {
227 const t = prompt.trim()
228 return commands.some(c => t === c || t.startsWith(`${c} `) || t.startsWith(`${c}\n`))
229}
230
231/** The person as the model reads it: "the user" by default, else the configured name. */
232export function personRef(person: string): string {
233 return person === DEFAULT_PERSON ? 'the user' : person
234}
235
236/** Whose words called an ask off, as the print and the confirm tool say it. */
237export function onWords(person: string): string {
238 return person === DEFAULT_PERSON ? 'on your words' : `on ${person}'s words`
239}
240hooks/barnacles.ts 189 lines1// Barnacles: friction that recurs across sessions. Pure functions over plain data.
2import type { Barnacle, Friction } from '../types'
3import { parseJsonObject } from './asks'
4
5export const FRICTION_CAP = 200
6export const MAX_BARNACLES = 6
7
8export type RecentCall = { tool: string; input: unknown; isError: boolean; at: number }
9export type FrictionInput = {
10 tool: string
11 input: unknown
12 resultText: string
13 isError: boolean
14 recent: RecentCall[]
15 /** Epoch ms of this call; defaults to the newest recent call's time, else 0. */
16 at?: number
17}
18
19export function noteFriction(log: Friction[], f: Friction): Friction[] {
20 return [...log, f].slice(-FRICTION_CAP)
21}
22
23/**
24 * Friction worth keeping (Bradley, 2026-10-09): a cancelled or refused write, a failing call,
25 * an MCP misuse. Editing a file under build is the work itself, never friction, so the
26 * third-edit kind is retired and its legacy entries are dropped on load.
27 */
28export function realFriction(log: Friction[]): Friction[] {
29 return log.filter((f) => f.kind !== 're-edit')
30}
31
32/** The Supabase dialog's own answer when a write is declined, and nothing else (no row data). */
33export const CANCEL_STATUS = /^\s*\{\s*"status"\s*:\s*"cancelled"\s*\}\s*$/
34
35/** An error that names a refusal by a guard, a permission rule or a hook; shared with the red warning (refusal.ts). */
36export const GUARD_DENIED = /(denied|refus(?:ed|ing|al)|permission to use|blocked by|not permitted|hook error)/i
37
38function cancelled(c: FrictionInput, at: number): Friction[] {
39 // A cancel is a refusal (an error naming it, as the witness hold's is) or the dialog's bare
40 // status; a successful result whose rows say "cancelled" is data (a field report).
41 const sqlCancelled =
42 /execute_sql/.test(c.tool) && (c.isError ? /cancel/i.test(c.resultText) : CANCEL_STATUS.test(c.resultText))
43 // A guard's refusal is a refused write too (Bradley, 2026-10-09: the shell guard's
44 // "Refusing a heredoc" went unrecorded), so a PreToolUse hook error counts.
45 const denied =
46 c.isError && /\b(denied|refus(?:ed|ing|al)|permission to use|blocked by|not permitted|hook error)\b/i.test(c.resultText)
47 if (!sqlCancelled && !denied) return []
48 const detail = sqlCancelled ? 'write cancelled at the prompt' : `call refused: ${gist(c.resultText)}`
49 return [{ kind: 'cancelled-write', key: c.tool, at, detail }]
50}
51
52/** The first line of an error, cut short, for a friction's detail. */
53const gist = (text: string): string => text.replace(/\s+/g, ' ').trim().slice(0, 80)
54
55/**
56 * A failing call. An MCP tool's error counts at once (a wrong column, a bad id, a misused
57 * server: a misremembering, Bradley 2026-10-09); any other tool's counts on its second
58 * failure in a row, since a shell command that fails once is often exploration.
59 */
60function callFailure(c: FrictionInput, at: number): Friction[] {
61 if (!c.isError) return []
62 if (c.tool.startsWith('mcp__')) return [{ kind: 'tool-failure', key: c.tool, at, detail: `${c.tool} failed: ${gist(c.resultText)}` }]
63 const last = [...c.recent].reverse().find((r) => r.tool === c.tool)
64 if (last === undefined || !last.isError) return []
65 return [{ kind: 'tool-failure', key: c.tool, at, detail: `${c.tool} failed twice in a row` }]
66}
67
68export function frictionFrom(c: FrictionInput): Friction[] {
69 const newest = c.recent.length > 0 ? c.recent[c.recent.length - 1]?.at ?? 0 : 0
70 const at = c.at ?? newest
71 // A cancelled or refused write is a refusal, never also a failing call.
72 const refused = cancelled(c, at)
73 return refused.length > 0 ? refused : callFailure(c, at)
74}
75
76const day = (at: number): string => new Date(at).toISOString().slice(0, 10)
77
78export function recurPrompt(log: Friction[], barnacles: Barnacle[]): string {
79 const groups = new Map<string, { kind: string; days: Set<string>; count: number; detail: string }>()
80 for (const f of log) {
81 const g = groups.get(f.key) ?? { kind: f.kind, days: new Set<string>(), count: 0, detail: f.detail }
82 g.days.add(day(f.at))
83 g.count++
84 groups.set(f.key, g)
85 }
86 const lines = [...groups.entries()].map(
87 ([key, g]) => `- key=${key} kind=${g.kind} count=${g.count} days=${[...g.days].sort().join(',')} detail=${g.detail}`,
88 )
89 const known = barnacles.map((b) => `- ${b.key}: ${b.text}`)
90 return [
91 'You read a log of friction an AI coding assistant hit (cancelled or refused writes, failing calls, MCP tool errors).',
92 'Keep only friction that recurs: the same key on 2 or more distinct days. Drop the rest, and drop any known barnacle whose key no longer recurs.',
93 'For each kept key write one plain sentence saying what keeps going wrong. Reuse the key exactly.',
94 `At most ${MAX_BARNACLES} entries. Output shape: {"barnacles": [{"key": "...", "text": "..."}]}`,
95 'Use {"barnacles": []} when nothing recurs. Reply with the JSON only.',
96 '',
97 'Known barnacles:',
98 known.length === 0 ? '(none)' : known.join('\n'),
99 '',
100 'Friction by key:',
101 lines.length === 0 ? '(none)' : lines.join('\n'),
102 ].join('\n')
103}
104
105export function parseRecur(reply: string): Barnacle[] {
106 const raw = parseJsonObject(reply)?.barnacles
107 if (!Array.isArray(raw)) return []
108 const out: Barnacle[] = []
109 for (const item of raw) {
110 if (item === null || typeof item !== 'object') continue
111 const { key, text } = item as Record<string, unknown>
112 if (typeof key !== 'string' || typeof text !== 'string') continue
113 if (key.trim() === '' || text.trim() === '' || out.some((b) => b.key === key.trim())) continue
114 out.push({ key: key.trim(), text: text.trim(), spoken: false })
115 if (out.length === MAX_BARNACLES) break
116 }
117 return out
118}
119
120/** Parsed barnacles keep the spoken flag of a known one with the same key. */
121export function mergeBarnacles(existing: Barnacle[], parsed: Barnacle[]): Barnacle[] {
122 return parsed.map((p) => {
123 const known = existing.find((e) => e.key === p.key)
124 return { ...p, spoken: known?.spoken ?? false }
125 })
126}
127
128/** A scrub on record: when the key came off the shell, and what its barnacle said, so it can regrow at once. */
129export type ScrubRecord = { at: number; text: string }
130/** The scrubs on record, by barnacle key. */
131export type Scrubbed = Readonly<Record<string, ScrubRecord>>
132
133/** A stored scrub record; a bare number (the first cut's shape) is a scrub with no words kept. */
134export function asScrubbed(v: unknown): Scrubbed {
135 if (v === null || typeof v !== 'object' || Array.isArray(v)) return {}
136 const out: Record<string, ScrubRecord> = {}
137 for (const [k, rec] of Object.entries(v as Record<string, unknown>)) {
138 if (typeof rec === 'number') out[k] = { at: rec, text: '' }
139 else if (rec !== null && typeof rec === 'object' && typeof (rec as ScrubRecord).at === 'number') {
140 const text = (rec as ScrubRecord).text
141 out[k] = { at: (rec as ScrubRecord).at, text: typeof text === 'string' ? text : '' }
142 }
143 }
144 return out
145}
146
147/**
148 * The friction the recurrence pass may read after a scrub (/barnacles, 1.1): a scrubbed key
149 * forgets everything logged at or before its scrub. (New friction on that key regrows the
150 * barnacle at once through `regrown`, which also lifts the scrub.)
151 */
152export function afterScrub(log: Friction[], scrubbed: Scrubbed): Friction[] {
153 return log.filter((f) => f.at > (scrubbed[f.key]?.at ?? Number.NEGATIVE_INFINITY))
154}
155
156/** The shell without the barnacle `key` (every barnacle when `key` is null); a new list. */
157export function scrub(barnacles: Barnacle[], key: string | null): Barnacle[] {
158 return key === null ? [] : barnacles.filter((b) => b.key !== key).map((b) => ({ ...b }))
159}
160
161/** The scrub record with each of `gone` stamped `at`, its words kept for the regrowth; a new object. */
162export function stampScrub(scrubbed: Scrubbed, gone: readonly Barnacle[], at: number): Scrubbed {
163 return gone.reduce<Record<string, ScrubRecord>>((acc, b) => ({ ...acc, [b.key]: { at, text: b.text } }), { ...scrubbed })
164}
165
166/**
167 * The barnacle that regrows the moment friction `f` lands on a scrubbed key after its scrub
168 * (Bradley, 2026-10-09: "if the friction occurs again it should be an instant barnacle"):
169 * the old words, unspoken so it speaks again. Null when nothing regrows.
170 */
171export function regrown(scrubbed: Scrubbed, f: Friction): Barnacle | null {
172 const rec = scrubbed[f.key]
173 if (rec === undefined || f.at <= rec.at) return null
174 return { key: f.key, text: rec.text !== '' ? rec.text : `${f.detail}, again after a scrub.`, spoken: false }
175}
176
177/** The scrub record without `key`: a regrown barnacle's whole history is in view again. */
178export function unscrub(scrubbed: Scrubbed, key: string): Scrubbed {
179 return Object.fromEntries(Object.entries(scrubbed).filter(([k]) => k !== key))
180}
181
182export function nextToSpeak(barnacles: Barnacle[]): Barnacle | null {
183 return barnacles.find((b) => !b.spoken) ?? null
184}
185
186export function markSpoken(barnacles: Barnacle[], key: string): Barnacle[] {
187 return barnacles.map((b) => (b.key === key ? { ...b, spoken: true } : { ...b }))
188}
189hooks/body.ts 134 lines1import type { Body, Mood } from '../types'
2
3/**
4 * The one place the `body` option is read. `naut` is the documented value; `phi` is the older
5 * name for the same nautilus and stays accepted. The internal identifier stays `phi` (it keys
6 * the sprite, eye, blush and prop tables), so the rest of the code sees one canonical value.
7 * `phial` is the flask; anything else is the nautilus, as before the rename.
8 */
9export function bodyFromOption(value: unknown): Body {
10 return value === 'phial' ? 'phial' : 'phi'
11}
12
13const PALE: Record<Body, string> = { phi: '#CFC8BC', phial: '#BFD0D3' }
14const DEEP: Record<Body, string> = { phi: '#876D4C', phial: '#B9771F' }
15
16/**
17 * The inks the chime and the barnacles wear live, apart from the body colour, the way the
18 * metered eye already does (Bradley, 2026-10-09): iniphi teal for the bells, iniphi gold for
19 * the barnacles. A held write's safelight still colours the whole creature.
20 */
21export const INKS: Readonly<{ bells: string; barnacles: string; costume: string; hookGem: string; skillGem: string; blush: string; blushAmber: string }> = {
22 bells: '#649090',
23 barnacles: '#B59670',
24 // The gem on the shell (1.5, Bradley 2026-10-11): green for a hook candidate, blue for a skill candidate.
25 // Theme keys, never hex, so they follow the person's light or dark theme as the costume's error does.
26 hookGem: 'success',
27 skillGem: 'suggestion',
28 // A costume is red (Bradley's live look, 2026-10-09): the theme's error colour, never a hex, as the lab draws every prop.
29 costume: 'error',
30 // The blush (1.7, Bradley 2026-10-11) is the same theme key: red is one colour, and the extent says how bad.
31 blush: 'error',
32 // Amber below red (1.10.0, Bradley 2026-10-11): rung 1 and a refusal's afterglow wear the theme's warning colour.
33 blushAmber: 'warning',
34}
35
36function channel(hex: string, i: number): number {
37 return parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16)
38}
39
40function toHex(n: number): string {
41 return Math.round(n).toString(16).padStart(2, '0').toUpperCase()
42}
43
44/** Pale to deep as the developed share rises; null (no claims) counts as 0. */
45export function colourFor(body: Body, share: number | null): string {
46 const t = share === null || Number.isNaN(share) ? 0 : Math.max(0, Math.min(1, share))
47 const parts = [0, 1, 2].map((i) => {
48 const a = channel(PALE[body], i)
49 const b = channel(DEEP[body], i)
50 return toHex(a + (b - a) * t)
51 })
52 return '#' + parts.join('')
53}
54
55export type MoodInput = {
56 held: boolean
57 working: boolean
58 idle: boolean
59 pale: number
60 claims: number
61 asksDone: number
62 asksTotal: number
63 rowsLanded: boolean
64}
65
66export function moodFor(m: MoodInput): Mood {
67 if (m.held) return 'shielding'
68 if (m.rowsLanded) return 'alert'
69 if (m.idle) return 'resting'
70 if (m.pale > 0) return 'doubtful'
71 if (m.claims > 0 && m.pale === 0 && m.asksTotal > 0 && m.asksDone === m.asksTotal) return 'proud'
72 return 'calm'
73}
74
75export type SpeechInput = {
76 header: string
77 text: string
78 width: number
79 maxHeight: number
80 tailRow: number
81}
82
83/** Greedy word wrap; a word longer than the line is split. Never returns an empty list. */
84function wrap(text: string, width: number): string[] {
85 const lines: string[] = []
86 let line = ''
87 for (const raw of text.split(/\s+/).filter((w) => w.length > 0)) {
88 let word = raw
89 while (word.length > width) {
90 if (line) {
91 lines.push(line)
92 line = ''
93 }
94 lines.push(word.slice(0, width))
95 word = word.slice(width)
96 }
97 if (line && line.length + 1 + word.length > width) {
98 lines.push(line)
99 line = word
100 } else {
101 line = line ? line + ' ' + word : word
102 }
103 }
104 if (line) lines.push(line)
105 return lines.length > 0 ? lines : ['']
106}
107
108function cutTo(lines: string[], room: number, width: number): string[] {
109 if (lines.length <= room) return lines
110 const kept = lines.slice(0, room)
111 const last = kept[room - 1] ?? ''
112 const base = last.length + 3 > width ? last.slice(0, width - 3) : last
113 kept[room - 1] = base.replace(/\s+$/, '') + '...'
114 return kept
115}
116
117function topBorder(header: string, width: number): string {
118 const room = width - 2
119 const label = header ? ' ' + header + ' ' : ''
120 const shown = label.length > room - 1 ? label.slice(0, Math.max(0, room - 1)) : label
121 return '╭' + '─' + shown.padEnd(room - 1, '─') + '╮'
122}
123
124export function speechBox(s: SpeechInput): string[] {
125 const width = Math.max(6, Math.trunc(s.width))
126 const room = Math.max(1, Math.trunc(s.maxHeight) - 2)
127 const inner = width - 4
128 const body = cutTo(wrap(s.text, inner), room, inner)
129 const rows = body.map((t) => '│ ' + t.padEnd(inner, ' ') + ' │')
130 const tail = Math.max(1, Math.min(rows.length, Math.trunc(s.tailRow))) - 1
131 rows[tail] = '<' + (rows[tail] ?? '').slice(1)
132 return [topBorder(s.header, width), ...rows, '╰' + '─'.repeat(width - 2) + '╯']
133}
134hooks/sprites.ts 333 lines1// The companion's frames and the costumes it can wear. Pure: rows in, rows out.
2//
3// 1.1 (2026-10-09, Bradley's rulings in ../FAMILY.md section 2): the four watch bells hang
4// as a chime at the creature's back, the side away from its face, one per row from the
5// second row down (his live look: "one rung down"), with one blank column from the shell.
6// The band mirrors the art, so the back is the LEFT edge here and the right edge on screen.
7// The sprite is 14 columns for the chime (the full-size 28-column sprite was removed in 1.3.9).
8// Naut's shell top is low lines with an undertie wave (.__‿_., the
9// wave keeping the three animation positions) and its rim overlines with the tie ⁀ under
10// the wave, its mirror image, moving with it. Phial carries the same chime; its base is
11// plain. The props are masks over Naut's compact frame, ported from the ammonite
12// lab: razor \== and compass (<+) on the tentacle row, horn tips 6 and 6 on the shell's
13// corners. Each mask is stored facing right like the art, so the compass is (+>) here and
14// the horns 9 9: the band's mirror turns them. Preview outside Claude Code with
15// python scripts/sprite-preview.py [--mirror --band 80]
16// which reads one frame per line, so every frame below stays on its own line.
17
18import type { Body, Costume, Mood, Prop, Size } from '../types'
19
20type Frames = string[][]
21type Cell = [number, number]
22type PerFrame = Cell[][]
23type Table<T> = Record<Body, Record<Size, T>>
24
25/**
26 * Three animation frames per body: 5 rows x 14. The
27 * props follow as one-frame compact masks (spaces except their glyphs), which is how the
28 * preview tool tells a prop from a body.
29 */
30export const FRAMES: Table<Frames> & Record<Prop, { compact: Frames }> = {
31 phi: {
32 compact: [
33 [' .__‿_. ', '○ / .-. \\ ', '○ | ( @ ) o>~ ', '○ \\ `-\' /~ ', ' ‾‾⁀‾‾ '],
34 [' .__‿_. ', '○ / .-. \\ ', '○ | ( @ ) ->- ', '○ \\ `-\' /- ', ' ‾‾⁀‾‾ '],
35 [' ._‿__. ', '○ / .-. \\ ', '○ | ( @ ) o>≈ ', '○ \\ `-\' /≈ ', ' ‾⁀‾‾‾ '],
36 ],
37 },
38 phial: {
39 compact: [
40 [' |~~| ', '○ | | ', '○ / o o \\ ', '○ ( ~‿‿~ ) ', ' `------\' '],
41 [' |~~| ', '○ | o| ', '○ / - - \\ ', '○ ( ~‿‿~ ) ', ' `------\' '],
42 [' |o~| ', '○ | | ', '○ / o o \\ ', '○ ( ~‿‿~ ) ', ' `------\' '],
43 ],
44 },
45 razor: {
46 compact: [
47 // Bradley, 2026-10-09: '\==' on screen, on the tentacle row ahead of the tentacle's tip.
48 [' ', ' ', ' ', ' ==/', ' '],
49 ],
50 },
51 compass: {
52 compact: [
53 // '(<+)' on screen, its closing bracket taking the tentacle's tip (GRIP) so Naut holds it.
54 [' ', ' ', ' ', ' (+>)', ' '],
55 ],
56 },
57 horns: {
58 compact: [
59 // The tips read 6 and 6 on screen; the band's mirror turns a 9 into a 6.
60 [' 9 9 ', ' ', ' ', ' ', ' '],
61 ],
62 },
63 devil: {
64 compact: [
65 // The horns /(_‿__)\ over the shell top (1.3): the two corner dots and the blank cell
66 // outside each. Stored facing right; the band's mirror turns it. Worn by Naut for one
67 // draw while a guest drawing stands narrow above the band, never by /wear's atom alone.
68 [' /( )\\ ', ' ', ' ', ' ', ' '],
69 ],
70 },
71}
72
73/** Eye cells per frame ([row, col]); Naut has one, Phial two (left then right). */
74const EYES: Table<PerFrame> = {
75 phi: {
76 compact: [[[2, 10]], [[2, 10]], [[2, 10]]],
77 },
78 phial: {
79 compact: [[[2, 5], [2, 8]], [[2, 5], [2, 8]], [[2, 5], [2, 8]]],
80 },
81}
82
83/**
84 * The chime: three bell cells per frame, top to bottom, down the creature's back, the
85 * bottom bell on the tentacle row above the rim (Bradley, 2026-10-09: an hour a bell,
86 * filling from the bottom, and the bells start on the tentacle row, not the rim).
87 */
88const BELLS: Table<PerFrame> = {
89 phi: {
90 compact: [[[1, 0], [2, 0], [3, 0]], [[1, 0], [2, 0], [3, 0]], [[1, 0], [2, 0], [3, 0]]],
91 },
92 phial: {
93 compact: [[[1, 0], [2, 0], [3, 0]], [[1, 0], [2, 0], [3, 0]], [[1, 0], [2, 0], [3, 0]]],
94 },
95}
96
97/** Interior cells that are spaces in all three frames, in fill order. */
98const BARNACLES: Table<Cell[]> = {
99 phi: {
100 compact: [[1, 4], [1, 8], [3, 4], [3, 8]],
101 },
102 phial: {
103 compact: [[3, 3], [3, 4], [3, 9], [3, 10]],
104 },
105}
106
107/** The three extents of the safelight blush (1.7): the rim, then the shell's walls, then its top. */
108export type BlushPart = 'rim' | 'walls' | 'top'
109
110/**
111 * The shell cells the blush may redden, per body, as drawn (facing right). Read off the frames:
112 * the same non-space glyphs in all three, none a barnacle or gem cell, a bell or an eye, and
113 * never the coil. Naut: the rim under the wave, the side strokes `/ \ | \ /`, the top `.__‿_.`.
114 */
115const BLUSH: Table<Record<BlushPart, Cell[]>> = {
116 phi: {
117 compact: {
118 rim: [[4, 4], [4, 5], [4, 6], [4, 7], [4, 8]],
119 walls: [[1, 3], [1, 9], [2, 2], [3, 3], [3, 9]],
120 top: [[0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8]],
121 },
122 },
123 phial: {
124 compact: {
125 rim: [[4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10]],
126 walls: [[1, 5], [1, 8], [2, 3], [2, 10], [3, 2], [3, 11]],
127 top: [[0, 5], [0, 6], [0, 7], [0, 8]],
128 },
129 },
130}
131
132/** The parts of the shell a rung reddens: 1 the rim, 2 the rim and walls, 3 the rim, walls and top. */
133export const BLUSH_PARTS: Readonly<Record<1 | 2 | 3, readonly BlushPart[]>> = {
134 1: ['rim'],
135 2: ['rim', 'walls'],
136 3: ['rim', 'walls', 'top'],
137}
138
139/** The cells a rung reddens, as drawn (facing right); a rung outside 1 to 3 reddens nothing. */
140export function blushCellsOf(body: Body, size: Size, rung: number): Cell[] {
141 const parts = BLUSH_PARTS[rung as 1 | 2 | 3] ?? []
142 return parts.flatMap((p) => copyCells(BLUSH[body][size][p]))
143}
144
145/**
146 * The tentacle tip a held prop may take: the compass's bracket sits here so Naut grips it.
147 * The only tentacle cell any prop replaces.
148 */
149export const GRIP: Cell = [3, 10]
150
151/** The shell's two top corners, which the horns (and the devil, with the blank beside each) replace. */
152export const CORNERS: Cell[] = [[0, 3], [0, 8]]
153
154const FILLED = '●'
155const EMPTY = '○'
156/** Half a bell: thirty minutes. Mirrored to the right-half glyph by the band. */
157const HALF = '◐'
158
159const EYE_GLYPH: Record<Mood, string> = {
160 calm: 'o',
161 resting: '-',
162 alert: 'O',
163 shielding: '>',
164 doubtful: '.',
165 proud: '^',
166}
167
168export function frame(body: Body, size: Size, index: number): string[] {
169 const frames = FRAMES[body][size]
170 const i = ((Math.trunc(index) % frames.length) + frames.length) % frames.length
171 return frames[i] ?? []
172}
173
174function diffCount(a: string[], b: string[]): number {
175 let n = 0
176 a.forEach((row, r) => {
177 for (let c = 0; c < row.length; c++) if (row[c] !== (b[r] ?? '')[c]) n++
178 })
179 return n
180}
181
182/** Which frame these rows are: the nearest by cell difference, so edited rows still resolve. */
183function frameIndexOf(rows: string[], body: Body, size: Size): number {
184 const diffs = FRAMES[body][size].map((f) => diffCount(f, rows))
185 return diffs.indexOf(Math.min(...diffs))
186}
187
188function put(rows: string[], cells: Cell[], glyphs: string[]): string[] {
189 const out = rows.slice()
190 cells.forEach(([r, c], k) => {
191 const row = out[r] ?? ''
192 out[r] = row.slice(0, c) + glyphs[k] + row.slice(c + 1)
193 })
194 return out
195}
196
197const copyCells = (cells: Cell[]): Cell[] => cells.map(([r, c]) => [r, c] as Cell)
198
199function eyeGlyphs(body: Body, mood: Mood, n: number): string[] {
200 if (mood === 'shielding' && body === 'phial') return ['>', '<']
201 return Array.from({ length: n }, () => EYE_GLYPH[mood])
202}
203
204/** Where the eyes are in these rows, as drawn (facing right): [row, column] per eye. */
205export function eyeCellsOf(rows: string[], body: Body, size: Size): Cell[] {
206 return copyCells(EYES[body][size][frameIndexOf(rows, body, size)] ?? [])
207}
208
209/** The chime's three bell cells in these rows, top to bottom, as drawn (facing right). */
210export function bellCellsOf(rows: string[], body: Body, size: Size): Cell[] {
211 return copyCells(BELLS[body][size][frameIndexOf(rows, body, size)] ?? [])
212}
213
214/** The cells the first `count` barnacles occupy, as drawn (facing right). */
215export function barnacleCellsOf(body: Body, size: Size, count: number): Cell[] {
216 const all = BARNACLES[body][size]
217 const n = Math.max(0, Math.min(all.length, Math.trunc(count)))
218 return copyCells(all.slice(0, n))
219}
220
221export function withMood(rows: string[], body: Body, size: Size, mood: Mood): string[] {
222 const cells = EYES[body][size][frameIndexOf(rows, body, size)] ?? []
223 return put(rows, cells, eyeGlyphs(body, mood, cells.length))
224}
225
226/**
227 * The chime filled to `halves` half-bells from the bottom (1.1): the lowest bell takes the
228 * first two halves, then the one above it. A half is ◐, a whole ●, an empty bell ○.
229 */
230export function withBells(rows: string[], body: Body, size: Size, halves: number): string[] {
231 const cells = BELLS[body][size][frameIndexOf(rows, body, size)] ?? []
232 const n = Math.max(0, Math.min(2 * cells.length, Math.trunc(halves)))
233 const glyphs = cells.map((_, k) => {
234 const fromBottom = cells.length - 1 - k
235 const fill = Math.max(0, Math.min(2, n - 2 * fromBottom))
236 return fill === 2 ? FILLED : fill === 1 ? HALF : EMPTY
237 })
238 return put(rows, cells, glyphs)
239}
240
241export function withBarnacles(rows: string[], body: Body, size: Size, count: number): string[] {
242 const cells = barnacleCellsOf(body, size, count)
243 return put(rows, cells, cells.map(() => '*'))
244}
245
246/** What waits on the shell: barnacles, and the hook and skill candidates not yet settled. */
247export type DecorCounts = { barnacles: number; hooks: number; skills: number }
248
249/** The cells each kind of decoration got, as drawn (facing right). */
250export type Decor = { barnacles: Cell[]; hooks: Cell[]; skills: Cell[] }
251
252/** The gem: a bright faceted diamond, symmetric, so the band's mirror leaves it alone. */
253export const GEM = '◈'
254
255const wholeCount = (n: number): number => Math.max(0, Math.trunc(Number.isFinite(n) ? n : 0))
256
257/**
258 * How the shell's four decoration cells are shared (1.5, Bradley 2026-10-11): barnacles and the
259 * candidate gems use the same cells. Every kind present first gets one cell (three kinds at most,
260 * so it always fits); the cells left go to barnacles, then hooks, then skills, each up to its own
261 * count. With no candidates this is exactly the barnacles' own fill.
262 */
263export function shareCells(room: number, want: DecorCounts): DecorCounts {
264 const n = { barnacles: wholeCount(want.barnacles), hooks: wholeCount(want.hooks), skills: wholeCount(want.skills) }
265 const got = { barnacles: Math.min(1, n.barnacles), hooks: Math.min(1, n.hooks), skills: Math.min(1, n.skills) }
266 let left = Math.max(0, room - got.barnacles - got.hooks - got.skills)
267 for (const kind of ['barnacles', 'hooks', 'skills'] as const) {
268 const more = Math.min(left, n[kind] - got[kind])
269 got[kind] += more
270 left -= more
271 }
272 return got
273}
274
275/**
276 * The cells the shell's decorations occupy, per kind, taken from the barnacles' fill order:
277 * barnacles first, then the hook gems, then the skill gems.
278 */
279export function shellDecor(body: Body, size: Size, want: DecorCounts): Decor {
280 const all = BARNACLES[body][size]
281 const got = shareCells(all.length, want)
282 return {
283 barnacles: copyCells(all.slice(0, got.barnacles)),
284 hooks: copyCells(all.slice(got.barnacles, got.barnacles + got.hooks)),
285 skills: copyCells(all.slice(got.barnacles + got.hooks, got.barnacles + got.hooks + got.skills)),
286 }
287}
288
289/** The shell with its decorations drawn: `*` for a barnacle, the gem for a hook or skill candidate. */
290export function withDecor(rows: string[], decor: Decor): string[] {
291 const cells = [...decor.barnacles, ...decor.hooks, ...decor.skills]
292 const glyphs = [...decor.barnacles.map(() => '*'), ...decor.hooks.map(() => GEM), ...decor.skills.map(() => GEM)]
293 return put(rows, cells, glyphs)
294}
295
296export const PROPS: readonly Prop[] = ['razor', 'compass', 'horns', 'devil']
297
298/** The word after /wear: a prop, `none` (or `off`) to undress, null for anything else or nothing. */
299export function parseCostume(args: unknown): Costume | null {
300 const word = (typeof args === 'string' ? args : '').trim().toLowerCase()
301 if (word === 'none' || word === 'off') return 'none'
302 return PROPS.find((p) => p === word) ?? null
303}
304
305/** A prop's cells: every non-space cell of its mask, with the glyph it draws. */
306export function propCells(prop: Prop): Array<[number, number, string]> {
307 const mask = FRAMES[prop].compact[0] ?? []
308 const out: Array<[number, number, string]> = []
309 mask.forEach((row, r) => {
310 Array.from(row).forEach((ch, c) => {
311 if (ch !== ' ') out.push([r, c, ch])
312 })
313 })
314 return out
315}
316
317/**
318 * Naut's compact rows with the prop drawn over them; a new list, the input untouched. A
319 * prop is a costume on Naut only (one companion, one identity, the role shown by what it
320 * holds): on Phial the rows come back unchanged.
321 */
322export function withProp(rows: string[], body: Body, size: Size, prop: Prop): string[] {
323 if (body !== 'phi' || size !== 'compact') return rows.slice()
324 const out = rows.slice()
325 for (const [r, c, glyph] of propCells(prop)) {
326 const chars = Array.from(out[r] ?? '')
327 if (c >= chars.length) continue
328 chars[c] = glyph
329 out[r] = chars.join('')
330 }
331 return out
332}
333hooks/evidence.ts 316 lines1// The confirm channel (Bradley, S162): Claude tells the companion an ask is done,
2// and the companion believes it only on evidence it checks itself. A citation is a
3// tool call the companion observed in this session - a piece of its input, and
4// words found in its OUTPUT but not in its input, so a command cannot manufacture
5// its own proof (an `echo "verified"` cites itself and fails) - or words Bradley
6// typed himself, for what only he can witness, such as a layout. Pure.
7
8import type { Ask, AskWitness, Heard, Observed } from '../types'
9import { cleanText, isSessionAsk, restates } from './asks'
10import { DEFAULT_PERSON, onWords, personRef } from './config'
11
12export const CONFIRM_TOOL = 'mcp__witness__confirm'
13/**
14 * Calls kept as evidence. 200 ran out in one long turn (S163): the read-back an early
15 * ask rested on had aged out before the work was confirmed. Each entry is bounded
16 * (INPUT_CAP + RESULT_HEAD + RESULT_TAIL), so 600 is at most a few MB.
17 */
18export const OBSERVED_CAP = 600
19export const HEARD_CAP = 50
20/** The head and tail of a result are kept: a test run's verdict is at its end. */
21export const RESULT_HEAD = 1_500
22export const RESULT_TAIL = 2_500
23export const INPUT_CAP = 2_000
24export const MIN_EXCERPT = 6
25export const MIN_COMMAND = 3
26
27export type Evidence =
28 | { source: 'call'; command: string; excerpt: string }
29 | { source: 'user'; excerpt: string }
30
31/** `outcome: 'dropped'` (0.6.2, a field report): the user called the ask off; absent means done. */
32export type ConfirmItem = { ask: string; evidence: Evidence[]; outcome?: 'dropped' }
33
34export type Verdict = {
35 ask: string
36 askId: string | null
37 ok: boolean
38 reason: string
39 refs: string[]
40 dropped?: boolean
41}
42
43const INPUT_KEYS = ['command', 'query', 'file_path', 'path', 'pattern', 'id', 'page_id', 'url', 'name']
44
45/** A tool call's input as text: its command, query or path, else the whole input as JSON. */
46export function inputText(input: Readonly<Record<string, unknown>>): string {
47 const picked = INPUT_KEYS.map(k => input[k]).filter((v): v is string => typeof v === 'string')
48 const text = picked.length > 0 ? picked.join(' ') : JSON.stringify(input)
49 return text.slice(0, INPUT_CAP)
50}
51
52export function trimResult(text: string): string {
53 if (text.length <= RESULT_HEAD + RESULT_TAIL) return text
54 return `${text.slice(0, RESULT_HEAD)}\n...\n${text.slice(-RESULT_TAIL)}`
55}
56
57/** Tools whose result is a subagent's report, or its launch notice (1.1). */
58export const REPORT_TOOLS: ReadonlySet<string> = new Set(['Agent', 'Task', 'TaskOutput', 'Workflow'])
59
60/**
61 * A call whose output may never be cited (1.1, ruled 2026-10-09): a subagent's own call,
62 * or an Agent, Task, TaskOutput or Workflow result (a Workflow's result relays its agents'
63 * reports). A report is a claim the main session reads
64 * back, never the read-back itself.
65 */
66export function isReport(o: Pick<Observed, 'tool' | 'agent'>): boolean {
67 return o.agent || REPORT_TOOLS.has(o.tool)
68}
69
70/**
71 * Appends one observed call, newest kept. Never the confirm tool's own, and never a
72 * subagent's (1.1): nothing a subagent ran is evidence, so it would only push the main
73 * loop's read-backs out of the window.
74 */
75export function observe(log: readonly Observed[], o: Observed): Observed[] {
76 if (o.tool === CONFIRM_TOOL || o.agent) return [...log]
77 const kept: Observed = { ...o, input: o.input.slice(0, INPUT_CAP), result: trimResult(o.result) }
78 return [...log, kept].slice(-OBSERVED_CAP)
79}
80
81export function hear(log: readonly Heard[], h: Heard): Heard[] {
82 return [...log, h].slice(-HEARD_CAP)
83}
84
85const norm = (s: string): string => cleanText(s).toLowerCase()
86
87/**
88 * Text as the model read it: an MCP result arrives JSON-encoded inside the tool-result
89 * envelope, so its quotes are stored as \" or \\\" (two or three escapes deep; one level
90 * was not enough, seen live in S163) and a quoted excerpt would never match. Any run of
91 * backslashes before a quote or an n is undone. Applied to input and output alike, so the
92 * input-must-not-contain-the-excerpt rule still binds.
93 */
94const unescaped = (s: string): string => s.replace(/\\+"/g, '"').replace(/\\+n/g, ' ')
95
96/** Does `text` contain `excerpt`, as stored or with its JSON-escaped quotes undone? */
97const holds = (text: string, excerpt: string): boolean =>
98 norm(text).includes(excerpt) || norm(unescaped(text)).includes(excerpt)
99
100/** The ref of the observed call or heard prompt that bears this evidence out, made after `since`; else null. */
101export function bearsOut(e: Evidence, observed: readonly Observed[], heard: readonly Heard[], since: number): string | null {
102 const excerpt = norm(e.excerpt)
103 if (excerpt.length < MIN_EXCERPT) return null
104 if (e.source === 'user') {
105 const h = heard.find(x => x.at >= since && norm(x.text).includes(excerpt))
106 return h === undefined ? null : `user@${h.at}`
107 }
108 const command = norm(e.command)
109 if (command.length < MIN_COMMAND) return null
110 const o = observed.find(
111 x =>
112 x.at >= since &&
113 !x.isError &&
114 x.tool !== CONFIRM_TOOL &&
115 !isReport(x) &&
116 holds(x.input, command) &&
117 holds(x.result, excerpt) &&
118 !holds(x.input, excerpt),
119 )
120 return o === undefined ? null : o.toolUseId
121}
122
123/** An ask by id, else by its text (exact, then a unique containment either way), ignoring dropped asks. */
124export function findAsk(asks: readonly Ask[], key: string): Ask | null {
125 const live = asks.filter(a => a.state !== 'dropped')
126 const byId = live.find(a => a.id === key)
127 if (byId) return byId
128 const k = norm(key)
129 if (k.length === 0) return null
130 const exact = live.find(a => norm(a.text) === k)
131 if (exact) return exact
132 const near = live.filter(a => norm(a.text).includes(k) || k.includes(norm(a.text)))
133 if (near.length > 0) return near.length === 1 ? (near[0] ?? null) : null
134 // A close paraphrase, when one live ask clearly wins (a field report: five of five
135 // free-text confirms missed and needed a second call). A tie at the top is never guessed.
136 const scored = live.flatMap(a => {
137 const share = restates(a.text, key)
138 return share === null ? [] : [{ a, share }]
139 })
140 const top = Math.max(0, ...scored.map(x => x.share))
141 const best = scored.filter(x => x.share === top)
142 return best.length === 1 ? (best[0]?.a ?? null) : null
143}
144
145function judge(item: ConfirmItem, ask: Ask, observed: readonly Observed[], heard: readonly Heard[], person: string): Verdict {
146 const base = { ask: item.ask, askId: ask.id, refs: [] as string[] }
147 if (ask.state === 'witnessed') return { ...base, ok: true, reason: 'already witnessed' }
148 if (item.evidence.length === 0) return { ...base, ok: false, reason: 'no evidence cited' }
149 // A drop rests on the user alone: the model may not call off an ask on its own say.
150 if (item.outcome === 'dropped' && !item.evidence.some(e => e.source === 'user')) {
151 return { ...base, ok: false, reason: `a drop needs ${personRef(person)}'s own words calling the ask off (source user)` }
152 }
153 const refs = item.evidence.map(e => bearsOut(e, observed, heard, ask.at))
154 const missing = refs.findIndex(r => r === null)
155 if (missing !== -1) {
156 const e = item.evidence[missing]
157 const why =
158 e?.source === 'user'
159 ? `those words are not in any of ${personRef(person)}'s prompts since the ask was raised`
160 : 'no call since the ask was raised has that input with that excerpt in its output (and not in its input)'
161 return { ...base, ok: false, reason: `evidence ${missing + 1} did not check out: ${why}` }
162 }
163 const proved = refs.filter((r): r is string => r !== null)
164 if (item.outcome === 'dropped') return { ...base, ok: true, reason: `called off ${onWords(person)}`, refs: proved, dropped: true }
165 return { ...base, ok: true, reason: 'witnessed', refs: proved }
166}
167
168/** Checks every item; an ask whose every citation checks out becomes witnessed. */
169export function confirmAsks(
170 asks: readonly Ask[],
171 items: readonly ConfirmItem[],
172 observed: readonly Observed[],
173 heard: readonly Heard[],
174 now: number,
175 person: string = DEFAULT_PERSON,
176): { asks: Ask[]; verdicts: Verdict[] } {
177 const verdicts: Verdict[] = items.map(item => {
178 const ask = findAsk(asks, item.ask)
179 if (ask === null) return { ask: item.ask, askId: null, ok: false, reason: 'no single live ask matches that', refs: [] }
180 return judge(item, ask, observed, heard, person)
181 })
182 const passed = new Map(verdicts.filter(v => v.ok && v.askId !== null && v.refs.length > 0).map(v => [v.askId, v]))
183 const next = asks.map((a): Ask => {
184 const v = passed.get(a.id)
185 if (v === undefined) return { ...a }
186 if (v.dropped) return { ...a, state: 'dropped', calledOff: { refs: v.refs, at: now } }
187 const by: AskWitness['by'] = v.refs.some(r => r.startsWith('user@')) ? 'user' : 'evidence'
188 return { ...a, state: 'witnessed', witness: { by, refs: v.refs, at: now } }
189 })
190 return { asks: next, verdicts }
191}
192
193/** Parses the tool's input defensively; anything malformed is dropped, never thrown. */
194export function parseItems(input: unknown): ConfirmItem[] {
195 const raw = (input as { items?: unknown })?.items
196 if (!Array.isArray(raw)) return []
197 return raw.flatMap(item => {
198 const ask = (item as { ask?: unknown })?.ask
199 const ev = (item as { evidence?: unknown })?.evidence
200 if (typeof ask !== 'string' || !Array.isArray(ev)) return []
201 const evidence = ev.flatMap((e): Evidence[] => {
202 const x = e as { source?: unknown; command?: unknown; excerpt?: unknown }
203 if (typeof x?.excerpt !== 'string') return []
204 if (x.source === 'user') return [{ source: 'user', excerpt: x.excerpt }]
205 if (x.source === 'call' && typeof x.command === 'string') return [{ source: 'call', command: x.command, excerpt: x.excerpt }]
206 return []
207 })
208 const dropped = (item as { outcome?: unknown })?.outcome === 'dropped'
209 return [dropped ? { ask, outcome: 'dropped' as const, evidence } : { ask, evidence }]
210 })
211}
212
213/** The tool's answer to the model: one line per item, then the asks still undone with their ids. */
214export function confirmReport(verdicts: readonly Verdict[], asks: readonly Ask[], closeName = '/close'): string {
215 const head = (v: Verdict) => (!v.ok ? 'NOT WITNESSED' : v.dropped ? 'DROPPED' : 'WITNESSED')
216 const lines = verdicts.map(v => `${head(v)} - ${v.ask}: ${v.reason}`)
217 // A build is held for /close, never listed as this session's undone work (0.6.0), and a
218 // carried ask is the last watch's, listed apart so it is never read as this session's.
219 const undoneHere = (a: Ask) => a.settled === undefined && (a.state === 'open' || a.state === 'claimed')
220 const open = asks.filter(a => isSessionAsk(a) && undoneHere(a))
221 const carried = asks.filter(a => a.source === 'carried' && undoneHere(a))
222 const builds = asks.filter(a => a.source === 'build' && a.state !== 'dropped').length
223 const row = (a: Ask) => ` ${a.id}: ${a.text}`
224 const tail =
225 open.length > 0
226 ? ['Still undone:', ...open.map(row)]
227 : [carried.length > 0 ? 'Nothing undone this session.' : 'Nothing undone.']
228 const fromLast = carried.length === 0 ? [] : ['Carried in from the last watch (not counted in asks n/m):', ...carried.map(row)]
229 const held = builds === 0 ? [] : [`(${builds} build${builds === 1 ? '' : 's'} held for ${closeName}, to become to-dos)`]
230 return [...lines, ...tail, ...fromLast, ...held].join('\n')
231}
232
233/** The confirm tool's input schema, naming the person as the model reads it. */
234export function confirmSchema(person: string): Record<string, unknown> {
235 const who = personRef(person)
236 return {
237 type: 'object',
238 properties: {
239 items: {
240 type: 'array',
241 items: {
242 type: 'object',
243 properties: {
244 ask: { type: 'string', description: 'The ask id, or its text as /undone shows it.' },
245 outcome: {
246 type: 'string',
247 enum: ['done', 'dropped'],
248 description:
249 `done (the default): the work is done, cite read-backs. dropped: ${who} called the ask off; cite those words (source user), the only evidence a drop takes.`,
250 },
251 evidence: {
252 type: 'array',
253 items: {
254 type: 'object',
255 properties: {
256 source: { type: 'string', enum: ['call', 'user'] },
257 command: {
258 type: 'string',
259 description: 'source call: a piece of the input of a tool call made in this session (the Bash command, the SQL, the path).',
260 },
261 excerpt: {
262 type: 'string',
263 description: `call: words from that call's OUTPUT that are not in its input. user: words ${who} typed in one of their prompts.`,
264 },
265 },
266 required: ['source', 'excerpt'],
267 },
268 },
269 },
270 required: ['ask', 'evidence'],
271 },
272 },
273 },
274 required: ['items'],
275 }
276}
277
278export const CONFIRM_SCHEMA: Record<string, unknown> = confirmSchema(DEFAULT_PERSON)
279
280/** The confirm tool's description, naming the person as the model reads it. */
281export function confirmDescription(person: string): string {
282 const who = personRef(person)
283 return (
284 'Tell the witness companion that undone asks are done, with evidence it checks itself. ' +
285 'Confirm an ask in the same turn as its read-back, before calling it done: a later bulk confirm redoes the read-backs. ' +
286 'For each ask cite evidence from a read-back made AFTER the ask was raised: ' +
287 '{source:"call", command:<a piece of a tool call\'s input from this session>, excerpt:<words in that call\'s output, not in its input>}, ' +
288 `or, for what only ${who} can witness (a layout), {source:"user", excerpt:<words ${who} typed>}. ` +
289 `Only the first ${RESULT_HEAD} and last ${RESULT_TAIL} characters of an output are kept, ` +
290 'so cite a short read-back (a grep or narrow query of the passage), never the middle of a long one. ' +
291 'Every citation must check out or the ask stays undone; a claim is not evidence, ' +
292 "nor is a subagent's report or its own calls (an Agent, Task or TaskOutput result): read back what it changed. " +
293 `When ${who} called an ask off, pass outcome "dropped" with those words as {source:"user"} evidence: ` +
294 'the ask is then neither done nor undone, and never carried. Never drop an ask on your own judgement.'
295 )
296}
297
298export const CONFIRM_DESCRIPTION = confirmDescription(DEFAULT_PERSON)
299
300/** Most asks one note names; the rest wait for the next. */
301export const NOTE_MAX_ASKS = 5
302
303/**
304 * The one line put to Claude on Bradley's next prompt when a turn ended with asks it
305 * called done but never proved (Bradley, S165, option B): about 40 tokens, once per ask,
306 * against a /tackle sweep that redoes the read-backs later.
307 */
308export function unprovedNote(asks: ReadonlyArray<{ id: string; text: string }>): string {
309 // Each with its id, so one confirm call closes it (a field report: the model cannot run /undone).
310 const list = asks
311 .slice(0, NOTE_MAX_ASKS)
312 .map(a => `${a.id}: "${a.text}"`)
313 .join('; ')
314 return `witness: claimed done but not proved by a read-back: ${list}. Read each back and confirm it with ${CONFIRM_TOOL} in this turn, citing the id.`
315}
316hooks/content.ts 169 lines1// Content-checked claims (1.15). A write whose new text is known (an Edit's
2// new_string, a Write's content, a sed -i replacement) carries a short mark: a line
3// of the new text that the old text does not hold, and, where the old text is known,
4// a line of it the new text does not hold. A later read develops the write only when
5// its output shows the new mark; a read that shows the old mark and not the new one
6// contradicts it. A grep that still finds the old text is no longer a read-back.
7// Pure: no DOM, no Node, no $; never mutates.
8
9import type { ContentMark, Touch } from '../types'
10import { ALL_FILES, normPath } from './classify'
11
12/** A mark shorter than this, once whitespace is collapsed, says too little to check: none is kept. */
13export const MIN_MARK = 8
14/** A mark is at most this long: the head of its line, so a long line still matches in a cut window. */
15export const MARK_MAX = 80
16
17/** Text as a read shows it: JSON-escaped quotes and newlines undone, whitespace collapsed, lower case. */
18export function flat(text: string): string {
19 return text
20 .replace(/\\+"/g, '"')
21 .replace(/\\+[nt]/g, ' ')
22 .replace(/\s+/g, ' ')
23 .trim()
24 .toLowerCase()
25}
26
27/** The longest line of `text` that `other` does not hold, flattened and cut to MARK_MAX; null below MIN_MARK. */
28export function markOf(text: string, other = ''): string | null {
29 const rest = flat(other)
30 const lines = text
31 .split(/\r?\n/)
32 .map((l) => flat(l).slice(0, MARK_MAX))
33 .filter((l) => l.length >= MIN_MARK && !rest.includes(l))
34 if (lines.length === 0) return null
35 return lines.reduce((a, b) => (b.length > a.length ? b : a))
36}
37
38function mark(next: string, prev = ''): ContentMark | undefined {
39 const fresh = markOf(next, prev)
40 if (fresh === null) return undefined
41 const old = prev === '' ? null : markOf(prev, next)
42 return old === null ? { fresh } : { fresh, old }
43}
44
45const str = (v: unknown): string => (typeof v === 'string' ? v : '')
46
47// sed's s command: a delimiter, the pattern, the replacement, flags. Only a literal
48// replacement is marked (a & or a backslash names text the mark cannot spell), and
49// the pattern is an old mark only when it holds no regex metacharacter.
50const SED_S = /^s(.)(.*?)(?<!\\)\1(.*?)(?<!\\)\1[a-z0-9]*$/i
51const REGEX_META = /[.*[\]^$\\+?(){}|]/
52
53/** The quoted words of one shell segment, quotes removed. */
54function shellWords(seg: string): string[] {
55 const out: string[] = []
56 const re = /'([^']*)'|"((?:[^"\\]|\\.)*)"|(\S+)/g
57 for (let m = re.exec(seg); m !== null; m = re.exec(seg)) out.push(m[1] ?? m[2] ?? m[3] ?? '')
58 return out
59}
60
61/** A command cut at its separators (&&, ||, |, ;, newline) outside quotes. */
62function segments(command: string): string[] {
63 const out: string[] = []
64 let cur = ''
65 let quote = ''
66 for (let i = 0; i < command.length; i++) {
67 const c = command[i] ?? ''
68 if (quote !== '') {
69 if (c === quote) quote = ''
70 cur += c
71 } else if (c === "'" || c === '"') {
72 quote = c
73 cur += c
74 } else if (c === ';' || c === '\n' || c === '|' || (c === '&' && command[i + 1] === '&')) {
75 out.push(cur)
76 cur = ''
77 if (command[i + 1] === c) i++
78 } else cur += c
79 }
80 return [...out, cur]
81}
82
83type SedEdit = { files: string[]; mark: ContentMark }
84
85/** Each `sed -i 's/a/b/' file...` in a command: its files and the mark of its replacement. */
86export function sedEdits(command: string): SedEdit[] {
87 const edits: SedEdit[] = []
88 for (const seg of segments(command)) {
89 const ws = shellWords(seg.trim())
90 if ((ws[0] ?? '').replace(/^.*\//, '') !== 'sed') continue
91 const args = ws.slice(1)
92 if (!args.some((a) => /^-[a-z]*i/i.test(a) || a.startsWith('--in-place'))) continue
93 let script: string | null = null
94 let scripts = 0
95 const files: string[] = []
96 for (let i = 0; i < args.length; i++) {
97 const a = args[i] ?? ''
98 if (a === '-e' || a === '--expression') {
99 scripts++
100 script = args[++i] ?? ''
101 } else if (a.startsWith('-')) continue
102 else if (script === null) {
103 scripts++
104 script = a
105 } else files.push(a)
106 }
107 // Several scripts: which one a read should show is not known, so none is marked.
108 const s = scripts === 1 ? SED_S.exec(script ?? '') : null
109 if (s === null || files.length === 0) continue
110 const [, , pattern = '', replacement = ''] = s
111 if (/[&\\]/.test(replacement)) continue
112 const fresh = markOf(replacement)
113 if (fresh === null) continue
114 const old = REGEX_META.test(pattern) ? null : markOf(pattern, replacement)
115 edits.push({ files, mark: old === null ? { fresh } : { fresh, old } })
116 }
117 return edits
118}
119
120/** Does the file write `target` name this sed file argument (the same path, or a path ending in it)? */
121function names(target: string, file: string): boolean {
122 const f = normPath(file)
123 return f !== '' && (target === f || target.endsWith(`/${f}`))
124}
125
126/**
127 * The marks of a call's writes, by index (undefined: no mark, so presence still
128 * develops it). Only file writes are marked, and only from a tool whose new text
129 * is in its input.
130 */
131export function writeMarks(tool: string, input: Readonly<Record<string, unknown>>, writes: readonly Touch[]): Array<ContentMark | undefined> {
132 const forFile = (m: ContentMark | undefined) => writes.map((w) => (w.kind === 'file' ? m : undefined))
133 switch (tool) {
134 case 'Edit':
135 return forFile(mark(str(input.new_string), str(input.old_string)))
136 case 'Write':
137 return forFile(mark(str(input.content)))
138 case 'NotebookEdit':
139 return forFile(mark(str(input.new_source)))
140 case 'MultiEdit': {
141 const edits = Array.isArray(input.edits) ? (input.edits as Array<Record<string, unknown>>) : []
142 const last = edits[edits.length - 1]
143 return forFile(last === undefined ? undefined : mark(str(last.new_string), str(last.old_string)))
144 }
145 case 'Bash': {
146 const edits = sedEdits(str(input.command))
147 if (edits.length === 0) return writes.map(() => undefined)
148 return writes.map((w) => (w.kind === 'file' ? edits.find((e) => e.files.some((f) => names(w.target, f)))?.mark : undefined))
149 }
150 default:
151 return writes.map(() => undefined)
152 }
153}
154
155/** A test run reads every file but shows none of their text: it keeps presence. */
156export const showsText = (read: Touch): boolean => read.target !== ALL_FILES
157
158/**
159 * What a covering read's output says of a marked write: `shown` (the new mark is in
160 * it), `contradicted` (the old mark is, the new one is not), or `silent`. A write with
161 * no mark, or a read that shows no text (a test run), is `shown`: presence, as before.
162 */
163export function verdict(read: Touch, output: string | undefined, m: ContentMark | undefined): 'shown' | 'contradicted' | 'silent' {
164 if (m === undefined || !showsText(read)) return 'shown'
165 const seen = flat(output ?? '')
166 if (seen.includes(m.fresh)) return 'shown'
167 return m.old !== undefined && seen.includes(m.old) ? 'contradicted' : 'silent'
168}
169hooks/notes.ts 523 lines1// Two sections of the Witness print, ruled by Bradley in S163 (2026-10-07):
2//
3// - "Notes taken": what the witness itself SAW this watch - writes it held and how they
4// were answered, friction (cancelled writes, repeated failures, re-edits), and what it
5// said in its bubble. Built only from ledgers it already keeps; nothing is extracted.
6// - "Hook and skill candidates": a side pass reads recurring friction and the session's
7// call digest and proposes "this could be a hook" (an event-bound guard or check) or
8// "this could be a skill" (a repeated multi-step procedure), each with its evidence.
9// Listed in the print and appended to one running file. Proposals only: the witness
10// never builds a hook or a skill. Pure.
11
12import type { Candidate, Friction, Observed, Spoken } from '../types'
13import { cleanText, normalise, parseJsonObject } from './asks'
14import { GAP_CHARS, GAP_WHY, MAX_GAP_CANDIDATES, hasProcedureShape, isTestAfterEditHook } from './charter'
15
16export const SPOKEN_CAP = 60
17export const NOTES_CAP = 25
18export const MAX_CANDIDATES = 5
19export const CANDIDATES_KEPT = 40
20/** The candidate pass runs at most this often, and only after this many new calls. */
21export const CANDIDATE_SCAN_MS = 30 * 60_000
22export const CANDIDATE_MIN_NEW_CALLS = 25
23export const DIGEST_CALLS = 150
24const DIGEST_CHARS = 100
25const TITLE_CHARS = 80
26const WHY_CHARS = 160
27const EVIDENCE_CHARS = 200
28
29/** Headers that are not notes: the print announcing itself. */
30const NOT_A_NOTE = new Set(['PRINT'])
31
32const one = (text: string, max: number): string => {
33 const t = cleanText(text)
34 return t.length <= max ? t : `${t.slice(0, max - 3)}...`
35}
36
37/** Records one thing the companion said; an immediate repeat collapses, the newest are kept. */
38export function noteSpoken(log: readonly Spoken[], said: Spoken): Spoken[] {
39 const last = log[log.length - 1]
40 if (last !== undefined && last.header === said.header && last.text === said.text) return [...log]
41 return [...log, { ...said }].slice(-SPOKEN_CAP)
42}
43
44/** The header a note from beneath is recorded under. */
45export const HEADS_UP = 'HEADS UP'
46
47/** Records a note heard from beneath once per watch: one already in the log, anywhere, is not added again. */
48export function noteHeard(log: readonly Spoken[], said: Spoken): Spoken[] {
49 const seen = log.some(x => x.header === said.header && x.text === said.text)
50 return seen ? [...log] : [...log, { ...said }].slice(-SPOKEN_CAP)
51}
52
53function frictionLine(f: Friction): string {
54 const key = one(f.key, 120)
55 const detail = one(f.detail, 160)
56 switch (f.kind) {
57 case 'cancelled-write':
58 return `- held or cancelled write: ${key} - ${detail}`
59 case 'let-through':
60 return `- let through once: ${key} - ${detail}`
61 case 'returning-added':
62 return `- held, RETURNING added: ${key} - ${detail}`
63 case 'tool-failure':
64 return `- repeated failure: ${key} - ${detail}`
65 case 're-edit':
66 return `- re-edited three times: ${key}`
67 }
68}
69
70/** The "Notes taken" lines for the print: this watch only, one line per note. */
71export function notesSection(o: { friction: readonly Friction[]; spoken: readonly Spoken[]; since: number }): string[] {
72 const events = [
73 ...o.friction.filter(f => f.at >= o.since).map(f => ({ at: f.at, line: frictionLine(f) })),
74 ...o.spoken
75 .filter(x => x.at >= o.since && !NOT_A_NOTE.has(x.header))
76 .map(x => ({ at: x.at, line: `- said (${one(x.header, 40)}): ${one(x.text, 200)}` })),
77 ].sort((a, b) => a.at - b.at)
78 const lines = [...new Set(events.map(e => e.line))]
79 const head = ['### Notes taken', '']
80 if (lines.length === 0) return [...head, '- Nothing noted.']
81 const kept = lines.slice(0, NOTES_CAP)
82 const more = lines.length - kept.length
83 return more > 0 ? [...head, ...kept, `- ... and ${more} more`] : [...head, ...kept]
84}
85
86/**
87 * Turn tags (1.8, Bradley 2026-10-11): a parallel batch of calls inside one turn is one event, not
88 * several. Each distinct turn id gets `[t1]`, `[t2]` ... in order of first appearance among the
89 * main-session calls; calls recorded without a turn get no tag.
90 */
91export function turnTagMap(observed: readonly Observed[]): Map<string, string> {
92 const tags = new Map<string, string>()
93 for (const o of observed) {
94 if (o.agent || o.turn === undefined || tags.has(o.turn)) continue
95 tags.set(o.turn, `[t${tags.size + 1}]`)
96 }
97 return tags
98}
99
100const tagged = (tag: string | undefined, text: string): string => (tag === undefined ? text : `${tag} ${text}`)
101
102/**
103 * A short, stable session tag (Bradley, 2026-10-11, "Two sessions"): five hex characters of an
104 * FNV-1a hash of the session id, so the band, the print and the public export never carry a
105 * session id. `?` is the one unknown session: friction stored before sessions were kept.
106 */
107export function sessionTag(id: string | undefined): string {
108 if (id === undefined || id === '') return '?'
109 let h = 0x811c9dc5
110 for (let i = 0; i < id.length; i++) h = Math.imul(h ^ id.charCodeAt(i), 0x01000193) >>> 0
111 return h.toString(16).padStart(8, '0').slice(0, 5)
112}
113
114const sessionTagged = (session: string | undefined, turn: string | undefined): string | undefined => {
115 if (session === undefined) return turn
116 return `[s${session}${turn === undefined ? '' : ` ${turn}`}]`
117}
118
119/** `t3` out of a `[t3]` turn tag. */
120const turnPart = (tag: string | undefined): string | undefined => (tag === undefined ? undefined : tag.slice(1, -1))
121
122/**
123 * This session's main-session calls, one short line each, newest last, each tagged with its turn.
124 * With `session` (this session's tag) the tag is `[s3f2a t2]`, so a quoted tag names a session.
125 */
126export function callDigest(observed: readonly Observed[], max = DIGEST_CALLS, session?: string): string[] {
127 const tags = turnTagMap(observed)
128 return observed
129 .filter(o => !o.agent)
130 .slice(-max)
131 .map(o => {
132 const turn = o.turn === undefined ? undefined : tags.get(o.turn)
133 const tag = session === undefined ? turn : sessionTagged(session, turnPart(turn))
134 return tagged(tag, one(`${o.tool}: ${o.input}`, DIGEST_CHARS))
135 })
136}
137
138/** Friction with the session and turn it fell in, when known. */
139export type TaggedFriction = Friction & { tag?: string }
140
141/**
142 * Each friction tagged. With `self` (this session's id): friction of another session carries only
143 * its session, `[s9c41]` (turn ids restart in each session, so its turn means nothing here);
144 * friction with no session is the one unknown session, `[s?]`; this session's own carries the turn
145 * of the latest main-session call at or before it, `[s3f2a t2]`. Without `self`, turn tags only.
146 */
147export function tagFriction(friction: readonly Friction[], observed: readonly Observed[], self?: string): TaggedFriction[] {
148 const tags = turnTagMap(observed)
149 const calls = observed.filter(o => !o.agent && o.turn !== undefined).sort((a, b) => a.at - b.at)
150 return friction.map(f => {
151 if (self !== undefined && f.session !== self) return { ...f, tag: `[s${sessionTag(f.session)}]` }
152 let turn: string | undefined
153 for (const o of calls) {
154 if (o.at > f.at) break
155 turn = o.turn
156 }
157 const turnTag = turn === undefined ? undefined : tags.get(turn)
158 const tag = self === undefined ? turnTag : sessionTagged(sessionTag(self), turnPart(turnTag))
159 return tag === undefined ? { ...f } : { ...f, tag }
160 })
161}
162
163const TAG_RE = /\[(?:s[0-9a-f?]{1,6}\s+)?t(\d+)\]/g
164const SESSION_RE = /\[s([0-9a-f]{4,6}|\?)(?:\s+t\d+)?\]/g
165
166/** How many distinct turn tags a text cites. */
167export function distinctTurns(text: string): number {
168 return new Set([...text.matchAll(TAG_RE)].map(m => m[1])).size
169}
170
171/** How many distinct SESSION tags a text cites (`[s3f2a t2]`, `[s9c41]`, `[s?]`): a jewel needs two. */
172export function distinctSessions(text: string): number {
173 return new Set([...text.matchAll(SESSION_RE)].map(m => m[1])).size
174}
175
176/** A script in the session repo's scripts/ folder, with its first docstring or comment line. */
177export type ScriptNote = { name: string; summary: string }
178/** The `#`/`##` headings of one CLAUDE.md the session loads. */
179export type HeadingNote = { file: string; headings: readonly string[] }
180
181export const MAX_SCRIPTS = 40
182export const MAX_HEADINGS = 40
183const SCRIPT_SUMMARY = 80
184
185/** The first docstring or comment line of a script's text; '' when it has none. Pure. */
186export function scriptSummary(text: string): string {
187 for (const raw of text.split(/\r?\n/).slice(0, 25)) {
188 const line = raw.trim()
189 if (line === '' || line.startsWith('#!') || /^(["']{3}|\/\*+)$/.test(line)) continue
190 const m = /^(?:#+|\/\/+|--|rem\b|\/\*+|\*|"""|''')\s*(.*?)(?:\*\/|"""|''')?$/i.exec(line)
191 if (m !== null && m[1] !== undefined && m[1].trim() !== '') return one(m[1], SCRIPT_SUMMARY)
192 if (m === null) return ''
193 }
194 return ''
195}
196
197/** The `#` and `##` headings of a markdown text, in order. Pure. */
198export function mdHeadings(text: string): string[] {
199 const out: string[] = []
200 let fenced = false
201 for (const raw of text.split(/\r?\n/)) {
202 if (/^\s*(```|~~~)/.test(raw)) fenced = !fenced
203 if (fenced) continue
204 const m = /^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(raw)
205 if (m !== null && m[2] !== undefined) out.push(one(m[2], 70))
206 }
207 return out
208}
209
210/** Installed slash commands the candidate pass is shown, at most, and each description's length. */
211export const MAX_INSTALLED = 80
212const INSTALLED_DESC = 90
213
214/**
215 * One installed guard or mod. `covers`: term sets, any one of which, all its terms found
216 * (lowercase substrings) in a hook candidate's title and why, means the guard already does it.
217 */
218export type Guard = {
219 name: string
220 where: string
221 does: string
222 covers: ReadonlyArray<readonly string[]>
223 disabled?: boolean
224}
225
226/**
227 * The installed guards and mods (to-do 3f23...b0be, second half), from the wired-hooks
228 * table in ~/.claude/rules/common/hooks.md and the estate's CLAUDE.md "Supabase write
229 * paths". Static: edit it when a guard or a mod is wired, unwired or retired.
230 */
231export const INSTALLED_GUARDS: readonly Guard[] = [
232 { name: 'shell-guard.py', where: 'PreToolUse Bash|PowerShell (managed)', does: 'blocks heredoc and here-string writes to a file, .env clobbers, and git add -A / git add . / git commit -a', covers: [['heredoc'], ['here-string'], ['.env'], ['git add -a'], ['git add .'], ['commit -a']] },
233 { name: 'agent-contract.py', where: 'PreToolUse, all tools (managed)', does: "binds a subagent to its contract in agent-contracts.json: paths, tools, call and wall-clock budgets", covers: [['agent contract'], ['subagent', 'path'], ['subagent', 'budget'], ['subagent', 'forbidden']] },
234 { name: 'agent-contract.py', where: 'SubagentStart, SubagentStop (managed)', does: 'starts the budget clock; reports a zero-tool-call fork and a missing exit artifact', covers: [['silent fork'], ['zero tool'], ['zero-tool'], ['exit artifact']] },
235 { name: 'hook-show-me-hint.py', where: 'UserPromptSubmit', does: 'hints the show-me staging viewer when a prompt asks to see a file', covers: [['show-me'], ['show me', 'file'], ['staging viewer']] },
236 { name: 'hook-crosstalk-nudge.py', where: 'UserPromptSubmit', does: 'nudges toward /crosstalk when a prompt reads like a cross-agent handoff', covers: [['crosstalk', 'nudge'], ['crosstalk', 'remind'], ['crosstalk', 'prompt'], ['handoff', 'prompt']] },
237 { name: 'supabase-sql-verdict.py', where: 'PreToolUse mcp__claude_ai_Supabase__.*', does: 'judges every Supabase MCP call; only one keyed UPDATE or DELETE on a known workspace table, with RETURNING, passes', covers: [['execute_sql', 'write'], ['execute_sql', 'confirm'], ['execute_sql', 'destructive'], ['execute_sql', 'update'], ['execute_sql', 'delete'], ['update', 'returning'], ['delete', 'returning'], ['bare update'], ['bare delete'], ['destructive sql'], ['destructive-sql']] },
238 { name: 'supabase-elicitation-accept.py', where: 'Elicitation', does: "auto-accepts the Supabase destructive-SQL dialog only when the session's recent Supabase verdicts all passed", covers: [['elicitation'], ['destructive', 'dialog'], ['auto-accept'], ['auto accept']] },
239 { name: 'trap-annotator', where: 'mod, tool.call', does: 'notes a tool result that reads like proof but is not (Notion update no-ops, the reconcile request id, multi-statement execute_sql, first-write stamps)', covers: [['no-op'], ['silent success'], ['request id'], ['multi-statement']] },
240 { name: 'subagent-model-guard', where: 'mod, agent.spawn', does: 'gives a spawn with no model Sonnet; toasts an Opus or Fable spawn or fork', covers: [['subagent', 'model'], ['agent', 'sonnet'], ['opus'], ['fable']] },
241 { name: 'witness', where: 'mod', does: 'holds a bare Supabase UPDATE or DELETE with no RETURNING; keeps "done" claims pale until a read-back; tracks asks and the confirm tool', covers: [['read-back'], ['read back'], ['claim', 'verif'], ['done', 'verif'], ['returning']] },
242 { name: 'estate-status', where: 'mod, disabled (folded into witness 0.3.0)', does: 'drew the estate ticket line; witness draws it now', covers: [['estate ticket'], ['ticket line']], disabled: true },
243]
244
245/** The guard or mod a hook candidate restates, or null; skills are never filtered here. */
246export function coveringGuard(
247 c: { kind: string; title: string; why: string },
248 guards: readonly Guard[] = INSTALLED_GUARDS,
249): Guard | null {
250 if (c.kind !== 'hook') return null
251 const text = `${c.title} ${c.why}`.toLowerCase()
252 return guards.find(g => g.covers.some(terms => terms.every(t => text.includes(t)))) ?? null
253}
254
255const guardLine = (g: Guard): string => `- ${g.name} [${g.where}]: ${g.does}`
256
257/** The side pass's prompt: candidates only on evidence, strict JSON back. */
258export function candidatesPrompt(o: {
259 friction: readonly (Friction | TaggedFriction)[]
260 calls: readonly string[]
261 existing: readonly Candidate[]
262 /** Installed commands and skills (a field report): never proposed again as skills. */
263 installed?: ReadonlyArray<{ name: string; description: string }>
264 /** The guards to name (1.0): the estate's list where the estate is present, else none. */
265 guards?: readonly Guard[]
266 /** The session repo's scripts (1.8): what already exists. Omitted from the prompt when empty. */
267 scripts?: readonly ScriptNote[]
268 /** The headings of the CLAUDE.md files the session loads (1.8). Omitted from the prompt when empty. */
269 headings?: readonly HeadingNote[]
270 /** Routine heads seen in two or more sessions (1.9), from `sharedRoutines`. Omitted from the prompt when empty. */
271 routines?: readonly string[]
272 /** Titles of jewels dismissed in any project (1.11). Omitted from the prompt when empty. */
273 dismissed?: readonly string[]
274 /** The hooks actually configured (1.11), `- event matcher: script` lines. `undefined` omits the section. */
275 hooks?: readonly string[]
276}): string {
277 const guards = (o.guards ?? INSTALLED_GUARDS).map(guardLine)
278 const dismissed = (o.dismissed ?? []).slice(0, 40)
279 const friction = o.friction.slice(-60).map(f => {
280 const tag = (f as TaggedFriction).tag
281 return `- ${tagged(tag, `${f.kind} ${one(f.key, 80)}: ${one(f.detail, 100)}`)}`
282 })
283 const scripts = (o.scripts ?? []).slice(0, MAX_SCRIPTS).map(x => `- scripts/${x.name}${x.summary === '' ? '' : `: ${one(x.summary, SCRIPT_SUMMARY)}`}`)
284 let room = MAX_HEADINGS
285 const headings = (o.headings ?? []).flatMap(h => {
286 const take = h.headings.slice(0, Math.max(room, 0))
287 room -= take.length
288 return take.length === 0 ? [] : [`- ${h.file}: ${take.join(' | ')}`]
289 })
290 const covered = [
291 ...(scripts.length > 0 ? ['', 'Scripts already in the repo (scripts/):', ...scripts] : []),
292 ...(headings.length > 0 ? ['', 'Headings of the CLAUDE.md files the session loads:', ...headings] : []),
293 ]
294 const existing = o.existing.map(c => `- [${c.kind}] ${c.title}`)
295 const installed = (o.installed ?? []).slice(0, MAX_INSTALLED).map(c => `- /${c.name}: ${one(c.description, INSTALLED_DESC)}`)
296 return [
297 'You read what one Claude Code session did: its recorded friction and a digest of its tool calls.',
298 'Propose things that could be automated, ONLY where the log itself is the evidence:',
299 '- HOOK: something that should happen, or be prevented, every time an event occurs (a guard, a check, a reminder). Evidence: friction that recurs, or a mistake corrected more than once.',
300 '- SKILL: a multi-step manual sequence (three or more steps) done two or more times, that a named procedure could run. Evidence: the repeated calls.',
301 'Never propose a skill that an installed command already covers, even if the session did the steps by hand.',
302 'Never propose a hook or guard that an installed guard or mod already covers, even if the friction shows it firing: that is the guard working.',
303 'Never propose a script or skill for a job that a script listed below or a CLAUDE.md heading listed below already covers: if the friction is that the existing route was missed, that is not a candidate.',
304 'Calls and friction carry a tag such as [s3f2a t3]: s3f2a names the SESSION, t3 the turn within it. Friction from other sessions carries the session alone, [s9c41]; [s?] is one session whose id was not kept. Calls in one turn (one parallel message) are ONE event, however many lines they take.',
305 'A candidate needs evidence from at least TWO DIFFERENT SESSIONS: quote the tags, for example "[s3f2a t2] ... [s9c41] ...". Repeats within one session, however many turns, are recorded but never minted: one session is never a pattern, and a one-off repair is not a procedure worth automating.',
306 'One candidate per ROOT CAUSE: several symptoms of one fault are one jewel, not several.',
307 'A fault that the instructions (CLAUDE.md headings, scripts) record as fixed, with a dated line, after the evidence is not a candidate.',
308 'Evidence counts the tool calls themselves, never text echoed back into the transcript (the content of a file, the text of a jewel).',
309 'A single tool call (one Grep, one external command) is not a procedure. A SKILL needs a sequence of at least two different kinds of call, and its evidence must cite them.',
310 'Prefer "a script beside the helper that already does half" over a skill when a listed script is close.',
311 'A hook candidate may not claim that a hook exists, or restate one, unless it is in the list of configured hooks below.',
312 'Never propose a hook that runs tests, typecheck or build after an edit: that is test-first work, the red phase is expected.',
313 `One exception to the two-session rule, at most ${MAX_GAP_CANDIDATES} per pass: a candidate from ONE session survives only if it names a GAP in "gap": a gate that does not run (a typecheck or test that skipped a folder, so did not cover what failed), or a check rebuilt by hand each sitting that no listed script holds. Quote the concrete gate or check. Without a real gap, one session is not a candidate.`,
314 'Quote the log in "evidence". Skip anything already proposed. If nothing qualifies, return {"candidates": []}.',
315 'Each candidate must also carry "uncovered": a short reason that nothing listed below (installed commands, guards, scripts, CLAUDE.md headings) already does this job. A candidate without it is dropped.',
316 `At most ${MAX_CANDIDATES}. Reply with strict JSON only:`,
317 `{"candidates": [{"kind": "hook" | "skill", "title": "<= 80 chars", "why": "<= 160 chars", "evidence": "<= 200 chars, with turn tags", "uncovered": "<= 120 chars", "gap": "<= ${GAP_CHARS} chars, ONLY for a one-session candidate"}]}`,
318 '',
319 'Already proposed:',
320 ...(existing.length > 0 ? existing : ['- (none)']),
321 ...(dismissed.length > 0
322 ? ['', 'Shapes dismissed before (do not propose these again in any wording):', ...dismissed.map(d => `- ${d}`)]
323 : []),
324 ...(o.hooks === undefined ? [] : ['', 'Hooks configured (settings files; event, matcher, script):', ...(o.hooks.length > 0 ? o.hooks : ['- (none)'])]),
325 '',
326 'Installed commands:',
327 ...(installed.length > 0 ? installed : ['- (none listed)']),
328 '',
329 'Installed guards and mods:',
330 ...(guards.length > 0 ? guards : ['- (none listed)']),
331 ...covered,
332 '',
333 'Friction:',
334 ...(friction.length > 0 ? friction : ['- (none)']),
335 '',
336 'Tool calls, oldest first:',
337 ...(o.calls.length > 0 ? o.calls.map(c => `- ${c}`) : ['- (none)']),
338 ...((o.routines ?? []).length > 0
339 ? ['', 'Routines seen in two or more sessions (the call head, then each session with its calls and turns; a SKILL candidate may cite one by its session tags):', ...(o.routines ?? [])]
340 : []),
341 ].join('\n')
342}
343
344const candidateKey = (kind: string, title: string): string => `${kind}:${normalise(title)}`
345
346/** The side pass's reply as candidates: tolerant of junk, validated, deduped, capped. */
347export function parseCandidates(
348 reply: string,
349 existing: readonly Candidate[],
350 at: number,
351 guards: readonly Guard[] = INSTALLED_GUARDS,
352): Candidate[] {
353 const raw = parseJsonObject(reply)?.candidates
354 if (!Array.isArray(raw)) return []
355 const seen = new Set(existing.map(c => c.key))
356 const out: Candidate[] = []
357 let gapUsed = 0
358 for (const item of raw) {
359 const x = item as { kind?: unknown; title?: unknown; why?: unknown; evidence?: unknown; uncovered?: unknown; gap?: unknown }
360 if (x?.kind !== 'hook' && x?.kind !== 'skill') continue
361 // The covered check (1.8): a candidate must say why nothing that exists covers it.
362 if (typeof x.uncovered !== 'string' || cleanText(x.uncovered) === '') continue
363 // Two sessions (Bradley, 2026-10-11): evidence from one session is recorded, never minted. This
364 // subsumes 1.8's two-turn check (two sessions are two turns); turn tags stay for grouping.
365 // Exception (1.11, "Gap exception"): one session survives only when it names a gap, and at most
366 // one such candidate a pass.
367 const sessions = distinctSessions(typeof x.evidence === 'string' ? x.evidence : '')
368 const gap = typeof x.gap === 'string' ? one(x.gap, GAP_CHARS) : ''
369 const viaGap = sessions < 2
370 if (viaGap && (sessions < 1 || gap === '' || gapUsed >= MAX_GAP_CANDIDATES)) continue
371 const title = one(typeof x.title === 'string' ? x.title : '', TITLE_CHARS)
372 if (title === '') continue
373 // The charter's shape rules (1.11): no test-after-edit hook; a skill is a procedure of 2+ call heads.
374 if (x.kind === 'hook' && isTestAfterEditHook(title)) continue
375 if (x.kind === 'skill' && !hasProcedureShape(typeof x.evidence === 'string' ? x.evidence : '')) continue
376 const key = candidateKey(x.kind, title)
377 if (seen.has(key)) continue
378 seen.add(key)
379 const why = one(viaGap ? `${GAP_WHY}: ${gap}. ${typeof x.why === 'string' ? x.why : ''}` : typeof x.why === 'string' ? x.why : '', WHY_CHARS)
380 if (coveringGuard({ kind: x.kind, title, why }, guards) !== null) continue
381 const evidence = one(typeof x.evidence === 'string' ? x.evidence : '', EVIDENCE_CHARS)
382 if (viaGap) gapUsed += 1
383 out.push({ key, kind: x.kind, title, why, evidence, at, filed: false })
384 if (out.length >= MAX_CANDIDATES) break
385 }
386 return out
387}
388
389export function mergeCandidates(existing: readonly Candidate[], fresh: readonly Candidate[]): Candidate[] {
390 return [...existing, ...fresh].slice(-CANDIDATES_KEPT)
391}
392
393/**
394 * The project's stored candidates and this session's, merged by key (1.7.1, Bradley 2026-10-11:
395 * "when a skill or hook is taken it reappears in the jewel section"). Every live session holds the
396 * list it loaded at its start, and writing that copy whole put back a jewel another session had
397 * settled: the one-slot problem friction and carry already had. So what is stored is kept, a
398 * settled jewel never goes back to unsettled, and a filed one never back to unfiled. Stored order
399 * first, this session's new keys after, then the cap keeps the newest.
400 */
401export function mergeCandidatesByKey(stored: readonly Candidate[], mine: readonly Candidate[]): Candidate[] {
402 const byKey = new Map<string, Candidate>()
403 for (const c of [...stored, ...mine]) {
404 const had = byKey.get(c.key)
405 if (had === undefined) {
406 byKey.set(c.key, { ...c })
407 continue
408 }
409 const settled = had.settled ?? c.settled
410 const merged: Candidate = { ...had, ...c, filed: had.filed || c.filed }
411 byKey.set(c.key, settled === undefined ? withoutSettled(merged) : { ...merged, settled })
412 }
413 return [...byKey.values()].slice(-CANDIDATES_KEPT)
414}
415
416function withoutSettled(c: Candidate): Candidate {
417 const { settled: _settled, ...rest } = c
418 return rest
419}
420
421/**
422 * A stray subfolder slot folded into the project's own (1.11.1, "Repo root, retire stray"): its
423 * candidates are merged by key, each unsettled one marked `retired` (and filed, so the running
424 * candidates file never takes it). A settled one keeps its settle, and the project's own settled
425 * jewel is never overwritten (`mergeCandidatesByKey`). Pure and idempotent.
426 */
427export function retireStrays(own: readonly Candidate[], strays: ReadonlyArray<readonly Candidate[]>, now: number): Candidate[] {
428 const room = Math.max(0, CANDIDATES_KEPT - own.length)
429 const retired = strays
430 .flat()
431 .map(c => (c.settled === undefined ? { ...c, filed: true, settled: { how: 'retired' as const, at: now } } : { ...c }))
432 .sort((a, b) => a.at - b.at)
433 .slice(room === 0 ? Infinity : -room)
434 return mergeCandidatesByKey(own, retired)
435}
436
437export function markFiled(candidates: readonly Candidate[], keys: readonly string[]): Candidate[] {
438 const filed = new Set(keys)
439 return candidates.map(c => (filed.has(c.key) ? { ...c, filed: true } : { ...c }))
440}
441
442/**
443 * The candidates still waiting on the person (1.5, the gem): those with no `settled`. `filed` is
444 * not settled, since filing is the automatic append at /wrap and must not take a gem off.
445 */
446export function unsettled(candidates: readonly Candidate[]): Candidate[] {
447 return candidates.filter(c => c.settled === undefined)
448}
449
450/** The candidates with these keys settled, merged by key; the rest are copied untouched. */
451export function settleCandidatesIn(candidates: readonly Candidate[], keys: readonly string[], how: 'taken' | 'dismissed', at: number): Candidate[] {
452 const set = new Set(keys)
453 return candidates.map(c => (set.has(c.key) && c.settled === undefined ? { ...c, settled: { how, at } } : { ...c }))
454}
455
456/** What `take` puts in the prompt box: the candidate, and a request to build it or say why not. */
457export function takePrompt(c: Candidate): string {
458 return `A witness ${c.kind} candidate: ${c.title}. Why: ${c.why}. Evidence: ${c.evidence}. Propose how to build it as a ${c.kind}, or say why it should not be built.`
459}
460
461/** Is a candidate pass due? Both the interval and enough new calls since the last one. */
462export function shouldScan(o: { now: number; lastScanAt: number; newCalls: number }): boolean {
463 return o.now - o.lastScanAt >= CANDIDATE_SCAN_MS && o.newCalls >= CANDIDATE_MIN_NEW_CALLS
464}
465
466const candidateLine = (c: Candidate): string =>
467 `- [${c.kind}] ${c.title}${c.why ? ` - ${c.why}` : ''}${c.evidence ? ` (evidence: ${c.evidence})` : ''}`
468
469/** The print's candidates section: this watch's proposals. */
470export function candidatesSection(candidates: readonly Candidate[], since: number): string[] {
471 const now = candidates.filter(c => c.at >= since && c.settled?.how !== 'retired')
472 const head = ['### Hook and skill candidates', '']
473 return now.length === 0 ? [...head, '- None proposed.'] : [...head, ...now.map(candidateLine)]
474}
475
476const FILE_HEAD = [
477 '# Witness candidates',
478 '',
479 'Hook and skill candidates the witness companion proposed from friction and repeated',
480 'sequences it saw. Proposals only: nothing here was built. Strike a line (~~...~~) to dismiss it:',
481 'the next session start reads a struck line as a dismissal of that jewel.',
482 '',
483].join('\n')
484
485// A line `candidateLine` wrote, struck: `- ~~[hook] title - why (evidence: ...)~~ reason`, or the
486// whole line struck, dash and all. Captures the kind and the text after it, up to the closing ~~.
487const STRUCK = /^\s*(?:-\s*~~|~~\s*-)\s*\[(hook|skill)\]\s+(.*?)(?:~~|$)/
488
489/**
490 * The keys of unsettled candidates whose line in the candidates file is struck (1.14.0, ledger
491 * note 1 of jewel-calibration-102_pm: "S110 struck seven jewels ... all seven came back"). A line
492 * is matched by kind and the title exactly as `candidateLine` wrote it, so a struck line whose
493 * title was edited matches nothing. A settled jewel is left alone: a taken one is ruled through
494 * `/jewels built|dismissed`, and a settle is never changed.
495 */
496export function struckKeys(candidates: readonly Candidate[], fileText: string): string[] {
497 const struck: Array<{ kind: string; text: string }> = []
498 for (const line of fileText.split(/\r?\n/)) {
499 const m = STRUCK.exec(line)
500 if (m !== null) struck.push({ kind: m[1]!, text: m[2]!.trim() })
501 }
502 if (struck.length === 0) return []
503 const titled = (text: string, title: string): boolean =>
504 text === title || text.startsWith(`${title} - `) || text.startsWith(`${title} (evidence: `)
505 return unsettled(candidates)
506 .filter(c => c.title.trim() !== '' && struck.some(s => s.kind === c.kind && titled(s.text, c.title.trim())))
507 .map(c => c.key)
508}
509
510/** The running file with this watch's unfiled candidates appended; unchanged when there are none. */
511export function appendCandidates(fileText: string, candidates: readonly Candidate[], o: { date: string; source: string }): string {
512 const fresh = candidates.filter(c => !c.filed)
513 if (fresh.length === 0) return fileText
514 const base = fileText.trim() === '' ? FILE_HEAD : fileText.replace(/\s*$/, '\n')
515 return `${base}\n## ${o.date} - ${one(o.source, 80)}\n\n${fresh.map(candidateLine).join('\n')}\n`
516}
517
518/** Where the running file lives: reports/ when the project has one, else beside the session logs. */
519export function candidatesPath(cwd: string, hasReports: boolean): string {
520 const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '')
521 return hasReports ? `${root}/reports/witness-candidates.md` : `${root}/.claude/witness-candidates.md`
522}
523hooks/carry.ts 62 lines1// Carry-over per session (1.2, ruled by Bradley 2026-10-09). Until now one slot per project held
2// the leftover asks, rewritten after every turn: with several sessions open in one repository a
3// new session took another LIVE session's undone asks as its own carried work, and whichever
4// turn ended last overwrote the slot (seen live in S170, and named by a side agent's note).
5// Ruled: each session keeps its leftovers in a slot of its own, and a starting session takes only
6// the slots of sessions that have ENDED (written at their end, or untouched for hours: a crash),
7// merged, one hop as before. A live session's slot is never taken and never overwritten. Pure.
8
9import type { Ask } from '../types'
10import { normalise } from './asks'
11
12/** A slot untouched this long is a session that ended without saying so (a crash, a closed window). */
13export const CARRY_STALE_MS = 6 * 60 * 60_000
14
15/** One session's leftovers, under `carry:<project>:<session id>`. */
16export type CarrySlot = { v: 2; sessionId: string; savedAt: number; ended: boolean; asks: Ask[] }
17
18export const carryPrefix = (project: string): string => `carry:${project}:`
19export const carrySlotKey = (project: string, sessionId: string): string => `${carryPrefix(project)}${sessionId}`
20
21export function carrySlot(o: { sessionId: string; savedAt: number; ended: boolean; asks: readonly Ask[] }): CarrySlot {
22 return { v: 2, sessionId: o.sessionId, savedAt: o.savedAt, ended: o.ended, asks: o.asks.map(a => ({ ...a })) }
23}
24
25/** A stored slot read back; null for anything else (the older single slot is a bare list, read apart). */
26export function asCarrySlot(v: unknown): CarrySlot | null {
27 if (v === null || typeof v !== 'object' || Array.isArray(v)) return null
28 const o = v as Record<string, unknown>
29 if (o.v !== 2 || typeof o.sessionId !== 'string' || typeof o.savedAt !== 'number' || !Number.isFinite(o.savedAt)) return null
30 if (typeof o.ended !== 'boolean' || !Array.isArray(o.asks)) return null
31 return carrySlot({ sessionId: o.sessionId, savedAt: o.savedAt, ended: o.ended, asks: o.asks as Ask[] })
32}
33
34/** Whether a starting session may take this slot: another session's, ended or gone stale. */
35export function takeable(slot: CarrySlot, now: number, self: string): boolean {
36 return slot.sessionId !== self && (slot.ended || now - slot.savedAt > CARRY_STALE_MS)
37}
38
39/**
40 * A session's OWN slot read back (1.3.6, F9, 2026-10-11: the laptop restarted, and the resumed
41 * conversation ran with an empty ledger while its own slot, never ended, sat stranded): the slot's
42 * asks this session does not already hold, by their text. A resumed process holds none and takes
43 * them all; a hot reload in the same process holds them all and takes none.
44 */
45export function ownLeftovers(slot: readonly Ask[], held: readonly Ask[]): Ask[] {
46 const have = new Set(held.map(a => normalise(a.text)))
47 return slot.filter(a => !have.has(normalise(a.text))).map(a => ({ ...a }))
48}
49
50/** Leftovers from several ended sessions as one list, the same ask (by its text) once. */
51export function mergeCarried(lists: ReadonlyArray<readonly Ask[]>): Ask[] {
52 const seen = new Set<string>()
53 const out: Ask[] = []
54 for (const a of lists.flat()) {
55 const k = normalise(a.text)
56 if (seen.has(k)) continue
57 seen.add(k)
58 out.push({ ...a })
59 }
60 return out
61}
62hooks/frictionslots.ts 76 lines1// Friction per session (1.2, ruled by Bradley 2026-10-09, after the carry ruling). One slot per
2// project held the friction log, rewritten after every turn from what each session loaded at its
3// start plus its own: with several pods open in one repository, the last writer won and the
4// others' friction was lost (seen live, S170: three entries survived a day of five pods), so the
5// barnacles undercounted. Now each session writes ONLY its own friction, to a slot of its own;
6// every session READS all the project's slots, live or ended (friction is history, not work to
7// take); and slots nobody has touched for a day are folded into the project's archive slot (the
8// old single key) and deleted, so the store stays bounded. Pure.
9
10import type { Friction } from '../types'
11import { FRICTION_CAP } from './barnacles'
12
13/** A session's slot untouched this long is folded into the archive at the next start. */
14export const FRICTION_ARCHIVE_MS = 24 * 60 * 60_000
15
16/** One session's own friction, under `friction:<project>:<session id>`. */
17export type FrictionSlot = { v: 2; sessionId: string; savedAt: number; entries: Friction[] }
18
19export const frictionPrefix = (project: string): string => `friction:${project}:`
20export const frictionSlotKey = (project: string, sessionId: string): string => `${frictionPrefix(project)}${sessionId}`
21
22export function frictionSlot(o: { sessionId: string; savedAt: number; entries: readonly Friction[] }): FrictionSlot {
23 return { v: 2, sessionId: o.sessionId, savedAt: o.savedAt, entries: o.entries.slice(-FRICTION_CAP).map(f => ({ ...f })) }
24}
25
26const isFriction = (f: unknown): f is Friction =>
27 f !== null &&
28 typeof f === 'object' &&
29 typeof (f as Friction).kind === 'string' &&
30 typeof (f as Friction).key === 'string' &&
31 typeof (f as Friction).at === 'number' &&
32 typeof (f as Friction).detail === 'string'
33
34/** An entry as stored: a `session` that is not a non-empty string is dropped (legacy: the unknown session). */
35const cleanFriction = (f: Friction): Friction => {
36 const { session, ...rest } = f
37 return typeof session === 'string' && session !== '' ? { ...rest, session } : { ...rest }
38}
39
40/** A stored list of friction (the archive, or the old single slot), malformed entries dropped. */
41export const asFrictionList = (v: unknown): Friction[] => (Array.isArray(v) ? v.filter(isFriction).map(cleanFriction) : [])
42
43/** Entries with no session take the slot's: a slot knows whose it is (1.9). Entries already stamped keep theirs. */
44export const stampSession = (entries: readonly Friction[], session: string): Friction[] =>
45 entries.map(f => (f.session === undefined ? { ...f, session } : { ...f }))
46
47/** A stored slot read back; null for anything else. */
48export function asFrictionSlot(v: unknown): FrictionSlot | null {
49 if (v === null || typeof v !== 'object' || Array.isArray(v)) return null
50 const o = v as Record<string, unknown>
51 if (o.v !== 2 || typeof o.sessionId !== 'string' || typeof o.savedAt !== 'number' || !Number.isFinite(o.savedAt)) return null
52 return frictionSlot({ sessionId: o.sessionId, savedAt: o.savedAt, entries: asFrictionList(o.entries) })
53}
54
55/** Whether a slot is folded into the archive: another session's, untouched for a day. */
56export const archivable = (slot: FrictionSlot, now: number, self: string): boolean =>
57 slot.sessionId !== self && now - slot.savedAt > FRICTION_ARCHIVE_MS
58
59const entryKey = (f: Friction): string => `${f.kind}\u0000${f.key}\u0000${f.at}\u0000${f.detail}`
60
61/** Several logs as one, oldest first, each entry once, the newest FRICTION_CAP kept. */
62export function mergeFriction(lists: ReadonlyArray<readonly Friction[]>): Friction[] {
63 const seen = new Set<string>()
64 const out: Friction[] = []
65 for (const f of lists.flat()) {
66 const k = entryKey(f)
67 if (seen.has(k)) continue
68 seen.add(k)
69 out.push({ ...f })
70 }
71 return out.sort((a, b) => a.at - b.at).slice(-FRICTION_CAP)
72}
73
74/** What this session writes to its own slot: the friction recorded since it started. */
75export const ownFriction = (log: readonly Friction[], since: number): Friction[] => log.filter(f => f.at >= since).map(f => ({ ...f }))
76