counterparts 0.3.12 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/docs/module-map.md +1 -1
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +36 -10
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  6. package/src/adapters/claude-code/NOTES.md +131 -0
  7. package/src/adapters/claude-code/bin/hook.ts +35 -2
  8. package/src/adapters/claude-code/doctor.ts +155 -21
  9. package/src/adapters/claude-code/hooks.ts +49 -7
  10. package/src/adapters/claude-code/index.ts +11 -0
  11. package/src/adapters/claude-code/night-run.ts +133 -12
  12. package/src/adapters/claude-code/transcript.ts +268 -1
  13. package/src/adapters/cli/CONTRACT.md +5 -0
  14. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  15. package/src/adapters/cli/NOTES.md +111 -0
  16. package/src/adapters/cli/commands.ts +65 -14
  17. package/src/adapters/cli/dream-core.ts +57 -42
  18. package/src/adapters/cli/export.ts +320 -21
  19. package/src/adapters/cli/index.ts +1 -0
  20. package/src/adapters/cli/install.ts +39 -7
  21. package/src/adapters/cli/mechanisms.ts +7 -1
  22. package/src/adapters/cli/uninstall.ts +13 -5
  23. package/src/adapters/cli/wire.ts +189 -63
  24. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  25. package/src/adapters/dashboard/NOTES.md +79 -0
  26. package/src/adapters/dashboard/registries.ts +10 -2
  27. package/src/adapters/dashboard/web/README.md +19 -14
  28. package/src/adapters/dashboard/web/actions.ts +23 -1
  29. package/src/adapters/dashboard/web/flow.ts +4 -1
  30. package/src/adapters/dashboard/web/lanes.ts +3 -0
  31. package/src/adapters/dashboard/web/narrate.ts +30 -2
  32. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  33. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  34. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  35. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  36. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  37. package/src/adapters/dashboard/web/server.ts +0 -5
  38. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  39. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  40. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  41. package/src/adapters/dashboard/web/views/health.ts +1 -1
  42. package/src/adapters/dashboard/web/views/search.ts +4 -45
  43. package/src/adapters/dashboard/web/views.ts +2 -2
  44. package/src/adapters/fired.ts +410 -25
  45. package/src/adapters/host-wiring.ts +300 -0
  46. package/src/adapters/lifecycle.ts +14 -0
  47. package/src/adapters/log/index.ts +2 -0
  48. package/src/adapters/mcp/CONTRACT.md +33 -3
  49. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  50. package/src/adapters/mcp/NOTES.md +136 -0
  51. package/src/adapters/mcp/bin/serve.ts +30 -0
  52. package/src/adapters/mcp/facts.ts +13 -1
  53. package/src/adapters/mcp/meaning.ts +208 -13
  54. package/src/adapters/mcp/server.ts +87 -15
  55. package/src/adapters/mcp/stdio.ts +3 -1
  56. package/src/adapters/mcp/stood-down.ts +51 -0
  57. package/src/adapters/mcp/tools.ts +27 -7
  58. package/src/adapters/plugin-run.sh +133 -0
  59. package/src/adapters/plugin.ts +329 -0
  60. package/src/core/associate/CONTRACT.md +2 -1
  61. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  62. package/src/core/associate/NOTES.md +45 -0
  63. package/src/core/briefing.ts +12 -3
  64. package/src/core/contradictions.ts +184 -0
  65. package/src/core/counterpart.ts +451 -18
  66. package/src/core/dream/CONTRACT.md +5 -2
  67. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  68. package/src/core/dream/NOTES.md +21 -0
  69. package/src/core/dream/index.ts +33 -1
  70. package/src/core/dream/reflect.ts +20 -5
  71. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  72. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  73. package/src/core/fit/NOTES.md +5 -2
  74. package/src/core/fit/index.ts +4 -1
  75. package/src/core/handoff/CONTRACT.md +37 -2
  76. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  77. package/src/core/handoff/NOTES.md +66 -0
  78. package/src/core/handoff/index.ts +214 -12
  79. package/src/core/mint.ts +8 -2
  80. package/src/core/physics/CONTRACT.md +11 -1
  81. package/src/core/physics/NOTES.md +30 -0
  82. package/src/core/physics/index.ts +26 -4
  83. package/src/core/prospective/CONTRACT.md +45 -6
  84. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  85. package/src/core/prospective/NOTES.md +138 -0
  86. package/src/core/prospective/derive.ts +33 -5
  87. package/src/core/prospective/index.ts +90 -5
  88. package/src/core/prospective/windows.ts +72 -1
  89. package/src/core/recall/CONTRACT.md +6 -2
  90. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  91. package/src/core/recall/NOTES.md +57 -1
  92. package/src/core/recall/probe.ts +58 -0
  93. package/src/core/recall/session.ts +27 -3
  94. package/src/core/recall/time-ask.ts +116 -18
  95. package/src/core/remember/CONTRACT.md +4 -1
  96. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  97. package/src/core/remember/proposals.ts +38 -5
  98. package/src/core/revision.ts +5 -0
  99. package/src/core/schemas/CONTRACT.md +13 -1
  100. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  101. package/src/core/schemas/NOTES.md +127 -0
  102. package/src/core/schemas/types.ts +2 -0
  103. package/src/core/self/CONTRACT.md +15 -4
  104. package/src/core/self/INTERFACE-GAPS.md +7 -2
  105. package/src/core/self/NOTES.md +49 -0
  106. package/src/core/self/briefing.ts +12 -2
  107. package/src/core/self/index.ts +82 -8
  108. package/src/core/self/page.ts +88 -0
  109. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  110. package/src/core/sleep/NOTES.md +11 -0
  111. package/src/core/sleep/prune.ts +6 -2
  112. package/src/core/store/NOTES.md +14 -0
  113. package/src/core/store/index.ts +107 -0
  114. package/src/core/time.ts +152 -0
  115. package/tools/install-loop/run.sh +48 -12
  116. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -12,12 +12,13 @@ import type { Counterpart } from "../../core/counterpart.js";
