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.
Files changed (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,760 @@
1
+ /**
2
+ * THE JOURNAL'S MARKDOWN COPY — the one file the owner can open in any editor.
3
+ *
4
+ * Constitution line 6 promises "memories kept as prose the owner can view".
5
+ * Since the floor (schema v6) every body is a column, so that promise is kept
6
+ * in two named places and nowhere else: `counterparts export --markdown`, and
7
+ * this — a `.md` per episode under `<store>/journal/`, written as each chapter
8
+ * lands. It is here rather than in an adapter because the owner ruled it so
9
+ * (decision 2, 2026-09-17 §15 item 9: "the self is being recovered from v1
10
+ * right now because its pages and journal were plain files that outlived their
11
+ * system").
12
+ *
13
+ * **BY OWNER DECISION 2 THIS IS THE ONE `self/` MODULE THAT TREATS `Store.dir`
14
+ * AS A FILESYSTEM ROOT.** Said at the top rather than left for a reviewer to
15
+ * find. `remember/spans.ts` is the precedent: a core module that owns one
16
+ * directory inside the store and nothing else.
17
+ *
18
+ * Four properties, and each one is a decision somebody can reverse:
19
+ *
20
+ * - **DERIVED AND WRITE-ONLY.** The row is the truth. Nothing in this
21
+ * codebase ever reads a journal file back into the store — there is no
22
+ * parser here, on purpose, and `render.ts` says the same from its side.
23
+ * Deleting `journal/` loses nothing: the next chapter, or the background
24
+ * worker's next backfill pass, writes it again.
25
+ * - **WRITTEN AS IS** (owner ruling 2, 2026-09-18). No summary, no
26
+ * re-rendering of the words, no second renderer: `render.ts#renderMarkdown`
27
+ * is what export writes and it is what this writes, byte for byte. The
28
+ * front matter identifies the episode — id, session, dates, chapter count —
29
+ * and carries nothing the row does not hold. Credentials were redacted at
30
+ * the gate before the row was written (`self/index.ts#appendChapter`); this
31
+ * copies the row and cannot un-redact anything.
32
+ * - **IT NEVER FAILS A SESSION.** Nothing here throws. A copy that cannot be
33
+ * written is a `journal.copy.failed` row with a reason code; the chapter is
34
+ * already committed and is not at risk. A `chapter` call, a Stop hook and a
35
+ * boundary must not be able to fail because a disk was full.
36
+ * - **THE REMOVAL CHASE REACHES IT.** A file holding a removed memory's words
37
+ * while the console prints `unchased: nothing` is the finding F5's reviews
38
+ * raised twice (B MAJOR-1, C NEW-MAJOR-1) and the span buffer's scar before
39
+ * that. `syncJournalCopy` is the executable form of the invariant: a live
40
+ * episode row gets a file that matches it, and anything else gets no file.
41
+ * The owner's destruction console calls it as a named surface. (Named
42
+ * obliquely on purpose: a test greps every file under `src/` for that
43
+ * module's own filename and fails on a mention, which is how the
44
+ * one-importer rule is kept honest.)
45
+ */
46
+ import {
47
+ existsSync,
48
+ lstatSync,
49
+ mkdirSync,
50
+ readFileSync,
51
+ readdirSync,
52
+ renameSync,
53
+ rmSync,
54
+ statSync,
55
+ writeFileSync,
56
+ } from "node:fs";
57
+ import { join } from "node:path";
58
+
59
+ import { renderMarkdown, rowTombstoned } from "../store/index.js";
60
+ import type { ProseDoc, Store } from "../store/index.js";
61
+
62
+ /** The directory, spelled once. `store/paths.ts#LAYOUT` classified it before
63
+ * this file existed — scar §2.11, and the reason that entry carries a date. */
64
+ export const JOURNAL_DIR = "journal";
65
+
66
+ /** A copy landed. Payload: the episode id, the store-relative file, bytes. */
67
+ export const JOURNAL_COPY_WRITTEN_EVENT = "journal.copy.written";
68
+ /** A copy did not land, with the reason code. The row is safe either way. */
69
+ export const JOURNAL_COPY_FAILED_EVENT = "journal.copy.failed";
70
+
71
+ /**
72
+ * How many missing copies one backfill pass writes.
73
+ *
74
+ * WHERE IT ACTUALLY RUNS, checked rather than assumed: `Self.boundary()` is the
75
+ * consolidation cycle's last content write, reached through
76
+ * `core/briefing.ts#selfRenderer` (SEAMS G), so the backfill runs in the
77
+ * DETACHED WORKER — not in the session's Stop hook, which calls
78
+ * `Counterpart.boundary` (a different method: it appends spans and thinks about
79
+ * nothing). The owner's `counterparts rebrief` is the other door.
80
+ *
81
+ * It is still bounded twice, by this count and by the deadline below, for the
82
+ * same reason every other phase in that worker is: the worker is watchdogged
83
+ * and shares a cycle with decay, dedup and the prune, and a file loop with no
84
+ * ceiling is how one phase eats another's budget. The cost of the bound is
85
+ * honest: a store with a thousand episodes and no `journal/` fills over forty
86
+ * WORKER RUNS, which on the owner's cadence is weeks, not minutes. The chapter
87
+ * door is what keeps a live store's copies current; this is for a store whose
88
+ * episodes predate the feature, or whose `journal/` was deleted.
89
+ */
90
+ export const JOURNAL_BACKFILL_PER_PASS = 25;
91
+
92
+ /**
93
+ * …and the bound for a store that has NO copies at all.
94
+ *
95
+ * The case is a restore. Since 2026-09-20 `journal/` is not in the backup set
96
+ * (f6f7 review MAJOR-5: copying it put removed episodes' words into every
97
+ * rotating snapshot as plain markdown), so a restored store has the rows and
98
+ * none of the files — and "a restored snapshot brings the copies back" must not
99
+ * mean "over the next forty worker runs". The wall clock below is the real
100
+ * protection and it still applies; this only stops the COUNT from being the
101
+ * thing that makes a restore take weeks.
102
+ */
103
+ export const JOURNAL_BACKFILL_COLD_PASS = 1_000;
104
+
105
+ /** …and the wall-clock half of that bound. A slow disk stops the pass, not the
106
+ * cycle; whatever is left is the next run's work. It is what bounds the cold
107
+ * pass above, so a restore of a very large store is still many passes — just
108
+ * passes measured by the clock rather than by a count chosen for a warm one. */
109
+ export const JOURNAL_BACKFILL_BUDGET_MS = 250;
110
+
111
+ /**
112
+ * How old an abandoned `.tmp-*` must be before a later pass removes it.
113
+ *
114
+ * Same shape and the same reasoning as `cli/export.ts#EXPORT_SCRATCH_STALE_MS`:
115
+ * the bound is what keeps a sweep from taking a CONCURRENT writer's temp file
116
+ * mid-rename. A crashed rename leaves a file holding a chapter's words, and
117
+ * a crashed rename otherwise leaves a chapter's words in a file nothing owns,
118
+ * inside the store, for ever.
119
+ */
120
+ export const JOURNAL_TEMP_STALE_MS = 60 * 60_000;
121
+
122
+ /** The date part of a path when the row carries no date at all. A row with no
123
+ * `learned_on` is real (`self/briefing.ts` writes one), and "undated" is a
124
+ * better answer in a filename than an invented day. */
125
+ export const UNDATED = "undated";
126
+
127
+ export type JournalCopyOutcome =
128
+ /** The file was written (or rewritten) and now matches the row. */
129
+ | "written"
130
+ /** The file already matched the row. Nothing was touched. */
131
+ | "unchanged"
132
+ /** The row is gone, tombstoned or denied, so its file was removed. */
133
+ | "removed"
134
+ /** There was nothing to write and nothing to remove. */
135
+ | "absent"
136
+ /** Named, never silent. The row is canonical and is not at risk. */
137
+ | "failed";
138
+
139
+ export interface JournalCopyResult {
140
+ readonly episodeId: string;
141
+ readonly outcome: JournalCopyOutcome;
142
+ /** Store-RELATIVE, always — an absolute path in a durable row says more about
143
+ * the machine than the owner typed (§5 G10). Null when there is no file. */
144
+ readonly file: string | null;
145
+ readonly bytes: number;
146
+ /** A CODE, never a message that could carry body text. */
147
+ readonly reason: string | null;
148
+ }
149
+
150
+ /** The store-relative directory. */
151
+ export function journalDir(storeDir: string): string {
152
+ return join(storeDir, JOURNAL_DIR);
153
+ }
154
+
155
+ /**
156
+ * `journal/<YYYY>/<YYYY-MM-DD>-<episodeId>.md`.
157
+ *
158
+ * **One file per episode, not per chapter and not per day.** An episode is one
159
+ * row that every chapter is appended into (`episodes.ts#appendChapter`), so a
160
+ * per-chapter file would have to take the row apart to write it and a per-day
161
+ * file would have to join two sessions' accounts into one document. Neither is
162
+ * the thing the row is. A whole-file rewrite per append is idempotent, which is
163
+ * what makes "delete it and it comes back" true.
164
+ *
165
+ * The DATE is the row's `learnedOn` — when the session lived, which is what a
166
+ * reader browsing `journal/2026/` is looking for. `happenedOn` is deliberately
167
+ * not used: it is stated at whatever precision the author gave (`2026`,
168
+ * `2026-08`), and a filename that is sometimes a year is not a filename.
169
+ */
170
+ export function journalRelativePath(doc: Pick<ProseDoc, "id" | "learnedOn">): string {
171
+ const date = /^\d{4}-\d{2}-\d{2}$/.test(doc.learnedOn) ? doc.learnedOn : UNDATED;
172
+ const year = date === UNDATED ? UNDATED : date.slice(0, 4);
173
+ return `${JOURNAL_DIR}/${year}/${date}-${doc.id}.md`;
174
+ }
175
+
176
+ /**
177
+ * The episode id a STORE-RELATIVE journal path addresses, or null.
178
+ *
179
+ * It matches the temp form too (`…​.md.tmp-<rand>`), which is the point: a
180
+ * crashed rename leaves a file holding the chapter's words, and a sweep that
181
+ * only knew the final name would walk past it. `<date>-` is a fixed-width
182
+ * prefix so the id comes back EXACTLY rather than by `includes`, which would
183
+ * let `epi_ab` match `epi_abc`'s file.
184
+ *
185
+ * **It takes the whole path and pins the DEPTH** (review f6f7 NIT-2, and the
186
+ * reason MAJOR-4's consequence was worse than mess): it used to match on the
187
+ * basename, so any `.md` anywhere under `journal/` with a date-shaped name was
188
+ * treated as a copy — including one an export smuggled in through a symlinked
189
+ * target, which `journalFilesFor` then returned, the next append deleted as
190
+ * "stale", and the backfill counted as a copy the episode already had.
191
+ * Exactly `journal/<year>/<file>` is ours; anything else under that directory
192
+ * belongs to whoever put it there.
193
+ */
194
+ export function journalFileEpisodeId(relativePath: string): string | null {
195
+ const m =
196
+ /^journal\/(?:\d{4}|undated)\/(?:\d{4}-\d{2}-\d{2}|undated)-(.+?)\.md(?:\.tmp-[A-Za-z0-9]+)?$/.exec(
197
+ relativePath,
198
+ );
199
+ return m === null ? null : (m[1] as string);
200
+ }
201
+
202
+ /**
203
+ * THE SYMLINK RULE — what makes "this module owns one directory INSIDE the
204
+ * store" true rather than intended.
205
+ *
206
+ * `journalFiles` used to walk with `statSync`, which FOLLOWS links, and every
207
+ * arm downstream resolved the same path through them. So a symlink anywhere at
208
+ * or under `journal/` turned this module into a writer and a deleter outside
209
+ * the store. Measured by the f6f7 review: a chapter's full body landed in a
210
+ * directory outside the store, and a removal ceremony deleted a file out there
211
+ * and reported `chased: journal(1 markdown copy)` for it.
212
+ *
213
+ * It is not only an attacker's story. `journal/` is the one directory the owner
214
+ * is INVITED to treat as files, so pointing a year at an external disk, a synced
215
+ * folder or a vault is exactly the thing a person does with it. The answer is
216
+ * not to follow it, and to SAY SO (`journal-symlink`) — a copy that quietly
217
+ * wrote somewhere else would be worse than one that did not write at all.
218
+ *
219
+ * Every component from `journal` down to the file is `lstat`ed. A component that
220
+ * does not exist is fine: it is about to be created, and nothing beyond it can
221
+ * exist either. A component that IS a link is refused. `journal` itself is
222
+ * included, because `mkdirSync(…, { recursive: true })` succeeds straight
223
+ * THROUGH a symlinked directory — so this has to run before the mkdir, not after.
224
+ */
225
+ export function journalPathIsLinked(storeDir: string, relativePath: string): boolean {
226
+ let at = storeDir;
227
+ for (const part of relativePath.split("/")) {
228
+ at = join(at, part);
229
+ try {
230
+ if (lstatSync(at).isSymbolicLink()) return true;
231
+ } catch {
232
+ return false;
233
+ }
234
+ }
235
+ return false;
236
+ }
237
+
238
+ /** True for the temp form only — what a sweep may take and a copy may not. */
239
+ export function isJournalTempName(name: string): boolean {
240
+ return /\.md\.tmp-[A-Za-z0-9]+$/.test(name);
241
+ }
242
+
243
+ /**
244
+ * FAILURES THAT ARE ABOUT THE DIRECTORY, not about an episode.
245
+ *
246
+ * The distinction earns its keep twice (review f6f7 MAJOR-2). A `journal/` that
247
+ * will not take a file is ONE fact about the store: saying it once a day is the
248
+ * whole truth, and saying it once per chapter and then 25 times per worker cycle
249
+ * — 80 rows in the review's probe, thousands a week on the owner's cadence —
250
+ * buries every other row in the log that `fired`, the dashboard and `doctor`
251
+ * read. And a directory-level failure must not spend the backfill's budget at
252
+ * all: there is nothing to retry until the directory changes.
253
+ */
254
+ export const JOURNAL_DIRECTORY_REASONS: readonly string[] = [
255
+ "journal-symlink",
256
+ "journal-dir-unwritable",
257
+ "journal-unreadable",
258
+ ];
259
+
260
+ export function isJournalDirectoryFailure(reason: string | null): boolean {
261
+ return reason !== null && JOURNAL_DIRECTORY_REASONS.includes(reason);
262
+ }
263
+
264
+ export interface JournalScan {
265
+ /** Every REAL file under `journal/`, store-relative, sorted. */
266
+ readonly files: string[];
267
+ /** A symlink was found at or under `journal/` and was not followed. The
268
+ * module stands down by name when this is true, rather than reporting an
269
+ * absence it cannot vouch for. */
270
+ readonly linked: boolean;
271
+ }
272
+
273
+ /**
274
+ * Walk `journal/` without following a single link, and say whether one was
275
+ * there.
276
+ *
277
+ * The `linked` half is not decoration. Skipping what is behind a link makes
278
+ * this module SAFE; saying so makes it HONEST — otherwise an owner who pointed
279
+ * `journal/2026` at his vault would get `absent` and "nothing beside the row"
280
+ * from a module that simply could not see.
281
+ */
282
+ export function journalScan(storeDir: string): JournalScan {
283
+ const root = journalDir(storeDir);
284
+ const out: string[] = [];
285
+ let linked = false;
286
+ try {
287
+ if (lstatSync(root).isSymbolicLink()) return { files: [], linked: true };
288
+ } catch {
289
+ return { files: [], linked: false };
290
+ }
291
+ const walk = (at: string, rel: string): void => {
292
+ let names: string[];
293
+ try {
294
+ names = readdirSync(at).sort();
295
+ } catch {
296
+ return;
297
+ }
298
+ for (const name of names) {
299
+ const full = join(at, name);
300
+ const next = rel === "" ? name : `${rel}/${name}`;
301
+ try {
302
+ // `lstat`, never `stat`: a symlink is SKIPPED, file or directory alike.
303
+ // That one word is what keeps every arm downstream — the rewrite, the
304
+ // removal's unlink, the temp sweep — inside the store, because a path
305
+ // behind a link is never listed and so is never acted on.
306
+ const st = lstatSync(full);
307
+ if (st.isSymbolicLink()) {
308
+ linked = true;
309
+ continue;
310
+ }
311
+ if (st.isDirectory()) walk(full, next);
312
+ else out.push(`${JOURNAL_DIR}/${next}`);
313
+ } catch {
314
+ /* vanished underneath the walk */
315
+ }
316
+ }
317
+ };
318
+ walk(root, "");
319
+ return { files: out, linked };
320
+ }
321
+
322
+ /** Every real file under `journal/`, store-relative, sorted. Names only;
323
+ * nothing is read, and nothing behind a symlink is listed. */
324
+ export function journalFiles(storeDir: string): string[] {
325
+ return journalScan(storeDir).files;
326
+ }
327
+
328
+ /** Every journal file that addresses `episodeId` — the current name, any name
329
+ * it wore under an earlier date, and any crashed temp. */
330
+ export function journalFilesFor(storeDir: string, episodeId: string): string[] {
331
+ return journalFiles(storeDir).filter((rel) => journalFileEpisodeId(rel) === episodeId);
332
+ }
333
+
334
+ /**
335
+ * Remove `.tmp-*` files older than the bound. Never throws.
336
+ *
337
+ * Bounded by mtime for the same reason `export.ts`'s temp sweep is: without it
338
+ * a pass would delete a CONCURRENT writer's file between its write and its
339
+ * rename. Unbounded housekeeping is how a sweep becomes the bug.
340
+ */
341
+ export function sweepJournalTemps(storeDir: string, now = Date.now()): string[] {
342
+ const swept: string[] = [];
343
+ for (const rel of journalFiles(storeDir)) {
344
+ const name = rel.slice(rel.lastIndexOf("/") + 1);
345
+ // OURS, at our depth, and wearing the temp form. A `.tmp-` file somebody
346
+ // else left under `journal/` is not this sweep's to take.
347
+ if (!isJournalTempName(name) || journalFileEpisodeId(rel) === null) continue;
348
+ const full = join(storeDir, rel);
349
+ try {
350
+ if (now - statSync(full).mtimeMs < JOURNAL_TEMP_STALE_MS) continue;
351
+ rmSync(full, { force: true });
352
+ swept.push(rel);
353
+ } catch {
354
+ /* a file that will not stat or will not go is not this pass's problem */
355
+ }
356
+ }
357
+ return swept;
358
+ }
359
+
360
+ /** The row's own markdown — `render.ts`, never a second renderer (§1.5). */
361
+ export function renderJournalCopy(doc: ProseDoc): string {
362
+ return renderMarkdown(doc);
363
+ }
364
+
365
+ /**
366
+ * MAKE THE FILES SAY WHAT THE ROWS SAY, for one episode.
367
+ *
368
+ * One function rather than a write and a delete, because the invariant is one
369
+ * sentence: *a journal file exists exactly when a live episode row does, and
370
+ * holds exactly what that row holds.* Removal calls this after the chase and
371
+ * gets the delete for free; the chapter door calls it after the write and gets
372
+ * the rewrite. A rule expressed twice is a rule that will be true in one place.
373
+ *
374
+ * NEVER THROWS. The caller has already committed the row.
375
+ */
376
+ export function syncJournalCopy(store: Store, episodeId: string): JournalCopyResult {
377
+ const result = (
378
+ outcome: JournalCopyOutcome,
379
+ extra: Partial<JournalCopyResult> = {},
380
+ ): JournalCopyResult => ({
381
+ episodeId,
382
+ outcome,
383
+ file: null,
384
+ bytes: 0,
385
+ reason: null,
386
+ ...extra,
387
+ });
388
+
389
+ // A LINK ANYWHERE AT OR UNDER `journal/` AND THIS MODULE STANDS DOWN, BY
390
+ // NAME. One rule rather than three: the walk already refuses to look behind
391
+ // one, so what is left to decide is whether the outcome is an honest
392
+ // `journal-symlink` or a misleading `absent`/`written`. It is the first,
393
+ // every time — including the removal arm, where the review watched a file
394
+ // outside the store get deleted and reported as chased.
395
+ let scan: JournalScan;
396
+ try {
397
+ scan = journalScan(store.dir);
398
+ } catch {
399
+ return result("failed", { reason: "journal-unreadable" });
400
+ }
401
+ if (scan.linked) return result("failed", { reason: "journal-symlink" });
402
+ // THE DIRECTORY, asked once and named as itself. Without this the chapter door
403
+ // reported `write-failed` per episode for a store whose `journal/` is a file,
404
+ // which is five rows for one fact (MAJOR-2).
405
+ try {
406
+ mkdirSync(journalDir(store.dir), { recursive: true });
407
+ } catch {
408
+ return result("failed", { reason: "journal-dir-unwritable" });
409
+ }
410
+ const existing = scan.files.filter((rel) => journalFileEpisodeId(rel) === episodeId);
411
+
412
+ // IS THERE A LIVE EPISODE HERE? A removed row survives as a tombstone (blank
413
+ // body, blank hash) and its id is on the deny-list, and `readProse` refuses a
414
+ // denied id by name. Both are asked before anything is read, so the file goes
415
+ // without this function ever holding the words again.
416
+ let doc: ProseDoc | null = null;
417
+ try {
418
+ const row = store.row(episodeId);
419
+ const live =
420
+ row !== undefined &&
421
+ row.type === "episode" &&
422
+ !rowTombstoned(row) &&
423
+ !store.deniedIds().includes(episodeId);
424
+ if (live) doc = store.readProse(episodeId);
425
+ } catch {
426
+ // A row that will not read is not a row whose file may stand: fall through
427
+ // to the removal arm, which is the safe direction for a derived copy.
428
+ doc = null;
429
+ }
430
+
431
+ if (doc === null) {
432
+ let removed = 0;
433
+ for (const rel of existing) {
434
+ // Never unlink THROUGH a link. `journalFiles` already refuses to list
435
+ // what is behind one, so this is the second lock on the same door: the
436
+ // review's probe planted a file outside the store under a copy's name and
437
+ // watched the removal ceremony delete it, reporting it as chased.
438
+ if (journalPathIsLinked(store.dir, rel)) {
439
+ return result("failed", { reason: "journal-symlink", file: rel });
440
+ }
441
+ try {
442
+ rmSync(join(store.dir, rel), { force: true });
443
+ removed += 1;
444
+ } catch {
445
+ return result("failed", { reason: "unlink-failed", file: rel });
446
+ }
447
+ }
448
+ return removed === 0 ? result("absent") : result("removed", { file: existing[0] as string });
449
+ }
450
+
451
+ let text: string;
452
+ try {
453
+ text = renderJournalCopy(doc);
454
+ } catch {
455
+ // `renderMarkdown` refuses meta it cannot serialize and a malformed id. The
456
+ // CODE is what rides; its detail could name a title.
457
+ return result("failed", { reason: "render-refused" });
458
+ }
459
+ const rel = journalRelativePath(doc);
460
+ const bytes = Buffer.byteLength(text, "utf8");
461
+ const target = join(store.dir, rel);
462
+
463
+ // EVERY COMPONENT ON THE WAY DOWN, before the mkdir: a linked year directory
464
+ // is how the review's probe put a chapter's whole body outside the store, and
465
+ // `mkdirSync(…, { recursive: true })` succeeds straight through one.
466
+ if (journalPathIsLinked(store.dir, rel)) {
467
+ return result("failed", { reason: "journal-symlink", file: rel, bytes });
468
+ }
469
+
470
+ // A file this episode wore under a different date, and any crashed temp of
471
+ // its own, go first: two files for one episode is the state where "delete
472
+ // `journal/` and it comes back" stops being true.
473
+ const strandedStale: string[] = [];
474
+ for (const stale of existing) {
475
+ if (stale === rel) continue;
476
+ try {
477
+ rmSync(join(store.dir, stale), { force: true });
478
+ } catch {
479
+ // NAMED, not swallowed (review f6f7 NIT-3). It used to carry a comment
480
+ // promising it was "named below" and nothing below named it, so two files
481
+ // for one episode was a state that could exist and be reported `written`.
482
+ strandedStale.push(stale);
483
+ }
484
+ }
485
+
486
+ try {
487
+ if (
488
+ strandedStale.length === 0 &&
489
+ !lstatSync(target).isSymbolicLink() &&
490
+ readFileSync(target, "utf8") === text
491
+ ) {
492
+ return result("unchanged", { file: rel, bytes });
493
+ }
494
+ } catch {
495
+ /* not there, or unreadable: rewrite it, which is a derived copy's answer */
496
+ }
497
+
498
+ // ATOMIC: write a temp beside it and rename. A reader opening the file mid
499
+ // write must see the previous chapter or this one, never half a sentence.
500
+ // The temp is named `<final>.md.tmp-<rand>` so that ONE matcher finds the
501
+ // file, its older date, and a crashed temp (`journalFileEpisodeId`).
502
+ const temp = `${target}.tmp-${Math.random().toString(36).slice(2, 10)}`;
503
+ try {
504
+ mkdirSync(join(target, ".."), { recursive: true });
505
+ writeFileSync(temp, text, "utf8");
506
+ renameSync(temp, target);
507
+ } catch {
508
+ try {
509
+ rmSync(temp, { force: true });
510
+ } catch {
511
+ /* the sweep takes it later; it is bounded and it is inside the store */
512
+ }
513
+ return result("failed", { reason: "write-failed", file: rel, bytes });
514
+ }
515
+ // The copy landed — and if an older name for this same episode would not go,
516
+ // SAY SO rather than report a clean write over a store that now holds two
517
+ // files for one episode.
518
+ if (strandedStale.length > 0) {
519
+ return result("failed", { reason: "stale-copy-stranded", file: strandedStale[0] as string, bytes });
520
+ }
521
+ return result("written", { file: rel, bytes });
522
+ }
523
+
524
+ /** How far back the standing-failure read looks. Two lived days, because a
525
+ * failure recorded yesterday is still standing this morning and the lived
526
+ * clock only moves inside the worker's own cycle. */
527
+ export const JOURNAL_FAILURE_WINDOW_DAYS = 2;
528
+
529
+ /**
530
+ * Episodes whose copy FAILED and has not been written since — the ids the next
531
+ * pass must not spend its budget on.
532
+ *
533
+ * The starvation the review reasoned and this measures: the failing ids sit at
534
+ * the head of `store.list({type:"episode"})` and take the whole 25-slot budget
535
+ * on every pass, so nothing behind them is ever backfilled. Not "never retry" —
536
+ * never retry *ahead of work that has not been tried at all*. A later success
537
+ * clears the id, exactly as it clears the doctor's line, and the window means a
538
+ * store that was broken last week starts trying again.
539
+ *
540
+ * One bounded read of the event log, not a query per id. Ids only.
541
+ *
542
+ * THE WINDOW IS IN LIVED DAYS while the dedup key is in calendar dates, and the
543
+ * mismatch is deliberate rather than an oversight: the lived clock only moves
544
+ * inside the worker's own cycle, so on a store whose worker has been dead for a
545
+ * week this window covers EVERY row since the last cycle. That is the safe
546
+ * direction — more ids excluded from a pass, never fewer — and the alternative
547
+ * (a calendar window) would start retrying a broken episode on a store where
548
+ * nothing has run to fix it.
549
+ */
550
+ export function standingJournalFailures(store: Store): Set<string> {
551
+ const sinceDay = Math.max(0, store.livedDay() - JOURNAL_FAILURE_WINDOW_DAYS);
552
+ const newest = (name: string): Map<string, number> => {
553
+ const out = new Map<string, number>();
554
+ for (const row of store.eventLog({ name, sinceDay, limit: 5_000 })) {
555
+ if (row.ref !== null) out.set(row.ref, row.seq);
556
+ }
557
+ return out;
558
+ };
559
+ const failed = newest(JOURNAL_COPY_FAILED_EVENT);
560
+ const written = newest(JOURNAL_COPY_WRITTEN_EVENT);
561
+ const standing = new Set<string>();
562
+ for (const [id, seq] of failed) {
563
+ if ((written.get(id) ?? -1) < seq) standing.add(id);
564
+ }
565
+ return standing;
566
+ }
567
+
568
+ /**
569
+ * Episodes with no file — the backfill's work list, bounded by the caller.
570
+ *
571
+ * Ids and names only: one `SELECT id`, one directory walk, one bounded read of
572
+ * the log, no row read and no body. That is what makes it cheap enough to ask
573
+ * at every cycle.
574
+ *
575
+ * It fills what is MISSING and does not re-derive what is present. Drift within
576
+ * a file is the chapter door's business (it rewrites on every append) and the
577
+ * removal chase's (it syncs what it removed); a pass that re-rendered every
578
+ * episode would read every body in the store to prove nothing had changed.
579
+ */
580
+ export function journalBackfillTargets(store: Store, limit: number): string[] {
581
+ let have: Set<string>;
582
+ try {
583
+ have = new Set(
584
+ journalFiles(store.dir)
585
+ .map((rel) => journalFileEpisodeId(rel))
586
+ .filter((id): id is string => id !== null),
587
+ );
588
+ } catch {
589
+ return [];
590
+ }
591
+ const denied = new Set(store.deniedIds());
592
+ let standing: Set<string>;
593
+ try {
594
+ standing = standingJournalFailures(store);
595
+ } catch {
596
+ standing = new Set();
597
+ }
598
+ const out: string[] = [];
599
+ for (const id of store.list({ type: "episode" })) {
600
+ if (out.length >= limit) break;
601
+ if (have.has(id) || denied.has(id) || standing.has(id)) continue;
602
+ out.push(id);
603
+ }
604
+ return out;
605
+ }
606
+
607
+ export interface JournalBackfillReport {
608
+ readonly written: number;
609
+ readonly failed: number;
610
+ /** Ids whose copy landed — the caller writes the durable rows. */
611
+ readonly results: readonly JournalCopyResult[];
612
+ /** True when the bound stopped the pass with work left. */
613
+ readonly more: boolean;
614
+ readonly sweptTemps: number;
615
+ }
616
+
617
+ /**
618
+ * One bounded backfill pass. Never throws.
619
+ *
620
+ * `now` is injected so a test can age a temp file rather than wait an hour.
621
+ */
622
+ export function backfillJournalCopies(
623
+ store: Store,
624
+ opts: { limit?: number; budgetMs?: number; now?: () => number } = {},
625
+ ): JournalBackfillReport {
626
+ const budget = opts.budgetMs ?? JOURNAL_BACKFILL_BUDGET_MS;
627
+ const clock = opts.now ?? Date.now;
628
+ const started = clock();
629
+ // A COLD STORE GETS THE BIGGER COUNT. No copies at all and episodes to copy
630
+ // is what a restore looks like — `journal/` is not in the backup set — and a
631
+ // restore that took forty worker runs to become readable would have made the
632
+ // "it costs nothing to stop copying it" argument false. The wall clock below
633
+ // still bounds the pass either way.
634
+ const cold = (() => {
635
+ try {
636
+ return journalFiles(store.dir).length === 0;
637
+ } catch {
638
+ return false;
639
+ }
640
+ })();
641
+ const limit = opts.limit ?? (cold ? JOURNAL_BACKFILL_COLD_PASS : JOURNAL_BACKFILL_PER_PASS);
642
+ let sweptTemps = 0;
643
+ try {
644
+ sweptTemps = sweepJournalTemps(store.dir, started).length;
645
+ } catch {
646
+ /* housekeeping never decides whether the copies get written */
647
+ }
648
+ const results: JournalCopyResult[] = [];
649
+ let targets: string[];
650
+ try {
651
+ targets = journalBackfillTargets(store, limit);
652
+ } catch {
653
+ return { written: 0, failed: 0, results: [], more: false, sweptTemps };
654
+ }
655
+ let more = false;
656
+ for (const id of targets) {
657
+ if (clock() - started > budget) {
658
+ more = true;
659
+ break;
660
+ }
661
+ const result = syncJournalCopy(store, id);
662
+ // A DIRECTORY-LEVEL FAILURE ENDS THE PASS. It is one fact about the store,
663
+ // it is the same answer for every remaining episode, and spending 25 slots
664
+ // and 25 rows re-discovering it is what made the log unreadable (MAJOR-2).
665
+ // The result is carried as ITSELF, with no episode attached, so the row the
666
+ // caller writes says what is actually wrong.
667
+ if (isJournalDirectoryFailure(result.reason)) {
668
+ results.push({ ...result, episodeId: "", file: null, bytes: 0 });
669
+ return {
670
+ written: 0,
671
+ failed: 1,
672
+ results,
673
+ // There is work left, and no amount of retrying reaches it until the
674
+ // directory changes.
675
+ more: true,
676
+ sweptTemps,
677
+ };
678
+ }
679
+ results.push(result);
680
+ }
681
+ if (!more && targets.length >= limit) more = true;
682
+ return {
683
+ written: results.filter((r) => r.outcome === "written").length,
684
+ failed: results.filter((r) => r.outcome === "failed").length,
685
+ results,
686
+ more,
687
+ sweptTemps,
688
+ };
689
+ }
690
+
691
+ /**
692
+ * The durable row for one copy — `journal.copy.written` or `.failed`.
693
+ *
694
+ * Content-by-reference (§5 G10): the episode id, the store-relative file, a
695
+ * byte count, a chapter count, a reason CODE. Never a word of the chapter. The
696
+ * `date` field is what `adapters/fired.ts` reads to say when this mechanism
697
+ * last fired, so it rides on every row.
698
+ *
699
+ * It never throws either: an observer's store refuses every write by name, and
700
+ * a copy that could not be recorded is still a copy.
701
+ *
702
+ * **A FAILURE IS DEDUPED, per (episode, reason, day); a directory-level failure
703
+ * is deduped per (reason, day) and names no episode** (review f6f7 MAJOR-2,
704
+ * measured at 80 rows for one broken directory across five chapters and three
705
+ * worker cycles). The latch is the store's own `dedupKey`, so the second row of
706
+ * the same fact is refused inside the same transaction that would have written
707
+ * it rather than by a read this function would have to get right.
708
+ *
709
+ * THE DAY IN THE KEY IS THE CALENDAR DATE, not the lived day, and that is a
710
+ * deliberate divergence from the ask's wording: it is the same `date` the
711
+ * payload carries and `doctor` prints, so the key and the row cannot disagree
712
+ * about what a day is. The lived clock advances only inside the worker's own
713
+ * cycle (`episodes.ts#asksSpentOn`, scar I32), so keying on it would make a
714
+ * store whose worker has not run for a week dedup a week of failures into one.
715
+ *
716
+ * The cost, said out loud: dedup-keyed rows are never swept by `pruneEvents` —
717
+ * they are the replay latch. One row per episode per reason per day is a bounded
718
+ * price for a log that can be read; a permanently broken directory leaves one
719
+ * row a day, for ever, and that is the point rather than an oversight.
720
+ *
721
+ * SUCCESSES ARE NOT DEDUPED. "The copy was written" is what the fired view
722
+ * counts, and a mechanism that recorded one firing a day would under-report the
723
+ * thing the owner is watching for.
724
+ */
725
+ export function noteJournalCopy(
726
+ store: Store,
727
+ result: JournalCopyResult,
728
+ opts: { day: number; chapters?: number; site: string },
729
+ ): void {
730
+ if (result.outcome === "unchanged" || result.outcome === "absent") return;
731
+ const failed = result.outcome === "failed";
732
+ const directory = isJournalDirectoryFailure(result.reason);
733
+ // A directory-level row names no episode: `ref` is the subject, and the
734
+ // subject here is the store's own directory.
735
+ const ref = failed && directory ? null : result.episodeId === "" ? null : result.episodeId;
736
+ const date = store.today();
737
+ const dedupKey = failed
738
+ ? `${JOURNAL_COPY_FAILED_EVENT}:${directory ? "dir" : String(ref)}:${String(result.reason)}:${date}`
739
+ : undefined;
740
+ try {
741
+ store.appendEvent({
742
+ name: failed ? JOURNAL_COPY_FAILED_EVENT : JOURNAL_COPY_WRITTEN_EVENT,
743
+ day: opts.day,
744
+ ref,
745
+ ...(dedupKey === undefined ? {} : { dedupKey }),
746
+ payload: {
747
+ date,
748
+ site: opts.site,
749
+ outcome: result.outcome,
750
+ file: result.file,
751
+ bytes: result.bytes,
752
+ ...(opts.chapters === undefined ? {} : { chapters: opts.chapters }),
753
+ ...(result.reason === null ? {} : { reason: result.reason }),
754
+ ...(directory ? { scope: "directory" } : {}),
755
+ },
756
+ });
757
+ } catch {
758
+ /* a row that cannot be recorded does not undo the file that was written */
759
+ }
760
+ }