counterparts 0.1.0
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.
- package/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* The hook entry script. ONE executable for every hook, dispatching on the
|
|
4
|
+
* host's own event name.
|
|
5
|
+
*
|
|
6
|
+
* Run by the host as, e.g.:
|
|
7
|
+
*
|
|
8
|
+
* ~/.bun/bin/bun run <repo>/src/adapters/claude-code/bin/hook.ts
|
|
9
|
+
*
|
|
10
|
+
* with the hook payload on stdin. It writes the context block (or nothing) to
|
|
11
|
+
* stdout and ALWAYS exits 0 — a hook that fails the host is the one failure
|
|
12
|
+
* mode this adapter does not have (CONTRACT §5 G2). Everything in here is host
|
|
13
|
+
* trivia and may change with the host without touching a core contract (G9).
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { resolve } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
|
|
19
|
+
import { DATA_DIR_ENV, dataDir, describeGuardRefusal } from "../../../core/store/index.js";
|
|
20
|
+
import {
|
|
21
|
+
defaultConfigPath,
|
|
22
|
+
implicitConfigRefusal,
|
|
23
|
+
namedConfigRefusal,
|
|
24
|
+
namedUnreadableRefusal,
|
|
25
|
+
resolveConfigPath,
|
|
26
|
+
} from "../../config-path.js";
|
|
27
|
+
import type { ConfigChoice } from "../../config-path.js";
|
|
28
|
+
import {
|
|
29
|
+
describeScopeTrouble,
|
|
30
|
+
lookupScope,
|
|
31
|
+
mostRestrictiveVerdict,
|
|
32
|
+
readScopes,
|
|
33
|
+
scopesPath,
|
|
34
|
+
stanceOfMode,
|
|
35
|
+
} from "../../scopes.js";
|
|
36
|
+
import type { ScopeRead, ScopeVerdict } from "../../scopes.js";
|
|
37
|
+
import { canonicalScope, readSession } from "../../sessions.js";
|
|
38
|
+
import { loadConfig } from "../config.js";
|
|
39
|
+
import type { AdapterConfig } from "../config.js";
|
|
40
|
+
import { loadCredentials, permissionWarning } from "../credentials.js";
|
|
41
|
+
import type { CredentialLoad } from "../credentials.js";
|
|
42
|
+
import { HOOKS, openAdapter } from "../index.js";
|
|
43
|
+
import type { HookInput, HookName } from "../hooks.js";
|
|
44
|
+
import {
|
|
45
|
+
CONFIG_REFUSED,
|
|
46
|
+
CONFIG_UNREADABLE,
|
|
47
|
+
classifyStandDown,
|
|
48
|
+
decideSay,
|
|
49
|
+
readMark,
|
|
50
|
+
writeMark,
|
|
51
|
+
} from "../standdown.js";
|
|
52
|
+
import type { SaysSoHook, StandDownFault } from "../standdown.js";
|
|
53
|
+
import { readTranscript } from "../transcript.js";
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The host's own spelling of the one event that carries a notice. It appears
|
|
57
|
+
* twice — as a key below, and as `hookSpecificOutput.hookEventName` in the JSON
|
|
58
|
+
* form — and the host matches that field against its own name, so the two
|
|
59
|
+
* spellings must be one constant.
|
|
60
|
+
*/
|
|
61
|
+
export const HOST_SESSION_START = "SessionStart";
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* THE MOST STDOUT THIS HOOK MAY PRINT AS JSON, and why the number is 9,500.
|
|
65
|
+
*
|
|
66
|
+
* The host's own cap, verbatim (https://code.claude.com/docs/en/hooks): "Hook
|
|
67
|
+
* output strings, including `additionalContext`, `systemMessage`, and plain
|
|
68
|
+
* stdout, are capped at 10,000 characters. Output that exceeds this limit is
|
|
69
|
+
* saved to a file and replaced with a preview and file path."
|
|
70
|
+
*
|
|
71
|
+
* Which is survivable for PLAIN stdout — a truncated wake is still a wake — and
|
|
72
|
+
* fatal for the JSON form: replace the printed object with a preview and the
|
|
73
|
+
* stdout no longer parses as JSON, so `additionalContext` is never read and the
|
|
74
|
+
* ENTIRE WAKE is dropped. And the envelope is bigger than the wake it carries:
|
|
75
|
+
* JSON escaping turns every newline into two characters, so a 9,038-byte wake
|
|
76
|
+
* plus a 352-character notice measured 9,618 characters of stdout — one bad day
|
|
77
|
+
* away from losing the wake on exactly the morning something was red.
|
|
78
|
+
*
|
|
79
|
+
* So the JSON form is used only while it demonstrably fits, with 500 characters
|
|
80
|
+
* of margin for the escaping, and the fallback is the plain wake: the notice is
|
|
81
|
+
* what gets dropped, never the memory. `counterparts doctor` still prints it.
|
|
82
|
+
*/
|
|
83
|
+
export const ENVELOPE_MAX_CHARS = 9500;
|
|
84
|
+
|
|
85
|
+
/** The host's event names, mapped to this adapter's. Host trivia, by definition. */
|
|
86
|
+
const HOST_HOOKS: Record<string, HookName> = {
|
|
87
|
+
[HOST_SESSION_START]: "session-start",
|
|
88
|
+
UserPromptSubmit: "user-prompt-submit",
|
|
89
|
+
Stop: "stop",
|
|
90
|
+
SessionEnd: "session-end",
|
|
91
|
+
PreCompact: "pre-compact",
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Where the host's configuration for this package lives BY DEFAULT — the path
|
|
96
|
+
* this file has read since it was written, unchanged, and the one the owner's
|
|
97
|
+
* live host resolves at every hook event because it passes no flag.
|
|
98
|
+
*
|
|
99
|
+
* `--config <absolute path>` and `COUNTERPARTS_CONFIG` override it, in that
|
|
100
|
+
* order (`adapters/config-path.ts` states the rule for all four entry points).
|
|
101
|
+
* Neither is set on the live host; a run that sets neither resolves exactly
|
|
102
|
+
* this.
|
|
103
|
+
*/
|
|
104
|
+
export const CONFIG_PATH = defaultConfigPath();
|
|
105
|
+
|
|
106
|
+
/** The worker script this hook's spawn runs. Resolved from THIS file's location,
|
|
107
|
+
* never from a working directory the host chose. */
|
|
108
|
+
export const RUNNER_PATH = fileURLToPath(new URL("./runner.ts", import.meta.url));
|
|
109
|
+
|
|
110
|
+
async function readStdin(): Promise<string> {
|
|
111
|
+
const chunks: Buffer[] = [];
|
|
112
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
113
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The configuration this process runs on, AND the credential load it performed.
|
|
118
|
+
*
|
|
119
|
+
* The credentials are read HERE, at the process entry point, before anything
|
|
120
|
+
* asks for a key: the spawner's `base` env is `process.env`, the two clients
|
|
121
|
+
* read `process.env`, and the capability report reads `process.env` — so the gap
|
|
122
|
+
* must be filled before any of them look. Measured day 0 of the parallel run:
|
|
123
|
+
* this host's hook processes carry neither name, so without this line the worker
|
|
124
|
+
* refuses every spawn and the embedder never opens.
|
|
125
|
+
*
|
|
126
|
+
* `env` is injected so a test can prove the whole path over a fresh object
|
|
127
|
+
* instead of mutating the suite's own process.
|
|
128
|
+
*/
|
|
129
|
+
export function hostConfig(
|
|
130
|
+
path = CONFIG_PATH,
|
|
131
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
132
|
+
): { config: AdapterConfig; credentials: CredentialLoad; reason: string } {
|
|
133
|
+
let raw: unknown;
|
|
134
|
+
try {
|
|
135
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
136
|
+
} catch {
|
|
137
|
+
// Absent is ordinary; unreadable resolves to OBSERVER inside `loadConfig`,
|
|
138
|
+
// which is the fail direction observer-mode G5 requires.
|
|
139
|
+
raw = undefined;
|
|
140
|
+
}
|
|
141
|
+
const load = loadConfig(raw);
|
|
142
|
+
const loaded = load.config;
|
|
143
|
+
// Only a configuration we UNDERSTOOD names a file. An unreadable one resolves
|
|
144
|
+
// to `{ observer: true }` above, and an observer opens no credential.
|
|
145
|
+
const credentials = loadCredentials(loaded.credentialsFile, env);
|
|
146
|
+
// The data dir is RESOLVED here and carried explicitly, so the spawner has a
|
|
147
|
+
// value to pin onto the child (scar §2.13). Leaving it undefined would make
|
|
148
|
+
// the parent and the child resolve it independently, from an environment
|
|
149
|
+
// either of them might have inherited differently.
|
|
150
|
+
// `reason` travels out so the caller can tell "we understood this" from "we
|
|
151
|
+
// stood down because we did not" — the difference matters only for a config
|
|
152
|
+
// somebody NAMED (`namedUnreadableRefusal`).
|
|
153
|
+
return {
|
|
154
|
+
config: { ...loaded, dataDir: loaded.dataDir ?? dataDir() },
|
|
155
|
+
credentials,
|
|
156
|
+
reason: load.reason,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The configuration this hook process will read, and which of the three rules
|
|
162
|
+
* chose it. Exported and injectable so the no-flag, no-env case — the ONLY case
|
|
163
|
+
* the owner's live host produces — is provable without a process.
|
|
164
|
+
*/
|
|
165
|
+
export function hookConfigChoice(
|
|
166
|
+
argv: readonly string[] = process.argv.slice(2),
|
|
167
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
168
|
+
): ConfigChoice {
|
|
169
|
+
return resolveConfigPath(argv, env as Record<string, string | undefined>);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* WHERE THE AGENT'S SHELL IS RIGHT NOW — the directory THIS EVENT happened in,
|
|
174
|
+
* and nothing more.
|
|
175
|
+
*
|
|
176
|
+
* **The 2026-09-04 measurement this used to rest on is retired.** It read the
|
|
177
|
+
* payload's `cwd` as "the project directory"; the host documents it as
|
|
178
|
+
* "current working directory (follows Claude into worktrees)", and it does. A
|
|
179
|
+
* session that walks into a git worktree — which is how every piece of work in
|
|
180
|
+
* this repository is done — reports the worktree here from that turn onward. One
|
|
181
|
+
* real session on 2026-09-17 had its spans filed under FOUR directories on this
|
|
182
|
+
* value alone.
|
|
183
|
+
*
|
|
184
|
+
* So this is no longer the scope anything is FILED under. It answers exactly one
|
|
185
|
+
* question — which directory the owner's registry should be consulted about for
|
|
186
|
+
* this event — and the filing scope is `sessionScope` below. The payload first,
|
|
187
|
+
* because the whole point is that it moves; the two fallbacks are for a payload
|
|
188
|
+
* that arrived unparsable.
|
|
189
|
+
*/
|
|
190
|
+
export function eventDirectory(
|
|
191
|
+
payload: Record<string, unknown>,
|
|
192
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
193
|
+
): string {
|
|
194
|
+
if (typeof payload["cwd"] === "string" && payload["cwd"].length > 0) {
|
|
195
|
+
return resolve(payload["cwd"]);
|
|
196
|
+
}
|
|
197
|
+
const projectDir = env["CLAUDE_PROJECT_DIR"];
|
|
198
|
+
if (typeof projectDir === "string" && projectDir.length > 0) return resolve(projectDir);
|
|
199
|
+
return process.cwd();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* THE `SessionStart` SOURCES THAT OPEN A SESSION rather than interrupting one.
|
|
204
|
+
*
|
|
205
|
+
* The host fires `SessionStart` five ways and says which in `source`: `startup`,
|
|
206
|
+
* `resume`, `clear`, `fork` — all of them a session beginning, in whatever
|
|
207
|
+
* directory the host launched it in — and `compact`, which arrives in the MIDDLE
|
|
208
|
+
* of a session whose MCP server is not relaunched. Treating a compaction as a
|
|
209
|
+
* start would re-anchor a long session's scope to wherever its shell had got to,
|
|
210
|
+
* which is the failure this file is fixing, arriving by another door.
|
|
211
|
+
*
|
|
212
|
+
* A `source` this list does not know, or none at all, does NOT re-anchor a
|
|
213
|
+
* session that already has a record: the safe direction for an unrecognised
|
|
214
|
+
* event is to leave the session where it is.
|
|
215
|
+
*/
|
|
216
|
+
export const FRESH_SESSION_SOURCES: readonly string[] = ["startup", "resume", "clear", "fork"];
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* THE ONE DIRECTORY A SESSION IS FILED UNDER, FOR ITS WHOLE LIFE — spans,
|
|
220
|
+
* boundaries, coverage, the ask's coverage read, the session registry record and
|
|
221
|
+
* the worker's session state.
|
|
222
|
+
*
|
|
223
|
+
* **Why it is not the event's directory.** Measured on the owner's store,
|
|
224
|
+
* 2026-09-17: one session's spans landed in four scope directories and its
|
|
225
|
+
* boundaries in all four, while its authored deposits and their coverage marks
|
|
226
|
+
* landed in ONE — because the MCP server's scope is fixed at launch and a
|
|
227
|
+
* deposit only covers spans in its own scope. Everything the session wrote in
|
|
228
|
+
* the other three was left uncovered, to be rewritten twelve hours later by the
|
|
229
|
+
* crash fallback as though the session had died. Two worktree scopes on that
|
|
230
|
+
* store hold 298 fallback memories and zero authored ones.
|
|
231
|
+
*
|
|
232
|
+
* **Two sources, in this order, and they agree by construction.**
|
|
233
|
+
*
|
|
234
|
+
* 1. **The session registry's own record** (`adapters/sessions.ts`), which
|
|
235
|
+
* SessionStart wrote and which `recordSession` refuses to rewrite after a
|
|
236
|
+
* start. It is the recorded fact of where this session began, and it is the
|
|
237
|
+
* SAME string `mcp/server.ts#requireBoundSession` matches a deposit
|
|
238
|
+
* against — so a scope taken from here cannot disagree with the server that
|
|
239
|
+
* claims coverage.
|
|
240
|
+
* 2. **`CLAUDE_PROJECT_DIR`, then the payload's `cwd`, then `process.cwd()`**,
|
|
241
|
+
* for the first event of a session and for a session whose record was
|
|
242
|
+
* pruned. The host documents `CLAUDE_PROJECT_DIR` as the project root where
|
|
243
|
+
* the session started, exports it to hook processes AND to stdio MCP
|
|
244
|
+
* servers, and keeps it put when the agent enters a worktree or runs `cd` —
|
|
245
|
+
* which is exactly the property the payload's `cwd` lacks. `serve.ts` reads
|
|
246
|
+
* the same variable in the same position, which is what makes the two sides
|
|
247
|
+
* agree without either one telling the other.
|
|
248
|
+
*
|
|
249
|
+
* Canonical on both sides (`canonicalScope`): the record stores a realpath, so a
|
|
250
|
+
* scope read back from it and one resolved fresh have to be the same string or
|
|
251
|
+
* the session would split on `/tmp` versus `/private/tmp` alone — and span
|
|
252
|
+
* directories are keyed by a hash of this exact string (`remember/spans.ts`).
|
|
253
|
+
*/
|
|
254
|
+
export function sessionScope(
|
|
255
|
+
/** The store the session registry lives under. Absent ⇒ no record to read. */
|
|
256
|
+
dataDir: string | undefined,
|
|
257
|
+
payload: Record<string, unknown>,
|
|
258
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
259
|
+
): string {
|
|
260
|
+
const sessionId = typeof payload["session_id"] === "string" ? payload["session_id"] : "";
|
|
261
|
+
if (dataDir !== undefined && dataDir.length > 0 && sessionId.length > 0 && !opensASession(payload)) {
|
|
262
|
+
// `readSession` answers null on every failure rather than throwing, which is
|
|
263
|
+
// the rule this whole path lives by: a hook may not fail the host (§5 G2).
|
|
264
|
+
const recorded = readSession(dataDir, sessionId)?.scope;
|
|
265
|
+
// Canonicalised HERE rather than trusted from the file: `recordSession`
|
|
266
|
+
// canonicalises on write, so this is a no-op for every record this code
|
|
267
|
+
// wrote — and a record written by anything else (a hand edit, an older
|
|
268
|
+
// build, a future writer) would otherwise file this session's spans under a
|
|
269
|
+
// directory keyed by a hash of a string nothing else spells that way.
|
|
270
|
+
if (recorded !== undefined && recorded.length > 0) return canonicalScope(recorded);
|
|
271
|
+
}
|
|
272
|
+
return startDirectory(payload, env);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Is this event a session BEGINNING, whose directory becomes the session's? */
|
|
276
|
+
function opensASession(payload: Record<string, unknown>): boolean {
|
|
277
|
+
if (payload["hook_event_name"] !== HOST_SESSION_START) return false;
|
|
278
|
+
const source = payload["source"];
|
|
279
|
+
return typeof source === "string" && FRESH_SESSION_SOURCES.includes(source);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The directory a session that has no record yet began in. `CLAUDE_PROJECT_DIR`
|
|
284
|
+
* first — see `sessionScope` for why the payload's `cwd` is not good enough.
|
|
285
|
+
*/
|
|
286
|
+
export function startDirectory(
|
|
287
|
+
payload: Record<string, unknown>,
|
|
288
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
289
|
+
): string {
|
|
290
|
+
const projectDir = env["CLAUDE_PROJECT_DIR"];
|
|
291
|
+
if (typeof projectDir === "string" && projectDir.length > 0) return canonicalScope(projectDir);
|
|
292
|
+
if (typeof payload["cwd"] === "string" && payload["cwd"].length > 0) {
|
|
293
|
+
return canonicalScope(payload["cwd"]);
|
|
294
|
+
}
|
|
295
|
+
return canonicalScope(process.cwd());
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* THE SCOPE VERDICT for this event: which entry in `<config dir>/scopes.json`
|
|
300
|
+
* governs, and whether the file itself could be read.
|
|
301
|
+
*
|
|
302
|
+
* It takes as many directories as the caller has, and answers with the MOST
|
|
303
|
+
* RESTRICTIVE verdict among them (`scopes.ts#mostRestrictiveVerdict`) — because
|
|
304
|
+
* one event now has two directories to answer for, the session's and the shell's,
|
|
305
|
+
* and privacy follows both while filing follows only the first. The FIRST
|
|
306
|
+
* directory is the session's own and wins every tie, so the `unset` that raises
|
|
307
|
+
* the first-launch question is asked about the directory the session is filed
|
|
308
|
+
* under rather than about wherever it happens to be standing.
|
|
309
|
+
*
|
|
310
|
+
* Exported and injectable because the hook's most important behaviour — `off`
|
|
311
|
+
* means nothing is opened at all — is decided from it before any store exists,
|
|
312
|
+
* and that has to be provable without a process.
|
|
313
|
+
*/
|
|
314
|
+
export function hookScopeVerdict(
|
|
315
|
+
configPath: string,
|
|
316
|
+
...scopes: readonly string[]
|
|
317
|
+
): { verdict: ScopeVerdict; read: ScopeRead } {
|
|
318
|
+
const read = readScopes(scopesPath(configPath));
|
|
319
|
+
return { verdict: verdictOver(read, scopes), read };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The most restrictive verdict over `scopes`, first one winning ties. */
|
|
323
|
+
function verdictOver(read: ScopeRead, scopes: readonly string[]): ScopeVerdict {
|
|
324
|
+
let verdict: ScopeVerdict = { mode: "unset", matched: null, entry: null };
|
|
325
|
+
let first = true;
|
|
326
|
+
for (const dir of scopes) {
|
|
327
|
+
const one = lookupScope(read.registry, dir);
|
|
328
|
+
verdict = first ? one : mostRestrictiveVerdict(verdict, one);
|
|
329
|
+
first = false;
|
|
330
|
+
}
|
|
331
|
+
return verdict;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function toHookInput(
|
|
335
|
+
payload: Record<string, unknown>,
|
|
336
|
+
opts: {
|
|
337
|
+
/** The scope this session is filed under, when the caller already resolved
|
|
338
|
+
* it. Absent: resolved here, from the registry under `dataDir`. */
|
|
339
|
+
readonly scope?: string;
|
|
340
|
+
readonly dataDir?: string;
|
|
341
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
342
|
+
} = {},
|
|
343
|
+
): HookInput {
|
|
344
|
+
const scope = opts.scope ?? sessionScope(opts.dataDir, payload, opts.env ?? process.env);
|
|
345
|
+
const transcriptPath =
|
|
346
|
+
typeof payload["transcript_path"] === "string" && payload["transcript_path"].length > 0
|
|
347
|
+
? payload["transcript_path"]
|
|
348
|
+
: undefined;
|
|
349
|
+
const transcript = readTranscript(transcriptPath);
|
|
350
|
+
return {
|
|
351
|
+
sessionId: typeof payload["session_id"] === "string" ? payload["session_id"] : "",
|
|
352
|
+
scope,
|
|
353
|
+
turns: transcript.turns,
|
|
354
|
+
expansions: transcript.expansions,
|
|
355
|
+
// THE PATH ITSELF, beside the parse of it. The delivery check reads the head
|
|
356
|
+
// of the same file for the attachment `parseTranscript` deliberately skips
|
|
357
|
+
// (`hooks.ts#checkWakeArrival`), and a parsed turn list cannot answer for
|
|
358
|
+
// what the host injected.
|
|
359
|
+
...(transcriptPath === undefined ? {} : { transcriptPath }),
|
|
360
|
+
// The host's re-fire of a blocked Stop, carried INTO the adapter and not
|
|
361
|
+
// only handled at delivery: the pass that says nothing must also advance
|
|
362
|
+
// nothing (`hooks.ts#askAtStop`).
|
|
363
|
+
...(payload["stop_hook_active"] === true ? { reFired: true } : {}),
|
|
364
|
+
...(typeof payload["prompt"] === "string" ? { prompt: payload["prompt"] } : {}),
|
|
365
|
+
at: new Date().toISOString().slice(0, 10),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* THE TWO EVENTS THE HOST DISPLAYS A `systemMessage` ON — measured by the
|
|
371
|
+
* owner's probe on 2026-09-11 and re-stated in `hostDelivery` below. Every other
|
|
372
|
+
* event's stand-down has nowhere to be seen, so it stays on stderr alone.
|
|
373
|
+
*/
|
|
374
|
+
const SAYS_SO_HOOKS: readonly SaysSoHook[] = ["session-start", "user-prompt-submit"];
|
|
375
|
+
|
|
376
|
+
/** Narrowed, so the say rule is written against the two events it is about. */
|
|
377
|
+
function saysSo(hook: HookName): hook is SaysSoHook {
|
|
378
|
+
return (SAYS_SO_HOOKS as readonly HookName[]).includes(hook);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* MAY THIS EVENT'S FAULT REACH THE OWNER'S TERMINAL AT ALL — the three gates,
|
|
383
|
+
* ahead of the question of what to say (`standdown.ts#decideSay`).
|
|
384
|
+
*
|
|
385
|
+
* Exported because a close-time throw cannot be induced from a hermetic test:
|
|
386
|
+
* it needs a patched tree, which is how the review that found the `didWork` gap
|
|
387
|
+
* proved it. The rule is worth pinning even so, and a pure predicate is the
|
|
388
|
+
* honest shape for a thing a process cannot reach.
|
|
389
|
+
*/
|
|
390
|
+
export function reachesTheOwner(
|
|
391
|
+
said: Pick<Said, "hook" | "wroteStdout" | "didWork">,
|
|
392
|
+
): said is Pick<Said, "hook" | "wroteStdout" | "didWork"> & { hook: SaysSoHook } {
|
|
393
|
+
// The work already happened, so this is the tidying-up failing: stderr's.
|
|
394
|
+
if (said.didWork) return false;
|
|
395
|
+
// Nothing may follow the wake, or stdout stops parsing as JSON.
|
|
396
|
+
if (said.wroteStdout) return false;
|
|
397
|
+
// And only where the host displays a `systemMessage` at all.
|
|
398
|
+
return saysSo(said.hook);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* WHAT THE STAND-DOWN PATH KNOWS ABOUT THIS EVENT SO FAR.
|
|
403
|
+
*
|
|
404
|
+
* Filled in as `main` learns each fact, because a fault can arrive before any of
|
|
405
|
+
* them is known: an unopenable store throws after the configuration is read, a
|
|
406
|
+
* refused configuration throws before there is a store to mark anything in.
|
|
407
|
+
*/
|
|
408
|
+
interface Said {
|
|
409
|
+
readonly hook: HookName;
|
|
410
|
+
readonly sessionId: string;
|
|
411
|
+
/** The store this run meant to use, once a configuration named one. */
|
|
412
|
+
dataDir: string | undefined;
|
|
413
|
+
/**
|
|
414
|
+
* TRUE once anything has gone to stdout. Nothing may follow it: the host reads
|
|
415
|
+
* stdout as JSON only when the WHOLE of it parses, so a JSON object printed
|
|
416
|
+
* after the wake would turn the wake into plain text and inject the warning
|
|
417
|
+
* into the model's context instead of showing it to the owner.
|
|
418
|
+
*/
|
|
419
|
+
wroteStdout: boolean;
|
|
420
|
+
/**
|
|
421
|
+
* TRUE once this event's WORK IS DONE — recall composed, the turn captured,
|
|
422
|
+
* the session record written. A failure after that point is not a failure of
|
|
423
|
+
* the turn, and must not be reported as one.
|
|
424
|
+
*
|
|
425
|
+
* It is a second flag rather than a reading of `wroteStdout`, and the review
|
|
426
|
+
* that found this says why: `wroteStdout` is an ORDERING guard, and on
|
|
427
|
+
* SessionStart the two coincide because SessionStart always writes stdout.
|
|
428
|
+
* On UserPromptSubmit they come apart — an ordinary prompt with nothing to
|
|
429
|
+
* inject writes nothing — so a throw from the `close()` in the `finally`
|
|
430
|
+
* below, which is I38's own shape, told the owner "skipped this turn" about a
|
|
431
|
+
* turn that had just succeeded. A warning that is sometimes false is the one
|
|
432
|
+
* outcome this whole track cannot afford.
|
|
433
|
+
*/
|
|
434
|
+
didWork: boolean;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* ONE LINE ON STDERR ALWAYS — AND, WHEN THIS WAS A FAULT, ONE RED LINE WHERE
|
|
439
|
+
* THE OWNER WILL SEE IT.
|
|
440
|
+
*
|
|
441
|
+
* Exit code is untouched (0, always) and nothing else is injected: no wake, no
|
|
442
|
+
* context, just the `systemMessage` the host displays. WHAT to say and WHETHER
|
|
443
|
+
* to say it is `standdown.ts#decideSay`'s, which is the rule that tells a store
|
|
444
|
+
* that will not open from a database that was merely busy; this function is the
|
|
445
|
+
* process end of it — the two channels, the mark, and the ordering.
|
|
446
|
+
*
|
|
447
|
+
* `marker` is false for the two configuration refusals — the first has no store
|
|
448
|
+
* at all, and the second stands down precisely so as not to touch the DEFAULT
|
|
449
|
+
* store's host state on the way out (see its call site) — so those keep no count
|
|
450
|
+
* and say it every turn. `standdown.ts` states why saying it again beats saying
|
|
451
|
+
* nothing.
|
|
452
|
+
*/
|
|
453
|
+
function standDown(
|
|
454
|
+
said: Said,
|
|
455
|
+
what: { readonly line: string; readonly fault: StandDownFault | null; readonly marker: boolean },
|
|
456
|
+
): void {
|
|
457
|
+
process.stderr.write(`[counterparts] hook stood down: ${what.line}\n`);
|
|
458
|
+
const fault = what.fault;
|
|
459
|
+
if (fault === null) return;
|
|
460
|
+
if (!reachesTheOwner(said)) return;
|
|
461
|
+
const dataDir = what.marker ? said.dataDir : undefined;
|
|
462
|
+
const decision = decideSay(fault, said.hook, said.sessionId, readMark(dataDir, said.sessionId));
|
|
463
|
+
// THE MARK IS WRITTEN EITHER WAY. A busy database nobody was told about is
|
|
464
|
+
// still one this session has met, and the count is what decides the next one.
|
|
465
|
+
writeMark(dataDir, said.sessionId, decision.mark);
|
|
466
|
+
if (decision.message === null) return;
|
|
467
|
+
process.stdout.write(JSON.stringify({ systemMessage: decision.message }));
|
|
468
|
+
said.wroteStdout = true;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* A configuration refusal as a REASON clause. `config-path.ts` writes its
|
|
473
|
+
* sentences to stand alone on stderr, so each opens with `refused: ` — which
|
|
474
|
+
* inside this message would read "memory is OFF for this session: refused: …".
|
|
475
|
+
* Said once.
|
|
476
|
+
*/
|
|
477
|
+
function refusalReason(sentence: string): string {
|
|
478
|
+
const opener = "refused: ";
|
|
479
|
+
return sentence.startsWith(opener) ? sentence.slice(opener.length) : sentence;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async function main(): Promise<void> {
|
|
483
|
+
let payload: Record<string, unknown> = {};
|
|
484
|
+
try {
|
|
485
|
+
const text = await readStdin();
|
|
486
|
+
if (text.trim().length > 0) payload = JSON.parse(text) as Record<string, unknown>;
|
|
487
|
+
} catch {
|
|
488
|
+
/* an unreadable payload is a quiet hook, never a failed session */
|
|
489
|
+
}
|
|
490
|
+
const name = HOST_HOOKS[String(payload["hook_event_name"] ?? "")];
|
|
491
|
+
if (name === undefined || !HOOKS.includes(name)) return;
|
|
492
|
+
|
|
493
|
+
// WHICH CONFIGURATION, decided before anything is read and refused rather
|
|
494
|
+
// than guessed. A caller who named one and named it badly gets a stand-down,
|
|
495
|
+
// never a silent fall-back onto the default store (`config-path.ts`).
|
|
496
|
+
const choice = hookConfigChoice();
|
|
497
|
+
const said: Said = {
|
|
498
|
+
hook: name,
|
|
499
|
+
sessionId: typeof payload["session_id"] === "string" ? payload["session_id"] : "",
|
|
500
|
+
dataDir: undefined,
|
|
501
|
+
wroteStdout: false,
|
|
502
|
+
didWork: false,
|
|
503
|
+
};
|
|
504
|
+
// THE FAULT HANDLER, HERE RATHER THAN AT THE ENTRY POINT, because this is
|
|
505
|
+
// where the event's own facts are in scope — which hook, which session, which
|
|
506
|
+
// store — and all three are needed to say a stand-down out loud once. The
|
|
507
|
+
// entry point's handler below stays exactly what it was: the last resort for
|
|
508
|
+
// anything that fails before any of this is known.
|
|
509
|
+
try {
|
|
510
|
+
await runHook(name, payload, choice, said);
|
|
511
|
+
} catch (err) {
|
|
512
|
+
// MASTER'S EXIT CODE, RESTORED EXACTLY. On master a throw out of `main`
|
|
513
|
+
// reached the entry point's rejection handler, which always exits 0 — so a
|
|
514
|
+
// Stop that had set `exitCode = 2` for an ask and then threw on `close()`
|
|
515
|
+
// exited 0. Catching the throw HERE let that 2 survive, which would have
|
|
516
|
+
// blocked the stop and fed this hook's whole stderr back to the model as
|
|
517
|
+
// Stop-hook feedback. Maybe an improvement; not this PR's to make. The one
|
|
518
|
+
// thing that changes on this branch is that two displayed events gain a
|
|
519
|
+
// `systemMessage`.
|
|
520
|
+
process.exitCode = 0;
|
|
521
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
522
|
+
const remedy = `Set "dataDir" in ${choice.path}, or set ${DATA_DIR_ENV}.`;
|
|
523
|
+
standDown(said, {
|
|
524
|
+
line: describeGuardRefusal(err, remedy) ?? detail,
|
|
525
|
+
fault: classifyStandDown(err),
|
|
526
|
+
marker: true,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function runHook(
|
|
532
|
+
name: HookName,
|
|
533
|
+
payload: Record<string, unknown>,
|
|
534
|
+
choice: ConfigChoice,
|
|
535
|
+
said: Said,
|
|
536
|
+
): Promise<void> {
|
|
537
|
+
// `namedConfigRefusal` covers the flag's own refusals AND the one the first
|
|
538
|
+
// review of this rule found: an absolute path to a file that is not there was
|
|
539
|
+
// honoured silently, read as an absent config, and fell through to `dataDir()`
|
|
540
|
+
// — the live store on any machine with an install. An absent DEFAULT is still
|
|
541
|
+
// ordinary; this only ever refuses a path somebody named.
|
|
542
|
+
//
|
|
543
|
+
// `implicitConfigRefusal` is the explicit-dir guard at this door: with
|
|
544
|
+
// `COUNTERPARTS_REQUIRE_EXPLICIT_DIR=1` an UNNAMED configuration stands the
|
|
545
|
+
// hook down too, because the default one names a store. The live host never
|
|
546
|
+
// sets it, so the no-flag, no-env case there resolves exactly what it did.
|
|
547
|
+
//
|
|
548
|
+
// ONE OF THE TWO IS A FAULT AND THE OTHER IS NOT. A configuration somebody
|
|
549
|
+
// NAMED and that could not be honoured is the third of the three invisible
|
|
550
|
+
// stand-downs H1 is about — a typo, and the adapter is off with nothing said.
|
|
551
|
+
// The guard's refusal keeps the treatment it has: it is the normal state of
|
|
552
|
+
// every agent and test shell in this project, and a red line in each of them
|
|
553
|
+
// is how a warning becomes wallpaper (`standdown.ts#isDeliberate`).
|
|
554
|
+
const named = namedConfigRefusal(choice);
|
|
555
|
+
const refusal = named ?? implicitConfigRefusal(choice);
|
|
556
|
+
if (refusal !== null) {
|
|
557
|
+
// No marker: nothing has named a store yet, so there is nowhere to keep one.
|
|
558
|
+
standDown(said, {
|
|
559
|
+
line: refusal,
|
|
560
|
+
fault:
|
|
561
|
+
named === null ? null : { code: CONFIG_REFUSED, reason: refusalReason(named), kind: "persistent" },
|
|
562
|
+
marker: false,
|
|
563
|
+
});
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
// WHICH DIRECTORY, AND WHAT THIS HOST WAS TOLD ABOUT IT — decided here,
|
|
567
|
+
// before a store is opened, because that ordering is the whole guarantee
|
|
568
|
+
// (`../CONTRACT.md` §5 G13): a directory set `off` produces no output and no
|
|
569
|
+
// write because nothing was ever constructed to produce either. An
|
|
570
|
+
// unreadable registry resolves to `unset` (⇒ on, today's behaviour) and is
|
|
571
|
+
// reported as a ring event once the adapter that owns the ring exists.
|
|
572
|
+
//
|
|
573
|
+
// THE EVENT'S OWN DIRECTORY IS CHECKED FIRST AND ALONE, and that ordering is
|
|
574
|
+
// load-bearing: it is what keeps an `off` directory's silence byte-for-byte
|
|
575
|
+
// what it was. Nothing has been read but the registry at this point — not the
|
|
576
|
+
// configuration, not the session record — so a directory the owner opted out
|
|
577
|
+
// of still costs exactly one small file read and returns. The session's own
|
|
578
|
+
// directory is folded in below, once there is a store path to look it up in.
|
|
579
|
+
const eventDir = eventDirectory(payload);
|
|
580
|
+
const { verdict: eventVerdict, read } = hookScopeVerdict(choice.path, eventDir);
|
|
581
|
+
if (stanceOfMode(eventVerdict.mode) === "off") {
|
|
582
|
+
// Silent on BOTH channels, deliberately. `off` is an opt-out, not an
|
|
583
|
+
// observer stand-down: there is no store to log to without writing one, and
|
|
584
|
+
// UserPromptSubmit fires every turn, so a line per event would be a
|
|
585
|
+
// permanent noise floor in the host's log for a directory that asked to be
|
|
586
|
+
// left alone. The record that this happened is the registry itself, which
|
|
587
|
+
// `counterparts scope <path>` prints on demand.
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
// A REGISTRY IN TROUBLE IS NOT SILENT, and that is a DIFFERENT exception from
|
|
591
|
+
// the one above (#92 review, F2). `off` is silent because the owner said leave
|
|
592
|
+
// this alone; a file that could not be read — or an entry in it that could not
|
|
593
|
+
// — has said nothing at all, and its fail direction is `unset`, which is ON.
|
|
594
|
+
// The review's measurement: one typo'd mode turned every correctly typed `off`
|
|
595
|
+
// in the file on, with the only evidence a ring event in a process that lives
|
|
596
|
+
// for one turn. So: one line, on SessionStart ONLY (UserPromptSubmit fires
|
|
597
|
+
// every turn and this is a warning, not a nag), AFTER the `off` return above
|
|
598
|
+
// so that the silence of an off directory stays byte-for-byte.
|
|
599
|
+
if (name === "session-start") {
|
|
600
|
+
const trouble = describeScopeTrouble(read, scopesPath(choice.path));
|
|
601
|
+
if (trouble !== null) process.stderr.write(`${trouble}\n`);
|
|
602
|
+
}
|
|
603
|
+
const { config: loaded, credentials, reason } = hostConfig(choice.path);
|
|
604
|
+
// THE THIRD ARM, and it is answered BEFORE anything reads under `dataDir`: a
|
|
605
|
+
// named file that parses but whose fields do not typecheck resolves to
|
|
606
|
+
// observer, and an observer with no `dataDir` reads the DEFAULT store.
|
|
607
|
+
// Standing down is the only answer that keeps the promise the flag makes, and
|
|
608
|
+
// standing down before the session registry is consulted is what keeps it from
|
|
609
|
+
// touching the default store's host state on the way out. An unreadable
|
|
610
|
+
// DEFAULT is unchanged — observer, as it always was.
|
|
611
|
+
const unreadable = namedUnreadableRefusal(choice, reason);
|
|
612
|
+
if (unreadable !== null) {
|
|
613
|
+
// Said out loud, and with NO marker: `hostConfig` has already resolved
|
|
614
|
+
// `dataDir` to the DEFAULT store, and leaving a file under it is exactly the
|
|
615
|
+
// host state this stand-down exists to keep its hands off. So it says it
|
|
616
|
+
// every turn instead — the cost of not touching a store this run refused.
|
|
617
|
+
standDown(said, {
|
|
618
|
+
line: unreadable,
|
|
619
|
+
fault: { code: CONFIG_UNREADABLE, reason: refusalReason(unreadable), kind: "persistent" },
|
|
620
|
+
marker: false,
|
|
621
|
+
});
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
// From here the configuration was understood, so the store it names is the one
|
|
625
|
+
// a stand-down may leave its once-per-session mark under.
|
|
626
|
+
said.dataDir = loaded.dataDir;
|
|
627
|
+
// THE SESSION'S OWN DIRECTORY — the one everything this event captures will be
|
|
628
|
+
// FILED under, whatever directory the agent's shell has wandered into. It is
|
|
629
|
+
// resolved here rather than above because its first source is the session
|
|
630
|
+
// registry, which lives under the store the configuration names.
|
|
631
|
+
const scope = sessionScope(loaded.dataDir, payload);
|
|
632
|
+
// AND PRIVACY FOLLOWS BOTH DIRECTORIES, most restrictive winning. Filing
|
|
633
|
+
// follows the session; a session that walks into a directory the owner set
|
|
634
|
+
// `off` or `observer` goes at least as quiet as that directory, or the stable
|
|
635
|
+
// scope would have become a way to carry capture past an opt-out. The
|
|
636
|
+
// session's verdict is first, so it wins a tie and its `unset` is the one that
|
|
637
|
+
// raises the first-launch question.
|
|
638
|
+
const verdict = mostRestrictiveVerdict(lookupScope(read.registry, scope), eventVerdict);
|
|
639
|
+
if (stanceOfMode(verdict.mode) === "off") {
|
|
640
|
+
// Silent, for the same reason the event-directory return above is silent —
|
|
641
|
+
// and reached only when the session's OWN directory is the one that is off,
|
|
642
|
+
// which is a session whose SessionStart ran somewhere the owner opted out
|
|
643
|
+
// of. Nothing has been written; the configuration and the session record
|
|
644
|
+
// were read, and neither is a write.
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
// THE COMBINATION: the most restrictive of what the configuration said and
|
|
648
|
+
// what the registry says (`adapters/scopes.ts#effectiveStance`, applied here
|
|
649
|
+
// by folding the registry's `observer` into the config the adapter opens on).
|
|
650
|
+
// It only ever adds restriction, which is why the three private directories
|
|
651
|
+
// running on an observer CONFIG are untouched by any of this.
|
|
652
|
+
const config: AdapterConfig =
|
|
653
|
+
verdict.mode === "observer" ? { ...loaded, observer: true } : loaded;
|
|
654
|
+
// A file the group or the world can read is WARNED about, by mode, and never
|
|
655
|
+
// refused: the owner's machine, the owner's call (§5 G2 — a throw here would
|
|
656
|
+
// fail the host over a permission bit).
|
|
657
|
+
const warning = permissionWarning(config.credentialsFile, credentials);
|
|
658
|
+
if (warning !== null) process.stderr.write(`${warning}\n`);
|
|
659
|
+
const adapter = openAdapter(config, {
|
|
660
|
+
command: process.execPath,
|
|
661
|
+
args: ["run", RUNNER_PATH],
|
|
662
|
+
credentials,
|
|
663
|
+
// WHICH FILE THIS RUN READ, carried into the adapter so it can be RECORDED:
|
|
664
|
+
// a hook cannot print to the owner (its stdout is the model's context), so
|
|
665
|
+
// the answer goes into the session registry record and the event ring
|
|
666
|
+
// instead. It is also pinned onto the worker's environment, so the child
|
|
667
|
+
// reads the same file its parent did rather than resolving one of its own.
|
|
668
|
+
configPath: choice.path,
|
|
669
|
+
// The verdict travels IN, for the same reason the credentials do: it is a
|
|
670
|
+
// fact about this process's startup, decided before anything opened, and
|
|
671
|
+
// the adapter's jobs with it are to record it and — when it is `unset` — to
|
|
672
|
+
// ask the question once (G41).
|
|
673
|
+
scope: verdict,
|
|
674
|
+
...(read.error === null ? {} : { scopeUnreadable: read.error }),
|
|
675
|
+
...(read.refused.length === 0 ? {} : { scopeRefused: read.refused.map((r) => r.key) }),
|
|
676
|
+
});
|
|
677
|
+
try {
|
|
678
|
+
// ONE read of the transcript, shared by the hook and the notice: `toHookInput`
|
|
679
|
+
// opens and parses the transcript file, and calling it twice would pay for
|
|
680
|
+
// that twice on the hot path. The scope is handed IN rather than resolved
|
|
681
|
+
// again: it was decided above, the registry verdict was taken on it, and two
|
|
682
|
+
// resolutions of one value is the shape scar §2.13 is about.
|
|
683
|
+
const input = toHookInput(payload, { scope });
|
|
684
|
+
const result = adapter.hook(name, input);
|
|
685
|
+
// THE WORK HAPPENED. Recall was composed, the turn was captured, the session
|
|
686
|
+
// record was written — whatever this event's job was, `adapter.hook` has
|
|
687
|
+
// done it and swallowed its own failures doing so (§5 G2). Anything that
|
|
688
|
+
// throws from here on is a failure of the tidying-up, not of the turn, and
|
|
689
|
+
// `standDown` keeps it to stderr.
|
|
690
|
+
said.didWork = true;
|
|
691
|
+
// THE NOTICE, AFTER THE WAKE AND ONLY AT SESSION START. Never on
|
|
692
|
+
// user-prompt-submit: the owner asked for a warning, not a nag. `notice()`
|
|
693
|
+
// is red-only, bounded, and returns null rather than throwing, so the line
|
|
694
|
+
// below cannot change what the wake does on a healthy day.
|
|
695
|
+
const notice = name === "session-start" ? adapter.notice(input) : null;
|
|
696
|
+
const delivery = hostDelivery(name, result, payload, notice);
|
|
697
|
+
// A notice the envelope could not carry leaves a row rather than nothing:
|
|
698
|
+
// "the terminal said nothing" and "there was nothing to say" are different
|
|
699
|
+
// facts about the same morning (scar §2.4).
|
|
700
|
+
if (delivery.dropped !== null) adapter.noteNoticeDropped(delivery.dropped);
|
|
701
|
+
if (delivery.stdout.length > 0) {
|
|
702
|
+
process.stdout.write(delivery.stdout);
|
|
703
|
+
// Recorded, not inferred: a fault thrown after this point (the close in
|
|
704
|
+
// the `finally` below is inside the same try) may not print a second
|
|
705
|
+
// object, or the wake stops being JSON and lands in the model's context.
|
|
706
|
+
said.wroteStdout = true;
|
|
707
|
+
}
|
|
708
|
+
if (delivery.stderr.length > 0) process.stderr.write(delivery.stderr);
|
|
709
|
+
process.exitCode = delivery.exitCode;
|
|
710
|
+
} finally {
|
|
711
|
+
adapter.counterpart.close();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* How each hook's output reaches the model on THIS host — measured, not
|
|
717
|
+
* assumed (scar §2.18), on day 0 of the parallel run (2026-09-03):
|
|
718
|
+
*
|
|
719
|
+
* - SessionStart / UserPromptSubmit: plain stdout with exit 0 is added to the
|
|
720
|
+
* model's context. The wake (8,859 B) arrived that way.
|
|
721
|
+
* - Stop: plain stdout with exit 0 reaches NOBODY. An ask written that way
|
|
722
|
+
* was recorded (`adapter.episode.ask asked:true`) and never seen. The one
|
|
723
|
+
* channel proven on this host is the blocking one bansai has used all along:
|
|
724
|
+
* the text on STDERR and exit code 2, which the host feeds back to the model
|
|
725
|
+
* as "Stop hook feedback" and lets it continue. The host then re-fires Stop
|
|
726
|
+
* with `stop_hook_active: true`; that re-fire must ask NOTHING or the ask
|
|
727
|
+
* loops forever (v1's anti-loop, kept here for the same reason).
|
|
728
|
+
*
|
|
729
|
+
* **The fourth channel, added 2026-09-14 for I32: `systemMessage`.** Documented
|
|
730
|
+
* at https://code.claude.com/docs/en/hooks (formerly
|
|
731
|
+
* docs.claude.com/en/docs/claude-code/hooks) and measured by the owner's own
|
|
732
|
+
* probe on 2026-09-11: a SessionStart hook that exits 0 and prints JSON with a
|
|
733
|
+
* top-level `systemMessage` gets that text DISPLAYED in the terminal
|
|
734
|
+
* (`SessionStart:startup says: …`), non-blocking, while `additionalContext` and
|
|
735
|
+
* stderr do not show. The doc also states the rule that makes this safe or
|
|
736
|
+
* dangerous depending on which form you print: **when stdout parses as JSON the
|
|
737
|
+
* raw stdout is NOT also added to context** — only the JSON's fields are. So the
|
|
738
|
+
* wake must ride ENTIRELY in `hookSpecificOutput.additionalContext`, byte for
|
|
739
|
+
* byte what plain stdout would have carried, and a day with nothing red prints
|
|
740
|
+
* the plain form it has printed since day 0 rather than a JSON wrapper nobody
|
|
741
|
+
* has measured on this host.
|
|
742
|
+
*
|
|
743
|
+
* Pure, so the test proves the channel choice without a process. `dropped` is
|
|
744
|
+
* how a pure function reports the one thing it cannot do itself: the caller
|
|
745
|
+
* turns it into the ring row that makes a silent terminal explicable.
|
|
746
|
+
*/
|
|
747
|
+
export interface Delivery {
|
|
748
|
+
readonly stdout: string;
|
|
749
|
+
readonly stderr: string;
|
|
750
|
+
readonly exitCode: 0 | 2;
|
|
751
|
+
/** Non-null when the notice was dropped to keep the wake whole. */
|
|
752
|
+
readonly dropped: { readonly noticeChars: number; readonly envelopeChars: number; readonly limitChars: number } | null;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export function hostDelivery(
|
|
756
|
+
name: HookName,
|
|
757
|
+
result: { injection: string | null; ask: string | null },
|
|
758
|
+
payload: Record<string, unknown>,
|
|
759
|
+
/** The owner-facing warning, or null. Only SessionStart carries one. */
|
|
760
|
+
notice: string | null = null,
|
|
761
|
+
): Delivery {
|
|
762
|
+
const ask = result.ask !== null && result.ask.length > 0 ? result.ask : null;
|
|
763
|
+
if (name !== "stop") {
|
|
764
|
+
const out = [result.injection ?? "", ask ?? ""].filter((s) => s.length > 0).join("\n\n");
|
|
765
|
+
if (name === "session-start" && notice !== null && notice.length > 0) {
|
|
766
|
+
const envelope = JSON.stringify({
|
|
767
|
+
systemMessage: notice,
|
|
768
|
+
hookSpecificOutput: { hookEventName: HOST_SESSION_START, additionalContext: out },
|
|
769
|
+
});
|
|
770
|
+
// THE WAKE WINS. Over `ENVELOPE_MAX_CHARS` the host would replace this
|
|
771
|
+
// whole string with a preview, the JSON would stop parsing, and the
|
|
772
|
+
// session would start with no memory at all — a worse outcome than not
|
|
773
|
+
// seeing the warning, which `counterparts doctor` prints on request.
|
|
774
|
+
if (envelope.length > ENVELOPE_MAX_CHARS) {
|
|
775
|
+
return {
|
|
776
|
+
stdout: out,
|
|
777
|
+
stderr: "",
|
|
778
|
+
exitCode: 0,
|
|
779
|
+
dropped: { noticeChars: notice.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS },
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
return { stdout: envelope, stderr: "", exitCode: 0, dropped: null };
|
|
783
|
+
}
|
|
784
|
+
return { stdout: out, stderr: "", exitCode: 0, dropped: null };
|
|
785
|
+
}
|
|
786
|
+
// The re-fire is refused twice on purpose: the adapter asks nothing on it, and
|
|
787
|
+
// this channel would not carry it even if something did.
|
|
788
|
+
if (payload["stop_hook_active"] === true || ask === null) {
|
|
789
|
+
return { stdout: "", stderr: "", exitCode: 0, dropped: null };
|
|
790
|
+
}
|
|
791
|
+
return { stdout: "", stderr: ask, exitCode: 2, dropped: null };
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** True only when this file is the process entry point — so a test may import
|
|
795
|
+
* `toHookInput` and `hostConfig` without the script running itself. */
|
|
796
|
+
export function isEntryPoint(argv1: string | undefined, url: string): boolean {
|
|
797
|
+
if (argv1 === undefined) return false;
|
|
798
|
+
return resolve(argv1) === fileURLToPath(new URL(url));
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
if (isEntryPoint(process.argv[1], import.meta.url)) {
|
|
802
|
+
void main().then(
|
|
803
|
+
() => process.exit(process.exitCode === 2 ? 2 : 0),
|
|
804
|
+
(err: unknown) => {
|
|
805
|
+
// A failed hook is a QUIET hook, never a failed session — but a
|
|
806
|
+
// stand-down stays observable (observer-mode G6). One line names it:
|
|
807
|
+
// e.g. an observer stance finding no store to read (cli §7) says
|
|
808
|
+
// STORE_UNINITIALIZED here instead of minting one silently.
|
|
809
|
+
//
|
|
810
|
+
// The explicit-dir guard gets a SENTENCE with THIS entry point's remedy:
|
|
811
|
+
// a hook has no `--dir`, so the way to name its store is the `dataDir`
|
|
812
|
+
// field of the file it was pointed at (the gap between the two guards —
|
|
813
|
+
// a named configuration that names no store; #80 review).
|
|
814
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
815
|
+
const remedy = `Set "dataDir" in ${hookConfigChoice().path}, or set ${DATA_DIR_ENV}.`;
|
|
816
|
+
process.stderr.write(`[counterparts] hook stood down: ${describeGuardRefusal(err, remedy) ?? detail}\n`);
|
|
817
|
+
process.exit(0);
|
|
818
|
+
},
|
|
819
|
+
);
|
|
820
|
+
}
|