@fractalsynapse/dsh-chapters 0.0.0-stage → 0.2.20

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 (195) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +76 -2
  3. package/cordis.patch.yml +363 -0
  4. package/docs/architecture.md +692 -0
  5. package/docs/autorun-guide.md +248 -0
  6. package/docs/backlog.md +2022 -0
  7. package/docs/contract.md +938 -0
  8. package/docs/development.md +990 -0
  9. package/docs/host-compaction-seam.md +225 -0
  10. package/docs/host-protected-head-ask.md +80 -0
  11. package/docs/knowledge-repo.md +1332 -0
  12. package/docs/plans-carriage.md +571 -0
  13. package/docs/project-state.md +642 -0
  14. package/docs/provider.md +98 -0
  15. package/docs/superpowers/plans/2026-10-17-chapters-save.md +198 -0
  16. package/docs/superpowers/plans/2026-11-02-chapter-removal.md +151 -0
  17. package/docs/superpowers/specs/2026-11-02-chapter-removal-design.md +115 -0
  18. package/docs/verify.md +561 -0
  19. package/lib/archive.d.ts +161 -0
  20. package/lib/archive.js +229 -0
  21. package/lib/archive.js.map +1 -0
  22. package/lib/arrival.d.ts +23 -0
  23. package/lib/arrival.js +125 -0
  24. package/lib/arrival.js.map +1 -0
  25. package/lib/artifact-query.d.ts +62 -0
  26. package/lib/artifact-query.js +187 -0
  27. package/lib/artifact-query.js.map +1 -0
  28. package/lib/attach.d.ts +46 -0
  29. package/lib/attach.js +120 -0
  30. package/lib/attach.js.map +1 -0
  31. package/lib/auto-save.d.ts +145 -0
  32. package/lib/auto-save.js +334 -0
  33. package/lib/auto-save.js.map +1 -0
  34. package/lib/aux-message.d.ts +17 -0
  35. package/lib/aux-message.js +20 -0
  36. package/lib/aux-message.js.map +1 -0
  37. package/lib/client.js +1419 -0
  38. package/lib/client.js.map +1 -0
  39. package/lib/codegraph.d.ts +76 -0
  40. package/lib/codegraph.js +190 -0
  41. package/lib/codegraph.js.map +1 -0
  42. package/lib/commands.d.ts +52 -0
  43. package/lib/commands.js +946 -0
  44. package/lib/commands.js.map +1 -0
  45. package/lib/compose.d.ts +30 -0
  46. package/lib/compose.js +185 -0
  47. package/lib/compose.js.map +1 -0
  48. package/lib/continue-core.d.ts +245 -0
  49. package/lib/continue-core.js +405 -0
  50. package/lib/continue-core.js.map +1 -0
  51. package/lib/diag.d.ts +55 -0
  52. package/lib/diag.js +186 -0
  53. package/lib/diag.js.map +1 -0
  54. package/lib/engine-core.d.ts +301 -0
  55. package/lib/engine-core.js +531 -0
  56. package/lib/engine-core.js.map +1 -0
  57. package/lib/engine-note.d.ts +35 -0
  58. package/lib/engine-note.js +32 -0
  59. package/lib/engine-note.js.map +1 -0
  60. package/lib/engine.d.ts +329 -0
  61. package/lib/engine.js +1179 -0
  62. package/lib/engine.js.map +1 -0
  63. package/lib/enrich-queue.d.ts +66 -0
  64. package/lib/enrich-queue.js +126 -0
  65. package/lib/enrich-queue.js.map +1 -0
  66. package/lib/enrich-store.d.ts +31 -0
  67. package/lib/enrich-store.js +103 -0
  68. package/lib/enrich-store.js.map +1 -0
  69. package/lib/enrich-wire.d.ts +163 -0
  70. package/lib/enrich-wire.js +353 -0
  71. package/lib/enrich-wire.js.map +1 -0
  72. package/lib/enrich.d.ts +102 -0
  73. package/lib/enrich.js +267 -0
  74. package/lib/enrich.js.map +1 -0
  75. package/lib/gitops.d.ts +107 -0
  76. package/lib/gitops.js +539 -0
  77. package/lib/gitops.js.map +1 -0
  78. package/lib/index.d.ts +241 -0
  79. package/lib/index.js +1162 -0
  80. package/lib/index.js.map +1 -0
  81. package/lib/indexing.d.ts +98 -0
  82. package/lib/indexing.js +223 -0
  83. package/lib/indexing.js.map +1 -0
  84. package/lib/injections.d.ts +90 -0
  85. package/lib/injections.js +165 -0
  86. package/lib/injections.js.map +1 -0
  87. package/lib/last-resort.d.ts +24 -0
  88. package/lib/last-resort.js +27 -0
  89. package/lib/last-resort.js.map +1 -0
  90. package/lib/log-shape.d.ts +38 -0
  91. package/lib/log-shape.js +93 -0
  92. package/lib/log-shape.js.map +1 -0
  93. package/lib/models-command.d.ts +74 -0
  94. package/lib/models-command.js +100 -0
  95. package/lib/models-command.js.map +1 -0
  96. package/lib/notice.d.ts +74 -0
  97. package/lib/notice.js +92 -0
  98. package/lib/notice.js.map +1 -0
  99. package/lib/plans.d.ts +154 -0
  100. package/lib/plans.js +315 -0
  101. package/lib/plans.js.map +1 -0
  102. package/lib/preset.d.ts +186 -0
  103. package/lib/preset.js +212 -0
  104. package/lib/preset.js.map +1 -0
  105. package/lib/prompt-keys.d.ts +7 -0
  106. package/lib/prompt-keys.js +8 -0
  107. package/lib/prompt-keys.js.map +1 -0
  108. package/lib/prompt-loop.d.ts +73 -0
  109. package/lib/prompt-loop.js +147 -0
  110. package/lib/prompt-loop.js.map +1 -0
  111. package/lib/prompt-push.d.ts +47 -0
  112. package/lib/prompt-push.js +115 -0
  113. package/lib/prompt-push.js.map +1 -0
  114. package/lib/prompt-runner.d.ts +48 -0
  115. package/lib/prompt-runner.js +90 -0
  116. package/lib/prompt-runner.js.map +1 -0
  117. package/lib/prompt-state.d.ts +142 -0
  118. package/lib/prompt-state.js +101 -0
  119. package/lib/prompt-state.js.map +1 -0
  120. package/lib/prompt.d.ts +270 -0
  121. package/lib/prompt.js +408 -0
  122. package/lib/prompt.js.map +1 -0
  123. package/lib/provider.d.ts +44 -0
  124. package/lib/provider.js +66 -0
  125. package/lib/provider.js.map +1 -0
  126. package/lib/redact.d.ts +24 -0
  127. package/lib/redact.js +85 -0
  128. package/lib/redact.js.map +1 -0
  129. package/lib/registry.d.ts +187 -0
  130. package/lib/registry.js +235 -0
  131. package/lib/registry.js.map +1 -0
  132. package/lib/removal.d.ts +159 -0
  133. package/lib/removal.js +556 -0
  134. package/lib/removal.js.map +1 -0
  135. package/lib/render.d.ts +97 -0
  136. package/lib/render.js +530 -0
  137. package/lib/render.js.map +1 -0
  138. package/lib/repair-run.d.ts +76 -0
  139. package/lib/repair-run.js +506 -0
  140. package/lib/repair-run.js.map +1 -0
  141. package/lib/repair.d.ts +208 -0
  142. package/lib/repair.js +357 -0
  143. package/lib/repair.js.map +1 -0
  144. package/lib/repo.d.ts +78 -0
  145. package/lib/repo.js +184 -0
  146. package/lib/repo.js.map +1 -0
  147. package/lib/rules-commands.d.ts +46 -0
  148. package/lib/rules-commands.js +379 -0
  149. package/lib/rules-commands.js.map +1 -0
  150. package/lib/rules.d.ts +267 -0
  151. package/lib/rules.js +478 -0
  152. package/lib/rules.js.map +1 -0
  153. package/lib/save-core.d.ts +72 -0
  154. package/lib/save-core.js +220 -0
  155. package/lib/save-core.js.map +1 -0
  156. package/lib/search.d.ts +112 -0
  157. package/lib/search.js +282 -0
  158. package/lib/search.js.map +1 -0
  159. package/lib/session-rules.d.ts +222 -0
  160. package/lib/session-rules.js +454 -0
  161. package/lib/session-rules.js.map +1 -0
  162. package/lib/signature.d.ts +45 -0
  163. package/lib/signature.js +199 -0
  164. package/lib/signature.js.map +1 -0
  165. package/lib/store.d.ts +156 -0
  166. package/lib/store.js +368 -0
  167. package/lib/store.js.map +1 -0
  168. package/lib/sync.d.ts +220 -0
  169. package/lib/sync.js +810 -0
  170. package/lib/sync.js.map +1 -0
  171. package/lib/tools.d.ts +113 -0
  172. package/lib/tools.js +1090 -0
  173. package/lib/tools.js.map +1 -0
  174. package/lib/treedx/client.d.ts +57 -0
  175. package/lib/treedx/client.js +82 -0
  176. package/lib/treedx/client.js.map +1 -0
  177. package/lib/treedx/provider.d.ts +39 -0
  178. package/lib/treedx/provider.js +479 -0
  179. package/lib/treedx/provider.js.map +1 -0
  180. package/lib/treedx/state.d.ts +27 -0
  181. package/lib/treedx/state.js +65 -0
  182. package/lib/treedx/state.js.map +1 -0
  183. package/lib/types.d.ts +210 -0
  184. package/lib/types.js +31 -0
  185. package/lib/types.js.map +1 -0
  186. package/lib/version.d.ts +9 -0
  187. package/lib/version.js +10 -0
  188. package/lib/version.js.map +1 -0
  189. package/lib/vocabulary.d.ts +41 -0
  190. package/lib/vocabulary.js +118 -0
  191. package/lib/vocabulary.js.map +1 -0
  192. package/lib/warnings.d.ts +10 -0
  193. package/lib/warnings.js +18 -0
  194. package/lib/warnings.js.map +1 -0
  195. package/package.json +151 -4
