@vaubaan/harness 2.4.0 → 3.0.0

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 (53) hide show
  1. package/README.md +207 -83
  2. package/dist/cli/index.js +4165 -843
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/commands/harn-canvas.cmd.md +23 -0
  5. package/dist/commands/{decision.cmd.md → harn-decision.cmd.md} +6 -6
  6. package/dist/commands/{doc-audit.cmd.md → harn-doc-audit.cmd.md} +7 -7
  7. package/dist/commands/{drift.cmd.md → harn-drift.cmd.md} +6 -6
  8. package/dist/commands/{handbook.cmd.md → harn-handbook.cmd.md} +6 -6
  9. package/dist/commands/harn-improve.cmd.md +20 -0
  10. package/dist/commands/{intent.cmd.md → harn-intent.cmd.md} +9 -9
  11. package/dist/commands/{readme.cmd.md → harn-readme.cmd.md} +6 -6
  12. package/dist/commands/{spec.cmd.md → harn-spec.cmd.md} +6 -6
  13. package/dist/commands/{test-plan.cmd.md → harn-test-plan.cmd.md} +6 -6
  14. package/dist/commands/harn-upgrade.cmd.md +22 -0
  15. package/dist/commands/{workflow.cmd.md → harn-workflow.cmd.md} +6 -6
  16. package/dist/index.d.ts +32 -3
  17. package/dist/index.js +533 -96
  18. package/dist/index.js.map +1 -1
  19. package/dist/init.d.ts +1 -1
  20. package/dist/init.js +468 -93
  21. package/dist/init.js.map +1 -1
  22. package/dist/linters/index.d.ts +3 -34
  23. package/dist/linters/index.js +996 -554
  24. package/dist/linters/index.js.map +1 -1
  25. package/dist/parser/index.d.ts +96 -6
  26. package/dist/parser/index.js +220 -10
  27. package/dist/parser/index.js.map +1 -1
  28. package/dist/render-BhUar2gf.d.ts +81 -0
  29. package/dist/render.d.ts +1 -1
  30. package/dist/render.js +233 -22
  31. package/dist/render.js.map +1 -1
  32. package/dist/skills/harn-canvas-review.skill.md +87 -0
  33. package/dist/skills/{decision-record-writer.skill.md → harn-decision-record-writer.skill.md} +2 -1
  34. package/dist/skills/{doc-audit.skill.md → harn-doc-audit.skill.md} +75 -26
  35. package/dist/skills/{drift-detector.skill.md → harn-drift-detector.skill.md} +15 -14
  36. package/dist/skills/harn-guide.skill.md +137 -0
  37. package/dist/skills/{handbook-writer.skill.md → harn-handbook-writer.skill.md} +2 -1
  38. package/dist/skills/{intent-writer.skill.md → harn-intent-writer.skill.md} +83 -16
  39. package/dist/skills/{readme-writer.skill.md → harn-readme-writer.skill.md} +4 -4
  40. package/dist/skills/harn-self-improve.skill.md +84 -0
  41. package/dist/skills/{spec-writer.skill.md → harn-spec-writer.skill.md} +8 -8
  42. package/dist/skills/{test-plan-writer.skill.md → harn-test-plan-writer.skill.md} +6 -5
  43. package/dist/skills/harn-upgrade.skill.md +171 -0
  44. package/dist/skills/{workflow-writer.skill.md → harn-workflow-writer.skill.md} +6 -5
  45. package/dist/templates/decisions-index.md.tmpl +11 -0
  46. package/dist/templates/handbook-index.md.tmpl +8 -0
  47. package/dist/templates/profile.md.tmpl +30 -0
  48. package/dist/types-CfUByAIr.d.ts +35 -0
  49. package/dist/view/index.d.ts +117 -0
  50. package/dist/view/index.js +3987 -0
  51. package/dist/view/index.js.map +1 -0
  52. package/package.json +5 -1
  53. package/dist/render-CTx7VNOK.d.ts +0 -45
