@treeseed/dsh-chapters 0.1.24 → 0.2.1

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 (103) hide show
  1. package/README.md +2 -1
  2. package/cordis.patch.yml +49 -1
  3. package/docs/architecture.md +1 -496
  4. package/docs/backlog.md +234 -4
  5. package/docs/contract.md +127 -1
  6. package/docs/development.md +248 -12
  7. package/docs/host-compaction-seam.md +108 -0
  8. package/docs/knowledge-repo.md +532 -16
  9. package/docs/project-state.md +323 -0
  10. package/docs/verify.md +266 -0
  11. package/lib/archive.d.ts +49 -1
  12. package/lib/archive.js +56 -2
  13. package/lib/archive.js.map +1 -1
  14. package/lib/arrival.js +24 -10
  15. package/lib/arrival.js.map +1 -1
  16. package/lib/attach.d.ts +46 -0
  17. package/lib/attach.js +120 -0
  18. package/lib/attach.js.map +1 -0
  19. package/lib/auto-save.d.ts +74 -0
  20. package/lib/auto-save.js +175 -26
  21. package/lib/auto-save.js.map +1 -1
  22. package/lib/client.js +413 -11
  23. package/lib/client.js.map +1 -1
  24. package/lib/commands.d.ts +8 -1
  25. package/lib/commands.js +135 -7
  26. package/lib/commands.js.map +1 -1
  27. package/lib/compose.js +25 -6
  28. package/lib/compose.js.map +1 -1
  29. package/lib/continue-core.d.ts +24 -1
  30. package/lib/continue-core.js +41 -9
  31. package/lib/continue-core.js.map +1 -1
  32. package/lib/diag.d.ts +55 -0
  33. package/lib/diag.js +186 -0
  34. package/lib/diag.js.map +1 -0
  35. package/lib/engine-core.d.ts +53 -1
  36. package/lib/engine-core.js +64 -7
  37. package/lib/engine-core.js.map +1 -1
  38. package/lib/engine.d.ts +99 -0
  39. package/lib/engine.js +488 -36
  40. package/lib/engine.js.map +1 -1
  41. package/lib/enrich-queue.js +28 -2
  42. package/lib/enrich-queue.js.map +1 -1
  43. package/lib/enrich-wire.d.ts +92 -2
  44. package/lib/enrich-wire.js +135 -17
  45. package/lib/enrich-wire.js.map +1 -1
  46. package/lib/enrich.d.ts +27 -2
  47. package/lib/enrich.js +114 -18
  48. package/lib/enrich.js.map +1 -1
  49. package/lib/index.d.ts +52 -0
  50. package/lib/index.js +182 -2
  51. package/lib/index.js.map +1 -1
  52. package/lib/indexing.d.ts +7 -0
  53. package/lib/indexing.js.map +1 -1
  54. package/lib/injections.d.ts +1 -0
  55. package/lib/injections.js +38 -0
  56. package/lib/injections.js.map +1 -1
  57. package/lib/last-resort.d.ts +24 -0
  58. package/lib/last-resort.js +27 -0
  59. package/lib/last-resort.js.map +1 -0
  60. package/lib/prompt.d.ts +130 -0
  61. package/lib/prompt.js +255 -0
  62. package/lib/prompt.js.map +1 -0
  63. package/lib/registry.d.ts +39 -1
  64. package/lib/registry.js +76 -9
  65. package/lib/registry.js.map +1 -1
  66. package/lib/render.d.ts +31 -3
  67. package/lib/render.js +75 -3
  68. package/lib/render.js.map +1 -1
  69. package/lib/repair-run.d.ts +49 -0
  70. package/lib/repair-run.js +423 -0
  71. package/lib/repair-run.js.map +1 -0
  72. package/lib/repair.d.ts +200 -0
  73. package/lib/repair.js +354 -0
  74. package/lib/repair.js.map +1 -0
  75. package/lib/rules-commands.d.ts +22 -0
  76. package/lib/rules-commands.js +177 -20
  77. package/lib/rules-commands.js.map +1 -1
  78. package/lib/rules.d.ts +184 -7
  79. package/lib/rules.js +312 -27
  80. package/lib/rules.js.map +1 -1
  81. package/lib/save-core.d.ts +31 -1
  82. package/lib/save-core.js +153 -17
  83. package/lib/save-core.js.map +1 -1
  84. package/lib/session-rules.d.ts +222 -0
  85. package/lib/session-rules.js +454 -0
  86. package/lib/session-rules.js.map +1 -0
  87. package/lib/store.d.ts +22 -1
  88. package/lib/store.js +94 -17
  89. package/lib/store.js.map +1 -1
  90. package/lib/sync.js +13 -1
  91. package/lib/sync.js.map +1 -1
  92. package/lib/tools.d.ts +14 -0
  93. package/lib/tools.js +321 -32
  94. package/lib/tools.js.map +1 -1
  95. package/lib/types.d.ts +12 -1
  96. package/lib/types.js.map +1 -1
  97. package/lib/version.d.ts +9 -0
  98. package/lib/version.js +10 -0
  99. package/lib/version.js.map +1 -0
  100. package/lib/warnings.d.ts +10 -0
  101. package/lib/warnings.js +18 -0
  102. package/lib/warnings.js.map +1 -0
  103. package/package.json +9 -3
package/lib/engine.js CHANGED
@@ -13,14 +13,16 @@
13
13
  import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
14
14
  import { extractSignature, enrichSignatureWithCodegraph, turnSpanOf } from "./signature.js";
15
15
  import { appendCollection } from "./registry.js";
16
- import { appendFileSync } from 'node:fs';
16
+ import { configureDiagnosticsCap, diagnosticNote, diagnosticWarn, ensureDiagnosticsDefault } from "./diag.js";
17
+ import { makeChildArchiveListener } from "./auto-save.js";
17
18
  import z from '@deepseek-ai/schemastery';
18
- import { CHAPTERS_PROVIDER, DETERMINISTIC_MODEL, buildFinalizedChapters, findOpenCompactionId, planSummarize, reconstructShadowedSeqs, scanChaptersSummaries, } from "./engine-core.js";
19
+ import { assertReservationMatchesPlan, CHAPTERS_PROVIDER, DETERMINISTIC_MODEL, buildFinalizedChapters, findOpenCompactionId, planSummarize, reconstructShadowedSeqs, scanChaptersSummaries, scanAndFinalize, } from "./engine-core.js";
19
20
  import { composeChapters } from "./compose.js";
20
21
  import { carryActivePlan, detectPlans } from "./plans.js";
21
- import { stripReminderSpans } from "./injections.js";
22
+ import { isInjectedProse, stripReminderSpans } from "./injections.js";
22
23
  import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm';
23
24
  import { applyArrivalStubs } from "./arrival.js";
25
+ import { lastResortCeilingTokens } from "./last-resort.js";
24
26
  import { extractPlot } from "./engine-core.js";
25
27
  import { appendChapters, isFinalized, markFinalized, rememberPlan, reserve } from "./registry.js";
