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,1186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DESTRUCTION PATH. It lives here, in the owner's console, and nowhere else.
|
|
3
|
+
*
|
|
4
|
+
* `src/core/store/owner-op-seam.ts` declares `OwnerRemovalPort` as TYPES ONLY —
|
|
5
|
+
* the store exports no delete, no unlink, no rm, and that absence is the
|
|
6
|
+
* enforcement (§5 G2, §16 G1). This file is the one implementation. A test in
|
|
7
|
+
* `test/cli.test.ts` walks the import graph and fails if any core module, any
|
|
8
|
+
* other adapter, or anything a model can reach imports it. **That test failing
|
|
9
|
+
* is the point**: it is the caller-universality check the contract asks for
|
|
10
|
+
* (§16 G2, earned-mechanism #14).
|
|
11
|
+
*
|
|
12
|
+
* The order below is not style. Every step is a crash point, and at every one of
|
|
13
|
+
* them the memory is either fully alive, or dark AND RECORDED (§16 G10–G11):
|
|
14
|
+
*
|
|
15
|
+
* 1. **Validate the target.** Memory-bearing roots only (§16 G16). The
|
|
16
|
+
* archive, the backups, the graph and the removal record itself are never
|
|
17
|
+
* nameable, so a typo cannot point removal at the record of removal.
|
|
18
|
+
* 2. **Read everything that must be read, BEFORE anything is chased** (§16
|
|
19
|
+
* G13). v1 named this bug by making it: chasing copies first left every
|
|
20
|
+
* span unidentifiable, so the contamination scan had nothing to match on.
|
|
21
|
+
* The scan returns **ids only** — printing the matches would re-leak
|
|
22
|
+
* exactly what is being erased (§16 G15).
|
|
23
|
+
* 3. **`requested`.** If the record cannot be written, NOTHING MOVES. A
|
|
24
|
+
* removal that happened without a record is the one outcome worse than a
|
|
25
|
+
* removal that did not happen.
|
|
26
|
+
* 4. **`dark`.** From this moment `Store.deniedIds()` contains the id, and
|
|
27
|
+
* every consumer that consults it — recall, sleep, associate, prospective,
|
|
28
|
+
* the cache rebuild — skips it. A restored backup or a stray copy cannot
|
|
29
|
+
* quietly resurrect it; the stray is skipped and LOGGED, never deleted
|
|
30
|
+
* (§16 G12).
|
|
31
|
+
* 5. **Chase**, then `chased`, then `complete`. Whatever could not be chased
|
|
32
|
+
* is REPORTED, never silently dropped (§16 G15: no silent partial success).
|
|
33
|
+
* The raw-capture buffer under `spans/` is chased here, because it is
|
|
34
|
+
* `remember/`'s state machine and not this module's to unlink; box 2 (the
|
|
35
|
+
* row, its BODY and every archived version's body, its edges, its
|
|
36
|
+
* prospective windows, the gate rows that name it, and every content
|
|
37
|
+
* pointer it had) by `chaseRemoved` on the store's owner-op seam, which
|
|
38
|
+
* appends the `chased` stage inside its own transaction; box 3 by a
|
|
39
|
+
* rebuild that skips and logs the denied id. *(Until the floor — schema
|
|
40
|
+
* v6, 2026-09-20 — there was a box 1 to chase here as well: the memory's
|
|
41
|
+
* prose file and every archived version file. The words are columns now,
|
|
42
|
+
* so they go with the row, in one transaction; see `reclaim` below for
|
|
43
|
+
* what that costs.)*
|
|
44
|
+
*
|
|
45
|
+
* The record carries no body and no content hash (§16 G9, scar §2.20): a hash of
|
|
46
|
+
* low-entropy content is brute-forceable, which would make the record of a
|
|
47
|
+
* removal a leak of the thing removed.
|
|
48
|
+
*/
|
|
49
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
50
|
+
import { join, relative } from "node:path";
|
|
51
|
+
|
|
52
|
+
// The span buffer's OWN scope-directory function, imported rather than
|
|
53
|
+
// re-derived: `spans/<keyFor(scope)>/` is `remember/`'s layout, and a second
|
|
54
|
+
// copy of that arithmetic living in the destruction path is how a report starts
|
|
55
|
+
// naming a file that does not exist.
|
|
56
|
+
import { SpanBuffer, keyFor } from "../../core/remember/index.js";
|
|
57
|
+
// The buffer's own destruction seam — the second VALUE import this file makes
|
|
58
|
+
// from core, and pinned by the same caller-universality test as the first. The
|
|
59
|
+
// strike is `remember/`'s because `spans/` is `remember/`'s state machine: an
|
|
60
|
+
// `rmSync` from here would race a claim renaming the file aside, which is the
|
|
61
|
+
// one state spec §2 G6 forbids (cli/INTERFACE-GAPS §9, closed 2026-09-05).
|
|
62
|
+
import { strikeSpans } from "../../core/remember/owner-strike-seam.js";
|
|
63
|
+
// The journal's markdown copy is a SURFACE (F6): a derived file under
|
|
64
|
+
// `<store>/journal/` holding an episode's words. `syncJournalCopy` is imported
|
|
65
|
+
// rather than an `rmSync` from here for the same reason `strikeSpans` is — the
|
|
66
|
+
// directory belongs to `self/`, and the invariant it keeps ("a file exists
|
|
67
|
+
// exactly when a live episode row does") is what makes the chase provable.
|
|
68
|
+
import { journalFilesFor, syncJournalCopy } from "../../core/self/journal-file.js";
|
|
69
|
+
import { paths, rowTombstoned } from "../../core/store/index.js";
|
|
70
|
+
import { isLocked, openDb } from "../../core/store/db.js";
|
|
71
|
+
import type {
|
|
72
|
+
OwnerRemovalOutcome,
|
|
73
|
+
OwnerRemovalRequest,
|
|
74
|
+
RemovalNote,
|
|
75
|
+
Store,
|
|
76
|
+
} from "../../core/store/index.js";
|
|
77
|
+
// The one VALUE imported from the seam, and the reason the caller-universality
|
|
78
|
+
// test pins this file AND that one: `chaseRemoved` is the box-2 half of the
|
|
79
|
+
// destruction path. It is reachable by importing the seam on purpose, never by
|
|
80
|
+
// holding a `Store` (INTERFACE-GAPS §1, closed 2026-08-25).
|
|
81
|
+
import { chaseRemoved } from "../../core/store/owner-op-seam.js";
|
|
82
|
+
// The page has its own door out (`self-page --clear`), and removal is not it.
|
|
83
|
+
import { isSelfPageRow } from "../../core/self/page.js";
|
|
84
|
+
|
|
85
|
+
export interface RemovalPlan {
|
|
86
|
+
readonly targetId: string;
|
|
87
|
+
readonly valid: boolean;
|
|
88
|
+
readonly reason: "ok" | "unknown-id" | "not-memory-bearing" | "already-removed" | "is-the-self-page";
|
|
89
|
+
/** IDS ONLY. Other memories whose text overlaps the doomed content (§16 G15). */
|
|
90
|
+
readonly contamination: readonly string[];
|
|
91
|
+
/** What the chase will visit, by surface name. Counts, never contents. */
|
|
92
|
+
readonly surfaces: { readonly surface: string; readonly count: number }[];
|
|
93
|
+
/**
|
|
94
|
+
* The SEVENTH surface: `remember/`'s raw capture buffer. Always present, in
|
|
95
|
+
* all three states — a surface that is silent when it is empty is exactly the
|
|
96
|
+
* silent partial success §16 G15 forbids. Since 2026-09-05 `held` is CHASED,
|
|
97
|
+
* through `remember/`'s own strike seam, and `unknown` is the one state that
|
|
98
|
+
* still lands in `unchasable`.
|
|
99
|
+
*/
|
|
100
|
+
readonly spans: SpanSurface;
|
|
101
|
+
/**
|
|
102
|
+
* The chase key, carried from the plan to the run so the strike does not have
|
|
103
|
+
* to re-derive it after the prose is gone. Hashes and a scope — never the
|
|
104
|
+
* body, which stays a local in `planRemoval` and reaches the seam only as a
|
|
105
|
+
* predicate the caller closes over.
|
|
106
|
+
*/
|
|
107
|
+
readonly spanChase: SpanChase;
|
|
108
|
+
/** Surfaces this implementation cannot reach — named, never implied. */
|
|
109
|
+
readonly unchasable: readonly string[];
|
|
110
|
+
/**
|
|
111
|
+
* Lines this removal LEAVES on purpose, said in their own words. Not
|
|
112
|
+
* `unchasable`: nothing failed, and filing them under "dark via the deny-list"
|
|
113
|
+
* described a conversation turn as though it had an id and a tombstone
|
|
114
|
+
* (review F6).
|
|
115
|
+
*/
|
|
116
|
+
readonly leftAlone: readonly string[];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* `held` — a line under `spans/` carries this memory's words, right now, checked.
|
|
121
|
+
* `unknown` — this console cannot rule it out, and says which way it is blind.
|
|
122
|
+
* `not-applicable` — checked, and there is nothing of this memory there.
|
|
123
|
+
*/
|
|
124
|
+
export type SpanState = "held" | "unknown" | "not-applicable";
|
|
125
|
+
|
|
126
|
+
export interface SpanSurface {
|
|
127
|
+
readonly surface: "spans";
|
|
128
|
+
readonly state: SpanState;
|
|
129
|
+
/** Store-RELATIVE, and only when one can be named. Never an absolute path. */
|
|
130
|
+
readonly path: string | null;
|
|
131
|
+
/** Lines the strike will take, counted at plan time. Zero unless `held`. */
|
|
132
|
+
readonly count: number;
|
|
133
|
+
/**
|
|
134
|
+
* OTHER lines under `spans/` that quote these words without being this
|
|
135
|
+
* memory's own capture — the conversation turn in which they were said,
|
|
136
|
+
* still waiting to be interpreted. They are LEFT, on purpose: a conversation
|
|
137
|
+
* span is many turns joined, belongs to no single memory, and striking it
|
|
138
|
+
* because one memory quoted it would destroy material nobody named. Counted
|
|
139
|
+
* and disclosed rather than passed over in silence (§16 G15).
|
|
140
|
+
*/
|
|
141
|
+
readonly echoes: number;
|
|
142
|
+
/**
|
|
143
|
+
* HOW the memory's own line was identified — printed, because the two are not
|
|
144
|
+
* equally strong and a reader deciding whether to confirm deserves to know
|
|
145
|
+
* which one is about to run (review F4). `hash` is the identity the mint
|
|
146
|
+
* recorded. `content` is a jot whose FULL text equals the doomed body.
|
|
147
|
+
*/
|
|
148
|
+
readonly matchedBy: "hash" | "content" | "none";
|
|
149
|
+
/**
|
|
150
|
+
* The scope-unknown content case, refused rather than performed (review F4).
|
|
151
|
+
* A migrated row carries `origin: { ref }` and NO scope, so a content chase
|
|
152
|
+
* would have to visit every project on the machine. These are the jot lines
|
|
153
|
+
* that would have matched, named as files and counts — no text, no strike —
|
|
154
|
+
* so the owner can look and decide. `--strike-by-content-across-scopes`
|
|
155
|
+
* performs it.
|
|
156
|
+
*/
|
|
157
|
+
readonly candidates: readonly { readonly file: string; readonly lines: number }[];
|
|
158
|
+
/** The whole sentence the console prints, and the `unchasable` entry when it is one. */
|
|
159
|
+
readonly line: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* How the buffer is addressed. `hashes` is the chase BY IDENTITY — the span
|
|
164
|
+
* hash the mint recorded in the memory's prose meta (`origin.spanHash`), plus
|
|
165
|
+
* every `own: true` coverage mark for its `origin_ref`, which is what makes the
|
|
166
|
+
* chase work on rows minted before that meta key existed. `byContent` says the
|
|
167
|
+
* console had no hash and will match on the doomed body instead.
|
|
168
|
+
*/
|
|
169
|
+
export interface SpanChase {
|
|
170
|
+
readonly scope: string | null;
|
|
171
|
+
readonly hashes: readonly string[];
|
|
172
|
+
/** True when the strike will match on the body. EXACT-LINE equality on a jot,
|
|
173
|
+
* never a substring, and never outside `scope` unless the owner passed
|
|
174
|
+
* `--strike-by-content-across-scopes` (review F4). */
|
|
175
|
+
readonly byContent: boolean;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** What `planRemoval` was told the owner asked for. */
|
|
179
|
+
export interface PlanOptions {
|
|
180
|
+
/**
|
|
181
|
+
* The owner's explicit say-so for the one chase this console refuses by
|
|
182
|
+
* default: matching a body across EVERY scope on the machine, for a row whose
|
|
183
|
+
* provenance never recorded which project it came from.
|
|
184
|
+
*/
|
|
185
|
+
crossScopeContent?: boolean;
|
|
186
|
+
/** How many episodes the journal-echo check reads. Injectable so a test can
|
|
187
|
+
* prove the bound is REPORTED rather than silent. */
|
|
188
|
+
echoScanMax?: number;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface RemovalOptions extends PlanOptions {
|
|
192
|
+
/** Wall-clock, not lived days: a week away must still be a week of second
|
|
193
|
+
* thoughts (§16's note on the released ceremony). */
|
|
194
|
+
now?: () => number;
|
|
195
|
+
onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Prose families a removal may target. Everything else is chased, never named. */
|
|
199
|
+
const MEMORY_BEARING = new Set(["memory", "episode", "schema"]);
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The one state still unreachable, in the same words wherever it is reported.
|
|
203
|
+
* Kept as a constant for the reason it was written as one: a blind spot
|
|
204
|
+
* described two different ways in two places is a blind spot nobody can grep.
|
|
205
|
+
*/
|
|
206
|
+
const SPANS_BLIND =
|
|
207
|
+
"this removal did not reach it, and a later backup would copy it (export would not).";
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The journal surface's own blind sentence, for the same reason `SPANS_BLIND`
|
|
211
|
+
* is one: a directory that still holds the words after a chase said it was
|
|
212
|
+
* clean is a fact the owner must be handed, in the same words wherever it is
|
|
213
|
+
* printed. (It is no longer in the backup set — see `olderCopiesNote` — so the
|
|
214
|
+
* sentence is about this store's own disk, not about future copies.)
|
|
215
|
+
*/
|
|
216
|
+
const JOURNAL_STILL_THERE =
|
|
217
|
+
"journal/ — it is a derived copy, and deleting that file by hand loses nothing";
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* WHAT A REMOVAL CANNOT REACH: the copies already on disk.
|
|
221
|
+
*
|
|
222
|
+
* F6 did not create this gap — every snapshot has always held whatever the
|
|
223
|
+
* store held when it was taken — but it changed its severity by a wide margin
|
|
224
|
+
* and nothing said so (f6f7 review MAJOR-5). A removed memory inside an old
|
|
225
|
+
* snapshot's DATABASE is a file somebody must know to open; the same words in
|
|
226
|
+
* an old snapshot's `journal/*.md` are a grep hit, a Spotlight result, a synced
|
|
227
|
+
* folder's problem.
|
|
228
|
+
*
|
|
229
|
+
* Two things make this sentence honest rather than alarming, and both are said:
|
|
230
|
+
* snapshots taken FROM TODAY carry no `journal/` at all (it left the backup set
|
|
231
|
+
* in the same change), and a snapshot is the owner's own file to delete.
|
|
232
|
+
*
|
|
233
|
+
* It names the DEFAULT snapshot directory and counts what is in it. The console
|
|
234
|
+
* reads no host configuration, so a configured `snapshots.dir` is not visible
|
|
235
|
+
* from here — the sentence says so rather than implying the default is the
|
|
236
|
+
* whole story.
|
|
237
|
+
*/
|
|
238
|
+
function olderCopiesNote(storeDir: string): string {
|
|
239
|
+
const snapshots = join(storeDir, "..", "snapshots");
|
|
240
|
+
let copies = 0;
|
|
241
|
+
try {
|
|
242
|
+
copies = readdirSync(snapshots).length;
|
|
243
|
+
} catch {
|
|
244
|
+
/* none, or not readable from here: the sentence still holds */
|
|
245
|
+
}
|
|
246
|
+
return (
|
|
247
|
+
`snapshots and backups TAKEN BEFORE TODAY still hold these words, and the journal ones hold them as plain markdown` +
|
|
248
|
+
(copies === 0
|
|
249
|
+
? ` — none in the default location (${relative(storeDir, snapshots)}), and a location set in your host configuration is not visible from this console.`
|
|
250
|
+
: ` — ${copies} cop${copies === 1 ? "y" : "ies"} in the default location (${relative(storeDir, snapshots)}), plus anywhere else you have taken one.`) +
|
|
251
|
+
" A removal does not reach into them; they are yours to delete. Snapshots taken from today carry no journal/ at all."
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Every `*.jsonl` under a directory — the live streams and the claims beside
|
|
257
|
+
* them — AND every `*.jsonl.striking` aside (review F1).
|
|
258
|
+
*
|
|
259
|
+
* An aside is a crashed strike's survivors, and it sits off every path the
|
|
260
|
+
* buffer itself reads. Missing it here meant a later `remove` reported "not
|
|
261
|
+
* applicable" while the words were on disk and `backup` copied them — the
|
|
262
|
+
* silent partial success this whole surface exists to prevent. The strike's own
|
|
263
|
+
* recovery pass folds any aside back before it runs, so naming it here is not
|
|
264
|
+
* a promise the chase cannot keep.
|
|
265
|
+
*/
|
|
266
|
+
function jsonlUnder(root: string): string[] {
|
|
267
|
+
if (!existsSync(root)) return [];
|
|
268
|
+
const out: string[] = [];
|
|
269
|
+
const walk = (at: string): void => {
|
|
270
|
+
for (const name of readdirSync(at).sort()) {
|
|
271
|
+
const full = join(at, name);
|
|
272
|
+
if (statSync(full).isDirectory()) walk(full);
|
|
273
|
+
else if (name.endsWith(".jsonl") || name.endsWith(".jsonl.striking")) out.push(full);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
walk(root);
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Does this file hold a line of this memory? BY HASH first — the identity the
|
|
282
|
+
* mint recorded — and by the doomed TEXT only as the fallback for a row minted
|
|
283
|
+
* before the provenance existed. Reads the file; never returns a word of it.
|
|
284
|
+
*
|
|
285
|
+
* Only lines that are SPANS count. `coverage.jsonl`, `consumed.jsonl` and
|
|
286
|
+
* `failures.jsonl` carry span hashes too, and matching a hash there would report
|
|
287
|
+
* a file that holds nothing but bookkeeping as one that holds the owner's words.
|
|
288
|
+
*/
|
|
289
|
+
function spanLinesIn(
|
|
290
|
+
path: string,
|
|
291
|
+
hashes: ReadonlySet<string>,
|
|
292
|
+
needle: string | null,
|
|
293
|
+
): { byHash: number; byTextJot: number; byTextOther: number } {
|
|
294
|
+
const none = { byHash: 0, byTextJot: 0, byTextOther: 0 };
|
|
295
|
+
let text: string;
|
|
296
|
+
try {
|
|
297
|
+
text = readFileSync(path, "utf8");
|
|
298
|
+
} catch {
|
|
299
|
+
return none;
|
|
300
|
+
}
|
|
301
|
+
let byHash = 0;
|
|
302
|
+
let byTextJot = 0;
|
|
303
|
+
let byTextOther = 0;
|
|
304
|
+
let parsedAny = false;
|
|
305
|
+
for (const line of text.split("\n")) {
|
|
306
|
+
if (line.trim().length === 0) continue;
|
|
307
|
+
try {
|
|
308
|
+
const record = JSON.parse(line) as { text?: unknown; hash?: unknown; kind?: unknown };
|
|
309
|
+
if (typeof record.text !== "string") continue;
|
|
310
|
+
parsedAny = true;
|
|
311
|
+
if (typeof record.hash === "string" && hashes.has(record.hash)) byHash += 1;
|
|
312
|
+
else if (needle !== null && record.text.includes(needle)) {
|
|
313
|
+
// A text match is only ever this MEMORY's own line when the span is a
|
|
314
|
+
// JOT — the words deposited as themselves — and when its WHOLE text is
|
|
315
|
+
// the body, not merely a stretch containing it. Substring matching is
|
|
316
|
+
// what turned removing "buy milk" into the destruction of two unrelated
|
|
317
|
+
// jots in two unrelated projects (review F4): a jot reading "buy milk
|
|
318
|
+
// and call the vet" contains the doomed words and is somebody else's
|
|
319
|
+
// memory. Everything short of full equality is an echo, and a record
|
|
320
|
+
// with no `kind` is an echo too — the conservative direction is the one
|
|
321
|
+
// that destroys nothing.
|
|
322
|
+
if (record.kind === "jot" && record.text.trim() === needle) byTextJot += 1;
|
|
323
|
+
else byTextOther += 1;
|
|
324
|
+
}
|
|
325
|
+
} catch {
|
|
326
|
+
/* a half-written line: covered by the raw check below */
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// The raw substring is what catches a file this console does not understand —
|
|
330
|
+
// a format change, a half-written line. It counts as an ECHO, never as a line
|
|
331
|
+
// to strike: this console did not manage to identify it.
|
|
332
|
+
if (byHash === 0 && byTextJot === 0 && byTextOther === 0 && !parsedAny && needle !== null && text.includes(needle)) {
|
|
333
|
+
return { byHash: 0, byTextJot: 0, byTextOther: 1 };
|
|
334
|
+
}
|
|
335
|
+
return { byHash, byTextJot, byTextOther };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* THE CHASE KEY. Two sources, both already durable, neither of them the body:
|
|
340
|
+
*
|
|
341
|
+
* 1. `origin.spanHash` in the memory's PROSE META. The mint records it for
|
|
342
|
+
* every jot (`core/mint.ts`), and it lives in the prose rather than in a
|
|
343
|
+
* box-2 column on purpose — a hash of low-entropy content is
|
|
344
|
+
* brute-forceable (§16 G9), so the pointer must die with the document it
|
|
345
|
+
* points at instead of outliving the removal in the row skeleton.
|
|
346
|
+
* 2. The `own: true` COVERAGE MARKS for this memory's `origin_ref`. Every
|
|
347
|
+
* accepted proposal writes `{spanHash, proposalId, own}` into the scope's
|
|
348
|
+
* `coverage.jsonl`, and the mint stores the proposal id in `origin_ref` —
|
|
349
|
+
* so the link from a memory to the span it WAS has been on disk since long
|
|
350
|
+
* before this feature, and the chase works on rows minted before it.
|
|
351
|
+
*
|
|
352
|
+
* `own` is the whole filter. The other spans a proposal covered are the
|
|
353
|
+
* conversation AROUND it, which belong to no single memory; striking those
|
|
354
|
+
* because one memory cited them would be a destruction nobody asked for.
|
|
355
|
+
*/
|
|
356
|
+
function chaseHashes(store: Store, doc: { meta?: Record<string, unknown> } | null, row: {
|
|
357
|
+
origin_scope?: unknown;
|
|
358
|
+
origin_ref?: unknown;
|
|
359
|
+
} | undefined): { scope: string | null; hashes: string[] } {
|
|
360
|
+
const scope =
|
|
361
|
+
typeof row?.origin_scope === "string" && row.origin_scope.length > 0 ? row.origin_scope : null;
|
|
362
|
+
const hashes = new Set<string>();
|
|
363
|
+
|
|
364
|
+
const origin = doc?.meta?.["origin"];
|
|
365
|
+
if (origin !== null && typeof origin === "object") {
|
|
366
|
+
const spanHash = (origin as { spanHash?: unknown }).spanHash;
|
|
367
|
+
if (typeof spanHash === "string" && spanHash.length > 0) hashes.add(spanHash);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const ref = typeof row?.origin_ref === "string" && row.origin_ref.length > 0 ? row.origin_ref : null;
|
|
371
|
+
if (ref !== null && scope !== null) {
|
|
372
|
+
const coverage = join(store.dir, "spans", keyFor(scope), "coverage.jsonl");
|
|
373
|
+
if (existsSync(coverage)) {
|
|
374
|
+
let text = "";
|
|
375
|
+
try {
|
|
376
|
+
text = readFileSync(coverage, "utf8");
|
|
377
|
+
} catch {
|
|
378
|
+
text = "";
|
|
379
|
+
}
|
|
380
|
+
for (const line of text.split("\n")) {
|
|
381
|
+
if (line.trim().length === 0) continue;
|
|
382
|
+
try {
|
|
383
|
+
const mark = JSON.parse(line) as { spanHash?: unknown; proposalId?: unknown; own?: unknown };
|
|
384
|
+
if (mark.own !== true) continue;
|
|
385
|
+
if (mark.proposalId !== ref) continue;
|
|
386
|
+
if (typeof mark.spanHash === "string") hashes.add(mark.spanHash);
|
|
387
|
+
} catch {
|
|
388
|
+
/* an unreadable mark is not a hash */
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return { scope, hashes: [...hashes] };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* THE SEVENTH SURFACE (LAUNCH-STATUS §I2; option A shipped 2026-09-04, option B
|
|
399
|
+
* — the chase — on 2026-09-05).
|
|
400
|
+
*
|
|
401
|
+
* A note taken through the MCP `note` tool or `counterparts note` is CAPTURED
|
|
402
|
+
* first — `captureJot` appends the verbatim text to `spans/<keyFor(scope)>/jots.jsonl` —
|
|
403
|
+
* and minted second. The chase never reached that file, `unchasable` was a
|
|
404
|
+
* hardcoded `[]`, and `remove` reported `unchased: nothing` while the words were
|
|
405
|
+
* still on disk. It reaches it now, through `remember/`'s own strike seam.
|
|
406
|
+
*
|
|
407
|
+
* **Identity first, evidence second, provenance third.** The state is decided by
|
|
408
|
+
* looking: the memory's own span hash (from the mint) and then its words are
|
|
409
|
+
* searched for in the buffer files, and a hit is a fact rather than an
|
|
410
|
+
* inference. The hash is what lets the chase work when the prose is already
|
|
411
|
+
* gone, which is the case the content search could never answer. Provenance only
|
|
412
|
+
* breaks the tie when both come back empty — because `source = 'authored'` means
|
|
413
|
+
* this memory came through the jot door, and "I did not find it" is not "it was
|
|
414
|
+
* never there". The remaining blind spot (prose gone AND no hash recorded) is
|
|
415
|
+
* reported as `unknown` rather than resolved in the comfortable direction.
|
|
416
|
+
*/
|
|
417
|
+
export function spanResidue(
|
|
418
|
+
store: Store,
|
|
419
|
+
targetId: string,
|
|
420
|
+
body: string,
|
|
421
|
+
hashes: readonly string[] = [],
|
|
422
|
+
opts: PlanOptions = {},
|
|
423
|
+
): SpanSurface {
|
|
424
|
+
const row = store.row(targetId);
|
|
425
|
+
const source = typeof row?.source === "string" && row.source.length > 0 ? row.source : null;
|
|
426
|
+
const scope = typeof row?.origin_scope === "string" && row.origin_scope.length > 0 ? row.origin_scope : null;
|
|
427
|
+
const spansRoot = join(store.dir, "spans");
|
|
428
|
+
const scopeDir = scope === null ? spansRoot : join(spansRoot, keyFor(scope));
|
|
429
|
+
const files = jsonlUnder(scopeDir);
|
|
430
|
+
const rel = (path: string): string => relative(store.dir, path);
|
|
431
|
+
const named = scope === null ? "spans/" : `${rel(scopeDir)}/`;
|
|
432
|
+
|
|
433
|
+
const none = (state: SpanState, line: string, extra: Partial<SpanSurface> = {}): SpanSurface => ({
|
|
434
|
+
surface: "spans",
|
|
435
|
+
state,
|
|
436
|
+
path: null,
|
|
437
|
+
count: 0,
|
|
438
|
+
echoes: 0,
|
|
439
|
+
matchedBy: "none",
|
|
440
|
+
candidates: [],
|
|
441
|
+
line,
|
|
442
|
+
...extra,
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
if (files.length === 0) {
|
|
446
|
+
return none(
|
|
447
|
+
"not-applicable",
|
|
448
|
+
`spans: not applicable — there is no capture buffer at ${named} for this memory, so nothing of it rode one.`,
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const needle = body.trim().length > 0 ? body.trim() : null;
|
|
453
|
+
const keys = new Set(hashes);
|
|
454
|
+
|
|
455
|
+
// THE CONTENT CHASE IS SCOPED (review F4). A hash names one span anywhere; a
|
|
456
|
+
// BODY names a shape, and a shape matched across every project on the machine
|
|
457
|
+
// is how removing one memory reaches into another person's work. Migrated rows
|
|
458
|
+
// are exactly this case — `tools/migrate/apply.ts` writes `origin: { ref }`
|
|
459
|
+
// with no scope at all — so this is not a hypothetical about a rare row, it is
|
|
460
|
+
// the shape of ~12,000 of them. Without a recorded scope the console REFUSES
|
|
461
|
+
// to strike by content and lists what it would have matched instead.
|
|
462
|
+
const contentAllowed = keys.size === 0 && needle !== null;
|
|
463
|
+
const contentScoped = contentAllowed && (scope !== null || opts.crossScopeContent === true);
|
|
464
|
+
|
|
465
|
+
// ONE pass over the buffer, three numbers out of it.
|
|
466
|
+
//
|
|
467
|
+
// `count` — lines the strike will take.
|
|
468
|
+
// `echoes` — other lines carrying these words: the conversation they
|
|
469
|
+
// were said in, or a longer jot that quotes them. LEFT,
|
|
470
|
+
// because they belong to no single memory — and SAID,
|
|
471
|
+
// because a grep will find them (§16 G15).
|
|
472
|
+
// `candidates` — the scope-unknown content case: jot lines whose whole text
|
|
473
|
+
// IS the body, somewhere on this machine. Named, not struck.
|
|
474
|
+
let count = 0;
|
|
475
|
+
let echoes = 0;
|
|
476
|
+
let first: string | null = null;
|
|
477
|
+
const candidates: { file: string; lines: number }[] = [];
|
|
478
|
+
for (const file of files) {
|
|
479
|
+
const hits = spanLinesIn(file, keys, needle);
|
|
480
|
+
const exact = keys.size > 0 ? 0 : hits.byTextJot;
|
|
481
|
+
const mine = keys.size > 0 ? hits.byHash : contentScoped ? hits.byTextJot : 0;
|
|
482
|
+
echoes += keys.size > 0 ? hits.byTextJot + hits.byTextOther : hits.byTextOther;
|
|
483
|
+
if (!contentScoped && exact > 0) candidates.push({ file: rel(file), lines: exact });
|
|
484
|
+
if (mine === 0) continue;
|
|
485
|
+
count += mine;
|
|
486
|
+
if (first === null) first = rel(file);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** The disclosure sentence, appended to whatever verdict the state reaches. */
|
|
490
|
+
const echoNote =
|
|
491
|
+
echoes === 0
|
|
492
|
+
? ""
|
|
493
|
+
: ` ${echoes} line${echoes === 1 ? "" : "s"} of conversation under ${named} quote${echoes === 1 ? "s" : ""} these words — transcript, not this memory's own capture, and left alone; nothing prunes the buffer today, so ${echoes === 1 ? "it stays" : "they stay"} there.`;
|
|
494
|
+
|
|
495
|
+
if (first !== null) {
|
|
496
|
+
const where = count === 1 ? first : `${first} (and ${count - 1} more line${count === 2 ? "" : "s"})`;
|
|
497
|
+
const how =
|
|
498
|
+
keys.size > 0
|
|
499
|
+
? "matched by the span hash its mint recorded"
|
|
500
|
+
: opts.crossScopeContent === true && scope === null
|
|
501
|
+
? "matched by content across every scope, on your say-so (--strike-by-content-across-scopes)"
|
|
502
|
+
: "matched by content — a jot whose whole text is this memory's body";
|
|
503
|
+
return {
|
|
504
|
+
surface: "spans",
|
|
505
|
+
state: "held",
|
|
506
|
+
path: first,
|
|
507
|
+
count,
|
|
508
|
+
echoes,
|
|
509
|
+
matchedBy: keys.size > 0 ? "hash" : "content",
|
|
510
|
+
candidates: [],
|
|
511
|
+
line: `${where} — the raw capture buffer holds this memory's words (${how}); the removal strikes them out of it.${echoNote}`,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// The refusal, and what it is refusing: named files and counts, never a word
|
|
516
|
+
// of what is in them (§16 G15). The owner can look, and can override.
|
|
517
|
+
if (candidates.length > 0) {
|
|
518
|
+
const total = candidates.reduce((n, c) => n + c.lines, 0);
|
|
519
|
+
const where = candidates.map((c) => `${c.file} (${c.lines})`).join(", ");
|
|
520
|
+
return {
|
|
521
|
+
surface: "spans",
|
|
522
|
+
state: "unknown",
|
|
523
|
+
path: named,
|
|
524
|
+
count: 0,
|
|
525
|
+
echoes,
|
|
526
|
+
matchedBy: "none",
|
|
527
|
+
candidates,
|
|
528
|
+
line: `${named} — this memory's provenance records no scope and no span hash, so a chase by content would have to visit EVERY project on this machine. NOT done: ${total} jot line${total === 1 ? "" : "s"} whose whole text is this memory's body would have matched, in ${where}. Look, then re-run with --strike-by-content-across-scopes if they are yours to remove; until then ${SPANS_BLIND}${echoNote}`,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (needle === null && keys.size === 0) {
|
|
533
|
+
return none(
|
|
534
|
+
"unknown",
|
|
535
|
+
`${named} — the prose is already gone and no span hash was recorded, so this console cannot tell whether the words rode the buffer; if they did, ${SPANS_BLIND}${echoNote}`,
|
|
536
|
+
{ echoes, path: named },
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// Searched — by hash where there was one, by content where that was allowed —
|
|
541
|
+
// and this memory's own line is not there. Whether that settles it depends on
|
|
542
|
+
// how the memory was minted.
|
|
543
|
+
if (keys.size > 0) {
|
|
544
|
+
return none(
|
|
545
|
+
"not-applicable",
|
|
546
|
+
echoes === 0
|
|
547
|
+
? `spans: not applicable — this memory's own span is named in its provenance, and no line under ${named} still carries it.`
|
|
548
|
+
: `spans: not applicable — this memory's own capture is already gone from ${named}.${echoNote}`,
|
|
549
|
+
{ echoes },
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
if (source === "authored") {
|
|
553
|
+
return none(
|
|
554
|
+
"unknown",
|
|
555
|
+
`${named} — this memory came through the jot door, so its words rode the buffer; no jot there matches them now, and this console cannot prove the capture is gone; if one survives, ${SPANS_BLIND}${echoNote}`,
|
|
556
|
+
{ echoes, path: named },
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
if (source === null) {
|
|
560
|
+
return none(
|
|
561
|
+
"unknown",
|
|
562
|
+
`${named} — unknown whether the words rode the buffer: this memory's provenance was never recorded, and a buffer exists; if a jot is there, ${SPANS_BLIND}${echoNote}`,
|
|
563
|
+
{ echoes, path: named },
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
return none(
|
|
567
|
+
"not-applicable",
|
|
568
|
+
`spans: not applicable — a '${source}' memory is not captured as a jot, and no jot under ${named} holds its words.${echoNote}`,
|
|
569
|
+
{ echoes },
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* How many episodes the echo check reads before it stops and says so.
|
|
575
|
+
*
|
|
576
|
+
* It reads bodies, which is the expensive thing this console does — but removal
|
|
577
|
+
* is a rare, deliberate owner operation and the alternative is the failure this
|
|
578
|
+
* bound exists to replace. A store past this many episodes gets a REPORTED
|
|
579
|
+
* partial check rather than a silent one.
|
|
580
|
+
*/
|
|
581
|
+
export const JOURNAL_ECHO_SCAN_MAX = 2_000;
|
|
582
|
+
|
|
583
|
+
export interface JournalEcho {
|
|
584
|
+
/** Episode ids whose chapters hold these words. Ids only (§16 G15). */
|
|
585
|
+
readonly ids: readonly string[];
|
|
586
|
+
/** Episodes actually read, and how many exist. Equal ⇒ the check was whole. */
|
|
587
|
+
readonly checked: number;
|
|
588
|
+
readonly total: number;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** Whitespace-folded, so a chapter that wrapped a sentence differently from the
|
|
592
|
+
* memory minted out of it is still recognised as holding it. */
|
|
593
|
+
function folded(text: string): string {
|
|
594
|
+
return text.replace(/\s+/g, " ").trim();
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* WHICH EPISODES HOLD THESE WORDS — asked exactly, not ranked.
|
|
599
|
+
*
|
|
600
|
+
* This used to read the `contamination` list, which is `store.search(body, 20)`:
|
|
601
|
+
* a ranked top-20 full-text search. Measured by the f6f7 review (MAJOR-3): with
|
|
602
|
+
* twenty-five near-identical memories — the ordinary shape of a store that has
|
|
603
|
+
* thought about one subject for a while — the episode fell off the end of the
|
|
604
|
+
* list, and the report printed `chase journal: 0`, `journal(0, nothing beside
|
|
605
|
+
* the row)` and `unchased: nothing` while a plain `.md` under the store still
|
|
606
|
+
* held the removed sentence. That is F5 review-B MAJOR-1's shape one directory
|
|
607
|
+
* over, with an FTS rank as the only thing between this console and it.
|
|
608
|
+
*
|
|
609
|
+
* Two questions, cheapest first:
|
|
610
|
+
*
|
|
611
|
+
* 1. **The exact link.** A memory minted from an episode carries
|
|
612
|
+
* `meta.episodeId` (`self/episodes.ts` writes it; `memoriesForEpisode`
|
|
613
|
+
* reads it). One field, no scan, no ambiguity.
|
|
614
|
+
* 2. **The containment scan**, for the un-linked "quotes these words" case:
|
|
615
|
+
* every `type: "episode"` row, whitespace-folded, asked whether it holds
|
|
616
|
+
* the doomed body. Bounded by `JOURNAL_ECHO_SCAN_MAX`, and the bound is
|
|
617
|
+
* REPORTED — a stated bound is survivable, a silent one is not.
|
|
618
|
+
*
|
|
619
|
+
* The episodes' markdown copies say exactly what their rows say, so an answer
|
|
620
|
+
* about the rows is an answer about the files.
|
|
621
|
+
*/
|
|
622
|
+
function journalEcho(
|
|
623
|
+
store: Store,
|
|
624
|
+
targetId: string,
|
|
625
|
+
body: string,
|
|
626
|
+
doc: { meta?: Record<string, unknown> } | null,
|
|
627
|
+
opts: PlanOptions,
|
|
628
|
+
): JournalEcho {
|
|
629
|
+
const ids: string[] = [];
|
|
630
|
+
const linked = doc?.meta?.["episodeId"];
|
|
631
|
+
if (typeof linked === "string" && linked.length > 0 && linked !== targetId) {
|
|
632
|
+
const row = store.row(linked);
|
|
633
|
+
if (row !== undefined && row.type === "episode" && !rowTombstoned(row)) ids.push(linked);
|
|
634
|
+
}
|
|
635
|
+
const needle = folded(body);
|
|
636
|
+
let episodes: string[];
|
|
637
|
+
try {
|
|
638
|
+
episodes = store.list({ type: "episode" });
|
|
639
|
+
} catch {
|
|
640
|
+
return { ids, checked: 0, total: 0 };
|
|
641
|
+
}
|
|
642
|
+
if (needle.length === 0) return { ids, checked: episodes.length, total: episodes.length };
|
|
643
|
+
const cap = Math.max(0, opts.echoScanMax ?? JOURNAL_ECHO_SCAN_MAX);
|
|
644
|
+
let checked = 0;
|
|
645
|
+
for (const id of episodes) {
|
|
646
|
+
if (checked >= cap) break;
|
|
647
|
+
checked += 1;
|
|
648
|
+
if (id === targetId || ids.includes(id)) continue;
|
|
649
|
+
try {
|
|
650
|
+
const row = store.row(id);
|
|
651
|
+
if (row === undefined || rowTombstoned(row)) continue;
|
|
652
|
+
if (folded(store.readProse(id).body).includes(needle)) ids.push(id);
|
|
653
|
+
} catch {
|
|
654
|
+
/* a row that will not read cannot be claimed either way */
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return { ids, checked, total: episodes.length };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* STEP 1 + 2: validate, then read everything the removal will need. Pure — it
|
|
662
|
+
* writes nothing and takes no lock, so it is safe to run before a confirmation
|
|
663
|
+
* prompt and safe to run again after one (scar §2.13's re-plan-under-the-lock
|
|
664
|
+
* rule; E5's never-hold-a-lock-across-a-human-prompt rule).
|
|
665
|
+
*/
|
|
666
|
+
export function planRemoval(
|
|
667
|
+
store: Store,
|
|
668
|
+
targetId: string,
|
|
669
|
+
opts: PlanOptions = {},
|
|
670
|
+
): RemovalPlan {
|
|
671
|
+
const none = (reason: RemovalPlan["reason"]): RemovalPlan => ({
|
|
672
|
+
targetId,
|
|
673
|
+
valid: false,
|
|
674
|
+
reason,
|
|
675
|
+
contamination: [],
|
|
676
|
+
surfaces: [],
|
|
677
|
+
// An invalid target is not a memory to have residue: nothing was read and
|
|
678
|
+
// nothing is claimed about the buffer.
|
|
679
|
+
spans: {
|
|
680
|
+
surface: "spans",
|
|
681
|
+
state: "not-applicable",
|
|
682
|
+
path: null,
|
|
683
|
+
count: 0,
|
|
684
|
+
echoes: 0,
|
|
685
|
+
matchedBy: "none",
|
|
686
|
+
candidates: [],
|
|
687
|
+
line: "spans: not applicable — there is nothing here to have ridden the buffer.",
|
|
688
|
+
},
|
|
689
|
+
spanChase: { scope: null, hashes: [], byContent: false },
|
|
690
|
+
unchasable: [],
|
|
691
|
+
leftAlone: [],
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
const row = store.row(targetId);
|
|
695
|
+
if (row === undefined) return none("unknown-id");
|
|
696
|
+
if (!MEMORY_BEARING.has(row.type)) return none("not-memory-bearing");
|
|
697
|
+
if (store.deniedIds().includes(targetId)) return none("already-removed");
|
|
698
|
+
// THE SELF PAGE IS NOT REMOVED, IT IS CLEARED (2026-09-18, S1, and the
|
|
699
|
+
// adversarial review that found the dead end). Removal tombstones a row —
|
|
700
|
+
// blank body, blank content hash, id on the deny-list, row still listed — and
|
|
701
|
+
// `schemas/` reads every `type: "schema"` row at open, so removing the page
|
|
702
|
+
// (or the identity core, which has had the same exposure since it shipped)
|
|
703
|
+
// left a store that would not open at all, with the wake hook swallowing the
|
|
704
|
+
// error so the symptom was silence.
|
|
705
|
+
//
|
|
706
|
+
// *(The floor, 2026-09-20, closed the crash half of that: `Schemas.load`
|
|
707
|
+
// SKIPS a tombstoned row and counts it, so a removed page no longer takes the
|
|
708
|
+
// session down. Everything below still holds and is why this door stays —
|
|
709
|
+
// removal is permanent and the page is the one schema row the owner is
|
|
710
|
+
// guaranteed to have, so sending him to `--clear` is about being able to put
|
|
711
|
+
// it back, not only about the store opening.)*
|
|
712
|
+
//
|
|
713
|
+
// The page is also the most conspicuous schema row an owner has:
|
|
714
|
+
// `enumerate()` lists it and `status` prints its id. So the console sends him
|
|
715
|
+
// one door along, to the one that keeps the page as a version and lets him
|
|
716
|
+
// put it back.
|
|
717
|
+
if (isSelfPageRow(store, targetId)) return none("is-the-self-page");
|
|
718
|
+
|
|
719
|
+
// EVERYTHING THAT READS THE DOOMED CONTENT HAPPENS HERE (§16 G13).
|
|
720
|
+
let body = "";
|
|
721
|
+
let doc: { meta?: Record<string, unknown> } | null = null;
|
|
722
|
+
try {
|
|
723
|
+
const read = store.readProse(targetId);
|
|
724
|
+
body = read.body;
|
|
725
|
+
doc = read;
|
|
726
|
+
} catch {
|
|
727
|
+
// The prose is already gone. The removal still proceeds — the row, the
|
|
728
|
+
// graph and the deny-list entry are the rest of the surface, and the span
|
|
729
|
+
// hash is still reachable through `origin_ref` and the coverage marks.
|
|
730
|
+
}
|
|
731
|
+
const chase = chaseHashes(store, doc, row);
|
|
732
|
+
const contamination: string[] = [];
|
|
733
|
+
if (body.trim().length > 0) {
|
|
734
|
+
for (const hit of store.search(body, 20)) {
|
|
735
|
+
if (hit.id !== targetId) contamination.push(hit.id);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const versions = store.versions(targetId);
|
|
740
|
+
const edges = store.edgesFrom(targetId);
|
|
741
|
+
const prospective = store.prospectiveFor(targetId);
|
|
742
|
+
// Read WITH the rest (§16 G13): the buffer is searched for this memory's span
|
|
743
|
+
// before anything is chased, because after the chase there is nothing left to
|
|
744
|
+
// search for. Counts and states come out; not one line of what it read.
|
|
745
|
+
const spans = spanResidue(store, targetId, body, chase.hashes, opts);
|
|
746
|
+
// THE JOURNAL'S MARKDOWN COPY (F6). Two different questions, and they get
|
|
747
|
+
// two different answers:
|
|
748
|
+
// - this memory's OWN file — an episode has one; anything else has none —
|
|
749
|
+
// which the chase syncs away with the row.
|
|
750
|
+
// - OTHER episodes whose chapters quote these words. LEFT ON PURPOSE and
|
|
751
|
+
// said out loud, the way a spans echo is (§16 G15) — never "unchased",
|
|
752
|
+
// because nothing failed to be reached.
|
|
753
|
+
const ownJournalFiles = journalFilesFor(store.dir, targetId).length;
|
|
754
|
+
const journalEchoes = journalEcho(store, targetId, body, doc, opts);
|
|
755
|
+
|
|
756
|
+
return {
|
|
757
|
+
targetId,
|
|
758
|
+
valid: true,
|
|
759
|
+
reason: "ok",
|
|
760
|
+
contamination,
|
|
761
|
+
surfaces: [
|
|
762
|
+
{ surface: "prose", count: 1 },
|
|
763
|
+
{ surface: "versions", count: versions.length },
|
|
764
|
+
{ surface: "edges", count: edges.length },
|
|
765
|
+
{ surface: "prospective", count: prospective.length },
|
|
766
|
+
{ surface: "operational rows", count: 1 },
|
|
767
|
+
{ surface: "cache", count: 1 },
|
|
768
|
+
// Stated at 0 too, like `spans`: silence about an empty surface is what
|
|
769
|
+
// made the span residue undiscoverable (LAUNCH-STATUS §I2). The count is
|
|
770
|
+
// this memory's OWN copy; the echo below is a different question and gets
|
|
771
|
+
// its own sentence, because a `0` here with an echo under it would read as
|
|
772
|
+
// "this surface is clean" over a file that holds the words.
|
|
773
|
+
{ surface: "journal", count: ownJournalFiles },
|
|
774
|
+
// The seventh, and it is in this list rather than beside it now: a surface
|
|
775
|
+
// that is chased belongs with the chased ones. It is stated at 0 too — the
|
|
776
|
+
// silence about an empty buffer is what made the residue undiscoverable
|
|
777
|
+
// (LAUNCH-STATUS §I2). Not for `unknown`, where a `0` beside a "NOT
|
|
778
|
+
// chased" line would read as a contradiction rather than a disclosure;
|
|
779
|
+
// that state says its whole piece in its own sentence.
|
|
780
|
+
...(spans.state === "unknown" ? [] : [{ surface: "spans", count: spans.count }]),
|
|
781
|
+
],
|
|
782
|
+
spans,
|
|
783
|
+
spanChase: {
|
|
784
|
+
scope: chase.scope,
|
|
785
|
+
hashes: chase.hashes,
|
|
786
|
+
// A content match is what the strike falls back to when the mint recorded
|
|
787
|
+
// no hash. Only when there IS a body to match on, and only when the scope
|
|
788
|
+
// is recorded — or the owner has said, in so many words, that a chase
|
|
789
|
+
// across every project on the machine is what they want (review F4).
|
|
790
|
+
byContent:
|
|
791
|
+
chase.hashes.length === 0 &&
|
|
792
|
+
body.trim().length > 0 &&
|
|
793
|
+
(chase.scope !== null || opts.crossScopeContent === true),
|
|
794
|
+
},
|
|
795
|
+
// Empty of CHASE failures until run time (the box-2 chase landed 2026-08-25,
|
|
796
|
+
// INTERFACE-GAPS §1; the span chase 2026-09-05) — and no longer holding the
|
|
797
|
+
// `held` case, which is chased. `unknown` stays: a surface this console
|
|
798
|
+
// cannot rule out is exactly what §16 G15's "no silent partial success"
|
|
799
|
+
// says a plan must name here rather than let the report say `nothing`.
|
|
800
|
+
// A surface this console could not rule out. NOT the echo, which is not a
|
|
801
|
+
// failure to reach anything — see `leftAlone` (review F6).
|
|
802
|
+
unchasable: spans.state === "unknown" ? [spans.line] : [],
|
|
803
|
+
// What is deliberately not taken. The wording is the plan's, so the dry run
|
|
804
|
+
// and the completion report say the same thing about the same lines.
|
|
805
|
+
leftAlone: [
|
|
806
|
+
...(spans.echoes > 0
|
|
807
|
+
? [
|
|
808
|
+
`spans echo: ${spans.echoes} line${spans.echoes === 1 ? "" : "s"} of conversation quoting these words — transcript, not this memory's capture. Left on purpose. Nothing prunes the buffer today, so ${spans.echoes === 1 ? "it stays" : "they stay"} there.`,
|
|
809
|
+
]
|
|
810
|
+
: []),
|
|
811
|
+
...(journalEchoes.ids.length > 0
|
|
812
|
+
? [
|
|
813
|
+
`journal echo: ${journalEchoes.ids.length} episode${journalEchoes.ids.length === 1 ? "" : "s"} whose chapters quote these words — the counterpart's own account of those days, not this memory. Left on purpose, row and markdown copy alike, so ${journalEchoes.ids.length === 1 ? "that .md under journal/ still holds the words" : "those .md files under journal/ still hold the words"}, and any snapshot or backup already taken holds them too. To take one as well: ${journalEchoes.ids.map((id) => `counterparts remove ${id} --confirm`).join(" · ")}`,
|
|
814
|
+
]
|
|
815
|
+
: []),
|
|
816
|
+
// A BOUNDED CHECK SAYS SO. A stated bound is survivable; a silent one is
|
|
817
|
+
// the finding this whole line exists to close (MAJOR-3).
|
|
818
|
+
...(journalEchoes.checked < journalEchoes.total
|
|
819
|
+
? [
|
|
820
|
+
`journal echo check was BOUNDED: checked ${journalEchoes.checked} of ${journalEchoes.total} episodes, so an episode past that quoting these words is not named above. 'counterparts export --out <dir> --markdown --plaintext' writes every chapter out if you want to look yourself.`,
|
|
821
|
+
]
|
|
822
|
+
: []),
|
|
823
|
+
// THE COPIES ALREADY ON DISK, whenever a journal file is in play — this
|
|
824
|
+
// memory's own, or another episode's (review f6f7 MAJOR-5).
|
|
825
|
+
...(row.type === "episode" || journalEchoes.ids.length > 0
|
|
826
|
+
? [olderCopiesNote(store.dir)]
|
|
827
|
+
: []),
|
|
828
|
+
],
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* STEPS 3–5. The one implementation of `OwnerRemovalPort`.
|
|
834
|
+
*
|
|
835
|
+
* It throws only when the RECORD cannot be written, because that is the single
|
|
836
|
+
* failure where doing nothing is correct. Every later failure is caught, counted
|
|
837
|
+
* and reported in `unchased` — a chase that half-worked must say so.
|
|
838
|
+
*/
|
|
839
|
+
export function ownerRemoval(
|
|
840
|
+
store: Store,
|
|
841
|
+
request: OwnerRemovalRequest,
|
|
842
|
+
opts: RemovalOptions = {},
|
|
843
|
+
): OwnerRemovalOutcome {
|
|
844
|
+
const emit = opts.onEvent ?? ((): void => {});
|
|
845
|
+
const notes: RemovalNote[] = [];
|
|
846
|
+
const append = (stage: RemovalNote["stage"], addendum?: string): void => {
|
|
847
|
+
const note: RemovalNote = {
|
|
848
|
+
memoryId: request.targetId,
|
|
849
|
+
stage,
|
|
850
|
+
actor: request.actor,
|
|
851
|
+
// The OWNER's reason stays first and whole; an addendum is appended
|
|
852
|
+
// rather than substituted, because why he removed it is the part of this
|
|
853
|
+
// record that matters longest.
|
|
854
|
+
reason: addendum === undefined ? request.reason : `${request.reason} [${addendum}]`,
|
|
855
|
+
};
|
|
856
|
+
store.appendRemovalRecord(note);
|
|
857
|
+
notes.push(note);
|
|
858
|
+
emit("cli.removal.stage", { stage, target: request.targetId });
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
const plan = planRemoval(store, request.targetId, {
|
|
862
|
+
...(opts.crossScopeContent === undefined ? {} : { crossScopeContent: opts.crossScopeContent }),
|
|
863
|
+
});
|
|
864
|
+
if (!plan.valid) {
|
|
865
|
+
// Nothing is recorded for a target that was never removable: a record here
|
|
866
|
+
// would put an id on the deny-list on the strength of a typo.
|
|
867
|
+
throw new Error(`removal refused: ${plan.reason}`);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// 3. REQUESTED — if this throws, nothing has moved and nothing will (§16 G10).
|
|
871
|
+
append("requested");
|
|
872
|
+
|
|
873
|
+
// Read the body BEFORE `dark`, and keep it local: it is the strike's fallback
|
|
874
|
+
// predicate for a memory whose mint recorded no span hash, and after the chase
|
|
875
|
+
// there is nothing left to match on. It never enters the plan, the report or
|
|
876
|
+
// any record — the seam receives a FUNCTION, not a string (§16 G15).
|
|
877
|
+
let doomedBody = "";
|
|
878
|
+
try {
|
|
879
|
+
doomedBody = store.readProse(request.targetId).body.trim();
|
|
880
|
+
} catch {
|
|
881
|
+
/* already gone; the hashes are the chase then, or nothing is */
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// 4. DARK — the deny-list is live from this line onward (§16 G12).
|
|
885
|
+
append("dark");
|
|
886
|
+
|
|
887
|
+
const chased: string[] = [];
|
|
888
|
+
const unchased: string[] = [...plan.unchasable];
|
|
889
|
+
const leftAlone: string[] = [...plan.leftAlone];
|
|
890
|
+
|
|
891
|
+
// 5. CHASE. THE SPAN BUFFER FIRST, because it is the only surface whose key
|
|
892
|
+
// the later steps destroy: `chaseRemoved` blanks the row — its
|
|
893
|
+
// `origin_ref`, its body and its `content_hash` — and those are what
|
|
894
|
+
// address a span. Strike while the addressing still exists.
|
|
895
|
+
//
|
|
896
|
+
// It is `remember/`'s own seam, not an `rmSync` from here: `spans/` is that
|
|
897
|
+
// module's state machine, and a claim renaming the buffer aside underneath
|
|
898
|
+
// a naive rewrite is the "in neither claim nor buffer" state spec §2 G6
|
|
899
|
+
// exists to forbid (cli/INTERFACE-GAPS §9).
|
|
900
|
+
if (plan.spans.state === "held") {
|
|
901
|
+
try {
|
|
902
|
+
const buffer = new SpanBuffer({ dir: store.dir, day: () => store.livedDay() });
|
|
903
|
+
const report = strikeSpans(buffer, {
|
|
904
|
+
scope: plan.spanChase.scope,
|
|
905
|
+
hashes: plan.spanChase.hashes,
|
|
906
|
+
// EXACT-LINE EQUALITY, never a substring (review F4). A jot whose whole
|
|
907
|
+
// text is this memory's body IS this memory; a jot that merely contains
|
|
908
|
+
// the words is a different memory that mentions them, and striking it
|
|
909
|
+
// is a destruction nobody asked for.
|
|
910
|
+
...(plan.spanChase.byContent && doomedBody.length > 0
|
|
911
|
+
? { predicate: (text: string): boolean => text.trim() === doomedBody }
|
|
912
|
+
: {}),
|
|
913
|
+
});
|
|
914
|
+
if (report.reason === "STRUCK") {
|
|
915
|
+
chased.push(`spans(${report.struck} line${report.struck === 1 ? "" : "s"} in ${report.files.length} file${report.files.length === 1 ? "" : "s"})`);
|
|
916
|
+
// What happened to the OTHER two places a span hash lives, said out
|
|
917
|
+
// loud: the terminal ledger keeps the hash so nothing re-admits the
|
|
918
|
+
// words, and a claim file mid-arc was rewritten under its worker.
|
|
919
|
+
if (report.ledgered > 0) {
|
|
920
|
+
chased.push(`spans ledger(${report.ledgered} hash${report.ledgered === 1 ? "" : "es"} kept in consumed.jsonl so nothing re-captures the words)`);
|
|
921
|
+
}
|
|
922
|
+
if (report.touchedClaim) chased.push("spans claim file(rewritten; a restore cannot put it back)");
|
|
923
|
+
emit("cli.removal.spans", {
|
|
924
|
+
struck: report.struck,
|
|
925
|
+
files: report.files.length,
|
|
926
|
+
ledgered: report.ledgered,
|
|
927
|
+
byHash: plan.spanChase.hashes.length > 0,
|
|
928
|
+
});
|
|
929
|
+
if (report.recovered > 0) {
|
|
930
|
+
chased.push(`spans recovered(${report.recovered} line${report.recovered === 1 ? "" : "s"} folded back out of a crashed strike's aside)`);
|
|
931
|
+
}
|
|
932
|
+
} else {
|
|
933
|
+
// The failure arm gets its OWN sentence. Reusing the plan's line here
|
|
934
|
+
// printed "the removal strikes them out of it" underneath a strike that
|
|
935
|
+
// did not happen — the report contradicting itself in the one place it
|
|
936
|
+
// must not (review, note-only).
|
|
937
|
+
unchased.push(
|
|
938
|
+
`spans (${report.reason}) — the strike did not run; ${plan.spans.path ?? "the capture buffer"} still holds this memory's words, and ${SPANS_BLIND}`,
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
} catch {
|
|
942
|
+
unchased.push(
|
|
943
|
+
`spans (threw) — the strike did not run; ${plan.spans.path ?? "the capture buffer"} still holds this memory's words, and ${SPANS_BLIND}`,
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// THE WORDS ARE NOT A SEPARATE STEP ANY MORE. Until the floor this is
|
|
949
|
+
// where box 1 was chased: unlink the memory's prose file, unlink each
|
|
950
|
+
// archived version's file, remove the `versions/<id>/` directory — four
|
|
951
|
+
// filesystem operations with three crash points between them and the box-2
|
|
952
|
+
// transaction below, each one leaving a different half-erased state. Since
|
|
953
|
+
// schema v6 the words are columns on the rows, so `chaseRemoved` blanks
|
|
954
|
+
// them inside the same transaction that removes the edges and appends the
|
|
955
|
+
// record. One commit; no window (§16 G11).
|
|
956
|
+
//
|
|
957
|
+
// Box 2, and the `chased` stage with it: the seam appends the record INSIDE
|
|
958
|
+
// its own transaction, so the rows and the record land together or not at all.
|
|
959
|
+
// What survives is named in the report, never implied (§16 G15).
|
|
960
|
+
try {
|
|
961
|
+
const report = chaseRemoved(store, request.targetId);
|
|
962
|
+
for (const surface of report.removed) chased.push(`${surface.surface}(${surface.count})`);
|
|
963
|
+
for (const surface of report.neutralized) {
|
|
964
|
+
chased.push(`${surface.surface}(${surface.count}, tombstoned)`);
|
|
965
|
+
}
|
|
966
|
+
notes.push({ memoryId: request.targetId, stage: "chased", actor: request.actor });
|
|
967
|
+
emit("cli.removal.stage", { stage: "chased", target: request.targetId });
|
|
968
|
+
} catch {
|
|
969
|
+
unchased.push("operational rows");
|
|
970
|
+
append("chased");
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// THE JOURNAL'S MARKDOWN COPY (F6), chased after the row and before the
|
|
974
|
+
// cache, because it is derived from the row and the row has just gone dark.
|
|
975
|
+
//
|
|
976
|
+
// It is a file under `<store>/journal/` holding an episode's words, and it is
|
|
977
|
+
// exactly the shape of finding the reviews raised twice on this floor: a
|
|
978
|
+
// second on-disk copy the chase does not visit while the console prints
|
|
979
|
+
// `unchased: nothing`. `syncJournalCopy` re-asks the invariant rather than
|
|
980
|
+
// deleting by name — the row is tombstoned and denied by now, so the answer
|
|
981
|
+
// is "no file", and the same call is what the chapter door uses to write one.
|
|
982
|
+
try {
|
|
983
|
+
const synced = syncJournalCopy(store, request.targetId);
|
|
984
|
+
if (synced.outcome === "failed") {
|
|
985
|
+
unchased.push(
|
|
986
|
+
`journal (${synced.reason ?? "unknown"}) — the markdown copy of this episode is still under ${JOURNAL_STILL_THERE}`,
|
|
987
|
+
);
|
|
988
|
+
} else if (synced.outcome === "removed") {
|
|
989
|
+
chased.push("journal(1 markdown copy)");
|
|
990
|
+
} else {
|
|
991
|
+
// "nothing to remove" is a disclosure, not a silence: a memory that never
|
|
992
|
+
// had a journal file and an episode whose file was chased must not read
|
|
993
|
+
// the same (§16 G15). And when an ECHO was reported, this line may not
|
|
994
|
+
// say "nothing beside the row" — that reads as "this surface is clean"
|
|
995
|
+
// two lines above a disclosure that it is not (review f6f7 MAJOR-3).
|
|
996
|
+
const echoes = plan.leftAlone.filter((line) => line.startsWith("journal echo:")).length;
|
|
997
|
+
chased.push(
|
|
998
|
+
echoes === 0
|
|
999
|
+
? "journal(0, nothing beside the row)"
|
|
1000
|
+
: "journal(0 of its own; other episodes' copies left on purpose, see above)",
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
} catch {
|
|
1004
|
+
unchased.push(`journal (threw) — the markdown copy may still be under ${JOURNAL_STILL_THERE}`);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Box 3: the rebuild skips every denied id and LOGS the skip, so the cache
|
|
1008
|
+
// comes back without the memory and with a record that it was left out.
|
|
1009
|
+
try {
|
|
1010
|
+
store.rebuildCache();
|
|
1011
|
+
chased.push("cache");
|
|
1012
|
+
} catch {
|
|
1013
|
+
unchased.push("cache");
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// THE WRITE-AHEAD LOG IS A SURFACE, and the floor is what made it one.
|
|
1017
|
+
//
|
|
1018
|
+
// §16 G14 says every copy is chased. While the words were a file, the blank
|
|
1019
|
+
// of the row's pointer and the `rmSync` of the file between them left nothing
|
|
1020
|
+
// readable behind. Now the words are a COLUMN, and an `UPDATE ... SET
|
|
1021
|
+
// body = ''` in WAL mode appends the change to the `-wal` while the page
|
|
1022
|
+
// holding the old text stays in it until a checkpoint moves it. Measured
|
|
1023
|
+
// 2026-09-20 on this branch: right after a chase the doomed text is NOT in
|
|
1024
|
+
// `counterparts.sqlite` and IS in `counterparts.sqlite-wal`; one TRUNCATE
|
|
1025
|
+
// checkpoint clears it from both. (Nothing that LEAVES the machine ever held
|
|
1026
|
+
// it — `backup` and `export` are `VACUUM INTO`, measured clean either way.)
|
|
1027
|
+
//
|
|
1028
|
+
// TRUNCATE rather than PASSIVE, because PASSIVE leaves the file at its length
|
|
1029
|
+
// with the old bytes still in it. On its own connection, and it never throws:
|
|
1030
|
+
// a checkpoint contended by another reader is reported as unchased, which is
|
|
1031
|
+
// true and actionable, rather than taking the removal down after the rows
|
|
1032
|
+
// have already gone.
|
|
1033
|
+
chaseWriteAheadLog(store.dir, chased, unchased);
|
|
1034
|
+
|
|
1035
|
+
// THE DURABLE RECORD MUST NOT CLAIM MORE THAN THE CONSOLE (third review's
|
|
1036
|
+
// open question). The record's stages carry no surface list, so `complete`
|
|
1037
|
+
// has always meant "the ceremony finished", not "everything was reached" —
|
|
1038
|
+
// but a reader coming back to it months later has only that word. So when
|
|
1039
|
+
// anything went unchased the count rides on the stage's own `reason`, beside
|
|
1040
|
+
// the owner's: the console's sentence is ephemeral and this is not.
|
|
1041
|
+
append(
|
|
1042
|
+
"complete",
|
|
1043
|
+
unchased.length === 0
|
|
1044
|
+
? undefined
|
|
1045
|
+
: `${unchased.length} surface${unchased.length === 1 ? "" : "s"} unchased — see the console report`,
|
|
1046
|
+
);
|
|
1047
|
+
emit("cli.removal.complete", {
|
|
1048
|
+
target: request.targetId,
|
|
1049
|
+
chased: chased.length,
|
|
1050
|
+
unchased: unchased.length,
|
|
1051
|
+
contamination: plan.contamination.length,
|
|
1052
|
+
});
|
|
1053
|
+
|
|
1054
|
+
return { chased, unchased, leftAlone, notes };
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Fold the write-ahead log back into the database and truncate it, so the page
|
|
1059
|
+
* that held the removed words stops being readable beside the store.
|
|
1060
|
+
*
|
|
1061
|
+
* Never throws (CLI CONTRACT §5 G8's reasoning): by the time this runs the rows
|
|
1062
|
+
* are already gone and the record is already written, and a failure here is a
|
|
1063
|
+
* line in the report, not an exception out of a removal that succeeded.
|
|
1064
|
+
*/
|
|
1065
|
+
function chaseWriteAheadLog(dir: string, chased: string[], unchased: string[]): void {
|
|
1066
|
+
// BOTH DATABASES, and the second one is review B's MAJOR-1.
|
|
1067
|
+
//
|
|
1068
|
+
// The first draft checkpointed box 2 and called the surface done. Box 3 is
|
|
1069
|
+
// also in WAL and also holds the removed memory's text — as `doc_tokens`
|
|
1070
|
+
// rows, rewritten by the `rebuildCache()` one step earlier — and the OLD
|
|
1071
|
+
// pages sit in `cache/cache.sqlite` until something folds them over.
|
|
1072
|
+
// Reviewer B found the words there in 3 of 5 runs of one shape while the
|
|
1073
|
+
// console printed `unchased: nothing`: the owner told the directory was
|
|
1074
|
+
// clean when it was not. The index really was chased (`live_rows=[]`); it was
|
|
1075
|
+
// the bytes on disk that were not, and the same open-checkpoint-close cleared
|
|
1076
|
+
// them 3/3 when asked directly.
|
|
1077
|
+
//
|
|
1078
|
+
// Not a freelist problem and not a `secure_delete` one (`freelist_count` was
|
|
1079
|
+
// 0 in those runs): these are exactly box 2's pages, in the database this
|
|
1080
|
+
// function did not visit. Reported as its OWN surface, so "cache" keeps
|
|
1081
|
+
// meaning the index and this keeps meaning the file.
|
|
1082
|
+
reclaim(paths.operational(dir), "write-ahead log and freed pages", chased, unchased);
|
|
1083
|
+
reclaim(paths.cache(dir), "cache write-ahead log and freed pages", chased, unchased);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
* One database made to stop holding the removed words: **VACUUM, then a TRUNCATE
|
|
1088
|
+
* checkpoint**, reported by name.
|
|
1089
|
+
*
|
|
1090
|
+
* **Why VACUUM and not just the checkpoint** (the third review's NEW-MAJOR-1).
|
|
1091
|
+
* Blanking a body frees the pages it sat on, and a body long enough to take
|
|
1092
|
+
* OVERFLOW pages leaves whole pages on the freelist. `secure_delete` is 2 (FAST)
|
|
1093
|
+
* by default, which zeroes only the slack of a page being rewritten, never a
|
|
1094
|
+
* whole freed page — so the words stayed legible in `counterparts.sqlite`
|
|
1095
|
+
* itself, in a page no row points at, while the report said `unchased: nothing`.
|
|
1096
|
+
* Measured on this branch, deterministic 5/5 with marks at the start, middle and
|
|
1097
|
+
* end of a ~40 KB body: only the START mark was cleared (its page gets reused),
|
|
1098
|
+
* the middle and the end survived. A SECOND checkpoint does not help. VACUUM
|
|
1099
|
+
* rebuilds the file from the live pages only, and it is the one remedy that
|
|
1100
|
+
* clears residue whatever freed the page and whenever — a revision months ago,
|
|
1101
|
+
* a prune, this removal — which is what "removed means gone" has to mean.
|
|
1102
|
+
*
|
|
1103
|
+
* **Order matters:** in WAL mode a VACUUM writes into the log, so the main file
|
|
1104
|
+
* is unchanged until a checkpoint. VACUUM alone reads as a no-op.
|
|
1105
|
+
*
|
|
1106
|
+
* `secure_delete = ON` for the chase's own connection was the cheaper candidate
|
|
1107
|
+
* and is NOT used: it measured clean on some shapes and left the middle and end
|
|
1108
|
+
* marks on others, because it only zeroes what THAT transaction frees — a page
|
|
1109
|
+
* freed by an earlier revision is not its business. A guarantee that depends on
|
|
1110
|
+
* page-allocation luck is not a guarantee.
|
|
1111
|
+
*
|
|
1112
|
+
* **Cost, measured, on a 17,000-memory store** (9.3 MB box 2, 16.6 MB box 3):
|
|
1113
|
+
* VACUUM 23 ms and 58 ms, checkpoint under a millisecond. Removal is a rare,
|
|
1114
|
+
* deliberate owner operation; this is not a price anyone will feel.
|
|
1115
|
+
*
|
|
1116
|
+
* It never throws (CLI CONTRACT §5 G8): by the time this runs the rows are gone
|
|
1117
|
+
* and the record is written. A contended VACUUM is a line in the report saying
|
|
1118
|
+
* what is still there and what clears it — never silence, and never `nothing`.
|
|
1119
|
+
*/
|
|
1120
|
+
function reclaim(path: string, surface: string, chased: string[], unchased: string[]): void {
|
|
1121
|
+
// A database that is not there has nothing to reclaim. Box 3 is rebuildable
|
|
1122
|
+
// and a store may never have built one.
|
|
1123
|
+
if (!existsSync(path)) return;
|
|
1124
|
+
let db;
|
|
1125
|
+
try {
|
|
1126
|
+
db = openDb(path);
|
|
1127
|
+
db.exec("VACUUM");
|
|
1128
|
+
const row = db.get<Record<string, number>>("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
1129
|
+
// The first column is 1 when SQLite could not finish — a reader was holding
|
|
1130
|
+
// an older snapshot. Say so; the next checkpoint clears it.
|
|
1131
|
+
const busy = row === undefined ? 1 : Object.values(row)[0];
|
|
1132
|
+
if (busy === 0) chased.push(surface);
|
|
1133
|
+
else unchased.push(`${surface} (${STILL_THERE})`);
|
|
1134
|
+
} catch (err) {
|
|
1135
|
+
// The REASON rides along — a SQLite message is a code and a path, never
|
|
1136
|
+
// memory text (§5 G10) — because "could not" with no why is the silence
|
|
1137
|
+
// this whole report exists to remove.
|
|
1138
|
+
const why = isLocked(err) ? "the database was busy" : String((err as Error).message ?? err);
|
|
1139
|
+
unchased.push(`${surface} (${why}; ${STILL_THERE})`);
|
|
1140
|
+
} finally {
|
|
1141
|
+
try {
|
|
1142
|
+
db?.close();
|
|
1143
|
+
} catch {
|
|
1144
|
+
/* a handle that will not close has already said what it could */
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* What is true when the reclaim could not finish, and what clears it. Said in
|
|
1151
|
+
* the report rather than left as a silence: the ROWS are gone either way — this
|
|
1152
|
+
* is about pages no row points at, which a later removal or a named command
|
|
1153
|
+
* folds over.
|
|
1154
|
+
*/
|
|
1155
|
+
const STILL_THERE =
|
|
1156
|
+
"the memory's rows are gone, but its words may remain in pages no row points at until " +
|
|
1157
|
+
"the next successful removal or 'counterparts verify --dir <store> --rebuild'";
|
|
1158
|
+
|
|
1159
|
+
/**
|
|
1160
|
+
* The read-back a removal is only trustworthy with: is the id dark, is its prose
|
|
1161
|
+
* gone, and does any canonical file still hold its text? Ids only in, verdict
|
|
1162
|
+
* out — no body ever crosses this boundary.
|
|
1163
|
+
*/
|
|
1164
|
+
export function verifyRemoval(store: Store, targetId: string): {
|
|
1165
|
+
denied: boolean;
|
|
1166
|
+
/** True when the row carries no words: the body is blank. Named `proseGone`
|
|
1167
|
+
* while the words were a file; it asks the same question of the column. */
|
|
1168
|
+
bodyGone: boolean;
|
|
1169
|
+
/** True while a row exists at all — after the chase it is a stripped skeleton. */
|
|
1170
|
+
rowSurvives: boolean;
|
|
1171
|
+
/** True when that row has been stripped of every content pointer. */
|
|
1172
|
+
rowTombstoned: boolean;
|
|
1173
|
+
/** Box-2 state that should be gone: edges, prospective windows, gate rows. */
|
|
1174
|
+
darkState: number;
|
|
1175
|
+
} {
|
|
1176
|
+
const row = store.row(targetId);
|
|
1177
|
+
const tombstone = store.tombstones().find((e) => e.id === targetId);
|
|
1178
|
+
return {
|
|
1179
|
+
denied: store.deniedIds().includes(targetId),
|
|
1180
|
+
bodyGone: row === undefined || row.body === "",
|
|
1181
|
+
rowSurvives: row !== undefined,
|
|
1182
|
+
rowTombstoned: tombstone !== undefined && row !== undefined && rowTombstoned(row),
|
|
1183
|
+
darkState:
|
|
1184
|
+
store.edgesFrom(targetId).length + store.prospectiveFor(targetId).length,
|
|
1185
|
+
};
|
|
1186
|
+
}
|