counterparts 0.3.13 → 0.3.14

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 (84) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/package.json +1 -1
  3. package/src/adapters/claude-code/bin/hook.mjs +4 -2
  4. package/src/adapters/claude-code/bin/hook.ts +11 -4
  5. package/src/adapters/claude-code/bin/nightly.ts +5 -1
  6. package/src/adapters/claude-code/bin/runner.ts +11 -3
  7. package/src/adapters/claude-code/doctor.ts +69 -5
  8. package/src/adapters/claude-code/embed-client.ts +3 -0
  9. package/src/adapters/cli/bin/counterparts.mjs +4 -2
  10. package/src/adapters/cli/bin/counterparts.ts +11 -3
  11. package/src/adapters/cli/commands.ts +65 -23
  12. package/src/adapters/cli/index.ts +1 -0
  13. package/src/adapters/cli/install.ts +22 -9
  14. package/src/adapters/cli/settle.ts +39 -2
  15. package/src/adapters/cli/wire.ts +4 -0
  16. package/src/adapters/config.ts +29 -1
  17. package/src/adapters/dashboard/NOTES.md +33 -0
  18. package/src/adapters/dashboard/bin/dashboard.mjs +4 -2
  19. package/src/adapters/dashboard/bin/dashboard.ts +11 -3
  20. package/src/adapters/dashboard/index.ts +14 -0
  21. package/src/adapters/dashboard/source.ts +0 -8
  22. package/src/adapters/dashboard/web/fired.ts +8 -0
  23. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -1
  24. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +7 -10
  25. package/src/adapters/dashboard/web/pages/memories/memories.css +3 -0
  26. package/src/adapters/dashboard/web/pages/memories/row.js +5 -2
  27. package/src/adapters/dashboard/web/pages/memories/sections/hold.js +2 -1
  28. package/src/adapters/dashboard/web/pages/memories/sections/search.js +19 -3
  29. package/src/adapters/dashboard/web/server.ts +16 -4
  30. package/src/adapters/dashboard/web/shared/dates.js +6 -16
  31. package/src/adapters/dashboard/web/shared/memory-modal.js +21 -8
  32. package/src/adapters/dashboard/web/views/health.ts +11 -0
  33. package/src/adapters/dashboard/web/views/mechanism-panel.ts +8 -5
  34. package/src/adapters/dashboard/web/views/memories.ts +26 -7
  35. package/src/adapters/dashboard/web/views/memory-words.ts +16 -0
  36. package/src/adapters/dashboard/web/views/memory.ts +51 -2
  37. package/src/adapters/dashboard/web/views/mind.ts +31 -6
  38. package/src/adapters/empty-bunfig.toml +5 -0
  39. package/src/adapters/fired.ts +6 -2
  40. package/src/adapters/host-wiring.ts +4 -3
  41. package/src/adapters/log/index.ts +2 -2
  42. package/src/adapters/mcp/CONTRACT.md +16 -2
  43. package/src/adapters/mcp/INTERFACE-GAPS.md +15 -1
  44. package/src/adapters/mcp/NOTES.md +243 -0
  45. package/src/adapters/mcp/bin/serve.mjs +4 -2
  46. package/src/adapters/mcp/bin/serve.ts +11 -4
  47. package/src/adapters/mcp/facts.ts +72 -4
  48. package/src/adapters/mcp/meaning.ts +218 -15
  49. package/src/adapters/mcp/server.ts +1 -1
  50. package/src/adapters/mcp/tools.ts +81 -57
  51. package/src/adapters/plugin-run.sh +405 -33
  52. package/src/adapters/plugin.ts +14 -2
  53. package/src/adapters/runtime.ts +192 -17
  54. package/src/adapters/sessions.ts +2 -2
  55. package/src/core/associate/NOTES.md +10 -0
  56. package/src/core/bridge.ts +1 -1
  57. package/src/core/briefing.ts +20 -3
  58. package/src/core/contradictions.ts +56 -20
  59. package/src/core/counterpart.ts +39 -17
  60. package/src/core/dream/CONTRACT.md +4 -12
  61. package/src/core/dream/INTERFACE-GAPS.md +3 -2
  62. package/src/core/dream/NOTES.md +10 -0
  63. package/src/core/dream/index.ts +10 -52
  64. package/src/core/embed/static.ts +5 -1
  65. package/src/core/encode/INTERFACE-GAPS.md +2 -1
  66. package/src/core/encode/NOTES.md +12 -0
  67. package/src/core/encode/chunk.ts +6 -30
  68. package/src/core/encode/index.ts +0 -1
  69. package/src/core/encode/types.ts +1 -13
  70. package/src/core/handoff/last-here.ts +18 -2
  71. package/src/core/physics/CONTRACT.md +6 -0
  72. package/src/core/physics/NOTES.md +33 -2
  73. package/src/core/physics/index.ts +22 -7
  74. package/src/core/prospective/CONTRACT.md +3 -1
  75. package/src/core/prospective/NOTES.md +15 -0
  76. package/src/core/recall/time-ask.ts +154 -19
  77. package/src/core/self/CONTRACT.md +23 -3
  78. package/src/core/self/NOTES.md +64 -0
  79. package/src/core/self/behind.ts +6 -3
  80. package/src/core/self/briefing.ts +272 -11
  81. package/src/core/self/index.ts +50 -4
  82. package/src/core/sleep/NOTES.md +32 -0
  83. package/src/core/store/NOTES.md +16 -0
  84. package/src/core/time.ts +15 -0
@@ -9,19 +9,140 @@
9
9
  * writes into a host's configuration, and every worker it spawns, is
10
10
  * `<runtime> <scriptArgs(script)>`, with the runtime the one running NOW
11
11
  * (`process.execPath`) — so `counterparts install` run under Node wires Node,