@@ -0,0 +1,531 @@
1
+ import { chapterTopics } from "./signature.js";
2
+ import { estimateTokens, noticeIndexSection, renderChapter } from "./render.js";
3
+ import { isInjectedProse } from "./injections.js";
4
+ import { lineageOf } from "./types.js";
5
+ import { slugify, toStoredPath } from "./archive.js";
6
+ import { isFinalized } from "./registry.js";
7
+ /** provider tag written into `compaction/summary` — our event-scan discriminator. */
8
+ export const CHAPTERS_PROVIDER = 'dsh-chapters';
9
+ export const DETERMINISTIC_MODEL = 'deterministic';
10
+ /** Framing tags the host's summarizer wraps checkpoints in (compaction-basic summarizer.ts:21-22). */
11
+ export const SUMMARY_OPEN_TAG = '<compacted-summary>';
12
+ export const SUMMARY_CLOSE_TAG = '</compacted-summary>';
13
+ export const ENGINE_CONFIG_DEFAULTS = {
14
+ artifactStoreRoot: '.dsh-chapters',
15
+ knowledgeMirrorDir: '.dsh-knowledge',
16
+ noticeIndexCap: 6,
17
+ openRequestCarryMaxChars: 4000,
18
+ lastResortArtifact: true,
19
+ diagnosticsMaxBytes: 8388608,
20
+ chapterTokenTarget: 8000,
21
+ toolResultDeferFloorTokens: 200,
22
+ mergeThreshold: 0.3,
23
+ chapterLimit: 8000,
24
+ toolResultArtifactTokens: 8000,
25
+ planInlineChars: 900,
26
+ callArgArtifactTokens: 0,
27
+ elicitedPlot: true,
28
+ plansInCheckpoint: true,
29
+ planCheckpointChars: 1600,
30
+ };
31
+ // ---------------------------------------------------------------- text helpers
32
+ const messageText = (msg) => (msg?.content ?? []).filter((b) => b.type === 'text').map((b) => b.text ?? '').join('\n');
33
+ /** Every `<compacted-summary>…</compacted-summary>` block in the region, in order. */
34
+ export function extractCheckpointBlocks(messages) {
35
+ const blocks = [];
36
+ for (const msg of messages) {
37
+ const text = messageText(msg);
38
+ let from = 0;
39
+ for (;;) {
40
+ const open = text.indexOf(SUMMARY_OPEN_TAG, from);
41
+ if (open === -1)
42
+ break;
43
+ const close = text.indexOf(SUMMARY_CLOSE_TAG, open);
44
+ if (close === -1) {
45
+ blocks.push(text.slice(open + SUMMARY_OPEN_TAG.length));
46
+ break;
47
+ }
48
+ blocks.push(text.slice(open + SUMMARY_OPEN_TAG.length, close));
49
+ from = close + SUMMARY_CLOSE_TAG.length;
50
+ }
51
+ }
52
+ return blocks;
53
+ }
54
+ /** `N. [Title](path) — summary` as rendered by renderIndex; the accumulation format. */
55
+ const BULLET = /^\s*\d+\.\s+\[(.*?)\]\((.*?)\)\s+—\s+(.*)$/;
56
+ /**
57
+ * Merge-forward: parse prior bullets out of every checkpoint block. Lines that
58
+ * are not our bullet format (e.g. an LLM summary produced by `basic` before
59
+ * this engine took over) are returned as verbatim carry-overs — dropping them
60
+ * would be exactly the loss this plugin exists to prevent.
61
+ */
62
+ export function parseTocState(blocks) {
63
+ const bullets = [];
64
+ const carriedProse = [];
65
+ const seen = new Set();
66
+ for (const block of blocks) {
67
+ let blockHadBullets = false;
68
+ for (const line of block.split('\n')) {
69
+ const m = BULLET.exec(line);
70
+ if (m === null)
71
+ continue;
72
+ blockHadBullets = true;
73
+ const bullet = { title: m[1], path: m[2], summary: m[3] };
74
+ if (seen.has(bullet.path))
75
+ continue; // accumulation dedups by path; numbers may repeat across roots
76
+ seen.add(bullet.path);
77
+ bullets.push(bullet);
78
+ }
79
+ if (!blockHadBullets && block.trim().length > 0)
80
+ carriedProse.push(block.trim());
81
+ }
82
+ return { bullets, carriedProse };
83
+ }
84
+ // ---------------------------------------------------------------- transaction scanning
85
+ /**
86
+ * The open transaction's compactionId: the latest `compaction/start` with no
87
+ * later `compaction/end` carrying the same id. The base appends the start
88
+ * BEFORE awaiting summarize (region.ts:211) and the durable lock admits only
89
+ * one open transaction per session — so a backward scan finds exactly it.
90
+ */
91
+ export function findOpenCompactionId(session) {
92
+ const closed = new Set();
93
+ for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
94
+ const ev = session.eventAt(seq);
95
+ const raw = ev?.data?.compactionId;
96
+ const cid = typeof raw === 'string' && raw.length > 0 ? raw : null;
97
+ if (ev?.type === 'compaction/end' && cid !== null) {
98
+ closed.add(cid);
99
+ continue;
100
+ }
101
+ if (ev?.type === 'compaction/start' && cid !== null && !closed.has(cid))
102
+ return cid;
103
+ }
104
+ return null;
105
+ }
106
+ /** All OUR finalized-or-not summary events (provider-tagged), oldest first. */
107
+ export function scanChaptersSummaries(session) {
108
+ const out = [];
109
+ for (let seq = 0; seq < session.seq; seq += 1) {
110
+ const ev = session.eventAt(seq);
111
+ if (ev?.type !== 'compaction/summary')
112
+ continue;
113
+ if (ev.data?.provider !== CHAPTERS_PROVIDER)
114
+ continue;
115
+ const cid = ev.data?.compactionId;
116
+ const shadowed = ev.data?.shadowedSeqs;
117
+ if (typeof cid !== 'string' || !Array.isArray(shadowed))
118
+ continue;
119
+ out.push({ compactionId: cid, summarySeq: seq, shadowedSeqs: shadowed.map(Number) });
120
+ }
121
+ return out;
122
+ }
123
+ // ---------------------------------------------------------------- citation resolution
124
+ /**
125
+ * Follow `tool/result` replacement chains to the first version (the un-pruned
126
+ * original). Only single-cited tool results qualify — a compaction checkpoint
127
+ * `user/message` also carries sourceEventSeqs, and following THOSE would pull
128
+ * lifecycle bookkeeping into chapter bodies.
129
+ */
130
+ export function resolveOriginalEvent(session, seq) {
131
+ let cursor = seq;
132
+ const guard = new Set();
133
+ for (;;) {
134
+ if (guard.has(cursor))
135
+ throw new Error(`resolveOriginalEvent: citation cycle at seq ${cursor}`);
136
+ guard.add(cursor);
137
+ const ev = session.eventAt(cursor);
138
+ if (ev === undefined)
139
+ throw new Error(`resolveOriginalEvent: missing event at ${cursor}`);
140
+ if (ev.type !== 'tool/result')
141
+ return ev;
142
+ const cited = ev.sourceEventSeqs;
143
+ if (cited === undefined || cited.length !== 1)
144
+ return ev;
145
+ cursor = cited[0];
146
+ }
147
+ }
148
+ /** Deterministic title/summary from region content. Never model-authored (invariant 4 — the model is absent). */
149
+ export function deriveIdentity(messages, hasCheckpoint,
150
+ /**
151
+ * A plan submitted inside this span, when there is one (docs/plans-carriage.md
152
+ * § 6): the submission IS the identity of a planning chapter, and it beats the
153
+ * first prose line the same way a file's own header beats a guess about it.
154
+ * Callers that hold events pass it; the summarize path, which sees provider
155
+ * messages only, passes nothing and keeps the old derivation.
156
+ */
157
+ planTitle) {
158
+ // Title source: the first USER message that is actual human/agent prose.
159
+ // Harness injections (system reminders, runtime-context snapshots) ride as
160
+ // user messages too — an earlier fork titled a chapter "System reminder 1"
161
+ // from a runtime snapshot that happened to open the span. Skip them; the
162
+ // r29 command tests pin this behavior.
163
+ // The same predicate that screens chapter BODIES chooses a title (#59). Two lists of what counts as
164
+ // injected context is how a runtime snapshot became a filename and a TOC citation.
165
+ const firstUser = messages.find((m) => m.role === 'user'
166
+ && !messageText(m).includes(SUMMARY_OPEN_TAG)
167
+ && !isInjectedProse(messageText(m)));
168
+ const userCount = messages.filter((m) => m.role === 'user').length;
169
+ const assistantCount = messages.filter((m) => m.role === 'assistant').length;
170
+ const headLine = planTitle !== undefined && planTitle.trim() !== ''
171
+ ? planTitle.trim()
172
+ : firstUser === undefined ? '' : messageText(firstUser).split('\n')[0].trim();
173
+ const title = headLine.length > 0
174
+ ? headLine.length > 72 ? `${headLine.slice(0, 72)}…` : headLine
175
+ : hasCheckpoint ? 'Earlier history' : 'Conversation span';
176
+ return {
177
+ title,
178
+ summary: `${userCount} user / ${assistantCount} assistant messages (${estimateTokens(messages.map(messageText).join(' '))} est tokens)`,
179
+ };
180
+ }
181
+ /** Workspace-relative chapter path for a reserved number. */
182
+ export const chapterPathFor = (config, rootSession, number, title) =>
183
+ // #69: normalized at the mint. The realm resolves an ABSOLUTE store root to reach the filesystem, but
184
+ // the RECORD must carry the workspace-relative form, or chapter 1 written by compaction never matches
185
+ // the same file listed from disk and the auditor reports its own archive as lost knowledge.
186
+ toStoredPath(config.workspaceCwd, `${config.artifactStoreRoot.replace(/\/+$/, '')}/${rootSession}/chapters/${String(number).padStart(3, '0')}-${slugify(title)}.md`);
187
+ /**
188
+ * Map the prepared summarize input back to the log seqs it was built from
189
+ * (the host builds region messages as `deriveEventMessage(eventAt(seq))` for
190
+ * the shadowed selection). Returns null — meaning "use the legacy
191
+ * single-chapter path" — whenever the Session lacks the mapping API, nothing
192
+ * matches, or MORE THAN ONE contiguous run matches (duplicate small
193
+ * messages are common; guessing a wrong span would cite chapters that never
194
+ * cover their seqs, and an honest legacy chapter beats that).
195
+ */
196
+ export function reconstructShadowedSeqs(session, input) {
197
+ const nodes = session.surface?.nodes;
198
+ const derive = session.deriveEventMessage;
199
+ if (nodes === undefined || nodes.length === 0 || derive === undefined)
200
+ return null;
201
+ let region = input.messages;
202
+ if (region[0]?.role === 'system')
203
+ region = region.slice(1); // the prepended system head
204
+ if (region.length === 0)
205
+ return null;
206
+ const encoded = region.map((m) => JSON.stringify(m));
207
+ const matches = [];
208
+ for (let start = 0; start < nodes.length && matches.length < 2; start += 1) {
209
+ const seqs = [];
210
+ let mi = 0;
211
+ let ok = true;
212
+ for (let ni = start; ni < nodes.length && mi < encoded.length; ni += 1) {
213
+ const ev = session.eventAt(nodes[ni].seq);
214
+ if (ev === undefined)
215
+ continue;
216
+ const msg = derive(ev);
217
+ if (msg === null || msg === undefined)
218
+ continue;
219
+ if (JSON.stringify(msg) !== encoded[mi]) {
220
+ ok = false;
221
+ break;
222
+ }
223
+ seqs.push(ev.seq);
224
+ mi += 1;
225
+ }
226
+ if (ok && mi === encoded.length && seqs.length > 0)
227
+ matches.push(seqs);
228
+ }
229
+ return matches.length === 1 ? matches[0] : null;
230
+ }
231
+ /**
232
+ * The summarize-time plan: merge prior bullets, derive this span's identity,
233
+ * reserve numbers (attempt-keyed by the OPEN transaction's compactionId),
234
+ * build the TOC. Pure given the state; the caller persists the returned
235
+ * state change BEFORE this text can ever be cited.
236
+ *
237
+ * `composition` (r29): topic-sequential ranges from the composer (record
238
+ * §4.2), spanning the whole selected region head-to-tail (the adapter
239
+ * absorbs any strays). Present => reserve one number per chapter and cite
240
+ * them all; absent => the legacy single-chapter identity path, unchanged.
241
+ */
242
+ export function planSummarize(session, state, input, config, reserveFn,
243
+ /** Required: the caller fails loudly when no `compaction/start` is open. */
244
+ compactionId, composition = null,
245
+ /** Model-authored plot note carried into this checkpoint (may be null). */
246
+ plot = null,
247
+ /**
248
+ * The operative plan, already rendered as checkpoint prose by `carryActivePlan`
249
+ * (plans.ts). Carried on BOTH the composed and the legacy path, because the
250
+ * composed path is where real pressure compaction lands. Note the asymmetry this
251
+ * deliberately does NOT touch: `plot` is still only prefixed on the legacy path
252
+ * (`:415`), and changing that would rewrite checkpoint bytes for every plot-carrying
253
+ * session — i.e. the committed tapes. Plans are new, so carrying them is free.
254
+ */
255
+ planCarry = null,
256
+ /**
257
+ * #50 §7.6 — the rules block carried across this checkpoint, already rendered
258
+ * by the ONE builder that renders it for the notice too (`rules.buildRulesSection`).
259
+ * This is the hole the round exists to close: `leadSections` was
260
+ * `[planSection, plotSection]`, so a plan and a plot survived a compaction and a
261
+ * RULE did not. Null (nothing active, or the corpus unreadable) renders ZERO
262
+ * bytes — which is what keeps every committed plot-carrying checkpoint intact.
263
+ */
264
+ rulesCarry = null) {
265
+ const planSection = planCarry !== null && planCarry.trim() !== ''
266
+ ? `Active plan — carried across this checkpoint (it is STILL the work directive):\n\n${planCarry.trim()}`
267
+ : null;
268
+ const rulesSection = rulesCarry !== null && rulesCarry.trim() !== '' ? rulesCarry.trim() : null;
269
+ const leadSections0 = [planSection, rulesSection].filter((x) => x !== null && x !== '');
270
+ const blocks = extractCheckpointBlocks(input.messages);
271
+ const { bullets, carriedProse } = parseTocState(blocks);
272
+ const identity = deriveIdentity(input.messages, blocks.length > 0);
273
+ const attemptId = `compaction:${compactionId}`;
274
+ if (composition !== null && composition.length > 0) {
275
+ const reserved = reserveFn(state, attemptId, composition.length);
276
+ const usedPaths = new Set();
277
+ const chapters = composition.map((range, i) => {
278
+ const number = reserved.numbers[i];
279
+ let path = chapterPathFor(config, state.rootSession, number, range.title);
280
+ // Mirror writeArchive's collision rule so the cited path can never dangle.
281
+ if (usedPaths.has(path))
282
+ path = path.replace(/\.md$/, `-${number}.md`);
283
+ usedPaths.add(path);
284
+ return { number, path, title: range.title, summary: range.summary, startSeq: range.startSeq, endSeq: range.endSeq };
285
+ });
286
+ const allBullets = [...bullets, ...chapters.map((c) => ({ title: c.title, path: c.path, summary: c.summary }))];
287
+ const index = noticeIndexSection(allBullets, config.noticeIndexCap);
288
+ const quote = (p) => p.split('\n').map((l) => `> ${l}`).join('\n');
289
+ const composedParts = [
290
+ `Chapter archive: ${allBullets.length} chapter(s) under ${config.artifactStoreRoot}/ — verbatim text; reload any with the read tool on its path.`,
291
+ 'Tool results shown as head+…+tail in the replaced history were archived in full; oversized ones are file references inside the chapter.',
292
+ index,
293
+ ];
294
+ if (carriedProse.length > 0) {
295
+ composedParts.push('Earlier summary carried forward (not chapter-formatted):', ...carriedProse.map(quote));
296
+ }
297
+ return {
298
+ plan: {
299
+ tocText: leadSections0.length === 0
300
+ ? composedParts.join('\n\n')
301
+ : `${leadSections0.join('\n\n')}\n\n${composedParts.join('\n\n')}`,
302
+ numbers: reserved.numbers,
303
+ chapter: { title: chapters[0].title, summary: chapters[0].summary, path: chapters[0].path },
304
+ chapters,
305
+ },
306
+ state: reserved.state,
307
+ };
308
+ }
309
+ const reserved = reserveFn(state, attemptId, 1);
310
+ const number = reserved.numbers[0];
311
+ const path = chapterPathFor(config, state.rootSession, number, identity.title);
312
+ const allBullets = [...bullets, { title: identity.title, path, summary: identity.summary }];
313
+ const index = noticeIndexSection(allBullets, config.noticeIndexCap);
314
+ const quote = (p) => p.split('\n').map((l) => `> ${l}`).join('\n');
315
+ const parts = [
316
+ `Chapter archive: ${allBullets.length} chapter(s) under ${config.artifactStoreRoot}/ — verbatim text; reload any with the read tool on its path.`,
317
+ 'Tool results shown as head+…+tail in the replaced history were archived in full; oversized ones are file references inside the chapter.',
318
+ index,
319
+ ];
320
+ if (carriedProse.length > 0) {
321
+ parts.push('Earlier summary carried forward (not chapter-formatted):', ...carriedProse.map(quote));
322
+ }
323
+ const plotSection = plot !== null && plot.trim() !== ''
324
+ ? `Working plot (model-authored, carried across this checkpoint):\n\nPLOT: ${plot.trim()}\n\n(If it has gone stale, revise it in your next reply.)`
325
+ : null;
326
+ const leadSections = [planSection, rulesSection, plotSection].filter((x) => x !== null && x !== '');
327
+ const tocText = leadSections.length === 0 ? parts.join('\n\n') : `${leadSections.join('\n\n')}\n\n${parts.join('\n\n')}`;
328
+ return {
329
+ plan: {
330
+ tocText,
331
+ numbers: reserved.numbers,
332
+ chapter: { title: identity.title, summary: identity.summary, path },
333
+ },
334
+ state: reserved.state,
335
+ };
336
+ }
337
+ /**
338
+ * The plot note (architecture.md amendment 2026-09-19): a short forward-
339
+ * maintained statement of what the agent is MID-WAY through, authored by the
340
+ * model itself and carried forward across every in-place checkpoint.
341
+ */
342
+ export const PLOT_MARKER = 'PLOT:';
343
+ /**
344
+ * Latest plot paragraph in the region about to be shadowed. Assistant text
345
+ * wins; a PLOT carried in an earlier checkpoint (user-role, plugin-sourced)
346
+ * is the fallback, so the thread survives repeatedly shadowed chains.
347
+ * Returns the paragraph text WITHOUT the marker line, capped at maxChars.
348
+ *
349
+ * Shaped by the 2026-09-25 real-world audit (treeseed's first four-session
350
+ * run): ALL EIGHT checkpoints carried a "plot" that was actually the persona
351
+ * suffix's own instruction text — `...end each reply with one line beginning
352
+ * 'PLOT:' (max 60 words — objective...)`. A raw substring scan matched that
353
+ * quoted marker, and because the result was non-null it also SUPPRESSED the
354
+ * bounded elicited fallback: every session silently inherited boilerplate
355
+ * instead of a plot. Extraction now honors the contract the marker lives in:
356
+ * - the marker must START a line ("one line beginning 'PLOT:'" —
357
+ * mid-sentence quotes are instructions, not plots);
358
+ * - system-role messages never yield a plot (invariant 4's cousin: the
359
+ * MODEL authors plots; the prompt only asks for them);
360
+ * - bodies echoing the instruction template are rejected (belt and braces
361
+ * for historical sessions where such text already rides in user
362
+ * messages).
363
+ * A null result now genuinely means "no plot authored" — which is exactly
364
+ * when the bounded elicited fallback must run.
365
+ */
366
+ const PLOT_LINE = /^[ \t]*PLOT:[ \t]*([^\n]*)/gm;
367
+ const PLOT_TEMPLATE_ECHO = /max \d+ words|carries this plot forward|revise it on your next plot line/i;
368
+ export function extractPlot(messages, maxChars = 900) {
369
+ const scan = (roleWanted) => {
370
+ for (let i = messages.length - 1; i >= 0; i--) {
371
+ const m = messages[i];
372
+ if (m.role === 'system')
373
+ continue;
374
+ if (roleWanted === 'assistant' && m.role !== 'assistant')
375
+ continue;
376
+ const text = messageText(messages[i]);
377
+ let found = null;
378
+ for (const line of text.matchAll(PLOT_LINE)) {
379
+ const body = (line[1] ?? '').trim();
380
+ if (body.length === 0)
381
+ continue;
382
+ if (PLOT_TEMPLATE_ECHO.test(body))
383
+ continue;
384
+ found = body;
385
+ }
386
+ if (found !== null)
387
+ return found.length > maxChars ? found.slice(0, maxChars) + '…' : found;
388
+ }
389
+ return null;
390
+ };
391
+ return scan('assistant') ?? scan('any');
392
+ }
393
+ // ---------------------------------------------------------------- finalization
394
+ /**
395
+ * Post-commit: render the chapter body for one compaction from the durable
396
+ * log (citation-resolved), and return the record to commit. The caller writes
397
+ * files (via archive.writeArchive) and persists state; this stays pure over
398
+ * the event data so the pruner-composition rule is testable.
399
+ */
400
+ export function buildFinalizedChapter(session, shadowedSeqs, plan, config) {
401
+ const events = shadowedSeqs.map((seq) => {
402
+ const ev = resolveOriginalEvent(session, seq);
403
+ if (ev === undefined)
404
+ throw new Error(`buildFinalizedChapter: event vanished at ${seq}`);
405
+ return ev;
406
+ });
407
+ const lo = Math.min(...shadowedSeqs, ...events.map((e) => e.seq));
408
+ const hi = Math.max(...shadowedSeqs, ...events.map((e) => e.seq));
409
+ // Subagent lineage (issue #47): a compacting child stamps the same header fact
410
+ // the save doors do — undefined for ordinary sessions, byte-identical output.
411
+ const lineage = lineageOf(session.header);
412
+ return renderChapter(events, {
413
+ title: plan.chapter.title,
414
+ summary: plan.chapter.summary,
415
+ startSeq: lo,
416
+ endSeq: hi,
417
+ }, {
418
+ chapterTokenTarget: config.chapterTokenTarget,
419
+ toolResultDeferFloorTokens: config.toolResultDeferFloorTokens,
420
+ planInlineChars: config.planInlineChars,
421
+ callArgArtifactTokens: config.callArgArtifactTokens,
422
+ ...(lineage !== undefined ? { subagentOf: lineage } : {}),
423
+ }, [], chapterTopics(events, lo, hi));
424
+ }
425
+ /**
426
+ * Render the manifest's chapters (r29) — authoritative ranges, no
427
+ * recomposition (the TOC cited them). A plan without composed chapters
428
+ * returns the legacy single render. Mismatch between manifest and the
429
+ * committed shadowed span is a LOUD error: the finalizer defers and warns,
430
+ * never silently archives the wrong content.
431
+ */
432
+ export function buildFinalizedChapters(session, shadowedSeqs, plan, config) {
433
+ const composed = plan.chapters;
434
+ if (composed === undefined || composed.length === 0) {
435
+ return [buildFinalizedChapter(session, shadowedSeqs, plan, config)];
436
+ }
437
+ const events = shadowedSeqs.map((seq) => {
438
+ const ev = resolveOriginalEvent(session, seq);
439
+ if (ev === undefined)
440
+ throw new Error(`buildFinalizedChapters: event vanished at ${seq}`);
441
+ return ev;
442
+ });
443
+ const shadowMin = Math.min(...shadowedSeqs);
444
+ const shadowMax = Math.max(...shadowedSeqs);
445
+ const last = composed[composed.length - 1];
446
+ if (composed[0].startSeq > shadowMin || last.endSeq < shadowMax) {
447
+ throw new Error(`buildFinalizedChapters: manifest [${composed[0].startSeq}..${last.endSeq}] does not cover shadowed [${shadowMin}..${shadowMax}] — reconstruction drift`);
448
+ }
449
+ const lineage = lineageOf(session.header);
450
+ const renderCfg = {
451
+ chapterTokenTarget: config.chapterTokenTarget,
452
+ toolResultDeferFloorTokens: config.toolResultDeferFloorTokens,
453
+ planInlineChars: config.planInlineChars,
454
+ callArgArtifactTokens: config.callArgArtifactTokens,
455
+ ...(lineage !== undefined ? { subagentOf: lineage } : {}),
456
+ };
457
+ return composed.map((ch) => {
458
+ const inRange = events.filter((e) => e.seq >= ch.startSeq && e.seq <= ch.endSeq);
459
+ if (inRange.length === 0) {
460
+ throw new Error(`buildFinalizedChapters: chapter ${ch.number} [${ch.startSeq}..${ch.endSeq}] holds no shadowed events`);
461
+ }
462
+ // The WHOLE shadowed list goes in, not just this chapter's events: a plan
463
+ // verdict can land past a composed boundary, and pairing inside one range
464
+ // only would print an approved plan as pending (plans-carriage § 1).
465
+ // renderChapter filters to the range itself.
466
+ return renderChapter(events, {
467
+ title: ch.title,
468
+ summary: ch.summary,
469
+ startSeq: Math.min(...inRange.map((e) => e.seq)),
470
+ endSeq: Math.max(...inRange.map((e) => e.seq)),
471
+ }, renderCfg, [], chapterTopics(inRange, ch.startSeq, ch.endSeq));
472
+ });
473
+ }
474
+ /** The registry record shape written post-writeArchive for an engine chapter. */
475
+ export function engineRecord(plan, shadowedSeqs, rendered, writtenPath, sha256hex) {
476
+ return {
477
+ number: plan.numbers[0],
478
+ path: writtenPath,
479
+ title: plan.chapter.title,
480
+ summary: plan.chapter.summary,
481
+ startSeq: rendered.range.startSeq,
482
+ endSeq: rendered.range.endSeq,
483
+ topics: rendered.topics,
484
+ messages: rendered.stats.messages,
485
+ shadowedSeqs: [...shadowedSeqs],
486
+ sha256: sha256hex,
487
+ estimatedTokens: rendered.stats.estimatedTokens,
488
+ artifacts: rendered.artifacts.map((a) => ({ path: a.path, sha256: a.sha256, bytes: a.bytes })),
489
+ ...(rendered.stats.plans !== undefined && rendered.stats.plans.length > 0 ? { plans: rendered.stats.plans } : {}),
490
+ ...(rendered.stats.planMode !== undefined && rendered.stats.planMode !== 'unknown' ? { planMode: rendered.stats.planMode } : {}),
491
+ };
492
+ }
493
+ /** Numbers the plan reserved, or null when the manifest disagrees (corruption). */
494
+ /**
495
+ * Walk the provider-tagged summaries of one session and finalize each that is not yet finalized,
496
+ * ONE AT A TIME (#59): an item whose manifest is gone is reported and skipped, never allowed to
497
+ * abort the items behind it. Pure over injected effects so the poison-pill case is testable without
498
+ * a host.
499
+ */
500
+ export async function scanAndFinalize(state, summaries, finalizeOne, onSkip) {
501
+ const done = [];
502
+ const skipped = [];
503
+ for (const found of summaries) {
504
+ if (isFinalized(state, found.compactionId))
505
+ continue;
506
+ const hasManifest = state.plans[found.compactionId] !== undefined
507
+ && state.reservations[`compaction:${found.compactionId}`] !== undefined;
508
+ if (!hasManifest) {
509
+ // The field case: the manifest row was erased by a stale whole-row put. Nothing can write the
510
+ // chapter now (the cited path/number are not durable), so say which and move on.
511
+ skipped.push({ compactionId: found.compactionId, reason: 'no-manifest' });
512
+ onSkip?.({ compactionId: found.compactionId, reason: 'no-manifest' }, new Error('no durable plan/reservation'));
513
+ continue;
514
+ }
515
+ try {
516
+ await finalizeOne(found);
517
+ done.push(found.compactionId);
518
+ }
519
+ catch (error) {
520
+ // Keep the rest of the queue alive; the item itself stays un-finalized and is retried next touch.
521
+ skipped.push({ compactionId: found.compactionId, reason: 'finalize-failed' });
522
+ onSkip?.({ compactionId: found.compactionId, reason: 'finalize-failed' }, error);
523
+ }
524
+ }
525
+ return { done, skipped };
526
+ }
527
+ export function assertReservationMatchesPlan(state, compactionId, plan) {
528
+ const got = state.reservations[`compaction:${compactionId}`];
529
+ return got !== undefined && got.length === plan.numbers.length && got.every((n, i) => n === plan.numbers[i]);
530
+ }
531
+ //# sourceMappingURL=engine-core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-core.js","sourceRoot":"","sources":["../src/engine-core.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAe,MAAM,aAAa,CAAA;AAC5F,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AACtC,OAAO,EAAE,OAAO,EA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,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAA;YAC7E,MAAM,EAAE,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,MAAM,EAAE,iBAAiB,EAAE,EAAE,KAAK,CAAC,CAAA;QAClF,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAA;AAC1B,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAAmB,EAAE,YAAoB,EAAE,IAAmB;IACzG,MAAM,GAAG,GAAG,KAAK,CAAC,YAAY,CAAC,cAAc,YAAY,EAAE,CAAC,CAAA;IAC5D,OAAO,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAA;AAC9G,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The relief decision note — one formatter, so the numbers a diagnosis needs are never optional (#143).
3
+ *
4
+ * Why a module for one string: the live instrumented run of 2026-10-28 showed the note already carried the compaction
5
+ * id, the route, the surface and the ratio, but **nothing** about the span a pass removed — `grep -c shadowed` over
6
+ * 3,772 engine lines in the sink returned zero. That is the difference between answering "why did relief need ~19
7
+ * calls?" and re-guessing at it, so the field is now produced here and pinned by a row (`engine-lifecycle.test.ts`,
8
+ * #143) rather than being remembered at the call site. Same reason `#noteDecision` exists at all: `decided: none` covers
9
+ * two opposite bugs (no routed target vs. genuinely under threshold), so the abstention has to say which.
10
+ *
11
+ * Pure: no cordis, no ctx, no fs. `#noteDecision` gathers the inputs (it can fail, and the try/catch stays there) and
12
+ * hands them over; this turns them into bytes. Every field the previous inline template emitted is still emitted, in
13
+ * the same spellings, because existing rows grep them.
14
+ */
15
+ export type CompactionNoteInput = {
16
+ readonly where: string;
17
+ readonly trigger: unknown;
18
+ readonly sessionId?: string | null;
19
+ /** `null` means the session has no routed target — a different failure than "under threshold". */
20
+ readonly route: string | null;
21
+ readonly surfaceTokens: number | null;
22
+ readonly window: number | null;
23
+ readonly ratio?: number | string | null;
24
+ /** Nodes still on the surface — read off the SESSION, because the result does not carry it (#143). */
25
+ readonly surfaceNodes?: number | null;
26
+ /** The base engine's result, or `null` when it abstained. Field names mirror `CompactionResult` in
27
+ * `@deepseek-ai/dsh-compaction/lib/types/types.d.ts:shadowedSeqs / shadowedTokenCount`, measured not assumed. */
28
+ readonly result: {
29
+ readonly compactionId?: string | null;
30
+ readonly shadowedSeqs?: readonly number[] | null;
31
+ readonly shadowedTokenCount?: number | null;
32
+ } | null;
33
+ };
34
+ /** One line, every field, no missing values: absent counts are `0`, absent numbers are `?`. */
35
+ export declare function compactionNote(input: CompactionNoteInput): string;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The relief decision note — one formatter, so the numbers a diagnosis needs are never optional (#143).
3
+ *
4
+ * Why a module for one string: the live instrumented run of 2026-10-28 showed the note already carried the compaction
5
+ * id, the route, the surface and the ratio, but **nothing** about the span a pass removed — `grep -c shadowed` over
6
+ * 3,772 engine lines in the sink returned zero. That is the difference between answering "why did relief need ~19
7
+ * calls?" and re-guessing at it, so the field is now produced here and pinned by a row (`engine-lifecycle.test.ts`,
8
+ * #143) rather than being remembered at the call site. Same reason `#noteDecision` exists at all: `decided: none` covers
9
+ * two opposite bugs (no routed target vs. genuinely under threshold), so the abstention has to say which.
10
+ *
11
+ * Pure: no cordis, no ctx, no fs. `#noteDecision` gathers the inputs (it can fail, and the try/catch stays there) and
12
+ * hands them over; this turns them into bytes. Every field the previous inline template emitted is still emitted, in
13
+ * the same spellings, because existing rows grep them.
14
+ */
15
+ /** One line, every field, no missing values: absent counts are `0`, absent numbers are `?`. */
16
+ export function compactionNote(input) {
17
+ const r = input.result;
18
+ const shadowed = Array.isArray(r?.shadowedSeqs) ? r.shadowedSeqs.length : 0;
19
+ const shadowedTok = typeof r?.shadowedTokenCount === 'number' ? r.shadowedTokenCount : 0;
20
+ const decided = r === null
21
+ ? 'none'
22
+ : `compaction ${String(r?.compactionId ?? '?')}`;
23
+ const route = input.route === null ? 'none' : input.route;
24
+ const surface = input.surfaceTokens === null ? '?' : `${String(input.surfaceTokens)} tok`;
25
+ const window = input.window === null ? '?' : String(input.window);
26
+ const nodes = input.surfaceNodes === null || input.surfaceNodes === undefined ? '?' : String(input.surfaceNodes);
27
+ const ratio = input.ratio === null || input.ratio === undefined ? '?' : String(input.ratio);
28
+ return `${input.where} decided: ${decided} (trigger=${JSON.stringify(input.trigger)}, `
29
+ + `session=${String(input.sessionId ?? '?')}, route=${route}, surface=${surface}, ratio=${ratio}, `
30
+ + `window=${window}, shadowed=${String(shadowed)}, shadowedTok=${String(shadowedTok)}, nodes=${nodes})`;
31
+ }
32
+ //# sourceMappingURL=engine-note.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-note.js","sourceRoot":"","sources":["../src/engine-note.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAsBH,+FAA+F;AAC/F,MAAM,UAAU,cAAc,CAAC,KAA0B;IACvD,MAAM,CAAC,GAAG,KAAK,CAAC,MAAM,CAAA;IACtB,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,YAAkC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IAClG,MAAM,WAAW,GAAG,OAAO,CAAC,EAAE,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAA;IACxF,MAAM,OAAO,GAAG,CAAC,KAAK,IAAI;QACxB,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,cAAc,MAAM,CAAC,CAAC,EAAE,YAAY,IAAI,GAAG,CAAC,EAAE,CAAA;IAClD,MAAM,KAAK,GAAG,K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