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,2240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hooks — this host's sensory and motor surface.
|
|
3
|
+
*
|
|
4
|
+
* Everything host-specific lives here so the core stays host-agnostic
|
|
5
|
+
* (constitution 5). The rules this file mechanizes, each from the CONTRACT:
|
|
6
|
+
*
|
|
7
|
+
* **G2 — no hook ever fails the host.** Every entry point below is wrapped in
|
|
8
|
+
* `guard()`: one try/catch, one logged failure, one safe return. There is no
|
|
9
|
+
* path out of this file that throws.
|
|
10
|
+
* **G3 — every session-ending path reaches the boundary.** `SESSION_ENDING`
|
|
11
|
+
* is the enumeration and `BOUNDARY_KIND` the mapping; `test/claude-code.test.ts`
|
|
12
|
+
* walks the list and asserts each one claims spans. Compaction destroying the
|
|
13
|
+
* transcript must not destroy the day (spec §2 G5).
|
|
14
|
+
* **G4 — host limits are reported, not assumed.** The injection ceiling comes
|
|
15
|
+
* from configuration and reaches the core as an argument; a bundle that
|
|
16
|
+
* exceeds it is an EVENT, never a silent truncation (scar §2.18/§2.4).
|
|
17
|
+
* **G7 — an observer stands down at the hook boundary**, and says so.
|
|
18
|
+
* **G8 — the read cursor is per-session and advances after a successful
|
|
19
|
+
* append**, which is `remember/`'s property; the adapter's job is to hand it
|
|
20
|
+
* the same session key every time and never to re-slice the transcript itself.
|
|
21
|
+
* **§2.3 — delivery telemetry is distinct from render telemetry.** The wake
|
|
22
|
+
* states its own sentinel; the FIRST PROMPT of the session reads the head of
|
|
23
|
+
* the host's transcript and reports what the host recorded as injected. The
|
|
24
|
+
* expectation is carried in the session registry record, because every hook is
|
|
25
|
+
* its own process. v1 shipped eleven days of truncated wakes because only the
|
|
26
|
+
* render was instrumented.
|
|
27
|
+
* **§2 G10/G11 — conversational text only, and injected context is excluded
|
|
28
|
+
* from PACING but kept in CAPTURE.** `substanceOf` counts one and
|
|
29
|
+
* `captureSpans` receives the other; the two are computed from the same turns
|
|
30
|
+
* in the same function, so they cannot drift apart.
|
|
31
|
+
* **The parallel run's G3/G5 — exactly one system delivers, and the shadow is
|
|
32
|
+
* ENCODE-ONLY.** Behind `parallel.enabled` (absent by default), every
|
|
33
|
+
* DELIVERING hook asks `primacy.ts` first and stands down when the answer is
|
|
34
|
+
* anything but a clean "engram". A stand-down withholds the wake, the recall
|
|
35
|
+
* and both asks; it withholds NOTHING from capture, because the shadow's whole
|
|
36
|
+
* job is to encode the same days v1 encodes. Both verdicts are durable
|
|
37
|
+
* (parallel-run G4: the mute is evidenced, not asserted).
|
|
38
|
+
*/
|
|
39
|
+
import {
|
|
40
|
+
ADAPTER_ASK_EVENT,
|
|
41
|
+
BOUNDARY_EVENT,
|
|
42
|
+
CHECKOUT_EVENT,
|
|
43
|
+
Counterpart,
|
|
44
|
+
RECALL_CREDIT_EVENT,
|
|
45
|
+
PRIMACY_DELIVER_EVENT,
|
|
46
|
+
PRIMACY_STANDDOWN_EVENT,
|
|
47
|
+
RECALL_DELIVERED_EVENT,
|
|
48
|
+
SPAWN_FAILED_EVENT,
|
|
49
|
+
SPAWN_REFUSED_EVENT,
|
|
50
|
+
SPAWN_STARTED_EVENT,
|
|
51
|
+
WAKE_DELIVERED_EVENT,
|
|
52
|
+
WAKE_INJECTED_EVENT,
|
|
53
|
+
} from "../../core/counterpart.js";
|
|
54
|
+
import type { AdapterDurableEventName } from "../../core/counterpart.js";
|
|
55
|
+
import type {
|
|
56
|
+
BoundaryKind,
|
|
57
|
+
CaptureResult,
|
|
58
|
+
Turn as CapturedTurn,
|
|
59
|
+
} from "../../core/remember/index.js";
|
|
60
|
+
|
|
61
|
+
import { CONFIG_FILE_EVENT } from "../config-path.js";
|
|
62
|
+
import {
|
|
63
|
+
SCOPE_EVENT,
|
|
64
|
+
SCOPE_JOINED_LATE_EVENT,
|
|
65
|
+
SCOPE_REFUSED_EVENT,
|
|
66
|
+
SCOPE_UNREADABLE_EVENT,
|
|
67
|
+
stanceOfMode,
|
|
68
|
+
} from "../scopes.js";
|
|
69
|
+
import type { ScopeVerdict } from "../scopes.js";
|
|
70
|
+
import { countTranslated, readHandleResolutions, translateExpansions } from "../expansions.js";
|
|
71
|
+
import type { ExpansionsRead } from "../expansions.js";
|
|
72
|
+
import { pruneSessions, readSession, recordSession } from "../sessions.js";
|
|
73
|
+
import type { SessionPhase, SessionRecord } from "../sessions.js";
|
|
74
|
+
|
|
75
|
+
import {
|
|
76
|
+
SELF_PAGE_WRITER_EVENT,
|
|
77
|
+
SELF_TUNABLES,
|
|
78
|
+
writerInstruction,
|
|
79
|
+
writerInstructionOverhead,
|
|
80
|
+
} from "../../core/self/index.js";
|
|
81
|
+
import { capabilities, interpretSeat, pageWriterMode } from "./config.js";
|
|
82
|
+
import { TUNABLES } from "./config.js";
|
|
83
|
+
import type { AdapterConfig, CapabilityReport } from "./config.js";
|
|
84
|
+
import { CREDENTIAL_FILE_EVENT, credentialRow } from "./credentials.js";
|
|
85
|
+
import type { CredentialLoad } from "./credentials.js";
|
|
86
|
+
import { SESSION_NOTICE_BUDGET_MS, checkoutIsGraded, doctorFindings, noticeMessage, readCheckout } from "./doctor.js";
|
|
87
|
+
import type { CheckoutReading } from "./doctor.js";
|
|
88
|
+
import { primacy } from "./primacy.js";
|
|
89
|
+
import { planSpawn, spawnDetached } from "./spawn.js";
|
|
90
|
+
import type { SpawnOutcome, Spawner } from "./spawn.js";
|
|
91
|
+
import { NO_ARRIVAL, readWakeArrival } from "./transcript.js";
|
|
92
|
+
import type { Expansion, WakeArrival } from "./transcript.js";
|
|
93
|
+
|
|
94
|
+
/** Every hook this adapter installs, by the name it is wired under. */
|
|
95
|
+
export const HOOKS = [
|
|
96
|
+
"session-start",
|
|
97
|
+
"user-prompt-submit",
|
|
98
|
+
"stop",
|
|
99
|
+
"session-end",
|
|
100
|
+
"pre-compact",
|
|
101
|
+
] as const;
|
|
102
|
+
export type HookName = (typeof HOOKS)[number];
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The session-ending paths. THREE, not one — the whole point of G3. `stop` is
|
|
106
|
+
* the ordinary turn end, `session-end` is the host closing the session, and
|
|
107
|
+
* `pre-compact` is the transcript about to be destroyed.
|
|
108
|
+
*/
|
|
109
|
+
export const SESSION_ENDING = ["stop", "session-end", "pre-compact"] as const;
|
|
110
|
+
export type SessionEndingHook = (typeof SESSION_ENDING)[number];
|
|
111
|
+
|
|
112
|
+
/** Host event name → `remember/`'s boundary vocabulary. Total by construction. */
|
|
113
|
+
export const BOUNDARY_KIND: Record<SessionEndingHook, BoundaryKind> = {
|
|
114
|
+
stop: "stop",
|
|
115
|
+
"session-end": "session-end",
|
|
116
|
+
"pre-compact": "pre-compaction",
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/** A turn as the host reports it. `source` is what makes G10/G11 decidable. */
|
|
120
|
+
export interface HostTurn extends CapturedTurn {}
|
|
121
|
+
|
|
122
|
+
export interface HookInput {
|
|
123
|
+
readonly sessionId: string;
|
|
124
|
+
/** The project scope. The host's cwd, resolved — never a raw relative path. */
|
|
125
|
+
readonly scope: string;
|
|
126
|
+
/** The transcript slice the host can see. The cursor decides what is new. */
|
|
127
|
+
readonly turns?: readonly HostTurn[];
|
|
128
|
+
/** Deliberate-recall calls positioned against `turns` (`transcript.ts#Expansion`). */
|
|
129
|
+
readonly expansions?: readonly Expansion[];
|
|
130
|
+
/** What the user typed this turn (`user-prompt-submit`). */
|
|
131
|
+
readonly prompt?: string;
|
|
132
|
+
/**
|
|
133
|
+
* WHERE THE HOST IS KEEPING THIS SESSION'S TRANSCRIPT — the path the payload
|
|
134
|
+
* named, carried so the delivery check can read the head of it and see what
|
|
135
|
+
* the host recorded as injected at SessionStart (`transcript.ts`). The turns
|
|
136
|
+
* above come from the same file, parsed for conversation; this is the same
|
|
137
|
+
* file read for the one thing that parse deliberately skips.
|
|
138
|
+
*/
|
|
139
|
+
readonly transcriptPath?: string;
|
|
140
|
+
/** Today's calendar date, for the temporal channel and the horizon lane. */
|
|
141
|
+
readonly at?: string;
|
|
142
|
+
/**
|
|
143
|
+
* THE HOST'S RE-FIRE. A blocked Stop comes back with `stop_hook_active`, and
|
|
144
|
+
* that pass must ask nothing — v1's anti-loop, kept for the same reason. It is
|
|
145
|
+
* checked HERE, not only at delivery, so the re-fire also burns no pacing and
|
|
146
|
+
* no day-cap slot: a silent ask that still advanced the counters would spend
|
|
147
|
+
* the day's chapters on nobody.
|
|
148
|
+
*/
|
|
149
|
+
readonly reFired?: boolean;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface HookResult {
|
|
153
|
+
readonly hook: HookName;
|
|
154
|
+
readonly ok: boolean;
|
|
155
|
+
readonly reason: string;
|
|
156
|
+
/** What to add to the host's context. The EMPTY STRING on a quiet hook. */
|
|
157
|
+
readonly injection: string;
|
|
158
|
+
readonly bytes: number;
|
|
159
|
+
/**
|
|
160
|
+
* The render's own tail line. At SessionStart it is also the expectation the
|
|
161
|
+
* delivery check tests: it is written into the session registry record, and
|
|
162
|
+
* the session's first prompt compares it against what the host's transcript
|
|
163
|
+
* says arrived.
|
|
164
|
+
*/
|
|
165
|
+
readonly sentinel: string | null;
|
|
166
|
+
readonly surfaced: readonly string[];
|
|
167
|
+
readonly footnotes: readonly string[];
|
|
168
|
+
/**
|
|
169
|
+
* THE ask this hook raises — at a Stop, memories and the chapter, one text,
|
|
170
|
+
* one pacer. Null when this Stop is not due one. There is exactly one field
|
|
171
|
+
* because there is exactly one ask at a boundary: two fields is how the
|
|
172
|
+
* blocked moment grew back into two asks (§13 G3).
|
|
173
|
+
*
|
|
174
|
+
* SessionStart uses the same field for the first-launch scope question
|
|
175
|
+
* (`SCOPE_ASK`, G41) and, since S2, for the nightly page writer's block. It
|
|
176
|
+
* is the same field for the same reason: it is the one channel that reaches
|
|
177
|
+
* the model WITHOUT being inside the wake bundle, whose byte count and tail
|
|
178
|
+
* line are stated by its own sentinel.
|
|
179
|
+
*
|
|
180
|
+
* **Three claimants, and the rule is not "they cannot collide" any more** —
|
|
181
|
+
* that sentence was true when there were two, one at `session-start` and one
|
|
182
|
+
* at `stop`. The Stop ask still cannot meet either of the others, and the
|
|
183
|
+
* Stop pacer is untouched by both. The two SessionStart ones CAN want the
|
|
184
|
+
* field on the same morning, and there the first-launch question wins: it is
|
|
185
|
+
* asked once in the life of a directory and ends when anybody answers, while
|
|
186
|
+
* the writer's comes back tomorrow at no cost. The loser is deferred with an
|
|
187
|
+
* event, never concatenated — two unrelated requests in front of a session
|
|
188
|
+
* that has just woken is the shape §13 G3 is about, even though the pacer is
|
|
189
|
+
* not involved.
|
|
190
|
+
*/
|
|
191
|
+
readonly ask: string | null;
|
|
192
|
+
readonly spansAppended: number;
|
|
193
|
+
readonly spawn: SpawnOutcome | null;
|
|
194
|
+
readonly observer: boolean;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export interface AdapterEvent {
|
|
198
|
+
readonly at: number;
|
|
199
|
+
readonly name: string;
|
|
200
|
+
readonly data: Record<string, string | number | boolean | null>;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface AdapterOptions {
|
|
204
|
+
readonly counterpart: Counterpart;
|
|
205
|
+
readonly config: AdapterConfig;
|
|
206
|
+
/** The interpreter the detached worker runs under. */
|
|
207
|
+
readonly command?: string;
|
|
208
|
+
readonly args?: readonly string[];
|
|
209
|
+
readonly spawner?: Spawner;
|
|
210
|
+
readonly onEvent?: (e: AdapterEvent) => void;
|
|
211
|
+
readonly now?: () => number;
|
|
212
|
+
/**
|
|
213
|
+
* What this PROCESS's credential file answered, from the entry point that
|
|
214
|
+
* loaded it (`bin/hook.ts`). Passed in rather than looked up: provenance is a
|
|
215
|
+
* fact about one process's startup, and the adapter's only jobs with it are to
|
|
216
|
+
* say `env` or `file` on the capability row and to leave ONE ring event saying
|
|
217
|
+
* the file was used. Names and counts only — never a value.
|
|
218
|
+
*/
|
|
219
|
+
readonly credentials?: CredentialLoad;
|
|
220
|
+
/**
|
|
221
|
+
* WHICH `claude-code.json` THIS PROCESS READ — an absolute path, resolved by
|
|
222
|
+
* the entry point (`bin/hook.ts`, via `adapters/config-path.ts`) and passed in
|
|
223
|
+
* for the same reason `credentials` is: it is a fact about one process's
|
|
224
|
+
* startup, not something the adapter may go and re-derive.
|
|
225
|
+
*
|
|
226
|
+
* The adapter does three things with it, all of them recording:
|
|
227
|
+
* - one ring event at construction, exactly as the credential file gets;
|
|
228
|
+
* - the `config` field of every session registry record it writes, which is
|
|
229
|
+
* the only DURABLE trace a hook can leave of this (a hook has no stdout to
|
|
230
|
+
* tell the owner with — that channel is the model's context);
|
|
231
|
+
* - the pin onto the detached worker's environment, so parent and child read
|
|
232
|
+
* one file rather than resolving two.
|
|
233
|
+
*/
|
|
234
|
+
readonly configPath?: string;
|
|
235
|
+
/**
|
|
236
|
+
* WHAT `<config dir>/scopes.json` SAYS ABOUT THIS DIRECTORY, resolved by the
|
|
237
|
+
* entry point before anything opened (`bin/hook.ts#hookScopeVerdict`).
|
|
238
|
+
*
|
|
239
|
+
* The adapter does exactly two things with it: records it once, and — when it
|
|
240
|
+
* is `unset` — appends the first-launch question to the wake, once per
|
|
241
|
+
* session (G41). The `off` decision is NOT here: it is made in the entry
|
|
242
|
+
* point, because "no output and no write" is only a guarantee if nothing was
|
|
243
|
+
* constructed. `guard()` still refuses on it as a second, cheap site, for the
|
|
244
|
+
* same reason the observer stand-down lives at the store seam as well as at
|
|
245
|
+
* the entry point (observer-mode G8).
|
|
246
|
+
*/
|
|
247
|
+
readonly scope?: ScopeVerdict;
|
|
248
|
+
/** The sentence a registry that IS there and could not be read produced. */
|
|
249
|
+
readonly scopeUnreadable?: string;
|
|
250
|
+
/**
|
|
251
|
+
* The ENTRIES that registry refused, by key (#92 review, F2). A file can parse
|
|
252
|
+
* while one directory's entry does not, and those directories read as unset —
|
|
253
|
+
* which is ON. Ring event here, and a flag on the wake's durable row, because
|
|
254
|
+
* a hook process lives for one turn and "why is this directory recording
|
|
255
|
+
* again" has to be answerable tomorrow.
|
|
256
|
+
*/
|
|
257
|
+
readonly scopeRefused?: readonly string[];
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* THE FIRST-LAUNCH QUESTION (owner ask G41, 2026-09-10).
|
|
262
|
+
*
|
|
263
|
+
* The hooks are registered globally, so the first session in a new directory
|
|
264
|
+
* already has capture running by the time anyone could have been asked. The
|
|
265
|
+
* honest fix the owner asked for is a question asked once and remembered — and
|
|
266
|
+
* the host offers `SessionStart` as the only place to ask and no place at all
|
|
267
|
+
* to receive an answer, which is `INTERFACE-GAPS.md` gap 7's shape all over
|
|
268
|
+
* again. So the block asks the MODEL to ask the PERSON, and names the console
|
|
269
|
+
* line that records the reply.
|
|
270
|
+
*
|
|
271
|
+
* Advisory wording, mechanized existence (CONTRACT §5 G9): what is guaranteed
|
|
272
|
+
* is that an `unset` directory raises the question exactly once per session and
|
|
273
|
+
* that setting any mode ends it, not the sentences.
|
|
274
|
+
*/
|
|
275
|
+
export const SCOPE_ASK = [
|
|
276
|
+
"<counterparts-scope>",
|
|
277
|
+
"No setting yet for this directory, so Counterparts is remembering here by default.",
|
|
278
|
+
"Early on, ask the user once which they want: on, observer (reads and recalls, records",
|
|
279
|
+
"nothing), or off (nothing at all). Record the answer with the `scope` tool (mode: on |",
|
|
280
|
+
"observer | off), or with `counterparts scope . --on`, `--observer` or `--off`. Then",
|
|
281
|
+
"do not ask again.",
|
|
282
|
+
"</counterparts-scope>",
|
|
283
|
+
].join("\n");
|
|
284
|
+
|
|
285
|
+
/** The room the question needs, separator included. Measured, never guessed. */
|
|
286
|
+
export const SCOPE_ASK_BYTES = Buffer.byteLength(`\n\n${SCOPE_ASK}`, "utf8");
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* THE NIGHTLY PAGE WRITER'S ASK, in `session` mode (S2, 2026-09-20).
|
|
290
|
+
*
|
|
291
|
+
* The plan's fallback for "who runs the nightly writer", and the one that needs
|
|
292
|
+
* no background process: when nothing has revised the page for the day just
|
|
293
|
+
* gone, the first session of the next day is handed that day and asked to do
|
|
294
|
+
* the night's work. It rides in `HookResult.ask` — beside the wake, never
|
|
295
|
+
* inside it — for the reason the scope question does: the wake's byte count and
|
|
296
|
+
* its tail sentinel are load-bearing, and text appended inside the bundle would
|
|
297
|
+
* make `bytes`, the sentinel's number and the tail disagree.
|
|
298
|
+
*
|
|
299
|
+
* **It is not a second pacer.** The scar this package carries about pacers
|
|
300
|
+
* (`self/CONTRACT.md` §3, "one ask, one pacer, a conjunction") is about the
|
|
301
|
+
* BLOCKED MOMENT at Stop, where two asks on two substance pacers once drew
|
|
302
|
+
* about a dozen asks from a 13-turn evening. Nothing here touches that: this
|
|
303
|
+
* fires at SessionStart, it consults no substance, and its cadence is the day
|
|
304
|
+
* boundary itself — at most `PAGE_WRITER_ASKS_PER_DAY` sessions are handed one
|
|
305
|
+
* day, and the first durable row claims it for everyone.
|
|
306
|
+
*
|
|
307
|
+
* The TEXT is the core's (`self/writer.ts#writerInstruction`), because it
|
|
308
|
+
* carries the page and the day and those are memory, not host trivia. What is
|
|
309
|
+
* mechanized here is that the moment exists, that it fits inside the reported
|
|
310
|
+
* ceiling or is deferred rather than truncated, that one session is asked once,
|
|
311
|
+
* and that the ask leaves a durable row (CONTRACT §5 G9).
|
|
312
|
+
*/
|
|
313
|
+
export const PAGE_WRITER_TOOL = "counterparts self_page";
|
|
314
|
+
|
|
315
|
+
/** The separator `bin/hook.ts#hostDelivery` joins the ask on after the wake. */
|
|
316
|
+
export const ASK_SEPARATOR_BYTES = 2;
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* How many recorded deferrals the first-launch question gets before the writer
|
|
320
|
+
* takes the ask field instead.
|
|
321
|
+
*
|
|
322
|
+
* ONE, because the two asks are not symmetrical. The scope question is
|
|
323
|
+
* per-SESSION and comes back at the next one at no cost; the writer's night
|
|
324
|
+
* happens once, and a night that passes is a day missing from the page for
|
|
325
|
+
* good. On a blank store the scope question is exactly what is pending on
|
|
326
|
+
* nights 1–3, so an unanswered one starved the writer for as long as nobody
|
|
327
|
+
* answered — which on a store where nobody ever does is for ever (S2 review,
|
|
328
|
+
* MINOR-5).
|
|
329
|
+
*
|
|
330
|
+
* It counts DEFERRAL ROWS, which are deduped one per night per reason, so the
|
|
331
|
+
* flip is "this night has already lost the field once" — the first session of a
|
|
332
|
+
* day raises the scope question, the second gives the writer its night, and the
|
|
333
|
+
* third raises the scope question again because the night is claimed by then.
|
|
334
|
+
*/
|
|
335
|
+
export const SCOPE_PATIENCE_DEFERRALS = 1;
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* THE ONE STOP ASK — v2's front door and its journal, in one text.
|
|
339
|
+
*
|
|
340
|
+
* The wording is advisory (remember G11 [A], CONTRACT §5 G9); that an ask exists
|
|
341
|
+
* at a session-ending path is what is mechanized. It names the TOOLS, because
|
|
342
|
+
* the RETURN channel is a tool, not a hook: a hook can only put text into the
|
|
343
|
+
* context, and the deposits come back through `Counterpart.submitSessionEnd`
|
|
344
|
+
* and `Counterpart.appendEpisode` — reached, in this host, by the MCP adapter's
|
|
345
|
+
* `session_end` and `chapter` (`mcp/CONTRACT.md`). Filed in
|
|
346
|
+
* `INTERFACE-GAPS.md` §7.
|
|
347
|
+
*
|
|
348
|
+
* **ONE ask, not two.** Behavioral-spec §13 G3 said it in v1's words — "the
|
|
349
|
+
* blocked moment carries a single ask; new features do not get to grow it back
|
|
350
|
+
* into two" — and v2 grew it back into two anyway: the authorship ask on its own
|
|
351
|
+
* turn/byte pacer and the episode ask on the chapter pacer, firing at different
|
|
352
|
+
* Stops. Measured 2026-09-04: about a dozen asks in a 13-turn evening. They are
|
|
353
|
+
* one text on one pacer here, and the pacer is the chapter's.
|
|
354
|
+
*
|
|
355
|
+
* The other three corrections, all measured the same day:
|
|
356
|
+
*
|
|
357
|
+
* - **It names the session id and both tools.** The host's MCP servers are
|
|
358
|
+
* launched from a static config and never learn which session they are
|
|
359
|
+
* serving, so the id has to travel in the ask — it is what the server binds
|
|
360
|
+
* itself with (`adapters/sessions.ts`, `mcp/server.ts#requireBoundSession`).
|
|
361
|
+
* Without it the model reached for `note` 34 times in one session and no
|
|
362
|
+
* session's dump ever landed. On the Stops where only the episode half
|
|
363
|
+
* fired, the model got no id and no tool name at all.
|
|
364
|
+
* - **`updates` is a FIELD, and the ask says so.** The old wording said
|
|
365
|
+
* "say `updates: <id>`", and four notes duly arrived with `updates: mem_x.`
|
|
366
|
+
* as the first words of their prose — unlinked, because prose is not a
|
|
367
|
+
* field. It is a field on a `session_end` entry AND on `note`.
|
|
368
|
+
* - **The chapter number is the store's.** It is one past what was WRITTEN,
|
|
369
|
+
* never one past what was asked, so an unanswered ask does not silently
|
|
370
|
+
* renumber the journal.
|
|
371
|
+
* - **It says salience is the author's to set.** An unclaimed authored memory
|
|
372
|
+
* takes a modest default floor, deliberately below the semantic band
|
|
373
|
+
* (`physics/`, 2026-09-04), and the author's own claim is the only channel
|
|
374
|
+
* by which lived testimony outranks something a sweep noticed — the sweep's
|
|
375
|
+
* claim is capped where the author's is not.
|
|
376
|
+
*
|
|
377
|
+
* Short on purpose: a model reads this at every Stop that is due one.
|
|
378
|
+
*/
|
|
379
|
+
export function stopAsk(sessionId: string, chapter: number): string {
|
|
380
|
+
return [
|
|
381
|
+
"Before this session closes, two things, both yours to write — and a third only if you are leaving work unfinished here:",
|
|
382
|
+
`1. What did you LEARN here that is worth keeping? Your own words, one idea per memory, the way you would want to find it again. Hand them back with the counterparts session_end tool, session: ${sessionId}. \`updates\` is a FIELD on an entry (and on note), never prose: the id of the memory that entry revises. Set \`salience\` (0-1) on anything that should last: unset entries take a modest default, and your claim is the only way what you lived outranks what a sweep noticed.`,
|
|
383
|
+
chapter === 1
|
|
384
|
+
? `2. Write this session's episode with the counterparts chapter tool, session: ${sessionId} — first person, your voice, any length: what happened and what mattered, how it felt, what you learned about them and about yourself, what is still open. For the next you, not a report; append in the moment when something happens later.`
|
|
385
|
+
: `2. Add chapter ${String(chapter)} to this session's episode with the counterparts chapter tool, session: ${sessionId} — this stretch, in the moment, in your own voice. Not a recap of the earlier chapters.`,
|
|
386
|
+
HANDOFF_LINE,
|
|
387
|
+
"Nothing worth keeping is a real answer, and a short true episode beats a manufactured deep one.",
|
|
388
|
+
].join("\n");
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* THE THIRD LINE, AND STILL ONE ASK (E1). The handoff is a FIELD on the
|
|
393
|
+
* `session_end` call the line above already names — not a third tool, not a
|
|
394
|
+
* second moment, and not a second pacer: the whole of §13 G3's scar is that the
|
|
395
|
+
* blocked moment carries a single ask, and a field is not an ask.
|
|
396
|
+
*
|
|
397
|
+
* It is numbered `3.` rather than folded into item 1 because item 1 is about
|
|
398
|
+
* MEMORIES — what will still be true next week — and a handoff is the opposite
|
|
399
|
+
* claim: what is true only for the next fortnight, in this directory. Reading
|
|
400
|
+
* them as one sentence is what would produce handoffs filed as memories.
|
|
401
|
+
*
|
|
402
|
+
* Short on purpose, and deliberately conditional in its own words ("if you are
|
|
403
|
+
* leaving anything unfinished"): a session that finished what it started should
|
|
404
|
+
* leave no pointer, and the ask should not push one out of politeness.
|
|
405
|
+
*/
|
|
406
|
+
export const HANDOFF_LINE =
|
|
407
|
+
"3. Set `handoff` on that same session_end call: where this directory stands and what to pick up next. Not a memory — the next session HERE sees a line of it, and it expires.";
|
|
408
|
+
|
|
409
|
+
const EVENT_RING = 500;
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Where the per-reason spawn refusal counters live: box 2's meta, under
|
|
413
|
+
* `adapter.spawn.refusals.<reason>`.
|
|
414
|
+
*
|
|
415
|
+
* In the STORE because scar E4's escalation is a claim about a HOST over time
|
|
416
|
+
* and a hook process lives for one turn. I32 is the bill for having kept it in
|
|
417
|
+
* an instance field: the worker was refused at every boundary for a week and
|
|
418
|
+
* `escalate` read false every single time, because every count was the first.
|
|
419
|
+
*
|
|
420
|
+
* Meta keys, not a schema change — the same shape `sleep.pruned.<id>` uses.
|
|
421
|
+
*/
|
|
422
|
+
export const SPAWN_REFUSAL_PREFIX = "adapter.spawn.refusals.";
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* The other side's counter (2026-09-20, E2): how many times the worker HAS
|
|
426
|
+
* started today. Two fixed keys rather than one per date, because nothing mows
|
|
427
|
+
* meta and the only question the `adapter.spawn.started` row asks of it is "how
|
|
428
|
+
* many today" — the row itself carries the date.
|
|
429
|
+
*/
|
|
430
|
+
export const SPAWN_START_DATE_KEY = "adapter.spawn.started.date";
|
|
431
|
+
export const SPAWN_START_COUNT_KEY = "adapter.spawn.started.count";
|
|
432
|
+
|
|
433
|
+
export class ClaudeCodeAdapter {
|
|
434
|
+
readonly counterpart: Counterpart;
|
|
435
|
+
readonly config: AdapterConfig;
|
|
436
|
+
readonly observer: boolean;
|
|
437
|
+
|
|
438
|
+
private readonly command: string;
|
|
439
|
+
private readonly args: readonly string[];
|
|
440
|
+
private readonly spawner: Spawner | undefined;
|
|
441
|
+
private readonly onEvent: ((e: AdapterEvent) => void) | undefined;
|
|
442
|
+
private readonly nowFn: () => number;
|
|
443
|
+
private readonly credentials: CredentialLoad | undefined;
|
|
444
|
+
/** The `claude-code.json` this process read — recorded, pinned, never re-derived. */
|
|
445
|
+
private readonly configPath: string | undefined;
|
|
446
|
+
/** What the scope registry said about this directory. `unset` when nobody said. */
|
|
447
|
+
readonly scope: ScopeVerdict;
|
|
448
|
+
/**
|
|
449
|
+
* WHETHER THE REGISTRY ITSELF WAS IN TROUBLE when this process read it, for
|
|
450
|
+
* the wake's durable row (#92 review, F2): `unreadable` is the whole file,
|
|
451
|
+
* `partial` is one or more entries refused by name. Null is the ordinary day,
|
|
452
|
+
* and the field is `null` on the row rather than absent, so a reader can tell
|
|
453
|
+
* "the registry was fine" from "this row predates the question".
|
|
454
|
+
*/
|
|
455
|
+
private scopeTrouble: "unreadable" | "partial" | null = null;
|
|
456
|
+
private readonly ring: AdapterEvent[] = [];
|
|
457
|
+
/** The anti-loop guard: one hook per session in flight at a time. */
|
|
458
|
+
private readonly inFlight = new Set<string>();
|
|
459
|
+
/**
|
|
460
|
+
* Consecutive identical spawn refusals, per reason (scar E4's escalation) —
|
|
461
|
+
* IN MEMORY ONLY when this adapter cannot write, which is the observer case.
|
|
462
|
+
*
|
|
463
|
+
* The durable copy lives in box 2's meta under `adapter.spawn.refusals.<reason>`
|
|
464
|
+
* and is the one that counts. This map used to BE the counter, and that is
|
|
465
|
+
* half of why I32 ran for a week: a hook process lives for one turn, so
|
|
466
|
+
* "consecutive" was always 1, `escalate` was always false, and scar E4's
|
|
467
|
+
* widening — a repeated refusal reaches a human — was inert on this host after
|
|
468
|
+
* shipping. An instrument still counts here and nowhere else (§15 G3).
|
|
469
|
+
*/
|
|
470
|
+
private readonly volatileRefusals = new Map<string, number>();
|
|
471
|
+
|
|
472
|
+
constructor(opts: AdapterOptions) {
|
|
473
|
+
this.counterpart = opts.counterpart;
|
|
474
|
+
this.config = opts.config;
|
|
475
|
+
this.observer = opts.counterpart.observer;
|
|
476
|
+
this.command = opts.command ?? process.execPath;
|
|
477
|
+
this.args = opts.args ?? [];
|
|
478
|
+
this.spawner = opts.spawner;
|
|
479
|
+
this.onEvent = opts.onEvent;
|
|
480
|
+
this.nowFn = opts.now ?? ((): number => Date.now());
|
|
481
|
+
this.credentials = opts.credentials;
|
|
482
|
+
this.configPath = opts.configPath;
|
|
483
|
+
this.scope = opts.scope ?? { mode: "unset", matched: null, entry: null };
|
|
484
|
+
// ONE event naming the configuration this process read, for the same reason
|
|
485
|
+
// the credential file gets one: a hook's stdout belongs to the model, so
|
|
486
|
+
// "which file answered" has nowhere else to go in-process. The durable half
|
|
487
|
+
// is the session record's `config` field (`noteSession`).
|
|
488
|
+
if (opts.configPath !== undefined && opts.configPath.length > 0) {
|
|
489
|
+
this.emit(CONFIG_FILE_EVENT, { path: opts.configPath });
|
|
490
|
+
}
|
|
491
|
+
// ONE event, and only when the file actually answered. A run whose keys came
|
|
492
|
+
// from the environment says nothing here, so the presence of this line in
|
|
493
|
+
// the ring IS the record that the configured file was the source (§4 G4:
|
|
494
|
+
// a host fact, surfaced rather than assumed). Last in the constructor:
|
|
495
|
+
// `emit` needs `nowFn`.
|
|
496
|
+
if (opts.credentials !== undefined && opts.credentials.loaded.length > 0) {
|
|
497
|
+
this.emit(CREDENTIAL_FILE_EVENT, credentialRow(opts.credentials));
|
|
498
|
+
}
|
|
499
|
+
// ONE event naming the scope verdict this process ran under, and which
|
|
500
|
+
// entry produced it — the answer to "why did this directory record nothing
|
|
501
|
+
// today", which is otherwise a question only a person reading two JSON
|
|
502
|
+
// files can answer.
|
|
503
|
+
this.emit(SCOPE_EVENT, {
|
|
504
|
+
mode: this.scope.mode,
|
|
505
|
+
matched: this.scope.matched,
|
|
506
|
+
stance: stanceOfMode(this.scope.mode),
|
|
507
|
+
});
|
|
508
|
+
// A registry that IS there and could not be read resolved to `unset` — on,
|
|
509
|
+
// today's behaviour — and says so, because a silent fall-back to the
|
|
510
|
+
// default is exactly the shape scar §2.4 is about.
|
|
511
|
+
if (opts.scopeUnreadable !== undefined && opts.scopeUnreadable.length > 0) {
|
|
512
|
+
this.emit(SCOPE_UNREADABLE_EVENT, { detail: opts.scopeUnreadable });
|
|
513
|
+
}
|
|
514
|
+
// The per-ENTRY half of the same fact. Those directories read as unset,
|
|
515
|
+
// which is on: an `off` somebody typed badly is an `off` nobody is keeping.
|
|
516
|
+
if (opts.scopeRefused !== undefined && opts.scopeRefused.length > 0) {
|
|
517
|
+
this.scopeTrouble = "partial";
|
|
518
|
+
this.emit(SCOPE_REFUSED_EVENT, {
|
|
519
|
+
count: opts.scopeRefused.length,
|
|
520
|
+
keys: opts.scopeRefused.join(", "),
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
// An unreadable FILE outranks refused entries: there were no entries.
|
|
524
|
+
if (opts.scopeUnreadable !== undefined && opts.scopeUnreadable.length > 0) {
|
|
525
|
+
this.scopeTrouble = "unreadable";
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
events(name?: string): AdapterEvent[] {
|
|
530
|
+
return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** §4 G4: every host-dependent limit, as a checkable value. */
|
|
534
|
+
capabilities(): CapabilityReport[] {
|
|
535
|
+
return capabilities(this.config, process.env, this.credentials);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// ── session start: the wake ────────────────────────────────────────────────
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Inject what the previous boundary published. Zero compute, zero model calls,
|
|
542
|
+
* zero network (§1 G1) — and THE WAKE NEVER FAILS THE SESSION (§1 G7): every
|
|
543
|
+
* failure below returns the empty string and a clean exit.
|
|
544
|
+
*/
|
|
545
|
+
sessionStart(input: HookInput): HookResult {
|
|
546
|
+
return this.guard("session-start", input, (out) => {
|
|
547
|
+
// ASKED BEFORE THE REGISTRY IS REWRITTEN: `noteSession` rewrites the
|
|
548
|
+
// record whole, so the flag that says "this session has already been
|
|
549
|
+
// asked" has to be read while it is still the previous process's answer.
|
|
550
|
+
const wantsAsk = this.scopeAskDue(input);
|
|
551
|
+
// BEFORE the delivery verdict, because the registry is not delivery: a
|
|
552
|
+
// muted shadow still lives a session, and the tool that writes its dump
|
|
553
|
+
// still has to be able to find out that the session is real.
|
|
554
|
+
this.noteSession("start", input);
|
|
555
|
+
// FIRST, before anything is read or composed: is this ours to deliver?
|
|
556
|
+
// A stand-down sets no delivery expectation, because there is no render
|
|
557
|
+
// for the next hook to check — recording one would put a false negative
|
|
558
|
+
// into scar §2.3's telemetry on every muted day.
|
|
559
|
+
if (!this.deliveryVerdict("session-start", input)) {
|
|
560
|
+
return { ...out, ok: true, reason: "primacy-standdown" };
|
|
561
|
+
}
|
|
562
|
+
const budget = this.config.injectionBudgetBytes;
|
|
563
|
+
if (budget === undefined) {
|
|
564
|
+
// The tripwire. We inject what exists, and we say that nobody told us
|
|
565
|
+
// what this host can carry — an invented ceiling is scar §2.18.
|
|
566
|
+
this.emit("adapter.budget.unreported", {});
|
|
567
|
+
}
|
|
568
|
+
// THE DELIVERY PREFACE is asked for here, at injection, and composed
|
|
569
|
+
// nowhere else. The stored bundle was rendered at the last boundary and is
|
|
570
|
+
// served unchanged to every session until the next one; on 2026-09-03 the
|
|
571
|
+
// memory system under this host changed mid-day and the body went on
|
|
572
|
+
// speaking as the old one, with only the HTML comment naming the new. The
|
|
573
|
+
// date is the HOST's — this hook is the only place that has it — and
|
|
574
|
+
// nothing in the line varies between two sessions of the same day, so the
|
|
575
|
+
// delivery expectation below stays a stable string (§2.3).
|
|
576
|
+
// WHERE this session woke rides beside WHEN (E1). The published bundle is
|
|
577
|
+
// one per store and is read by sessions in every directory, so which
|
|
578
|
+
// directory this one opened in is a delivery-time fact exactly as the date
|
|
579
|
+
// is — and it is the only thing that can decide whose handoff pointer,
|
|
580
|
+
// if any, belongs at the foot of this wake.
|
|
581
|
+
const woke = this.counterpart.wake(
|
|
582
|
+
budget,
|
|
583
|
+
{ ...(input.at === undefined ? {} : { date: input.at }) },
|
|
584
|
+
{ scope: input.scope, session: input.sessionId.length === 0 ? null : input.sessionId },
|
|
585
|
+
);
|
|
586
|
+
// THE EXPECTATION, WRITTEN WHERE THE NEXT PROCESS CAN READ IT. This used
|
|
587
|
+
// to be a `Map` on this instance, which is a line that only looks like it
|
|
588
|
+
// works: every hook is its own process, so the hook that tests it always
|
|
589
|
+
// met an empty map. `adapter.wake.delivered` wrote no row in two weeks of
|
|
590
|
+
// running (mechanism inventory 2026-09-17, S2).
|
|
591
|
+
this.noteWakeExpectation(input, woke.sentinel);
|
|
592
|
+
|
|
593
|
+
if (budget !== undefined && woke.bytes > budget) {
|
|
594
|
+
// Exceeding a reported limit is an EVENT, never silent degradation. The
|
|
595
|
+
// bundle still goes: truncated-and-detectable beats absent.
|
|
596
|
+
this.emit("adapter.injection.overbudget", { bytes: woke.bytes, budget });
|
|
597
|
+
}
|
|
598
|
+
this.record(WAKE_INJECTED_EVENT, input, {
|
|
599
|
+
ok: woke.ok,
|
|
600
|
+
reason: woke.reason,
|
|
601
|
+
bytes: woke.bytes,
|
|
602
|
+
budget: budget ?? null,
|
|
603
|
+
sentinel: woke.sentinel !== null,
|
|
604
|
+
preface: woke.preface !== null,
|
|
605
|
+
// THE DURABLE HALF of a registry in trouble (#92 review, F2). It rides
|
|
606
|
+
// the session-start row this hook already writes, for the reason
|
|
607
|
+
// `adapter.scope.unreadable` is ring-only: a durable event NAME is a
|
|
608
|
+
// core change (`AdapterDurableEventName`) and this fact is about
|
|
609
|
+
// exactly the moment that row describes.
|
|
610
|
+
scopeRegistry: this.scopeTrouble,
|
|
611
|
+
});
|
|
612
|
+
// THE QUESTION RIDES BESIDE THE WAKE, NEVER INSIDE IT, and only if it
|
|
613
|
+
// FITS.
|
|
614
|
+
//
|
|
615
|
+
// Beside, because the wake's own accounting is load-bearing: its sentinel
|
|
616
|
+
// states the bundle's byte count and must be the LAST line of the bundle,
|
|
617
|
+
// so a truncated wake is detectable from its tail alone (§1 G2, scar
|
|
618
|
+
// §2.3). Text appended inside the injection would make `bytes`, the
|
|
619
|
+
// sentinel's number and the tail all disagree — three lies to deliver one
|
|
620
|
+
// question. `ask` is the field the host delivery already appends after
|
|
621
|
+
// the injection (`bin/hook.ts#hostDelivery`), which is exactly the
|
|
622
|
+
// placement asked for and costs the wake nothing.
|
|
623
|
+
//
|
|
624
|
+
// And only if it fits, because what the host places in context is the
|
|
625
|
+
// whole block: the ceiling it reported governs the wake's bytes plus this
|
|
626
|
+
// one's. With no room the ask is DEFERRED rather than truncated or
|
|
627
|
+
// smuggled past the limit — the session record is left unmarked, so the
|
|
628
|
+
// next session in this directory asks instead, and the deferral is an
|
|
629
|
+
// event rather than a silence.
|
|
630
|
+
//
|
|
631
|
+
// TWO ASKS CAN NOW WANT THIS FIELD, and the first-launch question wins.
|
|
632
|
+
// It is asked once in the life of a directory and ends when anybody
|
|
633
|
+
// answers; the page writer's comes back tomorrow at no cost. Concatenating
|
|
634
|
+
// them would put two unrelated requests in front of a session that has
|
|
635
|
+
// just woken, which is the shape §13 G3 is about even though the pacer is
|
|
636
|
+
// not. The loser is DEFERRED with a row, never dropped silently.
|
|
637
|
+
// ...and after two mornings of losing, the writer goes first. The scope
|
|
638
|
+
// question is advisory and returns at the next session; a night that
|
|
639
|
+
// passes is a day missing from the page for good (S2 review, MINOR-5).
|
|
640
|
+
const scopeFirst = wantsAsk && !this.writerStarvedByScope();
|
|
641
|
+
const ask = scopeFirst ? this.deliverScopeAsk(input, woke.bytes, budget) : "";
|
|
642
|
+
const chosen =
|
|
643
|
+
ask.length > 0 ? ask : this.deliverPageWriterAsk(input, woke.bytes, budget, false);
|
|
644
|
+
if (ask.length > 0) this.deliverPageWriterAsk(input, woke.bytes, budget, true);
|
|
645
|
+
return {
|
|
646
|
+
...out,
|
|
647
|
+
ok: woke.ok,
|
|
648
|
+
reason: woke.reason,
|
|
649
|
+
injection: woke.text,
|
|
650
|
+
bytes: woke.bytes,
|
|
651
|
+
sentinel: woke.sentinel,
|
|
652
|
+
ask: chosen.length === 0 ? null : chosen,
|
|
653
|
+
};
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Is this session owed the first-launch question (G41)?
|
|
659
|
+
*
|
|
660
|
+
* Three ways to be owed nothing: the directory has an entry (somebody
|
|
661
|
+
* answered, whatever they answered); this session was already asked; or this
|
|
662
|
+
* is an instrument, which has no business asking a person to change a store
|
|
663
|
+
* it may not write — and, having written no session record, no way to
|
|
664
|
+
* remember that it did.
|
|
665
|
+
*/
|
|
666
|
+
private scopeAskDue(input: HookInput): boolean {
|
|
667
|
+
if (this.scope.mode !== "unset") return false;
|
|
668
|
+
if (this.observer) {
|
|
669
|
+
this.emit("adapter.scope.ask.skipped", { reason: "observer" });
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
if (input.sessionId.length === 0) return false;
|
|
673
|
+
try {
|
|
674
|
+
return readSession(this.counterpart.store.dir, input.sessionId)?.askedScope !== true;
|
|
675
|
+
} catch {
|
|
676
|
+
// A registry this cannot read is not a reason to ask twice OR to fail a
|
|
677
|
+
// hook; the quiet answer is the safe one.
|
|
678
|
+
return false;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Deliver the question, and remember that it was delivered. Returns the block
|
|
684
|
+
* to append, or the empty string when there was no room for it.
|
|
685
|
+
*/
|
|
686
|
+
private deliverScopeAsk(input: HookInput, wakeBytes: number, budget: number | undefined): string {
|
|
687
|
+
if (budget !== undefined && wakeBytes + SCOPE_ASK_BYTES > budget) {
|
|
688
|
+
this.emit("adapter.scope.ask.deferred", {
|
|
689
|
+
wakeBytes,
|
|
690
|
+
budget,
|
|
691
|
+
need: SCOPE_ASK_BYTES,
|
|
692
|
+
});
|
|
693
|
+
return "";
|
|
694
|
+
}
|
|
695
|
+
// The mark is a SECOND write of the same phase rather than a field folded
|
|
696
|
+
// into the first: the first write happens before the delivery verdict (a
|
|
697
|
+
// muted session still lives one) and the ask is decided after the wake, so
|
|
698
|
+
// one write cannot carry both facts without moving the other.
|
|
699
|
+
const marked = recordSession(this.counterpart.store.dir, {
|
|
700
|
+
sessionId: input.sessionId,
|
|
701
|
+
scope: input.scope,
|
|
702
|
+
phase: "start",
|
|
703
|
+
at: this.nowFn(),
|
|
704
|
+
askedScope: true,
|
|
705
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
706
|
+
? {}
|
|
707
|
+
: { config: this.configPath }),
|
|
708
|
+
});
|
|
709
|
+
this.emit("adapter.scope.ask", { bytes: SCOPE_ASK_BYTES, recorded: marked !== null });
|
|
710
|
+
return SCOPE_ASK;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* A NIGHT THAT WAS NOT OFFERED, written down where tomorrow can read it.
|
|
715
|
+
*
|
|
716
|
+
* A deferral claims nothing — that is what makes it a deferral — so before
|
|
717
|
+
* this it left only a ring event, which dies with the hook process. That is
|
|
718
|
+
* I32's shape on the newest mechanism in the tree: refused every morning,
|
|
719
|
+
* with nothing durable behind it (S2 review, MINOR-5). The row is `skipped`,
|
|
720
|
+
* which `pageWriterDue` is explicit about never treating as a claim, and it
|
|
721
|
+
* is deduped to ONE per date per reason so a ceiling that is too small every
|
|
722
|
+
* session leaves one line rather than forty.
|
|
723
|
+
*/
|
|
724
|
+
private noteWriterDeferred(about: string, reason: string): void {
|
|
725
|
+
try {
|
|
726
|
+
this.counterpart.recordPageWriterRun({
|
|
727
|
+
about,
|
|
728
|
+
mode: "session",
|
|
729
|
+
outcome: "skipped",
|
|
730
|
+
detail: reason,
|
|
731
|
+
dedupKey: `${SELF_PAGE_WRITER_EVENT}:deferred:${about}:${reason}`,
|
|
732
|
+
});
|
|
733
|
+
} catch {
|
|
734
|
+
/* a deferral that cannot be recorded is still a deferral (§5 G7) */
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* HOW MANY MORNINGS THE FIRST-LAUNCH QUESTION HAS TAKEN THE FIELD.
|
|
740
|
+
*
|
|
741
|
+
* The scope question wins the ask field, and on a blank store it is exactly
|
|
742
|
+
* what is pending on nights 1–3 — so the writer was starved for as long as
|
|
743
|
+
* nobody answered it, which on a store where nobody ever answers is forever
|
|
744
|
+
* (S2 review, MINOR-5). After `SCOPE_PATIENCE_DEFERRALS` deferrals the writer
|
|
745
|
+
* goes first instead: the scope question is advisory and comes back next
|
|
746
|
+
* session, while a night that passes is a day missing from the page for good.
|
|
747
|
+
*/
|
|
748
|
+
private writerStarvedByScope(): boolean {
|
|
749
|
+
try {
|
|
750
|
+
const runs = this.counterpart.pageWriterRuns({ limit: 64 });
|
|
751
|
+
// ONCE THE WRITER HAS BEEN ASKED, IT IS NOT STARVED, and the field goes
|
|
752
|
+
// back to the first-launch question. Without this the priority flipped
|
|
753
|
+
// permanently: the writer took both of the night's two asks and the scope
|
|
754
|
+
// question — which is the thing a person actually has to answer — stopped
|
|
755
|
+
// being raised at all.
|
|
756
|
+
if (runs.some((r) => r.outcome === "asked")) return false;
|
|
757
|
+
const deferred = runs.filter(
|
|
758
|
+
(r) => r.outcome === "skipped" && r.detail === "scope-question",
|
|
759
|
+
);
|
|
760
|
+
return deferred.length >= SCOPE_PATIENCE_DEFERRALS;
|
|
761
|
+
} catch {
|
|
762
|
+
return false;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* THE NIGHTLY PAGE WRITER'S ASK, in `session` mode — build it, check it fits,
|
|
768
|
+
* claim the day, and hand it back. Returns the block, or the empty string.
|
|
769
|
+
*
|
|
770
|
+
* `standDownOnly` is for the pass where the first-launch question took the
|
|
771
|
+
* field: the verdict is still computed and the deferral still leaves a ring
|
|
772
|
+
* event, so "why was I not asked" is answerable, but nothing is claimed and
|
|
773
|
+
* nothing is recorded — a day that was never offered must stay owed.
|
|
774
|
+
*
|
|
775
|
+
* **The whole body is fail-open.** A writer that cannot be composed costs the
|
|
776
|
+
* ASK and never the wake (§1 G7): every throw below lands in the catch, the
|
|
777
|
+
* session gets its bundle, and the ring says which step gave up.
|
|
778
|
+
*/
|
|
779
|
+
private deliverPageWriterAsk(
|
|
780
|
+
input: HookInput,
|
|
781
|
+
wakeBytes: number,
|
|
782
|
+
budget: number | undefined,
|
|
783
|
+
standDownOnly: boolean,
|
|
784
|
+
): string {
|
|
785
|
+
try {
|
|
786
|
+
const mode = pageWriterMode(this.config);
|
|
787
|
+
// SESSION MODE ONLY. In `host` mode the night is run by a windowless
|
|
788
|
+
// child the worker starts — and that child's own SessionStart hook runs
|
|
789
|
+
// this same code, so without this line the writer would be asked to
|
|
790
|
+
// write inside the session that was started to do the writing.
|
|
791
|
+
if (mode !== "session") return "";
|
|
792
|
+
const due = this.counterpart.pageWriterDue({ mode });
|
|
793
|
+
if (!due.due) {
|
|
794
|
+
// `already-claimed` and `no-previous-day` are the ordinary answers on
|
|
795
|
+
// most mornings; emitting a line for each of them at every session
|
|
796
|
+
// start is how a ring becomes unreadable. Only the two that mean
|
|
797
|
+
// something stood the mechanism down get one.
|
|
798
|
+
if (due.reason === "off" || due.reason === "asks-spent") {
|
|
799
|
+
this.emit("adapter.page.writer.skipped", { reason: due.reason, about: due.about });
|
|
800
|
+
}
|
|
801
|
+
return "";
|
|
802
|
+
}
|
|
803
|
+
if (input.sessionId.length === 0) return "";
|
|
804
|
+
// ALREADY ASKED, IN THIS SESSION. `noteSession("start")` has already run
|
|
805
|
+
// by the time this is called and it rewrites the record whole — but it
|
|
806
|
+
// CARRIES `pageWriterFor` forward, the way it carries `config`, so the
|
|
807
|
+
// mark a previous SessionStart in this same session left is still here.
|
|
808
|
+
// A compaction re-firing SessionStart must not re-ask.
|
|
809
|
+
const record = readSession(this.counterpart.store.dir, input.sessionId);
|
|
810
|
+
if (record?.pageWriterFor === due.about) return "";
|
|
811
|
+
if (standDownOnly) {
|
|
812
|
+
this.emit("adapter.page.writer.deferred", { reason: "scope-question", about: due.about });
|
|
813
|
+
this.noteWriterDeferred(due.about, "scope-question");
|
|
814
|
+
return "";
|
|
815
|
+
}
|
|
816
|
+
const framing = { tool: PAGE_WRITER_TOOL, session: input.sessionId };
|
|
817
|
+
// SIZE THE DAY TO THE ROOM THE WAKE LEFT, rather than composing what the
|
|
818
|
+
// tunable allows and then discovering it does not fit.
|
|
819
|
+
//
|
|
820
|
+
// The wake already carries the page — which is why the block does not
|
|
821
|
+
// repeat it (`self/writer.ts`) — and what is left over varies with the
|
|
822
|
+
// day: on a busy one the memories alone are 8 KB against a ceiling a real
|
|
823
|
+
// wake has already spent most of. Composing the whole tunable and
|
|
824
|
+
// deferring on the total would defer EVERY morning once a store is a few
|
|
825
|
+
// days old, and the only trace would be a ring event that dies with this
|
|
826
|
+
// process, which is I32's shape exactly.
|
|
827
|
+
//
|
|
828
|
+
// So the empty block is measured first — it is the same function with no
|
|
829
|
+
// memories in it, so the two cannot drift — and the day gets whatever is
|
|
830
|
+
// left. A day that could not all fit is delivered SHORT, with `dropped`
|
|
831
|
+
// counted on the run's row; only a block whose own furniture will not fit
|
|
832
|
+
// is deferred.
|
|
833
|
+
//
|
|
834
|
+
// **MEASURED AFTER COMPOSING, not predicted before it** (S2 review,
|
|
835
|
+
// MINOR-1). The estimate was the empty block, which takes the "nothing was
|
|
836
|
+
// written down" branch; the delivered one takes a longer header, a framing
|
|
837
|
+
// line and `3 + len` per bullet against a budget charged at 16 + len. The
|
|
838
|
+
// difference put the composition up to 20 bytes over the host's reported
|
|
839
|
+
// ceiling. So the estimate only SIZES the day, and the real bytes are
|
|
840
|
+
// checked afterwards — one extra composition on a path that already
|
|
841
|
+
// composes twice, and the ceiling becomes a fact instead of an argument.
|
|
842
|
+
const empty = this.counterpart.pageWriterInput({ about: due.about, budgetBytes: 0 });
|
|
843
|
+
const overhead = writerInstructionOverhead(empty, framing) + ASK_SEPARATOR_BYTES;
|
|
844
|
+
const roomFor = (spent: number): number =>
|
|
845
|
+
budget === undefined
|
|
846
|
+
? SELF_TUNABLES.PAGE_WRITER_MEMORY_BYTES
|
|
847
|
+
: Math.min(SELF_TUNABLES.PAGE_WRITER_MEMORY_BYTES, budget - wakeBytes - spent);
|
|
848
|
+
const defer = (need: number): string => {
|
|
849
|
+
// DEFERRED, never truncated and never smuggled past the ceiling — the
|
|
850
|
+
// same rule the scope question follows. The day is left unclaimed, so
|
|
851
|
+
// the next session in any directory is offered it instead.
|
|
852
|
+
this.emit("adapter.page.writer.deferred", {
|
|
853
|
+
reason: "no-room",
|
|
854
|
+
about: due.about,
|
|
855
|
+
wakeBytes,
|
|
856
|
+
budget: budget ?? 0,
|
|
857
|
+
need,
|
|
858
|
+
});
|
|
859
|
+
this.noteWriterDeferred(due.about, "no-room");
|
|
860
|
+
return "";
|
|
861
|
+
};
|
|
862
|
+
if (roomFor(overhead) < 0) return defer(overhead);
|
|
863
|
+
let built = this.counterpart.pageWriterInput({
|
|
864
|
+
about: due.about,
|
|
865
|
+
budgetBytes: roomFor(overhead),
|
|
866
|
+
});
|
|
867
|
+
let text = writerInstruction(built, framing);
|
|
868
|
+
let bytes = Buffer.byteLength(`\n\n${text}`, "utf8");
|
|
869
|
+
if (budget !== undefined && wakeBytes + bytes > budget) {
|
|
870
|
+
// One re-composition, against the room the FIRST attempt proved was
|
|
871
|
+
// really left. It cannot loop: the second budget is smaller than what
|
|
872
|
+
// the first composition actually spent on memories, so the second block
|
|
873
|
+
// is strictly shorter.
|
|
874
|
+
const over = wakeBytes + bytes - budget;
|
|
875
|
+
const second = roomFor(overhead + over);
|
|
876
|
+
if (second < 0) return defer(bytes);
|
|
877
|
+
built = this.counterpart.pageWriterInput({ about: due.about, budgetBytes: second });
|
|
878
|
+
text = writerInstruction(built, framing);
|
|
879
|
+
bytes = Buffer.byteLength(`\n\n${text}`, "utf8");
|
|
880
|
+
// Still over after the retry — only reachable when the block's own
|
|
881
|
+
// furniture is the thing that does not fit — and then it is deferred
|
|
882
|
+
// rather than delivered over the ceiling.
|
|
883
|
+
if (wakeBytes + bytes > budget) return defer(bytes);
|
|
884
|
+
}
|
|
885
|
+
// A BLOCK THAT CAN CARRY NONE OF THE DAY IS NOT WORTH A NIGHT'S CLAIM
|
|
886
|
+
// (S2 review, MAJOR-1, the other half). The text is honest about it now —
|
|
887
|
+
// it says "I could not see the day" rather than "the day was empty" — but
|
|
888
|
+
// spending one of two asks on a block whose only content is that sentence
|
|
889
|
+
// is worse than leaving the night owed for a session with more room.
|
|
890
|
+
if (built.memories.length === 0 && built.dropped > 0) return defer(bytes);
|
|
891
|
+
// THE CLAIM, and it is durable rather than a flag on this session: two
|
|
892
|
+
// boundaries, or two machines' worth of hooks against one store, must not
|
|
893
|
+
// both set a night going. It is written BEFORE the text is handed over,
|
|
894
|
+
// so a crash between the two costs one day's revision rather than an
|
|
895
|
+
// unbounded re-ask (the same order `openChapter` commits in).
|
|
896
|
+
const claimed = this.counterpart.recordPageWriterRun({
|
|
897
|
+
about: due.about,
|
|
898
|
+
mode: "session",
|
|
899
|
+
outcome: "asked",
|
|
900
|
+
detail:
|
|
901
|
+
`attempt ${String(due.attempt)}` +
|
|
902
|
+
(built.dropped > 0 ? `; ${String(built.dropped)} of the day did not fit the wake's ceiling` : ""),
|
|
903
|
+
bytesBefore: built.page?.bytes ?? 0,
|
|
904
|
+
considered: built.memories.length,
|
|
905
|
+
omitted: built.omitted,
|
|
906
|
+
});
|
|
907
|
+
const marked = recordSession(this.counterpart.store.dir, {
|
|
908
|
+
sessionId: input.sessionId,
|
|
909
|
+
scope: input.scope,
|
|
910
|
+
phase: "start",
|
|
911
|
+
at: this.nowFn(),
|
|
912
|
+
pageWriterFor: due.about,
|
|
913
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
914
|
+
? {}
|
|
915
|
+
: { config: this.configPath }),
|
|
916
|
+
});
|
|
917
|
+
this.emit("adapter.page.writer.ask", {
|
|
918
|
+
about: due.about,
|
|
919
|
+
attempt: due.attempt,
|
|
920
|
+
bytes,
|
|
921
|
+
considered: built.memories.length,
|
|
922
|
+
dropped: built.dropped,
|
|
923
|
+
omitted: built.omitted,
|
|
924
|
+
claimed,
|
|
925
|
+
recorded: marked !== null,
|
|
926
|
+
});
|
|
927
|
+
return text;
|
|
928
|
+
} catch (err) {
|
|
929
|
+
this.emit("adapter.page.writer.failed", {
|
|
930
|
+
code: err instanceof Error ? err.name : "UNKNOWN",
|
|
931
|
+
});
|
|
932
|
+
return "";
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// ── the turn ───────────────────────────────────────────────────────────────
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Recall for this turn. The check that the SESSION'S WAKE ARRIVED runs first,
|
|
940
|
+
* once per session (scar §2.3), then the composed recall — all three borrowed
|
|
941
|
+
* channels bound by the composition root, with today's date so the temporal
|
|
942
|
+
* channel exists.
|
|
943
|
+
*/
|
|
944
|
+
userPromptSubmit(input: HookInput): HookResult {
|
|
945
|
+
return this.guard("user-prompt-submit", input, (out) => {
|
|
946
|
+
// The stand-down precedes the delivery check for the same reason it
|
|
947
|
+
// precedes the recall: a muted session rendered nothing, so there is no
|
|
948
|
+
// expectation to test and a "not delivered" record would be a lie.
|
|
949
|
+
if (!this.deliveryVerdict("user-prompt-submit", input)) {
|
|
950
|
+
return { ...out, ok: true, reason: "primacy-standdown" };
|
|
951
|
+
}
|
|
952
|
+
this.checkWakeArrival(input);
|
|
953
|
+
const text = input.prompt ?? "";
|
|
954
|
+
if (text.trim().length === 0) {
|
|
955
|
+
return { ...out, ok: true, reason: "empty-prompt" };
|
|
956
|
+
}
|
|
957
|
+
const result = this.counterpart.recallForTurn(
|
|
958
|
+
{
|
|
959
|
+
sessionId: input.sessionId,
|
|
960
|
+
text,
|
|
961
|
+
...(this.config.injectionBudgetBytes === undefined
|
|
962
|
+
? {}
|
|
963
|
+
: { budgetBytes: this.config.injectionBudgetBytes }),
|
|
964
|
+
},
|
|
965
|
+
{ ...(input.at === undefined ? {} : { at: input.at }) },
|
|
966
|
+
);
|
|
967
|
+
const decision = result.decision;
|
|
968
|
+
// The recall block states its own sentinel too, and nothing checks it: the
|
|
969
|
+
// line that used to hold it was the same dead `Map` the wake's expectation
|
|
970
|
+
// lived in. A recall-arrival check would need the same shape as the wake's
|
|
971
|
+
// — a persisted expectation and a turn-scoped read — and is an open ask
|
|
972
|
+
// (INTERFACE-GAPS §11), not a thing this row can pretend to.
|
|
973
|
+
this.record(RECALL_DELIVERED_EVENT, input, {
|
|
974
|
+
reason: decision.reason,
|
|
975
|
+
surfaced: decision.surfaced.length,
|
|
976
|
+
footnotes: decision.footnotes.length,
|
|
977
|
+
bytes: decision.bytes,
|
|
978
|
+
budget: decision.budgetBytes,
|
|
979
|
+
observer: decision.observer,
|
|
980
|
+
// WHERE the semantic channel's input came from, on the row a coverage
|
|
981
|
+
// watch can read out of the store tomorrow. `semantic: "none"` on every
|
|
982
|
+
// real turn is exactly the finding this PR closes; anything but
|
|
983
|
+
// "lagged" here after a worker ran is the lag failing, by name.
|
|
984
|
+
semantic: decision.semanticSource,
|
|
985
|
+
semanticFrom: decision.semanticFromTurn,
|
|
986
|
+
});
|
|
987
|
+
return {
|
|
988
|
+
...out,
|
|
989
|
+
ok: true,
|
|
990
|
+
reason: decision.reason,
|
|
991
|
+
injection: result.injection,
|
|
992
|
+
bytes: decision.bytes,
|
|
993
|
+
sentinel: decision.sentinel,
|
|
994
|
+
// The footnote tier is carried SEPARATELY from the loud one, because the
|
|
995
|
+
// two mean different things to reinforcement: a footnote trains nothing.
|
|
996
|
+
surfaced: decision.surfaced,
|
|
997
|
+
footnotes: decision.footnotes,
|
|
998
|
+
};
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// ── the boundary, and the three paths that reach it ────────────────────────
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* THE APPENDER. Microseconds, no model call, no judgment — and it cannot throw
|
|
1006
|
+
* into the host, because `SpanBuffer.capture` swallows its own failures and
|
|
1007
|
+
* `guard()` catches anything above it (§2 G1/G12).
|
|
1008
|
+
*/
|
|
1009
|
+
boundary(hook: SessionEndingHook, input: HookInput): HookResult {
|
|
1010
|
+
return this.guard(hook, input, (out) => this.claim(hook, input, out));
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* Stop: the boundary, then the ONE ask, then the detached worker.
|
|
1015
|
+
*
|
|
1016
|
+
* Order matters. The spans are durable before anything else is attempted, so a
|
|
1017
|
+
* crash between here and the worker costs a run, never a day. The ask's state
|
|
1018
|
+
* advance is committed inside `self.openChapter` BEFORE the ask is handed
|
|
1019
|
+
* back, so a crash cannot re-ask in a loop (§13 G3–G4); and any failure in the
|
|
1020
|
+
* ask is fail-open — collection never depends on the ritual (§13 G5).
|
|
1021
|
+
*/
|
|
1022
|
+
stop(input: HookInput): HookResult {
|
|
1023
|
+
return this.guard("stop", input, (out) => {
|
|
1024
|
+
const claimed = this.claim("stop", input, out);
|
|
1025
|
+
// The clock the lazy bind reads, refreshed BEFORE the ask that names this
|
|
1026
|
+
// session id goes out: the id has to be live by the time the model reads
|
|
1027
|
+
// it, and a session already running when this shipped never saw a
|
|
1028
|
+
// SessionStart write — so this is also where it first becomes bindable.
|
|
1029
|
+
this.noteSession("boundary", input);
|
|
1030
|
+
// The boundary is UNCONDITIONAL — the shadow encodes the same days v1
|
|
1031
|
+
// encodes, and a parallel run that stopped capturing would be comparing
|
|
1032
|
+
// nothing (parallel-run G5: encode-only, and honest). What the stand-down
|
|
1033
|
+
// withholds is the ASK, which is delivery: an ask from a system the
|
|
1034
|
+
// owner is not talking to today is exactly the double-voice G3 forbids.
|
|
1035
|
+
const deliver = this.deliveryVerdict("stop", input);
|
|
1036
|
+
// THE AUTHORED FRONT DOOR, first: the experiencer writes its own memories
|
|
1037
|
+
// while it still has the pen, and the sweep the worker spawns below is
|
|
1038
|
+
// only the fallback for the day nobody got to (contract §4). The ask goes
|
|
1039
|
+
// out after the spans are durable, so a crash between the two costs a
|
|
1040
|
+
// dump, never a day.
|
|
1041
|
+
//
|
|
1042
|
+
// The worker below still spawns at EVERY boundary — it carries the
|
|
1043
|
+
// Hebbian flush and the sleep cycle, which are not optional — but since
|
|
1044
|
+
// 2026-09-04 its sweep step selects nothing unless a session is CRASHED
|
|
1045
|
+
// (`remember/fallback.ts`: uncovered spans, no `session-end` boundary,
|
|
1046
|
+
// silent past `CRASH_STALE_MS`). Before that gate this line was a comment
|
|
1047
|
+
// the code did not keep: one evening's Stops billed 13 chunks and minted
|
|
1048
|
+
// 61 memories beside 34 the model had authored itself.
|
|
1049
|
+
const ask = deliver ? this.askAtStop(input) : null;
|
|
1050
|
+
const spawn = this.spawnWorker(input);
|
|
1051
|
+
return { ...claimed, ask, spawn };
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/** The host closing the session: a boundary, the tail measurement, a worker. */
|
|
1056
|
+
sessionEnd(input: HookInput): HookResult {
|
|
1057
|
+
return this.guard("session-end", input, (out) => {
|
|
1058
|
+
const claimed = this.claim("session-end", input, out);
|
|
1059
|
+
// One tiny rename, inside the 1.5 s this event's hooks share. It closes
|
|
1060
|
+
// the session to any later claim: a dump arriving after this is the
|
|
1061
|
+
// sweep's job, not the experiencer's.
|
|
1062
|
+
this.noteSession("end", input);
|
|
1063
|
+
this.noteTail(input);
|
|
1064
|
+
return { ...claimed, spawn: this.spawnWorker(input) };
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Pre-compaction: the transcript is about to be destroyed. This is the
|
|
1070
|
+
* compaction-amnesia backstop, and it is why the boundary list has three
|
|
1071
|
+
* members instead of one.
|
|
1072
|
+
*/
|
|
1073
|
+
preCompact(input: HookInput): HookResult {
|
|
1074
|
+
return this.guard("pre-compact", input, (out) => {
|
|
1075
|
+
const claimed = this.claim("pre-compact", input, out);
|
|
1076
|
+
this.noteTail(input);
|
|
1077
|
+
return claimed;
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/** Dispatch by name — what the entry script calls, and what the totality test walks. */
|
|
1082
|
+
hook(name: HookName, input: HookInput): HookResult {
|
|
1083
|
+
switch (name) {
|
|
1084
|
+
case "session-start":
|
|
1085
|
+
return this.sessionStart(input);
|
|
1086
|
+
case "user-prompt-submit":
|
|
1087
|
+
return this.userPromptSubmit(input);
|
|
1088
|
+
case "stop":
|
|
1089
|
+
return this.stop(input);
|
|
1090
|
+
case "session-end":
|
|
1091
|
+
return this.sessionEnd(input);
|
|
1092
|
+
case "pre-compact":
|
|
1093
|
+
return this.preCompact(input);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* MAY THIS HOOK DELIVER? — the parallel run's G3, at every delivering channel.
|
|
1101
|
+
*
|
|
1102
|
+
* Without the knob this is `true` and nothing is emitted at all: the flag's
|
|
1103
|
+
* absence must be indistinguishable from a build that never had it, or every
|
|
1104
|
+
* test and every ordinary session grows a primacy record it cannot explain.
|
|
1105
|
+
*
|
|
1106
|
+
* With the knob, `primacy()` decides and BOTH verdicts are recorded — the
|
|
1107
|
+
* stand-down because an unevidenced mute is indistinguishable from a broken
|
|
1108
|
+
* hook (parallel-run G4, scar §2.4), and the delivery because a Phase P day
|
|
1109
|
+
* has to be able to show positive evidence that v2 spoke. Each record goes to
|
|
1110
|
+
* the ring AND to box 2, because the ring dies with the hook process and the
|
|
1111
|
+
* daily count is a claim about the run.
|
|
1112
|
+
*
|
|
1113
|
+
* `date` rides in the durable payload deliberately: the log's `day` column is
|
|
1114
|
+
* the store's LIVED day, which only the heavy cycle advances, so a hook-path
|
|
1115
|
+
* row would stamp whatever lived day the store was already on.
|
|
1116
|
+
*/
|
|
1117
|
+
private deliveryVerdict(hook: HookName, input: HookInput): boolean {
|
|
1118
|
+
if (this.config.parallel?.enabled !== true) return true;
|
|
1119
|
+
const verdict = primacy();
|
|
1120
|
+
const name = verdict.deliver ? PRIMACY_DELIVER_EVENT : PRIMACY_STANDDOWN_EVENT;
|
|
1121
|
+
const data = {
|
|
1122
|
+
hook,
|
|
1123
|
+
reason: verdict.reason,
|
|
1124
|
+
system: verdict.system,
|
|
1125
|
+
date: input.at ?? null,
|
|
1126
|
+
session: input.sessionId,
|
|
1127
|
+
};
|
|
1128
|
+
this.emit(name, data);
|
|
1129
|
+
this.counterpart.noteAdapterEvent(name, data);
|
|
1130
|
+
return verdict.deliver;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* A DELIVERY record: to the ring and to box 2, with the calendar date and the
|
|
1135
|
+
* session riding in the payload for the same reason `deliveryVerdict` puts
|
|
1136
|
+
* them there — the store's `day` column is the lived day, and the parallel
|
|
1137
|
+
* run counts these per calendar day, per session, after the process is gone.
|
|
1138
|
+
*/
|
|
1139
|
+
private record(
|
|
1140
|
+
name: AdapterDurableEventName,
|
|
1141
|
+
input: HookInput,
|
|
1142
|
+
data: Record<string, string | number | boolean | null>,
|
|
1143
|
+
): void {
|
|
1144
|
+
const row = { ...data, date: input.at ?? null, session: input.sessionId };
|
|
1145
|
+
this.emit(name, row);
|
|
1146
|
+
this.counterpart.noteAdapterEvent(name, row);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* Capture and record the boundary. ONE function for all three paths, so a
|
|
1151
|
+
* fourth session-ending event added later cannot accidentally get a different
|
|
1152
|
+
* shape (G3).
|
|
1153
|
+
*/
|
|
1154
|
+
private claim(hook: SessionEndingHook, input: HookInput, out: HookResult): HookResult {
|
|
1155
|
+
const turns = input.turns ?? [];
|
|
1156
|
+
// THE STRETCH THIS MEMORY WAS TOLD NOT TO HAVE, sealed before anything is
|
|
1157
|
+
// captured. After a `sealed` the ordinary capture below reads NOTHING_NEW;
|
|
1158
|
+
// after a `failed` it does not run at all, because a cursor that would not
|
|
1159
|
+
// move is a boundary with no way to tell what is new from what was lived
|
|
1160
|
+
// outside this memory — and an append lands before a cursor write does.
|
|
1161
|
+
const seal = this.sealJoinedLate(hook, input, turns);
|
|
1162
|
+
// G10/G11 computed side by side: capture takes EVERYTHING conversational
|
|
1163
|
+
// including host-injected context; pacing counts only what the user said.
|
|
1164
|
+
const captured: CaptureResult =
|
|
1165
|
+
seal === "failed"
|
|
1166
|
+
? {
|
|
1167
|
+
captured: false,
|
|
1168
|
+
reason: "IO_FAILED",
|
|
1169
|
+
spans: [],
|
|
1170
|
+
deduped: 0,
|
|
1171
|
+
excluded: turns.length,
|
|
1172
|
+
cursorBefore: 0,
|
|
1173
|
+
cursorAfter: 0,
|
|
1174
|
+
}
|
|
1175
|
+
: this.counterpart.captureSpans({
|
|
1176
|
+
session: input.sessionId,
|
|
1177
|
+
scope: input.scope,
|
|
1178
|
+
turns,
|
|
1179
|
+
});
|
|
1180
|
+
const record = this.counterpart.boundary({
|
|
1181
|
+
session: input.sessionId,
|
|
1182
|
+
scope: input.scope,
|
|
1183
|
+
kind: BOUNDARY_KIND[hook],
|
|
1184
|
+
});
|
|
1185
|
+
// Reference resolution (recall §9.2) over the SAME slice capture just took:
|
|
1186
|
+
// the cursor is the one authority on what is new, for credit as for spans.
|
|
1187
|
+
this.creditAtBoundary(input, captured.cursorBefore, captured.cursorAfter);
|
|
1188
|
+
this.record(BOUNDARY_EVENT, input, {
|
|
1189
|
+
hook,
|
|
1190
|
+
kind: record.kind,
|
|
1191
|
+
captured: captured.captured,
|
|
1192
|
+
reason: captured.reason,
|
|
1193
|
+
spans: captured.spans.length,
|
|
1194
|
+
deduped: captured.deduped,
|
|
1195
|
+
excluded: captured.excluded,
|
|
1196
|
+
cursorBefore: captured.cursorBefore,
|
|
1197
|
+
cursorAfter: captured.cursorAfter,
|
|
1198
|
+
ask: record.askRaised,
|
|
1199
|
+
// The DURABLE half of `adapter.scope.joined-late`: the boundary row is
|
|
1200
|
+
// the one durable name a boundary already has, and this is a fact about
|
|
1201
|
+
// THIS boundary. A row that says `joinedLate: true, captured: false` is
|
|
1202
|
+
// the whole evidence that a stretch was sealed rather than lost.
|
|
1203
|
+
joinedLate: seal !== "none",
|
|
1204
|
+
});
|
|
1205
|
+
return { ...out, ok: true, reason: captured.reason, spansAppended: captured.spans.length };
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* THE RETROACTIVE-CAPTURE GUARD (PR #92 review, F1) — the one place a
|
|
1210
|
+
* directory that was `off` can still lose its silence.
|
|
1211
|
+
*
|
|
1212
|
+
* A session that lived under `off` or `paused` wrote NOTHING: no session
|
|
1213
|
+
* record, because the hook process returned before a store was opened, and no
|
|
1214
|
+
* span cursor for the same reason. Turn the directory back on mid-session —
|
|
1215
|
+
* `counterparts scope . --resume`, or the `scope` tool, which is deliberately
|
|
1216
|
+
* the one tool that answers in an off directory — and the next boundary sees
|
|
1217
|
+
* a cursor of 0 against a transcript holding the WHOLE off conversation. It
|
|
1218
|
+
* would deposit all of it. Measured on this branch before this guard: six
|
|
1219
|
+
* marker hits in the buffer after the flip.
|
|
1220
|
+
*
|
|
1221
|
+
* So a boundary that finds NO SESSION RECORD and a cursor still at 0 treats
|
|
1222
|
+
* the stretch as somebody else's: it advances the cursor to the end of what
|
|
1223
|
+
* it can see, deposits nothing, and records that it did. What follows the
|
|
1224
|
+
* flip is captured normally, because the cursor now starts there.
|
|
1225
|
+
*
|
|
1226
|
+
* **How the cursor moves without a deposit.** `SpanBuffer.capture` advances
|
|
1227
|
+
* to `turns.length` when nothing in the slice is capture-eligible
|
|
1228
|
+
* (`remember/spans.ts`, the ALL_EXCLUDED arm: "still advance, or the same
|
|
1229
|
+
* tool output is re-scanned forever"). So the seal hands it `turns.length`
|
|
1230
|
+
* PLACEHOLDERS whose source is `tool` — `enters()` refuses them — and the
|
|
1231
|
+
* real turns are never passed to the core at all. That is the only
|
|
1232
|
+
* adapter-reachable way to set a cursor today; a `SpanBuffer.sealCursor` in
|
|
1233
|
+
* core would be the honest one, and is named in the PR as a core ask.
|
|
1234
|
+
*
|
|
1235
|
+
* Three conditions, each load-bearing:
|
|
1236
|
+
* - **not an observer**: an observer captures nothing and writes no session
|
|
1237
|
+
* record anyway, and a cursor it cannot write would make the seal a lie.
|
|
1238
|
+
* An `off → observer → on` session is therefore still sealed at the first
|
|
1239
|
+
* boundary after it reaches `on` — the observer stretch left no record.
|
|
1240
|
+
* - **no session record**: the positive evidence that SessionStart ran
|
|
1241
|
+
* inside this memory. It is what a live session has and an off one does not.
|
|
1242
|
+
* - **cursor still 0**: a record PRUNED out from under a long-lived session
|
|
1243
|
+
* (seven days, `sessions.ts`) leaves a cursor behind; that session has
|
|
1244
|
+
* been captured all along and must not lose the turns since its last
|
|
1245
|
+
* boundary.
|
|
1246
|
+
*/
|
|
1247
|
+
private sealJoinedLate(
|
|
1248
|
+
hook: SessionEndingHook,
|
|
1249
|
+
input: HookInput,
|
|
1250
|
+
turns: readonly HostTurn[],
|
|
1251
|
+
): "none" | "sealed" | "failed" {
|
|
1252
|
+
if (this.observer) return "none";
|
|
1253
|
+
if (input.sessionId.length === 0) return "none";
|
|
1254
|
+
try {
|
|
1255
|
+
if (readSession(this.counterpart.store.dir, input.sessionId) !== null) return "none";
|
|
1256
|
+
if (this.counterpart.spans.cursor(input.scope, input.sessionId) !== 0) return "none";
|
|
1257
|
+
} catch {
|
|
1258
|
+
// A registry or a cursor this cannot read is not a reason to fail a hook
|
|
1259
|
+
// (§5 G2). The quiet answer here is the ordinary path.
|
|
1260
|
+
return "none";
|
|
1261
|
+
}
|
|
1262
|
+
const placeholders: CapturedTurn[] = turns.map(() => ({
|
|
1263
|
+
role: "user",
|
|
1264
|
+
text: "",
|
|
1265
|
+
source: "tool",
|
|
1266
|
+
}));
|
|
1267
|
+
const sealed = this.counterpart.captureSpans({
|
|
1268
|
+
session: input.sessionId,
|
|
1269
|
+
scope: input.scope,
|
|
1270
|
+
turns: placeholders,
|
|
1271
|
+
});
|
|
1272
|
+
const moved = sealed.cursorAfter === turns.length;
|
|
1273
|
+
this.emit(SCOPE_JOINED_LATE_EVENT, {
|
|
1274
|
+
hook,
|
|
1275
|
+
mode: this.scope.mode,
|
|
1276
|
+
turns: turns.length,
|
|
1277
|
+
cursor: sealed.cursorAfter,
|
|
1278
|
+
sealed: moved,
|
|
1279
|
+
reason: sealed.reason,
|
|
1280
|
+
});
|
|
1281
|
+
// THE ORDER IS THE SAFETY. The cursor moves first and the session record is
|
|
1282
|
+
// written only if it did: a record written beside a cursor that stayed at 0
|
|
1283
|
+
// would make the NEXT boundary read this session as an ordinary one and
|
|
1284
|
+
// deposit the whole off stretch after all. A seal that could not move the
|
|
1285
|
+
// cursor leaves no record either, so the next boundary tries again.
|
|
1286
|
+
if (!moved) return "failed";
|
|
1287
|
+
// The session becomes bindable HERE, at the first boundary inside the
|
|
1288
|
+
// memory — `pre-compact` never calls `noteSession`, and a session with no
|
|
1289
|
+
// record is a session the MCP tools refuse.
|
|
1290
|
+
this.noteSession("boundary", input);
|
|
1291
|
+
return "sealed";
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* THE ONE ASK, ON ONE PACER, fail-open: an error in the ritual never costs the
|
|
1296
|
+
* collection (§13 G5).
|
|
1297
|
+
*
|
|
1298
|
+
* What changed on 2026-09-04, and why:
|
|
1299
|
+
*
|
|
1300
|
+
* - **One pacer.** The authorship ask paced itself on turns-and-bytes since
|
|
1301
|
+
* its own last ask; the episode ask paced itself on the chapter rule. They
|
|
1302
|
+
* fired on different Stops, so the model was asked about a dozen times in
|
|
1303
|
+
* one 13-turn evening. `episodeAsk` is now the only pacer, and its verdict
|
|
1304
|
+
* decides whether this Stop says anything at all.
|
|
1305
|
+
* - **The coverage read stays, as a RECORD and not a gate.** It measures
|
|
1306
|
+
* rather than assumes (§2 G12) and it puts the unaskable tail on the
|
|
1307
|
+
* record as a number instead of a hope; what it must not do is add a
|
|
1308
|
+
* second condition to a single ask.
|
|
1309
|
+
* - **The re-fired Stop asks nothing and advances nothing.**
|
|
1310
|
+
*/
|
|
1311
|
+
/**
|
|
1312
|
+
* THE CREDIT SEAM — the consumer recall INTERFACE-GAPS §5 said had no home.
|
|
1313
|
+
*
|
|
1314
|
+
* Assistant `conversation` turns and deliberate-recall calls from the new
|
|
1315
|
+
* slice go to `Counterpart.creditReferences`, which decides (`reference.ts`)
|
|
1316
|
+
* and credits (`resolveUses`). One durable row per boundary, `recall.credit`,
|
|
1317
|
+
* with a `reason` the daily's readers split on: `credited` is the signal the
|
|
1318
|
+
* `memory.reinforced` watch turns green on; `failed` and `budget-exceeded`
|
|
1319
|
+
* are the ones to alarm on. A boundary that credits nothing still leaves its
|
|
1320
|
+
* row (`nothing-to-credit` / `no-candidates`) — silence must never masquerade
|
|
1321
|
+
* as health, and a seam that only wrote rows when it worked would be the ring
|
|
1322
|
+
* this repo already learned from (I32).
|
|
1323
|
+
*
|
|
1324
|
+
* Never fails the boundary: telemetry may not fail the host (§1 G7), and a
|
|
1325
|
+
* credit that could not be decided is a `failed` row, not a lost capture.
|
|
1326
|
+
*/
|
|
1327
|
+
private creditAtBoundary(input: HookInput, from: number, to: number): void {
|
|
1328
|
+
const started = this.nowFn();
|
|
1329
|
+
// Read before the try: the failed row carries the day too.
|
|
1330
|
+
const day = this.counterpart.store.livedDay();
|
|
1331
|
+
const turns = input.turns ?? [];
|
|
1332
|
+
const slice = turns.slice(Math.max(0, from), Math.max(from, to));
|
|
1333
|
+
const assistantTurns = slice
|
|
1334
|
+
.filter((t) => t.role === "assistant" && (t.source === undefined || t.source === "conversation"))
|
|
1335
|
+
.map((t) => t.text);
|
|
1336
|
+
// Half-open on the left: a call positioned AT `from` sat before the first
|
|
1337
|
+
// new turn and belonged to the previous slice, which already judged it.
|
|
1338
|
+
const raw = (input.expansions ?? [])
|
|
1339
|
+
.filter((e) => e.atTurn > from && e.atTurn <= to)
|
|
1340
|
+
.flatMap((e) => [...e.ids]);
|
|
1341
|
+
// G50: a handle the recall tool RESOLVED becomes the id it resolved to.
|
|
1342
|
+
// The transcript still decides WHICH handles and WHEN; what it cannot say is
|
|
1343
|
+
// whose answer resolved them, so the translation is filtered to THIS
|
|
1344
|
+
// PROJECT's resolutions — the same `sameScope` comparison the MCP server
|
|
1345
|
+
// already trusts to bind a session. Without it the log hands this boundary
|
|
1346
|
+
// the last answer anyone anywhere got, including the owner's resolution of a
|
|
1347
|
+
// confidential memory this session was refused (or never asked for at all).
|
|
1348
|
+
// A handle nobody resolved in this scope still counts `unresolvedHandles`.
|
|
1349
|
+
//
|
|
1350
|
+
// The SECOND filter is this session's own start, out of the same registry
|
|
1351
|
+
// (`sessions.ts`): a project is a place, not a conversation, so one
|
|
1352
|
+
// directory's table also holds last week's answers, and a resolution
|
|
1353
|
+
// recorded before this session existed cannot be an answer to anything this
|
|
1354
|
+
// session asked. A session whose first hook event is this very Stop has no
|
|
1355
|
+
// record yet — `claim()` runs before `noteSession("boundary")` — and gets no
|
|
1356
|
+
// floor; that is under-credit's direction only in the sense that it does not
|
|
1357
|
+
// tighten, and it is the residual §9 records.
|
|
1358
|
+
//
|
|
1359
|
+
// The file is read only when there is something to translate — and the row
|
|
1360
|
+
// says which of those two it was. `resolvedHandles: 0` alone cannot tell an
|
|
1361
|
+
// idle table from a dead one, which is the exact shape of I32's failure.
|
|
1362
|
+
//
|
|
1363
|
+
// ALL OF IT INSIDE THE TRY. The first draft translated before the try, which
|
|
1364
|
+
// meant any throw on this path cost the boundary its row entirely — and a
|
|
1365
|
+
// seam that only writes rows when it works is the ring I32 is named for.
|
|
1366
|
+
// Only the `expansionsRead` declaration, which cannot throw, sits outside,
|
|
1367
|
+
// so the `failed` row can still say how far the read had got.
|
|
1368
|
+
let expansionsRead: ExpansionsRead | "not-read" = "not-read";
|
|
1369
|
+
try {
|
|
1370
|
+
let resolutions = new Map<string, string | null>();
|
|
1371
|
+
// Carried off the read rather than fetched again: the key a handle lands
|
|
1372
|
+
// on is the store's salt plus the handle (G58), and the two halves of one
|
|
1373
|
+
// lookup must not be able to disagree about which salt that was.
|
|
1374
|
+
let salt = "";
|
|
1375
|
+
if (raw.length > 0) {
|
|
1376
|
+
const dataDir = this.counterpart.store.dir;
|
|
1377
|
+
const sessionStartedAt = readSession(dataDir, input.sessionId)?.startedAt;
|
|
1378
|
+
const read = readHandleResolutions(dataDir, {
|
|
1379
|
+
now: this.nowFn(),
|
|
1380
|
+
scope: input.scope,
|
|
1381
|
+
...(sessionStartedAt === undefined ? {} : { since: sessionStartedAt }),
|
|
1382
|
+
});
|
|
1383
|
+
resolutions = read.map;
|
|
1384
|
+
salt = read.salt;
|
|
1385
|
+
expansionsRead = read.reason;
|
|
1386
|
+
}
|
|
1387
|
+
const resolvedHandles = countTranslated(raw, resolutions, salt);
|
|
1388
|
+
const expansions = translateExpansions(raw, resolutions, salt);
|
|
1389
|
+
const summary = this.counterpart.creditReferences(input.sessionId, {
|
|
1390
|
+
assistantTurns,
|
|
1391
|
+
expansions,
|
|
1392
|
+
deadline: started + TUNABLES.CREDIT_BUDGET_MS,
|
|
1393
|
+
now: this.nowFn,
|
|
1394
|
+
});
|
|
1395
|
+
this.emit(RECALL_CREDIT_EVENT, {
|
|
1396
|
+
reason: summary.reason,
|
|
1397
|
+
considered: summary.considered,
|
|
1398
|
+
expanded: summary.expanded,
|
|
1399
|
+
quoted: summary.quoted,
|
|
1400
|
+
credited: summary.credited,
|
|
1401
|
+
elapsedMs: this.nowFn() - started,
|
|
1402
|
+
});
|
|
1403
|
+
this.counterpart.noteAdapterEvent(RECALL_CREDIT_EVENT, {
|
|
1404
|
+
reason: summary.reason,
|
|
1405
|
+
session: input.sessionId,
|
|
1406
|
+
date: input.at ?? null,
|
|
1407
|
+
day: summary.day,
|
|
1408
|
+
turns: assistantTurns.length,
|
|
1409
|
+
considered: summary.considered,
|
|
1410
|
+
expanded: summary.expanded,
|
|
1411
|
+
quoted: summary.quoted,
|
|
1412
|
+
credited: summary.credited,
|
|
1413
|
+
unresolvedHandles: summary.unresolvedHandles,
|
|
1414
|
+
/** G50: expansions the handle-resolution log translated on the way in.
|
|
1415
|
+
* Beside `unresolvedHandles`, it is the pair that says whether a
|
|
1416
|
+
* by-title expansion earned credit or fell through the old gap. */
|
|
1417
|
+
resolvedHandles,
|
|
1418
|
+
/** WHY the log answered the way it did. `resolvedHandles: 0` on its own
|
|
1419
|
+
* cannot tell an idle table from an absent, unreadable or corrupt one,
|
|
1420
|
+
* and a number that cannot say which is how I32 stayed invisible.
|
|
1421
|
+
* `not-read` means this slice carried no expansion to translate. */
|
|
1422
|
+
expansionsRead,
|
|
1423
|
+
skippedForBudget: summary.skippedForBudget,
|
|
1424
|
+
unreadable: summary.unreadable,
|
|
1425
|
+
refused: summary.refused,
|
|
1426
|
+
ids: summary.ids.slice(0, 64),
|
|
1427
|
+
idsTotal: summary.ids.length,
|
|
1428
|
+
expandedIds: summary.expandedIds.slice(0, 64),
|
|
1429
|
+
expandedTotal: summary.expandedIds.length,
|
|
1430
|
+
elapsedMs: this.nowFn() - started,
|
|
1431
|
+
});
|
|
1432
|
+
} catch (err) {
|
|
1433
|
+
const code = codeOf(err);
|
|
1434
|
+
this.emit(RECALL_CREDIT_EVENT, { reason: "failed", code });
|
|
1435
|
+
this.counterpart.noteAdapterEvent(RECALL_CREDIT_EVENT, {
|
|
1436
|
+
reason: "failed",
|
|
1437
|
+
session: input.sessionId,
|
|
1438
|
+
date: input.at ?? null,
|
|
1439
|
+
day,
|
|
1440
|
+
code,
|
|
1441
|
+
turns: assistantTurns.length,
|
|
1442
|
+
// The RAW count: the translated list may not exist on this path, and a
|
|
1443
|
+
// translation is one-for-one anyway.
|
|
1444
|
+
expansions: raw.length,
|
|
1445
|
+
expansionsRead,
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
private askAtStop(input: HookInput): string | null {
|
|
1451
|
+
try {
|
|
1452
|
+
// The host's re-fire of a blocked Stop. Nothing is evaluated: no pacing
|
|
1453
|
+
// advance, no ask slot, no row — the previous pass already left one.
|
|
1454
|
+
if (input.reFired === true) return null;
|
|
1455
|
+
const substance = substanceOf(input.turns ?? []);
|
|
1456
|
+
// THE CAP IS THIS SESSION'S OWN, PER CALENDAR DAY (2026-09-17, amended
|
|
1457
|
+
// 2026-09-18), so nothing outside the session can spend it and a session
|
|
1458
|
+
// that spans days gets its allowance back with each one.
|
|
1459
|
+
//
|
|
1460
|
+
// It used to be the day's, four asks shared by every session a day held,
|
|
1461
|
+
// and that cap kept two failures alive. I32: the day was the LIVED day,
|
|
1462
|
+
// whose clock only the detached worker advances, so a worker that could
|
|
1463
|
+
// not start froze `self.episode.day.185 = 4` and the model was never
|
|
1464
|
+
// asked for a chapter again; keying it to `input.at` fixed the freeze but
|
|
1465
|
+
// not the sharing. Finding 12: with the owner running five or more
|
|
1466
|
+
// sessions a day, 196 of 264 Stops were refused `capped` and the
|
|
1467
|
+
// crash-fallback sweep wrote 888 memories to the author's 193. Then the
|
|
1468
|
+
// session's whole life turned out to be too long a window in the other
|
|
1469
|
+
// direction — a coordinating session spent all six inside one working day
|
|
1470
|
+
// and its end-of-day handoff was never offered the pen — so the count now
|
|
1471
|
+
// starts over on the store's own calendar date (`self/episodes.ts`), the
|
|
1472
|
+
// key I32 already argued for and for the same reason.
|
|
1473
|
+
//
|
|
1474
|
+
// The date is still on every `adapter.ask` row below (`record` stamps
|
|
1475
|
+
// `input.at`, a UTC ISO date, the same zone as every other `date` in this
|
|
1476
|
+
// store), because "how often was the pen offered today" ACROSS sessions is
|
|
1477
|
+
// a question the rows answer and no counter is kept for.
|
|
1478
|
+
const chapter = this.counterpart.episodeAsk(input.sessionId, substance);
|
|
1479
|
+
const outcome = chapter.asked
|
|
1480
|
+
? "asked"
|
|
1481
|
+
: chapter.verdict.reason === "session-ask-cap"
|
|
1482
|
+
? "capped"
|
|
1483
|
+
: "paced";
|
|
1484
|
+
let coverage: { spans: number; covered: number; uncovered: number; unaskableSpans: number; unaskableBytes: number } | null =
|
|
1485
|
+
null;
|
|
1486
|
+
try {
|
|
1487
|
+
coverage = this.counterpart.spans.coverageReport(input.scope);
|
|
1488
|
+
} catch (err) {
|
|
1489
|
+
this.emit("adapter.coverage.failed", { code: codeOf(err) });
|
|
1490
|
+
}
|
|
1491
|
+
this.record(ADAPTER_ASK_EVENT, input, {
|
|
1492
|
+
asked: chapter.asked,
|
|
1493
|
+
outcome,
|
|
1494
|
+
reason: chapter.verdict.reason,
|
|
1495
|
+
chapter: chapter.chapter,
|
|
1496
|
+
turns: substance.turns,
|
|
1497
|
+
bytes: substance.bytes,
|
|
1498
|
+
sinceTurns: chapter.verdict.sinceTurns,
|
|
1499
|
+
sinceBytes: chapter.verdict.sinceBytes,
|
|
1500
|
+
spans: coverage?.spans ?? null,
|
|
1501
|
+
covered: coverage?.covered ?? null,
|
|
1502
|
+
uncovered: coverage?.uncovered ?? null,
|
|
1503
|
+
unaskableSpans: coverage?.unaskableSpans ?? null,
|
|
1504
|
+
unaskableBytes: coverage?.unaskableBytes ?? null,
|
|
1505
|
+
});
|
|
1506
|
+
// The ask NAMES this session and its chapter: the id is what the MCP
|
|
1507
|
+
// server binds itself with, so an ask that omitted it would be an
|
|
1508
|
+
// invitation the model has no way to accept on this host — and the
|
|
1509
|
+
// chapter number is the STORE's, one past what was written.
|
|
1510
|
+
return chapter.asked ? stopAsk(input.sessionId, chapter.chapter) : null;
|
|
1511
|
+
} catch (err) {
|
|
1512
|
+
this.emit("adapter.ask.failed", { code: codeOf(err) });
|
|
1513
|
+
return null;
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
/**
|
|
1518
|
+
* THE LIVE-SESSION REGISTRY (`adapters/sessions.ts`), written here because the
|
|
1519
|
+
* hooks are the only thing on this host that knows the session id.
|
|
1520
|
+
*
|
|
1521
|
+
* Host state, not memory: an id, a scope, three timestamps, no content. It is
|
|
1522
|
+
* what lets the MCP server — which this host launches from a static config
|
|
1523
|
+
* that carries no session — bind itself to the session the ask named, and
|
|
1524
|
+
* refuse anything else. Ring-only telemetry: this fires at every Stop, and a
|
|
1525
|
+
* durable row per turn to say "the file was written" is not evidence anyone
|
|
1526
|
+
* needs.
|
|
1527
|
+
*
|
|
1528
|
+
* Under observer NOTHING is recorded (the tools stand down anyway), and every
|
|
1529
|
+
* failure is silent by construction: `recordSession` returns null rather than
|
|
1530
|
+
* throwing, because a hook may not fail the host (§5 G2).
|
|
1531
|
+
*/
|
|
1532
|
+
private noteSession(phase: SessionPhase, input: HookInput): void {
|
|
1533
|
+
if (this.observer) return;
|
|
1534
|
+
if (input.sessionId.length === 0) return;
|
|
1535
|
+
// The STORE's dir, not the config's: it is the one that went through
|
|
1536
|
+
// `assertSafeDataDir`, and it is the same value the MCP server resolves on
|
|
1537
|
+
// its own side. Reading the raw config here could put the registry in a
|
|
1538
|
+
// sibling directory the tool never looks in, over a trailing slash.
|
|
1539
|
+
const dir = this.counterpart.store.dir;
|
|
1540
|
+
const record = recordSession(dir, {
|
|
1541
|
+
sessionId: input.sessionId,
|
|
1542
|
+
scope: input.scope,
|
|
1543
|
+
phase,
|
|
1544
|
+
at: this.nowFn(),
|
|
1545
|
+
// THE DURABLE ANSWER TO "WHICH CONFIG DID THIS HOOK READ". A hook cannot
|
|
1546
|
+
// print it — stdout is the model's context — so it is recorded here, in
|
|
1547
|
+
// the one file this process writes that is host state rather than memory,
|
|
1548
|
+
// under the store the configuration itself named. A record written by a
|
|
1549
|
+
// process that was told nothing carries no field at all.
|
|
1550
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
1551
|
+
? {}
|
|
1552
|
+
: { config: this.configPath }),
|
|
1553
|
+
});
|
|
1554
|
+
this.emit("adapter.session.registry", { phase, ok: record !== null });
|
|
1555
|
+
// Bounded growth, once per session rather than once per turn — and never on
|
|
1556
|
+
// the SessionEnd path, whose hooks share 1.5 s between them.
|
|
1557
|
+
if (phase === "start") {
|
|
1558
|
+
const pruned = pruneSessions(dir, this.nowFn());
|
|
1559
|
+
if (pruned > 0) this.emit("adapter.session.registry.pruned", { removed: pruned });
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* WRITE DOWN WHAT THE HOST WAS JUST HANDED, so a later process can ask whether
|
|
1565
|
+
* it arrived. A second write of the same phase, for the same reason
|
|
1566
|
+
* `deliverScopeAsk` makes one: the first write happens before the delivery
|
|
1567
|
+
* verdict and the bundle is composed after it.
|
|
1568
|
+
*
|
|
1569
|
+
* A wake with NO sentinel — the bootstrap line a store with nothing in it
|
|
1570
|
+
* publishes — writes nothing, and the absence is the answer: there was no
|
|
1571
|
+
* checkable bundle, so nothing was supposed to arrive.
|
|
1572
|
+
*/
|
|
1573
|
+
private noteWakeExpectation(input: HookInput, sentinel: string | null): void {
|
|
1574
|
+
if (this.observer) return;
|
|
1575
|
+
if (input.sessionId.length === 0) return;
|
|
1576
|
+
if (sentinel === null || sentinel.length === 0) return;
|
|
1577
|
+
const marked = recordSession(this.counterpart.store.dir, {
|
|
1578
|
+
sessionId: input.sessionId,
|
|
1579
|
+
scope: input.scope,
|
|
1580
|
+
phase: "start",
|
|
1581
|
+
at: this.nowFn(),
|
|
1582
|
+
wakeSentinel: sentinel,
|
|
1583
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
1584
|
+
? {}
|
|
1585
|
+
: { config: this.configPath }),
|
|
1586
|
+
});
|
|
1587
|
+
this.emit("adapter.wake.expected", { recorded: marked !== null });
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
/**
|
|
1591
|
+
* DID THE WAKE THIS SESSION COMPOSED REACH THE SESSION? — once, at the first
|
|
1592
|
+
* prompt, and never again for this session.
|
|
1593
|
+
*
|
|
1594
|
+
* **Why here and not at the end.** Nothing inside the SessionStart hook can
|
|
1595
|
+
* know what the host did with its return value, and SessionEnd's hooks share
|
|
1596
|
+
* 1.5 s between them. The first `UserPromptSubmit` is the earliest moment the
|
|
1597
|
+
* host has written the record of its own injection, and it is once per session
|
|
1598
|
+
* rather than once per turn.
|
|
1599
|
+
*
|
|
1600
|
+
* **What it reads.** The head of the host's transcript, bounded
|
|
1601
|
+
* (`transcript.ts#readWakeArrival`): this package's SessionStart attachment
|
|
1602
|
+
* carries what the hook printed beside what the host says it injected, and the
|
|
1603
|
+
* wake's two sentinels stand inside both. The comparison is against
|
|
1604
|
+
* `wakeSentinel` from the session record — the expectation a fresh process
|
|
1605
|
+
* cannot otherwise have.
|
|
1606
|
+
*
|
|
1607
|
+
* **What it records.** One `adapter.wake.delivered` row: ids, numbers, flags
|
|
1608
|
+
* and an outcome. Never a byte of the bundle.
|
|
1609
|
+
*
|
|
1610
|
+
* **What it cannot do.** Fail the hook (§5 G2) or cost the turn its recall. A
|
|
1611
|
+
* session with no registry record is left entirely alone — it is either an
|
|
1612
|
+
* observer, a session older than this code, or the off→on flip the
|
|
1613
|
+
* retroactive-capture guard reads that same absence to detect, and a record
|
|
1614
|
+
* written from here would take that evidence away.
|
|
1615
|
+
*/
|
|
1616
|
+
private checkWakeArrival(input: HookInput): void {
|
|
1617
|
+
if (this.observer) return;
|
|
1618
|
+
if (input.sessionId.length === 0) return;
|
|
1619
|
+
const started = this.nowFn();
|
|
1620
|
+
let record: SessionRecord | null;
|
|
1621
|
+
try {
|
|
1622
|
+
record = readSession(this.counterpart.store.dir, input.sessionId);
|
|
1623
|
+
} catch {
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
if (record === null || record.wakeChecked === true) return;
|
|
1627
|
+
const expected = record.wakeSentinel ?? null;
|
|
1628
|
+
try {
|
|
1629
|
+
// Nothing was supposed to arrive: no expectation, no read. A cold start's
|
|
1630
|
+
// bootstrap line and a SessionStart that stood down both land here, and
|
|
1631
|
+
// the row says so rather than reporting a wake that was never composed.
|
|
1632
|
+
const arrival =
|
|
1633
|
+
expected === null ? NO_ARRIVAL : readWakeArrival(input.transcriptPath, { expect: expected });
|
|
1634
|
+
const outcome = wakeOutcome(expected, arrival);
|
|
1635
|
+
this.record(WAKE_DELIVERED_EVENT, input, {
|
|
1636
|
+
outcome,
|
|
1637
|
+
// `ok` and `delivered` say the same thing under the two names this row's
|
|
1638
|
+
// readers already look for.
|
|
1639
|
+
ok: outcome === "delivered",
|
|
1640
|
+
delivered: outcome === "delivered",
|
|
1641
|
+
expected: expected !== null,
|
|
1642
|
+
found: arrival.found,
|
|
1643
|
+
transcript: arrival.reason,
|
|
1644
|
+
// The two sentinels in what the HOST SAYS IT INJECTED, and in what the
|
|
1645
|
+
// hook PRINTED. A tail present in one and not the other is the shape
|
|
1646
|
+
// scar §2.3 is about: the render was whole and the delivery was not.
|
|
1647
|
+
headInContent: arrival.head.present,
|
|
1648
|
+
tailInContent: arrival.tail.present,
|
|
1649
|
+
headInStdout: arrival.headPrinted.present,
|
|
1650
|
+
tailInStdout: arrival.tailPrinted.present,
|
|
1651
|
+
// Whether the host recorded an injected `content` at all — the
|
|
1652
|
+
// difference between "it arrived empty" and "this build does not say".
|
|
1653
|
+
contentRecorded: arrival.contentRecorded,
|
|
1654
|
+
// What each sentinel DECLARED, against what actually arrived.
|
|
1655
|
+
headBytes: arrival.head.bytes,
|
|
1656
|
+
headElements: arrival.head.elements,
|
|
1657
|
+
tailBytes: arrival.tail.bytes,
|
|
1658
|
+
tailElements: arrival.tail.elements,
|
|
1659
|
+
contentBytes: arrival.contentBytes,
|
|
1660
|
+
stdoutBytes: arrival.stdoutBytes,
|
|
1661
|
+
linesRead: arrival.linesRead,
|
|
1662
|
+
bytesRead: arrival.bytesRead,
|
|
1663
|
+
corrupt: arrival.corrupt,
|
|
1664
|
+
elapsedMs: this.nowFn() - started,
|
|
1665
|
+
});
|
|
1666
|
+
// THE VERDICT CROSSES THE SEAM, NOT THE TEXT. `noteDelivered` asks two
|
|
1667
|
+
// questions of its argument — was a sentinel seen, and was it the
|
|
1668
|
+
// expectation — and both are already answered here. Handing it the
|
|
1669
|
+
// matched line would carry a string cut out of the wake bundle (memory
|
|
1670
|
+
// text, if a body opened a sentinel it never closed) into a core module;
|
|
1671
|
+
// `""` is "seen, and not the one we printed".
|
|
1672
|
+
this.counterpart.noteWakeDelivered(
|
|
1673
|
+
arrival.tail.present ? (arrival.tail.matchesExpected ? expected : "") : null,
|
|
1674
|
+
expected,
|
|
1675
|
+
);
|
|
1676
|
+
} catch (err) {
|
|
1677
|
+
this.emit("adapter.wake.check.failed", {
|
|
1678
|
+
code: codeOf(err),
|
|
1679
|
+
elapsedMs: this.nowFn() - started,
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
// AFTER the row, never before: a flag written first and a row that then
|
|
1683
|
+
// failed would close the question for this session with nothing recorded,
|
|
1684
|
+
// which is I32's shape. This order can duplicate a row if the flag write
|
|
1685
|
+
// fails — the cheaper of the two.
|
|
1686
|
+
this.markWakeChecked(input, record);
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
/**
|
|
1690
|
+
* Close the question for this session. `boundary` creates a record when one is
|
|
1691
|
+
* missing, so this is only ever called with a record already read — and it is
|
|
1692
|
+
* written at the clock the record already carried, because a prompt is not a
|
|
1693
|
+
* boundary and the lazy bind's liveness window is measured from those.
|
|
1694
|
+
*/
|
|
1695
|
+
private markWakeChecked(input: HookInput, prior: SessionRecord): void {
|
|
1696
|
+
try {
|
|
1697
|
+
recordSession(this.counterpart.store.dir, {
|
|
1698
|
+
sessionId: input.sessionId,
|
|
1699
|
+
scope: input.scope,
|
|
1700
|
+
phase: "boundary",
|
|
1701
|
+
at: prior.lastBoundaryAt,
|
|
1702
|
+
wakeChecked: true,
|
|
1703
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
1704
|
+
? {}
|
|
1705
|
+
: { config: this.configPath }),
|
|
1706
|
+
});
|
|
1707
|
+
} catch {
|
|
1708
|
+
/* the check runs again next turn; a hook may not fail the host (§5 G2) */
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
/** The orphanable tail: bounded and measured, never pretended away (§13). */
|
|
1713
|
+
private noteTail(input: HookInput): void {
|
|
1714
|
+
try {
|
|
1715
|
+
// The same session state the ask above reads, for the same reason: a tail
|
|
1716
|
+
// line that disagreed with the ask about why is how this bug gets found
|
|
1717
|
+
// twice.
|
|
1718
|
+
this.counterpart.noteOrphanTail(input.sessionId, substanceOf(input.turns ?? []));
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
this.emit("adapter.tail.failed", { code: codeOf(err) });
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/**
|
|
1725
|
+
* The detached worker. The plan is checked BEFORE anything starts — watchdog
|
|
1726
|
+
* against the staleness window, data dir, stance — and a refusal that repeats
|
|
1727
|
+
* ESCALATES rather than re-logging (scar E4's widening).
|
|
1728
|
+
*
|
|
1729
|
+
* **The credential is NOT a precondition any more** (I32, 2026-09-11). The
|
|
1730
|
+
* worker starts without one and degrades the single step that needs it; see
|
|
1731
|
+
* `spawn.ts`'s §2.18 paragraph for why refusing was worse than running.
|
|
1732
|
+
*
|
|
1733
|
+
* **Every refusal and every failure now leaves a DURABLE row**, one per reason
|
|
1734
|
+
* per calendar date, and the per-reason counter that decides escalation lives
|
|
1735
|
+
* in box 2's meta rather than in this object. Both halves are the same repair:
|
|
1736
|
+
* a hook process lives for one turn, so anything it knows about a repeated
|
|
1737
|
+
* failure dies before the next hook could act on it.
|
|
1738
|
+
*/
|
|
1739
|
+
private spawnWorker(input?: HookInput): SpawnOutcome {
|
|
1740
|
+
// The child is TOLD whose turn it just followed. Without it the worker can
|
|
1741
|
+
// sweep and sleep but cannot leave the next turn a semantic cue, because
|
|
1742
|
+
// that cue is per-session state (`recall/session.ts`).
|
|
1743
|
+
const bound = {
|
|
1744
|
+
...(input?.sessionId === undefined || input.sessionId.length === 0
|
|
1745
|
+
? {}
|
|
1746
|
+
: { session: input.sessionId }),
|
|
1747
|
+
...(input?.scope === undefined || input.scope.length === 0 ? {} : { scope: input.scope }),
|
|
1748
|
+
// The child reads the SAME configuration this process read. Without the
|
|
1749
|
+
// pin the worker would resolve its own — and a hook driven by `--config`
|
|
1750
|
+
// would spawn a worker that went back to the default file, which is the
|
|
1751
|
+
// shape scar §2.13 is about: parent and child resolving one value twice.
|
|
1752
|
+
...(this.configPath === undefined || this.configPath.length === 0
|
|
1753
|
+
? {}
|
|
1754
|
+
: { configPath: this.configPath }),
|
|
1755
|
+
};
|
|
1756
|
+
const seat = interpretSeat(this.config, new Date(this.nowFn()).toISOString().slice(0, 10));
|
|
1757
|
+
if (!seat.usable) {
|
|
1758
|
+
// A placeholder that expired is a decision nobody made (scar §2.15c). It
|
|
1759
|
+
// has never stopped the spawn and must not start to: the seat belongs to
|
|
1760
|
+
// the SWEEP's model call, which is one of the worker's five jobs, and the
|
|
1761
|
+
// interpret client refuses it by name at the far end. Said here so the
|
|
1762
|
+
// ring carries the reason the sweep is about to decline.
|
|
1763
|
+
this.emit("adapter.spawn.seat", { seat: seat.seat, status: seat.status });
|
|
1764
|
+
}
|
|
1765
|
+
const plan = planSpawn({
|
|
1766
|
+
config: this.config,
|
|
1767
|
+
command: this.command,
|
|
1768
|
+
args: this.args,
|
|
1769
|
+
priorFailures: 0,
|
|
1770
|
+
...bound,
|
|
1771
|
+
});
|
|
1772
|
+
// The PERSISTED count, read before the replan: `escalate` is a claim about
|
|
1773
|
+
// how often this has happened on this host, not about this process.
|
|
1774
|
+
const prior = plan.ok ? 0 : this.refusalCount(plan.reason);
|
|
1775
|
+
const replanned = plan.ok
|
|
1776
|
+
? plan
|
|
1777
|
+
: planSpawn({
|
|
1778
|
+
config: this.config,
|
|
1779
|
+
command: this.command,
|
|
1780
|
+
args: this.args,
|
|
1781
|
+
priorFailures: prior,
|
|
1782
|
+
...bound,
|
|
1783
|
+
});
|
|
1784
|
+
const outcome = spawnDetached(replanned, {
|
|
1785
|
+
...(this.spawner === undefined ? {} : { spawner: this.spawner }),
|
|
1786
|
+
onEvent: (name, data) => this.emit(name, data),
|
|
1787
|
+
});
|
|
1788
|
+
if (outcome.started) {
|
|
1789
|
+
// A start clears the slate for every reason: whatever was wrong is not
|
|
1790
|
+
// wrong now, and a counter that only ever climbed would escalate forever
|
|
1791
|
+
// off one bad afternoon.
|
|
1792
|
+
this.clearRefusals();
|
|
1793
|
+
this.noteSpawnStart(input);
|
|
1794
|
+
return outcome;
|
|
1795
|
+
}
|
|
1796
|
+
const count = this.bumpRefusal(String(outcome.reason));
|
|
1797
|
+
this.noteSpawnRefusal(outcome, count, input);
|
|
1798
|
+
return outcome;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/**
|
|
1802
|
+
* THE DURABLE ROW for a worker that DID start (2026-09-20, E2).
|
|
1803
|
+
*
|
|
1804
|
+
* I32 made every refusal durable and left the other half open: a healthy
|
|
1805
|
+
* start wrote nothing, so a worker dead all week and a week with nothing to
|
|
1806
|
+
* do read exactly alike, and the fired view could only call the mechanism
|
|
1807
|
+
* blind (inventory §2 row 23). Scar §2.4 is symmetrical — a door that opened
|
|
1808
|
+
* and a door nobody opened must not be the same absence either.
|
|
1809
|
+
*
|
|
1810
|
+
* ONE ROW PER CALENDAR DATE, latched at the store exactly like the refusals
|
|
1811
|
+
* beside it. This runs at every boundary, which is a hot path, and three
|
|
1812
|
+
* hundred identical rows a day would drown the log the view reads.
|
|
1813
|
+
*
|
|
1814
|
+
* **THE ROW CARRIES NO COUNT, on purpose.** The latch means only the FIRST
|
|
1815
|
+
* start of a day ever writes, so any tally put here would read `1` forever —
|
|
1816
|
+
* a number that looks like a measurement and is an artefact of the latch. The
|
|
1817
|
+
* day's real tally lives in box 2's meta beside the refusal counters, where
|
|
1818
|
+
* `spawnStarts()` reads it and doctor's Spawn line prints it.
|
|
1819
|
+
*
|
|
1820
|
+
* Never throws, writes nothing under observer, and is not on the critical
|
|
1821
|
+
* path: the worker has already been started by the time this runs.
|
|
1822
|
+
*/
|
|
1823
|
+
private noteSpawnStart(input?: HookInput): void {
|
|
1824
|
+
if (this.observer) return;
|
|
1825
|
+
const date = input?.at ?? new Date(this.nowFn()).toISOString().slice(0, 10);
|
|
1826
|
+
try {
|
|
1827
|
+
this.bumpStart(date);
|
|
1828
|
+
this.counterpart.noteAdapterEvent(
|
|
1829
|
+
SPAWN_STARTED_EVENT,
|
|
1830
|
+
{ date, session: input?.sessionId ?? null },
|
|
1831
|
+
{ dedupKey: `${SPAWN_STARTED_EVENT}:${date}` },
|
|
1832
|
+
);
|
|
1833
|
+
} catch (err) {
|
|
1834
|
+
this.emit("adapter.spawn.record.failed", { code: codeOf(err) });
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
/** How many times the worker has started TODAY, and the date that tally is
|
|
1839
|
+
* for. The row says it happened; this says how often. A read, never a write. */
|
|
1840
|
+
spawnStarts(): { date: string | null; count: number } {
|
|
1841
|
+
try {
|
|
1842
|
+
const store = this.counterpart.store;
|
|
1843
|
+
const date = store.getMeta(SPAWN_START_DATE_KEY) ?? null;
|
|
1844
|
+
return { date, count: Number(store.getMeta(SPAWN_START_COUNT_KEY) ?? "0") };
|
|
1845
|
+
} catch {
|
|
1846
|
+
return { date: null, count: 0 };
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
/**
|
|
1851
|
+
* The day's start tally, beside the refusal counters in box 2's meta. TWO
|
|
1852
|
+
* KEYS, not one per date: a key per day would grow without a sweep to mow it,
|
|
1853
|
+
* and the only question this answers is "how many today". The tally resets
|
|
1854
|
+
* the moment the date it was stamped with is no longer today.
|
|
1855
|
+
*/
|
|
1856
|
+
private bumpStart(date: string): number {
|
|
1857
|
+
try {
|
|
1858
|
+
const store = this.counterpart.store;
|
|
1859
|
+
const on = store.getMeta(SPAWN_START_DATE_KEY);
|
|
1860
|
+
const next = on === date ? Number(store.getMeta(SPAWN_START_COUNT_KEY) ?? "0") + 1 : 1;
|
|
1861
|
+
if (on !== date) store.setMeta(SPAWN_START_DATE_KEY, date);
|
|
1862
|
+
store.setMeta(SPAWN_START_COUNT_KEY, String(next));
|
|
1863
|
+
return next;
|
|
1864
|
+
} catch {
|
|
1865
|
+
// A lost count is never a lost hook (§5 G2). The row still lands, and it
|
|
1866
|
+
// still says the worker started today, which is what it is for.
|
|
1867
|
+
return 1;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
/**
|
|
1872
|
+
* THE DURABLE ROW for a worker that did not start (I32).
|
|
1873
|
+
*
|
|
1874
|
+
* One row per reason per CALENDAR DATE — `dedupKey` does the gating at the
|
|
1875
|
+
* store, so a refusal repeating at every boundary writes once and not three
|
|
1876
|
+
* hundred times. `count` is the persisted counter AT THIS MOMENT, so the day's
|
|
1877
|
+
* one row still says how deep the hole was by the time it was written; the
|
|
1878
|
+
* live depth is `spawnRefusals()`.
|
|
1879
|
+
*
|
|
1880
|
+
* Never throws: this is the tail of a hook, and a hook may not fail the host
|
|
1881
|
+
* (§5 G2). An observer writes nothing — `noteAdapterEvent` stands down at the
|
|
1882
|
+
* core's own seam, and the counter above stayed in memory for the same reason.
|
|
1883
|
+
*/
|
|
1884
|
+
private noteSpawnRefusal(outcome: SpawnOutcome, count: number, input?: HookInput): void {
|
|
1885
|
+
if (this.observer) return;
|
|
1886
|
+
const name = outcome.reason === "SPAWN_FAILED" ? SPAWN_FAILED_EVENT : SPAWN_REFUSED_EVENT;
|
|
1887
|
+
const date = input?.at ?? null;
|
|
1888
|
+
try {
|
|
1889
|
+
this.counterpart.noteAdapterEvent(
|
|
1890
|
+
name,
|
|
1891
|
+
{
|
|
1892
|
+
reason: String(outcome.reason),
|
|
1893
|
+
code: outcome.code,
|
|
1894
|
+
count,
|
|
1895
|
+
escalate: outcome.escalate,
|
|
1896
|
+
date,
|
|
1897
|
+
session: input?.sessionId ?? null,
|
|
1898
|
+
},
|
|
1899
|
+
// No date is still one row per reason per RUN OF DAYS rather than per
|
|
1900
|
+
// boundary: a caller that knows no date is a test or a bare invocation,
|
|
1901
|
+
// and neither should be able to flood the log.
|
|
1902
|
+
{ dedupKey: `${name}:${String(outcome.reason)}:${date ?? "no-date"}` },
|
|
1903
|
+
);
|
|
1904
|
+
} catch (err) {
|
|
1905
|
+
this.emit("adapter.spawn.record.failed", { code: codeOf(err) });
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* The per-reason refusal counters, as they stand. PR 2's session-start notice
|
|
1911
|
+
* reads this — "your background worker has not started in four days" is a
|
|
1912
|
+
* sentence somebody has to be able to say — and it is a read, never a write.
|
|
1913
|
+
*/
|
|
1914
|
+
spawnRefusals(): Record<string, number> {
|
|
1915
|
+
const out: Record<string, number> = {};
|
|
1916
|
+
if (this.observer) {
|
|
1917
|
+
for (const [reason, n] of this.volatileRefusals) out[reason] = n;
|
|
1918
|
+
return out;
|
|
1919
|
+
}
|
|
1920
|
+
try {
|
|
1921
|
+
for (const [key, value] of this.counterpart.store.metaWithPrefix(SPAWN_REFUSAL_PREFIX)) {
|
|
1922
|
+
const n = Number(value);
|
|
1923
|
+
if (n > 0) out[key.slice(SPAWN_REFUSAL_PREFIX.length)] = n;
|
|
1924
|
+
}
|
|
1925
|
+
} catch (err) {
|
|
1926
|
+
this.emit("adapter.spawn.refusals.failed", { code: codeOf(err) });
|
|
1927
|
+
}
|
|
1928
|
+
return out;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
/**
|
|
1932
|
+
* THE ONE OR TWO LINES THE OWNER SEES AT SESSION START, or null.
|
|
1933
|
+
*
|
|
1934
|
+
* I32's closing move. #95 made the refusals durable and `doctor.ts` reads
|
|
1935
|
+
* them; this is the surface that puts the worst RED finding where a human
|
|
1936
|
+
* already looks — the terminal — instead of leaving it in a store for whoever
|
|
1937
|
+
* thinks to ask (adapter INTERFACE-GAPS, "Nothing SAYS the worker has not
|
|
1938
|
+
* run"). The owner's ruling, 2026-09-11: the warning must reach the USER's
|
|
1939
|
+
* terminal.
|
|
1940
|
+
*
|
|
1941
|
+
* Three properties, each load-bearing:
|
|
1942
|
+
*
|
|
1943
|
+
* - **Red only.** Amber belongs to `counterparts doctor`, which the owner
|
|
1944
|
+
* runs on purpose. A hook that spoke every time something was imperfect is
|
|
1945
|
+
* a hook people learn to scroll past.
|
|
1946
|
+
* - **An observer says nothing at all**, before any read: an instrument that
|
|
1947
|
+
* narrated the host it is measuring would be doing more than reading.
|
|
1948
|
+
* - **It cannot fail the wake** (§5 G2). Every failure — a store that will
|
|
1949
|
+
* not read, a clock that throws — returns null and leaves ONE ring event,
|
|
1950
|
+
* and the wake goes out on exactly the path it took yesterday.
|
|
1951
|
+
*
|
|
1952
|
+
* Bounded at `SESSION_NOTICE_BUDGET_MS` and checked between finding groups,
|
|
1953
|
+
* because this runs inside a foreground hook.
|
|
1954
|
+
*/
|
|
1955
|
+
notice(
|
|
1956
|
+
input: HookInput,
|
|
1957
|
+
opts: { budgetMs?: number; now?: () => number; checkout?: CheckoutReading } = {},
|
|
1958
|
+
): string | null {
|
|
1959
|
+
if (this.observer) return null;
|
|
1960
|
+
try {
|
|
1961
|
+
const today = input.at ?? new Date(this.nowFn()).toISOString().slice(0, 10);
|
|
1962
|
+
// WHICH CODE IS LIVE, read before anything else and RECORDED. The reading
|
|
1963
|
+
// is bounded and never throws (`readCheckout`); the row is the mechanized
|
|
1964
|
+
// half — a day on master leaves one latched row, and a day the tree
|
|
1965
|
+
// wandered leaves one per state it wandered into.
|
|
1966
|
+
const checkout = opts.checkout ?? readCheckout();
|
|
1967
|
+
if (!checkoutIsGraded(checkout)) {
|
|
1968
|
+
// git missing, slow, or no repository at all: nothing to record, and
|
|
1969
|
+
// only a "git would not answer" is worth a ring row.
|
|
1970
|
+
if (checkout.reason === "unreadable") {
|
|
1971
|
+
// `why` separates the two silences: a git that answered "no
|
|
1972
|
+
// origin/master" is a fact about the repository, and a git that ran
|
|
1973
|
+
// out of `CHECKOUT_BUDGET_MS` is a fact about the machine — and only
|
|
1974
|
+
// the second one means the grade is missing on a morning it mattered.
|
|
1975
|
+
this.emit("adapter.checkout.unreadable", {
|
|
1976
|
+
root: checkout.root,
|
|
1977
|
+
why: checkout.timedOut ? "timeout" : "git",
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
} else {
|
|
1981
|
+
try {
|
|
1982
|
+
this.counterpart.noteAdapterEvent(
|
|
1983
|
+
CHECKOUT_EVENT,
|
|
1984
|
+
{
|
|
1985
|
+
reason: checkout.reason,
|
|
1986
|
+
branch: checkout.branch,
|
|
1987
|
+
head: checkout.head,
|
|
1988
|
+
dirty: checkout.dirty,
|
|
1989
|
+
behindBy: checkout.behindBy,
|
|
1990
|
+
originMaster: checkout.originMaster,
|
|
1991
|
+
atMaster: checkout.atMaster,
|
|
1992
|
+
date: today,
|
|
1993
|
+
},
|
|
1994
|
+
// THE REASON IS PART OF THE LATCH. Date, head and dirtiness alone
|
|
1995
|
+
// let a day's first row stand for every later one: a `git fetch` in
|
|
1996
|
+
// the shared tree moves origin/master, so the SAME clean head that
|
|
1997
|
+
// graded `master` at breakfast grades `behind` by lunchtime — and
|
|
1998
|
+
// the day's record would still say master. One row per state the
|
|
1999
|
+
// tree was actually in, which is the claim the row is for.
|
|
2000
|
+
{
|
|
2001
|
+
dedupKey: `${CHECKOUT_EVENT}:${today}:${checkout.head ?? "none"}:${checkout.dirty}:${checkout.reason}`,
|
|
2002
|
+
},
|
|
2003
|
+
);
|
|
2004
|
+
} catch (err) {
|
|
2005
|
+
this.emit("adapter.checkout.record.failed", { code: codeOf(err) });
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
const findings = doctorFindings({
|
|
2009
|
+
checkout,
|
|
2010
|
+
configPath: this.configPath ?? "(none)",
|
|
2011
|
+
// `bin/hook.ts` REFUSED an absent or unreadable NAMED configuration long
|
|
2012
|
+
// before this line, so there is no reason left for this reading to
|
|
2013
|
+
// re-derive: null says "the caller already vouched for the file".
|
|
2014
|
+
configReason: null,
|
|
2015
|
+
config: this.config,
|
|
2016
|
+
dir: this.config.dataDir ?? "",
|
|
2017
|
+
credentials: this.credentials ?? {
|
|
2018
|
+
loaded: [],
|
|
2019
|
+
skippedPresent: [],
|
|
2020
|
+
ignoredLines: 0,
|
|
2021
|
+
reason: "not-configured",
|
|
2022
|
+
mode: null,
|
|
2023
|
+
permissive: false,
|
|
2024
|
+
},
|
|
2025
|
+
credentialsPath: this.config.credentialsFile,
|
|
2026
|
+
store: this.counterpart.store,
|
|
2027
|
+
today,
|
|
2028
|
+
refusals: this.spawnRefusals(),
|
|
2029
|
+
starts: this.spawnStarts(),
|
|
2030
|
+
budgetMs: opts.budgetMs ?? SESSION_NOTICE_BUDGET_MS,
|
|
2031
|
+
...(opts.now === undefined ? {} : { now: opts.now }),
|
|
2032
|
+
});
|
|
2033
|
+
return noticeMessage(findings);
|
|
2034
|
+
} catch (err) {
|
|
2035
|
+
// A reading that failed is not a session that failed. One ring row, so the
|
|
2036
|
+
// silence is distinguishable from a clean bill of health (scar §2.4).
|
|
2037
|
+
this.emit("adapter.doctor.failed", { code: codeOf(err) });
|
|
2038
|
+
return null;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/**
|
|
2043
|
+
* RECORD THAT THE TERMINAL DID NOT GET THE WARNING, and why.
|
|
2044
|
+
*
|
|
2045
|
+
* The host caps a hook's stdout at 10,000 characters, and over that it
|
|
2046
|
+
* replaces the string with a preview — which makes the JSON envelope
|
|
2047
|
+
* unparseable and drops the wake with it. `bin/hook.ts` therefore prints the
|
|
2048
|
+
* PLAIN wake and throws the notice away when the envelope is too big
|
|
2049
|
+
* (`ENVELOPE_MAX_CHARS`), and this is how that choice stays visible instead of
|
|
2050
|
+
* looking like a healthy morning. Ids and counts only, like every other row.
|
|
2051
|
+
*/
|
|
2052
|
+
noteNoticeDropped(chars: { noticeChars: number; envelopeChars: number; limitChars: number }): void {
|
|
2053
|
+
this.emit("adapter.notice.dropped", { ...chars });
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
private refusalCount(reason: string): number {
|
|
2057
|
+
if (this.observer) return this.volatileRefusals.get(reason) ?? 0;
|
|
2058
|
+
try {
|
|
2059
|
+
return Number(this.counterpart.store.getMeta(`${SPAWN_REFUSAL_PREFIX}${reason}`) ?? "0");
|
|
2060
|
+
} catch {
|
|
2061
|
+
return 0;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
/** Returns the count AFTER this refusal. A meta write that loses the lock to
|
|
2066
|
+
* an overlapping runner costs the count, never the hook (§5 G2). */
|
|
2067
|
+
private bumpRefusal(reason: string): number {
|
|
2068
|
+
const next = this.refusalCount(reason) + 1;
|
|
2069
|
+
if (this.observer) {
|
|
2070
|
+
this.volatileRefusals.set(reason, next);
|
|
2071
|
+
return next;
|
|
2072
|
+
}
|
|
2073
|
+
try {
|
|
2074
|
+
this.counterpart.store.setMeta(`${SPAWN_REFUSAL_PREFIX}${reason}`, String(next));
|
|
2075
|
+
} catch (err) {
|
|
2076
|
+
this.emit("adapter.spawn.count.failed", { code: codeOf(err) });
|
|
2077
|
+
}
|
|
2078
|
+
return next;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
private clearRefusals(): void {
|
|
2082
|
+
this.volatileRefusals.clear();
|
|
2083
|
+
if (this.observer) return;
|
|
2084
|
+
try {
|
|
2085
|
+
const store = this.counterpart.store;
|
|
2086
|
+
for (const [key, value] of store.metaWithPrefix(SPAWN_REFUSAL_PREFIX)) {
|
|
2087
|
+
// Zero, not deleted: `meta` has no delete on the write seam's allowlist,
|
|
2088
|
+
// and a zero reads identically everywhere the counter is consulted.
|
|
2089
|
+
if (value !== "0") store.setMeta(key, "0");
|
|
2090
|
+
}
|
|
2091
|
+
} catch (err) {
|
|
2092
|
+
this.emit("adapter.spawn.count.failed", { code: codeOf(err) });
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
/**
|
|
2097
|
+
* The one wrapper. Stance first (an instrument stands down and SAYS SO), then
|
|
2098
|
+
* the anti-loop guard, then the work — and nothing that happens inside reaches
|
|
2099
|
+
* the host as an exception (G2, G7).
|
|
2100
|
+
*/
|
|
2101
|
+
private guard(
|
|
2102
|
+
hook: HookName,
|
|
2103
|
+
input: HookInput,
|
|
2104
|
+
body: (out: HookResult) => HookResult,
|
|
2105
|
+
): HookResult {
|
|
2106
|
+
const base: HookResult = {
|
|
2107
|
+
hook,
|
|
2108
|
+
ok: false,
|
|
2109
|
+
reason: "unknown",
|
|
2110
|
+
injection: "",
|
|
2111
|
+
bytes: 0,
|
|
2112
|
+
sentinel: null,
|
|
2113
|
+
surfaced: [],
|
|
2114
|
+
footnotes: [],
|
|
2115
|
+
ask: null,
|
|
2116
|
+
spansAppended: 0,
|
|
2117
|
+
spawn: null,
|
|
2118
|
+
observer: this.observer,
|
|
2119
|
+
};
|
|
2120
|
+
const key = `${hook}:${input.sessionId}`;
|
|
2121
|
+
if (this.inFlight.has(key)) {
|
|
2122
|
+
// Re-entrancy: our own injection lands in the transcript, and a hook that
|
|
2123
|
+
// re-enters on it would recall on its own render forever.
|
|
2124
|
+
this.emit("adapter.reentrant", { hook, session: input.sessionId });
|
|
2125
|
+
return { ...base, ok: true, reason: "reentrant" };
|
|
2126
|
+
}
|
|
2127
|
+
this.inFlight.add(key);
|
|
2128
|
+
try {
|
|
2129
|
+
// THE SECOND `off` SITE. The entry point already refused before anything
|
|
2130
|
+
// opened, which is where the "no output, no write" guarantee actually
|
|
2131
|
+
// comes from; this is the same predicate at the seam a future caller
|
|
2132
|
+
// reaches, so a library user who constructs an adapter directly inherits
|
|
2133
|
+
// the rule instead of having to remember it (observer-mode G8's shape).
|
|
2134
|
+
// It is silent on purpose — see `bin/hook.ts` — and the ring event is
|
|
2135
|
+
// free here because the ring is already open.
|
|
2136
|
+
if (stanceOfMode(this.scope.mode) === "off") {
|
|
2137
|
+
this.emit("adapter.scope.off", { hook, matched: this.scope.matched });
|
|
2138
|
+
return { ...base, ok: true, reason: "scope-off" };
|
|
2139
|
+
}
|
|
2140
|
+
if (this.observer && hook !== "session-start" && hook !== "user-prompt-submit") {
|
|
2141
|
+
// An instrument reads (the wake is delivered, recall works) and deposits
|
|
2142
|
+
// nothing. The stand-down is logged: silence is indistinguishable from a
|
|
2143
|
+
// broken hook (scar E7, §2.4).
|
|
2144
|
+
this.emit("adapter.observer.standdown", { hook });
|
|
2145
|
+
return { ...base, ok: true, reason: "observer" };
|
|
2146
|
+
}
|
|
2147
|
+
return body(base);
|
|
2148
|
+
} catch (err) {
|
|
2149
|
+
// NO HOOK EVER FAILS THE HOST (G2). Logged, swallowed, clean exit.
|
|
2150
|
+
this.emit("adapter.hook.failed", { hook, code: codeOf(err) });
|
|
2151
|
+
return { ...base, ok: false, reason: "failed" };
|
|
2152
|
+
} finally {
|
|
2153
|
+
this.inFlight.delete(key);
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
private emit(name: string, data: Record<string, string | number | boolean | null>): void {
|
|
2158
|
+
const event: AdapterEvent = { at: this.nowFn(), name, data };
|
|
2159
|
+
this.ring.push(event);
|
|
2160
|
+
if (this.ring.length > EVENT_RING) this.ring.shift();
|
|
2161
|
+
try {
|
|
2162
|
+
this.onEvent?.(event);
|
|
2163
|
+
} catch {
|
|
2164
|
+
// Even telemetry may not fail the host (§1 G7: "failed telemetry means
|
|
2165
|
+
// the bootstrap line or nothing, and a clean exit").
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
/**
|
|
2171
|
+
* Substance for PACING — conversational turns only.
|
|
2172
|
+
*
|
|
2173
|
+
* Host-injected material is user-role but is not the user speaking, so it must
|
|
2174
|
+
* not pace a ritual (§2 G11); tool output, file contents and images are the
|
|
2175
|
+
* declared blind spot and never counted (§2 G10). The same turn list feeds
|
|
2176
|
+
* `captureSpans`, where injected context IS kept — the two rules live one
|
|
2177
|
+
* function apart on purpose.
|
|
2178
|
+
*/
|
|
2179
|
+
export function substanceOf(turns: readonly HostTurn[]): { turns: number; bytes: number } {
|
|
2180
|
+
let count = 0;
|
|
2181
|
+
let bytes = 0;
|
|
2182
|
+
for (const turn of turns) {
|
|
2183
|
+
if ((turn.source ?? "conversation") !== "conversation") continue;
|
|
2184
|
+
count += 1;
|
|
2185
|
+
bytes += Buffer.byteLength(turn.text, "utf8");
|
|
2186
|
+
}
|
|
2187
|
+
return { turns: count, bytes };
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
/** The six answers the delivery check can give, in plain words. */
|
|
2191
|
+
export type WakeOutcome =
|
|
2192
|
+
| "delivered"
|
|
2193
|
+
| "truncated"
|
|
2194
|
+
| "mismatch"
|
|
2195
|
+
| "printed-unverified"
|
|
2196
|
+
| "not-found"
|
|
2197
|
+
| "no-wake-expected";
|
|
2198
|
+
|
|
2199
|
+
/**
|
|
2200
|
+
* THE VERDICT, read from the TAIL SENTINEL ALONE — which is the whole point of
|
|
2201
|
+
* the sentinel: "verify arrival from the last line" (§1 G2, scar §2.3). The
|
|
2202
|
+
* head sentinel and the measured lengths ride on the row as evidence; they are
|
|
2203
|
+
* not inputs to this answer, because a bundle clipped in transit loses its tail
|
|
2204
|
+
* first and a reader that needed both would report nothing when it mattered.
|
|
2205
|
+
*
|
|
2206
|
+
* `mismatch` is the case a resumed session produces: the head of the file holds
|
|
2207
|
+
* the SessionStart attachment of the run that created it, so a wake arrived and
|
|
2208
|
+
* it is not the one this session composed. "Something else arrived" and "it was
|
|
2209
|
+
* cut off" are different mornings.
|
|
2210
|
+
*
|
|
2211
|
+
* `printed-unverified` is the case a HOST BUILD produces. The verdict is read
|
|
2212
|
+
* from `content`, a field of the host's private transcript format measured once;
|
|
2213
|
+
* a build that does not record it leaves nothing to read, and answering
|
|
2214
|
+
* `truncated` there would say v1's silent-loss bug was happening to every
|
|
2215
|
+
* session on that host. When the field is absent the printed side answers
|
|
2216
|
+
* instead — it is this package's own stdout, so an intact sentinel there says
|
|
2217
|
+
* the hook did its half and the host's half is simply not on the record.
|
|
2218
|
+
*/
|
|
2219
|
+
export function wakeOutcome(expected: string | null, arrival: WakeArrival): WakeOutcome {
|
|
2220
|
+
if (expected === null) return "no-wake-expected";
|
|
2221
|
+
if (!arrival.found) return "not-found";
|
|
2222
|
+
if (arrival.tail.present) return arrival.tail.matchesExpected ? "delivered" : "mismatch";
|
|
2223
|
+
if (!arrival.contentRecorded) {
|
|
2224
|
+
if (arrival.tailPrinted.matchesExpected) return "printed-unverified";
|
|
2225
|
+
if (arrival.tailPrinted.present) return "mismatch";
|
|
2226
|
+
// Neither recorded nor printed: the attachment is not a wake at all.
|
|
2227
|
+
if (!arrival.headPrinted.present) return "not-found";
|
|
2228
|
+
}
|
|
2229
|
+
return "truncated";
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
function codeOf(err: unknown): string {
|
|
2233
|
+
if (err !== null && typeof err === "object") {
|
|
2234
|
+
const code = (err as { code?: unknown }).code;
|
|
2235
|
+
if (typeof code === "string") return code;
|
|
2236
|
+
const name = (err as { name?: unknown }).name;
|
|
2237
|
+
if (typeof name === "string") return name;
|
|
2238
|
+
}
|
|
2239
|
+
return "UNKNOWN";
|
|
2240
|
+
}
|