counterparts 0.3.6 → 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 (168) hide show
  1. package/CHANGELOG.md +258 -0
  2. package/docs/module-map.md +5 -1
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +138 -55
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +8 -3
  6. package/src/adapters/claude-code/NOTES.md +190 -0
  7. package/src/adapters/claude-code/bin/hook.ts +155 -33
  8. package/src/adapters/claude-code/bin/nightly.ts +95 -0
  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 +146 -69
  12. package/src/adapters/claude-code/doctor.ts +556 -70
  13. package/src/adapters/claude-code/envelope.ts +38 -0
  14. package/src/adapters/claude-code/hooks.ts +455 -59
  15. package/src/adapters/claude-code/index.ts +25 -18
  16. package/src/adapters/claude-code/night-run.ts +515 -0
  17. package/src/adapters/cli/CONTRACT.md +9 -0
  18. package/src/adapters/cli/commands.ts +286 -6
  19. package/src/adapters/cli/coverage.ts +100 -0
  20. package/src/adapters/cli/dream-core.ts +36 -6
  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 +84 -39
  27. package/src/adapters/dashboard/web/app.html +0 -3
  28. package/src/adapters/dashboard/web/flow.ts +12 -0
  29. package/src/adapters/dashboard/web/lanes.ts +11 -0
  30. package/src/adapters/dashboard/web/mechanisms/dreaming/panel.js +2 -1
  31. package/src/adapters/dashboard/web/mechanisms/emotional/panel.js +2 -2
  32. package/src/adapters/dashboard/web/mechanisms/episodic-semantic/panel.js +2 -1
  33. package/src/adapters/dashboard/web/mechanisms/index.js +2 -0
  34. package/src/adapters/dashboard/web/mechanisms/interference/index.js +8 -4
  35. package/src/adapters/dashboard/web/mechanisms/interference/panel.js +13 -0
  36. package/src/adapters/dashboard/web/mechanisms/prospective/panel.js +2 -1
  37. package/src/adapters/dashboard/web/narrate.ts +62 -4
  38. package/src/adapters/dashboard/web/pages/health/health.css +2 -0
  39. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +2 -4
  40. package/src/adapters/dashboard/web/pages/health/sections/mechanisms.js +9 -0
  41. package/src/adapters/dashboard/web/pages/home/home.css +7 -4
  42. package/src/adapters/dashboard/web/pages/home/index.js +4 -3
  43. package/src/adapters/dashboard/web/pages/home/sections/feel.js +9 -19
  44. package/src/adapters/dashboard/web/pages/home/sections/map.js +6 -5
  45. package/src/adapters/dashboard/web/pages/memories/index.js +35 -19
  46. package/src/adapters/dashboard/web/pages/memories/memories.css +72 -65
  47. package/src/adapters/dashboard/web/pages/memories/row.js +75 -25
  48. package/src/adapters/dashboard/web/pages/memories/sections/feel.js +13 -173
  49. package/src/adapters/dashboard/web/pages/memories/sections/hold.js +122 -36
  50. package/src/adapters/dashboard/web/pages/memories/sections/list.js +70 -36
  51. package/src/adapters/dashboard/web/pages/memories/sections/search.js +147 -90
  52. package/src/adapters/dashboard/web/pages/memories/sections/tools.js +5 -4
  53. package/src/adapters/dashboard/web/pages/memories/state.js +12 -5
  54. package/src/adapters/dashboard/web/pages/self/index.js +2 -0
  55. package/src/adapters/dashboard/web/pages/self/sections/dreams.js +2 -2
  56. package/src/adapters/dashboard/web/pages/self/sections/journal.js +7 -11
  57. package/src/adapters/dashboard/web/pages/self/sections/map.js +417 -116
  58. package/src/adapters/dashboard/web/pages/self/sections/page.js +47 -17
  59. package/src/adapters/dashboard/web/pages/self/sections/wake.js +16 -5
  60. package/src/adapters/dashboard/web/pages/self/self.css +23 -20
  61. package/src/adapters/dashboard/web/shared/dates.js +55 -0
  62. package/src/adapters/dashboard/web/shared/memory-marks.css +2 -4
  63. package/src/adapters/dashboard/web/shared/memory-marks.js +24 -27
  64. package/src/adapters/dashboard/web/shared/memory-modal.js +58 -33
  65. package/src/adapters/dashboard/web/shared/modal.css +5 -0
  66. package/src/adapters/dashboard/web/shared/voice.js +18 -0
  67. package/src/adapters/dashboard/web/shared/widgets/feel-radar.js +140 -0
  68. package/src/adapters/dashboard/web/views/archive-words.ts +1 -1
  69. package/src/adapters/dashboard/web/views/mechanism-panel.ts +39 -0
  70. package/src/adapters/dashboard/web/views/mechanisms.ts +9 -1
  71. package/src/adapters/dashboard/web/views/memories.ts +98 -7
  72. package/src/adapters/dashboard/web/views/memory-words.ts +29 -1
  73. package/src/adapters/dashboard/web/views/memory.ts +3 -2
  74. package/src/adapters/dashboard/web/views/mind.ts +57 -17
  75. package/src/adapters/dashboard/web/views/search.ts +170 -58
  76. package/src/adapters/fired.ts +29 -1
  77. package/src/adapters/log/CONTRACT.md +70 -0
  78. package/src/adapters/log/INTERFACE-GAPS.md +15 -0
  79. package/src/adapters/log/NOTES.md +49 -0
  80. package/src/adapters/log/index.ts +420 -0
  81. package/src/adapters/mcp/CONTRACT.md +11 -0
  82. package/src/adapters/mcp/INTERFACE-GAPS.md +8 -0
  83. package/src/adapters/mcp/NOTES.md +63 -0
  84. package/src/adapters/mcp/bin/serve.ts +23 -1
  85. package/src/adapters/mcp/deliberate.ts +119 -7
  86. package/src/adapters/mcp/index.ts +7 -2
  87. package/src/adapters/mcp/server.ts +296 -60
  88. package/src/adapters/mcp/tools.ts +116 -23
  89. package/src/adapters/mcp/write-up.ts +5 -9
  90. package/src/adapters/mechanism-evidence.ts +28 -9
  91. package/src/adapters/sessions.ts +158 -172
  92. package/src/core/associate/CONTRACT.md +33 -4
  93. package/src/core/associate/INTERFACE-GAPS.md +70 -0
  94. package/src/core/associate/NOTES.md +220 -1
  95. package/src/core/associate/buffer.ts +12 -9
  96. package/src/core/associate/contiguity.ts +81 -0
  97. package/src/core/associate/edges.ts +117 -6
  98. package/src/core/associate/index.ts +224 -7
  99. package/src/core/associate/pending.ts +7 -3
  100. package/src/core/associate/spread.ts +154 -69
  101. package/src/core/associate/tunables.ts +75 -5
  102. package/src/core/contradictions.ts +607 -0
  103. package/src/core/counterpart.ts +671 -34
  104. package/src/core/coverage/CONTRACT.md +77 -0
  105. package/src/core/coverage/INTERFACE-GAPS.md +46 -0
  106. package/src/core/coverage/NOTES.md +100 -0
  107. package/src/core/coverage/index.ts +660 -0
  108. package/src/core/coverage/tunables.ts +29 -0
  109. package/src/core/dream/CONTRACT.md +93 -21
  110. package/src/core/dream/INTERFACE-GAPS.md +6 -0
  111. package/src/core/dream/NOTES.md +94 -2
  112. package/src/core/dream/index.ts +1402 -236
  113. package/src/core/dream/mind.ts +123 -41
  114. package/src/core/dream/reflect.ts +321 -96
  115. package/src/core/dream/slices.ts +217 -0
  116. package/src/core/dream/tunables.ts +75 -12
  117. package/src/core/fit/CONTRACT.md +80 -0
  118. package/src/core/fit/INTERFACE-GAPS.md +16 -0
  119. package/src/core/fit/NOTES.md +37 -0
  120. package/src/core/fit/index.ts +499 -0
  121. package/src/core/handoff/CONTRACT.md +8 -2
  122. package/src/core/handoff/NOTES.md +2 -0
  123. package/src/core/handoff/index.ts +100 -14
  124. package/src/core/physics/CONTRACT.md +23 -1
  125. package/src/core/physics/NOTES.md +10 -0
  126. package/src/core/physics/index.ts +78 -1
  127. package/src/core/prospective/CONTRACT.md +4 -1
  128. package/src/core/prospective/NOTES.md +16 -1
  129. package/src/core/prospective/index.ts +21 -2
  130. package/src/core/recall/CONTRACT.md +23 -2
  131. package/src/core/recall/INTERFACE-GAPS.md +17 -0
  132. package/src/core/recall/NOTES.md +87 -0
  133. package/src/core/recall/activate.ts +320 -62
  134. package/src/core/recall/gate.ts +73 -4
  135. package/src/core/recall/index.ts +65 -10
  136. package/src/core/recall/render.ts +26 -3
  137. package/src/core/recall/session.ts +8 -0
  138. package/src/core/recall/standing.ts +124 -0
  139. package/src/core/recall/tunables.ts +30 -0
  140. package/src/core/remember/CONTRACT.md +8 -8
  141. package/src/core/remember/NOTES.md +41 -0
  142. package/src/core/remember/index.ts +2 -5
  143. package/src/core/remember/owes.ts +80 -217
  144. package/src/core/remember/proposals.ts +31 -2
  145. package/src/core/retrieval.ts +15 -6
  146. package/src/core/revision.ts +60 -3
  147. package/src/core/schemas/CONTRACT.md +6 -3
  148. package/src/core/schemas/NOTES.md +15 -0
  149. package/src/core/self/CONTRACT.md +28 -13
  150. package/src/core/self/NOTES.md +86 -0
  151. package/src/core/self/behind.ts +89 -0
  152. package/src/core/self/briefing.ts +136 -5
  153. package/src/core/self/episodes.ts +43 -48
  154. package/src/core/self/identity.ts +42 -6
  155. package/src/core/self/index.ts +20 -2
  156. package/src/core/self/writer.ts +26 -26
  157. package/src/core/sleep/NOTES.md +11 -0
  158. package/src/core/sleep/decay.ts +16 -1
  159. package/src/core/sleep/prune.ts +16 -1
  160. package/src/core/store/CONTRACT.md +12 -0
  161. package/src/core/store/NOTES.md +52 -0
  162. package/src/core/store/errors.ts +6 -0
  163. package/src/core/store/index.ts +465 -2
  164. package/src/core/store/operational.ts +248 -3
  165. package/src/core/store/owner-op-seam.ts +65 -1
  166. package/src/core/time.ts +60 -3
  167. package/src/core/types.ts +25 -0
  168. package/src/adapters/claude-code/page-writer.ts +0 -482