26
28
  import { acquireChapterStore, makeAllocator, makeArchiveFs, resolveStoreRoot } from "./store.js";
@@ -29,6 +31,10 @@ import { registerProvider } from "./provider.js";
29
31
  import { createTreedxProvider } from "./treedx/provider.js";
30
32
  import { createEnrichWiring } from "./enrich-wire.js";
31
33
  import { writeArchive } from "./archive.js";
34
+ import { ENRICH_MAX_TOKENS_DEFAULT } from "./enrich.js";
35
+ import { hostname } from 'node:os';
36
+ import path from 'node:path';
37
+ import { captureMinedRules, makeHeaderParentReader, makeRuleCaptureListener, renderRulesBlock } from "./session-rules.js";
32
38
  /**
33
39
  * Per-turn deterministic signature listener (knowledge-repo.md §4.1), as a
34
40
  * plain factory so the LOGIC is unit-testable against the real host Session
@@ -65,13 +71,19 @@ export function makeSignatureListener(deps) {
65
71
  // CodeGraph symbol verification is async and fire-and-forget. The cwd
66
72
  // comes from the session header; missing cwd or missing CLI → silent no-op.
67
73
  const cwd = session?.header?.cwd;
74
+ // #61: the compaction realm is where the SAIP finalization failures happened, and all three left
75
+ // zero trace because the sink had to be configured before it existed. Resolve it from the session
76
+ // that is compacting, first one wins.
77
+ if (cwd !== undefined && deps.storeRoot !== undefined) {
78
+ ensureDiagnosticsDefault(path.join(cwd, deps.storeRoot, 'diagnostics.log'));
79
+ }
68
80
  const enrichPromise = cwd !== undefined
69
81
  ? enrichSignatureWithCodegraph(sig, span, deps.subprocess, cwd).catch(() => { })
70
82
  : Promise.resolve();
71
- const job = () => enrichPromise.then(() => deps.store()).then(({ store }) => {
72
- const state = store.get(id);
73
- return state.then((st) => store.put(id, appendCollection(st, sig)));
74
- }).then(() => undefined).catch(deps.warn);
83
+ // One serialized section (#59): the signature listener used to get→append→put with the whole
84
+ // row snapshot, so a turn that landed during another door's await could erase that door's
85
+ // committed state. The lost signature is what dropped a COMPLETED turn out of the archive.
86
+ const job = () => enrichPromise.then(() => deps.store()).then(({ store }) => store.mutate(id, (st) => appendCollection(st, sig))).then(() => undefined).catch(deps.warn);
75
87
  const prev = chains.get(id);
76
88
  const next = prev === undefined ? job() : prev.then(job);
77
89
  chains.set(id, next);
@@ -106,6 +118,28 @@ export function makeFirstTurnPullListener(deps) {
106
118
  }
107
119
  };
108
120
  }
121
+ export function carryOpenRequest(parts, messages, capChars) {
122
+ // ONE predicate for "is this injected machine prose" — `src/injections.ts`, the same screen the
123
+ // archive body and the title chooser use. A second list here is the #59 bug re-made: it would lag
124
+ // the first, and a drift row exists precisely to catch that (it caught this, minutes after I wrote it).
125
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
126
+ const m = messages[i];
127
+ if (m?.role !== 'user')
128
+ continue;
129
+ const c = m.content;
130
+ const text = typeof c === 'string' ? c
131
+ : Array.isArray(c) ? c.filter((b) => b?.type === 'text').map((b) => b.text ?? '').join('\n') : '';
132
+ const t = text.trim();
133
+ if (t === '' || isInjectedProse(t))
134
+ continue;
135
+ const clipped = t.length > capChars;
136
+ const body = clipped
137
+ ? `${t.slice(0, capChars)}\n[carried in part: ${String(t.length)} characters total, ${String(capChars)} included — the whole turn stays in the durable log]`
138
+ : t;
139
+ return [...parts, { type: 'text', text: `OPEN REQUEST (verbatim; this relief shadows the turn that asked it):\n"""\n${body}\n"""` }];
140
+ }
141
+ return [...parts];
142
+ }
109
143
  export class ChaptersCompactionEngine extends BasicCompactionEngine {
110
144
  // Base inject is ['llm','tokenMeter','sessions']; subclassing INHERITS statics,
111
145
  // so re-declare with what the chapter flow adds (r12's crash, FINDINGS).
@@ -136,6 +170,12 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
136
170
  })),
137
171
  auto: z.boolean(),
138
172
  artifactStoreRoot: z.string(),
173
+ knowledgeMirrorDir: z.string().default('.dsh-knowledge'),
174
+ openRequestCarryMaxChars: z.number().step(1).min(200).default(4000),
175
+ /** #78 A: the last-resort deferral switch. Operator-visible, default on. */
176
+ lastResortArtifact: z.boolean().default(true),
177
+ /** #95 follow-up: diagnostics sink cap, bytes. 0 = uncapped. */
178
+ diagnosticsMaxBytes: z.number().step(1).min(0).default(8388608),
139
179
  chapterTokenTarget: z.number().step(1).min(1),
140
180
  toolResultDeferFloorTokens: z.number().step(1).min(0),
141
181
  // The composition knobs ride the same row so the engine path and the fork
@@ -145,12 +185,29 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
145
185
  chapterLimit: z.number().step(1).min(1).default(8000),
146
186
  syncDebounceMs: z.number().step(1).min(0).default(30000),
147
187
  toolResultArtifactTokens: z.number().step(1).min(256).default(8000),
188
+ // #61 Amendment A — the seventh archive moment. A `ch-*` continuation child has origin `user`, so
189
+ // door 5 never sees it: the field case archived NOTHING across 2,363 events because no moment was
190
+ // watching. Save-only, fires at turn/end, thresholds are config and never literals.
191
+ childAutoArchive: z.boolean().default(true),
192
+ childAutoArchiveMinTurns: z.number().step(1).min(1).default(4),
148
193
  elicitedPlot: z.boolean().default(true),
194
+ harnessId: z.string().default(''),
195
+ sessionRulesEnabled: z.boolean().default(true),
196
+ rulesMarkerPrefix: z.string().default('ADD RULE:'),
197
+ coreRulesBudgetTokens: z.number().step(1).min(1).default(1200),
198
+ projectRulesDisplayCap: z.number().step(1).min(0).default(12),
199
+ sessionRulesDisplayCap: z.number().step(1).min(0).default(12),
200
+ rulesRelevance: z.boolean().default(true),
201
+ rulesEnrichment: z.boolean().default(true),
202
+ rulesMinedPerChapter: z.number().step(1).min(0).default(3),
203
+ rulesAutoActivate: z.boolean().default(true),
204
+ rulesModel: z.string().default(''),
149
205
  enrichmentEnabled: z.boolean().default(true),
150
206
  enrichmentModel: z.string().default(''),
151
207
  enrichmentTrigger: z.string().default('both'),
152
208
  enrichmentIdleMs: z.number().step(1).min(0).default(60000),
