counterparts 0.3.7 → 0.3.8

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 (127) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/docs/module-map.md +4 -1
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +73 -52
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +8 -3
  6. package/src/adapters/claude-code/NOTES.md +119 -0
  7. package/src/adapters/claude-code/bin/hook.ts +95 -33
  8. package/src/adapters/claude-code/bin/nightly.ts +21 -2
  9. package/src/adapters/claude-code/bin/runner.ts +55 -44
  10. package/src/adapters/claude-code/child.ts +203 -0
  11. package/src/adapters/claude-code/config.ts +66 -69
  12. package/src/adapters/claude-code/doctor.ts +249 -68
  13. package/src/adapters/claude-code/envelope.ts +38 -0
  14. package/src/adapters/claude-code/hooks.ts +206 -42
  15. package/src/adapters/claude-code/index.ts +7 -20
  16. package/src/adapters/claude-code/night-run.ts +19 -8
  17. package/src/adapters/cli/CONTRACT.md +9 -0
  18. package/src/adapters/cli/commands.ts +282 -4
  19. package/src/adapters/cli/coverage.ts +100 -0
  20. package/src/adapters/cli/dream-core.ts +11 -0
  21. package/src/adapters/cli/help.ts +6 -0
  22. package/src/adapters/cli/mechanisms.ts +23 -6
  23. package/src/adapters/cli/self-page.ts +4 -4
  24. package/src/adapters/cli/settle.ts +63 -0
  25. package/src/adapters/dashboard/registries.ts +29 -1
  26. package/src/adapters/dashboard/web/README.md +41 -11
  27. package/src/adapters/dashboard/web/flow.ts +12 -0
  28. package/src/adapters/dashboard/web/lanes.ts +11 -0
  29. package/src/adapters/dashboard/web/mechanisms/dreaming/panel.js +2 -1
  30. package/src/adapters/dashboard/web/mechanisms/emotional/panel.js +2 -2
  31. package/src/adapters/dashboard/web/mechanisms/episodic-semantic/panel.js +2 -1
  32. package/src/adapters/dashboard/web/mechanisms/index.js +2 -0
  33. package/src/adapters/dashboard/web/mechanisms/interference/index.js +8 -4
  34. package/src/adapters/dashboard/web/mechanisms/interference/panel.js +13 -0
  35. package/src/adapters/dashboard/web/mechanisms/prospective/panel.js +2 -1
  36. package/src/adapters/dashboard/web/narrate.ts +62 -4
  37. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +2 -4
  38. package/src/adapters/dashboard/web/pages/memories/index.js +6 -1
  39. package/src/adapters/dashboard/web/pages/memories/memories.css +43 -26
  40. package/src/adapters/dashboard/web/pages/memories/row.js +52 -15
  41. package/src/adapters/dashboard/web/pages/memories/sections/hold.js +112 -24
  42. package/src/adapters/dashboard/web/pages/memories/sections/list.js +3 -3
  43. package/src/adapters/dashboard/web/pages/memories/sections/search.js +75 -15
  44. package/src/adapters/dashboard/web/pages/memories/state.js +3 -2
  45. package/src/adapters/dashboard/web/pages/self/sections/dreams.js +2 -2
  46. package/src/adapters/dashboard/web/pages/self/sections/journal.js +7 -11
  47. package/src/adapters/dashboard/web/pages/self/sections/page.js +47 -17
  48. package/src/adapters/dashboard/web/pages/self/sections/wake.js +16 -5
  49. package/src/adapters/dashboard/web/shared/dates.js +55 -0
  50. package/src/adapters/dashboard/web/shared/memory-marks.css +1 -0
  51. package/src/adapters/dashboard/web/shared/memory-marks.js +23 -12
  52. package/src/adapters/dashboard/web/shared/memory-modal.js +15 -11
  53. package/src/adapters/dashboard/web/shared/widgets/feel-radar.js +8 -5
  54. package/src/adapters/dashboard/web/views/mechanism-panel.ts +39 -0
  55. package/src/adapters/dashboard/web/views/mechanisms.ts +9 -1
  56. package/src/adapters/dashboard/web/views/mind.ts +57 -17
  57. package/src/adapters/dashboard/web/views/search.ts +170 -58
  58. package/src/adapters/fired.ts +28 -0
  59. package/src/adapters/log/CONTRACT.md +70 -0
  60. package/src/adapters/log/INTERFACE-GAPS.md +15 -0
  61. package/src/adapters/log/NOTES.md +49 -0
  62. package/src/adapters/log/index.ts +420 -0
  63. package/src/adapters/mcp/CONTRACT.md +11 -0
  64. package/src/adapters/mcp/INTERFACE-GAPS.md +8 -0
  65. package/src/adapters/mcp/NOTES.md +34 -0
  66. package/src/adapters/mcp/bin/serve.ts +23 -1
  67. package/src/adapters/mcp/deliberate.ts +39 -2
  68. package/src/adapters/mcp/index.ts +5 -2
  69. package/src/adapters/mcp/server.ts +181 -43
  70. package/src/adapters/mcp/tools.ts +78 -11
  71. package/src/adapters/mcp/write-up.ts +5 -9
  72. package/src/adapters/mechanism-evidence.ts +28 -9
  73. package/src/adapters/sessions.ts +158 -172
  74. package/src/core/contradictions.ts +607 -0
  75. package/src/core/counterpart.ts +273 -26
  76. package/src/core/coverage/CONTRACT.md +77 -0
  77. package/src/core/coverage/INTERFACE-GAPS.md +46 -0
  78. package/src/core/coverage/NOTES.md +100 -0
  79. package/src/core/coverage/index.ts +660 -0
  80. package/src/core/coverage/tunables.ts +29 -0
  81. package/src/core/dream/CONTRACT.md +14 -8
  82. package/src/core/dream/INTERFACE-GAPS.md +6 -0
  83. package/src/core/dream/NOTES.md +27 -0
  84. package/src/core/dream/index.ts +90 -29
  85. package/src/core/dream/mind.ts +14 -13
  86. package/src/core/dream/reflect.ts +29 -0
  87. package/src/core/dream/tunables.ts +3 -0
  88. package/src/core/handoff/CONTRACT.md +8 -2
  89. package/src/core/handoff/NOTES.md +2 -0
  90. package/src/core/handoff/index.ts +100 -14
  91. package/src/core/physics/CONTRACT.md +23 -1
  92. package/src/core/physics/NOTES.md +10 -0
  93. package/src/core/physics/index.ts +78 -1
  94. package/src/core/prospective/CONTRACT.md +4 -1
  95. package/src/core/prospective/NOTES.md +16 -1
  96. package/src/core/prospective/index.ts +21 -2
  97. package/src/core/recall/CONTRACT.md +10 -0
  98. package/src/core/recall/INTERFACE-GAPS.md +7 -0
  99. package/src/core/recall/NOTES.md +11 -0
  100. package/src/core/recall/index.ts +20 -1
  101. package/src/core/recall/render.ts +15 -3
  102. package/src/core/recall/standing.ts +124 -0
  103. package/src/core/remember/CONTRACT.md +8 -8
  104. package/src/core/remember/NOTES.md +41 -0
  105. package/src/core/remember/index.ts +2 -5
  106. package/src/core/remember/owes.ts +80 -217
  107. package/src/core/remember/proposals.ts +31 -2
  108. package/src/core/revision.ts +60 -3
  109. package/src/core/schemas/CONTRACT.md +6 -3
  110. package/src/core/schemas/NOTES.md +15 -0
  111. package/src/core/self/CONTRACT.md +28 -13
  112. package/src/core/self/NOTES.md +86 -0
  113. package/src/core/self/behind.ts +89 -0
  114. package/src/core/self/briefing.ts +136 -5
  115. package/src/core/self/episodes.ts +43 -48
  116. package/src/core/self/identity.ts +42 -6
  117. package/src/core/self/index.ts +20 -2
  118. package/src/core/self/writer.ts +26 -26
  119. package/src/core/store/CONTRACT.md +12 -0
  120. package/src/core/store/NOTES.md +52 -0
  121. package/src/core/store/errors.ts +6 -0
  122. package/src/core/store/index.ts +339 -0
  123. package/src/core/store/operational.ts +248 -3
  124. package/src/core/store/owner-op-seam.ts +65 -1
  125. package/src/core/time.ts +60 -3
  126. package/src/core/types.ts +25 -0
  127. package/src/adapters/claude-code/page-writer.ts +0 -516
