@fractalsynapse/dsh-chapters 0.0.0-stage → 0.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +76 -2
  3. package/cordis.patch.yml +363 -0
  4. package/docs/architecture.md +692 -0
  5. package/docs/autorun-guide.md +248 -0
  6. package/docs/backlog.md +2022 -0
  7. package/docs/contract.md +938 -0
  8. package/docs/development.md +990 -0
  9. package/docs/host-compaction-seam.md +225 -0
  10. package/docs/host-protected-head-ask.md +80 -0
  11. package/docs/knowledge-repo.md +1332 -0
  12. package/docs/plans-carriage.md +571 -0
  13. package/docs/project-state.md +642 -0
  14. package/docs/provider.md +98 -0
  15. package/docs/superpowers/plans/2026-10-17-chapters-save.md +198 -0
  16. package/docs/superpowers/plans/2026-11-02-chapter-removal.md +151 -0
  17. package/docs/superpowers/specs/2026-11-02-chapter-removal-design.md +115 -0
  18. package/docs/verify.md +561 -0
  19. package/lib/archive.d.ts +161 -0
  20. package/lib/archive.js +229 -0
  21. package/lib/archive.js.map +1 -0
  22. package/lib/arrival.d.ts +23 -0
  23. package/lib/arrival.js +125 -0
  24. package/lib/arrival.js.map +1 -0
  25. package/lib/artifact-query.d.ts +62 -0
  26. package/lib/artifact-query.js +187 -0
  27. package/lib/artifact-query.js.map +1 -0
  28. package/lib/attach.d.ts +46 -0
  29. package/lib/attach.js +120 -0
  30. package/lib/attach.js.map +1 -0
  31. package/lib/auto-save.d.ts +145 -0
  32. package/lib/auto-save.js +334 -0
  33. package/lib/auto-save.js.map +1 -0
  34. package/lib/aux-message.d.ts +17 -0
  35. package/lib/aux-message.js +20 -0
  36. package/lib/aux-message.js.map +1 -0
  37. package/lib/client.js +1419 -0
  38. package/lib/client.js.map +1 -0
  39. package/lib/codegraph.d.ts +76 -0
  40. package/lib/codegraph.js +190 -0
  41. package/lib/codegraph.js.map +1 -0
  42. package/lib/commands.d.ts +52 -0
  43. package/lib/commands.js +946 -0
  44. package/lib/commands.js.map +1 -0
  45. package/lib/compose.d.ts +30 -0
  46. package/lib/compose.js +185 -0
  47. package/lib/compose.js.map +1 -0
  48. package/lib/continue-core.d.ts +245 -0
  49. package/lib/continue-core.js +405 -0
  50. package/lib/continue-core.js.map +1 -0
  51. package/lib/diag.d.ts +55 -0
  52. package/lib/diag.js +186 -0
  53. package/lib/diag.js.map +1 -0
  54. package/lib/engine-core.d.ts +301 -0
  55. package/lib/engine-core.js +531 -0
  56. package/lib/engine-core.js.map +1 -0
  57. package/lib/engine-note.d.ts +35 -0
  58. package/lib/engine-note.js +32 -0
  59. package/lib/engine-note.js.map +1 -0
  60. package/lib/engine.d.ts +329 -0
  61. package/lib/engine.js +1179 -0
  62. package/lib/engine.js.map +1 -0
  63. package/lib/enrich-queue.d.ts +66 -0
  64. package/lib/enrich-queue.js +126 -0
  65. package/lib/enrich-queue.js.map +1 -0
  66. package/lib/enrich-store.d.ts +31 -0
  67. package/lib/enrich-store.js +103 -0
  68. package/lib/enrich-store.js.map +1 -0
  69. package/lib/enrich-wire.d.ts +163 -0
  70. package/lib/enrich-wire.js +353 -0
  71. package/lib/enrich-wire.js.map +1 -0
  72. package/lib/enrich.d.ts +102 -0
  73. package/lib/enrich.js +267 -0
  74. package/lib/enrich.js.map +1 -0
  75. package/lib/gitops.d.ts +107 -0
  76. package/lib/gitops.js +539 -0
  77. package/lib/gitops.js.map +1 -0
  78. package/lib/index.d.ts +241 -0
  79. package/lib/index.js +1162 -0
  80. package/lib/index.js.map +1 -0
  81. package/lib/indexing.d.ts +98 -0
  82. package/lib/indexing.js +223 -0
  83. package/lib/indexing.js.map +1 -0
  84. package/lib/injections.d.ts +90 -0
  85. package/lib/injections.js +165 -0
  86. package/lib/injections.js.map +1 -0
  87. package/lib/last-resort.d.ts +24 -0
  88. package/lib/last-resort.js +27 -0
  89. package/lib/last-resort.js.map +1 -0
  90. package/lib/log-shape.d.ts +38 -0
  91. package/lib/log-shape.js +93 -0
  92. package/lib/log-shape.js.map +1 -0
  93. package/lib/models-command.d.ts +74 -0
  94. package/lib/models-command.js +100 -0
  95. package/lib/models-command.js.map +1 -0
  96. package/lib/notice.d.ts +74 -0
  97. package/lib/notice.js +92 -0
  98. package/lib/notice.js.map +1 -0
  99. package/lib/plans.d.ts +154 -0
  100. package/lib/plans.js +315 -0
  101. package/lib/plans.js.map +1 -0
  102. package/lib/preset.d.ts +186 -0
  103. package/lib/preset.js +212 -0
  104. package/lib/preset.js.map +1 -0
  105. package/lib/prompt-keys.d.ts +7 -0
  106. package/lib/prompt-keys.js +8 -0
  107. package/lib/prompt-keys.js.map +1 -0
  108. package/lib/prompt-loop.d.ts +73 -0
  109. package/lib/prompt-loop.js +147 -0
  110. package/lib/prompt-loop.js.map +1 -0
  111. package/lib/prompt-push.d.ts +47 -0
  112. package/lib/prompt-push.js +115 -0
  113. package/lib/prompt-push.js.map +1 -0
  114. package/lib/prompt-runner.d.ts +48 -0
  115. package/lib/prompt-runner.js +90 -0
  116. package/lib/prompt-runner.js.map +1 -0
  117. package/lib/prompt-state.d.ts +142 -0
  118. package/lib/prompt-state.js +101 -0
  119. package/lib/prompt-state.js.map +1 -0
  120. package/lib/prompt.d.ts +270 -0
  121. package/lib/prompt.js +408 -0
  122. package/lib/prompt.js.map +1 -0
  123. package/lib/provider.d.ts +44 -0
  124. package/lib/provider.js +66 -0
  125. package/lib/provider.js.map +1 -0
  126. package/lib/redact.d.ts +24 -0
  127. package/lib/redact.js +85 -0
  128. package/lib/redact.js.map +1 -0
  129. package/lib/registry.d.ts +187 -0
  130. package/lib/registry.js +235 -0
  131. package/lib/registry.js.map +1 -0
  132. package/lib/removal.d.ts +159 -0
  133. package/lib/removal.js +556 -0
  134. package/lib/removal.js.map +1 -0
  135. package/lib/render.d.ts +97 -0
  136. package/lib/render.js +530 -0
  137. package/lib/render.js.map +1 -0
  138. package/lib/repair-run.d.ts +76 -0
  139. package/lib/repair-run.js +506 -0
  140. package/lib/repair-run.js.map +1 -0
  141. package/lib/repair.d.ts +208 -0
  142. package/lib/repair.js +357 -0
  143. package/lib/repair.js.map +1 -0
  144. package/lib/repo.d.ts +78 -0
  145. package/lib/repo.js +184 -0
  146. package/lib/repo.js.map +1 -0
  147. package/lib/rules-commands.d.ts +46 -0
  148. package/lib/rules-commands.js +379 -0
  149. package/lib/rules-commands.js.map +1 -0
  150. package/lib/rules.d.ts +267 -0
  151. package/lib/rules.js +478 -0
  152. package/lib/rules.js.map +1 -0
  153. package/lib/save-core.d.ts +72 -0
  154. package/lib/save-core.js +220 -0
  155. package/lib/save-core.js.map +1 -0
  156. package/lib/search.d.ts +112 -0
  157. package/lib/search.js +282 -0
  158. package/lib/search.js.map +1 -0
  159. package/lib/session-rules.d.ts +222 -0
  160. package/lib/session-rules.js +454 -0
  161. package/lib/session-rules.js.map +1 -0
  162. package/lib/signature.d.ts +45 -0
  163. package/lib/signature.js +199 -0
  164. package/lib/signature.js.map +1 -0
  165. package/lib/store.d.ts +156 -0
  166. package/lib/store.js +368 -0
  167. package/lib/store.js.map +1 -0
  168. package/lib/sync.d.ts +220 -0
  169. package/lib/sync.js +810 -0
  170. package/lib/sync.js.map +1 -0
  171. package/lib/tools.d.ts +113 -0
  172. package/lib/tools.js +1090 -0
  173. package/lib/tools.js.map +1 -0
  174. package/lib/treedx/client.d.ts +57 -0
  175. package/lib/treedx/client.js +82 -0
  176. package/lib/treedx/client.js.map +1 -0
  177. package/lib/treedx/provider.d.ts +39 -0
  178. package/lib/treedx/provider.js +479 -0
  179. package/lib/treedx/provider.js.map +1 -0
  180. package/lib/treedx/state.d.ts +27 -0
  181. package/lib/treedx/state.js +65 -0
  182. package/lib/treedx/state.js.map +1 -0
  183. package/lib/types.d.ts +210 -0
  184. package/lib/types.js +31 -0
  185. package/lib/types.js.map +1 -0
  186. package/lib/version.d.ts +9 -0
  187. package/lib/version.js +10 -0
  188. package/lib/version.js.map +1 -0
  189. package/lib/vocabulary.d.ts +41 -0
  190. package/lib/vocabulary.js +118 -0
  191. package/lib/vocabulary.js.map +1 -0
  192. package/lib/warnings.d.ts +10 -0
  193. package/lib/warnings.js +18 -0
  194. package/lib/warnings.js.map +1 -0
  195. package/package.json +151 -3