153
209
  enrichmentBatchCap: z.number().step(1).min(1).default(5),
210
+ enrichmentMaxTokens: z.number().step(1).min(400).default(ENRICH_MAX_TOKENS_DEFAULT),
154
211
  vocabApply: z.boolean().default(false),
155
212
  vocabCoMin: z.number().step(1).min(2).default(3),
156
213
  vocabOverlapMin: z.number().default(0.5),
@@ -162,13 +219,33 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
162
219
  treedxLeaseRetryDelayMs: z.number().step(1).min(0).default(1000),
163
220
  });
164
221
  chaptersConfig;
222
+ /** #50 §7.5/§7.3: capture + rendering numbers, host plane mirrored in. */
223
+ ruleCfg = { harnessId: '', captureEnabled: false, markerPrefix: 'ADD RULE:', budgetTokens: 1200, projectCap: 12, sessionCap: 12, relevance: true, mine: true, mineCap: 3, autoActivate: true, model: '' };
165
224
  storePromise = null;
225
+ /** #52: the delegation-edge reader, built lazily because a field initializer
226
+ * cannot see the constructor parameter and the realm may hold neither service.
227
+ * null = not built yet; undefined = built and unavailable (registry edges only). */
228
+ parentOfReader = null;
229
+ /** The reader the rule-ancestry walk uses. Absent ⇒ delegation contributes no edge. */
230
+ ruleParentOf() {
231
+ if (this.parentOfReader === null) {
232
+ this.parentOfReader = makeHeaderParentReader((name) => {
233
+ try {
234
+ return this.ctx.get?.(name);
235
+ }
236
+ catch {
237
+ return undefined;
238
+ }
239
+ });
240
+ }
241
+ return this.parentOfReader ?? undefined;
242
+ }
166
243
  constructor(ctx, config = {}) {
167
244
  // The base's resolveConfig rejects unknown keys at runtime (measured r18:
168
245
  // `BasicCompactionConfig: unknown key "artifactStoreRoot"`) — the archive's
169
246
  // own keys are peeled off and held here; the base receives exactly its
170
247
  // documented shape. (The loader does not strip them for us either.)
171
- const { artifactStoreRoot, chapterTokenTarget, toolResultDeferFloorTokens, mergeThreshold, chapterLimit, syncDebounceMs, toolResultArtifactTokens, elicitedPlot, planInlineChars, callArgArtifactTokens, plansInCheckpoint, planCheckpointChars, enrichmentEnabled, enrichmentModel, enrichmentTrigger, enrichmentIdleMs, enrichmentBatchCap, vocabApply, vocabCoMin, vocabOverlapMin, treedxFetchTimeoutMs, treedxWorkspaceTtlSeconds, treedxLeaseRetries, treedxLeaseRetryDelayMs, ...baseConfig } = config;
248
+ const { artifactStoreRoot, knowledgeMirrorDir, openRequestCarryMaxChars, lastResortArtifact, diagnosticsMaxBytes, chapterTokenTarget, toolResultDeferFloorTokens, mergeThreshold, chapterLimit, syncDebounceMs, toolResultArtifactTokens, elicitedPlot, childAutoArchive, childAutoArchiveMinTurns, planInlineChars, callArgArtifactTokens, plansInCheckpoint, planCheckpointChars, harnessId, sessionRulesEnabled, rulesMarkerPrefix, coreRulesBudgetTokens, projectRulesDisplayCap, sessionRulesDisplayCap, rulesRelevance, rulesEnrichment, rulesMinedPerChapter, rulesAutoActivate, rulesModel, enrichmentEnabled, enrichmentModel, enrichmentTrigger, enrichmentIdleMs, enrichmentBatchCap, vocabApply, vocabCoMin, vocabOverlapMin, enrichmentMaxTokens, treedxFetchTimeoutMs, treedxWorkspaceTtlSeconds, treedxLeaseRetries, treedxLeaseRetryDelayMs, ...baseConfig } = config;
172
249
  super(ctx, baseConfig);
173
250
  // The realm's module copy owns its own provider registry (cordis isolation
174
251
  // between planes): register the configured TreeDX transport HERE, exactly
@@ -182,27 +259,55 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
182
259
  }));
183
260
  this.chaptersConfig = {
184
261
  artifactStoreRoot: artifactStoreRoot ?? '.dsh-chapters',
262
+ knowledgeMirrorDir: knowledgeMirrorDir ?? DEFAULT_CLONE_DIR,
263
+ openRequestCarryMaxChars: openRequestCarryMaxChars ?? 4000,
264
+ lastResortArtifact: lastResortArtifact ?? true,
265
+ diagnosticsMaxBytes: diagnosticsMaxBytes ?? 8388608,
185
266
  chapterTokenTarget: chapterTokenTarget ?? 8000,
186
267
  toolResultDeferFloorTokens: toolResultDeferFloorTokens ?? 200,
187
268
  mergeThreshold: mergeThreshold ?? 0.3,
188
269
  chapterLimit: chapterLimit ?? 8000,
189
270
  toolResultArtifactTokens: toolResultArtifactTokens ?? 8000,
271
+ childAutoArchive: childAutoArchive ?? true,
272
+ childAutoArchiveMinTurns: childAutoArchiveMinTurns ?? 4,
190
273
  planInlineChars: planInlineChars ?? 900,
191
274
  callArgArtifactTokens: callArgArtifactTokens ?? 0,
192
275
  plansInCheckpoint: plansInCheckpoint ?? true,
193
276
  planCheckpointChars: planCheckpointChars ?? 1600,
194
277
  elicitedPlot: elicitedPlot ?? true,
195
278
  };
279
+ // The realm row is a second place the cap can legitimately come from (a plugin plane may boot before
280
+ // any session exists). Applying it here means the first door writes with the row's value.
281
+ configureDiagnosticsCap(this.chaptersConfig.diagnosticsMaxBytes);
196
282
  this.syncDebounceMs = syncDebounceMs ?? 30000;
197
283
  this.vocabCfg = { apply: vocabApply ?? false, coMin: vocabCoMin ?? 3, overlapMin: vocabOverlapMin ?? 0.5 };
198
284
  this.enrichCfg = {
199
285
  enabled: enrichmentEnabled ?? true,
200
286
  model: enrichmentModel ?? '',
287
+ mineRules: rulesEnrichment ?? true,
288
+ mineCap: rulesMinedPerChapter ?? 3,
289
+ rulesAutoActivate: rulesAutoActivate ?? true,
290
+ rulesModel: rulesModel ?? '',
291
+ maxTokens: enrichmentMaxTokens ?? ENRICH_MAX_TOKENS_DEFAULT,
201
292
  trigger: (enrichmentTrigger ?? 'both'),
202
293
  idleMs: enrichmentIdleMs ?? 60000,
203
294
  batchCap: enrichmentBatchCap ?? 5,
204
295
  };