@@ -34,9 +34,11 @@ import {
34
34
  stanceOfMode,
35
35
  } from "../../scopes.js";
36
36
  import type { ScopeRead, ScopeVerdict } from "../../scopes.js";
37
- import { PAGE_WRITER_ENV, canonicalScope, readSession } from "../../sessions.js";
37
+ import { canonicalScope, isEntrypoint, readSession } from "../../sessions.js";
38
+ import { openLog } from "../../log/index.js";
39
+ import type { LogEvent, ProcessLog } from "../../log/index.js";
38
40
  import { resolveZone, todayIn } from "../../../core/time.js";
39
- import { loadConfig, withEmbedderDefault } from "../config.js";
41
+ import { TUNABLES, loadConfig, withEmbedderDefault } from "../config.js";
40
42
  import type { AdapterConfig } from "../config.js";
41
43
  import { HOOKS, openAdapter } from "../index.js";
42
44
  import { STOP_HUMAN_LINE, plainLine, withoutDream, withoutDreamNote, withoutPlain } from "../hooks.js";
@@ -56,18 +58,12 @@ import type { SaysSoHook, StandDownFault } from "../standdown.js";
56
58
  import { readTranscript } from "../transcript.js";
57
59
 
58
60
  /**
59
- * The host's own spelling of the one event that carries a notice. It appears
60
- * twice — as a key below, and as `hookSpecificOutput.hookEventName` in the JSON
61
- * form — and the host matches that field against its own name, so the two
62
- * spellings must be one constant.
61
+ * The host's own spellings of the two events that carry a notice — one
62
+ * constant each, shared with `hooks.ts`, which measures the same envelope
63
+ * before it decides what rides beside the wake (`../envelope.ts`).
63
64
  */
