@fractalsynapse/dsh-chapters 0.2.31 → 0.2.32

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.
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The `chapters-tools` realm row (#330) — the seven `chapters_*` tools and the three
3
+ * continuation door commands, mounted INSIDE the preset composition (the `preset-chapters`
4
+ * row's `plugins:` list in `cordis.patch.yml`), the same seam the host's own `dsh-tool-fs`
5
+ * and `dsh-tool-subagent` rows use.
6
+ *
7
+ * WHY A ROW AND NOT THE HOST PLANE
8
+ * --------------------------------
9
+ * A tool registered on the host plane rides EVERY session's request, whatever preset
10
+ * composes it — measured in the #319 e2e logs, where `standard`-preset headers carried the
11
+ * whole `chapters_*` schema set while the chapters persona suffix was absent. A tool
12
+ * description is prompt text: shipping the archive vocabulary to agents that never chose
13
+ * the archive is the leak #330 closes (AGENTS invariant 3, extended). Rows mounted from a
14
+ * preset composition are scoped to sessions composing that preset — that is what the
15
+ * standard/chapters tool-set differences (e.g. `tool-ralph`) have always proven.
16
+ *
17
+ * WHAT STAYS HOST-PLANE
18
+ * ---------------------
19
+ * The declaration row (`src/preset.ts`), roster verification, storage, the engine realm
20
+ * row, the subagent-settlement listener (header-gated), the prompt bar, and the operator
21
+ * commands — `/chapters-status`, `/chapters-link`, `/chapters-enrich`, `/chapters-remove`,
22
+ * `/chapters-prompt`, and the repair/restore doors registered through
23
+ * `registerChaptersRepairRestore` (a broken chapters child may not compose its realm at
24
+ * all, and `/chapters-restore` (#319) is the documented way in). Command text is not a
25
+ * model surface; tools are.
26
+ *
27
+ * The store is ACQUIRED, never bare-opened (engine.ts's rule: the host plane may own the
28
+ * reservation); the domain closes at facility unmount, not at this fiber's — same shape as
29
+ * `apply()` in src/index.ts (r35). Services not named in an `isolate:` block resolve
30
+ * through the host scope, which is how the realm rows see `tools`, `storageDomain`,
31
+ * `agents` and `sessionProjections` (the host's own realm tool rows are the precedent).
32
+ *
33
+ * @module dsh-chapters/src/tools-row
34
+ */
35
+ import { Service } from '@deepseek-ai/cordis';
36
+ import z from '@deepseek-ai/schemastery';
37
+ /** One mounted row of a preset composition reaches these host services; declare only what
38
+ * is used (docs/contract.md § Services). `commands` comes through `ctx.get` optionally,
39
+ * exactly as the host plane has always done it. */
40
+ interface RowCtx {
41
+ agents: {
42
+ create(opts: Record<string, unknown>): Promise<{
43
+ agent: unknown;
44
+ dispose?: () => Promise<void> | void;
45
+ }>;
46
+ };
47
+ tools: {
48
+ register(def: unknown): () => void;
49
+ };
50
+ llm?: {
51
+ resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<{
52
+ context?: {
53
+ contextWindow?: number;
54
+ };
55
+ } | undefined>;
56
+ };
57
+ sessionProjections?: {
58
+ stateOf(session: unknown, key: string): unknown;
59
+ };
60
+ get?(name: string): unknown;
61
+ logger?: {
62
+ info?: (m: string) => void;
63
+ warn?: (m: string) => void;
64
+ };
65
+ }
66
+ /** The row's config — the doors' and tools' tunables, declared on this plane (#330).
67
+ * Names and defaults mirror the host plane's `Config` (index.ts): the two planes carry no
68
+ * cross-channel, so a profile that retunes a shared key sets it in both places, and
69
+ * leaving either unset keeps the documented default. `searchMaxTokens` is the realm-side
70
+ * name of the host's `searchDefaultMaxTokens`. */
71
+ export interface ToolsRowConfig {
72
+ artifactStoreRoot: string;
73
+ knowledgeRemote: string;
74
+ /** The host plane declares the union on the interface and validates the scheme at
75
+ * link time (`providerKindFor`); the same shape here, so one `SchedulerConfig`
76
+ * contract covers both planes. */
77
+ knowledgeProvider: 'auto' | 'git' | 'treedx';
78
+ projectKeyOverride: string;
79
+ syncDebounceMs: number;
80
+ vocabApply: boolean;
81
+ vocabCoMin: number;
82
+ vocabOverlapMin: number;
83
+ harnessId: string;
84
+ chapterTokenTarget: number;
85
+ chapterLimit: number;
86
+ chapterOversizeFactor: number;
87
+ mergeThreshold: number;
88
+ toolResultDeferFloorTokens: number;
89
+ continuationBudgetRatio: number;
90
+ fallbackPreset: string;
91
+ warningsDisplayCap: number;
92
+ segmentCandidateCapTokens: number;
93
+ repairReportMaxLines: number;
94
+ planInlineChars: number;
95
+ callArgArtifactTokens: number;
96
+ plansInNotice: boolean;
97
+ retrievalHints: boolean;
98
+ planSeedMode: boolean;
99
+ searchMaxTokens: number;
100
+ coreRulesBudgetTokens: number;
101
+ rulesCoreBonus: number;
102
+ projectRulesDisplayCap: number;
103
+ sessionRulesDisplayCap: number;
104
+ rulesRelevance: boolean;
105
+ }
106
+ export default class ChaptersToolsRow {
107
+ static inject: readonly ["agents", "tools", "llm", "storageDomain", "sessionProjections"];
108
+ static Config: z<Schemastery.ObjectS<{
109
+ artifactStoreRoot: z<string, string>;
110
+ knowledgeRemote: z<string, string>;
111
+ knowledgeProvider: z<string, string>;
112
+ projectKeyOverride: z<string, string>;
113
+ syncDebounceMs: z<number, number>;
114
+ vocabApply: z<boolean, boolean>;
115
+ vocabCoMin: z<number, number>;
116
+ vocabOverlapMin: z<number, number>;
117
+ harnessId: z<string, string>;
118
+ chapterTokenTarget: z<number, number>;
119
+ chapterLimit: z<number, number>;
120
+ chapterOversizeFactor: z<number, number>;
121
+ mergeThreshold: z<number, number>;
122
+ toolResultDeferFloorTokens: z<number, number>;
123
+ continuationBudgetRatio: z<number, number>;
124
+ fallbackPreset: z<string, string>;
125
+ warningsDisplayCap: z<number, number>;
126
+ segmentCandidateCapTokens: z<number, number>;
127
+ repairReportMaxLines: z<number, number>;
128
+ planInlineChars: z<number, number>;
129
+ callArgArtifactTokens: z<number, number>;
130
+ plansInNotice: z<boolean, boolean>;
131
+ retrievalHints: z<boolean, boolean>;
132
+ planSeedMode: z<boolean, boolean>;
133
+ searchMaxTokens: z<number, number>;
134
+ coreRulesBudgetTokens: z<number, number>;
135
+ rulesCoreBonus: z<number, number>;
136
+ projectRulesDisplayCap: z<number, number>;
137
+ sessionRulesDisplayCap: z<number, number>;
138
+ rulesRelevance: z<boolean, boolean>;
139
+ }>, Schemastery.ObjectT<{
140
+ artifactStoreRoot: z<string, string>;
141
+ knowledgeRemote: z<string, string>;
142
+ knowledgeProvider: z<string, string>;
143
+ projectKeyOverride: z<string, string>;
144
+ syncDebounceMs: z<number, number>;
145
+ vocabApply: z<boolean, boolean>;
146
+ vocabCoMin: z<number, number>;
147
+ vocabOverlapMin: z<number, number>;
148
+ harnessId: z<string, string>;
149
+ chapterTokenTarget: z<number, number>;
150
+ chapterLimit: z<number, number>;
151
+ chapterOversizeFactor: z<number, number>;
152
+ mergeThreshold: z<number, number>;
153
+ toolResultDeferFloorTokens: z<number, number>;
154
+ continuationBudgetRatio: z<number, number>;
155
+ fallbackPreset: z<string, string>;
156
+ warningsDisplayCap: z<number, number>;
157
+ segmentCandidateCapTokens: z<number, number>;
158
+ repairReportMaxLines: z<number, number>;
159
+ planInlineChars: z<number, number>;
160
+ callArgArtifactTokens: z<number, number>;
161
+ plansInNotice: z<boolean, boolean>;
162
+ retrievalHints: z<boolean, boolean>;
163
+ planSeedMode: z<boolean, boolean>;
164
+ searchMaxTokens: z<number, number>;
165
+ coreRulesBudgetTokens: z<number, number>;
166
+ rulesCoreBonus: z<number, number>;
167
+ projectRulesDisplayCap: z<number, number>;
168
+ sessionRulesDisplayCap: z<number, number>;
169
+ rulesRelevance: z<boolean, boolean>;
170
+ }>>;
171
+ ctx: RowCtx;
172
+ config: ToolsRowConfig;
173
+ constructor(ctx: RowCtx, config: ToolsRowConfig);
174
+ /** Register, then hand Cordis the disposer — the tool/command registrations live and
175
+ * die with the mount (the preset row yields its registry disposer for the same
176
+ * reason; an `ctx.effect` on a fiber that finishes early would unregister the tools
177
+ * the instant they appeared). */
178
+ [Service.init](): AsyncGenerator<() => void, void>;
179
+ }
180
+ export {};
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The `chapters-tools` realm row (#330) — the seven `chapters_*` tools and the three
3
+ * continuation door commands, mounted INSIDE the preset composition (the `preset-chapters`
4
+ * row's `plugins:` list in `cordis.patch.yml`), the same seam the host's own `dsh-tool-fs`
5
+ * and `dsh-tool-subagent` rows use.
6
+ *
7
+ * WHY A ROW AND NOT THE HOST PLANE
8
+ * --------------------------------
9
+ * A tool registered on the host plane rides EVERY session's request, whatever preset
10
+ * composes it — measured in the #319 e2e logs, where `standard`-preset headers carried the
11
+ * whole `chapters_*` schema set while the chapters persona suffix was absent. A tool
12
+ * description is prompt text: shipping the archive vocabulary to agents that never chose
13
+ * the archive is the leak #330 closes (AGENTS invariant 3, extended). Rows mounted from a
14
+ * preset composition are scoped to sessions composing that preset — that is what the
15
+ * standard/chapters tool-set differences (e.g. `tool-ralph`) have always proven.
16
+ *
17
+ * WHAT STAYS HOST-PLANE
18
+ * ---------------------
19
+ * The declaration row (`src/preset.ts`), roster verification, storage, the engine realm
20
+ * row, the subagent-settlement listener (header-gated), the prompt bar, and the operator
21
+ * commands — `/chapters-status`, `/chapters-link`, `/chapters-enrich`, `/chapters-remove`,
22
+ * `/chapters-prompt`, and the repair/restore doors registered through
23
+ * `registerChaptersRepairRestore` (a broken chapters child may not compose its realm at
24
+ * all, and `/chapters-restore` (#319) is the documented way in). Command text is not a
25
+ * model surface; tools are.
26
+ *
27
+ * The store is ACQUIRED, never bare-opened (engine.ts's rule: the host plane may own the
28
+ * reservation); the domain closes at facility unmount, not at this fiber's — same shape as
29
+ * `apply()` in src/index.ts (r35). Services not named in an `isolate:` block resolve
30
+ * through the host scope, which is how the realm rows see `tools`, `storageDomain`,
31
+ * `agents` and `sessionProjections` (the host's own realm tool rows are the precedent).
32
+ *
33
+ * @module dsh-chapters/src/tools-row
34
+ */
35
+ import { Service } from '@deepseek-ai/cordis';
36
+ import z from '@deepseek-ai/schemastery';
37
+ import { hostname } from 'node:os';
38
+ import { acquireChapterStore } from "./store.js";
39
+ import { createScheduler } from "./index.js";
40
+ import { registerChaptersTools } from "./tools.js";
41
+ export default class ChaptersToolsRow {
42
+ static inject = ['agents', 'tools', 'llm', 'storageDomain', 'sessionProjections'];
43
+ static Config = z.object({
44
+ artifactStoreRoot: z.string().default('.dsh-chapters'),
45
+ knowledgeRemote: z.string().default(''),
46
+ knowledgeProvider: z.string().default('auto'),
47
+ projectKeyOverride: z.string().default(''),
48
+ syncDebounceMs: z.number().default(30000),
49
+ vocabApply: z.boolean().default(false),
50
+ vocabCoMin: z.number().default(3),
51
+ vocabOverlapMin: z.number().default(0.5),
52
+ harnessId: z.string().default(hostname()),
53
+ chapterTokenTarget: z.number().default(8000),
54
+ chapterLimit: z.number().default(8000),
55
+ chapterOversizeFactor: z.number().default(2),
56
+ mergeThreshold: z.number().default(0.3),
57
+ toolResultDeferFloorTokens: z.number().default(200),
58
+ continuationBudgetRatio: z.number().default(0.25),
59
+ fallbackPreset: z.string().default('chapters'),
60
+ warningsDisplayCap: z.number().default(6),
61
+ segmentCandidateCapTokens: z.number().default(4000),
62
+ repairReportMaxLines: z.number().default(60),
63
+ planInlineChars: z.number().default(900),
64
+ callArgArtifactTokens: z.number().default(0),
65
+ plansInNotice: z.boolean().default(true),
66
+ retrievalHints: z.boolean().default(true),
67
+ planSeedMode: z.boolean().default(true),
68
+ searchMaxTokens: z.number().default(400),
69
+ coreRulesBudgetTokens: z.number().default(1200),
70
+ rulesCoreBonus: z.number().default(0.15),
71
+ projectRulesDisplayCap: z.number().default(12),
72
+ sessionRulesDisplayCap: z.number().default(12),
73
+ rulesRelevance: z.boolean().default(true),
74
+ });
75
+ ctx;
76
+ config;
77
+ constructor(ctx, config) {
78
+ this.ctx = ctx;
79
+ this.config = config;
80
+ }
81
+ /** Register, then hand Cordis the disposer — the tool/command registrations live and
82
+ * die with the mount (the preset row yields its registry disposer for the same
83
+ * reason; an `ctx.effect` on a fiber that finishes early would unregister the tools
84
+ * the instant they appeared). */
85
+ async *[Service.init]() {
86
+ const sd = this.ctx.get?.('storageDomain');
87
+ if (sd === undefined) {
88
+ // A realm without the storage facility cannot build a registry store. Say it
89
+ // LOUDLY and mount nothing rather than half-registering tool definitions whose
90
+ // every call would throw (a tool nobody can call is worse than an absent one).
91
+ this.ctx.logger?.warn?.('dsh-chapters: chapters-tools row — storageDomain service absent, tools NOT mounted');
92
+ return;
93
+ }
94
+ const handle = await acquireChapterStore(sd);
95
+ const { store, domain } = handle;
96
+ // The realm's own scheduler (§5): the same factory the host plane uses (one
97
+ // scheduler shape, two planes), and the same discipline as the engine row's
98
+ // `#scheduler()` — the file lock and debounce keep every instance honest.
99
+ const scheduler = createScheduler(store, domain, this.config, undefined, undefined, (m) => this.ctx.logger?.warn?.(m));
100
+ const toolsConfig = {
101
+ ...this.config,
102
+ scheduler,
103
+ // The caller's routed model on every tool use, persisted through the SHARED
104
+ // settings table — the realm's equivalent of the host plane's `noteRoute`
105
+ // (#330 moved the doors in-realm; the manual `/chapters-enrich` resolver on the
106
+ // host already falls back to `enrichment.route`, so the note still lands).
107
+ noteRoute: (r) => {
108
+ void store.putSetting('enrichment.route', `${r.provider}/${r.model}`).catch(() => undefined);
109
+ },
110
+ };
111
+ const dispose = registerChaptersTools(this.ctx, store, toolsConfig);
112
+ this.ctx.logger?.info?.('dsh-chapters: chapters-tools row mounted — seven tools + three continuation doors, this realm only (#330)');
113
+ // The store handle is NOT closed here: the storage facility owns domain teardown
114
+ // (r35 — a close effect on this fiber closed the domain under later commands).
115
+ yield dispose;
116
+ }
117
+ }
118
+ //# sourceMappingURL=tools-row.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-row.js","sourceRoot":"","sources":["../src/tools-row.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAC7C,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAC5C,OAAO,EAAE,qBAAqB,EAAoB,MAAM,YAAY,CA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F,CAAA;QACD,MAAM,OAAO,GAAG,qBAAqB,CAAC,IAAI,CAAC,GAAY,EAAE,KAAK,EAAE,WAAW,CAAC,CAAA;QAC5E,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,2GAA2G,CAAC,CAAA;QACpI,iFAAiF;QACjF,+EAA+E;QAC/E,MAAM,OAAO,CAAA;IACf,CAAC"}
package/lib/tools.d.ts CHANGED
@@ -111,4 +111,21 @@ export declare function buildChaptersTools(ctx: ToolsCtx, store: RegistryStore,
111
111
  repairCommand: HostCommand;
112
112
  restoreCommand: HostCommand;
113
113
  };
114
+ /**
115
+ * The realm-side registrar (#330): the seven `chapters_*` tools and the three
116
+ * continuation door commands mount on the plane that requested them — ONLY the
117
+ * `chapters-tools` row inside the preset composition calls this, from
118
+ * `src/tools-row.ts`. The host plane never calls it: a tool registered on the host
119
+ * plane rides EVERY session's request whatever preset composes (measured in the #319
120
+ * e2e logs as `chapters_*` schemas inside `standard`-preset headers), which is the leak
121
+ * #330 exists to close.
122
+ */
114
123
  export declare function registerChaptersTools(ctx: ToolsCtx, store: RegistryStore, config: ToolsConfig): () => void;
124
+ /**
125
+ * The host-side registrar (#330): `/chapters-repair` and `/chapters-restore` stay
126
+ * operator-side so a broken chapters archive is fixable FROM ANY SESSION — a poisoned
127
+ * chapters child may not compose its realm at all, and the restore door (#319) is the
128
+ * documented way in. Command text is not a model prompt surface; these registrations
129
+ * are human reach, not agent attention, which is the line #330 draws.
130
+ */
131
+ export declare function registerChaptersRepairRestore(ctx: ToolsCtx, store: RegistryStore, config: ToolsConfig): () => void;
package/lib/tools.js CHANGED
@@ -14,7 +14,7 @@ import { REPAIR_CLASS_ALIASES, resolveRepairClasses } from "./repair.js";
14
14
  import { readDurableSession } from "./auto-save.js";
15
15
  import { makeRestoreCommand } from "./restore-command.js";
16
16
  import * as path from 'node:path';
17
- import { candidateTotals, estimateTokens, toolResultCandidates } from "./render.js";
17
+ import { candidateTotals, defersAtArchive, toolResultCandidates } from "./render.js";
18
18
  import { detectPlans } from "./plans.js";
19
19
  import { makeHeaderParentReader, queryTopics, renderRulesBlock } from "./session-rules.js";
20
20
  import { rulesCommand } from "./rules-commands.js";
@@ -35,6 +35,15 @@ const jsonOutput = (render) => ({
35
35
  render: (_args, value) => [{ type: 'text', text: render(value) }],
36
36
  });
37
37
  const CALLER_MISSING = { ok: false, reason: 'no calling agent: this tool runs only inside an agent session' };
38
+ /**
39
+ * #330 — the shape of a budget receipt the MODEL may see: the size of the NOTICE the
40
+ * plugin measured against its allowance, both properties of an artifact being written.
41
+ * The admission inputs (`windowTokens`, `headerBoundTokens`) measure the live session —
42
+ * a gauge the model cannot read for itself and would only learn to guess with — so they
43
+ * are withheld here deliberately. The refusal REASON carries the same discipline (see
44
+ * continue-core); human door text and the logs may carry the full probe.
45
+ */
46
+ const noticeReceipt = (b) => ({ usedTokens: b.usedTokens, allowanceTokens: b.allowanceTokens });
38
47
  function callerOf(exec) {
39
48
  const agent = exec.agent;
40
49
  return agent ?? CALLER_MISSING;
@@ -245,9 +254,10 @@ export function buildChaptersTools(ctx, store, config) {
245
254
  // ---------------------------------------------------------------- segment
246
255
  const chaptersSegment = defineTool({
247
256
  name: 'chapters_segment',
248
- description: 'Facts for planning a chapter archive of THIS session: the completed-turn archive ceiling, '
249
- + 'every tool result with its real size, and the chapters already in the registry. '
250
- + 'Returns ranges for you to propose in chapters_continue — you never write chapter text; the plugin renders it from the log.',
257
+ description: 'Facts for planning a chapter archive of THIS session: the completed-turn ceiling, which tool '
258
+ + 'results will be cited as file references versus repeated inline, and the chapters already in '
259
+ + 'the registry. Returns ranges for you to propose in chapters_continue — you never write chapter '
260
+ + 'text; the plugin renders it from the log.',
251
261
  parameters: {},
252
262
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
253
263
  async execute(_args, exec) {
@@ -272,8 +282,6 @@ export function buildChaptersTools(ctx, store, config) {
272
282
  title: p.title,
273
283
  status: p.status,
274
284
  resultSeq: p.resultSeq,
275
- bytes: p.bytes,
276
- estimatedTokens: estimateTokens(p.text),
277
285
  outline: p.outline,
278
286
  verdict: p.verdict === null ? null : p.verdict.slice(0, 200),
279
287
  });
@@ -295,10 +303,11 @@ export function buildChaptersTools(ctx, store, config) {
295
303
  : { planHint: 'a submitted plan is a topic boundary: the chapter that carries it ENDS there, and its title becomes the chapter title' }),
296
304
  // fresh literals, not the ToolResultCandidate interface: anonymous
297
305
  // object types carry the implicit index signature JsonValue needs.
298
- // #61: the candidate list is CAPPED and says so. The field version returned 49,932 characters
299
- // while also reporting `Omitted 275266 bytes` — ~81K est tokens into a 32K-class window, asking
300
- // the model to keep/drop-judge a list it had not received. Ranking is by size descending, so the
301
- // cap removes the SMALL entries and the big ones a real decision turns on stay visible.
306
+ // #61: the candidate list is CAPPED and says so — but #330 took the SIZE
307
+ // NUMBERS out of it: per-result bytes/token estimates read to the model as a
308
+ // fuel gauge, and the cap line's "KB withheld" was the same quantity the
309
+ // caller cannot verify. The list says what is on it and what the archive will
310
+ // reference by default; the plugin does the measuring.
302
311
  ...(() => {
303
312
  const range = { title: '', summary: '', startSeq: 0, endSeq: ceiling };
304
313
  const cap = config.segmentCandidateCapTokens ?? 4000;
@@ -307,17 +316,18 @@ export function buildChaptersTools(ctx, store, config) {
307
316
  : toolResultCandidates(below, range);
308
317
  const totals = candidateTotals(below, range);
309
318
  const withheld = Math.max(0, totals.count - kept.length);
310
- const withheldBytes = Math.max(0, totals.bytes - kept.reduce((m, c) => m + c.bytes, 0));
319
+ const floor = config.toolResultDeferFloorTokens ?? 200;
311
320
  return {
312
- toolResults: kept.map((c) => ({ seq: c.seq, toolName: c.toolName, bytes: c.bytes, estimatedTokens: c.estimatedTokens, excerpt: c.excerpt })),
313
- toolResultsReport: `showing ${kept.length} of ${totals.count} candidates by size, ${(withheldBytes / 1024).toFixed(0)} KB withheld`
314
- + (cap > 0 ? ` (segmentCandidateCapTokens=${cap})` : ' (uncapped)'),
321
+ // `deferred` is the SAME decision the renderer makes (one predicate,
322
+ // defersAtArchive): this result's full text will be cited as a file path
323
+ // in its chapter rather than repeated. An archive fact, not a session one.
324
+ toolResults: kept.map((c) => ({ seq: c.seq, toolName: c.toolName, excerpt: c.excerpt, deferred: defersAtArchive(c.estimatedTokens, floor) })),
325
+ toolResultsReport: `listing ${kept.length} of ${totals.count} tool results${withheld > 0 ? ` (${String(withheld)} smaller ones omitted by the cap${cap > 0 ? `, segmentCandidateCapTokens=${cap}` : ''})` : ''}`,
315
326
  };
316
327
  })(),
317
328
  existingChapters: callerState.chapters.map((c) => ({
318
329
  number: c.number, path: c.path, title: c.title, startSeq: c.startSeq, endSeq: c.endSeq,
319
330
  })),
320
- budgetHint: { continuationBudgetRatio: config.continuationBudgetRatio, chapterTokenTarget: config.chapterTokenTarget },
321
331
  };
322
332
  },
323
333
  });
@@ -326,12 +336,12 @@ export function buildChaptersTools(ctx, store, config) {
326
336
  name: 'chapters_continue',
327
337
  description: 'Archive this conversation as verbatim Markdown chapters and open a NEW session that starts from their '
328
338
  + 'table of contents plus your handoff note. Supply event ranges (startSeq/endSeq) — never chapter text; '
329
- + 'the plugin renders bodies from the session log. This session is left untouched; the child gets its own '
330
- + 'cache and can reload any chapter with read. Oversized tool results defer to reference files by default; '
331
- + 'toolResultOverrides marks the exceptions you want kept inline (it still writes the artifact).',
339
+ + 'the plugin renders bodies from the session log. This session is left untouched; the child can reload any '
340
+ + 'chapter with read. Large tool results are cited as file references in the chapter by default; '
341
+ + 'toolResultOverrides names the few you want repeated inline instead (the file is still written).',
332
342
  parameters: {
333
343
  title: { type: 'string', required: true, description: 'Name for the continued session.' },
334
- handoffNote: { type: 'string', required: true, description: 'State of play for the child: what was in progress, decisions held, the next step. Budget-checked as part of the notice, never silently truncated.' },
344
+ handoffNote: { type: 'string', required: true, description: 'State of play for the child: what was in progress, decisions held, the next step. It reaches the child whole, never clipped.' },
335
345
  chapters: {
336
346
  type: 'array',
337
347
  required: true,
@@ -355,7 +365,7 @@ export function buildChaptersTools(ctx, store, config) {
355
365
  additionalProperties: false,
356
366
  properties: {
357
367
  seq: { type: 'integer', required: true, description: 'The tool result event seq (from chapters_segment toolResults).' },
358
- inline: { type: 'boolean', required: true, description: 'Keep inline (true) or defer (false), overriding the size default for this one result.' },
368
+ inline: { type: 'boolean', required: true, description: 'Repeat this one result inline (true) or as a file reference (false), overriding the archive default for it.' },
359
369
  },
360
370
  },
361
371
  },
@@ -395,7 +405,7 @@ export function buildChaptersTools(ctx, store, config) {
395
405
  ...(result.presetUsed !== undefined ? { presetUsed: result.presetUsed } : {}),
396
406
  ...(result.chapters !== undefined ? { chapters: result.chapters } : {}),
397
407
  ...(result.warnings !== undefined && result.warnings.length > 0 ? { warnings: result.warnings } : {}),
398
- ...(result.budget !== undefined ? { budget: result.budget } : {}),
408
+ ...(result.budget !== undefined ? { budget: noticeReceipt(result.budget) } : {}),
399
409
  };
400
410
  }
401
411
  catch (error) {
@@ -404,7 +414,7 @@ export function buildChaptersTools(ctx, store, config) {
404
414
  return {
405
415
  ok: false,
406
416
  reason: refusal.reason ?? 'refused',
407
- ...(refusal.budget !== undefined ? { budget: refusal.budget } : {}),
417
+ ...(refusal.budget !== undefined ? { budget: noticeReceipt(refusal.budget) } : {}),
408
418
  ...(refusal.warnings !== undefined && refusal.warnings.length > 0 ? { warnings: refusal.warnings } : {}),
409
419
  };
410
420
  }
@@ -416,11 +426,11 @@ export function buildChaptersTools(ctx, store, config) {
416
426
  const chaptersFork = defineTool({
417
427
  name: 'chapters_fork',
418
428
  description: 'Open a SIBLING session citing the same chapter archive this one already has — nothing new is '
419
- + 'archived, no files written, no numbers spent. Use for trying a genuinely different approach '
420
- + 'while the current session keeps working. Your handoff note says what the sibling should do.',
429
+ + 'archived, no files written, no chapter numbers consumed. Use for trying a genuinely different '
430
+ + 'approach while the current session keeps working. Your handoff note says what the sibling should do.',
421
431
  parameters: {
422
432
  title: { type: 'string', required: true, description: 'Name for the forked session.' },
423
- handoffNote: { type: 'string', required: true, description: 'What the sibling is for — its whole context is the archive TOC plus this note.' },
433
+ handoffNote: { type: 'string', required: true, description: 'What the sibling is for — it starts from the archive TOC plus this note.' },
424
434
  },
425
435
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
426
436
  async execute(args, exec) {
@@ -454,13 +464,13 @@ export function buildChaptersTools(ctx, store, config) {
454
464
  ok: true,
455
465
  ...(result.childSessionId !== undefined ? { childSessionId: result.childSessionId } : {}),
456
466
  ...(result.presetUsed !== undefined ? { presetUsed: result.presetUsed } : {}),
457
- ...(result.budget !== undefined ? { budget: result.budget } : {}),
467
+ ...(result.budget !== undefined ? { budget: noticeReceipt(result.budget) } : {}),
458
468
  };
459
469
  }
460
470
  catch (error) {
461
471
  const refusal = refusalResult(error);
462
472
  if (refusal !== null) {
463
- return { ok: false, reason: refusal.reason ?? 'refused', ...(refusal.budget !== undefined ? { budget: refusal.budget } : {}) };
473
+ return { ok: false, reason: refusal.reason ?? 'refused', ...(refusal.budget !== undefined ? { budget: noticeReceipt(refusal.budget) } : {}) };
464
474
  }
465
475
  return { ok: false, reason: `chapters_fork failed: ${error?.stack ?? String(error)}`.slice(0, 800) };
466
476
  }
@@ -756,7 +766,7 @@ export function buildChaptersTools(ctx, store, config) {
756
766
  + 'Pass a topic or keyword query; raise maxTokens to see more of the ranked list. Results are file paths readable with the read tool.',
757
767
  parameters: {
758
768
  query: { type: 'string', required: true, description: 'Topic or keyword query.' },
759
- maxTokens: { type: 'number', description: 'Token budget for the result list (default 400; raise to page deeper).' },
769
+ maxTokens: { type: 'number', description: 'Cap on the returned list length (default 400; raise to page deeper).' },
760
770
  },
761
771
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
762
772
  async execute(args, exec) {
@@ -834,17 +844,17 @@ export function buildChaptersTools(ctx, store, config) {
834
844
  });
835
845
  const chaptersArtifact = defineTool({
836
846
  name: 'chapters_artifact',
837
- description: 'Query a stored artifact (a tool result too large to sit in context — deferred blobs and arrival-stored documents alike) '
847
+ description: 'Query a stored artifact (a large tool result or arrival-stored document the archive keeps as a file) '
838
848
  + 'WITHOUT loading it whole: action "toc" = heading map with line numbers (structured/markdown files), '
839
849
  + '"search" = query (regex or phrase) → small matched blocks with line numbers, "read" = exact line range. '
840
- + 'path accepts the artifacts/… path or the bare sha256 from the stub line.',
850
+ + 'path accepts the artifacts/… path or the bare sha256 from the reference line.',
841
851
  parameters: {
842
852
  path: { type: 'string', required: true, description: 'Artifact reference from the stub: artifacts/<xx>/<sha>.txt path or the 64-hex sha.' },
843
853
  action: { type: 'string', required: true, description: 'One of: toc | search | read.' },
844
854
  query: { type: 'string', description: 'Required for search: regex or literal phrase (case-insensitive).' },
845
855
  offset: { type: 'number', description: 'read: first line (1-based). Default 1.' },
846
856
  limit: { type: 'number', description: 'read: line count (hard cap 400).' },
847
- maxTokens: { type: 'number', description: 'search: budget for returned blocks (default 400).' },
857
+ maxTokens: { type: 'number', description: 'search: how many matched blocks to return (default 400).' },
848
858
  },
849
859
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
850
860
  async execute(args, exec) {
@@ -928,12 +938,12 @@ export function buildChaptersTools(ctx, store, config) {
928
938
  const chaptersRules = defineTool({
929
939
  name: 'chapters_rules',
930
940
  description: 'Assemble the rules that govern a task: the approved project tier plus this session tree\u2019s '
931
- + 'captured session rules, verbatim, within budget. Run it BEFORE starting a task. The answer '
941
+ + 'captured session rules, verbatim. Run it BEFORE starting a task. The answer '
932
942
  + 'names what it withheld, so "you are seeing all of them" is a fact rather than a guess.',
933
943
  parameters: {
934
944
  query: { type: 'string', required: true, description: 'What the session is about to do, in a sentence or two \u2014 it selects relevance.' },
935
945
  scope: { type: 'string', description: "'all' (default) or 'project' to see only the shared tier a branch would inherit." },
936
- maxTokens: { type: 'number', description: 'Token ceiling for this answer (defaults to coreRulesBudgetTokens).' },
946
+ maxTokens: { type: 'number', description: 'Cap on the returned rules text (default: the configured core-rules budget).' },
937
947
  },
938
948
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
939
949
  async execute(args, exec) {
@@ -1122,6 +1132,15 @@ export function buildChaptersTools(ctx, store, config) {
1122
1132
  const restoreCommand = makeRestoreCommand({ store, config, portsFor, runRepair });
1123
1133
  return { segment: chaptersSegment, chaptersContinue, chaptersFork, chaptersSearch, chaptersArtifact, chaptersRulePropose, chaptersRules, forkCommand, continueCommand, saveCommand, repairCommand, restoreCommand };
1124
1134
  }
1135
+ /**
1136
+ * The realm-side registrar (#330): the seven `chapters_*` tools and the three
1137
+ * continuation door commands mount on the plane that requested them — ONLY the
1138
+ * `chapters-tools` row inside the preset composition calls this, from
1139
+ * `src/tools-row.ts`. The host plane never calls it: a tool registered on the host
1140
+ * plane rides EVERY session's request whatever preset composes (measured in the #319
1141
+ * e2e logs as `chapters_*` schemas inside `standard`-preset headers), which is the leak
1142
+ * #330 exists to close.
1143
+ */
1125
1144
  export function registerChaptersTools(ctx, store, config) {
1126
1145
  const built = buildChaptersTools(ctx, store, config);
1127
1146
  const disposeSegment = ctx.tools.register(built.segment);
@@ -1135,11 +1154,10 @@ export function registerChaptersTools(ctx, store, config) {
1135
1154
  const commands = ctx.get?.('commands');
1136
1155
  if (commands?.register !== undefined) {
1137
1156
  try {
1138
- // Both deterministic doors register on the same seam. Keep EVERY disposer: a loop
1139
- // that overwrote `disposeCommand` would leak the first registration and unregister
1140
- // only whichever door was added last.
1157
+ // Keep EVERY disposer: a loop that overwrote `disposeCommand` would leak the
1158
+ // first registration and unregister only whichever door was added last.
1141
1159
  const commandDisposers = [];
1142
- for (const def of [built.forkCommand, built.continueCommand, built.saveCommand, built.repairCommand, built.restoreCommand]) {
1160
+ for (const def of [built.forkCommand, built.continueCommand, built.saveCommand]) {
1143
1161
  const disposer = commands.register(def);
1144
1162
  if (typeof disposer === 'function')
1145
1163
  commandDisposers.push(disposer);
@@ -1166,4 +1184,30 @@ export function registerChaptersTools(ctx, store, config) {
1166
1184
  disposeCommand?.();
1167
1185
  };
1168
1186
  }
1187
+ /**
1188
+ * The host-side registrar (#330): `/chapters-repair` and `/chapters-restore` stay
1189
+ * operator-side so a broken chapters archive is fixable FROM ANY SESSION — a poisoned
1190
+ * chapters child may not compose its realm at all, and the restore door (#319) is the
1191
+ * documented way in. Command text is not a model prompt surface; these registrations
1192
+ * are human reach, not agent attention, which is the line #330 draws.
1193
+ */
1194
+ export function registerChaptersRepairRestore(ctx, store, config) {
1195
+ const built = buildChaptersTools(ctx, store, config);
1196
+ const disposers = [];
1197
+ const commands = ctx.get?.('commands');
1198
+ if (commands?.register !== undefined) {
1199
+ try {
1200
+ for (const def of [built.repairCommand, built.restoreCommand]) {
1201
+ const disposer = commands.register(def);
1202
+ if (typeof disposer === 'function')
1203
+ disposers.push(disposer);
1204
+ }
1205
+ }
1206
+ catch (error) {
1207
+ ctx.logger?.warn?.(`dsh-chapters: repair/restore command registration failed (${String(error)})`);
1208
+ }
1209
+ }
1210
+ return () => { for (const d of disposers)
1211
+ d(); };
1212
+ }
1169
1213
  //# sourceMappingURL=tools.js.map