296
+ this.ruleCfg = {
297
+ harnessId: harnessId ?? '',
298
+ captureEnabled: sessionRulesEnabled ?? true,
299
+ markerPrefix: rulesMarkerPrefix ?? 'ADD RULE:',
300
+ budgetTokens: coreRulesBudgetTokens ?? 1200,
301
+ projectCap: projectRulesDisplayCap ?? 12,
302
+ sessionCap: sessionRulesDisplayCap ?? 12,
303
+ relevance: rulesRelevance ?? true,
304
+ mine: rulesEnrichment ?? true,
305
+ mineCap: rulesMinedPerChapter ?? 3,
306
+ autoActivate: rulesAutoActivate ?? true,
307
+ model: rulesModel ?? '',
308
+ };
205
309
  this.#listenForSignatures();
310
+ this.#listenForRuleCapture();
206
311
  this.#listenForFirstTurnPull();
207
312
  ctx.logger?.info?.('dsh-chapters: engine constructed for a mount (signature listener live)');
208
313
  }
@@ -217,7 +322,7 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
217
322
  * lock and debounce keep the two honest against each other. */
218
323
  syncDebounceMs = 30000;
219
324
  vocabCfg = { apply: false, coMin: 3, overlapMin: 0.5 };
220
- enrichCfg = { enabled: false, model: '', trigger: 'both', idleMs: 60000, batchCap: 5 };
325
+ enrichCfg = { enabled: false, model: '', trigger: 'both', idleMs: 60000, batchCap: 5, mineRules: true, mineCap: 3 };
221
326
  enrichPromise = null;
222
327
  lastCwd = null;
223
328
  lastRoute = null;
@@ -254,9 +359,30 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
254
359
  const r = route ?? this.lastRoute;
255
360
  if (r === null || r.provider === '' || r.model === '')
256
361
  throw new Error('no auxiliary route yet');
257
- return await this.#auxComplete(prompt, r, 900);
362
+ return await this.#auxComplete(prompt, r, this.enrichCfg.maxTokens ?? ENRICH_MAX_TOKENS_DEFAULT);
258
363
  },
259
364
  conversationRoute: () => this.lastRoute,
365
+ // §7.5 the sink: the realm plane owns disk, identity and the registry, so it
366
+ // writes what the pass mined. Session rules are LOCAL — nothing is armed on
367
+ // the scheduler here, because the pool never carries them.
368
+ onMinedRules: async ({ sessionId, chapterNumber, humanText, rules, max, autoActivate }) => {
369
+ const cwd = this.lastCwd ?? undefined;
370
+ if (cwd === undefined)
371
+ return { written: 0, stated: 0, inferred: 0, pending: 0 };
372
+ const { store } = await this.store();
373
+ const res = captureMinedRules({
374
+ storeDir: resolveStoreRoot(cwd, this.chaptersConfig.artifactStoreRoot),
375
+ harnessId: (this.ruleCfg.harnessId !== '' ? this.ruleCfg.harnessId : hostname()),
376
+ sessionId,
377
+ records: store.rules(),
378
+ humanText,
379
+ rules,
380
+ maxPerChapter: max,
381
+ chapterNumber,
382
+ autoActivate,
383
+ });
384
+ return { written: res.ids.length, stated: res.stated, inferred: res.inferred, pending: res.pending };
385
+ },
260
386
  scheduler: { schedule: (cwd, why) => { void this.#scheduler().then((s) => s.schedule(cwd, why)).catch(() => undefined); } },
261
387
  log: (m) => this.ctx.logger?.info?.(`dsh-chapters: ${m}`),
262
388
  warn: (m) => this.ctx.logger?.warn?.(`dsh-chapters: ${m}`),
@@ -318,16 +444,67 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
318
444
  store: () => this.store(),
319
445
  warn: (error) => { this.ctx.logger?.warn?.(`dsh-chapters: signature capture failed (${String(error)})`); },
320
446
  subprocess,
447
+ storeRoot: this.chaptersConfig.artifactStoreRoot,
321
448
  onCollected: (id, sig) => {
322
449
  this.ctx.logger?.info?.(`dsh-chapters: signature collected for ${id} (${sig.seqs.length} events, ${sig.paths.length} paths, ${sig.size} est tokens)`);
323
450
  },
324
451
  }));
452
+ // #61: the seventh moment, registered where the other turn/end doors already live. Its own
453
+ // watermark makes a re-run a no-op, and it creates NO session — the mid-step rule stays intact.
454
+ this.ctx.on('session/event', makeChildArchiveListener({
455
+ ctx: { logger: this.ctx.logger },
456
+ // the store opens lazily and once — same accessor the signature listener uses; a row that
457
+ // resolved it per turn would reopen the domain on every turn/end.
458
+ store: () => this.store().then(({ store }) => store),
459
+ wiring: {
460
+ presetId: 'chapters',
461
+ artifactStoreRoot: this.chaptersConfig.artifactStoreRoot,
462
+ chapterTokenTarget: this.chaptersConfig.chapterTokenTarget,
463
+ toolResultDeferFloorTokens: this.chaptersConfig.toolResultDeferFloorTokens,
464
+ mergeThreshold: this.chaptersConfig.mergeThreshold,
465
+ chapterLimit: this.chaptersConfig.chapterLimit,
466
+ scheduler: { schedule: (cwd, reason) => { void this.#scheduler().then((sc) => sc.schedule(cwd, reason)); } },
467
+ },
468
+ enabled: this.chaptersConfig.childAutoArchive ?? true,
469
+ minTurns: this.chaptersConfig.childAutoArchiveMinTurns ?? 4,
470
+ }));
325
471
  }
326
472
  catch {
327
473
  // A non-cordis ctx (L0 construction) has no event bus — signatures are
328
474
  // optional there by design; the compaction path is unaffected.
329
475
  }
330
476
  }
477
+ /**
478
+ * #50 §7.5: capture `ADD RULE:` markers at the SAME `turn/end` boundary the
479
+ * topic signatures use — this extends an existing door, it is not a sixth
480
+ * archive moment. Deterministic and model-free (invariant 1): no marker in the
481
+ * turn costs one string scan and nothing else. Gated off when `harnessId` is
482
+ * absent, because a rule with no author partition is a rule nothing can
483
+ * revoke.
484
+ */
485
+ #listenForRuleCapture() {
486
+ try {
487
+ this.ctx.on('session/event', makeRuleCaptureListener({
488
+ enabled: () => this.ruleCfg.captureEnabled,
489
+ prefix: () => this.ruleCfg.markerPrefix,
490
+ // The realm row's harnessId, or the same default the host plane's config
491
+ // uses (`hostname()`). A custom host-plane override does NOT strand the
492
+ // rule: the directory is only an author partition, and rendering walks
493
+ // every dir under `rules/` and activates by scope+ancestry (§7.5) — the
494
+ // id prefix differs, nothing else.
495
+ harnessId: () => (this.ruleCfg.harnessId !== '' ? this.ruleCfg.harnessId : hostname()),
496
+ storeRoot: (cwd) => resolveStoreRoot(cwd, this.chaptersConfig.artifactStoreRoot),
497
+ store: async () => ({ store: (await this.store()).store }),
498
+ warn: (error) => { this.ctx.logger?.warn?.(`dsh-chapters: session-rule capture failed (${String(error)})`); },
499
+ onCaptured: (sessionId, ids) => {
500
+ this.ctx.logger?.info?.(`dsh-chapters: ${ids.length} session rule(s) captured for ${sessionId} (${ids.join(', ')})`);
501
+ },
502
+ }));
503
+ }
504
+ catch {
505
+ // same containment as signatures: a non-cordis ctx has no event bus
506
+ }
507
+ }
331
508
  /** Lazy, once. `storageDomain` is a host-plane singleton the realm resolves;
332
509
  * acquire (never bare-open): a mounted tools-plugin may already own the reservation. */