64
- export const HOST_SESSION_START = "SessionStart";
65
-
66
- /**
67
- * The same, for the second event that carries one since roadmap E
68
- * (2026-09-23): the update notice, at a prompt (`hostDelivery`).
69
- */
70
- export const HOST_USER_PROMPT_SUBMIT = "UserPromptSubmit";
65
+ import { HOST_SESSION_START, HOST_USER_PROMPT_SUBMIT, envelopeJson } from "../envelope.js";
66
+ export { HOST_SESSION_START, HOST_USER_PROMPT_SUBMIT } from "../envelope.js";
71
67
 
72
68
  /**
73
69
  * THE MOST STDOUT THIS HOOK MAY PRINT AS JSON, and why the number is 9,500.
@@ -89,7 +85,7 @@ export const HOST_USER_PROMPT_SUBMIT = "UserPromptSubmit";
89
85
  * of margin for the escaping, and the fallback is the plain wake: the notice is
90
86
  * what gets dropped, never the memory. `counterparts doctor` still prints it.
91
87
  */
92
- export const ENVELOPE_MAX_CHARS = 9500;
88
+ export const ENVELOPE_MAX_CHARS: number = TUNABLES.ENVELOPE_CHARS;
93
89
 
94
90
  /**
95
91
  * HOW A DUE STOP ASK LEAVES THIS PROCESS — ONE shape (owner, 2026-09-24).
@@ -398,12 +394,15 @@ export function toHookInput(
398
394
  // nothing (`hooks.ts#askAtStop`).
399
395
  ...(payload["stop_hook_active"] === true ? { reFired: true } : {}),
400
396
  ...(typeof payload["prompt"] === "string" ? { prompt: payload["prompt"] } : {}),
401
- // The host-mode page writer's headless child (`page-writer.ts` sets this):
402
- // no one reads its terminal, so it must not spend a plain reminder's beat.
403
- ...(((opts.env ?? process.env)[PAGE_WRITER_ENV] ?? "").trim().length > 0 ? { pageWriter: true } : {}),
404
397
  // The headless nightly run's child (`night-run.ts` sets this, 2026-09-29):
405
398
  // a windowless session our hooks keep QUIET — no capture, no asks.
406
399
  ...(((opts.env ?? process.env)[NIGHT_RUN_ENV] ?? "").trim().length > 0 ? { nightRun: true } : {}),
400
+ // HOW THE HOST WAS STARTED (review of #285, N2): the host sets
401
+ // `CLAUDE_CODE_ENTRYPOINT` at startup — `cli` at a terminal, `sdk-cli` for
402
+ // `claude -p` — and its hooks inherit it. Absent or odd: not carried.
403
+ ...(isEntrypoint((opts.env ?? process.env)["CLAUDE_CODE_ENTRYPOINT"])
404
+ ? { entrypoint: (opts.env ?? process.env)["CLAUDE_CODE_ENTRYPOINT"] as string }
405
+ : {}),
407
406
  // THE PERSON'S DAY (docs/time.md, 2026-09-25; UTC before). It dates the
408
407
  // hook's rows, the wake preface, the prospective "today" and the date the
409
408
  // boundary hands the lived clock — which is why the lived clock can see a
@@ -481,6 +480,8 @@ interface Said {
481
480
  * outcome this whole track cannot afford.
482
481
  */
483
482
  didWork: boolean;
483
+ /** This event's process log, once a configuration named a store (`adapters/log/`). */
484
+ log?: ProcessLog;
484
485
  }
485
486
 