@@ -1659,3 +1659,193 @@ refusal or an unreadable block. The fix text no longer names `injectionBudgetByt
1659
1659
  host mode. The CONTRACT's old "amber while off and a page stands" was drift — the code
1660
1660
  had said green since the S2 review — and the CONTRACT now says what the code does.
1661
1661
  Doctor's Dreaming line leads with the setting.
1662
+
1663
+ ## 2026-09-29 — the ask the person sees; the headless nightly run
1664
+
1665
+ Working defaults, held lightly (dream NOTES has the why).
1666
+
1667
+ - **A — the ask.** `dreamLines` no longer claims an ask: it returns the offer as
1668
+ `HookResult.dream`, and `bin/hook.ts#deliverTurn` claims it (`claimDream`) only when the
1669
+ envelope carries the person's line, after the plain reminders and before the update
1670
+ notice. Without room, or on a lost race, the model's line is stripped (`withoutDream`)
1671
+ and the next prompt offers it again.
1672
+ - **B — where the spawn lives.** In the hook process, beside the worker's spawn, through
1673
+ the same `spawnDetached` and the same injected `spawner` — so the tests see the plan and
1674
+ nothing starts. The detached process is `bin/nightly.ts`, not the session-end worker
1675
+ (whose watchdog is five minutes; a run is about five). Its own planner, not `planSpawn`:
1676
+ `validateWatchdog` guards span claims this process never makes, and would refuse a
1677
+ 20-minute watchdog. Its outer `timeout` is set past the child's watchdog plus both kill
1678
+ graces, though in practice it is moot — `spawn`'s timeout lives in the hook process,
1679
+ which exits at once; the watchdog that matters is `runNight`'s, inside `bin/nightly.ts`.
1680
+ - **The watchdog** is `page-writer.ts#startChild`, now exported and shared (plus `cwd` and
1681
+ the OS spawn code): SIGTERM to the group, SIGKILL after `KILL_GRACE_MS`, stop waiting
1682
+ after `REAP_GRACE_MS`.
1683
+ - **Two opens, not one held open.** `runNight` opens the store to compose and record
1684
+ `started`, closes it for the run (the child's own MCP server writes meanwhile), and opens
1685
+ it again to record the end.
1686
+ - **`nightArgs` is required to start a run.** An adapter built without it (every test, any
1687
+ other host) records `could-not-start` / `runner` and asks instead — so no test can start
1688
+ a real `claude` by accident. `bin/hook.ts` passes `["run", NIGHTLY_PATH]`.
1689
+ - **The page writer's child is unchanged** apart from sharing `startChild`: its `pageWriter`
1690
+ flag still means only "no dream lines, no plain reminders". The quiet set is the night
1691
+ run's.
1692
+ - **Unproven until a real run** (the coordinator's, against a temp store): that a detached
1693
+ `claude -p` reaches the subscription login; that removing `CLAUDECODE` is enough for a
1694
+ nested start; whether `claude -p` fires UserPromptSubmit/Stop inside the child (the quiet
1695
+ flag covers both either way); and how long a real run takes against `NIGHT_RUN_MS`.
1696
+
1697
+ ## 2026-09-29, later — the fix round after the review of #282
1698
+
1699
+ (`docs/adversarial-review-pr282-2026-09-29.md`; owner decisions A–D the same day.)
1700
+
1701
+ - **Binding is pinned, not lazy (finding 1).** A session left open overnight is stale in the
1702
+ registry at the morning's first prompt — a prompt is not a boundary — and the child's
1703
+ fresh MCP server refused the lazy bind, which then read as "the MCP server is not
1704
+ registered". The launching session and its directory now ride on the child's
1705
+ environment and in its MCP server's own `--mcp-config` env, so `serve.ts` launches bound.
1706
+ - **Locked down (finding 3, owner decision B).** `--disallowedTools` (names read from the
1707
+ 2.1.284 build's own strings, since `--help` lists the flag but not the tool names;
1708
+ `MultiEdit` is not one there; `ToolSearch` deliberately left), `--strict-mcp-config` with
1709
+ a generated `--mcp-config` for counterparts only — derived from `mcp/bin/serve.ts` beside
1710
+ this file and `process.execPath`, i.e. THIS install's server, which is also the version
1711
+ the hooks run; it is not read from the user's `claude mcp` registration — a neutral
1712
+ working directory (the store's), and `--max-turns` (not in `--help`, but defined in that
1713
+ build: "Maximum number of agentic turns in non-interactive mode … only works with
1714
+ --print"). `--permission-mode default` is valid there: `manual` is its display name and
1715
+ maps to `default`.
1716
+ - **Fall back on everything that did not work (finding 4).** Timed out, failed, or never
1717
+ reported (a `started` row past its watchdog plus a grace — the row now carries the
1718
+ watchdog), having begun nothing: the next offer asks. `bin/nightly.ts` records its own
1719
+ stand-downs where the store opens, and `runNight` no longer reopens a store that would not
1720
+ open just to say so.
1721
+ - **Partial (finding 5, owner).** Parts on the row; `partial` in the record, doctor, and
1722
+ `counterparts dream` (the latest run under the setting; `--show` on its dream).
1723
+ - **The same-prompt fallback is an ask (finding 7)**, not a relaunch.
1724
+ - **Under way means under way (finding 10).** A `started` row inside its watchdog is
1725
+ `dreaming-now`, so a long `dreaming.timeoutMs` cannot let a second run start.
1726
+ - **`askLine` starts nothing, so it claims no headless offer (finding 9).**
1727
+ - **Owner decisions:** A — an explicit `auto` from before is reset to `ask` once, recorded
1728
+ and told; C — the hand-back stays "next prompt anywhere"; D — "no dreams" takes effect
1729
+ from the next run and says so.
1730
+ - **Still open:** the dashboard's vocabulary does not name `dream.night` or the two latch
1731
+ events yet (every reader guards unknown names). The host-mode page writer's child has the
1732
+ same exposure finding 3 describes and is not locked down here.
1733
+
1734
+ ## 2026-09-29 — doctor's Contradictions and Upgrade to v10 lines
1735
+
1736
+ `contradictionFindings`: green, always printed — over the last 7 lived days, how many
1737
+ pairs a dream flagged, how many settled and how (changed, corrected, open) and by whom
1738
+ (sessions, dreams, reflections, the page writer, the owner), how many undone; standing
1739
+ now, how many open and how many unsettled with both memories live (pointing at
1740
+ `counterparts settle`). `upgradeV10Findings`: what the v10 carry found (flags, pairs,
1741
+ already raised, still standing); silent on a store born at v10. Both are read-only table
1742
+ and meta reads. The awake raise line (`dreams.raiseLines`) now names the pair's id and
1743
+ the `note` settle.
1744
+
1745
+ After the review of #284: the Contradictions line counts a pair recorded while pressure
1746
+ builds on a core memory (`source` pressure) as flagged, beside a dream's flags.
1747
+
1748
+ ## 2026-09-29 — cleanup batch: host mode out, one envelope budget, short write-ups
1749
+
1750
+ Working defaults, held lightly.
1751
+
1752
+ - **Host mode removed.** `page-writer.ts` is gone; what the headless nightly run shared
1753
+ with it (the plan / starter shape, `startChild`, the kill and reap graces, the host
1754
+ command, the permission mode) moved unchanged to `child.ts`, with its own test
1755
+ (`test/child.test.ts`, the SIGTERM-ignoring stub included). Also gone: the worker's step
1756
+ 5 and its `configPath` / `startPageWriter` inputs, `COUNTERPARTS_PAGE_WRITER` (the
1757
+ MCP door no longer reads it, the night child no longer scrubs it), `HookInput.pageWriter`,
1758
+ `PAGE_WRITER_MS`, and doctor's host-mode fix text. Old configurations load:
1759
+ `pageWriter.mode: "host"`, `pageWriter.timeoutMs` and `pageWriter.command` go to the
1760
+ old-settings line (`retired`), never also to the block's `ignored`, and the mode reads
1761
+ `session`. The dashboard's why-map still carries the `host-mode` / `not-host-mode`
1762
+ labels; nothing produces them now (a dashboard follow-up).
1763
+ - **One size budget per envelope.** The order, first to go → last: SessionStart —
1764
+ notices → write-up pointer → first-launch question → plain reminders (to the first
1765
+ prompt, unclaimed) → the wake (never cut here). UserPromptSubmit — update notice → the
1766
+ turn's recall (`recallRoom`: the configured budget, or less when the clock, plain lines,
1767
+ dream lines and person lines leave less; the JSON envelope's 9,500 when a person-facing
1768
+ line rides the prompt) → the dream's lines → plain reminders and the clock. The audit's
1769
+ "`nowLine` and plain reminders aren't reserved" was already untrue at SessionStart (`sent`
1770
+ counted them since #271); what changed there is that the first-launch question is now
1771
+ measured against the host's cap, like the pointer, instead of the reported injection
1772
+ budget — a second ceiling. The dream's lines are reserved, not shed, because they are
1773
+ claimed when composed (a hand-back, a carried share, a raise line); shedding them after
1774
+ the claim would lose them. `adapter.envelope.gave-way` names what gave way.
1775
+ - **The fallback is a tripwire.** `hostDelivery`'s plain form is now measured against
1776
+ `HOST_OUTPUT_CHARS`; past it the delivery carries `overCap`, the hook records
1777
+ `adapter.envelope.overcap` and prints it on stderr. It does not cut: by then the asks are
1778
+ marked, and the pure function cannot tell a wake from an ask. What can still reach it
1779
+ is a wake composed past the cap by a misconfigured budget.
1780
+ - **Short write-ups.** The pointer offers a session under the first-ask threshold a
1781
+ one-line write-up (`WRITE_UP_SHORT_LINE`). Order: a full debt not yet pointed at today,
1782
+ then short ones, then a full one already pointed at today — a plain "full before short"
1783
+ would let one unwritten full session hold every short one back for ever. A short debt is
1784
+ offered only for a session the registry knows, so the unbound MCP server's shared `mcp`
1785
+ id is passed by; it is not in doctor's awaiting count (it ages out in a week, and
1786
+ `WRITE_UP_WAIT_DAYS` is 3, so counting it would turn doctor amber for a debt that clears
1787
+ itself).
1788
+ - **Unproven:** how often short pointers fire on the owner's machine (every quick session,
1789
+ including any `claude` sessions other tools start in a project with hooks on, now owes
1790
+ one line); whether one-line answers are worth the pointer's room.
1791
+
1792
+ ## 2026-09-29, later — the fix round after the review of #285
1793
+
1794
+ (`docs/adversarial-review-pr285-2026-09-29.md`; the probes are regression tests now.)
1795
+
1796
+ - **S1, the short write-up waits for the whole store.** The allowance is one count for the
1797
+ store, so a short debt is offered only when no full debt in ANY project is waiting and
1798
+ not yet pointed at today (`owedWriteUps`' `fullFirst`). Named cost: a full debt in a
1799
+ project nobody reopens holds every short one back; doctor turns amber on it after
1800
+ `WRITE_UP_WAIT_DAYS`, and the short ones age out with their week, as before.
1801
+ - **S2, the SessionStart order is real now.** A reminder reaches the person only in the
1802
+ JSON form, so when one is due and fits beside the wake in that form, the question and the
1803
+ pointer are measured against it (`EnvelopeRoom`, `envelope.ts` — the one envelope shape
1804
+ both `hooks.ts` and `bin/hook.ts` use). Measured: on a 9,000-byte wake of ordinary
1805
+ lines the JSON form of the wake and one reminder is already past 9,500, so on the
1806
+ owner's near-full wake a reminder cannot be shown at SessionStart whatever the asks do;
1807
+ it moves to the first prompt, which was already the behaviour, and the asks use the plain
1808
+ room. The ordering shows on a smaller wake (tested by walking wake sizes through the real
1809
+ `deliverTurn`). `adapter.envelope.gave-way` is now recorded where the giving way
1810
+ happens: each ask's deferral (`question`, `pointer`) and the delivery (`plain`, `dream`,
1811
+ `update-notice`, through the `noteGaveWay` door). The adapter no longer guesses it.
1812
+ - **M2, recall's room is measured.** In the JSON form, `recallRoom` measures the escaped
1813
+ envelope of the clock, the context and the person's lines, keys included. The one
1814
+ estimate left is recall's own escaping (`ENVELOPE_ESCAPE_RESERVE`, 200): its text does
1815
+ not exist when its budget is set, and composing twice would spend its fires twice. Plain
1816
+ stdout reserves nothing.
1817
+ - **M3, doctor names the cause.** A deferred pointer's record carries `beside` (the
1818
+ question, the reminders) and `limit`; doctor says "the wake and the first-launch question
1819
+ left …" and advises lowering `injectionBudgetBytes` only if it keeps happening.
1820
+ - **N2, entrypoints.** Read from the 2.1.285 host binary (strings, not docs): the host sets
1821
+ `CLAUDE_CODE_ENTRYPOINT` at startup — `cli` for a terminal session, `sdk-cli` when the
1822
+ start is non-interactive (`-p`/`--print`, `--init-only`, `--sdk-url`, or stdout not a
1823
+ TTY), `sdk-ts` / `sdk-py` from the Agent SDK, `mcp` for `claude mcp serve`,
1824
+ `claude-code-github-action` under `CLAUDE_CODE_ACTION`; an inherited `cli` becomes
1825
+ `sdk-cli` for a non-interactive start. This session's own Bash environment carries
1826
+ `CLAUDE_CODE_ENTRYPOINT=cli`, so the host exports it to children. What is NOT verified:
1827
+ a hook process's environment on a real `claude -p` run (running one here would fire the
1828
+ owner's live hooks). The hook records the value on the session's registry record; a
1829
+ short debt whose entrypoint is one of the five non-interactive names is not offered.
1830
+ Unknown or absent reads as a person's. A long `claude -p` session still owes a full
1831
+ write-up; only the short offer is skipped.
1832
+ - **N1** (the first-launch question can now fit beside a full wake): kept as built, on
1833
+ Mike's word — once per session in each unscoped directory until he answers there, the
1834
+ original G41 design.
1835
+
1836
+ ## 2026-09-30 — the wake keeps up (self NOTES §30)
1837
+
1838
+ - **The worker** calls `Counterpart.refreshWake({ at: today })` after its cycle (step 3a in
1839
+ `bin/runner.ts`), in its own try: nothing marked, nothing rendered; a failure is a
1840
+ `runner.failed` row with `step: "wake"` and the mark stays. The re-fired Stop after a
1841
+ session answers the ask still spawns a worker (`stop()`: `askAtStop` is skipped, the
1842
+ spawn is not), which is what catches a write-up; tested.
1843
+ - **The nightly process** refreshes with `trigger: "run-end"` after the child returns,
1844
+ whatever the run's state, in the `finally` of the store read in `runNight`, before the
1845
+ run's row is written. `openNightCounterpart` already carried the host's budget; a config
1846
+ without one refuses the render, as `rebrief` does. The child is quiet, so no turn-end of
1847
+ its own follows the page it wrote — the run's end is the trigger that matters under
1848
+ `auto`, where the day's first worker renders before the writer writes (tested with a
1849
+ `start` that runs the worker first).
1850
+ - **Delivery.** The delivery check compares each session's wake with the sentinel recorded
1851
+ at ITS start, so a session that woke before a rebuild still reads `delivered` (tested).
@@ -34,14 +34,18 @@ 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
- import { STOP_HUMAN_LINE, plainLine, withoutPlain } from "../hooks.js";
44
+ import { STOP_HUMAN_LINE, plainLine, withoutDream, withoutDreamNote, withoutPlain } from "../hooks.js";
43
45
  import type { PlainReminder } from "../../../core/counterpart.js";
