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,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HOST MODE — the nightly page writer as a windowless session of the self.
|
|
3
|
+
*
|
|
4
|
+
* The owner's pick for S2 (spec §15 item 10, plan §3): once a night the
|
|
5
|
+
* boundary's worker starts a real host session with no window, `claude -p`, so
|
|
6
|
+
* the ordinary SessionStart hook fires inside it and the writer wakes with the
|
|
7
|
+
* wake — the same bundle a live session gets, page first. It is handed the day
|
|
8
|
+
* just gone as its prompt and exactly ONE pre-approved tool: the page's. No
|
|
9
|
+
* API key of its own, no second model seat, the same subscription and the same
|
|
10
|
+
* model as the owner's sessions. "What makes a model call me is the memory it
|
|
11
|
+
* wakes with", and this is that sentence taken literally.
|
|
12
|
+
*
|
|
13
|
+
* **What is unverified until a real machine runs it**, and it is written down
|
|
14
|
+
* rather than claimed: whether a background process can reach the keychain for
|
|
15
|
+
* the subscription login. `claude setup-token` is the documented route for
|
|
16
|
+
* unattended runs (spec §16). Everything in this file is proved against a STUB
|
|
17
|
+
* executable; the PR says what the owner must do by hand to try the real thing.
|
|
18
|
+
*
|
|
19
|
+
* **The shape is `spawn.ts`'s, deliberately.** A pure planner that decides
|
|
20
|
+
* everything and starts nothing, and a starter small enough to read — because
|
|
21
|
+
* everything worth testing is in the pure half. The package's own values are
|
|
22
|
+
* written onto the child's environment LAST, so nothing a caller exported can
|
|
23
|
+
* redirect the run (§2.13), and the two variables that would make the child's
|
|
24
|
+
* MCP server bind to the PARENT's session are removed rather than inherited.
|
|
25
|
+
*
|
|
26
|
+
* **The outcome is read from the STORE, never from the child's stdout.** A
|
|
27
|
+
* windowless session's output is prose we did not write and must not parse into
|
|
28
|
+
* a verdict; what the run actually did is in the page's own version chain and
|
|
29
|
+
* in the row the tool left. Exit code and the watchdog decide only between
|
|
30
|
+
* "the writer had nothing to say" and "the writer could not run".
|
|
31
|
+
*/
|
|
32
|
+
import { spawn } from "node:child_process";
|
|
33
|
+
|
|
34
|
+
import type { Counterpart } from "../../core/counterpart.js";
|
|
35
|
+
import { writerInstruction } from "../../core/self/index.js";
|
|
36
|
+
import type { PageWriterOutcome } from "../../core/self/index.js";
|
|
37
|
+
import { CONFIG_ENV as CONFIG_PATH_ENV } from "../config-path.js";
|
|
38
|
+
import { PAGE_WRITER_ENV } from "../sessions.js";
|
|
39
|
+
import { OBSERVER_ENV } from "../stance-env.js";
|
|
40
|
+
|
|
41
|
+
import { TUNABLES, pageWriterMode } from "./config.js";
|
|
42
|
+
import type { AdapterConfig } from "./config.js";
|
|
43
|
+
import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV } from "./spawn.js";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* THE ONE TOOL THE WRITER MAY CALL, spelled the way the host names an MCP tool.
|
|
47
|
+
*
|
|
48
|
+
* One, and the page's, because a writer that could call anything else would be
|
|
49
|
+
* an unattended session with a shell — and the thing it is unattended FOR is
|
|
50
|
+
* one paragraph of prose. Everything else it might want (the page as it stands,
|
|
51
|
+
* the day just gone) is already in the prompt or in its own wake.
|
|
52
|
+
*/
|
|
53
|
+
export const MCP_SELF_PAGE_TOOL = "mcp__counterparts__self_page";
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* WHICH NIGHT THIS CHILD IS WRITING, pinned onto its environment as a DATE.
|
|
57
|
+
*
|
|
58
|
+
* It is how the MCP server inside the child knows to record `by: "writer"`
|
|
59
|
+
* rather than `by: "session"`. `by` is the door's and is not claimable from
|
|
60
|
+
* outside (`self/page.ts`), and in session mode the door's evidence is a mark
|
|
61
|
+
* on the session registry record; a windowless child has no such mark, because
|
|
62
|
+
* its session id is minted by the host after this process is gone. The
|
|
63
|
+
* variable is the same evidence by the only channel that reaches it — and it is
|
|
64
|
+
* honoured only while that night's claim is still open, so an inherited or
|
|
65
|
+
* stale value cannot relabel anything.
|
|
66
|
+
*/
|
|
67
|
+
export { PAGE_WRITER_ENV } from "../sessions.js";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The permission mode the child runs under. `default` and one allowed tool: the
|
|
71
|
+
* page's tool needs no approval and everything else stops — in a session with
|
|
72
|
+
* no window, a prompt nobody can answer is a refusal, which is the direction
|
|
73
|
+
* this should fail in.
|
|
74
|
+
*/
|
|
75
|
+
export const PERMISSION_MODE = "default";
|
|
76
|
+
|
|
77
|
+
/** The host CLI, when the configuration names none. Resolved on the child's PATH. */
|
|
78
|
+
export const DEFAULT_HOST_COMMAND = "claude";
|
|
79
|
+
|
|
80
|
+
export type PageWriterRefusal =
|
|
81
|
+
| "NOT_HOST_MODE"
|
|
82
|
+
| "OBSERVER"
|
|
83
|
+
| "NO_DATA_DIR"
|
|
84
|
+
| "NO_COMMAND"
|
|
85
|
+
| "TIMEOUT_NOT_FINITE";
|
|
86
|
+
|
|
87
|
+
export interface PageWriterPlan {
|
|
88
|
+
readonly ok: boolean;
|
|
89
|
+
readonly reason: PageWriterRefusal | "ready";
|
|
90
|
+
readonly command: string;
|
|
91
|
+
readonly args: readonly string[];
|
|
92
|
+
/** What goes on the child's STDIN — the instruction. It is not in `argv`
|
|
93
|
+
* because a command line is readable by every process on the machine. */
|
|
94
|
+
readonly stdin: string;
|
|
95
|
+
/** The child's complete environment. This package's values are written LAST. */
|
|
96
|
+
readonly env: Readonly<Record<string, string>>;
|
|
97
|
+
readonly timeoutMs: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface PageWriterPlanInput {
|
|
101
|
+
readonly config: AdapterConfig;
|
|
102
|
+
/** The calendar date the run is about. */
|
|
103
|
+
readonly about: string;
|
|
104
|
+
/** The instruction the child is started with (`self/writer.ts`). */
|
|
105
|
+
readonly prompt: string;
|
|
106
|
+
readonly baseEnv?: Readonly<Record<string, string | undefined>>;
|
|
107
|
+
/** The configuration file the parent read, pinned so parent and child agree. */
|
|
108
|
+
readonly configPath?: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* EVERYTHING DECIDED, NOTHING STARTED. Pure.
|
|
113
|
+
*
|
|
114
|
+
* The order is load-bearing, the same way `planSpawn`'s is: the stances refuse
|
|
115
|
+
* first, then the things that make a command impossible, and only then is the
|
|
116
|
+
* environment written.
|
|
117
|
+
*/
|
|
118
|
+
export function planPageWriter(input: PageWriterPlanInput): PageWriterPlan {
|
|
119
|
+
const timeoutMs = input.config.pageWriter?.timeoutMs ?? TUNABLES.PAGE_WRITER_MS;
|
|
120
|
+
const command = input.config.pageWriter?.command ?? DEFAULT_HOST_COMMAND;
|
|
121
|
+
const env: Record<string, string> = {};
|
|
122
|
+
for (const [k, v] of Object.entries(input.baseEnv ?? process.env)) {
|
|
123
|
+
if (v !== undefined) env[k] = v;
|
|
124
|
+
}
|
|
125
|
+
// NO POSITIONAL PROMPT: it rides on stdin (see `PageWriterPlan.stdin`).
|
|
126
|
+
const args = ["-p", "--allowedTools", MCP_SELF_PAGE_TOOL, "--permission-mode", PERMISSION_MODE];
|
|
127
|
+
const no = (reason: PageWriterRefusal): PageWriterPlan => ({
|
|
128
|
+
ok: false,
|
|
129
|
+
reason,
|
|
130
|
+
command,
|
|
131
|
+
args,
|
|
132
|
+
stdin: input.prompt,
|
|
133
|
+
env,
|
|
134
|
+
timeoutMs,
|
|
135
|
+
});
|
|
136
|
+
// An instrument starts no writer against a store it may not write, and a
|
|
137
|
+
// configuration that is not in host mode is not a refusal to report — it is
|
|
138
|
+
// simply a different mechanism.
|
|
139
|
+
if (pageWriterMode(input.config) !== "host") {
|
|
140
|
+
return no(input.config.observer === true ? "OBSERVER" : "NOT_HOST_MODE");
|
|
141
|
+
}
|
|
142
|
+
if (input.config.dataDir === undefined || input.config.dataDir.trim().length === 0) {
|
|
143
|
+
return no("NO_DATA_DIR");
|
|
144
|
+
}
|
|
145
|
+
if (command.trim().length === 0) return no("NO_COMMAND");
|
|
146
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return no("TIMEOUT_NOT_FINITE");
|
|
147
|
+
|
|
148
|
+
// THE PARENT'S SESSION IS NOT THE CHILD'S. These two pin the detached
|
|
149
|
+
// worker's run to the session that spawned it; inherited by a whole new host
|
|
150
|
+
// session they would make its MCP server bind to a session that has already
|
|
151
|
+
// ended, and every tool call refuse. Removed rather than overwritten, because
|
|
152
|
+
// "no session" is the truth: the host mints the child's id itself.
|
|
153
|
+
delete env[SESSION_ENV];
|
|
154
|
+
delete env[SCOPE_ENV];
|
|
155
|
+
// AND THE STANCE VARIABLE, for a third reason (S2 review, MINOR-7). A shell
|
|
156
|
+
// that exported `COUNTERPARTS_OBSERVER` would hand the child an observer
|
|
157
|
+
// store: its `self_page` refuses, the page is untouched, and the night reads
|
|
158
|
+
// `nothing-to-say` — fail-closed, but a silently WRONG answer, which is worse
|
|
159
|
+
// than a loud one. The stance of a session this package starts is this
|
|
160
|
+
// package's to decide, and it decides `not an observer`.
|
|
161
|
+
delete env[OBSERVER_ENV];
|
|
162
|
+
// ...and this package's own values last, so nothing exported anywhere can
|
|
163
|
+
// point the child at another store.
|
|
164
|
+
env[DATA_DIR_ENV] = input.config.dataDir;
|
|
165
|
+
env[PAGE_WRITER_ENV] = input.about;
|
|
166
|
+
if (input.configPath !== undefined && input.configPath.length > 0) {
|
|
167
|
+
env[CONFIG_PATH_ENV] = input.configPath;
|
|
168
|
+
}
|
|
169
|
+
return { ok: true, reason: "ready", command, args, stdin: input.prompt, env, timeoutMs };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** What one child did, as the OS reported it. Injected so a test can prove the
|
|
173
|
+
* whole path without starting a process. */
|
|
174
|
+
export interface ChildResult {
|
|
175
|
+
readonly code: number | null;
|
|
176
|
+
readonly timedOut: boolean;
|
|
177
|
+
readonly error: string | null;
|
|
178
|
+
}
|
|
179
|
+
export type PageWriterStarter = (
|
|
180
|
+
plan: PageWriterPlan,
|
|
181
|
+
signal?: AbortSignal,
|
|
182
|
+
) => Promise<ChildResult>;
|
|
183
|
+
|
|
184
|
+
export interface PageWriterRunResult {
|
|
185
|
+
readonly ran: boolean;
|
|
186
|
+
readonly about: string;
|
|
187
|
+
readonly outcome: PageWriterOutcome;
|
|
188
|
+
readonly detail: string;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* RUN THE NIGHT, in host mode.
|
|
193
|
+
*
|
|
194
|
+
* Called from the boundary's worker, after everything else it does. The order
|
|
195
|
+
* is: decide, compose, claim, start, wait, then READ THE STORE for what
|
|
196
|
+
* happened. The claim goes in before the child starts, so a crash between the
|
|
197
|
+
* two costs one night rather than leaving a writer that can be started twice.
|
|
198
|
+
*
|
|
199
|
+
* It never throws: a nightly writer that could fail a worker would take the
|
|
200
|
+
* sweep, the flush, the cycle and the snapshot down with it.
|
|
201
|
+
*/
|
|
202
|
+
export async function runPageWriter(opts: {
|
|
203
|
+
counterpart: Counterpart;
|
|
204
|
+
config: AdapterConfig;
|
|
205
|
+
configPath?: string;
|
|
206
|
+
baseEnv?: Readonly<Record<string, string | undefined>>;
|
|
207
|
+
start?: PageWriterStarter;
|
|
208
|
+
/**
|
|
209
|
+
* THE WORKER'S OWN WATCHDOG, and it outranks this one.
|
|
210
|
+
*
|
|
211
|
+
* The two numbers can disagree — the worker's is five minutes by default and
|
|
212
|
+
* this child's is ten — and without this the worker would sit in its `finally`
|
|
213
|
+
* for twice the life its own contract states, holding the store open past the
|
|
214
|
+
* moment everything else in the run had given up. So the child is killed when
|
|
215
|
+
* the worker's watchdog fires, and the run is recorded as `failed(watchdog)`
|
|
216
|
+
* exactly as its own timeout would be. Whichever alarm rings first wins.
|
|
217
|
+
*/
|
|
218
|
+
signal?: AbortSignal;
|
|
219
|
+
}): Promise<PageWriterRunResult> {
|
|
220
|
+
const { counterpart, config } = opts;
|
|
221
|
+
const mode = pageWriterMode(config);
|
|
222
|
+
const today = counterpart.store.today();
|
|
223
|
+
if (mode !== "host") {
|
|
224
|
+
return { ran: false, about: "", outcome: "skipped", detail: "not-host-mode" };
|
|
225
|
+
}
|
|
226
|
+
const due = counterpart.pageWriterDue({ mode, today });
|
|
227
|
+
if (!due.due) {
|
|
228
|
+
// NO ROW for an ordinary refusal. "It already ran" and "this store has no
|
|
229
|
+
// yesterday" are the answer at most boundaries of most days, and a row for
|
|
230
|
+
// each would bury the nights that did happen.
|
|
231
|
+
return { ran: false, about: due.about, outcome: "skipped", detail: due.reason };
|
|
232
|
+
}
|
|
233
|
+
const about = due.about;
|
|
234
|
+
let prompt: string;
|
|
235
|
+
let considered = 0;
|
|
236
|
+
let omitted = 0;
|
|
237
|
+
let bytesBefore = 0;
|
|
238
|
+
try {
|
|
239
|
+
const built = counterpart.pageWriterInput({ about });
|
|
240
|
+
prompt = writerInstruction(built, { tool: MCP_SELF_PAGE_TOOL });
|
|
241
|
+
considered = built.memories.length;
|
|
242
|
+
omitted = built.omitted;
|
|
243
|
+
bytesBefore = built.page?.bytes ?? 0;
|
|
244
|
+
} catch (err) {
|
|
245
|
+
record(counterpart, { about, outcome: "failed", detail: code(err) });
|
|
246
|
+
return { ran: false, about, outcome: "failed", detail: code(err) };
|
|
247
|
+
}
|
|
248
|
+
const plan = planPageWriter({
|
|
249
|
+
config,
|
|
250
|
+
about,
|
|
251
|
+
prompt,
|
|
252
|
+
...(opts.baseEnv === undefined ? {} : { baseEnv: opts.baseEnv }),
|
|
253
|
+
...(opts.configPath === undefined ? {} : { configPath: opts.configPath }),
|
|
254
|
+
});
|
|
255
|
+
if (!plan.ok) {
|
|
256
|
+
record(counterpart, { about, outcome: "failed", detail: plan.reason, considered, omitted });
|
|
257
|
+
return { ran: false, about, outcome: "failed", detail: plan.reason };
|
|
258
|
+
}
|
|
259
|
+
// THE CLAIM, before anything is started.
|
|
260
|
+
record(counterpart, { about, outcome: "started", considered, omitted, bytesBefore });
|
|
261
|
+
const before = counterpart.selfPage();
|
|
262
|
+
let result: ChildResult;
|
|
263
|
+
try {
|
|
264
|
+
result = await (opts.start ?? startChild)(plan, opts.signal);
|
|
265
|
+
} catch (err) {
|
|
266
|
+
record(counterpart, { about, outcome: "failed", detail: code(err), considered, omitted });
|
|
267
|
+
return { ran: true, about, outcome: "failed", detail: code(err) };
|
|
268
|
+
}
|
|
269
|
+
// WHAT HAPPENED, read from the store. The child's own tool call already left
|
|
270
|
+
// a terminal row if it wrote through the MCP server; the page's version chain
|
|
271
|
+
// is the second reading, for a child that reached the seam some other way.
|
|
272
|
+
const closed = counterpart
|
|
273
|
+
.pageWriterRuns({ about })
|
|
274
|
+
.find((r) => r.outcome !== "asked" && r.outcome !== "started");
|
|
275
|
+
if (closed !== undefined) {
|
|
276
|
+
return { ran: true, about, outcome: closed.outcome, detail: closed.detail };
|
|
277
|
+
}
|
|
278
|
+
const after = counterpart.selfPage();
|
|
279
|
+
const moved = after !== null && (before === null || after.version !== before.version);
|
|
280
|
+
if (moved) {
|
|
281
|
+
record(counterpart, {
|
|
282
|
+
about,
|
|
283
|
+
outcome: "revised",
|
|
284
|
+
considered,
|
|
285
|
+
omitted,
|
|
286
|
+
bytesBefore,
|
|
287
|
+
bytesAfter: after.bytes,
|
|
288
|
+
});
|
|
289
|
+
return { ran: true, about, outcome: "revised", detail: "" };
|
|
290
|
+
}
|
|
291
|
+
if (result.timedOut || result.code !== 0) {
|
|
292
|
+
const detail = result.timedOut
|
|
293
|
+
? "watchdog"
|
|
294
|
+
: (result.error ?? `exit ${String(result.code ?? "null")}`);
|
|
295
|
+
record(counterpart, { about, outcome: "failed", detail, considered, omitted, bytesBefore });
|
|
296
|
+
return { ran: true, about, outcome: "failed", detail };
|
|
297
|
+
}
|
|
298
|
+
// A clean exit with the page untouched IS an answer: a session handed one day
|
|
299
|
+
// and one tool that chose not to use it has said there was nothing to say.
|
|
300
|
+
record(counterpart, {
|
|
301
|
+
about,
|
|
302
|
+
outcome: "nothing-to-say",
|
|
303
|
+
considered,
|
|
304
|
+
omitted,
|
|
305
|
+
bytesBefore,
|
|
306
|
+
bytesAfter: bytesBefore,
|
|
307
|
+
});
|
|
308
|
+
return { ran: true, about, outcome: "nothing-to-say", detail: "" };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function record(
|
|
312
|
+
counterpart: Counterpart,
|
|
313
|
+
run: {
|
|
314
|
+
about: string;
|
|
315
|
+
outcome: PageWriterOutcome;
|
|
316
|
+
detail?: string;
|
|
317
|
+
considered?: number;
|
|
318
|
+
omitted?: number;
|
|
319
|
+
bytesBefore?: number;
|
|
320
|
+
bytesAfter?: number;
|
|
321
|
+
},
|
|
322
|
+
): void {
|
|
323
|
+
try {
|
|
324
|
+
counterpart.recordPageWriterRun({ ...run, mode: "host" });
|
|
325
|
+
} catch {
|
|
326
|
+
/* a run that cannot be recorded still ran (§5 G7) */
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function code(err: unknown): string {
|
|
331
|
+
return err instanceof Error ? err.name : "UNKNOWN";
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* HOW LONG A CHILD GETS TO DIE POLITELY before it is killed, and how long after
|
|
336
|
+
* that before this stops waiting for the OS to confirm it.
|
|
337
|
+
*
|
|
338
|
+
* Both exist because of one hole (S2 review, MAJOR-3): the first version
|
|
339
|
+
* resolved only on `close` or `error`, and both alarms — `spawn`'s own timeout
|
|
340
|
+
* and the worker's abort — send SIGTERM and nothing else. A child that ignores
|
|
341
|
+
* SIGTERM (a trapping shell wrapper, an uninterruptible wait, a CLI with its
|
|
342
|
+
* own handler) therefore kept the promise pending, which kept the worker inside
|
|
343
|
+
* its `finally` HOLDING THE STORE OPEN, for as long as the child lived. It was
|
|
344
|
+
* reproduced: `trap '' TERM; sleep 60` with a 3-second child watchdog and a
|
|
345
|
+
* 1.2-second worker abort still had the worker alive at 25 seconds, with a
|
|
346
|
+
* `started` row and no terminal one beside it.
|
|
347
|
+
*/
|
|
348
|
+
export const KILL_GRACE_MS = 5_000;
|
|
349
|
+
export const REAP_GRACE_MS = 2_000;
|
|
350
|
+
|
|
351
|
+
/** The real starter: one child, two alarms, and an end that does not need it. */
|
|
352
|
+
async function startChild(plan: PageWriterPlan, abort?: AbortSignal): Promise<ChildResult> {
|
|
353
|
+
return await new Promise<ChildResult>((resolve) => {
|
|
354
|
+
let settled = false;
|
|
355
|
+
let terminated = false;
|
|
356
|
+
const timers: ReturnType<typeof setTimeout>[] = [];
|
|
357
|
+
let off: (() => void) | null = null;
|
|
358
|
+
const done = (r: ChildResult): void => {
|
|
359
|
+
if (settled) return;
|
|
360
|
+
settled = true;
|
|
361
|
+
for (const t of timers) clearTimeout(t);
|
|
362
|
+
off?.();
|
|
363
|
+
resolve(r);
|
|
364
|
+
};
|
|
365
|
+
const child = spawn(plan.command, [...plan.args], {
|
|
366
|
+
// DETACHED ONLY SO THERE IS A PROCESS GROUP TO KILL. The worker still
|
|
367
|
+
// awaits this child — `unref` is deliberately not called — so a writer
|
|
368
|
+
// whose outcome nobody can record is still impossible. What `detached`
|
|
369
|
+
// buys is that a host CLI which spawned helpers of its own cannot survive
|
|
370
|
+
// in them after the watchdog fires.
|
|
371
|
+
detached: true,
|
|
372
|
+
// THE PROMPT GOES ON STDIN, not in `argv`: the day's memories in a command
|
|
373
|
+
// line are readable by every process on the machine through `ps` (S2
|
|
374
|
+
// review, NIT-2). `claude -p` with no positional prompt reads stdin.
|
|
375
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
376
|
+
env: { ...plan.env },
|
|
377
|
+
});
|
|
378
|
+
try {
|
|
379
|
+
child.stdin?.end(plan.stdin);
|
|
380
|
+
} catch {
|
|
381
|
+
/* a child that died before its stdin opened is handled by `error` below */
|
|
382
|
+
}
|
|
383
|
+
/** SIGTERM, then SIGKILL, then stop waiting. Each step arms the next. */
|
|
384
|
+
const terminate = (): void => {
|
|
385
|
+
if (terminated) return;
|
|
386
|
+
terminated = true;
|
|
387
|
+
signal(child, "SIGTERM");
|
|
388
|
+
timers.push(
|
|
389
|
+
arm(() => {
|
|
390
|
+
// The polite ask was ignored. SIGKILL cannot be trapped; the process
|
|
391
|
+
// GROUP goes with it, because a `claude` that spawned its own
|
|
392
|
+
// children would otherwise leave them holding the terminal.
|
|
393
|
+
signal(child, "SIGKILL");
|
|
394
|
+
// ...and if even that does not produce a `close` — a child wedged in
|
|
395
|
+
// an uninterruptible wait is the case — this stops waiting anyway.
|
|
396
|
+
// The worker gets its answer and exits; the row says
|
|
397
|
+
// `failed(unkillable)` rather than nothing at all.
|
|
398
|
+
timers.push(
|
|
399
|
+
arm(() => {
|
|
400
|
+
done({ code: null, timedOut: true, error: "unkillable" });
|
|
401
|
+
}, REAP_GRACE_MS),
|
|
402
|
+
);
|
|
403
|
+
}, KILL_GRACE_MS),
|
|
404
|
+
);
|
|
405
|
+
};
|
|
406
|
+
// THE CHILD'S OWN WATCHDOG, armed here rather than left to `spawn`'s
|
|
407
|
+
// `timeout` option, which only signals and never resolves anything.
|
|
408
|
+
if (Number.isFinite(plan.timeoutMs) && plan.timeoutMs > 0) {
|
|
409
|
+
timers.push(arm(terminate, plan.timeoutMs));
|
|
410
|
+
}
|
|
411
|
+
// THE WORKER'S WATCHDOG, which may be shorter than the child's. Fired, it
|
|
412
|
+
// takes the child with it rather than leaving the worker holding the store
|
|
413
|
+
// open past the life its own contract states.
|
|
414
|
+
if (abort !== undefined) {
|
|
415
|
+
const onAbort = (): void => {
|
|
416
|
+
terminate();
|
|
417
|
+
};
|
|
418
|
+
if (abort.aborted) onAbort();
|
|
419
|
+
else {
|
|
420
|
+
abort.addEventListener("abort", onAbort, { once: true });
|
|
421
|
+
off = (): void => {
|
|
422
|
+
abort.removeEventListener("abort", onAbort);
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
child.on("error", (err) => {
|
|
427
|
+
done({ code: null, timedOut: false, error: err.name });
|
|
428
|
+
});
|
|
429
|
+
child.on("close", (exit, sig) => {
|
|
430
|
+
done({
|
|
431
|
+
code: exit,
|
|
432
|
+
timedOut: terminated || sig === "SIGTERM" || sig === "SIGKILL",
|
|
433
|
+
error: terminated ? "killed" : null,
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** A timer that never keeps the process alive on its own. */
|
|
440
|
+
function arm(fn: () => void, ms: number): ReturnType<typeof setTimeout> {
|
|
441
|
+
const t = setTimeout(fn, ms);
|
|
442
|
+
t.unref?.();
|
|
443
|
+
return t;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Signal the child's whole process GROUP where the platform has one, falling
|
|
448
|
+
* back to the child alone. A host CLI that spawned helpers of its own would
|
|
449
|
+
* otherwise survive in them.
|
|
450
|
+
*/
|
|
451
|
+
function signal(child: { pid?: number | undefined; kill: (s: NodeJS.Signals) => boolean }, sig: NodeJS.Signals): void {
|
|
452
|
+
try {
|
|
453
|
+
if (child.pid !== undefined) process.kill(-child.pid, sig);
|
|
454
|
+
} catch {
|
|
455
|
+
/* no group, or already gone — fall through to the child itself */
|
|
456
|
+
}
|
|
457
|
+
try {
|
|
458
|
+
child.kill(sig);
|
|
459
|
+
} catch {
|
|
460
|
+
/* already gone */
|
|
461
|
+
}
|
|
462
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE PRIMACY RESOLVER — who delivers, for the parallel run only.
|
|
3
|
+
*
|
|
4
|
+
* For one or two weeks v2 runs BESIDE v1 (bansai) on the owner's real sessions.
|
|
5
|
+
* The parallel-run contract's G3 is that exactly one system delivers: two wakes,
|
|
6
|
+
* two recall blocks and two episode asks in the same context is not a comparison,
|
|
7
|
+
* it is noise the owner has to live inside.
|
|
8
|
+
*
|
|
9
|
+
* v1 already owns the switch. It reads `~/.memory-ab/assignment.json` — the file
|
|
10
|
+
* the retired engram pairing left behind — and MUTES its wake, its recall
|
|
11
|
+
* injection and its episode ask only when the resolved system is `engram`. v2
|
|
12
|
+
* occupies the slot engram vacated: `override: "engram"` means "the other one
|
|
13
|
+
* delivers today", and the other one is now this.
|
|
14
|
+
*
|
|
15
|
+
* {"mode":"alternate-day","anchor":"2026-07-17","override":"bansai"}
|
|
16
|
+
*
|
|
17
|
+
* **The rule that makes the joint failure state safe: we FAIL TOWARD MUTE.**
|
|
18
|
+
* v1 fails toward INJECT — a missing, torn or unrecognized file resolves to
|
|
19
|
+
* "both", and v1 speaks. So this resolver delivers on exactly ONE reading of the
|
|
20
|
+
* file (it parsed, and `override` is the string `engram`) and stands down on
|
|
21
|
+
* every other reading, named. Two failing resolvers therefore land on v1-only,
|
|
22
|
+
* never on silence and never on a double injection.
|
|
23
|
+
*
|
|
24
|
+
* `assignmentHealth()` is the preflight's half. `override: null` is the state
|
|
25
|
+
* that must not exist during the run: v1 would fall back to `alternate-day`
|
|
26
|
+
* against a system that no longer exists and mute ITSELF every other day, while
|
|
27
|
+
* v2 (reading no `engram`) mutes every day — the silence neither resolver's own
|
|
28
|
+
* fail direction can produce alone. The preflight asserts it away before Phase P
|
|
29
|
+
* starts rather than discovering it as a quiet day.
|
|
30
|
+
*
|
|
31
|
+
* Nothing here throws, nothing here caches, nothing here writes. The directory
|
|
32
|
+
* is resolved AT CALL TIME so a test (and the preflight) can redirect it with
|
|
33
|
+
* `MEMORY_AB_DIR` without this module having been loaded in a particular order.
|
|
34
|
+
*/
|
|
35
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
36
|
+
import { homedir } from "node:os";
|
|
37
|
+
import { join } from "node:path";
|
|
38
|
+
|
|
39
|
+
/** The one environment variable that moves the A/B directory. Tests use it. */
|
|
40
|
+
export const AB_DIR_ENV = "MEMORY_AB_DIR";
|
|
41
|
+
|
|
42
|
+
/** The system v1's assignment file names when it means "stand down". */
|
|
43
|
+
export const V2_OVERRIDE = "engram";
|
|
44
|
+
|
|
45
|
+
/** Read at call time, never cached: the directory may move between calls. */
|
|
46
|
+
export function abDir(): string {
|
|
47
|
+
return process.env[AB_DIR_ENV] ?? join(homedir(), ".memory-ab");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function assignmentPath(): string {
|
|
51
|
+
return join(abDir(), "assignment.json");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type AssignmentState = "ok" | "missing" | "unreadable" | "malformed";
|
|
55
|
+
|
|
56
|
+
/** v1's file, as far as v2 is entitled to understand it. Strings or null. */
|
|
57
|
+
export interface Assignment {
|
|
58
|
+
readonly override: string | null;
|
|
59
|
+
readonly mode: string | null;
|
|
60
|
+
readonly anchor: string | null;
|
|
61
|
+
readonly state: AssignmentState;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A pure read. Never throws — a resolver that can throw is a resolver that can
|
|
66
|
+
* fail a hook, and the fail direction would then be the host's, not ours.
|
|
67
|
+
*/
|
|
68
|
+
export function readAssignment(): Assignment {
|
|
69
|
+
const empty = { override: null, mode: null, anchor: null } as const;
|
|
70
|
+
const path = assignmentPath();
|
|
71
|
+
if (!existsSync(path)) return { ...empty, state: "missing" };
|
|
72
|
+
let raw: string;
|
|
73
|
+
try {
|
|
74
|
+
raw = readFileSync(path, "utf8");
|
|
75
|
+
} catch {
|
|
76
|
+
return { ...empty, state: "unreadable" };
|
|
77
|
+
}
|
|
78
|
+
let parsed: unknown;
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(raw);
|
|
81
|
+
} catch {
|
|
82
|
+
// A torn write mid-run reads as unreadable, not as an assignment.
|
|
83
|
+
return { ...empty, state: "unreadable" };
|
|
84
|
+
}
|
|
85
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
86
|
+
return { ...empty, state: "malformed" };
|
|
87
|
+
}
|
|
88
|
+
const rec = parsed as Record<string, unknown>;
|
|
89
|
+
const str = (key: string): string | null =>
|
|
90
|
+
typeof rec[key] === "string" ? (rec[key] as string) : null;
|
|
91
|
+
return { override: str("override"), mode: str("mode"), anchor: str("anchor"), state: "ok" };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type PrimacyReason =
|
|
95
|
+
| "override-engram"
|
|
96
|
+
| "override-bansai"
|
|
97
|
+
| "override-absent"
|
|
98
|
+
| "file-missing"
|
|
99
|
+
| "unreadable"
|
|
100
|
+
| "malformed";
|
|
101
|
+
|
|
102
|
+
export interface Primacy {
|
|
103
|
+
/** True on exactly one reading of the file. Everything else is a stand-down. */
|
|
104
|
+
readonly deliver: boolean;
|
|
105
|
+
/** Who is delivering right now, as the daily record spells it. */
|
|
106
|
+
readonly system: "v1" | "v2";
|
|
107
|
+
readonly reason: PrimacyReason;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Should v2 deliver into this session's context?
|
|
112
|
+
*
|
|
113
|
+
* TRUE iff the file parses and `override === "engram"`. Every other reading is
|
|
114
|
+
* a named refusal — the fail-toward-mute rule at the top of this file.
|
|
115
|
+
*/
|
|
116
|
+
export function primacy(): Primacy {
|
|
117
|
+
const assignment = readAssignment();
|
|
118
|
+
if (assignment.state === "missing") return mute("file-missing");
|
|
119
|
+
if (assignment.state === "unreadable") return mute("unreadable");
|
|
120
|
+
if (assignment.state === "malformed") return mute("malformed");
|
|
121
|
+
if (assignment.override === V2_OVERRIDE) {
|
|
122
|
+
return { deliver: true, system: "v2", reason: "override-engram" };
|
|
123
|
+
}
|
|
124
|
+
if (assignment.override === "bansai") return mute("override-bansai");
|
|
125
|
+
// null, "none", "counterparts", or any other string: v1 does not read it as
|
|
126
|
+
// "stand down", so v2 must not read it as "deliver".
|
|
127
|
+
return mute("override-absent");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function mute(reason: PrimacyReason): Primacy {
|
|
131
|
+
return { deliver: false, system: "v1", reason };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface AssignmentHealth {
|
|
135
|
+
/** Only an EXPLICIT `bansai` or `engram` is a state the run may start in. */
|
|
136
|
+
readonly healthy: boolean;
|
|
137
|
+
readonly reason: PrimacyReason;
|
|
138
|
+
/** Advisory: `alternate-day` against a retired engram is the latent hazard. */
|
|
139
|
+
readonly mode: string | null;
|
|
140
|
+
readonly override: string | null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The preflight's check. Healthy requires `override` to be exactly `bansai` or
|
|
145
|
+
* `engram` — the two readings under which the two resolvers cannot both mute.
|
|
146
|
+
* `mode` rides along unjudged so the preflight can note that a file whose
|
|
147
|
+
* override is ever cleared falls back to day-alternation against a system that
|
|
148
|
+
* is not there any more.
|
|
149
|
+
*/
|
|
150
|
+
export function assignmentHealth(): AssignmentHealth {
|
|
151
|
+
const assignment = readAssignment();
|
|
152
|
+
const verdict = primacy();
|
|
153
|
+
const healthy =
|
|
154
|
+
assignment.state === "ok" &&
|
|
155
|
+
(assignment.override === V2_OVERRIDE || assignment.override === "bansai");
|
|
156
|
+
return {
|
|
157
|
+
healthy,
|
|
158
|
+
reason: verdict.reason,
|
|
159
|
+
mode: assignment.mode,
|
|
160
|
+
override: assignment.override,
|
|
161
|
+
};
|
|
162
|
+
}
|