@@ -0,0 +1,3987 @@
1
+ // src/view/graph.ts
2
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs";
3
+ import { basename as basename5, join as join11, posix as posix3, relative as relative2 } from "path";
4
+ import fg6 from "fast-glob";
5
+
6
+ // src/cli/manifest.ts
7
+ import { createHash } from "crypto";
8
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "fs";
9
+ import { join as join2 } from "path";
10
+ import { z } from "zod";
11
+
12
+ // src/version.ts
13
+ var VERSION = "3.0.0";
14
+
15
+ // src/cli/managed-paths.ts
16
+ import { lstatSync, realpathSync, statSync } from "fs";
17
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from "path";
18
+ var MANAGED_FILES = /* @__PURE__ */ new Set([
19
+ "AGENTS.md",
20
+ "CLAUDE.md",
21
+ ".harness-manifest.json",
22
+ // Indexes of the intents and profiles pillars, rendered while the pillar is active.
23
+ "docs/intents/README.md",
24
+ "docs/profiles/README.md",
25
+ // Its 2.2 location, kept managed so `update` can remove it (see MOVED_PATHS).
26
+ "docs/journeys/README.md"
27
+ ]);
28
+ var RELEASED_PATHS = [
29
+ ".mcp.json",
30
+ ".codex/config.toml",
31
+ ".opencode/opencode.json",
32
+ ".opencode/mcp.json",
33
+ ".claude/settings.json",
34
+ ".codex/hooks.json"
35
+ ];
36
+ var MANAGED_DIRECTORIES = [
37
+ ".claude/agents/",
38
+ ".claude/commands/",
39
+ ".claude/skills/",
40
+ ".codex/agents/",
41
+ ".codex/commands/",
42
+ ".codex/skills/",
43
+ ".agents/skills/",
44
+ ".opencode/agents/",
45
+ ".opencode/commands/",
46
+ ".opencode/skills/",
47
+ ".opencode/plugins/"
48
+ ];
49
+ function canonicalTargetRoot(root) {
50
+ let ancestor = resolve(root);
51
+ const missing = [];
52
+ while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
53
+ missing.unshift(basename(ancestor));
54
+ ancestor = dirname(ancestor);
55
+ }
56
+ const canonical = realpathSync(ancestor);
57
+ if (!statSync(canonical).isDirectory()) {
58
+ throw new Error(`harness target is not a directory: ${root}`);
59
+ }
60
+ return join(canonical, ...missing);
61
+ }
62
+ function assertManagedLocation(path) {
63
+ const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
64
+ if (isAbsolute(path) || win32.isAbsolute(path) || path.includes("\\") || path.includes("\0") || invalidSegment) {
65
+ throw new Error(`unsafe harness path: ${path}`);
66
+ }
67
+ if (!MANAGED_FILES.has(path) && !MANAGED_DIRECTORIES.some((prefix) => path.startsWith(prefix))) {
68
+ throw new Error(`path is outside harness-managed locations: ${path}`);
69
+ }
70
+ }
71
+ function assertNoSymbolicComponents(root, path) {
72
+ const parts = path.split("/");
73
+ let current = root;
74
+ for (const [index, part] of parts.entries()) {
75
+ current = join(current, part);
76
+ const info = lstatSync(current, { throwIfNoEntry: false });
77
+ if (!info) return;
78
+ if (info.isSymbolicLink()) {
79
+ throw new Error(`symbolic link in harness path: ${path}`);
80
+ }
81
+ const isLeaf = index === parts.length - 1;
82
+ if (isLeaf ? !info.isFile() : !info.isDirectory()) {
83
+ throw new Error(`unexpected file type in harness path: ${path}`);
84
+ }
85
+ }
86
+ }
87
+ function assertManagedPaths(root, files) {
88
+ for (const path of files) assertManagedLocation(path);
89
+ const canonicalRoot = canonicalTargetRoot(root);
90
+ for (const path of files) assertNoSymbolicComponents(canonicalRoot, path);
91
+ }
92
+
93
+ // src/cli/manifest.ts
94
+ var MANIFEST_FILENAME = ".harness-manifest.json";
95
+ var MANIFEST_VERSION = "6";
96
+ var ManifestSchema = z.object({
97
+ version: z.enum(["4", "5", MANIFEST_VERSION]),
98
+ engines: z.array(z.string()),
99
+ renderedAt: z.string(),
100
+ files: z.array(z.string()),
101
+ harnessVersion: z.string().optional(),
102
+ overridesDir: z.string().optional(),
103
+ fileHashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)).optional(),
104
+ preservedFiles: z.array(z.string()).optional()
105
+ });
106
+ function manifestPath(targetDir) {
107
+ return join2(targetDir, MANIFEST_FILENAME);
108
+ }
109
+ function readManifest(targetDir) {
110
+ assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
111
+ const path = manifestPath(targetDir);
112
+ if (!existsSync(path)) return null;
113
+ const raw = JSON.parse(readFileSync(path, "utf8"));
114
+ return ManifestSchema.parse(raw);
115
+ }
116
+
117
+ // src/cli/plan-render.ts
118
+ import { existsSync as existsSync7 } from "fs";
119
+ import { dirname as dirname2, join as join8, resolve as resolve2 } from "path";
120
+ import { fileURLToPath } from "url";
121
+
122
+ // src/loader.ts
123
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
124
+ import { join as join4 } from "path";
125
+ import fg from "fast-glob";
126
+ import { z as z3 } from "zod";
127
+
128
+ // src/parser/common.ts
129
+ import { readFileSync as readFileSync2 } from "fs";
130
+ import matter from "gray-matter";
131
+
132
+ // src/parser/schemas.ts
133
+ import { z as z2 } from "zod";
134
+
135
+ // src/pillars.ts
136
+ import { existsSync as existsSync2, readdirSync, statSync as statSync2 } from "fs";
137
+ import { join as join3 } from "path";
138
+ var PILLAR_IDS = [
139
+ "readme",
140
+ "spec",
141
+ "decisions",
142
+ "handbook",
143
+ "tests",
144
+ "workflow",
145
+ "quality",
146
+ "skills",
147
+ "intents",
148
+ "profiles"
149
+ ];
150
+ var PILLARS = [
151
+ { id: "readme", core: true },
152
+ { id: "spec", dir: "docs/spec", core: true },
153
+ {
154
+ id: "decisions",
155
+ dir: "docs/decisions",
156
+ core: false,
157
+ starters: [{ template: "decisions-index.md.tmpl", path: "docs/decisions/README.md" }],
158
+ next: "write the first decision with the `harn-decision-record-writer` skill (`/harn-decision`)"
159
+ },
160
+ {
161
+ id: "handbook",
162
+ dir: "docs/handbook",
163
+ core: false,
164
+ starters: [{ template: "handbook-index.md.tmpl", path: "docs/handbook/README.md" }],
165
+ next: "write the first handbook with the `harn-handbook-writer` skill (`/harn-handbook`)"
166
+ },
167
+ {
168
+ id: "tests",
169
+ dir: "docs/tests",
170
+ core: false,
171
+ starters: [
172
+ { template: "integration-tests.md.tmpl", path: "docs/tests/integration-tests.md" },
173
+ { template: "e2e-tests.md.tmpl", path: "docs/tests/e2e-tests.md" }
174
+ ],
175
+ next: "fill both test plans with the `harn-test-plan-writer` skill (`/harn-test-plan`); the lint fails on their placeholders until then"
176
+ },
177
+ {
178
+ id: "workflow",
179
+ dir: "docs/workflow",
180
+ core: false,
181
+ starters: [{ template: "coding-workflow.md.tmpl", path: "docs/workflow/coding-workflow.md" }],
182
+ next: "fill the workflow with the `harn-workflow-writer` skill (`/harn-workflow`); the lint fails on its placeholders until then"
183
+ },
184
+ {
185
+ id: "quality",
186
+ dir: "docs/quality",
187
+ core: false,
188
+ starters: [{ template: "code-quality.md.tmpl", path: "docs/quality/code-quality.md" }],
189
+ next: "fill docs/quality/code-quality.md by hand: the tools, the project's rules, the accepted deviations"
190
+ },
191
+ // Active as soon as it holds a `*.skill.md`: nothing to add.
192
+ { id: "skills", dir: "docs/skills", core: false },
193
+ {
194
+ id: "intents",
195
+ dir: "docs/intents",
196
+ core: false,
197
+ starters: [],
198
+ next: "write the first intent with the `harn-intent-writer` skill (`/harn-intent <verb + object>`)"
199
+ },
200
+ {
201
+ id: "profiles",
202
+ dir: "docs/profiles",
203
+ core: false,
204
+ starters: [],
205
+ next: "describe the first profile with the `harn-intent-writer` skill, from the research you point it to"
206
+ }
207
+ ];
208
+ var ADDABLE_PILLARS = PILLARS.filter(
209
+ (pillar) => pillar.starters !== void 0
210
+ );
211
+ function getPillar(id) {
212
+ return PILLARS.find((pillar) => pillar.id === id);
213
+ }
214
+ function isDirectory(path) {
215
+ return existsSync2(path) && statSync2(path).isDirectory();
216
+ }
217
+ function isPillarActive(repoRoot, id) {
218
+ const pillar = getPillar(id);
219
+ if (!pillar) return false;
220
+ if (pillar.core) return true;
221
+ return pillar.dir !== void 0 && isDirectory(join3(repoRoot, pillar.dir));
222
+ }
223
+ function activePillars(repoRoot) {
224
+ return new Set(PILLARS.filter((p) => isPillarActive(repoRoot, p.id)).map((p) => p.id));
225
+ }
226
+ function allPillars() {
227
+ return new Set(PILLAR_IDS);
228
+ }
229
+ function emptyPillarDirs(repoRoot) {
230
+ const holdsFile = (dir) => readdirSync(dir, { withFileTypes: true }).some(
231
+ (entry) => entry.isDirectory() ? holdsFile(join3(dir, entry.name)) : true
232
+ );
233
+ return PILLARS.flatMap((pillar) => {
234
+ if (!pillar.dir) return [];
235
+ const full = join3(repoRoot, pillar.dir);
236
+ return isDirectory(full) && !holdsFile(full) ? [pillar.dir] : [];
237
+ });
238
+ }
239
+
240
+ // src/types.ts
241
+ var ENGINES = ["claude-code", "codex-cli", "opencode"];
242
+ var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
243
+ var CAPABILITIES_MATRIX = {
244
+ "claude-code": ["multi-step", "slash-command", "inline-exec"],
245
+ "codex-cli": ["multi-step", "slash-command", "inline-exec"],
246
+ opencode: ["multi-step", "slash-command", "inline-exec"]
247
+ };
248
+ var DEGRADED_CAPABILITIES = {
249
+ "codex-cli": ["multi-step"]
250
+ };
251
+
252
+ // src/parser/schemas.ts
253
+ var IdSchema = z2.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
254
+ var SkillFrontmatterSchema = z2.object({
255
+ id: IdSchema,
256
+ description: z2.string().min(1),
257
+ engines: z2.array(z2.enum(ENGINES)).min(1).optional(),
258
+ requires: z2.array(z2.enum(CAPABILITIES)).optional(),
259
+ /** Rendered while one of these pillars is active; omitted = always. */
260
+ pillars: z2.array(z2.enum(PILLAR_IDS)).min(1).optional(),
261
+ tags: z2.array(z2.string()).optional()
262
+ }).strict();
263
+ var CmdArgEnumSchema = z2.object({
264
+ name: z2.string().min(1),
265
+ type: z2.literal("enum"),
266
+ values: z2.array(z2.string()).min(1),
267
+ default: z2.string().optional(),
268
+ /** False when the command runs without the argument. Defaults to true. */
269
+ required: z2.boolean().optional()
270
+ }).strict();
271
+ var CmdArgStringSchema = z2.object({
272
+ name: z2.string().min(1),
273
+ type: z2.literal("string"),
274
+ default: z2.string().optional(),
275
+ /** False when the command runs without the argument. Defaults to true. */
276
+ required: z2.boolean().optional()
277
+ }).strict();
278
+ var CmdArgSchema = z2.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
279
+ var CmdFrontmatterSchema = z2.object({
280
+ id: IdSchema,
281
+ trigger: z2.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
282
+ invokes_skill: IdSchema,
283
+ args: z2.array(CmdArgSchema).optional(),
284
+ description: z2.string().min(1)
285
+ }).strict();
286
+ var INTENT_STATUSES = ["proposed", "implemented", "deprecated"];
287
+ var IntentFrontmatterSchema = z2.object({
288
+ title: z2.string().min(1),
289
+ status: z2.enum(INTENT_STATUSES),
290
+ actors: z2.array(z2.string().min(1)).min(1),
291
+ spec: z2.union([z2.string().min(1), z2.array(z2.string().min(1)).min(1)]),
292
+ last_reviewed: z2.union([z2.date(), z2.string().min(1)])
293
+ }).strict();
294
+ var PROFILE_STATUSES = ["hypothesis", "validated"];
295
+ var ProfileFrontmatterSchema = z2.object({
296
+ title: z2.string().min(1),
297
+ status: z2.enum(PROFILE_STATUSES),
298
+ evidence: z2.union([z2.string().min(1), z2.array(z2.string().min(1)).min(1)]).optional(),
299
+ last_reviewed: z2.union([z2.date(), z2.string().min(1)])
300
+ }).strict();
301
+ var Schemas = {
302
+ Skill: SkillFrontmatterSchema,
303
+ Cmd: CmdFrontmatterSchema,
304
+ Intent: IntentFrontmatterSchema,
305
+ Profile: ProfileFrontmatterSchema
306
+ };
307
+ var ParseError = class extends Error {
308
+ constructor(file, issues) {
309
+ const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
310
+ super(`Frontmatter validation failed for ${file}:
311
+ ${messages}`);
312
+ this.file = file;
313
+ this.issues = issues;
314
+ this.name = "ParseError";
315
+ }
316
+ file;
317
+ issues;
318
+ };
319
+
320
+ // src/parser/common.ts
321
+ function parseWithSchema(filePath, source, schema) {
322
+ const parsed = matter(source);
323
+ const result = schema.safeParse(parsed.data);
324
+ if (!result.success) {
325
+ throw new ParseError(filePath, result.error.issues);
326
+ }
327
+ return {
328
+ meta: result.data,
329
+ body: parsed.content.trim(),
330
+ sourcePath: filePath
331
+ };
332
+ }
333
+
334
+ // src/parser/cmd.ts
335
+ function parseCmd(filePath, source) {
336
+ return parseWithSchema(filePath, source, Schemas.Cmd);
337
+ }
338
+
339
+ // src/parser/skill.ts
340
+ function parseSkill(filePath, source) {
341
+ return parseWithSchema(filePath, source, Schemas.Skill);
342
+ }
343
+
344
+ // src/util/yaml.ts
345
+ import { parse as yamlParse } from "yaml";
346
+ function parseYAML(source) {
347
+ return yamlParse(source);
348
+ }
349
+
350
+ // src/loader.ts
351
+ var DisableYamlSchema = z3.object({ disable: z3.array(z3.string()).optional() }).passthrough();
352
+ function loadHarness(packageDir, opts = {}) {
353
+ const skillsDir = opts.skillsDir ?? join4(packageDir, "skills");
354
+ const commandsDir = opts.commandsDir ?? join4(packageDir, "commands");
355
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
356
+ const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
357
+ return {
358
+ skills: skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8"))),
359
+ cmds: cmdFiles.map((f) => parseCmd(f, readFileSync3(f, "utf8")))
360
+ };
361
+ }
362
+ function loadProjectSkills(targetDir) {
363
+ const skillsDir = join4(targetDir, "docs", "skills");
364
+ if (!existsSync3(skillsDir)) return [];
365
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
366
+ return skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8")));
367
+ }
368
+ function loadOverrides(worktreeDir) {
369
+ const overridesDir = join4(worktreeDir, ".harness-overrides");
370
+ if (!existsSync3(overridesDir)) return void 0;
371
+ const added = loadHarness(overridesDir, {
372
+ skillsDir: join4(overridesDir, "skills"),
373
+ commandsDir: join4(overridesDir, "commands")
374
+ });
375
+ const disablePath = join4(overridesDir, "disable.yaml");
376
+ let disable = [];
377
+ if (existsSync3(disablePath)) {
378
+ try {
379
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync3(disablePath, "utf8")));
380
+ if (parsed.success && parsed.data.disable) {
381
+ disable = parsed.data.disable;
382
+ }
383
+ } catch {
384
+ }
385
+ }
386
+ return { add: added, disable };
387
+ }
388
+
389
+ // src/parser/intent.ts
390
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
391
+ import { basename as basename2, join as join5 } from "path";
392
+ import matter2 from "gray-matter";
393
+ var INTENTS_DIR = "docs/intents";
394
+ var INTENTS_INDEX_PATH = `${INTENTS_DIR}/README.md`;
395
+ var NODE_FIELDS = [
396
+ "status",
397
+ "spec",
398
+ "anchors",
399
+ "acceptance",
400
+ "requires",
401
+ "creates",
402
+ "relieves",
403
+ "delivers"
404
+ ];
405
+ var TERMINAL_FIELDS = [
406
+ "anchors",
407
+ "acceptance",
408
+ "requires",
409
+ "creates",
410
+ "relieves",
411
+ "delivers"
412
+ ];
413
+ var MASKED_LINE = "\0";
414
+ var FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
415
+ var HEADING_RE = /^(#{1,6})[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*$/;
416
+ var FIELD_RE = /^([a-z][a-z-]*):\s*(.*)$/;
417
+ var LIST_ITEM_RE = /^\s*-\s+(.*)$/;
418
+ function maskFencedCode(lines) {
419
+ let fence;
420
+ return lines.map((line) => {
421
+ const m = FENCE_RE.exec(line);
422
+ if (fence !== void 0) {
423
+ if (m?.[1] && m[1][0] === fence[0] && m[1].length >= fence.length) fence = void 0;
424
+ return MASKED_LINE;
425
+ }
426
+ if (m?.[1]) {
427
+ fence = m[1];
428
+ return MASKED_LINE;
429
+ }
430
+ return line;
431
+ });
432
+ }
433
+ function parseHeading(line) {
434
+ const m = HEADING_RE.exec(line);
435
+ if (!m?.[1] || !m[2]) return void 0;
436
+ return { depth: m[1].length, title: m[2] };
437
+ }
438
+ function splitList(value) {
439
+ return value.split(",").map((v) => v.trim()).filter(Boolean);
440
+ }
441
+ function bodyStart(lines) {
442
+ if (lines[0]?.trim() !== "---") return 0;
443
+ for (let i = 1; i < lines.length; i++) {
444
+ const l = lines[i]?.trim();
445
+ if (l === "---" || l === "...") return i + 1;
446
+ }
447
+ return lines.length;
448
+ }
449
+ function parseFrontmatter(text, errors) {
450
+ let data;
451
+ try {
452
+ data = matter2(text).data;
453
+ } catch (error) {
454
+ const reason = error instanceof Error ? error.message.split("\n")[0] : String(error);
455
+ errors.push({ line: 1, message: `invalid frontmatter YAML: ${reason}` });
456
+ return void 0;
457
+ }
458
+ const result = Schemas.Intent.safeParse(data);
459
+ if (result.success) return result.data;
460
+ for (const issue of result.error.issues) {
461
+ const where = issue.path.length ? ` \`${issue.path.join(".")}\`` : "";
462
+ errors.push({ line: 1, message: `frontmatter${where}: ${issue.message}` });
463
+ }
464
+ return void 0;
465
+ }
466
+ function newNode(title, level, line) {
467
+ return {
468
+ title,
469
+ level,
470
+ line,
471
+ isTerminal: true,
472
+ fieldLines: {},
473
+ anchors: [],
474
+ acceptance: [],
475
+ requires: [],
476
+ creates: [],
477
+ relieves: [],
478
+ delivers: [],
479
+ unknownFields: []
480
+ };
481
+ }
482
+ function parseFields(node, lines, from, to, errors) {
483
+ let lastKey;
484
+ for (let i = from; i < to; i++) {
485
+ const line = lines[i] ?? "";
486
+ if (line.trim() === "") continue;
487
+ const lineNo = i + 1;
488
+ const field = FIELD_RE.exec(line.trimEnd());
489
+ if (field?.[1] !== void 0) {
490
+ const key = field[1];
491
+ const value = (field[2] ?? "").trim();
492
+ lastKey = key;
493
+ if (!NODE_FIELDS.includes(key)) {
494
+ node.unknownFields.push({ key, line: lineNo });
495
+ continue;
496
+ }
497
+ const known = key;
498
+ node.fieldLines[known] = lineNo;
499
+ if (known === "status") {
500
+ if (INTENT_STATUSES.includes(value)) {
501
+ node.status = value;
502
+ } else {
503
+ errors.push({
504
+ line: lineNo,
505
+ message: `invalid status \`${value}\` (expected ${INTENT_STATUSES.join(" | ")})`
506
+ });
507
+ }
508
+ } else if (known === "spec") {
509
+ node.spec = value;
510
+ } else if (known === "acceptance") {
511
+ if (value) node.acceptance.push(value);
512
+ } else {
513
+ node[known] = splitList(value);
514
+ }
515
+ continue;
516
+ }
517
+ const item = LIST_ITEM_RE.exec(line);
518
+ if (lastKey === "acceptance" && item) {
519
+ const text = (item[1] ?? "").trim();
520
+ if (text) node.acceptance.push(text);
521
+ continue;
522
+ }
523
+ return;
524
+ }
525
+ }
526
+ function parseIntentFile(relPath, text) {
527
+ const errors = [];
528
+ const meta = parseFrontmatter(text, errors);
529
+ const lines = maskFencedCode(text.split(/\r?\n/));
530
+ const start = bodyStart(lines);
531
+ const headings = [];
532
+ for (let i = start; i < lines.length; i++) {
533
+ const h = parseHeading(lines[i] ?? "");
534
+ if (h) headings.push({ index: i, ...h });
535
+ }
536
+ const h1 = headings.find((h) => h.depth === 1);
537
+ let statement;
538
+ if (h1) {
539
+ const paragraph = [];
540
+ for (let i = h1.index + 1; i < lines.length; i++) {
541
+ const line = lines[i] ?? "";
542
+ if (line.trim() === "") {
543
+ if (paragraph.length) break;
544
+ continue;
545
+ }
546
+ if (line === MASKED_LINE || parseHeading(line)) break;
547
+ paragraph.push(line.trim());
548
+ }
549
+ if (paragraph.length) statement = paragraph.join(" ");
550
+ }
551
+ const nodes = [];
552
+ const stack = [];
553
+ for (const [k, h] of headings.entries()) {
554
+ if (h.depth < 2) continue;
555
+ const node = newNode(h.title, h.depth - 1, h.index + 1);
556
+ while (stack.length) {
557
+ const top = nodes[stack[stack.length - 1]];
558
+ if (top && top.level < node.level) break;
559
+ stack.pop();
560
+ }
561
+ const parentIndex = stack[stack.length - 1];
562
+ if (parentIndex !== void 0) {
563
+ node.parent = parentIndex;
564
+ const parent = nodes[parentIndex];
565
+ if (parent) parent.isTerminal = false;
566
+ }
567
+ const next = headings[k + 1];
568
+ parseFields(node, lines, h.index + 1, next ? next.index : lines.length, errors);
569
+ const inherited = parentIndex !== void 0 ? nodes[parentIndex]?.effectiveStatus : meta?.status;
570
+ node.effectiveStatus = node.status ?? inherited;
571
+ stack.push(nodes.length);
572
+ nodes.push(node);
573
+ }
574
+ const title = meta?.title ?? h1?.title ?? basename2(relPath, ".md");
575
+ return { ...meta ? { meta } : {}, title, ...statement ? { statement } : {}, nodes, errors };
576
+ }
577
+ function listIntentFiles(targetDir) {
578
+ const dir = join5(targetDir, INTENTS_DIR);
579
+ if (!existsSync4(dir) || !statSync3(dir).isDirectory()) return [];
580
+ return readdirSync2(dir).filter((f) => f.endsWith(".md") && f !== "README.md").filter((f) => statSync3(join5(dir, f)).isFile()).sort();
581
+ }
582
+ function readIntentFiles(targetDir) {
583
+ return listIntentFiles(targetDir).map((file) => {
584
+ const path = `${INTENTS_DIR}/${file}`;
585
+ const text = readFileSync4(join5(targetDir, path), "utf8");
586
+ return { path, file, ...parseIntentFile(path, text) };
587
+ });
588
+ }
589
+ function loadIntentFiles(targetDir) {
590
+ const intentFiles = readIntentFiles(targetDir);
591
+ const problems = intentFiles.flatMap(
592
+ (j) => j.errors.map((e) => ` - ${j.path}${e.line !== void 0 ? `:${e.line}` : ""}: ${e.message}`)
593
+ );
594
+ if (problems.length) {
595
+ throw new Error(
596
+ `invalid intents (run \`npx @vaubaan/harness lint --pillar intents\`):
597
+ ${problems.join("\n")}`
598
+ );
599
+ }
600
+ return intentFiles;
601
+ }
602
+
603
+ // src/parser/profile.ts
604
+ import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync as readdirSync3, statSync as statSync5 } from "fs";
605
+ import { basename as basename3, join as join7 } from "path";
606
+ import matter4 from "gray-matter";
607
+
608
+ // src/parser/docs.ts
609
+ function headingSlug(title) {
610
+ return title.toLowerCase().replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}\s-]/gu, "").trim().replace(/\s/g, "-");
611
+ }
612
+ function readHeadings(text) {
613
+ const lines = maskFencedCode(text.split(/\r?\n/));
614
+ const out = [];
615
+ for (const [i, line] of lines.entries()) {
616
+ const h = parseHeading(line);
617
+ if (h) out.push({ depth: h.depth, title: h.title, line: i + 1, slug: headingSlug(h.title) });
618
+ }
619
+ return out;
620
+ }
621
+ var VOCABULARY_HEADING = /^#+\s*(\d+(\.\d+)*\.?\s*)?(Vocabulary|Vocabulaire)\b/i;
622
+ var TERM = /^\s*[-*]\s+\*\*([^*]+)\*\*\s*(?:[—–:-]+\s*)?(.*)$/;
623
+ var TABLE_ROW = /^\s*\|(.+)\|\s*$/;
624
+ var TABLE_SEPARATOR = /^\s*\|?\s*:?-{3,}/;
625
+ function entitySlug(term) {
626
+ return term.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
627
+ }
628
+ function tableTerm(line, next) {
629
+ const row = TABLE_ROW.exec(line)?.[1];
630
+ if (row === void 0 || TABLE_SEPARATOR.test(line)) return void 0;
631
+ if (next !== void 0 && TABLE_SEPARATOR.test(next)) return void 0;
632
+ const cells = row.split("|").map((c) => c.trim());
633
+ const cell = (cells[0] ?? "").replace(/[*_`]/g, "").trim();
634
+ if (!cell || /^<.*>$/.test(cell)) return void 0;
635
+ return [cell, cells[1] ?? ""];
636
+ }
637
+ function vocabularyTerms(specText) {
638
+ const lines = maskFencedCode(specText.split(/\r?\n/));
639
+ let depth;
640
+ let terms;
641
+ for (const [i, line] of lines.entries()) {
642
+ const heading = parseHeading(line);
643
+ if (depth !== void 0) {
644
+ if (heading && heading.depth <= depth) break;
645
+ const bullet = TERM.exec(line);
646
+ const found = bullet?.[1] ? [bullet[1], bullet[2] ?? ""] : tableTerm(line, lines[i + 1]);
647
+ if (found) {
648
+ const [term, definition] = found;
649
+ terms?.push({ term: term.trim(), slug: entitySlug(term), line: i + 1, definition });
650
+ }
651
+ continue;
652
+ }
653
+ if (heading && VOCABULARY_HEADING.test(line)) {
654
+ depth = heading.depth;
655
+ terms = [];
656
+ }
657
+ }
658
+ return terms;
659
+ }
660
+ function vocabularyOf(specText) {
661
+ const terms = vocabularyTerms(specText);
662
+ return terms ? new Set(terms.map((t) => t.slug)) : void 0;
663
+ }
664
+ var LINK_REGEX = /\[([^\]]+)\]\(([^)]+)\)/g;
665
+ function maskCodeSpans(text) {
666
+ return text.replace(/```[\s\S]*?```/g, (m) => m.replace(/[^\n]/g, " ")).replace(/`[^`\n]*`/g, (m) => " ".repeat(m.length));
667
+ }
668
+ function readLinks(text) {
669
+ const lines = maskCodeSpans(text).split("\n");
670
+ const out = [];
671
+ for (const [i, line] of lines.entries()) {
672
+ LINK_REGEX.lastIndex = 0;
673
+ let match = LINK_REGEX.exec(line);
674
+ while (match !== null) {
675
+ if (match[2]) out.push({ url: match[2], line: i + 1 });
676
+ match = LINK_REGEX.exec(line);
677
+ }
678
+ }
679
+ return out;
680
+ }
681
+ function isExternalOrAnchor(url) {
682
+ return /^(https?:|mailto:|#)/.test(url);
683
+ }
684
+ function stripFragment(url) {
685
+ const i = url.indexOf("#");
686
+ return i < 0 ? url : url.slice(0, i);
687
+ }
688
+ var ADR_SECTIONS = [
689
+ { label: "Context", pattern: /^##\s+(Context|Contexte)\b/m },
690
+ { label: "Decision", pattern: /^##\s+(Decision|D[ée]cision)\b/m },
691
+ { label: "Consequences", pattern: /^##\s+(Consequences|Cons[ée]quences)\b/m },
692
+ {
693
+ label: "Rejected alternatives",
694
+ pattern: /^##\s+(Rejected\s+alternatives|Alternatives(\s+rejet[ée]es)?)\b/im
695
+ }
696
+ ];
697
+ function readAdr(text) {
698
+ const missing = ADR_SECTIONS.filter((s) => !s.pattern.test(text)).map((s) => s.label);
699
+ const lines = maskFencedCode(text.split(/\r?\n/));
700
+ const decisionPattern = ADR_SECTIONS[1]?.pattern;
701
+ const alternativesPattern = ADR_SECTIONS[3]?.pattern;
702
+ let section;
703
+ const paragraph = [];
704
+ let paragraphDone = false;
705
+ const alternatives = [];
706
+ for (const [i, line] of lines.entries()) {
707
+ const heading = parseHeading(line);
708
+ if (heading && heading.depth <= 2) {
709
+ section = decisionPattern?.test(line) ? "decision" : alternativesPattern?.test(line) ? "alternatives" : void 0;
710
+ continue;
711
+ }
712
+ if (section === "decision" && !paragraphDone) {
713
+ if (line.trim() === "") {
714
+ if (paragraph.length) paragraphDone = true;
715
+ } else paragraph.push(line.trim());
716
+ }
717
+ if (section === "alternatives") {
718
+ if (heading && heading.depth === 3) {
719
+ alternatives.push({ title: heading.title, line: i + 1, text: "" });
720
+ } else if (line.trim() && alternatives.length) {
721
+ const last = alternatives[alternatives.length - 1];
722
+ if (last) last.text = last.text ? `${last.text} ${line.trim()}` : line.trim();
723
+ }
724
+ }
725
+ }
726
+ return {
727
+ missing,
728
+ ...paragraph.length ? { decision: paragraph.join(" ") } : {},
729
+ alternatives
730
+ };
731
+ }
732
+ var KNOWN_GAPS_HEADING = /^#+\s*(\d+(\.\d+)*\.?\s*)?(Known gaps|Lacunes connues|Trous connus)\b/i;
733
+ function readKnownGaps(text) {
734
+ const lines = maskFencedCode(text.split(/\r?\n/));
735
+ let depth;
736
+ const out = [];
737
+ for (const [i, line] of lines.entries()) {
738
+ const heading = parseHeading(line);
739
+ if (depth !== void 0) {
740
+ if (heading && heading.depth <= depth) break;
741
+ const bullet = /^\s*[-*]\s+(.*)$/.exec(line);
742
+ if (bullet?.[1]) {
743
+ out.push({
744
+ line: i + 1,
745
+ text: bullet[1].trim(),
746
+ links: readLinks(line).map((l) => l.url)
747
+ });
748
+ }
749
+ continue;
750
+ }
751
+ if (heading && KNOWN_GAPS_HEADING.test(line)) depth = heading.depth;
752
+ }
753
+ return out;
754
+ }
755
+ function readLede(text) {
756
+ const lines = maskFencedCode(text.split(/\r?\n/));
757
+ let afterTitle = false;
758
+ const paragraph = [];
759
+ let inFrontmatter = lines[0]?.trim() === "---";
760
+ for (const [i, line] of lines.entries()) {
761
+ if (inFrontmatter) {
762
+ if (i > 0 && line.trim() === "---") inFrontmatter = false;
763
+ continue;
764
+ }
765
+ const heading = parseHeading(line);
766
+ if (!afterTitle) {
767
+ if (heading?.depth === 1) afterTitle = true;
768
+ continue;
769
+ }
770
+ if (heading) break;
771
+ if (line.trim() === "" || line.startsWith(">") || line.startsWith("<!--")) {
772
+ if (paragraph.length) break;
773
+ continue;
774
+ }
775
+ if (line === "\0") break;
776
+ paragraph.push(line.trim());
777
+ }
778
+ return paragraph.length ? paragraph.join(" ") : void 0;
779
+ }
780
+
781
+ // src/linters/intent-util.ts
782
+ import { posix } from "path";
783
+ function intentFileSpecs(meta) {
784
+ if (!meta) return [];
785
+ return typeof meta.spec === "string" ? [meta.spec] : [...meta.spec];
786
+ }
787
+ function resolveSpecPath(filePath, spec) {
788
+ const withoutFragment = spec.split("#")[0] ?? "";
789
+ return posix.normalize(posix.join(posix.dirname(filePath), withoutFragment));
790
+ }
791
+
792
+ // src/linters/util.ts
793
+ import { execFileSync } from "child_process";
794
+ import { existsSync as existsSync5, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
795
+ import { join as join6, relative } from "path";
796
+ import fg2 from "fast-glob";
797
+ import matter3 from "gray-matter";
798
+ function fileExists(repoRoot, relativePath) {
799
+ return existsSync5(join6(repoRoot, relativePath));
800
+ }
801
+ function readText(repoRoot, relativePath) {
802
+ return readFileSync5(join6(repoRoot, relativePath), "utf8");
803
+ }
804
+ function trackedPathExists(repoRoot, pattern) {
805
+ if (pattern.includes("*")) {
806
+ return fg2.sync(pattern, { cwd: repoRoot, absolute: false }).length > 0;
807
+ }
808
+ return existsSync5(join6(repoRoot, pattern));
809
+ }
810
+ function listMarkdown(repoRoot, dir) {
811
+ const cwd = join6(repoRoot, dir);
812
+ if (!existsSync5(cwd)) return [];
813
+ return fg2.sync("**/*.md", { cwd, absolute: false, ignore: ["**/node_modules/**", "**/dist/**"] }).filter((f) => !f.endsWith("README.md")).map((f) => join6(dir, f));
814
+ }
815
+ function dirExists(repoRoot, relativePath) {
816
+ const full = join6(repoRoot, relativePath);
817
+ if (!existsSync5(full)) return false;
818
+ return statSync4(full).isDirectory();
819
+ }
820
+ function parseFrontmatter2(text) {
821
+ const m = matter3(text);
822
+ return { data: m.data, body: m.content };
823
+ }
824
+ function gitLastCommitForPath(repoRoot, relativePath) {
825
+ try {
826
+ const out = execFileSync("git", ["log", "-1", "--format=%H:%ct", "--", relativePath], {
827
+ cwd: repoRoot,
828
+ encoding: "utf8",
829
+ stdio: ["ignore", "pipe", "ignore"]
830
+ }).trim();
831
+ if (!out) return void 0;
832
+ const idx = out.indexOf(":");
833
+ if (idx < 0) return void 0;
834
+ const hash = out.slice(0, idx);
835
+ const ts = Number.parseInt(out.slice(idx + 1), 10);
836
+ return { hash, timestamp: ts };
837
+ } catch {
838
+ return void 0;
839
+ }
840
+ }
841
+ function gitCommitsSince(repoRoot, relativePath, sinceCommit) {
842
+ try {
843
+ const out = execFileSync(
844
+ "git",
845
+ ["log", `${sinceCommit}..HEAD`, "--format=%H", "--", relativePath],
846
+ {
847
+ cwd: repoRoot,
848
+ encoding: "utf8",
849
+ stdio: ["ignore", "pipe", "ignore"]
850
+ }
851
+ ).trim();
852
+ if (!out) return 0;
853
+ return out.split("\n").filter(Boolean).length;
854
+ } catch {
855
+ return 0;
856
+ }
857
+ }
858
+ function findLineNumber(text, needle) {
859
+ const lines = text.split("\n");
860
+ for (let i = 0; i < lines.length; i++) {
861
+ const line = lines[i] ?? "";
862
+ if (typeof needle === "string" ? line.includes(needle) : needle.test(line)) {
863
+ return i + 1;
864
+ }
865
+ }
866
+ return void 0;
867
+ }
868
+
869
+ // src/linters/intent-vocabulary.ts
870
+ var intentVocabulary = {
871
+ id: "lint:intent-vocabulary",
872
+ pillars: ["intents"],
873
+ defaultSeverity: "error",
874
+ suggestedSkills: ["/harn-spec"],
875
+ run(repoRoot) {
876
+ const issues = [];
877
+ for (const intentFile of readIntentFiles(repoRoot)) {
878
+ const used = intentFile.nodes.flatMap(
879
+ (node) => [...node.requires, ...node.creates].map((entity) => ({ entity, node }))
880
+ );
881
+ if (used.length === 0) continue;
882
+ const specs = intentFileSpecs(intentFile.meta).map((spec) => resolveSpecPath(intentFile.path, spec)).filter((path) => fileExists(repoRoot, path));
883
+ if (specs.length === 0) continue;
884
+ const entities = /* @__PURE__ */ new Set();
885
+ let hasVocabulary = false;
886
+ for (const spec of specs) {
887
+ const terms = vocabularyOf(readText(repoRoot, spec));
888
+ if (!terms) continue;
889
+ hasVocabulary = true;
890
+ for (const term of terms) entities.add(term);
891
+ }
892
+ if (!hasVocabulary) {
893
+ issues.push({
894
+ linter: this.id,
895
+ severity: "warning",
896
+ file: intentFile.path,
897
+ message: `no Vocabulary section in ${specs.join(", ")}; entities not checked`
898
+ });
899
+ continue;
900
+ }
901
+ for (const { entity, node } of used) {
902
+ if (entities.has(entity)) continue;
903
+ issues.push({
904
+ linter: this.id,
905
+ severity: "error",
906
+ file: intentFile.path,
907
+ line: node.line,
908
+ message: `"${node.title}": entity \`${entity}\` is not a Vocabulary term of ${specs.join(", ")}`
909
+ });
910
+ }
911
+ }
912
+ return issues;
913
+ }
914
+ };
915
+
916
+ // src/parser/profile.ts
917
+ var PROFILES_DIR = "docs/profiles";
918
+ var PROFILES_INDEX_PATH = `${PROFILES_DIR}/README.md`;
919
+ var PAINS_HEADING = /^(Pains|Irritants|Douleurs)\s*$/i;
920
+ var GAINS_HEADING = /^(Gains|B[ée]n[ée]fices)\s*$/i;
921
+ var BULLET = /^[-*]\s+(.*)$/;
922
+ var NAMED = /^\*\*([^*]+)\*\*/;
923
+ function parseFrontmatter3(text, errors) {
924
+ let data;
925
+ try {
926
+ data = matter4(text).data;
927
+ } catch (error) {
928
+ const reason = error instanceof Error ? error.message.split("\n")[0] : String(error);
929
+ errors.push({ line: 1, message: `invalid frontmatter YAML: ${reason}` });
930
+ return void 0;
931
+ }
932
+ const result = Schemas.Profile.safeParse(data);
933
+ if (result.success) return result.data;
934
+ for (const issue of result.error.issues) {
935
+ const where = issue.path.length ? ` \`${issue.path.join(".")}\`` : "";
936
+ errors.push({ line: 1, message: `frontmatter${where}: ${issue.message}` });
937
+ }
938
+ return void 0;
939
+ }
940
+ function parseProfileFile(relPath, text) {
941
+ const errors = [];
942
+ const meta = parseFrontmatter3(text, errors);
943
+ const lines = maskFencedCode(text.split(/\r?\n/));
944
+ const pains = [];
945
+ const gains = [];
946
+ let h1;
947
+ let current;
948
+ let start = 0;
949
+ if (lines[0]?.trim() === "---") {
950
+ const end = lines.findIndex((line, i) => i > 0 && /^(---|\.\.\.)\s*$/.test(line));
951
+ start = end < 0 ? lines.length : end + 1;
952
+ }
953
+ for (let i = start; i < lines.length; i++) {
954
+ const line = lines[i] ?? "";
955
+ const heading = parseHeading(line);
956
+ if (heading) {
957
+ if (heading.depth === 1 && h1 === void 0) h1 = heading.title;
958
+ if (current && heading.depth > current.depth) continue;
959
+ if (PAINS_HEADING.test(heading.title)) {
960
+ current = { kind: "pain", depth: heading.depth, items: pains };
961
+ } else if (GAINS_HEADING.test(heading.title)) {
962
+ current = { kind: "gain", depth: heading.depth, items: gains };
963
+ } else {
964
+ current = void 0;
965
+ }
966
+ continue;
967
+ }
968
+ if (!current) continue;
969
+ const bullet = BULLET.exec(line)?.[1];
970
+ if (bullet === void 0) continue;
971
+ const name = NAMED.exec(bullet)?.[1]?.trim();
972
+ const slug = name ? entitySlug(name) : "";
973
+ if (!name || !slug) {
974
+ errors.push({ line: i + 1, message: `a ${current.kind} opens with its name in bold` });
975
+ continue;
976
+ }
977
+ if (current.items.some((item) => item.slug === slug)) {
978
+ errors.push({ line: i + 1, message: `duplicate ${current.kind} \`${slug}\`` });
979
+ continue;
980
+ }
981
+ current.items.push({ name, slug, line: i + 1 });
982
+ }
983
+ if (pains.length === 0 && gains.length === 0) {
984
+ errors.push({ message: "a profile names at least one pain or one gain" });
985
+ }
986
+ const title = meta?.title ?? h1 ?? basename3(relPath, ".md");
987
+ return { ...meta ? { meta } : {}, title, pains, gains, errors };
988
+ }
989
+ function listProfileFiles(targetDir) {
990
+ const dir = join7(targetDir, PROFILES_DIR);
991
+ if (!existsSync6(dir) || !statSync5(dir).isDirectory()) return [];
992
+ return readdirSync3(dir).filter((f) => f.endsWith(".md") && f !== "README.md").filter((f) => statSync5(join7(dir, f)).isFile()).sort();
993
+ }
994
+ function readProfileFiles(targetDir) {
995
+ return listProfileFiles(targetDir).map((file) => {
996
+ const path = `${PROFILES_DIR}/${file}`;
997
+ const text = readFileSync6(join7(targetDir, path), "utf8");
998
+ return { path, file, slug: basename3(file, ".md"), ...parseProfileFile(path, text) };
999
+ });
1000
+ }
1001
+ function profileEvidence(meta) {
1002
+ if (!meta?.evidence) return [];
1003
+ return typeof meta.evidence === "string" ? [meta.evidence] : [...meta.evidence];
1004
+ }
1005
+
1006
+ // src/renderers/common.ts
1007
+ import { stringify as yamlStringify } from "yaml";
1008
+ function checkSkillCapabilities(skill, engine) {
1009
+ const blockingWarnings = [];
1010
+ const degradedWarnings = [];
1011
+ const supported = CAPABILITIES_MATRIX[engine];
1012
+ const degraded = DEGRADED_CAPABILITIES[engine] ?? [];
1013
+ if (!skill.meta.requires) return { blockingWarnings, degradedWarnings };
1014
+ for (const cap of skill.meta.requires) {
1015
+ if (!supported.includes(cap)) {
1016
+ blockingWarnings.push(
1017
+ `skill "${skill.meta.id}" requires "${cap}" not supported by "${engine}" \u2014 skipped`
1018
+ );
1019
+ } else if (degraded.includes(cap)) {
1020
+ degradedWarnings.push(
1021
+ `skill "${skill.meta.id}" requires "${cap}" \u2014 supported by "${engine}" with degradation`
1022
+ );
1023
+ }
1024
+ }
1025
+ return { blockingWarnings, degradedWarnings };
1026
+ }
1027
+ function isSkillEngineAllowed(skill, engine) {
1028
+ if (!skill.meta.engines) return true;
1029
+ return skill.meta.engines.includes(engine);
1030
+ }
1031
+ function yamlFrontmatter(data) {
1032
+ const rendered = yamlStringify(data, { lineWidth: 0 }).trimEnd();
1033
+ return `---
1034
+ ${rendered}
1035
+ ---
1036
+ `;
1037
+ }
1038
+ function frontmatterDataForSkill(skill) {
1039
+ const data = {
1040
+ name: skill.meta.id,
1041
+ description: skill.meta.description
1042
+ };
1043
+ if (skill.meta.tags && skill.meta.tags.length > 0) data.tags = skill.meta.tags;
1044
+ return data;
1045
+ }
1046
+ function frontmatterDataForCmd(cmd) {
1047
+ const data = {
1048
+ id: cmd.meta.id,
1049
+ trigger: cmd.meta.trigger,
1050
+ description: cmd.meta.description
1051
+ };
1052
+ if (cmd.meta.args && cmd.meta.args.length > 0) {
1053
+ data.args = cmd.meta.args.map((a) => ({
1054
+ name: a.name,
1055
+ type: a.type,
1056
+ ...a.type === "enum" ? { values: a.values } : {},
1057
+ ...a.default !== void 0 ? { default: a.default } : {},
1058
+ ...a.required === false ? { required: false } : {}
1059
+ }));
1060
+ }
1061
+ return data;
1062
+ }
1063
+ function buildUmbrellaBody(extras) {
1064
+ const triggersBySkill = /* @__PURE__ */ new Map();
1065
+ for (const c of extras.availableCommands) {
1066
+ const triggers = triggersBySkill.get(c.meta.invokes_skill) ?? [];
1067
+ triggers.push(c.meta.trigger);
1068
+ triggersBySkill.set(c.meta.invokes_skill, triggers);
1069
+ }
1070
+ const skillLines = extras.availableSkills.map((s) => {
1071
+ const triggers = triggersBySkill.get(s.meta.id) ?? [];
1072
+ const label = triggers.length > 0 ? `\`${s.meta.id}\` (${triggers.map((t) => `\`${t}\``).join(", ")})` : `\`${s.meta.id}\``;
1073
+ return `- ${label} \u2014 ${s.meta.description.split("\n")[0]}`;
1074
+ });
1075
+ const has = (pillar) => extras.activePillars.has(pillar);
1076
+ const exposes = (id) => extras.availableSkills.some((s) => s.meta.id === id);
1077
+ const when = (condition, ...lines) => condition ? lines : [];
1078
+ const inactive = ADDABLE_PILLARS.filter((pillar) => !has(pillar.id)).map((p) => `\`${p.id}\``);
1079
+ const sections = [
1080
+ "# How we work",
1081
+ "",
1082
+ "This file describes **how to work in this project**. The **business context** (what the project does, how to run it, which subsystems it contains) lives in `README.md` and `docs/`. Read them first.",
1083
+ "",
1084
+ "## Project map",
1085
+ "",
1086
+ "- `README.md` \u2014 pitch, quick start, scripts. Entry point.",
1087
+ "- `docs/spec/<subsystem>.md` \u2014 *what* and *why* (tech-agnostic).",
1088
+ ...when(
1089
+ has("handbook"),
1090
+ "- `docs/handbook/<feature>.md` \u2014 what the code does not say: entry points, traps, settings outside the repo, manual procedures."
1091
+ ),
1092
+ ...when(
1093
+ has("decisions"),
1094
+ "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives."
1095
+ ),
1096
+ ...when(
1097
+ has("tests"),
1098
+ "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 test scope, stack, conventions, known gaps."
1099
+ ),
1100
+ ...when(
1101
+ has("workflow"),
1102
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release. How this team works: follow it."
1103
+ ),
1104
+ ...when(
1105
+ extras.hasProjectSkills === true,
1106
+ "- `docs/skills/*.skill.md` \u2014 the project's domain skills."
1107
+ ),
1108
+ ...when(
1109
+ has("quality"),
1110
+ "- `docs/quality/code-quality.md` \u2014 the project's code-quality rules: mechanical checks, judgment rules, accepted deviations. Read it before writing or auditing code."
1111
+ ),
1112
+ ...when(
1113
+ has("intents"),
1114
+ "- `docs/intents/<intent>.md` \u2014 user intents, one tree per level-1 intent, anchored to the code. `docs/intents/README.md` is the generated index."
1115
+ ),
1116
+ ...when(
1117
+ has("profiles"),
1118
+ "- `docs/profiles/<profile>.md` \u2014 who the project serves, their pains and gains. `docs/profiles/README.md` is the generated index: which intent serves which pain."
1119
+ ),
1120
+ ...when(
1121
+ inactive.length > 0,
1122
+ "",
1123
+ `Not in this project yet: ${inactive.join(", ")}. A pillar is added the day the project needs it, with \`npx @vaubaan/harness add <pillar>\`${exposes("harn-guide") ? "; the `harn-guide` skill says when each one is worth it" : ""}. Propose it to the human, never create the folder unasked.`
1124
+ ),
1125
+ "",
1126
+ "## Doc-first",
1127
+ "",
1128
+ "The order is: **understand the docs \u2192 fill the gaps \u2192 code \u2192 update the docs \u2192 commit**. If the docs are silent or stale on something you change, fill the gap upfront with the doc-skill writers \u2014 not downstream, not after the fact.",
1129
+ "",
1130
+ ...when(
1131
+ has("intents"),
1132
+ "- Visible change of behavior \u2192 a `proposed` intent first (`/harn-intent <verb + object>`), never the code first."
1133
+ ),
1134
+ "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
1135
+ ...when(
1136
+ has("decisions"),
1137
+ "- Implicit structural decision in your changes \u2192 an ADR (`/harn-decision`)."
1138
+ ),
1139
+ ...when(
1140
+ has("handbook"),
1141
+ "- Changed feature behavior \u2192 update the matching handbook (`/harn-handbook`)."
1142
+ ),
1143
+ ...when(
1144
+ exposes("harn-drift-detector"),
1145
+ "- Suspected code \u2194 doc drift \u2192 `/harn-drift` before moving on."
1146
+ ),
1147
+ "",
1148
+ "## Checks",
1149
+ "",
1150
+ "Run `npx @vaubaan/harness lint` before you commit; CI runs the same linters on every pull request. Fix what it reports with the skill it suggests.",
1151
+ "",
1152
+ "The files the harness generates (`AGENTS.md`, `CLAUDE.md`, the `.claude/`, `.agents/` and `.opencode/` folders, `.harness-manifest.json`) are committed. Never edit them by hand: change their source in `docs/` or `.harness-overrides/`, run `npx @vaubaan/harness update .`, and commit the result. The linter fails when a generated file no longer matches its render."
1153
+ ];
1154
+ if (skillLines.length > 0) {
1155
+ sections.push("", "## Skills", "", skillLines.join("\n"));
1156
+ }
1157
+ return `${sections.join("\n")}
1158
+ `;
1159
+ }
1160
+
1161
+ // src/renderers/claude-code.ts
1162
+ var ENGINE = "claude-code";
1163
+ var BASE = ".claude";
1164
+ var claudeCodeRenderer = {
1165
+ engine: ENGINE,
1166
+ renderSkill(skill) {
1167
+ if (!isSkillEngineAllowed(skill, ENGINE)) {
1168
+ return {
1169
+ files: [],
1170
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE}"`]
1171
+ };
1172
+ }
1173
+ const check = checkSkillCapabilities(skill, ENGINE);
1174
+ if (check.blockingWarnings.length > 0) {
1175
+ return { files: [], warnings: check.blockingWarnings };
1176
+ }
1177
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
1178
+ ${skill.body}
1179
+ `;
1180
+ return {
1181
+ files: [{ path: `${BASE}/skills/${skill.meta.id}/SKILL.md`, content }],
1182
+ warnings: check.degradedWarnings
1183
+ };
1184
+ },
1185
+ renderCmd(cmd) {
1186
+ const content = `${yamlFrontmatter(frontmatterDataForCmd(cmd))}
1187
+ ${cmd.body}
1188
+ `;
1189
+ return {
1190
+ files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
1191
+ warnings: []
1192
+ };
1193
+ }
1194
+ };
1195
+
1196
+ // src/renderers/codex-cli.ts
1197
+ var ENGINE2 = "codex-cli";
1198
+ var SKILLS_BASE = ".agents/skills";
1199
+ var codexCliRenderer = {
1200
+ engine: ENGINE2,
1201
+ renderSkill(skill) {
1202
+ if (!isSkillEngineAllowed(skill, ENGINE2)) {
1203
+ return {
1204
+ files: [],
1205
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE2}"`]
1206
+ };
1207
+ }
1208
+ const check = checkSkillCapabilities(skill, ENGINE2);
1209
+ if (check.blockingWarnings.length > 0) {
1210
+ return { files: [], warnings: check.blockingWarnings };
1211
+ }
1212
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
1213
+ ${skill.body}
1214
+ `;
1215
+ return {
1216
+ files: [{ path: `${SKILLS_BASE}/${skill.meta.id}/SKILL.md`, content }],
1217
+ warnings: check.degradedWarnings
1218
+ };
1219
+ },
1220
+ // Codex custom prompts are deprecated in favour of skills: nothing to render.
1221
+ renderCmd(_cmd) {
1222
+ return { files: [], warnings: [] };
1223
+ }
1224
+ };
1225
+
1226
+ // src/renderers/opencode.ts
1227
+ var ENGINE3 = "opencode";
1228
+ var BASE2 = ".opencode";
1229
+ var opencodeRenderer = {
1230
+ engine: ENGINE3,
1231
+ renderSkill(skill) {
1232
+ if (!isSkillEngineAllowed(skill, ENGINE3)) {
1233
+ return {
1234
+ files: [],
1235
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE3}"`]
1236
+ };
1237
+ }
1238
+ const check = checkSkillCapabilities(skill, ENGINE3);
1239
+ if (check.blockingWarnings.length > 0) {
1240
+ return { files: [], warnings: check.blockingWarnings };
1241
+ }
1242
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
1243
+ ${skill.body}
1244
+ `;
1245
+ return {
1246
+ files: [{ path: `${BASE2}/skills/${skill.meta.id}/SKILL.md`, content }],
1247
+ warnings: check.degradedWarnings
1248
+ };
1249
+ },
1250
+ renderCmd(cmd) {
1251
+ const content = `${yamlFrontmatter({ description: cmd.meta.description })}
1252
+ ${cmd.body}
1253
+ `;
1254
+ return {
1255
+ files: [{ path: `${BASE2}/commands/${cmd.meta.id}.md`, content }],
1256
+ warnings: []
1257
+ };
1258
+ }
1259
+ };
1260
+
1261
+ // src/renderers/index.ts
1262
+ var RENDERERS = {
1263
+ "claude-code": claudeCodeRenderer,
1264
+ "codex-cli": codexCliRenderer,
1265
+ opencode: opencodeRenderer
1266
+ };
1267
+ function getRenderer(engine) {
1268
+ return RENDERERS[engine];
1269
+ }
1270
+
1271
+ // src/renderers/intents-index.ts
1272
+ var INTRO = "User intents of this project, anchored to the code. Generated by `@vaubaan/harness` from `docs/intents/*.md`: edit the intents, not this file, then run `npx @vaubaan/harness update .`.";
1273
+ var EMPTY = "No intent yet. `/harn-intent <verb + object>` writes the first one, before the code.";
1274
+ function buildIntentsIndex(intentFiles) {
1275
+ const lines = ["# Intents", "", INTRO, ""];
1276
+ if (intentFiles.length === 0) lines.push(EMPTY);
1277
+ const sorted = [...intentFiles].sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
1278
+ for (const intentFile of sorted) {
1279
+ const status = intentFile.meta?.status ?? "proposed";
1280
+ const actors = intentFile.meta?.actors.join(", ") ?? "";
1281
+ lines.push(`- [${intentFile.title}](./${intentFile.file}) \u2014 ${status} \xB7 ${actors}`);
1282
+ for (const node of intentFile.nodes) {
1283
+ lines.push(`${" ".repeat(node.level)}- ${node.title} \u2014 ${node.effectiveStatus ?? status}`);
1284
+ }
1285
+ }
1286
+ return `${lines.join("\n")}
1287
+ `;
1288
+ }
1289
+
1290
+ // src/renderers/profiles-index.ts
1291
+ var INTRO2 = "Who this project serves, and what the intents do for them. Generated by `@vaubaan/harness` from `docs/profiles/*.md` and `docs/intents/*.md`: edit those, not this file, then run `npx @vaubaan/harness update .`.";
1292
+ var EMPTY2 = "No profile yet. The `harn-intent-writer` skill writes the first one from the research you point it to.";
1293
+ function buildProfilesIndex(profiles, intentFiles = []) {
1294
+ const lines = ["# Profiles", "", INTRO2];
1295
+ if (profiles.length === 0) lines.push("", EMPTY2);
1296
+ const sortedIntents = [...intentFiles].sort(
1297
+ (a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0
1298
+ );
1299
+ for (const profile of [...profiles].sort((a, b) => a.file < b.file ? -1 : 1)) {
1300
+ const theirs = sortedIntents.filter((file) => file.meta?.actors.includes(profile.slug));
1301
+ lines.push(
1302
+ "",
1303
+ `## [${profile.title}](./${profile.file}) \u2014 ${profile.meta?.status ?? "hypothesis"}`,
1304
+ ""
1305
+ );
1306
+ lines.push(
1307
+ theirs.length ? `Intents: ${theirs.map((f) => `[${f.title}](../intents/${f.file})`).join(", ")}.` : "Intents: none names this profile yet."
1308
+ );
1309
+ const served = (kind, item) => {
1310
+ const by = [];
1311
+ for (const file of theirs) {
1312
+ for (const node of file.nodes) {
1313
+ if (node[kind].includes(item.slug)) {
1314
+ by.push(`[${node.title}](../intents/${file.file})`);
1315
+ }
1316
+ }
1317
+ }
1318
+ if (by.length) return by.join(", ");
1319
+ return kind === "relieves" ? "*no intent relieves it yet*" : "*no intent delivers it yet*";
1320
+ };
1321
+ if (profile.pains.length) {
1322
+ lines.push("", "Pains, most severe first:", "");
1323
+ for (const pain of profile.pains) {
1324
+ lines.push(`- **${pain.name}** (\`${pain.slug}\`) \u2014 ${served("relieves", pain)}`);
1325
+ }
1326
+ }
1327
+ if (profile.gains.length) {
1328
+ lines.push("", "Gains:", "");
1329
+ for (const gain of profile.gains) {
1330
+ lines.push(`- **${gain.name}** (\`${gain.slug}\`) \u2014 ${served("delivers", gain)}`);
1331
+ }
1332
+ }
1333
+ }
1334
+ return `${lines.join("\n")}
1335
+ `;
1336
+ }
1337
+
1338
+ // src/render.ts
1339
+ var RenderError = class extends Error {
1340
+ constructor(message) {
1341
+ super(message);
1342
+ this.name = "RenderError";
1343
+ }
1344
+ };
1345
+ function mergeById(stock, added) {
1346
+ const result = /* @__PURE__ */ new Map();
1347
+ for (const item of stock) result.set(item.meta.id, item);
1348
+ if (added) {
1349
+ for (const item of added) result.set(item.meta.id, item);
1350
+ }
1351
+ return Array.from(result.values());
1352
+ }
1353
+ function removeByIds(items, disabled) {
1354
+ if (disabled.length === 0) return [...items];
1355
+ const disabledSet = new Set(disabled);
1356
+ return items.filter((item) => !disabledSet.has(item.meta.id));
1357
+ }
1358
+ function applyOverrides(harness, overrides) {
1359
+ const disabled = overrides?.disable ?? [];
1360
+ return {
1361
+ skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
1362
+ cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
1363
+ };
1364
+ }
1365
+ var CLAUDE_MD_STUB = "@AGENTS.md\n";
1366
+ function opencodeLast(engines) {
1367
+ return [...engines].sort((a, b) => Number(a === "opencode") - Number(b === "opencode"));
1368
+ }
1369
+ function servesAnActivePillar(skill, active) {
1370
+ return !skill.meta.pillars || skill.meta.pillars.some((pillar) => active.has(pillar));
1371
+ }
1372
+ function render(input) {
1373
+ const { engines } = input;
1374
+ if (engines.length === 0) {
1375
+ throw new RenderError("at least one engine must be selected");
1376
+ }
1377
+ const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
1378
+ const active = input.activePillars ?? allPillars();
1379
+ const merged = applyOverrides(base, input.overrides);
1380
+ const harness = {
1381
+ ...merged,
1382
+ skills: merged.skills.filter((skill) => servesAnActivePillar(skill, active))
1383
+ };
1384
+ const files = [];
1385
+ const warnings = [];
1386
+ const exposedSkills = /* @__PURE__ */ new Map();
1387
+ const exposedCmds = /* @__PURE__ */ new Map();
1388
+ for (const engine of opencodeLast(engines)) {
1389
+ const renderer = getRenderer(engine);
1390
+ const renderedSkillIds = /* @__PURE__ */ new Set();
1391
+ for (const skill of harness.skills) {
1392
+ const result = renderer.renderSkill(skill);
1393
+ warnings.push(...result.warnings);
1394
+ if (result.files.length > 0) {
1395
+ const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
1396
+ if (!alreadyVisible) files.push(...result.files);
1397
+ renderedSkillIds.add(skill.meta.id);
1398
+ exposedSkills.set(skill.meta.id, skill);
1399
+ }
1400
+ }
1401
+ for (const cmd of harness.cmds) {
1402
+ if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
1403
+ const result = renderer.renderCmd(cmd);
1404
+ warnings.push(...result.warnings);
1405
+ if (result.files.length > 0) {
1406
+ files.push(...result.files);
1407
+ exposedCmds.set(cmd.meta.id, cmd);
1408
+ }
1409
+ }
1410
+ }
1411
+ const umbrellaContent = buildUmbrellaBody({
1412
+ availableSkills: Array.from(exposedSkills.values()),
1413
+ availableCommands: Array.from(exposedCmds.values()),
1414
+ hasProjectSkills: (input.projectSkills?.length ?? 0) > 0,
1415
+ activePillars: active
1416
+ });
1417
+ files.push({ path: "AGENTS.md", content: umbrellaContent });
1418
+ if (engines.includes("claude-code")) {
1419
+ files.push({ path: "CLAUDE.md", content: CLAUDE_MD_STUB });
1420
+ }
1421
+ if (input.intentFiles) {
1422
+ files.push({ path: INTENTS_INDEX_PATH, content: buildIntentsIndex(input.intentFiles) });
1423
+ }
1424
+ if (input.profileFiles) {
1425
+ files.push({
1426
+ path: PROFILES_INDEX_PATH,
1427
+ content: buildProfilesIndex(input.profileFiles, input.intentFiles ?? [])
1428
+ });
1429
+ }
1430
+ return { files, warnings };
1431
+ }
1432
+
1433
+ // src/cli/plan-render.ts
1434
+ function resolveEngineList(requested) {
1435
+ if (!requested || requested.length === 0) {
1436
+ throw new Error(
1437
+ `no engine selected: pass --engines=<list> with one or more of ${ENGINES.join(", ")}`
1438
+ );
1439
+ }
1440
+ const engines = requested.map((e) => {
1441
+ if (!ENGINES.includes(e)) {
1442
+ throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
1443
+ }
1444
+ return e;
1445
+ });
1446
+ return [...new Set(engines)];
1447
+ }
1448
+ function defaultPackageDir() {
1449
+ const here = dirname2(fileURLToPath(import.meta.url));
1450
+ if (existsSync7(join8(here, "skills"))) return here;
1451
+ return resolve2(here, "..");
1452
+ }
1453
+ function planInit(args) {
1454
+ const engines = resolveEngineList(args.engines);
1455
+ const packageDir = args.packageDir ?? defaultPackageDir();
1456
+ const harness = loadHarness(packageDir);
1457
+ const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
1458
+ const projectSkills = loadProjectSkills(args.targetDir);
1459
+ const active = activePillars(args.targetDir);
1460
+ const output = render({
1461
+ harness,
1462
+ engines,
1463
+ overrides,
1464
+ projectSkills,
1465
+ activePillars: active,
1466
+ ...active.has("intents") ? { intentFiles: loadIntentFiles(args.targetDir) } : {},
1467
+ ...active.has("profiles") ? { profileFiles: readProfileFiles(args.targetDir) } : {}
1468
+ });
1469
+ return { engines, output };
1470
+ }
1471
+
1472
+ // src/linters/cross-links.ts
1473
+ import { existsSync as existsSync8 } from "fs";
1474
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join9, resolve as resolve3 } from "path";
1475
+ import fg3 from "fast-glob";
1476
+ var LINKED_DOC_IGNORES = [
1477
+ "**/node_modules/**",
1478
+ "**/dist/**",
1479
+ ".harness-overrides/**",
1480
+ "skills/**",
1481
+ "agents/**",
1482
+ "commands/**",
1483
+ "templates/**",
1484
+ "**/*.skill.md",
1485
+ "**/*.cmd.md",
1486
+ "**/*.agent.md"
1487
+ ];
1488
+ function resolveLink(repoRoot, sourceFile, link) {
1489
+ const noFrag = stripFragment(link);
1490
+ if (isAbsolute2(noFrag)) return join9(repoRoot, noFrag);
1491
+ return resolve3(dirname3(join9(repoRoot, sourceFile)), noFrag);
1492
+ }
1493
+ var crossLinks = {
1494
+ id: "lint:cross-links",
1495
+ pillars: ["all"],
1496
+ defaultSeverity: "error",
1497
+ run(repoRoot, ctx) {
1498
+ const extra = ctx?.config.ignore ?? [];
1499
+ const issues = [];
1500
+ const allDocs = fg3.sync("**/*.md", {
1501
+ cwd: repoRoot,
1502
+ absolute: false,
1503
+ ignore: [...LINKED_DOC_IGNORES, ...extra]
1504
+ });
1505
+ for (const f of allDocs) {
1506
+ for (const { url, line } of readLinks(readText(repoRoot, f))) {
1507
+ if (isExternalOrAnchor(url)) continue;
1508
+ const noFrag = stripFragment(url);
1509
+ if (noFrag === "" || noFrag.startsWith("data:")) continue;
1510
+ if (!existsSync8(resolveLink(repoRoot, f, url))) {
1511
+ issues.push({
1512
+ linter: this.id,
1513
+ severity: "error",
1514
+ file: f,
1515
+ line,
1516
+ message: `broken link: ${url}`
1517
+ });
1518
+ }
1519
+ }
1520
+ }
1521
+ return issues;
1522
+ }
1523
+ };
1524
+
1525
+ // src/linters/adr-no-tracks.ts
1526
+ var ADR_DIR = "docs/decisions";
1527
+ var adrNoTracks = {
1528
+ id: "lint:adr-no-tracks",
1529
+ pillars: ["decisions"],
1530
+ defaultSeverity: "error",
1531
+ suggestedSkills: ["/harn-decision"],
1532
+ run(repoRoot) {
1533
+ const issues = [];
1534
+ const files = listMarkdown(repoRoot, ADR_DIR);
1535
+ for (const f of files) {
1536
+ const text = readText(repoRoot, f);
1537
+ const { data } = parseFrontmatter2(text);
1538
+ if (!("tracks" in data)) continue;
1539
+ const value = data.tracks;
1540
+ if (Array.isArray(value) && value.length === 0) continue;
1541
+ issues.push({
1542
+ linter: this.id,
1543
+ severity: "error",
1544
+ file: f,
1545
+ message: "ADRs must not declare `tracks:` (or must set it to []). ADRs document a decision frozen in time, not the current state of code \u2014 use status: superseded to mark them obsolete instead."
1546
+ });
1547
+ }
1548
+ return issues;
1549
+ }
1550
+ };
1551
+
1552
+ // src/linters/cardinal-files.ts
1553
+ var REQUIRED_FILES = [
1554
+ { dir: "docs/tests", files: ["docs/tests/integration-tests.md", "docs/tests/e2e-tests.md"] },
1555
+ { dir: "docs/workflow", files: ["docs/workflow/coding-workflow.md"] }
1556
+ ];
1557
+ var cardinalFiles = {
1558
+ id: "lint:cardinal-files",
1559
+ pillars: ["tests", "workflow"],
1560
+ defaultSeverity: "error",
1561
+ suggestedSkills: ["/harn-test-plan", "/harn-workflow"],
1562
+ run(repoRoot) {
1563
+ const issues = [];
1564
+ for (const { dir, files } of REQUIRED_FILES) {
1565
+ if (!dirExists(repoRoot, dir)) continue;
1566
+ for (const f of files) {
1567
+ if (!fileExists(repoRoot, f)) {
1568
+ issues.push({
1569
+ linter: this.id,
1570
+ severity: "error",
1571
+ file: f,
1572
+ message: `missing required cardinal file: ${f}`
1573
+ });
1574
+ }
1575
+ }
1576
+ }
1577
+ return issues;
1578
+ }
1579
+ };
1580
+
1581
+ // src/linters/config.ts
1582
+ import { cosmiconfigSync } from "cosmiconfig";
1583
+ var DEFAULT_CONFIG = { ignore: [] };
1584
+ function loadLintConfig(repoRoot) {
1585
+ const explorer = cosmiconfigSync("harness", {
1586
+ searchPlaces: [
1587
+ "package.json",
1588
+ ".harnessrc",
1589
+ ".harnessrc.json",
1590
+ ".harnessrc.yaml",
1591
+ ".harnessrc.yml",
1592
+ "harness.config.js",
1593
+ "harness.config.cjs"
1594
+ ]
1595
+ });
1596
+ const result = explorer.search(repoRoot);
1597
+ if (!result || result.isEmpty) return DEFAULT_CONFIG;
1598
+ const raw = result.config;
1599
+ if (!raw) return DEFAULT_CONFIG;
1600
+ const lint = raw.lint;
1601
+ if (!lint) return DEFAULT_CONFIG;
1602
+ const ignore = lint.ignore;
1603
+ if (!Array.isArray(ignore)) return DEFAULT_CONFIG;
1604
+ return { ignore: ignore.filter((x) => typeof x === "string") };
1605
+ }
1606
+
1607
+ // src/linters/decision-schema.ts
1608
+ var decisionSchema = {
1609
+ id: "lint:decision-schema",
1610
+ pillars: ["decisions"],
1611
+ defaultSeverity: "error",
1612
+ suggestedSkills: ["/harn-decision"],
1613
+ run(repoRoot) {
1614
+ const issues = [];
1615
+ const files = listMarkdown(repoRoot, "docs/decisions");
1616
+ for (const f of files) {
1617
+ const text = readText(repoRoot, f);
1618
+ for (const { label, pattern } of ADR_SECTIONS) {
1619
+ if (!pattern.test(text)) {
1620
+ issues.push({
1621
+ linter: this.id,
1622
+ severity: "error",
1623
+ file: f,
1624
+ message: `missing required section: "${label}"`
1625
+ });
1626
+ }
1627
+ }
1628
+ }
1629
+ return issues;
1630
+ }
1631
+ };
1632
+
1633
+ // src/linters/doc-layout.ts
1634
+ var docLayout = {
1635
+ id: "lint:doc-layout",
1636
+ pillars: ["all"],
1637
+ defaultSeverity: "error",
1638
+ run(repoRoot) {
1639
+ return emptyPillarDirs(repoRoot).map((dir) => ({
1640
+ linter: this.id,
1641
+ severity: "error",
1642
+ file: dir,
1643
+ message: `empty pillar folder: git does not record ${dir}/, so the pillar would be active on this machine only \u2014 fill it (\`npx @vaubaan/harness add ${dir.replace("docs/", "")}\`) or remove it`
1644
+ }));
1645
+ }
1646
+ };
1647
+
1648
+ // src/linters/frontmatter-tracks.ts
1649
+ var TRACKED_DIRS = ["docs/handbook", "docs/tests", "docs/workflow"];
1650
+ var frontmatterTracks = {
1651
+ id: "lint:frontmatter-tracks",
1652
+ pillars: ["handbook", "tests", "workflow"],
1653
+ defaultSeverity: "error",
1654
+ suggestedSkills: ["/harn-handbook", "/harn-test-plan", "/harn-workflow"],
1655
+ run(repoRoot) {
1656
+ const issues = [];
1657
+ for (const dir of TRACKED_DIRS) {
1658
+ const files = listMarkdown(repoRoot, dir);
1659
+ for (const f of files) {
1660
+ const text = readText(repoRoot, f);
1661
+ const { data } = parseFrontmatter2(text);
1662
+ if (!Array.isArray(data.tracks)) {
1663
+ issues.push({
1664
+ linter: this.id,
1665
+ severity: "error",
1666
+ file: f,
1667
+ message: "missing frontmatter `tracks:` array"
1668
+ });
1669
+ continue;
1670
+ }
1671
+ for (const tracked of data.tracks) {
1672
+ if (typeof tracked !== "string") {
1673
+ issues.push({
1674
+ linter: this.id,
1675
+ severity: "error",
1676
+ file: f,
1677
+ message: "`tracks` entries must be strings"
1678
+ });
1679
+ continue;
1680
+ }
1681
+ if (!trackedPathExists(repoRoot, tracked)) {
1682
+ issues.push({
1683
+ linter: this.id,
1684
+ severity: "error",
1685
+ file: f,
1686
+ message: `tracked path does not exist: ${tracked}`
1687
+ });
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1692
+ return issues;
1693
+ }
1694
+ };
1695
+
1696
+ // src/linters/generated-fresh.ts
1697
+ import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
1698
+ import { join as join10, resolve as resolve4 } from "path";
1699
+ var FIX = "run `npx @vaubaan/harness update .` and commit the result";
1700
+ var generatedFresh = {
1701
+ id: "lint:generated-fresh",
1702
+ pillars: ["repo-root"],
1703
+ defaultSeverity: "error",
1704
+ run(repoRoot) {
1705
+ const issue = (file, message) => ({
1706
+ linter: this.id,
1707
+ severity: "error",
1708
+ file,
1709
+ message
1710
+ });
1711
+ let manifest;
1712
+ try {
1713
+ manifest = readManifest(repoRoot);
1714
+ } catch (error) {
1715
+ const reason = error instanceof Error ? error.message : String(error);
1716
+ return [issue(".harness-manifest.json", `invalid harness manifest: ${reason}`)];
1717
+ }
1718
+ if (!manifest) return [];
1719
+ const overridesParent = manifest.overridesDir ? resolve4(repoRoot, manifest.overridesDir) : repoRoot;
1720
+ const hasOverrides = existsSync9(join10(overridesParent, ".harness-overrides"));
1721
+ let rendered;
1722
+ try {
1723
+ rendered = planInit({
1724
+ targetDir: repoRoot,
1725
+ engines: manifest.engines,
1726
+ overridesDir: hasOverrides ? overridesParent : void 0
1727
+ });
1728
+ } catch (error) {
1729
+ const reason = error instanceof Error ? error.message : String(error);
1730
+ return [issue(".harness-manifest.json", `cannot render the harness: ${reason}`)];
1731
+ }
1732
+ const preserved = new Set(manifest.preservedFiles ?? []);
1733
+ const issues = [];
1734
+ const renderedPaths = /* @__PURE__ */ new Set();
1735
+ for (const file of rendered.output.files) {
1736
+ if (preserved.has(file.path)) continue;
1737
+ renderedPaths.add(file.path);
1738
+ const full = join10(repoRoot, file.path);
1739
+ if (!existsSync9(full)) {
1740
+ issues.push(issue(file.path, `generated file is missing; ${FIX}`));
1741
+ } else if (readFileSync7(full, "utf8") !== file.content) {
1742
+ issues.push(
1743
+ issue(
1744
+ file.path,
1745
+ `generated file differs from the current render; edit its source in docs/ or .harness-overrides/, then ${FIX}`
1746
+ )
1747
+ );
1748
+ }
1749
+ }
1750
+ for (const path of manifest.files) {
1751
+ if (renderedPaths.has(path) || preserved.has(path) || RELEASED_PATHS.includes(path)) continue;
1752
+ if (existsSync9(join10(repoRoot, path))) {
1753
+ issues.push(issue(path, `stale generated file, no longer rendered; ${FIX}`));
1754
+ }
1755
+ }
1756
+ return issues;
1757
+ }
1758
+ };
1759
+
1760
+ // src/linters/gitignore-harness.ts
1761
+ var REQUIRED_GITIGNORE_ENTRIES = [
1762
+ ".harness-overrides/",
1763
+ ".vaubaan/"
1764
+ ];
1765
+ var FORBIDDEN_GITIGNORE_ENTRIES = [
1766
+ "AGENTS.md",
1767
+ "CLAUDE.md",
1768
+ ".claude/",
1769
+ ".codex/",
1770
+ ".agents/",
1771
+ ".opencode/",
1772
+ ".harness-manifest.json",
1773
+ "docs/intents/README.md",
1774
+ "docs/profiles/README.md"
1775
+ ];
1776
+ function gitignoreEntries(text) {
1777
+ const entries = /* @__PURE__ */ new Set();
1778
+ for (const raw of text.split("\n")) {
1779
+ const line = raw.trim();
1780
+ if (!line || line.startsWith("#")) continue;
1781
+ entries.add(line.replace(/^\//, "").replace(/\/$/, ""));
1782
+ }
1783
+ return entries;
1784
+ }
1785
+ function normalize(entry) {
1786
+ return entry.replace(/\/$/, "");
1787
+ }
1788
+ function missingGitignoreEntries(text) {
1789
+ const lines = gitignoreEntries(text);
1790
+ return REQUIRED_GITIGNORE_ENTRIES.filter((entry) => !lines.has(normalize(entry)));
1791
+ }
1792
+ function forbiddenGitignoreEntries(text) {
1793
+ const lines = gitignoreEntries(text);
1794
+ return FORBIDDEN_GITIGNORE_ENTRIES.filter((entry) => lines.has(normalize(entry)));
1795
+ }
1796
+ var gitignoreHarness = {
1797
+ id: "lint:gitignore-harness",
1798
+ pillars: ["repo-root"],
1799
+ defaultSeverity: "error",
1800
+ run(repoRoot) {
1801
+ if (!fileExists(repoRoot, ".gitignore")) {
1802
+ return [
1803
+ {
1804
+ linter: this.id,
1805
+ severity: "error",
1806
+ file: ".gitignore",
1807
+ message: ".gitignore is missing at repo root"
1808
+ }
1809
+ ];
1810
+ }
1811
+ const text = readText(repoRoot, ".gitignore");
1812
+ const issues = [];
1813
+ for (const entry of missingGitignoreEntries(text)) {
1814
+ issues.push({
1815
+ linter: this.id,
1816
+ severity: "error",
1817
+ file: ".gitignore",
1818
+ message: `.gitignore must contain "${entry}"`
1819
+ });
1820
+ }
1821
+ for (const entry of forbiddenGitignoreEntries(text)) {
1822
+ issues.push({
1823
+ linter: this.id,
1824
+ severity: "error",
1825
+ file: ".gitignore",
1826
+ message: `.gitignore must not contain "${entry}": files the harness generates are committed`
1827
+ });
1828
+ }
1829
+ return issues;
1830
+ }
1831
+ };
1832
+
1833
+ // src/linters/intent-anchors.ts
1834
+ var intentAnchors = {
1835
+ id: "lint:intent-anchors",
1836
+ pillars: ["intents"],
1837
+ defaultSeverity: "error",
1838
+ suggestedSkills: ["/harn-intent"],
1839
+ run(repoRoot) {
1840
+ const issues = [];
1841
+ for (const intentFile of readIntentFiles(repoRoot)) {
1842
+ for (const node of intentFile.nodes) {
1843
+ if (node.effectiveStatus === "deprecated") continue;
1844
+ for (const anchor of node.anchors) {
1845
+ if (trackedPathExists(repoRoot, anchor)) continue;
1846
+ issues.push({
1847
+ linter: this.id,
1848
+ severity: "error",
1849
+ file: intentFile.path,
1850
+ line: node.line,
1851
+ message: `"${node.title}": anchor matches no file: ${anchor}`
1852
+ });
1853
+ }
1854
+ }
1855
+ }
1856
+ return issues;
1857
+ }
1858
+ };
1859
+
1860
+ // src/linters/intent-graph.ts
1861
+ var intentGraph = {
1862
+ id: "lint:intent-graph",
1863
+ pillars: ["intents"],
1864
+ defaultSeverity: "warning",
1865
+ suggestedSkills: ["/harn-intent"],
1866
+ run(repoRoot) {
1867
+ const intentFiles = readIntentFiles(repoRoot);
1868
+ const terminals = intentFiles.flatMap(
1869
+ (intentFile) => intentFile.nodes.filter((node) => node.isTerminal).map((node) => ({ intentFile, node }))
1870
+ );
1871
+ const created = new Set(terminals.flatMap(({ node }) => node.creates));
1872
+ const issues = [];
1873
+ for (const { intentFile, node } of terminals) {
1874
+ for (const entity of node.requires) {
1875
+ if (created.has(entity)) continue;
1876
+ issues.push({
1877
+ linter: this.id,
1878
+ severity: "warning",
1879
+ file: intentFile.path,
1880
+ line: node.line,
1881
+ message: `"${node.title}": entity \`${entity}\` is required here but no terminal intent creates it`
1882
+ });
1883
+ }
1884
+ }
1885
+ return issues;
1886
+ }
1887
+ };
1888
+
1889
+ // src/linters/intent-profiles.ts
1890
+ var intentProfiles = {
1891
+ id: "lint:intent-profiles",
1892
+ pillars: ["intents", "profiles"],
1893
+ defaultSeverity: "error",
1894
+ suggestedSkills: ["/harn-intent"],
1895
+ run(repoRoot) {
1896
+ const issues = [];
1897
+ const intentFiles = readIntentFiles(repoRoot);
1898
+ const profilesActive = dirExists(repoRoot, PROFILES_DIR);
1899
+ const profiles = new Map(readProfileFiles(repoRoot).map((p) => [p.slug, p]));
1900
+ for (const intentFile of intentFiles) {
1901
+ const report = (message, line) => {
1902
+ issues.push({
1903
+ linter: this.id,
1904
+ severity: "error",
1905
+ file: intentFile.path,
1906
+ ...line !== void 0 ? { line } : {},
1907
+ message
1908
+ });
1909
+ };
1910
+ const actors = intentFile.meta?.actors ?? [];
1911
+ if (profilesActive) {
1912
+ for (const actor of actors) {
1913
+ if (!profiles.has(actor)) {
1914
+ report(`actor \`${actor}\` is not a profile: no ${PROFILES_DIR}/${actor}.md`, 1);
1915
+ }
1916
+ }
1917
+ }
1918
+ const theirs = actors.flatMap((actor) => profiles.get(actor) ?? []);
1919
+ const pains = new Set(theirs.flatMap((p) => p.pains.map((item) => item.slug)));
1920
+ const gains = new Set(theirs.flatMap((p) => p.gains.map((item) => item.slug)));
1921
+ for (const node of intentFile.nodes) {
1922
+ const fields = [
1923
+ { key: "relieves", values: node.relieves, known: pains, kind: "pain" },
1924
+ { key: "delivers", values: node.delivers, known: gains, kind: "gain" }
1925
+ ];
1926
+ for (const { key, values, known, kind } of fields) {
1927
+ if (values.length === 0) continue;
1928
+ const line = node.fieldLines[key] ?? node.line;
1929
+ if (!profilesActive) {
1930
+ report(
1931
+ `"${node.title}": \`${key}:\` needs the profiles pillar \u2014 \`npx @vaubaan/harness add profiles\``,
1932
+ line
1933
+ );
1934
+ continue;
1935
+ }
1936
+ for (const slug of values) {
1937
+ if (!known.has(slug)) {
1938
+ report(
1939
+ `"${node.title}": \`${slug}\` is not a ${kind} of ${actors.length ? actors.map((a) => `\`${a}\``).join(", ") : "any actor"}`,
1940
+ line
1941
+ );
1942
+ }
1943
+ }
1944
+ }
1945
+ }
1946
+ }
1947
+ return issues;
1948
+ }
1949
+ };
1950
+
1951
+ // src/linters/intent-schema.ts
1952
+ var DERIVABLE_FIELDS = /* @__PURE__ */ new Set(["uses", "guards"]);
1953
+ var intentSchema = {
1954
+ id: "lint:intent-schema",
1955
+ pillars: ["intents"],
1956
+ defaultSeverity: "error",
1957
+ suggestedSkills: ["/harn-intent"],
1958
+ run(repoRoot) {
1959
+ const issues = [];
1960
+ for (const intentFile of readIntentFiles(repoRoot)) {
1961
+ const report = (message, line) => {
1962
+ issues.push({
1963
+ linter: this.id,
1964
+ severity: "error",
1965
+ file: intentFile.path,
1966
+ ...line !== void 0 ? { line } : {},
1967
+ message
1968
+ });
1969
+ };
1970
+ for (const error of intentFile.errors) report(error.message, error.line);
1971
+ for (const spec of intentFileSpecs(intentFile.meta)) {
1972
+ if (!fileExists(repoRoot, resolveSpecPath(intentFile.path, spec))) {
1973
+ report(`frontmatter \`spec\` does not resolve: ${spec}`, 1);
1974
+ }
1975
+ }
1976
+ for (const node of intentFile.nodes) {
1977
+ const at = (message) => report(`"${node.title}": ${message}`, node.line);
1978
+ for (const { key, line } of node.unknownFields) {
1979
+ report(
1980
+ DERIVABLE_FIELDS.has(key) ? `"${node.title}": \`${key}:\` is derivable, never declared` : `"${node.title}": unknown field \`${key}:\``,
1981
+ line
1982
+ );
1983
+ }
1984
+ if (node.spec !== void 0 && !fileExists(repoRoot, resolveSpecPath(intentFile.path, node.spec))) {
1985
+ report(`"${node.title}": \`spec:\` does not resolve: ${node.spec}`, node.fieldLines.spec);
1986
+ }
1987
+ if (!node.isTerminal) {
1988
+ for (const field of TERMINAL_FIELDS) {
1989
+ const line = node.fieldLines[field];
1990
+ if (line !== void 0) {
1991
+ report(
1992
+ `"${node.title}": \`${field}:\` is a field of a terminal intent, this node has sub-intents`,
1993
+ line
1994
+ );
1995
+ }
1996
+ }
1997
+ continue;
1998
+ }
1999
+ if (Object.keys(node.fieldLines).length === 0) {
2000
+ at("a terminal intent carries at least one field");
2001
+ continue;
2002
+ }
2003
+ if (node.effectiveStatus === "implemented" && node.anchors.length === 0) {
2004
+ at("an `implemented` intent needs `anchors:`");
2005
+ }
2006
+ if (node.effectiveStatus === "proposed" && node.acceptance.length === 0) {
2007
+ at("a `proposed` intent needs `acceptance:` with at least one `- ` item");
2008
+ }
2009
+ }
2010
+ }
2011
+ return issues;
2012
+ }
2013
+ };
2014
+
2015
+ // src/linters/orphan-decisions.ts
2016
+ import { basename as basename4 } from "path";
2017
+ import fg4 from "fast-glob";
2018
+ var orphanDecisions = {
2019
+ id: "lint:orphan-decisions",
2020
+ pillars: ["decisions"],
2021
+ defaultSeverity: "warning",
2022
+ suggestedSkills: ["/harn-handbook"],
2023
+ run(repoRoot, ctx) {
2024
+ const extra = ctx?.config.ignore ?? [];
2025
+ const issues = [];
2026
+ const adrs = listMarkdown(repoRoot, "docs/decisions");
2027
+ if (adrs.length === 0) return issues;
2028
+ const otherDocs = fg4.sync("**/*.md", {
2029
+ cwd: repoRoot,
2030
+ absolute: false,
2031
+ ignore: [
2032
+ "**/node_modules/**",
2033
+ "**/dist/**",
2034
+ ".harness-overrides/**",
2035
+ "docs/decisions/**",
2036
+ "skills/**",
2037
+ "agents/**",
2038
+ "commands/**",
2039
+ "templates/**",
2040
+ ...extra
2041
+ ]
2042
+ });
2043
+ const referenceCorpus = otherDocs.map((f) => readText(repoRoot, f)).join("\n");
2044
+ for (const adr of adrs) {
2045
+ const filename = basename4(adr);
2046
+ const stem = filename.replace(/\.md$/, "");
2047
+ const referenced = referenceCorpus.includes(filename) || referenceCorpus.includes(stem);
2048
+ if (!referenced) {
2049
+ issues.push({
2050
+ linter: this.id,
2051
+ severity: "warning",
2052
+ file: adr,
2053
+ message: "ADR is not referenced by any other doc file (orphan)"
2054
+ });
2055
+ }
2056
+ }
2057
+ return issues;
2058
+ }
2059
+ };
2060
+
2061
+ // src/linters/profile-schema.ts
2062
+ import { posix as posix2 } from "path";
2063
+ var EXTERNAL = /^[a-z][a-z0-9+.-]*:/i;
2064
+ var profileSchema = {
2065
+ id: "lint:profile-schema",
2066
+ pillars: ["profiles"],
2067
+ defaultSeverity: "error",
2068
+ suggestedSkills: ["/harn-intent"],
2069
+ run(repoRoot) {
2070
+ const issues = [];
2071
+ for (const profile of readProfileFiles(repoRoot)) {
2072
+ const report = (message, line) => {
2073
+ issues.push({
2074
+ linter: this.id,
2075
+ severity: "error",
2076
+ file: profile.path,
2077
+ ...line !== void 0 ? { line } : {},
2078
+ message
2079
+ });
2080
+ };
2081
+ for (const error of profile.errors) report(error.message, error.line);
2082
+ const evidence = profileEvidence(profile.meta);
2083
+ if (profile.meta?.status === "validated" && evidence.length === 0) {
2084
+ report("a `validated` profile needs `evidence:` \u2014 without it, it is a `hypothesis`", 1);
2085
+ }
2086
+ for (const link of evidence) {
2087
+ if (EXTERNAL.test(link)) continue;
2088
+ const target = posix2.normalize(
2089
+ posix2.join(posix2.dirname(profile.path), link.split("#")[0] ?? "")
2090
+ );
2091
+ if (!fileExists(repoRoot, target)) report(`\`evidence\` does not resolve: ${link}`, 1);
2092
+ }
2093
+ }
2094
+ return issues;
2095
+ }
2096
+ };
2097
+
2098
+ // src/linters/quality-schema.ts
2099
+ var QUALITY_DIR = "docs/quality";
2100
+ var CARDINAL_FILE = `${QUALITY_DIR}/code-quality.md`;
2101
+ var REQUIRED_SECTIONS = [
2102
+ {
2103
+ label: "Mechanical checks",
2104
+ pattern: /^##\s+(Mechanical\s+checks|V[ée]rifications\s+m[ée]caniques)\s*$/im
2105
+ },
2106
+ { label: "Project rules", pattern: /^##\s+(Project\s+rules|R[èe]gles\s+du\s+projet)\s*$/im },
2107
+ {
2108
+ label: "Accepted deviations",
2109
+ pattern: /^##\s+(Accepted\s+deviations|[ÉE]carts\s+assum[ée]s)\s*$/im
2110
+ }
2111
+ ];
2112
+ var qualitySchema = {
2113
+ id: "lint:quality-schema",
2114
+ pillars: ["quality"],
2115
+ defaultSeverity: "error",
2116
+ run(repoRoot) {
2117
+ if (!dirExists(repoRoot, QUALITY_DIR)) return [];
2118
+ if (!fileExists(repoRoot, CARDINAL_FILE)) {
2119
+ return [
2120
+ {
2121
+ linter: this.id,
2122
+ severity: "error",
2123
+ file: CARDINAL_FILE,
2124
+ message: `missing required cardinal file: ${CARDINAL_FILE}`
2125
+ }
2126
+ ];
2127
+ }
2128
+ const text = readText(repoRoot, CARDINAL_FILE);
2129
+ return REQUIRED_SECTIONS.filter(({ pattern }) => !pattern.test(text)).map(({ label }) => ({
2130
+ linter: this.id,
2131
+ severity: "error",
2132
+ file: CARDINAL_FILE,
2133
+ message: `missing required section: "${label}"`
2134
+ }));
2135
+ }
2136
+ };
2137
+
2138
+ // src/linters/readme-presence.ts
2139
+ var readmePresence = {
2140
+ id: "lint:readme-presence",
2141
+ pillars: ["readme"],
2142
+ defaultSeverity: "error",
2143
+ suggestedSkills: ["/harn-readme"],
2144
+ run(repoRoot) {
2145
+ if (fileExists(repoRoot, "README.md")) return [];
2146
+ return [
2147
+ {
2148
+ linter: this.id,
2149
+ severity: "error",
2150
+ file: "README.md",
2151
+ message: "README.md is missing at repo root"
2152
+ }
2153
+ ];
2154
+ }
2155
+ };
2156
+
2157
+ // src/linters/readme-sections.ts
2158
+ var REQUIRED_SECTIONS2 = [
2159
+ /^#\s+\S/m,
2160
+ /^##?\s+(What is this|Quick start)/im,
2161
+ /^##?\s+(Quick start|Install|Getting started)/im
2162
+ ];
2163
+ var REQUIRED_LABELS = ["title (# H1)", "What is this / intro", "Quick start / Install"];
2164
+ var readmeSections = {
2165
+ id: "lint:readme-sections",
2166
+ pillars: ["readme"],
2167
+ defaultSeverity: "error",
2168
+ suggestedSkills: ["/harn-readme"],
2169
+ run(repoRoot) {
2170
+ if (!fileExists(repoRoot, "README.md")) return [];
2171
+ const text = readText(repoRoot, "README.md");
2172
+ const issues = [];
2173
+ for (let i = 0; i < REQUIRED_SECTIONS2.length; i++) {
2174
+ const pattern = REQUIRED_SECTIONS2[i];
2175
+ const label = REQUIRED_LABELS[i];
2176
+ if (pattern && !pattern.test(text)) {
2177
+ issues.push({
2178
+ linter: this.id,
2179
+ severity: "error",
2180
+ file: "README.md",
2181
+ message: `missing required section: ${label}`
2182
+ });
2183
+ }
2184
+ }
2185
+ return issues;
2186
+ }
2187
+ };
2188
+
2189
+ // src/linters/spec-has-content.ts
2190
+ var specHasContent = {
2191
+ id: "lint:spec-has-content",
2192
+ pillars: ["spec"],
2193
+ defaultSeverity: "warning",
2194
+ suggestedSkills: ["/harn-spec"],
2195
+ run(repoRoot) {
2196
+ const files = listMarkdown(repoRoot, "docs/spec");
2197
+ if (files.length > 0) return [];
2198
+ return [
2199
+ {
2200
+ linter: this.id,
2201
+ severity: "warning",
2202
+ file: "docs/spec",
2203
+ message: "no spec yet: docs/spec/ has no markdown file \u2014 write the first spec document"
2204
+ }
2205
+ ];
2206
+ }
2207
+ };
2208
+
2209
+ // src/linters/spec-tech-agnostic.ts
2210
+ function maskFencedBlocks(text) {
2211
+ return text.replace(/```[\s\S]*?```/g, (m) => m.replace(/[^\n]/g, " "));
2212
+ }
2213
+ var TECH_BLOCKLIST = [
2214
+ { pattern: /\bNext\.?js\b/i, keyword: "Next.js" },
2215
+ { pattern: /\bSupabase\b/i, keyword: "Supabase" },
2216
+ { pattern: /\bVercel\b/i, keyword: "Vercel" },
2217
+ { pattern: /\bReact\b/, keyword: "React" },
2218
+ { pattern: /\bTypeScript\b/, keyword: "TypeScript" },
2219
+ { pattern: /\bDocker\b/, keyword: "Docker" },
2220
+ { pattern: /\bKubernetes\b/i, keyword: "Kubernetes" },
2221
+ { pattern: /\bPostgres(QL)?\b/i, keyword: "Postgres" },
2222
+ { pattern: /\bMySQL\b/i, keyword: "MySQL" },
2223
+ { pattern: /\bRedis\b/i, keyword: "Redis" },
2224
+ { pattern: /\bnpm\b/, keyword: "npm" },
2225
+ { pattern: /\bpnpm\b/, keyword: "pnpm" },
2226
+ { pattern: /\byarn\b/, keyword: "yarn" }
2227
+ ];
2228
+ var specTechAgnostic = {
2229
+ id: "lint:spec-tech-agnostic",
2230
+ pillars: ["spec"],
2231
+ defaultSeverity: "error",
2232
+ suggestedSkills: ["/harn-spec"],
2233
+ run(repoRoot) {
2234
+ const issues = [];
2235
+ const files = listMarkdown(repoRoot, "docs/spec");
2236
+ for (const f of files) {
2237
+ const text = maskFencedBlocks(readText(repoRoot, f));
2238
+ for (const { pattern, keyword } of TECH_BLOCKLIST) {
2239
+ if (pattern.test(text)) {
2240
+ const issue = {
2241
+ linter: this.id,
2242
+ severity: "error",
2243
+ file: f,
2244
+ message: `forbidden tech keyword "${keyword}" \u2014 should be in handbook/ or decisions/`
2245
+ };
2246
+ const line = findLineNumber(text, pattern);
2247
+ if (line !== void 0) issue.line = line;
2248
+ issues.push(issue);
2249
+ }
2250
+ }
2251
+ }
2252
+ return issues;
2253
+ }
2254
+ };
2255
+
2256
+ // src/linters/tracks-drift.ts
2257
+ import fg5 from "fast-glob";
2258
+ var TRACKED_DIRS2 = ["docs/handbook", "docs/tests", "docs/workflow"];
2259
+ var INTENTS_DIR2 = "docs/intents";
2260
+ var DEFAULT_DRIFT_THRESHOLD = 10;
2261
+ function expandGlob(repoRoot, pattern) {
2262
+ if (pattern.includes("*")) {
2263
+ return fg5.sync(pattern, { cwd: repoRoot, absolute: false });
2264
+ }
2265
+ return [pattern];
2266
+ }
2267
+ function trackedPaths(dir, file, text, data) {
2268
+ if (dir === INTENTS_DIR2) {
2269
+ const anchors = parseIntentFile(file, text).nodes.flatMap((node) => node.anchors);
2270
+ return anchors.length > 0 ? [...new Set(anchors)] : void 0;
2271
+ }
2272
+ return Array.isArray(data.tracks) ? data.tracks : void 0;
2273
+ }
2274
+ function driftOf(repoRoot, file) {
2275
+ const dir = TRACKED_DIRS2.find((d) => file.startsWith(`${d}/`)) ?? (file.startsWith(`${INTENTS_DIR2}/`) ? INTENTS_DIR2 : void 0);
2276
+ if (!dir) return void 0;
2277
+ const text = readText(repoRoot, file);
2278
+ const { data } = parseFrontmatter2(text);
2279
+ const tracks = trackedPaths(dir, file, text, data);
2280
+ if (!tracks) return void 0;
2281
+ const docCommit = gitLastCommitForPath(repoRoot, file);
2282
+ if (!docCommit) return void 0;
2283
+ const threshold = typeof data.driftThreshold === "number" && data.driftThreshold > 0 ? data.driftThreshold : DEFAULT_DRIFT_THRESHOLD;
2284
+ let commits = 0;
2285
+ const tracked = [];
2286
+ for (const entry of tracks) {
2287
+ if (typeof entry !== "string") continue;
2288
+ tracked.push(entry);
2289
+ const targets = expandGlob(repoRoot, entry);
2290
+ for (const t of targets.length > 0 ? targets : [entry]) {
2291
+ commits += gitCommitsSince(repoRoot, t, docCommit.hash);
2292
+ }
2293
+ }
2294
+ return { commits, threshold, tracked };
2295
+ }
2296
+ var tracksDrift = {
2297
+ id: "lint:tracks-drift",
2298
+ pillars: ["handbook", "tests", "workflow", "intents"],
2299
+ defaultSeverity: "warning",
2300
+ suggestedSkills: ["/harn-drift", "/harn-handbook"],
2301
+ run(repoRoot) {
2302
+ const issues = [];
2303
+ for (const dir of [...TRACKED_DIRS2, INTENTS_DIR2]) {
2304
+ for (const f of listMarkdown(repoRoot, dir)) {
2305
+ const drift2 = driftOf(repoRoot, f);
2306
+ if (!drift2 || drift2.commits <= drift2.threshold) continue;
2307
+ issues.push({
2308
+ linter: this.id,
2309
+ severity: "warning",
2310
+ file: f,
2311
+ message: `tracked files changed in ${drift2.commits} commits since doc last edit (threshold ${drift2.threshold})`
2312
+ });
2313
+ }
2314
+ }
2315
+ return issues;
2316
+ }
2317
+ };
2318
+
2319
+ // src/linters/index.ts
2320
+ var ALL_LINTERS = [
2321
+ readmePresence,
2322
+ readmeSections,
2323
+ docLayout,
2324
+ cardinalFiles,
2325
+ decisionSchema,
2326
+ adrNoTracks,
2327
+ frontmatterTracks,
2328
+ tracksDrift,
2329
+ specTechAgnostic,
2330
+ specHasContent,
2331
+ crossLinks,
2332
+ orphanDecisions,
2333
+ gitignoreHarness,
2334
+ qualitySchema,
2335
+ intentSchema,
2336
+ intentAnchors,
2337
+ intentVocabulary,
2338
+ intentGraph,
2339
+ intentProfiles,
2340
+ profileSchema,
2341
+ generatedFresh
2342
+ ];
2343
+ function runLinters(repoRoot, opts = {}) {
2344
+ const config = loadLintConfig(repoRoot);
2345
+ const ctx = { repoRoot, config };
2346
+ const filtered = ALL_LINTERS.filter((l) => {
2347
+ if (opts.only && !opts.only.includes(l.id)) return false;
2348
+ if (opts.pillar && !l.pillars.includes(opts.pillar) && !l.pillars.includes("all")) return false;
2349
+ return true;
2350
+ });
2351
+ const issues = [];
2352
+ for (const linter of filtered) {
2353
+ try {
2354
+ issues.push(...linter.run(repoRoot, ctx));
2355
+ } catch (err) {
2356
+ issues.push({
2357
+ linter: linter.id,
2358
+ severity: "error",
2359
+ file: "<internal>",
2360
+ message: `linter crashed: ${err instanceof Error ? err.message : String(err)}`
2361
+ });
2362
+ }
2363
+ }
2364
+ const errors = issues.filter((i) => i.severity === "error").length;
2365
+ const warnings = issues.filter((i) => i.severity === "warning").length;
2366
+ return {
2367
+ version: 1,
2368
+ summary: { errors, warnings, pass: errors === 0 },
2369
+ issues
2370
+ };
2371
+ }
2372
+
2373
+ // src/view/graph.ts
2374
+ var NODE_TYPES = [
2375
+ "readme",
2376
+ "spec",
2377
+ "section",
2378
+ "term",
2379
+ "decision",
2380
+ "alternative",
2381
+ "handbook",
2382
+ "test-plan",
2383
+ "known-gap",
2384
+ "workflow",
2385
+ "quality",
2386
+ "doc",
2387
+ "intent-file",
2388
+ "intent",
2389
+ "linter",
2390
+ "skill",
2391
+ "command",
2392
+ "rendered-file",
2393
+ "path",
2394
+ "glob",
2395
+ "lesson"
2396
+ ];
2397
+ var HARNESS_SOURCE = "@vaubaan/harness";
2398
+ var LESSONS_FILE = ".vaubaan/lessons/lessons.json";
2399
+ var PILLAR_PATHS = {
2400
+ readme: ["README.md"],
2401
+ spec: ["docs/spec/"],
2402
+ decisions: ["docs/decisions/"],
2403
+ handbook: ["docs/handbook/"],
2404
+ tests: ["docs/tests/"],
2405
+ workflow: ["docs/workflow/"],
2406
+ quality: ["docs/quality/"],
2407
+ intents: ["docs/intents/"],
2408
+ profiles: ["docs/profiles/"]
2409
+ };
2410
+ var RENDERED_SKILL_DIRS = [".claude/skills", ".agents/skills", ".opencode/skills"];
2411
+ var RENDERED_COMMAND_DIRS = [".claude/commands", ".opencode/commands"];
2412
+ function docType(path) {
2413
+ if (path === "README.md") return "readme";
2414
+ if (path.endsWith("/README.md")) return "doc";
2415
+ if (path.startsWith("docs/spec/")) return "spec";
2416
+ if (path.startsWith("docs/decisions/")) return "decision";
2417
+ if (path.startsWith("docs/handbook/")) return "handbook";
2418
+ if (path.startsWith("docs/tests/")) return "test-plan";
2419
+ if (path.startsWith("docs/workflow/")) return "workflow";
2420
+ if (path.startsWith("docs/quality/")) return "quality";
2421
+ if (path.startsWith("docs/intents/")) return "intent-file";
2422
+ return "doc";
2423
+ }
2424
+ function dateString(value) {
2425
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
2426
+ if (typeof value === "string" && value) return value;
2427
+ return void 0;
2428
+ }
2429
+ function truncate(text, max = 280) {
2430
+ if (!text) return void 0;
2431
+ const flat = text.replace(/\s+/g, " ").trim();
2432
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
2433
+ }
2434
+ function compact(attrs) {
2435
+ const out = {};
2436
+ for (const [k, v] of Object.entries(attrs)) if (v !== void 0) out[k] = v;
2437
+ return out;
2438
+ }
2439
+ function engineOf(path) {
2440
+ if (path.startsWith(".claude/") || path === "CLAUDE.md") return "claude-code";
2441
+ if (path.startsWith(".agents/")) return "codex-cli";
2442
+ if (path.startsWith(".opencode/")) return "opencode";
2443
+ return void 0;
2444
+ }
2445
+ var Builder = class {
2446
+ nodes = /* @__PURE__ */ new Map();
2447
+ edges = /* @__PURE__ */ new Map();
2448
+ add(node) {
2449
+ const existing = this.nodes.get(node.id);
2450
+ if (existing) return existing;
2451
+ const full = { ...node, attrs: compact(node.attrs ?? {}), issues: [] };
2452
+ this.nodes.set(node.id, full);
2453
+ return full;
2454
+ }
2455
+ edge(from, to, type, line) {
2456
+ if (from === to) return;
2457
+ const key = `${from}\0${type}\0${to}`;
2458
+ const existing = this.edges.get(key);
2459
+ if (!existing || line < existing.line) this.edges.set(key, { from, to, type, line });
2460
+ }
2461
+ /** A `tracks:` entry or an anchor, as a path or glob node. */
2462
+ target(repoRoot, pattern) {
2463
+ const isGlob = pattern.includes("*");
2464
+ const id = `${isGlob ? "glob" : "path"}:${pattern}`;
2465
+ if (!this.nodes.has(id)) {
2466
+ const matches = isGlob ? fg6.sync(pattern, { cwd: repoRoot }).length : void 0;
2467
+ this.add({
2468
+ id,
2469
+ type: isGlob ? "glob" : "path",
2470
+ domain: "project",
2471
+ title: pattern,
2472
+ sourcePath: pattern,
2473
+ line: 0,
2474
+ attrs: {
2475
+ exists: isGlob ? (matches ?? 0) > 0 : trackedPathExists(repoRoot, pattern),
2476
+ matches
2477
+ }
2478
+ });
2479
+ }
2480
+ return id;
2481
+ }
2482
+ };
2483
+ function intentSlugPath(nodes, index) {
2484
+ const parts = [];
2485
+ let i = index;
2486
+ while (i !== void 0) {
2487
+ const n = nodes[i];
2488
+ if (!n) break;
2489
+ parts.unshift(headingSlug(n.title));
2490
+ i = n.parent;
2491
+ }
2492
+ return parts.join("/");
2493
+ }
2494
+ function linkTarget(b, repoRoot, from, url) {
2495
+ const abs = resolveLink(repoRoot, from, url);
2496
+ const rel = relative2(repoRoot, abs).split("\\").join("/");
2497
+ const hash = url.includes("#") ? url.slice(url.indexOf("#") + 1) : "";
2498
+ if (hash && b.nodes.has(`sec:${rel}#${hash}`)) return `sec:${rel}#${hash}`;
2499
+ if (b.nodes.has(`doc:${rel}`)) return `doc:${rel}`;
2500
+ return void 0;
2501
+ }
2502
+ function buildGraph(repoRoot, opts = {}) {
2503
+ const b = new Builder();
2504
+ const config = loadLintConfig(repoRoot);
2505
+ const manifest = (() => {
2506
+ try {
2507
+ return readManifest(repoRoot);
2508
+ } catch {
2509
+ return null;
2510
+ }
2511
+ })();
2512
+ const rendered = new Set(manifest?.files ?? []);
2513
+ const docFiles = fg6.sync(["README.md", "docs/**/*.md"], {
2514
+ cwd: repoRoot,
2515
+ ignore: [...LINKED_DOC_IGNORES, ...config.ignore]
2516
+ }).filter((f) => !rendered.has(f)).sort();
2517
+ const texts = /* @__PURE__ */ new Map();
2518
+ for (const path of docFiles) {
2519
+ const text = readFileSync8(join11(repoRoot, path), "utf8");
2520
+ texts.set(path, text);
2521
+ const { data } = parseFrontmatter2(text);
2522
+ const h1 = readHeadings(text).find((h) => h.depth === 1);
2523
+ const title = typeof data.title === "string" && data.title || h1?.title || basename5(path, ".md");
2524
+ const type = docType(path);
2525
+ b.add({
2526
+ id: `doc:${path}`,
2527
+ type,
2528
+ domain: "project",
2529
+ title,
2530
+ sourcePath: path,
2531
+ line: 1,
2532
+ attrs: {
2533
+ lede: truncate(readLede(text)),
2534
+ status: typeof data.status === "string" ? data.status : void 0,
2535
+ lastReviewed: dateString(data.last_reviewed),
2536
+ lines: text.split("\n").length
2537
+ }
2538
+ });
2539
+ }
2540
+ for (const path of docFiles.filter((p) => docType(p) === "spec")) {
2541
+ const text = texts.get(path) ?? "";
2542
+ for (const h of readHeadings(text)) {
2543
+ if (h.depth < 2 || h.depth > 3) continue;
2544
+ b.add({
2545
+ id: `sec:${path}#${h.slug}`,
2546
+ type: "section",
2547
+ domain: "project",
2548
+ title: h.title,
2549
+ sourcePath: path,
2550
+ line: h.line,
2551
+ parent: `doc:${path}`,
2552
+ attrs: { depth: h.depth }
2553
+ });
2554
+ b.edge(`doc:${path}`, `sec:${path}#${h.slug}`, "contains", h.line);
2555
+ }
2556
+ for (const term of vocabularyTerms(text) ?? []) {
2557
+ const id = `term:${term.slug}`;
2558
+ b.add({
2559
+ id,
2560
+ type: "term",
2561
+ domain: "project",
2562
+ title: term.term,
2563
+ sourcePath: path,
2564
+ line: term.line,
2565
+ parent: `doc:${path}`,
2566
+ attrs: { defined: true, definition: truncate(term.definition, 400) }
2567
+ });
2568
+ b.edge(`doc:${path}`, id, "contains", term.line);
2569
+ }
2570
+ }
2571
+ for (const path of docFiles.filter((p) => docType(p) === "decision")) {
2572
+ const adr = readAdr(texts.get(path) ?? "");
2573
+ const node = b.nodes.get(`doc:${path}`);
2574
+ if (node) {
2575
+ node.attrs = compact({
2576
+ ...node.attrs,
2577
+ decision: truncate(adr.decision, 600),
2578
+ missingSections: adr.missing.length ? adr.missing : void 0
2579
+ });
2580
+ }
2581
+ const stem = basename5(path, ".md");
2582
+ for (const alt of adr.alternatives) {
2583
+ const id = `alt:${stem}/${headingSlug(alt.title)}`;
2584
+ b.add({
2585
+ id,
2586
+ type: "alternative",
2587
+ domain: "project",
2588
+ title: alt.title,
2589
+ sourcePath: path,
2590
+ line: alt.line,
2591
+ parent: `doc:${path}`,
2592
+ attrs: { text: truncate(alt.text, 400) }
2593
+ });
2594
+ b.edge(`doc:${path}`, id, "contains", alt.line);
2595
+ }
2596
+ }
2597
+ for (const path of docFiles) {
2598
+ const type = docType(path);
2599
+ if (type !== "handbook" && type !== "test-plan" && type !== "workflow") continue;
2600
+ const text = texts.get(path) ?? "";
2601
+ const { data } = parseFrontmatter2(text);
2602
+ const lines = text.split("\n");
2603
+ if (Array.isArray(data.tracks)) {
2604
+ for (const entry of data.tracks) {
2605
+ if (typeof entry !== "string") continue;
2606
+ const line = lines.findIndex((l) => l.includes(entry)) + 1 || 1;
2607
+ b.edge(`doc:${path}`, b.target(repoRoot, entry), "tracks", line);
2608
+ }
2609
+ }
2610
+ }
2611
+ for (const path of docFiles.filter((p) => docType(p) === "test-plan")) {
2612
+ for (const gap of readKnownGaps(texts.get(path) ?? "")) {
2613
+ const id = `gap:${path}:${gap.line}`;
2614
+ b.add({
2615
+ id,
2616
+ type: "known-gap",
2617
+ domain: "project",
2618
+ title: truncate(gap.text.replace(/⚠️|\*/gu, "").trim(), 120) ?? gap.text,
2619
+ sourcePath: path,
2620
+ line: gap.line,
2621
+ parent: `doc:${path}`,
2622
+ attrs: { text: gap.text }
2623
+ });
2624
+ b.edge(`doc:${path}`, id, "contains", gap.line);
2625
+ }
2626
+ }
2627
+ for (const file of readIntentFiles(repoRoot)) {
2628
+ const fileId = `doc:${file.path}`;
2629
+ const fileNode = b.nodes.get(fileId);
2630
+ if (fileNode) {
2631
+ fileNode.title = file.title;
2632
+ fileNode.attrs = compact({
2633
+ ...fileNode.attrs,
2634
+ status: file.meta?.status,
2635
+ actors: file.meta?.actors ? [...file.meta.actors] : void 0,
2636
+ statement: truncate(file.statement, 400)
2637
+ });
2638
+ }
2639
+ const stem = basename5(file.path, ".md");
2640
+ const ids = file.nodes.map((_, i) => `intent:${stem}/${intentSlugPath(file.nodes, i)}`);
2641
+ file.nodes.forEach((n, i) => {
2642
+ const id = ids[i];
2643
+ const parent = n.parent !== void 0 ? ids[n.parent] : fileId;
2644
+ b.add({
2645
+ id,
2646
+ type: "intent",
2647
+ domain: "project",
2648
+ title: n.title,
2649
+ sourcePath: file.path,
2650
+ line: n.line,
2651
+ parent,
2652
+ attrs: {
2653
+ level: n.level,
2654
+ terminal: n.isTerminal,
2655
+ status: n.status,
2656
+ effectiveStatus: n.effectiveStatus,
2657
+ acceptance: n.acceptance.length ? [...n.acceptance] : void 0
2658
+ }
2659
+ });
2660
+ b.edge(parent, id, "contains", n.line);
2661
+ for (const entity of n.requires)
2662
+ b.edge(id, termId(b, entity, file.path, n.line), "requires", n.line);
2663
+ for (const entity of n.creates)
2664
+ b.edge(id, termId(b, entity, file.path, n.line), "creates", n.line);
2665
+ for (const anchor of n.anchors)
2666
+ b.edge(id, b.target(repoRoot, anchor), "anchors", n.fieldLines.anchors ?? n.line);
2667
+ if (n.spec) {
2668
+ const target = linkTarget(b, repoRoot, file.path, n.spec);
2669
+ if (target) b.edge(id, target, "spec", n.fieldLines.spec ?? n.line);
2670
+ }
2671
+ });
2672
+ const progress = (index) => {
2673
+ const n = file.nodes[index];
2674
+ if (!n) return [0, 0];
2675
+ if (n.isTerminal) return [n.effectiveStatus === "implemented" ? 1 : 0, 1];
2676
+ let done = 0;
2677
+ let total = 0;
2678
+ file.nodes.forEach((c, j) => {
2679
+ if (c.parent !== index) return;
2680
+ const [d, t] = progress(j);
2681
+ done += d;
2682
+ total += t;
2683
+ });
2684
+ return [done, total];
2685
+ };
2686
+ let fileDone = 0;
2687
+ let fileTotal = 0;
2688
+ file.nodes.forEach((n, i) => {
2689
+ const [done, total] = progress(i);
2690
+ const node = b.nodes.get(ids[i]);
2691
+ if (node) node.attrs = { ...node.attrs, done, total };
2692
+ if (n.parent === void 0) {
2693
+ fileDone += done;
2694
+ fileTotal += total;
2695
+ }
2696
+ });
2697
+ if (fileNode) fileNode.attrs = { ...fileNode.attrs, done: fileDone, total: fileTotal };
2698
+ for (const spec of intentFileSpecs(file.meta)) {
2699
+ const path = resolveSpecPath(file.path, spec);
2700
+ if (b.nodes.has(`doc:${path}`)) b.edge(fileId, `doc:${path}`, "spec", 1);
2701
+ }
2702
+ }
2703
+ for (const path of docFiles) {
2704
+ for (const { url, line } of readLinks(texts.get(path) ?? "")) {
2705
+ if (isExternalOrAnchor(url) || stripFragment(url) === "") continue;
2706
+ const target = linkTarget(b, repoRoot, path, url);
2707
+ if (target) b.edge(`doc:${path}`, target, "links-to", line);
2708
+ }
2709
+ }
2710
+ const packageDir = opts.packageDir ?? defaultPackageDir();
2711
+ const shipped = existsSync10(join11(packageDir, "skills")) ? loadHarness(packageDir) : { skills: [], cmds: [] };
2712
+ const overridesParent = manifest?.overridesDir ? join11(repoRoot, manifest.overridesDir) : repoRoot;
2713
+ const overrides = loadOverrides(overridesParent);
2714
+ const disabled = new Set(overrides?.disable ?? []);
2715
+ const skillLayers = [
2716
+ [[...shipped.skills], "shipped"],
2717
+ [loadProjectSkills(repoRoot), "project"],
2718
+ [[...overrides?.add?.skills ?? []], "override"]
2719
+ ];
2720
+ for (const [skills, layer] of skillLayers) {
2721
+ for (const skill of skills) {
2722
+ const id = `skill:${skill.meta.id}`;
2723
+ const replaced = b.nodes.get(id);
2724
+ if (replaced) b.nodes.delete(id);
2725
+ const relSource = layer === "shipped" ? HARNESS_SOURCE : relative2(repoRoot, skill.sourcePath).split("\\").join("/");
2726
+ b.add({
2727
+ id,
2728
+ type: "skill",
2729
+ domain: layer === "shipped" ? "harness" : layer === "project" ? "project" : "local",
2730
+ title: skill.meta.id,
2731
+ sourcePath: relSource,
2732
+ line: layer === "shipped" ? 0 : 1,
2733
+ attrs: {
2734
+ layer,
2735
+ replaces: replaced ? replaced.attrs.layer : void 0,
2736
+ disabled: disabled.has(skill.meta.id) || void 0,
2737
+ description: truncate(skill.meta.description, 400),
2738
+ tags: skill.meta.tags ? [...skill.meta.tags] : void 0,
2739
+ requires: skill.meta.requires ? [...skill.meta.requires] : void 0,
2740
+ engines: skill.meta.engines ? [...skill.meta.engines] : void 0,
2741
+ lines: skill.body.split("\n").length
2742
+ }
2743
+ });
2744
+ }
2745
+ }
2746
+ const cmdLayers = [
2747
+ [shipped.cmds, "shipped"],
2748
+ [overrides?.add?.cmds ?? [], "override"]
2749
+ ];
2750
+ const triggerToSkill = /* @__PURE__ */ new Map();
2751
+ for (const [cmds, layer] of cmdLayers) {
2752
+ for (const cmd of cmds) {
2753
+ const id = `cmd:${cmd.meta.id}`;
2754
+ b.nodes.delete(id);
2755
+ b.add({
2756
+ id,
2757
+ type: "command",
2758
+ domain: layer === "shipped" ? "harness" : "local",
2759
+ title: cmd.meta.trigger,
2760
+ sourcePath: layer === "shipped" ? HARNESS_SOURCE : relative2(repoRoot, cmd.sourcePath),
2761
+ line: 0,
2762
+ attrs: {
2763
+ layer,
2764
+ skill: cmd.meta.invokes_skill,
2765
+ description: truncate(cmd.meta.description)
2766
+ }
2767
+ });
2768
+ triggerToSkill.set(cmd.meta.trigger, `skill:${cmd.meta.invokes_skill}`);
2769
+ b.edge(id, `skill:${cmd.meta.invokes_skill}`, "invokes", 0);
2770
+ }
2771
+ }
2772
+ for (const path of [...rendered].sort()) {
2773
+ b.add({
2774
+ id: `rendered:${path}`,
2775
+ type: "rendered-file",
2776
+ domain: "project",
2777
+ title: path,
2778
+ sourcePath: path,
2779
+ line: 1,
2780
+ attrs: {
2781
+ engine: engineOf(path),
2782
+ preserved: manifest?.preservedFiles?.includes(path) || void 0
2783
+ }
2784
+ });
2785
+ const skillDir = RENDERED_SKILL_DIRS.find((d) => path.startsWith(`${d}/`));
2786
+ if (skillDir) {
2787
+ const skillId = path.slice(skillDir.length + 1).split("/")[0];
2788
+ if (skillId) b.edge(`skill:${skillId}`, `rendered:${path}`, "renders-to", 0);
2789
+ }
2790
+ const cmdDir = RENDERED_COMMAND_DIRS.find((d) => path.startsWith(`${d}/`));
2791
+ if (cmdDir) b.edge(`cmd:${basename5(path, ".md")}`, `rendered:${path}`, "renders-to", 0);
2792
+ }
2793
+ for (const linter of ALL_LINTERS) {
2794
+ const id = `linter:${linter.id.replace(/^lint:/, "")}`;
2795
+ b.add({
2796
+ id,
2797
+ type: "linter",
2798
+ domain: "harness",
2799
+ title: linter.id,
2800
+ sourcePath: HARNESS_SOURCE,
2801
+ line: 0,
2802
+ attrs: {
2803
+ pillars: [...linter.pillars],
2804
+ severity: linter.defaultSeverity,
2805
+ suggests: linter.suggestedSkills?.length ? [...linter.suggestedSkills] : void 0
2806
+ }
2807
+ });
2808
+ for (const trigger of linter.suggestedSkills ?? []) {
2809
+ const skill = triggerToSkill.get(trigger);
2810
+ if (skill) b.edge(id, skill, "suggests", 0);
2811
+ }
2812
+ for (const pillar of linter.pillars) {
2813
+ for (const prefix of PILLAR_PATHS[pillar] ?? []) {
2814
+ for (const path of docFiles) {
2815
+ if (path === prefix || prefix.endsWith("/") && path.startsWith(prefix)) {
2816
+ b.edge(id, `doc:${path}`, "checks", 0);
2817
+ }
2818
+ }
2819
+ }
2820
+ }
2821
+ }
2822
+ const lessonsPath = join11(repoRoot, LESSONS_FILE);
2823
+ if (existsSync10(lessonsPath)) {
2824
+ try {
2825
+ const lessons = JSON.parse(readFileSync8(lessonsPath, "utf8"));
2826
+ if (Array.isArray(lessons)) {
2827
+ for (const raw of lessons) {
2828
+ if (!raw || typeof raw !== "object") continue;
2829
+ const l = raw;
2830
+ if (typeof l.id !== "string" || typeof l.rule !== "string") continue;
2831
+ b.add({
2832
+ id: `lesson:${l.id}`,
2833
+ type: "lesson",
2834
+ domain: "local",
2835
+ title: l.rule,
2836
+ sourcePath: LESSONS_FILE,
2837
+ line: 0,
2838
+ attrs: JSON.parse(
2839
+ JSON.stringify({
2840
+ status: typeof l.status === "string" ? l.status : "proposed",
2841
+ domain: l.domain,
2842
+ pillar: l.pillar,
2843
+ seen: typeof l.seen === "number" ? l.seen : void 0,
2844
+ evidence: Array.isArray(l.evidence) ? l.evidence.map((e) => typeof e === "string" ? e : JSON.stringify(e)) : void 0
2845
+ })
2846
+ )
2847
+ });
2848
+ }
2849
+ }
2850
+ } catch {
2851
+ }
2852
+ }
2853
+ const ran = opts.report !== void 0 || opts.lint !== false;
2854
+ const report = opts.report ?? (opts.lint === false ? void 0 : runLinters(repoRoot));
2855
+ const unattached = [];
2856
+ const byFile = /* @__PURE__ */ new Map();
2857
+ for (const node of b.nodes.values()) {
2858
+ if (node.domain === "harness" || node.line === 0 && node.type !== "path") continue;
2859
+ const list = byFile.get(node.sourcePath) ?? [];
2860
+ list.push(node);
2861
+ byFile.set(node.sourcePath, list);
2862
+ }
2863
+ for (const issue of report?.issues ?? []) {
2864
+ const candidates = byFile.get(issue.file) ?? [];
2865
+ const fileNode = b.nodes.get(`doc:${issue.file}`) ?? b.nodes.get(`rendered:${issue.file}`);
2866
+ let target;
2867
+ if (issue.line !== void 0) {
2868
+ for (const n of candidates) {
2869
+ if (n.line <= issue.line && (!target || n.line > target.line)) target = n;
2870
+ }
2871
+ }
2872
+ target = target ?? fileNode;
2873
+ if (target) target.issues.push(issue);
2874
+ else unattached.push(issue);
2875
+ const linter = b.nodes.get(`linter:${issue.linter.replace(/^lint:/, "")}`);
2876
+ if (linter)
2877
+ linter.attrs = { ...linter.attrs, issues: (linter.attrs.issues ?? 0) + 1 };
2878
+ }
2879
+ for (const node of b.nodes.values()) {
2880
+ if (node.type !== "handbook" && node.type !== "test-plan" && node.type !== "workflow" && node.type !== "intent-file")
2881
+ continue;
2882
+ const drift2 = driftOf(repoRoot, node.sourcePath);
2883
+ if (drift2)
2884
+ node.attrs = { ...node.attrs, drift: { commits: drift2.commits, threshold: drift2.threshold } };
2885
+ }
2886
+ const nodes = [...b.nodes.values()].sort((x, y) => x.id < y.id ? -1 : x.id > y.id ? 1 : 0);
2887
+ const known = new Set(nodes.map((n) => n.id));
2888
+ const edges = [...b.edges.values()].filter((e) => known.has(e.from) && known.has(e.to)).sort(
2889
+ (x, y) => x.from !== y.from ? x.from < y.from ? -1 : 1 : x.type !== y.type ? x.type < y.type ? -1 : 1 : x.to < y.to ? -1 : x.to > y.to ? 1 : 0
2890
+ );
2891
+ return {
2892
+ version: 1,
2893
+ harness: VERSION,
2894
+ nodes,
2895
+ edges,
2896
+ lint: {
2897
+ ran,
2898
+ errors: report?.summary.errors ?? 0,
2899
+ warnings: report?.summary.warnings ?? 0,
2900
+ unattached
2901
+ }
2902
+ };
2903
+ }
2904
+ function termId(b, entity, file, line) {
2905
+ const id = `term:${entity}`;
2906
+ if (!b.nodes.has(id)) {
2907
+ b.add({
2908
+ id,
2909
+ type: "term",
2910
+ domain: "project",
2911
+ title: entity,
2912
+ sourcePath: file,
2913
+ line,
2914
+ attrs: { defined: false }
2915
+ });
2916
+ }
2917
+ return id;
2918
+ }
2919
+ function serializeGraph(graph) {
2920
+ return `${JSON.stringify(graph, null, 2)}
2921
+ `;
2922
+ }
2923
+ var GRAPH_PATH = posix3.join(".vaubaan", "graph.json");
2924
+
2925
+ // src/view/html.ts
2926
+ import { createHash as createHash2 } from "crypto";
2927
+
2928
+ // src/view/assets.ts
2929
+ var VIEW_STYLE = `
2930
+ :root{--bg:#f4f6f5;--surface:#fff;--sunk:#e9edeb;--fg:#17211d;--muted:#5b6862;--line:#d3d9d5;--accent:#0f6e62;--accent-soft:#d6ebe6;
2931
+ --ok:#2f7d3c;--ok-soft:#e0f0e2;--warn:#9a6200;--warn-soft:#f8ecd2;--err:#b3361f;--err-soft:#f7dfd9;--dot:#c8cfca;
2932
+ --f:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color-scheme:light}
2933
+ @media (prefers-color-scheme:dark){:root{--bg:#111614;--surface:#1a201d;--sunk:#0d1110;--fg:#e3eae5;--muted:#95a39b;--line:#2c3530;--accent:#4fc2b0;--accent-soft:#163430;
2934
+ --ok:#6cc47a;--ok-soft:#183019;--warn:#e7ad45;--warn-soft:#352a12;--err:#f0806a;--err-soft:#3b1d17;--dot:#29312d;color-scheme:dark}}
2935
+ *{box-sizing:border-box}html,body{height:100%}
2936
+ body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 var(--f);display:flex;flex-direction:column}
2937
+ a{color:var(--accent)}code,.mono{font-family:var(--mono);font-size:.86em}code{background:var(--sunk);padding:0 .3em;border-radius:3px}
2938
+ h2{font-size:1.3rem;margin:0 0 .3rem}h3{font-size:1rem;margin:0 0 .4rem}h4{margin:.8rem 0 .3rem;font-size:.8rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
2939
+ .k{color:var(--muted);font-size:.85em}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
2940
+ button{font:inherit;cursor:pointer;border:1px solid var(--line);background:var(--surface);color:var(--fg);border-radius:6px;padding:4px 10px}
2941
+ button:hover{border-color:var(--accent)}button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
2942
+ button[disabled]{opacity:.5;cursor:default}
2943
+ header.top{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;padding:8px 16px;border-bottom:1px solid var(--line);background:var(--surface);position:relative;z-index:5}
2944
+ .brand{display:flex;flex-direction:column;line-height:1.2;min-width:0}
2945
+ .tabs{display:flex;flex-wrap:wrap;gap:2px}
2946
+ .tabs a{padding:4px 10px;border-radius:6px;text-decoration:none;color:var(--muted)}
2947
+ .tabs a.on{background:var(--accent-soft);color:var(--accent);font-weight:600}
2948
+ .status{margin-left:auto;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
2949
+ #q{border:1px solid var(--line);background:var(--bg);color:var(--fg);border-radius:6px;padding:4px 8px;width:180px}
2950
+ .live{display:inline-flex;gap:5px;align-items:center;font-size:.8rem;color:var(--muted)}.live i{width:7px;height:7px;border-radius:50%;background:var(--ok)}
2951
+ .seg{display:inline-flex;border:1px solid var(--line);border-radius:7px;padding:1px}.seg button{border:0;padding:3px 8px;font-size:.8rem}
2952
+ .seg button[aria-pressed=true]{background:var(--accent-soft);color:var(--accent);font-weight:600}
2953
+ main{flex:1;min-height:0;position:relative;overflow:auto}
2954
+ .view{padding:16px 20px}.js .view:not(.active){display:none}
2955
+ #view-canvas{padding:0;height:100%}
2956
+ .pill{display:inline-block;font-size:.72rem;font-weight:600;padding:0 .5em;border-radius:99px;white-space:nowrap;margin-right:3px}
2957
+ .p-ok{background:var(--ok-soft);color:var(--ok)}.p-warn{background:var(--warn-soft);color:var(--warn)}.p-err{background:var(--err-soft);color:var(--err)}
2958
+ .p-acc{background:var(--accent-soft);color:var(--accent)}.p-mut{background:var(--sunk);color:var(--muted)}
2959
+ .cv{position:relative;height:100%;min-height:420px;overflow:hidden;background-image:radial-gradient(var(--dot) 1.1px,transparent 1.2px);background-size:22px 22px;touch-action:none;cursor:grab;outline:none}
2960
+ .cv.drag{cursor:grabbing}.cv-world{position:absolute;left:0;top:0;transform-origin:0 0}
2961
+ .frame{position:absolute;border:1.5px solid var(--line);border-radius:14px;background:color-mix(in srgb,var(--surface) 70%,transparent)}
2962
+ .frame.f-harness{border-style:dashed;border-color:var(--accent)}
2963
+ .ft{position:absolute;top:-11px;left:14px;background:var(--bg);padding:0 8px;font-size:.72rem;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
2964
+ .n{position:absolute;height:100px;overflow:hidden;display:flex;flex-direction:column;gap:1px;z-index:1;background:var(--surface);border:1px solid var(--line);border-radius:9px;padding:7px 10px;color:var(--fg);text-decoration:none;box-shadow:0 1px 2px rgb(0 0 0/.05)}
2965
+ .n:hover{border-color:var(--accent)}.n .t{font-weight:600;font-size:.82rem;line-height:1.25;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
2966
+ .n .s{font-size:.7rem;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.n .row{margin-top:auto;white-space:nowrap;overflow:hidden;display:flex;gap:4px;align-items:center}.n>.k{font-size:.66rem;text-transform:uppercase;letter-spacing:.06em}
2967
+ .n .bar{width:60px}
2968
+ .n.d-harness{border-style:dashed}.n.has-err{border-color:var(--err)}
2969
+ .n.t-intent-file,.n.t-readme,.n.t-spec{background:var(--sunk)}
2970
+ .n.sel{outline:2px solid var(--accent);outline-offset:2px;z-index:2}.n.dim{opacity:.25}
2971
+ .edges{position:absolute;left:0;top:0;pointer-events:none;overflow:visible}
2972
+ .edges path{fill:none;stroke:var(--muted);opacity:.45}.edges path.on{stroke:var(--accent);opacity:1}
2973
+ .cv.focusing .frame,.cv.focusing .n:not(.sel):not(.nb),.cv.focusing .edges path:not(.on){opacity:.12}
2974
+ .focus{display:none;position:absolute;left:0;top:0}.focus.on{display:block}
2975
+ .fl{position:absolute;left:0;top:0;width:1px;height:1px;overflow:visible;pointer-events:none}.fl path{fill:none;stroke:var(--accent);stroke-width:1.6}
2976
+ .fb{position:absolute;z-index:3;background:var(--surface);border:1px solid var(--accent);border-radius:10px;box-shadow:0 6px 18px rgb(0 0 0/.12)}
2977
+ .fbt{position:absolute;left:10px;top:6px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--accent)}.fbt i{font-style:normal;color:var(--muted)}
2978
+ .fi{position:absolute;z-index:4;height:34px;display:flex;align-items:center;gap:6px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--fg);text-decoration:none;font-size:.76rem;overflow:hidden}
2979
+ .fi .t{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600}.fi .k{font-size:.68rem;white-space:nowrap}
2980
+ .dot{width:8px;height:8px;border-radius:50%;flex:none;background:var(--muted)}.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn)}
2981
+ .fi:hover,.fi.sel{border-color:var(--accent);outline:1px solid var(--accent)}.fi[data-doc]{background:var(--sunk)}.fi.has-err{border-color:var(--err)}
2982
+ .cv[data-view=diff] .fi.is-add{border:2px solid var(--ok)}.cv[data-view=diff] .fi.is-chg{border:2px solid var(--warn)}.cv[data-view=diff] .fi.is-del{border:2px dashed var(--err)}
2983
+ .cv-hint{position:absolute;left:12px;bottom:6px;margin:0;font-size:.75rem;color:var(--muted);pointer-events:none}
2984
+ .cv-tools{position:absolute;right:12px;bottom:12px;display:flex;gap:4px;z-index:3}.cv-tools button{box-shadow:0 1px 3px rgb(0 0 0/.1)}
2985
+ .cv-tools button[aria-pressed=true]{background:var(--accent-soft);color:var(--accent)}
2986
+ .cv[data-view=before] .is-add{display:none}.cv[data-view=now] .is-del{display:none}
2987
+ .cv[data-view=diff] .n.is-add{border:2px solid var(--ok);box-shadow:0 0 0 4px var(--ok-soft)}
2988
+ .cv[data-view=diff] .n.is-chg{border:2px solid var(--warn);box-shadow:0 0 0 4px var(--warn-soft)}
2989
+ .cv[data-view=diff] .n.is-del{border:2px dashed var(--err);opacity:.75}.cv[data-view=diff] .n.is-del .t{text-decoration:line-through}
2990
+ .diff-tag{display:none;position:absolute;top:2px;right:6px;font-size:.6rem;font-weight:700;padding:0 5px;border-radius:99px;color:var(--surface)}
2991
+ .cv[data-view=diff] .diff-tag{display:block}.is-add .diff-tag{background:var(--ok)}.is-chg .diff-tag{background:var(--warn)}.is-del .diff-tag{background:var(--err)}
2992
+ .side{position:fixed;right:0;top:0;bottom:0;width:min(420px,100%);background:var(--surface);border-left:1px solid var(--line);z-index:10;overflow:auto;padding:16px 18px;box-shadow:-6px 0 20px rgb(0 0 0/.08)}
2993
+ .js .side{transform:translateX(105%);transition:transform .15s}.js .side.open{transform:none}
2994
+ @media (prefers-reduced-motion:reduce){.js .side{transition:none}}
2995
+ .side .close{position:absolute;right:10px;top:8px;border:0;font-size:1.3rem;padding:0 6px}
2996
+ .js .detail{display:none}.js .detail.on{display:block}.js .side.open .empty{display:none}
2997
+ .detail{border-bottom:1px solid var(--line);padding-bottom:12px;margin-bottom:12px}.detail header{margin-bottom:8px}.detail h3{font-size:1.05rem;margin:2px 0}
2998
+ dl{display:grid;grid-template-columns:96px 1fr;gap:4px 10px;margin:8px 0}dt{color:var(--muted);font-size:.8rem}dd{margin:0;min-width:0;overflow-wrap:anywhere}
2999
+ dd ul{margin:0;padding-left:1.1em}dl.rel dt{grid-column:1/-1;margin-top:6px;font-weight:600}dl.rel dd{grid-column:1/-1}
3000
+ .issues{list-style:none;padding:0;margin:8px 0}.issues li{border-left:3px solid var(--err);background:var(--err-soft);padding:6px 8px;border-radius:0 6px 6px 0;margin-bottom:4px}
3001
+ .issues li.sev-warning{border-color:var(--warn);background:var(--warn-soft)}
3002
+ .comments textarea,.reply textarea{width:100%;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--fg);font:inherit;padding:6px}
3003
+ .comments form,.reply{display:grid;gap:6px;margin-top:6px}.btns{display:flex;gap:6px}
3004
+ .thread{border:1px solid var(--line);border-radius:8px;padding:8px;margin:6px 0;background:var(--bg)}
3005
+ .thread header{display:flex;gap:6px;align-items:center;flex-wrap:wrap}.msg{margin-top:6px}.msg p{margin:2px 0;white-space:pre-wrap}
3006
+ .who{font-size:.72rem;font-weight:700;color:var(--muted)}.m-agent .who{color:var(--accent)}.chg{background:var(--accent-soft);padding:0 4px;border-radius:3px}
3007
+ .tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:12px 0}
3008
+ .tile{background:var(--surface);border:1px solid var(--line);border-radius:9px;padding:10px 12px;display:grid}
3009
+ .tile.bad{border-color:var(--err)}.tile.warn{border-color:var(--warn)}
3010
+ .tl{font-size:.68rem;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);font-weight:700}.tv{font-size:1.4rem;font-weight:700;font-variant-numeric:tabular-nums}.ts{font-size:.75rem;color:var(--muted)}
3011
+ .cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr));gap:12px}
3012
+ .panel{background:var(--surface);border:1px solid var(--line);border-radius:9px;padding:12px}
3013
+ .list{list-style:none;padding:0;margin:0;display:grid;gap:5px}
3014
+ .tree{list-style:none;padding:0;margin:0;display:grid;gap:4px;max-width:980px}
3015
+ .tr{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-left:calc(var(--d)*20px);background:var(--surface);border:1px solid var(--line);border-radius:7px;padding:6px 10px}
3016
+ .tr .ttl{flex:1;min-width:200px}.tr.pr{border-color:var(--warn)}.tr .acc{flex-basis:100%;margin:2px 0 0;padding-left:1.2em;color:var(--muted);font-size:.85rem}
3017
+ .bar{display:inline-block;width:90px;height:6px;background:var(--sunk);border-radius:99px;overflow:hidden}.bar i{display:block;height:100%;background:var(--ok)}
3018
+ .terms{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:8px}
3019
+ .term{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:8px 10px;display:grid;gap:2px}
3020
+ .term.warn{border-color:var(--warn)}.term.bad{border-color:var(--err)}.term.dim{border-style:dashed;opacity:.7}.term .note{font-size:.78rem;color:var(--warn)}
3021
+ .adrs{display:grid;gap:6px;max-width:980px}.adr{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:8px 12px}
3022
+ .adr summary{cursor:pointer}.adr p{margin:6px 0}.alt{font-size:.85rem;color:var(--muted);border-left:2px solid var(--line);padding-left:8px;margin:4px 0}
3023
+ .lint-map{display:grid;gap:6px;max-width:1100px}
3024
+ .lr{display:grid;grid-template-columns:200px 1fr 220px;gap:10px;align-items:center;background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:7px 10px}
3025
+ .lp{font-weight:600}.lc{display:flex;flex-wrap:wrap;gap:5px}
3026
+ .lk{font-family:var(--mono);font-size:.76rem;border:1px solid var(--err);border-radius:5px;padding:1px 7px;text-decoration:none;color:var(--fg)}
3027
+ .lk.w{border-color:var(--warn);border-style:dashed}.lk i{font-style:normal;font-weight:700;color:var(--ok)}.lk i.bad{color:var(--err)}
3028
+ .ls{font-family:var(--mono);font-size:.76rem;color:var(--accent)}.ls.none{color:var(--warn)}
3029
+ @media (max-width:760px){.lr{grid-template-columns:1fr}}
3030
+ .layers{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}.ly{border:1px solid var(--line);border-radius:99px;padding:1px 10px;font-size:.8rem;color:var(--muted)}
3031
+ .ly.on{border-color:var(--accent);color:var(--accent);font-weight:600}
3032
+ .tbl{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--surface);max-width:1100px}
3033
+ table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:6px 10px;border-bottom:1px solid var(--line);white-space:nowrap}
3034
+ th{font-size:.7rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);background:var(--sunk)}
3035
+ td.ok{color:var(--ok)}td.no{color:var(--muted)}td.warn{color:var(--warn)}td.num{text-align:right;font-variant-numeric:tabular-nums}
3036
+ .lessons{display:grid;gap:8px;max-width:980px}.lesson{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:8px 12px;display:grid;gap:4px}
3037
+ .session-actions{display:flex;gap:8px;margin:8px 0}.session-actions [data-submit]{background:var(--accent);color:var(--surface);border-color:var(--accent)}
3038
+ .journal{margin:0;padding-left:1.2em;display:grid;gap:4px}.threads{display:grid;gap:6px;max-width:900px}
3039
+ `;
3040
+ var VIEW_SCRIPT = `
3041
+ (function(){
3042
+ "use strict";
3043
+ var d=document,B=d.body;B.classList.add("js");
3044
+ var st={tab:"canvas",sel:null,s:1,x:0,y:0,fitted:false,diff:"now",edges:false,q:""};
3045
+ function $(s,r){return (r||d).querySelector(s)}function $$(s,r){return Array.prototype.slice.call((r||d).querySelectorAll(s))}
3046
+ function cv(){return $("#cv")}function world(){return $("#world")}
3047
+ function apply(){var w=world();if(w)w.style.transform="translate("+st.x+"px,"+st.y+"px) scale("+st.s+")"}
3048
+ function fit(){var c=cv(),w=world();if(!c||!w||!c.clientWidth)return;var W=w.offsetWidth,H=w.offsetHeight;
3049
+ st.s=Math.min(1,Math.max(.12,Math.min(c.clientWidth/W,c.clientHeight/Math.min(H,2400))));st.x=Math.max(8,(c.clientWidth-W*st.s)/2);st.y=10;st.fitted=true;apply()}
3050
+ function zoomAt(f,cx,cy){var ns=Math.min(2.5,Math.max(.08,st.s*f));st.x=cx-(cx-st.x)*ns/st.s;st.y=cy-(cy-st.y)*ns/st.s;st.s=ns;apply()}
3051
+ function showTab(t){if(!d.getElementById("view-"+t))t="canvas";st.tab=t;$$(".view").forEach(function(v){v.classList.toggle("active",v.id==="view-"+t)});
3052
+ $$("[data-tab]").forEach(function(a){a.classList.toggle("on",a.getAttribute("data-tab")===t)});if(t==="canvas"&&!st.fitted)setTimeout(fit,0)}
3053
+ function zoomBox(b){var c=cv();if(!c||!b)return;var side=$("#side"),cw=c.clientWidth-(side&&side.classList.contains("open")?side.offsetWidth:0);var s=Math.min(1.05,Math.max(.2,Math.min(cw/b[2],(c.clientHeight-30)/b[3])));st.s=s;st.x=(cw-b[2]*s)/2-b[0]*s;st.y=Math.max(10,(c.clientHeight-b[3]*s)/2)-b[1]*s;apply()}
3054
+ function unfocus(){st.focus=null;var c=cv();if(c)c.classList.remove("focusing");$$(".focus.on,.n.nb,.n.sel,.fi.sel,.edges path.on").forEach(function(x){x.classList.remove("on","nb","sel")})}
3055
+ function focusOn(doc,move){unfocus();var layer=$('.focus[data-for="'+doc+'"]');var card=d.getElementById("c-"+doc.slice(2));if(!layer||!card)return false;st.focus=doc;
3056
+ cv().classList.add("focusing");layer.classList.add("on");card.classList.add("sel");
3057
+ $$("[data-doc]",layer).forEach(function(i){var nc=d.getElementById("c-"+i.getAttribute("data-n").slice(2));if(nc)nc.classList.add("nb")});
3058
+ $$('.edges path[data-a="'+doc+'"],.edges path[data-b="'+doc+'"]').forEach(function(p){p.classList.add("on")});
3059
+ if(move)zoomBox((layer.getAttribute("data-box")||"").split(",").map(Number));return true}
3060
+ function select(nid,o){o=o||{};st.sel=nid;$$(".detail.on").forEach(function(x){x.classList.remove("on")});$$(".fi.sel").forEach(function(x){x.classList.remove("sel")});var side=$("#side");
3061
+ if(!nid){side.classList.remove("open");return}var det=d.getElementById(nid);if(det){det.classList.add("on");side.classList.add("open");side.scrollTop=0}
3062
+ if(!o.keep){var doc=d.getElementById("c-"+nid.slice(2))?nid:det&&det.getAttribute("data-map");if(doc&&doc!==st.focus)focusOn(doc,o.move!==false);else if(doc&&o.move)focusOn(doc,true)}
3063
+ $$('.focus.on .fi[data-n="'+nid+'"]').forEach(function(x){x.classList.add("sel")})}
3064
+ function filter(){var q=st.q.toLowerCase();$$(".n").forEach(function(n){n.classList.toggle("dim",!!q&&(n.getAttribute("data-q")||"").indexOf(q)<0)})}
3065
+ function restore(){showTab(st.tab);var c=cv();if(c)c.setAttribute("data-view",st.diff);var f=st.focus;if(f)focusOn(f,false);apply();if(st.sel)select(st.sel,{keep:true,move:false});filter();
3066
+ $$("[data-diff]").forEach(function(b){b.setAttribute("aria-pressed",String(b.getAttribute("data-diff")===st.diff))});var eb=$("[data-edges]");if(eb)eb.setAttribute("aria-pressed",String(st.edges))}
3067
+ d.addEventListener("click",function(e){var t=e.target.closest("a,button");if(!t)return;
3068
+ var n=t.getAttribute("data-n");if(n){e.preventDefault();if(moved)return;var inFocus=!!t.closest(".focus");select(n,{keep:inFocus&&!t.hasAttribute("data-doc"),move:true});return}
3069
+ var tab=t.getAttribute("data-tab");if(tab){e.preventDefault();showTab(tab);try{history.replaceState(null,"","#view-"+tab)}catch(_){}return}
3070
+ var z=t.getAttribute("data-zoom");if(z){var c=cv();if(z==="fit")fit();else zoomAt(z==="in"?1.25:.8,c.clientWidth/2,c.clientHeight/2);return}
3071
+ if(t.hasAttribute("data-edges")){st.edges=!st.edges;restore();return}
3072
+ var df=t.getAttribute("data-diff");if(df){st.diff=df;restore();return}
3073
+ if(t.hasAttribute("data-close")){select(null);return}
3074
+ if(t.hasAttribute("data-submit")){post("/api/submit",{});return}
3075
+ if(t.hasAttribute("data-end")){if(confirm("End the review? The agent then keeps or discards the changes."))post("/api/end",{});return}
3076
+ var rs=t.getAttribute("data-resolve");if(rs){post("/api/threads/"+encodeURIComponent(rs)+"/resolve",{});return}});
3077
+ d.addEventListener("submit",function(e){var f=e.target;var ta=$("textarea",f);var body=ta&&ta.value.trim();e.preventDefault();if(!body)return;
3078
+ if(f.classList.contains("comment"))post("/api/threads",{nodeId:f.getAttribute("data-node"),body:body}).then(function(ok){if(ok)ta.value=""});
3079
+ else if(f.classList.contains("reply"))post("/api/threads/"+encodeURIComponent(f.getAttribute("data-thread"))+"/messages",{body:body}).then(function(ok){if(ok)ta.value=""})});
3080
+ var q=$("#q");if(q)q.addEventListener("input",function(){st.q=q.value;filter()});
3081
+ if(q)q.addEventListener("keydown",function(e){if(e.key==="Enter"){var m=$(".n:not(.dim)");if(m&&st.q){showTab("canvas");select(m.getAttribute("data-n"),{move:true})}}});
3082
+ d.addEventListener("keydown",function(e){if(/INPUT|TEXTAREA/.test((e.target.tagName||"")))return;
3083
+ if(e.key==="/"){e.preventDefault();if(q)q.focus()}else if(e.key==="f")fit();else if(e.key==="l"){st.edges=!st.edges;restore()}
3084
+ else if(e.key==="d"&&B.hasAttribute("data-session")){st.diff=st.diff==="diff"?"now":"diff";restore()}else if(e.key==="Escape"){select(null);unfocus();fit()}});
3085
+ var drag=null,moved=false,pts={},pinch=null;
3086
+ d.addEventListener("pointerdown",function(e){var c=cv();if(!c||!c.contains(e.target)||e.target.closest(".cv-tools"))return;
3087
+ pts[e.pointerId]={x:e.clientX,y:e.clientY};var k=Object.keys(pts);moved=false;
3088
+ if(k.length===1){drag={x:e.clientX-st.x,y:e.clientY-st.y,sx:e.clientX,sy:e.clientY};c.classList.add("drag")}
3089
+ else if(k.length===2){var a=pts[k[0]],b=pts[k[1]];pinch={d:Math.hypot(a.x-b.x,a.y-b.y),s:st.s};drag=null}});
3090
+ d.addEventListener("pointermove",function(e){if(!pts[e.pointerId])return;pts[e.pointerId]={x:e.clientX,y:e.clientY};var k=Object.keys(pts),c=cv();
3091
+ if(pinch&&k.length===2){var a=pts[k[0]],b=pts[k[1]],r=c.getBoundingClientRect();zoomAt(pinch.s*Math.hypot(a.x-b.x,a.y-b.y)/pinch.d/st.s,(a.x+b.x)/2-r.left,(a.y+b.y)/2-r.top);moved=true}
3092
+ else if(drag){if(Math.abs(e.clientX-drag.sx)+Math.abs(e.clientY-drag.sy)>4)moved=true;st.x=e.clientX-drag.x;st.y=e.clientY-drag.y;apply()}});
3093
+ function up(e){var c=cv();if(c&&!moved&&drag&&c.contains(e.target)&&!e.target.closest("a,button,.fb")&&st.focus){select(null);unfocus();fit()}delete pts[e.pointerId];if(Object.keys(pts).length<2)pinch=null;if(!Object.keys(pts).length){drag=null;var c=cv();if(c)c.classList.remove("drag");setTimeout(function(){moved=false},0)}}
3094
+ d.addEventListener("pointerup",up);d.addEventListener("pointercancel",up);
3095
+ d.addEventListener("wheel",function(e){var c=cv();if(!c||!c.contains(e.target))return;e.preventDefault();var r=c.getBoundingClientRect();
3096
+ if(e.ctrlKey||e.metaKey||Math.abs(e.deltaY)>=Math.abs(e.deltaX)&&!e.shiftKey)zoomAt(Math.exp(-e.deltaY*.0015),e.clientX-r.left,e.clientY-r.top);else{st.x-=e.deltaX;st.y-=e.deltaY;apply()}},{passive:false});
3097
+ window.addEventListener("resize",function(){if(st.tab==="canvas"&&!st.sel)fit()});
3098
+ var h=location.hash.replace(/^#/,"");if(/^view-/.test(h))showTab(h.slice(5));else{showTab("canvas");if(/^n-/.test(h))setTimeout(function(){select(h,{move:true})},0)}
3099
+ setTimeout(fit,0);
3100
+ // ---------------------------------------------------------------- session
3101
+ var live=B.hasAttribute("data-session");
3102
+ function post(url,body){return fetch(url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body),credentials:"same-origin"})
3103
+ .then(function(r){if(!r.ok)return r.text().then(function(t){alert(t||("error "+r.status));return false});return refresh().then(function(){return true})})
3104
+ .catch(function(){return false})}
3105
+ function refresh(){if(!live)return Promise.resolve();return fetch(location.pathname,{cache:"no-store",credentials:"same-origin"}).then(function(r){return r.text()}).then(function(html){
3106
+ var doc=new DOMParser().parseFromString(html,"text/html");var drafts={};$$("textarea").forEach(function(t){if(t.id&&t.value)drafts[t.id]=t.value});
3107
+ ["main","#side","#hs"].forEach(function(sel){var a=$(sel),b=$(sel,doc);if(a&&b)a.replaceChildren.apply(a,Array.prototype.slice.call(b.childNodes).map(function(n){return d.importNode(n,true)}))});
3108
+ B.setAttribute("data-revision",doc.body.getAttribute("data-revision")||"");Object.keys(drafts).forEach(function(id){var t=d.getElementById(id);if(t)t.value=drafts[id]});restore()})}
3109
+ if(live&&window.EventSource){var es=new EventSource("/api/events");es.addEventListener("update",function(ev){if(ev.data!==B.getAttribute("data-revision"))refresh()});
3110
+ es.addEventListener("end",function(){var l=$(".live");if(l)l.textContent="review ended";es.close()})}
3111
+ })();
3112
+ `;
3113
+
3114
+ // src/view/html.ts
3115
+ function esc(text) {
3116
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3117
+ }
3118
+ function md(text) {
3119
+ return text.split(/(`[^`]+`)/g).map(
3120
+ (part) => part.startsWith("`") && part.endsWith("`") && part.length > 1 ? `<code>${esc(part.slice(1, -1))}</code>` : esc(part.replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1"))
3121
+ ).join("");
3122
+ }
3123
+ function htmlId(nodeId) {
3124
+ return `n-${createHash2("sha1").update(nodeId).digest("hex").slice(0, 10)}`;
3125
+ }
3126
+ function str(v) {
3127
+ return typeof v === "string" ? v : void 0;
3128
+ }
3129
+ function num(v) {
3130
+ return typeof v === "number" ? v : void 0;
3131
+ }
3132
+ function arr(v) {
3133
+ return Array.isArray(v) ? v : [];
3134
+ }
3135
+ function drift(n) {
3136
+ const d = n.attrs.drift;
3137
+ if (d && typeof d === "object" && !Array.isArray(d)) {
3138
+ const commits = num(d.commits);
3139
+ const threshold = num(d.threshold);
3140
+ if (commits !== void 0 && threshold !== void 0) return { commits, threshold };
3141
+ }
3142
+ return void 0;
3143
+ }
3144
+ function pill(text, tone = "mut") {
3145
+ return `<span class="pill p-${tone}">${esc(text)}</span>`;
3146
+ }
3147
+ function statusPill(status) {
3148
+ if (!status) return "";
3149
+ const tone = status === "implemented" ? "ok" : status === "proposed" ? "warn" : "mut";
3150
+ return pill(status, tone);
3151
+ }
3152
+ function driftPill(n) {
3153
+ const d = drift(n);
3154
+ if (!d) return "";
3155
+ const tone = d.commits > d.threshold ? "err" : d.commits >= d.threshold * 0.8 ? "warn" : "ok";
3156
+ return pill(`drift ${d.commits}/${d.threshold}`, tone);
3157
+ }
3158
+ function issuesPill(issues) {
3159
+ if (issues.length === 0) return "";
3160
+ const errors = issues.filter((i) => i.severity === "error").length;
3161
+ return errors ? pill(`${errors} error${errors > 1 ? "s" : ""}`, "err") : pill(`${issues.length} warning${issues.length > 1 ? "s" : ""}`, "warn");
3162
+ }
3163
+ var TYPE_LABEL = {
3164
+ readme: "README",
3165
+ spec: "spec",
3166
+ section: "section",
3167
+ term: "term",
3168
+ decision: "decision",
3169
+ alternative: "rejected alternative",
3170
+ handbook: "handbook",
3171
+ "test-plan": "test plan",
3172
+ "known-gap": "known gap",
3173
+ workflow: "workflow",
3174
+ quality: "quality",
3175
+ doc: "doc",
3176
+ "intent-file": "level-1 intent",
3177
+ intent: "intent",
3178
+ linter: "linter",
3179
+ skill: "skill",
3180
+ command: "command",
3181
+ "rendered-file": "generated file",
3182
+ path: "path",
3183
+ glob: "glob",
3184
+ lesson: "lesson"
3185
+ };
3186
+ var Index = class {
3187
+ constructor(graph) {
3188
+ this.graph = graph;
3189
+ for (const n of graph.nodes) this.byId.set(n.id, n);
3190
+ for (const e of graph.edges) {
3191
+ this.out.set(e.from, [...this.out.get(e.from) ?? [], e]);
3192
+ this.in.set(e.to, [...this.in.get(e.to) ?? [], e]);
3193
+ }
3194
+ }
3195
+ graph;
3196
+ byId = /* @__PURE__ */ new Map();
3197
+ out = /* @__PURE__ */ new Map();
3198
+ in = /* @__PURE__ */ new Map();
3199
+ of(type) {
3200
+ return this.graph.nodes.filter((n) => n.type === type);
3201
+ }
3202
+ outOf(id, type) {
3203
+ return (this.out.get(id) ?? []).filter((e) => !type || e.type === type);
3204
+ }
3205
+ inOf(id, type) {
3206
+ return (this.in.get(id) ?? []).filter((e) => !type || e.type === type);
3207
+ }
3208
+ };
3209
+ function signature(n) {
3210
+ return JSON.stringify([n.title, n.attrs, n.issues.map((i) => `${i.linter}|${i.message}`)]);
3211
+ }
3212
+ var MAP_TYPES = [
3213
+ "readme",
3214
+ "spec",
3215
+ "decision",
3216
+ "handbook",
3217
+ "test-plan",
3218
+ "workflow",
3219
+ "quality",
3220
+ "doc",
3221
+ "intent-file"
3222
+ ];
3223
+ var HARNESS_LINTERS = "harness:linters";
3224
+ var HARNESS_SKILLS = "harness:skills";
3225
+ var CARD_W = 214;
3226
+ var CARD_H = 100;
3227
+ var GAP = 10;
3228
+ var FRAME_PAD = 14;
3229
+ var FRAME_HEAD = 30;
3230
+ var FRAME_GAP = 30;
3231
+ var ITEM_W = 196;
3232
+ var ITEM_H = 34;
3233
+ var ITEM_GAP = 6;
3234
+ var BLOCK_ROWS = 10;
3235
+ var FOCUS_ROW_W = 1100;
3236
+ function mapOf(ix, id) {
3237
+ let n = ix.byId.get(id);
3238
+ while (n) {
3239
+ if (MAP_TYPES.includes(n.type)) return n.id;
3240
+ if (n.type === "linter") return HARNESS_LINTERS;
3241
+ if (n.type === "skill" || n.type === "command") return HARNESS_SKILLS;
3242
+ n = n.parent ? ix.byId.get(n.parent) : void 0;
3243
+ }
3244
+ return void 0;
3245
+ }
3246
+ function familyOf(ix, docId) {
3247
+ return ix.graph.nodes.filter(
3248
+ (n) => n.id === docId || n.id !== docId && mapOf(ix, n.id) === docId
3249
+ );
3250
+ }
3251
+ function worstDiff(states) {
3252
+ if (states.includes("del")) return states.every((s) => s === "del") ? "del" : "chg";
3253
+ if (states.includes("add")) return states.every((s) => s === "add") ? "add" : "chg";
3254
+ return states.includes("chg") ? "chg" : void 0;
3255
+ }
3256
+ function mapFrames(ix, removed) {
3257
+ const all = [...ix.graph.nodes, ...removed.filter((n) => MAP_TYPES.includes(n.type))];
3258
+ const pick = (types) => all.filter((n) => types.includes(n.type));
3259
+ return [
3260
+ { title: "Intents", domain: "project", cards: pick(["intent-file"]) },
3261
+ { title: "README & spec", domain: "project", cards: pick(["readme", "spec"]) },
3262
+ { title: "Decisions", domain: "project", cards: pick(["decision"]) },
3263
+ { title: "Handbook", domain: "project", cards: pick(["handbook"]) },
3264
+ {
3265
+ title: "Tests, workflow, quality",
3266
+ domain: "project",
3267
+ cards: pick(["test-plan", "workflow", "quality"])
3268
+ },
3269
+ { title: "Other docs", domain: "project", cards: pick(["doc"]) }
3270
+ ].filter((f) => f.cards.length > 0);
3271
+ }
3272
+ function count(n, one, many = `${one}s`) {
3273
+ return `${n} ${n === 1 ? one : many}`;
3274
+ }
3275
+ function mapCardBody(n, ix, family) {
3276
+ const of = (t) => family.filter((m) => m.type === t);
3277
+ const sub = [];
3278
+ const pills = [];
3279
+ switch (n.type) {
3280
+ case "intent-file": {
3281
+ const terminals = of("intent").filter((m) => m.attrs.terminal === true);
3282
+ const proposed = terminals.filter((m) => m.attrs.effectiveStatus === "proposed").length;
3283
+ const done = num(n.attrs.done) ?? 0;
3284
+ const total = num(n.attrs.total) ?? terminals.length;
3285
+ sub.push(`${done}/${total} delivered`);
3286
+ if (proposed) pills.push(pill(`${proposed} proposed`, "warn"));
3287
+ pills.push(
3288
+ total ? `<span class="bar" title="${done}/${total}"><i style="width:${Math.round(done / total * 100)}%"></i></span>` : ""
3289
+ );
3290
+ break;
3291
+ }
3292
+ case "spec":
3293
+ sub.push(`${count(of("term").length, "term")} \xB7 ${count(of("section").length, "section")}`);
3294
+ break;
3295
+ case "decision": {
3296
+ const refs = ix.inOf(n.id, "links-to").length;
3297
+ sub.push(count(of("alternative").length, "alternative"));
3298
+ pills.push(pill(`cited \xD7${refs}`, refs <= 1 ? "warn" : "mut"));
3299
+ break;
3300
+ }
3301
+ case "handbook":
3302
+ case "test-plan":
3303
+ case "workflow": {
3304
+ const gaps = of("known-gap").length;
3305
+ sub.push(
3306
+ `tracks ${count(ix.outOf(n.id, "tracks").length, "path")}${gaps ? ` \xB7 ${count(gaps, "known gap")}` : ""}`
3307
+ );
3308
+ pills.push(driftPill(n));
3309
+ break;
3310
+ }
3311
+ default:
3312
+ sub.push(n.sourcePath);
3313
+ }
3314
+ pills.push(issuesPill(family.flatMap((m) => m.issues)));
3315
+ return `<span class="k">${esc(TYPE_LABEL[n.type])}</span><span class="t">${md(n.title)}</span><span class="s">${esc(sub.join(" \xB7 "))}</span><span class="row">${pills.join("")}</span>`;
3316
+ }
3317
+ function focusGroups(ix, doc, family) {
3318
+ const inFamily = new Set(family.map((n) => n.id));
3319
+ const groups = /* @__PURE__ */ new Map();
3320
+ const add = (label, node, note, indent) => {
3321
+ if (!node || node.id === doc.id) return;
3322
+ const g = groups.get(label) ?? /* @__PURE__ */ new Map();
3323
+ if (!g.has(node.id))
3324
+ g.set(node.id, {
3325
+ node,
3326
+ ...note ? { note } : {},
3327
+ ...indent !== void 0 ? { indent } : {}
3328
+ });
3329
+ groups.set(label, g);
3330
+ };
3331
+ const other = (id, keepIntent = false) => {
3332
+ const n = ix.byId.get(id);
3333
+ if (!n) return void 0;
3334
+ if (n.type === "term" || keepIntent && n.type === "intent") return n;
3335
+ const m = mapOf(ix, id);
3336
+ return m && m !== HARNESS_LINTERS && m !== HARNESS_SKILLS ? ix.byId.get(m) : n;
3337
+ };
3338
+ const contents = {
3339
+ "intent-file": "intent",
3340
+ spec: "term",
3341
+ decision: "alternative",
3342
+ "test-plan": "known-gap"
3343
+ };
3344
+ const child = contents[doc.type];
3345
+ if (child) {
3346
+ const label = {
3347
+ intent: "Intents",
3348
+ term: "Vocabulary",
3349
+ alternative: "Rejected alternatives",
3350
+ "known-gap": "Known gaps"
3351
+ }[child];
3352
+ for (const n of family.filter((m) => m.type === child).sort((a, b) => a.line - b.line)) {
3353
+ add(
3354
+ label,
3355
+ n,
3356
+ n.type === "intent" && n.attrs.terminal === true ? str(n.attrs.effectiveStatus) : void 0,
3357
+ n.type === "intent" ? (num(n.attrs.level) ?? 1) - 1 : void 0
3358
+ );
3359
+ }
3360
+ }
3361
+ for (const m of family) {
3362
+ for (const e of ix.outOf(m.id)) {
3363
+ if (inFamily.has(e.to) || e.type === "contains") continue;
3364
+ const label = {
3365
+ "links-to": "Cites",
3366
+ spec: "Cites",
3367
+ tracks: "Tracks",
3368
+ anchors: "Code anchors",
3369
+ requires: "Uses words",
3370
+ creates: "Uses words"
3371
+ }[e.type];
3372
+ if (label)
3373
+ add(
3374
+ label,
3375
+ other(e.to),
3376
+ e.type === "creates" ? "creates" : e.type === "requires" ? "requires" : void 0
3377
+ );
3378
+ }
3379
+ for (const e of ix.inOf(m.id)) {
3380
+ if (inFamily.has(e.from) || e.type === "contains") continue;
3381
+ const label = {
3382
+ "links-to": "Cited by",
3383
+ spec: "Cited by",
3384
+ requires: "Words used by",
3385
+ creates: "Words used by",
3386
+ checks: "Checked by"
3387
+ }[e.type];
3388
+ if (label)
3389
+ add(
3390
+ label,
3391
+ other(e.from, e.type === "requires" || e.type === "creates"),
3392
+ e.type === "creates" ? "creates" : e.type === "requires" ? "requires" : void 0
3393
+ );
3394
+ }
3395
+ }
3396
+ const order = [
3397
+ "Intents",
3398
+ "Vocabulary",
3399
+ "Rejected alternatives",
3400
+ "Known gaps",
3401
+ "Cites",
3402
+ "Cited by",
3403
+ "Uses words",
3404
+ "Words used by",
3405
+ "Tracks",
3406
+ "Code anchors",
3407
+ "Checked by"
3408
+ ];
3409
+ return order.filter((l) => groups.has(l)).map((label) => ({ label, items: [...groups.get(label)?.values() ?? []] }));
3410
+ }
3411
+ function focusItem(it, x, y, diff, ix) {
3412
+ const n = it.node;
3413
+ const isDoc = MAP_TYPES.includes(n.type);
3414
+ const cls = ["fi", `t-${n.type}`, `d-${n.domain}`];
3415
+ const state = isDoc ? worstDiff(familyOf(ix, n.id).map((m) => diff.get(m.id))) : diff.get(n.id);
3416
+ if (state) cls.push(`is-${state}`);
3417
+ if (n.issues.some((i) => i.severity === "error") || n.attrs.exists === false || n.attrs.defined === false)
3418
+ cls.push("has-err");
3419
+ const indent = (it.indent ?? 0) * 12;
3420
+ const tone = it.note === "implemented" ? "ok" : it.note === "proposed" ? "warn" : "mut";
3421
+ return `<a class="${cls.join(" ")}" href="#${htmlId(n.id)}" data-n="${htmlId(n.id)}"${isDoc ? ' data-doc="1"' : ""} style="left:${x + indent}px;top:${y}px;width:${ITEM_W - indent}px"><span class="t">${md(n.title)}</span>${it.note === "implemented" || it.note === "proposed" ? `<i class="dot ${tone}" title="${esc(it.note)}"></i>` : it.note ? `<span class="k">${esc(it.note)}</span>` : `<span class="k">${esc(TYPE_LABEL[n.type])}</span>`}</a>`;
3422
+ }
3423
+ function renderFocus(ix, doc, at, family, diff) {
3424
+ const groups = focusGroups(ix, doc, family);
3425
+ const parts = [];
3426
+ const lines = [];
3427
+ const x0 = at.x + at.w + 90;
3428
+ let x = x0;
3429
+ let top = at.y - 20;
3430
+ let rowH = 0;
3431
+ let right = x0;
3432
+ let bottom = at.y + at.h;
3433
+ for (const g of groups) {
3434
+ const cols = Math.ceil(g.items.length / BLOCK_ROWS);
3435
+ const rows = Math.min(BLOCK_ROWS, g.items.length);
3436
+ const w = cols * (ITEM_W + ITEM_GAP) - ITEM_GAP + 2 * 10;
3437
+ const h = 28 + rows * (ITEM_H + ITEM_GAP) + 6;
3438
+ if (x > x0 && x + w > x0 + FOCUS_ROW_W) {
3439
+ x = x0;
3440
+ top += rowH + 24;
3441
+ rowH = 0;
3442
+ }
3443
+ parts.push(
3444
+ `<div class="fb" style="left:${x}px;top:${top}px;width:${w}px;height:${h}px"><span class="fbt">${esc(g.label)} <i>${g.items.length}</i></span></div>`
3445
+ );
3446
+ g.items.forEach((it, i) => {
3447
+ const col = Math.floor(i / BLOCK_ROWS);
3448
+ const row = i % BLOCK_ROWS;
3449
+ parts.push(
3450
+ focusItem(
3451
+ it,
3452
+ x + 10 + col * (ITEM_W + ITEM_GAP),
3453
+ top + 28 + row * (ITEM_H + ITEM_GAP),
3454
+ diff,
3455
+ ix
3456
+ )
3457
+ );
3458
+ });
3459
+ const x1 = at.x + at.w;
3460
+ const y1 = at.y + at.h / 2;
3461
+ const y2 = top + 14;
3462
+ lines.push(`<path d="M${x1} ${y1} C${x1 + 50} ${y1},${x - 50} ${y2},${x} ${y2}"/>`);
3463
+ rowH = Math.max(rowH, h);
3464
+ right = Math.max(right, x + w);
3465
+ bottom = Math.max(bottom, top + h);
3466
+ x += w + 24;
3467
+ }
3468
+ const start = at.y - 20;
3469
+ const box = {
3470
+ x: at.x - 20,
3471
+ y: Math.min(start, at.y) - 20,
3472
+ w: right - at.x + 40,
3473
+ h: bottom - start + 40
3474
+ };
3475
+ const empty = groups.length ? "" : `<div class="fb fb-empty" style="left:${at.x + at.w + 90}px;top:${at.y}px;width:220px;height:${at.h}px"><span class="fbt">Linked to nothing</span></div>`;
3476
+ return {
3477
+ html: `<div class="focus" data-for="${htmlId(doc.id)}" data-box="${box.x},${box.y},${box.w},${box.h}"><svg class="fl" aria-hidden="true">${lines.join("")}</svg>${parts.join("")}${empty}</div>`,
3478
+ box
3479
+ };
3480
+ }
3481
+ function renderCanvas(ix, diff, removed) {
3482
+ const placed = /* @__PURE__ */ new Map();
3483
+ const frameHtml = [];
3484
+ const cards = [];
3485
+ const focus = [];
3486
+ const families = /* @__PURE__ */ new Map();
3487
+ const famOf = (n) => {
3488
+ const f = families.get(n.id) ?? (ix.byId.has(n.id) ? familyOf(ix, n.id) : [n]);
3489
+ families.set(n.id, f);
3490
+ return f;
3491
+ };
3492
+ const specs = mapFrames(ix, removed).map(
3493
+ (f) => ({
3494
+ title: f.title,
3495
+ domain: f.domain,
3496
+ items: f.cards.map((n) => ({
3497
+ id: n.id,
3498
+ html: (b) => {
3499
+ const family = famOf(n);
3500
+ const state = worstDiff(family.map((m) => diff.get(m.id)));
3501
+ const cls = ["n", `t-${n.type}`, `d-${n.domain}`];
3502
+ if (state) cls.push(`is-${state}`);
3503
+ if (family.some((m) => m.issues.some((i) => i.severity === "error"))) cls.push("has-err");
3504
+ const tag = state ? `<span class="diff-tag">${state === "add" ? "added" : state === "chg" ? "changed" : "removed"}</span>` : "";
3505
+ const q = family.map((m) => m.title).join(" ").toLowerCase();
3506
+ if (ix.byId.has(n.id)) focus.push(renderFocus(ix, n, b, family, diff).html);
3507
+ return `<a class="${cls.join(" ")}" id="c-${htmlId(n.id).slice(2)}" href="#${htmlId(n.id)}" data-n="${htmlId(n.id)}" data-q="${esc(`${q} ${n.sourcePath}`.toLowerCase())}" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px">${tag}${mapCardBody(n, ix, family)}</a>`;
3508
+ }
3509
+ }))
3510
+ })
3511
+ );
3512
+ const linters = ix.of("linter");
3513
+ const skills = ix.of("skill");
3514
+ const lintIssues = linters.reduce((s, l) => s + (num(l.attrs.issues) ?? 0), 0);
3515
+ specs.push({
3516
+ title: "Harness",
3517
+ domain: "harness",
3518
+ items: [
3519
+ {
3520
+ id: HARNESS_LINTERS,
3521
+ html: (b) => `<a class="n t-harness d-harness" href="#view-linters" data-tab="linters" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px"><span class="k">harness</span><span class="t">Linters</span><span class="s">${esc(count(linters.length, "linter"))}</span><span class="row">${pill(`${lintIssues} issues`, lintIssues ? "err" : "ok")}</span></a>`
3522
+ },
3523
+ {
3524
+ id: HARNESS_SKILLS,
3525
+ html: (b) => `<a class="n t-harness d-harness" href="#view-skills" data-tab="skills" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px"><span class="k">harness</span><span class="t">Skills</span><span class="s">${esc(`${count(skills.length, "skill")} \xB7 ${count(ix.of("command").length, "command")}`)}</span><span class="row"></span></a>`
3526
+ }
3527
+ ]
3528
+ });
3529
+ const layout = (shelfW, ratio) => {
3530
+ let x = 20;
3531
+ let y = 20;
3532
+ let shelfH = 0;
3533
+ let maxX = 0;
3534
+ const frames = specs.map((f) => {
3535
+ const n = f.items.length;
3536
+ const cols = Math.max(1, Math.min(n, Math.round(Math.sqrt(n * ratio))));
3537
+ const rows = Math.ceil(n / cols);
3538
+ const w = 2 * FRAME_PAD + cols * CARD_W + (cols - 1) * GAP;
3539
+ const h = FRAME_HEAD + FRAME_PAD + rows * CARD_H + (rows - 1) * GAP;
3540
+ if (x > 20 && x + w > shelfW) {
3541
+ x = 20;
3542
+ y += shelfH + FRAME_GAP;
3543
+ shelfH = 0;
3544
+ }
3545
+ const at = { x, y, w, h, cols };
3546
+ x += w + FRAME_GAP;
3547
+ shelfH = Math.max(shelfH, h);
3548
+ maxX = Math.max(maxX, at.x + w);
3549
+ return at;
3550
+ });
3551
+ const W = maxX + 40;
3552
+ const H = y + shelfH + 40;
3553
+ return { frames, W, H, scale: Math.min(1440 / W, 860 / H) };
3554
+ };
3555
+ let best = layout(1640, 1.6);
3556
+ for (let r = 2; r <= 20; r++) {
3557
+ const ratio = r / 4;
3558
+ for (let shelfW = 1e3; shelfW <= 3600; shelfW += 50) {
3559
+ const l = layout(shelfW, ratio);
3560
+ if (l.scale > best.scale + 1e-9) best = l;
3561
+ }
3562
+ }
3563
+ specs.forEach((f, k) => {
3564
+ const at = best.frames[k];
3565
+ if (!at) return;
3566
+ frameHtml.push(
3567
+ `<div class="frame f-${f.domain}" style="left:${at.x}px;top:${at.y}px;width:${at.w}px;height:${at.h}px"><span class="ft">${esc(f.title)} <i>${f.items.length}</i></span></div>`
3568
+ );
3569
+ f.items.forEach((it, i) => {
3570
+ const b = {
3571
+ x: at.x + FRAME_PAD + i % at.cols * (CARD_W + GAP),
3572
+ y: at.y + FRAME_HEAD + Math.floor(i / at.cols) * (CARD_H + GAP),
3573
+ w: CARD_W,
3574
+ h: CARD_H
3575
+ };
3576
+ placed.set(it.id, b);
3577
+ cards.push(it.html(b));
3578
+ });
3579
+ });
3580
+ const worldW = best.W;
3581
+ const worldH = best.H;
3582
+ const pairs = /* @__PURE__ */ new Map();
3583
+ for (const e of ix.graph.edges) {
3584
+ if (!["links-to", "spec", "requires", "creates", "suggests", "checks"].includes(e.type))
3585
+ continue;
3586
+ if (e.type === "checks") continue;
3587
+ const a = mapOf(ix, e.from);
3588
+ const b = mapOf(ix, e.to);
3589
+ if (!a || !b || a === b) continue;
3590
+ const [p, q] = a < b ? [a, b] : [b, a];
3591
+ const key = `${p}\0${q}`;
3592
+ const cur = pairs.get(key) ?? { a: p, b: q, n: 0 };
3593
+ cur.n += 1;
3594
+ pairs.set(key, cur);
3595
+ }
3596
+ const edges = [];
3597
+ for (const { a, b, n } of [...pairs.values()].sort((x, y) => x.a + x.b < y.a + y.b ? -1 : 1)) {
3598
+ const A = placed.get(a);
3599
+ const B = placed.get(b);
3600
+ if (!A || !B) continue;
3601
+ const ax = A.x + A.w / 2;
3602
+ const ay = A.y + A.h / 2;
3603
+ const bx = B.x + B.w / 2;
3604
+ const by = B.y + B.h / 2;
3605
+ const mx = (ax + bx) / 2;
3606
+ const my = (ay + by) / 2 - Math.min(80, Math.abs(bx - ax) / 6);
3607
+ const ida = a.startsWith("harness:") ? a : htmlId(a);
3608
+ const idb = b.startsWith("harness:") ? b : htmlId(b);
3609
+ edges.push(
3610
+ `<path class="me" data-a="${ida}" data-b="${idb}" stroke-width="${(1 + Math.log2(n)).toFixed(2)}" d="M${ax} ${ay} Q${mx} ${my} ${bx} ${by}"><title>${n} link${n > 1 ? "s" : ""}</title></path>`
3611
+ );
3612
+ }
3613
+ return `<div class="cv" id="cv" data-view="now" tabindex="0" aria-label="Context map">
3614
+ <div class="cv-world" id="world" style="width:${worldW}px;height:${worldH}px">
3615
+ <svg class="edges" width="${worldW}" height="${worldH}" aria-hidden="true">${edges.join("")}</svg>
3616
+ ${frameHtml.join("\n")}
3617
+ ${cards.join("\n")}
3618
+ <div class="focus-layers">${focus.join("\n")}</div>
3619
+ </div>
3620
+ <p class="cv-hint">Select a card to see what it is linked to. Esc or a click on the background returns to the map.</p>
3621
+ <div class="cv-tools"><button type="button" data-zoom="out" aria-label="Zoom out">\u2212</button><button type="button" data-zoom="fit">Fit</button><button type="button" data-zoom="in" aria-label="Zoom in">+</button></div>
3622
+ </div>`;
3623
+ }
3624
+ function sourceLink(n, prefix) {
3625
+ if (n.domain === "harness" || !n.sourcePath || n.type === "glob")
3626
+ return `<span class="mono">${esc(n.sourcePath)}</span>`;
3627
+ const where = n.line > 0 ? `${n.sourcePath}:${n.line}` : n.sourcePath;
3628
+ return `<a class="mono src" href="${esc(prefix + n.sourcePath)}">${esc(where)}</a>`;
3629
+ }
3630
+ function nodeRef(ix, id) {
3631
+ const n = ix.byId.get(id);
3632
+ if (!n) return esc(id);
3633
+ return `<a href="#${htmlId(id)}" data-n="${htmlId(id)}">${md(n.title)}</a> <span class="k">${esc(TYPE_LABEL[n.type])}</span>`;
3634
+ }
3635
+ function attrRows(n) {
3636
+ const rows = [];
3637
+ const add = (k, v) => rows.push(`<dt>${esc(k)}</dt><dd>${v}</dd>`);
3638
+ const a = n.attrs;
3639
+ if (str(a.lede) && !str(a.statement)) add("Says", md(str(a.lede) ?? ""));
3640
+ if (str(a.statement)) add("Statement", md(str(a.statement) ?? ""));
3641
+ if (str(a.definition)) add("Definition", md(str(a.definition) ?? ""));
3642
+ if (str(a.decision)) add("Decision", md(str(a.decision) ?? ""));
3643
+ if (str(a.text) && n.type !== "known-gap") add("Text", md(str(a.text) ?? ""));
3644
+ if (str(a.description)) add("Description", md(str(a.description) ?? ""));
3645
+ if (str(a.status) || str(a.effectiveStatus))
3646
+ add("Status", statusPill(str(a.status) ?? str(a.effectiveStatus)));
3647
+ if (arr(a.actors).length) add("Actors", esc(arr(a.actors).join(", ")));
3648
+ const d = drift(n);
3649
+ if (d) add("Drift", `${driftPill(n)} commits on the tracked files since this doc's last commit`);
3650
+ if (str(a.lastReviewed)) add("Reviewed", esc(str(a.lastReviewed) ?? ""));
3651
+ const acc = arr(a.acceptance);
3652
+ if (acc.length) add("Acceptance", `<ul>${acc.map((c) => `<li>${md(c)}</li>`).join("")}</ul>`);
3653
+ if (arr(a.missingSections).length) add("Missing", esc(arr(a.missingSections).join(", ")));
3654
+ if (arr(a.pillars).length) add("Pillars", esc(arr(a.pillars).join(", ")));
3655
+ if (str(a.severity)) add("Severity", esc(str(a.severity) ?? ""));
3656
+ if (str(a.layer))
3657
+ add(
3658
+ "Layer",
3659
+ esc(`${str(a.layer)}${str(a.replaces) ? ` (replaces the ${str(a.replaces)} one)` : ""}`)
3660
+ );
3661
+ if (arr(a.tags).length) add("Tags", esc(arr(a.tags).join(", ")));
3662
+ if (arr(a.requires).length) add("Needs", esc(arr(a.requires).join(", ")));
3663
+ if (num(a.lines)) add("Lines", String(num(a.lines)));
3664
+ if (typeof a.exists === "boolean")
3665
+ add("Exists", a.exists ? pill("yes", "ok") : pill("no", "err"));
3666
+ if (num(a.matches) !== void 0) add("Matches", `${num(a.matches)} files`);
3667
+ if (str(a.engine)) add("Engine", esc(str(a.engine) ?? ""));
3668
+ if (str(a.pillar)) add("Goes to", esc(str(a.pillar) ?? ""));
3669
+ if (arr(a.evidence).length)
3670
+ add(
3671
+ "Evidence",
3672
+ `<ul>${arr(a.evidence).map((e) => `<li>${md(e)}</li>`).join("")}</ul>`
3673
+ );
3674
+ return rows.length ? `<dl>${rows.join("")}</dl>` : "";
3675
+ }
3676
+ function edgeList(ix, n) {
3677
+ const groups = /* @__PURE__ */ new Map();
3678
+ const push = (label, item) => groups.set(label, [...groups.get(label) ?? [], item]);
3679
+ const OUT = {
3680
+ tracks: "Tracks",
3681
+ anchors: "Anchored in",
3682
+ requires: "Requires",
3683
+ creates: "Creates",
3684
+ spec: "Spec",
3685
+ "links-to": "Links to",
3686
+ "gap-of": "Gap of",
3687
+ checks: "Checks",
3688
+ suggests: "Suggests",
3689
+ invokes: "Invokes",
3690
+ "renders-to": "Rendered to",
3691
+ contains: "Contains"
3692
+ };
3693
+ const IN = {
3694
+ tracks: "Tracked by",
3695
+ anchors: "Anchor of",
3696
+ requires: "Required by",
3697
+ creates: "Created by",
3698
+ spec: "Spec of",
3699
+ "links-to": "Cited by",
3700
+ "gap-of": "Known gaps",
3701
+ checks: "Checked by",
3702
+ suggests: "Suggested by",
3703
+ invokes: "Command",
3704
+ "renders-to": "Rendered from",
3705
+ contains: "Part of"
3706
+ };
3707
+ for (const e of ix.outOf(n.id)) push(OUT[e.type] ?? e.type, nodeRef(ix, e.to));
3708
+ for (const e of ix.inOf(n.id)) push(IN[e.type] ?? e.type, nodeRef(ix, e.from));
3709
+ if (!groups.size) return "";
3710
+ return `<dl class="rel">${[...groups.entries()].map(
3711
+ ([k, items]) => `<dt>${esc(k)} <span class="k">${items.length}</span></dt><dd><ul>${items.map((i) => `<li>${i}</li>`).join("")}</ul></dd>`
3712
+ ).join("")}</dl>`;
3713
+ }
3714
+ function issueList(issues) {
3715
+ if (!issues.length) return "";
3716
+ return `<ul class="issues">${issues.map(
3717
+ (i) => `<li class="sev-${i.severity}">${pill(i.severity, i.severity === "error" ? "err" : "warn")} <span class="mono">${esc(i.linter)}</span>${i.line !== void 0 ? ` <span class="k">line ${i.line}</span>` : ""}<br>${esc(i.message)}</li>`
3718
+ ).join("")}</ul>`;
3719
+ }
3720
+ function threadHtml(t, ix) {
3721
+ return `<article class="thread st-${t.status}" id="t-${esc(t.id)}"><header>${pill(t.status, t.status === "answered" ? "acc" : t.status === "resolved" ? "ok" : t.status === "submitted" ? "warn" : "mut")} <span class="k">${esc(t.id)}</span> ${nodeRef(ix, t.anchor.nodeId)}</header>${t.messages.map(
3722
+ (m) => `<div class="msg m-${m.author}"><span class="who">${m.author === "human" ? "you" : "agent"}</span><p>${esc(m.body)}</p>${(m.changes ?? []).map((c) => `<span class="mono chg">${esc(`${c.path}:${c.line}`)}</span>`).join(" ")}</div>`
3723
+ ).join("")}${t.status === "answered" || t.status === "open" ? `<form class="reply" data-thread="${esc(t.id)}"><label class="sr" for="r-${esc(t.id)}">Reply</label><textarea id="r-${esc(t.id)}" rows="2" placeholder="Reply"></textarea><div class="btns"><button type="submit">Reply</button>${t.status === "answered" ? `<button type="button" data-resolve="${esc(t.id)}">Resolve</button>` : ""}</div></form>` : ""}</article>`;
3724
+ }
3725
+ function renderDetails(ix, prefix, removed, session) {
3726
+ const threadsOf = /* @__PURE__ */ new Map();
3727
+ for (const t of session?.threads ?? [])
3728
+ threadsOf.set(t.anchor.nodeId, [...threadsOf.get(t.anchor.nodeId) ?? [], t]);
3729
+ const all = [...ix.graph.nodes, ...removed];
3730
+ return all.map((n) => {
3731
+ const domainLabel = n.domain === "harness" ? "harness (read-only: change it upstream)" : n.domain;
3732
+ const threads = threadsOf.get(n.id) ?? [];
3733
+ const comment = session ? `<section class="comments"><h4>Comments</h4>${threads.map((t) => threadHtml(t, ix)).join("")}<form class="comment" data-node="${esc(n.id)}"><label class="sr" for="cm-${htmlId(n.id)}">Comment on this card</label><textarea id="cm-${htmlId(n.id)}" rows="3" placeholder="${n.domain === "harness" ? "Comment: the agent drafts an upstream issue" : "Comment: the agent changes the source"}"></textarea><button type="submit">Add comment</button></form></section>` : "";
3734
+ return `<article class="detail" id="${htmlId(n.id)}" data-node="${esc(n.id)}"${(() => {
3735
+ const m = mapOf(ix, n.id);
3736
+ return m && !m.startsWith("harness:") ? ` data-map="${htmlId(m)}"` : "";
3737
+ })()}><header><span class="k">${esc(TYPE_LABEL[n.type])} \xB7 ${esc(domainLabel)}</span><h3>${md(n.title)}</h3>${sourceLink(n, prefix)}</header>${issueList(n.issues)}${attrRows(n)}${edgeList(ix, n)}${comment}</article>`;
3738
+ }).join("\n");
3739
+ }
3740
+ function overview(ix) {
3741
+ const g = ix.graph;
3742
+ const terminals = ix.of("intent").filter((n) => n.attrs.terminal === true);
3743
+ const delivered = terminals.filter((n) => n.attrs.effectiveStatus === "implemented").length;
3744
+ const proposed = terminals.filter((n) => n.attrs.effectiveStatus === "proposed");
3745
+ const tracked = g.nodes.filter((n) => drift(n));
3746
+ const maxDrift = tracked.reduce((m, n) => Math.max(m, drift(n)?.commits ?? 0), 0);
3747
+ const decisions = ix.of("decision");
3748
+ const orphans = decisions.filter((d) => ix.inOf(d.id, "links-to").length === 0).length;
3749
+ const unresolved = g.nodes.filter(
3750
+ (n) => (n.type === "path" || n.type === "glob") && n.attrs.exists === false
3751
+ ).length;
3752
+ const tile = (label, value, sub, tone = "") => `<div class="tile ${tone}"><span class="tl">${esc(label)}</span><span class="tv">${esc(value)}</span><span class="ts">${esc(sub)}</span></div>`;
3753
+ const review = [...tracked].sort((a, b) => {
3754
+ const ra = (drift(a)?.commits ?? 0) / (drift(a)?.threshold ?? 1);
3755
+ const rb = (drift(b)?.commits ?? 0) / (drift(b)?.threshold ?? 1);
3756
+ return rb - ra || (a.id < b.id ? -1 : 1);
3757
+ }).slice(0, 6);
3758
+ return `<section class="view" id="view-overview" data-title="Overview"><h2>State of the context</h2>
3759
+ <div class="tiles">
3760
+ ${tile("Lint", g.lint.ran ? `${g.lint.errors} \xB7 ${g.lint.warnings}` : "not run", "errors \xB7 warnings", g.lint.errors ? "bad" : "")}
3761
+ ${tile("Intents", `${delivered}/${terminals.length}`, `terminal intents delivered, ${proposed.length} proposed`)}
3762
+ ${tile("Tracked docs", String(tracked.length), `highest drift ${maxDrift} commits`)}
3763
+ ${tile("Decisions", String(decisions.length), `${orphans} cited by no doc`, orphans ? "warn" : "")}
3764
+ ${tile("Pointers", String(ix.of("path").length + ix.of("glob").length), `${unresolved} do not resolve`, unresolved ? "bad" : "")}
3765
+ </div>
3766
+ <div class="cols"><div class="panel"><h3>Review first</h3><p class="k">Tracked docs closest to their drift threshold.</p><ul class="list">${review.map((n) => `<li>${driftPill(n)} ${nodeRef(ix, n.id)}</li>`).join("")}</ul></div>
3767
+ <div class="panel"><h3>Proposed, not delivered</h3><ul class="list">${proposed.map(
3768
+ (n) => `<li>${nodeRef(ix, n.id)} <span class="k">${arr(n.attrs.acceptance).length} criteria</span></li>`
3769
+ ).join("") || '<li class="k">Nothing proposed.</li>'}</ul></div>
3770
+ <div class="panel"><h3>Lint</h3>${g.lint.ran ? g.nodes.some((n) => n.issues.length) || g.lint.unattached.length ? `<ul class="list">${g.nodes.filter((n) => n.issues.length).map((n) => `<li>${issuesPill(n.issues)} ${nodeRef(ix, n.id)}</li>`).join(
3771
+ ""
3772
+ )}${g.lint.unattached.map((i) => `<li>${pill(i.severity, "err")} ${esc(`${i.file}: ${i.message}`)}</li>`).join("")}</ul>` : '<p class="k">Every linter passes.</p>' : '<p class="k">Run without lint (<code>--no-lint</code>).</p>'}</div></div></section>`;
3773
+ }
3774
+ function intentsView(ix) {
3775
+ const rows = [];
3776
+ const children = /* @__PURE__ */ new Map();
3777
+ for (const n of ix.of("intent"))
3778
+ children.set(n.parent ?? "", [...children.get(n.parent ?? "") ?? [], n]);
3779
+ for (const list of children.values()) list.sort((a, b) => a.line - b.line);
3780
+ const bar = (n) => {
3781
+ const done = num(n.attrs.done) ?? 0;
3782
+ const total = num(n.attrs.total) ?? 0;
3783
+ if (!total) return "";
3784
+ return `<span class="bar" title="${done}/${total}"><i style="width:${Math.round(done / total * 100)}%"></i></span><span class="mono k">${done}/${total}</span>`;
3785
+ };
3786
+ const walk = (id, depth) => {
3787
+ for (const n of children.get(id) ?? []) {
3788
+ const status = str(n.attrs.effectiveStatus);
3789
+ const terminal = n.attrs.terminal === true;
3790
+ const acc = arr(n.attrs.acceptance);
3791
+ rows.push(
3792
+ `<li class="tr l${depth}${terminal && status === "proposed" ? " pr" : ""}" style="--d:${depth}"><span class="ttl">${nodeRef(ix, n.id)}</span>${terminal ? statusPill(status) : bar(n)}${acc.length ? `<ul class="acc">${acc.map((c) => `<li>${md(c)}</li>`).join("")}</ul>` : ""}</li>`
3793
+ );
3794
+ walk(n.id, depth + 1);
3795
+ }
3796
+ };
3797
+ for (const f of ix.of("intent-file")) {
3798
+ rows.push(
3799
+ `<li class="tr l0" style="--d:0"><span class="ttl"><b>${nodeRef(ix, f.id)}</b></span>${bar(f)}</li>`
3800
+ );
3801
+ walk(f.id, 1);
3802
+ }
3803
+ return `<section class="view" id="view-intents" data-title="Intents"><h2>Intent tree</h2><p class="k">What the product does, what is left: the share of delivered terminal intents under each node.</p><ul class="tree">${rows.join("")}</ul></section>`;
3804
+ }
3805
+ function vocabularyView(ix) {
3806
+ const terms = ix.of("term");
3807
+ const cards = terms.map((t) => {
3808
+ const req = ix.inOf(t.id, "requires").length;
3809
+ const cre = ix.inOf(t.id, "creates").length;
3810
+ const tone = t.attrs.defined === false ? "bad" : req > 0 && cre === 0 ? "warn" : req + cre === 0 ? "dim" : "";
3811
+ const note = t.attrs.defined === false ? "used, not in any Vocabulary" : req > 0 && cre === 0 ? "required, created by no intent" : req + cre === 0 ? "defined, used by no intent" : "";
3812
+ return `<div class="term ${tone}">${nodeRef(ix, t.id)}<span class="k">created by ${cre} \xB7 required by ${req}</span>${note ? `<span class="note">${esc(note)}</span>` : ""}</div>`;
3813
+ });
3814
+ return `<section class="view" id="view-vocabulary" data-title="Vocabulary"><h2>Vocabulary</h2><p class="k">The spec's words, and the intents that create and require them.</p><div class="terms">${cards.join("")}</div></section>`;
3815
+ }
3816
+ function decisionsView(ix) {
3817
+ const items = ix.of("decision").map((d) => {
3818
+ const alts = ix.outOf(d.id, "contains").map((e) => ix.byId.get(e.to)).filter((n) => !!n);
3819
+ const refs = ix.inOf(d.id, "links-to").length;
3820
+ return `<details class="adr"><summary>${nodeRef(ix, d.id)} ${pill(`cited \xD7${refs}`, refs <= 1 ? "warn" : "mut")} ${issuesPill(d.issues)}</summary>${str(d.attrs.decision) ? `<p>${md(str(d.attrs.decision) ?? "")}</p>` : ""}${alts.map(
3821
+ (a) => `<div class="alt"><b>Rejected \xB7 ${md(a.title)}</b> ${md(str(a.attrs.text) ?? "")}</div>`
3822
+ ).join("")}</details>`;
3823
+ });
3824
+ return `<section class="view" id="view-decisions" data-title="Decisions"><h2>Decisions in force</h2><p class="k">Why it is done this way, and what was set aside.</p><div class="adrs">${items.join("")}</div></section>`;
3825
+ }
3826
+ function lintersView(ix) {
3827
+ const groups = /* @__PURE__ */ new Map();
3828
+ for (const l of ix.of("linter")) {
3829
+ const key = arr(l.attrs.pillars).join(", ");
3830
+ groups.set(key, [...groups.get(key) ?? [], l]);
3831
+ }
3832
+ const rows = [...groups.entries()].map(([pillars, list]) => {
3833
+ const skills = [...new Set(list.flatMap((l) => arr(l.attrs.suggests)))];
3834
+ return `<div class="lr"><span class="lp">${esc(pillars)}</span><span class="lc">${list.map(
3835
+ (l) => `<a class="lk ${str(l.attrs.severity) === "error" ? "e" : "w"}" href="#${htmlId(l.id)}" data-n="${htmlId(l.id)}">${esc(l.title.replace(/^lint:/, ""))} <i class="${num(l.attrs.issues) ? "bad" : ""}">${num(l.attrs.issues) ?? 0}</i></a>`
3836
+ ).join(
3837
+ ""
3838
+ )}</span><span class="ls${skills.length ? "" : " none"}">${skills.length ? `\u2192 ${esc(skills.join(", "))}` : "no skill suggested"}</span></div>`;
3839
+ });
3840
+ return `<section class="view" id="view-linters" data-title="Linters"><h2>Linters <span class="k">harness domain</span></h2><p class="k">What is checked, where, with which result, and which skill fixes it. Solid border: error. Dashed: warning. The number is the current issues.</p><div class="lint-map">${rows.join("")}</div></section>`;
3841
+ }
3842
+ function skillsView(ix) {
3843
+ const skills = ix.of("skill");
3844
+ const layers = ["shipped", "project", "override"].map((l) => {
3845
+ const n = skills.filter((s) => s.attrs.layer === l).length;
3846
+ return `<span class="ly${n ? " on" : ""}">${esc(l === "shipped" ? "Shipped (harness)" : l === "project" ? "Project docs/skills/" : "Local overrides")} \xB7 ${n}</span>`;
3847
+ });
3848
+ const disabled = skills.filter((s) => s.attrs.disabled).length;
3849
+ const engines = ["claude-code", "codex-cli", "opencode"];
3850
+ const rows = skills.map((s) => {
3851
+ const cmd = ix.inOf(s.id, "invokes").map((e) => ix.byId.get(e.from)?.title).filter(Boolean).join(", ");
3852
+ const suggestedBy = ix.inOf(s.id, "suggests").length;
3853
+ const rendered = ix.outOf(s.id, "renders-to").map((e) => str(ix.byId.get(e.to)?.attrs.engine));
3854
+ const cells = engines.map((eng) => {
3855
+ const has = rendered.includes(eng) || eng === "opencode" && rendered.length > 0 && ix.graph.nodes.some((n) => n.type === "rendered-file" && n.attrs.engine === "opencode");
3856
+ return `<td class="${has ? "ok" : "no"}">${has ? "\u2713" : "\u2014"}</td>`;
3857
+ });
3858
+ return `<tr><td>${nodeRef(ix, s.id)}</td><td class="mono">${esc(cmd || "\u2014")}</td><td>${esc(arr(s.attrs.tags).join(", "))}</td><td class="${suggestedBy ? "" : "warn"}">${suggestedBy ? `${suggestedBy} linter${suggestedBy > 1 ? "s" : ""}` : "none"}</td>${cells.join("")}<td class="num">${num(s.attrs.lines) ?? 0}</td></tr>`;
3859
+ });
3860
+ return `<section class="view" id="view-skills" data-title="Skills"><h2>Skills</h2><p class="k">What the agent can load, where it comes from, where it is rendered. Lines hint at the context a skill costs when loaded.</p><div class="layers">${layers.join("")}${disabled ? `<span class="ly">Disabled \xB7 ${disabled}</span>` : ""}</div><div class="tbl"><table><thead><tr><th>Skill</th><th>Command</th><th>Tags</th><th>Suggested by</th><th>Claude Code</th><th>Codex</th><th>OpenCode</th><th>Lines</th></tr></thead><tbody>${rows.join("")}</tbody></table></div></section>`;
3861
+ }
3862
+ function lessonsView(ix) {
3863
+ const lessons = ix.of("lesson");
3864
+ if (!lessons.length) return "";
3865
+ return `<section class="view" id="view-lessons" data-title="Lessons"><h2>Lessons proposed <span class="k">local</span></h2><p class="k">Patches reviews keep asking for, and the rule that would prevent them. Accept, edit or reject them with <code>/harn-improve</code>.</p><div class="lessons">${lessons.map(
3866
+ (l) => `<div class="lesson">${nodeRef(ix, l.id)}<span class="row">${pill(str(l.attrs.status) ?? "proposed", str(l.attrs.status) === "accepted" ? "ok" : str(l.attrs.status) === "rejected" ? "mut" : "acc")}${str(l.attrs.domain) ? pill(str(l.attrs.domain) ?? "", "mut") : ""}${num(l.attrs.seen) ? pill(`seen ${num(l.attrs.seen)}\xD7`, "mut") : ""}${str(l.attrs.pillar) ? `<span class="k">\u2192 ${esc(str(l.attrs.pillar) ?? "")}</span>` : ""}</span></div>`
3867
+ ).join("")}</div></section>`;
3868
+ }
3869
+ function sessionView(ix, s, diff) {
3870
+ const count2 = (state) => [...diff.values()].filter((d) => d === state).length;
3871
+ const baseIssues = new Set(
3872
+ s.base.nodes.flatMap((n) => n.issues).concat(s.base.lint.unattached).map((i) => `${i.linter}|${i.file}|${i.message}`)
3873
+ );
3874
+ const nowIssues = ix.graph.nodes.flatMap((n) => n.issues).concat(ix.graph.lint.unattached);
3875
+ const nowKeys = new Set(nowIssues.map((i) => `${i.linter}|${i.file}|${i.message}`));
3876
+ const added = nowIssues.filter((i) => !baseIssues.has(`${i.linter}|${i.file}|${i.message}`));
3877
+ const gone = s.base.nodes.flatMap((n) => n.issues).filter((i) => !nowKeys.has(`${i.linter}|${i.file}|${i.message}`));
3878
+ const open = s.threads.filter((t) => t.status === "open").length;
3879
+ return `<section class="view" id="view-session" data-title="Session"><h2>Review session <span class="k">${esc(s.id)}</span></h2>
3880
+ <div class="tiles"><div class="tile"><span class="tl">Cards</span><span class="tv">+${count2("add")} ~${count2("chg")} \u2212${count2("del")}</span><span class="ts">since the session start</span></div><div class="tile ${added.length ? "bad" : ""}"><span class="tl">Lint</span><span class="tv">+${added.length} \u2212${gone.length}</span><span class="ts">issues since the start</span></div><div class="tile"><span class="tl">Comments</span><span class="tv">${s.threads.length}</span><span class="ts">${open} not handed over yet</span></div></div>
3881
+ <div class="session-actions"><button type="button" data-submit ${open ? "" : "disabled"}>Hand over to the agent (${open})</button><button type="button" data-end>End the review</button></div>
3882
+ <div class="cols"><div class="panel"><h3>Lint since the start</h3><ul class="list">${added.map(
3883
+ (i) => `<li>${pill(`+ ${i.severity}`, "err")} <span class="mono">${esc(i.linter)}</span> ${esc(`${i.file}${i.line ? `:${i.line}` : ""}: ${i.message}`)}</li>`
3884
+ ).join(
3885
+ ""
3886
+ )}${gone.map((i) => `<li>${pill(`\u2212 ${i.severity}`, "ok")} <span class="mono">${esc(i.linter)}</span> ${esc(`${i.file}: ${i.message}`)}</li>`).join("") || (added.length ? "" : '<li class="k">No change.</li>')}</ul></div>
3887
+ <div class="panel"><h3>Journal</h3><ol class="journal">${[...s.journal].reverse().map(
3888
+ (j) => `<li><span class="mono k">${esc(j.at.slice(11, 19))}</span> ${esc(j.files.join(", ") || "\u2014")} ${pill(`${j.errors} \xB7 ${j.warnings}`, j.errors ? "err" : "ok")}${j.note ? `<br><em>${esc(j.note)}</em>` : ""}</li>`
3889
+ ).join("") || '<li class="k">No change yet.</li>'}</ol></div></div>
3890
+ <h3>Comments</h3><div class="threads">${s.threads.map((t) => threadHtml(t, ix)).join("") || '<p class="k">Select a card, then comment it in the side panel.</p>'}</div></section>`;
3891
+ }
3892
+ function diffOf(graph, base) {
3893
+ const diff = /* @__PURE__ */ new Map();
3894
+ if (!base) return { diff, removed: [] };
3895
+ const before = new Map(base.nodes.map((n) => [n.id, n]));
3896
+ for (const n of graph.nodes) {
3897
+ const b = before.get(n.id);
3898
+ if (!b) diff.set(n.id, "add");
3899
+ else if (signature(b) !== signature(n)) diff.set(n.id, "chg");
3900
+ }
3901
+ const now = new Set(graph.nodes.map((n) => n.id));
3902
+ const removed = base.nodes.filter((n) => !now.has(n.id) && n.type !== "section");
3903
+ for (const n of removed) diff.set(n.id, "del");
3904
+ return { diff, removed };
3905
+ }
3906
+ function renderView(graph, opts = {}) {
3907
+ const ix = new Index(graph);
3908
+ const prefix = opts.sourcePrefix ?? (opts.session ? "/" : "../../");
3909
+ const { diff, removed } = diffOf(graph, opts.session?.base);
3910
+ const project = ix.of("readme")[0]?.title ?? "Project";
3911
+ const views = [
3912
+ overview(ix),
3913
+ intentsView(ix),
3914
+ vocabularyView(ix),
3915
+ decisionsView(ix),
3916
+ lintersView(ix),
3917
+ skillsView(ix),
3918
+ lessonsView(ix),
3919
+ opts.session ? sessionView(ix, opts.session, diff) : ""
3920
+ ].filter(Boolean);
3921
+ const tabs = [
3922
+ ["canvas", "Canvas"],
3923
+ ...views.map((v) => {
3924
+ const id = /id="view-([a-z]+)"/.exec(v)?.[1] ?? "";
3925
+ const title = /data-title="([^"]+)"/.exec(v)?.[1] ?? id;
3926
+ return [id, title];
3927
+ })
3928
+ ];
3929
+ const lintTone = !graph.lint.ran ? "mut" : graph.lint.errors ? "err" : graph.lint.warnings ? "warn" : "ok";
3930
+ const lintText = graph.lint.ran ? `lint ${graph.lint.errors} \xB7 ${graph.lint.warnings}` : "lint not run";
3931
+ return `<!doctype html>
3932
+ <html lang="en">
3933
+ <head>
3934
+ <meta charset="utf-8">
3935
+ <meta name="viewport" content="width=device-width,initial-scale=1">
3936
+ <meta name="generator" content="@vaubaan/harness ${esc(graph.harness)}">
3937
+ <title>${esc(project)} \u2014 context</title>
3938
+ <style>${VIEW_STYLE}</style>
3939
+ </head>
3940
+ <body${opts.session ? ` data-session="${esc(opts.session.id)}" data-revision="${opts.session.revision}"` : ""}>
3941
+ <header class="top">
3942
+ <div class="brand"><b>${esc(project)}</b><span class="k">context \xB7 harness ${esc(graph.harness)}</span></div>
3943
+ <nav class="tabs" aria-label="Views">${tabs.map(([id, label]) => `<a href="#view-${id}" data-tab="${id}">${esc(label ?? "")}</a>`).join("")}</nav>
3944
+ <div class="status"><span id="hs">${pill(lintText, lintTone)}${opts.session ? '<span class="live" title="Live review session"><i></i>live</span>' : ""}</span>${opts.session ? `<span class="seg" role="group" aria-label="Differences"><button type="button" data-diff="before">Before</button><button type="button" data-diff="now" aria-pressed="true">Now</button><button type="button" data-diff="diff">Differences</button></span>` : ""}<label class="sr" for="q">Search</label><input id="q" type="search" placeholder="Search /" autocomplete="off"></div>
3945
+ </header>
3946
+ <main>
3947
+ <section class="view active" id="view-canvas" data-title="Canvas">${renderCanvas(ix, diff, removed)}</section>
3948
+ ${views.join("\n")}
3949
+ </main>
3950
+ <aside class="side" id="side" aria-label="Card details"><button type="button" class="close" data-close aria-label="Close">\xD7</button><p class="k empty">Select a card to see where it comes from and what it is linked to.</p>
3951
+ ${renderDetails(ix, prefix, removed, opts.session)}
3952
+ </aside>
3953
+ <script>${VIEW_SCRIPT}</script>
3954
+ </body>
3955
+ </html>
3956
+ `;
3957
+ }
3958
+
3959
+ // src/cli/view.ts
3960
+ import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
3961
+ import { dirname as dirname4, join as join12, resolve as resolve5 } from "path";
3962
+ var VIEW_PATH = ".vaubaan/view/index.html";
3963
+ function viewCommand(args) {
3964
+ const root = resolve5(args.targetDir);
3965
+ const outDir = args.outDir ? resolve5(args.outDir) : join12(root, ".vaubaan");
3966
+ const graph = buildGraph(root, {
3967
+ ...args.lint === false ? { lint: false } : {},
3968
+ ...args.packageDir ? { packageDir: args.packageDir } : {}
3969
+ });
3970
+ const graphPath = join12(outDir, "graph.json");
3971
+ const htmlPath = join12(outDir, "view", "index.html");
3972
+ mkdirSync(dirname4(htmlPath), { recursive: true });
3973
+ writeFileSync2(graphPath, serializeGraph(graph));
3974
+ writeFileSync2(htmlPath, renderView(graph));
3975
+ return { graph, graphPath, htmlPath };
3976
+ }
3977
+ export {
3978
+ GRAPH_PATH,
3979
+ NODE_TYPES,
3980
+ VIEW_PATH,
3981
+ buildGraph,
3982
+ htmlId,
3983
+ renderView,
3984
+ serializeGraph,
3985
+ viewCommand
3986
+ };
3987
+ //# sourceMappingURL=index.js.map