12
- * and under Bun wires Bun, and the Bun shape is byte-for-byte what it has been
13
- * since 2026-09-03.
12
+ * and under Bun wires Bun. The Bun shape was `run <script>` from 2026-09-03
13
+ * and is `--no-env-file --config=<empty-bunfig.toml> run <script>` since
14
+ * 2026-10-09 (below).
14
15
  *
15
16
  * The runtime is read off the executable's NAME, not off this process, so a
16
17
  * caller that passes a fixed executable (every test does) gets the shape that
17
18
  * executable needs. Anything not named `node…` is treated as Bun, which is what
18
19
  * every command written before Node support said.
20
+ *
21
+ * **BUN IS TOLD NOT TO READ THE PROJECT'S `.env` OR `bunfig.toml`
22
+ * (2026-10-09).** A host starts our hooks and servers in the person's project,
23
+ * and Bun reads two things from the WORKING DIRECTORY before any of our code
24
+ * runs:
25
+ *
26
+ * - `.env`, `.env.local` and `.env.<NODE_ENV>`, into `process.env`. A
27
+ * project whose `.env` set `COUNTERPARTS_DATA_DIR` or `COUNTERPARTS_CONFIG`
28
+ * could point Counterparts at another store — measured, for the plugin's
29
+ * server, which no `-e` pins, and for an npm install's hooks, which name no
30
+ * `--config` (scar §2.13 from a direction the spawner's pinning never
31
+ * covered). A variable already in the real environment still wins over a
32
+ * `.env` (also measured), so the hole was every variable nobody set.
33
+ * `--no-env-file` switches the loading off.
34
+ * - `bunfig.toml`, whose TOP-LEVEL `preload = [...]` runs the project's code
35
+ * inside our process before our entry (measured on Bun 1.3.10, through
36
+ * `run` and a bare script alike, the plugin's launcher included; `[run]
37
+ * preload` does not apply to these launches). `--config=<file>` makes Bun
38
+ * read that file instead, and `EMPTY_BUNFIG` is one with nothing in it. A
39
+ * missing one is fatal to Bun, so it ships beside this file and must stay.
40
+ *
41
+ * Node has neither: it reads a `.env` only when `--env-file` names one, and no
42
+ * `bunfig.toml`. Commands written before this lack one flag or both: they
43
+ * still parse (`parseScriptInvocation`, `projectEnv: "read"`), `doctor` names
44
+ * them, and `counterparts connect` rewrites them.
19
45
  */
20
46
  import { existsSync } from "node:fs";
47
+ import { basename, dirname, join } from "node:path";
21
48
  import { fileURLToPath } from "node:url";
22
49
 
23
50
  export type RuntimeKind = "bun" | "node";
24
51
 
52
+ /** Bun's switch that stops it loading `.env` files from the working directory. */
53
+ export const BUN_NO_ENV_FILE = "--no-env-file";
54
+
55
+ // ── the single binary (docs/single-binary.md) ──────────────────────────────
56
+ //
57
+ // `bun build --compile` (tools/single-binary/) packs every module, the model
58
+ // table and the dashboard's files into one executable that needs no Bun or Node
59
+ // on the machine — what the plugin downloads when it finds neither. Inside it,
60
+ // EVERY module's `import.meta.url` is the binary's own virtual file
61
+ // (`file:///$bunfs/root/<name>`; `B:/~BUN/root/<name>` on Windows), so a path
62
+ // computed from `import.meta.url` no longer says where a module lives, and the
63
+ // files the build embedded sit under that virtual root at their
64
+ // repository-relative paths. Everything below takes the binary as a parameter
65
+ // defaulting to `BINARY`, so a test can run every compiled branch from source.
66
+
67
+ /** The compiled binary this process is: `root`, the virtual directory its
68
+ * embedded files sit under; `self`, the executable on disk. */
69
+ export interface Binary {
70
+ readonly root: string;
71
+ readonly self: string;
72
+ }
73
+
74
+ /** The binary a module URL says this process is, or null when it is source.
75
+ * Pure: a test hands it a URL of either shape. */
76
+ export function binaryOf(moduleUrl: string, self: string): Binary | null {
77
+ const path = moduleUrl.startsWith("file:") ? decodeURIComponent(new URL(moduleUrl).pathname) : moduleUrl;
78
+ if (!/[\\/]\$bunfs[\\/]|(^|[\\/])~BUN[\\/]/.test(path)) return null;
79
+ // The directory holding the binary's own virtual file. By hand rather than
80
+ // `node:path`, which on a POSIX host does not split a Windows path.
81
+ const root = path.replace(/[\\/][^\\/]*$/, "").replace(/^\/([A-Za-z]:[\\/])/, "$1");
82
+ return { root, self };
83
+ }
84
+
85
+ /** This process, if it is the compiled binary; null from source. */
86
+ export const BINARY: Binary | null = binaryOf(import.meta.url, process.execPath);
87
+
88
+ /** Is this process (or the binary a test names) the compiled binary? */
89
+ export function isCompiled(binary: Binary | null = BINARY): boolean {
90
+ return binary !== null;
91
+ }
92
+
93
+ /** A file of this package by its path from the package root (`/`-separated):
94
+ * on disk from source, among the binary's embedded files when compiled. */
95
+ export function packagePath(rel: string, binary: Binary | null = BINARY): string {
96
+ if (binary === null) return fileURLToPath(new URL(`../../${rel}`, import.meta.url));
97
+ const sep = binary.root.includes("\\") ? "\\" : "/";
98
+ // Bun names an embedded file at the top of the build root `./<name>` (its
99
+ // `[dir]` is "."), and the virtual filesystem matches names exactly
100
+ // (measured on 1.3.10; `<binary> selfcheck`, run by every build, holds it).
101
+ return rel.includes("/") ? [binary.root, ...rel.split("/")].join(sep) : [binary.root, ".", rel].join(sep);
102
+ }
103
+
104
+ /** The model table's directory inside the binary; undefined from source,
105
+ * where `core/embed/static.ts` resolves the installed package itself. */
106
+ export function bundledModelDir(binary: Binary | null = BINARY): string | undefined {
107
+ return binary === null ? undefined : packagePath("node_modules/counterparts-model-potion", binary);
108
+ }
109
+
110
+ /** What the binary's first argument may be: the four a host runs, and the
111
+ * two it starts of itself (`scriptArgs`). `tools/single-binary/main.ts`
112
+ * dispatches on the same words. */
113
+ export const BINARY_MODES = ["hook", "mcp", "cli", "dashboard", "runner", "nightly"] as const;
114
+ export type BinaryMode = (typeof BINARY_MODES)[number];
115
+
116
+ /** Each entry script's mode, by file name — which survives the virtual paths. */
117
+ export const BINARY_MODE_OF: Readonly<Record<string, BinaryMode>> = {
118
+ "hook.ts": "hook",
119
+ "serve.ts": "mcp",
120
+ "counterparts.ts": "cli",
121
+ "dashboard.ts": "dashboard",
122
+ "runner.ts": "runner",
123
+ "nightly.ts": "nightly",
124
+ };
125
+
126
+ /** Does an executable's name look like the single binary? `counterparts`,
127
+ * `counterparts.exe`, `counterparts-0.3.14-darwin-arm64` — and not the npm
128
+ * shims `counterparts-hook`, `counterparts-mcp`, `counterparts-dashboard`. */
129
+ export function isBinaryName(exe: string): boolean {
130
+ const name = exe.split(/[\\/]/).pop() ?? "";
131
+ return /^counterparts([-.][\w.-]*)?$/i.test(name) && !/^counterparts-(hook|mcp|dashboard)(\.exe)?$/i.test(name);
132
+ }
133
+
134
+ function isBinaryMode(word: string | undefined): word is BinaryMode {
135
+ return (BINARY_MODES as readonly string[]).includes(word ?? "");
136
+ }
137
+
138
+ /** An empty `bunfig.toml`, shipped beside this file, that every Bun launch
139
+ * names in place of the project's own. Absolute, from this file. */
140
+ export const EMPTY_BUNFIG = fileURLToPath(new URL("./empty-bunfig.toml", import.meta.url));
141
+
142
+ /** How a Bun command names its configuration file: `--config=<path>`, ONE
143
+ * argument (Bun 1.3 does not read `--config <path>` as two the same way). */
144
+ export const BUN_CONFIG_PREFIX = "--config=";
145
+
25
146
  /** The module Node loads before a script (`--import`). Absolute, from this file. */
26
147
  export const NODE_HOOKS = fileURLToPath(new URL("./node-hooks.mjs", import.meta.url));
27
148
 
@@ -37,9 +158,11 @@ export function currentRuntime(): RuntimeKind {
37
158
  return process.versions.bun === undefined ? "node" : "bun";
38
159
  }
39
160
 
40
- /** `bun 1.3.0` or `node 24.9.0` — the runtime this process is, for a reader. */
41
- export function runtimeLabel(): string {
161
+ /** `bun 1.3.0`, `node 24.9.0`, or `the single binary (bun 1.3.10)` — the
162
+ * runtime this process is, for a reader. */
163
+ export function runtimeLabel(binary: Binary | null = BINARY): string {
42
164
  const bun = process.versions.bun;
165
+ if (binary !== null) return `the single binary (bun ${bun ?? "?"})`;
43
166
  return bun === undefined ? `node ${process.versions.node}` : `bun ${bun}`;
44
167
  }
45
168
 
@@ -49,36 +172,88 @@ export function runtimeOf(exe: string): RuntimeKind {
49
172
  return /^node(js)?(\d[\d.]*)?(\.exe)?$/i.test(exe.split(/[\\/]/).pop() ?? "") ? "node" : "bun";
50
173
  }
51
174
 
52
- /** The arguments that make `exe` run `script`: `run <script>` for Bun,
53
- * `--import <node-hooks.mjs> <script>` for Node. */
54
- export function scriptArgs(script: string, exe: string = process.execPath): string[] {
55
- return runtimeOf(exe) === "node" ? ["--import", NODE_HOOKS, script] : ["run", script];
175
+ /** The arguments that make `exe` run `script`: `--no-env-file
176
+ * --config=<empty-bunfig.toml> run <script>` for Bun, `--import
177
+ * <node-hooks.mjs> <script>` for Node, and the script's mode alone (`hook`,
178
+ * `runner`, …) when `exe` is the compiled binary itself, which reads no
179
+ * `.env` or `bunfig.toml` (it is built with both off). */
180
+ export function scriptArgs(script: string, exe: string = process.execPath, binary: Binary | null = BINARY): string[] {
181
+ // The compiled binary runs ITSELF in another mode: `<binary> runner`.
182
+ const mode = binary !== null && exe === binary.self ? BINARY_MODE_OF[basename(script)] : undefined;
183
+ if (mode !== undefined) return [mode];
184
+ return runtimeOf(exe) === "node"
185
+ ? ["--import", NODE_HOOKS, script]
186
+ : [BUN_NO_ENV_FILE, `${BUN_CONFIG_PREFIX}${EMPTY_BUNFIG}`, "run", script];
56
187
  }
57
188
 
58
189
  /** A command split into its parts, when it is `<exe> <scriptArgs(script)> <rest…>`. */
59
190
  export interface ScriptInvocation {
60
191
  readonly exe: string;
61
- readonly runtime: RuntimeKind;
192
+ /** `binary` for the single compiled binary, which is its own runtime. */
193
+ readonly runtime: RuntimeKind | "binary";
194
+ /** The script it runs — for the binary, the binary itself, which is the
195
+ * file that must be on disk for the command to run. */
62
196
  readonly script: string;
197
+ /** The binary's mode (`hook`, `mcp`, …); absent for Bun and Node. */
198
+ readonly mode?: BinaryMode;
63
199
  /** Whatever followed the script (`--config <path>`, flags). */
64
200
  readonly rest: readonly string[];
201
+ /** Whether the runtime reads the project's `.env` or `bunfig.toml` into the
202
+ * process: `read` for a Bun command lacking `--no-env-file` or a
203
+ * `--config=` (written before 2026-10-09), else `ignored`. */
204
+ readonly projectEnv: "read" | "ignored";
65
205
  }
66
206
 
67
207
  /**
68
- * Read `<exe> run <script> …` or `<exe> --import <…node-hooks.mjs> <script> …`
69
- * back out of a token list — the inverse of `scriptArgs`, for the readers that
70
- * must recognise what the writers wrote (`wire.ts#isOurHookCommand`, doctor's
71
- * runtime line). Null for any other shape: a command this cannot read is not
72
- * one of ours.
208
+ * Read `<exe> [bun flags] run [bun flags] <script> …`, `<exe> --import
209
+ * <…node-hooks.mjs> <script> …` or `<binary> <mode> …` back out of a token
210
+ * list — the inverse of `scriptArgs`, for the readers that must recognise what
211
+ * the writers wrote (`wire.ts#isOurHookCommand`, doctor's runtime line, the
212
+ * plugin's npm-wiring check). The Bun flags read are `--no-env-file` and
213
+ * `--config=<file>`, in any order, before or after `run`. A shape missing
214
+ * either is what installs wrote until 2026-10-09: still ours, and
215
+ * `projectEnv: "read"`. Null for any other shape: a command this cannot read
216
+ * is not one of ours.
73
217
  */
74
218
  export function parseScriptInvocation(tokens: readonly string[]): ScriptInvocation | null {
75
219
  const exe = tokens[0] ?? "";
76
220
  if (exe.length === 0) return null;
77
- if (tokens[1] === "run" && (tokens[2] ?? "").length > 0) {
78
- return { exe, runtime: runtimeOf(exe), script: tokens[2] as string, rest: tokens.slice(3) };
221
+ // `<binary> <mode> …` — what the single binary writes for itself
222
+ // (`scriptArgs`). It reads no `.env`: it is built with the autoload off.
223
+ if (isBinaryName(exe) && isBinaryMode(tokens[1])) {
224
+ return { exe, runtime: "binary", script: exe, mode: tokens[1], rest: tokens.slice(2), projectEnv: "ignored" };
225
+ }
226
+ let at = 1;
227
+ let noEnvFile = false;
228
+ let ownConfig = false;
229
+ const flags = (): void => {
230
+ for (;;) {
231
+ const t = tokens[at] ?? "";
232
+ if (t === BUN_NO_ENV_FILE) noEnvFile = true;
233
+ else if (t.startsWith(BUN_CONFIG_PREFIX) && t.length > BUN_CONFIG_PREFIX.length) ownConfig = true;
234
+ else return;
235
+ at += 1;
236
+ }
237
+ };
238
+ flags();
239
+ const flagged = at > 1;
240
+ if (tokens[at] === "run") {
241
+ at += 1;
242
+ flags();
243
+ const script = tokens[at] ?? "";
244
+ if (script.length === 0) return null;
245
+ const runtime = runtimeOf(exe);
246
+ return {
247
+ exe,
248
+ runtime,
249
+ script,
250
+ rest: tokens.slice(at + 1),
251
+ projectEnv: runtime === "node" || (noEnvFile && ownConfig) ? "ignored" : "read",
252
+ };
79
253
  }
254
+ if (flagged) return null;
80
255
  if (tokens[1] === "--import" && /(^|[/\\])node-hooks\.mjs$/.test(tokens[2] ?? "") && (tokens[3] ?? "").length > 0) {
81
- return { exe, runtime: "node", script: tokens[3] as string, rest: tokens.slice(4) };
256
+ return { exe, runtime: "node", script: tokens[3] as string, rest: tokens.slice(4), projectEnv: "ignored" };
82
257
  }
83
258
  return null;
84
259
  }
@@ -74,7 +74,6 @@ import {
74
74
  writeFileSync,
75
75
  } from "node:fs";
76
76
  import { join, resolve } from "node:path";
77
- import { fileURLToPath } from "node:url";
78
77
 
79
78
  import { wireChars } from "../core/fit/index.js";
80
79
 
@@ -95,6 +94,7 @@ import { CACHE_SCHEMA_VERSION, SCHEMA_VERSION } from "../core/store/index.js";
95
94
  import type { Store } from "../core/store/index.js";
96
95
 
97
96
  import { DEFAULT_HOST, isHostName, isPseudoScope, wordingFor } from "./hosts.js";
97
+ import { packagePath } from "./runtime.js";
98
98
 
99
99
  /** The one directory name. Classified in `store/paths.ts` LAYOUT. */
100
100
  export const SESSIONS_DIR = "sessions";
@@ -963,7 +963,7 @@ export function installedVersion(): string | null {
963
963
  */
964
964
  export function manifestVersionOnDisk(): string | null {
965
965
  try {
966
- const raw = readFileSync(fileURLToPath(new URL("../../package.json", import.meta.url)), "utf8");
966
+ const raw = readFileSync(packagePath("package.json"), "utf8");
967
967
  const said = (JSON.parse(raw) as Record<string, unknown>)["version"];
968
968
  return typeof said === "string" && said.length > 0 ? said : null;
969
969
  } catch {
@@ -456,3 +456,13 @@ code:
456
456
  The archived copy's rows stay until they decay to the floor and a flush sweeps them, so
457
457
  a re-run of the 10-02 count will still find them for a while; count what the live copy
458
458
  holds, not what the archived one still has.
459
+
460
+ ## 16. The frontier's scan, measured (2026-10-09)
461
+
462
+ The 2026-09-28 audit said the spread frontier was not sorted by what each node carries and
463
+ asked for a priority queue. Build 2 (§14) made it best-first the same day: `head()` picks
464
+ the strongest waiting node by one linear scan per expansion, so nothing sorts repeatedly.
465
+ Measured in memory on the densest graph the tunables allow (5,000 nodes, 32 strong edges
466
+ each, 40 seeds, 64 expansions, 1,632 contributions): about 0.9 ms a spread, of which
467
+ `head()` is about 0.3 ms. A heap would save at most that, per recall, beside the 64 edge
468
+ reads from the store a real spread makes. Not done.
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * 1. CHUNK-LEVEL GATED-MEANS-GATED: fallback-sweep chunks route through
10
10
  * `encodeChunk`, whose all-rejected rule already returns zero durable
11
- * effects (including prediction checks). The bridge adds no second
11
+ * effects. The bridge adds no second
12
12
  * implementation — it routes.
13
13
  * 2. THE EMOTION EXEMPTION IS ENGINE-SET HERE, from the proposal's source: a
14
14
  * session-end dump or an in-the-moment jot IS the experiencer writing, so
@@ -20,7 +20,7 @@
20
20
  * are already built; only the source was borrowed).
21
21
  */
22
22
  import type { RenderFn } from "./sleep/index.js";
23
- import { readableRecurrence } from "./time.js";
23
+ import { isDay, readableRecurrence } from "./time.js";
24
24
  import type { Recurrence } from "./time.js";
25
25
 
26
26
  /** Structurally `Self`, so this file imports no class. */
@@ -47,6 +47,12 @@ export interface RendererOptions {
47
47
  /** The "Yesterday" line, composed and dated by the root from yesterday's
48
48
  * chapters (2026-10-01). Absent: no line. */
49
49
  yesterday?: string;
50
+ /** Its shorter forms, widest first (review of #350): stepped down only to
51
+ * make room for "Still open"'s first item. */
52
+ yesterdayShorter?: readonly string[];
53
+ /** The room the delivery holds for "Work here", lent to "Still open"'s
54
+ * first item only (`self/briefing.ts#keepFirstOpen`, review of #350). */
55
+ lendBytes?: number;
50
56
  /** Telemetry only. A refusal must be loud, never a silently empty briefing. */
51
57
  onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
52
58
  }
@@ -65,17 +71,28 @@ export function selfRenderer(self: BriefingRenderer, opts: RendererOptions = {})
65
71
  : opts.prospective
66
72
  .horizon({ at: opts.at, day: ctx.day })
67
73
  // The date it is due rides along, so the line can say it (2026-10-01),
68
- // and how often it comes round when it repeats (2026-10-09).
74
+ // how often it comes round when it repeats (2026-10-09), and whether
75
+ // that date is already behind the day asked about — a one-off in its
76
+ // grace days says it WAS due (2026-10-09). Both are `YYYY-MM-DD`
77
+ // here, so the strings compare as the dates do.
69
78
  .items.map((i) => {
70
79
  if (i.eventDate === undefined) return { id: i.memoryId };
71
80
  const every = i.anchor === undefined || i.recurring === undefined ? "" : readableRecurrence(i.anchor, i.recurring);
72
- return every === "" ? { id: i.memoryId, due: i.eventDate } : { id: i.memoryId, due: i.eventDate, every };
81
+ const at = opts.at ?? "";
82
+ return {
83
+ id: i.memoryId,
84
+ due: i.eventDate,
85
+ ...(every === "" ? {} : { every }),
86
+ ...(isDay(i.eventDate) && isDay(at) && i.eventDate < at ? { past: true } : {}),
87
+ };
73
88
  });
74
89
  const result = self.boundary({
75
90
  day: ctx.day,
76
91
  budgetBytes: ctx.budgetBytes,
77
92
  ...(horizon === undefined ? {} : { horizon }),
78
93
  ...(opts.yesterday === undefined ? {} : { yesterday: opts.yesterday }),
94
+ ...(opts.yesterday === undefined || opts.yesterdayShorter === undefined ? {} : { yesterdayShorter: opts.yesterdayShorter }),
95
+ ...(opts.lendBytes === undefined || opts.lendBytes <= 0 ? {} : { lendBytes: opts.lendBytes }),
79
96
  });
80
97
  return { bytes: result.briefing.bytes, elements: result.briefing.elements };
81
98
  };
@@ -747,19 +747,51 @@ export function heldView(row: Pick<MemoryRow, "title" | "body" | "confidential">
747
747
  return { title, text: excerptOf(row.body, CONTRADICTION_TUNABLES.HELD_TEXT_CHARS) };
748
748
  }
749
749
 
750
+ /** One held `updates`, as its durable row recorded it (`CONTRADICTION_HELD_EVENT`). */
751
+ export interface HeldPair {
752
+ readonly seq: number;
753
+ /** The lived day it was held. */
754
+ readonly day: number;
755
+ /** The new memory, which said it changed or corrected… */
756
+ readonly holds: string;
757
+ /** …this one, which looked unrelated and was left as it was. */
758
+ readonly over: string;
759
+ readonly how: string;
760
+ /** Which reading decided: `meaning` or `words`. */
761
+ readonly by: string;
762
+ /** Settled by hand afterwards (a `contradiction.settled` row naming the same two). */
763
+ readonly settledAfter: boolean;
764
+ }
765
+
750
766
  /**
751
- * HOW OFTEN THE GUARD FIRED — a reader for doctor or the dashboard, which
752
- * neither calls yet (owed: `mcp/INTERFACE-GAPS.md`). Holds since `sinceDay`,
753
- * by which reading, and how many of them the writer settled by hand
754
- * afterwards (a `contradiction.settled` row naming the same two memories): a
755
- * hold later settled is most likely a related pair the guard got wrong; one
756
- * never settled is a wrong pointer caught, or a writer that had no one to
757
- * read its result (a write-up, the nightly catch-up).
767
+ * HOW OFTEN THE GUARD FIRED — doctor's Contradictions line reads it
768
+ * (2026-10-09). Holds since `sinceDay`, by which reading, and how many of them
769
+ * the writer settled by hand afterwards (a `contradiction.settled` row naming
770
+ * the same two memories): a hold later settled is most likely a related pair
771
+ * the guard got wrong; one never settled is a wrong pointer caught, or a
772
+ * writer that had no one to read its result (a write-up, the nightly
773
+ * catch-up). `settledAfter / held` is the number that says whether the bar
774
+ * (`UPDATE_COSINE`) holds back real corrections.
758
775
  */
759
776
  export function heldCorrections(
760
777
  store: Pick<Store, "eventLog">,
761
778
  opts: { sinceDay?: number } = {},
762
779
  ): { held: number; settledAfter: number; byMeaning: number; byWords: number } {
780
+ const holds = heldPairs(store, opts);
781
+ return {
782
+ held: holds.length,
783
+ settledAfter: holds.filter((h) => h.settledAfter).length,
784
+ byMeaning: holds.filter((h) => h.by === "meaning").length,
785
+ byWords: holds.filter((h) => h.by === "words").length,
786
+ };
787
+ }
788
+
789
+ /**
790
+ * Every hold since `sinceDay`, NEWEST first, each with whether it was settled
791
+ * by hand afterwards — what `counterparts settle` lists, so the owner can
792
+ * settle one the guard held and was meant (`--holds <new> --against <old>`).
793
+ */
794
+ export function heldPairs(store: Pick<Store, "eventLog">, opts: { sinceDay?: number } = {}): HeldPair[] {
763
795
  const limit = CONTRADICTION_TUNABLES.HELD_READ_ROWS;
764
796
  const read = (raw: string | null): Record<string, unknown> => {
765
797
  try {
@@ -768,8 +800,12 @@ export function heldCorrections(
768
800
  return {};
769
801
  }
770
802
  };
771
- // The newest holds, and every settle from the day of the oldest of them on
772
- // (`eventLog` reads 500 rows unless told otherwise, oldest first).
803
+ // The newest holds, and the settles from the day of the oldest of them on —
804
+ // both read NEWEST first (`eventLog` reads 500 rows unless told otherwise,
805
+ // oldest first). Past the limit an ascending settle read kept the oldest
806
+ // and dropped the newest, so the newest holds read as never settled
807
+ // (2026-10-09, audit #1's last caller). Under the limit the same rows come
808
+ // back, and `settledAfter` does not depend on their order.
773
809
  const holds = store
774
810
  .eventLog({ name: CONTRADICTION_HELD_EVENT, ...(opts.sinceDay === undefined ? {} : { sinceDay: opts.sinceDay }), order: "desc", limit })
775
811
  .map((e) => ({ seq: e.seq, day: e.day, p: read(e.payload) }));
@@ -777,15 +813,15 @@ export function heldCorrections(
777
813
  const settles =
778
814
  holds.length === 0
779
815
  ? []
780
- : store.eventLog({ name: CONTRADICTION_SETTLED_EVENT, sinceDay: from, limit }).map((e) => ({ seq: e.seq, p: read(e.payload) }));
781
- let settledAfter = 0;
782
- for (const h of holds) {
783
- if (settles.some((s) => s.seq > h.seq && s.p["holds"] === h.p["holds"] && s.p["over"] === h.p["over"])) settledAfter += 1;
784
- }
785
- return {
786
- held: holds.length,
787
- settledAfter,
788
- byMeaning: holds.filter((h) => h.p["by"] === "meaning").length,
789
- byWords: holds.filter((h) => h.p["by"] === "words").length,
790
- };
816
+ : store.eventLog({ name: CONTRADICTION_SETTLED_EVENT, sinceDay: from, order: "desc", limit }).map((e) => ({ seq: e.seq, p: read(e.payload) }));
817
+ const str = (v: unknown): string => (typeof v === "string" ? v : "");
818
+ return holds.map((h) => ({
819
+ seq: h.seq,
820
+ day: h.day,
821
+ holds: str(h.p["holds"]),
822
+ over: str(h.p["over"]),
823
+ how: str(h.p["how"]),
824
+ by: str(h.p["by"]),
825
+ settledAfter: settles.some((s) => s.seq > h.seq && s.p["holds"] === h.p["holds"] && s.p["over"] === h.p["over"]),
826
+ }));
791
827
  }
@@ -140,7 +140,7 @@ import {
140
140
  } from "./handoff/index.js";
141
141
  import type { Handoff, HandoffRefusal, HandoffWrite, PointerSince } from "./handoff/index.js";
142
142
  import { CLAIM_CHAPTER, askFromStretch, chapterClaims, claimUnwritten, sessionStretch, sessionsHere, workSince } from "./coverage/index.js";
143
- import { LAST_HERE_LIFE_DAYS, LAST_HERE_NOROOM_EVENT, chaptersBySession, chaptersHere, chaptersOn, elsewhereLine, lastHereLadder, yesterdayLine } from "./handoff/last-here.js";
143
+ import { LAST_HERE_LIFE_DAYS, LAST_HERE_NOROOM_EVENT, chaptersBySession, chaptersHere, chaptersOn, elsewhereLine, lastHereLadder, yesterdayLine, yesterdayShorter } from "./handoff/last-here.js";
144
144
  import type { ChapterHere, LastHere } from "./handoff/last-here.js";
145
145
  import { addDays, isDay, localStamp, localStampAfter } from "./time.js";
146
146
  import type { Recurrence } from "./time.js";
@@ -2389,15 +2389,23 @@ export class Counterpart {
2389
2389
  * id, the date in the line (`handoff/last-here.ts#yesterdayLine`). Undefined
2390
2390
  * without a date or a chapter that day; never throws — a store that will not
2391
2391
  * answer composes the wake without it.
2392
+ *
2393
+ * Its SHORTER FORMS ride beside it (review of #350, 2026-10-09): fewer
2394
+ * titles, the rest by count, for the wake to step down only when "Still
2395
+ * open" would otherwise list nothing (`handoff/last-here.ts#yesterdayShorter`).
2392
2396
  */
2393
- private yesterdayFor(at: string | undefined): string | undefined {
2394
- if (at === undefined || !isDay(at)) return undefined;
2397
+ private yesterdayFor(at: string | undefined): { yesterday?: string; yesterdayShorter?: string[] } {
2398
+ if (at === undefined || !isDay(at)) return {};
2395
2399
  try {
2396
2400
  const date = addDays(at, -1);
2397
2401
  const fromDay = Math.max(0, this.store.livedDay() - LAST_HERE_LIFE_DAYS + 1);
2398
- return yesterdayLine(chaptersOn(this.store, date, { fromDay }), date) ?? undefined;
2402
+ const day = chaptersOn(this.store, date, { fromDay });
2403
+ const line = yesterdayLine(day, date);
2404
+ if (line === null) return {};
2405
+ const shorter = yesterdayShorter(day, date);
2406
+ return shorter.length === 0 ? { yesterday: line } : { yesterday: line, yesterdayShorter: shorter };
2399
2407
  } catch {
2400
- return undefined;
2408
+ return {};
2401
2409
  }
2402
2410
  }
2403
2411
 
@@ -2590,7 +2598,7 @@ export class Counterpart {
2590
2598
  * pointer cost more than the eighth it could already. With no handoff and
2591
2599
  * no chapter here inside the fortnight, the reserve is zero as before.
2592
2600
  */
2593
- private wakeReserveBytes(budgetBytes: number): number {
2601
+ private wakeReserveBytes(budgetBytes: number, work = this.workReserveBytes(budgetBytes)): number {
2594
2602
  const norm = (s: string): string => s.trim().replace(/\/+$/, "");
2595
2603
  const blocks: number[] = [];
2596
2604
  let byScope = new Map<string, number[]>();
@@ -2620,7 +2628,7 @@ export class Counterpart {
2620
2628
  } catch {
2621
2629
  /* no chapter lines is the reserve as it was */
2622
2630
  }
2623
- return PREFACE_RESERVE_BYTES + reserveBytes(blocks, budgetBytes) + this.workReserveBytes(budgetBytes);
2631
+ return PREFACE_RESERVE_BYTES + reserveBytes(blocks, budgetBytes) + work;
2624
2632
  }
2625
2633
 
2626
2634
  /**
@@ -2864,6 +2872,14 @@ export class Counterpart {
2864
2872
  const first = this.prospective.occurrenceUndelivered(reminder.memoryId, reminder.windowKey);
2865
2873
  const claimed = this.prospective.claimPlain(reminder, { at: input.at, day });
2866
2874
  if (claimed && first) this.creditOccurrence(reminder.memoryId, reminder.windowKey, day, "plain");
2875
+ // TOLD ON ITS DAY, IT LEAVES "ARRIVING:" (2026-09-29) — and the wake
2876
+ // published before the telling still lists it, until something
2877
+ // re-renders. A day's first render can come before the day's first tell
2878
+ // (a late session's turn ending after midnight), and on 2026-10-09 a
2879
+ // reminder said outright on the 8th was still under "Arriving:" the next
2880
+ // morning. So the telling marks the wake behind, and the next turn-end
2881
+ // worker re-renders it (`refreshWake`).
2882
+ if (claimed && reminder.beat !== "opens") markWakeBehind(this.store, "told");
2867
2883
  return claimed;
2868
2884
  } catch (err) {
2869
2885
  this.emit("counterpart.prospective.plain.failed", reminder.memoryId, { code: errCode(err) });
@@ -4210,8 +4226,12 @@ export class Counterpart {
4210
4226
  async sessionEnd(input: SessionEndInput = {}): Promise<SessionEndReport> {
4211
4227
  const budgetBytes = input.budgetBytes ?? this.reportedBudget;
4212
4228
  if (input.budgetBytes !== undefined) this.reportedBudget = input.budgetBytes;
4229
+ // The "Work here" reserve, once: part of what the composition leaves the
4230
+ // delivery, and lent back to "Still open"'s first item when that is all
4231
+ // that would otherwise go unlisted (review of #350).
4232
+ const work = budgetBytes === null ? 0 : this.workReserveBytes(budgetBytes);
4213
4233
  const composeBudget =
4214
- budgetBytes === null ? null : Math.max(budgetBytes - this.wakeReserveBytes(budgetBytes), 0);
4234
+ budgetBytes === null ? null : Math.max(budgetBytes - this.wakeReserveBytes(budgetBytes, work), 0);
4215
4235
 
4216
4236
  // Three states, not two (I32): swept, skipped-and-said-so, or not asked for.
4217
4237
  // The middle one still writes the gate row — `ran: 0, scopes: 0`, with the
@@ -4260,11 +4280,11 @@ export class Counterpart {
4260
4280
  this.emit("counterpart.episode.reconcile.failed", undefined, { code: errCode(err) });
4261
4281
  }
4262
4282
 
4263
- const yesterday = this.yesterdayFor(input.at);
4264
4283
  const render = selfRenderer(this.self, {
4265
4284
  prospective: this.prospective,
4266
4285
  ...(input.at === undefined ? {} : { at: input.at }),
4267
- ...(yesterday === undefined ? {} : { yesterday }),
4286
+ ...this.yesterdayFor(input.at),
4287
+ lendBytes: work,
4268
4288
  onEvent: (name, data) => this.emit(name, undefined, data),
4269
4289
  });
4270
4290
  // The PHYSICS date key, and the host's to supply — every live entry point
@@ -4661,12 +4681,14 @@ export class Counterpart {
4661
4681
  counts: {},
4662
4682
  };
4663
4683
  }
4664
- const composeBudget = Math.max(budgetBytes - this.wakeReserveBytes(budgetBytes), 0);
4665
- const yesterday = this.yesterdayFor(input.at);
4684
+ const work = this.workReserveBytes(budgetBytes);
4685
+ const composeBudget = Math.max(budgetBytes - this.wakeReserveBytes(budgetBytes, work), 0);
4666
4686
  const render = selfRenderer(this.self, {
4667
4687
  prospective: this.prospective,
4668
4688
  ...(input.at === undefined ? {} : { at: input.at }),
4669
- ...(yesterday === undefined ? {} : { yesterday }),
4689
+ ...this.yesterdayFor(input.at),
4690
+ // Lent to "Still open"'s first item only (review of #350).
4691
+ lendBytes: work,
4670
4692
  onEvent: (name, data) => this.emit(name, undefined, data),
4671
4693
  });
4672
4694
  // Read before the render, as the boundary reads it (`self/behind.ts`).
@@ -6002,8 +6024,8 @@ export class Counterpart {
6002
6024
  /**
6003
6025
  * The fallback path's `apply`. ONE chunk's proposals go through `encodeChunk`
6004
6026
  * together — never `gateProposal` one at a time — so the chunk-level
6005
- * all-rejected rule holds and a fully-gated chunk moves zero durable state,
6006
- * prediction checks included (SEAMS item 1, scar §7b).
6027
+ * all-rejected rule holds and a fully-gated chunk moves zero durable state
6028
+ * (SEAMS item 1, scar §7b).
6007
6029
  *
6008
6030
  * A throw here is per-chunk failure isolation, not a lost sweep: `remember/`
6009
6031
  * catches it, records `APPLY_FAILED`, and restores that chunk's spans for the
@@ -6103,8 +6125,8 @@ export class Counterpart {
6103
6125
  // THE DURABLE RECORD, and it is written for EVERY chunk that reached the
6104
6126
  // gate — a fully-gated one above all, since those are most of what a refusal
6105
6127
  // distribution is made of. This is telemetry, not a `DurableEffect`: the
6106
- // chunk-level "gated means gated" rule is about strength, uses, revisions,
6107
- // mentions and prediction checks (encode §5 G3), and encode's own
6128
+ // chunk-level "gated means gated" rule is about strength, uses, revisions
6129
+ // and mentions (encode §5 G3), and encode's own
6108
6130
  // `encode.fullyGated` event stands on exactly the same footing.
6109
6131
  //
6110
6132
  // The latch is (chunk content, lived day): a replayed day appends nothing a
@@ -151,14 +151,9 @@ dreamer is the model (a background agent the session launches), outside this pro
151
151
  - An unsettled pair (a dream's flag, or a settle that was undone) is raised the same way,
152
152
  once — the pair's `raised_day` is the latch since v10 — when both memories are
153
153
  showable, naming the pair's id and the `note` settle.
154
- - **The ask, previewed** (2026-09-27, `previewAsk`, for the dashboard's Tonight box):
155
- `{ wouldAsk, reason, newSince }` from the same gate `status` and `askLine` run — the
156
- same dreamed / declined / asked-today checks, the same showable filter, the same
157
- queue (2026-09-28: no longer capped at `MAX_NEW`) — asked as a live session would ask it, so it answers under observer
158
- too. `newSince` is counted for every reason (the gate itself stops before counting
159
- once it knows). A live session previews its own gate; an observer previews a guest's
160
- (confidential memories not counted) unless it passes `owner: true`. Only a count comes
161
- back.
154
+ - *(Removed 2026-10-09: the ask's read-only preview, `previewAsk`, made for the
155
+ dashboard's Tonight box. The box left the home page in round 4 (#273) and nothing
156
+ called it since; NOTES 2026-10-09.)*
162
157
 
163
158
  ### 5.2 The nightly run, and the dream in it
164
159
 
@@ -256,10 +251,7 @@ dreamer is the model (a background agent the session launches), outside this pro
256
251
  from a confidential memory is confidential; a dated reminder and a memory the owner
257
252
  demoted from the core are not merged; a dream's merges are not "new" for the next
258
253
  ask; a dream left open is closed to changes once a newer one begins (review of #251).
259
- 5. **[M]** Under observer stance nothing is written and every phase says so. The ask's
260
- preview (`previewAsk`) answers under observer where `status` stands down, and claims
261
- no ask, records no event and writes nothing, in either stance (`test/dream-preview.test.ts`: byte-identical store,
262
- and it agrees with `status` and `askLine` case by case).
254
+ 5. **[M]** Under observer stance nothing is written and every phase says so.
263
255
  6. **[M]** The journal lives in the `dreams` table: no decay, dedup, prune or recall
264
256
  touches it.
265
257