333
510
  store() {
@@ -349,7 +526,7 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
349
526
  // digest; NO chapter path is cited, so nothing can dangle. A distinct
350
527
  // provider tag keeps the finalizer's scan from claiming this record.
351
528
  return {
352
- summary: [{ type: 'text', text: `Compacted ${input.messages.length} messages (deterministic digest; no chapter: ${cwd === null ? 'no workspace cwd' : cid === null ? 'no open transaction' : 'empty region'}).` }],
529
+ summary: carryOpenRequest([{ type: 'text', text: `Compacted ${input.messages.length} messages (deterministic digest; no chapter: ${cwd === null ? 'no workspace cwd' : cid === null ? 'no open transaction' : 'empty region'}).` }], input.messages, this.chaptersConfig.openRequestCarryMaxChars),
353
530
  provider: `${CHAPTERS_PROVIDER}-degraded`,
354
531
  model: DETERMINISTIC_MODEL,
355
532
  };
@@ -414,13 +591,38 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
414
591
  this.ctx.logger?.warn?.(`dsh-chapters: plan carriage skipped (${String(error)}) — the archive still holds the plan`);
415
592
  }
416
593
  }
417
- const { plan, state: next } = planSummarize(session, state, input, this.chaptersConfig, reserve, cid, composition, plot, planCarry);
418
- const stored = rememberPlan(next, cid, {
419
- number: plan.numbers[0], path: plan.chapter.path, title: plan.chapter.title, summary: plan.chapter.summary,
420
- ...(plan.chapters !== undefined ? { chapters: plan.chapters } : {}),
594
+ // #50 §7.6: the rules ride the checkpoint the way the plot and the plan do.
595
+ // Anything that goes wrong here DEGRADES TO NOTHING and is reported on the
596
+ // operator channel — the compaction critical path stays zero-model-token and
597
+ // never fails because of a rules read (§1 invariant 1, §7.3's non-blocking rule).
598
+ let rulesCarry = null;
599
+ try {
600
+ rulesCarry = await this.#rulesForCheckpoint(session);
601
+ }
602
+ catch (error) {
603
+ this.#diagnostic(`dsh-chapters: rule carriage skipped (${String(error)}) — the archive still holds every rule`);
604
+ }
605
+ // #59: everything ABOVE this line (composition, plot elicitation, rules, plan carry) is
606
+ // expensive and may cross a model call; the WRITE re-runs on a fresh row inside one section, so
607
+ // the reservation and manifest can no longer be rewound by a stale whole-row put — and the TOC
608
+ // text we are about to hand the host cites numbers that are durable at this point.
609
+ let tocText = '';
610
+ await store.mutate(session.id, (fresh) => {
611
+ // #69: the realm resolves an ABSOLUTE store root; hand planSummarize the session cwd so the record it
612
+ // mints is workspace-relative like every door's.
613
+ const wcwd = session.header?.cwd;
614
+ const { plan, state: next } = planSummarize(session, fresh, input, { ...this.chaptersConfig, workspaceCwd: wcwd }, reserve, cid, composition, plot, planCarry, rulesCarry);
615
+ const stored = rememberPlan(next, cid, {
616
+ number: plan.numbers[0], path: plan.chapter.path, title: plan.chapter.title, summary: plan.chapter.summary,
617
+ ...(plan.chapters !== undefined ? { chapters: plan.chapters } : {}),
618
+ });
619
+ // The drift check that has existed with zero callers: a manifest whose reservation is not
620
+ // durable (or not the same numbers) means the TOC we are about to emit cites the unreachable.
621
+ assertReservationMatchesPlan(stored, cid, plan);
622
+ tocText = plan.tocText;
623
+ return stored;
421
624
  });
422
- await store.put(session.id, stored); // reservation + manifest durable BEFORE the text cites them
423
- return { summary: [{ type: 'text', text: plan.tocText }], provider: CHAPTERS_PROVIDER, model: DETERMINISTIC_MODEL };
625
+ return { summary: carryOpenRequest([{ type: 'text', text: tocText }], input.messages, this.chaptersConfig.openRequestCarryMaxChars), provider: CHAPTERS_PROVIDER, model: DETERMINISTIC_MODEL };
424
626
  }
425
627
  // ------------------------------------------------------------ entry points (finalize after commit)
426
628
  /**
@@ -494,11 +696,19 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
494
696
  async #arrive(agent) {
495
697
  const session = agent.session;
496
698
  const cwd = session.header?.cwd;
497
- if (cwd === undefined || cwd === '')
699
+ if (cwd === undefined || cwd === '') {
700
+ // #78: two bare returns made arrival artifacting vanish COMPLETELY, silently — the very
701
+ // silence that lets a leg fail while nobody can say whether the code path ran. And the
702
+ // reason is printed as the SHAPE it found, because `session.header?.cwd` is precisely the
703
+ // assumption a host format bump retires (the v3→v4 log lesson).
704
+ diagnosticNote(this.ctx.logger, 'realm:engine:arrive', `arrival stubbing skipped: no session cwd (session keys=${Object.keys(session ?? {}).slice(0, 10).join(',')})`);
498
705
  return;
706
+ }
499
707
  const meter = this.ctx.tokenMeter;
500
- if (meter === undefined)
708
+ if (meter === undefined) {
709
+ diagnosticNote(this.ctx.logger, 'realm:engine:arrive', 'arrival stubbing skipped: no tokenMeter on the realm context');
501
710
  return;
711
+ }
502
712
  const r = await applyArrivalStubs(session, {
503
713
  cwd,
504
714
  storeRoot: this.chaptersConfig.artifactStoreRoot,
@@ -508,7 +718,150 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
508
718
  if (r.detail !== undefined)
509
719
  this.ctx.logger?.warn?.(`dsh-chapters: arrival stubbing degraded (${r.detail})`);
510
720
  }
721
+ /**
722
+ * One line per compaction decision — the second half of "is relief actually running?".
723
+ * `realm:engine:*` so the site is attributable, note-level so a routine decision never reads as
724
+ * a failure, and it names which entry point (`compactIfNeeded` on pressure/auto vs `compactNow`
725
+ * on `/compact`) because those two disagreeing is exactly the kind of drift a field report needs
726
+ * to be able to tell apart. (#78)
727
+ */
728
+ /**
729
+ * The last-resort deferral (#78 option A). Returns how many nodes it stubbed, and 0 — never a
730
+ * guess — unless every input to the ceiling is real: `resolveStoreRoot`-style derivation lives in
731
+ * `lastResortCeilingTokens`, so this method only supplies measured values. Runs only from the
732
+ * declined branch; the operator's `toolResultArtifactTokens` still governs every ordinary case.
733
+ */
734
+ async #lastResortRelief(agent, signal) {
735
+ try {
736
+ if (this.chaptersConfig.lastResortArtifact !== true)
737
+ return 0;
738
+ const route = this.lastRoute;
739
+ const meter = this.ctx.tokenMeter;
740
+ const llm = this.ctx.llm;
741
+ if (route === null || meter === undefined || typeof llm?.resolveModelInfo !== 'function')
742
+ return 0;
743
+ const info = await llm.resolveModelInfo(route.provider, route.model, signal);
744
+ const base = this;
745
+ // Quiet unless there is a problem to solve. Relief declines on EVERY ordinary pre-step because
746
+ // the surface is below the trigger, and the first two notes this feature ever emitted were that
747
+ // non-event — noise that also hid the case worth naming. Every value here is measured at this
748
+ // point in the method: no invented field and no assumed window (my first attempt reached for a
749
+ // `lastWindowTokens` that does not exist, and `tsc` was the only thing that caught it).
750
+ const surfaceNow = Number(meter.measure?.(agent.session)?.totalTokens ?? NaN);
751
+ const ratioNow = this.config?.thresholdRatio;
752
+ const windowNow = Number(info?.context?.contextWindow ?? NaN);
753
+ const overTrigger = Number.isFinite(surfaceNow) && Number.isFinite(windowNow)
754
+ && typeof ratioNow === 'number' && surfaceNow > windowNow * ratioNow;
755
+ const retainTokens = base.config?.retainTokens;
756
+ // The host builds model-info as `{ context: { contextWindow }, ...defaultMaxTokens ? { defaultMaxTokens } : {} }`
757
+ // — read out of the pinned bundle today. `defaultMaxTokens` is a SIBLING of `context`, so the previous line
758
+ // read a field that never exists, fell through to the base config's `maxTokens` (65,536: a routing
759
+ // headroom, `resolveConfig` defaults it from `headroomTokens`), and made the ceiling negative forever. The
760
+ // model's real output budget is 15,000 here, which is what makes `window − retain − reserved` derivable.
761
+ const reserved = Number(info?.defaultMaxTokens ?? info?.context?.maxTokens ?? base.config?.maxTokens ?? NaN);
762
+ const ceiling = lastResortCeilingTokens({
763
+ windowTokens: Number(info?.context?.contextWindow ?? NaN),
764
+ retainRatio: Number(base.config?.retainRatio ?? NaN),
765
+ // optional, not `| undefined`: `exactOptionalPropertyTypes` is on, and a property that can
766
+ // hold undefined is a different promise from one that may be absent.
767
+ ...(retainTokens !== undefined ? { retainTokens } : {}),
768
+ // The completion budget comes from the MODEL, measured: `resolveConfig` defaults
769
+ // `maxTokens` to `headroomTokens` (65,536 — a routing headroom, not a per-request output
770
+ // budget), so `32,000 − 5,120 − 65,536` is negative and the ceiling is permanently
771
+ // underivable. `info.context.maxTokens` (15,000 here) sits in the same object as
772
+ // `contextWindow`; the base config stays only as a fallback so the abstention path still
773
+ // fires and says so when neither is present.
774
+ reservedCompletionTokens: reserved,
775
+ });
776
+ if (ceiling === null) {
777
+ // Measured tonight: relief declined twice with `surface=39983 trigger=16000` and the last
778
+ // resort NEVER fired — and said nothing about why. A feature that abstains silently is
779
+ // indistinguishable from a feature that isn't installed, which is the exact complaint this
780
+ // branch has filed against everything else (#61a). So: name the missing input.
781
+ diagnosticNote(this.ctx.logger, 'realm:engine:last-resort', `not applied: coexistence ceiling underivable (window=${String(info?.context?.contextWindow)}, retainRatio=${String(base.config?.retainRatio)}, retainTokens=${String(base.config?.retainTokens)}, maxTokens=${String(base.config?.maxTokens)}) — check the realm row's compaction keys, not this feature`);
782
+ return 0;
783
+ }
784
+ const session = agent.session;
785
+ const cwd = session.header?.cwd ?? '';
786
+ if (cwd === '')
787
+ return 0; // no workspace identity, no deferral — same rule as `#arrive`
788
+ const before = [...session.surface.nodes].length;
789
+ const r = await applyArrivalStubs(session, {
790
+ cwd,
791
+ storeRoot: resolveStoreRoot(cwd, this.chaptersConfig.artifactStoreRoot),
792
+ floorTokens: ceiling,
793
+ estimate: (m) => meter.estimateMessage?.(m) ?? 0,
794
+ });
795
+ if (r.stubbed > 0) {
796
+ diagnosticWarn(this.ctx.logger, 'realm:engine:last-resort', `relief declined, so ${String(r.stubbed)} tool/result node(s) larger than the coexistence ceiling (${String(ceiling)} tok) were artifact-deferred regardless of toolResultArtifactTokens — survivability over economy (#78 A); the archive keeps every byte and chapters_artifact answers for them (surface nodes ${String(before)} → ${String(session.surface.nodes.length)})`);
797
+ }
798
+ return r.stubbed;
799
+ }
800
+ catch { /* a last resort must never become the reason relief failed */
801
+ return 0;
802
+ }
803
+ }
804
+ /** See the call site: a decline while OVER the trigger is a statement, not a shrug. Never throws. */
805
+ async #reportDecline(agent, signal) {
806
+ try {
807
+ const route = this.lastRoute;
808
+ const meter = this.ctx.tokenMeter;
809
+ if (route === null || meter === undefined)
810
+ return;
811
+ const surface = meter.measure?.(agent.session)?.totalTokens;
812
+ const llm = this.ctx.llm;
813
+ if (typeof surface !== 'number' || typeof llm?.resolveModelInfo !== 'function')
814
+ return;
815
+ const info = await llm.resolveModelInfo(route.provider, route.model, signal);
816
+ const window = info?.context?.contextWindow;
817
+ const ratio = this.config?.thresholdRatio;
818
+ if (typeof window !== 'number' || typeof ratio !== 'number')
819
+ return;
820
+ const triggerTokens = Math.floor(window * ratio);
821
+ if (surface <= triggerTokens)
822
+ return;
823
+ const session = agent.session;
824
+ let oversized = 0;
825
+ let biggest = 0;
826
+ for (const seq of session.surface.nodes) {
827
+ const ev = session.eventAt(seq);
828
+ if (ev?.type !== 'tool/result')
829
+ continue;
830
+ const est = meter.estimateMessage?.(ev.data?.message) ?? 0;
831
+ if (est > biggest)
832
+ biggest = est;
833
+ if (est > triggerTokens)
834
+ oversized += 1;
835
+ }
836
+ diagnosticWarn(this.ctx.logger, 'realm:engine:decline', `relief declined while the surface is over the trigger (surface=${String(surface)} trigger=${String(triggerTokens)} window=${String(window)} ratio=${String(ratio)}): no safe range to compact, and ${String(oversized)} inline tool/result node(s) individually exceed the trigger (largest ${String(biggest)} tok). Context relief needs the arrival floor below that node size — toolResultArtifactTokens is the operator switch, and the archive keeps every byte either way.`);
837
+ }
838
+ catch { /* a report must never become the reason compaction failed */ }
839
+ }
840
+ #noteDecision(where, trigger, result, agent) {
841
+ // The INPUTS, not just the verdict: `decided: none` is one word covering two opposite bugs —
842
+ // no routed target (the base returns null on line one) and under-threshold (a real decision).
843
+ // Heavy's leg sat exactly there, so the note now carries route, surface tokens and ratio.
844
+ // All of it wrapped: a diagnostic that can throw is a diagnostic that will eat the step.
845
+ let route = 'unknown';
846
+ let surface = '? tok';
847
+ try {
848
+ route = this.lastRoute === null ? 'none' : `${this.lastRoute.provider}/${this.lastRoute.model}`;
849
+ const meter = this.ctx.tokenMeter;
850
+ const measured = meter?.measure?.(agent.session);
851
+ if (typeof measured?.totalTokens === 'number')
852
+ surface = `${String(measured.totalTokens)} tok`;
853
+ }
854
+ catch { /* never let instrumentation break compaction */ }
855
+ diagnosticNote(this.ctx.logger, `realm:engine:${where}`, `${where} decided: ${result === null ? 'none' : `compaction ${String(result?.compactionId ?? '?')}`} (trigger=${JSON.stringify(trigger)}, session=${String(agent?.session?.id ?? '?')}, route=${route}, surface=${surface}, ratio=${String(this.config?.thresholdRatio ?? '?')})`);
856
+ }
511
857
  async compactIfNeeded(agent, trigger, signal) {
858
+ // #78: the entry line that proves the HOST called this. Every row in the lifecycle suite
859
+ // CALLS `compactIfNeeded` directly — the test has always been the caller, which is exactly
860
+ // how a suite stays green while the product relieves nothing. Field evidence on 0.2.0-rc.2:
861
+ // 35,428 tokens against a 16,000 trigger, ZERO `compaction/*` events, and no line anywhere
862
+ // saying whether relief ran. One info line per entry, carrying the trigger the host passed,
863
+ // makes "is context relief wired at all?" answerable from a session log instead of inferred.
864
+ diagnosticNote(this.ctx.logger, 'realm:engine:compact', `compactIfNeeded entered (trigger=${JSON.stringify(trigger)}, session=${String(agent?.session?.id ?? '?')})`);
512
865
  this.#observeRoute(agent);
513
866
  await this.#arrive(agent);
514
867
  // Finalization runs whether super resolves OR throws: the pressure retry
@@ -522,10 +875,49 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
522
875
  }
