counterparts 0.3.11 → 0.3.13

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 (150) hide show
  1. package/CHANGELOG.md +326 -0
  2. package/docs/QUICKSTART.md +5 -0
  3. package/docs/README.md +2 -2
  4. package/docs/module-map.md +3 -3
  5. package/package.json +1 -1
  6. package/src/adapters/claude-code/CONTRACT.md +36 -10
  7. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  8. package/src/adapters/claude-code/NOTES.md +182 -0
  9. package/src/adapters/claude-code/bin/hook.ts +46 -12
  10. package/src/adapters/claude-code/bin/runner.ts +7 -1
  11. package/src/adapters/claude-code/doctor.ts +632 -18
  12. package/src/adapters/claude-code/hooks.ts +61 -16
  13. package/src/adapters/claude-code/index.ts +11 -0
  14. package/src/adapters/claude-code/night-run.ts +150 -14
  15. package/src/adapters/claude-code/transcript.ts +268 -1
  16. package/src/adapters/cli/CONTRACT.md +5 -0
  17. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  18. package/src/adapters/cli/NOTES.md +111 -0
  19. package/src/adapters/cli/commands.ts +134 -92
  20. package/src/adapters/cli/dream-core.ts +57 -42
  21. package/src/adapters/cli/export.ts +320 -21
  22. package/src/adapters/cli/help.ts +2 -1
  23. package/src/adapters/cli/index.ts +1 -0
  24. package/src/adapters/cli/install.ts +39 -7
  25. package/src/adapters/cli/mechanisms.ts +7 -1
  26. package/src/adapters/cli/uninstall.ts +13 -5
  27. package/src/adapters/cli/wire.ts +189 -63
  28. package/src/adapters/config.ts +2 -0
  29. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  30. package/src/adapters/dashboard/NOTES.md +79 -0
  31. package/src/adapters/dashboard/registries.ts +34 -2
  32. package/src/adapters/dashboard/web/README.md +19 -14
  33. package/src/adapters/dashboard/web/actions.ts +23 -1
  34. package/src/adapters/dashboard/web/flow.ts +14 -0
  35. package/src/adapters/dashboard/web/lanes.ts +10 -0
  36. package/src/adapters/dashboard/web/narrate.ts +88 -2
  37. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  38. package/src/adapters/dashboard/web/pages/health/sections/checks.js +2 -0
  39. package/src/adapters/dashboard/web/pages/health/sections/wake.js +3 -1
  40. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  41. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  42. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  43. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  44. package/src/adapters/dashboard/web/server.ts +0 -5
  45. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  46. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  47. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  48. package/src/adapters/dashboard/web/views/health.ts +21 -3
  49. package/src/adapters/dashboard/web/views/search.ts +4 -45
  50. package/src/adapters/dashboard/web/views.ts +2 -2
  51. package/src/adapters/fired.ts +430 -28
  52. package/src/adapters/host-wiring.ts +300 -0
  53. package/src/adapters/hosts.ts +11 -0
  54. package/src/adapters/lifecycle.ts +42 -2
  55. package/src/adapters/log/index.ts +9 -0
  56. package/src/adapters/mcp/CONTRACT.md +151 -11
  57. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  58. package/src/adapters/mcp/NOTES.md +313 -1
  59. package/src/adapters/mcp/bin/serve.ts +74 -1
  60. package/src/adapters/mcp/deliberate.ts +169 -651
  61. package/src/adapters/mcp/facts.ts +1094 -0
  62. package/src/adapters/mcp/index.ts +25 -7
  63. package/src/adapters/mcp/meaning.ts +1610 -0
  64. package/src/adapters/mcp/server.ts +835 -150
  65. package/src/adapters/mcp/stdio.ts +3 -1
  66. package/src/adapters/mcp/stood-down.ts +51 -0
  67. package/src/adapters/mcp/tools.ts +167 -41
  68. package/src/adapters/plugin-run.sh +133 -0
  69. package/src/adapters/plugin.ts +329 -0
  70. package/src/adapters/sessions.ts +18 -4
  71. package/src/core/associate/CONTRACT.md +2 -1
  72. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  73. package/src/core/associate/NOTES.md +45 -0
  74. package/src/core/briefing.ts +12 -3
  75. package/src/core/contradictions.ts +184 -0
  76. package/src/core/counterpart.ts +797 -51
  77. package/src/core/dream/CONTRACT.md +36 -4
  78. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  79. package/src/core/dream/NOTES.md +107 -0
  80. package/src/core/dream/feeling-weeks.ts +198 -0
  81. package/src/core/dream/index.ts +109 -18
  82. package/src/core/dream/reflect.ts +346 -87
  83. package/src/core/dream/tunables.ts +24 -4
  84. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  85. package/src/core/encode/NOTES.md +7 -0
  86. package/src/core/encode/words.ts +45 -0
  87. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  88. package/src/core/fit/NOTES.md +39 -1
  89. package/src/core/fit/index.ts +40 -0
  90. package/src/core/handoff/CONTRACT.md +37 -2
  91. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  92. package/src/core/handoff/NOTES.md +72 -0
  93. package/src/core/handoff/index.ts +214 -12
  94. package/src/core/handoff/last-here.ts +6 -4
  95. package/src/core/mint.ts +12 -2
  96. package/src/core/physics/CONTRACT.md +14 -2
  97. package/src/core/physics/NOTES.md +33 -1
  98. package/src/core/physics/index.ts +28 -5
  99. package/src/core/prospective/CONTRACT.md +45 -6
  100. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  101. package/src/core/prospective/NOTES.md +138 -0
  102. package/src/core/prospective/derive.ts +33 -5
  103. package/src/core/prospective/index.ts +90 -5
  104. package/src/core/prospective/windows.ts +72 -1
  105. package/src/core/recall/CONTRACT.md +31 -12
  106. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  107. package/src/core/recall/NOTES.md +70 -1
  108. package/src/core/recall/feeling-ask.ts +10 -1
  109. package/src/core/recall/index.ts +3 -1
  110. package/src/core/recall/probe.ts +58 -0
  111. package/src/core/recall/session.ts +46 -2
  112. package/src/core/recall/time-ask.ts +487 -0
  113. package/src/core/remember/CONTRACT.md +4 -1
  114. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  115. package/src/core/remember/NOTES.md +8 -0
  116. package/src/core/remember/proposals.ts +47 -5
  117. package/src/core/revision.ts +18 -1
  118. package/src/core/schemas/CONTRACT.md +21 -1
  119. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  120. package/src/core/schemas/NOTES.md +144 -0
  121. package/src/core/schemas/aliases.ts +55 -5
  122. package/src/core/schemas/index.ts +93 -1
  123. package/src/core/schemas/types.ts +2 -0
  124. package/src/core/self/CONTRACT.md +32 -5
  125. package/src/core/self/INTERFACE-GAPS.md +7 -2
  126. package/src/core/self/NOTES.md +102 -1
  127. package/src/core/self/behind.ts +43 -3
  128. package/src/core/self/briefing.ts +12 -2
  129. package/src/core/self/chapter-address.ts +254 -0
  130. package/src/core/self/episodes.ts +27 -0
  131. package/src/core/self/index.ts +83 -8
  132. package/src/core/self/page.ts +88 -0
  133. package/src/core/self/tunables.ts +5 -0
  134. package/src/core/self/work.ts +35 -2
  135. package/src/core/self/writer.ts +30 -0
  136. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  137. package/src/core/sleep/NOTES.md +20 -1
  138. package/src/core/sleep/consolidate.ts +59 -7
  139. package/src/core/sleep/index.ts +3 -0
  140. package/src/core/sleep/prune.ts +6 -2
  141. package/src/core/sleep/types.ts +7 -0
  142. package/src/core/store/CONTRACT.md +16 -0
  143. package/src/core/store/NOTES.md +66 -0
  144. package/src/core/store/feelings.ts +14 -1
  145. package/src/core/store/index.ts +483 -16
  146. package/src/core/store/operational.ts +95 -2
  147. package/src/core/store/owner-op-seam.ts +23 -0
  148. package/src/core/time.ts +152 -0
  149. package/tools/install-loop/run.sh +48 -12
  150. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -22,6 +22,22 @@ import { preMigrationDir, snapshotBeforeMigration } from "./pre-migration.js";
