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
@@ -106,6 +106,7 @@ import {
106
106
  findSelfPage,
107
107
  readSelfPage,
108
108
  renderPage,
109
+ stripRevisedLines,
109
110
  } from "./page.js";
110
111
  import type { SelfPage, SelfPageAuthor } from "./page.js";
111
112
  import {
@@ -173,6 +174,7 @@ export * from "./journal-file.js";
173
174
  export * from "./page.js";
174
175
  export * from "./writer.js";
175
176
  export * from "./episodes.js";
177
+ export * from "./chapter-address.js";
176
178
  export * from "./freeze.js";
177
179
  export * from "./identity.js";
178
180
  export * from "./tunables.js";
@@ -197,6 +199,26 @@ export interface SelfEvent {
197
199
  */
198
200
  export const BRIEFING_KEY = "self.briefing";
199
201
 
202
+ /**
203
+ * THE IDS THE PUBLISHED BUNDLE LISTS UNDER "Still open:" (review of #332,
204
+ * 2026-10-09): a JSON array, written beside `BRIEFING_KEY` at each publish,
205
+ * so a line the delivery adds — the handoff's "since" line — can leave out
206
+ * what the wake already says is open rather than name it twice. Kept, not
207
+ * ranked, as the identity rotation's ids are.
208
+ */
209
+ export const THREADS_SHOWN_KEY = "self.threads.shown";
210
+
211
+ /** The ids the published bundle lists under "Still open:" — none when the
212
+ * key is absent (a bundle published before it) or unreadable. Never throws. */
213
+ export function threadsShown(store: Pick<Store, "getMeta">): Set<string> {
214
+ try {
215
+ const raw: unknown = JSON.parse(store.getMeta(THREADS_SHOWN_KEY) ?? "[]");
216
+ return new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []);
217
+ } catch {
218
+ return new Set();
219
+ }
220
+ }
221
+
200
222
  /**
201
223
  * The honest bootstrap line, and the ONLY case that may be shown in place of a
202
224
  * bundle: no bundle has ever been published. A present-but-damaged bundle is an
@@ -213,6 +235,13 @@ export interface SelfOptions {
213
235
  /** Told about each memory an episode ingestion mints, so the composition can
214
236
  * credit the cards it names (schemas NOTES §15). */
215
237
  onMemoryMinted?: (m: { id: string; title: string | null; body: string; day: number }) => void;
238
+ /**
239
+ * `associate.retargetOnSupersede`, so a regrown copy inherits the links its
240
+ * archived copy had learned (2026-10-09) — the same callback `schemas/` and
241
+ * `dream/` are handed, injected because `self/` may not import `associate/`.
242
+ * Absent: the new copy starts with no links (the behaviour before).
243
+ */
244
+ retarget?: (oldId: string, newId: string, day: number) => void;
216
245
  now?: () => number;
217
246
  /**
218
247
  * The IANA zone the CALENDAR day is taken in — the ask cap's day and the page
@@ -233,6 +262,12 @@ export interface HorizonItem {
233
262
  * learned (2026-10-01). Absent: the line carries the learned date alone.
234
263
  */
235
264
  readonly due?: string;
265
+ /**
266
+ * How often it comes round, in words, when the date repeats (`time.ts
267
+ * #readableRecurrence`, 2026-10-09): the line says `(due 2027-05-14, every
268
+ * May 14)`. Absent: a date that happens once.
269
+ */
270
+ readonly every?: string;
236
271
  }
237
272
 