523
876
  catch (error) {
524
877
  await this.#finalizeGuarded(agent);
878
+ // A throw while the surface is OVER the trigger is the same field failure as a null —
879
+ // arguably worse, because the user sees the endpoint's 400 rather than our explanation.
880
+ // Report first, then rethrow untouched; the report itself can never mask the error.
881
+ await this.#reportDecline(agent, signal);
882
+ // no result exists on this path — the base engine threw — so the line says `none` and the
883
+ // reason is the rethrown error, not a value invented for the log
884
+ this.#noteDecision('compactIfNeeded', trigger, null, agent);
525
885
  throw error;
526
886
  }
527
887
  if (result !== null)
528
888
  await this.#finalizeGuarded(agent);
889
+ // #78: entry alone is half the question. Three `trigger="pressure"` entries on 0.2.0-rc.2
890
+ // produced no `compaction/*` event at all, and nothing could say whether the base engine
891
+ // declined (a meter/threshold disagreement) or acted and our finalization lost the evidence.
892
+ // The decision now sits beside the entry, in the same artifact.
893
+ // #78: the quiet failure was the worst part. Six compactions, then a raw `400 … exceeds the
894
+ // context window` from the endpoint, and nothing the product said about WHY relief stopped.
895
+ // This reports the numbers it actually had — surface, trigger, window, ratio, and how many
896
+ // inline tool/results are individually larger than the trigger — and changes no behavior:
897
+ // the arrival floor is the operator's switch (AGENTS: a behavior switch, not a knob), and the
898
+ // engine does not get to reinterpret it silently.
899
+ if (result === null) {
900
+ // #78 option A: relief declined, so a node that cannot coexist with the mandatory tail is no
901
+ // longer an economy question — the session is stuck. Defer THAT node as a last resort and give
902
+ // relief one more chance. Ordering is the whole design: this sits inside the declined branch,
903
+ // never in `#arrive`, so `heavy` still proves pressure compaction first. An eager version would
904
+ // arrival-stub the surface and make the leg's claim untestable (AGENTS' named trap), which is
905
+ // what the anti-vacuity rows below guard against.
906
+ const deferred = await this.#lastResortRelief(agent, signal);
907
+ if (deferred > 0) {
908
+ try {
909
+ const retry = await super.compactIfNeeded(agent, trigger, signal);
910
+ if (retry !== null) {
911
+ await this.#finalizeGuarded(agent);
912
+ this.#noteDecision('compactIfNeeded', trigger, retry, agent);
913
+ return retry;
914
+ }
915
+ }
916
+ catch { /* still stuck: fall through to the decline report, then rethrow nothing */ }
917
+ }
918
+ await this.#reportDecline(agent, signal);
919
+ }
920
+ this.#noteDecision('compactIfNeeded', trigger, result, agent);
529
921
  return result;
