@esneiderbravo/speclaw 0.3.10 → 0.3.12
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.
- package/dist/cli/commands/lawbook.js +43 -6
- package/dist/cli/commands/query.js +49 -2
- package/dist/cli/commands/quick.js +35 -0
- package/dist/cli/commands/update.js +18 -0
- package/dist/cli/index.js +17 -3
- package/dist/modules/compass/db.js +15 -2
- package/dist/modules/compass/extract.js +44 -0
- package/dist/modules/compass/git-history-cache.js +19 -2
- package/dist/modules/compass/hotspots.js +230 -0
- package/dist/modules/compass/indexer.js +2 -0
- package/dist/modules/compass/languages.js +39 -0
- package/dist/modules/compass/register.js +17 -0
- package/dist/modules/foundation/doctor.js +63 -0
- package/dist/modules/lawbook/assets/commands/archive.md +5 -6
- package/dist/modules/lawbook/assets/commands/draft.md +6 -7
- package/dist/modules/lawbook/assets/commands/quick.md +14 -0
- package/dist/modules/lawbook/assets/skills/archive/steps/03-validate-and-sync.md +4 -3
- package/dist/modules/lawbook/assets/skills/draft/SKILL.md +1 -1
- package/dist/modules/lawbook/assets/skills/draft/steps/02-understand.md +3 -0
- package/dist/modules/lawbook/assets/skills/draft/steps/04-write-artifacts.md +28 -25
- package/dist/modules/lawbook/assets/skills/quick/SKILL.md +11 -0
- package/dist/modules/lawbook/assets/skills/quick/steps/01-scaffold.md +6 -0
- package/dist/modules/lawbook/assets/skills/quick/steps/02-implement.md +7 -0
- package/dist/modules/lawbook/engine.js +115 -55
- package/dist/modules/lawbook/levels.js +421 -0
- package/dist/modules/lawbook/quick.js +86 -0
- package/dist/modules/lawbook/register.js +10 -0
- package/dist/shared/exposure.js +3 -0
- package/dist/shared/git-history.js +85 -5
- package/package.json +1 -1
|
@@ -0,0 +1,421 @@
|
|
|
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) {
|
|
38
|
+
switch (level) {
|
|
39
|
+
case 0:
|
|
40
|
+
return {
|
|
41
|
+
record: true,
|
|
42
|
+
proposal: false,
|
|
43
|
+
design: false,
|
|
44
|
+
tasksFile: false,
|
|
45
|
+
deltaSpecs: false,
|
|
46
|
+
reports: true,
|
|
47
|
+
designOptionalWithJustification: false,
|
|
48
|
+
};
|
|
49
|
+
case 1:
|
|
50
|
+
return {
|
|
51
|
+
record: true,
|
|
52
|
+
proposal: false,
|
|
53
|
+
design: false,
|
|
54
|
+
tasksFile: true,
|
|
55
|
+
deltaSpecs: true,
|
|
56
|
+
reports: true,
|
|
57
|
+
designOptionalWithJustification: false,
|
|
58
|
+
};
|
|
59
|
+
case 2:
|
|
60
|
+
return {
|
|
61
|
+
record: false,
|
|
62
|
+
proposal: true,
|
|
63
|
+
design: false,
|
|
64
|
+
tasksFile: true,
|
|
65
|
+
deltaSpecs: true,
|
|
66
|
+
reports: true,
|
|
67
|
+
designOptionalWithJustification: true,
|
|
68
|
+
};
|
|
69
|
+
case 3:
|
|
70
|
+
return {
|
|
71
|
+
record: false,
|
|
72
|
+
proposal: true,
|
|
73
|
+
design: true,
|
|
74
|
+
tasksFile: true,
|
|
75
|
+
deltaSpecs: true,
|
|
76
|
+
reports: true,
|
|
77
|
+
designOptionalWithJustification: false,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function bucketPoints(value, edges, points) {
|
|
82
|
+
const i = edges.findIndex((max) => value <= max);
|
|
83
|
+
return points[i < 0 ? 3 : i];
|
|
84
|
+
}
|
|
85
|
+
/** Pure scoring; `onlyDocs` short-circuits to 0. */
|
|
86
|
+
export function scoreSignals(s, t = DEFAULT_THRESHOLDS) {
|
|
87
|
+
if (s.onlyDocs)
|
|
88
|
+
return 0;
|
|
89
|
+
let score = 0;
|
|
90
|
+
score += bucketPoints(s.filesTouched, BUCKETS.filesTouched, t.filesTouched);
|
|
91
|
+
score += bucketPoints(s.modulesTouched, BUCKETS.modulesTouched, t.modulesTouched);
|
|
92
|
+
score += bucketPoints(s.affectedTests, BUCKETS.affectedTests, t.affectedTests);
|
|
93
|
+
score += bucketPoints(s.blastRadiusNodes, BUCKETS.blastRadiusNodes, t.blastRadiusNodes);
|
|
94
|
+
if (s.touchesPublicApi)
|
|
95
|
+
score += t.publicApi;
|
|
96
|
+
if (s.touchesGlobalFile)
|
|
97
|
+
score += t.globalFile;
|
|
98
|
+
if (s.maxHotspotScore >= t.hotspotFloor)
|
|
99
|
+
score += t.hotspot;
|
|
100
|
+
return score;
|
|
101
|
+
}
|
|
102
|
+
export function levelFromScore(score, cuts = DEFAULT_THRESHOLDS.cuts) {
|
|
103
|
+
if (score < cuts[0])
|
|
104
|
+
return 0;
|
|
105
|
+
if (score < cuts[1])
|
|
106
|
+
return 1;
|
|
107
|
+
if (score < cuts[2])
|
|
108
|
+
return 2;
|
|
109
|
+
return 3;
|
|
110
|
+
}
|
|
111
|
+
export function explain(s, t, score, level) {
|
|
112
|
+
const parts = [
|
|
113
|
+
`${s.filesTouched} file(s)`,
|
|
114
|
+
`${s.modulesTouched} module(s)`,
|
|
115
|
+
`${s.affectedTests} affected test(s)`,
|
|
116
|
+
`${s.blastRadiusNodes} blast node(s)`,
|
|
117
|
+
s.touchesPublicApi ? "public API" : "no public API",
|
|
118
|
+
s.touchesGlobalFile ? "global file" : "no global file",
|
|
119
|
+
`hotspot=${s.maxHotspotScore.toFixed(2)}`,
|
|
120
|
+
];
|
|
121
|
+
if (s.onlyDocs)
|
|
122
|
+
parts.push("docs-only");
|
|
123
|
+
if (s.degraded.length)
|
|
124
|
+
parts.push(`degraded:[${s.degraded.join(",")}]`);
|
|
125
|
+
const lvl = level === null ? "none" : String(level);
|
|
126
|
+
return `${parts.join(", ")} → score ${score} → level ${lvl} (cuts ${t.cuts.join("/")})`;
|
|
127
|
+
}
|
|
128
|
+
export function proposeLevel(s, t = DEFAULT_THRESHOLDS) {
|
|
129
|
+
if (s.degraded.includes("no-index") && s.filesTouched === 0 && s.blastRadiusNodes === 0) {
|
|
130
|
+
return {
|
|
131
|
+
level: null,
|
|
132
|
+
score: 0,
|
|
133
|
+
signals: s,
|
|
134
|
+
rationale: explain(s, t, 0, null),
|
|
135
|
+
degraded: s.degraded,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
if (s.filesTouched === 0 &&
|
|
139
|
+
s.blastRadiusNodes === 0 &&
|
|
140
|
+
s.degraded.includes("unresolved-symbols")) {
|
|
141
|
+
return {
|
|
142
|
+
level: null,
|
|
143
|
+
score: 0,
|
|
144
|
+
signals: s,
|
|
145
|
+
rationale: explain(s, t, 0, null),
|
|
146
|
+
degraded: s.degraded,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const score = scoreSignals(s, t);
|
|
150
|
+
const level = levelFromScore(score, t.cuts);
|
|
151
|
+
return {
|
|
152
|
+
level,
|
|
153
|
+
score,
|
|
154
|
+
signals: s,
|
|
155
|
+
rationale: explain(s, t, score, level),
|
|
156
|
+
degraded: s.degraded,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function isSpecPath(rel) {
|
|
160
|
+
const n = rel.split("\\").join("/");
|
|
161
|
+
return n.startsWith("lawbook/specs/") || n.includes("/lawbook/specs/");
|
|
162
|
+
}
|
|
163
|
+
/** Resolve modules for paths using configured roots / inferModule. */
|
|
164
|
+
export function countModules(paths) {
|
|
165
|
+
const mods = new Set(paths.map((p) => inferModule(p.split("\\").join("/")) || p.split("/")[0] || p));
|
|
166
|
+
return mods.size;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Build signals from an explicit target list. When the Compass index is missing,
|
|
170
|
+
* marks `no-index` and does not invent a small blast radius.
|
|
171
|
+
*/
|
|
172
|
+
export function gatherSignals(projectPath, targets, t = DEFAULT_THRESHOLDS) {
|
|
173
|
+
const degraded = [];
|
|
174
|
+
const paths = new Set(targets.paths.map((p) => p.replace(/^\.\//, "").split("\\").join("/")));
|
|
175
|
+
if (!indexExists(projectPath)) {
|
|
176
|
+
degraded.push("no-index");
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
for (const sym of targets.symbols) {
|
|
180
|
+
const ex = explore(projectPath, sym);
|
|
181
|
+
if (ex.found && ex.symbol?.file)
|
|
182
|
+
paths.add(ex.symbol.file.split("\\").join("/"));
|
|
183
|
+
else
|
|
184
|
+
degraded.push("unresolved-symbols");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const pathList = [...paths];
|
|
188
|
+
const onlyDocs = pathList.length > 0 &&
|
|
189
|
+
pathList.every((p) => matchesAny(p, t.docGlobs)) &&
|
|
190
|
+
!pathList.some(isSpecPath);
|
|
191
|
+
let touchesGlobalFile = pathList.some((p) => matchesAny(p, t.globalGlobs));
|
|
192
|
+
try {
|
|
193
|
+
const cfg = loadAffectedConfig(projectPath);
|
|
194
|
+
if (pathList.some((p) => cfg.globalFiles.some((g) => matchGlob(p, g)))) {
|
|
195
|
+
touchesGlobalFile = true;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
/* soft */
|
|
200
|
+
}
|
|
201
|
+
let blastRadiusNodes = 0;
|
|
202
|
+
let affected = 0;
|
|
203
|
+
let touchesPublicApi = false;
|
|
204
|
+
let maxHotspotScore = 0;
|
|
205
|
+
if (indexExists(projectPath) && pathList.length > 0) {
|
|
206
|
+
try {
|
|
207
|
+
const imp = impact(projectPath, { files: pathList, format: "grouped", maxDepth: 4 });
|
|
208
|
+
blastRadiusNodes = imp.totals.nodes;
|
|
209
|
+
if (imp.global)
|
|
210
|
+
touchesGlobalFile = true;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
/* soft */
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
const at = affectedTests(projectPath, { files: pathList });
|
|
217
|
+
affected = at.mode === "all" ? Math.max(at.tests.length, 50) : at.tests.length;
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
/* soft */
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
const pkgPath = path.join(projectPath, "package.json");
|
|
224
|
+
if (fs.existsSync(pkgPath)) {
|
|
225
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
226
|
+
const entries = new Set();
|
|
227
|
+
if (typeof pkg.main === "string")
|
|
228
|
+
entries.add(pkg.main.replace(/^\.\//, ""));
|
|
229
|
+
if (typeof pkg.bin === "string")
|
|
230
|
+
entries.add(pkg.bin.replace(/^\.\//, ""));
|
|
231
|
+
else if (pkg.bin && typeof pkg.bin === "object") {
|
|
232
|
+
for (const v of Object.values(pkg.bin))
|
|
233
|
+
entries.add(String(v).replace(/^\.\//, ""));
|
|
234
|
+
}
|
|
235
|
+
for (const e of entries) {
|
|
236
|
+
if (pathList.some((p) => p === e || e.endsWith(p) || p.endsWith(e))) {
|
|
237
|
+
touchesPublicApi = true;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (pathList.some((p) => p === "src/cli/index.ts" || p === "src/server.ts")) {
|
|
241
|
+
touchesPublicApi = true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
/* soft */
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
const hs = hotspots(projectPath, { days: 90, sortBy: "combined", limit: 200 });
|
|
250
|
+
const byFile = new Map(hs.hotspots.map((h) => [h.file, h.combinedScore]));
|
|
251
|
+
let maxCombined = 0;
|
|
252
|
+
for (const h of hs.hotspots)
|
|
253
|
+
maxCombined = Math.max(maxCombined, h.combinedScore);
|
|
254
|
+
if (maxCombined <= 0)
|
|
255
|
+
degraded.push("no-hotspots");
|
|
256
|
+
else {
|
|
257
|
+
for (const p of pathList) {
|
|
258
|
+
const c = byFile.get(p) ?? 0;
|
|
259
|
+
maxHotspotScore = Math.max(maxHotspotScore, c / maxCombined);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
degraded.push("no-hotspots");
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
filesTouched: pathList.length,
|
|
269
|
+
modulesTouched: pathList.length ? countModules(pathList) : 0,
|
|
270
|
+
blastRadiusNodes,
|
|
271
|
+
affectedTests: affected,
|
|
272
|
+
touchesPublicApi,
|
|
273
|
+
maxHotspotScore,
|
|
274
|
+
touchesGlobalFile,
|
|
275
|
+
onlyDocs,
|
|
276
|
+
degraded: [...new Set(degraded)],
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/** Load ceremony thresholds from lawbook/config.yaml (line-oriented). */
|
|
280
|
+
export function loadCeremonyConfig(projectPath) {
|
|
281
|
+
const thresholds = structuredClone(DEFAULT_THRESHOLDS);
|
|
282
|
+
const cfgPath = path.join(projectPath, "lawbook", "config.yaml");
|
|
283
|
+
if (!fs.existsSync(cfgPath))
|
|
284
|
+
return { thresholds, invalidCuts: false };
|
|
285
|
+
const text = fs.readFileSync(cfgPath, "utf8");
|
|
286
|
+
const cuts = /^\s*cuts\s*:\s*\[([^\]]*)\]\s*$/im.exec(text);
|
|
287
|
+
let invalidCuts = false;
|
|
288
|
+
if (cuts) {
|
|
289
|
+
const nums = cuts[1]
|
|
290
|
+
.split(",")
|
|
291
|
+
.map((s) => Number(s.trim()))
|
|
292
|
+
.filter((n) => Number.isFinite(n));
|
|
293
|
+
if (nums.length === 3 && nums[0] < nums[1] && nums[1] < nums[2]) {
|
|
294
|
+
thresholds.cuts = [nums[0], nums[1], nums[2]];
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
invalidCuts = true;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const floor = /^\s*hotspotFloor\s*:\s*([0-9.]+)\s*$/im.exec(text);
|
|
301
|
+
if (floor)
|
|
302
|
+
thresholds.hotspotFloor = Number(floor[1]);
|
|
303
|
+
return { thresholds, invalidCuts };
|
|
304
|
+
}
|
|
305
|
+
export function changeJsonPath(projectPath, change) {
|
|
306
|
+
return path.join(projectPath, "lawbook", "changes", change, "change.json");
|
|
307
|
+
}
|
|
308
|
+
export function readCeremonyRecord(projectPath, change) {
|
|
309
|
+
const p = changeJsonPath(projectPath, change);
|
|
310
|
+
if (!fs.existsSync(p))
|
|
311
|
+
return null;
|
|
312
|
+
try {
|
|
313
|
+
return JSON.parse(fs.readFileSync(p, "utf8"));
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/** Confirmed level, or 3 when change.json is missing. */
|
|
320
|
+
export function confirmedLevel(projectPath, change) {
|
|
321
|
+
return readCeremonyRecord(projectPath, change)?.confirmedLevel ?? 3;
|
|
322
|
+
}
|
|
323
|
+
export function writeCeremonyRecord(projectPath, change, record) {
|
|
324
|
+
const p = changeJsonPath(projectPath, change);
|
|
325
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
326
|
+
fs.writeFileSync(p, JSON.stringify(record, null, 2) + "\n");
|
|
327
|
+
}
|
|
328
|
+
export function setCeremonyLevel(projectPath, change, opts) {
|
|
329
|
+
const proposed = opts.proposal.level;
|
|
330
|
+
if (proposed !== null && opts.level < proposed && !opts.reason) {
|
|
331
|
+
throw new Error(`mode 'set' to a lower level than proposed (${proposed}) requires 'reason'`);
|
|
332
|
+
}
|
|
333
|
+
const prev = readCeremonyRecord(projectPath, change);
|
|
334
|
+
const record = {
|
|
335
|
+
...opts.proposal,
|
|
336
|
+
confirmedLevel: opts.level,
|
|
337
|
+
confirmedBy: opts.confirmedBy,
|
|
338
|
+
confirmedAt: new Date().toISOString(),
|
|
339
|
+
overrideReason: opts.reason,
|
|
340
|
+
promotions: prev?.promotions ?? [],
|
|
341
|
+
};
|
|
342
|
+
writeCeremonyRecord(projectPath, change, record);
|
|
343
|
+
return record;
|
|
344
|
+
}
|
|
345
|
+
export function promoteCeremonyLevel(projectPath, change, to, reason) {
|
|
346
|
+
const prev = readCeremonyRecord(projectPath, change);
|
|
347
|
+
if (!prev)
|
|
348
|
+
throw new Error(`change "${change}" has no change.json to promote`);
|
|
349
|
+
if (to <= prev.confirmedLevel) {
|
|
350
|
+
throw new Error(`promote requires a higher level than ${prev.confirmedLevel}`);
|
|
351
|
+
}
|
|
352
|
+
const record = {
|
|
353
|
+
...prev,
|
|
354
|
+
confirmedLevel: to,
|
|
355
|
+
confirmedAt: new Date().toISOString(),
|
|
356
|
+
promotions: [
|
|
357
|
+
...prev.promotions,
|
|
358
|
+
{ from: prev.confirmedLevel, to, at: new Date().toISOString(), reason },
|
|
359
|
+
],
|
|
360
|
+
};
|
|
361
|
+
writeCeremonyRecord(projectPath, change, record);
|
|
362
|
+
scaffoldArtifactsForLevel(projectPath, change, to);
|
|
363
|
+
return record;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Create missing higher-level artifacts when promoting. Never deletes `record.md`.
|
|
367
|
+
* Seeds `proposal.md` / `tasks.md` from `record.md` when present.
|
|
368
|
+
*/
|
|
369
|
+
export function scaffoldArtifactsForLevel(projectPath, change, level) {
|
|
370
|
+
const changeDir = path.join(projectPath, "lawbook", "changes", change);
|
|
371
|
+
if (!fs.existsSync(changeDir))
|
|
372
|
+
return;
|
|
373
|
+
const needs = artifactNeeds(level);
|
|
374
|
+
const recordPath = path.join(changeDir, "record.md");
|
|
375
|
+
const recordText = fs.existsSync(recordPath) ? fs.readFileSync(recordPath, "utf8") : "";
|
|
376
|
+
const ensure = (rel, content) => {
|
|
377
|
+
const abs = path.join(changeDir, rel);
|
|
378
|
+
if (!fs.existsSync(abs)) {
|
|
379
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
380
|
+
fs.writeFileSync(abs, content);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
if (needs.proposal) {
|
|
384
|
+
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`);
|
|
385
|
+
}
|
|
386
|
+
if (needs.design && !needs.designOptionalWithJustification) {
|
|
387
|
+
ensure("design.md", `# Design — ${change}\n\n## Approach\n\n(promoted — fill in)\n`);
|
|
388
|
+
}
|
|
389
|
+
if (needs.tasksFile) {
|
|
390
|
+
const steps = extractChecklist(recordText);
|
|
391
|
+
ensure("tasks.md", steps.length
|
|
392
|
+
? steps.map((s) => `- [ ] ${s}`).join("\n") + "\n"
|
|
393
|
+
: `- [ ] Implement\n- [ ] Add or update tests\n- [ ] Write discipline report under reports/\n`);
|
|
394
|
+
}
|
|
395
|
+
ensure("reports/README.md", `# Reports — ${change}\n\nAdd at least one discipline report before archive.\n`);
|
|
396
|
+
}
|
|
397
|
+
function extractWhy(recordMd) {
|
|
398
|
+
const m = /\*\*Why:\*\*\s*(.+)/i.exec(recordMd);
|
|
399
|
+
return m?.[1]?.trim() ?? "";
|
|
400
|
+
}
|
|
401
|
+
function extractChecklist(recordMd) {
|
|
402
|
+
const out = [];
|
|
403
|
+
for (const line of recordMd.split("\n")) {
|
|
404
|
+
const m = /^\s*[-*]\s+\[[ xX]\]\s+(.+)$/.exec(line);
|
|
405
|
+
if (m)
|
|
406
|
+
out.push(m[1].trim());
|
|
407
|
+
}
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
/** Count unchecked `- [ ]` tasks in markdown (tasks.md or record.md Steps). */
|
|
411
|
+
export function countUncheckedTasks(markdown) {
|
|
412
|
+
return (markdown.match(/^\s*[-*]\s+\[ \]/gm) ?? []).length;
|
|
413
|
+
}
|
|
414
|
+
export function hasDisciplineReport(changeDir) {
|
|
415
|
+
const reportsDir = path.join(changeDir, "reports");
|
|
416
|
+
if (!fs.existsSync(reportsDir))
|
|
417
|
+
return false;
|
|
418
|
+
return fs
|
|
419
|
+
.readdirSync(reportsDir)
|
|
420
|
+
.some((n) => n.endsWith(".md") && n.toLowerCase() !== "readme.md");
|
|
421
|
+
}
|
|
@@ -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,7 @@ 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";
|
|
8
9
|
import { buildCoverageReport, loadCoverageConfig, renderCoverageAgent } from "./coverage.js";
|
|
9
10
|
import { buildDriftReport, renderDriftAgent } from "./drift.js";
|
|
10
11
|
const ASSETS = assetsDir(import.meta.url);
|
|
@@ -29,6 +30,15 @@ export function registerSpec(server, opts = {}) {
|
|
|
29
30
|
};
|
|
30
31
|
add("lawbook_init", "Create the lawbook/ workspace (specs, changes, archive, config). Idempotent.", { projectPath: z.string() }, async ({ projectPath }) => text(specInit(projectPath)));
|
|
31
32
|
add("lawbook_list", "List active changes, archives, and canonical capabilities under lawbook/.", { projectPath: z.string() }, async ({ projectPath }) => text(specList(projectPath)));
|
|
33
|
+
add("lawbook_level", "Propose, set, promote, or explain a change's ceremony level (0–3).", {
|
|
34
|
+
projectPath: z.string(),
|
|
35
|
+
mode: z.enum(["propose", "set", "promote", "explain"]),
|
|
36
|
+
change: z.string().optional(),
|
|
37
|
+
paths: z.array(z.string()).optional(),
|
|
38
|
+
symbols: z.array(z.string()).optional(),
|
|
39
|
+
level: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]).optional(),
|
|
40
|
+
reason: z.string().optional(),
|
|
41
|
+
}, async (args) => text(handleLevel(args)));
|
|
32
42
|
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
43
|
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
44
|
add("lawbook_archive", "Sync a change into canonical specs, then move it under changes/archive/.", {
|
package/dist/shared/exposure.js
CHANGED
|
@@ -12,11 +12,14 @@ export const MINIMAL_OMIT = new Set([
|
|
|
12
12
|
"compass_watch",
|
|
13
13
|
"compass_impact",
|
|
14
14
|
"compass_affected_tests",
|
|
15
|
+
"compass_hotspots",
|
|
16
|
+
"compass_coupling",
|
|
15
17
|
"compass_trace",
|
|
16
18
|
"compass_visualize",
|
|
17
19
|
"lawbook_init",
|
|
18
20
|
"lawbook_archive",
|
|
19
21
|
"lawbook_list",
|
|
22
|
+
"lawbook_level",
|
|
20
23
|
"init_project",
|
|
21
24
|
"scaffold",
|
|
22
25
|
"configure_agent",
|
|
@@ -144,34 +144,114 @@ export function churn(projectPath, opts = {}) {
|
|
|
144
144
|
}
|
|
145
145
|
return { shallow, byPath };
|
|
146
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* Richer per-file activity (commits, lines added/deleted, distinct authors).
|
|
149
|
+
*
|
|
150
|
+
* Fail-soft and shallow-aware like {@link churn}. Does not follow renames.
|
|
151
|
+
* Suitable for hotspot ranking; existing {@link churn} callers stay on commit counts.
|
|
152
|
+
*
|
|
153
|
+
* @param projectPath - Project root to query.
|
|
154
|
+
* @param opts - Optional `since` window and `pathspec` filter.
|
|
155
|
+
*/
|
|
156
|
+
export function fileActivity(projectPath, opts = {}) {
|
|
157
|
+
const shallow = isShallowRepo(projectPath);
|
|
158
|
+
// Per commit: \0<author>\0 then numstat lines until the next leading NUL.
|
|
159
|
+
const args = ["log", "--numstat", "--format=%x00%an%x00"];
|
|
160
|
+
if (opts.since)
|
|
161
|
+
args.push(`--since=${opts.since}`);
|
|
162
|
+
if (opts.pathspec && opts.pathspec.length > 0)
|
|
163
|
+
args.push("--", ...opts.pathspec);
|
|
164
|
+
const out = git(projectPath, args);
|
|
165
|
+
const byPath = new Map();
|
|
166
|
+
const authorsByPath = new Map();
|
|
167
|
+
if (out === null)
|
|
168
|
+
return { shallow, byPath };
|
|
169
|
+
const records = out.split(NUL);
|
|
170
|
+
for (let i = 1; i + 1 < records.length; i += 2) {
|
|
171
|
+
const author = (records[i] ?? "").trim();
|
|
172
|
+
const tail = records[i + 1] ?? "";
|
|
173
|
+
if (!author && !tail.trim())
|
|
174
|
+
continue;
|
|
175
|
+
for (const line of tail.split("\n")) {
|
|
176
|
+
const cols = line.split("\t");
|
|
177
|
+
if (cols.length < 3)
|
|
178
|
+
continue;
|
|
179
|
+
const path = cols[2].replace(/^\0+/, "").trim();
|
|
180
|
+
if (!path)
|
|
181
|
+
continue;
|
|
182
|
+
const added = numstat(cols[0]);
|
|
183
|
+
const deleted = numstat(cols[1]);
|
|
184
|
+
const cur = byPath.get(path) ?? { commits: 0, linesAdded: 0, linesDeleted: 0, authors: 0 };
|
|
185
|
+
cur.commits += 1;
|
|
186
|
+
cur.linesAdded += added;
|
|
187
|
+
cur.linesDeleted += deleted;
|
|
188
|
+
byPath.set(path, cur);
|
|
189
|
+
if (author) {
|
|
190
|
+
let set = authorsByPath.get(path);
|
|
191
|
+
if (!set) {
|
|
192
|
+
set = new Set();
|
|
193
|
+
authorsByPath.set(path, set);
|
|
194
|
+
}
|
|
195
|
+
set.add(author);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
for (const [path, act] of byPath) {
|
|
200
|
+
act.authors = authorsByPath.get(path)?.size ?? 0;
|
|
201
|
+
}
|
|
202
|
+
return { shallow, byPath };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Jaccard-style coupling strength: `both / (commitsA + commitsB - both)`.
|
|
206
|
+
* Returns `0` when the denominator is zero.
|
|
207
|
+
*/
|
|
208
|
+
export function jaccardStrength(both, commitsA, commitsB) {
|
|
209
|
+
const denom = commitsA + commitsB - both;
|
|
210
|
+
if (denom <= 0)
|
|
211
|
+
return 0;
|
|
212
|
+
return both / denom;
|
|
213
|
+
}
|
|
147
214
|
/**
|
|
148
215
|
* For every pair of files that changed together, how many commits touched both.
|
|
149
216
|
*
|
|
150
217
|
* Groups each commit's changed files and emits a count per unordered pair. Pairs
|
|
151
|
-
* with fewer than `minSupport` shared commits are omitted.
|
|
152
|
-
*
|
|
218
|
+
* with fewer than `minSupport` shared commits are omitted. Commits that touch
|
|
219
|
+
* more than `maxFilesPerCommit` files (when set) are skipped and counted in
|
|
220
|
+
* `skippedTooLarge`. Fail-soft (empty on git failure) and does not follow
|
|
221
|
+
* renames. Carries the shallow marker.
|
|
153
222
|
*
|
|
154
223
|
* @param projectPath - Project root to query.
|
|
155
|
-
* @param opts - Optional `since` window
|
|
224
|
+
* @param opts - Optional `since` window, `minSupport` (default `1`), and
|
|
225
|
+
* `maxFilesPerCommit` (omit to keep all commits).
|
|
156
226
|
* @returns The qualifying co-change pairs and the shallow marker.
|
|
157
227
|
*/
|
|
158
228
|
export function coChanges(projectPath, opts = {}) {
|
|
159
229
|
const shallow = isShallowRepo(projectPath);
|
|
160
230
|
const minSupport = opts.minSupport ?? 1;
|
|
231
|
+
const maxFiles = opts.maxFilesPerCommit;
|
|
161
232
|
const args = ["log", "--name-only", "--format=%x00"];
|
|
162
233
|
if (opts.since)
|
|
163
234
|
args.push(`--since=${opts.since}`);
|
|
164
235
|
const out = git(projectPath, args);
|
|
165
236
|
if (out === null)
|
|
166
|
-
return { shallow, pairs: [] };
|
|
237
|
+
return { shallow, pairs: [], skippedTooLarge: 0, commitsScanned: 0 };
|
|
167
238
|
const counts = new Map();
|
|
239
|
+
let skippedTooLarge = 0;
|
|
240
|
+
let commitsScanned = 0;
|
|
168
241
|
// Each commit's file list is the run of lines between two %x00 markers.
|
|
169
242
|
for (const commitBlock of out.split(NUL)) {
|
|
170
243
|
const files = commitBlock
|
|
171
244
|
.split("\n")
|
|
172
245
|
.map((l) => l.trim())
|
|
173
246
|
.filter((l) => l.length > 0);
|
|
247
|
+
if (files.length === 0)
|
|
248
|
+
continue;
|
|
174
249
|
const unique = [...new Set(files)].sort();
|
|
250
|
+
if (maxFiles !== undefined && unique.length > maxFiles) {
|
|
251
|
+
skippedTooLarge++;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
commitsScanned++;
|
|
175
255
|
for (let i = 0; i < unique.length; i++) {
|
|
176
256
|
for (let j = i + 1; j < unique.length; j++) {
|
|
177
257
|
const key = `${unique[i]}\t${unique[j]}`;
|
|
@@ -187,7 +267,7 @@ export function coChanges(projectPath, opts = {}) {
|
|
|
187
267
|
pairs.push({ a: a, b: b, count });
|
|
188
268
|
}
|
|
189
269
|
pairs.sort((x, y) => y.count - x.count || x.a.localeCompare(y.a) || x.b.localeCompare(y.b));
|
|
190
|
-
return { shallow, pairs };
|
|
270
|
+
return { shallow, pairs, skippedTooLarge, commitsScanned };
|
|
191
271
|
}
|
|
192
272
|
/**
|
|
193
273
|
* The SHA of the most recent commit that touched `relPath`, or `null` when the
|