counterparts 0.3.13 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +264 -0
  2. package/docs/QUICKSTART.md +22 -0
  3. package/docs/README.md +1 -0
  4. package/package.json +1 -1
  5. package/src/adapters/claude-code/CONTRACT.md +48 -0
  6. package/src/adapters/claude-code/NOTES.md +148 -0
  7. package/src/adapters/claude-code/bin/hook.mjs +4 -2
  8. package/src/adapters/claude-code/bin/hook.ts +61 -7
  9. package/src/adapters/claude-code/bin/nightly.ts +5 -1
  10. package/src/adapters/claude-code/bin/runner.ts +11 -3
  11. package/src/adapters/claude-code/claim.ts +319 -0
  12. package/src/adapters/claude-code/doctor.ts +170 -16
  13. package/src/adapters/claude-code/embed-client.ts +3 -0
  14. package/src/adapters/cli/CONTRACT.md +5 -0
  15. package/src/adapters/cli/NOTES.md +25 -0
  16. package/src/adapters/cli/bin/counterparts.mjs +4 -2
  17. package/src/adapters/cli/bin/counterparts.ts +49 -3
  18. package/src/adapters/cli/commands.ts +169 -32
  19. package/src/adapters/cli/desktop.ts +112 -7
  20. package/src/adapters/cli/help.ts +10 -0
  21. package/src/adapters/cli/index.ts +1 -0
  22. package/src/adapters/cli/install.ts +94 -14
  23. package/src/adapters/cli/self-page.ts +5 -8
  24. package/src/adapters/cli/settle.ts +39 -2
  25. package/src/adapters/cli/wire.ts +18 -1
  26. package/src/adapters/config.ts +29 -1
  27. package/src/adapters/dashboard/NOTES.md +33 -0
  28. package/src/adapters/dashboard/bin/dashboard.mjs +4 -2
  29. package/src/adapters/dashboard/bin/dashboard.ts +11 -3
  30. package/src/adapters/dashboard/index.ts +14 -0
  31. package/src/adapters/dashboard/registries.ts +3 -0
  32. package/src/adapters/dashboard/source.ts +0 -8
  33. package/src/adapters/dashboard/web/fired.ts +8 -0
  34. package/src/adapters/dashboard/web/flow.ts +1 -0
  35. package/src/adapters/dashboard/web/lanes.ts +1 -0
  36. package/src/adapters/dashboard/web/narrate.ts +11 -0
  37. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -1
  38. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +7 -10
  39. package/src/adapters/dashboard/web/pages/memories/memories.css +3 -0
  40. package/src/adapters/dashboard/web/pages/memories/row.js +5 -2
  41. package/src/adapters/dashboard/web/pages/memories/sections/hold.js +2 -1
  42. package/src/adapters/dashboard/web/pages/memories/sections/search.js +19 -3
  43. package/src/adapters/dashboard/web/server.ts +16 -4
  44. package/src/adapters/dashboard/web/shared/dates.js +6 -16
  45. package/src/adapters/dashboard/web/shared/memory-modal.js +21 -8
  46. package/src/adapters/dashboard/web/views/health.ts +19 -5
  47. package/src/adapters/dashboard/web/views/mechanism-panel.ts +8 -5
  48. package/src/adapters/dashboard/web/views/memories.ts +26 -7
  49. package/src/adapters/dashboard/web/views/memory-words.ts +16 -0
  50. package/src/adapters/dashboard/web/views/memory.ts +51 -2
  51. package/src/adapters/dashboard/web/views/mind.ts +38 -6
  52. package/src/adapters/empty-bunfig.toml +5 -0
  53. package/src/adapters/fired.ts +16 -2
  54. package/src/adapters/host-wiring.ts +112 -17
  55. package/src/adapters/log/index.ts +2 -2
  56. package/src/adapters/mcp/CONTRACT.md +17 -2
  57. package/src/adapters/mcp/INTERFACE-GAPS.md +15 -1
  58. package/src/adapters/mcp/NOTES.md +269 -0
  59. package/src/adapters/mcp/bin/serve.mjs +4 -2
  60. package/src/adapters/mcp/bin/serve.ts +17 -6
  61. package/src/adapters/mcp/facts.ts +72 -4
  62. package/src/adapters/mcp/meaning.ts +218 -15
  63. package/src/adapters/mcp/server.ts +21 -6
  64. package/src/adapters/mcp/tools.ts +86 -61
  65. package/src/adapters/plugin-run.sh +413 -34
  66. package/src/adapters/plugin.ts +141 -17
  67. package/src/adapters/runtime.ts +192 -17
  68. package/src/adapters/sessions.ts +2 -2
  69. package/src/core/associate/NOTES.md +10 -0
  70. package/src/core/bridge.ts +1 -1
  71. package/src/core/briefing.ts +20 -3
  72. package/src/core/contradictions.ts +56 -20
  73. package/src/core/counterpart.ts +72 -23
  74. package/src/core/dream/CONTRACT.md +6 -14
  75. package/src/core/dream/INTERFACE-GAPS.md +3 -2
  76. package/src/core/dream/NOTES.md +10 -0
  77. package/src/core/dream/index.ts +11 -53
  78. package/src/core/dream/reflect.ts +11 -2
  79. package/src/core/embed/static.ts +5 -1
  80. package/src/core/encode/INTERFACE-GAPS.md +2 -1
  81. package/src/core/encode/NOTES.md +12 -0
  82. package/src/core/encode/chunk.ts +6 -30
  83. package/src/core/encode/index.ts +0 -1
  84. package/src/core/encode/types.ts +1 -13
  85. package/src/core/handoff/INTERFACE-GAPS.md +1 -1
  86. package/src/core/handoff/index.ts +2 -1
  87. package/src/core/handoff/last-here.ts +18 -2
  88. package/src/core/physics/CONTRACT.md +6 -0
  89. package/src/core/physics/NOTES.md +33 -2
  90. package/src/core/physics/index.ts +22 -7
  91. package/src/core/prospective/CONTRACT.md +3 -1
  92. package/src/core/prospective/NOTES.md +15 -0
  93. package/src/core/recall/activate.ts +1 -1
  94. package/src/core/recall/time-ask.ts +173 -19
  95. package/src/core/self/CONTRACT.md +56 -19
  96. package/src/core/self/NOTES.md +172 -0
  97. package/src/core/self/behind.ts +6 -3
  98. package/src/core/self/briefing.ts +384 -28
  99. package/src/core/self/index.ts +105 -44
  100. package/src/core/self/page.ts +12 -85
  101. package/src/core/self/tunables.ts +16 -19
  102. package/src/core/self/writer.ts +31 -4
  103. package/src/core/sleep/NOTES.md +32 -0
  104. package/src/core/store/NOTES.md +21 -2
  105. package/src/core/store/index.ts +2 -1
  106. package/src/core/time.ts +15 -0