530
922
  }
531
923
  async compactNow(agent, signal, sourceCommandId) {
@@ -537,10 +929,15 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
537
929
  }
538
930
  catch (error) {
539
931
  await this.#finalizeGuarded(agent);
932
+ this.#noteDecision('compactNow', 'manual', null, agent);
540
933
  throw error;
541
934
  }
542
935
  if (result !== null)
543
936
  await this.#finalizeGuarded(agent);
937
+ // #78: the same decision line on the manual path. Reporting only the pressure route would
938
+ // leave `/compact` — the door a human actually pulls — as silent as the bug this instrument
939
+ // exists to catch.
940
+ this.#noteDecision('compactNow', 'manual', result, agent);
544
941
  return result;
545
942
  }
546
943
  /**
@@ -557,6 +954,54 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
557
954
  this.#diagnostic(`dsh-chapters: chapter finalization deferred (session ${session.id}): ${String(error?.stack ?? error)}`);
558
955
  }
559
956
  }
957
+ /**
958
+ * §7.3/§7.6: the block this session's rebuilt head should carry, from the ONE
959
+ * builder that renders it for the notice too — a second rule-ranking or
960
+ * rule-selecting implementation is forbidden (record §8: two doors, one
961
+ * scorer). Zero bytes when nothing is active.
962
+ *
963
+ * Relevance topics come from the session's OWN stored turn signatures
964
+ * (deterministic, already on disk, no model call), newest last. With
965
+ * `rulesRelevance` off the selection falls back to category→id order, which is
966
+ * the order the tapes were distilled against.
967
+ */
968
+ async #rulesForCheckpoint(session) {
969
+ const cwd = session.header?.cwd;
970
+ if (cwd === undefined || cwd === '')
971
+ return null;
972
+ const { store } = await this.store();
973
+ const harness = this.ruleCfg.harnessId !== '' ? this.ruleCfg.harnessId : hostname();
974
+ const project = projectForCwd(store.projects(), cwd);
975
+ // the SAME renderer the doors use — one builder for every rebuilt head (§7.3)
976
+ const built = await renderRulesBlock({
977
+ // #85: the configured root, not the constant — an e2e boot pins this per port so a notice
978
+ // cannot pick up rules from whatever the developer's repo happens to contain.
979
+ mirrorDir: resolveStoreRoot(cwd, this.chaptersConfig.knowledgeMirrorDir ?? DEFAULT_CLONE_DIR),
980
+ storeDir: resolveStoreRoot(cwd, this.chaptersConfig.artifactStoreRoot),
981
+ projectKey: project?.projectKey ?? '',
982
+ harnessId: harness,
983
+ budgetTokens: this.ruleCfg.budgetTokens,
984
+ projectCap: this.ruleCfg.projectCap,
985
+ sessionCap: this.ruleCfg.sessionCap,
986
+ relevance: this.ruleCfg.relevance,
987
+ includeSession: true,
988
+ store,
989
+ sessionId: session.id,
990
+ // #52: the delegation edge. A subagent that compacts in place must see the
991
+ // rules of the session that delegated it, or the whole point of the tier is
992
+ // lost exactly where the work actually happens.
993
+ ...(() => { const p = this.ruleParentOf(); return p !== undefined ? { parentOf: p } : {}; })(),
994
+ });
995
+ if (built.kind === 'none')
996
+ return null;
997
+ if (built.kind === 'refusal') {
998
+ // announced, never clipped: the head says the rules did not fit rather
999
+ // than silently carrying none of them
1000
+ this.#diagnostic(`dsh-chapters: rules over budget at this checkpoint — ${built.reason}`);
1001
+ return `Rules NOT carried into this checkpoint (their token budget was exceeded, so nothing was clipped): ${built.reason}`;
1002
+ }
1003
+ return built.text;
1004
+ }
560
1005
  /**
561
1006
  * The operator-visible warn channel (r19: headless profiles route ctx.logger
562
1007
  * where nobody can see it; measured again 2026-09-27: even the in-process
@@ -565,24 +1010,30 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
565
1010
  * not a tunable. Any degradation that leaves the user wondering "did the
566
1011
  * feature run?" belongs here.
567
1012
  */