486
487
  /**
@@ -567,6 +568,7 @@ async function main(): Promise<void> {
567
568
  // thing that changes on this branch is that two displayed events gain a
568
569
  // `systemMessage`.
569
570
  process.exitCode = 0;
571
+ said.log?.threw(err);
570
572
  const detail = err instanceof Error ? err.message : String(err);
571
573
  const remedy = `Set "dataDir" in ${choice.path}, or set ${DATA_DIR_ENV}.`;
572
574
  standDown(said, {
@@ -706,6 +708,12 @@ async function runHook(
706
708
  // running on an observer CONFIG are untouched by any of this.
707
709
  const config: AdapterConfig =
708
710
  verdict.mode === "observer" ? { ...loaded, observer: true } : loaded;
711
+ // THE PROCESS LOG (`adapters/log/`) is opened once the store has, below: a
712
+ // store this build refuses gets no lines (its stand-down marker, stderr and
713
+ // `systemMessage` say so), and every line lands where SessionStart prunes.
714
+ // Until then the adapter's events go through this closure to nothing.
715
+ let log: ProcessLog | null = null;
716
+ const toLog = (e: LogEvent): void => log?.event(e);
709
717
  const adapter = openAdapter(config, {
710
718
  command: process.execPath,
711
719
  args: ["run", RUNNER_PATH],
@@ -722,7 +730,21 @@ async function runHook(
722
730
  scope: verdict,
723
731
  ...(read.error === null ? {} : { scopeUnreadable: read.error }),
724
732
  ...(read.refused.length === 0 ? {} : { scopeRefused: read.refused.map((r) => r.key) }),
733
+ onEvent: toLog,
734
+ onCounterpartEvent: toLog,
725
735
  });
736
+ const opened = openLog({
737
+ dataDir: adapter.counterpart.store.dir,
738
+ proc: `hook:${name}`,
739
+ session: said.sessionId,
740
+ ...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
741
+ observer: config.observer === true,
742
+ });
743
+ log = opened;
744
+ said.log = opened;
745
+ // No start line at a prompt, the most frequent event: its end carries `ms`.
746
+ if (name !== "user-prompt-submit") opened.start();
747
+ let outcome = "ok";
726
748
  try {
727
749
  // ONE read of the transcript, shared by the hook and the notice: `toHookInput`
728
750
  // opens and parses the transcript file, and calling it twice would pay for
@@ -734,6 +756,7 @@ async function runHook(
734
756
  ...(loaded.timeZone === undefined ? {} : { timeZone: loaded.timeZone }),
735
757
  });
736
758
  const result = adapter.hook(name, input);
759
+ outcome = result.reason;
737
760
  // THE WORK HAPPENED. Recall was composed, the turn was captured, the session
738
761
  // record was written — whatever this event's job was, `adapter.hook` has
739
762
  // done it and swallowed its own failures doing so (§5 G2). Anything that
@@ -768,6 +791,12 @@ async function runHook(
768
791
  // "the terminal said nothing" and "there was nothing to say" are different
769
792
  // facts about the same morning (scar §2.4).
770
793
  if (delivery.dropped !== null) adapter.noteNoticeDropped(delivery.dropped);
794
+ // PAST THE HOST'S CAP EVEN IN PLAIN FORM: the host shows a preview. Said
795
+ // where a person can find it (the host's debug log), and on the ring.
796
+ if (delivery.overCap !== undefined) {
797
+ adapter.noteOverCap(delivery.overCap);
798
+ process.stderr.write(`[counterparts] adapter.envelope.overcap: ${JSON.stringify(delivery.overCap)}\n`);
799
+ }
771
800
  if (delivery.stdout.length > 0) {
772
801
  process.stdout.write(delivery.stdout);
773
802
  // Recorded, not inferred: a fault thrown after this point (the close in
@@ -793,6 +822,8 @@ async function runHook(
793
822
  } finally {
794
823
  adapter.counterpart.close();
795
824
  }
825
+ // A throw above never reaches this line: `main`'s handler writes it instead.
826
+ opened.end(outcome);
796
827
  }
797
828
 
798
829
  /** The two adapter doors `deliverTurn` needs — structural, so a test can
@@ -814,6 +845,12 @@ export interface UpdateNoticeDoors {
814
845
  claimDream?(input: HookInput, offer: DreamOffer): boolean;
815
846
  /** Claim the one-time line about `auto` set back to `ask` (`ClaudeCodeAdapter#claimDreamNote`). */
816
847
  claimDreamNote?(input: HookInput): boolean;
848
+ /**
849
+ * Record what this delivery left for later for want of ROOM — `plain`
850
+ * reminders (how many), the `dream` offer, the `update-notice`
851
+ * (`ClaudeCodeAdapter#noteGaveWay`). Absent: nothing is recorded.
852
+ */
853
+ noteGaveWay?(input: HookInput, part: string, count: number): void;
817
854
  }
818
855
 
