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,659 @@
1
+ /**
2
+ * `counterparts repair-dates` — giving the migrated rows back their real dates.
3
+ *
4
+ * THE FINDING (PARALLEL-RUN-STATUS 2026-09-04, LAUNCH-STATUS §I7). 12,334 of the
5
+ * 14,529 migrated memories on the live store carry the IMPORT DAY as `learned_on`:
6
+ * v1's traces mostly had no `created` field, and `store.put` defaulted the date to
7
+ * whatever day the importer ran. `bornDay` kept the real age, so the physics is
8
+ * unaffected and nothing decayed wrongly — but every one of those rows now tells
9
+ * the owner it was learned on a day it was not, and #29/#30 had to render them as
10
+ * an upper bound ("by 2026-09-03 ·") because the row does not say which it is.
11
+ *
12
+ * THE REPAIR IS EVIDENCE, NOT ARITHMETIC. This tool invents no dates. It reads
13
+ * what the migration already carried into each row's prose meta and proposes a
14
+ * date only where something in the row actually says one:
15
+ *
16
+ * HIGH the v1 document said so — a `created` (or `created_at` / `date`) field
17
+ * carried through as `meta.v1Extra`, or an engram-era id that IS a
18
+ * millisecond timestamp (`…_1721984400000`), which is a fact about when
19
+ * the row was minted rather than an inference about it.
20
+ * MEDIUM something ADJACENT to the row says so — `meta.sessionRef` carrying a
21
+ * timestamp or a date (a session id dates the conversation, and a trace
22
+ * from that session was learned during it), or the `statedOn` /
23
+ * `openedOn` a v1 SCHEMA ELEMENT carried (a real v1 date about the
24
+ * statement rather than about the encode — one step removed, which is
25
+ * what separates this tier from the one above).
26
+ * LOW the PATH says so — the source path the trace was read from carries a
27
+ * `YYYY-MM` or a `YYYY-MM-DD` (v1 filed some traces by month). A month
28
+ * resolves to its first day and says so; that is a bound presented as a
29
+ * date, so it is the tier nothing applies by default.
30
+ *
31
+ * Every proposal is checked against a window — no earlier than `PLAUSIBLE_FLOOR`,
32
+ * no later than the import day — because a fourteen-digit number that happens to
33
+ * parse is not evidence, and a "learned" date after the day of the import is a
34
+ * contradiction on its face. A stronger tier's candidate that fails the window
35
+ * yields to a weaker one BEHIND it, and that is counted too (`supersededTier`), so
36
+ * the report's tier counts and its rejection counts add up to the target set
37
+ * rather than to some of it.
38
+ *
39
+ * THREE RE-RUN GUARDS, all of them added after an adversarial review reproduced
40
+ * the failure (PR #67 review §2): a second `--apply` on a repaired store wrote ten
41
+ * no-op revisions and ten events for five rows, and at live scale that is ~12K
42
+ * archived documents recording a change that did not happen.
43
+ *
44
+ * 1. **The import day is PINNED, not re-measured.** `measureImportDay` takes the
45
+ * MODE of `learned_on`, and after a repair the mode can move to a repaired
46
+ * date — which both narrows the plausibility window and pulls correctly-dated
47
+ * rows into the target set. So the first run RECORDS the day it used
48
+ * (`IMPORT_DAY_META`, and the migration writes `MIGRATED_ON_META` for stores
49
+ * imported from here on), later runs read it back, and a measured day that
50
+ * disagrees with a recorded one is a REFUSAL rather than a silent winner.
51
+ * 2. **A row that was already repaired is never a target.** `--apply` writes
52
+ * `meta.dateRepaired` onto the document; a row carrying it is skipped by name.
53
+ * 3. **A proposal equal to the row's current date is never written.** A re-dating
54
+ * that changes nothing must not archive a version and claim it did.
55
+ *
56
+ * DRY RUN IS THE DEFAULT and `--apply` is the only way past it, exactly as
57
+ * `backfill-claims` works. `--apply` writes through `store.revise`, so the prior
58
+ * document — with its wrong date — is archived into `versions/` first and stays
59
+ * readable: correcting a date is a revision, and constitution 7 says a revision
60
+ * keeps its history. The owner runs `--apply`; nothing here runs it for him.
61
+ */
62
+ import { Store, storeExists } from "../../core/store/index.js";
63
+
64
+ /** No memory in either lineage predates this. A parse below it is a coincidence. */
65
+ export const PLAUSIBLE_FLOOR = "2015-01-01";
66
+
67
+ /** Store meta: the import day THIS TOOL used, written by the first `--apply`. */
68
+ export const IMPORT_DAY_META = "repairDates.importDay";
69
+ /** Store meta: the day the v1 importer ran, written by `tools/migrate/apply.ts`. */
70
+ export const MIGRATED_ON_META = "migratedOn";
71
+ /** Prose meta on a repaired document. Read by `self/`'s wake to drop the bound. */
72
+ export const DATE_REPAIRED_META = "dateRepaired";
73
+
74
+ /**
75
+ * A single proposed date carrying more than this share of the target set is a
76
+ * BULK STAMP, not a set of real dates, and the dry run says so in as many words.
77
+ * v1's own importer stamping one day onto everything is exactly what this tool
78
+ * exists to undo, and re-doing it at confidence `high` would be the worst outcome
79
+ * available (PR #67 review §3).
80
+ */
81
+ export const BULK_STAMP_SHARE = 0.05;
82
+ /**
83
+ * ...and carrying at least this many rows. Without a floor the warning fires on
84
+ * every date in a five-row store, where "50% of the proposals" is one row, and a
85
+ * warning that fires every time is a warning nobody reads. At the live scale this
86
+ * exists for (12,334 rows) five percent is ~600, so the floor never suppresses a
87
+ * real bulk stamp — it only stops the small-store cry of wolf.
88
+ */
89
+ export const BULK_STAMP_MIN_ROWS = 5;
90
+
91
+ export type Confidence = "high" | "medium" | "low";
92
+
93
+ export interface DateProposal {
94
+ readonly date: string;
95
+ readonly confidence: Confidence;
96
+ /** Which field the date was read out of — printed, so a sample row is checkable. */
97
+ readonly from: string;
98
+ /** How it was read: the shape of the evidence, not its content. */
99
+ readonly how:
100
+ | "v1-date-field"
101
+ | "id-timestamp"
102
+ | "session-timestamp"
103
+ | "session-date"
104
+ | "element-stated-on"
105
+ | "element-opened-on"
106
+ | "path-date"
107
+ | "path-month";
108
+ }
109
+
110
+ export type RefusalReason =
111
+ | "no-evidence"
112
+ | "out-of-window"
113
+ | "already-correct"
114
+ | "already-repaired";
115
+
116
+ export type ProposalOutcome =
117
+ | {
118
+ readonly ok: true;
119
+ readonly proposal: DateProposal;
120
+ /** A STRONGER candidate existed and failed the window; this one won behind it. */
121
+ readonly superseded: boolean;
122
+ }
123
+ | { readonly ok: false; readonly reason: RefusalReason };
124
+
125
+ /** v1 frontmatter keys that carried a real encode date. Read in this order. */
126
+ const V1_DATE_KEYS = ["created", "created_at", "createdAt", "date", "encoded"] as const;
127
+
128
+ /** 13 digits starting with 1: epoch ms from 2001-09-09 to 2286. Bounded further below. */
129
+ const MS_RUN = /(?<!\d)(1\d{12})(?!\d)/;
130
+ const ISO_DAY = /(?<!\d)(\d{4})-(\d{2})-(\d{2})(?!\d)/;
131
+ const ISO_MONTH = /(?<!\d)(\d{4})-(\d{2})(?![\d-])/;
132
+
133
+ const TIER_ORDER: Record<Confidence, number> = { low: 0, medium: 1, high: 2 };
134
+
135
+ function dateOfMs(ms: number): string {
136
+ return new Date(ms).toISOString().slice(0, 10);
137
+ }
138
+
139
+ /** A real calendar day inside the window the store could plausibly have lived. */
140
+ function withinWindow(date: string, importDay: string): boolean {
141
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return false;
142
+ const at = Date.parse(`${date}T00:00:00Z`);
143
+ if (Number.isNaN(at)) return false;
144
+ // A round-trip catches 2026-02-31 and friends, which `Date.parse` rolls over.
145
+ if (dateOfMs(at) !== date) return false;
146
+ return date >= PLAUSIBLE_FLOOR && date <= importDay;
147
+ }
148
+
149
+ function str(v: unknown): string {
150
+ return typeof v === "string" ? v : "";
151
+ }
152
+
153
+ function record(v: unknown): Record<string, unknown> {
154
+ return typeof v === "object" && v !== null && !Array.isArray(v)
155
+ ? (v as Record<string, unknown>)
156
+ : {};
157
+ }
158
+
159
+ /**
160
+ * What a migrated row says about its own date, at the strongest tier that says
161
+ * anything AND survives the window. Tiers in order; a stronger candidate that
162
+ * fails the window yields to a weaker one and the result says `superseded: true`,
163
+ * so a silent fall-through is a counted fact rather than an invisible one.
164
+ */
165
+ export function proposeDate(meta: Record<string, unknown>, importDay: string): ProposalOutcome {
166
+ if (meta[DATE_REPAIRED_META] !== undefined) return { ok: false, reason: "already-repaired" };
167
+
168
+ const candidates: DateProposal[] = [];
169
+ const migratedFrom = str(meta["migratedFrom"]);
170
+ const hash = migratedFrom.lastIndexOf("#");
171
+ const v1Id = hash >= 0 ? migratedFrom.slice(hash + 1) : str(meta["v1Id"]);
172
+ const sourcePath = hash >= 0 ? migratedFrom.slice(0, hash) : migratedFrom;
173
+ // v1's OWN document wins over the envelope around it: the migration writes
174
+ // nothing named `created` at top level today, and if it ever did, the outer
175
+ // wrapper must not shadow the field it was wrapping (review §4).
176
+ const extra = { ...meta, ...record(meta["v1Extra"]) };
177
+
178
+ // HIGH — the v1 document carried a date field.
179
+ for (const key of V1_DATE_KEYS) {
180
+ const raw = str(extra[key]);
181
+ const day = ISO_DAY.exec(raw);
182
+ if (day !== null && day[0] !== undefined) {
183
+ candidates.push({ date: day[0], confidence: "high", from: `v1Extra.${key}`, how: "v1-date-field" });
184
+ break;
185
+ }
186
+ const ms = MS_RUN.exec(raw);
187
+ if (ms !== null && ms[1] !== undefined) {
188
+ candidates.push({
189
+ date: dateOfMs(Number(ms[1])),
190
+ confidence: "high",
191
+ from: `v1Extra.${key}`,
192
+ how: "v1-date-field",
193
+ });
194
+ break;
195
+ }
196
+ }
197
+
198
+ // HIGH — the engram-era id IS a millisecond timestamp.
199
+ const idMs = MS_RUN.exec(v1Id);
200
+ if (idMs !== null && idMs[1] !== undefined) {
201
+ candidates.push({
202
+ date: dateOfMs(Number(idMs[1])),
203
+ confidence: "high",
204
+ from: "migratedFrom#id",
205
+ how: "id-timestamp",
206
+ });
207
+ }
208
+
209
+ // MEDIUM — the session the trace came from.
210
+ const sessionRef = str(meta["sessionRef"]) || str(meta["session"]);
211
+ const sessionMs = MS_RUN.exec(sessionRef);
212
+ if (sessionMs !== null && sessionMs[1] !== undefined) {
213
+ candidates.push({
214
+ date: dateOfMs(Number(sessionMs[1])),
215
+ confidence: "medium",
216
+ from: "sessionRef",
217
+ how: "session-timestamp",
218
+ });
219
+ } else {
220
+ const sessionDay = ISO_DAY.exec(sessionRef);
221
+ if (sessionDay !== null && sessionDay[0] !== undefined) {
222
+ candidates.push({
223
+ date: sessionDay[0],
224
+ confidence: "medium",
225
+ from: "sessionRef",
226
+ how: "session-date",
227
+ });
228
+ }
229
+ }
230
+
231
+ // MEDIUM — a v1 SCHEMA ELEMENT's own dates (`tools/migrate/plan.ts` writes both
232
+ // onto element-as-memory rows). Real v1 dates, and better evidence than a path
233
+ // month — but they date the STATEMENT, not the encode, which is why they sit
234
+ // here and not beside `created`.
235
+ for (const [key, how] of [
236
+ ["statedOn", "element-stated-on"],
237
+ ["openedOn", "element-opened-on"],
238
+ ] as const) {
239
+ const raw = str(meta[key]);
240
+ const day = ISO_DAY.exec(raw);
241
+ if (day !== null && day[0] !== undefined) {
242
+ candidates.push({ date: day[0], confidence: "medium", from: `meta.${key}`, how });
243
+ }
244
+ }
245
+
246
+ // LOW — the path v1 filed it under.
247
+ const pathDay = ISO_DAY.exec(sourcePath);
248
+ if (pathDay !== null && pathDay[0] !== undefined) {
249
+ candidates.push({ date: pathDay[0], confidence: "low", from: "migratedFrom#path", how: "path-date" });
250
+ } else {
251
+ const pathMonth = ISO_MONTH.exec(sourcePath);
252
+ if (pathMonth !== null && pathMonth[1] !== undefined && pathMonth[2] !== undefined) {
253
+ candidates.push({
254
+ date: `${pathMonth[1]}-${pathMonth[2]}-01`,
255
+ confidence: "low",
256
+ from: "migratedFrom#path",
257
+ how: "path-month",
258
+ });
259
+ }
260
+ }
261
+
262
+ if (candidates.length === 0) return { ok: false, reason: "no-evidence" };
263
+ const index = candidates.findIndex((c) => withinWindow(c.date, importDay));
264
+ if (index < 0) return { ok: false, reason: "out-of-window" };
265
+ const usable = candidates[index];
266
+ if (usable === undefined) return { ok: false, reason: "out-of-window" };
267
+ // Superseded means a STRONGER tier was available and the window refused it —
268
+ // not merely that some earlier candidate lost, which ordering alone would say.
269
+ const superseded = candidates
270
+ .slice(0, index)
271
+ .some((c) => TIER_ORDER[c.confidence] > TIER_ORDER[usable.confidence]);
272
+ return { ok: true, proposal: usable, superseded };
273
+ }
274
+
275
+ export interface RepairTarget {
276
+ readonly id: string;
277
+ readonly kind: string;
278
+ readonly learnedOn: string;
279
+ readonly outcome: ProposalOutcome;
280
+ }
281
+
282
+ export type ImportDaySource = "flag" | "recorded" | "migration" | "measured";
283
+
284
+ export interface RepairPlan {
285
+ /** The date the importer stamped. Every target carries it as `learned_on`. */
286
+ readonly importDay: string;
287
+ /** Where the import day came from — never silently re-measured after a repair. */
288
+ readonly importDayFrom: ImportDaySource;
289
+ /** The mode of `learned_on` over live migrated rows, always measured for the report. */
290
+ readonly measuredDay: string;
291
+ /** A recorded day that the measurement contradicts. Non-null means REFUSE. */
292
+ readonly disagreement: { recorded: string; measured: string } | null;
293
+ /** Live migrated rows carrying the import day. */
294
+ readonly targets: readonly RepairTarget[];
295
+ readonly counts: {
296
+ /** LIVE migrated rows — the same set every other number here is over. */
297
+ readonly migrated: number;
298
+ readonly high: number;
299
+ readonly medium: number;
300
+ readonly low: number;
301
+ readonly noEvidence: number;
302
+ readonly outOfWindow: number;
303
+ readonly alreadyCorrect: number;
304
+ readonly alreadyRepaired: number;
305
+ /** Proposals where a STRONGER tier existed and the window refused it. */
306
+ readonly supersededTier: number;
307
+ };
308
+ }
309
+
310
+ export function meetsConfidence(c: Confidence, floor: Confidence): boolean {
311
+ return TIER_ORDER[c] >= TIER_ORDER[floor];
312
+ }
313
+
314
+ /** Live, migrated, not removed — ONE definition, so every count below is over it. */
315
+ function liveMigratedIds(store: Store): string[] {
316
+ const denied = new Set(store.deniedIds());
317
+ const out: string[] = [];
318
+ for (const id of store.list()) {
319
+ if (denied.has(id)) continue;
320
+ const row = store.row(id);
321
+ if (row === undefined || row.source !== "migrated") continue;
322
+ if (row.archived === 1 || row.superseded_by !== null) continue;
323
+ out.push(id);
324
+ }
325
+ return out;
326
+ }
327
+
328
+ /**
329
+ * The mode of `learned_on` over LIVE migrated rows — the same denominator every
330
+ * other number in the report uses (review §4: two denominators on adjacent lines).
331
+ *
332
+ * MEASURED IS NOT THE SAME AS TRUSTED. The importer wrote one date onto everything
333
+ * it could not date otherwise, so on an unrepaired store the mode IS the import
334
+ * day. After a repair it need not be: enough rows moved to one recovered date and
335
+ * the mode moves with them. That is why `resolveImportDay` prefers a RECORDED day
336
+ * and treats a disagreement as a refusal.
337
+ */
338
+ export function measureImportDay(store: Store): { day: string; migrated: number } {
339
+ const tally = new Map<string, number>();
340
+ const ids = liveMigratedIds(store);
341
+ for (const id of ids) {
342
+ const row = store.row(id);
343
+ if (row === undefined) continue;
344
+ tally.set(row.learned_on, (tally.get(row.learned_on) ?? 0) + 1);
345
+ }
346
+ let day = "";
347
+ let best = 0;
348
+ for (const [d, n] of [...tally].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
349
+ if (n > best) {
350
+ best = n;
351
+ day = d;
352
+ }
353
+ }
354
+ return { day, migrated: ids.length };
355
+ }
356
+
357
+ /**
358
+ * Which day this run treats as the import day, and where it came from.
359
+ *
360
+ * Order: the owner's flag, then the day a previous `--apply` recorded, then the
361
+ * day the migration recorded, then the measurement. A recorded day that the
362
+ * measurement contradicts is reported as a DISAGREEMENT and the command refuses:
363
+ * the two ways that happens are "somebody repaired this store already" and
364
+ * "this is not the store you think it is", and both want a human.
365
+ */
366
+ export function resolveImportDay(
367
+ store: Store,
368
+ flag?: string,
369
+ ): { day: string; from: ImportDaySource; measured: string; disagreement: { recorded: string; measured: string } | null } {
370
+ const measured = measureImportDay(store).day;
371
+ if (flag !== undefined) return { day: flag, from: "flag", measured, disagreement: null };
372
+ const recorded = store.getMeta(IMPORT_DAY_META) ?? store.getMeta(MIGRATED_ON_META) ?? "";
373
+ const from: ImportDaySource = store.getMeta(IMPORT_DAY_META) !== undefined ? "recorded" : "migration";
374
+ if (recorded !== "") {
375
+ const disagreement = measured !== "" && measured !== recorded ? { recorded, measured } : null;
376
+ return { day: recorded, from, measured, disagreement };
377
+ }
378
+ return { day: measured, from: "measured", measured, disagreement: null };
379
+ }
380
+
381
+ /** Read-only, always: the plan is made against an observer store (scar E5). */
382
+ export function planRepair(dir: string, importDayFlag?: string): RepairPlan {
383
+ const store = Store.open({ dir, observer: true });
384
+ try {
385
+ const resolved = resolveImportDay(store, importDayFlag);
386
+ const importDay = resolved.day;
387
+ const targets: RepairTarget[] = [];
388
+ const counts = {
389
+ migrated: 0,
390
+ high: 0,
391
+ medium: 0,
392
+ low: 0,
393
+ noEvidence: 0,
394
+ outOfWindow: 0,
395
+ alreadyCorrect: 0,
396
+ alreadyRepaired: 0,
397
+ supersededTier: 0,
398
+ };
399
+ const ids = liveMigratedIds(store);
400
+ counts.migrated = ids.length;
401
+ if (importDay === "") {
402
+ return {
403
+ importDay,
404
+ importDayFrom: resolved.from,
405
+ measuredDay: resolved.measured,
406
+ disagreement: resolved.disagreement,
407
+ targets,
408
+ counts,
409
+ };
410
+ }
411
+ for (const id of ids) {
412
+ const row = store.row(id);
413
+ if (row === undefined) continue;
414
+ // The repair is for the rows that carry the import day — a migrated row that
415
+ // kept a real v1 date is already right and is never rewritten.
416
+ if (row.learned_on !== importDay) continue;
417
+ let meta: Record<string, unknown> = {};
418
+ try {
419
+ meta = store.readProse(id).meta;
420
+ } catch {
421
+ meta = {};
422
+ }
423
+ let outcome = proposeDate(meta, importDay);
424
+ // A re-dating that changes nothing must not archive a version and claim it
425
+ // did (review §2a). Checked here rather than inside the evidence rules,
426
+ // because "what the row says" and "what the row already reads" are two
427
+ // different questions.
428
+ if (outcome.ok && outcome.proposal.date === row.learned_on) {
429
+ outcome = { ok: false, reason: "already-correct" };
430
+ }
431
+ if (outcome.ok) {
432
+ counts[outcome.proposal.confidence] += 1;
433
+ if (outcome.superseded) counts.supersededTier += 1;
434
+ } else if (outcome.reason === "no-evidence") counts.noEvidence += 1;
435
+ else if (outcome.reason === "already-correct") counts.alreadyCorrect += 1;
436
+ else if (outcome.reason === "already-repaired") counts.alreadyRepaired += 1;
437
+ else counts.outOfWindow += 1;
438
+ targets.push({ id, kind: row.kind, learnedOn: row.learned_on, outcome });
439
+ }
440
+ return {
441
+ importDay,
442
+ importDayFrom: resolved.from,
443
+ measuredDay: resolved.measured,
444
+ disagreement: resolved.disagreement,
445
+ targets,
446
+ counts,
447
+ };
448
+ } finally {
449
+ store.close();
450
+ }
451
+ }
452
+
453
+ export interface RepairIo {
454
+ out(line: string): void;
455
+ err(line: string): void;
456
+ }
457
+
458
+ export const SAMPLE_ROWS = 20;
459
+ export const HISTOGRAM_ROWS = 10;
460
+
461
+ export interface RepairOptions {
462
+ readonly apply?: boolean;
463
+ readonly minConfidence?: Confidence;
464
+ readonly importDay?: string;
465
+ readonly sample?: number;
466
+ }
467
+
468
+ export interface RepairReport {
469
+ readonly plan: RepairPlan;
470
+ readonly wouldWrite: number;
471
+ readonly written: number;
472
+ readonly failures: readonly string[];
473
+ /** Proposed dates by count, commonest first — the bulk-stamp detector. */
474
+ readonly histogram: readonly { date: string; n: number; share: number }[];
475
+ /** Dates carrying more than `BULK_STAMP_SHARE` of the proposals. */
476
+ readonly bulkStamps: readonly string[];
477
+ /** Set when the command refused rather than reported. */
478
+ readonly refused: "import-day-disagreement" | null;
479
+ }
480
+
481
+ /**
482
+ * The command's body. Returns the report so a test can assert on numbers rather
483
+ * than on printed lines; `commands.ts` turns it into an exit code.
484
+ */
485
+ export function repairDates(dir: string, io: RepairIo, opts: RepairOptions = {}): RepairReport | null {
486
+ if (!storeExists(dir)) {
487
+ io.err(`no store at ${dir}`);
488
+ return null;
489
+ }
490
+ const floor: Confidence = opts.minConfidence ?? "high";
491
+ const plan = planRepair(dir, opts.importDay);
492
+ const sampleSize = opts.sample ?? SAMPLE_ROWS;
493
+ const empty = { plan, wouldWrite: 0, written: 0, failures: [], histogram: [], bulkStamps: [], refused: null } as const;
494
+
495
+ if (plan.counts.migrated === 0) {
496
+ io.out("No migrated memories in this store. Nothing to repair.");
497
+ return empty;
498
+ }
499
+
500
+ // THE REFUSAL, BEFORE ANY NUMBER IS PRINTED. A recorded import day the store no
501
+ // longer agrees with means either this store was repaired already or it is not
502
+ // the store the record belongs to. Both want a human, and neither wants a tool
503
+ // that picks a winner (review §2).
504
+ if (plan.disagreement !== null) {
505
+ io.err(
506
+ `repair-dates: this store records an import day of ${plan.disagreement.recorded}, but the commonest date among its live migrated rows is ${plan.disagreement.measured}.`,
507
+ );
508
+ io.err("That usually means the repair has already run here. Nothing has been read further and nothing has changed.");
509
+ io.err(`To go ahead anyway, name the day out loud: --import-day ${plan.disagreement.recorded}`);
510
+ return { ...empty, refused: "import-day-disagreement" };
511
+ }
512
+
513
+ if (plan.importDay === "") {
514
+ io.out("No migrated memories carry a date to repair. Nothing to do.");
515
+ return empty;
516
+ }
517
+
518
+ const proposable = plan.targets.filter(
519
+ (t) => t.outcome.ok && meetsConfidence(t.outcome.proposal.confidence, floor),
520
+ );
521
+
522
+ const source =
523
+ plan.importDayFrom === "flag"
524
+ ? "given with --import-day"
525
+ : plan.importDayFrom === "recorded"
526
+ ? `recorded by an earlier run (store meta ${IMPORT_DAY_META})`
527
+ : plan.importDayFrom === "migration"
528
+ ? `recorded by the migration (store meta ${MIGRATED_ON_META})`
529
+ : "measured: the date most live migrated rows share";
530
+ io.out(`Import day: ${plan.importDay} (${source})`);
531
+ io.out(`Live migrated memories: ${plan.counts.migrated}`);
532
+ io.out(` … of those, carrying the import day: ${plan.targets.length}`);
533
+ io.out("");
534
+ io.out(`Proposals by confidence (over the ${plan.targets.length} rows above):`);
535
+ io.out(` high ${plan.counts.high} — the v1 document's own date, or an id that is a timestamp`);
536
+ io.out(` medium ${plan.counts.medium} — the session it came from, or a v1 element's statedOn / openedOn`);
537
+ io.out(` low ${plan.counts.low} — the path v1 filed it under (a month resolves to its 1st)`);
538
+ io.out(` none ${plan.counts.noEvidence} — nothing in the row says a date; left exactly as it is`);
539
+ io.out(` rejected ${plan.counts.outOfWindow} — a date parsed but fell outside ${PLAUSIBLE_FLOOR}..${plan.importDay}`);
540
+ io.out(` same ${plan.counts.alreadyCorrect} — the evidence agrees with the date already there; nothing to write`);
541
+ io.out(` repaired ${plan.counts.alreadyRepaired} — an earlier run already re-dated this row`);
542
+ if (plan.counts.supersededTier > 0) {
543
+ io.out(
544
+ ` (${plan.counts.supersededTier} of the proposals above are a WEAKER tier standing in for a stronger one the window refused.)`,
545
+ );
546
+ }
547
+
548
+ // THE HISTOGRAM — the one thing the tier counts cannot show. A v1 importer that
549
+ // stamped one `created` date onto thousands of documents reads as `high` here,
550
+ // and applying it would re-do the very failure this tool exists to undo. Two
551
+ // lines of output stand between the owner and that (review §3).
552
+ const byDate = new Map<string, number>();
553
+ for (const t of proposable) {
554
+ if (!t.outcome.ok) continue;
555
+ byDate.set(t.outcome.proposal.date, (byDate.get(t.outcome.proposal.date) ?? 0) + 1);
556
+ }
557
+ const histogram = [...byDate]
558
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
559
+ .map(([date, n]) => ({ date, n, share: proposable.length === 0 ? 0 : n / proposable.length }));
560
+ const isBulk = (h: { n: number; share: number }): boolean =>
561
+ h.share > BULK_STAMP_SHARE && h.n >= BULK_STAMP_MIN_ROWS;
562
+ const bulkStamps = histogram.filter(isBulk).map((h) => h.date);
563
+
564
+ io.out("");
565
+ io.out(`At or above confidence ${floor}: ${proposable.length} rows would be re-dated.`);
566
+ if (histogram.length > 0) {
567
+ io.out("");
568
+ io.out(`Proposed dates by count (${Math.min(HISTOGRAM_ROWS, histogram.length)} of ${histogram.length} distinct):`);
569
+ for (const h of histogram.slice(0, HISTOGRAM_ROWS)) {
570
+ const pct = (h.share * 100).toFixed(1);
571
+ const flag = isBulk(h) ? " <-- more than 5% on ONE day: check this is not a bulk stamp" : "";
572
+ io.out(` ${h.date} ${String(h.n).padStart(6)} ${pct.padStart(5)}%${flag}`);
573
+ }
574
+ if (bulkStamps.length > 0) {
575
+ io.out("");
576
+ io.out(
577
+ `WARNING: ${bulkStamps.length} date(s) each carry more than ${(BULK_STAMP_SHARE * 100).toFixed(0)}% of the proposals: ${bulkStamps.join(", ")}.`,
578
+ );
579
+ io.out("A v1 importer that stamped one date onto everything reads exactly like this. Look before you apply.");
580
+ }
581
+ }
582
+
583
+ const sample = proposable.slice(0, sampleSize);
584
+ if (sample.length > 0) {
585
+ io.out("");
586
+ io.out(`Sample (${sample.length} of ${proposable.length}) — ids and dates only:`);
587
+ io.out(" id kind now -> proposed confidence read from");
588
+ for (const t of sample) {
589
+ if (!t.outcome.ok) continue;
590
+ const p = t.outcome.proposal;
591
+ io.out(
592
+ ` ${t.id.padEnd(18)} ${t.kind.padEnd(9)} ${t.learnedOn} -> ${p.date} ${p.confidence.padEnd(10)} ${p.from} (${p.how})`,
593
+ );
594
+ }
595
+ }
596
+
597
+ if (opts.apply !== true) {
598
+ io.out("");
599
+ io.out("Dry run. Nothing has changed. Re-run with --apply to write the dates.");
600
+ return { plan, wouldWrite: proposable.length, written: 0, failures: [], histogram, bulkStamps, refused: null };
601
+ }
602
+
603
+ if (proposable.length === 0) {
604
+ io.out("");
605
+ io.out("Nothing to do.");
606
+ return { plan, wouldWrite: 0, written: 0, failures: [], histogram, bulkStamps, refused: null };
607
+ }
608
+
609
+ const store = Store.open({ dir });
610
+ const failures: string[] = [];
611
+ let written = 0;
612
+ try {
613
+ // PIN THE DAY BEFORE THE FIRST WRITE. From here on the mode of `learned_on`
614
+ // is no longer the import day, and a later run that re-measured would narrow
615
+ // its own window and pull correctly-dated rows in (review §2b).
616
+ if (store.getMeta(IMPORT_DAY_META) === undefined) store.setMeta(IMPORT_DAY_META, plan.importDay);
617
+ for (const t of proposable) {
618
+ if (!t.outcome.ok) continue;
619
+ const p = t.outcome.proposal;
620
+ // The third guard, at the last possible moment: never write X -> X.
621
+ if (p.date === t.learnedOn) continue;
622
+ try {
623
+ // `revise` archives the prior document first, so the wrong date stays
624
+ // readable in `versions/` — a correction, with its history kept. The
625
+ // marker rides the same write: `self/`'s wake reads it to stop rendering
626
+ // a repaired date as an upper bound.
627
+ store.revise(t.id, {
628
+ learnedOn: p.date,
629
+ meta: {
630
+ [DATE_REPAIRED_META]: {
631
+ confidence: p.confidence,
632
+ how: p.how,
633
+ from: p.from,
634
+ previous: t.learnedOn,
635
+ },
636
+ },
637
+ reason: "date.repaired",
638
+ });
639
+ store.appendEvent({
640
+ name: "date.repaired",
641
+ day: store.livedDay(),
642
+ ref: t.id,
643
+ payload: { from: t.learnedOn, to: p.date, confidence: p.confidence, how: p.how },
644
+ });
645
+ written += 1;
646
+ } catch (err) {
647
+ failures.push(`${t.id}: ${String((err as Error).message ?? err)}`);
648
+ }
649
+ }
650
+ } finally {
651
+ store.close();
652
+ }
653
+
654
+ io.out("");
655
+ io.out(`Re-dated ${written} memories.`);
656
+ io.out(`Import day ${plan.importDay} recorded in store meta (${IMPORT_DAY_META}); a re-run will not re-measure it.`);
657
+ for (const f of failures) io.err(` FAILED ${f}`);
658
+ return { plan, wouldWrite: proposable.length, written, failures, histogram, bulkStamps, refused: null };
659
+ }