44
- import type { HookInput, HookName } from "../hooks.js";
46
+ import type { DreamTold, HookInput, HookName } from "../hooks.js";
47
+ import { NIGHT_RUN_ENV } from "../night-run.js";
48
+ import type { DreamOffer } from "../../../core/dream/index.js";
45
49
  import {
46
50
  CONFIG_REFUSED,
47
51
  CONFIG_UNREADABLE,
@@ -54,18 +58,12 @@ import type { SaysSoHook, StandDownFault } from "../standdown.js";
54
58
  import { readTranscript } from "../transcript.js";
55
59
 
56
60
  /**
57
- * The host's own spelling of the one event that carries a notice. It appears
58
- * twice — as a key below, and as `hookSpecificOutput.hookEventName` in the JSON
59
- * form — and the host matches that field against its own name, so the two
60
- * 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`).
61
64
  */
62
- export const HOST_SESSION_START = "SessionStart";
63
-
64
- /**
65
- * The same, for the second event that carries one since roadmap E
66
- * (2026-09-23): the update notice, at a prompt (`hostDelivery`).
67
- */
68
- 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";
69
67
 
70
68
  /**
71
69
  * THE MOST STDOUT THIS HOOK MAY PRINT AS JSON, and why the number is 9,500.
@@ -87,7 +85,7 @@ export const HOST_USER_PROMPT_SUBMIT = "UserPromptSubmit";
87
85
  * of margin for the escaping, and the fallback is the plain wake: the notice is
88
86
  * what gets dropped, never the memory. `counterparts doctor` still prints it.
89
87
  */
90
- export const ENVELOPE_MAX_CHARS = 9500;
88
+ export const ENVELOPE_MAX_CHARS: number = TUNABLES.ENVELOPE_CHARS;
91
89
 
92
90
  /**
93
91
  * HOW A DUE STOP ASK LEAVES THIS PROCESS — ONE shape (owner, 2026-09-24).
@@ -145,6 +143,8 @@ export const CONFIG_PATH = defaultConfigPath();
145
143
  /** The worker script this hook's spawn runs. Resolved from THIS file's location,
146
144
  * never from a working directory the host chose. */
147
145
  export const RUNNER_PATH = fileURLToPath(new URL("./runner.ts", import.meta.url));
146
+ /** The headless nightly run's own process (2026-09-29, `night-run.ts`). */
147
+ export const NIGHTLY_PATH = fileURLToPath(new URL("./nightly.ts", import.meta.url));
148
148
 
149
149
  async function readStdin(): Promise<string> {
150
150
  const chunks: Buffer[] = [];
@@ -394,9 +394,15 @@ export function toHookInput(
394
394
  // nothing (`hooks.ts#askAtStop`).
395
395
  ...(payload["stop_hook_active"] === true ? { reFired: true } : {}),
396
396
  ...(typeof payload["prompt"] === "string" ? { prompt: payload["prompt"] } : {}),
397
- // The host-mode page writer's headless child (`page-writer.ts` sets this):
398
- // no one reads its terminal, so it must not spend a plain reminder's beat.
399
- ...(((opts.env ?? process.env)[PAGE_WRITER_ENV] ?? "").trim().length > 0 ? { pageWriter: true } : {}),
397
+ // The headless nightly run's child (`night-run.ts` sets this, 2026-09-29):
398
+ // a windowless session our hooks keep QUIET — no capture, no asks.
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
+ : {}),
400
406
  // THE PERSON'S DAY (docs/time.md, 2026-09-25; UTC before). It dates the
401
407
  // hook's rows, the wake preface, the prospective "today" and the date the
402
408
  // boundary hands the lived clock — which is why the lived clock can see a
@@ -474,6 +480,8 @@ interface Said {
474
480
  * outcome this whole track cannot afford.
475
481
  */
476
482
  didWork: boolean;
483
+ /** This event's process log, once a configuration named a store (`adapters/log/`). */
484
+ log?: ProcessLog;
477
485
  }
478
486
 
479
487
  /**
@@ -560,6 +568,7 @@ async function main(): Promise<void> {
560
568
  // thing that changes on this branch is that two displayed events gain a
561
569
  // `systemMessage`.
562
570
  process.exitCode = 0;
571
+ said.log?.threw(err);
563
572
  const detail = err instanceof Error ? err.message : String(err);
564
573
  const remedy = `Set "dataDir" in ${choice.path}, or set ${DATA_DIR_ENV}.`;
565
574
  standDown(said, {
@@ -699,9 +708,16 @@ async function runHook(
699
708
  // running on an observer CONFIG are untouched by any of this.
700
709
  const config: AdapterConfig =
701
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);
702
717
  const adapter = openAdapter(config, {
703
718
  command: process.execPath,
704
719
  args: ["run", RUNNER_PATH],
720
+ nightArgs: ["run", NIGHTLY_PATH],
705
721
  // WHICH FILE THIS RUN READ, carried into the adapter so it can be RECORDED:
706
722
  // a hook cannot print to the owner (its stdout is the model's context), so
707
723
  // the answer goes into the session registry record and the event ring
@@ -714,7 +730,21 @@ async function runHook(
714
730
  scope: verdict,
715
731
  ...(read.error === null ? {} : { scopeUnreadable: read.error }),
716
732
  ...(read.refused.length === 0 ? {} : { scopeRefused: read.refused.map((r) => r.key) }),
733
+ onEvent: toLog,
734
+ onCounterpartEvent: toLog,
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,
717
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";
718
748
  try {
719
749
  // ONE read of the transcript, shared by the hook and the notice: `toHookInput`
720
750
  // opens and parses the transcript file, and calling it twice would pay for
@@ -726,6 +756,7 @@ async function runHook(
726
756
  ...(loaded.timeZone === undefined ? {} : { timeZone: loaded.timeZone }),
727
757
  });
728
758
  const result = adapter.hook(name, input);
759
+ outcome = result.reason;
729
760
  // THE WORK HAPPENED. Recall was composed, the turn was captured, the session
730
761
  // record was written — whatever this event's job was, `adapter.hook` has
731
762
  // done it and swallowed its own failures doing so (§5 G2). Anything that
@@ -760,6 +791,12 @@ async function runHook(
760
791
  // "the terminal said nothing" and "there was nothing to say" are different
761
792
  // facts about the same morning (scar §2.4).
762
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
+ }
763
800
  if (delivery.stdout.length > 0) {
764
801
  process.stdout.write(delivery.stdout);
765
802
  // Recorded, not inferred: a fault thrown after this point (the close in
@@ -785,6 +822,8 @@ async function runHook(
785
822
  } finally {
786
823
  adapter.counterpart.close();
787
824
  }
825
+ // A throw above never reaches this line: `main`'s handler writes it instead.
826
+ opened.end(outcome);
788
827
  }
789
828
 
790
829
  /** The two adapter doors `deliverTurn` needs — structural, so a test can
@@ -798,6 +837,20 @@ export interface UpdateNoticeDoors {
798
837
  * claimed, so nothing is shown and every one waits for a later turn.
799
838
  */
800
839
  claimPlain?(input: HookInput, due: readonly PlainReminder[]): readonly PlainReminder[];
840
+ /**
841
+ * Claim the day's dream line this delivery is certainly about to show
842
+ * (`ClaudeCodeAdapter#claimDream`). Absent: nothing can be claimed, so the
843
+ * line is not shown and waits for a later prompt.
844
+ */
845
+ claimDream?(input: HookInput, offer: DreamOffer): boolean;
846
+ /** Claim the one-time line about `auto` set back to `ask` (`ClaudeCodeAdapter#claimDreamNote`). */
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;
801
854
  }
802
855
 
803
856
  /**
@@ -828,6 +881,8 @@ export function deliverTurn(
828
881
  ask: string | null;
829
882
  notices?: readonly string[];
830
883
  plain?: readonly PlainReminder[];
884
+ dream?: DreamTold;
885
+ dreamNote?: { notice: string; context: string };
831
886
  },
832
887
  payload: Record<string, unknown>,
833
888
  /** SessionStart's priority-ordered notices (after any plain reminders), or
@@ -864,9 +919,55 @@ export function deliverTurn(
864
919
  const beat = (x: PlainReminder): string => `${x.memoryId} ${x.windowKey} ${x.beat}`;
865
920
  const kept = new Set(claimed.map(beat));
866
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);
867
925
  r = withoutPlain(r, due.filter((d) => !kept.has(beat(d))));
868
926
  if (shownPlain.length > 0) ordered = [shownPlain.map(plainLine).join("\n"), ...(notices ?? [])];
869
927
  }
928
+ // THE DAY'S DREAM LINE (2026-09-29), after the plain reminders and under
929
+ // their rule: an ask is CLAIMED only once the envelope is known to carry the
930
+ // person's line, and without room it waits — its model line stripped too, so
931
+ // the model never answers a question the person was not shown. A line whose
932
+ // day is already claimed (the headless run has started) keeps its model line
933
+ // and only loses the terminal one.
934
+ const told = r.dream;
935
+ if (told !== undefined) {
936
+ const probe = hostDelivery(name, r, payload, [...(ordered ?? []), told.notice]);
937
+ let showDream = false;
938
+ if (probe.dropped === null) {
939
+ if (told.offer === null) showDream = true;
940
+ else {
941
+ try {
942
+ showDream = doors.claimDream?.(input, told.offer) ?? false;
943
+ } catch {
944
+ showDream = false;
945
+ }
946
+ }
947
+ } else {
948
+ if (deferred === null) deferred = probe.dropped;
949
+ gaveWay(doors, input, "dream", 1);
950
+ }
951
+ if (showDream) ordered = [...(ordered ?? []), told.notice];
952
+ else if (told.offer !== null) r = withoutDream(r);
953
+ }
954
+ // THE ONE-TIME RESET LINE (owner decision A), under the same rule.
955
+ const note = r.dreamNote;
956
+ if (note !== undefined) {
957
+ const probe = hostDelivery(name, r, payload, [...(ordered ?? []), note.notice]);
958
+ let shownNote = false;
959
+ if (probe.dropped === null) {
960
+ try {
961
+ shownNote = doors.claimDreamNote?.(input) ?? false;
962
+ } catch {
963
+ shownNote = false;
964
+ }
965
+ } else if (deferred === null) {
966
+ deferred = probe.dropped;
967
+ }
968
+ if (shownNote) ordered = [...(ordered ?? []), note.notice];
969
+ else r = withoutDreamNote(r);
970
+ }
870
971
  const shown = hostDelivery(name, r, payload, ordered);
871
972
  const base = shown.dropped === null && deferred !== null ? { ...shown, dropped: deferred } : shown;
872
973
  if (name !== "user-prompt-submit") return base;
@@ -874,13 +975,25 @@ export function deliverTurn(
874
975
  const update = doors.updateNotice(input);
875
976
  if (update === null) return base;
876
977
  const carried = hostDelivery(name, r, payload, [...(ordered ?? []), update]);
877
- 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
+ }
878
982
  return doors.markUpdateNotice(input) ? carried : base;
879
983
  } catch {
880
984
  return base;
881
985
  }
882
986
  }
883
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
+
884
997
  /**
885
998
  * SessionStart's stamp on a session that OPENS, and nothing else: run AFTER the
886
999
  * wake is written (`main`), and swallowed if it throws — the stamp is
@@ -940,6 +1053,24 @@ export interface Delivery {
940
1053
  /** Non-null when a notice was left out to keep the wake whole — all of them,
941
1054
  * or (with several) the lower ones that no longer fit. */
942
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 };
943
1074
  }