22
22
  import type { ProseType } from "./prose.js";
23
23
 
24
24
  /**
25
+ * Bumped to 12 (2026-10-03, the write side of deliberate recall): ADDITIVE,
26
+ * through the same copy-first seam, and nothing re-filed. `memories` (and
27
+ * `versions`, which mirror the words' own fields) gain three columns the
28
+ * WRITER fills at write time: `occurred_on` (when the thing the memory is
29
+ * about happened — the same day, month, range or year shapes `event_date`
30
+ * takes, but the past or present, where `event_date` is a future date to be
31
+ * reminded on and `happened_on` is the lived day of a write-up), `said_by`
32
+ * (`owner`, `self` or `inferred`: who said it, not which channel wrote the
33
+ * row) and `status` (`done`, `planned`, `proposed`, `asked`). NULL on every
34
+ * row written before: they cannot be filled without a model. One table is
35
+ * new, `memory_subjects`: a memory linked to the entity cards it names, filled
36
+ * at write time from the alias index and once, after the upgrade, for the rows
37
+ * already there (`Counterpart`'s backfill — this transaction has no alias
38
+ * index). The upgrade records its moment (`V12_UPGRADE_KEY`), which is what
39
+ * doctor's "since v12" reads. `store/NOTES.md` 2026-10-03.
40
+ *
25
41
  * Bumped to 11 (2026-09-30, the feelings wheel v2): ADDITIVE, through the same
26
42
  * copy-first seam. The wheel's six cores become seven (happy, warm, calm,
27
43
  * curious, sad, uneasy, angry — `core/feelings-wheel.ts`), and `feelings`
@@ -123,7 +139,7 @@ import type { ProseType } from "./prose.js";
123
139
  * migrated open MUST converge on the identical schema; a test asserts
124
140
  * table_info equality.
125
141
  */
