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,522 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* The detached worker — everything the foreground hook refused to wait for.
|
|
4
|
+
*
|
|
5
|
+
* Started by `spawn.ts` with a pinned environment (`COUNTERPARTS_DATA_DIR` last)
|
|
6
|
+
* and a watchdog it is TOLD about (`COUNTERPARTS_WATCHDOG_MS`), so the timeout
|
|
7
|
+
* that guards this process is the same number the spawner validated against
|
|
8
|
+
* `remember/`'s claim-staleness window. It arms that watchdog itself as well as
|
|
9
|
+
* being subject to the parent's, because a child that hangs past the window can
|
|
10
|
+
* hold spans a second run would also claim (scars E4/E5, SEAMS queued item 10).
|
|
11
|
+
*
|
|
12
|
+
* What it runs, in order (the composition root owns the order, not this file):
|
|
13
|
+
* 0a. the LAGGED SEMANTIC CUE for the session that just spoke — before
|
|
14
|
+
* anything else, because it reads the live span buffer and the sweep's
|
|
15
|
+
* claim moves those spans out of it (`vectors.ts`). It runs on EVERY
|
|
16
|
+
* boundary, outside the sweep gate and regardless of its verdict: the cue
|
|
17
|
+
* expires after one turn, so a step that fired only when a session had
|
|
18
|
+
* crashed would leave the semantic channel dark on every ordinary turn;
|
|
19
|
+
* 0b. one bounded EMBEDDING BACKFILL, on the same terms and for the same
|
|
20
|
+
* reason — the store's blind memories gain vectors at a guaranteed rate
|
|
21
|
+
* rather than only when a deposit happens to pay for one, and running it
|
|
22
|
+
* first means a long sweep cannot starve it;
|
|
23
|
+
* 1. the crash-fallback sweep, over EVERY scope holding experience (§2 G9) —
|
|
24
|
+
* which SELECTS NOTHING unless a session actually crashed (uncovered spans,
|
|
25
|
+
* no `session-end` boundary, silent for `CRASH_STALE_MS`). This worker is
|
|
26
|
+
* spawned at every boundary for the flush and the cycle below; the sweep is
|
|
27
|
+
* a fallback and its ordinary answer is "nothing crashed", recorded as the
|
|
28
|
+
* durable `sweep.gate` row so the silence is evidenced (owner ruling
|
|
29
|
+
* 2026-09-04, `remember/fallback.ts`);
|
|
30
|
+
* 2. the Hebbian flush;
|
|
31
|
+
* 3. the sleep cycle, whose last content write is the wake briefing;
|
|
32
|
+
* 4. the DAILY ROTATING SNAPSHOT (`adapters/snapshots.ts`), last and outside
|
|
33
|
+
* the cycle. Last because it copies the state the three steps above just
|
|
34
|
+
* left; outside because sleep must not learn that the floor is changing —
|
|
35
|
+
* it is not a `core/sleep/` phase and never becomes one. It runs in the
|
|
36
|
+
* `finally` below, so a boundary that FAILED still gets its copy: the day
|
|
37
|
+
* the worker breaks is the day a backup is worth most.
|
|
38
|
+
*
|
|
39
|
+
* **IT DEGRADES, STEP BY STEP; IT DOES NOT REFUSE** (I32, 2026-09-11). Exactly
|
|
40
|
+
* one of the five jobs above needs a model credential — the sweep — and until
|
|
41
|
+
* this date its absence refused the SPAWN, so a blanked credentials file stopped
|
|
42
|
+
* the clock, the flush, the cue, the backfill and the cycle for a week while
|
|
43
|
+
* every visible surface read healthy. Each step now asks its own question and
|
|
44
|
+
* records its own answer by name: the sweep's is `sweep.gate` with
|
|
45
|
+
* `reason: "no-credential"`, the vector steps' are `no-credentials` /
|
|
46
|
+
* `embedder-off`. A step that cannot run says so where tomorrow can read it.
|
|
47
|
+
*
|
|
48
|
+
* It exits 0 on every path. Nothing about a failed run may reach the host.
|
|
49
|
+
*/
|
|
50
|
+
import { readFileSync } from "node:fs";
|
|
51
|
+
import { resolve } from "node:path";
|
|
52
|
+
import { fileURLToPath } from "node:url";
|
|
53
|
+
|
|
54
|
+
import { Counterpart, RUNNER_FAILED_EVENT } from "../../../core/counterpart.js";
|
|
55
|
+
import { dataDir, describeGuardRefusal } from "../../../core/store/index.js";
|
|
56
|
+
|
|
57
|
+
import {
|
|
58
|
+
configLine,
|
|
59
|
+
defaultConfigPath,
|
|
60
|
+
implicitConfigRefusal,
|
|
61
|
+
namedConfigRefusal,
|
|
62
|
+
namedUnreadableRefusal,
|
|
63
|
+
resolveConfigPath,
|
|
64
|
+
} from "../../config-path.js";
|
|
65
|
+
import type { ConfigChoice } from "../../config-path.js";
|
|
66
|
+
|
|
67
|
+
import { loadConfig } from "../config.js";
|
|
68
|
+
import type { AdapterConfig } from "../config.js";
|
|
69
|
+
import { loadCredentials, permissionWarning } from "../credentials.js";
|
|
70
|
+
import type { CredentialLoad } from "../credentials.js";
|
|
71
|
+
import { openEmbedder } from "../index.js";
|
|
72
|
+
import type { LiveEmbedder } from "../embed-client.js";
|
|
73
|
+
import { interpretClient } from "../interpret-client.js";
|
|
74
|
+
import type { FetchLike } from "../interpret-client.js";
|
|
75
|
+
import { API_KEY_ENV, EMBED_KEY_ENV } from "../config.js";
|
|
76
|
+
import { runPageWriter } from "../page-writer.js";
|
|
77
|
+
import type { PageWriterStarter } from "../page-writer.js";
|
|
78
|
+
import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV } from "../spawn.js";
|
|
79
|
+
import { backfillVectors, laggedSemantic } from "../vectors.js";
|
|
80
|
+
import type { BackfillReport, LagReport } from "../vectors.js";
|
|
81
|
+
import { runSnapshot } from "../../snapshots.js";
|
|
82
|
+
import type { SnapshotRunReport } from "../../snapshots.js";
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The default, unchanged: the same file the hook reads when nobody says
|
|
86
|
+
* otherwise. `--config <absolute path>` and the `COUNTERPARTS_CONFIG` the
|
|
87
|
+
* spawner pins override it in that order (`adapters/config-path.ts`).
|
|
88
|
+
*/
|
|
89
|
+
export const CONFIG_PATH = defaultConfigPath();
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Which configuration this worker will read, and which rule chose it. Exported
|
|
93
|
+
* and injectable so the pinned case — the only one a hook produces — is provable
|
|
94
|
+
* without a process.
|
|
95
|
+
*/
|
|
96
|
+
export function runnerConfigChoice(
|
|
97
|
+
argv: readonly string[] = process.argv.slice(2),
|
|
98
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
99
|
+
): ConfigChoice {
|
|
100
|
+
return resolveConfigPath(argv, env as Record<string, string | undefined>);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface RunReport {
|
|
104
|
+
readonly ran: boolean;
|
|
105
|
+
/** `ran` covers the keyless run too: the day HAPPENED, minus the sweep. The
|
|
106
|
+
* step that did not is named on the durable `sweep.gate` row, not here. */
|
|
107
|
+
readonly reason: "ran" | "no-data-dir" | "observer" | "failed";
|
|
108
|
+
readonly swept: number;
|
|
109
|
+
readonly minted: number;
|
|
110
|
+
readonly code: string | null;
|
|
111
|
+
/** The next turn's semantic cue, and the vectors this run bought. Null when
|
|
112
|
+
* the run refused before reaching them. */
|
|
113
|
+
readonly lag: LagReport | null;
|
|
114
|
+
readonly backfill: BackfillReport | null;
|
|
115
|
+
/** The day's copy of the store, or what stopped it. Null when the run refused
|
|
116
|
+
* before it opened a store at all. */
|
|
117
|
+
readonly snapshot: SnapshotRunReport | null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* One run. Exported and injectable so the whole worker is testable without a
|
|
122
|
+
* process, a socket, or a real data directory.
|
|
123
|
+
*/
|
|
124
|
+
export async function runOnce(input: {
|
|
125
|
+
config: AdapterConfig;
|
|
126
|
+
/** Injected so the whole worker is provable without a socket. */
|
|
127
|
+
fetch?: FetchLike;
|
|
128
|
+
today?: string;
|
|
129
|
+
date?: string;
|
|
130
|
+
signal?: AbortSignal;
|
|
131
|
+
/** The session this run follows, and its scope — pinned onto the child by the
|
|
132
|
+
* spawner (`SESSION_ENV` / `SCOPE_ENV`). Absent ⇒ no lagged cue is computed
|
|
133
|
+
* and none is claimed: a run nobody bound to a session has nobody to cue. */
|
|
134
|
+
session?: string;
|
|
135
|
+
scope?: string;
|
|
136
|
+
/** Injected so the whole vector path is provable without a socket. */
|
|
137
|
+
embedder?: LiveEmbedder | null;
|
|
138
|
+
/** The configuration file this process read, pinned onto the nightly page
|
|
139
|
+
* writer's child so parent and child read one file rather than resolving two. */
|
|
140
|
+
configPath?: string;
|
|
141
|
+
/** Injected so `host` mode is provable without launching a host session. */
|
|
142
|
+
startPageWriter?: PageWriterStarter;
|
|
143
|
+
/** Defaults to `process.env`: read for PRESENCE of the embed key, never value. */
|
|
144
|
+
env?: NodeJS.ProcessEnv;
|
|
145
|
+
onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
|
|
146
|
+
}): Promise<RunReport> {
|
|
147
|
+
const { config } = input;
|
|
148
|
+
const emit = input.onEvent ?? ((): void => {});
|
|
149
|
+
if (config.dataDir === undefined || config.dataDir.trim().length === 0) {
|
|
150
|
+
emit("runner.refused", { reason: "no-data-dir" });
|
|
151
|
+
return { ran: false, reason: "no-data-dir", swept: 0, minted: 0, code: null, lag: null, backfill: null, snapshot: null };
|
|
152
|
+
}
|
|
153
|
+
if (config.observer === true) {
|
|
154
|
+
// A cycle advances the clock, decays the store and rewrites the briefing:
|
|
155
|
+
// the instrument mutating what it measures (§15 G3).
|
|
156
|
+
emit("runner.refused", { reason: "observer" });
|
|
157
|
+
return { ran: false, reason: "observer", swept: 0, minted: 0, code: null, lag: null, backfill: null, snapshot: null };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The embedder, when the owner switched it on. This is the composition root
|
|
161
|
+
// that MINTS — the fallback sweep runs here — so an embedder wired only into
|
|
162
|
+
// `openAdapter` would be an embedder the memories never meet. Its `fetch` is
|
|
163
|
+
// the same injected one the interpreter uses, so the whole worker stays
|
|
164
|
+
// provable without a socket.
|
|
165
|
+
const embedder =
|
|
166
|
+
input.embedder !== undefined
|
|
167
|
+
? input.embedder
|
|
168
|
+
: openEmbedder(config, {
|
|
169
|
+
// ONE injected `fetch` for the whole worker; the two clients call
|
|
170
|
+
// different endpoints, and a fake that answers both proves it.
|
|
171
|
+
...(input.fetch === undefined ? {} : { fetch: input.fetch }),
|
|
172
|
+
...(input.today === undefined ? {} : { today: input.today }),
|
|
173
|
+
...(input.signal === undefined ? {} : { signal: input.signal }),
|
|
174
|
+
onEvent: emit,
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
const counterpart = Counterpart.open({
|
|
178
|
+
dir: config.dataDir,
|
|
179
|
+
...(embedder === null ? {} : { embed: embedder.embed, vectors: embedder }),
|
|
180
|
+
...(config.injectionBudgetBytes === undefined
|
|
181
|
+
? {}
|
|
182
|
+
: { budgetBytes: config.injectionBudgetBytes }),
|
|
183
|
+
...(config.owner === undefined ? {} : { owner: config.owner }),
|
|
184
|
+
onEvent: (e) => emit(e.name, { ...(e.data ?? {}) }),
|
|
185
|
+
});
|
|
186
|
+
// The embed credential, by PRESENCE only — the value is never read here and
|
|
187
|
+
// never logged. `embedClient` makes the same check before it opens a socket;
|
|
188
|
+
// asking here is what lets the two vector steps record `no-credentials` as a
|
|
189
|
+
// NAME instead of as a failed call nobody can tell from an empty store.
|
|
190
|
+
const env = input.env ?? process.env;
|
|
191
|
+
const hasCredential = (env[EMBED_KEY_ENV] ?? "").trim().length > 0;
|
|
192
|
+
// THE INTERPRET CREDENTIAL, by PRESENCE only, and read here rather than
|
|
193
|
+
// refused at the spawn (I32). `runnerConfig` has already filled the gap from
|
|
194
|
+
// the configured credentials file, so this is the whole question. Its VALUE is
|
|
195
|
+
// never read, never logged, never compared.
|
|
196
|
+
//
|
|
197
|
+
// Four of this worker's five jobs — the cue, the backfill, the Hebbian flush
|
|
198
|
+
// and the sleep cycle (clock, decay, prune, dedup, consolidate, briefing) —
|
|
199
|
+
// need no model call at all. Only the crash-fallback sweep does. So a missing
|
|
200
|
+
// key costs the sweep and nothing else, and the sweep's own gate row says so
|
|
201
|
+
// by name. Refusing the whole run instead is what froze the lived-day clock
|
|
202
|
+
// for a week while every visible surface read healthy.
|
|
203
|
+
const hasInterpretCredential = (env[API_KEY_ENV] ?? "").trim().length > 0;
|
|
204
|
+
|
|
205
|
+
// ONE DATE FOR THE WHOLE RUN, resolved before the first step that could
|
|
206
|
+
// record anything. The `sweep.gate` row carries it; so must every failure row,
|
|
207
|
+
// or a replay with a pinned date would dedup against the wall clock instead.
|
|
208
|
+
const today = input.date ?? new Date().toISOString().slice(0, 10);
|
|
209
|
+
|
|
210
|
+
let lag: LagReport | null = null;
|
|
211
|
+
let backfill: BackfillReport | null = null;
|
|
212
|
+
try {
|
|
213
|
+
// 0a. BEFORE THE SWEEP. The cue is read out of the LIVE span buffer and the
|
|
214
|
+
// sweep's claim moves those spans out of it — run this after `sessionEnd`
|
|
215
|
+
// and the session that just spoke has nothing left to be cued from.
|
|
216
|
+
// BOTH or neither: a data dir is not a scope, and guessing one would look
|
|
217
|
+
// in the wrong span stream and report `no-text` for a session that spoke.
|
|
218
|
+
if (
|
|
219
|
+
input.session !== undefined &&
|
|
220
|
+
input.session.length > 0 &&
|
|
221
|
+
input.scope !== undefined &&
|
|
222
|
+
input.scope.length > 0
|
|
223
|
+
) {
|
|
224
|
+
lag = await laggedSemantic({
|
|
225
|
+
counterpart,
|
|
226
|
+
sessionId: input.session,
|
|
227
|
+
scope: input.scope,
|
|
228
|
+
embedder,
|
|
229
|
+
hasCredential,
|
|
230
|
+
onEvent: emit,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
// 0b. One bounded batch, before the variable-length sweep, so a long sweep
|
|
234
|
+
// (or the watchdog that ends one) cannot starve the store's blind memories.
|
|
235
|
+
backfill = await backfillVectors({ counterpart, embedder, hasCredential, onEvent: emit });
|
|
236
|
+
} catch (err) {
|
|
237
|
+
// Neither step may cost the run. A cue is a nicety; the sweep is the day.
|
|
238
|
+
const code = err instanceof Error ? err.name : "UNKNOWN";
|
|
239
|
+
emit("vectors.failed", { code });
|
|
240
|
+
// DURABLE, now that the counterpart is open (I32): a vector step that failed
|
|
241
|
+
// inside a detached process wrote to a ring that nothing ever read, and
|
|
242
|
+
// stdio is ignored on this path by construction.
|
|
243
|
+
noteFailure(counterpart, emit, code, "vectors", today);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Step 4's answer, filled in the `finally` below and joined to whichever of
|
|
247
|
+
// the two results the boundary produced. A `let` rather than a fourth return
|
|
248
|
+
// arm because the copy must happen on BOTH paths and before `close()`.
|
|
249
|
+
let snapshotReport: SnapshotRunReport | null = null;
|
|
250
|
+
let result: RunReport;
|
|
251
|
+
try {
|
|
252
|
+
// NO INTERPRETER IS BUILT when there is no key. Not a client that would
|
|
253
|
+
// refuse at its first call — the sweep would then claim spans, hand them to
|
|
254
|
+
// something that cannot read them, and the claim would have to be restored.
|
|
255
|
+
// The boundary is told "skipped, and why" instead, and everything that does
|
|
256
|
+
// not need a model still runs.
|
|
257
|
+
const report = await counterpart.sessionEnd({
|
|
258
|
+
date: today,
|
|
259
|
+
at: today,
|
|
260
|
+
sweep: hasInterpretCredential
|
|
261
|
+
? {
|
|
262
|
+
interpret: interpretClient({
|
|
263
|
+
config,
|
|
264
|
+
...(input.fetch === undefined ? {} : { fetch: input.fetch }),
|
|
265
|
+
...(input.today === undefined ? {} : { today: input.today }),
|
|
266
|
+
...(input.signal === undefined ? {} : { signal: input.signal }),
|
|
267
|
+
onEvent: emit,
|
|
268
|
+
}),
|
|
269
|
+
}
|
|
270
|
+
: { skipped: "no-credential" },
|
|
271
|
+
});
|
|
272
|
+
const swept = report.sweeps.reduce((n, s) => n + s.spansSwept, 0);
|
|
273
|
+
const minted = report.sweeps.reduce((n, s) => n + s.proposals, 0);
|
|
274
|
+
emit("runner.done", {
|
|
275
|
+
day: report.cycle.day,
|
|
276
|
+
scopes: report.sweeps.length,
|
|
277
|
+
swept,
|
|
278
|
+
minted,
|
|
279
|
+
edges: report.edges.reason,
|
|
280
|
+
// What this run carried in from the hooks' pending file — the host's own
|
|
281
|
+
// learned association, which no hook writes any more.
|
|
282
|
+
carried: report.carried?.reason ?? "threw",
|
|
283
|
+
carriedRows: report.carried?.rows ?? 0,
|
|
284
|
+
interpret: hasInterpretCredential,
|
|
285
|
+
});
|
|
286
|
+
result = { ran: true, reason: "ran", swept, minted, code: null, lag, backfill, snapshot: null };
|
|
287
|
+
} catch (err) {
|
|
288
|
+
const code =
|
|
289
|
+
err !== null && typeof err === "object" && typeof (err as { code?: unknown }).code === "string"
|
|
290
|
+
? (err as { code: string }).code
|
|
291
|
+
: "UNKNOWN";
|
|
292
|
+
emit("runner.failed", { code });
|
|
293
|
+
// Durable before `close()` in the `finally` below — a worker that died at
|
|
294
|
+
// the boundary is the failure a person most needs to be able to read
|
|
295
|
+
// tomorrow, and this process's stderr goes nowhere (I32).
|
|
296
|
+
noteFailure(counterpart, emit, code, "sessionEnd", today);
|
|
297
|
+
result = { ran: false, reason: "failed", swept: 0, minted: 0, code, lag, backfill, snapshot: null };
|
|
298
|
+
} finally {
|
|
299
|
+
// 4. THE DAY'S COPY OF THE STORE — after everything above has written, on
|
|
300
|
+
// the failed path as well as the good one, and before the store is closed.
|
|
301
|
+
// It never throws by construction (`adapters/snapshots.ts`); the try is
|
|
302
|
+
// belt and braces, because a backup that took the worker down with it would
|
|
303
|
+
// be the mechanism defeating its own purpose.
|
|
304
|
+
try {
|
|
305
|
+
snapshotReport = runSnapshot({
|
|
306
|
+
counterpart,
|
|
307
|
+
dataDir: config.dataDir,
|
|
308
|
+
...(config.snapshots === undefined ? {} : { config: config.snapshots }),
|
|
309
|
+
date: today,
|
|
310
|
+
...(input.signal === undefined ? {} : { signal: input.signal }),
|
|
311
|
+
});
|
|
312
|
+
emit("runner.snapshot", {
|
|
313
|
+
reason: snapshotReport.reason,
|
|
314
|
+
name: snapshotReport.name,
|
|
315
|
+
kept: snapshotReport.rotation?.kept ?? 0,
|
|
316
|
+
deleted: snapshotReport.rotation?.deleted.length ?? 0,
|
|
317
|
+
ms: snapshotReport.ms,
|
|
318
|
+
});
|
|
319
|
+
} catch (err) {
|
|
320
|
+
emit("snapshot.threw", { code: err instanceof Error ? err.name : "UNKNOWN" });
|
|
321
|
+
}
|
|
322
|
+
// 5. THE NIGHT'S PAGE WRITER, in `host` mode only (S2). Last, and inside
|
|
323
|
+
// the `finally` beside the snapshot, for the same two reasons: it must run
|
|
324
|
+
// on the failed path as well as the good one — a day whose sweep broke is
|
|
325
|
+
// still a day that was lived — and it must run before the store closes, so
|
|
326
|
+
// the outcome it reads is read through the same handle everything else
|
|
327
|
+
// wrote through. It never throws (`page-writer.ts`), and on every other
|
|
328
|
+
// mode it is one comparison and a return.
|
|
329
|
+
try {
|
|
330
|
+
const page = await runPageWriter({
|
|
331
|
+
counterpart,
|
|
332
|
+
config,
|
|
333
|
+
...(input.configPath === undefined ? {} : { configPath: input.configPath }),
|
|
334
|
+
...(input.startPageWriter === undefined ? {} : { start: input.startPageWriter }),
|
|
335
|
+
// THE WORKER'S OWN WATCHDOG OUTRANKS THE WRITER'S. They are different
|
|
336
|
+
// numbers (5 minutes here, 10 for the child by default) and without this
|
|
337
|
+
// the worker would sit in this `finally` for twice the life it promises.
|
|
338
|
+
...(input.signal === undefined ? {} : { signal: input.signal }),
|
|
339
|
+
});
|
|
340
|
+
if (page.ran || page.outcome !== "skipped") {
|
|
341
|
+
emit("runner.page-writer", { outcome: page.outcome, about: page.about, detail: page.detail });
|
|
342
|
+
}
|
|
343
|
+
} catch (err) {
|
|
344
|
+
emit("page-writer.threw", { code: err instanceof Error ? err.name : "UNKNOWN" });
|
|
345
|
+
}
|
|
346
|
+
counterpart.close();
|
|
347
|
+
}
|
|
348
|
+
return { ...result, snapshot: snapshotReport };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* One durable row for a step that failed inside the detached worker.
|
|
353
|
+
*
|
|
354
|
+
* Pre-open failures are NOT covered here and do not need to be: the parent's
|
|
355
|
+
* `adapter.spawn.refused` / `adapter.spawn.failed` row already says the worker
|
|
356
|
+
* never got as far as a store. This is the other half — it opened one, and then
|
|
357
|
+
* something went wrong where nobody was looking.
|
|
358
|
+
*
|
|
359
|
+
* `dedupKey` gates it to one row per step per calendar date, the same rule the
|
|
360
|
+
* spawn rows follow, so a failure that repeats at every boundary is a fact and
|
|
361
|
+
* not a flood. It never throws: a failed record may not turn a failed step into
|
|
362
|
+
* a failed process.
|
|
363
|
+
*/
|
|
364
|
+
function noteFailure(
|
|
365
|
+
counterpart: Counterpart,
|
|
366
|
+
emit: (name: string, data: Record<string, string | number | boolean | null>) => void,
|
|
367
|
+
code: string,
|
|
368
|
+
step: string,
|
|
369
|
+
date: string,
|
|
370
|
+
): void {
|
|
371
|
+
if (counterpart.observer) return;
|
|
372
|
+
try {
|
|
373
|
+
counterpart.noteAdapterEvent(
|
|
374
|
+
RUNNER_FAILED_EVENT,
|
|
375
|
+
{ code, step, date },
|
|
376
|
+
{ dedupKey: `${RUNNER_FAILED_EVENT}:${step}:${date}` },
|
|
377
|
+
);
|
|
378
|
+
} catch (err) {
|
|
379
|
+
emit("runner.record.failed", { code: err instanceof Error ? err.name : "UNKNOWN" });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** The watchdog this process arms on itself, from the number it was told. */
|
|
384
|
+
export function watchdogMs(env: Record<string, string | undefined> = process.env): number | null {
|
|
385
|
+
const raw = env[WATCHDOG_ENV];
|
|
386
|
+
if (raw === undefined) return null;
|
|
387
|
+
const parsed = Number(raw);
|
|
388
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The data dir this process was PINNED to. Never resolved from anywhere else. */
|
|
392
|
+
export function pinnedDataDir(env: Record<string, string | undefined> = process.env): string | null {
|
|
393
|
+
const raw = env[DATA_DIR_ENV];
|
|
394
|
+
return raw !== undefined && raw.trim().length > 0 ? raw : null;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The session (and its scope) this process was told to follow. Read from the
|
|
398
|
+
* pinned environment for the same reason the data dir is: the spawner wrote
|
|
399
|
+
* them last, so nothing a caller exported can redirect the cue. */
|
|
400
|
+
export function pinnedSession(env: Record<string, string | undefined> = process.env): string | null {
|
|
401
|
+
const raw = env[SESSION_ENV];
|
|
402
|
+
return raw !== undefined && raw.trim().length > 0 ? raw : null;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function pinnedScope(env: Record<string, string | undefined> = process.env): string | null {
|
|
406
|
+
const raw = env[SCOPE_ENV];
|
|
407
|
+
return raw !== undefined && raw.trim().length > 0 ? raw : null;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function isEntryPoint(argv1: string | undefined, url: string): boolean {
|
|
411
|
+
if (argv1 === undefined) return false;
|
|
412
|
+
return resolve(argv1) === fileURLToPath(new URL(url));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* This process's configuration, its pinned data dir, and its credential load.
|
|
417
|
+
*
|
|
418
|
+
* BELT AND BRACES on the credential. A worker the hook spawned already carries
|
|
419
|
+
* the keys — the spawner copies `process.env` into the child, and the hook
|
|
420
|
+
* filled the gap before that copy — but this process also runs when nothing
|
|
421
|
+
* spawned it that way, and it reads the same configuration, so it loads from the
|
|
422
|
+
* same configured file rather than assuming an ancestor did. The load is a no-op
|
|
423
|
+
* where the keys are already there: the ENVIRONMENT WINS, always, and an
|
|
424
|
+
* inherited key is reported as `skippedPresent`, not overwritten.
|
|
425
|
+
*
|
|
426
|
+
* Exported and injectable so the runner's credential path is provable without a
|
|
427
|
+
* process (the entry point itself is not importable).
|
|
428
|
+
*/
|
|
429
|
+
export function runnerConfig(
|
|
430
|
+
path = CONFIG_PATH,
|
|
431
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
432
|
+
): { config: AdapterConfig; credentials: CredentialLoad; reason: string } {
|
|
433
|
+
let raw: unknown;
|
|
434
|
+
try {
|
|
435
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
436
|
+
} catch {
|
|
437
|
+
raw = undefined;
|
|
438
|
+
}
|
|
439
|
+
const loaded = loadConfig(raw);
|
|
440
|
+
const credentials = loadCredentials(loaded.config.credentialsFile, env);
|
|
441
|
+
const pinned = pinnedDataDir(env);
|
|
442
|
+
return {
|
|
443
|
+
config: {
|
|
444
|
+
...loaded.config,
|
|
445
|
+
// The PIN wins. The spawner wrote it last precisely so nothing else can.
|
|
446
|
+
dataDir: pinned ?? loaded.config.dataDir ?? dataDir(),
|
|
447
|
+
},
|
|
448
|
+
credentials,
|
|
449
|
+
reason: loaded.reason,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async function main(): Promise<void> {
|
|
454
|
+
const choice = runnerConfigChoice();
|
|
455
|
+
// The second refusal is the explicit-dir guard (`config-path.ts#implicitConfigRefusal`):
|
|
456
|
+
// armed, an UNNAMED configuration stands the worker down too, because the
|
|
457
|
+
// default one names a store. Never armed on the live host.
|
|
458
|
+
const refusal = namedConfigRefusal(choice) ?? implicitConfigRefusal(choice);
|
|
459
|
+
if (refusal !== null) {
|
|
460
|
+
// Same direction as the hook: a worker told to read a configuration it
|
|
461
|
+
// cannot resolve — relative, or absolute and not there — does NOT fall back
|
|
462
|
+
// to the default store. It says so and exits 0: nothing about a failed run
|
|
463
|
+
// may reach the host. This one matters even though the spawner pins a path
|
|
464
|
+
// the parent already read, because the pin travels through an environment
|
|
465
|
+
// and a file can be moved between the two processes.
|
|
466
|
+
process.stderr.write(`[counterparts] worker stood down: ${refusal}\n`);
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
const { config, credentials, reason } = runnerConfig(choice.path);
|
|
470
|
+
const unreadable = namedUnreadableRefusal(choice, reason);
|
|
471
|
+
if (unreadable !== null) {
|
|
472
|
+
process.stderr.write(`[counterparts] worker stood down: ${unreadable}\n`);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
// Detached, this stderr goes nowhere (`spawn.ts` runs the child with stdio
|
|
476
|
+
// ignored); run by hand it is the line that says which file answered. The
|
|
477
|
+
// record for a detached run is the pin itself — `COUNTERPARTS_CONFIG` in the
|
|
478
|
+
// environment the spawner wrote — and the session record the parent left.
|
|
479
|
+
process.stderr.write(`[counterparts] worker config: ${configLine(choice)}\n`);
|
|
480
|
+
// No ring here — the worker has no adapter — so the permission warning is a
|
|
481
|
+
// stderr line and nothing else. Warned, never refused (§4).
|
|
482
|
+
const warning = permissionWarning(config.credentialsFile, credentials);
|
|
483
|
+
if (warning !== null) process.stderr.write(`${warning}\n`);
|
|
484
|
+
|
|
485
|
+
const timeout = watchdogMs();
|
|
486
|
+
const controller = new AbortController();
|
|
487
|
+
const timer =
|
|
488
|
+
timeout === null
|
|
489
|
+
? null
|
|
490
|
+
: setTimeout(() => {
|
|
491
|
+
controller.abort();
|
|
492
|
+
}, timeout);
|
|
493
|
+
timer?.unref?.();
|
|
494
|
+
try {
|
|
495
|
+
await runOnce({
|
|
496
|
+
config,
|
|
497
|
+
signal: controller.signal,
|
|
498
|
+
...(pinnedSession() === null ? {} : { session: pinnedSession() as string }),
|
|
499
|
+
...(pinnedScope() === null ? {} : { scope: pinnedScope() as string }),
|
|
500
|
+
configPath: choice.path,
|
|
501
|
+
});
|
|
502
|
+
} finally {
|
|
503
|
+
if (timer !== null) clearTimeout(timer);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (isEntryPoint(process.argv[1], import.meta.url)) {
|
|
508
|
+
void main().then(
|
|
509
|
+
() => process.exit(0),
|
|
510
|
+
(err: unknown) => {
|
|
511
|
+
// Exit 0 either way — nothing about a failed run may reach the host — but
|
|
512
|
+
// SAY why, the way the hook does. Before this line, the gap between the
|
|
513
|
+
// two guards (a named configuration that names no store, nothing else
|
|
514
|
+
// naming it) was a bare exit 0 (#80 review). Detached, this goes nowhere;
|
|
515
|
+
// run by hand, it is the reason.
|
|
516
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
517
|
+
const remedy = `Set "dataDir" in ${runnerConfigChoice().path}, or set ${DATA_DIR_ENV}.`;
|
|
518
|
+
process.stderr.write(`[counterparts] worker stood down: ${describeGuardRefusal(err, remedy) ?? detail}\n`);
|
|
519
|
+
process.exit(0);
|
|
520
|
+
},
|
|
521
|
+
);
|
|
522
|
+
}
|