@esneiderbravo/speclaw 0.3.11 → 0.3.13

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 (29) hide show
  1. package/dist/cli/commands/lawbook.js +84 -6
  2. package/dist/cli/commands/quick.js +35 -0
  3. package/dist/cli/commands/update.js +18 -0
  4. package/dist/cli/index.js +17 -1
  5. package/dist/modules/foundation/doctor.js +94 -0
  6. package/dist/modules/lawbook/assets/commands/archive.md +5 -6
  7. package/dist/modules/lawbook/assets/commands/draft.md +6 -7
  8. package/dist/modules/lawbook/assets/commands/investigate.md +7 -0
  9. package/dist/modules/lawbook/assets/commands/quick.md +14 -0
  10. package/dist/modules/lawbook/assets/rules/spec-reports-disciplines.md +8 -0
  11. package/dist/modules/lawbook/assets/skills/archive/steps/03-validate-and-sync.md +4 -3
  12. package/dist/modules/lawbook/assets/skills/draft/SKILL.md +1 -1
  13. package/dist/modules/lawbook/assets/skills/draft/steps/02-understand.md +3 -0
  14. package/dist/modules/lawbook/assets/skills/draft/steps/04-write-artifacts.md +29 -25
  15. package/dist/modules/lawbook/assets/skills/investigate/SKILL.md +10 -0
  16. package/dist/modules/lawbook/assets/skills/investigate/steps/01-investigate.md +7 -0
  17. package/dist/modules/lawbook/assets/skills/investigate/steps/02-hand-off.md +6 -0
  18. package/dist/modules/lawbook/assets/skills/quick/SKILL.md +11 -0
  19. package/dist/modules/lawbook/assets/skills/quick/steps/01-scaffold.md +6 -0
  20. package/dist/modules/lawbook/assets/skills/quick/steps/02-implement.md +7 -0
  21. package/dist/modules/lawbook/bugfix.js +195 -0
  22. package/dist/modules/lawbook/engine.js +178 -55
  23. package/dist/modules/lawbook/investigate.js +358 -0
  24. package/dist/modules/lawbook/levels.js +468 -0
  25. package/dist/modules/lawbook/quick.js +86 -0
  26. package/dist/modules/lawbook/register.js +18 -0
  27. package/dist/modules/lawbook/stack-parse.js +135 -0
  28. package/dist/shared/exposure.js +2 -0
  29. package/package.json +1 -1