126
- export const SCHEMA_VERSION = 11;
142
+ export const SCHEMA_VERSION = 12;
127
143
  /**
128
144
  * The oldest schema an OBSERVER may open without a migration having run.
129
145
  *
@@ -158,6 +174,16 @@ export const SCHEMA_VERSION = 11;
158
174
  * Raised to 11 with v11 (2026-09-30): a v10 file's feelings are filed under
159
175
  * cores this build's readers do not draw (fear, surprise, disgust), and its
160
176
  * rows have no `valence`.
177
+ *
178
+ * NOT raised with v12 (2026-10-03). The question each raise answered yes to
179
+ * is whether an instrument reading the older file gets a WRONG answer, and
180
+ * for v12 it does not: rows are read `m.*`, so a v11 row simply has no
181
+ * `occurred_on` / `said_by` / `status` (the row type carries them optional),
182
+ * nothing re-filed what a v11 row says, and the one instrument that reads the
183
+ * new fields — doctor's `Write fields` line — asks for the column and the
184
+ * table first and says it is waiting for the upgrade. Keeping the floor keeps
185
+ * doctor and the dashboard reading a v11 store between an install and the
186
+ * first writer that opens it.
161
187
  */
162
188
  export const OBSERVER_READ_FLOOR = 11;
163
189
  /** Retention for superseded-version rows, in LIVED days. TUNABLE (module-map ruling 2).
@@ -257,7 +283,10 @@ export const DDL: readonly string[] = [
257
283
  last_dream_day INTEGER,
258
284
  about TEXT,
259
285
  about_by TEXT,
260
- fade REAL NOT NULL DEFAULT 1
286
+ fade REAL NOT NULL DEFAULT 1,
287
+ occurred_on TEXT,
288
+ said_by TEXT,
289
+ status TEXT
261
290
  )`,
262
291
  `CREATE INDEX IF NOT EXISTS memories_band ON memories (band, archived)`,
263
292
  `CREATE INDEX IF NOT EXISTS memories_kind ON memories (kind, archived)`,
@@ -286,6 +315,9 @@ export const DDL: readonly string[] = [
286
315
  created_at INTEGER,
287
316
  model TEXT,
288
317
  event_date TEXT,
318
+ occurred_on TEXT,
319
+ said_by TEXT,
320
+ status TEXT,
289
321
  PRIMARY KEY (memory_id, seq)
290
322
  )`,
291
323
  `CREATE TABLE IF NOT EXISTS edges (
@@ -538,6 +570,24 @@ export const DDL: readonly string[] = [
538
570
  )`,
539
571
  `CREATE INDEX IF NOT EXISTS contradiction_settles_pair ON contradiction_settles (pair_id)`,
540
572
  `CREATE INDEX IF NOT EXISTS contradiction_settles_at ON contradiction_settles (at)`,
573
+ // v12 (2026-10-03): WHAT A MEMORY NAMES — one row per memory and entity
574
+ // card (schema `role: entity`) its title or body names as a whole word,
575
+ // by the alias index's one rule (`schemas/aliases.ts`). `via` says how the
576
+ // link was found: `write` (the memory's own write, or a revise of its
577
+ // words), `birth` (a card born after the memory, which then looked for the
578
+ // memories already naming it) or `backfill` (the one pass after the
579
+ // upgrade). Ids only — a link is an address, never words. Not foreign-keyed,
580
+ // like `contradictions`: the owner's removal deletes a removed memory's or
581
+ // card's rows itself. Read both ways: a memory's subjects (the primary key)
582
+ // and a subject's memories (`memory_subjects_subject`).
583
+ `CREATE TABLE IF NOT EXISTS memory_subjects (
584
+ memory_id TEXT NOT NULL,
585
+ subject_id TEXT NOT NULL,
586
+ via TEXT NOT NULL,
587
+ created_at INTEGER NOT NULL,
588
+ PRIMARY KEY (memory_id, subject_id)
589
+ )`,
590
+ `CREATE INDEX IF NOT EXISTS memory_subjects_subject ON memory_subjects (subject_id, memory_id)`,
541
591
  `CREATE INDEX IF NOT EXISTS core_events_memory ON core_events (memory_id)`,
542
592
  `CREATE INDEX IF NOT EXISTS core_events_at ON core_events (at)`,
543
593
  `CREATE INDEX IF NOT EXISTS feelings_whose_core ON feelings (whose, core)`,
@@ -704,6 +754,18 @@ export interface MemoryRow extends Row {
704
754
  about_by: string | null;
705
755
  /** v10: the strength multiplier a `changed` settle sets (physics §5.12); 1 otherwise. */
706
756
  fade: number;
757
+ /**
758
+ * v12: when the thing the memory is about happened, as the writer said it —
759
+ * a day, a month, a year or a range (`time.ts#parseCalendarDate`). Not
760
+ * `happened_on` (the lived day of a write-up) and not `event_date` (a
761
+ * future date to be reminded on). A v11 file read before its upgrade has
762
+ * no column, and reads undefined (`OBSERVER_READ_FLOOR`): read it `?? null`.
763
+ */
764
+ occurred_on: string | null;
765
+ /** v12: who said it — `owner`, `self` or `inferred` (`SAID_BY`). */
766
+ said_by: string | null;
767
+ /** v12: what kind of thing it is — `done`, `planned`, `proposed`, `asked` (`STATUSES`). */
768
+ status: string | null;
707
769
  }