package/lib/rules.js ADDED
@@ -0,0 +1,478 @@
1
+ /**
2
+ * P3 — rules are chapters of a different kind (record §7.1): same file
3
+ * format, same sync, searched like anything else; this module adds ONLY the
4
+ * lifecycle-shaped parts:
5
+ *
6
+ * - the rule file (written ONCE, status: proposed, immutable thereafter),
7
+ * - the per-machine status resolution (§15 amendment 2026-09-20): effective
8
+ * status comes from the APPROVING MACHINE's own curation facts
9
+ * (edits/<harnessId>/curation.jsonl, `rule-status` entries), never from a
10
+ * file rewrite — authorship stays partitioned, and a rule proposed on one
11
+ * machine affects no other machine's notice until a human there approves,
12
+ * - the rules block (§7.3): active rules verbatim + a category index,
13
+ * budgeted, refuse-with-numbers on overflow, and — load-bearing for the
14
+ * tape corpus — BYTE-IDENTICAL NOTHING when there are no rules: an empty
15
+ * project renders no section at all.
16
+ *
17
+ * #50 (record §7.1, §7.3–§7.5) adds the SECOND TIER without adding a second
18
+ * subsystem: `scope: project | session` on the same file format. Absent means
19
+ * `project`, so every rule record written before this amendment keeps its exact
20
+ * bytes. Session rules are machine-local, captured from human bytes, and their
21
+ * activation is DERIVED from the ancestor path — never a curation fact, because
22
+ * `edits/<harness>/curation.jsonl` is pool-synced and reserved for human status
23
+ * decisions (§15 amendment 2026-09-20, unrelaxed). They are also never staged
24
+ * (§7.5, `planStoreToRepo`), so the pool cannot accumulate one machine's
25
+ * mis-generalizations.
26
+ */
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import { z } from 'zod';
30
+ import { estimateTokens, sha256 } from "./render.js";
31
+ import { parseCuration } from "./indexing.js";
32
+ import { parseChapterFile } from "./enrich-store.js";
33
+ import { diagnostic } from "./diag.js";
34
+ export const RULE_STATUS = ['proposed', 'core', 'revoked'];
35
+ /** §7.1: two tiers, one store. Absent scope on any file or record ⇒ `project`. */
36
+ export const RULE_SCOPE = ['project', 'session'];
37
+ /** How the bytes came to be: a person, the deterministic marker, or the model. */
38
+ export const RULE_DERIVED_FROM = ['human', 'marker', 'model'];
39
+ /**
40
+ * The WARRANT behind a rule — what a human reads when deciding whether to trust
41
+ * it (record §7.5, amended 2026-10-21). `stated` means a human sentence is behind
42
+ * the rule; `inferred` means the model judged that a standing order would help and
43
+ * nobody said it. BOTH govern by default, because the premise of the tier is that
44
+ * the human may not know the rule yet — the distinction is displayed, not used as
45
+ * a permission check. Requiring a human to have already said it would make this
46
+ * tier redundant with the deterministic `ADD RULE:` marker.
47
+ */
48
+ export const RULE_BASIS = ['human', 'marker', 'stated', 'inferred'];
49
+ export const ruleRecordSchema = z.object({
50
+ id: z.string().min(3),
51
+ projectKey: z.string().min(1),
52
+ number: z.number().int().positive(),
53
+ path: z.string().min(1),
54
+ category: z.string().min(1),
55
+ title: z.string(),
56
+ sourceSession: z.string(),
57
+ at: z.string(),
58
+ scope: z.enum(RULE_SCOPE).optional(),
59
+ session: z.string().optional(),
60
+ derivedFrom: z.enum(RULE_DERIVED_FROM).optional(),
61
+ pinned: z.boolean().optional(),
62
+ reviewOnly: z.boolean().optional(),
63
+ basis: z.enum(RULE_BASIS).optional(),
64
+ chapter: z.number().int().positive().optional(),
65
+ });
66
+ export const ruleSlug = (category, title) => {
67
+ const s = (t) => t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
68
+ return `${s(category) || 'rule'}-${s(title) || 'untitled'}`;
69
+ };
70
+ export const rulePath = (storeRoot, harnessId, number, category, title) => path.posix.join(storeRoot, 'rules', harnessId, `${String(number).padStart(3, '0')}-${ruleSlug(category, title)}.md`);
71
+ /** one write, ever: rules are proposed by their author and never rewritten (status rides facts) */
72
+ export function renderRuleFile(input) {
73
+ // §7.1 byte-compatibility: a project rule derived from a human and unpinned
74
+ // emits NOTHING extra, so every rule file written before #50 keeps rendering
75
+ // the same bytes. Defaults are absent, never printed.
76
+ const extras = [];
77
+ if (input.scope !== undefined && input.scope !== 'project')
78
+ extras.push(`scope: ${input.scope}`);
79
+ if (input.session !== undefined && input.session !== '')
80
+ extras.push(`session: ${JSON.stringify(input.session)}`);
81
+ if (input.derivedFrom !== undefined && input.derivedFrom !== 'human')
82
+ extras.push(`derivedFrom: ${input.derivedFrom}`);
83
+ if (input.pinned === true)
84
+ extras.push('pinned: true');
85
+ if (input.reviewOnly === true)
86
+ extras.push('reviewOnly: true');
87
+ if (input.basis !== undefined && input.basis !== 'human')
88
+ extras.push(`basis: ${input.basis}`);
89
+ if (input.chapter !== undefined && input.chapter > 0)
90
+ extras.push(`chapter: ${input.chapter}`);
91
+ return [
92
+ '---',
93
+ `number: ${input.number}`,
94
+ 'kind: rule',
95
+ `category: ${JSON.stringify(input.category)}`,
96
+ `title: ${JSON.stringify(input.title)}`,
97
+ 'status: proposed',
98
+ ...extras,
99
+ `sourceSession: ${JSON.stringify(input.sourceSession)}`,
100
+ `authoredAt: ${JSON.stringify(input.at)}`,
101
+ `sha256: ${sha256(input.body)}`,
102
+ '---',
103
+ input.body,
104
+ ].join('\n');
105
+ }
106
+ export function parseRuleFile(text) {
107
+ try {
108
+ const doc = parseChapterFile(text);
109
+ const fm = new Map();
110
+ for (const line of doc.fmLines) {
111
+ const m = /^([A-Za-z][\w]*):\s*(.*)$/.exec(line);
112
+ if (m !== null)
113
+ fm.set(m[1], m[2].trim());
114
+ }
115
+ if (fm.get('kind') !== 'rule')
116
+ return null;
117
+ const unq = (v, d) => (v ?? d).replace(/^"|"$/g, '');
118
+ const rawStatus = unq(fm.get('status'), 'proposed');
119
+ const rawScope = unq(fm.get('scope'), 'project');
120
+ const rawDerived = unq(fm.get('derivedFrom'), 'human');
121
+ return {
122
+ number: Number(fm.get('number') ?? '0'),
123
+ category: unq(fm.get('category'), 'general'),
124
+ title: unq(fm.get('title'), ''),
125
+ fileStatus: RULE_STATUS.includes(rawStatus) ? rawStatus : 'proposed',
126
+ sourceSession: unq(fm.get('sourceSession'), ''),
127
+ body: doc.body,
128
+ // an unrecognized value degrades to the SAFE default: a hand-edited or
129
+ // future-versioned file must never become active by accident
130
+ scope: RULE_SCOPE.includes(rawScope) ? rawScope : 'project',
131
+ session: unq(fm.get('session'), ''),
132
+ derivedFrom: RULE_DERIVED_FROM.includes(rawDerived) ? rawDerived : 'human',
133
+ pinned: unq(fm.get('pinned'), '') === 'true',
134
+ reviewOnly: unq(fm.get('reviewOnly'), '') === 'true',
135
+ basis: RULE_BASIS.includes(unq(fm.get('basis'), '')) ? unq(fm.get('basis'), '') : 'human',
136
+ chapter: Number(unq(fm.get('chapter'), '0')) > 0 ? Number(unq(fm.get('chapter'), '0')) : 0,
137
+ };
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ }
143
+ /** the machine's own facts, last-write-wins per rule (append-only file order) */
144
+ export function loadRuleStatusFacts(mirrorDir, harnessId) {
145
+ const out = new Map();
146
+ const file = path.join(mirrorDir, 'edits', harnessId, 'curation.jsonl');
147
+ if (!fs.existsSync(file))
148
+ return out;
149
+ for (const f of parseCuration(fs.readFileSync(file, 'utf8'))) {
150
+ if (f.type !== 'rule-status')
151
+ continue;
152
+ const f2 = f;
153
+ if (typeof f2.rule !== 'string' || typeof f2.status !== 'string')
154
+ continue;
155
+ if (!RULE_STATUS.includes(f2.status))
156
+ continue;
157
+ out.set(f2.rule, { rule: f2.rule, status: f2.status, at: f2.at ?? '' });
158
+ }
159
+ return out;
160
+ }
161
+ /** append-only, like every other curation write */
162
+ export function appendRuleStatusFact(mirrorDir, harnessId, fact) {
163
+ const dir = path.join(mirrorDir, 'edits', harnessId);
164
+ fs.mkdirSync(dir, { recursive: true });
165
+ fs.appendFileSync(path.join(dir, 'curation.jsonl'), JSON.stringify({ type: 'rule-status', ...fact }) + '\n');
166
+ }
167
+ export function effectiveStatus(ruleId, facts, fileStatus) {
168
+ return facts.get(ruleId)?.status ?? fileStatus;
169
+ }
170
+ export function appendRulePinFact(mirrorDir, harnessId, fact) {
171
+ const dir = path.join(mirrorDir, 'edits', harnessId);
172
+ fs.mkdirSync(dir, { recursive: true });
173
+ fs.appendFileSync(path.join(dir, 'curation.jsonl'), JSON.stringify({ type: 'rule-pin', ...fact }) + '\n');
174
+ }
175
+ /** the machine's pins, last-write-wins (so `unpin` is a later fact, not a delete) */
176
+ export function loadRulePins(mirrorDir, harnessId) {
177
+ const out = new Set();
178
+ const file = path.join(mirrorDir, 'edits', harnessId, 'curation.jsonl');
179
+ if (!fs.existsSync(file))
180
+ return out;
181
+ for (const f of parseCuration(fs.readFileSync(file, 'utf8'))) {
182
+ if (f.type !== 'rule-pin')
183
+ continue;
184
+ const f2 = f;
185
+ if (typeof f2.rule !== 'string')
186
+ continue;
187
+ if (f2.pinned === true)
188
+ out.add(f2.rule);
189
+ else
190
+ out.delete(f2.rule);
191
+ }
192
+ return out;
193
+ }
194
+ /** every rule file the mirror knows for one project, with THIS machine's effective status */
195
+ export function collectMirrorRules(mirrorDir, projectKey, harnessId) {
196
+ const root = path.join(mirrorDir, 'rules', projectKey);
197
+ if (!fs.existsSync(root))
198
+ return [];
199
+ const facts = loadRuleStatusFacts(mirrorDir, harnessId);
200
+ const pins = loadRulePins(mirrorDir, harnessId);
201
+ const out = [];
202
+ const walk = (dir, rel) => {
203
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
204
+ const p = path.join(dir, e.name);
205
+ if (e.isDirectory()) {
206
+ walk(p, rel === '' ? e.name : path.join(rel, e.name));
207
+ continue;
208
+ }
209
+ if (!e.name.endsWith('.md'))
210
+ continue;
211
+ const relPath = path.posix.join('rules', projectKey, rel === '' ? e.name : `${rel}/${e.name}`);
212
+ const rule = parseRuleFile(fs.readFileSync(p, 'utf8'));
213
+ if (rule === null)
214
+ continue;
215
+ const harness = e.name === '' ? harnessId : path.basename(path.dirname(p));
216
+ const id = `${harness}/${String(rule.number).padStart(3, '0')}`;
217
+ const status = effectiveStatus(id, facts, rule.fileStatus);
218
+ out.push({
219
+ id, relPath, status, category: rule.category, title: rule.title,
220
+ body: rule.body.trim(), bodyTokens: estimateTokens(rule.body.trim()),
221
+ scope: rule.scope, session: rule.session, derivedFrom: rule.derivedFrom,
222
+ // file-level pin (an authored default) OR this machine's pin fact (§7.4)
223
+ pinned: rule.pinned || pins.has(id),
224
+ reviewOnly: rule.reviewOnly, basis: rule.basis, chapter: rule.chapter,
225
+ });
226
+ }
227
+ };
228
+ walk(root, '');
229
+ return out.sort((a, b) => a.category < b.category ? -1 : a.category > b.category ? 1 : a.id < b.id ? -1 : 0);
230
+ }
231
+ /** deterministic term set for overlap scoring — no clock, no locale surprises */
232
+ const ruleTerms = (r) => new Set(`${r.category} ${r.title} ${r.body}`.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2));
233
+ /**
234
+ * §7.4 selection: pinned first (ground rules are OLD — anything that ranks by
235
+ * recency or topicality evicts them first), then topicality when topics are
236
+ * supplied, then the pre-#50 category/id order. A pure function of the inputs,
237
+ * so two machines with the same files render the same head and the tapes stay
238
+ * stable.
239
+ */
240
+ export function selectRules(rules, topics) {
241
+ const bag = topics === undefined || topics.length === 0 ? null : new Set(topics.map((t) => t.toLowerCase()));
242
+ const overlap = (r) => {
243
+ if (bag === null)
244
+ return 0;
245
+ const terms = ruleTerms(r);
246
+ let n = 0;
247
+ for (const t of bag)
248
+ if (terms.has(t) || terms.has(t.replace(/s$/, '')))
249
+ n += 1;
250
+ return n;
251
+ };
252
+ return [...rules].sort((a, b) => (a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1)
253
+ || (overlap(b) - overlap(a))
254
+ || (a.category < b.category ? -1 : a.category > b.category ? 1 : 0)
255
+ || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
256
+ }
257
+ /** the rule ids a human switched off on THIS machine (both tiers) */
258
+ export function revokedRuleIds(mirrorDir, harnessId) {
259
+ const out = new Set();
260
+ for (const [id, f] of loadRuleStatusFacts(mirrorDir, harnessId))
261
+ if (f.status === 'revoked')
262
+ out.add(id);
263
+ return out;
264
+ }
265
+ /**
266
+ * §7.5: session rules are collected from the LOCAL store, never from the pool
267
+ * mirror — they are not staged (`planStoreToRepo` skips `scope: session`), so
268
+ * the only place they exist is `<storeDir>/rules/<harness>/*.md`. Same parser,
269
+ * same id shape, so `list`, numbering and search stay one mechanism for both
270
+ * tiers.
271
+ */
272
+ export function collectStoreRules(storeDir, harnessId,
273
+ /** §7.5: this machine's `rule-status` facts, so a human `approve` can switch a
274
+ * SUGGESTED model rule on without rewriting the write-once file. */
275
+ facts) {
276
+ const root = path.join(storeDir, 'rules');
277
+ if (!fs.existsSync(root))
278
+ return [];
279
+ const out = [];
280
+ const walk = (dir, rel) => {
281
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
282
+ const p = path.join(dir, e.name);
283
+ if (e.isDirectory()) {
284
+ walk(p, rel === '' ? e.name : path.join(rel, e.name));
285
+ continue;
286
+ }
287
+ if (!e.name.endsWith('.md'))
288
+ continue;
289
+ const relPath = path.posix.join('rules', rel === '' ? e.name : `${rel}/${e.name}`);
290
+ const rule = parseRuleFile(fs.readFileSync(p, 'utf8'));
291
+ if (rule === null)
292
+ continue;
293
+ const harness = rel === '' ? harnessId : path.basename(path.dirname(p));
294
+ const id = `${harness}/${String(rule.number).padStart(3, '0')}`;
295
+ out.push({
296
+ id, relPath, status: facts === undefined ? rule.fileStatus : effectiveStatus(id, facts, rule.fileStatus),
297
+ category: rule.category, title: rule.title,
298
+ body: rule.body.trim(), bodyTokens: estimateTokens(rule.body.trim()),
299
+ scope: rule.scope, session: rule.session, derivedFrom: rule.derivedFrom,
300
+ pinned: rule.pinned, reviewOnly: rule.reviewOnly, basis: rule.basis, chapter: rule.chapter,
301
+ });
302
+ }
303
+ };
304
+ walk(root, '');
305
+ return out.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
306
+ }
307
+ /**
308
+ * §7.5 transport predicate: is this authored rule file part of the machine-local
309
+ * session tier? Reads it through the SAME parser the collectors use — one
310
+ * definition of `scope`, never a second lightweight guess that can drift from it.
311
+ * An unreadable or non-rule file is treated as project (staged), because the
312
+ * exclusion must be a decision about the session tier specifically, not a
313
+ * side-effect of a parse miss.
314
+ */
315
+ export function isSessionRuleFile(absPath) {
316
+ try {
317
+ return parseRuleFile(fs.readFileSync(absPath, 'utf8'))?.scope === 'session';
318
+ }
319
+ catch {
320
+ return false;
321
+ }
322
+ }
323
+ /**
324
+ * §7.5 activation, DERIVED rather than approved: a session rule binds exactly
325
+ * one session tree — its own session must be on the current session's ancestor
326
+ * path — and a human `revoke` is the one fact that can switch it off (files are
327
+ * write-once, §1.3, so there is nothing else to edit).
328
+ */
329
+ export function sessionRuleActive(rule,
330
+ /** `facts` is unused here (the caller resolves status into `rule.status`); it is
331
+ * accepted so both collectors and callers pass ONE options object around. */
332
+ opts) {
333
+ if (rule.scope !== 'session')
334
+ return false;
335
+ if (rule.session === '')
336
+ return false;
337
+ if (opts.revoked.has(rule.id))
338
+ return false;
339
+ // Review posture, NOT an evidence test (amended 2026-10-21): a mined rule is
340
+ // inert only when the plugin is configured to hold mined rules for review. What
341
+ // keeps an inferred rule from doing damage is that it is machine-local, never
342
+ // staged, count-capped, rendered with its warrant, and one command from
343
+ // revoke — not a requirement that a human have already said it.
344
+ if (rule.reviewOnly && rule.status !== 'core')
345
+ return false;
346
+ return opts.ancestorSessions.has(rule.session);
347
+ }
348
+ /** The session-tier view for one rebuilt head: active rules, id-ordered. */
349
+ export function collectActiveSessionRules(storeDir, harnessId, opts) {
350
+ return collectStoreRules(storeDir, harnessId, opts.facts).filter((r) => sessionRuleActive(r, opts));
351
+ }
352
+ /**
353
+ * §7.5 re-derivation and the capture path: scan text for the marker at LINE
354
+ * START and return the rule bodies, in order, deduped by exact body.
355
+ *
356
+ * Deterministic and model-free by contract (§1 invariant 1) — this is the
357
+ * per-turn path AND the rebuild-after-loss path, so it must never touch `ctx.llm`.
358
+ */
359
+ export function parseRuleMarkers(text, prefix) {
360
+ const out = [];
361
+ const p = prefix.trim();
362
+ if (p === '')
363
+ return out;
364
+ for (const raw of text.split(/\r?\n/)) {
365
+ // line START only: a sentence that merely mentions the prefix mid-prose is
366
+ // conversation, not a capture request.
367
+ const line = raw.replace(/^\s+/, '');
368
+ if (!line.startsWith(p))
369
+ continue;
370
+ const body = line.slice(p.length).trim();
371
+ if (body.length < 10)
372
+ continue; // same minimum the add command enforces
373
+ if (!out.includes(body))
374
+ out.push(body);
375
+ }
376
+ return out;
377
+ }
378
+ const capLine = (tier, active, shown) => shown >= active ? null : `${active - shown} more ${tier} rule(s) active but not shown — /chapters-rule active lists them, pin one to keep it here`;
379
+ /**
380
+ * §7.3: the rules block a rebuilt head carries. `kind: 'none'` (no active rules
381
+ * and no corpus) MUST produce zero injected bytes at the call site — the tape
382
+ * corpus depends on it. Overflow of the TOKEN ceiling refuses with per-rule
383
+ * numbers, never clips (§1.2); a count CAP selects, and what it left out is
384
+ * ANNOUNCED, because silent selection would rebuild "lost in the noise" inside
385
+ * the fix for it.
386
+ */
387
+ export function buildRulesSection(mirrorDir, opts) {
388
+ const statusFacts = loadRuleStatusFacts(mirrorDir, opts.harnessId);
389
+ const revoked = new Set([...statusFacts].filter(([, f]) => f.status === 'revoked').map(([id]) => id));
390
+ const all = collectMirrorRules(mirrorDir, opts.projectKey, opts.harnessId);
391
+ const projectActive = all.filter((r) => r.scope === 'project' && r.status === 'core');
392
+ const sessionActive = opts.storeDir !== undefined && opts.ancestorSessions !== undefined
393
+ ? collectActiveSessionRules(opts.storeDir, opts.harnessId, { ancestorSessions: opts.ancestorSessions, revoked, facts: statusFacts })
394
+ : [];
395
+ const categories = new Map();
396
+ for (const r of all) {
397
+ if (r.status === 'revoked' || r.scope !== 'project')
398
+ continue;
399
+ const prev = categories.get(r.category);
400
+ categories.set(r.category, {
401
+ count: (prev?.count ?? 0) + 1,
402
+ essence: prev?.essence ?? r.title,
403
+ samplePath: prev?.samplePath ?? r.relPath,
404
+ });
405
+ }
406
+ if (projectActive.length === 0 && sessionActive.length === 0 && categories.size === 0)
407
+ return { kind: 'none' };
408
+ // #113, and the reason this is a note rather than a comment: the rig's local boots contribute the rules
409
+ // section and a GitHub runner does not, and the section is message 0 of every request — so the whole tape
410
+ // corpus keys on which side of this line each machine lands. Counting the three inputs is the only way to
411
+ // learn which one differs, and the engine-errors sink is per-port and already uploaded by CI on failure.
412
+ diagnostic('rules-section', `contributing: project=${String(projectActive.length)}`
413
+ + ` session=${String(sessionActive.length)} categories=${String(categories.size)}`
414
+ + ` projectKey=${opts.projectKey ?? 'none'} harness=${opts.harnessId ?? 'none'}`);
415
+ const topics = opts.relevanceTopics;
416
+ const pSel = selectRules(projectActive, topics);
417
+ const sSel = selectRules(sessionActive, topics);
418
+ const pShown = opts.projectCap === undefined ? pSel : pSel.slice(0, Math.max(0, opts.projectCap));
419
+ const sShown = opts.sessionCap === undefined ? sSel : sSel.slice(0, Math.max(0, opts.sessionCap));
420
+ const withheld = { project: pSel.length - pShown.length, session: sSel.length - sShown.length };
421
+ // the token ceiling is measured on what would actually render (§1.2)
422
+ let total = 0;
423
+ for (const r of [...pShown, ...sShown])
424
+ total += r.bodyTokens;
425
+ if (total > opts.budgetTokens) {
426
+ return {
427
+ kind: 'refusal',
428
+ reason: `core rules exceed their budget: ${total} tokens over a cap of ${opts.budgetTokens}. Revoke one ("/chapters-rule revoke <id>") or split a category — the notice never clips rules.`,
429
+ perRule: [...pShown, ...sShown].map((r) => ({ id: r.id, tokens: r.bodyTokens })),
430
+ cap: opts.budgetTokens,
431
+ total,
432
+ };
433
+ }
434
+ const lines = [];
435
+ if (pShown.length > 0) {
436
+ lines.push('## CORE RULES (approved for this project — follow them)');
437
+ for (const r of pShown)
438
+ lines.push(`[${r.id}] (${r.category}) ${r.body}`, '');
439
+ }
440
+ // Every rule carries its WARRANT, because a human has to be able to tell a
441
+ // standing order they gave from a standing order a model inferred (§7.5).
442
+ const tag = (r) => {
443
+ if (r.scope === 'project' || r.derivedFrom !== 'model')
444
+ return r.derivedFrom === 'marker' ? 'you said this' : '';
445
+ const from = r.chapter > 0 ? `ch.${r.chapter}` : 'this session tree';
446
+ return r.basis === 'stated' ? `stated by you, mined from ${from}` : `inferred from ${from} — nobody said it`;
447
+ };
448
+ const pWithheld = capLine('project', pSel.length, pShown.length);
449
+ if (pWithheld !== null)
450
+ lines.push(pWithheld, '');
451
+ if (sShown.length > 0) {
452
+ lines.push('## SESSION RULES (captured this session — they refine the project rules above; they never override them)');
453
+ for (const r of sShown) {
454
+ const t = tag(r);
455
+ lines.push(`[${r.id}] (${r.category}${t !== '' ? `; ${t}` : ''}) ${r.body}`, '');
456
+ }
457
+ const sWithheld = capLine('session', sSel.length, sShown.length);
458
+ if (sWithheld !== null)
459
+ lines.push(sWithheld, '');
460
+ }
461
+ if (sShown.length > 0) {
462
+ // The transparency the tier needs: an inferred standing order is exactly the
463
+ // kind of thing a human must be able to catch, so the agent names which rules
464
+ // actually shaped its reply (§7.5). Scoped to blocks that carry session rules —
465
+ // a project-only block keeps its pre-#50 bytes (the R0 golden row pins that),
466
+ // so this costs nothing to a session that has no mined rules.
467
+ lines.push('Name by id the session rule(s) above that actually shaped what you did — say "none" if none applied. A rule cited wrongly twice should be revoked.', '');
468
+ }
469
+ if (categories.size > 0) {
470
+ lines.push('Rule categories (load a category from the repo when this session\u2019s topics overlap it):');
471
+ for (const [cat, m] of [...categories.entries()].sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) {
472
+ lines.push(`- ${cat} (${m.count}): ${m.essence} — e.g. ${m.samplePath}`);
473
+ }
474
+ }
475
+ const text = lines.join('\n').trimEnd();
476
+ return { kind: 'ok', text, tokens: estimateTokens(text), shown: { project: pShown.length, session: sShown.length }, withheld };
477
+ }
478
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.js","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;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,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YACxG,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,UAAU,EAAE,CAAC,CAAA;QAC1E,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAA;IACvC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,CAAA;AAChI,CAAC"}
@@ -0,0 +1,72 @@
1
+ import { type RegistryStore } from './store.ts';
2
+ import { type SupersedeReason } from './repair.ts';
3
+ import type { ChapterRecord } from './archive.ts';
4
+ import type { RenderConfig, SessionEventLike } from './types.ts';
5
+ export interface SaveSessionConfig extends RenderConfig {
6
+ artifactStoreRoot: string;
7
+ /** Topic-sequential composition (record §4.2): merge while overlap ≥ τ. */
8
+ mergeThreshold: number;
9
+ /** Estimated-token cap per composed chapter. */
10
+ chapterLimit: number;
11
+ /** Hard oversize multiple of `chapterTokenTarget`; past it a door refuses (#59). */
12
+ chapterOversizeFactor?: number | undefined;
13
+ }
14
+ export interface SaveSessionArgs {
15
+ /** Full snapshot of the authoring session's durable log (the caller read it). */
16
+ events: SessionEventLike[];
17
+ /** The session whose registry state owns the watermark and the numbering. */
18
+ sessionId: string;
19
+ /** Workspace cwd — where the store root lives (makeArchiveFs roots RELATIVE paths here). */
20
+ cwd: string;
21
+ store: RegistryStore;
22
+ config: SaveSessionConfig;
23
+ /**
24
+ * Lineage stamp for the chapter frontmatter (issue #47). Pass
25
+ * `lineageOf(session.header)` — undefined for an ordinary session, which
26
+ * renders byte-identically to the pre-feature shape.
27
+ */
28
+ subagentOf?: string | undefined;
29
+ /**
30
+ * REPAIR ONLY (#60): archive this exact span instead of the watermark tail. A repair must re-derive a
31
+ * specific hole (a hollow chapter's seqs, an unsigned completed turn), not "everything new".
32
+ */
33
+ span?: {
34
+ fromSeq: number;
35
+ toSeq: number;
36
+ } | undefined;
37
+ /**
38
+ * REPAIR ONLY (#60): mark chapter `over` superseded by what this call writes, in the SAME registry
39
+ * section that commits the replacement — so a record and its replacement can never be observed apart.
40
+ */
41
+ supersede?: {
42
+ over: number;
43
+ reason: SupersedeReason;
44
+ } | undefined;
45
+ /** REPAIR ONLY: a distinct idempotence key per repair run, so a repair is not eaten by the original save's key. */
46
+ attemptSalt?: string | undefined;
47
+ }
48
+ export type SaveSessionSkip = 'no-completed-turn'
49
+ /** Everything in the span was already archived (watermark at or past the anchor). */
50
+ | 'nothing-new'
51
+ /**
52
+ * #58 — the span rendered zero conversation bytes. A payload read that went wrong, never a
53
+ * short conversation, and never a reason to reserve a number or write a file.
54
+ */
55
+ | 'payloadless'
56
+ /** The archive rendered, but a chapter blew past the hard oversize ceiling (#59). */
57
+ | 'oversize';
58
+ export interface SaveSessionOutcome {
59
+ /** null → the archive was written. Otherwise WHY nothing was written. */
60
+ skipped: SaveSessionSkip | null;
61
+ fromSeq: number;
62
+ /** Last completed turn (the anchor); -1 when there is none. */
63
+ anchor: number;
64
+ /** Highest endSeq already archived before this call (watermark). */
65
+ lastArchived: number;
66
+ /** Chapter records already in the registry for this session, BEFORE this call. */
67
+ priorChapters: number;
68
+ /** Records written by THIS call (empty when skipped). */
69
+ records: ChapterRecord[];
70
+ warnings: string[];
71
+ }
72
+ export declare function saveSession(a: SaveSessionArgs): Promise<SaveSessionOutcome>;