238
273
  export interface BoundaryRequest extends BriefingRequest {
@@ -488,6 +523,7 @@ export class Self {
488
523
  private readonly gate: EpisodeGate;
489
524
  private readonly onEvent: ((e: SelfEvent) => void) | undefined;
490
525
  private readonly onMemoryMinted: SelfOptions["onMemoryMinted"];
526
+ private readonly retarget: SelfOptions["retarget"];
491
527
  private readonly now: () => number;
492
528
  private readonly zone: string | undefined;
493
529
  private readonly ring: SelfEvent[] = [];
@@ -502,6 +538,7 @@ export class Self {
502
538
  this.gate = opts.gate ?? NO_GATE;
503
539
  this.onEvent = opts.onEvent;
504
540
  this.onMemoryMinted = opts.onMemoryMinted;
541
+ this.retarget = opts.retarget;
505
542
  this.now = opts.now ?? (() => Date.now());
506
543
  this.zone = opts.zone;
507
544
  }
@@ -553,15 +590,20 @@ export class Self {
553
590
  }
554
591
  const base: Resolve = req.resolve ?? ((id) => this.resolveStatement(id, docs, sources));
555
592
  // An arriving occasion's due date, beside its learned one (2026-10-01).
556
- const dues = new Map<string, string>();
557
- for (const h of req.horizon ?? []) if (h.due !== undefined && h.due.trim() !== "") dues.set(h.id, h.due.trim());
593
+ // A repeating one says how often, beside it (2026-10-09).
594
+ const dues = new Map<string, { due: string; every?: string }>();
595
+ for (const h of req.horizon ?? []) {
596
+ if (h.due === undefined || h.due.trim() === "") continue;
597
+ const every = h.every?.trim() ?? "";
598
+ dues.set(h.id, every === "" ? { due: h.due.trim() } : { due: h.due.trim(), every });
599
+ }
558
600
  const resolve: Resolve =
559
601
  dues.size === 0
560
602
  ? base
561
603
  : (id) => {
562
604
  const r = base(id);
563
605
  const due = dues.get(id);
564
- return due === undefined ? r : { ...r, due };
606
+ return due === undefined ? r : { ...r, ...due };
565
607
  };
566
608
  // THE DAY-0 LANE (NOTES §11). The lookup is guarded by the empty lane and by
567
609
  // nothing else: it reads prose, and a store with even one identity element
@@ -816,7 +858,12 @@ export class Self {
816
858
  */
817
859
  revisePage(body: string, opts: PageWriteOptions): PageRevision {
818
860
  const day = opts.day ?? this.store.livedDay();
819
- const draft = body.replace(/\r\n/g, "\n").trim();
861
+ // THE PAGE'S OWN "LAST REVISED" LINE IS LEFT OUT (2026-10-09), before the
862
+ // caps and the gate see it: the wake dates the page, and a stored page that
863
+ // carried one printed two. The revision row counts what went
864
+ // (`datelines`), so a hand-written page edited here says so.
865
+ const own = stripRevisedLines(body.replace(/\r\n/g, "\n").trim());
866
+ const draft = own.body;
820
867
  let bytes = byteLength(draft);
821
868
  const session = opts.session ?? null;
822
869
  const none = {
@@ -983,6 +1030,7 @@ export class Self {
983
1030
  created: existing === null,
984
1031
  wakeCap: this.tunables.PAGE_WAKE_BYTES,
985
1032
  ...(warning === null ? {} : { warning }),
1033
+ ...(own.stripped === 0 ? {} : { datelines: own.stripped }),
986
1034
  },
987
1035
  });
988
1036
  this.emit("self.page.revised", id, {
@@ -1258,6 +1306,12 @@ export class Self {
1258
1306
  this.pageStale(page),
1259
1307
  this.tunables.PAGE_STALE_DAYS,
1260
1308
  );
1309
+ // THE PAGE'S OWN "LAST REVISED" LINE IS NOT PRINTED (2026-10-09): the
1310
+ // dateline above is the wake's, and a page that carried one of its own
1311
+ // printed two. A page that is nothing else is printed as it is.
1312
+ const own = stripRevisedLines(page.body);
1313
+ const body = own.body.length === 0 ? page.body : own.body;
1314
+ const bodyBytes = byteLength(body);
1261
1315
  const room = budgetBytes - PAGE_FLOOR_RESERVE_BYTES;
1262
1316
  // A ceiling with no room for the wake's OWN furniture has none for a line
1263
1317
  // about the page either, so "Who I am" carries nothing at all rather than a
@@ -1272,15 +1326,15 @@ export class Self {
1272
1326
  // forbids, moved from identity to the page (adversarial review MINOR-D).
1273
1327
  if (room <= 0) return NO_ROOM;
1274
1328
  const cap = Math.min(this.tunables.PAGE_WAKE_BYTES, room);
1275
- if (cap < PAGE_MIN_RENDER_BYTES && page.bytes > cap) {
1329
+ if (cap < PAGE_MIN_RENDER_BYTES && bodyBytes > cap) {
1276
1330
  return {
1277
- text: pageTooLargeLine(page.bytes),
1331
+ text: pageTooLargeLine(bodyBytes),
1278
1332
  dateline: null,
1279
1333
  truncated: true,
1280
- wholeBytes: page.bytes,
1334
+ wholeBytes: bodyBytes,
1281
1335
  };
1282
1336
  }
1283
- const rendered = renderPage(page.body, cap);
1337
+ const rendered = renderPage(body, cap);
1284
1338
  return {
1285
1339
  text: rendered.text,
1286
1340
  dateline,
@@ -1374,6 +1428,10 @@ export class Self {
1374
1428
  }
1375
1429
 
1376
1430
  this.store.setMeta(BRIEFING_KEY, briefing.text);
1431
+ // What this bundle lists as still open, so the delivery's "since" line
1432
+ // does not name it again (review of #332). Written at every publish, an
1433
+ // empty lane included, so it never describes an older bundle.
1434
+ this.store.setMeta(THREADS_SHOWN_KEY, JSON.stringify(briefing.kept.threads));
1377
1435
  // The rotation's memory: the identity ids this bundle KEPT, stamped with
1378
1436
  // the day. Kept, not ranked — an element the budget trimmed did not render
1379
1437
  // and keeps its place at the front of the next rotation.
@@ -2086,6 +2144,23 @@ export class Self {
2086
2144
  this.store.archive(stale, "episode-regrown");
2087
2145
  archived.push(stale);
2088
2146
  }
2147
+ // THE LINKS GO WITH THE WORDS (2026-10-09). An archived copy stops
2148
+ // conducting, so every link it had learned (the session's contiguity, a
2149
+ // co-use, a dream's tie) was stranded on it: 260 of a live store's 1,200
2150
+ // edge rows on 10-02. The new copy inherits them the way a dream merge's
2151
+ // memory inherits its originals' — after the archive, so one stale copy's
2152
+ // tie to another is not carried. A failure costs the links, never the copy.
2153
+ let relinkFailed = 0;
2154
+ for (const stale of archived) {
2155
+ try {
2156
+ this.retarget?.(stale, memoryId, d);
2157
+ } catch {
2158
+ relinkFailed += 1;
2159
+ }
2160
+ }
2161
+ if (relinkFailed > 0) {
2162
+ this.emit("self.episode.relink.failed", state.episodeId, { memory: memoryId, failed: relinkFailed });
2163
+ }
2089
2164
 
2090
2165
  this.persistState(
2091
2166
  {
@@ -276,6 +276,94 @@ function byteLengthOf(s: string): number {
276
276
  return new TextEncoder().encode(s).length;
277
277
  }
278
278
 
279
+ // ── the page's own revision line ────────────────────────────────────────────
280
+
281
+ /**
282
+ * The longest line that can be a page's own revision line. Past it the line
283
+ * is prose that happens to open with the words, and it stays.
284
+ */
285
+ export const REVISED_LINE_MAX_CHARS = 160;
286
+
287
+ /** A date as a dateline states one: ISO or numeric, a month's name and a day,
288
+ * or the day words the writers used before the 10-01 guidance. */
289
+ const REVISED_DATE = String.raw`(?:(?:\d{4}-\d{1,2}-\d{1,2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(?:\d{4}|\d{1,2}))(?!\d)|(?:\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*|today|tonight|yesterday)(?![a-z]))`;
290
+
291
+ /** "Last revised", then the date — straight after, or after "on" or a short
292
+ * "by …" (review of #332: without the date, "Last revised my view of …", a
293
+ * quoted line and a list entry were all taken). */
294
+ const REVISED_OPENING = new RegExp(
295
+ String.raw`^last\s+revised\b[\s:,(*_\-–—]*(?:on\s+)?(?:by\s+[^,;:\n]{1,48}?[\s,]+(?:on\s+)?)?${REVISED_DATE}`,
296
+ "iu",
297
+ );
298
+
299
+ /** A Markdown list entry: `- `, `* `, `+ `, `1. ` or `1) `. */
300
+ const LIST_ENTRY = /^\s*(?:[-*+]|\d+[.)])\s+/u;
301
+
302
+ /** A code fence's opening or closing line. */
303
+ const FENCE = /^\s{0,3}(?:```|~~~)/u;
304
+
305
+ /**
306
+ * IS THIS LINE THE PAGE'S OWN "LAST REVISED" LINE (2026-10-09)? A whole line
307
+ * that opens — past any wrapping of parentheses, brackets, emphasis, a quote
308
+ * marker or a dash — with "Last revised" and a date (`REVISED_OPENING`), and
309
+ * is short. A sentence that says the words in the middle of a paragraph is
310
+ * not one, and neither is a line that opens with them and goes on to say
311
+ * something else. Where it stands is `stripRevisedLines`'s to judge.
312
+ */
313
+ export function isRevisedLine(line: string): boolean {
314
+ const t = line.trim();
315
+ if (t.length === 0 || t.length > REVISED_LINE_MAX_CHARS) return false;
316
+ return REVISED_OPENING.test(t.replace(/^[>(\[*_\s\-–—]+/u, ""));
317
+ }
318
+
319
+ /**
320
+ * THE PAGE WITHOUT ITS OWN "LAST REVISED" LINES (2026-10-09). The wake dates
321
+ * the page (`briefing.ts#pageDateline`), so a page that carries its own line
322
+ * printed two, one under the other. The writers were told not to add one
323
+ * (`writer.ts#PAGE_WRITING_RULE`, 2026-10-01), which is guidance and checks
324
+ * nothing, and a page that already carried the line kept printing it. Taken
325
+ * out where the wake renders the page and where the page is written
326
+ * (`Self#revisePage`), so a stored page heals the next time it is written.
327
+ *
328
+ * A dateline stands alone, so three places keep the line (review of #332):
329
+ * inside a code fence; beside another such line, with no blank between (two
330
+ * in a row are the page's own history); and as an entry of a list, beside
331
+ * another entry. A lone one, at the head, the foot or between sections, goes.
332
+ *
333
+ * Only the line goes, and the blank line it stood behind when it stood
334
+ * between two, so a removed line leaves no gap of two. `stripped` counts what
335
+ * went; with none, the body is returned exactly as it came. Pure.
336
+ */
337
+ export function stripRevisedLines(body: string): { body: string; stripped: number } {
338
+ const lines = body.split("\n");
339
+ let fenced = false;
340
+ const dateline = lines.map((l) => {
341
+ if (FENCE.test(l)) {
342
+ fenced = !fenced;
343
+ return false;
344
+ }
345
+ return !fenced && isRevisedLine(l);
346
+ });
347
+ const beside = (i: number): number[] =>
348
+ [i - 1, i + 1].filter((j) => j >= 0 && j < lines.length && (lines[j] ?? "").trim() !== "");
349
+ const kept = (i: number): boolean =>
350
+ beside(i).some((j) => dateline[j] === true) ||
351
+ (LIST_ENTRY.test(lines[i] ?? "") && beside(i).some((j) => LIST_ENTRY.test(lines[j] ?? "")));
352
+ const out: string[] = [];
353
+ let stripped = 0;
354
+ for (let i = 0; i < lines.length; i++) {
355
+ const line = lines[i] ?? "";
356
+ if (dateline[i] !== true || kept(i)) {
357
+ out.push(line);
358
+ continue;
359
+ }
360
+ stripped += 1;
361
+ const before = out[out.length - 1];
362
+ if ((before === undefined || before.trim() === "") && (lines[i + 1] ?? "x").trim() === "") i += 1;
363
+ }
364
+ return stripped === 0 ? { body, stripped: 0 } : { body: out.join("\n").trim(), stripped };
365
+ }
366
+
279
367
  // ── what the wake prints ────────────────────────────────────────────────────
280
368
 
281
369
  export interface RenderedPage {
@@ -50,6 +50,10 @@ export interface SelfTunables {
50
50
  CRAFT_AT_DELIVERY: boolean;
51
51
  /** How many work lines one delivery shows for its directory. CAL. */
52
52
  WORK_HERE_MAX: number;
53
+ /** How many work lines are ranked for the rotation to choose `WORK_HERE_MAX`
54
+ * from (`work.ts#rotateWork`, 2026-10-02). Each costs
55
+ * `WORK_HERE_READ_PER_LINE` prose reads per delivery. CAL. */
56
+ WORK_HERE_POOL: number;
53
57
  /** Characters of a work line's excerpt, after its title. CAL. */
54
58
  WORK_HERE_EXCERPT: number;
55
59
  /** Most open threads considered. CAL. [v1 threads lane: count-capped at 12;
@@ -209,6 +213,7 @@ export const SELF_TUNABLES: SelfTunables = {
209
213
  CRAFT_MAX: 8,
210
214
  CRAFT_AT_DELIVERY: true,
211
215
  WORK_HERE_MAX: 4,
216
+ WORK_HERE_POOL: 8,
212
217
  WORK_HERE_EXCERPT: 60,
213
218
  THREADS_MAX: 5,
214
219
  HINTS_MAX: 8,
@@ -85,6 +85,15 @@ export function isWorkMemory(m: WorkFacts): boolean {
85
85
  */
86
86
  export const WORK_HERE_HEADING = "Work here, if it helps:";
87
87
 
88
+ /**
89
+ * MORE WORK THAN THE WAKE SHOWED (2026-10-02): one durable row per directory
90
+ * per lived day when a delivery had more work lines than it carried — more
91
+ * than `WORK_HERE_MAX` (`cause: "cap"`, so the lines rotate), or fewer fitted
92
+ * the room the handoff and "Last here" left (`cause: "room"`, none at all
93
+ * when `shown` is 0). Counts and bytes, the directory as `scope`; never text.
94
+ */
95
+ export const WORK_OVERFLOW_EVENT = "self.work.overflow";
96
+
88
97
  export interface WorkHereOptions {
89
98
  /** The lived day strength is read at. */
90
99
  readonly day: number;
@@ -94,6 +103,9 @@ export interface WorkHereOptions {
94
103
  readonly excerpt: number;
95
104
  /** Ids no lane here may show: what a later memory settled over. */
96
105
  readonly skip?: ReadonlySet<string>;
106
+ /** How many lines to rank, best first, for the caller to rotate through
107
+ * (`SelfTunables.WORK_HERE_POOL`). Absent: `max`. */
108
+ readonly pool?: number;
97
109
  }
98
110
 
99
111
  interface Candidate {
@@ -149,11 +161,12 @@ export function workHere(
149
161
  scope: string,
150
162
  opts: WorkHereOptions,
151
163
  ): string[] {
164
+ const pool = Math.max(opts.max, opts.pool ?? opts.max);
152
165
  if (opts.max <= 0 || scope.trim().length === 0) return [];
153
166
  const seen = new Set<string>();
154
167
  const found: Candidate[] = [];
155
168
  for (const where of scopesFor(scope)) {
156
- for (const id of store.workCandidates(where, opts.max * WORK_HERE_READ_PER_LINE)) {
169
+ for (const id of store.workCandidates(where, pool * WORK_HERE_READ_PER_LINE)) {
157
170
  if (seen.has(id) || opts.skip?.has(id) === true) continue;
158
171
  seen.add(id);
159
172
  const row = store.row(id);
@@ -180,7 +193,27 @@ export function workHere(
180
193
  }
181
194
  }
182
195
  found.sort((a, b) => b.touched - a.touched || b.strength - a.strength || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
183
- return found.slice(0, opts.max).map((c) => workLine(c.id, c.doc, opts.excerpt, c.bounded));
196
+ return found.slice(0, pool).map((c) => workLine(c.id, c.doc, opts.excerpt, c.bounded));
197
+ }
198
+
199
+ /**
200
+ * WHICH OF THE RANKED LINES SHOW TODAY (2026-10-02). With no more than `max`,
201
+ * all of them. With more, the newest stays first — the work just done is the
202
+ * likeliest to help — and the other `max - 1` places rotate through the rest
203
+ * by lived day, so every session that day sees the same lines and the next
204
+ * day shows the next ones (identity's once-a-day rule, NOTES §30). Shown in
205
+ * ranked order. Stateless: nothing is written to remember a rotation. Pure.
206
+ */
207
+ export function rotateWork(lines: readonly string[], max: number, day: number): string[] {
208
+ if (max <= 0) return [];
209
+ if (lines.length <= max) return [...lines];
210
+ const [first, ...rest] = lines;
211
+ const k = max - 1;
212
+ if (first === undefined || k === 0) return first === undefined ? [] : [first];
213
+ const offset = (((Math.floor(day) * k) % rest.length) + rest.length) % rest.length;
214
+ const picked = new Set<number>();
215
+ for (let i = 0; i < k; i++) picked.add((offset + i) % rest.length);
216
+ return [first, ...rest.filter((_, i) => picked.has(i))];
184
217
  }
185
218
 
186
219
  /** One work line (see `workHere`). */
@@ -73,6 +73,7 @@
73
73
  * passed as `nothing-to-say`, derived and labelled as derived. A stored outcome
74
74
  * that pretends to knowledge nobody has is the thing §2.4 is about.
75
75
  */
76
+ import { TOOL_RESULT_CEILING, wireChars } from "../fit/index.js";
76
77
  import { strength } from "../physics/index.js";
77
78
  import type { Store } from "../store/index.js";
78
79
  import { calendarDate } from "./calendar.js";
@@ -709,6 +710,35 @@ export function dayMemories(
709
710
  export const NIGHT_WRITER_MEMORY_BYTES = 40_000;
710
711
  export const NIGHT_WRITER_MEMORY_MAX = 150;
711
712
 
713
+ /** The tool the nightly writer is told to write the page with — the MCP server's `self_page`. */
714
+ export const NIGHT_WRITER_TOOL = "counterparts self_page";
715
+ /** Room beside the writer's block in its result: the phase, `about`, `ifVersion`, `how`, `next`. */
716
+ const NIGHT_WRITER_RESULT_MARGIN = 2_000;
717
+ /** How many times the day's room is shrunk before the block goes as it is (the server's net is behind it). */
718
+ const NIGHT_WRITER_FIT_TRIES = 4;
719
+
720
+ /**
721
+ * THE NIGHT'S DAY, FITTED TO ONE TOOL RESULT (2026-10-02). The writer's
722
+ * block rides in one result beside the page carried whole (up to 16 KB), so
723
+ * `NIGHT_WRITER_MEMORY_BYTES` alone did not bound it: it came to 46,735 and
724
+ * 45,786 characters on the first two measured nights, near Claude Code's
725
+ * 50,000 (`fit/TOOL_RESULT_CEILING`). Measured as it leaves — the text
726
+ * escaped in the result's JSON, by `wireChars`, with room for the phase's
727
+ * other fields — and when it is over, the day's room shrinks by what was
728
+ * over (and a tenth more, for the escaping) and the block is built again.
729
+ * What no longer fits is `dropped`, counted and said, as always. Pure.
730
+ */
731
+ export function fitNightWriter<B>(build: (budgetBytes: number) => B, render: (built: B) => string): { built: B; text: string } {
732
+ let budget = NIGHT_WRITER_MEMORY_BYTES;
733
+ for (let tries = 0; ; tries += 1) {
734
+ const built = build(budget);
735
+ const text = render(built);
736
+ const over = wireChars(JSON.stringify(text)) + NIGHT_WRITER_RESULT_MARGIN - TOOL_RESULT_CEILING.CHARS;
737
+ if (over <= 0 || budget === 0 || tries >= NIGHT_WRITER_FIT_TRIES) return { built, text };
738
+ budget = Math.max(0, budget - Math.ceil(over * 1.1) - MEMORY_LINE_OVERHEAD * 10);
739
+ }
740
+ }
741
+
712
742
  /** What one bullet costs beside its statement: `- `, a newline, and slack. */
713
743
  const MEMORY_LINE_OVERHEAD = 16;
714
744
 
@@ -17,7 +17,13 @@ Two seams are genuinely stubbed and both are declared: the briefing renderer
17
17
 
18
18
  ---
19
19
 
20
- ## 1. `store/` — box 3 has no strength column and no box-3 writer (WORKED AROUND)
20
+ ## 1. `store/` — box 3 has no strength column and no box-3 writer (WORKED AROUND) — CLOSED 2026-08-25 (noted 2026-10-09)
21
+
22
+ **Closed by the wave-3 seam pass** (`d88f957`, 2026-08-25, SEAMS item J): `cache.sqlite`
23
+ has a `ranking` table that `resetCache` drops with the rest, `Store.setRanking` /
24
+ `ranking` / `rankingAll` read and write it, and `cycle.ts` takes the store as the cache
25
+ (`storeRankingCache`) whenever it supports ranking. `strength-cache.ts` stays, as the
26
+ fallback for a port without `setRanking`. The text below is the gap as filed.
21
27
 
22
28
  **Owner:** `store/`.
23
29
  **Needed:** the decay tick materializes `strength(m, d)` and `band(m, d)` into
@@ -114,7 +120,11 @@ three record types and all three become queryable, which is what the dashboard
114
120
 
115
121
  ---
116
122
 
117
- ## 4. The minting seam — `updates:` must actually reach canonical state
123
+ ## 4. The minting seam — `updates:` must actually reach canonical state — CLOSED 2026-08-25 (noted 2026-10-09)
124
+
125
+ **Closed by the wave-3 seam pass** (`d88f957`, 2026-08-25): `core/mint.ts` writes the
126
+ RESOLVED id to `doc.meta["updates"]`, and an unresolved declaration writes no key (its
127
+ header names this section). The text below is the gap as filed.
118
128
 
119
129
  **Owner:** whoever mints memories from `remember/`'s proposals.
120
130
  **Needed:** CONTRACT §5 G9 — *a memory that declares `updates:` is never merged
@@ -132,7 +142,12 @@ first.
132
142
 
133
143
  ---
134
144
 
135
- ## 5. `physics/` — there is no `consolidationEligibility()`
145
+ ## 5. `physics/` — there is no `consolidationEligibility()` — CLOSED 2026-08-25 (noted 2026-10-09)
146
+
147
+ **Closed by the wave-3 seam pass** (`d88f957`, 2026-08-25): `physics/index.ts` exports
148
+ `consolidationEligibility`, and `consolidate.ts` executes it. Since #251 (2026-09-26) it
149
+ is for legacy memories only (a post-upgrade memory is refused `not-legacy`), so the
150
+ criterion written below is no longer the rule. The text below is the gap as filed.
136
151
 
137
152
  **Owner:** `physics/`.
138
153
  **Needed:** "memories crossing the physics consolidation criteria get the flag".
@@ -270,6 +285,10 @@ more than a name match (a person card for the owner, an embedding), that is a
270
285
  `schemas/` question, and this phase should receive the verdict rather than compute it.
271
286
  The owner's demotions arrive through the optional `coreDemoted`; a port without it
272
287
  cannot be told "not this one".
288
+ *(Noted 2026-10-09: the first paragraph no longer describes the code. Since store v9
289
+ (`0a3e7e9`, #256, 2026-09-27) `aboutMe` reads the memory's `about` mark (the row's, or the
290
+ document's when the row has none) and no longer reads `owner`; the consolidate phase does
291
+ not call `ownerNames`; the dream and the reflection do, among others.)*
273
292
 
274
293
 
275
294
  ## Demotion has no way back (2026-09-26, working default)
@@ -857,7 +857,15 @@ Working defaults, held lightly.
857
857
  - **The promotion record names its returns' sources** (`returnSources`, `reflectionOnly`),
858
858
  read off the memory's `returns` rows when the port has `returnsOf` — and
859
859
  `feelingRecordedLater` (review of #256): it would not have crossed tonight with the
860
- door to feelings recorded later closed.
860
+ door to feelings recorded later closed. Since #317 an ordinary session's feeling-now
861
+ (`source: awake`) comes through that door too, so the record also says WHOSE
862
+ (`feelingRecordedLaterBy`, 2026-10-02, review of #317): the later sources with a feeling
863
+ at `CORE_FAST_FEELING` — `reflection`, `awake`, or both — read off `feelingsFor`.
864
+ Doctor and the reflection's share credit a reflection only when it names `reflection`
865
+ (`laterFeelingWasReflections`); an `awake` one is said apart, and one both could have
866
+ carried is said once, as both (review of #319). Absent (an older record, no
867
+ `feelingsFor`, or none found — never an empty list), it reads as a reflection's: before
868
+ #317 nothing else came through.
861
869
  - **The fast lane's door for feelings recorded later** is a meta row,
862
870
  `core.fast.acceptsReflectedFeeling` (`on` / `off`), read once per consolidation
863
871
  (`acceptsReflectedFeeling`); absent, the physics tunable decides (open).
@@ -902,3 +910,14 @@ cursor the way `consolidate` does (`markers.ts`): start strictly after it, wrap,
902
910
  under `apply`. `dedup` (pairs, rebuilt each run) and `fade` (`schemas/`' own sweep) are
903
911
  unchanged; `log` needs none.
904
912
 
913
+
914
+ ## 2026-10-09 — the prune passes physics one more fact: a repeating date
915
+
916
+ `runPrune` now tells `pruneVerdict` whether the row's reminder date still repeats
917
+ (`recurring: store#recurrenceOfRow(row) !== null` — a day `event_date` and a recurrence
918
+ word in its meta, the predicate `recurringMemories` reads), beside `inLiveRevisionChain`.
919
+ Physics refuses such a row by name (`blocked:recurring` on the cycle row, counted by the
920
+ fired view as a real refusal beside `protected`) — only on a night the floor would
921
+ otherwise have let it go (review of #341), so a repeat above the floor counts under
922
+ `above-floor` alone. The phase adds no criterion of its own;
923
+ why the gate exists is physics NOTES 2026-10-09 and prospective NOTES §16.
@@ -33,7 +33,7 @@
33
33
  */
34
34
 
35
35
  import { TUNABLES as PHYSICS_TUNABLES, consolidationEligibility, promote, promotionEligibility, strength } from "../physics/index.js";
36
- import { CORE_ABOUT_MARKS, isSelfRelevantFeeling } from "../store/index.js";
36
+ import { CORE_ABOUT_MARKS, LATER_FEELING_SOURCES, isSelfRelevantFeeling } from "../store/index.js";
37
37
  import type { CoreContext, MemoryPhysics, PromotionCrossing, PromotionReason } from "../physics/index.js";
38
38
  import { rowToPhysics } from "../store/operational.js";
39
39
  import type { MemoryRow } from "../store/operational.js";
@@ -189,7 +189,7 @@ export function selfRelevantFeeling(
189
189
  (f) =>
190
190
  f.whose === "self" &&
191
191
  f.strength >= PHYSICS_TUNABLES.CORE_FAST_FEELING &&
192
- (f.source === null || f.source === "session" || (f.source === "reflection" && acceptsReflected)) &&
192
+ (f.source === null || f.source === "session" || ((LATER_FEELING_SOURCES as readonly (string | null)[]).includes(f.source) && acceptsReflected)) &&
193
193
  isSelfRelevantFeeling(f.emotion, f.other_word),
194
194
  );
195
195
  } catch {
@@ -197,6 +197,53 @@ export function selfRelevantFeeling(
197
197
  }
198
198
  }
199
199
 
200
+ /**
201
+ * WHICH LATER FEELING CARRIED A PROMOTION (2026-10-02, review of #317): the
202
+ * sources among `LATER_FEELING_SOURCES` with a feeling on the memory at the
203
+ * fast lane's strength (`CORE_FAST_FEELING`, on the raw strength the peak
204
+ * reads). Asked only when the lane would not have been met with the door
205
+ * closed — every lived feeling fell short — so each source listed could have
206
+ * met it alone; both may be. Undefined when the port cannot read feelings or
207
+ * none is found (never an empty list): the record then says only
208
+ * `feelingRecordedLater`, read as a reflection's.
209
+ */
210
+ export function laterFeelingCarriers(store: Pick<SleepStore, "feelingsFor">, id: string): readonly ("reflection" | "awake")[] | undefined {
211
+ if (store.feelingsFor === undefined) return undefined;
212
+ try {
213
+ const rows = store.feelingsFor(id);
214
+ const out: ("reflection" | "awake")[] = [];
215
+ for (const src of LATER_FEELING_SOURCES) {
216
+ if (src !== "reflection" && src !== "awake") continue;
217
+ if (rows.some((f) => f.source === src && f.strength >= PHYSICS_TUNABLES.CORE_FAST_FEELING)) out.push(src);
218
+ }
219
+ // None found (review of #319): say nothing rather than an empty list a
220
+ // reader would credit to no one; absent reads as a reflection's.
221
+ return out.length === 0 ? undefined : out;
222
+ } catch {
223
+ return undefined;
224
+ }
225
+ }
226
+
227
+ /** The fields of a promotion record the two readers below look at, as parsed JSON. */
228
+ type LaterFeelingFields = { readonly feelingRecordedLater?: unknown; readonly feelingRecordedLaterBy?: unknown };
229
+
230
+ /**
231
+ * Did a REFLECTION's feeling carry this promotion? `feelingRecordedLater`, with
232
+ * `feelingRecordedLaterBy` naming a reflection — or naming no one, as on a
233
+ * record written before #317, when no other source came through the door.
234
+ */
235
+ export function laterFeelingWasReflections(rec: LaterFeelingFields): boolean {
236
+ if (rec.feelingRecordedLater !== true) return false;
237
+ const by = rec.feelingRecordedLaterBy;
238
+ return !Array.isArray(by) || by.includes("reflection");
239
+ }
240
+
241
+ /** Did an ordinary session's feeling-now (`awake`, #317) carry this promotion? */
242
+ export function laterFeelingWasAwake(rec: LaterFeelingFields): boolean {
243
+ const by = rec.feelingRecordedLaterBy;
244
+ return rec.feelingRecordedLater === true && Array.isArray(by) && by.includes("awake");
245
+ }
246
+
200
247
  /**
201
248
  * DOES THIS PERSON MEMORY NAME THE OWNER? — the old kind reading (title, body,
202
249
  * or its `name` / `entity` meta, whole word), kept for what it still answers
@@ -378,17 +425,22 @@ export function runConsolidate(ctx: PhaseCtx): ConsolidateResult {
378
425
  // alone" is a number doctor can print rather than a guess.
379
426
  const sources = returnSourcesOf(store, e.id);
380
427
  // AND WHETHER THE OPEN DOOR CARRIED IT (review of #256, S4): with the
381
- // fast lane open to feelings a reflection recorded later, would it still
382
- // have crossed with that door closed? If not, a reflection's feeling is
383
- // what carried it — shown like a promotion on reflection alone, whatever
384
- // the source of its return.
428
+ // fast lane open to feelings recorded later, would it still have crossed
429
+ // with that door closed? If not, a later feeling is what carried it.
430
+ // WHOSE (review of #317, 2026-10-02): since #317 an ordinary session's
431
+ // feeling-now (`awake`) comes through the same door as a reflection's, so
432
+ // the record names which could have carried it — a reflection's is shown
433
+ // like a promotion on reflection alone, an awake one is said apart.
385
434
  const closed = reflected ? promotionEligibility(e.physics, { aboutMe: true, day, acceptsReflectedFeeling: false }) : null;
435
+ const later = closed !== null && !closed.fast.met && !closed.slow.met;
436
+ const by = later ? laterFeelingCarriers(store, e.id) : undefined;
386
437
  const record: PromotionRecord = {
387
438
  id: e.id,
388
439
  ...e.crossing,
389
440
  returnSources: sources,
390
441
  reflectionOnly: sources.reflection > 0 && sources.awake === 0,
391
- feelingRecordedLater: closed !== null && !closed.fast.met && !closed.slow.met,
442
+ feelingRecordedLater: later,
443
+ ...(by === undefined ? {} : { feelingRecordedLaterBy: by }),
392
444
  };
393
445
  if (ctx.apply) {
394
446
  // Record BEFORE the flag: a crossing nobody could account for afterwards
@@ -75,6 +75,9 @@ export {
75
75
  aboutMe,
76
76
  acceptsReflectedFeeling,
77
77
  coreContextFor,
78
+ laterFeelingCarriers,
79
+ laterFeelingWasAwake,
80
+ laterFeelingWasReflections,
78
81
  namesOwner,
79
82
  ownerNames,
80
83
  promotionRecordKey,
@@ -24,6 +24,7 @@
24
24
 
25
25
  import { pressureAt, pruneVerdict, supersededResolvable } from "../physics/index.js";
26
26
  import type { MemoryPhysics, PruneReason } from "../physics/index.js";
27
+ import { recurrenceOfRow } from "../store/index.js";
27
28
  import { rowToPhysics } from "../store/operational.js";
28
29
  import { PRUNE_ARCHIVE_REASON, PRUNE_RECORD_PREFIX } from "./tunables.js";
29
30
  import type { MemoryRow, PhaseCtx, PhaseOutcome, PrunedRecord } from "./types.js";
@@ -36,7 +37,7 @@ const PRUNE_PHASE: Phase = "prune";
36
37
 
37
38
  export interface PruneResult extends PhaseOutcome {
38
39
  readonly pruned: readonly PrunedRecord[];
39
- /** Every blocking gate, counted — physics names all five, not just the first. */
40
+ /** Every blocking gate, counted — physics names all six, not just the first. */
40
41
  readonly blocked: Readonly<Record<string, number>>;
41
42
  /** Memories left in place because their record could not be written. */
42
43
  readonly recordFailures: readonly { id: string; error: string }[];
@@ -131,9 +132,12 @@ export function runPrune(ctx: PhaseCtx): PruneResult {
131
132
  const p = rowToPhysics(row);
132
133
  const verdict = pruneVerdict(p, day, {
133
134
  inLiveRevisionChain: inLiveRevisionChain(store, id, row, p, day),
135
+ // A reminder date that still repeats (2026-10-09): physics refuses it by
136
+ // name. The meta is the row's, read here because physics cannot see it.
137
+ recurring: recurrenceOfRow(row) !== null,
134
138
  });
135
139
  if (!verdict.prune || verdict.record === null) {
136
- // EVERY failing gate, not just the first — physics names all five, and a
140
+ // EVERY failing gate, not just the first — physics names all six, and a
137
141
  // memory blocked by two reasons that reports one is a memory nobody can
138
142
  // explain. Mirrored into the skip map so the cycle report carries them.
139
143
  for (const reason of verdict.blockedBy) {