@fractalsynapse/dsh-chapters 0.2.32 → 0.2.34

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 (69) hide show
  1. package/cordis.patch.yml +17 -6
  2. package/docs/architecture.md +305 -1
  3. package/docs/backlog.md +36 -1
  4. package/docs/contract.md +79 -2
  5. package/docs/development.md +45 -1
  6. package/docs/host-compaction-seam.md +68 -0
  7. package/docs/plans-carriage.md +32 -2
  8. package/docs/project-state.md +180 -2
  9. package/docs/verify.md +70 -0
  10. package/lib/archive.d.ts +11 -0
  11. package/lib/archive.js +27 -1
  12. package/lib/archive.js.map +1 -1
  13. package/lib/auto-save.js +7 -3
  14. package/lib/auto-save.js.map +1 -1
  15. package/lib/client.js +1 -1
  16. package/lib/client.js.map +1 -1
  17. package/lib/continue-core.d.ts +18 -3
  18. package/lib/continue-core.js +48 -16
  19. package/lib/continue-core.js.map +1 -1
  20. package/lib/engine-core.d.ts +95 -10
  21. package/lib/engine-core.js +90 -21
  22. package/lib/engine-core.js.map +1 -1
  23. package/lib/engine.d.ts +34 -0
  24. package/lib/engine.js +124 -8
  25. package/lib/engine.js.map +1 -1
  26. package/lib/goal-carriage.d.ts +62 -0
  27. package/lib/goal-carriage.js +92 -0
  28. package/lib/goal-carriage.js.map +1 -0
  29. package/lib/index.d.ts +16 -0
  30. package/lib/index.js +210 -108
  31. package/lib/index.js.map +1 -1
  32. package/lib/injections.d.ts +5 -1
  33. package/lib/injections.js +27 -4
  34. package/lib/injections.js.map +1 -1
  35. package/lib/log-shape.d.ts +55 -1
  36. package/lib/log-shape.js +85 -1
  37. package/lib/log-shape.js.map +1 -1
  38. package/lib/preset.d.ts +17 -2
  39. package/lib/preset.js +23 -2
  40. package/lib/preset.js.map +1 -1
  41. package/lib/prompt.d.ts +11 -0
  42. package/lib/prompt.js +79 -7
  43. package/lib/prompt.js.map +1 -1
  44. package/lib/registry.d.ts +23 -2
  45. package/lib/registry.js +18 -3
  46. package/lib/registry.js.map +1 -1
  47. package/lib/render.d.ts +104 -5
  48. package/lib/render.js +299 -60
  49. package/lib/render.js.map +1 -1
  50. package/lib/repair-run.js +2 -0
  51. package/lib/repair-run.js.map +1 -1
  52. package/lib/repair.d.ts +1 -1
  53. package/lib/repair.js +40 -0
  54. package/lib/repair.js.map +1 -1
  55. package/lib/save-core.d.ts +20 -0
  56. package/lib/save-core.js +71 -20
  57. package/lib/save-core.js.map +1 -1
  58. package/lib/store.d.ts +3 -1
  59. package/lib/store.js +7 -2
  60. package/lib/store.js.map +1 -1
  61. package/lib/tools-row.js +8 -1
  62. package/lib/tools-row.js.map +1 -1
  63. package/lib/tools.js +57 -10
  64. package/lib/tools.js.map +1 -1
  65. package/lib/types.d.ts +7 -0
  66. package/lib/types.js.map +1 -1
  67. package/lib/version.d.ts +1 -1
  68. package/lib/version.js +1 -1
  69. package/package.json +5 -1
package/cordis.patch.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # dsh-chapters bundle patch — ACTIVE: package.json declares this file as the
2
2
  # plugin's composition patch, applied when a profile adds the plugin. The YAML
3
3
  # below the comment block is functional; everything in this comment is the
4
- # complete configuration reference (kept in sync with src/index.ts and
4
+ # configuration reference for the HOST plane (kept in sync with src/index.ts and
5
5
  # src/engine.ts — verified 2026-10-01 against both schemas, including the
6
6
  # 2026-09-21 transport keys). The site's §17 (Configuration) is the readable
7
7
  # authority; this header mirrors it.
@@ -77,11 +77,14 @@
77
77
  # # DSH_CHAPTERS_ENGINE_ERRORS overrides it; the literal 'off' is the
78
78
  # # only silence. Before this, unset meant NO TRACE ON DISK — the three
79
79
  # # SAIP compaction finalization failures left none.
80
- # childAutoArchive: true # the seventh archive moment (#61): a ch-* continuation child is not a
80
+ # childAutoArchive: true # INERT HERE (#354) — this is a key of the preset's `chapters-engine`
81
+ # # realm row (src/engine.ts), and the host Schema has no such key, so setting it in a
82
+ # # profile's plugin config: block changes nothing. Set it on the row. The seventh archive moment (#61): a ch-* continuation child is not a
81
83
  # # subagent, so door 5 never sees it. `ch-dc3be3ab` reached 2,363
82
84
  # # events and 3 completed turns with chapters: [] — nothing failed,
83
85
  # # NO MOMENT WAS WATCHING. Set false to close this door.
84
- # childAutoArchiveMinTurns: 4 # after the first archive, how many unarchived completed turns re-arm it
86
+ # childAutoArchiveMinTurns: 4 # INERT HERE (#354) — realm-row key, as above. After the first
87
+ # # archive, how many unarchived completed turns re-arm it
85
88
  # # (the first archive always fires: never-archived is the defect).
86
89
  # chapterOversizeFactor: 2 # hard oversize multiple of chapterTokenTarget (#59): over the
87
90
  # # TARGET warns ("split at the next boundary, never clip"), over
@@ -142,9 +145,9 @@
142
145
  # # '' ⇒ the feature does not exist (zero calls,
143
146
  # # zero surface); setting one IS the enable.
144
147
  # # Runtime: /chapters-prompt model <p/m|clear>
145
- # promptContextChars: 4000 # hard budget on the assembled input slice
148
+ # promptContextChars: 32000 # hard budget on the assembled input slice
146
149
  # # (chapter summaries + screened live tail)
147
- # promptMaxChars: 240 # cap on the recommendation; over-cap ⇒ retry
150
+ # promptMaxChars: 4096 # cap on the recommendation; over-cap ⇒ retry
148
151
  # # once ⇒ refuse with numbers, never truncate
