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,479 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE STRIKE — the one place in `remember/` that destroys lived experience.
|
|
3
|
+
*
|
|
4
|
+
* It is the span buffer's half of the destruction path, and it exists because
|
|
5
|
+
* "anything can be removed loudly" (constitution 6/7) was not true of a note.
|
|
6
|
+
* A note is CAPTURED before it is minted: `captureJot` appends the verbatim text
|
|
7
|
+
* to `spans/<key>/jots.jsonl`, and nothing ever pruned that file. `remove`
|
|
8
|
+
* chased the prose, the rows, the links and the cache, reported `unchased:
|
|
9
|
+
* nothing`, and the words stayed on disk — where a later `backup` copied them
|
|
10
|
+
* (LAUNCH-STATUS §I2, measured 2026-09-04; the honest-report half shipped as
|
|
11
|
+
* option A in #53, and this is option B).
|
|
12
|
+
*
|
|
13
|
+
* **Why it is a seam and not a method.** `SpanBuffer` is held by `Counterpart`,
|
|
14
|
+
* which is held by the MCP server, which a model talks to. A public
|
|
15
|
+
* `buffer.strike()` would be the same mistake as a `Store.delete()`: reachable
|
|
16
|
+
* by anyone holding the object (`store/` §5 G2, §16 G1 — "enforced by
|
|
17
|
+
* absence"). So the buffer HANDS this module a capability at construction time
|
|
18
|
+
* (a WeakMap the rest of the program cannot see), exactly the way `Store` hands
|
|
19
|
+
* `store/owner-op-seam.ts` its own, and `test/cli.test.ts` pins who may import
|
|
20
|
+
* this file at all. Nothing reaches `strikeSpans` by having a `SpanBuffer`.
|
|
21
|
+
*
|
|
22
|
+
* **Why it is not an `rmSync` from the destruction path.** `spans/` is
|
|
23
|
+
* `remember/`'s state machine. Spec §2 G6 forbids a span being in NEITHER a
|
|
24
|
+
* claim nor the buffer, and a claim renaming a file out from under a chase is
|
|
25
|
+
* exactly the race that guarantee exists to prevent (cli/INTERFACE-GAPS §9).
|
|
26
|
+
*
|
|
27
|
+
* **The choreography, and what each move is for.** Per text-bearing file:
|
|
28
|
+
*
|
|
29
|
+
* 1. **Ledger first.** Every struck hash goes into `consumed.jsonl` BEFORE a
|
|
30
|
+
* byte moves. That file is the terminal ledger `seenHashes`, `restore` and
|
|
31
|
+
* `mergeOrphans` all already filter against — so from this moment a
|
|
32
|
+
* re-capture of the same words dedups away, a worker mid-arc cannot
|
|
33
|
+
* restore the span it is holding in memory, and a crashed run's orphan
|
|
34
|
+
* cannot merge it back. It is the same disposition a QUARANTINED span
|
|
35
|
+
* gets, and for the same reason: terminal, not pass-through, so scar
|
|
36
|
+
* §2.20's "restored hashes must not enter the ledger" does not apply.
|
|
37
|
+
* 2. **Rename ASIDE, then append the survivors back** — `claim()`'s move, for
|
|
38
|
+
* `claim()`'s reason. `mutate()` is a stance check and a try/catch, NOT a
|
|
39
|
+
* lock: a read-filter-write-over would lose a turn appended between the
|
|
40
|
+
* read and the rename, because that append lands on the old inode. The
|
|
41
|
+
* aside carries a `.striking` suffix, which is not `.jsonl`, so nothing —
|
|
42
|
+
* `claimFiles()` least of all — picks it up as an ordinary orphan.
|
|
43
|
+
* 3. **Fold a previous crash's aside back in first.** A `.striking` file left
|
|
44
|
+
* by a crashed strike is read, filtered through the same predicate, and
|
|
45
|
+
* merged (deduped by hash) before this strike runs. Nothing is stranded.
|
|
46
|
+
*
|
|
47
|
+
* **What it writes.** `strikes.jsonl` beside the streams: counts, file names and
|
|
48
|
+
* a lived day — never a hash, never a word. §16 G9's rule about the removal
|
|
49
|
+
* record is the rule here too: a hash of low-entropy content is brute-forceable,
|
|
50
|
+
* so the durable trace of a destruction must not carry one.
|
|
51
|
+
*/
|
|
52
|
+
import {
|
|
53
|
+
appendFileSync,
|
|
54
|
+
closeSync,
|
|
55
|
+
existsSync,
|
|
56
|
+
fsyncSync,
|
|
57
|
+
openSync,
|
|
58
|
+
readFileSync,
|
|
59
|
+
renameSync,
|
|
60
|
+
rmSync,
|
|
61
|
+
writeSync,
|
|
62
|
+
} from "node:fs";
|
|
63
|
+
import { basename } from "node:path";
|
|
64
|
+
|
|
65
|
+
import type { Span, SpanKind, WriteSite } from "./spans.js";
|
|
66
|
+
|
|
67
|
+
// ── the capability ──────────────────────────────────────────────────────────
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* What a `SpanBuffer` hands this module, and nothing else. Every entry is a
|
|
71
|
+
* bound closure over the buffer's own private members, so the strike writes
|
|
72
|
+
* through the SAME seam (`mutate`) every other write site uses and inherits its
|
|
73
|
+
* stand-down instead of remembering to check.
|
|
74
|
+
*/
|
|
75
|
+
export interface SpanStrikeAccess {
|
|
76
|
+
readonly observer: boolean;
|
|
77
|
+
scopes(): string[];
|
|
78
|
+
scopeDir(scope: string): string;
|
|
79
|
+
path(scope: string, name: string): string;
|
|
80
|
+
claimFiles(scope: string): string[];
|
|
81
|
+
streamPath(scope: string, kind: SpanKind): string;
|
|
82
|
+
ensureScope(scope: string): void;
|
|
83
|
+
readLines<T>(file: string): T[];
|
|
84
|
+
mutate<T>(
|
|
85
|
+
site: WriteSite,
|
|
86
|
+
fn: () => T,
|
|
87
|
+
): { ok: true; value: T } | { ok: false; reason: "OBSERVER" | "IO_FAILED"; code: string };
|
|
88
|
+
emit(name: string, ref?: string, data?: Record<string, string | number | boolean | null>): void;
|
|
89
|
+
now(): number;
|
|
90
|
+
day(): number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const GRANTS = new WeakMap<object, SpanStrikeAccess>();
|
|
94
|
+
|
|
95
|
+
/** Called once, by `SpanBuffer`'s constructor. */
|
|
96
|
+
export function grantSpanStrike(buffer: object, access: SpanStrikeAccess): void {
|
|
97
|
+
GRANTS.set(buffer, access);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ── the request and the report ──────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
export interface StrikeRequest {
|
|
103
|
+
/** One scope, or every scope holding experience when the origin is unrecorded. */
|
|
104
|
+
scope: string | null;
|
|
105
|
+
/**
|
|
106
|
+
* Span hashes to strike — the chase BY IDENTITY. `origin.spanHash` in the
|
|
107
|
+
* memory's prose meta is one; the `own: true` coverage marks for its
|
|
108
|
+
* `origin_ref` are the other, and they are what makes the chase work on rows
|
|
109
|
+
* minted before the meta key existed.
|
|
110
|
+
*/
|
|
111
|
+
hashes?: readonly string[];
|
|
112
|
+
/**
|
|
113
|
+
* The fallback for a memory whose provenance never recorded a hash: a
|
|
114
|
+
* predicate over a span's TEXT. The destruction path passes the doomed body,
|
|
115
|
+
* which is the only thing it can match on before it destroys it. The text
|
|
116
|
+
* never leaves the caller — this module receives a function, not a string.
|
|
117
|
+
*/
|
|
118
|
+
predicate?: (text: string) => boolean;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What one strike touched. Counts and file names — never contents (§16 G9). */
|
|
122
|
+
export interface StrikeReport {
|
|
123
|
+
readonly reason: "STRUCK" | "RECOVERED" | "NOTHING" | "OBSERVER" | "IO_FAILED";
|
|
124
|
+
/** Lines removed, across every file and every scope. */
|
|
125
|
+
readonly struck: number;
|
|
126
|
+
/** Per file, scope-relative: `<12-hex key>/jots.jsonl`. */
|
|
127
|
+
readonly files: readonly { readonly file: string; readonly struck: number }[];
|
|
128
|
+
/** Scopes looked at. A strike with no `scope` looks at all of them. */
|
|
129
|
+
readonly scopes: number;
|
|
130
|
+
/** Hashes appended to `consumed.jsonl` so nothing re-admits the span. */
|
|
131
|
+
readonly ledgered: number;
|
|
132
|
+
/** True when a claim file was one of the files rewritten (see the note below). */
|
|
133
|
+
readonly touchedClaim: boolean;
|
|
134
|
+
/** Asides from a CRASHED earlier strike, folded back before this one ran. */
|
|
135
|
+
readonly recovered: number;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The streams that carry TEXT. Everything else under a scope is hashes and counts. */
|
|
139
|
+
const TEXT_STREAMS: readonly SpanKind[] = ["conversation", "jot", "assistant"];
|
|
140
|
+
|
|
141
|
+
const EMPTY: StrikeReport = {
|
|
142
|
+
reason: "NOTHING",
|
|
143
|
+
struck: 0,
|
|
144
|
+
files: [],
|
|
145
|
+
scopes: 0,
|
|
146
|
+
ledgered: 0,
|
|
147
|
+
touchedClaim: false,
|
|
148
|
+
recovered: 0,
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Strike every span matching the request out of the buffer, atomically per file.
|
|
153
|
+
*
|
|
154
|
+
* It refuses under observer (the stand-down is the buffer's own, emitted from
|
|
155
|
+
* `mutate`) and it never throws: like every path in this module, it returns a
|
|
156
|
+
* REASON, because the caller — the owner's console mid-removal — must be able to
|
|
157
|
+
* report a partial success rather than crash inside a destruction (§16 G15).
|
|
158
|
+
*/
|
|
159
|
+
export function strikeSpans(buffer: object, request: StrikeRequest): StrikeReport {
|
|
160
|
+
const access = GRANTS.get(buffer);
|
|
161
|
+
if (access === undefined) throw new Error("SPAN_STRIKE_UNGRANTED");
|
|
162
|
+
// STANCE FIRST, WORK SECOND — the store seam's ordering and this module's:
|
|
163
|
+
// an instrument refuses before it has read a byte, let alone staged one, and
|
|
164
|
+
// the stand-down is emitted through `mutate` so the totality test sees this
|
|
165
|
+
// site the same way it sees every other (§5 G8). Before the has-anything-to-do
|
|
166
|
+
// check on purpose: "there was nothing to strike" and "I am not allowed to
|
|
167
|
+
// strike" are different answers and must not collapse into each other.
|
|
168
|
+
if (access.observer) {
|
|
169
|
+
access.mutate("strike", () => undefined);
|
|
170
|
+
return { ...EMPTY, reason: "OBSERVER" };
|
|
171
|
+
}
|
|
172
|
+
const hashes = new Set(request.hashes ?? []);
|
|
173
|
+
const predicate = request.predicate;
|
|
174
|
+
if (hashes.size === 0 && predicate === undefined) return EMPTY;
|
|
175
|
+
|
|
176
|
+
// A HASH names one span. A PREDICATE names a shape, and the only shape it is
|
|
177
|
+
// ever allowed to name is a JOT — the memory's own words, deposited as
|
|
178
|
+
// themselves. A conversation span is many turns joined; it belongs to no
|
|
179
|
+
// single memory, and striking one because a memory's body happens to appear
|
|
180
|
+
// inside it would destroy material nobody named. The console reports those
|
|
181
|
+
// lines instead (`SpanSurface.echoes`), and this is the half of that rule
|
|
182
|
+
// that cannot be got round by calling the seam directly.
|
|
183
|
+
const matches = (span: Span): boolean => {
|
|
184
|
+
if (hashes.has(span.hash)) return true;
|
|
185
|
+
if (predicate === undefined || typeof span.text !== "string") return false;
|
|
186
|
+
return span.kind === "jot" && predicate(span.text);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const scopes = request.scope === null ? access.scopes() : [request.scope];
|
|
190
|
+
const files: { file: string; struck: number }[] = [];
|
|
191
|
+
let struck = 0;
|
|
192
|
+
let ledgered = 0;
|
|
193
|
+
let touchedClaim = false;
|
|
194
|
+
let recovered = 0;
|
|
195
|
+
let failed = false;
|
|
196
|
+
let observed = false;
|
|
197
|
+
|
|
198
|
+
for (const scope of scopes) {
|
|
199
|
+
if (!existsSync(access.scopeDir(scope))) continue;
|
|
200
|
+
const targets = [
|
|
201
|
+
...TEXT_STREAMS.map((kind) => access.streamPath(scope, kind)),
|
|
202
|
+
access.path(scope, "quarantine.jsonl"),
|
|
203
|
+
...access.claimFiles(scope),
|
|
204
|
+
];
|
|
205
|
+
|
|
206
|
+
// 0. RECOVERY, FIRST AND UNCONDITIONALLY (review F3). A `.striking` aside is
|
|
207
|
+
// a crashed strike's survivors, sitting off every path the buffer reads:
|
|
208
|
+
// the sweep cannot see them, `claimFiles()` cannot see them, and the
|
|
209
|
+
// console's residue walk used to miss them too. Folding them back is not
|
|
210
|
+
// this strike's business, which is exactly why it must not be gated on
|
|
211
|
+
// this strike having something to do — a scope repaired only by the
|
|
212
|
+
// removal that happens to name it is a scope repaired by luck.
|
|
213
|
+
for (const file of targets) {
|
|
214
|
+
const back = access.mutate("strike", () => foldAside(file));
|
|
215
|
+
if (back.ok) recovered += back.value;
|
|
216
|
+
else if (back.reason === "OBSERVER") observed = true;
|
|
217
|
+
else failed = true;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// The hashes this scope is about to lose, read BEFORE anything moves. The
|
|
221
|
+
// asides are gone by now — folded into their streams above — so this one
|
|
222
|
+
// walk sees everything.
|
|
223
|
+
const doomed = new Set<string>();
|
|
224
|
+
for (const file of targets) {
|
|
225
|
+
for (const span of access.readLines<Span>(file)) {
|
|
226
|
+
if (typeof span.hash === "string" && matches(span)) doomed.add(span.hash);
|
|
227
|
+
}
|
|
228
|
+
for (const span of access.readLines<Span>(`${file}.striking`)) {
|
|
229
|
+
if (typeof span.hash === "string" && matches(span)) doomed.add(span.hash);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (doomed.size === 0) continue;
|
|
233
|
+
|
|
234
|
+
// 1. THE LEDGER, first and on its own. If this fails, nothing is rewritten:
|
|
235
|
+
// a struck span whose hash never reached the ledger is one a restore or
|
|
236
|
+
// an orphan merge can put straight back.
|
|
237
|
+
const ledger = access.mutate("strike", () => {
|
|
238
|
+
access.ensureScope(scope);
|
|
239
|
+
const file = access.path(scope, "consumed.jsonl");
|
|
240
|
+
const held = new Set(
|
|
241
|
+
access.readLines<{ hash: string }>(file).map((l) => l.hash),
|
|
242
|
+
);
|
|
243
|
+
const fresh = [...doomed].filter((h) => !held.has(h));
|
|
244
|
+
if (fresh.length > 0) {
|
|
245
|
+
const at = access.now();
|
|
246
|
+
appendFileSync(
|
|
247
|
+
file,
|
|
248
|
+
`${fresh.map((hash) => JSON.stringify({ hash, at })).join("\n")}\n`,
|
|
249
|
+
"utf8",
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
return fresh.length;
|
|
253
|
+
});
|
|
254
|
+
if (!ledger.ok) {
|
|
255
|
+
if (ledger.reason === "OBSERVER") observed = true;
|
|
256
|
+
else failed = true;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
ledgered += ledger.value;
|
|
260
|
+
|
|
261
|
+
// 2. THE REWRITE, one file at a time. Counted PER SCOPE as well as across
|
|
262
|
+
// them: a scope's record must carry that scope's numbers, or an
|
|
263
|
+
// all-scopes strike writes scope B's record with scope A's totals in it.
|
|
264
|
+
let scopeStruck = 0;
|
|
265
|
+
let scopeFiles = 0;
|
|
266
|
+
for (const file of targets) {
|
|
267
|
+
const outcome = access.mutate("strike", () => rewrite(access, file, matches));
|
|
268
|
+
if (!outcome.ok) {
|
|
269
|
+
if (outcome.reason === "OBSERVER") observed = true;
|
|
270
|
+
else failed = true;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (outcome.value === 0) continue;
|
|
274
|
+
struck += outcome.value;
|
|
275
|
+
scopeStruck += outcome.value;
|
|
276
|
+
scopeFiles += 1;
|
|
277
|
+
files.push({ file: relName(access, scope, file), struck: outcome.value });
|
|
278
|
+
if (file.includes(`${sep}claims${sep}`)) touchedClaim = true;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 3. THE RECORD. Counts and file names, never a hash and never a word.
|
|
282
|
+
access.mutate("strike", () => {
|
|
283
|
+
access.ensureScope(scope);
|
|
284
|
+
appendFileSync(
|
|
285
|
+
access.path(scope, "strikes.jsonl"),
|
|
286
|
+
`${JSON.stringify({
|
|
287
|
+
at: access.now(),
|
|
288
|
+
day: access.day(),
|
|
289
|
+
by: "owner",
|
|
290
|
+
files: scopeFiles,
|
|
291
|
+
struck: scopeStruck,
|
|
292
|
+
ledgered: ledger.value,
|
|
293
|
+
})}\n`,
|
|
294
|
+
"utf8",
|
|
295
|
+
);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const reason: StrikeReport["reason"] = observed
|
|
300
|
+
? "OBSERVER"
|
|
301
|
+
: failed
|
|
302
|
+
? "IO_FAILED"
|
|
303
|
+
: struck > 0 || ledgered > 0
|
|
304
|
+
? "STRUCK"
|
|
305
|
+
: recovered > 0
|
|
306
|
+
? "RECOVERED"
|
|
307
|
+
: "NOTHING";
|
|
308
|
+
|
|
309
|
+
if (reason !== "NOTHING") {
|
|
310
|
+
// The durable record's twin on the ring. Counts only, here too.
|
|
311
|
+
access.emit("remember.span.struck", undefined, {
|
|
312
|
+
reason,
|
|
313
|
+
struck,
|
|
314
|
+
files: files.length,
|
|
315
|
+
scopes: scopes.length,
|
|
316
|
+
ledgered,
|
|
317
|
+
touchedClaim,
|
|
318
|
+
recovered,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return { reason, struck, files, scopes: scopes.length, ledgered, touchedClaim, recovered };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ── internals ───────────────────────────────────────────────────────────────
|
|
326
|
+
|
|
327
|
+
const sep = "/";
|
|
328
|
+
|
|
329
|
+
function relName(access: SpanStrikeAccess, scope: string, file: string): string {
|
|
330
|
+
const dir = access.scopeDir(scope);
|
|
331
|
+
const rel = file.startsWith(dir) ? file.slice(dir.length + 1) : basename(file);
|
|
332
|
+
return `${basename(dir)}/${rel}`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Fold a crashed strike's aside back into its stream, DURABLY, and return how
|
|
337
|
+
* many lines came home.
|
|
338
|
+
*
|
|
339
|
+
* Review finding F2: the first draft read the aside into an array, removed it,
|
|
340
|
+
* and only then wrote the array back — so between those two moments the
|
|
341
|
+
* survivors existed in RAM and nowhere else, and NOTES' claim that "a crash
|
|
342
|
+
* strands nothing" was false. The order here is the one that makes it true:
|
|
343
|
+
*
|
|
344
|
+
* append (deduped against what the stream already holds) → **fsync** →
|
|
345
|
+
* remove the aside
|
|
346
|
+
*
|
|
347
|
+
* A crash before the fsync leaves the aside whole and the next fold repeats,
|
|
348
|
+
* deduped. A crash after it leaves duplicates in neither place, because the
|
|
349
|
+
* append landed first. Bounded duplication is this module's accepted failure;
|
|
350
|
+
* loss is not (spec §2 G6, scar E6).
|
|
351
|
+
*
|
|
352
|
+
* The review asked for temp → fsync → **rename over the original**. That is not
|
|
353
|
+
* taken, and the reason is the aside itself: a rename over the live path would
|
|
354
|
+
* clobber a turn appended by a hook in the meantime, which is the exact race
|
|
355
|
+
* the rename-aside choreography exists to survive. Append-then-fsync buys the
|
|
356
|
+
* same crash property without buying that one back.
|
|
357
|
+
*/
|
|
358
|
+
function foldAside(file: string): number {
|
|
359
|
+
const aside = `${file}.striking`;
|
|
360
|
+
if (!existsSync(aside)) return 0;
|
|
361
|
+
const held = new Set<string>();
|
|
362
|
+
for (const line of lines(file)) {
|
|
363
|
+
const span = parse(line);
|
|
364
|
+
if (span !== null) held.add(span.hash);
|
|
365
|
+
}
|
|
366
|
+
const back: string[] = [];
|
|
367
|
+
for (const line of lines(aside)) {
|
|
368
|
+
const span = parse(line);
|
|
369
|
+
// An unparseable line comes home too: this module destroys what it was
|
|
370
|
+
// asked to destroy and nothing else, and a line it cannot read is not
|
|
371
|
+
// something it can claim to have identified.
|
|
372
|
+
if (span !== null) {
|
|
373
|
+
if (held.has(span.hash)) continue;
|
|
374
|
+
held.add(span.hash);
|
|
375
|
+
}
|
|
376
|
+
back.push(line);
|
|
377
|
+
}
|
|
378
|
+
if (back.length > 0) appendDurably(file, `${back.join("\n")}\n`);
|
|
379
|
+
rmSync(aside, { force: true });
|
|
380
|
+
return back.length;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Append and make it survive the power going out, before anything is removed. */
|
|
384
|
+
function appendDurably(file: string, text: string): void {
|
|
385
|
+
const fd = openSync(file, "a");
|
|
386
|
+
try {
|
|
387
|
+
writeSync(fd, text);
|
|
388
|
+
fsyncSync(fd);
|
|
389
|
+
} finally {
|
|
390
|
+
closeSync(fd);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* One file, rewritten WITHOUT the matching lines. Returns how many went.
|
|
396
|
+
*
|
|
397
|
+
* The aside is the point: `renameSync` is atomic, so an append racing this
|
|
398
|
+
* lands in a fresh file at the original path and is untouched by what follows.
|
|
399
|
+
* The survivors are then appended back to that path — after the racing append,
|
|
400
|
+
* which reorders by at most one batch and loses nothing. Ordering inside a
|
|
401
|
+
* stream is `at`-sorted on read (`spans()`), so the shuffle is invisible.
|
|
402
|
+
*
|
|
403
|
+
* Nothing here is ever RAM-only across a destructive step: the survivors are on
|
|
404
|
+
* disk in the aside from the rename until the durable append has landed, and
|
|
405
|
+
* the aside is removed only after that (review F2).
|
|
406
|
+
*/
|
|
407
|
+
function rewrite(
|
|
408
|
+
access: SpanStrikeAccess,
|
|
409
|
+
file: string,
|
|
410
|
+
matches: (span: Span) => boolean,
|
|
411
|
+
): number {
|
|
412
|
+
const aside = `${file}.striking`;
|
|
413
|
+
|
|
414
|
+
// A previous crash's aside comes home first, durably and unfiltered. It is
|
|
415
|
+
// then re-read below with everything else, so a struck line does not survive
|
|
416
|
+
// by having been in an aside — it is simply struck on this pass instead.
|
|
417
|
+
foldAside(file);
|
|
418
|
+
|
|
419
|
+
if (!existsSync(file)) return 0;
|
|
420
|
+
|
|
421
|
+
// Nothing to do is nothing to do: a rename-and-restore of an untouched file
|
|
422
|
+
// would churn every stream in the scope on every strike.
|
|
423
|
+
const hits = lines(file).filter((line) => {
|
|
424
|
+
const span = parse(line);
|
|
425
|
+
return span !== null && matches(span);
|
|
426
|
+
}).length;
|
|
427
|
+
if (hits === 0) return 0;
|
|
428
|
+
|
|
429
|
+
// ONE rename, not two. A `file -> tmp -> aside` pair leaves a third name on
|
|
430
|
+
// disk if it crashes between them, and that name is one nothing looks for —
|
|
431
|
+
// survivors stranded off every path, with the struck text still beside them.
|
|
432
|
+
// The aside was folded and removed above, so renaming straight onto it is
|
|
433
|
+
// safe and the window is closed.
|
|
434
|
+
renameSync(file, aside);
|
|
435
|
+
const keep: string[] = [];
|
|
436
|
+
const seen = new Set<string>();
|
|
437
|
+
let struck = 0;
|
|
438
|
+
for (const line of lines(aside)) {
|
|
439
|
+
const span = parse(line);
|
|
440
|
+
if (span === null) {
|
|
441
|
+
keep.push(line);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (matches(span)) {
|
|
445
|
+
struck += 1;
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (seen.has(span.hash)) continue;
|
|
449
|
+
seen.add(span.hash);
|
|
450
|
+
keep.push(line);
|
|
451
|
+
}
|
|
452
|
+
// Durable BEFORE the aside goes: a crash here leaves the aside whole and the
|
|
453
|
+
// next strike (or the recovery pass at the top of `strikeSpans`) folds it
|
|
454
|
+
// back, deduped against whatever did land.
|
|
455
|
+
if (keep.length > 0) appendDurably(file, `${keep.join("\n")}\n`);
|
|
456
|
+
rmSync(aside, { force: true });
|
|
457
|
+
return struck;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function lines(file: string): string[] {
|
|
461
|
+
if (!existsSync(file)) return [];
|
|
462
|
+
try {
|
|
463
|
+
return readFileSync(file, "utf8").split("\n").filter((l) => l.trim().length > 0);
|
|
464
|
+
} catch {
|
|
465
|
+
return [];
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function parse(line: string): Span | null {
|
|
470
|
+
try {
|
|
471
|
+
const span = JSON.parse(line) as Span;
|
|
472
|
+
return typeof span.hash === "string" && typeof span.text === "string" ? span : null;
|
|
473
|
+
} catch {
|
|
474
|
+
// A half-written line from a crash. It is KEPT — this module destroys what
|
|
475
|
+
// it was asked to destroy and nothing else, and an unreadable line is not
|
|
476
|
+
// something it can claim to have identified.
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
}
|