@@ -0,0 +1,468 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { indexExists } from "../compass/db.js";
4
+ import { explore } from "../compass/query.js";
5
+ import { impact } from "../compass/query.js";
6
+ import { affectedTests } from "../compass/affected.js";
7
+ import { hotspots } from "../compass/hotspots.js";
8
+ import { loadAffectedConfig, matchGlob, matchesAny, inferModule, } from "../compass/affected-config.js";
9
+ /** Default thresholds from the adaptive-ceremony roadmap. */
10
+ export const DEFAULT_THRESHOLDS = {
11
+ filesTouched: [0, 1, 3, 5],
12
+ modulesTouched: [0, 2, 4, 6],
13
+ affectedTests: [0, 1, 2, 4],
14
+ blastRadiusNodes: [0, 1, 3, 5],
15
+ publicApi: 4,
16
+ globalFile: 5,
17
+ hotspot: 3,
18
+ hotspotFloor: 0.7,
19
+ cuts: [3, 8, 15],
20
+ globalGlobs: [
21
+ "package.json",
22
+ "package-lock.json",
23
+ "tsconfig*.json",
24
+ ".github/workflows/**",
25
+ "src/modules/compass/db.ts",
26
+ "lawbook/config.yaml",
27
+ ],
28
+ docGlobs: ["**/*.md", "docs/**", "assets/**"],
29
+ moduleRoots: ["src"],
30
+ };
31
+ const BUCKETS = {
32
+ filesTouched: [1, 3, 10, Infinity],
33
+ modulesTouched: [1, 2, 4, Infinity],
34
+ affectedTests: [0, 3, 15, Infinity],
35
+ blastRadiusNodes: [2, 10, 50, Infinity],
36
+ };
37
+ export function artifactNeeds(level, changeType = "feature") {
38
+ if (changeType === "bug") {
39
+ switch (level) {
40
+ case 0:
41
+ return {
42
+ record: false,
43
+ proposal: false,
44
+ design: false,
45
+ tasksFile: false,
46
+ deltaSpecs: false,
47
+ reports: true,
48
+ designOptionalWithJustification: false,
49
+ bugfix: true,
50
+ };
51
+ case 1:
52
+ return {
53
+ record: false,
54
+ proposal: false,
55
+ design: false,
56
+ tasksFile: true,
57
+ deltaSpecs: false,
58
+ reports: true,
59
+ designOptionalWithJustification: false,
60
+ bugfix: true,
61
+ };
62
+ case 2:
63
+ case 3:
64
+ return {
65
+ record: false,
66
+ proposal: false,
67
+ design: true,
68
+ tasksFile: true,
69
+ deltaSpecs: false,
70
+ reports: true,
71
+ designOptionalWithJustification: false,
72
+ bugfix: true,
73
+ };
74
+ }
75
+ }
76
+ switch (level) {
77
+ case 0:
78
+ return {
79
+ record: true,
80
+ proposal: false,
81
+ design: false,
82
+ tasksFile: false,
83
+ deltaSpecs: false,
84
+ reports: true,
85
+ designOptionalWithJustification: false,
86
+ bugfix: false,
87
+ };
88
+ case 1:
89
+ return {
90
+ record: true,
91
+ proposal: false,
92
+ design: false,
93
+ tasksFile: true,
94
+ deltaSpecs: true,
95
+ reports: true,
96
+ designOptionalWithJustification: false,
97
+ bugfix: false,
98
+ };
99
+ case 2:
100
+ return {
101
+ record: false,
102
+ proposal: true,
103
+ design: false,
104
+ tasksFile: true,
105
+ deltaSpecs: true,
106
+ reports: true,
107
+ designOptionalWithJustification: true,
108
+ bugfix: false,
109
+ };
110
+ case 3:
111
+ return {
112
+ record: false,
113
+ proposal: true,
114
+ design: true,
115
+ tasksFile: true,
116
+ deltaSpecs: true,
117
+ reports: true,
118
+ designOptionalWithJustification: false,
119
+ bugfix: false,
120
+ };
121
+ }
122
+ }
123
+ /** Read change type from change.json; missing ⇒ feature. */
124
+ export function readChangeType(projectPath, change) {
125
+ const rec = readCeremonyRecord(projectPath, change);
126
+ return rec?.changeType === "bug" ? "bug" : "feature";
127
+ }
128
+ function bucketPoints(value, edges, points) {
129
+ const i = edges.findIndex((max) => value <= max);
130
+ return points[i < 0 ? 3 : i];
131
+ }
132
+ /** Pure scoring; `onlyDocs` short-circuits to 0. */
133
+ export function scoreSignals(s, t = DEFAULT_THRESHOLDS) {
134
+ if (s.onlyDocs)
135
+ return 0;
136
+ let score = 0;
137
+ score += bucketPoints(s.filesTouched, BUCKETS.filesTouched, t.filesTouched);
138
+ score += bucketPoints(s.modulesTouched, BUCKETS.modulesTouched, t.modulesTouched);
139
+ score += bucketPoints(s.affectedTests, BUCKETS.affectedTests, t.affectedTests);
140
+ score += bucketPoints(s.blastRadiusNodes, BUCKETS.blastRadiusNodes, t.blastRadiusNodes);
141
+ if (s.touchesPublicApi)
142
+ score += t.publicApi;
143
+ if (s.touchesGlobalFile)
144
+ score += t.globalFile;
145
+ if (s.maxHotspotScore >= t.hotspotFloor)
146
+ score += t.hotspot;
147
+ return score;
148
+ }
149
+ export function levelFromScore(score, cuts = DEFAULT_THRESHOLDS.cuts) {
150
+ if (score < cuts[0])
151
+ return 0;
152
+ if (score < cuts[1])
153
+ return 1;
154
+ if (score < cuts[2])
155
+ return 2;
156
+ return 3;
157
+ }
158
+ export function explain(s, t, score, level) {
159
+ const parts = [
160
+ `${s.filesTouched} file(s)`,
161
+ `${s.modulesTouched} module(s)`,
162
+ `${s.affectedTests} affected test(s)`,
163
+ `${s.blastRadiusNodes} blast node(s)`,
164
+ s.touchesPublicApi ? "public API" : "no public API",
165
+ s.touchesGlobalFile ? "global file" : "no global file",
166
+ `hotspot=${s.maxHotspotScore.toFixed(2)}`,
167
+ ];
168
+ if (s.onlyDocs)
169
+ parts.push("docs-only");
170
+ if (s.degraded.length)
171
+ parts.push(`degraded:[${s.degraded.join(",")}]`);
172
+ const lvl = level === null ? "none" : String(level);
173
+ return `${parts.join(", ")} → score ${score} → level ${lvl} (cuts ${t.cuts.join("/")})`;
174
+ }
175
+ export function proposeLevel(s, t = DEFAULT_THRESHOLDS) {
176
+ if (s.degraded.includes("no-index") && s.filesTouched === 0 && s.blastRadiusNodes === 0) {
177
+ return {
178
+ level: null,
179
+ score: 0,
180
+ signals: s,
181
+ rationale: explain(s, t, 0, null),
182
+ degraded: s.degraded,
183
+ };
184
+ }
185
+ if (s.filesTouched === 0 &&
186
+ s.blastRadiusNodes === 0 &&
187
+ s.degraded.includes("unresolved-symbols")) {
188
+ return {
189
+ level: null,
190
+ score: 0,
191
+ signals: s,
192
+ rationale: explain(s, t, 0, null),
193
+ degraded: s.degraded,
194
+ };
195
+ }
196
+ const score = scoreSignals(s, t);
197
+ const level = levelFromScore(score, t.cuts);
198
+ return {
199
+ level,
200
+ score,
201
+ signals: s,
202
+ rationale: explain(s, t, score, level),
203
+ degraded: s.degraded,
204
+ };
205
+ }
206
+ function isSpecPath(rel) {
207
+ const n = rel.split("\\").join("/");
208
+ return n.startsWith("lawbook/specs/") || n.includes("/lawbook/specs/");
209
+ }
210
+ /** Resolve modules for paths using configured roots / inferModule. */
211
+ export function countModules(paths) {
212
+ const mods = new Set(paths.map((p) => inferModule(p.split("\\").join("/")) || p.split("/")[0] || p));
213
+ return mods.size;
214
+ }
215
+ /**
216
+ * Build signals from an explicit target list. When the Compass index is missing,
217
+ * marks `no-index` and does not invent a small blast radius.
218
+ */
219
+ export function gatherSignals(projectPath, targets, t = DEFAULT_THRESHOLDS) {
220
+ const degraded = [];
221
+ const paths = new Set(targets.paths.map((p) => p.replace(/^\.\//, "").split("\\").join("/")));
222
+ if (!indexExists(projectPath)) {
223
+ degraded.push("no-index");
224
+ }
225
+ else {
226
+ for (const sym of targets.symbols) {
227
+ const ex = explore(projectPath, sym);
228
+ if (ex.found && ex.symbol?.file)
229
+ paths.add(ex.symbol.file.split("\\").join("/"));
230
+ else
231
+ degraded.push("unresolved-symbols");
232
+ }
233
+ }
234
+ const pathList = [...paths];
235
+ const onlyDocs = pathList.length > 0 &&
236
+ pathList.every((p) => matchesAny(p, t.docGlobs)) &&
237
+ !pathList.some(isSpecPath);
238
+ let touchesGlobalFile = pathList.some((p) => matchesAny(p, t.globalGlobs));
239
+ try {
240
+ const cfg = loadAffectedConfig(projectPath);
241
+ if (pathList.some((p) => cfg.globalFiles.some((g) => matchGlob(p, g)))) {
242
+ touchesGlobalFile = true;
243
+ }
244
+ }
245
+ catch {
246
+ /* soft */
247
+ }
248
+ let blastRadiusNodes = 0;
249
+ let affected = 0;
250
+ let touchesPublicApi = false;
251
+ let maxHotspotScore = 0;
252
+ if (indexExists(projectPath) && pathList.length > 0) {
253
+ try {
254
+ const imp = impact(projectPath, { files: pathList, format: "grouped", maxDepth: 4 });
255
+ blastRadiusNodes = imp.totals.nodes;
256
+ if (imp.global)
257
+ touchesGlobalFile = true;
258
+ }
259
+ catch {
260
+ /* soft */
261
+ }
262
+ try {
263
+ const at = affectedTests(projectPath, { files: pathList });
264
+ affected = at.mode === "all" ? Math.max(at.tests.length, 50) : at.tests.length;
265
+ }
266
+ catch {
267
+ /* soft */
268
+ }
269
+ try {
270
+ const pkgPath = path.join(projectPath, "package.json");
271
+ if (fs.existsSync(pkgPath)) {
272
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
273
+ const entries = new Set();
274
+ if (typeof pkg.main === "string")
275
+ entries.add(pkg.main.replace(/^\.\//, ""));
276
+ if (typeof pkg.bin === "string")
277
+ entries.add(pkg.bin.replace(/^\.\//, ""));
278
+ else if (pkg.bin && typeof pkg.bin === "object") {
279
+ for (const v of Object.values(pkg.bin))
280
+ entries.add(String(v).replace(/^\.\//, ""));
281
+ }
282
+ for (const e of entries) {
283
+ if (pathList.some((p) => p === e || e.endsWith(p) || p.endsWith(e))) {
284
+ touchesPublicApi = true;
285
+ }
286
+ }
287
+ if (pathList.some((p) => p === "src/cli/index.ts" || p === "src/server.ts")) {
288
+ touchesPublicApi = true;
289
+ }
290
+ }
291
+ }
292
+ catch {
293
+ /* soft */
294
+ }
295
+ try {
296
+ const hs = hotspots(projectPath, { days: 90, sortBy: "combined", limit: 200 });
297
+ const byFile = new Map(hs.hotspots.map((h) => [h.file, h.combinedScore]));
298
+ let maxCombined = 0;
299
+ for (const h of hs.hotspots)
300
+ maxCombined = Math.max(maxCombined, h.combinedScore);
301
+ if (maxCombined <= 0)
302
+ degraded.push("no-hotspots");
303
+ else {
304
+ for (const p of pathList) {
305
+ const c = byFile.get(p) ?? 0;
306
+ maxHotspotScore = Math.max(maxHotspotScore, c / maxCombined);
307
+ }
308
+ }
309
+ }
310
+ catch {
311
+ degraded.push("no-hotspots");
312
+ }
313
+ }
314
+ return {
315
+ filesTouched: pathList.length,
316
+ modulesTouched: pathList.length ? countModules(pathList) : 0,
317
+ blastRadiusNodes,
318
+ affectedTests: affected,
319
+ touchesPublicApi,
320
+ maxHotspotScore,
321
+ touchesGlobalFile,
322
+ onlyDocs,
323
+ degraded: [...new Set(degraded)],
324
+ };
325
+ }
326
+ /** Load ceremony thresholds from lawbook/config.yaml (line-oriented). */
327
+ export function loadCeremonyConfig(projectPath) {
328
+ const thresholds = structuredClone(DEFAULT_THRESHOLDS);
329
+ const cfgPath = path.join(projectPath, "lawbook", "config.yaml");
330
+ if (!fs.existsSync(cfgPath))
331
+ return { thresholds, invalidCuts: false };
332
+ const text = fs.readFileSync(cfgPath, "utf8");
333
+ const cuts = /^\s*cuts\s*:\s*\[([^\]]*)\]\s*$/im.exec(text);
334
+ let invalidCuts = false;
335
+ if (cuts) {
336
+ const nums = cuts[1]
337
+ .split(",")
338
+ .map((s) => Number(s.trim()))
339
+ .filter((n) => Number.isFinite(n));
340
+ if (nums.length === 3 && nums[0] < nums[1] && nums[1] < nums[2]) {
341
+ thresholds.cuts = [nums[0], nums[1], nums[2]];
342
+ }
343
+ else {
344
+ invalidCuts = true;
345
+ }
346
+ }
347
+ const floor = /^\s*hotspotFloor\s*:\s*([0-9.]+)\s*$/im.exec(text);
348
+ if (floor)
349
+ thresholds.hotspotFloor = Number(floor[1]);
350
+ return { thresholds, invalidCuts };
351
+ }
352
+ export function changeJsonPath(projectPath, change) {
353
+ return path.join(projectPath, "lawbook", "changes", change, "change.json");
354
+ }
355
+ export function readCeremonyRecord(projectPath, change) {
356
+ const p = changeJsonPath(projectPath, change);
357
+ if (!fs.existsSync(p))
358
+ return null;
359
+ try {
360
+ return JSON.parse(fs.readFileSync(p, "utf8"));
361
+ }
362
+ catch {
363
+ return null;
364
+ }
365
+ }
366
+ /** Confirmed level, or 3 when change.json is missing. */
367
+ export function confirmedLevel(projectPath, change) {
368
+ return readCeremonyRecord(projectPath, change)?.confirmedLevel ?? 3;
369
+ }
370
+ export function writeCeremonyRecord(projectPath, change, record) {
371
+ const p = changeJsonPath(projectPath, change);
372
+ fs.mkdirSync(path.dirname(p), { recursive: true });
373
+ fs.writeFileSync(p, JSON.stringify(record, null, 2) + "\n");
374
+ }
375
+ export function setCeremonyLevel(projectPath, change, opts) {
376
+ const proposed = opts.proposal.level;
377
+ if (proposed !== null && opts.level < proposed && !opts.reason) {
378
+ throw new Error(`mode 'set' to a lower level than proposed (${proposed}) requires 'reason'`);
379
+ }
380
+ const prev = readCeremonyRecord(projectPath, change);
381
+ const record = {
382
+ ...opts.proposal,
383
+ confirmedLevel: opts.level,
384
+ confirmedBy: opts.confirmedBy,
385
+ confirmedAt: new Date().toISOString(),
386
+ overrideReason: opts.reason,
387
+ promotions: prev?.promotions ?? [],
388
+ };
389
+ writeCeremonyRecord(projectPath, change, record);
390
+ return record;
391
+ }
392
+ export function promoteCeremonyLevel(projectPath, change, to, reason) {
393
+ const prev = readCeremonyRecord(projectPath, change);
394
+ if (!prev)
395
+ throw new Error(`change "${change}" has no change.json to promote`);
396
+ if (to <= prev.confirmedLevel) {
397
+ throw new Error(`promote requires a higher level than ${prev.confirmedLevel}`);
398
+ }
399
+ const record = {
400
+ ...prev,
401
+ confirmedLevel: to,
402
+ confirmedAt: new Date().toISOString(),
403
+ promotions: [
404
+ ...prev.promotions,
405
+ { from: prev.confirmedLevel, to, at: new Date().toISOString(), reason },
406
+ ],
407
+ };
408
+ writeCeremonyRecord(projectPath, change, record);
409
+ scaffoldArtifactsForLevel(projectPath, change, to);
410
+ return record;
411
+ }
412
+ /**
413
+ * Create missing higher-level artifacts when promoting. Never deletes `record.md`.
414
+ * Seeds `proposal.md` / `tasks.md` from `record.md` when present.
415
+ */
416
+ export function scaffoldArtifactsForLevel(projectPath, change, level) {
417
+ const changeDir = path.join(projectPath, "lawbook", "changes", change);
418
+ if (!fs.existsSync(changeDir))
419
+ return;
420
+ const needs = artifactNeeds(level, readChangeType(projectPath, change));
421
+ const recordPath = path.join(changeDir, "record.md");
422
+ const recordText = fs.existsSync(recordPath) ? fs.readFileSync(recordPath, "utf8") : "";
423
+ const ensure = (rel, content) => {
424
+ const abs = path.join(changeDir, rel);
425
+ if (!fs.existsSync(abs)) {
426
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
427
+ fs.writeFileSync(abs, content);
428
+ }
429
+ };
430
+ if (needs.proposal) {
431
+ ensure("proposal.md", `# ${change}\n\n## Why\n\n${extractWhy(recordText) || "(promoted — fill in why)"}\n\n## What\n\n(promoted from level ${level})\n`);
432
+ }
433
+ if (needs.design && !needs.designOptionalWithJustification) {
434
+ ensure("design.md", `# Design — ${change}\n\n## Approach\n\n(promoted — fill in)\n`);
435
+ }
436
+ if (needs.tasksFile) {
437
+ const steps = extractChecklist(recordText);
438
+ ensure("tasks.md", steps.length
439
+ ? steps.map((s) => `- [ ] ${s}`).join("\n") + "\n"
440
+ : `- [ ] Implement\n- [ ] Add or update tests\n- [ ] Write discipline report under reports/\n`);
441
+ }
442
+ ensure("reports/README.md", `# Reports — ${change}\n\nAdd at least one discipline report before archive.\n`);
443
+ }
444
+ function extractWhy(recordMd) {
445
+ const m = /\*\*Why:\*\*\s*(.+)/i.exec(recordMd);
446
+ return m?.[1]?.trim() ?? "";
447
+ }
448
+ function extractChecklist(recordMd) {
449
+ const out = [];
450
+ for (const line of recordMd.split("\n")) {
451
+ const m = /^\s*[-*]\s+\[[ xX]\]\s+(.+)$/.exec(line);
452
+ if (m)
453
+ out.push(m[1].trim());
454
+ }
455
+ return out;
456
+ }
457
+ /** Count unchecked `- [ ]` tasks in markdown (tasks.md or record.md Steps). */
458
+ export function countUncheckedTasks(markdown) {
459
+ return (markdown.match(/^\s*[-*]\s+\[ \]/gm) ?? []).length;
460
+ }
461
+ export function hasDisciplineReport(changeDir) {
462
+ const reportsDir = path.join(changeDir, "reports");
463
+ if (!fs.existsSync(reportsDir))
464
+ return false;
465
+ return fs
466
+ .readdirSync(reportsDir)
467
+ .some((n) => n.endsWith(".md") && n.toLowerCase() !== "readme.md");
468
+ }
@@ -0,0 +1,86 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { gatherSignals, loadCeremonyConfig, promoteCeremonyLevel, proposeLevel, setCeremonyLevel, } from "./levels.js";
4
+ /**
5
+ * Scaffold a level-0 change: `record.md`, `change.json`, and `reports/`.
6
+ *
7
+ * @param projectPath - Project root with `lawbook/`.
8
+ * @param name - Change folder name (kebab-case).
9
+ * @param targets - Optional paths/symbols used to propose the level (default empty → score 0).
10
+ */
11
+ export function scaffoldQuick(projectPath, name, targets = { paths: [], symbols: [] }) {
12
+ const changeDir = path.join(projectPath, "lawbook", "changes", name);
13
+ if (fs.existsSync(changeDir)) {
14
+ throw new Error(`change "${name}" already exists under lawbook/changes/`);
15
+ }
16
+ const { thresholds } = loadCeremonyConfig(projectPath);
17
+ const signals = gatherSignals(projectPath, targets, thresholds);
18
+ const proposal = proposeLevel(signals, thresholds);
19
+ // quick always records level 0; if measurement says higher, still allow but note it.
20
+ const level = 0;
21
+ fs.mkdirSync(path.join(changeDir, "reports"), { recursive: true });
22
+ const rationale = proposal.level === null
23
+ ? proposal.rationale
24
+ : proposal.level > 0
25
+ ? `${proposal.rationale} — quick forced level 0; promote if scope grows`
26
+ : proposal.rationale;
27
+ const recordMd = `# ${name}
28
+
29
+ **Level:** 0 (proposed: ${proposal.level ?? "n/a"}, confirmed by: human)
30
+ **Why:** ${rationale}
31
+
32
+ ## What changes
33
+
34
+ <!-- 2–5 lines: what and why. -->
35
+
36
+ ## Steps
37
+
38
+ - [ ] Make the fix
39
+ - [ ] Add or update a regression test
40
+ - [ ] Record evidence under reports/
41
+
42
+ ## Evidence
43
+
44
+ - \`reports/\` — add a discipline report before archive
45
+ `;
46
+ fs.writeFileSync(path.join(changeDir, "record.md"), recordMd);
47
+ fs.writeFileSync(path.join(changeDir, "reports", "README.md"), `# Reports — ${name}\n\nAdd at least one discipline report before archive.\n`);
48
+ const record = setCeremonyLevel(projectPath, name, {
49
+ proposal: { ...proposal, rationale },
50
+ level,
51
+ confirmedBy: "human",
52
+ reason: proposal.level !== null && proposal.level > 0 ? "speclaw quick" : undefined,
53
+ });
54
+ return { change: name, proposal, record, dir: changeDir };
55
+ }
56
+ /**
57
+ * Handle `lawbook_level` modes: propose / set / promote / explain.
58
+ */
59
+ export function handleLevel(args) {
60
+ const targets = {
61
+ paths: args.paths ?? [],
62
+ symbols: args.symbols ?? [],
63
+ };
64
+ const { thresholds } = loadCeremonyConfig(args.projectPath);
65
+ const signals = gatherSignals(args.projectPath, targets, thresholds);
66
+ const proposal = proposeLevel(signals, thresholds);
67
+ if (args.mode === "propose" || args.mode === "explain") {
68
+ return { mode: args.mode, proposal };
69
+ }
70
+ if (!args.change)
71
+ throw new Error(`mode '${args.mode}' requires 'change'`);
72
+ if (args.mode === "set") {
73
+ if (args.level === undefined)
74
+ throw new Error("mode 'set' requires 'level'");
75
+ return setCeremonyLevel(args.projectPath, args.change, {
76
+ proposal,
77
+ level: args.level,
78
+ confirmedBy: "human",
79
+ reason: args.reason,
80
+ });
81
+ }
82
+ // promote
83
+ if (args.level === undefined)
84
+ throw new Error("mode 'promote' requires 'level'");
85
+ return promoteCeremonyLevel(args.projectPath, args.change, args.level, args.reason ?? "scope grew");
86
+ }
@@ -5,6 +5,8 @@ import { shouldExpose } from "../../shared/exposure.js";
5
5
  import { assetsDir } from "../../shared/paths.js";
6
6
  import { copyRendered } from "../../shared/install.js";
7
7
  import { specInit, specValidate, specSync, specArchive, specList } from "./engine.js";
8
+ import { handleLevel } from "./quick.js";
9
+ import { investigate, formatInvestigateResult } from "./investigate.js";
8
10
  import { buildCoverageReport, loadCoverageConfig, renderCoverageAgent } from "./coverage.js";
9
11
  import { buildDriftReport, renderDriftAgent } from "./drift.js";
10
12
  const ASSETS = assetsDir(import.meta.url);
@@ -29,6 +31,22 @@ export function registerSpec(server, opts = {}) {
29
31
  };
30
32
  add("lawbook_init", "Create the lawbook/ workspace (specs, changes, archive, config). Idempotent.", { projectPath: z.string() }, async ({ projectPath }) => text(specInit(projectPath)));
31
33
  add("lawbook_list", "List active changes, archives, and canonical capabilities under lawbook/.", { projectPath: z.string() }, async ({ projectPath }) => text(specList(projectPath)));
34
+ add("lawbook_level", "Propose, set, promote, or explain a change's ceremony level (0–3).", {
35
+ projectPath: z.string(),
36
+ mode: z.enum(["propose", "set", "promote", "explain"]),
37
+ change: z.string().optional(),
38
+ paths: z.array(z.string()).optional(),
39
+ symbols: z.array(z.string()).optional(),
40
+ level: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]).optional(),
41
+ reason: z.string().optional(),
42
+ }, async (args) => text(handleLevel(args)));
43
+ add("lawbook_investigate", "Rank bug origins from the graph. Pass stackTrace or symptom. Returns suspects with reasons — evidence, not a verdict.", {
44
+ projectPath: z.string(),
45
+ stackTrace: z.string().optional(),
46
+ symptom: z.string().optional(),
47
+ hintPaths: z.array(z.string()).optional(),
48
+ maxSuspects: z.number().int().min(1).max(25).optional(),
49
+ }, async (args) => text(formatInvestigateResult(await investigate(args))));
32
50
  add("lawbook_validate", "Validate a change's proposal, tasks, and delta specs before build or sync.", { projectPath: z.string(), change: z.string() }, async ({ projectPath, change }) => text(specValidate(projectPath, change)));
33
51
  add("lawbook_sync", "Promote a change's delta specs into canonical lawbook/specs/ without archiving.", { projectPath: z.string(), change: z.string() }, async ({ projectPath, change }) => text(specSync(projectPath, change)));
34
52
  add("lawbook_archive", "Sync a change into canonical specs, then move it under changes/archive/.", {