819
856
  /**
@@ -882,6 +919,9 @@ export function deliverTurn(
882
919
  const beat = (x: PlainReminder): string => `${x.memoryId} ${x.windowKey} ${x.beat}`;
883
920
  const kept = new Set(claimed.map(beat));
884
921
  const shownPlain = due.filter((d) => kept.has(beat(d)));
922
+ // WHAT GAVE WAY, as delivered: the reminders the envelope had no room for
923
+ // (a lost claim race is not room, and is recorded by `claimPlain`).
924
+ if (fits < due.length) gaveWay(doors, input, "plain", due.length - fits);
885
925
  r = withoutPlain(r, due.filter((d) => !kept.has(beat(d))));
886
926
  if (shownPlain.length > 0) ordered = [shownPlain.map(plainLine).join("\n"), ...(notices ?? [])];
887
927
  }
@@ -904,8 +944,9 @@ export function deliverTurn(
904
944
  showDream = false;
905
945
  }
906
946
  }
907
- } else if (deferred === null) {
908
- deferred = probe.dropped;
947
+ } else {
948
+ if (deferred === null) deferred = probe.dropped;
949
+ gaveWay(doors, input, "dream", 1);
909
950
  }
910
951
  if (showDream) ordered = [...(ordered ?? []), told.notice];
911
952
  else if (told.offer !== null) r = withoutDream(r);
@@ -934,13 +975,25 @@ export function deliverTurn(
934
975
  const update = doors.updateNotice(input);
935
976
  if (update === null) return base;
936
977
  const carried = hostDelivery(name, r, payload, [...(ordered ?? []), update]);
937
- if (carried.dropped !== null) return { ...base, dropped: base.dropped ?? carried.dropped };
978
+ if (carried.dropped !== null) {
979
+ gaveWay(doors, input, "update-notice", 1);
980
+ return { ...base, dropped: base.dropped ?? carried.dropped };
981
+ }
938
982
  return doors.markUpdateNotice(input) ? carried : base;
939
983
  } catch {
940
984
  return base;
941
985
  }
942
986
  }
943
987
 
988
+ /** `doors.noteGaveWay`, fail-open: a record that cannot be made costs nothing. */
989
+ function gaveWay(doors: UpdateNoticeDoors, input: HookInput, part: string, count: number): void {
990
+ try {
991
+ doors.noteGaveWay?.(input, part, count);
992
+ } catch {
993
+ /* bookkeeping */
994
+ }
995
+ }
996
+
944
997
  /**
945
998
  * SessionStart's stamp on a session that OPENS, and nothing else: run AFTER the
946
999
  * wake is written (`main`), and swallowed if it throws — the stamp is
@@ -1000,6 +1053,24 @@ export interface Delivery {
1000
1053
  /** Non-null when a notice was left out to keep the wake whole — all of them,
1001
1054
  * or (with several) the lower ones that no longer fit. */
1002
1055
  readonly dropped: { readonly noticeChars: number; readonly envelopeChars: number; readonly limitChars: number } | null;
1056
+ /**
1057
+ * THE PLAIN FALLBACK, CHECKED (2026-09-29, audit item 9). Set when the plain
1058
+ * stdout this prints is itself past the host's cap (`HOST_OUTPUT_CHARS`), so
1059
+ * the host will show a preview in its place. A TRIPWIRE, not a cut: by here
1060
+ * the asks are already marked as delivered and this function cannot tell a
1061
+ * wake from an ask, so it reports and the caller records it. The adapter's
1062
+ * one budget per envelope is what keeps it from happening; what can still
1063
+ * reach it is a wake composed past the cap by a misconfigured budget.
1064
+ */
1065
+ readonly overCap?: { readonly chars: number; readonly limitChars: number };
1066
+ }
1067
+
1068
+ /** The plain form of an envelope, with the over-cap tripwire read. */
1069
+ function plainOut(out: string, dropped: Delivery["dropped"]): Delivery {
1070
+ const chars = out.length;
1071
+ return chars > TUNABLES.HOST_OUTPUT_CHARS
1072
+ ? { stdout: out, stderr: "", exitCode: 0, dropped, overCap: { chars, limitChars: TUNABLES.HOST_OUTPUT_CHARS } }
1073
+ : { stdout: out, stderr: "", exitCode: 0, dropped };
1003
1074
  }
1004
1075
 
1005
1076
  export function hostDelivery(
@@ -1024,11 +1095,7 @@ export function hostDelivery(
1024
1095
  (n): n is string => n !== null && n.length > 0,
1025
1096
  );
1026
1097
  if (name === "session-start" && notices.length > 0) {
1027
- const envelopeOf = (message: string): string =>
1028
- JSON.stringify({
1029
- systemMessage: message,
1030
- hookSpecificOutput: { hookEventName: HOST_SESSION_START, additionalContext: out },
1031
- });
1098
+ const envelopeOf = (message: string): string => envelopeJson(HOST_SESSION_START, message, out);
1032
1099
  // THE WAKE WINS. Over `ENVELOPE_MAX_CHARS` the host would replace this
1033
1100
  // whole string with a preview, the JSON would stop parsing, and the
1034
1101
  // session would start with no memory at all — a worse outcome than not
@@ -1048,7 +1115,7 @@ export function hostDelivery(
1048
1115
  envelopeChars: envelopeOf(notices.join("\n")).length,
1049
1116
  limitChars: ENVELOPE_MAX_CHARS,
1050
1117
  };
1051
- if (kept.length === 0) return { stdout: out, stderr: "", exitCode: 0, dropped };
1118
+ if (kept.length === 0) return plainOut(out, dropped);
1052
1119
  return { stdout: envelopeOf(kept.join("\n")), stderr: "", exitCode: 0, dropped };
1053
1120
  }
1054
1121
  // THE UPDATE NOTICE, AT A PROMPT (roadmap E, 2026-09-23) — the same
@@ -1068,16 +1135,11 @@ export function hostDelivery(
1068
1135
  : { hookSpecificOutput: { hookEventName: HOST_USER_PROMPT_SUBMIT, additionalContext: out } }),
1069
1136
  });