@@ -57,9 +57,11 @@ import {
57
57
  } from "../standdown.js";
58
58
  import type { SaysSoHook, StandDownFault } from "../standdown.js";
59
59
  import { readTranscript } from "../transcript.js";
60
- import { scriptArgs } from "../../runtime.js";
60
+ import { BINARY, scriptArgs } from "../../runtime.js";
61
+ import type { Binary } from "../../runtime.js";
61
62
  import { npmWiring } from "../../host-wiring.js";
62
- import { ensureFirstRun, hookGate, runningAsPlugin } from "../../plugin.js";
63
+ import { ensureFirstRun, hookGate, pluginOrigin, runningAsPlugin } from "../../plugin.js";
64
+ import { claimDelivery, deliveryClaimKey, finishClaim } from "../claim.js";
63
65
 
64
66
  /**
65
67
  * The host's own spellings of the two events that carry a notice — one
@@ -568,7 +570,12 @@ async function main(): Promise<void> {
568
570
  if (runningAsPlugin(process.env)) {
569
571
  const home = homedir();
570
572
  const projectDir = process.env["CLAUDE_PROJECT_DIR"] ?? eventDirectory(payload);
571
- const gate = hookGate(npmWiring({ home, env: process.env, cwd: projectDir, read: { mcp: false } }), home);
573
+ const gate = hookGate(
574
+ npmWiring({ home, env: process.env, cwd: projectDir, read: { mcp: false } }),
575
+ home,
576
+ // Where the plugin was loaded from changes only the session-start line.
577
+ name === "session-start" ? pluginOrigin({ home, env: process.env, cwd: projectDir }) : undefined,
578
+ );
572
579
  if (gate.standDown) {
573
580
  process.stderr.write("[counterparts] plugin hook stood down: the npm install's hooks are live in this host\n");
574
581
  if (name === "session-start" && gate.line !== null) process.stdout.write(JSON.stringify({ systemMessage: gate.line }));
@@ -781,6 +788,42 @@ async function runHook(
781
788
  said.log = opened;
782
789
  // No start line at a prompt, the most frequent event: its end carries `ms`.
783
790
  if (name !== "user-prompt-submit") opened.start();
791
+ // ONE DELIVERY PER EVENT (`../claim.ts`, 2026-10-09). Two wirings of
792
+ // Counterparts live in this host both run this event at once; the first to
793
+ // claim it does the whole job — the wake, the recall, the ask, the boundary,
794
+ // the worker — and its twin leaves here, before any of it, with no output.
795
+ // Fail-open: no claim made is a delivery, so one wiring is exactly as it was.
796
+ const claimKey = deliveryClaimKey(name, payload);
797
+ const claim = claimDelivery(adapter.counterpart, {
798
+ hook: name,
799
+ key: claimKey,
800
+ sessionId: said.sessionId,
801
+ side: runningAsPlugin(process.env) ? "plugin" : "settings",
802
+ observer: config.observer === true,
803
+ });
804
+ if (claim.outcome === "lost") {
805
+ process.stderr.write(
806
+ `[counterparts] ${name} stood down by claim: another Counterparts hook (${claim.heldBy ?? "?"}) already took this event — two wirings are live in this host\n`,
807
+ );
808
+ try {
809
+ adapter.counterpart.close();
810
+ } finally {
811
+ opened.end("claimed-elsewhere", { heldBy: claim.heldBy ?? null });
812
+ }
813
+ return;
814
+ }
815
+ // A CLAIM THAT COULD NOT BE WRITTEN goes into the process log's end line
816
+ // either way. Only a FAULT (the claims file cannot be made, opened or written)
817
+ // is said on stderr too, the host's debug log, where someone chasing two wakes
818
+ // would look. Contention is not: another claim held the file past
819
+ // `CLAIM_WAIT_MS`, it passes, and with one wiring nothing was lost.
820
+ const unclaimed =
821
+ claim.outcome === "unclaimed" && claim.detail !== undefined && claim.detail !== "no session id" && claim.detail !== "observer"
822
+ ? claim.detail
823
+ : null;
824
+ if (unclaimed !== null && claim.busy !== true) {
825
+ process.stderr.write(`[counterparts] ${name} delivered unclaimed: ${unclaimed}\n`);
826
+ }
784
827
  let outcome = "ok";
785
828
  try {
786
829
  // ONE read of the transcript, shared by the hook and the notice: `toHookInput`
@@ -858,10 +901,15 @@ async function runHook(
858
901
  }
859
902
  }
860
903
  } finally {
904
+ // The claim says it is done, so the next event that looks the same — one
905
+ // that starts after this — is not taken for this one's twin (`../claim.ts`).
906
+ if (claim.outcome === "won" && claimKey !== null && claim.at !== undefined) {
907
+ finishClaim(adapter.counterpart, claimKey, claim.at);
908
+ }
861
909
  adapter.counterpart.close();
862
910
  }
863
911
  // A throw above never reaches this line: `main`'s handler writes it instead.
864
- opened.end(outcome);
912
+ opened.end(outcome, unclaimed === null ? undefined : { unclaimed, busy: claim.busy === true });
865
913
  }
866
914
 
867
915
  /** `CLAUDE_CODE_SESSION_ATTENDED` as `HookInput.attended`: `1`/`true` and
@@ -1224,12 +1272,16 @@ export function hostDelivery(
1224
1272
 
1225
1273
  /** True only when this file is the process entry point — so a test may import
1226
1274
  * `toHookInput` and `hostConfig` without the script running itself. */