944
1075
 
945
1076
  export function hostDelivery(
@@ -964,11 +1095,7 @@ export function hostDelivery(
964
1095
  (n): n is string => n !== null && n.length > 0,
965
1096
  );
966
1097
  if (name === "session-start" && notices.length > 0) {
967
- const envelopeOf = (message: string): string =>
968
- JSON.stringify({
969
- systemMessage: message,
970
- hookSpecificOutput: { hookEventName: HOST_SESSION_START, additionalContext: out },
971
- });
1098
+ const envelopeOf = (message: string): string => envelopeJson(HOST_SESSION_START, message, out);
972
1099
  // THE WAKE WINS. Over `ENVELOPE_MAX_CHARS` the host would replace this
973
1100
  // whole string with a preview, the JSON would stop parsing, and the
974
1101
  // session would start with no memory at all — a worse outcome than not
@@ -988,7 +1115,7 @@ export function hostDelivery(
988
1115
  envelopeChars: envelopeOf(notices.join("\n")).length,
989
1116
  limitChars: ENVELOPE_MAX_CHARS,
990
1117
  };
991
- if (kept.length === 0) return { stdout: out, stderr: "", exitCode: 0, dropped };
1118
+ if (kept.length === 0) return plainOut(out, dropped);
992
1119
  return { stdout: envelopeOf(kept.join("\n")), stderr: "", exitCode: 0, dropped };
993
1120
  }
994
1121
  // THE UPDATE NOTICE, AT A PROMPT (roadmap E, 2026-09-23) — the same
@@ -1008,16 +1135,11 @@ export function hostDelivery(
1008
1135
  : { hookSpecificOutput: { hookEventName: HOST_USER_PROMPT_SUBMIT, additionalContext: out } }),
1009
1136
  });