12
12
  import { nightPartsWords, nightRunWords } from "../../core/dream/index.js";
13
13
  import type { DreamingSetting, NightRun } from "../../core/dream/index.js";
14
14
  import { acceptsReflectedFeeling } from "../../core/sleep/index.js";
15
- import type { ReflectionRow } from "../../core/store/index.js";
15
+ import type { DreamChangeRow, ReflectionRow, Store } from "../../core/store/index.js";
16
16
 
17
- /** How a memory id reads in a list: its first line, or why it is not shown. */
18
- export function memoryWords(counterpart: Counterpart, id: string | null, max = 80): string {
17
+ /** How a memory id reads in a list: its first line, or why it is not shown.
18
+ * Only the store is read, so `export --markdown` asks it too. */
19
+ export function memoryWords(source: { readonly store: Store }, id: string | null, max = 80): string {
19
20
  if (id === null) return "(removed by the owner)";
20
- const row = counterpart.store.row(id);
21
+ const row = source.store.row(id);
21
22
  if (row === undefined) return "(no such memory)";
22
23
  if (row.confidential === 1) return "[confidential]";
23
24
  if (row.body === "") return "(removed by the owner)";
@@ -97,7 +98,7 @@ export function dreamListLines(counterpart: Counterpart, limit: number | "all" =
97
98
  return out;
98
99
  }
99
100
 
100
- function parseIdList(json: string): string[] {
101
+ export function parseIdList(json: string): string[] {
101
102
  try {
102
103
  const v: unknown = JSON.parse(json);
103
104
  return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
@@ -106,18 +107,63 @@ function parseIdList(json: string): string[] {
106
107
  }
107
108
  }
108
109
 
110
+ /** What became of a morning share, in the words `dream --show` and the export both use. */
111
+ export const SHARE_STATE_WORDS: Readonly<Record<string, string>> = {
112
+ none: "no share",
113
+ offered: "share not told yet",
114
+ carried: "share carried to a later session",
115
+ told: "share told",
116
+ };
117
+
109
118
  /** One line: after which dream, what it did, and what became of the share. */
110
- function reflectionSummary(r: ReflectionRow): string {
119
+ export function reflectionSummary(r: ReflectionRow): string {
111
120
  const parts: string[] = [];
112
121
  parts.push(r.dream_id === null ? "on its own" : `after ${r.dream_id}`);
113
122
  if (r.state !== "reflected") return `${parts.join(", ")} — begun, not finished`;
114
123
  if (r.entry_id === null) parts.push("nothing much");
115
124
  if (r.page_version !== null) parts.push("rewrote the page");
116
- const share: Record<string, string> = { none: "no share", offered: "share not told yet", carried: "share carried to a later session", told: "share told" };
117
- parts.push(share[r.share_state] ?? r.share_state);
125
+ parts.push(SHARE_STATE_WORDS[r.share_state] ?? r.share_state);
118
126
  return parts.join(", ");
119
127
  }
120
128
 
129
+ /**
130
+ * ONE CHANGE A DREAM MADE, in words: its line, then any lines under it (a
131
+ * merge's originals, each "from …"). No mark and no indent: `dream --show`
132
+ * puts its own in front, and `export --markdown` makes a list of it.
133
+ */
134
+ export function dreamChangeWords(source: { readonly store: Store }, c: DreamChangeRow): [string, ...string[]] {
135
+ const words = (x: string | null): string => (x === null ? "(removed by the owner)" : `${x} "${memoryWords(source, x)}"`);
136
+ const a = c.ref;
137
+ const b = c.ref2;
138
+ switch (c.action) {
139
+ case "link":
140
+ case "contradiction":
141
+ return [`${c.action}: ${words(a)} ↔ ${words(b)}`];
142
+ case "settle": {
143
+ let how = "settled";
144
+ try {
145
+ const d = JSON.parse(c.detail) as { how?: unknown };
146
+ if (typeof d.how === "string") how = d.how;
147
+ } catch {
148
+ how = "settled";
149
+ }
150
+ return [`settle (${how}): ${words(a)} holds over ${words(b)}`];
151
+ }
152
+ case "merge": {
153
+ let from: string[] = [];
154
+ try {
155
+ const d = JSON.parse(c.detail) as { from?: unknown };
156
+ if (Array.isArray(d.from)) from = d.from.filter((x): x is string => typeof x === "string");
157
+ } catch {
158
+ from = [];
159
+ }
160
+ return [`merge into ${words(a)}`, ...from.map((f) => `from ${words(f)}`)];
161
+ }
162
+ default:
163
+ return [`${c.action}: ${words(a)}`];
164
+ }
165
+ }
166
+
121
167
  /** `counterparts dream --show <rfl_…>`: one reflection, whole. */
122
168
  export function reflectionShowLines(counterpart: Counterpart, id: string): string[] | null {
123
169
  const r = counterpart.reflections.show(id);
@@ -168,40 +214,9 @@ export function dreamShowLines(counterpart: Counterpart, id: string): string[] |
168
214
  out.push("", changes.length === 0 ? "Changes: none." : `Changes (${String(changes.length)}):`);
169
215
  for (const c of changes) {
170
216
  const mark = c.undone === 1 ? " [undone] " : " ";
171
- const a = c.ref === null ? null : c.ref;
172
- const b = c.ref2;
173
- const words = (x: string | null): string => (x === null ? "(removed by the owner)" : `${x} "${memoryWords(counterpart, x)}"`);
174
- switch (c.action) {
175
- case "link":
176
- case "contradiction":
177
- out.push(`${mark}${c.action}: ${words(a)} ↔ ${words(b)}`);
178
- break;
179
- case "settle": {
180
- let how = "settled";
181
- try {
182
- const d = JSON.parse(c.detail) as { how?: unknown };
183
- if (typeof d.how === "string") how = d.how;
184
- } catch {
185
- how = "settled";
186
- }
187
- out.push(`${mark}settle (${how}): ${words(a)} holds over ${words(b)}`);
188
- break;
189
- }
190
- case "merge": {
191
- let from: string[] = [];
192
- try {
193
- const d = JSON.parse(c.detail) as { from?: unknown };
194
- if (Array.isArray(d.from)) from = d.from.filter((x): x is string => typeof x === "string");
195
- } catch {
196
- from = [];
197
- }
198
- out.push(`${mark}merge into ${words(a)}`);
199
- for (const f of from) out.push(`${mark} from ${words(f)}`);
200
- break;
201
- }
202
- default:
203
- out.push(`${mark}${c.action}: ${words(a)}`);
204
- }
217
+ const [head, ...under] = dreamChangeWords(counterpart, c);
218
+ out.push(`${mark}${head}`);
219
+ for (const line of under) out.push(`${mark} ${line}`);
205
220
  }
206
221
  if (dream.state !== "undone") out.push("", `Reverse all of it: counterparts dream --undo ${dream.id}`);
207
222
  // What the waking self made of it — lived, so an undo of the dream leaves it.
@@ -46,9 +46,10 @@ import {
46
46
  renderMarkdown,
47
47
  rowTombstoned,
48
48
  } from "../../core/store/index.js";
49
- import type { MemoryRow, ProseDoc, Store } from "../../core/store/index.js";
49
+ import type { DreamRow, MemoryRow, ProseDoc, ReflectionRow, Store } from "../../core/store/index.js";
50
50
  import { isSelfPageRow } from "../../core/self/page.js";
51
- import { journalRelativePath } from "../../core/self/journal-file.js";
51
+ import { UNDATED, journalRelativePath } from "../../core/self/journal-file.js";
52
+ import { SHARE_STATE_WORDS, dreamChangeWords, memoryWords, parseIdList } from "./dream-core.js";
52
53
  import { assertSafeTarget, vacuumInto } from "./snapshot.js";
53
54
 
54
55
  /** The KDF's cost parameters travel WITH the blob: a hardcoded N is a format
@@ -64,8 +65,9 @@ export type ExportMode = "plaintext" | "encrypted";
64
65
  * WHAT KIND OF COPY. `database` is the whole store as one SQLite file — exact,
65
66
  * complete, and openable by anything that speaks SQLite. `markdown` is the
66
67
  * readable tree: one `.md` per memory, the journal as it stands, the self page
67
- * as its own file. They are different promises and neither replaces the other,
68
- * which is why the report names which one ran.
68
+ * as its own file, and one per dream and per reflection (2026-10-09). They are
69
+ * different promises and neither replaces the other, which is why the report
70
+ * names which one ran.
69
71
  */
70
72
  export type ExportKind = "database" | "markdown";
71
73
 
@@ -106,6 +108,14 @@ export interface ExportReport {
106
108
  readonly omittedConfidential: number;
107
109
  /** Ids whose markdown could not be rendered — named, never silently absent. */
108
110
  readonly notRendered: readonly string[];
111
+ /** Dreams and reflections written (markdown only; zero for a database
112
+ * export, which carries both tables whole). Never counted in `rows`. */
113
+ readonly dreams: number;
114
+ readonly reflections: number;
115
+ /** …and left out because they rest on a confidential memory, counted apart
116
+ * from `omittedConfidential` (which is memories). */
117
+ readonly omittedDreams: number;
118
+ readonly omittedReflections: number;
109
119
  }
110
120
 
111
121
  /** path (relative, portable) -> file bytes. */
@@ -153,6 +163,12 @@ interface MarkdownCensus {
153
163
  /** Live rows that are ARCHIVED — faded, superseded or merged. Exported, and
154
164
  * counted so the manifest can say so. */
155
165
  readonly archived: number;
166
+ /** Dreams and reflections written, and left out as resting on a
167
+ * confidential memory — a third unit, said apart from both above. */
168
+ readonly dreams: number;
169
+ readonly reflections: number;
170
+ readonly omittedDreams: number;
171
+ readonly omittedReflections: number;
156
172
  }
157
173
 
158
174
  /**
@@ -192,6 +208,12 @@ interface MarkdownCensus {
192
208
  * `renderMarkdown`'s, which carries the payload the row holds and not its
193
209
  * physics, and that renderer is shared with the journal copy. A count in the
194
210
  * manifest is the honest version of what this export knows.
211
+ *
212
+ * **DREAMS AND REFLECTIONS ARE IN IT TOO** (2026-10-09), one file each under
213
+ * `dreams/` and `reflections/`, laid out like the journal. They are not
214
+ * memories — a dream's journal is kept out of `memories` on purpose, so it is
215
+ * never mistaken for something lived — so they are rendered here, not by
216
+ * `renderMarkdown`, and their front matter carries no `payload:` line.
195
217
  */
196
218
  function collectMarkdown(store: Store, opts: ExportOptions): { bundle: Bundle; census: MarkdownCensus } {
197
219
  const bundle: Bundle = new Map();
@@ -205,6 +227,10 @@ function collectMarkdown(store: Store, opts: ExportOptions): { bundle: Bundle; c
205
227
  pageOmitted: false,
206
228
  omittedVersions: 0,
207
229
  archived: 0,
230
+ dreams: 0,
231
+ reflections: 0,
232
+ omittedDreams: 0,
233
+ omittedReflections: 0,
208
234
  };
209
235
  const counts = census as {
210
236
  rows: number;
@@ -216,6 +242,10 @@ function collectMarkdown(store: Store, opts: ExportOptions): { bundle: Bundle; c
216
242
  pageOmitted: boolean;
217
243
  omittedVersions: number;
218
244
  archived: number;
245
+ dreams: number;
246
+ reflections: number;
247
+ omittedDreams: number;
248
+ omittedReflections: number;
219
249
  };
220
250
  const denied = new Set(store.deniedIds());
221
251
 
@@ -294,6 +324,53 @@ function collectMarkdown(store: Store, opts: ExportOptions): { bundle: Bundle; c
294
324
  }
295
325
  }
296
326
 
327
+ // THE NIGHTS (dream INTERFACE-GAPS §4 and §7, closed 2026-10-09). A dream's
328
+ // journal and a reflection's entry and morning share live in their own
329
+ // tables, never as memories, so the loop above walked past them and the
330
+ // readable copy said nothing about the nights at all.
331
+ //
332
+ // TWO PASSES (review of #331): every night's fate is decided before any file
333
+ // is written, so a reflection's file never points at its dream's path when
334
+ // that dream was left out, and a dream's file says the same of each
335
+ // reflection after it.
336
+ const fates = new Map<string, NightFate>();
337
+ const fate = (dir: "dreams" | "reflections", id: string, date: string | null, rests: readonly (string | null)[]): NightFate => {
338
+ const path = nightPath(dir, id, date);
339
+ if (path === null) return { left: "unrenderable" };
340
+ if (opts.includeConfidential !== true && restsOnConfidential(store, rests)) return { left: "confidential" };
341
+ return { path };
342
+ };
343
+ const reflections = store.reflections({ limit: Math.max(1, store.reflectionCount()) });
344
+ const dreams = store.dreams({ limit: Math.max(1, store.dreamCount()) });
345
+ for (const r of reflections) {
346
+ fates.set(r.id, fate("reflections", r.id, r.date, [...parseIdList(r.shown), ...parseIdList(r.cites), ...parseIdList(r.share_cites), r.entry_id]));
347
+ }
348
+ for (const dream of dreams) {
349
+ const changes = store.dreamChanges(dream.id);
350
+ fates.set(dream.id, fate("dreams", dream.id, dream.date, [...parseIdList(dream.shown), ...changes.flatMap((c) => [c.ref, c.ref2])]));
351
+ }
352
+ for (const r of reflections) {
353
+ const f = fates.get(r.id);
354
+ if (f === undefined || "left" in f) {
355
+ if (f?.left === "confidential") counts.omittedReflections += 1;
356
+ else counts.notRendered.push(r.id);
357
+ continue;
358
+ }
359
+ put(f.path, reflectionMarkdown(store, r, r.dream_id === null ? undefined : fates.get(r.dream_id)));
360
+ counts.reflections += 1;
361
+ }
362
+ for (const dream of dreams) {
363
+ const f = fates.get(dream.id);
364
+ if (f === undefined || "left" in f) {
365
+ if (f?.left === "confidential") counts.omittedDreams += 1;
366
+ else counts.notRendered.push(dream.id);
367
+ continue;
368
+ }
369
+ const after = store.reflections({ dreamId: dream.id }).map((r) => ({ id: r.id, fate: fates.get(r.id) }));
370
+ put(f.path, dreamMarkdown(store, dream, after));
371
+ counts.dreams += 1;
372
+ }
373
+
297
374
  put("README.md", markdownReadme(census, opts));
298
375
  return { bundle, census };
299
376
  }
@@ -346,6 +423,163 @@ function pathFor(store: Store, row: MemoryRow, doc: ProseDoc): string {
346
423
  return `memories/${row.kind}/${row.id}.md`;
347
424
  }
348
425
 
426
+ /**
427
+ * Where a dream's or a reflection's file goes: `dreams/<year>/<date>-<id>.md`,
428
+ * the journal's own layout, `undated` the same way. Ids only, never a title.
429
+ * Null for an id that is not one plain path segment — none of ours is ever
430
+ * anything else, and a row that is would be named, not written somewhere odd.
431
+ */
432
+ function nightPath(dir: "dreams" | "reflections", id: string, date: string | null): string | null {
433
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) return null;
434
+ const day = date !== null && /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : UNDATED;
435
+ return `${dir}/${day === UNDATED ? UNDATED : day.slice(0, 4)}/${day}-${id}.md`;
436
+ }
437
+
438
+ /** What became of one night in this export: its file, or why it has none. */
439
+ type NightFate = { readonly path: string } | { readonly left: "confidential" | "unrenderable" };
440
+
441
+ /** How one night file names another: ` — \`path\``, or why that one is not in this copy. */
442
+ function nightWhere(f: NightFate | undefined): string {
443
+ if (f === undefined) return " (not in this copy)";
444
+ if ("path" in f) return ` — \`${f.path}\``;
445
+ return f.left === "confidential"
446
+ ? " (left out of this copy: it rests on a confidential memory)"
447
+ : " (not in this copy: its file could not be written; the README names it)";
448
+ }
449
+
450
+ /**
451
+ * DOES A DREAM OR A REFLECTION REST ON A CONFIDENTIAL MEMORY — was it shown
452
+ * one, did it change one, does it cite one, is its entry one? Asked of the
453
+ * memories as they are NOW. A night's words carry no confidentiality mark of
454
+ * their own, and since #318 a dream's bundle is read as a guest
455
+ * (`dream/tunables.ts#BUNDLE_OWNER`), so a night is not shown a confidential
456
+ * memory in the first place; this catches the one left — a memory marked
457
+ * confidential after the night that was shown it. Such a night is left out
458
+ * unless `--include-confidential`, and counted, like a confidential memory.
459
+ * A REMOVED memory does not count: the removal has already redacted every
460
+ * night that was shown it (`store/owner-op-seam.ts#redactDreamJournals`).
461
+ */
462
+ function restsOnConfidential(store: Store, ids: readonly (string | null)[]): boolean {
463
+ for (const id of ids) {
464
+ if (id === null) continue;
465
+ const row = store.row(id);
466
+ if (row === undefined || rowTombstoned(row)) continue;
467
+ if (row.confidential === 1) return true;
468
+ }
469
+ return false;
470
+ }
471
+
472
+ /** The front matter both kinds of night share: the memory files' fence and
473
+ * one `key: value` line each, and no `payload:` line — that line is how a
474
+ * future importer reads a MEMORY back, and a night is not one. */
475
+ function nightFrontMatter(lines: readonly (readonly [string, string | number | null])[]): string {
476
+ const kept = lines.filter(([, v]) => v !== null).map(([k, v]) => `${k}: ${String(v).replace(/\r?\n/g, " ")}`);
477
+ return `---\n${kept.join("\n")}\n---\n`;
478
+ }
479
+
480
+ /**
481
+ * ONE DREAM, readable: its journal as the dream wrote it, then every change it
482
+ * made in the words `dream --show` uses (`dream-core.ts#dreamChangeWords`),
483
+ * undone ones marked, then the reflections after it. A journal the owner's
484
+ * removal redacted is exported as the line it now holds.
485
+ */
486
+ function dreamMarkdown(
487
+ store: Store,
488
+ dream: DreamRow,
489
+ after: readonly { readonly id: string; readonly fate: NightFate | undefined }[],
490
+ ): string {
491
+ const out = [
492
+ nightFrontMatter([
493
+ ["id", dream.id],
494
+ ["type", "dream"],
495
+ ["title", dream.title === null || dream.title.length === 0 ? null : dream.title],
496
+ ["date", dream.date],
497
+ ["livedDay", dream.day],
498
+ ["state", dream.state],
499
+ ["model", dream.model],
500
+ ["session", dream.session],
501
+ ]),
502
+ ];
503
+ if (dream.state === "undone") {
504
+ out.push("This dream was undone: its changes were reversed, and its journal is kept.\n\n");
505
+ }
506
+ out.push(
507
+ dream.journal !== null && dream.journal.length > 0
508
+ ? dream.journal
509
+ : dream.state === "begun"
510
+ ? "(No journal: this dream was begun and never finished.)"
511
+ : "(No journal was written.)",
512
+ );
513
+ const changes = store.dreamChanges(dream.id);
514
+ out.push("\n\n## Changes\n\n");
515
+ if (changes.length === 0) out.push("None.\n");
516
+ for (const c of changes) {
517
+ const [head, ...under] = dreamChangeWords({ store }, c);
518
+ out.push(`- ${c.undone === 1 ? "[undone] " : ""}${head}\n`);
519
+ for (const line of under) out.push(` - ${line}\n`);
520
+ }
521
+ if (after.length > 0) {
522
+ out.push("\n## Reflected on afterwards\n\n");
523
+ for (const r of after) out.push(`- ${r.id}${nightWhere(r.fate)}\n`);
524
+ }
525
+ return out.join("");
526
+ }
527
+
528
+ /**
529
+ * ONE REFLECTION, readable: what it was asked, its entry, what the entry rests
530
+ * on, its morning share and what became of it (`dream-core.ts#SHARE_STATE_WORDS`),
531
+ * and the page version it wrote. An entry that cited anything is also a memory
532
+ * of source `reflection`, and is in `memories/` as well; this file says which.
533
+ */
534
+ function reflectionMarkdown(store: Store, r: ReflectionRow, dreamFate: NightFate | undefined): string {
535
+ const out = [
536
+ nightFrontMatter([
537
+ ["id", r.id],
538
+ ["type", "reflection"],
539
+ ["date", r.date],
540
+ ["livedDay", r.day],
541
+ ["state", r.state],
542
+ ["after", r.dream_id ?? "none (it reflected on its own)"],
543
+ ["model", r.model],
544
+ ["session", r.session],
545
+ ]),
546
+ ];
547
+ // Its dream's file only when that dream is in this copy too (review of
548
+ // #331): a dream left out as resting on a confidential memory is said so.
549
+ if (r.dream_id !== null && dreamFate !== undefined) out.push(`After dream ${r.dream_id}${nightWhere(dreamFate)}.\n\n`);
550
+ const questions = parseIdList(r.questions);
551
+ out.push("## Asked\n\n");
552
+ out.push(questions.length === 0 ? "(Nothing recorded.)\n" : questions.map((q) => `- ${q.replace(/\r?\n/g, " ")}\n`).join(""));
553
+ out.push("\n## Entry\n\n");
554
+ out.push(
555
+ r.entry !== null && r.entry.length > 0
556
+ ? `${r.entry}\n`
557
+ : r.state === "reflected"
558
+ ? "(No entry was written.)\n"
559
+ : "(No entry: this reflection was begun and never finished.)\n",
560
+ );
561
+ if (r.entry_id !== null) out.push(`\nKept as memory ${r.entry_id}.\n`);
562
+ const cites = parseIdList(r.cites);
563
+ if (cites.length > 0) {
564
+ out.push("\n## It rests on\n\n");
565
+ for (const c of cites) out.push(`- ${c} "${memoryWords({ store }, c)}"\n`);
566
+ }
567
+ out.push("\n## Morning share\n\n");
568
+ if (r.share === null || r.share.length === 0) {
569
+ out.push("None.\n");
570
+ } else {
571
+ out.push(`${r.share}\n\n${capitalise(SHARE_STATE_WORDS[r.share_state] ?? r.share_state)}.\n`);
572
+ }
573
+ if (r.page_version !== null) {
574
+ out.push(`\n## Self page\n\nIt rewrote the self page: version ${String(r.page_version)} (\`self-page.md\` is the page as it stands now).\n`);
575
+ }
576
+ return out.join("");
577
+ }
578
+
579
+ function capitalise(s: string): string {
580
+ return s.length === 0 ? s : `${s[0]?.toUpperCase() ?? ""}${s.slice(1)}`;
581
+ }
582
+
349
583
  /**
350
584
  * Remove any `.export-scratch-*` an interrupted export of an OLDER BUILD left in
351
585
  * this target.
@@ -444,6 +678,10 @@ export function exportStore(store: Store, opts: ExportOptions): ExportReport {
444
678
  rows: 0,
445
679
  omittedConfidential: 0,
446
680
  notRendered: [],
681
+ dreams: 0,
682
+ reflections: 0,
683
+ omittedDreams: 0,
684
+ omittedReflections: 0,
447
685
  });
448
686
 
449
687
  const encrypting = typeof opts.passphrase === "string" && opts.passphrase.length > 0;
@@ -535,6 +773,10 @@ export function exportStore(store: Store, opts: ExportOptions): ExportReport {
535
773
  omittedConfidential: census?.omittedConfidential ?? 0,
536
774
  omittedVersions: census?.omittedVersions ?? 0,
537
775
  notRendered: census?.notRendered ?? [],
776
+ dreams: census?.dreams ?? 0,
777
+ reflections: census?.reflections ?? 0,
778
+ omittedDreams: census?.omittedDreams ?? 0,
779
+ omittedReflections: census?.omittedReflections ?? 0,
538
780
  };
539
781
 
540
782
  if (!encrypting) {
@@ -576,7 +818,7 @@ export function exportStore(store: Store, opts: ExportOptions): ExportReport {
576
818
  (kind === "markdown"
577
819
  ? "Unencrypted, at the owner's explicit request. Every file is plain markdown."
578
820
  : "Unencrypted, at the owner's explicit request. The database is readable by any SQLite.") +
579
- confidentialNote(counted.omittedConfidential, counted.omittedVersions, opts) +
821
+ confidentialNote(counted, opts) +
580
822
  notRenderedNote(counted.notRendered) +
581
823
  replacedNote(collisions) +
582
824
  sweptNote(sweptScratch),
@@ -596,7 +838,7 @@ export function exportStore(store: Store, opts: ExportOptions): ExportReport {
596
838
  bytes,
597
839
  reason:
598
840
  `Encrypted with ${CIPHER} under a key derived from your passphrase. Lose the passphrase and this archive is gone.` +
599
- confidentialNote(counted.omittedConfidential, counted.omittedVersions, opts) +
841
+ confidentialNote(counted, opts) +
600
842
  notRenderedNote(counted.notRendered) +
601
843
  sweptNote(sweptScratch),
602
844
  ...counted,
@@ -609,25 +851,57 @@ export function exportStore(store: Store, opts: ExportOptions): ExportReport {
609
851
  * Ruling 4 says the export "says how many it omitted", and a line that appears
610
852
  * only when something was left out is one whose absence means two different
611
853
  * things: nothing was confidential, or nobody checked.
854
+ *
855
+ * Dreams and reflections that rest on a confidential memory are a sentence of
856
+ * their own, said only when there are some: they are not rows, and folding
857
+ * them into the row count would make "1 confidential row" mean two things.
612
858
  */
613
- function confidentialNote(omitted: number, omittedVersions: number, opts: ExportOptions): string {
859
+ function confidentialNote(
860
+ counted: {
861
+ readonly omittedConfidential: number;
862
+ readonly omittedVersions: number;
863
+ readonly omittedDreams: number;
864
+ readonly omittedReflections: number;
865
+ },
866
+ opts: ExportOptions,
867
+ ): string {
614
868
  if (opts.markdown !== true) return "";
615
869
  if (opts.includeConfidential === true) {
616
870
  return " Confidential rows are INCLUDED, because --include-confidential was passed.";
617
871
  }
618
- if (omitted === 0 && omittedVersions === 0) {
872
+ const omitted = counted.omittedConfidential;
873
+ const omittedVersions = counted.omittedVersions;
874
+ const nights = nightsWords(counted.omittedDreams, counted.omittedReflections);
875
+ if (omitted === 0 && omittedVersions === 0 && nights === null) {
619
876
  return " No confidential rows were left out (there were none).";
620
877
  }
621
- const versions =
622
- omittedVersions === 0
623
- ? ""
624
- : ` and ${String(omittedVersions)} confidential earlier wording${omittedVersions === 1 ? "" : "s"}`;
625
- const one = omitted === 1 && versions === "";
626
- return (
627
- ` ${String(omitted)} confidential row${omitted === 1 ? "" : "s"}${versions}` +
628
- `${one ? " was" : " were"} left out;` +
629
- ` pass --include-confidential to take ${one ? "it" : "them"} too.`
630
- );
878
+ let said = "";
879
+ if (omitted > 0 || omittedVersions > 0) {
880
+ const versions =
881
+ omittedVersions === 0
882
+ ? ""
883
+ : ` and ${String(omittedVersions)} confidential earlier wording${omittedVersions === 1 ? "" : "s"}`;
884
+ const one = omitted === 1 && versions === "";
885
+ said +=
886
+ ` ${String(omitted)} confidential row${omitted === 1 ? "" : "s"}${versions}` +
887
+ `${one ? " was" : " were"} left out;` +
888
+ ` pass --include-confidential to take ${one ? "it" : "them"} too.`;
889
+ }
890
+ if (nights !== null) {
891
+ said +=
892
+ ` ${nights.words} that rest${nights.one ? "s" : ""} on a confidential memory ${nights.one ? "was" : "were"} left out` +
893
+ (omitted > 0 || omittedVersions > 0 ? " too." : `; pass --include-confidential to take ${nights.one ? "it" : "them"} too.`);
894
+ }
895
+ return said;
896
+ }
897
+
898
+ /** "1 dream", "2 dreams and 1 reflection", or null when both are zero. */
899
+ function nightsWords(dreams: number, reflections: number): { words: string; one: boolean } | null {
900
+ const parts: string[] = [];
901
+ if (dreams > 0) parts.push(`${String(dreams)} dream${dreams === 1 ? "" : "s"}`);
902
+ if (reflections > 0) parts.push(`${String(reflections)} reflection${reflections === 1 ? "" : "s"}`);
903
+ if (parts.length === 0) return null;
904
+ return { words: parts.join(" and "), one: dreams + reflections === 1 };
631
905
  }
632
906
 
633
907
  /** WHICH files this export replaced, when the owner said to. The flag whose
@@ -743,10 +1017,23 @@ function markdownReadme(census: MarkdownCensus, opts: ExportOptions): string {
743
1017
  ? `, and **${String(census.omittedVersions)}** confidential earlier wording${census.omittedVersions === 1 ? "" : "s"} of memories that are otherwise here.`
744
1018
  : ". (Earlier wordings were not being exported; `--with-versions` writes them, confidential ones excepted.)") +
745
1019
  " They are still in your store; re-run with `--include-confidential` to take them too.";
1020
+ // A THIRD UNIT, said apart again: a night is neither a row nor a wording.
1021
+ // Only when confidential ones were being left out at all.
1022
+ const nightsOmitted =
1023
+ opts.includeConfidential === true
1024
+ ? []
1025
+ : [
1026
+ `- Dreams and reflections that rest on a confidential memory (were shown one, changed one or cite one): ` +
1027
+ `**${String(census.omittedDreams)}** dream${census.omittedDreams === 1 ? "" : "s"}, ` +
1028
+ `**${String(census.omittedReflections)}** reflection${census.omittedReflections === 1 ? "" : "s"}.` +
1029
+ (census.omittedDreams + census.omittedReflections > 0 ? " `--include-confidential` takes them too." : ""),
1030
+ ];
746
1031
  return [
747
1032
  "# Counterparts export (markdown)",
748
1033
  "",
749
- `${census.rows} rows, readable in any editor — memories, the journal, and the self page.`,
1034
+ `${census.rows} rows, readable in any editor — memories, the journal, and the self page — ` +
1035
+ `and ${String(census.dreams)} dream${census.dreams === 1 ? "" : "s"} and ` +
1036
+ `${String(census.reflections)} reflection${census.reflections === 1 ? "" : "s"}.`,
750
1037
  "Rendered from the database; this is a COPY, and the store itself is still where the",
751
1038
  "memories live.",
752
1039
  "",
@@ -772,15 +1059,27 @@ function markdownReadme(census: MarkdownCensus, opts: ExportOptions): string {
772
1059
  census.versions > 0
773
1060
  ? `- \`versions/<id>/<seq>.md\` — ${String(census.versions)} earlier wording${census.versions === 1 ? "" : "s"}, oldest first (\`--with-versions\`).`
774
1061
  : "- `versions/` — not included. Pass `--with-versions` to export every earlier wording too.",
1062
+ census.dreams === 0
1063
+ ? "- `dreams/` — none: this store has no dream to export."
1064
+ : `- \`dreams/<year>/<date>-<id>.md\` — ${String(census.dreams)} dream${census.dreams === 1 ? "" : "s"}, one file each:` +
1065
+ " its journal as it was written, every change it made (undone ones marked), and the" +
1066
+ " reflections after it. A dream's journal is not a memory, so it is here and not in `memories/`.",
1067
+ census.reflections === 0
1068
+ ? "- `reflections/` — none: this store has no reflection to export."
1069
+ : `- \`reflections/<year>/<date>-<id>.md\` — ${String(census.reflections)} reflection${census.reflections === 1 ? "" : "s"}, one file each:` +
1070
+ " what it was asked, its entry, what that entry rests on, and its morning share and what" +
1071
+ " became of it. An entry that cited a memory was also kept as a memory, so it is in `memories/` too.",
775
1072
  "",
776
1073
  "## What is NOT here",
777
1074
  "",
778
1075
  omitted,
1076
+ ...nightsOmitted,
779
1077
  "- Removed memories. A removal is permanent; a tombstoned row has no words left to export.",
780
1078
  census.notRendered.length === 0
781
- ? "- Nothing else. Every live row this export could reach is in it."
1079
+ ? "- Nothing else. Every live row, dream and reflection this export could reach is in it."
782
1080
  : `- ${String(census.notRendered.length)} row(s) whose markdown could not be rendered: ${census.notRendered.join(", ")}.`,
783
- "- The structured physics — strengths, edges, the association graph, the event log.",
1081
+ "- The structured physics — strengths, edges, the association graph, the event log, and",
1082
+ " the records a dream keeps beside its journal (what it was shown, what undoing it needs).",
784
1083
  " Those are in the database, and `counterparts export --out <dir> --plaintext` (without",
785
1084
  " `--markdown`) copies the whole thing as one SQLite file.",
786
1085
  "",
@@ -89,6 +89,7 @@ export {
89
89
  readHost,
90
90
  hostMcpFile,
91
91
  hostSettingsFiles,
92
+ hostSettingsDir,
92
93
  hostConfigBase,
93
94
  runCommand,
94
95
  settingsBlock,