708
770
 
709
771
  export interface ReflectionRow extends Row {
@@ -890,6 +952,10 @@ export interface VersionRow extends Row {
890
952
  created_at: number | null;
891
953
  model: string | null;
892
954
  event_date: string | null;
955
+ /** v12: the writer's three fields as they stood on these words (undefined on a v11 file). */
956
+ occurred_on: string | null;
957
+ said_by: string | null;
958
+ status: string | null;
893
959
  }
894
960
 
895
961
  export interface EdgeRow extends Row {
@@ -1302,6 +1368,21 @@ export function openOperational(path: string, opts: OpenOperationalOptions = {})
1302
1368
  }),
1303
1369
  );
1304
1370
  }
1371
+ // v12 (2026-10-03): THE MOMENT OF THE UPGRADE, for doctor's "since
1372
+ // v12" — the writer's three fields are NULL on every row it found, and
1373
+ // the share that counts is of the rows written after it. Nothing else
1374
+ // moves; the subject links are filled after the open (no alias index here).
1375
+ if (now !== null && Number.parseInt(now, 10) < 12) {
1376
+ const lived = db.get<{ value: string }>("SELECT value FROM meta WHERE key = 'livedDay'")?.value ?? "0";
1377
+ const memories = db.get<{ n: number }>(
1378
+ "SELECT COUNT(*) AS n FROM memories WHERE type = 'memory' AND archived = 0",
1379
+ )?.n ?? 0;
1380
+ db.run(
1381
+ "INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
1382
+ V12_UPGRADE_KEY,
1383
+ JSON.stringify({ from: now, day: Number.parseInt(lived, 10) || 0, at: Date.now(), memories }),
1384
+ );
1385
+ }
1305
1386
  const put = db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");
1306
1387
  put.run("livedDay", "0");
1307
1388
  put.run("lastActiveDate", "");
@@ -1454,6 +1535,15 @@ export const ADDED_COLUMNS: readonly { table: string; column: string; ddl: strin
1454
1535
  { table: "feelings", column: "valence", ddl: "ALTER TABLE feelings ADD COLUMN valence REAL" },
1455
1536
  { table: "feelings", column: "core_v10", ddl: "ALTER TABLE feelings ADD COLUMN core_v10 TEXT" },
1456
1537
  { table: "feelings", column: "emotion_v10", ddl: "ALTER TABLE feelings ADD COLUMN emotion_v10 TEXT" },
1538
+ // v12 (2026-10-03, the write side of deliberate recall): the writer's three
1539
+ // fields, on a memory and on each archived version of its words. NULL on
1540
+ // every row the upgrade finds: nothing can fill them without a model.
1541
+ { table: "memories", column: "occurred_on", ddl: "ALTER TABLE memories ADD COLUMN occurred_on TEXT" },
1542
+ { table: "memories", column: "said_by", ddl: "ALTER TABLE memories ADD COLUMN said_by TEXT" },
1543
+ { table: "memories", column: "status", ddl: "ALTER TABLE memories ADD COLUMN status TEXT" },
1544
+ { table: "versions", column: "occurred_on", ddl: "ALTER TABLE versions ADD COLUMN occurred_on TEXT" },
1545
+ { table: "versions", column: "said_by", ddl: "ALTER TABLE versions ADD COLUMN said_by TEXT" },
1546
+ { table: "versions", column: "status", ddl: "ALTER TABLE versions ADD COLUMN status TEXT" },
1457
1547
  ];
1458
1548
 
1459
1549
  /**
@@ -1520,6 +1610,9 @@ export const V10_UPGRADE_KEY = "contradictions.v10.upgrade";
1520
1610
  /** Meta key: what the v11 upgrade re-filed (`feelings.v11.upgrade`), for doctor. */
1521
1611
  export const V11_UPGRADE_KEY = "feelings.v11.upgrade";
1522
1612
 
1613
+ /** Meta key: when the v12 upgrade ran (`recall.v12.upgrade`) — doctor's "since v12". */
1614
+ export const V12_UPGRADE_KEY = "recall.v12.upgrade";
1615
+
1523
1616
  /**
1524
1617
  * THE v11 RE-FILING: every feeling the first wheel stored, moved onto the
1525
1618
  * seven cores by `feelings-wheel.ts#remapV10Feeling` (pure; the rule is
@@ -296,6 +296,17 @@ export function chaseRemoved(store: Store, id: string): ChaseReport {
296
296
  WHERE memory_id = ?`,
297
297
  id,
298
298
  );
299
+ // v12: the writer's three fields on those versions go too — when it
300
+ // happened, who said it and what kind of thing it was are facts ABOUT the
301
+ // removed memory. And its subject links, both ways: the memory's, and —
302
+ // when the removed row is a card — every memory's link to it. A file
303
+ // without the columns or the table has nothing here.
304
+ try {
305
+ db.run("UPDATE versions SET occurred_on = NULL, said_by = NULL, status = NULL WHERE memory_id = ?", id);
306
+ db.run("DELETE FROM memory_subjects WHERE memory_id = ? OR subject_id = ?", id, id);
307
+ } catch {
308
+ /* a store from before v12 */
309
+ }
299
310
 