1070
1137
  if (envelope.length > ENVELOPE_MAX_CHARS) {
1071
- return {
1072
- stdout: out,
1073
- stderr: "",
1074
- exitCode: 0,
1075
- dropped: { noticeChars: message.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS },
1076
- };
1138
+ return plainOut(out, { noticeChars: message.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS });
1077
1139
  }
1078
1140
  return { stdout: envelope, stderr: "", exitCode: 0, dropped: null };
1079
1141
  }
1080
- return { stdout: out, stderr: "", exitCode: 0, dropped: null };
1142
+ return plainOut(out, null);
1081
1143
  }
1082
1144
  // The re-fire is refused twice on purpose: the adapter asks nothing on it, and
1083
1145
  // this channel would not carry it even if something did.
@@ -12,6 +12,7 @@
12
12
  * the ROW is how the next session hears of it.
13
13
  */
14
14
  import { implicitConfigRefusal, namedConfigRefusal, namedUnreadableRefusal } from "../../config-path.js";
15
+ import { openLog } from "../../log/index.js";
15
16
 
16
17
  import { NIGHT_KIND_ENV, NIGHT_RUN_ENV, openNightCounterpart, readKind, runNight } from "../night-run.js";
17
18
  import { isEntryPoint, pinnedScope, pinnedSession, runnerConfig, runnerConfigChoice } from "./runner.js";
@@ -31,16 +32,27 @@ async function main(): Promise<void> {
31
32
  }
32
33
  const run = (process.env[NIGHT_RUN_ENV] ?? "").trim();
33
34
  const session = pinnedSession();
35
+ // THE PROCESS LOG (`adapters/log/`): this process's stdio is discarded, so
36
+ // its start, its end and the run's state are written here.
37
+ const log = openLog({
38
+ dataDir: config.dataDir,
39
+ proc: "nightly",
40
+ session,
41
+ ...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
42
+ observer: config.observer === true,
43
+ });
44
+ log.start({ run: run.length > 0 ? run : null, kind: readKind(process.env[NIGHT_KIND_ENV]).kind });
34
45
  if (run.length === 0 || session === null || config.observer === true) {
35
46
  process.stderr.write("[counterparts] nightly run stood down: no run, no session, or an observer\n");
36
47
  // SAID WHERE IT CAN BE (review of #282, finding 4): a run the hook started
37
48
  // and this process will not carry is recorded `could-not-start`, so the
38
49
  // next prompt asks instead of waiting on a row that stays `started`.
39
50
  if (run.length > 0 && config.observer !== true) standDown(config, run, session ?? "", readKind(process.env[NIGHT_KIND_ENV]).kind);
51
+ log.end("stood-down", { run: run.length > 0 ? run : null });
40
52
  return;
41
53
  }
