counterparts 0.3.49 → 0.3.52

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 (95) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +18 -10
  3. package/docs/QUICKSTART.md +46 -12
  4. package/docs/manual.md +2 -1
  5. package/docs/module-map.md +3 -0
  6. package/package.json +3 -2
  7. package/src/adapters/claude-code/NOTES.md +43 -0
  8. package/src/adapters/claude-code/child.ts +23 -2
  9. package/src/adapters/claude-code/doctor-growth.ts +269 -0
  10. package/src/adapters/claude-code/doctor-host.ts +19 -1
  11. package/src/adapters/claude-code/doctor-recall-steps.ts +84 -0
  12. package/src/adapters/claude-code/doctor.ts +26 -3
  13. package/src/adapters/claude-code/hooks.ts +7 -1
  14. package/src/adapters/cli/INTERFACE-GAPS.md +18 -0
  15. package/src/adapters/cli/NOTES.md +24 -0
  16. package/src/adapters/cli/commands-dashboard.ts +9 -1
  17. package/src/adapters/cli/commands-project.ts +2 -1
  18. package/src/adapters/cli/commands-readings.ts +19 -8
  19. package/src/adapters/cli/commands-verify.ts +1 -1
  20. package/src/adapters/cli/commands.ts +4 -2
  21. package/src/adapters/cli/export.ts +2 -1
  22. package/src/adapters/cli/install.ts +14 -6
  23. package/src/adapters/cli/mechanisms.ts +1 -1
  24. package/src/adapters/cli/wire.ts +22 -6
  25. package/src/adapters/dashboard/activity.ts +6 -3
  26. package/src/adapters/dashboard/registries.ts +11 -0
  27. package/src/adapters/dashboard/web/flow.ts +3 -0
  28. package/src/adapters/dashboard/web/lanes.ts +4 -0
  29. package/src/adapters/dashboard/web/narrate.ts +23 -0
  30. package/src/adapters/dashboard/web/views/activity.ts +4 -2
  31. package/src/adapters/dashboard/web/views/flow-view.ts +6 -0
  32. package/src/adapters/dashboard/web/views/memory.ts +13 -0
  33. package/src/adapters/dashboard/web/views/shared.ts +2 -1
  34. package/src/adapters/fired.ts +113 -11
  35. package/src/adapters/host-wiring.ts +3 -1
  36. package/src/adapters/lifecycle.ts +36 -9
  37. package/src/adapters/mcp/CONTRACT.md +22 -1
  38. package/src/adapters/mcp/server-args.ts +51 -0
  39. package/src/adapters/mcp/server-session-end.ts +8 -2
  40. package/src/adapters/mcp/server-words.ts +14 -1
  41. package/src/adapters/mcp/server.ts +117 -7
  42. package/src/adapters/mcp/tools.ts +4 -3
  43. package/src/adapters/plugin.ts +1 -0
  44. package/src/adapters/presence.ts +74 -0
  45. package/src/adapters/runtime.ts +258 -8
  46. package/src/adapters/scopes.ts +3 -2
  47. package/src/adapters/spawn.ts +3 -0
  48. package/src/adapters/update-check.ts +1 -1
  49. package/src/adapters/windows-shims.mjs +102 -0
  50. package/src/core/close-hint.ts +297 -0
  51. package/src/core/counterpart-boundary.ts +15 -0
  52. package/src/core/counterpart-deposit.ts +24 -3
  53. package/src/core/counterpart-events.ts +14 -0
  54. package/src/core/counterpart-types.ts +6 -0
  55. package/src/core/counterpart-wake-shape.ts +88 -19
  56. package/src/core/counterpart.ts +143 -7
  57. package/src/core/dream/index.ts +1 -1
  58. package/src/core/dream/reflect.ts +54 -34
  59. package/src/core/encode/NOTES.md +55 -0
  60. package/src/core/encode/secrets.ts +477 -3
  61. package/src/core/event-rollup.ts +175 -0
  62. package/src/core/handoff/CONTRACT.md +7 -0
  63. package/src/core/interference.ts +496 -0
  64. package/src/core/open-close.ts +583 -0
  65. package/src/core/prospective/CONTRACT.md +24 -0
  66. package/src/core/prospective/derive.ts +22 -1
  67. package/src/core/prospective/index.ts +115 -1
  68. package/src/core/recall/CONTRACT.md +9 -2
  69. package/src/core/recall/NOTES.md +99 -0
  70. package/src/core/recall/activate.ts +83 -6
  71. package/src/core/recall/index.ts +75 -5
  72. package/src/core/recall/probe.ts +134 -0
  73. package/src/core/recall/steps.ts +84 -0
  74. package/src/core/recall/tunables.ts +11 -0
  75. package/src/core/reconsolidation.ts +14 -4
  76. package/src/core/remember/CONTRACT.md +2 -1
  77. package/src/core/remember/NOTES.md +15 -0
  78. package/src/core/remember/spans.ts +44 -6
  79. package/src/core/self/NOTES.md +21 -0
  80. package/src/core/self/work.ts +9 -5
  81. package/src/core/sleep/CONTRACT.md +36 -2
  82. package/src/core/sleep/NOTES.md +35 -0
  83. package/src/core/sleep/close.ts +77 -0
  84. package/src/core/sleep/cycle.ts +44 -0
  85. package/src/core/sleep/index.ts +4 -0
  86. package/src/core/sleep/interfere.ts +73 -0
  87. package/src/core/sleep/log.ts +27 -2
  88. package/src/core/sleep/tunables.ts +19 -0
  89. package/src/core/sleep/types.ts +20 -0
  90. package/src/core/store/index.ts +157 -10
  91. package/src/core/store/operational.ts +22 -0
  92. package/src/core/store/owner-op-seam.ts +16 -0
  93. package/src/core/store/reads-history.ts +173 -7
  94. package/src/core/store/reads-memories.ts +253 -4
  95. package/src/core/store/shapes.ts +8 -0