149
152
  #
150
153
  # # ---- transport (2026-09-21 provider-seam amendment) -------------------
@@ -157,8 +160,16 @@
157
160
  # treedxLeaseRetries: 3 # pull-retry budget when the lease is held
158
161
  # treedxLeaseRetryDelayMs: 1000 # delay between lease retries
159
162
  #
163
+ # Keys the HOST config: block accepts and IGNORES (#354) — they exist in the host Schema.object, so a
164
+ # profile patch parses, but no host-plane code reads them (the exported Config interface omits them and
165
+ # the `as Schema<Config>` cast hides that from tsc), and they are absent from the shipped realm row.
166
+ # To retune one, set it on the `chapters-engine` row of the `preset-chapters` composition:
167
+ # knowledgeMirrorDir, noticeIndexCap, openRequestCarryMaxChars, lastResortArtifact
168
+ #
160
169
  # Realm-row-only keys (in the preset's engine row, not this patch):
161
- # harnessId, sessionRulesEnabled, rulesMarkerPrefix, coreRulesBudgetTokens,
170
+ # sessionRulesEnabled, rulesMarkerPrefix, coreRulesBudgetTokens,
171
+ # (harnessId is NOT in this list — it is declared on both planes: the host Config and the
172
+ # realm row. #354 removed the misclassification.)
162
173
  # enrichmentMaxTokens (4000 — one auxiliary completion budget; sized to cover
163
174
  # reasoning tokens, since the measured route reports reasoning inside completion usage
164
175
  # and does not enforce max_tokens)
@@ -108,6 +108,36 @@ Division of labour:
108
108
  a range is refused with its own number, on every door including compaction: the field produced an
109
109
  89,982-token chapter, an unrepaired 237,870-token orphan, and eleven chapters over 32K — against a
110
110
  8K target and 32K-class hardware. A chapter that cannot be re-read is not an archive.