42
- await runNight({
43
- open: () => openNightCounterpart(config),
54
+ const out = await runNight({
55
+ open: () => openNightCounterpart(config, log.event),
44
56
  config,
45
57
  run,
46
58
  session,
@@ -48,6 +60,13 @@ async function main(): Promise<void> {
48
60
  kind: readKind(process.env[NIGHT_KIND_ENV]),
49
61
  configPath: choice.path,
50
62
  });
63
+ log.end(out.state, {
64
+ run: out.run,
65
+ why: out.reason,
66
+ detail: out.detail,
67
+ code: out.code,
68
+ parts: (out.parts ?? []).join(","),
69
+ });
51
70
  }
52
71
 
53
72
  /** One `could-not-start` row for a run this process stood down from. Never throws. */
@@ -29,7 +29,12 @@
29
29
  * 2026-09-04, `remember/fallback.ts`);
30
30
  * 2. the Hebbian flush;
31
31
  * 3. the sleep cycle, whose last content write is the wake briefing;
32
- * 3b. RAW TRANSCRIPT RETENTION (owner's ruling 2026-09-23): once per date —
32
+ * 3a. the wake's catch-up (2026-09-30): re-rendered again when the page was
33
+ * written or a write-up landed since its last render (`refreshWake`);
34
+ * 3b. WHAT IS NOT WRITTEN UP (2026-09-30): the coverage ledger's rows — a
35
+ * stretch owed, written up, lapsed — one per stretch per state
36
+ * (`core/coverage/`);
37
+ * 3c. RAW TRANSCRIPT RETENTION (owner's ruling 2026-09-23): once per date —
33
38
  * behind an `O_EXCL` latch under `spans/retention/` — a session's captured
34
39
  * text is deleted 7 days after it ended when it owes no write-up and the
35
40
  * registry does not hold it open (`remember/owes.ts` decides,
@@ -63,6 +68,7 @@ import { resolve } from "node:path";
63
68
  import { fileURLToPath } from "node:url";
64
69
 
65
70
  import { Counterpart, RUNNER_FAILED_EVENT } from "../../../core/counterpart.js";
71
+ import { recordCoverage } from "../../../core/coverage/index.js";
66
72
  import { RETENTION_EVENT, retentionRow, retentionRuns } from "../../../core/remember/index.js";
67
73
  import type { HostSessionEvidence, RetentionReport } from "../../../core/remember/index.js";
68
74
  // THE DELETING HALF, by path, and from this file alone (PR #189 review, B1):
@@ -72,6 +78,7 @@ import { pruneRetention } from "../../../core/remember/retention.js";
72
78
  import { dataDir, describeGuardRefusal } from "../../../core/store/index.js";
73
79
  import type { Store } from "../../../core/store/index.js";
74
80
  import { hostSessionEvidence, writeUpSources } from "../../sessions.js";
81
+ import { openLog } from "../../log/index.js";
75
82
 
76
83
  import {
77
84
  configLine,
@@ -87,8 +94,6 @@ import { loadConfig, withEmbedderDefault } from "../config.js";
87
94
  import type { AdapterConfig } from "../config.js";
88
95
  import { openEmbedder } from "../index.js";
89
96
  import type { LiveEmbedder } from "../embed-client.js";
90
- import { runPageWriter } from "../page-writer.js";
91
- import type { PageWriterStarter } from "../page-writer.js";
92
97
  import { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV } from "../spawn.js";
93
98
  import { backfillVectors, laggedSemantic } from "../vectors.js";
94
99
  import type { BackfillReport, LagReport } from "../vectors.js";
@@ -184,10 +189,9 @@ export const retentionHost: (store: Store) => (session: string) => HostSessionEv
184
189
  * (review n1, named rather than moved).
185
190
  *
186
191
  * What it may delete is decided by `remember/owes.ts` and nothing here: the
187
- * pacer's record (`self/episodes.ts#episodeFacts`), the handoff rows, and this
188
- * host's registry and ask rows (`retentionHost`) are the facts, and a session
189
- * that owes a write-up, or that the registry holds open, is never in any
190
- * request.
192
+ * coverage ledger (`core/coverage/`) and this host's registry
193
+ * (`retentionHost`) are the facts, and a session that owes a write-up, or that
194
+ * the registry holds open, is never in any request.
191
195
  */
192
196
  export function retentionJob(input: {
193
197
  counterpart: Counterpart;
@@ -201,14 +205,10 @@ export function retentionJob(input: {
201
205
  const store = counterpart.store;
202
206
  try {
203
207
  if (retentionRuns(store).some((r) => r.date === date)) return { ...none, reason: "already-ran" };
204
- const t = counterpart.self.tunables;
205
208
  // THE SAME SOURCES THE WRITE-UP READS (`sessions.ts#writeUpSources`), so
206
209
  // what this pass keeps as owed and what the next session is asked to write
207
210
  // up are one set, by construction rather than by two copies agreeing.
208
- const sources = writeUpSources(store, {
209
- turns: t.FIRST_ASK_TURNS,
210
- textBytes: t.FIRST_ASK_TEXT_BYTES,
211
- });
211
+ const sources = writeUpSources(store);
212
212
  // THE DATE IS VISIBLE FROM THE MOMENT IT IS HELD (re-review R7): a
213
213
  // `STARTED` row goes in as soon as the latch is taken, before anything is
214
214
  // planned, so a run the watchdog kills halfway leaves "started, never
@@ -299,11 +299,6 @@ export async function runOnce(input: {
299
299
  scope?: string;
300
300
  /** Injected so the whole vector path is provable without the weights. */
301
301
  embedder?: LiveEmbedder | null;
302
- /** The configuration file this process read, pinned onto the nightly page
303
- * writer's child so parent and child read one file rather than resolving two. */
304
- configPath?: string;
305
- /** Injected so `host` mode is provable without launching a host session. */
306
- startPageWriter?: PageWriterStarter;
307
302
  onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
308
303
  }): Promise<RunReport> {
309
304
  const { config } = input;
@@ -405,6 +400,17 @@ export async function runOnce(input: {
405
400
  carriedRows: report.carried?.rows ?? 0,
406
401
  sweep: "next-session",
407
402
  });
403
+ // 3a. THE WAKE CATCHES UP (2026-09-30): a page written or a write-up
404
+ // landed since the last render re-renders it now, not at the next lived
405
+ // day. After the cycle, whose own render already caught up to what was
406
+ // marked before it; nothing marked, nothing rendered.
407
+ // Its own try: a render that fails costs the refresh, and the mark stays.
408
+ try {
409
+ const wake = counterpart.refreshWake({ at: today });
410
+ if (wake.reason !== "current") emit("runner.wake", { reason: wake.reason, triggers: wake.triggers.join(","), bytes: wake.bytes });
411
+ } catch (err) {
412
+ noteFailure(counterpart, emit, err instanceof Error ? err.name : "UNKNOWN", "wake", today);
413
+ }
408
414
  result = { ran: true, reason: "ran", swept, minted, code: null, lag, backfill, snapshot: null, retention: null };
409
415
  } catch (err) {
410
416
  const code =
@@ -418,7 +424,22 @@ export async function runOnce(input: {
418
424
  noteFailure(counterpart, emit, code, "sessionEnd", today);
419
425
  result = { ran: false, reason: "failed", swept: 0, minted: 0, code, lag, backfill, snapshot: null, retention: null };
420
426
  } finally {
421
- // 3b. RETENTION — on the failed path as well as the good one (a day whose
427
+ // 3b. WHAT IS NOT WRITTEN UP (2026-09-30, `core/coverage/`): one row per
428
+ // stretch per state — owed, written up, lapsed — at every turn-end, keyless.
429
+ // Before retention, so a lapse is recorded while its pieces are there to
430
+ // count. Its own try: a ledger that will not read may not cost the rest.
431
+ try {
432
+ const host = hostSessionEvidence(counterpart.store);
433
+ const covered = recordCoverage(counterpart.spans, counterpart.store, {
434
+ now: counterpart.store.now(),
435
+ zone: counterpart.store.zone(),
436
+ host: (s) => ({ endedAt: host(s).endedAt }),
437
+ });
438
+ emit("runner.coverage", { ...covered });
439
+ } catch (err) {
440
+ emit("coverage.threw", { code: err instanceof Error ? err.name : "UNKNOWN" });
441
+ }
442
+ // 3c. RETENTION — on the failed path as well as the good one (a day whose
422
443
  // sweep broke still ages the week-old text of sessions that owe nothing),
423
444
  // and BEFORE the copy below, so the day's backup never carries raw text
424
445
  // past its week. Its own try: a retention pass may not cost the snapshot.
@@ -453,30 +474,6 @@ export async function runOnce(input: {
453
474
  } catch (err) {
454
475
  emit("snapshot.threw", { code: err instanceof Error ? err.name : "UNKNOWN" });
455
476
  }
456
- // 5. THE NIGHT'S PAGE WRITER, in `host` mode only (S2). Last, and inside
457
- // the `finally` beside the snapshot, for the same two reasons: it must run
458
- // on the failed path as well as the good one — a day whose sweep broke is
459
- // still a day that was lived — and it must run before the store closes, so
460
- // the outcome it reads is read through the same handle everything else
461
- // wrote through. It never throws (`page-writer.ts`), and on every other
462
- // mode it is one comparison and a return.
463
- try {
464
- const page = await runPageWriter({
465
- counterpart,
466
- config,
467
- ...(input.configPath === undefined ? {} : { configPath: input.configPath }),
468
- ...(input.startPageWriter === undefined ? {} : { start: input.startPageWriter }),
469
- // THE WORKER'S OWN WATCHDOG OUTRANKS THE WRITER'S. They are different
470
- // numbers (5 minutes here, 10 for the child by default) and without this
471
- // the worker would sit in this `finally` for twice the life it promises.
472
- ...(input.signal === undefined ? {} : { signal: input.signal }),
473
- });
474
- if (page.ran || page.outcome !== "skipped") {
475
- emit("runner.page-writer", { outcome: page.outcome, about: page.about, detail: page.detail });
476
- }
477
- } catch (err) {
478
- emit("page-writer.threw", { code: err instanceof Error ? err.name : "UNKNOWN" });
479
- }
480
477
  counterpart.close();
481
478
  }
482
479
  return { ...result, snapshot: snapshotReport, retention: retentionReport };
@@ -613,14 +610,28 @@ async function main(): Promise<void> {
613
610
  controller.abort();
614
611
  }, timeout);
615
612
  timer?.unref?.();
613
+ // THE PROCESS LOG (`adapters/log/`) — the one place this detached run's
614
+ // events outlive it, since its stdio goes nowhere.
615
+ const log = openLog({
616
+ dataDir: config.dataDir,
617
+ proc: "worker",
618
+ session: pinnedSession(),
619
+ ...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
620
+ observer: config.observer === true,
621
+ });
622
+ log.start();
616
623
  try {
617
- await runOnce({
624
+ const report = await runOnce({
618
625
  config,
619
626
  signal: controller.signal,
620
627
  ...(pinnedSession() === null ? {} : { session: pinnedSession() as string }),
621
628
  ...(pinnedScope() === null ? {} : { scope: pinnedScope() as string }),
622
- configPath: choice.path,
629
+ onEvent: (name, data) => log.event({ name, data }),
623
630
  });
631
+ log.end(report.reason, { swept: report.swept, minted: report.minted, code: report.code });
632
+ } catch (err) {
633
+ log.threw(err);
634
+ throw err;
624
635
  } finally {
625
636
  if (timer !== null) clearTimeout(timer);
626
637
  }