1010
1137
  if (envelope.length > ENVELOPE_MAX_CHARS) {
1011
- return {
1012
- stdout: out,
1013
- stderr: "",
1014
- exitCode: 0,
1015
- dropped: { noticeChars: message.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS },
1016
- };
1138
+ return plainOut(out, { noticeChars: message.length, envelopeChars: envelope.length, limitChars: ENVELOPE_MAX_CHARS });
1017
1139
  }
1018
1140
  return { stdout: envelope, stderr: "", exitCode: 0, dropped: null };
1019
1141
  }
1020
- return { stdout: out, stderr: "", exitCode: 0, dropped: null };
1142
+ return plainOut(out, null);
1021
1143
  }
1022
1144
  // The re-fire is refused twice on purpose: the adapter asks nothing on it, and
1023
1145
  // this channel would not carry it even if something did.
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * THE HEADLESS NIGHTLY RUN'S OWN PROCESS (2026-09-29) — started DETACHED by the
4
+ * hook when the dreaming setting is `auto` (`night-run.ts#planNightRunner`),
5
+ * with a pinned environment: the data dir and configuration the hook read, the
6
+ * session the run is attributed to and its directory, the run's id and what it
7
+ * is (`NIGHT_RUN_ENV`, `NIGHT_KIND_ENV`).
8
+ *
9
+ * It composes the launch prompt from the store, starts `claude -p` with it on
10
+ * stdin, waits under the run's watchdog, and records what became of the run —
11
+ * then exits 0 on every path. Nothing about a failed run may reach the host;
12
+ * the ROW is how the next session hears of it.
13
+ */
14
+ import { implicitConfigRefusal, namedConfigRefusal, namedUnreadableRefusal } from "../../config-path.js";
15
+ import { openLog } from "../../log/index.js";
16
+
17
+ import { NIGHT_KIND_ENV, NIGHT_RUN_ENV, openNightCounterpart, readKind, runNight } from "../night-run.js";
18
+ import { isEntryPoint, pinnedScope, pinnedSession, runnerConfig, runnerConfigChoice } from "./runner.js";
19
+
20
+ async function main(): Promise<void> {
21
+ const choice = runnerConfigChoice();
22
+ const refusal = namedConfigRefusal(choice) ?? implicitConfigRefusal(choice);
23
+ if (refusal !== null) {
24
+ process.stderr.write(`[counterparts] nightly run stood down: ${refusal}\n`);
25
+ return;
26
+ }
27
+ const { config, reason } = runnerConfig(choice.path);
28
+ const unreadable = namedUnreadableRefusal(choice, reason);
29
+ if (unreadable !== null) {
30
+ process.stderr.write(`[counterparts] nightly run stood down: ${unreadable}\n`);
31
+ return;
32
+ }
33
+ const run = (process.env[NIGHT_RUN_ENV] ?? "").trim();
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 });
45
+ if (run.length === 0 || session === null || config.observer === true) {
46
+ process.stderr.write("[counterparts] nightly run stood down: no run, no session, or an observer\n");
47
+ // SAID WHERE IT CAN BE (review of #282, finding 4): a run the hook started
48
+ // and this process will not carry is recorded `could-not-start`, so the
49
+ // next prompt asks instead of waiting on a row that stays `started`.
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 });
52
+ return;
53
+ }
54
+ const out = await runNight({
55
+ open: () => openNightCounterpart(config, log.event),
56
+ config,
57
+ run,
58
+ session,
59
+ scope: pinnedScope() ?? "",
60
+ kind: readKind(process.env[NIGHT_KIND_ENV]),
61
+ configPath: choice.path,
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
+ });
70
+ }
71
+
72
+ /** One `could-not-start` row for a run this process stood down from. Never throws. */
73
+ function standDown(config: Parameters<typeof openNightCounterpart>[0], run: string, session: string, kind: "night" | "reflection"): void {
74
+ try {
75
+ const c = openNightCounterpart(config);
76
+ try {
77
+ const now = c.store.now();
78
+ c.dreams.recordNightRun({ run, date: c.store.today(), state: "could-not-start", kind, session, startedAt: now, endedAt: now, reason: "refused", detail: session.length === 0 ? "NO_SESSION" : "STOOD_DOWN", code: null, dream: null, reflection: null });
79
+ } finally {
80
+ c.close();
81
+ }
82
+ } catch {
83
+ /* a store that will not open: the row stays `started` and reads as lost later */
84
+ }
85
+ }
86
+
87
+ if (isEntryPoint(process.argv[1], import.meta.url)) {
88
+ void main().then(
89
+ () => process.exit(0),
90
+ (err: unknown) => {
91
+ process.stderr.write(`[counterparts] nightly run stood down: ${err instanceof Error ? err.message : String(err)}\n`);
92
+ process.exit(0);
93
+ },
94
+ );
95
+ }