111
+ - **Subdivide before refusing, by size — and report a refusal as one** (#344). That refusal was being
112
+ reached by default in the deterministic doors, because `deriveRanges`/`composeChapters` emit one chapter
113
+ per **turn** and real opening turns are large. Measured with the shipped functions on three real logs:
114
+ eadc refused **2 of 3** turns, platfolio 55 of 153, arcnexus 32 of 308 — and in every log the refused
115
+ range was the session's **opening** turn, the one a later continuation most needs. So `/chapters-save`,
116
+ `/chapters-fork`, subagent settlement and forced-child archive could not archive real sessions; only
117
+ model-driven `chapters_continue` could. Worse, the tool had no `oversize` case, so the run on eadc
118
+ printed **"Saved: 0 chapter(s) archived … Enrichment queued."** — a success line for a refusal.
119
+
120
+ 1. `splitOversize` now runs on **every** deterministic door (it sat inside the repair-only
121
+ `a.span !== undefined` arm) and packs greedily against `chapterTokenTarget`, cutting only **between
122
+ events**. Equal-*count* chunking — the previous form — left 42 of 121 eadc parts over the ceiling on
123
+ real, unevenly-sized turns while its own note claimed a split had happened. Same three logs after:
124
+ **0 refused** (275 / 3,248 / 3,081 parts). Packing targets the *target*, not the refusal *ceiling*,
125
+ because the splitter measures an event-payload proxy while the gate measures **rendered** markdown and
126
+ the proxy runs low.
127
+ 2. The door branches on `skipped !== null && records.length === 0` rather than on an enumerated list of
128
+ reasons — `oversize` and `payloadless` had both fallen through to the success wording, and a per-case
129
+ list is how that recurs. The message names the size, both knobs, whether a chapter number was spent,
130
+ and the alternative that can still work (`chapters_continue`).
131
+
132
+ One row in `title-predicate-and-floors.test.ts` changed, and it is a **contract change, not a test fix**:
133
+ its fixture is a single ~120 KB assistant event that no boundary choice can reduce. #117's escape valve
134
+ already decided an indivisible single event is archived whole with a loud warning rather than refused,
135
+ because refusing an atom makes a long session permanently un-compactable (measured there:
136
+ `chapters_continue` refused four times over one 77,903-token event). Before #344 the deterministic doors
137
+ never reached that valve — equal-count splitting kept the giant inside a multi-event chapter, so it
138
+ errored. Now they reach it: the chapter is archived, with a warning naming the size, the knobs and how to
139
+ reload it in slices. The property the old row guarded — an un-readable chapter must not pass silently —
140
+ is carried by the warning instead of by losing the session's whole opening turn.
111
141
  - **A title is chosen by the same predicate that screens bodies** (#59). Bodies use `injections.ts`
112
142
  (`source.kind`); title derivation sees provider messages with no source, so it carried its own
113
143
  regex — which drifted behind the host and let an injected `time-context` snapshot become a chapter
@@ -115,6 +145,26 @@ Division of labour:
115
145
  live checkpoint). `isInjectedProse` is now the one predicate, fed by the same list of injected
116
146
  shapes; a row pins that both callers use it and that the regex file is gone.
117
147
 
148
+ - **The injection screen is chosen by provenance, not applied uniformly** (#347). Screening removes host
149
+ spans of two different kinds, and one regex was doing both. For a host-**injected** event an
150
+ unterminated `<system-reminder>` genuinely means "injected prose to the end of the field", so the
151
+ open-ended arm is right. For text a **human typed**, the same arm silently deletes their own words from
152
+ the first tag quote to the end of the message. Measured on the real event (session `17f7c1d6`, seq 8,
153
+ kept as `tests/fixtures/reminder-tail-seq8.json`): 5,061 characters, one opening tag, no closing tag —
154
+ a person quoting the marker while listing injected strings for an agent to search for. The archive kept
155
+ 2,543 characters, discarded the last **2,518**, and labelled the loss
156
+ *"omitted:host-injected … project state, not conversation"* — a human instruction reported as host
157
+ state, contradicting this module's own header ("a human typing the words AGENTS.md in prose is
158
+ conversation and stays verbatim").
159
+ So human-authored text is screened **balanced-only**: a span counts when the host closed it, and a
160
+ quoted marker plus everything after it stays. The decision lives in `screenConversation`, the single
161
+ shared site that already holds the event's `data` — the archive (`render.ts`) and the director's tail
162
+ (`prompt.ts`) both route through it, so no caller can forget a flag. That is #59's rule again: one
163
+ predicate per semantic decision, chosen where the fact is known rather than passed around.
164
+ Not widened to assistant text: a model's own words are verbatim for a different reason, and a runtime
165
+ snapshot has been observed appended under `role: user|system` — the existing behaviour there is left
166
+ alone and scoped deliberately.
167
+
118
168
  - **Model submits exceptions only**: `toolResultOverrides: [{seq, inline}]`. Usually empty or one entry, so
119
169
  the judgment costs almost no output tokens — which is why this is affordable where "the model writes the
120
170
  chapter bodies" was not.
@@ -210,6 +260,38 @@ rewrite costs the prefix nothing, unlike the pruner's mid-history cliff. Row con
210
260
  `toolResultArtifactTokens` is pinned per e2e project (500 for arrival, default
211
261
  8000 elsewhere).
212
262
 
263
+ ### Amendment (#334, 2026-11-14): a shadowed result's PAYLOAD is what a chapter archives
264
+
265
+ Arrival-time artifacting has a consumer the design did not account for: **the renderer**. A
266
+ shadowing replacement appends a second `tool/result` for the same callId whose text is the stub, and
267
+ the chapter renderer's copy rule — "keep the LAST result per callId", written 2026-09-29 against a
268
+ host redelivery where the two copies were byte-identical — therefore kept the stub. On current bytes
269
+ that premise never fires: measured across three production sessions, 44 callIds carry more than one
270
+ result, **0 are identical, and 44 are this exact shadow shape**. The chapter recorded the pointer,
271
+ discarded 932,462 characters of payload, named the dropped seq nowhere (not even in
272
+ `unrenderedSeqs`), and still counted it in `events:`.
273
+
274
+ The rule is now stated by **size, over the whole log**, in one predicate
275
+ (`resultRenderPlan`, `src/log-shape.ts`), consumed by both the chapter body and `chapters_segment`'s
276
+ candidate list:
277
+
278
+ - **largest copy wins**, ties break to the newest — so a true redelivery keeps the behaviour #61
279
+ documented, and a ~500-byte stub can never out-weigh what it replaced;
280
+ - **decided over the full log, not the range.** The old range-local choice made the archived bytes a
281
+ function of where the model put a chapter edge (span the pair → stub; stop before it → payload),
282
+ which is what invariant 4 forbids;
283
+ - a chapter containing **only** a stub renders the original's bytes at that position, accepting the
284
+ duplicate across two chapters. Duplication is bounded, visible, and stored once (the artifact store
285
+ is content-addressed); silent loss is none of those;
286
+ - the substitution is **written into the chapter** (`seq N is a shadowing stub; the full payload is
287
+ archived at seq M`), because a correction nobody can see is how this class of bug survived a year.
288
+
289
+ Invariant 1 was never at risk — the durable log keeps every copy, and the compaction finalizer
290
+ already resolves through the replacement chain (`resolveOriginalEvent`). The defect was entirely in
291
+ what the archive claimed. Note also that integrity checks pass over this: chapter `sha256` and
292
+ artifact hashes were verified consistent, **of the stub**. Internal consistency is not fidelity to
293
+ the log, and #334 is why the two must be asserted separately.
294
+
213
295
  ### Amendment (user-directed, 2026-09-19, APPROVED, **landed**): the plot note across in-place compaction
214
296
 
215
297
  > Shipped: the forward path is the preset persona suffix (the agent is told to end substantive turns
@@ -236,6 +318,43 @@ is **going on**, authored while the model still holds the thread:
236
318
  - Invariant check: the model authors *state*, never archive text (invariant 4 intact); the note rides
237
319
  the replacement event append-only; every byte of the conversation still lives in chapters.
238
320
 
321
+ ## What a chapter contains: coverage is a decision, never a default (#346)
322
+
323
+ The audit reported that ~75% of durable events never render into a chapter and asked for that to be
324
+ fixed. Measured against three real production logs — **55,334 events across 35 distinct types** — the
325
+ percentage was right and the implied conclusion was not: most of that mass is lifecycle bookkeeping an
326
+ archive should not contain. What was actually missing was not coverage but **a record of which absences
327
+ were chosen**, because "excluded" and "forgotten" were indistinguishable — and a new host event type
328
+ would land in the same silent place as the interesting ones.
329
+
330
+ `EXCLUDED_EVENT_TYPES` in `src/render.ts` is now that record: every type the renderer deliberately does
331
+ not write, with the reason. The `default:` branch counts a type as unrendered **unless it is listed**, so
332
+ judged silence is possible only where a reason is written down, and an unjudged type still surfaces in the
333
+ existing *"N event(s) rendered no output"* warning. The asymmetry is the entire design.
334
+
335
+ Three types did carry unique content and are now rendered:
336
+
337
+ - **`command/run`** — a human invoking a slash command, with its arguments. Verified unique against every
338
+ user/assistant message and tool call/result in all three logs. AGENTS already requires "always preserve
339
+ invocations and arguments in the body"; a command invocation was the one invocation being dropped.
340
+ - **`command/done`** — its outcome, because an invocation without its result is half a fact.
341
+ - **`goal/change`** — the goal **ledger** as one compact fact (operation, revision, id, a 120-char prefix,
342
+ the seq). Not the objective text: that arrives as `<goal_round>` user messages, which render verbatim, so
343
+ a full copy would duplicate them. The ledger points; the round holds the bytes.
344
+
345
+ And the most valuable finding here is a **negative** one, because it is the fix that must not be made.
346
+ `agent/inbox/spliced` is 2.4% of all events with ~2 MB of payload — the single largest "uncovered" type,
347
+ and the obvious candidate for a new case. Measured: **658 of 659** spliced messages are byte-identical to a
348
+ `user/message` the renderer already writes. Rendering the channel would have duplicated two megabytes of a
349
+ person's own words into every chapter that spans them, while making coverage look better. So it is excluded
350
+ *by measurement*, and the row that pins the non-render carries the count.
351
+
352
+ Consequences to keep in mind when extending this: an exclusion list makes the renderer quieter, and quieter
353
+ is not the same as correct — so the gate (`tests/unit/render-coverage.test.ts`) checks coverage against the
354
+ committed inventory of *observed* types, not against a hand-written list, rejects thin reasons, and asserts
355
+ that an unlisted type still warns. Add a type to the table only with a reason that would survive being read
356
+ in six months.
357
+
239
358
  ## The archive moments
240
359
 
241
360
  Chapters are written by exactly five doors, and knowledge that trips none of them is knowledge
@@ -282,7 +401,13 @@ that never enters the index. Four are session-facing, all idempotent over a per-
282
401
  is compacted. Enrichment is **queued** per settlement — a 10-child fanout must not `runNow` ten
283
402
  annotator passes — and an empty or refused chapter is never enqueued (#61). A continuable child
284
403
  settles repeatedly; the watermark makes every repeat after the first a save of only-new-turns.
285
- Config: `subagentAutoSave` (default on).
404
+ Config: `subagentAutoSave` (default on) — and **that flag gates this moment alone (#341)**. The
405
+ suggested-next-step door and the #319 reload self-check are separate doors that merely share the
406
+ turn/log boundary; they were nested inside this flag until #341, so disabling archiving also silenced
407
+ the prompt bar while `/chapters-prompt` kept reporting ON. The prompt plane's switch stays what it
408
+ always was — a configured prompt model, one knob, no second boolean.
409
+ `tests/unit/host-plane-door-gating.test.ts` pins the nesting structurally, because `apply()` has no
410
+ deterministic harness and an unobserved wiring block is exactly how this drifted.
286
411
 
287
412
  **Amendment 2026-10-22 (#61, item 5) — the seventh moment: a rooted child that has never archived.**
288
413
  A `ch-*` continuation child is a real session with a real `parentSession`, and door 5 does NOT cover it
@@ -306,6 +431,45 @@ actions mid-step" rule is not engaged — the same reasoning that let door 5 exi
306
431
  (`childAutoArchive`, `childAutoArchiveMinTurns`), never literals. Knowledge that trips none of the seven
307
432
  never enters the index: when adding a door, **extend this list, never copy the pipeline**.
308
433
 
434
+ ### The watermark is one predicate with two arms (#336)
435
+
436
+ The watermark is `max(endSeq)` over all records, `-1` when there are none, and the door that accepts a
437
+ submission holds it to a floor. That floor was **one-sided**: it refused a range starting *above* the
438
+ watermark (the seqs in between would be dropped, and a gap is loss) but accepted a range starting
439
+ *below* it, which re-archives committed seqs under **fresh chapter numbers** — the same text living in
440
+ two active records, against "keep chapter numbers and bodies immutable".
441
+
442
+ The refusal had no partner either, so nothing could see the result. `coverage()` starts its cursor at
443
+ the floor, so an under-floor submission reports `gaps: []` while inflating its own covered count (302
444
+ "covered" for 201 real seqs), and the repair auditor keeps coverage in a `Set<number>` and looks only
445
+ for seqs *missing* from it — a Set has no cardinality, so "in two chapters" and "in one" are the same
446
+ value to it. Live registry when this was measured: **42 of 64 rows self-overlapping, 1,453 duplicate
447
+ records, 29,871 seqs archived more than once.**
448
+
449
+ The rule now, in one place:
450
+
451
+ - `nextUnarchivedSeq(chapters)` is the ONLY derivation of "first seq not yet archived". The two doors
452
+ previously had different ones — `continue-core` seeded `max()` at `-1`, `save-core` at `0` and then
453
+ wrote `lastArchived > 0 ? lastArchived + 1 : 0`. Both are correct until a chapter legitimately covers
454
+ seq 0, which every real log is positioned to do (a durable log begins with `permission/preset` at
455
+ seq 0), after which save-core's form re-archives seq 0 on every call.
456
+ - `validateRanges` refuses on **both** sides of the floor and names which side was crossed.
457
+ - `duplicateCoveredSeqs(chapters)` counts owners per seq; `repair.ts` reports a `duplicate-coverage`
458
+ finding per contiguous run sharing one owner set. It is **report-only by decision**: choosing which
459
+ of two records to supersede is a call about which citation was meant to name which bytes, and the
460
+ durable log holds both copies either way. Auto-picking would mutate an immutable record on a
461
+ heuristic — the same posture `duplicate-number` already takes.
462
+
463
+ One exemption keeps a documented guarantee from being broken by the lower arm: a submission whose range
464
+ list is **exactly** what is already committed is a retry, not a duplicate. The attempt key
465
+ (`sessionId@ceiling`) makes that call reuse its numbers and write nothing new — `saveSession`'s
466
+ idempotence, pinned by `tests/integration/plans-carriage.test.ts` ("a retry of the same archive reuses
467
+ numbers and never duplicates the blob"), which the naive two-sided floor turned red. Only a range list
468
+ that *differs* from what is committed re-archives under new numbers, and that is what the refusal is
469
+ for. `chapters_continue`'s own retry path relies on this, so the exemption is load-bearing, not a
470
+ convenience — and it is pinned in both directions (`an exact replay stays idempotent while a differing
471
+ range list is refused`) so it cannot widen into a hole.
472
+
309
473
  ## Budgets and the Reserve Margin
310
474
 
311
475
  Two distinct ceilings. Conflating them caused the original design's silent-failure mode.
@@ -325,6 +489,12 @@ note may blow through before any work happens, and the plugin would refuse every
325
489
  the small-context hardware it targets. The header is a fixed cost to subtract, not a competitor for the
326
490
  index. Measure it once per generation and cache it.
327
491
 
492
+ The header bound is the last real request's **billed input**, not just its uncached part: the host reports
493
+ `inputTokens`, `cacheReadTokens` and `cacheWriteTokens` as DISJOINT arms whose sum is the prompt
494
+ (`@deepseek-ai/dsh-llm` `TokenUsage` contract), so admission subtracts all three (#395). Reading two of
495
+ three under-counts the header on exactly the turns that extend the prompt cache — the bound would stop
496
+ being conservative where conservatism matters most.
497
+
328
498
  The budget is enforced as a **preflight**: measure, then refuse with concrete numbers
329
499
  (`TOC 4,120 + note 2,800 = 6,920 > budget 5,750 (0.25 × (32,000 − 9,000))`) *before* creating any
330
500
  session. Never truncate to fit — a clipped handoff note is the lossy behaviour this plugin exists to
@@ -376,6 +546,44 @@ Two structural consequences:
376
546
  - **Append-only has no exceptions.** Nothing derived is written back into the store; the registry is the
377
547
  only mutable state, and it is a domain table designed for it.
378
548
 
549
+ ## The Goal Across a Renewal (#349)
550
+
551
+ An active goal is the one continuing intention a session has, and a child born at a renewal boundary does
552
+ not inherit it: `create_goal` requires a direct-human turn, and the child's first turn is
553
+ `plugin:dsh-chapters`. Before this, the objective stopped driving the work exactly where the plugin's own
554
+ promise begins, and AGENTS' rule to "carry the authorized outcome" was left to the model's prose.
555
+
556
+ **The rule now: carry the goal as text, and state aloud that it is not armed.** One selector
557
+ (`foldGoalFromLog`) folds the parent's durable `goal/change` events — operations `create`, `edit`, `pause`,
558
+ `resume`, `block`, `complete`, `clear`, with `{id, revision, objective, phase, maxGoalRounds, blockedReason}`
559
+ — and one renderer (`renderGoalCarriage`) emits the child's `## Goal (carried from the parent session)`
560
+ block: objective whole, revision, round cap, phase, the seq it came from, and the sentence that only a human
561
+ can re-arm. It sits with the plans block, **above** the fold, because an objective is the fact a child must
562
+ not reconstruct from recall.
563
+
564
+ Invariants this respects:
565
+
566
+ - **No goal, zero bytes.** Sessions that never used a goal get a byte-identical notice, which is also what
567
+ keeps recorded tapes unmoved. An empty section is treated as absent, not as an empty heading.
568
+ - **`clear` ends it; `complete` is reported as finished** and receives no re-arm instruction. A child must
569
+ not pick up a purpose the human closed, and must not be told to resume one that succeeded.
570
+ - **Unknown operations are ignored, not guessed.** If the host adds one, the fold keeps the last state it
571
+ understands rather than letting an unrecognized event rewrite the child's sense of its own objective.
572
+ - **The budget bounds display, never the instruction.** `goalNoticeChars` (default 600, host-declared and
573
+ defaulted on the plugin config — the #354 discipline) truncates the objective with the length stated;
574
+ the "only the human can re-arm" lines are never cut, because a truncated permission notice is worse than
575
+ none.
576
+ - **`phase` is foldable; `activation` is not.** The host keeps armed/disarmed process-local and the plugin
577
+ reads it from the live service for its own driver decisions, so the notice says who CAN change the driver
578
+ and never claims what the driver currently IS. Recovering armedness from history would be a guess in a
579
+ record's clothing.
580
+
581
+ **Deliberately not done, pending a maintainer decision (#349):** the underlying goal *service* has no
582
+ direct-human gate, so the plugin could arm a goal on the child unilaterally. Reaching a seam is not having
583
+ authority to use it; silently routing around a gate because the tool wrapper is the only thing enforcing it
584
+ is the kind of unexamined authority widening this whole release was a study in. If the answer is yes, it
585
+ becomes an explicit, documented, configurable step — not a side effect of the birth path.
586
+
379
587
  ## Storage
380
588
 
381
589
  Two stores because they have opposite requirements.
@@ -398,6 +606,23 @@ Layout:
398
606
  Add `<store-root>/` to `.gitignore` on first write and say so — polluting a user's tree silently is its
399
607
  own small bug.
400
608
 
609
+ **The chapter file name is unique by AUTHOR, not only by number (#337).** The directory above is keyed
610
+ by *chain root* — one dir per tree, deliberately, so a lineage shares its artifact store — while chapter
611
+ numbers restart at 1 for every `freshSession`. Parent and continuation child therefore both mint
612
+ `001-<slug>.md` into the same directory, and with a matching title the two paths are identical.
613
+ `writeArchive` used to overwrite unconditionally: the per-call `seenFile` set that "resolves title
614
+ collisions" cannot see a write made by another session, and the registry kept two records citing one
615
+ file — measured live, 40 paths claimed with different `sha256` and 393 `(tree dir, number)` pairs owned
616
+ by more than one session, where at most one citation of each pair can be true.
617
+
618
+ The rule now, in `writeArchive`: a chapter position is written only when it is free or already holds
619
+ **these exact bytes**. Identical bytes are a retry and keep the name, so the attempt-key idempotence
620
+ guarantee is untouched. Different bytes get a name carrying the authoring session's id; if even that is
621
+ held, the write **throws** rather than appending `-2`, `-3` until something is free — a record must not
622
+ cite a path nobody predicted, and a collision the plugin cannot resolve is precisely the fact to hand
623
+ the operator, with `/chapters-repair` named as the way out. Every resolution is reported as a warning,
624
+ never taken silently.
625
+
401
626
  **Registry: a DSH storage domain.** Ancestry, numbering, hashes, ranges, bullet lists. Sanctioned
402
627
  durability, survives restart, and gives the append-only counter a real allocation home instead of a
403
628
  directory scan racing a restart.
@@ -406,6 +631,72 @@ Trade-off to keep honest: a workspace-relative root makes a chain **cwd-scoped**
406
631
  means an absolute configured root, at which point `read` reachability must be re-verified — do not assume
407
632
  an absolute path inside one workspace stays reachable in another.
408
633
 
634
+ ### The registry must state which workspace its paths belong to (#348)
635
+
636
+ The two halves of that trade-off were mixed in a way that made the registry unable to address its own
637
+ archive: chapter and artifact paths are stored **relative to the session workspace**, but the storage
638
+ domain is **per home** — one `~/.dsh/storages/dsh_chapters.json` holding the sessions of every project on
639
+ the machine. A consumer holding only registry bytes therefore had no correct thing to resolve against.
640
+
641
+ Measured on this machine rather than reasoned about: resolving all 3,623 chapter entries against the
642
+ *current* workspace — the only choice available without an owning cwd — reports **1,431 (39%) as
643
+ "missing"**. Resolving each against its own session's workspace gives **3,620/3,623 present**. Nothing was
644
+ corrupt; the addressing was unattributable. Every path-iterating consumer inherits it: repair, restore,
645
+ `/chapters-remove`'s blob GC ("delete shared blobs only when no active record references them"), mirror
646
+ rehydration, and the knowledge sync's per-workspace projection.
647
+
648
+ The contract now:
649
+
650
+ - **A row carries the workspace its paths are relative to** (`SessionState.cwd`), stamped by
651
+ `appendChapters` — the one predicate every door's row write already passes through, which is why the
652
+ stamp lives there and not in each door. `commitChapters`, the save door, the continue/fork doors and the
653
+ compaction finalizer each supply the cwd they already resolved for `makeArchiveFs`; a door that does not
654
+ know one leaves the field absent rather than guessing, because a wrong workspace is worse than none.
655
+ - **Optional, so durable state keeps opening.** Rows written before this field must parse — the registry
656
+ has no shutdown migration hook — so `cwd` is `z.string().min(1).optional()`. Absent means "recovery for
657
+ this row stays the durable log", which is what *Recovery needs a surviving source* has always meant;
658
+ it must never mean "resolve against wherever we happen to be".
659
+ - **`''` is not a workspace.** The schema rejects it: an empty path resolves every relative chapter
660
+ against nothing and looks plausible while pointing nowhere.
661
+ - **`stampWorkspace` returns the same object** when the cwd is absent or unchanged, because
662
+ `store.mutate` treats object identity as "no change" — an unconditional stamp would turn every
663
+ idempotent retry into a write and a `rev` bump.
664
+
665
+ ### Artifact citations must be paths a reader can follow (#348, third defect)
666
+
667
+ The audit's third finding was that a citation prints `artifacts/8f/<sha>.txt`, which is relative to
668
+ `<storeRoot>/<rootSessionId>/` — neither workspace-relative nor absolute — so the `read` tool cannot open
669
+ it, while `chapters_artifact` can. Verified on this machine's real archive: the bytes sit at
670
+ `.dsh-chapters/17f7c1d6-…/artifacts/e3/e3b0c442….txt`, and every chapter said
671
+ `` `artifacts/e3/e3b0c442….txt` `` without ever naming the tool that could fetch it.
672
+
673
+ `artifactPath` is store-relative **on purpose** — it is what the writer returns and it stays stable across
674
+ workspaces. The defect was printing that internal form as if a reader could follow it. So `RenderConfig`
675
+ now carries an optional `citationBase`, computed by `citationBaseOf(storeRoot, rootSessionId, cwd)` —
676
+ workspace-relative when the store is inside the workspace, and **no base at all** when it is not:
677
+
678
+ - with a base, the line reads `` → `.dsh-chapters/<root>/artifacts/8f/<sha>.txt` ``, which `read` opens;
679
+ - without one, the line reads `` → `artifacts/8f/<sha>.txt (via chapters_artifact)` ``, naming the tool.
680
+
681
+ What is deliberately **not** allowed is a bare unopenable path with no hint. A model will retry a path
682
+ rather than question it, so an honest pointer to the retrieval tool beats a confident wrong location. Every
683
+ door supplies the base from values it already passes to `writeArchive` (save, continue/fork, and the
684
+ compaction finalizer, where the base is computed at finalize time because it depends on the session's
685
+ `rootSession`, not just the configured store root) — one convention across the archive moments rather than
686
+ a per-door dialect, which is the same mistake #69 settled for stored paths.
687
+
688
+ One existing row in `render.test.ts` asserted the bare store-relative fragment and had to change: it was
689
+ pinning the defect as the expected shape. It now requires the annotated fallback, and asserts the old form
690
+ is *absent* — so a regression to "confident unopenable path" fails loudly rather than matching the old
691
+ expectation.
692
+
693
+ Separately, the same audit found a second dialect in live rows: `#finalizeOne` passed an **absolute**
694
+ `resolveStoreRoot(...)` as `storeRoot` with no `cwd`, so `writeArchive` minted absolute stored paths
695
+ while the checkpoint TOC cited the workspace-relative form for the same file — the split #69 had already
696
+ settled ("relative is the right winner"). It now passes raw root + `cwd`, exactly as the save door does.
697
+ Consumers must still compare with `sameStoredPath`, never `===`, and a row that predates this still holds
698
+ the absolute form.
699
+
409
700
  ## Atomicity
410
701
 
411
702
  Writing files, allocating numbers, creating a session, and committing registry state is not
@@ -473,6 +764,19 @@ catch built a full diagnostic — and then the value was discarded. So the rule
473
764
  still wins; the literal `off` is honoured, because an operator must be able to silence it — but
474
765
  silence is now a choice, never a default. `diagnosticsLog` in the profile config sets the path
475
766
  declaratively; resolution order is env → config → `<store-root>/diagnostics.log`.
767
+ - **Every plane writes to it, not just the engine (#352).** The prompt plane was the exception: one
768
+ project's `diagnostics.log` held 21,138 `realm:*` lines, 4 `rules-section`, 4 `auto-save` and **zero**
769
+ prompt lines, so the door's own verdicts — did it see the turn boundary at all, did the model spec
770
+ reach the plane, why was this round skipped, was the registration refused — existed only in a terminal
771
+ and in a `ctx.logger` a rig boot throws away. That absence is why "suggestions are one turn behind"
772
+ (#340) and "the prompt door vanished with `subagentAutoSave`" (#341) each needed a full audit to find.
773
+ The runner's `log`/`warn`, the reload self-check, the boot reclaim and a refused door registration now
774
+ go through the sink under a `prompt:` tag — **keeping the stderr copy**, since the two channels serve
775
+ different readers and #61 added stderr precisely because the logger is not retained. High-frequency
776
+ per-turn witnesses stay on stderr only: the file carries decisions, not a firehose.
777
+ `tests/unit/prompt-diagnostics.test.ts` asserts both halves — the wiring calls the sink, *and* a
778
+ `prompt:`-tagged note really lands in the file — because a structural grep alone passes happily
779
+ against a no-op.
476
780
  - **Warnings reach humans, with a limit and a withheld count.** `(86 warning(s))` told a user nothing
477
781
  about 86 real findings; the ones that mattered named the husk and the unarchived 0–4082 hole. Doors
478
782
  print the first `warningsDisplayCap` texts and `…and M more`, through ONE formatter — a per-door copy
package/docs/backlog.md CHANGED
@@ -1,4 +1,39 @@
1
- # Open items — 2026-10-23 (host 0.2.0-rc.2)
1
+ # Open items — 2026-11-17 (host 0.2.0-rc.2)
2
+
3
+ - **0.2.34 follow-waves (2026-11-17 audit):** the composed checkpoint has never been OBSERVED on a live
4
+ host — the heavy leg's first sight, tracked as `docs/verify.md` C3, in the same family as #143's
5
+ convergence bound. The deprecated live reads (`eventAt`/`snapshotEvents`/`ownEvents` — the host says
6
+ "new calls are prohibited") are inventoried by `tests/unit/host-composer-shape.test.ts`; the migration
7
+ to `deriveMessages`/`requestHeader` (live) and `SessionQuery.readSession` (durable) is the first gate to
8
+ re-run before any host bump. #397 (`meta.parentSession` for continuation children) awaits a maintainer
9
+ decision on amending `docs/contract.md` § Lineage. #383 (#379) and #368 (#340) are held by maintainer
10
+ direction for **0.2.35**, together with the `prompt`-leg re-record.
11
+ - **#355 — the 2026-11-14 correctness audit: 24 issues filed for this audit (25 counting #386), 22 fixed across 24 PRs, released in 0.2.33.**
12
+ Every finding was reproduced against real bytes before it was changed, and the shape they share is the
13
+ release's subject: **a check that cannot fail**. Concretely: the preset-row health witness compared a
14
+ *number* (`fiberState`) to a *string* (`'active'`) and so read "all active" under every condition, while
15
+ two `chapters`-preset sessions were being compacted entirely by a foreign engine — 6 and 8 summaries with
16
+ provider `qwen-token-plan`, no TOC, no store, for a week (#339/#360). Chapter integrity agreed with a
17
+ truncated archive because the hash covered arrival's stub (#334, 932,462 chars; now 0). `# fail 0` printed
18
+ over **22 cancelled** tests because a door awaited a `setTimeout` handle it had just `.unref()`'d (#358).
19
+ A log line asserted "seven tools + three continuation doors" while the strict `commands` lookup returned
20
+ undefined and no door mounted (#353). The deterministic doors refused real sessions' **opening turns**
21
+ (2/3, 55/153, 32/308) and printed "Saved: 0 chapter(s) archived" (#344). A human message quoting
22
+ `<system-reminder>` lost 2,518 characters of its own instruction, labelled as host state (#347). 39% of
23
+ registry paths were unresolvable from registry bytes (#348), and artifact citations pointed where `read`
24
+ cannot go (#348c). Coverage of all 35 real event types became a table with reasons (#346) — including the
25
+ finding that the largest apparent gap, `agent/inbox/spliced` at ~2 MB, is **658/659 already-rendered
26
+ duplicate** and must never be rendered. The director took 9,482 ms per turn boundary (#350) and its
27
+ chapter block was uncapped (#379, held). The prompt plane wrote nothing durable, which is why two
28
+ user-reported symptoms needed a full audit to diagnose (#352). The config surface drifted in both
29
+ directions with no comparison between them (#354), and the anchor hashed comment prose, so a docs edit
30
+ demanded a re-anchor while a real prompt change could slip past (#362).
31
+ **Still open after this release:** #340 (suggestion freshness — built, held for the `prompt`-leg
32
+ re-record) · #379 (block cap — same wave) · #335 (arguments artifact-backed by default, or drop the docs
33
+ promise; maintainer's call) · #349 and #372 (both need a browser rig; left unbuilt rather than shipped
34
+ as unobserved wiring) · #331 (`enrich` annotate-title nondeterminism) · #336/#337 damage stays
35
+ **report-only** pending an operator decision under the deletion exception · the method note for the next
36
+ audit: `docs/project-state.md` § 2026-11-15.
2
37
 
3
38
  - **#330 — chapters tools in-realm + the model never measures its own context (2026-11-14, LANDED — released in 0.2.32).**
4
39
  Two shipped changes: the seven `chapters_*` tools and the three continuation doors mount through a
package/docs/contract.md CHANGED
@@ -186,7 +186,7 @@ const chaptersContinue = defineTool({
186
186
 
187
187
  Register **in-realm** (#330, 0.2.32): the seven chapters tools and the three continuation door commands
188
188
  (`/chapters-fork`, `/chapters-continue`, `/chapters-save`) mount through a `chapters-tools` row
189
- (`@fractalsynapse/dsh-chapters/tools`) inside the `preset-chapters` composition — the same seam the host's
189
+ (`@fractalsynapse/dsh-chapters/tools-row`) inside the `preset-chapters` composition — the same seam the host's
190
190
  own `dsh-tool-fs` and `dsh-tool-subagent` rows use — and the host plane registers none of them.
191
191
  `/chapters-repair` and `/chapters-restore` stay on the host plane: they are operator surfaces that must
192
192
  reach a broken chapters archive from any session, and human command text is not model-visible. The measured
@@ -236,7 +236,13 @@ callback exactly as session-controller's `composeAgent` does it
236
236
  ```ts
237
237
  ctx.agents.create({
238
238
  sessionId: newId,
239
- seed: [tocNoticeEvent], // exactly one event at seq 0 (invariant 2)
239
+ // #319 part 2: the TOC notice is AUTHORED as the child's first turn, never seeded. The seed
240
+ // carries synthetic STATE events only — today `plan/mode`, and only for an eligible
241
+ // continuation — so the normal seed is EMPTY. The kernel admits `seed[i]` only when
242
+ // `seed[i].seq === i` ("seed must be contiguous from 0", dsh-session lib/index.js:1330), so a
243
+ // lone state event is seq **0**, not seq 1. Invariant 2 constrains what the seed may contain
244
+ // (nothing from the parent's log), not how many events it holds.
245
+ seed: [...modeEvents], // contiguous from seq 0, or empty
240
246
  inheritedEventCount: 0,
241
247
  meta: { cwd: parentCwd, agentPreset: presetId },
242
248
  agentOptions: ctx.get('agentDefaultModel').currentSelection(),
@@ -325,6 +331,42 @@ The subclass seam, with everything measured by rounds 12-17 (sources: the instal
325
331
  - `@deepseek-ai/dsh-home-paths` exports `dshHomePath(...segments)` — the sanctioned
326
332
  way to reach `$DSH_HOME` from plugin code (host rc.2 line).
327
333
 
334
+ ### Preset row health: what the boot line can and cannot say (#339, documented late — #361 shipped it without this)
335
+
336
+ The plugin registers `preset-chapters` as a declaration row, then asks the **host's own roster** whether the
337
+ preset actually exists, and asks the **preset registry's composition inventory** how its mounted rows are
338
+ doing. Those are three different facts and the line states the third only when the first two allow it.
339
+
340
+ | line (exact) | meaning |
341
+ | --- | --- |
342
+ | `preset "chapters" registered as a declaration row` | the row was accepted by this host |
343
+ | `preset "chapters" is in the host roster — N mounted rows all active — chapter-form compaction and continuations will compose` | present, and every mounted row reports a usable state |
344
+ | `preset "chapters" is DECLARED BUT BROKEN — …` | the row resolves but a child will not activate; sessions choosing it will not compose |
345
+ | `UNHEALTHY — preset "chapters" is NOT in the host roster (roster: …)` | the composition is missing: existing sessions refuse to open with `agent-preset/not-found` while their logs stay intact |
346
+ | `could not verify the preset roster (…)` | the check itself failed; **treat chapter-form compaction as unconfirmed** — this is not a pass |
347
+
348
+ **`N mounted rows all active` is a claim, and until #361 it could not be false.** `unusableRows` compared
349
+ cordis' `fiberState` — a **number** — against the string `'active'`, so every row looked healthy under every
350
+ condition, including the week two `chapters` sessions were being compacted by a foreign engine. The number is
351
+ read as a number now. Treat the sentence as evidence: it can say `K of N rows NOT active (…)` when it means
352
+ it, and `rows not reported by this host` / `rows unreadable (…)` when the inventory is unavailable — which is
353
+ **not** the same as "all active", and is printed as its own phrase so a reader cannot conflate them.
354
+
355
+ Two consequences worth stating because they are the failure modes this line exists to prevent:
356
+
357
+ - **Presence is not activation, and activation is not usefulness.** A preset can be in the roster with every
358
+ row active and still be served by another engine's compaction; the ownership witness (#360,
359
+ `realm:engine:provenance` plus the `/chapters-status` provenance lines) is the check for *that*, and no
360
+ boot line substitutes for it.
361
+ - **A degraded check never prints the healthy wording.** Missing inventory, an exception, or a non-numeric
362
+ state each produce their own text. The reason is #339 exactly: a check that falls back to the success
363
+ string is worse than no check, because it is read and believed.
364
+
365
+ This section was written twelve rounds after #361 changed the behaviour, which is a missed
366
+ documentation-first step: the code change shipped with tests and no contract, and the only place the
367
+ behaviour was described was the install page's sample output — a sample that, at the time, was itself the
368
+ symptom. Recorded here so the omission is closed rather than inherited, and noted in #355's process findings.
369
+
328
370
  ## Lineage: Kernel Fields We Must Not Lean On
329
371
 
330
372
  `SessionHeader` (`packages/core/session/src/types.ts:93-122`) carries `version`, `id`, `createdAt`,
@@ -975,6 +1017,41 @@ The rule now: **arming prompt autorun displaces the goal's continuation, and the
975
1017
  - Re-arming the goal (`/goal resume`, or the bar's next human Run of a `GOAL:` step) is a human act, matching
976
1018
  the host's own rule that a model may not resume a paused goal (`GOAL_TOOL_RESUME_PAUSED`).
977
1019
 
1020
+ ### The director's input assembly is bounded work, and dedupes by path (#350)
1021
+
1022
+ The suggestion director is assembled at a turn boundary **on the host's event loop**, so its cost is not a
1023
+ detail: measured at real project scale (800 chapters / 36 MB) the pre-#350 code took **9,482 ms** for one
1024
+ input. Three causes were identified; two are fixed, and the third is named here so it is not mistaken for
1025
+ gone.
1026
+
1027
+ 1. **Duplicate lineage rows.** `promptChaptersForLineage` concatenated every ancestor row with no
1028
+ dedupe, while the registry holds rows carrying copies of their parent's entries — measured 391 identical
1029
+ number+path records, and a lineage call returning 507 rows for **56 distinct paths**. Each duplicate also
1030
+ re-read its file, so 419 bodies / ~19 MB were read synchronously per boundary, and up to 43% of the
1031
+ director's chapter block was the same text twice. Now deduped by **path**, the same key the TOC
1032
+ accumulation uses (`engine-core.ts:214`), with one body read per distinct file. Path and not number
1033
+ because numbers legitimately repeat across roots — a `number`-keyed dedupe would drop real chapters.
1034
+ 2. **A quadratic drop search.** Over budget, the oldest chapter is dropped until the input fits; the loop
1035
+ re-assembled the *entire* candidate string for every drop value. Since dropping only shortens the input,
1036
+ `assemble(d).length` is non-increasing and the first fit is findable in `O(log n)` probes — `firstFitDrop`.
1037
+ Measured after the change: **136 ms** at the same scale, a 70× reduction.
1038
+ Two things this must not paper over. (a) The binary search is exact **only** for a non-increasing length
1039
+ function; that precondition is asserted by a row that measures the real assembly across 120 chapters, and
1040
+ a runtime neighbour check falls back to the linear scan if it is ever violated — worst case is the old
1041
+ behaviour, never a wrong answer. (b) The remaining 136 ms is dominated by constructing tens of megabytes
1042
+ of string **once**, which the budget makes inevitable — see 3.
1043
+ 3. **Still open: the budget itself.** `resolvePromptLimits` derives `contextChars = floor(window ×
1044
+ promptContextRatio × 4)`, so a 1M-token route yields ~2,000,000 chars ≈ 500K tokens of auxiliary input
1045
+ per turn, and the chapter block dominates so thoroughly that the newest turn is about one character in
1046
+ two million — the third mechanism behind "suggestions are not about my last message" (#7). Bounding the
1047
+ chapter block as a *share* of the budget (with a floor share guaranteed to the newest turn) is the fix
1048
+ that removes the megabytes, not the milliseconds-squared, and it is a policy change to the director's
1049
+ input, so it is tracked separately rather than folded into a performance PR.
1050
+
1051
+ **Acceptance note, stated rather than quietly missed:** #350 asked for "< 50 ms at 800 chapters / 36 MB".
1052
+ These changes deliver 136 ms, not 50 — and the gap is cause 3, not the search. Quoting the target as met
1053
+ would make the number mean nothing.
1054
+
978
1055
  ## Seeded-continuation load deadlock — the fold rule vs the header recorder (measured 2026-11-05, #314)
979
1056
 
980
1057
  The native-V4 relationships validator (`@deepseek-ai/dsh-session-format-v3-to-v4`, entered as