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,661 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading this host's transcript file — pure host trivia (CONTRACT §5 G9), and
|
|
3
|
+
* the one place that knows what a Claude Code transcript line looks like.
|
|
4
|
+
*
|
|
5
|
+
* Two rules from the spec govern what comes out of here, and both are decided at
|
|
6
|
+
* THIS line rather than downstream:
|
|
7
|
+
*
|
|
8
|
+
* **§2 G10 — conversational text only.** Tool output, file contents and images
|
|
9
|
+
* never enter capture. That is a DECLARED blind spot, not an oversight, so a
|
|
10
|
+
* block this reader cannot classify as conversation is tagged with what it
|
|
11
|
+
* actually is (`tool`, `file`, `image`) and `remember/`'s `enters()` drops it.
|
|
12
|
+
* **§2 G11 — injected context is kept in capture and excluded from pacing.**
|
|
13
|
+
* Host-injected material is user-role but is not the user speaking, so it is
|
|
14
|
+
* tagged `injected` rather than discarded: `enters()` keeps it, `substanceOf`
|
|
15
|
+
* does not count it.
|
|
16
|
+
*
|
|
17
|
+
* And three more this host's shapes force:
|
|
18
|
+
*
|
|
19
|
+
* **G8 — foreign injection never enters.** While v2 runs beside v1, v1's own
|
|
20
|
+
* hooks put text into this same transcript: a wake bundle, a recall block, a
|
|
21
|
+
* Stop-hook ask. It arrives user-role and reads like conversation, and if it
|
|
22
|
+
* entered capture v2 would encode v1's briefing as a memory of having thought
|
|
23
|
+
* it — a feedback loop between two memory systems, which is worse than either
|
|
24
|
+
* system's ordinary failure. So it is tagged `foreign` and `enters()` refuses
|
|
25
|
+
* it outright. The recognizers are ONE constant, `FOREIGN_MARKERS`, so the
|
|
26
|
+
* parallel-run preflight's transcript canary scans for exactly what the
|
|
27
|
+
* reader excludes rather than for its own copy of the list.
|
|
28
|
+
*
|
|
29
|
+
* **PEER MESSAGES ARE KEPT, BUT NEVER AS THE OWNER'S WORDS.** This host
|
|
30
|
+
* delivers messages from the owner's OTHER Claude Code sessions into this
|
|
31
|
+
* transcript as user-role text wrapped in `<cross-session-message …>`
|
|
32
|
+
* (documented at code.claude.com/docs/en/cross-session-messaging; attributes
|
|
33
|
+
* read off the v2.1.260 bundle: `from`, `from-name`, `from-session`,
|
|
34
|
+
* `from-mode`, `hop-chain`). Measured 2026-09-04: capture read those as the
|
|
35
|
+
* owner speaking and the fallback sweep minted another instance's findings —
|
|
36
|
+
* "v2 challenge effect has no live consumer" — as things the owner said. The
|
|
37
|
+
* content IS real experience and is kept; the WRAPPER is replaced in place
|
|
38
|
+
* with a short structural label the interpreter can read, and a block that is
|
|
39
|
+
* nothing but a peer message is tagged `injected` so it never paces a ritual.
|
|
40
|
+
* The rewrite is in place, one block still one turn, because the per-session
|
|
41
|
+
* cursor indexes into this turn list: splitting a block into several turns
|
|
42
|
+
* would re-slice a live session's uncaptured tail.
|
|
43
|
+
*
|
|
44
|
+
* **CONTRACT §5 G11 — this system's own asks never enter.** (Not the
|
|
45
|
+
* behavioral spec's §2 G11 three paragraphs up: that one is about injected
|
|
46
|
+
* context, this one is about our own voice.) The host returns a blocking
|
|
47
|
+
* Stop hook's stderr to the model as user-role `Stop hook feedback:` text, so
|
|
48
|
+
* v2's authorship and episode asks arrive back in its own transcript looking
|
|
49
|
+
* like something the owner said. Earlier this reader left that block
|
|
50
|
+
* `conversation`, reasoning that excluding the wrapper would "blind this
|
|
51
|
+
* reader to its own voice." That reasoning is SUPERSEDED: the ask's durable
|
|
52
|
+
* record is `adapter.authorship.ask`, not the transcript copy, and what the
|
|
53
|
+
* transcript copy actually buys is v2 encoding its own ritual wording as
|
|
54
|
+
* lived experience. It is tagged `ritual`, `enters()` refuses it, and the
|
|
55
|
+
* refusal lands in the boundary record's `excluded` count so the silence is
|
|
56
|
+
* visible. A `Stop hook feedback:` block carrying a v1 marker is still
|
|
57
|
+
* `foreign` — foreign is checked first, so the canary's agreement holds.
|
|
58
|
+
*
|
|
59
|
+
* Nothing here throws. A transcript we cannot read yields no turns, which costs
|
|
60
|
+
* a boundary's capture; a transcript that throws would cost the session.
|
|
61
|
+
*
|
|
62
|
+
* The file also holds the WAKE-ARRIVAL READER (bottom of this file), which reads
|
|
63
|
+
* the same transcript for a different question and keeps its own, bounded, pass:
|
|
64
|
+
* capture wants conversation and skips attachments, delivery wants exactly the
|
|
65
|
+
* attachment and skips conversation.
|
|
66
|
+
*/
|
|
67
|
+
import {
|
|
68
|
+
closeSync,
|
|
69
|
+
constants as FS,
|
|
70
|
+
existsSync,
|
|
71
|
+
fstatSync,
|
|
72
|
+
openSync,
|
|
73
|
+
readFileSync,
|
|
74
|
+
readSync,
|
|
75
|
+
statSync,
|
|
76
|
+
} from "node:fs";
|
|
77
|
+
|
|
78
|
+
import type { Turn, TurnSource } from "../../core/remember/index.js";
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The marker the host wraps around context it injected itself.
|
|
82
|
+
*
|
|
83
|
+
* `cross-session-*` is the conservative catch-all: `<cross-session-message>` is
|
|
84
|
+
* the ONE peer shape evidenced (docs + bundle), and it gets the attribution
|
|
85
|
+
* rewrite below, but any other wrapper the host may add under that prefix is at
|
|
86
|
+
* minimum host-delivered rather than owner-spoken, and `injected` is the honest
|
|
87
|
+
* reading of a shape we have not measured — kept in capture, out of pacing.
|
|
88
|
+
*/
|
|
89
|
+
const INJECTED =
|
|
90
|
+
/<(system-reminder|command-name|command-message|local-command-stdout|cross-session-[a-z-]+)\b/i;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The host's blocking-Stop channel, which returns a hook's own stderr to the
|
|
94
|
+
* model as user-role text. Anchored: a block that merely MENTIONS the phrase
|
|
95
|
+
* mid-sentence is conversation about the mechanism, not the mechanism.
|
|
96
|
+
*/
|
|
97
|
+
const STOP_HOOK_FEEDBACK = /^Stop hook feedback:/;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The peer-message wrapper this host uses for messages from the owner's other
|
|
101
|
+
* Claude Code sessions. Non-greedy body, `[\s\S]` so a multi-line message is one
|
|
102
|
+
* match, and the closing tag is required — a truncated wrapper is left alone and
|
|
103
|
+
* classified like any other text rather than swallowing the rest of the block.
|
|
104
|
+
*/
|
|
105
|
+
const CROSS_SESSION_MESSAGE = /<cross-session-message\b([^>]*)>([\s\S]*?)<\/cross-session-message>/gi;
|
|
106
|
+
|
|
107
|
+
/** The host's idle/exit notice, which is plain text rather than a wrapper
|
|
108
|
+
* (evidenced in the v2.1.260 bundle: `[Cross-session idle notice] "x" is idle
|
|
109
|
+
* now` / `… has exited`). Host bookkeeping about a peer, never the owner. */
|
|
110
|
+
const CROSS_SESSION_NOTICE = /^\[Cross-session idle notice\]/;
|
|
111
|
+
|
|
112
|
+
/** What a peer-attribution pass did to one block. */
|
|
113
|
+
export interface PeerAttribution {
|
|
114
|
+
/** The block with every wrapper replaced by a labelled, unwrapped quotation. */
|
|
115
|
+
readonly text: string;
|
|
116
|
+
/** How many wrappers were rewritten. Zero means the text is untouched. */
|
|
117
|
+
readonly peers: number;
|
|
118
|
+
/** True when the block also carried text of the owner's own outside a wrapper. */
|
|
119
|
+
readonly ownerText: boolean;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The attribute value, or undefined. Attributes are single- or double-quoted. */
|
|
123
|
+
function attr(attrs: string, name: string): string | undefined {
|
|
124
|
+
const found = new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i").exec(attrs);
|
|
125
|
+
const value = found?.[2] ?? found?.[3];
|
|
126
|
+
return value !== undefined && value.trim().length > 0 ? value.trim() : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Replace every peer wrapper with a structural label naming the speaker, IN
|
|
131
|
+
* PLACE. The label is prose the interpreter reads, not a field, because a span
|
|
132
|
+
* is text: several turns are joined into one span, so anything that must survive
|
|
133
|
+
* to interpretation has to be in the words.
|
|
134
|
+
*
|
|
135
|
+
* The name preferred is the host's `from-name` (a session's display name, the
|
|
136
|
+
* thing a human would recognize), then `from-session` — and "unnamed" when the
|
|
137
|
+
* host gave neither, since an unattributed peer message must still not read as
|
|
138
|
+
* the owner. The `from` attribute is DELIBERATELY NOT a fallback: it is a local
|
|
139
|
+
* socket path (`uds:/tmp/cc-socks/30478.sock`), and a machine-local path has no
|
|
140
|
+
* business in memory prose that outlives the socket by years.
|
|
141
|
+
*/
|
|
142
|
+
export function attributePeers(text: string): PeerAttribution {
|
|
143
|
+
CROSS_SESSION_MESSAGE.lastIndex = 0;
|
|
144
|
+
if (!CROSS_SESSION_MESSAGE.test(text)) {
|
|
145
|
+
return { text, peers: 0, ownerText: text.trim().length > 0 };
|
|
146
|
+
}
|
|
147
|
+
let peers = 0;
|
|
148
|
+
let cursor = 0;
|
|
149
|
+
const outside: string[] = [];
|
|
150
|
+
const parts: string[] = [];
|
|
151
|
+
CROSS_SESSION_MESSAGE.lastIndex = 0;
|
|
152
|
+
let match: RegExpExecArray | null;
|
|
153
|
+
while ((match = CROSS_SESSION_MESSAGE.exec(text)) !== null) {
|
|
154
|
+
peers += 1;
|
|
155
|
+
const before = text.slice(cursor, match.index);
|
|
156
|
+
outside.push(before);
|
|
157
|
+
parts.push(before);
|
|
158
|
+
const attrs = match[1] ?? "";
|
|
159
|
+
const who = attr(attrs, "from-name") ?? attr(attrs, "from-session") ?? "unnamed";
|
|
160
|
+
parts.push(`[message from another Claude session, ${who}]: ${(match[2] ?? "").trim()}`);
|
|
161
|
+
cursor = match.index + match[0].length;
|
|
162
|
+
}
|
|
163
|
+
const tail = text.slice(cursor);
|
|
164
|
+
outside.push(tail);
|
|
165
|
+
parts.push(tail);
|
|
166
|
+
return { text: parts.join("").trim(), peers, ownerText: outside.join("").trim().length > 0 };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Every shape v1 (bansai) puts into this host's transcript. ONE list, exported,
|
|
171
|
+
* because the preflight canary and this reader must not be able to disagree
|
|
172
|
+
* about what foreign material looks like.
|
|
173
|
+
*
|
|
174
|
+
* The first entry is the host's blocking-Stop-hook wrapper, which arrives as
|
|
175
|
+
* `Stop hook feedback:` followed by the hook's own line (the host may bullet
|
|
176
|
+
* it). A `Stop hook feedback:` block that does NOT carry a foreign marker is
|
|
177
|
+
* v2's OWN ask coming home through the same channel, and is `ritual` — refused
|
|
178
|
+
* for its own reason rather than being counted against v1. The two must stay
|
|
179
|
+
* distinct: `FOREIGN_MARKERS` is what the preflight canary scans for, and a list
|
|
180
|
+
* that swallowed v2's own asks would report v1 injection that never happened.
|
|
181
|
+
*/
|
|
182
|
+
export const FOREIGN_MARKERS: readonly RegExp[] = [
|
|
183
|
+
/^Stop hook feedback:\s*(?:[-*]\s*)?\[bansai\]/,
|
|
184
|
+
/^\[bansai\] /,
|
|
185
|
+
/<bansai-memory>/,
|
|
186
|
+
/^The following is your standing self-model \(bansai\)/,
|
|
187
|
+
/^bansai: your persistent memory is initializing/,
|
|
188
|
+
];
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The whole classification rule for one text block, as one pure function.
|
|
192
|
+
*
|
|
193
|
+
* The ORDER is the rule. Foreign first: a v1 wake bundle wrapped in a host
|
|
194
|
+
* reminder is foreign, not injected, and v1's `Stop hook feedback: [bansai] …`
|
|
195
|
+
* is foreign rather than ritual — which is what keeps the preflight canary and
|
|
196
|
+
* this reader agreeing about `FOREIGN_MARKERS`. Ritual second: what is left in
|
|
197
|
+
* that wrapper is v2's own ask coming home. Injected third, conversation last.
|
|
198
|
+
*/
|
|
199
|
+
export function classifyBlock(text: string): TurnSource {
|
|
200
|
+
const probe = text.trimStart();
|
|
201
|
+
for (const marker of FOREIGN_MARKERS) {
|
|
202
|
+
if (marker.test(probe)) return "foreign";
|
|
203
|
+
}
|
|
204
|
+
if (STOP_HOOK_FEEDBACK.test(probe)) return "ritual";
|
|
205
|
+
if (CROSS_SESSION_NOTICE.test(probe)) return "injected";
|
|
206
|
+
return INJECTED.test(text) ? "injected" : "conversation";
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* One deliberate-recall tool call, as evidence for reference resolution
|
|
211
|
+
* (recall CONTRACT §9.2). `atTurn` is the index of the NEXT conversational
|
|
212
|
+
* turn — the call sits between `turns[atTurn - 1]` and `turns[atTurn]` — so the
|
|
213
|
+
* boundary can slice expansions by the same cursor it slices turns with, and
|
|
214
|
+
* the turn list itself does not grow: a live session's cursor indexes into
|
|
215
|
+
* that list, and a tool call inserted as a turn would re-slice its uncaptured
|
|
216
|
+
* tail. `ids` are the raw `ids` / `handle` values from the call's input, not
|
|
217
|
+
* anything the assistant wrote in prose.
|
|
218
|
+
*/
|
|
219
|
+
export interface Expansion {
|
|
220
|
+
readonly atTurn: number;
|
|
221
|
+
readonly ids: readonly string[];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface TranscriptRead {
|
|
225
|
+
readonly turns: Turn[];
|
|
226
|
+
readonly ok: boolean;
|
|
227
|
+
readonly reason: "read" | "absent" | "unreadable";
|
|
228
|
+
/** Lines that were not JSON. Counted, never silently swallowed (scar §2.4). */
|
|
229
|
+
readonly corrupt: number;
|
|
230
|
+
/** Deliberate-recall calls, in order, positioned against `turns`. */
|
|
231
|
+
readonly expansions: Expansion[];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The recall tool as this host names it: the MCP prefix and server name are
|
|
236
|
+
* the host's, the tool name is ours. Anchored on the suffix so a renamed
|
|
237
|
+
* server still matches and `recall_bench` or `recall.decision` never do.
|
|
238
|
+
*/
|
|
239
|
+
export const RECALL_TOOL_NAME = /(^|__)recall$/;
|
|
240
|
+
|
|
241
|
+
/** The `ids` and `handle` fields of a recall call, as strings, in order. */
|
|
242
|
+
export function expansionIdsOf(input: unknown): string[] {
|
|
243
|
+
if (input === null || typeof input !== "object") return [];
|
|
244
|
+
const i = input as Record<string, unknown>;
|
|
245
|
+
const out: string[] = [];
|
|
246
|
+
if (typeof i["handle"] === "string") out.push(i["handle"]);
|
|
247
|
+
if (Array.isArray(i["ids"])) {
|
|
248
|
+
for (const id of i["ids"]) if (typeof id === "string") out.push(id);
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function readTranscript(path: string | undefined): TranscriptRead {
|
|
254
|
+
if (path === undefined || path.trim().length === 0) {
|
|
255
|
+
return { turns: [], ok: false, reason: "absent", corrupt: 0, expansions: [] };
|
|
256
|
+
}
|
|
257
|
+
if (!existsSync(path)) return { turns: [], ok: false, reason: "absent", corrupt: 0, expansions: [] };
|
|
258
|
+
let raw: string;
|
|
259
|
+
try {
|
|
260
|
+
raw = readFileSync(path, "utf8");
|
|
261
|
+
} catch {
|
|
262
|
+
return { turns: [], ok: false, reason: "unreadable", corrupt: 0, expansions: [] };
|
|
263
|
+
}
|
|
264
|
+
return parseTranscript(raw);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Exported so the parse is testable without a file (and it is the whole rule). */
|
|
268
|
+
export function parseTranscript(raw: string): TranscriptRead {
|
|
269
|
+
const turns: Turn[] = [];
|
|
270
|
+
const expansions: Expansion[] = [];
|
|
271
|
+
let corrupt = 0;
|
|
272
|
+
for (const line of raw.split("\n")) {
|
|
273
|
+
if (line.trim().length === 0) continue;
|
|
274
|
+
let entry: Record<string, unknown>;
|
|
275
|
+
try {
|
|
276
|
+
entry = JSON.parse(line) as Record<string, unknown>;
|
|
277
|
+
} catch {
|
|
278
|
+
corrupt += 1;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const message = entry["message"] as Record<string, unknown> | undefined;
|
|
282
|
+
const role = (message?.["role"] ?? entry["role"]) as unknown;
|
|
283
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
284
|
+
const content = message?.["content"] ?? entry["content"];
|
|
285
|
+
for (const piece of blocksOf(content, role)) {
|
|
286
|
+
// A recall call is the assistant's turn, kept as EVIDENCE beside the
|
|
287
|
+
// turn list rather than in it (see `Expansion`). Only the assistant
|
|
288
|
+
// calls tools; a user-role block never carries one.
|
|
289
|
+
if (piece.expansion !== undefined && role === "assistant" && piece.expansion.length > 0) {
|
|
290
|
+
expansions.push({ atTurn: turns.length, ids: piece.expansion });
|
|
291
|
+
}
|
|
292
|
+
if (piece.text.trim().length === 0) continue;
|
|
293
|
+
turns.push({ role, text: piece.text, source: piece.source });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { turns, ok: true, reason: "read", corrupt, expansions };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
type Piece = { text: string; source: TurnSource; expansion?: string[] };
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* One text block, classified and — where it carries peer messages — attributed.
|
|
303
|
+
*
|
|
304
|
+
* Peer rewriting applies to user-role text only, because that is the only role
|
|
305
|
+
* the host delivers a peer message in, and it never overrides `foreign` or
|
|
306
|
+
* `ritual`: those two are refusals, and a refused block is not made keepable by
|
|
307
|
+
* containing a quotation. A block that is ONLY a peer message becomes
|
|
308
|
+
* `injected` — kept in capture (it is real experience), out of pacing (nobody
|
|
309
|
+
* in this session spoke). A MIXED block stays `conversation`: the owner did
|
|
310
|
+
* speak in that turn, and the label separates the two voices inside it.
|
|
311
|
+
*/
|
|
312
|
+
function pieceOf(text: string, role: "user" | "assistant"): Piece {
|
|
313
|
+
const source = classifyBlock(text);
|
|
314
|
+
if (role !== "user" || source === "foreign" || source === "ritual") return { text, source };
|
|
315
|
+
const attributed = attributePeers(text);
|
|
316
|
+
if (attributed.peers === 0) return { text, source };
|
|
317
|
+
return { text: attributed.text, source: attributed.ownerText ? "conversation" : "injected" };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** One transcript entry's content, flattened into typed pieces. */
|
|
321
|
+
function blocksOf(content: unknown, role: "user" | "assistant"): Piece[] {
|
|
322
|
+
if (typeof content === "string") {
|
|
323
|
+
return [pieceOf(content, role)];
|
|
324
|
+
}
|
|
325
|
+
if (!Array.isArray(content)) return [];
|
|
326
|
+
const out: Piece[] = [];
|
|
327
|
+
for (const block of content) {
|
|
328
|
+
if (block === null || typeof block !== "object") continue;
|
|
329
|
+
const b = block as Record<string, unknown>;
|
|
330
|
+
const type = b["type"];
|
|
331
|
+
if (type === "text" && typeof b["text"] === "string") {
|
|
332
|
+
out.push(pieceOf(b["text"], role));
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
// Everything below is the DECLARED blind spot, tagged rather than dropped
|
|
336
|
+
// here so the drop happens at `remember/`'s one rule (`enters`).
|
|
337
|
+
if (type === "tool_use") {
|
|
338
|
+
const name = b["name"];
|
|
339
|
+
const expansion =
|
|
340
|
+
typeof name === "string" && RECALL_TOOL_NAME.test(name) ? expansionIdsOf(b["input"]) : undefined;
|
|
341
|
+
out.push({ text: "", source: "tool", ...(expansion === undefined ? {} : { expansion }) });
|
|
342
|
+
} else if (type === "tool_result") {
|
|
343
|
+
out.push({ text: "", source: "tool" });
|
|
344
|
+
} else if (type === "image") {
|
|
345
|
+
out.push({ text: "", source: "image" });
|
|
346
|
+
} else if (type === "document") {
|
|
347
|
+
out.push({ text: "", source: "file" });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// ── the wake's arrival ──────────────────────────────────────────────────────
|
|
354
|
+
//
|
|
355
|
+
// A SECOND, DELIBERATELY SEPARATE PASS over the same file, for the one question
|
|
356
|
+
// `parseTranscript` refuses to answer: did the wake this system printed at
|
|
357
|
+
// SessionStart actually reach the session's context?
|
|
358
|
+
//
|
|
359
|
+
// `parseTranscript` skips attachment entries because injected context is not
|
|
360
|
+
// conversation, and that stays exactly as it is. The check below wants the
|
|
361
|
+
// opposite half of the file: the host records a SessionStart hook's output as an
|
|
362
|
+
// entry of its own (`type: "attachment"`, `attachment.type: "hook_success"`),
|
|
363
|
+
// carrying what the hook PRINTED (`stdout`) beside what the host says it
|
|
364
|
+
// INJECTED (`content`). Measured 2026-09-17 on Claude Code 2.1.274: that entry
|
|
365
|
+
// is line 3 of a fresh session's file, before the first user message, and both
|
|
366
|
+
// wake sentinels stand inside it.
|
|
367
|
+
//
|
|
368
|
+
// Several hooks run on the same event and each leaves its own attachment, so the
|
|
369
|
+
// match is on the command line, not on the event name alone.
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* **CAL.** How much of the file's head this reader will look at, and why the
|
|
373
|
+
* numbers are 256 KiB and 40 lines.
|
|
374
|
+
*
|
|
375
|
+
* The attachment arrives before the first user message — line 3 in the measured
|
|
376
|
+
* case — so the answer is always in the first handful of entries, while the file
|
|
377
|
+
* itself grows to megabytes over a long session. Both bounds are belt and
|
|
378
|
+
* braces: the byte bound caps what is read off disk and parsed no matter how
|
|
379
|
+
* long one line is, the line bound caps the work when the lines are short. A
|
|
380
|
+
* wake is ~9 KB and appears twice in the attachment (printed and injected), so
|
|
381
|
+
* 256 KiB leaves room for that entry plus every other hook's on the same event.
|
|
382
|
+
*
|
|
383
|
+
* A file bigger than the bound is READ SHORT, never wholly; the last line of a
|
|
384
|
+
* short read is dropped, because it is cut mid-JSON by construction.
|
|
385
|
+
*/
|
|
386
|
+
export const WAKE_HEAD_MAX_BYTES = 256 * 1024;
|
|
387
|
+
export const WAKE_HEAD_MAX_LINES = 40;
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* THIS PACKAGE'S HOOK, as it appears in the host's record of the command it ran.
|
|
391
|
+
* Other hooks on the same event leave their own attachments; without this every
|
|
392
|
+
* SessionStart hook on the machine would answer for the wake.
|
|
393
|
+
*
|
|
394
|
+
* Two spellings, because there are two ways this package is wired: the source
|
|
395
|
+
* path (what the owner's host runs, and what the 2026-09-17 measurement read off
|
|
396
|
+
* a live transcript) and the `counterparts-hook` bin `package.json` installs. A
|
|
397
|
+
* THIRD is possible and unmeasured — a compiled binary under some other name —
|
|
398
|
+
* and the cost of missing it is a session that reads `not-found`, which is
|
|
399
|
+
* INTERFACE-GAPS §11's residual.
|
|
400
|
+
*/
|
|
401
|
+
export const COUNTERPARTS_HOOK_COMMAND = /claude-code[/\\]bin[/\\]hook\.ts|counterparts-hook/;
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* The wake's two sentinels, recognised INSIDE a larger string rather than as a
|
|
405
|
+
* whole line: what the host recorded may be the injected block (the wake plus
|
|
406
|
+
* the first-launch question) or, on a day that carried a notice, the JSON
|
|
407
|
+
* envelope the hook printed. The sentinel survives JSON escaping unchanged — it
|
|
408
|
+
* holds no quote, backslash or newline — so one substring search answers both
|
|
409
|
+
* forms. `[^>]*` cannot run past the comment's own close.
|
|
410
|
+
*
|
|
411
|
+
* They are a SECOND spelling of `self/briefing.ts`'s `OPEN_RE`/`SENTINEL_RE`,
|
|
412
|
+
* which are not exported and live in the core this adapter may not reach into. A
|
|
413
|
+
* core that exported them is the ask INTERFACE-GAPS §11 records; until then the anchors
|
|
414
|
+
* are written so that a match is the sentinel string byte for byte.
|
|
415
|
+
*/
|
|
416
|
+
const WAKE_HEAD_PREFIX = "<!-- counterparts:wake ";
|
|
417
|
+
const WAKE_TAIL_PREFIX = "<!-- counterparts:wake/end ";
|
|
418
|
+
const WAKE_HEAD_SENTINEL = /^<!-- counterparts:wake [^>\n]*elements=(\d+) bytes=(\d+) -->/;
|
|
419
|
+
const WAKE_TAIL_SENTINEL = /^<!-- counterparts:wake\/end [^>\n]*elements=(\d+) bytes=(\d+) -->/;
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* **CAL.** The longest a sentinel may be. It is one line of `day=`, one `lane=`
|
|
423
|
+
* per lane, `elements=` and `bytes=` — about 120 bytes on this store's widest
|
|
424
|
+
* day, and the cap is what keeps the search LINEAR: the anchored regex above
|
|
425
|
+
* only ever runs against a slice this long, so no amount of poisoned memory text
|
|
426
|
+
* can make it backtrack across the transcript.
|
|
427
|
+
*/
|
|
428
|
+
const SENTINEL_MAX_BYTES = 400;
|
|
429
|
+
|
|
430
|
+
/** What one sentinel said, or that it was not there. Numbers and flags only. */
|
|
431
|
+
export interface SentinelSighting {
|
|
432
|
+
readonly present: boolean;
|
|
433
|
+
readonly elements: number | null;
|
|
434
|
+
readonly bytes: number | null;
|
|
435
|
+
/**
|
|
436
|
+
* True when the sentinel is the one the session was told to expect, byte for
|
|
437
|
+
* byte. The comparison happens HERE so the matched text never leaves this
|
|
438
|
+
* function: a sentinel is found inside a bundle of memories, and the text
|
|
439
|
+
* around it is the owner's.
|
|
440
|
+
*/
|
|
441
|
+
readonly matchesExpected: boolean;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const ABSENT: SentinelSighting = {
|
|
445
|
+
present: false,
|
|
446
|
+
elements: null,
|
|
447
|
+
bytes: null,
|
|
448
|
+
matchesExpected: false,
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Find one sentinel and report what it said. Linear in the length of `text`.
|
|
453
|
+
*
|
|
454
|
+
* **The search is `indexOf`, not the regex.** The regexes above used to be run
|
|
455
|
+
* against the whole attachment with a leading `[^>]*`, which backtracks
|
|
456
|
+
* quadratically: an adversarial body holding thousands of "<!-- counterparts:wake"
|
|
457
|
+
* prefixes with no `>` between them measured 680 ms at 200 KB, four times per
|
|
458
|
+
* attachment, inside `UserPromptSubmit`. So the literal prefix is located with
|
|
459
|
+
* `indexOf`, a single line of at most `SENTINEL_MAX_BYTES` is cut from there,
|
|
460
|
+
* and the anchored regex runs on that slice alone. Every prefix is tried, in
|
|
461
|
+
* order — capping the attempts would let a poisoned body hide the real sentinel
|
|
462
|
+
* behind a few hundred fakes.
|
|
463
|
+
*
|
|
464
|
+
* **A match that IS the expectation wins over an earlier one that is not**, for
|
|
465
|
+
* the same reason: a memory whose body opens a sentinel it never closes would
|
|
466
|
+
* otherwise stand in front of the real one and turn a delivered wake into a
|
|
467
|
+
* `mismatch`. The first match is the answer only when nothing matches exactly.
|
|
468
|
+
*
|
|
469
|
+
* **The line is not sought, only the window** (2026-09-20, finding 7). This
|
|
470
|
+
* loop used to cut its slice at `text.indexOf("\n", from)`, and `indexOf` costs
|
|
471
|
+
* the distance it travels: a body of unterminated prefixes puts the next
|
|
472
|
+
* newline at the far end for every one of them, so the search was quadratic
|
|
473
|
+
* after all — 1.4 ms at 1,000 prefixes, 109 ms at 16,000, nearly four times the
|
|
474
|
+
* cost for twice the input. The anchored regexes exclude `\n` themselves, so
|
|
475
|
+
* cutting at `SENTINEL_MAX_BYTES` alone yields the identical match and makes
|
|
476
|
+
* every iteration cost the same bounded amount. The test that claimed this
|
|
477
|
+
* property was asserting a wall clock and never measured the growth.
|
|
478
|
+
*/
|
|
479
|
+
function sight(prefix: string, re: RegExp, text: string, expected: string | null): SentinelSighting {
|
|
480
|
+
let first: SentinelSighting | null = null;
|
|
481
|
+
let from = text.indexOf(prefix);
|
|
482
|
+
while (from !== -1) {
|
|
483
|
+
const end = Math.min(text.length, from + SENTINEL_MAX_BYTES);
|
|
484
|
+
const m = re.exec(text.slice(from, end));
|
|
485
|
+
if (m !== null) {
|
|
486
|
+
const matchesExpected = expected !== null && m[0] === expected;
|
|
487
|
+
const seen: SentinelSighting = {
|
|
488
|
+
present: true,
|
|
489
|
+
elements: Number(m[1]),
|
|
490
|
+
bytes: Number(m[2]),
|
|
491
|
+
matchesExpected,
|
|
492
|
+
};
|
|
493
|
+
if (matchesExpected) return seen;
|
|
494
|
+
if (first === null) first = seen;
|
|
495
|
+
}
|
|
496
|
+
from = text.indexOf(prefix, from + 1);
|
|
497
|
+
}
|
|
498
|
+
return first ?? ABSENT;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* What the head of one transcript says about the wake's arrival. Counts, flags
|
|
503
|
+
* and the sentinel lines — never a byte of the bundle itself.
|
|
504
|
+
*/
|
|
505
|
+
export interface WakeArrival {
|
|
506
|
+
/** `not-read` when nobody asked for a read (no expectation to test). */
|
|
507
|
+
readonly reason: "read" | "absent" | "unreadable" | "not-read";
|
|
508
|
+
/** True when THIS package's SessionStart attachment was found in the head. */
|
|
509
|
+
readonly found: boolean;
|
|
510
|
+
/** The sentinels as they stand in what the host says it INJECTED. */
|
|
511
|
+
readonly head: SentinelSighting;
|
|
512
|
+
readonly tail: SentinelSighting;
|
|
513
|
+
/** The same two in what the hook PRINTED — the truncation test needs both. */
|
|
514
|
+
readonly headPrinted: SentinelSighting;
|
|
515
|
+
readonly tailPrinted: SentinelSighting;
|
|
516
|
+
/**
|
|
517
|
+
* TRUE when the attachment carried a `content` string at all.
|
|
518
|
+
*
|
|
519
|
+
* `content` is a field of the host's private transcript format, measured once
|
|
520
|
+
* on Claude Code 2.1.274; it is not a contract. A build that renames it, drops
|
|
521
|
+
* it or sets it null leaves nothing to judge delivery from, and reading that
|
|
522
|
+
* absence as an empty injection would make every session report the one word
|
|
523
|
+
* that means v1's eleven-day silent-loss bug is back. An empty string that is
|
|
524
|
+
* PRESENT is a different fact, and this flag keeps them apart.
|
|
525
|
+
*/
|
|
526
|
+
readonly contentRecorded: boolean;
|
|
527
|
+
/** Measured lengths of the two strings, in bytes, for the declared numbers. */
|
|
528
|
+
readonly contentBytes: number;
|
|
529
|
+
readonly stdoutBytes: number;
|
|
530
|
+
readonly linesRead: number;
|
|
531
|
+
readonly bytesRead: number;
|
|
532
|
+
/** Lines in the head that were not JSON. Counted, never silently swallowed. */
|
|
533
|
+
readonly corrupt: number;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export const NO_ARRIVAL: WakeArrival = {
|
|
537
|
+
reason: "not-read",
|
|
538
|
+
found: false,
|
|
539
|
+
head: ABSENT,
|
|
540
|
+
tail: ABSENT,
|
|
541
|
+
headPrinted: ABSENT,
|
|
542
|
+
tailPrinted: ABSENT,
|
|
543
|
+
contentRecorded: false,
|
|
544
|
+
contentBytes: 0,
|
|
545
|
+
stdoutBytes: 0,
|
|
546
|
+
linesRead: 0,
|
|
547
|
+
bytesRead: 0,
|
|
548
|
+
corrupt: 0,
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Read at most `WAKE_HEAD_MAX_BYTES` from the front of a file. One open, one
|
|
553
|
+
* read, one close, and null on any failure at all — this runs on the prompt
|
|
554
|
+
* path, where a throw would cost the turn its recall.
|
|
555
|
+
*
|
|
556
|
+
* **Regular files only, checked three ways.** The path arrives in the host's
|
|
557
|
+
* payload, and `openSync` on a FIFO BLOCKS until somebody opens the other end —
|
|
558
|
+
* which would hang `UserPromptSubmit` until the host's own hook timeout. So the
|
|
559
|
+
* path is `stat`ed first (following symlinks, so a link to a FIFO is caught),
|
|
560
|
+
* opened with `O_NONBLOCK` so even a FIFO that appeared in between returns
|
|
561
|
+
* immediately, and `fstat`ed on the descriptor actually opened, which is the one
|
|
562
|
+
* check no rename can race.
|
|
563
|
+
*/
|
|
564
|
+
function readHead(path: string, maxBytes: number): { text: string; bytes: number } | null {
|
|
565
|
+
let fd: number | undefined;
|
|
566
|
+
try {
|
|
567
|
+
if (!statSync(path).isFile()) return null;
|
|
568
|
+
fd = openSync(path, FS.O_RDONLY | FS.O_NONBLOCK);
|
|
569
|
+
if (!fstatSync(fd).isFile()) return null;
|
|
570
|
+
const buf = Buffer.allocUnsafe(maxBytes);
|
|
571
|
+
const read = readSync(fd, buf, 0, maxBytes, 0);
|
|
572
|
+
// `bytes` is what came off the disk; `text.length` is characters, and the
|
|
573
|
+
// two differ on any file with a multi-byte character in its head.
|
|
574
|
+
return { text: buf.toString("utf8", 0, read), bytes: read };
|
|
575
|
+
} catch {
|
|
576
|
+
return null;
|
|
577
|
+
} finally {
|
|
578
|
+
if (fd !== undefined) {
|
|
579
|
+
try {
|
|
580
|
+
closeSync(fd);
|
|
581
|
+
} catch {
|
|
582
|
+
/* a descriptor we cannot close is not a reason to fail a hook */
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Find this package's SessionStart attachment in the head of a transcript and
|
|
590
|
+
* report what its two sentinels say.
|
|
591
|
+
*
|
|
592
|
+
* Nothing here throws, for the same reason nothing else in this file does: the
|
|
593
|
+
* caller is a hook, and a hook may not fail the host (CONTRACT §5 G2).
|
|
594
|
+
*/
|
|
595
|
+
export function readWakeArrival(
|
|
596
|
+
path: string | undefined,
|
|
597
|
+
opts: {
|
|
598
|
+
readonly maxBytes?: number;
|
|
599
|
+
readonly maxLines?: number;
|
|
600
|
+
/** Overridable so a test can name a different hook's command. */
|
|
601
|
+
readonly command?: RegExp;
|
|
602
|
+
/**
|
|
603
|
+
* The tail sentinel this session was told to expect. It is compared inside
|
|
604
|
+
* `sight()` and the comparison's ANSWER comes back; the matched text does
|
|
605
|
+
* not, so no byte of the bundle can reach a caller (review MINOR 2).
|
|
606
|
+
*/
|
|
607
|
+
readonly expect?: string | null;
|
|
608
|
+
} = {},
|
|
609
|
+
): WakeArrival {
|
|
610
|
+
if (path === undefined || path.trim().length === 0) return { ...NO_ARRIVAL, reason: "absent" };
|
|
611
|
+
if (!existsSync(path)) return { ...NO_ARRIVAL, reason: "absent" };
|
|
612
|
+
const maxBytes = opts.maxBytes ?? WAKE_HEAD_MAX_BYTES;
|
|
613
|
+
const maxLines = opts.maxLines ?? WAKE_HEAD_MAX_LINES;
|
|
614
|
+
const command = opts.command ?? COUNTERPARTS_HOOK_COMMAND;
|
|
615
|
+
const head = readHead(path, maxBytes);
|
|
616
|
+
if (head === null) return { ...NO_ARRIVAL, reason: "unreadable" };
|
|
617
|
+
// A read that filled the buffer was almost certainly cut mid-line, and half a
|
|
618
|
+
// line is not JSON. Dropping the last one costs nothing: the answer sits in
|
|
619
|
+
// the first few entries or it is not in the head at all.
|
|
620
|
+
const lines = head.text.split("\n");
|
|
621
|
+
if (head.bytes >= maxBytes && lines.length > 1) lines.pop();
|
|
622
|
+
let corrupt = 0;
|
|
623
|
+
let linesRead = 0;
|
|
624
|
+
for (const line of lines) {
|
|
625
|
+
if (linesRead >= maxLines) break;
|
|
626
|
+
if (line.trim().length === 0) continue;
|
|
627
|
+
linesRead += 1;
|
|
628
|
+
let entry: Record<string, unknown>;
|
|
629
|
+
try {
|
|
630
|
+
entry = JSON.parse(line) as Record<string, unknown>;
|
|
631
|
+
} catch {
|
|
632
|
+
corrupt += 1;
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
if (entry["type"] !== "attachment") continue;
|
|
636
|
+
const att = entry["attachment"];
|
|
637
|
+
if (att === null || typeof att !== "object" || Array.isArray(att)) continue;
|
|
638
|
+
const a = att as Record<string, unknown>;
|
|
639
|
+
if (a["type"] !== "hook_success" || a["hookEvent"] !== "SessionStart") continue;
|
|
640
|
+
if (typeof a["command"] !== "string" || !command.test(a["command"])) continue;
|
|
641
|
+
const contentRecorded = typeof a["content"] === "string";
|
|
642
|
+
const content = contentRecorded ? (a["content"] as string) : "";
|
|
643
|
+
const stdout = typeof a["stdout"] === "string" ? a["stdout"] : "";
|
|
644
|
+
const expect = opts.expect ?? null;
|
|
645
|
+
return {
|
|
646
|
+
reason: "read",
|
|
647
|
+
found: true,
|
|
648
|
+
head: sight(WAKE_HEAD_PREFIX, WAKE_HEAD_SENTINEL, content, null),
|
|
649
|
+
tail: sight(WAKE_TAIL_PREFIX, WAKE_TAIL_SENTINEL, content, expect),
|
|
650
|
+
headPrinted: sight(WAKE_HEAD_PREFIX, WAKE_HEAD_SENTINEL, stdout, null),
|
|
651
|
+
tailPrinted: sight(WAKE_TAIL_PREFIX, WAKE_TAIL_SENTINEL, stdout, expect),
|
|
652
|
+
contentRecorded,
|
|
653
|
+
contentBytes: Buffer.byteLength(content, "utf8"),
|
|
654
|
+
stdoutBytes: Buffer.byteLength(stdout, "utf8"),
|
|
655
|
+
linesRead,
|
|
656
|
+
bytesRead: head.bytes,
|
|
657
|
+
corrupt,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
return { ...NO_ARRIVAL, reason: "read", linesRead, bytesRead: head.bytes, corrupt };
|
|
661
|
+
}
|