568
- #diagnostic(message) {
569
- this.ctx.logger?.warn?.(message);
570
- const sink = process.env.DSH_CHAPTERS_ENGINE_ERRORS;
571
- if (sink !== undefined) {
572
- try {
573
- appendFileSync(sink, `[${new Date().toISOString()}] ${message}\n`);
574
- }
575
- catch { /* diagnostics must never mask the real failure */ }
576
- }
1013
+ #diagnostic(message, error) {
1014
+ // #54: ONE writer, in src/diag.ts. This held a private three-line copy of the sink while
1015
+ // the two places a user's door can actually fail — the host-plane tool and the shared
1016
+ // continuation core — wrote nothing anywhere. Which is how a kernel refusal that ended the
1017
+ // whole acceptance chain left no trace readable without a browser.
1018
+ diagnosticWarn(this.ctx.logger, 'realm:engine', message, error);
577
1019
  }
578
1020
  /** Every provider-tagged summary without a finalized manifest, oldest first. */
1021
+ /**
1022
+ * Per-item containment (#59). The scan used to await `#finalizeOne` in a bare loop, and
1023
+ * `#finalizeOne` THROWS when a manifest is missing — so one erased manifest (exactly what the
1024
+ * SAIP lost-update produced) aborted the scan on its first iteration forever: every later
1025
+ * compaction in that session could never write its chapters, and their numbers stayed burned.
1026
+ * One bad item may never poison the items behind it: report it, name it, continue.
1027
+ */
579
1028
  async #finalizeAllOutstanding(session) {
580
1029
  const { store } = await this.store();
581
- const state = await store.get(session.id);
582
- for (const found of scanChaptersSummaries(session)) {
583
- if (isFinalized(state, found.compactionId))
584
- continue;
585
- await this.#finalizeOne(session, store, found.compactionId, found.shadowedSeqs);
1030
+ const out = await scanAndFinalize(await store.get(session.id), scanChaptersSummaries(session), async (found) => { await this.#finalizeOne(session, store, found.compactionId, found.shadowedSeqs); }, (reason, error) => this.#diagnostic(`dsh-chapters: chapter finalization deferred for compaction ${reason.compactionId} (${reason.reason}: `
1031
+ + `${String(error?.message ?? error)}) — its chapter was never written and the `
1032
+ + 'rest of the queue still proceeds. Run /chapters-repair (issue #60) to materialize it.'));
1033
+ if (out.done.length > 0) {
1034
+ const cwd = session.header?.cwd;
1035
+ if (cwd !== undefined)
1036
+ void this.#scheduler().then((s2) => s2.schedule(cwd, 'archive:compaction')).catch(() => undefined);
586
1037
  }
587
1038
  }
588
1039
  async #finalizeOne(session, store, compactionId, shadowedSeqs) {
@@ -618,9 +1069,10 @@ export class ChaptersCompactionEngine extends BasicCompactionEngine {
618
1069
  // jointly account for what the surface replacement hid (legacy single-
619
1070
  // chapter behavior generalized).
620
1071
  const records = wrote.records.map((r) => ({ ...r, shadowedSeqs: [...shadowedSeqs] }));
621
- let next = appendChapters(state, records);
622
- next = markFinalized(next, compactionId, numbers);
623
- await store.put(session.id, next);
1072
+ // #59: `state` was read BEFORE writeArchive (render + every artifact write). Committing from it
1073
+ // would erase anything another door committed meanwhile — which is how the SAIP compaction lost
1074
+ // its record while its 960 KB file stayed on disk. The commit re-reads inside one section.
1075
+ await store.mutate(session.id, (fresh) => markFinalized(appendChapters(fresh, records), compactionId, numbers));
624
1076
  // §5.1: compaction finalization is a push point (debounced).
625
1077
  const cwdNow = session.header?.cwd;
626
1078
  if (cwdNow !== undefined)