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
@@ -1479,7 +1479,8 @@ Labels only; nothing about what the wake selects changed.
1479
1479
  "Last here" and the handoff.
1480
1480
  - **Open**: no habituation on the work lines (a memory used every day stays first);
1481
1481
  unmarked facts written in a directory but really personal wait for the reflection to
1482
- mark them.
1482
+ mark them. (2026-10-02: the lines past `WORK_HERE_MAX` now rotate by lived day — see
1483
+ that day's note.)
1483
1484
  - **Review of #313.** A name scope (`claude-desktop:`) is not a directory
1484
1485
  (`work.ts#isDirectoryScope`: an absolute path), so Desktop chat's unmarked notes stay in
1485
1486
  Nearby. Unmarked `person` and `self` memories are personal wherever written (they always
@@ -1497,3 +1498,103 @@ Labels only; nothing about what the wake selects changed.
1497
1498
  live copy, found by `origin_ref`); `ingestEpisode` gives a new copy the mark of the copy it
1498
1499
  replaces, else the episode's own. Latest act wins: the writer's chapter-time mark, then a
1499
1500
  reflection's on the copy, are both on the copy's row by the time it regrows.
1501
+
1502
+ ## 2026-10-02 — a wake another build published is behind (`version`)
1503
+
1504
+ The first wakes after an install were the ones the old version composed, until a mark or the
1505
+ next lived day: on 10-01 a question 0.3.11 closes stayed in "Still open" all afternoon. Now each
1506
+ publish stamps `self.wake.build` with the package version of the process that rendered it
1507
+ (`CounterpartOptions.build`; the turn-end worker, the nightly process and the console pass
1508
+ `installedVersion()`), and `refreshWake` adds the `version` trigger when the stamp differs from
1509
+ the running build, or is absent beside a bundle (one published before the stamp existed). No
1510
+ mark is written for it: the comparison is the mark. An unknown build compares nothing. What
1511
+ remains: the first SessionStart after the install still reads the old bundle — SessionStart
1512
+ renders nothing (CONTRACT §5 G1) — and that session's first Stop re-renders it for every
1513
+ session after.
1514
+
1515
+ ## 2026-10-02 — the work lines rotate, and an overflow leaves a row
1516
+
1517
+ With more work in a directory than `WORK_HERE_MAX`, the same newest four showed every day
1518
+ and the rest never did, and a "Work here" with no room left only a ring event. Now
1519
+ `workHere` ranks up to `WORK_HERE_POOL` (8) and `rotateWork` chooses the day's lines: the
1520
+ newest stays first, and the other places move through the rest by lived day, so every
1521
+ session that day sees the same lines (identity's once-a-day rule) and a week shows them all.
1522
+ Stateless: nothing is written to remember a rotation. Each line costs
1523
+ `WORK_HERE_READ_PER_LINE` prose reads at delivery, so the pool doubles the reads (40 at
1524
+ most). When a delivery carries fewer lines than it ranked, one durable `self.work.overflow`
1525
+ row per directory, cause and lived day says so: `cap` (more than a wake shows, so they
1526
+ rotate) or `room` (fewer fitted the room the handoff and "Last here" left; `shown: 0` is
1527
+ none). Doctor's Wake line counts the `room` days; the dashboard's wake bar counts the
1528
+ directories since the last render, as it does "Last here". `cap` is the rotation working,
1529
+ and is not a cost.
1530
+
1531
+ ## 2026-10-03 — chapter addresses (Release A of deliberate recall)
1532
+
1533
+ - **`epi_…#N`** names one chapter (1-based), and `chapter-address.ts#resolveChapter`
1534
+ resolves it to its heading, text, calendar date, span and the session's memories written
1535
+ in that span. The address is derived (the chapter's place among the engine headings,
1536
+ read by `handoff/last-here.ts#chaptersOf`, which now also returns the heading line).
1537
+ - **The moment each chapter was written is stored** in the episode's meta
1538
+ (`CHAPTER_AT_META`, carried whole like `models`), because the only other record — the
1539
+ `episode-chapter` version's `archived_at` — is pruned after the retention window.
1540
+ Episodes from before are read from those versions while they last; past them the
1541
+ resolver says `momentsFrom: "unknown"` and lists no memories rather than guessing from
1542
+ the heading's day.
1543
+ - **The span** runs from the chapter before's moment (open for the first) to this
1544
+ chapter's, each edge shifted by `CHAPTER_MOMENT_GRACE_MS` (five minutes, a working
1545
+ default): the end-of-stretch answer writes its memories and its chapter in one turn, in
1546
+ either order. Chapter copies are left out of the list. A write-up's memories carry the
1547
+ session's id but a later moment, so they sit under no chapter. No caller yet (Release B).
1548
+ - **First caller (Release B, meaning mode):** `chapterTimesOf` reads an episode's chapter
1549
+ moments once and `chapterAt` places one memory by the same span rule, so recall can put
1550
+ hundreds of a subject's memories under their chapters without a `resolveChapter` (and its
1551
+ per-memory prose reads) for each; a test holds the two to the same answer.
1552
+
1553
+ ## 2026-10-09 — a regrown copy keeps its links
1554
+
1555
+ - When a chapter grows, `ingestEpisode` mints the new copy and archives the old one
1556
+ (`episode-regrown`). The old copy's links (the session's contiguity, a co-use, a dream's
1557
+ tie) stayed on the archived row, which conducts nothing: on 10-02 that was 260 of a live
1558
+ store's 1,200 edge rows. `SelfOptions.retarget` now hands each archived copy's links to
1559
+ the new copy, after the archive. It is `associate.retargetOnSupersede`, injected by the
1560
+ composition root as for `schemas/` and `dream/`; absent, nothing is carried, as before.
1561
+ - A retarget that throws costs the links, never the copy: counted on
1562
+ `self.episode.relink.failed`, and the ingestion reports what it always did.
1563
+ - The links stranded before this are carried once at open, in `counterpart.ts`
1564
+ (associate NOTES §15).
1565
+
1566
+ ## 2026-10-09 — the page's own "Last revised" line is taken out
1567
+
1568
+ The 10-01 guidance (`PAGE_WRITING_RULE`, above) told both writers to add no revised-on
1569
+ line, and nothing checked it: the wake still printed two date lines under "Who I am" for a
1570
+ page that carried one, and a page that already had it kept it. Now
1571
+ `page.ts#stripRevisedLines` takes the line out in two places: where the wake renders the
1572
+ page (`Self#pageBlock`, so a page stored with the line prints one date from the next
1573
+ render), and at the one write door (`Self#revisePage`, before the caps, the gate and the
1574
+ byte count), so a stored page heals the next time anyone writes it. A line is the page's
1575
+ own when the whole of it opens with "Last revised" past any parentheses, brackets,
1576
+ emphasis, quote marker or dash, and it is at most 160 characters; the words inside a
1577
+ paragraph stay. The blank line it stood behind goes with it. The revision row says how many
1578
+ went (`datelines`), because the owner's console writes through the same door. A page that
1579
+ is nothing but the line is refused as `empty` at write, and printed as it stands at render.
1580
+ The guidance stays: the strip is the check, not a reason to stop asking.
1581
+
1582
+ **Review of #332: only a dateline.** As first built the rule took any short line opening
1583
+ "Last revised" past its wrappers, which took prose ("Last revised my view of …"), a quoted
1584
+ line, a list entry, a code block's line and a page's own history list — at the write door,
1585
+ so the words left the stored page. Now the words must be followed by a date (ISO or numeric,
1586
+ a month's name, or today / tonight / yesterday), straight after or after "on" or a short
1587
+ "by …"; and a line inside a code fence, beside another such line (a history), or an entry
1588
+ beside another entry of a list stays. A lone one, at the head, the foot or between
1589
+ sections, still goes.
1590
+
1591
+ ## 2026-10-09 — the Arriving line says how often a repeating date comes round
1592
+
1593
+ A horizon item whose date repeats (`prospective/` NOTES §15) carries `every` beside
1594
+ `due` (`core/briefing.ts#selfRenderer` → `HorizonItem.every` → `Resolved.every`), and
1595
+ `datePrefix` prints `2026-08-25 (due 2026-10-12, every Monday) · `. `due` is this
1596
+ occurrence, never the anchor, so a birthday stated in 1990 reads as due this year. Unlike
1597
+ a one-off date, the parenthesis stays when the occurrence falls on the learned date:
1598
+ "every May 14" is news even then. One change to what the lane selects (review of #339): a
1599
+ DAILY repeat takes no line (`prospective/` NOTES §15) — rendered the evening before, it
1600
+ would read as due yesterday.
@@ -17,16 +17,28 @@
17
17
  * the mark (`{ n, at, triggers }`), `caught` is the raw mark value the last render
18
18
  * read BEFORE it composed. Behind iff the two differ. A mark set while a render
19
19
  * is composing has a new value, so it is not swallowed by that render's catch-up.
20
+ *
21
+ * A THIRD KEY, FOR THE BUILD (2026-10-02): `build` is the package version of
22
+ * the process that last published the bundle. After an install the stored wake
23
+ * was still the old version's until something marked it or the next lived day
24
+ * came, so a question the new version closes stayed in "Still open". A
25
+ * process that knows its build (`CounterpartOptions.build`) and finds the
26
+ * stored one different — or absent, a bundle published before this key — treats
27
+ * the wake as behind under the `version` trigger. Nothing writes a mark for it:
28
+ * the comparison is the mark.
20
29
  */
21
30
  import type { Store } from "../store/index.js";
22
31
 
23
32
  export const WAKE_BEHIND_KEY = "self.wake.behind";
24
33
  export const WAKE_CAUGHT_KEY = "self.wake.caught";
25
34
 
26
- /** What made the wake behind: the self page written, a write-up landed, the nightly run ended. */
27
- export type WakeTrigger = "page" | "write-up" | "run-end";
35
+ export const WAKE_BUILD_KEY = "self.wake.build";
36
+
37
+ /** What made the wake behind: the self page written, a write-up landed, the
38
+ * nightly run ended, or the bundle was published by another build. */
39
+ export type WakeTrigger = "page" | "write-up" | "run-end" | "version";
28
40
 
29
- export const WAKE_TRIGGERS: readonly WakeTrigger[] = ["page", "write-up", "run-end"];
41
+ export const WAKE_TRIGGERS: readonly WakeTrigger[] = ["page", "write-up", "run-end", "version"];
30
42
 
31
43
  /** The mark as it stands, with its raw value — the thing a render records as caught. */
32
44
  export interface WakeBehind {
@@ -87,3 +99,31 @@ export function noteWakeCaught(store: Store, raw: string): void {
87
99
  /* the mark stays, and the next process with a budget renders again */
88
100
  }
89
101
  }
102
+
103
+ /**
104
+ * Was the published bundle composed by another build than `build`? False when
105
+ * `build` is unknown (a null is never evidence of a change) or when there is no
106
+ * bundle yet (the first render is the cycle's anyway). An absent stamp beside a
107
+ * bundle is a bundle from before the stamp existed, so it is another build.
108
+ * Never throws.
109
+ */
110
+ export function wakeFromOtherBuild(store: Store, briefingKey: string, build: string | null | undefined): boolean {
111
+ if (build === null || build === undefined || build.length === 0) return false;
112
+ try {
113
+ if (store.getMeta(briefingKey) === undefined) return false;
114
+ return store.getMeta(WAKE_BUILD_KEY) !== build;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /** A render by `build` has published: stamp it. Never throws — an unwritten
121
+ * stamp costs one more render, never the publish. */
122
+ export function noteWakeBuild(store: Store, build: string | null | undefined): void {
123
+ if (build === null || build === undefined || build.length === 0) return;
124
+ try {
125
+ store.setMeta(WAKE_BUILD_KEY, build);
126
+ } catch {
127
+ /* the next process with this build renders once more */
128
+ }
129
+ }
@@ -272,6 +272,12 @@ export interface Resolved {
272
272
  * place of `(of …)`. Only horizon items carry one.
273
273
  */
274
274
  readonly due?: string;
275
+ /**
276
+ * How often an arriving occasion comes round, in words (`HorizonItem.every`,
277
+ * 2026-10-09), printed beside its due date: `(due 2027-05-14, every May 14)`.
278
+ * Only a horizon item that repeats carries one.
279
+ */
280
+ readonly every?: string;
275
281
  /**
276
282
  * True when the encode date is only an UPPER BOUND — the element was known BY
277
283
  * then, not learned then. Set for migrated elements, whose `learned_on` is
@@ -471,8 +477,12 @@ export function datePrefix(r: Resolved): string {
471
477
  // "2026-09-27 · …" while the item was due 2026-10-03, and the learned date
472
478
  // alone reads as when it happens.
473
479
  if (due !== "") {
474
- if (learned === "") return `due ${due}${DATE_SEP}`;
475
- if (due !== learned) return `${r.boundedDate === true ? DATE_BOUND : ""}${learned} (due ${due})${DATE_SEP}`;
480
+ // A repeating one says how often beside it (2026-10-09) — even when it is
481
+ // due on the day it was learned, since "every May 14" is news there too.
482
+ const every = (r.every ?? "").trim();
483
+ const often = every === "" ? "" : `, ${every}`;
484
+ if (learned === "") return `due ${due}${often}${DATE_SEP}`;
485
+ if (due !== learned || often !== "") return `${r.boundedDate === true ? DATE_BOUND : ""}${learned} (due ${due}${often})${DATE_SEP}`;
476
486
  }
477
487
  if (learned === "") return "";
478
488
  const happened = (r.happenedOn ?? "").trim();
@@ -0,0 +1,254 @@
1
+ /**
2
+ * CHAPTER ADDRESSES (v12, 2026-10-03, the write side of deliberate recall) —
3
+ * one chapter of an episode, named `epi_…#N` (N counted from 1), resolved to
4
+ * its heading, its text, its span in time, and the memories its session
5
+ * wrote during that span.
6
+ *
7
+ * **Derived, not stored.** The address is the episode's id and the chapter's
8
+ * place among the engine headings in its body (`handoff/last-here.ts#
9
+ * chaptersOf`, the one reader of them); nothing records it. What IS stored is
10
+ * the moment each chapter was written (`episodes.ts#CHAPTER_AT_META`, from
11
+ * v12 on), because the only other record of it — the version row each new
12
+ * chapter leaves behind (`reason: episode-chapter`, its `archived_at` the
13
+ * moment the next chapter opened) — is pruned after the retention window. An
14
+ * episode written before v12 is read from those versions while they last;
15
+ * past them, a chapter's moment is unknown and the resolver says so rather
16
+ * than guessing one from the heading's calendar day.
17
+ *
18
+ * **A chapter's span** is the stretch it wrote up: from the moment the
19
+ * chapter before it was written (none for the first: open) to the moment it
20
+ * was written. The memories under it are its session's own (`origin_session`),
21
+ * live, minus the chapter copies themselves, written inside that span — with
22
+ * `CHAPTER_MOMENT_GRACE_MS` after each edge, because the end-of-stretch answer
23
+ * writes its memories and its chapter in one turn, in either order, and the
24
+ * memories written a moment after the chapter belong to it rather than to the
25
+ * next. A write-up's memories (another session writing this one's stretch
26
+ * up later) carry this session's id but a later moment, so they fall after
27
+ * the last chapter and are not listed under any.
28
+ *
29
+ * Recall's meaning mode (Release B) places many memories at once: it reads
30
+ * each episode's chapter moments once (`chapterTimesOf`) and puts a memory
31
+ * under a chapter by the same span rule (`chapterAt`), resolving in full only
32
+ * the chapters it shows.
33
+ */
34
+ import { chaptersOf } from "../handoff/last-here.js";
35
+ import type { ReadOnlyStore } from "../store/index.js";
36
+ import { CHAPTER_AT_META, chapterMoments } from "./episodes.js";
37
+
38
+ /**
39
+ * How long after a chapter is written a memory of its session still counts
40
+ * as that chapter's (a working default, 2026-10-03): the end-of-stretch
41
+ * answer lands `session_end` entries and the chapter in one turn, in either
42
+ * order, seconds apart. Five minutes covers a slow turn without taking much
43
+ * of the next stretch.
44
+ */
45
+ export const CHAPTER_MOMENT_GRACE_MS = 5 * 60_000;
46
+
47
+ /** `epi_…#N`: an episode id (no whitespace, no `#`) and a 1-based chapter number. */
48
+ const ADDRESS = /^(epi_[^\s#/]+)#([1-9]\d*)$/;
49
+
50
+ /** The address of chapter `n` (1-based) of an episode. */
51
+ export function chapterAddress(episodeId: string, n: number): string {
52
+ return `${episodeId}#${String(n)}`;
53
+ }
54
+
55
+ /** An address read, or null when it is not one. */
56
+ export function parseChapterAddress(text: unknown): { episodeId: string; chapter: number } | null {
57
+ if (typeof text !== "string") return null;
58
+ const m = ADDRESS.exec(text.trim());
59
+ if (m === null) return null;
60
+ return { episodeId: m[1] as string, chapter: Number(m[2]) };
61
+ }
62
+
63
+ /** Where a chapter's moments were read from. */
64
+ export type ChapterMomentSource = "stored" | "versions" | "unknown";
65
+
66
+ export interface ResolvedChapter {
67
+ readonly address: string;
68
+ readonly episodeId: string;
69
+ /** 1-based. */
70
+ readonly chapter: number;
71
+ /** How many chapters the episode holds. */
72
+ readonly of: number;
73
+ /** The engine heading line, or null for a body with none (one chapter, whole). */
74
+ readonly heading: string | null;
75
+ /** The chapter's own words, without its heading. */
76
+ readonly text: string;
77
+ /** The calendar date its heading names (`YYYY-MM-DD`), or null. */
78
+ readonly date: string | null;
79
+ /** The session that wrote the episode, or null when its meta does not say. */
80
+ readonly session: string | null;
81
+ /** The episode's title, when it has one. */
82
+ readonly title: string | null;
83
+ /**
84
+ * The stretch it wrote up, UTC ms: `from` is when the chapter before it was
85
+ * written (null for the first chapter: open), `to` when this one was (null
86
+ * when unknown). Without the grace: these are the moments themselves.
87
+ */
88
+ readonly span: { readonly from: number | null; readonly to: number | null };
89
+ readonly momentsFrom: ChapterMomentSource;
90
+ /**
91
+ * The session's live memories written inside the span (with the grace),
92
+ * oldest first — not the chapter copies. Empty, and `momentsFrom:
93
+ * "unknown"`, when the chapter's own moment cannot be read.
94
+ */
95
+ readonly moments: readonly string[];
96
+ }
97
+
98
+ export type ChapterResolution =
99
+ | { readonly ok: true; readonly chapter: ResolvedChapter }
100
+ | { readonly ok: false; readonly reason: "not-an-address" | "no-episode" | "no-such-chapter"; readonly of?: number };
101
+
102
+ /**
103
+ * Resolve `epi_…#N`. Reads only: the episode row, its version rows when it
104
+ * predates stored moments, and its session's memories. Never throws on a
105
+ * store that will not answer one of those — the part it could not read is
106
+ * empty and the rest stands.
107
+ */
108
+ export function resolveChapter(store: ReadOnlyStore, address: string): ChapterResolution {
109
+ const parsed = parseChapterAddress(address);
110
+ if (parsed === null) return { ok: false, reason: "not-an-address" };
111
+ const row = store.row(parsed.episodeId);
112
+ if (row === undefined || row.type !== "episode" || row.body.length === 0) return { ok: false, reason: "no-episode" };
113
+ let meta: Record<string, unknown> = {};
114
+ try {
115
+ meta = store.readProse(parsed.episodeId).meta;
116
+ } catch {
117
+ return { ok: false, reason: "no-episode" };
118
+ }
119
+ const all = chaptersOf(row.body);
120
+ const at = all[parsed.chapter - 1];
121
+ if (at === undefined) return { ok: false, reason: "no-such-chapter", of: all.length };
122
+
123
+ const { moments: written, from: momentsFrom } = chapterTimes(store, parsed.episodeId, meta, all.length, row.created_at);
124
+ const to = written[parsed.chapter] ?? null;
125
+ const from = parsed.chapter === 1 ? null : (written[parsed.chapter - 1] ?? null);
126
+ const session = typeof meta["sessionId"] === "string" ? (meta["sessionId"] as string) : null;
127
+ // The chapter before's moment unknown while this one's is known: the span
128
+ // cannot be cut at its start, so nothing is listed rather than too much.
129
+ const cuttable = to !== null && (parsed.chapter === 1 || from !== null);
130
+ const moments = cuttable && session !== null ? momentsIn(store, session, parsed.episodeId, from, to) : [];
131
+ return {
132
+ ok: true,
133
+ chapter: {
134
+ address: chapterAddress(parsed.episodeId, parsed.chapter),
135
+ episodeId: parsed.episodeId,
136
+ chapter: parsed.chapter,
137
+ of: all.length,
138
+ heading: at.heading,
139
+ text: at.text.trim(),
140
+ date: at.date,
141
+ session,
142
+ title: row.title,
143
+ span: { from, to },
144
+ momentsFrom: cuttable ? momentsFrom : "unknown",
145
+ moments,
146
+ },
147
+ };
148
+ }
149
+
150
+ /** When each chapter of an episode was written, read once (`chapterTimesOf`). */
151
+ export interface ChapterTimes {
152
+ readonly episodeId: string;
153
+ /** How many chapters the episode holds. */
154
+ readonly of: number;
155
+ /** Chapter number (1-based) -> the moment it was written, UTC ms; a chapter missing here is unknown. */
156
+ readonly moments: Readonly<Record<number, number>>;
157
+ readonly from: ChapterMomentSource;
158
+ }
159
+
160
+ /**
161
+ * The moments an episode's chapters were written, by `resolveChapter`'s own
162
+ * reading (stored, else the versions), without resolving each chapter's
163
+ * memories — for a caller that places many memories at once. Null when the
164
+ * id is not an episode with words. Never throws.
165
+ */
166
+ export function chapterTimesOf(store: ReadOnlyStore, episodeId: string): ChapterTimes | null {
167
+ try {
168
+ const row = store.row(episodeId);
169
+ if (row === undefined || row.type !== "episode" || row.body.length === 0) return null;
170
+ const meta = store.readProse(episodeId).meta;
171
+ const of = chaptersOf(row.body).length;
172
+ const { moments, from } = chapterTimes(store, episodeId, meta, of, row.created_at);
173
+ return { episodeId, of, moments, from };
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * The chapter (1-based) a memory of the episode's session written at `at`
181
+ * falls under, by `resolveChapter`'s span rule — after the chapter before it
182
+ * was written (plus the grace), up to this one's moment plus the grace — or
183
+ * null when no chapter's span can be cut there (its moment, or the one
184
+ * before it, unknown) or `at` is past the last chapter (a later write-up).
185
+ */
186
+ export function chapterAt(times: ChapterTimes, at: number): number | null {
187
+ for (let k = 1; k <= times.of; k++) {
188
+ const to = times.moments[k];
189
+ if (to === undefined) continue;
190
+ const from = k === 1 ? null : times.moments[k - 1];
191
+ if (from === undefined) continue;
192
+ const lo = from === null ? Number.NEGATIVE_INFINITY : from + CHAPTER_MOMENT_GRACE_MS;
193
+ if (at > lo && at <= to + CHAPTER_MOMENT_GRACE_MS) return k;
194
+ }
195
+ return null;
196
+ }
197
+
198
+ /**
199
+ * When each chapter was written, by number: the stored map (v12 on), else
200
+ * the episode's own version rows — chapter 1 at the row's birth, chapter k+1
201
+ * at the `archived_at` of the `episode-chapter` version whose words held k
202
+ * chapters — while they last.
203
+ */
204
+ function chapterTimes(
205
+ store: ReadOnlyStore,
206
+ episodeId: string,
207
+ meta: Record<string, unknown>,
208
+ count: number,
209
+ createdAt: number | null,
210
+ ): { moments: Record<number, number>; from: ChapterMomentSource } {
211
+ const stored = meta[CHAPTER_AT_META] === undefined ? {} : chapterMoments(meta);
212
+ const out: Record<number, number> = {};
213
+ // An episode that began before v12 and went on after it has stored moments
214
+ // for its later chapters only: the versions give the earlier ones.
215
+ if (Object.keys(stored).length < count) {
216
+ if (createdAt !== null) out[1] = createdAt;
217
+ try {
218
+ for (const v of store.versions(episodeId)) {
219
+ if (v.reason !== "episode-chapter" || v.body.length === 0) continue;
220
+ const held = chaptersOf(v.body).filter((c) => c.heading !== null).length;
221
+ if (held >= 1 && held < count && out[held + 1] === undefined) out[held + 1] = v.archived_at;
222
+ }
223
+ } catch {
224
+ /* versions unreadable: what the row gives */
225
+ }
226
+ }
227
+ for (const [k, v] of Object.entries(stored)) out[Number(k)] = v;
228
+ const from: ChapterMomentSource = Object.keys(stored).length > 0 ? "stored" : Object.keys(out).length > 0 ? "versions" : "unknown";
229
+ return { moments: out, from };
230
+ }
231
+
232
+ /** The session's live memories written in (from, to], each edge shifted by the grace; chapter copies left out. */
233
+ function momentsIn(store: ReadOnlyStore, session: string, episodeId: string, from: number | null, to: number): string[] {
234
+ const lo = from === null ? Number.NEGATIVE_INFINITY : from + CHAPTER_MOMENT_GRACE_MS;
235
+ const hi = to + CHAPTER_MOMENT_GRACE_MS;
236
+ const out: string[] = [];
237
+ try {
238
+ for (const m of store.memoriesOfSession(session)) {
239
+ if (m.at <= lo || m.at > hi) continue;
240
+ const row = store.row(m.id);
241
+ if (row === undefined || row.source === "episode") continue;
242
+ let copy = false;
243
+ try {
244
+ copy = store.readProse(m.id).meta["episodeId"] === episodeId;
245
+ } catch {
246
+ copy = false;
247
+ }
248
+ if (!copy) out.push(m.id);
249
+ }
250
+ } catch {
251
+ return [];
252
+ }
253
+ return out;
254
+ }
@@ -439,6 +439,28 @@ export function chapterHeading(chapter: number, day: number, date?: string, mode
439
439
  /** The model-id screen lives in `core/types.ts` now (2026-09-25); re-exported. */
440
440
  export { isModelId };
441
441
 
442
+ /**
443
+ * The episode's `meta` key for WHEN EACH CHAPTER WAS WRITTEN (v12,
444
+ * 2026-10-03): `{ "1": <UTC ms>, "2": … }`, the moment the chapter was opened,
445
+ * off the store's clock. The heading says the calendar day; this says the
446
+ * moment, which is what a chapter's span is cut by (`chapter-address.ts`).
447
+ * Stored because the only other record of it — the version row each new
448
+ * chapter leaves — is pruned after the retention window. Carried whole on
449
+ * every append, as `models` is (meta merges shallowly).
450
+ */
451
+ export const CHAPTER_AT_META = "chapterAt";
452
+
453
+ /** The episode's chapter moments (`CHAPTER_AT_META`), by chapter number. */
454
+ export function chapterMoments(meta: Record<string, unknown>): Record<string, number> {
455
+ const raw = meta[CHAPTER_AT_META];
456
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {};
457
+ const out: Record<string, number> = {};
458
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
459
+ if (/^\d+$/.test(k) && typeof v === "number" && Number.isFinite(v)) out[k] = v;
460
+ }
461
+ return out;
462
+ }
463
+
442
464
  /** Which model wrote each chapter, from an episode's meta — `{ "1": "claude-opus-5-5" }`. */
443
465
  export function chapterModels(meta: Record<string, unknown>): Record<string, string> {
444
466
  const raw = meta["models"];
@@ -540,6 +562,7 @@ export function appendChapter(
540
562
  sessionId: state.sessionId,
541
563
  chapters: chapter,
542
564
  ...(model === undefined ? {} : { models: { [String(chapter)]: model } }),
565
+ [CHAPTER_AT_META]: { [String(chapter)]: store.now() },
543
566
  ...(opts.about === undefined ? {} : { [EPISODE_ABOUT_META]: opts.about }),
544
567
  },
545
568
  // The experiencer writing its own journal is the "episode" channel —
@@ -568,12 +591,16 @@ export function appendChapter(
568
591
  // the whole map is carried.
569
592
  const models = chapterModels(prior.meta);
570
593
  if (opensChapter && model !== undefined) models[String(num)] = model;
594
+ // v12: the moment each chapter opened, carried whole like `models`.
595
+ const moments = chapterMoments(prior.meta);
596
+ if (opensChapter) moments[String(num)] = store.now();
571
597
  store.revise(state.episodeId, {
572
598
  body: `${prior.body.trimEnd()}\n\n${opensChapter ? chapterHeading(num, opts.day, opts.date, model) + `\n\n${text.trim()}\n` : `${text.trim()}\n`}`,
573
599
  meta: {
574
600
  sessionId: state.sessionId,
575
601
  chapters: Math.max(num, recorded),
576
602
  ...(Object.keys(models).length === 0 ? {} : { models }),
603
+ ...(Object.keys(moments).length === 0 ? {} : { [CHAPTER_AT_META]: moments }),
577
604
  ...(opts.about === undefined ? {} : { [EPISODE_ABOUT_META]: opts.about }),
578
605
  },
579
606
  reason: opensChapter ? "episode-chapter" : "episode-append",