@@ -0,0 +1,583 @@
1
+ /**
2
+ * THE NIGHT CLOSES OPEN ITEMS ITSELF (2026-11-07, SO1 step 1; Mike's "yes",
3
+ * lightly held). An open item (`unresolved`, with or without `settlesWhen`)
4
+ * that a later memory plainly shows done is closed by the night — no
5
+ * question in the share, no "Shall I close them?". Precision over recall: a
6
+ * wrong close hides a real debt, so the deterministic rule is one, exact,
7
+ * and what it can't be sure of is only LISTED, as "may be done", under
8
+ * `recall "still open"`. Nobody is asked.
9
+ *
10
+ * **The one rule (`release-supersedes`).** A release memory — "X.Y.Z
11
+ * released" / "published" (a FINAL verb beside the version in its headline,
12
+ * `interference.ts#subjectKeys`) — closes every open item in the same folder
13
+ * whose headline names an earlier patch of the same series as a release step
14
+ * still owed — ready, ready to publish, after-publish, publish, right beside
15
+ * the version (never cut, built, packed, merged, tagged: a bug report names
16
+ * those too) — "0.3.46 ready for Mike to publish" and "0.3.47 after-publish
17
+ * steps" close under "0.3.50 released". The release must be WRITTEN `done`
18
+ * (an unmarked "Plan: 0.3.50 released by Friday" is no release), of the same
19
+ * product (the word before the version: "site 0.3.46" is not "counterparts
20
+ * 0.3.50"), and strictly an earlier patch (W < Z): the same version's release
21
+ * does not close its own after-publish steps. Written strictly later (its
22
+ * moment, else its lived day). The release is read as the interference sweep
23
+ * reads it (`subjectKeys`: a final verb right beside the version, never a
24
+ * plan), so "Check ~7 lived days after 0.3.45" or "fix aimed at 0.3.30" never
25
+ * close.
26
+ *
27
+ * **What this rule never closes.** A question to the owner (`status:
28
+ * asked`): only his answer closes one — a write that `updates` it and says it
29
+ * is answered, or the reflection on what he said — and similarity is not his
30
+ * answer; one that may be settled is listed as "may be done". An item the
31
+ * owner reopened (`threadReopenedBy`). A problem ("0.3.46 cut breaks the
32
+ * wake", "… fix before any release": broke, fail, bug, missing, crash,
33
+ * regress, wrong, fix). A check (CHECK-AFTER, "Check due", a
34
+ * re-read): a release is when a check comes due, not its answer. An item that
35
+ * is conditional on a release ("after 0.3.45", "once 0.3.47 ships"). One the
36
+ * item itself already reads as final ("0.3.47 published but …": what it owes
37
+ * is past the release). Protected or archived rows (`closeThread`'s checks).
38
+ *
39
+ * **The write** is `closeThread`'s (`counterpart-deposit.ts`): the flag set
40
+ * false through `Store#revise` (reason `thread-closed`, the old meta kept in
41
+ * the version row), with `threadClosedBy: {by: "night", day, rule, shows,
42
+ * why}` beside it, and one durable `thread.night.closed` event per close
43
+ * naming the item, the memory that showed it and the reason. No DDL.
44
+ *
45
+ * **The way back** (`reopenNightClosed`): the reflect tool's phase "reopen"
46
+ * with the item's id (the owner says it isn't done), or a write that
47
+ * `updates` it and says `unresolved: true` (the thread goes on, on the new
48
+ * row). Either is recorded (`thread.night.reopened`) and marks the item
49
+ * `threadReopenedBy`, so no night closes it again on its own. Reading an
50
+ * item by id is not a touch: the morning line prints the ids, and looking at
51
+ * what closed must not undo it.
52
+ *
53
+ * **"May be done"** (`mayBeDoneOf`): what the night saw but would not close
54
+ * — an item naming a release step whose series moved on, an item naming a PR
55
+ * a later memory says merged — and what the reflection, reading with a
56
+ * model, thought looks done but wasn't sure of (its `close` ids, which used
57
+ * to be asked in the share). Kept on one store meta row, replaced each
58
+ * night; listed by `recall "still open"` beside the item, never in the wake.
59
+ */
60
+ import { THREAD_CLOSED_BY_META_KEY, THREAD_REOPENED_BY_META_KEY, UNRESOLVED_META_KEY } from "./mint.js";
61
+ import { INTERFERENCE_SOURCE, headline, subjectKeys } from "./interference.js";
62
+ import { undo } from "./reconsolidation.js";
63
+ import type { SubjectKeys } from "./interference.js";
64
+ import { settlesWhenOf } from "./types.js";
65
+ import { openThread } from "./self/identity.js";
66
+ import type { Store, WorkEventRow } from "./store/index.js";
67
+
68
+ /** The rule every night close records. */
69
+ export const NIGHT_CLOSE_RULE = "release-supersedes";
70
+
71
+ /** One durable row per close: the item (`ref`), the memory that showed it, the reason. */
72
+ export const NIGHT_CLOSE_EVENT = "thread.night.closed";
73
+
74
+ /** One durable row per reopen of a night-closed item: the item (`ref`) and what touched it. */
75
+ export const NIGHT_REOPEN_EVENT = "thread.night.reopened";
76
+
77
+ /** The store meta row the night writes its "may be done" list to (JSON; replaced each night). */
78
+ export const MAY_BE_DONE_META = "open.mayBeDone";
79
+
80
+ /** Working defaults, held lightly (2026-11-07). Read at use. */
81
+ export const OPEN_CLOSE_TUNABLES = {
82
+ /** The switch. Off: the phase runs, closes nothing, lists nothing, and counts `switched-off`. */
83
+ ON: true as boolean,
84
+ /**
85
+ * The release must be written in the item's own folder. A version series
86
+ * is one project's ("0.3.x" in another folder may be another product). CAL.
87
+ */
88
+ SAME_FOLDER: true as boolean,
89
+ /** "May be done" entries kept a night at most. CAL. */
90
+ MAY_BE_DONE_MAX: 200 as number,
91
+ /** Reflection proposals older than this many lived days are not listed. CAL. */
92
+ PROPOSED_DAYS: 7 as number,
93
+ /** The morning line names at most this many closes, then "+N more". CAL. */
94
+ MORNING_SHOWN: 5 as number,
95
+ /** A title in the morning line is clipped to this many characters. CAL. */
96
+ MORNING_TITLE_CHARS: 70 as number,
97
+ };
98
+
99
+ /** Who closed it, beside the flag (`threadClosedBy`) when the night did. */
100
+ export interface NightClosedBy {
101
+ readonly by: "night";
102
+ readonly day: number;
103
+ readonly rule: string;
104
+ readonly shows: string;
105
+ readonly why: string;
106
+ }
107
+
108
+ /** One close: the item, the memory that showed it done, the rule, and the why in a few words. */
109
+ export interface NightClose {
110
+ readonly id: string;
111
+ readonly shows: string;
112
+ readonly rule: string;
113
+ /** `0.3.46→0.3.50`. */
114
+ readonly key: string;
115
+ /** "0.3.50 released". */
116
+ readonly why: string;
117
+ }
118
+
119
+ /** One "may be done": the item, why it might be, and the memory, when one shows it. */
120
+ export interface MayBeDone {
121
+ readonly id: string;
122
+ readonly why: string;
123
+ readonly shows?: string;
124
+ readonly from: "night" | "reflection";
125
+ }
126
+
127
+ /** Why an open item was not closed, one word each (the phase's `skipped`). */
128
+ export type OpenCloseSkip =
129
+ | "not-open"
130
+ | "held"
131
+ | "asked"
132
+ | "reopened"
133
+ | "a-check"
134
+ | "conditional"
135
+ | "no-subject"
136
+ | "not-a-release-step"
137
+ | "a-problem"
138
+ | "no-later-release"
139
+ | "refused";
140
+
141
+ export interface OpenCloseInput {
142
+ readonly day: number;
143
+ /** False under observer: write nothing, count what a night would close. */
144
+ readonly apply: boolean;
145
+ /** Closes a night at most; the rest wait, counted. */
146
+ readonly budget: number;
147
+ }
148
+
149
+ export interface OpenCloseOutcome {
150
+ readonly on: boolean;
151
+ /** Open items judged. */
152
+ readonly examined: number;
153
+ readonly closed: readonly NightClose[];
154
+ /** What the night saw but would not close. */
155
+ readonly mayBeDone: readonly MayBeDone[];
156
+ readonly skipped: Readonly<Record<string, number>>;
157
+ readonly skippedForLimit: number;
158
+ }
159
+
160
+ /** A check is when something comes due, never what a release settles. */
161
+ const A_CHECK = /\bcheck(?:ed|s)?\b|CHECK-AFTER|\bre-?read\b|\bre-?check\b/i;
162
+ /** The version as a condition, not a subject: `after 0.3.45`, `once 0.3.47 ships`, `until 0.3.48`. */
163
+ const CONDITIONAL = /\b(?:after|once|when|until|post|before|since|by|in|into|for|aimed\s+at|ride|rides|riding)\s+(?:counterparts@|v)?\d{1,3}\.\d{1,3}\.\d{1,4}(?![\w.])/i;
164
+ /**
165
+ * A PROBLEM, NOT A STEP (review of #782): an item about something wrong with
166
+ * a build ("0.3.46 cut breaks the wake", "0.3.46 ready but the migration drops
167
+ * tags; fix before any release") is a debt a later release doesn't pay.
168
+ */
169
+ const A_PROBLEM = /\b(?:break|breaks|breaking|broke|broken|fail|fails|failed|failing|failure|bug|bugs|buggy|missing|crash|crashes|crashed|regress\w*|wrong|fix|fixes|fixed|fixing)\b/i;
170
+ /** A version, `major.minor.patch`, not part of a longer dotted run (as `interference.ts` reads one). */
171
+ const VERSION = /(?<![\w.])v?(\d{1,3})\.(\d{1,3})\.(\d{1,4})(?![\w]|\.\d)/g;
172
+ /**
173
+ * WHAT AN ITEM MAY BE (review of #782, the brief's words): a release step
174
+ * still owed — ready, ready to publish, after-publish, publish — beside the
175
+ * version. Never cut, built, packed, pushed, merged, approved, reviewed,
176
+ * queued or tagged: those name a state a bug report also names.
177
+ */
178
+ const ITEM_AFTER = /^(?:-[\w]+)?\s*[:,]?(?:\s+(?:is|now|all|fully|being|just|also|still))*\s+(?:ready|after-publish|to\s+publish|publish)(?![\w-])/i;
179
+ const ITEM_BEFORE = /(?<![\w.@/-])(?:ready\s+to\s+(?:publish|release)|to\s+publish|publish|publishing)(?:\s+(?:counterparts|version|v))?\s*@?\s*$/i;
180
+ /** The word right before a version that is no product name: verbs, fillers, determiners, the default names. */
181
+ const NOT_A_PRODUCT = /^(?:v|version|release|releases|counterparts|npm|the|a|an|of|for|to|and|or|is|was|now|fully|finally|just|then|also|has|been|being|after|ready|publish|published|released|shipped|deployed|installed|landed|tagged|merged|cut|built|packed|queued|pushed|mike|i|we)$/i;
182
+
183
+ /**
184
+ * WHICH PRODUCT A VERSION IS (review of #782): the word right before it —
185
+ * "site 0.3.46", "counterparts@0.3.50" — or null for the folder's own (no
186
+ * word, a verb, a filler, a date). Two different products' "0.3.x" are two
187
+ * series. Pure.
188
+ */
189
+ function productBefore(text: string, start: number): string | null {
190
+ const m = /([A-Za-z][\w-]*)[@\s]*$/.exec(text.slice(Math.max(0, start - 40), start));
191
+ if (m === null) return null;
192
+ const w = (m[1] ?? "").toLowerCase();
193
+ return NOT_A_PRODUCT.test(w) ? null : w;
194
+ }
195
+
196
+ /** An item's release steps: each series' LOWEST owed patch and its product, read beside the version. Pure. */
197
+ function itemSteps(head: string): Map<string, { patch: number; product: string | null }> {
198
+ const out = new Map<string, { patch: number; product: string | null }>();
199
+ for (const m of head.matchAll(VERSION)) {
200
+ const start = m.index;
201
+ const end = start + m[0].length;
202
+ if (!ITEM_AFTER.test(head.slice(end)) && !ITEM_BEFORE.test(head.slice(0, start))) continue;
203
+ const series = `${Number(m[1])}.${Number(m[2])}`;
204
+ const patch = Number(m[3]);
205
+ const had = out.get(series);
206
+ if (had === undefined || patch < had.patch) out.set(series, { patch, product: productBefore(head, start) });
207
+ }
208
+ return out;
209
+ }
210
+
211
+ /** The product before each released version in an evidence headline, per series. */
212
+ function releaseProducts(head: string, released: ReadonlyMap<string, number>): Map<string, string | null> {
213
+ const out = new Map<string, string | null>();
214
+ for (const m of head.matchAll(VERSION)) {
215
+ const series = `${Number(m[1])}.${Number(m[2])}`;
216
+ if (released.get(series) !== Number(m[3]) || out.has(series)) continue;
217
+ out.set(series, productBefore(head, m.index));
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /** A PR number: `#739`, `PR #41`. */
223
+ const PR = /(?<![\w&])#(\d{2,6})\b/g;
224
+
225
+ /** The night-closed record on a memory's meta, or null. */
226
+ export function nightClosedOf(meta: Readonly<Record<string, unknown>>): NightClosedBy | null {
227
+ const v = meta[THREAD_CLOSED_BY_META_KEY];
228
+ if (typeof v !== "object" || v === null) return null;
229
+ const r = v as Record<string, unknown>;
230
+ if (r["by"] !== "night") return null;
231
+ return {
232
+ by: "night",
233
+ day: typeof r["day"] === "number" ? r["day"] : 0,
234
+ rule: typeof r["rule"] === "string" ? r["rule"] : NIGHT_CLOSE_RULE,
235
+ shows: typeof r["shows"] === "string" ? r["shows"] : "",
236
+ why: typeof r["why"] === "string" ? r["why"] : "",
237
+ };
238
+ }
239
+
240
+ /** Did a later memory's headline say PR `n` was merged (the verb right beside it)? */
241
+ function saysMerged(text: string, n: string): boolean {
242
+ // A few words may stand between, as a name does ("#547 sidebar split merged"): this only lists, never closes.
243
+ const after = new RegExp(String.raw`(?<![\w&])#${n}\b(?:\s*\([^)]{0,40}\))?(?:\s+[\w-]+){0,3}?\s+merged\b`, "i");
244
+ const before = new RegExp(String.raw`\bmerged\s+(?:PR\s+|pull\s+)?#${n}\b`, "i");
245
+ return after.test(text) || before.test(text);
246
+ }
247
+
248
+ /** The release a memory's headline says happened, per series: its highest FINAL patch. */
249
+ function releasesOf(keys: SubjectKeys): Map<string, number> {
250
+ const out = new Map<string, number>();
251
+ for (const [series, patch] of keys.versions) if (keys.final.get(series) === true) out.set(series, patch);
252
+ return out;
253
+ }
254
+
255
+ interface Evidence {
256
+ readonly row: WorkEventRow;
257
+ readonly head: string;
258
+ readonly at: number;
259
+ readonly released: ReadonlyMap<string, number>;
260
+ /** The product named before each released version (null: the folder's own). */
261
+ readonly products: ReadonlyMap<string, string | null>;
262
+ /** Written `done`: only such a memory is evidence for a close (review of #782); an unmarked one may only list. */
263
+ readonly done: boolean;
264
+ }
265
+
266
+ /**
267
+ * THE NIGHT'S CLOSE SWEEP: every open item the one rule reads as settled by
268
+ * a later release in its folder, closed (`closeThread`'s write, with who and
269
+ * why), oldest first, `budget` a night; and the "may be done" list replaced.
270
+ * Under observer it counts and writes nothing. Never throws for one item: a
271
+ * write that fails is counted `refused`.
272
+ */
273
+ export function openCloseSweep(store: Store, input: OpenCloseInput): OpenCloseOutcome {
274
+ const skipped: Record<string, number> = {};
275
+ const skip = (why: OpenCloseSkip): void => {
276
+ skipped[why] = (skipped[why] ?? 0) + 1;
277
+ };
278
+ if (!OPEN_CLOSE_TUNABLES.ON) return { on: false, examined: 0, closed: [], mayBeDone: [], skipped, skippedForLimit: 0 };
279
+ const T = OPEN_CLOSE_TUNABLES;
280
+ const slot = (scope: string): string => (T.SAME_FOLDER ? scope : "*");
281
+
282
+ // The later side: live authored work memories, done or unmarked, by folder.
283
+ // Only a `done` one closes ("Plan: 0.3.50 released by Friday", "0.3.50
284
+ // released? Not yet" are unmarked); an unmarked one may only list.
285
+ const evidence = new Map<string, Evidence[]>();
286
+ for (const r of store.workEventRows()) {
287
+ if (r.status !== null && r.status !== "done") continue;
288
+ const head = headline(r);
289
+ const released = releasesOf(subjectKeys(head, "done"));
290
+ const ev: Evidence = { row: r, head, at: r.createdAt, released, products: releaseProducts(head, released), done: r.status === "done" };
291
+ const list = evidence.get(slot(r.scope)) ?? [];
292
+ list.push(ev);
293
+ evidence.set(slot(r.scope), list);
294
+ }
295
+ const laterThan = (e: Evidence, item: { at: number | null; day: number; id: string }): boolean =>
296
+ e.row.id !== item.id && (item.at !== null && item.at > 0 && e.at > 0 ? e.at > item.at : e.row.birthDay > item.day);
297
+
298
+ const closed: NightClose[] = [];
299
+ const maybe: MayBeDone[] = [];
300
+ let examined = 0;
301
+ let skippedForLimit = 0;
302
+ for (const id of store.openThreadIds()) {
303
+ const row = store.row(id);
304
+ // Open as the wake reads it (`self/identity.ts#openThread`): one already
305
+ // settled over under a successor is not an open item, whatever its flag.
306
+ if (row === undefined || !openThread(store, id)) {
307
+ skip("not-open");
308
+ continue;
309
+ }
310
+ let meta: Record<string, unknown>;
311
+ try {
312
+ meta = store.readProse(id).meta;
313
+ } catch {
314
+ skip("not-open");
315
+ continue;
316
+ }
317
+ if (meta[UNRESOLVED_META_KEY] !== true) {
318
+ skip("not-open");
319
+ continue;
320
+ }
321
+ examined += 1;
322
+ const head = headline({ title: row.title ?? null, body: row.body });
323
+ const settles = settlesWhenOf(meta);
324
+ const scope = row.origin_scope ?? "";
325
+ const pool = scope.length === 0 ? [] : (evidence.get(slot(scope)) ?? []);
326
+ const item = { at: row.created_at ?? null, day: row.birth_day, id };
327
+ const later = pool.filter((e) => laterThan(e, item));
328
+
329
+ // What it might be, for the "may be done" list, when it isn't closed.
330
+ const mayBe = (): MayBeDone | null => {
331
+ if (A_CHECK.test(head)) return null;
332
+ const words = [head, settles ?? ""].join(" \n ");
333
+ // A release step whose series moved on.
334
+ if (!CONDITIONAL.test(words)) {
335
+ const named = subjectKeys(words, "any");
336
+ let best: { e: Evidence; series: string; patch: number; theirs: number } | null = null;
337
+ for (const [series, patch] of named.versions) {
338
+ for (const e of later) {
339
+ const theirs = e.released.get(series);
340
+ if (theirs === undefined || theirs <= patch) continue;
341
+ if (best === null || theirs - patch < best.theirs - best.patch) best = { e, series, patch, theirs };
342
+ }
343
+ }
344
+ if (best !== null) return { id, why: `${best.series}.${String(best.theirs)} released since`, shows: best.e.row.id, from: "night" };
345
+ }
346
+ // A PR a later memory says merged.
347
+ for (const m of words.matchAll(PR)) {
348
+ const n = m[1] as string;
349
+ const e = later.find((x) => saysMerged(x.head, n));
350
+ if (e !== undefined) return { id, why: `#${n} merged since`, shows: e.row.id, from: "night" };
351
+ }
352
+ return null;
353
+ };
354
+ const notClosed = (why: OpenCloseSkip): void => {
355
+ skip(why);
356
+ const m = mayBe();
357
+ if (m !== null && maybe.length < T.MAY_BE_DONE_MAX) maybe.push(m);
358
+ };
359
+
360
+ if (row.protected === 1) {
361
+ skip("held");
362
+ continue;
363
+ }
364
+ if (row.status === "asked") {
365
+ notClosed("asked");
366
+ continue;
367
+ }
368
+ if (typeof meta[THREAD_REOPENED_BY_META_KEY] === "string") {
369
+ notClosed("reopened");
370
+ continue;
371
+ }
372
+ if (A_CHECK.test(head)) {
373
+ skip("a-check");
374
+ continue;
375
+ }
376
+ if (CONDITIONAL.test(head)) {
377
+ notClosed("conditional");
378
+ continue;
379
+ }
380
+ if (A_PROBLEM.test(head)) {
381
+ notClosed("a-problem");
382
+ continue;
383
+ }
384
+ const steps = itemSteps(head);
385
+ if (steps.size === 0) {
386
+ notClosed(subjectKeys(head, "any").versions.size === 0 ? "no-subject" : "not-a-release-step");
387
+ continue;
388
+ }
389
+ // The NEAREST later release, written done, of the same product: the fewest
390
+ // patches on (strictly more: W < Z), then the earliest written.
391
+ let best: { e: Evidence; key: string; gap: number } | null = null;
392
+ for (const e of later) {
393
+ if (!e.done || e.released.size === 0) continue;
394
+ for (const [series, step] of steps) {
395
+ const theirs = e.released.get(series);
396
+ if (theirs === undefined || theirs <= step.patch) continue;
397
+ if ((e.products.get(series) ?? null) !== step.product) continue;
398
+ const gap = theirs - step.patch;
399
+ if (best === null || gap < best.gap || (gap === best.gap && e.at < best.e.at)) best = { e, key: `${series}.${String(step.patch)}→${series}.${String(theirs)}`, gap };
400
+ }
401
+ }
402
+ if (best === null) {
403
+ notClosed("no-later-release");
404
+ continue;
405
+ }
406
+ if (closed.length >= input.budget) {
407
+ skippedForLimit += 1;
408
+ continue;
409
+ }
410
+ const to = best.key.split("→")[1] ?? "";
411
+ const c: NightClose = { id, shows: best.e.row.id, rule: NIGHT_CLOSE_RULE, key: best.key, why: `${to} released` };
412
+ if (!input.apply) {
413
+ closed.push(c);
414
+ continue;
415
+ }
416
+ if (!writeClose(store, c, input.day)) {
417
+ skip("refused");
418
+ continue;
419
+ }
420
+ closed.push(c);
421
+ }
422
+ if (input.apply) {
423
+ try {
424
+ store.setMeta(MAY_BE_DONE_META, JSON.stringify({ day: input.day, items: maybe.map((m) => ({ id: m.id, why: m.why, ...(m.shows === undefined ? {} : { shows: m.shows }) })) }));
425
+ } catch {
426
+ /* the list is a convenience: a failed write leaves last night's */
427
+ }
428
+ }
429
+ return { on: true, examined, closed, mayBeDone: maybe, skipped, skippedForLimit };
430
+ }
431
+
432
+ /** The close itself: the flag false with who and why beside it, and one durable row. False when the write fails. */
433
+ function writeClose(store: Store, c: NightClose, day: number): boolean {
434
+ const by: NightClosedBy = { by: "night", day, rule: c.rule, shows: c.shows, why: c.why };
435
+ try {
436
+ store.revise(c.id, { meta: { [UNRESOLVED_META_KEY]: false, [THREAD_CLOSED_BY_META_KEY]: by }, reason: "thread-closed" });
437
+ } catch {
438
+ return false;
439
+ }
440
+ try {
441
+ store.appendEvent({ name: NIGHT_CLOSE_EVENT, day, ref: c.id, payload: { id: c.id, shows: c.shows, rule: c.rule, key: c.key, reason: c.why, day } });
442
+ } catch {
443
+ /* the meta carries it; the row is the count */
444
+ }
445
+ return true;
446
+ }
447
+
448
+ /**
449
+ * REOPEN A NIGHT-CLOSED ITEM (the way back): the flag true again, reason
450
+ * `thread-reopened`, `threadReopenedBy` set so no night closes it again on
451
+ * its own, and one `thread.night.reopened` row naming what touched it
452
+ * (`reopen`: the reflect tool's phase, on the owner's word; `updates`: a
453
+ * write that carried the thread on). `restoreFlag` false: the thread lives
454
+ * on a successor (an `updates` that said `unresolved: true`), so only the
455
+ * record is written. Returns false when the item wasn't closed by a night.
456
+ */
457
+ export function reopenNightClosed(store: Store, id: string, via: { readonly by: "reopen" | "updates"; readonly session?: string | null; readonly successor?: string | null; readonly restoreFlag: boolean }): boolean {
458
+ let meta: Record<string, unknown>;
459
+ try {
460
+ meta = store.readProse(id).meta;
461
+ } catch {
462
+ return false;
463
+ }
464
+ const closedBy = nightClosedOf(meta);
465
+ if (closedBy === null) return false;
466
+ let undone = 0;
467
+ if (!via.restoreFlag) {
468
+ // The thread went on on a successor: this row stays closed, but no longer as the night's close.
469
+ store.revise(id, { meta: { [THREAD_CLOSED_BY_META_KEY]: null, [THREAD_REOPENED_BY_META_KEY]: `night:${String(closedBy.day)}` }, reason: "thread-reopened" });
470
+ }
471
+ if (via.restoreFlag) {
472
+ // The night's record leaves with the close (review of #782): a later close or reopen is never mistaken for this one.
473
+ store.revise(id, { meta: { [UNRESOLVED_META_KEY]: true, [THREAD_REOPENED_BY_META_KEY]: `night:${String(closedBy.day)}`, [THREAD_CLOSED_BY_META_KEY]: null }, reason: "thread-reopened" });
474
+ // A closed item a later night's interference sweep faded under a newer
475
+ // work event (`interference.ts`) is settled over, so out of Still open
476
+ // whatever its flag says: that fade is undone too, and the sweep's
477
+ // one-cut rule keeps it from fading again.
478
+ try {
479
+ for (const p of store.contradictionsOf([id]).get(id) ?? []) {
480
+ if (p.source !== INTERFERENCE_SOURCE || p.a !== id || p.state !== "settled") continue;
481
+ if (undo(store, { pair: p.id, actor: "session", actorId: via.session ?? null, why: "a night-closed item reopened" }).ok) undone += 1;
482
+ }
483
+ } catch {
484
+ /* the flag is back; a fade left in place is the slow curve's */
485
+ }
486
+ }
487
+ try {
488
+ store.appendEvent({
489
+ name: NIGHT_REOPEN_EVENT,
490
+ day: store.livedDay(),
491
+ ref: id,
492
+ payload: { id, by: via.by, closedOn: closedBy.day, rule: closedBy.rule, ...(undone > 0 ? { fadeUndone: undone } : {}), ...(via.session ? { session: via.session } : {}), ...(via.successor ? { successor: via.successor } : {}) },
493
+ });
494
+ } catch {
495
+ /* the flag is the state; the row is the count */
496
+ }
497
+ return true;
498
+ }
499
+
500
+ /**
501
+ * WHAT MAY BE DONE, by item (read at `recall "still open"`): the night's list
502
+ * (`MAY_BE_DONE_META`), then what the newest reflections thought looks done
503
+ * but weren't sure of (their `closeProposed`, within `PROPOSED_DAYS` lived
504
+ * days). Only items still open. Never throws: an unreadable store lists none.
505
+ */
506
+ export function mayBeDoneOf(store: Store): Map<string, MayBeDone> {
507
+ const out = new Map<string, MayBeDone>();
508
+ const stillOpen = (id: string): boolean => {
509
+ try {
510
+ return store.readProse(id).meta[UNRESOLVED_META_KEY] === true;
511
+ } catch {
512
+ return false;
513
+ }
514
+ };
515
+ try {
516
+ const raw = store.getMeta(MAY_BE_DONE_META);
517
+ if (raw !== undefined) {
518
+ const parsed = JSON.parse(raw) as { items?: unknown };
519
+ for (const x of Array.isArray(parsed.items) ? parsed.items : []) {
520
+ if (typeof x !== "object" || x === null) continue;
521
+ const r = x as Record<string, unknown>;
522
+ if (typeof r["id"] !== "string" || typeof r["why"] !== "string") continue;
523
+ out.set(r["id"], { id: r["id"], why: r["why"], ...(typeof r["shows"] === "string" ? { shows: r["shows"] } : {}), from: "night" });
524
+ }
525
+ }
526
+ } catch {
527
+ /* none from the night */
528
+ }
529
+ try {
530
+ const day = store.livedDay();
531
+ for (const r of store.reflections({ limit: 7 })) {
532
+ const birth = typeof r.day === "number" ? r.day : day;
533
+ if (day - birth > OPEN_CLOSE_TUNABLES.PROPOSED_DAYS) continue;
534
+ let d: Record<string, unknown> = {};
535
+ try {
536
+ d = JSON.parse(r.detail ?? "{}") as Record<string, unknown>;
537
+ } catch {
538
+ continue;
539
+ }
540
+ const ids = Array.isArray(d["closeProposed"]) ? d["closeProposed"].filter((x): x is string => typeof x === "string") : [];
541
+ for (const id of ids) if (!out.has(id)) out.set(id, { id, why: "the night's reflection thought it looks done", from: "reflection" });
542
+ }
543
+ } catch {
544
+ /* none from the reflections */
545
+ }
546
+ for (const id of [...out.keys()]) if (!stillOpen(id)) out.delete(id);
547
+ return out;
548
+ }
549
+
550
+ /** True when a memory was reopened after the night closed it (its `threadReopenedBy` names a night). */
551
+ export function reopenedFromNight(meta: Readonly<Record<string, unknown>>): boolean {
552
+ const v = meta[THREAD_REOPENED_BY_META_KEY];
553
+ return typeof v === "string" && v.startsWith("night:");
554
+ }
555
+
556
+ /**
557
+ * The closes of the newest night that closed anything, at or after lived day
558
+ * `sinceDay`, oldest first — only the ones that still stand as that night's
559
+ * close (review of #782: one reopened since is not said again).
560
+ */
561
+ export function lastNightCloses(store: Store, sinceDay: number): NightClose[] {
562
+ try {
563
+ const rows = store.eventLog({ name: NIGHT_CLOSE_EVENT, sinceDay, order: "desc", limit: 200 });
564
+ if (rows.length === 0) return [];
565
+ const newest = rows[0]?.day;
566
+ return rows
567
+ .filter((e) => e.day === newest)
568
+ .reverse()
569
+ .flatMap((e) => {
570
+ try {
571
+ const p = JSON.parse(e.payload ?? "{}") as Record<string, unknown>;
572
+ if (typeof p["id"] !== "string") return [];
573
+ const by = nightClosedOf(store.readProse(p["id"]).meta);
574
+ if (by === null || by.day !== e.day) return [];
575
+ return [{ id: p["id"], shows: typeof p["shows"] === "string" ? p["shows"] : "", rule: typeof p["rule"] === "string" ? p["rule"] : NIGHT_CLOSE_RULE, key: typeof p["key"] === "string" ? p["key"] : "", why: typeof p["reason"] === "string" ? p["reason"] : "" }];
576
+ } catch {
577
+ return [];
578
+ }
579
+ });
580
+ } catch {
581
+ return [];
582
+ }
583
+ }
@@ -116,6 +116,13 @@ clothes. **Hold debts, lose deadlines.**
116
116
  which now gates only a date a caller extracted. *(Since 2026-10-10 decay IS exempted
117
117
  before arrival — G10 below is reversed: physics holds a pending date, and `faded` refuses
118
118
  only after the window.)* Archived, skill and journal still refuse.
119
+ **A done memory dated today or earlier is refused `done`** (SO1 step 2, 2026-11-07,
120
+ lightly held): `status: done`, not repeating, and every window's last day on or before
121
+ the day asked about (a done dated today has happened, coordinator 11-07). Its date says
122
+ when it happened, so it neither arrives (cue, wake lane, Coming up, due today) nor counts
123
+ overdue, and `plainDue` tells it neither on its day nor late. Read off the row at derive
124
+ time, so older rows need no migration. A repeat is exempt (a done there closes one
125
+ occurrence, `closeOccurrence`); a done whose date ends after today is left alone.
119
126
  - **Precision is carried by the date's own format**, never rounded, and the ramp differs by
120
127
  precision — a stated month *means* early month more than the 29th. [v1] §12 G4. Since
121
128
  2026-09-26 there are four shapes (`core/time.ts`): a day, a month, a year (no window), and
@@ -164,6 +171,23 @@ clothes. **Hold debts, lose deadlines.**
164
171
  **A closed folder's work is held back from the lines above a wake** (2026-10-30, `Counterpart#plainHeldBack`): not
165
172
  offered to the delivery, so nothing claims it, and not handed over as a quiet cue either. Told after its folder turns
166
173
  on: on its day, or as its late beat inside the grace. No folder, or marked me, us, owner or world: told, whatever the folder.
174
+ **Another folder's is held back too** (SO1 step 3, 2026-11-07, `Counterpart#plainAway`): a reminder written in an open
175
+ folder that isn't the reader's (nor joined to it as one project), work or marked world, waits for its own folder's
176
+ first wake that day, unclaimed, so that wake tells it whole. Marked me, us or owner, or with no folder: told
177
+ everywhere. A reader with no folder (a claude.ai chat) is told only the personal ones.
178
+ **The fallback, so a real deadline can't go silent** (fix round of #780, `Counterpart#plainCrossing`): one held back
179
+ this way that went unsaid through its window (no beat told; a late beat counts only if told) crosses ONCE,
180
+ `PLAIN_CROSS_AFTER_LIVED_DAYS` (2) lived days past its last day, with its folder named ("garden: title, due …").
181
+ Only at a person's session start, or a wake tool call the host says a person is at (`CLAUDE_CODE_SESSION_ATTENDED`),
182
+ in a folder: never per prompt, never into a chat with no folder. A lived day is a calendar day a session start's
183
+ presence row (`adapter.wake.injected`, interactive) names, the one source doctor reads too (`adapters/presence.ts`).
184
+ Its latch is its own row (`prospective.plain.crossed`, once per memory and window across every folder), not a beat;
185
+ once crossed, its own folder's late beat doesn't say it again. Not a closed folder's, not a repeating one, not one
186
+ marked done or that already happened, not one of my own checks (CHECK-AFTER, "Check due", "Check ~", "Experiment
187
+ check" in its title or settles-when: those wait for their folder), not one more than `PLAIN_CROSS_LOOKBACK_DAYS` (30)
188
+ past its last day. A day with nothing unsaid is memoised (`prospective.cross.none`), so later starts that day cost one
189
+ meta read. Doctor reads one due while its folder had no session as info, and as a miss only once the day it should
190
+ have crossed has passed with a session and it still wasn't said.
167
191
 
168
192
  ## 4. Drops / simplifies
169
193
 
@@ -60,7 +60,11 @@ export type DeriveReason =
60
60
  * (`DerivableMemory.recurring`, review of #341, 2026-10-09). */
61
61
  | "faded"
62
62
  /** Every derived window is behind us — the property expiring by itself. */
63
- | "window-passed";
63
+ | "window-passed"
64
+ /** Marked done (`status: done`), not repeating, and its date ending on or
65
+ * before the day asked about (SO1 step 2, 2026-11-07): the date says when it
66
+ * HAPPENED, never a reminder, so it neither arrives nor reads as overdue. */
67
+ | "done";
64
68
 
65
69
  /** Kinds that can never tactfully arrive. `task-state` is excluded STRUCTURALLY:
66
70
  * v2's `Kind` has no such member, so it is a type error, not a runtime refusal
@@ -126,6 +130,18 @@ export interface DerivableMemory {
126
130
  * waived. Absent or false: `faded` refuses as before.
127
131
  */
128
132
  readonly recurring?: boolean;
133
+ /**
134
+ * Its status is `done` (v12 `memories.status`; SO1 step 2, 2026-11-07,
135
+ * lightly held). With a date ending on or before the day asked about (a done
136
+ * dated today has happened, coordinator 11-07), the date is
137
+ * when it happened, not a reminder: refused `done` (Mike's store on 11-07:
138
+ * "Handoff for 11-07 written" and "Night test PASSED" read as overdue in
139
+ * Coming up). A repeat is exempt: a done there closes one occurrence
140
+ * (`Prospective#closeOccurrence`), never the reminder. A done with a date
141
+ * after the day asked (tomorrow on) is left alone (ambiguous). Read at derive time off the row, so
142
+ * rows written before this need no migration. Absent or false: not done.
143
+ */
144
+ readonly done?: boolean;
129
145
  }
130
146
 
131
147
  /** A content-date the CALLER extracted. Its precision is its own shape (§12 G4). */
@@ -235,6 +251,11 @@ export function derive(
235
251
  } else if (windows.every((w) => w.phase === "passed")) {
236
252
  blockedBy.push("window-passed");
237
253
  }
254
+ // Done, its date today or behind us (SO1 step 2): its date is when it happened.
255
+ // `lastDay`, so a month or a range still running past `at` is left alone.
256
+ if (memory.done === true && memory.recurring !== true && windows.length > 0 && windows.every((w) => w.lastDay <= at)) {
257
+ blockedBy.push("done");
258
+ }
238
259
 
239
260
  return {
240
261
  memoryId: memory.id,