1227
- export function isEntryPoint(argv1: string | undefined, url: string): boolean {
1228
- if (argv1 === undefined) return false;
1275
+ export function isEntryPoint(argv1: string | undefined, url: string, binary: Binary | null = BINARY): boolean {
1276
+ // Never in the single binary, where every module shares one URL: its
1277
+ // dispatcher (tools/single-binary/main.ts) calls `start()` itself.
1278
+ if (argv1 === undefined || binary !== null) return false;
1229
1279
  return resolve(argv1) === fileURLToPath(new URL(url));
1230
1280
  }
1231
1281
 
1232
- if (isEntryPoint(process.argv[1], import.meta.url)) {
1282
+ /** Run the hook and exit — what this file does as a script, and what the
1283
+ * single binary's `hook` mode calls. */
1284
+ export function start(): void {
1233
1285
  void main().then(
1234
1286
  () => process.exit(process.exitCode === 2 ? 2 : 0),
1235
1287
  (err: unknown) => {
@@ -1249,3 +1301,5 @@ if (isEntryPoint(process.argv[1], import.meta.url)) {
1249
1301
  },
1250
1302
  );
1251
1303
  }
1304
+
1305
+ if (isEntryPoint(process.argv[1], import.meta.url)) start();
@@ -85,7 +85,9 @@ function standDown(config: Parameters<typeof openNightCounterpart>[0], run: stri
85
85
  }
86
86
  }
87
87
 
88
- if (isEntryPoint(process.argv[1], import.meta.url)) {
88
+ /** The nightly run, then exit — what this file does as a script, and what the
89
+ * single binary's `nightly` mode calls. */
90
+ export function start(): void {
89
91
  void main().then(
90
92
  () => process.exit(0),
91
93
  (err: unknown) => {
@@ -94,3 +96,5 @@ if (isEntryPoint(process.argv[1], import.meta.url)) {
94
96
  },
95
97
  );
96
98
  }
99
+
100
+ if (isEntryPoint(process.argv[1], import.meta.url)) start();
@@ -79,6 +79,8 @@ import { dataDir, describeGuardRefusal } from "../../../core/store/index.js";
79
79
  import type { Store } from "../../../core/store/index.js";
80
80
  import { hostSessionEvidence, installedVersion, writeUpSources } from "../../sessions.js";
81
81
  import { openLog } from "../../log/index.js";
82
+ import { BINARY } from "../../runtime.js";
83
+ import type { Binary } from "../../runtime.js";
82
84
 
83
85
  import {
84
86
  configLine,
@@ -544,8 +546,10 @@ export function pinnedScope(env: Record<string, string | undefined> = process.en
544
546
  return raw !== undefined && raw.trim().length > 0 ? raw : null;
545
547
  }
546
548
 
547
- export function isEntryPoint(argv1: string | undefined, url: string): boolean {
548
- if (argv1 === undefined) return false;
549
+ export function isEntryPoint(argv1: string | undefined, url: string, binary: Binary | null = BINARY): boolean {
550
+ // Never in the single binary, where every module shares one URL: its
551
+ // dispatcher (tools/single-binary/main.ts) calls `start()` itself.
552
+ if (argv1 === undefined || binary !== null) return false;
549
553
  return resolve(argv1) === fileURLToPath(new URL(url));
550
554
  }
551
555
 
@@ -643,7 +647,9 @@ async function main(): Promise<void> {
643
647
  }
644
648
  }
645
649
 
646
- if (isEntryPoint(process.argv[1], import.meta.url)) {
650
+ /** One worker run, then exit — what this file does as a script, and what the
651
+ * single binary's `runner` mode calls. */
652
+ export function start(): void {
647
653
  void main().then(
648
654
  () => process.exit(0),
649
655
  (err: unknown) => {
@@ -659,3 +665,5 @@ if (isEntryPoint(process.argv[1], import.meta.url)) {
659
665
  },
660
666
  );
661
667
  }
668
+
669
+ if (isEntryPoint(process.argv[1], import.meta.url)) start();
@@ -0,0 +1,319 @@
1
+ /**
2
+ * ONE DELIVERY PER EVENT, HOWEVER MANY WIRINGS FIRE IT (2026-10-09).
3
+ *
4
+ * Claude Code runs every hook registered for an event — from settings and from
5
+ * plugins alike — at the same moment, each handed the same input. When two
6
+ * wirings of Counterparts are live (the npm install's hooks in settings and
7
+ * the plugin's, or two settings files naming two builds), every event runs our
8
+ * hook twice: two wakes at session start, two recall blocks per prompt, two
9
+ * Stop asks, two boundaries, two background workers rewriting the wake bundle
10
+ * at each other. The plugin is meant to stand down when it sees the npm wiring
11
+ * (`adapters/plugin.ts#hookGate`), and on 2026-10-09 a plugin from an older
12
+ * build did not recognise the newer `connect`'s hook line and didn't. That
13
+ * reading is tolerant now (`host-wiring.ts#readOurHook`), and this is the
14
+ * backstop for the next way it fails: the FIRST hook process to claim the
15
+ * event does the event's whole job, and its twin exits with no output.
16
+ *
17
+ * THE CLAIM is one row of its OWN small database,
18
+ * `sessions/claims/hook-claims.sqlite` (`claimsPath`), changed in one `BEGIN
19
+ * IMMEDIATE` transaction: the second process waits and then reads what the
20
+ * first wrote. The row holds only the claims of the last `CLAIM_WINDOW_MS` (at
21
+ * most `CLAIM_KEEP` of them), so it never grows. Each of the claim's two writes
22
+ * waits at most `CLAIM_WAIT_MS`.
23
+ *
24
+ * ITS OWN FILE, NOT THE STORE'S `meta` (2026-10-10). Until then the row lived in
25
+ * `counterparts.sqlite`, so the claim waited on the store's one write lock, and
26
+ * the store's busiest writer is the detached worker the previous Stop or
27
+ * SessionEnd started: it reaches the store a bun start-up after its hook exits,
28
+ * which is just when the NEXT hook reaches it. On a loaded machine its commits
29
+ * held the lock for 300 to 600 ms at a time, past the claim's 500 ms, and the
30
+ * claim gave up (`database is locked`) where the hook's other writes, which wait
31
+ * five seconds, went through (CI on master a78e1dae; reproduced in a 2-CPU Linux
32
+ * container). In this file the only writers are claims, each well under a
33
+ * millisecond of work, so a claim waits on nothing but another claim, and a
34
+ * store somebody holds costs it nothing at all. The file is host state, not
35
+ * memory: inside `sessions/` (LAYOUT's entry says new state of that kind goes
36
+ * there), never backed up, and nothing in it outlives the window. In a
37
+ * directory of its own, as `log/` and `association/` are, because the sessions
38
+ * prune removes any FILE directly in `sessions/` untouched for a week, and in
39
+ * WAL a commit touches the log, not the database file.
40
+ *
41
+ * WHAT MAKES TWO PROCESSES TWINS — the same KEY, and running AT THE SAME TIME.
42
+ *
43
+ * - THE KEY is what Claude Code hands every hook of one event identically: the
44
+ * session id, the event, and `prompt_id` (2.1.296: "UUID correlating a user
45
+ * prompt with all subsequent events until the next prompt"), with the prompt
46
+ * text (UserPromptSubmit), `source` (SessionStart), `stop_hook_active` and
47
+ * the last assistant message (Stop), `reason` (SessionEnd) and `trigger`
48
+ * (PreCompact) folded in. Text is hashed; the key is a hash, and nothing of
49
+ * the prompt is stored. The transcript's size is NOT in it: the host may
50
+ * write between the twins starting, and a key that differs between twins is
51
+ * no claim at all.
52
+ * - AT THE SAME TIME: the host starts the twins together, so each began before
53
+ * the other could have finished. The winner records when its process started
54
+ * and, as it exits, when it finished; a process with the same key that
55
+ * STARTED BEFORE THE HOLDER FINISHED (or while it is still running) is its
56
+ * twin. A process that started after the holder finished is a separate event
57
+ * that happens to look the same — a host with no `prompt_id` sending the same
58
+ * words twice, a session resumed twice in a row — and it delivers. So the
59
+ * time a hook takes, the store's busy timeout or a slow start-up cannot turn
60
+ * a twin into a second delivery, and no repeat is ever swallowed by a clock.
61
+ * - A holder that never says it finished (killed, crashed) holds for
62
+ * `CLAIM_WINDOW_MS` and no longer.
63
+ *
64
+ * FAIL-OPEN, ALWAYS. No session id, an observer, a claims file that will not
65
+ * take the write: this process delivers. Two deliveries are a nuisance; none is
66
+ * a session that woke up with no memory. A single wiring therefore behaves
67
+ * exactly as before, at the cost of two small writes per event.
68
+ *
69
+ * WHY ONE WIRING CLAIMS TOO. A hook cannot know it has no twin: the claim is the
70
+ * backstop for exactly the case where reading the host's wiring got it wrong
71
+ * (2026-10-09), so it cannot be skipped on that same reading. What one wiring
72
+ * pays is the two small writes, on a file nothing else writes.
73
+ */
74
+ import { createHash } from "node:crypto";
75
+ import { mkdirSync } from "node:fs";
76
+ import { dirname, join } from "node:path";
77
+
78
+ import { HOOK_CLAIM_LOST_EVENT } from "../../core/counterpart.js";
79
+ import { isLocked, openDb } from "../../core/store/db.js";
80
+ import { sessionsDir } from "../sessions.js";
81
+ import type { HookName } from "./hooks.js";
82
+
83
+ /** The claims' own directory and database, inside the store's `sessions/`. */
84
+ export const CLAIMS_DIR = "claims";
85
+ export const CLAIMS_FILE = "hook-claims.sqlite";
86
+ /** The one row in it holding the recent claims (the key it had in `meta`). */
87
+ export const CLAIMS_ROW = "adapter.hook.claims";
88
+ /** How long a claim is kept, and the longest an unfinished one holds. */
89
+ export const CLAIM_WINDOW_MS = 15_000;
90
+ /** The most claims the row keeps, newest first — a bound on its size if a
91
+ * clock jumps or a burst of sessions fires at once. */
92
+ export const CLAIM_KEEP = 64;
93
+ /** How long each of the claim's two writes waits on another claim before it
94
+ * gives up (and the hook delivers). A twin outwaits its holder's claim — well
95
+ * under a millisecond of work — many times over. Only claims write the file,
96
+ * so the store's own writers (the worker, the MCP server, the CLI) never
97
+ * count against it. */
98
+ export const CLAIM_WAIT_MS = 500;
99
+
100
+ /** Where the claims live, for a store at `dataDir`. */
101
+ export function claimsPath(dataDir: string): string {
102
+ return join(sessionsDir(dataDir), CLAIMS_DIR, CLAIMS_FILE);
103
+ }
104
+
105
+ const CLAIMS_DDL = "CREATE TABLE IF NOT EXISTS claims (key TEXT PRIMARY KEY, value TEXT NOT NULL)";
106
+
107
+ /**
108
+ * READ, CHANGE AND WRITE THE CLAIMS ROW IN ONE `BEGIN IMMEDIATE`, on the claims
109
+ * file's own connection, opened for this one write and closed after it. `fn`
110
+ * gets the row as it stands inside the transaction and returns the new value,
111
+ * or `undefined` to leave it. Throws what SQLite or the file system throws.
112
+ *
113
+ * Opened as the store is (`openDb`, WAL), then: wait `CLAIM_WAIT_MS`, not the
114
+ * store's five seconds; `synchronous = NORMAL`, not the store's FULL, because
115
+ * nothing here outlives `CLAIM_WINDOW_MS`, so a commit a power cut takes back
116
+ * costs nothing, and in WAL NORMAL never corrupts the file. The two writes of
117
+ * an event, measured in a 2-CPU Linux container (2026-10-10): 3-4 ms with the
118
+ * rollback journal and FULL, about 1 ms with WAL and FULL (an fsync per commit),
119
+ * 0.2 ms with WAL and NORMAL. The log is folded
120
+ * every 100 pages rather than SQLite's 1000, so it stays under half a megabyte
121
+ * beside a row of a few kilobytes.
122
+ */
123
+ function updateClaims(dataDir: string, fn: (current: string | undefined) => string | undefined): void {
124
+ const path = claimsPath(dataDir);
125
+ mkdirSync(dirname(path), { recursive: true });
126
+ const db = openDb(path, { wal: true });
127
+ try {
128
+ db.exec(`PRAGMA busy_timeout = ${String(CLAIM_WAIT_MS)}`);
129
+ db.exec("PRAGMA synchronous = NORMAL");
130
+ db.exec("PRAGMA wal_autocheckpoint = 100");
131
+ db.exec(CLAIMS_DDL);
132
+ db.transaction(() => {
133
+ const row = db.get<{ value: string }>("SELECT value FROM claims WHERE key = ?", CLAIMS_ROW);
134
+ const next = fn(row?.value);
135
+ if (next !== undefined) db.run("INSERT OR REPLACE INTO claims (key, value) VALUES (?, ?)", CLAIMS_ROW, next);
136
+ });
137
+ } finally {
138
+ db.close();
139
+ }
140
+ }
141
+
142
+ /** Which side of the doubled wiring a hook process is, for the record. */
143
+ export type ClaimSide = "plugin" | "settings";
144
+
145
+ /** The outcome: `won` delivers, `lost` exits quietly, `unclaimed` delivers
146
+ * because no claim could be made (no session, an observer, a failed write). */
147
+ export type ClaimOutcome = "won" | "lost" | "unclaimed";
148
+
149
+ function text(payload: Record<string, unknown>, field: string): string {
150
+ const v = payload[field];
151
+ return typeof v === "string" ? v : "";
152
+ }
153
+
154
+ function digest(value: string): string {
155
+ return value.length === 0 ? "" : createHash("sha256").update(value).digest("hex").slice(0, 32);
156
+ }
157
+
158
+ /**
159
+ * The claim key for this event, from the input Claude Code gave the hook; null
160
+ * when there is no session id to claim under. Pure.
161
+ */
162
+ export function deliveryClaimKey(name: HookName, payload: Record<string, unknown>): string | null {
163
+ const session = text(payload, "session_id");
164
+ if (session.length === 0) return null;
165
+ const parts = [
166
+ session,
167
+ name,
168
+ text(payload, "prompt_id"),
169
+ text(payload, "agent_id"),
170
+ text(payload, "source"),
171
+ payload["stop_hook_active"] === true ? "re-fired" : "",
172
+ digest(text(payload, "prompt")),
173
+ digest(text(payload, "last_assistant_message")),
174
+ text(payload, "reason"),
175
+ text(payload, "trigger"),
176
+ digest(text(payload, "custom_instructions")),
177
+ ];
178
+ return digest(JSON.stringify(parts));
179
+ }
180
+
181
+ /** One held claim: when it was made, by which side, when its process started,
182
+ * and when it finished (absent while it runs). */
183
+ interface Held {
184
+ readonly at: number;
185
+ readonly side: string;
186
+ readonly started: number;
187
+ readonly ended?: number;
188
+ }
189
+
190
+ function readClaims(raw: string | undefined): Record<string, Held> {
191
+ if (raw === undefined) return {};
192
+ try {
193
+ const parsed: unknown = JSON.parse(raw);
194
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
195
+ const out: Record<string, Held> = {};
196
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
197
+ if (!Array.isArray(v) || typeof v[0] !== "number" || !Number.isFinite(v[0])) continue;
198
+ const at = v[0];
199
+ const started = typeof v[2] === "number" && Number.isFinite(v[2]) ? v[2] : at;
200
+ const ended = typeof v[3] === "number" && Number.isFinite(v[3]) ? v[3] : undefined;
201
+ out[k] = { at, side: typeof v[1] === "string" ? v[1] : "", started, ...(ended === undefined ? {} : { ended }) };
202
+ }
203
+ return out;
204
+ } catch {
205
+ return {};
206
+ }
207
+ }
208
+
209
+ function writeClaims(claims: Record<string, Held>): string {
210
+ return JSON.stringify(
211
+ Object.fromEntries(
212
+ Object.entries(claims).map(([k, h]) => [k, h.ended === undefined ? [h.at, h.side, h.started] : [h.at, h.side, h.started, h.ended]]),
213
+ ),
214
+ );
215
+ }
216
+
217
+ /** What a claim needs of the counterpart: the store's directory, under which
218
+ * the claims file lives, and the durable event log a loss is recorded in.
219
+ * Structural, so a test can hand it a directory no file can be made under. */
220
+ export interface ClaimDoors {
221
+ readonly store: { readonly dir: string };
222
+ noteAdapterEvent(name: typeof HOOK_CLAIM_LOST_EVENT, data: Record<string, unknown>): boolean;
223
+ }
224
+
225
+ export interface ClaimInput {
226
+ readonly hook: HookName;
227
+ readonly key: string | null;
228
+ readonly sessionId: string;
229
+ readonly side: ClaimSide;
230
+ /** Under observer nothing is written, so nothing is claimed. */
231
+ readonly observer: boolean;
232
+ /** When this process started (epoch ms); `performance.timeOrigin` by default. */
233
+ readonly started?: number;
234
+ readonly now?: number;
235
+ }
236
+
237
+ export interface Claim {
238
+ readonly outcome: ClaimOutcome;
239
+ /** The winner's claim time, which `finishClaim` names. */
240
+ readonly at?: number;
241
+ /** The side that holds the claim, when this process lost it. */
242
+ readonly heldBy?: string;
243
+ /** Why nothing was claimed. */
244
+ readonly detail?: string;
245
+ /** Set when the claim could not be written because another claim held the
246
+ * file past `CLAIM_WAIT_MS`: contention, which passes, not a fault. */
247
+ readonly busy?: boolean;
248
+ }
249
+
250
+ /**
251
+ * Claim this event for this process, or learn that its twin already has. A
252
+ * loss is recorded (`adapter.hook.claim.lost`, prunable telemetry). Never
253
+ * throws.
254
+ */
255
+ export function claimDelivery(doors: ClaimDoors, input: ClaimInput): Claim {
256
+ if (input.key === null) return { outcome: "unclaimed", detail: "no session id" };
257
+ if (input.observer) return { outcome: "unclaimed", detail: "observer" };
258
+ const key = input.key;
259
+ const now = input.now ?? Date.now();
260
+ const started = input.started ?? performance.timeOrigin;
261
+ const fresh = (h: Held): boolean => Math.abs(now - Math.max(h.at, h.ended ?? h.at)) < CLAIM_WINDOW_MS;
262
+ // Written inside the transaction's callback, read after it.
263
+ const seen: { heldBy: string | null } = { heldBy: null };
264
+ try {
265
+ updateClaims(doors.store.dir, (current) => {
266
+ const claims = readClaims(current);
267
+ const held = claims[key];
268
+ // A TWIN: the same event, and this process began before the holder ended.
269
+ if (held !== undefined && fresh(held) && (held.ended === undefined || started < held.ended)) {
270
+ seen.heldBy = held.side;
271
+ return undefined;
272
+ }
273
+ const kept = Object.entries(claims)
274
+ .filter(([k, h]) => k !== key && fresh(h))
275
+ .sort((a, b) => b[1].at - a[1].at)
276
+ .slice(0, CLAIM_KEEP - 1);
277
+ return writeClaims(Object.fromEntries([[key, { at: now, side: input.side, started }], ...kept]));
278
+ });
279
+ } catch (err) {
280
+ const detail = err instanceof Error ? err.message : String(err);
281
+ return isLocked(err) ? { outcome: "unclaimed", detail, busy: true } : { outcome: "unclaimed", detail };
282
+ }
283
+ const winner = seen.heldBy;
284
+ if (winner === null) return { outcome: "won", at: now };
285
+ try {
286
+ doors.noteAdapterEvent(HOOK_CLAIM_LOST_EVENT, {
287
+ hook: input.hook,
288
+ session: input.sessionId,
289
+ lost: input.side,
290
+ won: winner.length === 0 ? null : winner,
291
+ });
292
+ } catch {
293
+ // The row is the record, not the decision: the twin still stands down.
294
+ }
295
+ return { outcome: "lost", heldBy: winner };
296
+ }
297
+
298
+ /**
299
+ * THE WINNER IS DONE: stamp its claim with the time it finished, so a later
300
+ * process with the same key — one that started after this — is read as the
301
+ * separate event it is. Only this process's own claim (same key, same `at`) is
302
+ * touched. Never throws: a stamp that does not land leaves the claim to expire.
303
+ */
304
+ export function finishClaim(doors: Pick<ClaimDoors, "store">, key: string, at: number, now: number = Date.now()): boolean {
305
+ let stamped = false;
306
+ try {
307
+ updateClaims(doors.store.dir, (current) => {
308
+ const claims = readClaims(current);
309
+ const held = claims[key];
310
+ if (held === undefined || held.at !== at) return undefined;
311
+ claims[key] = { ...held, ended: now };
312
+ stamped = true;
313
+ return writeClaims(claims);
314
+ });
315
+ } catch {
316
+ return false;
317
+ }
318
+ return stamped;
319
+ }