300
311
  if (row !== undefined) {
301
312
  // The skeleton: an address, its family, and nothing else. Physics is
@@ -322,6 +333,11 @@ export function chaseRemoved(store: Store, id: string): ChaseReport {
322
333
  REMOVED_REASON,
323
334
  id,
324
335
  );
336
+ try {
337
+ db.run("UPDATE memories SET occurred_on = NULL, said_by = NULL, status = NULL WHERE id = ?", id);
338
+ } catch {
339
+ /* a store from before v12 */
340
+ }
325
341
  if (!noop) {
326
342
  db.run(
327
343
  `INSERT INTO removal_tombstone
@@ -524,6 +540,13 @@ function redactEntryMemory(db: Db, entryId: string, removedId: string): void {
524
540
  hashText(REDACTED_REFLECTION),
525
541
  entryId,
526
542
  );
543
+ // v12: its subject links said which cards the redacted words named; the
544
+ // words are gone, so what they named goes with them.
545
+ try {
546
+ db.run("DELETE FROM memory_subjects WHERE memory_id = ?", entryId);
547
+ } catch {
548
+ /* a store from before v12 */
549
+ }
527
550
  }
528
551
 
529
552
  // ── the repair ──────────────────────────────────────────────────────────────
package/src/core/time.ts CHANGED
@@ -222,6 +222,33 @@ export function localStampAfter(at: number, after: number, zone?: string): strin
222
222
  return q !== null && q.month === p.month && q.day === p.day ? clock : `${p.month}-${p.day} ${clock}`;
223
223
  }
224
224
 
225
+ /**
226
+ * The first moment of the calendar day `ymd` in `zone` — local midnight, as an
227
+ * instant (2026-10-09). A window over moments that is meant to be a person's
228
+ * days starts here, never at `${ymd}T00:00:00Z`, which is the UTC day: in
229
+ * Denver that opens the window six hours early, in Kiritimati fourteen hours
230
+ * late. Found by a search over `localDate` rather than by offset arithmetic, so
231
+ * a day a clock change starts at 01:00 still starts where the zone says it
232
+ * does. Throws on a malformed day — a caller's bug, as `addDays` does.
233
+ */
234
+ export function startOfLocalDay(ymd: string, zone?: string): number {
235
+ const z = zone === undefined || !isZoneCached(zone) ? machineZone() : zone;
236
+ const utcMidnight = Date.parse(`${ymd}T00:00:00Z`);
237
+ if (!isDay(ymd) || !Number.isFinite(utcMidnight)) throw new RangeError(`startOfLocalDay: not a day: ${ymd}`);
238
+ const minute = 60_000;
239
+ // Every offset in use lies inside UTC−12..UTC+14, so local midnight lies
240
+ // between these two bounds, with an hour to spare on each side: the first is
241
+ // always the day before in `z`, the second always `ymd` or later.
242
+ let before = Math.floor((utcMidnight - 15 * 3_600_000) / minute);
243
+ let onOrAfter = Math.floor((utcMidnight + 13 * 3_600_000) / minute);
244
+ while (onOrAfter - before > 1) {
245
+ const mid = Math.floor((before + onOrAfter) / 2);
246
+ if (localDate(mid * minute, z) < ymd) before = mid;
247
+ else onOrAfter = mid;
248
+ }
249
+ return onOrAfter * minute;
250
+ }
251
+
225
252
  /** Today's `YYYY-MM-DD` in `zone`. A store passes its own clock; the default is
226
253
  * the ambient one, for an adapter with no store open. */
227
254
  export function todayIn(zone?: string, at: number = Date.now()): string {
@@ -429,3 +456,128 @@ export function readableDate(ymd: string): string {
429
456
 
430
457
  /** Legacy name (`self/calendar.ts`, 2026-09-23): the local date of a moment. */
431
458
  export const calendarDate = localDate;
459
+
460
+ // ── a date that repeats (2026-10-09, the owner's design, held lightly) ───────
461
+
462
+ /**
463
+ * How often a stated DAY comes round again, anchored on that day: a birthday
464
+ * stored as `1990-05-14` with `yearly` is every May 14 from then on. Every
465
+ * other week, "the first Monday" and the like are not kept (loose first), and
466
+ * nothing finer than a day: dates and reminders here are per day.
467
+ */
468
+ export const RECURRENCES = ["daily", "weekly", "monthly", "yearly"] as const;
469
+ export type Recurrence = (typeof RECURRENCES)[number];
470
+
471
+ /** Is `v` one of the four recurrence words? */
472
+ export function isRecurrence(v: unknown): v is Recurrence {
473
+ return typeof v === "string" && (RECURRENCES as readonly string[]).includes(v);
474
+ }
475
+
476
+ const MONTH_NAMES = [
477
+ "January", "February", "March", "April", "May", "June",
478
+ "July", "August", "September", "October", "November", "December",
479
+ ] as const;
480
+ const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
481
+
482
+ /** A month `k` months after `(y, m)`, with the day held to that month's length. */
483
+ function monthsAfter(y: number, m: number, d: number, k: number): number {
484
+ const total = y * 12 + (m - 1) + k;
485
+ const yy = Math.floor(total / 12);
486
+ const mm = (total % 12) + 1;
487
+ return dayNumber(yy, mm, Math.min(d, daysInMonth(yy, mm)));
488
+ }
489
+
490
+ /**
491
+ * The `k`-th time a stated day comes round (`k = 0` is the day itself), as a
492
+ * day count. ALWAYS counted from the anchor, never from the last occurrence,
493
+ * so a short month cannot drag the rest of the year with it:
494
+ *
495
+ * - **monthly on the 29th, 30th or 31st** falls on the LAST day of a month
496
+ * too short to have it (Jan 31 → Feb 28, or 29 in a leap year → Mar 31 →
497
+ * Apr 30 → May 31);
498
+ * - **yearly on Feb 29** falls on Feb 28 in a year with no Feb 29.
499
+ */
500
+ function occurrenceNumber(y: number, m: number, d: number, rule: Recurrence, k: number): number {
501
+ switch (rule) {
502
+ case "daily":
503
+ return dayNumber(y, m, d) + k;
504
+ case "weekly":
505
+ return dayNumber(y, m, d) + 7 * k;
506
+ case "monthly":
507
+ return monthsAfter(y, m, d, k);
508
+ case "yearly":
509
+ return monthsAfter(y, m, d, 12 * k);
510
+ }
511
+ }
512
+
513
+ /** The anchor read as numbers, or null when it is not one real DAY. */
514
+ function anchorParts(anchor: string): [number, number, number] | null {
515
+ if (dayOf(anchor) === null) return null;
516
+ const [y, m, d] = anchor.split("-").map(Number) as [number, number, number];
517
+ return [y, m, d];
518
+ }
519
+
520
+ /** The `k`-th occurrence of `anchor` (k ≥ 0), `YYYY-MM-DD`; null for anything but a real day. */
521
+ export function occurrenceOf(anchor: string, rule: Recurrence, k: number): string | null {
522
+ const p = anchorParts(anchor);
523
+ if (p === null || !Number.isInteger(k) || k < 0) return null;
524
+ return fromDayNumber(occurrenceNumber(p[0], p[1], p[2], rule, k));
525
+ }
526
+
527
+ /**
528
+ * The first occurrence of `anchor` on or after `ymd`, and its index. Never one
529
+ * before the anchor: a repeat starts on the day it was stated. Null when either
530
+ * is not a real day.
531
+ */
532
+ export function occurrenceOnOrAfter(anchor: string, rule: Recurrence, ymd: string): { k: number; date: string } | null {
533
+ const p = anchorParts(anchor);
534
+ const target = dayOf(ymd);
535
+ if (p === null || target === null) return null;
536
+ const [y, m, d] = p;
537
+ const start = dayNumber(y, m, d);
538
+ if (target <= start) return { k: 0, date: anchor };
539
+ // A lower bound on k, then forward: at most a step or two past the estimate.
540
+ let k =
541
+ rule === "daily"
542
+ ? target - start
543
+ : rule === "weekly"
544
+ ? Math.floor((target - start) / 7)
545
+ : rule === "monthly"
546
+ ? Math.max(0, (Number(ymd.slice(0, 4)) - y) * 12 + (Number(ymd.slice(5, 7)) - m) - 1)
547
+ : Math.max(0, Number(ymd.slice(0, 4)) - y - 1);
548
+ while (occurrenceNumber(y, m, d, rule, k) < target) k += 1;
549
+ return { k, date: fromDayNumber(occurrenceNumber(y, m, d, rule, k)) };
550
+ }
551
+
552
+ /** Does some occurrence of `anchor` fall on a day from `from` to `to`, inclusive? The first one that does, or null. */
553
+ export function occurrenceBetween(anchor: string, rule: Recurrence, from: string, to: string): string | null {
554
+ const next = occurrenceOnOrAfter(anchor, rule, from);
555
+ return next !== null && next.date <= to ? next.date : null;
556
+ }
557
+
558
+ function ordinal(n: number): string {
559
+ const tens = n % 100;
560
+ const suffix = tens >= 11 && tens <= 13 ? "th" : n % 10 === 1 ? "st" : n % 10 === 2 ? "nd" : n % 10 === 3 ? "rd" : "th";
561
+ return `${String(n)}${suffix}`;
562
+ }
563
+
564
+ /**
565
+ * The repeat as a person says it, from the ANCHOR (so a monthly 31st reads as
566
+ * the 31st even in a February): `every day`, `every Monday`, `every month on
567
+ * the 14th`, `every May 14`. Empty for an anchor that is not a real day.
568
+ */
569
+ export function readableRecurrence(anchor: string, rule: Recurrence): string {
570
+ const p = anchorParts(anchor);
571
+ if (p === null) return "";
572
+ const [, m, d] = p;
573
+ switch (rule) {
574
+ case "daily":
575
+ return "every day";
576
+ case "weekly":
577
+ return `every ${WEEKDAY_NAMES[(((dayNumber(p[0], m, d) + 4) % 7) + 7) % 7] ?? ""}`;
578
+ case "monthly":
579
+ return `every month on the ${ordinal(d)}`;
580
+ case "yearly":
581
+ return `every ${MONTH_NAMES[m - 1] ?? ""} ${String(d)}`;
582
+ }
583
+ }
@@ -472,23 +472,25 @@ recall: $RECALL_OUT"
472
472
  fi
473
473
  fi
474
474
 
475
- step "an answer names the TIER it came back at"
475
+ step "the full answer counts its matches and says how each one stands"
476
476
  # `answered` says the question reached something, never that it is right. The
477
- # tier is the only confidence signal there is, and `--full` glosses every tier
478
- # on screen — and says "treat these as leads" when nothing came back vividly
479
- # (and only then). The SHORT answer no longer says it (owner, 2026-09-24: it
480
- # read as doubt about an answer that was right). Since `note` embeds on write,
481
- # the demo's answer may come back vivid.
477
+ # vivid / quiet / dim tiers went with #323 (0.3.12): `--full` is now the facts
478
+ # answer the model reads — a count first (`1 match · showing 1`, the line under
479
+ # `Store:`), then each fact numbered with its id and the ways it matched, who
480
+ # said it and its status, when it was learned, and whether it is still CURRENT.
481
+ # The short answer is step 18's.
482
482
  eval 'export COUNTERPARTS_DATA_DIR="$HOME/.counterparts/store"'
483
483
  FULL_OUT=$(eval "$RECALL_CMD --full" 2>&1)
484
484
  unset COUNTERPARTS_DATA_DIR
485
- if grep -q '^ vivid = ' <<<"$FULL_OUT"; then VIVID=1; else VIVID=0; fi
486
- if grep -q "treat these as leads" <<<"$FULL_OUT"; then LEADS=1; else LEADS=0; fi
487
- if grep -qE '^ (vivid|quiet|dim) = ' <<<"$FULL_OUT" && [ "$VIVID" != "$LEADS" ] &&
488
- ! grep -q "treat these as leads" <<<"$RECALL_OUT"; then
485
+ if sed -n 2p <<<"$FULL_OUT" | grep -qE '^[0-9]+ match( · |$)' &&
486
+ grep -qE '^1\. .*port 5433.* · mem_[0-9a-f]+ · (words|meaning|subject|time|session)' <<<"$FULL_OUT" &&
487
+ grep -qE '^ (you said|I said|inferred|speaker unknown) · ' <<<"$FULL_OUT" &&
488
+ grep -qE '^ learned .* · CURRENT' <<<"$FULL_OUT" &&
489
+ ! grep -q "Rancilio Silvia" <<<"$FULL_OUT" &&
490
+ ! grep -qE '^ (vivid|quiet|dim) = ' <<<"$FULL_OUT"; then
489
491
  ok
490
492
  else
491
- no "no tier gloss under --full, its leads line disagrees with it, or the short answer still says it" "short: $RECALL_OUT
493
+ no "--full did not open with the count, or a fact lacks its id, ways, speaker or standing" "short: $RECALL_OUT
492
494
  full: $FULL_OUT"
493
495
  fi
494
496
 
@@ -703,7 +705,8 @@ step "note then recall round-trips through the MCP server"
703
705
  # The canary is deliberately plain ASCII with no quotes or backslashes, so it
704
706
  # needs no JSON escaping to be embedded here.
705
707
  NOTE_PARAMS=$(printf '{"name":"note","arguments":{"text":"%s"}}' "$CANARY")
706
- RECALL_PARAMS='{"name":"recall","arguments":{"question":"what espresso machine is in the kitchen?"}}'
708
+ # A question needs `mode` since #323 (0.3.12): without one it is refused.
709
+ RECALL_PARAMS='{"name":"recall","arguments":{"question":"what espresso machine is in the kitchen?","mode":"facts"}}'
707
710
  RPC=$(
708
711
  printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{}}}'
709
712
  printf '%s\n' '{"jsonrpc":"2.0","method":"notifications/initialized"}'
@@ -869,6 +872,39 @@ else
869
872
  $OUT"
870
873
  fi
871
874
 
875
+ step "what were we about to do? a plan written after the handoff is named beside it"
876
+ # 2026-10-09: one session leaves a handoff in the project, another changes the
877
+ # plan there in a note and leaves the handoff as it was. The next session's wake
878
+ # carries the note under the pointer ("Since this handoff: …"), so the newer
879
+ # plan is not quiet. Two sessions, because what the handoff's own session writes
880
+ # within five minutes of it is the same answer (`handoff/index.ts`,
881
+ # SINCE_SAME_ANSWER_MS), and this loop runs in seconds.
882
+ PLAN_SESSION="install-loop-plan-$$"
883
+ NEXT_SESSION="install-loop-next-$$"
884
+ INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{}}}'
885
+ INITED='{"jsonrpc":"2.0","method":"notifications/initialized"}'
886
+ HANDOFF_CALL=$(printf '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"session_end","arguments":{"session":"%s","memories":[],"handoff":"%s"}}}' \
887
+ "$SESSION" "The install loop left the release half cut: the tarball is packed and not published.")
888
+ PLAN_CALL=$(printf '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"note","arguments":{"session":"%s","title":"%s","text":"%s","status":"planned"}}}' \
889
+ "$PLAN_SESSION" "Publish only after the docs pass" "Changed plan: the tarball is published only after the docs pass lands.")
890
+ HANDED=$(printf '%s\n' "$INIT" "$INITED" "$HANDOFF_CALL" |
891
+ COUNTERPARTS_DATA_DIR="$STORE" COUNTERPARTS_SCOPE="$HOME/project" counterparts-mcp 2>"$WORK/mcp-handoff.err" | grep '"id":2' || true)
892
+ payload SessionStart "$PLAN_SESSION" | counterparts-hook >/dev/null 2>"$WORK/hook-plan.err"
893
+ PLANNED=$(printf '%s\n' "$INIT" "$INITED" "$PLAN_CALL" |
894
+ COUNTERPARTS_DATA_DIR="$STORE" COUNTERPARTS_SCOPE="$HOME/project" counterparts-mcp 2>"$WORK/mcp-plan.err" | grep '"id":2' || true)
895
+ OUT=$(payload SessionStart "$NEXT_SESSION" | counterparts-hook 2>"$WORK/hook-next.err")
896
+ if grep -q '"isError":true' <<<"$HANDED$PLANNED"; then
897
+ no "the handoff or the note was refused" "$HANDED
898
+ $PLANNED"
899
+ elif grep -q "Where I left off in this directory" <<<"$OUT" &&
900
+ grep -q "Since this handoff: Publish only after the docs pass (planned, mem_[0-9a-f]\{12\})" <<<"$OUT"; then
901
+ ok
902
+ else
903
+ no "the next wake did not name the plan under the handoff" "$(cat "$WORK/hook-next.err")
904
+ note: $PLANNED
905
+ $OUT"
906
+ fi
907
+
872
908
  step "the dashboard opens the same store"
873
909
  CMD='counterparts-dashboard status --dir "$HOME/.counterparts/store"'
874
910
  if true; then
@@ -1,53 +0,0 @@
1
- /* Ask's answers, with a journal chapter and the memory drawn from it folded
2
- into one (2026-09-27, round 3; a try, not a rule).
3
-
4
- `counterparts ask` can return a journal chapter (`journal: true`, the entry)
5
- and the memory minted from it (`isChapterMemory`) side by side, with the
6
- same words. The page shows the memory once, where the better of the two was
7
- ranked, with a small "from chapter …" link to the entry. Pure (no DOM), so
8
- `bun test` checks it; the links come from `/api/chapters`
9
- (`views/search.ts#chapterLinks`).
10
-
11
- Since 2026-09-30 (U13) recall itself returns the pair as ONE answer — the
12
- chapter (`core/recall/activate.ts`, the collapse) — so the fold below sees a
13
- pair only from an older build's answer. A memory whose chapter was not in
14
- the answer still gets its "from chapter …" link. */
15
-
16
- const TIER_ORDER = { vivid: 0, quiet: 1, dim: 2 };
17
-
18
- /**
19
- * `mems`: Ask's `memories`, best first. `links`: `{ [memoryId]: { episodeId,
20
- * label } }`. Returns the answers to show, best first, each with `from` (its
21
- * chapter link, or null) and `chapter` (true for a chapter memory). An entry
22
- * whose chapter memory is also in the answer is dropped, and the memory takes
23
- * the entry's place and tier when the entry ranked higher.
24
- */
25
- export function foldChapters(mems, links) {
26
- const list = Array.isArray(mems) ? mems : [];
27
- const L = links || {};
28
- const at = new Map();
29
- list.forEach((m, i) => { if (m && m.journal) at.set(m.id, i); });
30
- const folded = new Set();
31
- const items = list.map((m, i) => {
32
- const link = L[m.id] || null;
33
- let rank = i, tier = m.tier;
34
- if (link && at.has(link.episodeId)) {
35
- const j = at.get(link.episodeId);
36
- folded.add(link.episodeId);
37
- if (j < rank) rank = j;
38
- const other = list[j].tier;
39
- if ((TIER_ORDER[other] ?? 9) < (TIER_ORDER[tier] ?? 9)) tier = other;
40
- }
41
- return { m: { ...m, tier, from: link, chapter: link !== null }, rank, i };
42
- });
43
- return items
44
- .filter((x) => !(x.m.journal && folded.has(x.m.id)))
45
- .sort((a, b) => a.rank - b.rank || a.i - b.i)
46
- .map((x) => x.m);
47
- }
48
-
49
- /** The link's words: `from chapter “Halfmoon pilot — 2026-06-01”`. */
50
- export function fromWords(from) {
51
- if (!from) return "";
52
- return from.label ? "from chapter “" + from.label + "”" : "from its journal chapter";
53
- }