@vaubaan/harness 1.4.0 → 2.1.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 (41) hide show
  1. package/README.md +301 -167
  2. package/dist/cli/index.js +886 -1882
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/commands/handbook.cmd.md +4 -3
  5. package/dist/commands/test-plan.cmd.md +4 -4
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +277 -1064
  8. package/dist/index.js.map +1 -1
  9. package/dist/init.d.ts +8 -23
  10. package/dist/init.js +270 -1036
  11. package/dist/init.js.map +1 -1
  12. package/dist/linters/index.js +687 -31
  13. package/dist/linters/index.js.map +1 -1
  14. package/dist/parser/index.d.ts +1 -26
  15. package/dist/parser/index.js +1 -17
  16. package/dist/parser/index.js.map +1 -1
  17. package/dist/{render-Cu2XrkkY.d.ts → render-C-FWmUfX.d.ts} +8 -15
  18. package/dist/render.d.ts +1 -1
  19. package/dist/render.js +18 -280
  20. package/dist/render.js.map +1 -1
  21. package/dist/skills/decision-record-writer.skill.md +93 -131
  22. package/dist/skills/doc-audit.skill.md +10 -10
  23. package/dist/skills/drift-detector.skill.md +6 -7
  24. package/dist/skills/handbook-writer.skill.md +68 -159
  25. package/dist/skills/readme-writer.skill.md +3 -3
  26. package/dist/skills/spec-writer.skill.md +111 -71
  27. package/dist/skills/test-plan-writer.skill.md +47 -54
  28. package/dist/skills/workflow-writer.skill.md +40 -6
  29. package/dist/templates/code-quality.md.tmpl +2 -2
  30. package/dist/templates/coding-workflow.md.tmpl +10 -0
  31. package/dist/templates/decision.md.tmpl +20 -47
  32. package/dist/templates/e2e-tests.md.tmpl +16 -45
  33. package/dist/templates/handbook.md.tmpl +20 -38
  34. package/dist/templates/integration-tests.md.tmpl +16 -34
  35. package/package.json +1 -1
  36. package/dist/agents/coding.agent.md +0 -182
  37. package/dist/agents/merge.agent.md +0 -139
  38. package/dist/agents/planning.agent.md +0 -194
  39. package/dist/agents/review.agent.md +0 -176
  40. package/dist/commands/clean-code.cmd.md +0 -26
  41. package/dist/skills/clean-code-guardian.skill.md +0 -391
package/dist/cli/index.js CHANGED
@@ -41,9 +41,9 @@ function gitLastCommitForPath(repoRoot, relativePath) {
41
41
  if (!out) return void 0;
42
42
  const idx = out.indexOf(":");
43
43
  if (idx < 0) return void 0;
44
- const hash2 = out.slice(0, idx);
44
+ const hash = out.slice(0, idx);
45
45
  const ts = Number.parseInt(out.slice(idx + 1), 10);
46
- return { hash: hash2, timestamp: ts };
46
+ return { hash, timestamp: ts };
47
47
  } catch {
48
48
  return void 0;
49
49
  }
@@ -356,435 +356,22 @@ var frontmatterTracks = {
356
356
  }
357
357
  };
358
358
 
359
- // src/linters/gitignore-harness.ts
360
- var REQUIRED_GITIGNORE_ENTRIES = [
361
- ".harness-overrides/",
362
- ".harness-manifest.json",
363
- ".harness/",
364
- ".claude/",
365
- ".codex/",
366
- ".opencode/",
367
- ".agents/",
368
- ".vaubaan/",
369
- "AGENTS.md",
370
- "CLAUDE.md",
371
- ".mcp.json"
372
- ];
373
- var gitignoreHarness = {
374
- id: "lint:gitignore-harness",
375
- pillars: ["repo-root"],
376
- defaultSeverity: "error",
377
- run(repoRoot) {
378
- const issues = [];
379
- if (!fileExists(repoRoot, ".gitignore")) {
380
- issues.push({
381
- linter: this.id,
382
- severity: "error",
383
- file: ".gitignore",
384
- message: ".gitignore is missing at repo root"
385
- });
386
- return issues;
387
- }
388
- const text = readText(repoRoot, ".gitignore");
389
- const lines = new Set(
390
- text.split("\n").map((l) => l.trim()).filter(Boolean)
391
- );
392
- for (const entry of REQUIRED_GITIGNORE_ENTRIES) {
393
- const variants = [entry, entry.replace(/\/$/, "")];
394
- if (!variants.some((v) => lines.has(v))) {
395
- issues.push({
396
- linter: this.id,
397
- severity: "error",
398
- file: ".gitignore",
399
- message: `.gitignore must contain "${entry}"`
400
- });
401
- }
402
- }
403
- return issues;
404
- }
405
- };
406
-
407
- // src/linters/orphan-decisions.ts
408
- import { basename } from "path";
409
- import fg4 from "fast-glob";
410
- var orphanDecisions = {
411
- id: "lint:orphan-decisions",
412
- pillars: ["decisions"],
413
- defaultSeverity: "warning",
414
- suggestedSkills: ["/handbook"],
415
- run(repoRoot, ctx) {
416
- const extra = ctx?.config.ignore ?? [];
417
- const issues = [];
418
- const adrs = listMarkdown(repoRoot, "docs/decisions");
419
- if (adrs.length === 0) return issues;
420
- const otherDocs = fg4.sync("**/*.md", {
421
- cwd: repoRoot,
422
- absolute: false,
423
- ignore: [
424
- "**/node_modules/**",
425
- "**/dist/**",
426
- ".harness-overrides/**",
427
- "docs/decisions/**",
428
- "skills/**",
429
- "agents/**",
430
- "commands/**",
431
- "templates/**",
432
- ...extra
433
- ]
434
- });
435
- const referenceCorpus = otherDocs.map((f) => readText(repoRoot, f)).join("\n");
436
- for (const adr of adrs) {
437
- const filename = basename(adr);
438
- const stem = filename.replace(/\.md$/, "");
439
- const referenced = referenceCorpus.includes(filename) || referenceCorpus.includes(stem);
440
- if (!referenced) {
441
- issues.push({
442
- linter: this.id,
443
- severity: "warning",
444
- file: adr,
445
- message: "ADR is not referenced by any other doc file (orphan)"
446
- });
447
- }
448
- }
449
- return issues;
450
- }
451
- };
452
-
453
- // src/linters/quality-schema.ts
454
- var QUALITY_DIR = "docs/quality";
455
- var CARDINAL_FILE = `${QUALITY_DIR}/code-quality.md`;
456
- var REQUIRED_SECTIONS2 = [
457
- {
458
- label: "Mechanical checks",
459
- pattern: /^##\s+(Mechanical\s+checks|V[ée]rifications\s+m[ée]caniques)\s*$/im
460
- },
461
- { label: "Project rules", pattern: /^##\s+(Project\s+rules|R[èe]gles\s+du\s+projet)\s*$/im },
462
- {
463
- label: "Accepted deviations",
464
- pattern: /^##\s+(Accepted\s+deviations|[ÉE]carts\s+assum[ée]s)\s*$/im
465
- }
466
- ];
467
- var qualitySchema = {
468
- id: "lint:quality-schema",
469
- pillars: ["quality"],
470
- defaultSeverity: "error",
471
- run(repoRoot) {
472
- if (!dirExists(repoRoot, QUALITY_DIR)) return [];
473
- if (!fileExists(repoRoot, CARDINAL_FILE)) {
474
- return [
475
- {
476
- linter: this.id,
477
- severity: "error",
478
- file: CARDINAL_FILE,
479
- message: `missing required cardinal file: ${CARDINAL_FILE}`
480
- }
481
- ];
482
- }
483
- const text = readText(repoRoot, CARDINAL_FILE);
484
- return REQUIRED_SECTIONS2.filter(({ pattern }) => !pattern.test(text)).map(({ label }) => ({
485
- linter: this.id,
486
- severity: "error",
487
- file: CARDINAL_FILE,
488
- message: `missing required section: "${label}"`
489
- }));
490
- }
491
- };
492
-
493
- // src/linters/readme-presence.ts
494
- var readmePresence = {
495
- id: "lint:readme-presence",
496
- pillars: ["readme"],
497
- defaultSeverity: "error",
498
- suggestedSkills: ["/readme"],
499
- run(repoRoot) {
500
- if (fileExists(repoRoot, "README.md")) return [];
501
- return [
502
- {
503
- linter: this.id,
504
- severity: "error",
505
- file: "README.md",
506
- message: "README.md is missing at repo root"
507
- }
508
- ];
509
- }
510
- };
511
-
512
- // src/linters/readme-sections.ts
513
- var REQUIRED_SECTIONS3 = [
514
- /^#\s+\S/m,
515
- /^##?\s+(What is this|Quick start)/im,
516
- /^##?\s+(Quick start|Install|Getting started)/im
517
- ];
518
- var REQUIRED_LABELS = ["title (# H1)", "What is this / intro", "Quick start / Install"];
519
- var readmeSections = {
520
- id: "lint:readme-sections",
521
- pillars: ["readme"],
522
- defaultSeverity: "error",
523
- suggestedSkills: ["/readme"],
524
- run(repoRoot) {
525
- if (!fileExists(repoRoot, "README.md")) return [];
526
- const text = readText(repoRoot, "README.md");
527
- const issues = [];
528
- for (let i = 0; i < REQUIRED_SECTIONS3.length; i++) {
529
- const pattern = REQUIRED_SECTIONS3[i];
530
- const label = REQUIRED_LABELS[i];
531
- if (pattern && !pattern.test(text)) {
532
- issues.push({
533
- linter: this.id,
534
- severity: "error",
535
- file: "README.md",
536
- message: `missing required section: ${label}`
537
- });
538
- }
539
- }
540
- return issues;
541
- }
542
- };
543
-
544
- // src/linters/spec-has-content.ts
545
- var specHasContent = {
546
- id: "lint:spec-has-content",
547
- pillars: ["spec"],
548
- defaultSeverity: "warning",
549
- suggestedSkills: ["/spec"],
550
- run(repoRoot) {
551
- if (!dirExists(repoRoot, "docs/spec")) return [];
552
- const files = listMarkdown(repoRoot, "docs/spec");
553
- if (files.length > 0) return [];
554
- return [
555
- {
556
- linter: this.id,
557
- severity: "warning",
558
- file: "docs/spec",
559
- message: "docs/spec/ has no markdown files \u2014 write at least one spec document"
560
- }
561
- ];
562
- }
563
- };
564
-
565
- // src/linters/spec-tech-agnostic.ts
566
- function maskFencedBlocks(text) {
567
- return text.replace(/```[\s\S]*?```/g, (m) => m.replace(/[^\n]/g, " "));
568
- }
569
- var TECH_BLOCKLIST = [
570
- { pattern: /\bNext\.?js\b/i, keyword: "Next.js" },
571
- { pattern: /\bSupabase\b/i, keyword: "Supabase" },
572
- { pattern: /\bVercel\b/i, keyword: "Vercel" },
573
- { pattern: /\bReact\b/, keyword: "React" },
574
- { pattern: /\bTypeScript\b/, keyword: "TypeScript" },
575
- { pattern: /\bDocker\b/, keyword: "Docker" },
576
- { pattern: /\bKubernetes\b/i, keyword: "Kubernetes" },
577
- { pattern: /\bPostgres(QL)?\b/i, keyword: "Postgres" },
578
- { pattern: /\bMySQL\b/i, keyword: "MySQL" },
579
- { pattern: /\bRedis\b/i, keyword: "Redis" },
580
- { pattern: /\bnpm\b/, keyword: "npm" },
581
- { pattern: /\bpnpm\b/, keyword: "pnpm" },
582
- { pattern: /\byarn\b/, keyword: "yarn" }
583
- ];
584
- var specTechAgnostic = {
585
- id: "lint:spec-tech-agnostic",
586
- pillars: ["spec"],
587
- defaultSeverity: "error",
588
- suggestedSkills: ["/spec"],
589
- run(repoRoot) {
590
- const issues = [];
591
- const files = listMarkdown(repoRoot, "docs/spec");
592
- for (const f of files) {
593
- const text = maskFencedBlocks(readText(repoRoot, f));
594
- for (const { pattern, keyword } of TECH_BLOCKLIST) {
595
- if (pattern.test(text)) {
596
- const issue = {
597
- linter: this.id,
598
- severity: "error",
599
- file: f,
600
- message: `forbidden tech keyword "${keyword}" \u2014 should be in handbook/ or decisions/`
601
- };
602
- const line = findLineNumber(text, pattern);
603
- if (line !== void 0) issue.line = line;
604
- issues.push(issue);
605
- }
606
- }
607
- }
608
- return issues;
609
- }
610
- };
611
-
612
- // src/linters/tracks-drift.ts
613
- import fg5 from "fast-glob";
614
- var TRACKED_DIRS2 = ["docs/handbook", "docs/tests", "docs/workflow"];
615
- var DEFAULT_DRIFT_THRESHOLD = 10;
616
- function expandGlob(repoRoot, pattern) {
617
- if (pattern.includes("*")) {
618
- return fg5.sync(pattern, { cwd: repoRoot, absolute: false });
619
- }
620
- return [pattern];
621
- }
622
- var tracksDrift = {
623
- id: "lint:tracks-drift",
624
- pillars: ["handbook", "tests", "workflow"],
625
- defaultSeverity: "warning",
626
- suggestedSkills: ["/drift", "/handbook"],
627
- run(repoRoot) {
628
- const issues = [];
629
- for (const dir of TRACKED_DIRS2) {
630
- const files = listMarkdown(repoRoot, dir);
631
- for (const f of files) {
632
- const text = readText(repoRoot, f);
633
- const { data } = parseFrontmatter(text);
634
- if (!Array.isArray(data.tracks)) continue;
635
- const docCommit = gitLastCommitForPath(repoRoot, f);
636
- if (!docCommit) continue;
637
- const threshold = typeof data.driftThreshold === "number" && data.driftThreshold > 0 ? data.driftThreshold : DEFAULT_DRIFT_THRESHOLD;
638
- let driftCount = 0;
639
- for (const tracked of data.tracks) {
640
- if (typeof tracked !== "string") continue;
641
- const targets = expandGlob(repoRoot, tracked);
642
- for (const t of targets.length > 0 ? targets : [tracked]) {
643
- driftCount += gitCommitsSince(repoRoot, t, docCommit.hash);
644
- }
645
- }
646
- if (driftCount > threshold) {
647
- issues.push({
648
- linter: this.id,
649
- severity: "warning",
650
- file: f,
651
- message: `tracked files changed in ${driftCount} commits since doc last edit (threshold ${threshold})`
652
- });
653
- }
654
- }
655
- }
656
- return issues;
657
- }
658
- };
659
-
660
- // src/linters/index.ts
661
- var ALL_LINTERS = [
662
- readmePresence,
663
- readmeSections,
664
- docLayout,
665
- cardinalFiles,
666
- decisionSchema,
667
- adrNoTracks,
668
- frontmatterTracks,
669
- tracksDrift,
670
- specTechAgnostic,
671
- specHasContent,
672
- crossLinks,
673
- orphanDecisions,
674
- gitignoreHarness,
675
- qualitySchema
676
- ];
677
- function runLinters(repoRoot, opts = {}) {
678
- const config = loadLintConfig(repoRoot);
679
- const ctx = { repoRoot, config };
680
- const filtered = ALL_LINTERS.filter((l) => {
681
- if (opts.only && !opts.only.includes(l.id)) return false;
682
- if (opts.pillar && !l.pillars.includes(opts.pillar) && !l.pillars.includes("all")) return false;
683
- return true;
684
- });
685
- const issues = [];
686
- for (const linter of filtered) {
687
- try {
688
- issues.push(...linter.run(repoRoot, ctx));
689
- } catch (err) {
690
- issues.push({
691
- linter: linter.id,
692
- severity: "error",
693
- file: "<internal>",
694
- message: `linter crashed: ${err instanceof Error ? err.message : String(err)}`
695
- });
696
- }
697
- }
698
- const errors = issues.filter((i) => i.severity === "error").length;
699
- const warnings = issues.filter((i) => i.severity === "warning").length;
700
- return {
701
- version: 1,
702
- summary: { errors, warnings, pass: errors === 0 },
703
- issues
704
- };
705
- }
706
- function suggestedSkillsFor(linterId) {
707
- const linter = ALL_LINTERS.find((l) => l.id === linterId);
708
- return linter?.suggestedSkills ?? [];
709
- }
710
- function formatReportText(report) {
711
- const lines = [];
712
- for (const issue of report.issues) {
713
- const location = issue.line !== void 0 ? `:${issue.line}` : "";
714
- lines.push(`${issue.file}${location}: ${issue.severity}[${issue.linter}]
715
- ${issue.message}`);
716
- const hints = suggestedSkillsFor(issue.linter);
717
- if (hints.length > 0) {
718
- lines.push(` \u2192 Try: ${hints.join(", ")}`);
719
- }
720
- }
721
- const { errors, warnings, pass } = report.summary;
722
- lines.push("");
723
- lines.push(
724
- `${errors} ${errors === 1 ? "error" : "errors"}, ${warnings} ${warnings === 1 ? "warning" : "warnings"}. ${pass ? "\u2714 CI passes." : "\u2718 CI fails."}`
725
- );
726
- return lines.join("\n");
727
- }
728
-
729
- // src/version.ts
730
- var VERSION = "1.4.0";
731
-
732
- // src/cli/check.ts
733
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
734
- import { join as join4 } from "path";
735
- var REQUIRED_DIRS2 = [
736
- "docs/spec",
737
- "docs/decisions",
738
- "docs/handbook",
739
- "docs/tests",
740
- "docs/workflow"
741
- ];
742
- function checkCommand(repoRoot) {
743
- const issues = [];
744
- if (!existsSync4(join4(repoRoot, "README.md"))) {
745
- issues.push("README.md missing at repo root");
746
- }
747
- for (const d of REQUIRED_DIRS2) {
748
- if (!existsSync4(join4(repoRoot, d))) {
749
- issues.push(`missing directory: ${d}/`);
750
- }
751
- }
752
- const gitignorePath = join4(repoRoot, ".gitignore");
753
- if (!existsSync4(gitignorePath)) {
754
- issues.push(".gitignore missing at repo root");
755
- } else {
756
- const text = readFileSync2(gitignorePath, "utf8");
757
- const lines = new Set(
758
- text.split("\n").map((l) => l.trim()).filter(Boolean)
759
- );
760
- for (const entry of REQUIRED_GITIGNORE_ENTRIES) {
761
- const variants = [entry, entry.replace(/\/$/, "")];
762
- if (!variants.some((v) => lines.has(v))) {
763
- issues.push(`.gitignore missing entry: ${entry}`);
764
- }
765
- }
766
- }
767
- return { pass: issues.length === 0, issues };
768
- }
769
-
770
- // src/cli/init.ts
771
- import { existsSync as existsSync13, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync4 } from "fs";
772
- import { dirname as dirname6, join as join15, resolve as resolve7 } from "path";
359
+ // src/linters/generated-fresh.ts
360
+ import { existsSync as existsSync7, readFileSync as readFileSync5 } from "fs";
361
+ import { join as join8, resolve as resolve4 } from "path";
773
362
 
774
363
  // src/cli/managed-paths.ts
775
364
  import { lstatSync, realpathSync, statSync as statSync2 } from "fs";
776
- import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, resolve as resolve2, win32 } from "path";
777
- var MANAGED_FILES = /* @__PURE__ */ new Set([
778
- "AGENTS.md",
779
- "CLAUDE.md",
365
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join4, resolve as resolve2, win32 } from "path";
366
+ var MANAGED_FILES = /* @__PURE__ */ new Set(["AGENTS.md", "CLAUDE.md", ".harness-manifest.json"]);
367
+ var RELEASED_PATHS = [
780
368
  ".mcp.json",
781
- ".harness-manifest.json",
782
- ".claude/settings.json",
783
369
  ".codex/config.toml",
784
- ".codex/hooks.json",
785
370
  ".opencode/opencode.json",
786
- ".opencode/mcp.json"
787
- ]);
371
+ ".opencode/mcp.json",
372
+ ".claude/settings.json",
373
+ ".codex/hooks.json"
374
+ ];
788
375
  var MANAGED_DIRECTORIES = [
789
376
  ".claude/agents/",
790
377
  ".claude/commands/",
@@ -802,14 +389,14 @@ function canonicalTargetRoot(root) {
802
389
  let ancestor = resolve2(root);
803
390
  const missing = [];
804
391
  while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
805
- missing.unshift(basename2(ancestor));
392
+ missing.unshift(basename(ancestor));
806
393
  ancestor = dirname2(ancestor);
807
394
  }
808
395
  const canonical = realpathSync(ancestor);
809
396
  if (!statSync2(canonical).isDirectory()) {
810
397
  throw new Error(`harness target is not a directory: ${root}`);
811
398
  }
812
- return join5(canonical, ...missing);
399
+ return join4(canonical, ...missing);
813
400
  }
814
401
  function assertManagedLocation(path) {
815
402
  const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
@@ -824,7 +411,7 @@ function assertNoSymbolicComponents(root, path) {
824
411
  const parts = path.split("/");
825
412
  let current = root;
826
413
  for (const [index, part] of parts.entries()) {
827
- current = join5(current, part);
414
+ current = join4(current, part);
828
415
  const info = lstatSync(current, { throwIfNoEntry: false });
829
416
  if (!info) return;
830
417
  if (info.isSymbolicLink()) {
@@ -844,128 +431,59 @@ function assertManagedPaths(root, files) {
844
431
 
845
432
  // src/cli/manifest.ts
846
433
  import { createHash } from "crypto";
847
- import { chmodSync, existsSync as existsSync7, readFileSync as readFileSync5, writeFileSync } from "fs";
848
- import { join as join8 } from "path";
849
- import { z as z3 } from "zod";
850
-
851
- // src/cli/opencode-config.ts
852
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
853
- import { join as join6 } from "path";
854
- import { isDeepStrictEqual } from "util";
434
+ import { chmodSync, existsSync as existsSync4, readFileSync as readFileSync2, writeFileSync } from "fs";
435
+ import { join as join5 } from "path";
855
436
  import { z } from "zod";
856
- var OPENCODE_CONFIG_PATH = ".opencode/opencode.json";
857
- var CLAUDE_MCP_PATH = ".mcp.json";
858
- var OPENCODE_SCHEMA = "https://opencode.ai/config.json";
859
- var ObjectSchema = z.record(z.unknown());
860
- var OPENCODE_TARGET = {
861
- path: OPENCODE_CONFIG_PATH,
862
- key: "mcp",
863
- label: "OpenCode",
864
- schema: OPENCODE_SCHEMA
865
- };
866
- var CLAUDE_TARGET = {
867
- path: CLAUDE_MCP_PATH,
868
- key: "mcpServers",
869
- label: "Claude Code"
870
- };
871
- var OpenCodeConfigOwnershipSchema = z.object({
872
- createdFile: z.boolean(),
873
- addedMcp: z.boolean(),
874
- addedSchema: z.boolean(),
875
- entries: z.record(ObjectSchema)
437
+
438
+ // src/version.ts
439
+ var VERSION = "2.1.0";
440
+
441
+ // src/cli/manifest.ts
442
+ var MANIFEST_FILENAME = ".harness-manifest.json";
443
+ var MANIFEST_VERSION = "6";
444
+ var ManifestSchema = z.object({
445
+ version: z.enum(["4", "5", MANIFEST_VERSION]),
446
+ engines: z.array(z.string()),
447
+ renderedAt: z.string(),
448
+ files: z.array(z.string()),
449
+ harnessVersion: z.string().optional(),
450
+ overridesDir: z.string().optional(),
451
+ fileHashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)).optional(),
452
+ preservedFiles: z.array(z.string()).optional()
876
453
  });
877
- function parseConfig(target, content) {
878
- try {
879
- const config = ObjectSchema.parse(JSON.parse(content));
880
- if (Object.hasOwn(config, target.key)) ObjectSchema.parse(config[target.key]);
881
- return config;
882
- } catch {
883
- throw new Error(`invalid ${target.path}: expected a JSON object with an MCP object`);
884
- }
885
- }
886
- function removeOwnedEntries(target, config, ownership, warnings) {
887
- if (Object.hasOwn(config, target.key)) {
888
- const mcp = ObjectSchema.parse(config[target.key]);
889
- for (const [id, installed] of Object.entries(ownership.entries)) {
890
- if (!Object.hasOwn(mcp, id)) continue;
891
- if (isDeepStrictEqual(mcp[id], installed)) delete mcp[id];
892
- else warnings.push(`preserved modified ${target.label} MCP server: ${id}`);
893
- }
894
- config[target.key] = mcp;
895
- if (ownership.addedMcp && Object.keys(mcp).length === 0)
896
- Reflect.deleteProperty(config, target.key);
897
- }
898
- if (target.schema && ownership.addedSchema && config.$schema === target.schema)
899
- Reflect.deleteProperty(config, "$schema");
900
- }
901
- function addMissingEntries(target, config, desired, createdFile, warnings) {
902
- const requested = ObjectSchema.parse(parseConfig(target, desired.content)[target.key]);
903
- const mcp = ObjectSchema.parse(config[target.key] ?? {});
904
- const entries = {};
905
- for (const [id, entry] of Object.entries(requested)) {
906
- if (Object.hasOwn(mcp, id)) {
907
- if (!isDeepStrictEqual(mcp[id], entry)) {
908
- warnings.push(
909
- `preserved existing ${target.label} MCP server instead of replacing it: ${id}`
910
- );
911
- }
912
- continue;
913
- }
914
- entries[id] = ObjectSchema.parse(entry);
915
- mcp[id] = entry;
916
- }
917
- if (Object.keys(entries).length === 0) return void 0;
918
- const ownership = {
919
- createdFile,
920
- addedMcp: !Object.hasOwn(config, target.key),
921
- addedSchema: target.schema !== void 0 && !Object.hasOwn(config, "$schema"),
922
- entries
923
- };
924
- config[target.key] = mcp;
925
- if (target.schema && ownership.addedSchema) config.$schema = target.schema;
926
- return ownership;
927
- }
928
- function planMcpJson(target, root, desired, previous) {
929
- const warnings = [];
930
- if (!desired && !previous) return { remove: false, warnings };
931
- const path = join6(root, target.path);
932
- const existed = existsSync5(path);
933
- if (!existed && !desired) return { remove: false, warnings };
934
- const original = existed ? readFileSync3(path, "utf8") : void 0;
935
- const config = original === void 0 ? {} : parseConfig(target, original);
936
- const before = structuredClone(config);
937
- if (previous) removeOwnedEntries(target, config, previous, warnings);
938
- const createdFile = !existed || previous?.createdFile === true;
939
- const ownership = desired ? addMissingEntries(target, config, desired, createdFile, warnings) : void 0;
940
- if (!ownership && createdFile && Object.keys(config).length === 0) {
941
- return { remove: existed, warnings };
942
- }
943
- return {
944
- remove: false,
945
- ownership,
946
- warnings,
947
- ...!existed || !isDeepStrictEqual(before, config) ? { write: { path: target.path, content: `${JSON.stringify(config, null, 2)}
948
- ` } } : {}
949
- };
454
+ function manifestPath(targetDir) {
455
+ return join5(targetDir, MANIFEST_FILENAME);
950
456
  }
951
- function planOpenCodeConfig(root, desired, previous) {
952
- return planMcpJson(OPENCODE_TARGET, root, desired, previous);
457
+ function hashContent(content) {
458
+ return createHash("sha256").update(content).digest("hex");
953
459
  }
954
- function planClaudeMcpConfig(root, desired, previous) {
955
- return planMcpJson(CLAUDE_TARGET, root, desired, previous);
460
+ function readManifest(targetDir) {
461
+ assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
462
+ const path = manifestPath(targetDir);
463
+ if (!existsSync4(path)) return null;
464
+ const raw = JSON.parse(readFileSync2(path, "utf8"));
465
+ return ManifestSchema.parse(raw);
956
466
  }
957
467
 
958
- // src/cli/update-config.ts
959
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "fs";
960
- import { join as join7 } from "path";
961
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
962
- import { z as z2 } from "zod";
468
+ // src/cli/plan-render.ts
469
+ import { existsSync as existsSync6 } from "fs";
470
+ import { dirname as dirname3, join as join7, resolve as resolve3 } from "path";
471
+ import { fileURLToPath } from "url";
963
472
 
964
- // src/renderers/common.ts
965
- import { stringify as yamlStringify } from "yaml";
473
+ // src/loader.ts
474
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
475
+ import { join as join6 } from "path";
476
+ import fg4 from "fast-glob";
477
+ import { z as z3 } from "zod";
478
+
479
+ // src/parser/common.ts
480
+ import { readFileSync as readFileSync3 } from "fs";
481
+ import matter2 from "gray-matter";
482
+
483
+ // src/parser/schemas.ts
484
+ import { z as z2 } from "zod";
966
485
 
967
486
  // src/types.ts
968
- var AGENT_IDS = ["coding", "review", "merge", "planning"];
969
487
  var ENGINES = ["claude-code", "codex-cli", "opencode"];
970
488
  var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
971
489
  var CAPABILITIES_MATRIX = {
@@ -977,8 +495,122 @@ var DEGRADED_CAPABILITIES = {
977
495
  "codex-cli": ["multi-step"]
978
496
  };
979
497
 
498
+ // src/parser/schemas.ts
499
+ var IdSchema = z2.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
500
+ var SkillFrontmatterSchema = z2.object({
501
+ id: IdSchema,
502
+ description: z2.string().min(1),
503
+ engines: z2.array(z2.enum(ENGINES)).min(1).optional(),
504
+ requires: z2.array(z2.enum(CAPABILITIES)).optional(),
505
+ tags: z2.array(z2.string()).optional()
506
+ }).strict();
507
+ var CmdArgEnumSchema = z2.object({
508
+ name: z2.string().min(1),
509
+ type: z2.literal("enum"),
510
+ values: z2.array(z2.string()).min(1),
511
+ default: z2.string().optional()
512
+ }).strict();
513
+ var CmdArgStringSchema = z2.object({
514
+ name: z2.string().min(1),
515
+ type: z2.literal("string"),
516
+ default: z2.string().optional()
517
+ }).strict();
518
+ var CmdArgSchema = z2.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
519
+ var CmdFrontmatterSchema = z2.object({
520
+ id: IdSchema,
521
+ trigger: z2.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
522
+ invokes_skill: IdSchema,
523
+ args: z2.array(CmdArgSchema).optional(),
524
+ description: z2.string().min(1)
525
+ }).strict();
526
+ var Schemas = {
527
+ Skill: SkillFrontmatterSchema,
528
+ Cmd: CmdFrontmatterSchema
529
+ };
530
+ var ParseError = class extends Error {
531
+ constructor(file, issues) {
532
+ const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
533
+ super(`Frontmatter validation failed for ${file}:
534
+ ${messages}`);
535
+ this.file = file;
536
+ this.issues = issues;
537
+ this.name = "ParseError";
538
+ }
539
+ file;
540
+ issues;
541
+ };
542
+
543
+ // src/parser/common.ts
544
+ function parseWithSchema(filePath, source, schema) {
545
+ const parsed = matter2(source);
546
+ const result = schema.safeParse(parsed.data);
547
+ if (!result.success) {
548
+ throw new ParseError(filePath, result.error.issues);
549
+ }
550
+ return {
551
+ meta: result.data,
552
+ body: parsed.content.trim(),
553
+ sourcePath: filePath
554
+ };
555
+ }
556
+
557
+ // src/parser/cmd.ts
558
+ function parseCmd(filePath, source) {
559
+ return parseWithSchema(filePath, source, Schemas.Cmd);
560
+ }
561
+
562
+ // src/parser/skill.ts
563
+ function parseSkill(filePath, source) {
564
+ return parseWithSchema(filePath, source, Schemas.Skill);
565
+ }
566
+
567
+ // src/util/yaml.ts
568
+ import { parse as yamlParse } from "yaml";
569
+ function parseYAML(source) {
570
+ return yamlParse(source);
571
+ }
572
+
573
+ // src/loader.ts
574
+ var DisableYamlSchema = z3.object({ disable: z3.array(z3.string()).optional() }).passthrough();
575
+ function loadHarness(packageDir, opts = {}) {
576
+ const skillsDir = opts.skillsDir ?? join6(packageDir, "skills");
577
+ const commandsDir = opts.commandsDir ?? join6(packageDir, "commands");
578
+ const skillFiles = fg4.sync("*.skill.md", { cwd: skillsDir, absolute: true });
579
+ const cmdFiles = fg4.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
580
+ return {
581
+ skills: skillFiles.map((f) => parseSkill(f, readFileSync4(f, "utf8"))),
582
+ cmds: cmdFiles.map((f) => parseCmd(f, readFileSync4(f, "utf8")))
583
+ };
584
+ }
585
+ function loadProjectSkills(targetDir) {
586
+ const skillsDir = join6(targetDir, "docs", "skills");
587
+ if (!existsSync5(skillsDir)) return [];
588
+ const skillFiles = fg4.sync("*.skill.md", { cwd: skillsDir, absolute: true });
589
+ return skillFiles.map((f) => parseSkill(f, readFileSync4(f, "utf8")));
590
+ }
591
+ function loadOverrides(worktreeDir) {
592
+ const overridesDir = join6(worktreeDir, ".harness-overrides");
593
+ if (!existsSync5(overridesDir)) return void 0;
594
+ const added = loadHarness(overridesDir, {
595
+ skillsDir: join6(overridesDir, "skills"),
596
+ commandsDir: join6(overridesDir, "commands")
597
+ });
598
+ const disablePath = join6(overridesDir, "disable.yaml");
599
+ let disable = [];
600
+ if (existsSync5(disablePath)) {
601
+ try {
602
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync4(disablePath, "utf8")));
603
+ if (parsed.success && parsed.data.disable) {
604
+ disable = parsed.data.disable;
605
+ }
606
+ } catch {
607
+ }
608
+ }
609
+ return { add: added, disable };
610
+ }
611
+
980
612
  // src/renderers/common.ts
981
- var STOP_HOOK_PACKAGE = "@vaubaan/harness";
613
+ import { stringify as yamlStringify } from "yaml";
982
614
  function checkSkillCapabilities(skill, engine) {
983
615
  const blockingWarnings = [];
984
616
  const degradedWarnings = [];
@@ -1009,39 +641,6 @@ ${rendered}
1009
641
  ---
1010
642
  `;
1011
643
  }
1012
- var SCALAR_NEEDS_QUOTE = /[^a-zA-Z0-9_./-]/;
1013
- function tomlEscapeString(s) {
1014
- return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
1015
- }
1016
- function tomlValue(v) {
1017
- if (Array.isArray(v)) {
1018
- return `[${v.map((x) => tomlValue(x)).join(", ")}]`;
1019
- }
1020
- if (typeof v === "string") {
1021
- if (v.includes("\n")) return tomlEscapeString(v);
1022
- return SCALAR_NEEDS_QUOTE.test(v) ? tomlEscapeString(v) : `"${v}"`;
1023
- }
1024
- if (typeof v === "boolean" || typeof v === "number") {
1025
- return String(v);
1026
- }
1027
- return tomlEscapeString(String(v));
1028
- }
1029
- function tomlMultilineString(s) {
1030
- const escaped = s.replace(/\\/g, "\\\\").replace(/"""/g, '""\\"');
1031
- return `"""
1032
- ${escaped}
1033
- """`;
1034
- }
1035
- function tomlQuoteString(s) {
1036
- return tomlValue(s);
1037
- }
1038
- function tomlInlineArray(items) {
1039
- return tomlValue([...items]);
1040
- }
1041
- function tomlInlineTable(table) {
1042
- const entries = Object.entries(table).map(([k, v]) => `${k} = ${tomlValue(v)}`);
1043
- return `{ ${entries.join(", ")} }`;
1044
- }
1045
644
  function frontmatterDataForSkill(skill) {
1046
645
  const data = {
1047
646
  name: skill.meta.id,
@@ -1066,11 +665,7 @@ function frontmatterDataForCmd(cmd) {
1066
665
  }
1067
666
  return data;
1068
667
  }
1069
- function buildAgentBody(agent) {
1070
- return `${agent.body.trim()}
1071
- `;
1072
- }
1073
- function buildUmbrellaBody(_agents, extras) {
668
+ function buildUmbrellaBody(extras) {
1074
669
  const triggerBySkill = new Map(
1075
670
  extras.availableCommands.map((c) => [c.meta.invokes_skill, c.meta.trigger])
1076
671
  );
@@ -1088,10 +683,10 @@ function buildUmbrellaBody(_agents, extras) {
1088
683
  "",
1089
684
  "- `README.md` \u2014 pitch, quick start, scripts. Entry point.",
1090
685
  "- `docs/spec/<subsystem>.md` \u2014 *what* and *why* (tech-agnostic).",
1091
- "- `docs/handbook/<feature>.md` \u2014 *how it actually works* today.",
686
+ "- `docs/handbook/<feature>.md` \u2014 what the code does not say: entry points, traps, settings outside the repo, manual procedures.",
1092
687
  "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives.",
1093
- "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 core scenarios.",
1094
- "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release.",
688
+ "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 test scope, stack, conventions, known gaps.",
689
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release. How this team works: follow it.",
1095
690
  ...extras.hasProjectSkills ? ["- `docs/skills/*.skill.md` \u2014 the project's domain skills."] : [],
1096
691
  ...extras.hasQualityDoc ? [
1097
692
  "- `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."
@@ -1104,7 +699,13 @@ function buildUmbrellaBody(_agents, extras) {
1104
699
  "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
1105
700
  "- Implicit structural decision in your changes \u2192 an ADR (`/decision`).",
1106
701
  "- Changed feature behavior \u2192 update the matching handbook (`/handbook`).",
1107
- "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on."
702
+ "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on.",
703
+ "",
704
+ "## Checks",
705
+ "",
706
+ "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.",
707
+ "",
708
+ "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."
1108
709
  ];
1109
710
  if (skillLines.length > 0) {
1110
711
  sections.push("", "## Doc-skills", "", skillLines.join("\n"));
@@ -1145,60 +746,11 @@ ${cmd.body}
1145
746
  files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
1146
747
  warnings: []
1147
748
  };
1148
- },
1149
- renderAgents(agents) {
1150
- const files = [];
1151
- for (const agent of agents) {
1152
- const subagentFrontmatter = yamlFrontmatter({
1153
- name: agent.meta.id,
1154
- description: agent.meta.description
1155
- });
1156
- const body = buildAgentBody(agent);
1157
- const content = `${subagentFrontmatter}
1158
- ${body}`;
1159
- files.push({ path: `${BASE}/agents/${agent.meta.id}.md`, content });
1160
- }
1161
- return { files, warnings: [] };
1162
- },
1163
- renderMcp(servers) {
1164
- if (servers.length === 0) return { files: [], warnings: [] };
1165
- const mcpServers = {};
1166
- for (const s of servers) {
1167
- const entry = { command: s.command, args: [...s.args] };
1168
- if (s.env) entry.env = s.env;
1169
- mcpServers[s.id] = entry;
1170
- }
1171
- const content = `${JSON.stringify({ mcpServers }, null, 2)}
1172
- `;
1173
- return { files: [{ path: ".mcp.json", content }], warnings: [] };
1174
- },
1175
- renderStopHook() {
1176
- const settings = {
1177
- hooks: {
1178
- Stop: [
1179
- {
1180
- matcher: "",
1181
- hooks: [
1182
- {
1183
- type: "command",
1184
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine claude`
1185
- }
1186
- ]
1187
- }
1188
- ]
1189
- }
1190
- };
1191
- return {
1192
- files: [{ path: `${BASE}/settings.json`, content: `${JSON.stringify(settings, null, 2)}
1193
- ` }],
1194
- warnings: []
1195
- };
1196
749
  }
1197
750
  };
1198
751
 
1199
752
  // src/renderers/codex-cli.ts
1200
753
  var ENGINE2 = "codex-cli";
1201
- var BASE2 = ".codex";
1202
754
  var SKILLS_BASE = ".agents/skills";
1203
755
  var codexCliRenderer = {
1204
756
  engine: ENGINE2,
@@ -1224,62 +776,12 @@ ${skill.body}
1224
776
  // Codex custom prompts are deprecated in favour of skills: nothing to render.
1225
777
  renderCmd(_cmd) {
1226
778
  return { files: [], warnings: [] };
1227
- },
1228
- renderAgents(agents) {
1229
- const files = [];
1230
- for (const agent of agents) {
1231
- const content = [
1232
- `name = ${tomlQuoteString(agent.meta.id)}`,
1233
- `description = ${tomlQuoteString(agent.meta.description)}`,
1234
- `developer_instructions = ${tomlMultilineString(buildAgentBody(agent).trimEnd())}`,
1235
- ""
1236
- ].join("\n");
1237
- files.push({ path: `${BASE2}/agents/${agent.meta.id}.toml`, content });
1238
- }
1239
- return { files, warnings: [] };
1240
- },
1241
- renderMcp(servers) {
1242
- if (servers.length === 0) return { files: [], warnings: [] };
1243
- const blocks = [];
1244
- for (const s of servers) {
1245
- const lines = [
1246
- `[mcp_servers.${s.id}]`,
1247
- `command = ${tomlQuoteString(s.command)}`,
1248
- `args = ${tomlInlineArray([...s.args])}`
1249
- ];
1250
- if (s.env) lines.push(`env = ${tomlInlineTable(s.env)}`);
1251
- blocks.push(lines.join("\n"));
1252
- }
1253
- const content = `${blocks.join("\n\n")}
1254
- `;
1255
- return { files: [{ path: `${BASE2}/config.toml`, content }], warnings: [] };
1256
- },
1257
- renderStopHook() {
1258
- const hooks = {
1259
- hooks: {
1260
- Stop: [
1261
- {
1262
- hooks: [
1263
- {
1264
- type: "command",
1265
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine codex`
1266
- }
1267
- ]
1268
- }
1269
- ]
1270
- }
1271
- };
1272
- return {
1273
- files: [{ path: `${BASE2}/hooks.json`, content: `${JSON.stringify(hooks, null, 2)}
1274
- ` }],
1275
- warnings: []
1276
- };
1277
779
  }
1278
780
  };
1279
781
 
1280
782
  // src/renderers/opencode.ts
1281
783
  var ENGINE3 = "opencode";
1282
- var BASE3 = ".opencode";
784
+ var BASE2 = ".opencode";
1283
785
  var opencodeRenderer = {
1284
786
  engine: ENGINE3,
1285
787
  renderSkill(skill) {
@@ -1297,7 +799,7 @@ var opencodeRenderer = {
1297
799
  ${skill.body}
1298
800
  `;
1299
801
  return {
1300
- files: [{ path: `${BASE3}/skills/${skill.meta.id}/SKILL.md`, content }],
802
+ files: [{ path: `${BASE2}/skills/${skill.meta.id}/SKILL.md`, content }],
1301
803
  warnings: check.degradedWarnings
1302
804
  };
1303
805
  },
@@ -1306,106 +808,7 @@ ${skill.body}
1306
808
  ${cmd.body}
1307
809
  `;
1308
810
  return {
1309
- files: [{ path: `${BASE3}/commands/${cmd.meta.id}.md`, content }],
1310
- warnings: []
1311
- };
1312
- },
1313
- renderAgents(agents) {
1314
- const files = [];
1315
- for (const agent of agents) {
1316
- const fm = yamlFrontmatter({
1317
- description: agent.meta.description,
1318
- mode: "all"
1319
- });
1320
- const body = buildAgentBody(agent);
1321
- files.push({ path: `${BASE3}/agents/${agent.meta.id}.md`, content: `${fm}
1322
- ${body}` });
1323
- }
1324
- return { files, warnings: [] };
1325
- },
1326
- renderMcp(servers) {
1327
- if (servers.length === 0) return { files: [], warnings: [] };
1328
- const mcp = {};
1329
- for (const s of servers) {
1330
- const entry = {
1331
- type: "local",
1332
- command: [s.command, ...s.args],
1333
- enabled: true
1334
- };
1335
- if (s.env) entry.environment = s.env;
1336
- mcp[s.id] = entry;
1337
- }
1338
- const config = { $schema: "https://opencode.ai/config.json", mcp };
1339
- const content = `${JSON.stringify(config, null, 2)}
1340
- `;
1341
- return { files: [{ path: `${BASE3}/opencode.json`, content }], warnings: [] };
1342
- },
1343
- renderStopHook() {
1344
- const content = `import { spawnSync } from "node:child_process";
1345
-
1346
- // Runs the harness lint and returns the report to inject, or "" when the
1347
- // turn may end.
1348
- const lintReport = (directory, sessionID) => {
1349
- const r = spawnSync(
1350
- "npx",
1351
- ["-y", "${STOP_HOOK_PACKAGE}", "stop-hook", "--engine", "opencode", "--cwd", directory],
1352
- { input: JSON.stringify({ sessionID }), encoding: "utf-8" },
1353
- );
1354
- const report = (r.stderr ?? "").trim();
1355
- return r.status === 2 ? report : "";
1356
- };
1357
-
1358
- // OpenCode 1.x entry point, exposed as server() below.
1359
- const HarnessStopHook = async ({ client, directory }) => ({
1360
- event: async ({ event }) => {
1361
- if (event.type !== "session.idle") return;
1362
- const sessionID = event.properties?.sessionID;
1363
- if (!sessionID) return;
1364
- const report = lintReport(directory, sessionID);
1365
- if (report === "") return;
1366
- // OpenCode defaults to its build agent when a prompt omits agent.
1367
- // Preserve the last conversation persona, excluding compaction summaries.
1368
- const history = await client.session.messages({ path: { id: sessionID } }).catch(() => undefined);
1369
- if (history?.error || !Array.isArray(history?.data)) return;
1370
- const current = history.data.findLast(({ info }) =>
1371
- (info.role === "user" || (info.role === "assistant" && !info.summary)) &&
1372
- typeof info.agent === "string" && info.agent.trim() !== "",
1373
- );
1374
- if (!current) return;
1375
- await client.session.prompt({
1376
- path: { id: sessionID },
1377
- body: { agent: current.info.agent, parts: [{ type: "text", text: report }] },
1378
- });
1379
- },
1380
- });
1381
-
1382
- // One default export for both majors: OpenCode 1.x calls server(),
1383
- // OpenCode 2.x calls setup(). A V2 session keeps its agent, so the report
1384
- // is sent without naming the persona.
1385
- export default {
1386
- id: "vaubaan-harness-stop-hook",
1387
- server: HarnessStopHook,
1388
- setup(context) {
1389
- const directory = context.location.directory;
1390
- const controller = new AbortController();
1391
- const listen = async () => {
1392
- for await (const event of context.event.subscribe({ signal: controller.signal })) {
1393
- if (event.type !== "session.idle") continue;
1394
- if (event.location?.directory && event.location.directory !== directory) continue;
1395
- const sessionID = event.data?.sessionID;
1396
- if (!sessionID) continue;
1397
- const report = lintReport(directory, sessionID);
1398
- if (report === "") continue;
1399
- await context.session.prompt({ sessionID, text: report }).catch(() => undefined);
1400
- }
1401
- };
1402
- listen().catch(() => undefined);
1403
- return () => controller.abort();
1404
- },
1405
- };
1406
- `;
1407
- return {
1408
- files: [{ path: `${BASE3}/plugins/harness-stop-hook.ts`, content }],
811
+ files: [{ path: `${BASE2}/commands/${cmd.meta.id}.md`, content }],
1409
812
  warnings: []
1410
813
  };
1411
814
  }
@@ -1420,602 +823,617 @@ var RENDERERS = {
1420
823
  function getRenderer(engine) {
1421
824
  return RENDERERS[engine];
1422
825
  }
1423
-
1424
- // src/cli/update-config.ts
1425
- var LEGACY_OPENCODE_CONFIG = ".opencode/mcp.json";
1426
- var SHARED_CONFIG_PATHS = [
1427
- ".mcp.json",
1428
- ".codex/config.toml",
1429
- OPENCODE_CONFIG_PATH,
1430
- LEGACY_OPENCODE_CONFIG,
1431
- ".claude/settings.json",
1432
- ".codex/hooks.json"
1433
- ];
1434
- var ObjectSchema2 = z2.record(z2.unknown());
1435
- var HookEntrySchema = z2.object({ group: ObjectSchema2, hook: ObjectSchema2 });
1436
- var HookConfigOwnershipSchema = z2.object({
1437
- createdFile: z2.boolean(),
1438
- addedHooks: z2.boolean(),
1439
- addedStop: z2.boolean(),
1440
- entries: z2.array(HookEntrySchema)
1441
- });
1442
- var HookConfigsOwnershipSchema = z2.object({
1443
- ".claude/settings.json": HookConfigOwnershipSchema.optional(),
1444
- ".codex/hooks.json": HookConfigOwnershipSchema.optional()
1445
- }).strict();
1446
- var HOOK_ENGINES = {
1447
- ".claude/settings.json": "claude-code",
1448
- ".codex/hooks.json": "codex-cli"
1449
- };
1450
- function parseObject(content, path) {
1451
- try {
1452
- return ObjectSchema2.parse(JSON.parse(content));
1453
- } catch {
1454
- throw new Error(`invalid shared configuration ${path}: expected a JSON object`);
1455
- }
1456
- }
1457
- function asObject(value) {
1458
- const parsed = ObjectSchema2.safeParse(value);
1459
- return parsed.success ? parsed.data : void 0;
1460
- }
1461
- function stopHooks(config, path) {
1462
- if (!Object.hasOwn(config, "hooks")) return [];
1463
- const hooks = asObject(config.hooks);
1464
- if (!hooks || Object.hasOwn(hooks, "Stop") && !Array.isArray(hooks.Stop)) {
1465
- throw new Error(`invalid shared configuration ${path}: expected hooks.Stop to be an array`);
1466
- }
1467
- return Array.isArray(hooks.Stop) ? hooks.Stop : [];
1468
- }
1469
- function groupMetadata(group) {
1470
- return Object.fromEntries(Object.entries(group).filter(([key]) => key !== "hooks"));
1471
- }
1472
- function sameEntry(left, right) {
1473
- return isDeepStrictEqual2(left.group, right.group) && isDeepStrictEqual2(left.hook, right.hook);
1474
- }
1475
- function appendEntry(entries, entry) {
1476
- if (!entries.some((existing) => sameEntry(existing, entry))) entries.push(entry);
1477
- }
1478
- function defaultStopGroup(engine) {
1479
- const file = getRenderer(engine).renderStopHook().files[0];
1480
- if (!file) throw new Error(`missing Stop hook renderer for ${engine}`);
1481
- const group = asObject(stopHooks(parseObject(file.content, file.path), file.path)[0]);
1482
- if (!group || !Array.isArray(group.hooks) || !asObject(group.hooks[0])) {
1483
- throw new Error(`invalid Stop hook renderer for ${engine}`);
1484
- }
1485
- return group;
1486
- }
1487
- function normalizeHarnessHooks(groups, expected, previous, claimExisting, warnings, path) {
1488
- const defaultHook = ObjectSchema2.parse(expected.hooks[0]);
1489
- const entries = [...previous?.entries ?? []];
1490
- let found = false;
1491
- const normalized = groups.map((value) => {
1492
- const group = asObject(value);
1493
- if (!group) return value;
1494
- const flat = group.type === "command" && group.command === defaultHook.command;
1495
- const hooks = flat ? [group] : Array.isArray(group.hooks) ? group.hooks : [];
1496
- const metadata = flat ? groupMetadata(expected) : groupMetadata(group);
1497
- for (const value2 of hooks) {
1498
- const hook = asObject(value2);
1499
- if (!hook || hook.type !== "command" || hook.command !== defaultHook.command) continue;
1500
- found = true;
1501
- const entry = { group: metadata, hook };
1502
- if (!claimExisting) continue;
1503
- if (previous && !previous.entries.some((old) => sameEntry(old, entry))) {
1504
- warnings.push(`preserved modified harness Stop hook: ${path}`);
1505
- } else {
1506
- appendEntry(entries, entry);
826
+
827
+ // src/render.ts
828
+ var RenderError = class extends Error {
829
+ constructor(message) {
830
+ super(message);
831
+ this.name = "RenderError";
832
+ }
833
+ };
834
+ function mergeById(stock, added) {
835
+ const result = /* @__PURE__ */ new Map();
836
+ for (const item of stock) result.set(item.meta.id, item);
837
+ if (added) {
838
+ for (const item of added) result.set(item.meta.id, item);
839
+ }
840
+ return Array.from(result.values());
841
+ }
842
+ function removeByIds(items, disabled) {
843
+ if (disabled.length === 0) return [...items];
844
+ const disabledSet = new Set(disabled);
845
+ return items.filter((item) => !disabledSet.has(item.meta.id));
846
+ }
847
+ function applyOverrides(harness, overrides) {
848
+ const disabled = overrides?.disable ?? [];
849
+ return {
850
+ skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
851
+ cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
852
+ };
853
+ }
854
+ var CLAUDE_MD_STUB = "@AGENTS.md\n";
855
+ function opencodeLast(engines) {
856
+ return [...engines].sort((a, b) => Number(a === "opencode") - Number(b === "opencode"));
857
+ }
858
+ function render(input) {
859
+ const { engines } = input;
860
+ if (engines.length === 0) {
861
+ throw new RenderError("at least one engine must be selected");
862
+ }
863
+ const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
864
+ const harness = applyOverrides(base, input.overrides);
865
+ const files = [];
866
+ const warnings = [];
867
+ const exposedSkills = /* @__PURE__ */ new Map();
868
+ const exposedCmds = /* @__PURE__ */ new Map();
869
+ for (const engine of opencodeLast(engines)) {
870
+ const renderer = getRenderer(engine);
871
+ const renderedSkillIds = /* @__PURE__ */ new Set();
872
+ for (const skill of harness.skills) {
873
+ const result = renderer.renderSkill(skill);
874
+ warnings.push(...result.warnings);
875
+ if (result.files.length > 0) {
876
+ const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
877
+ if (!alreadyVisible) files.push(...result.files);
878
+ renderedSkillIds.add(skill.meta.id);
879
+ exposedSkills.set(skill.meta.id, skill);
1507
880
  }
1508
881
  }
1509
- return flat && claimExisting ? { ...metadata, hooks: [group] } : value;
1510
- });
1511
- if (!found && !previous?.entries.length) {
1512
- normalized.push(expected);
1513
- appendEntry(entries, { group: groupMetadata(expected), hook: defaultHook });
1514
- } else if (!found) {
1515
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
1516
- }
1517
- return { groups: normalized, entries };
1518
- }
1519
- function removeOwnedHooks(config, ownership, path, warnings) {
1520
- const groups = stopHooks(config, path);
1521
- const remaining = [];
1522
- const matched = /* @__PURE__ */ new Set();
1523
- for (const value of groups) {
1524
- const group = asObject(value);
1525
- if (!group || !Array.isArray(group.hooks)) {
1526
- remaining.push(value);
1527
- continue;
1528
- }
1529
- const metadata = groupMetadata(group);
1530
- const hooks2 = group.hooks.filter((value2) => {
1531
- const hook = asObject(value2);
1532
- const entry = hook && ownership.entries.find((old) => sameEntry(old, { group: metadata, hook }));
1533
- if (entry) matched.add(entry);
1534
- return !entry;
1535
- });
1536
- if (hooks2.length > 0 || hooks2.length === group.hooks.length) {
1537
- remaining.push({ ...group, hooks: hooks2 });
882
+ for (const cmd of harness.cmds) {
883
+ if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
884
+ const result = renderer.renderCmd(cmd);
885
+ warnings.push(...result.warnings);
886
+ if (result.files.length > 0) {
887
+ files.push(...result.files);
888
+ exposedCmds.set(cmd.meta.id, cmd);
889
+ }
1538
890
  }
1539
891
  }
1540
- if (matched.size < ownership.entries.length) {
1541
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
1542
- }
1543
- const hooks = asObject(config.hooks);
1544
- if (!hooks) return;
1545
- if (ownership.addedStop && remaining.length === 0) Reflect.deleteProperty(hooks, "Stop");
1546
- else if (Object.hasOwn(hooks, "Stop")) hooks.Stop = remaining;
1547
- if (ownership.addedHooks && Object.keys(hooks).length === 0)
1548
- Reflect.deleteProperty(config, "hooks");
1549
- else config.hooks = hooks;
1550
- }
1551
- function recordMutation(plan, path, before, after, createdFile) {
1552
- if (createdFile && Object.keys(after).length === 0) {
1553
- if (before) plan.removals.push(path);
1554
- } else if (!isDeepStrictEqual2(before, after)) {
1555
- plan.writes.push({ path, content: `${JSON.stringify(after, null, 2)}
1556
- ` });
892
+ const umbrellaContent = buildUmbrellaBody({
893
+ availableSkills: Array.from(exposedSkills.values()),
894
+ availableCommands: Array.from(exposedCmds.values()),
895
+ hasProjectSkills: (input.projectSkills?.length ?? 0) > 0,
896
+ hasQualityDoc: input.hasQualityDoc === true
897
+ });
898
+ files.push({ path: "AGENTS.md", content: umbrellaContent });
899
+ if (engines.includes("claude-code")) {
900
+ files.push({ path: "CLAUDE.md", content: CLAUDE_MD_STUB });
1557
901
  }
902
+ return { files, warnings };
1558
903
  }
1559
- function planHookConfigCleanup(root, ownership) {
1560
- const plan = { writes: [], removals: [], warnings: [] };
1561
- if (!ownership) return plan;
1562
- const validated = HookConfigsOwnershipSchema.parse(ownership);
1563
- assertManagedPaths(root, Object.keys(validated));
1564
- for (const path of Object.keys(HOOK_ENGINES)) {
1565
- const owned = validated[path];
1566
- if (!owned || !existsSync6(join7(root, path))) continue;
1567
- const before = parseObject(readFileSync4(join7(root, path), "utf8"), path);
1568
- const config = structuredClone(before);
1569
- removeOwnedHooks(config, owned, path, plan.warnings);
1570
- recordMutation(plan, path, before, config, owned.createdFile);
1571
- }
1572
- return plan;
1573
- }
1574
- function planActiveHook(root, path, previous, claimExisting, plan) {
1575
- assertManagedPaths(root, [path]);
1576
- const existed = existsSync6(join7(root, path));
1577
- if (!existed && previous?.entries.length) {
1578
- plan.warnings.push(`preserved removed harness Stop hook configuration: ${path}`);
1579
- return previous;
1580
- }
1581
- const before = existed ? parseObject(readFileSync4(join7(root, path), "utf8"), path) : void 0;
1582
- const config = structuredClone(before ?? {});
1583
- const groups = stopHooks(config, path);
1584
- const hooks = asObject(config.hooks) ?? {};
1585
- const normalized = normalizeHarnessHooks(
1586
- groups,
1587
- defaultStopGroup(HOOK_ENGINES[path]),
1588
- previous,
1589
- claimExisting,
1590
- plan.warnings,
1591
- path
1592
- );
1593
- const legacyWholeFile = !previous && claimExisting && existed;
1594
- const ownership = {
1595
- createdFile: !existed || previous?.createdFile === true || legacyWholeFile,
1596
- addedHooks: previous?.addedHooks ?? (legacyWholeFile || !Object.hasOwn(config, "hooks")),
1597
- addedStop: previous?.addedStop ?? (legacyWholeFile || !Object.hasOwn(hooks, "Stop")),
1598
- entries: normalized.entries
1599
- };
1600
- if (!isDeepStrictEqual2(groups, normalized.groups)) {
1601
- config.hooks = { ...hooks, Stop: normalized.groups };
1602
- }
1603
- recordMutation(plan, path, before, config, ownership.createdFile);
1604
- return ownership.entries.length > 0 ? ownership : void 0;
1605
- }
1606
- function planLegacyOpenCode(root, previous, plan) {
1607
- if (!previous.files.includes(LEGACY_OPENCODE_CONFIG)) return;
1608
- const legacyPath = join7(root, LEGACY_OPENCODE_CONFIG);
1609
- if (!existsSync6(legacyPath)) return;
1610
- assertManagedPaths(root, [LEGACY_OPENCODE_CONFIG, OPENCODE_CONFIG_PATH]);
1611
- const legacy = parseObject(readFileSync4(legacyPath, "utf8"), LEGACY_OPENCODE_CONFIG);
1612
- if (!asObject(legacy.mcp)) {
904
+
905
+ // src/cli/plan-render.ts
906
+ var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
907
+ function resolveEngineList(requested) {
908
+ if (!requested || requested.length === 0) {
1613
909
  throw new Error(
1614
- `invalid shared configuration ${LEGACY_OPENCODE_CONFIG}: expected an MCP object`
910
+ `no engine selected: pass --engines=<list> with one or more of ${ENGINES.join(", ")}`
1615
911
  );
1616
912
  }
1617
- const merged = planOpenCodeConfig(
1618
- root,
1619
- { path: OPENCODE_CONFIG_PATH, content: JSON.stringify(legacy) },
1620
- void 0
1621
- );
1622
- if (merged.write) plan.writes.push(merged.write);
1623
- plan.warnings.push(...merged.warnings);
1624
- if (merged.ownership) {
1625
- const old = previous.opencodeConfig;
1626
- plan.opencodeConfig = {
1627
- createdFile: merged.ownership.createdFile || old?.createdFile === true,
1628
- addedMcp: merged.ownership.addedMcp || old?.addedMcp === true,
1629
- addedSchema: merged.ownership.addedSchema || old?.addedSchema === true,
1630
- entries: { ...old?.entries, ...merged.ownership.entries }
1631
- };
1632
- }
1633
- plan.removals.push(LEGACY_OPENCODE_CONFIG);
913
+ const engines = requested.map((e) => {
914
+ if (!ENGINES.includes(e)) {
915
+ throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
916
+ }
917
+ return e;
918
+ });
919
+ return [...new Set(engines)];
1634
920
  }
1635
- function planUpdateConfigs(root, previous, hookEngines) {
1636
- const plan = {
1637
- writes: [],
1638
- removals: [],
1639
- ownedFiles: [],
1640
- warnings: [],
1641
- ...previous.opencodeConfig ? { opencodeConfig: previous.opencodeConfig } : {}
1642
- };
1643
- planLegacyOpenCode(root, previous, plan);
1644
- const hookConfigs = {};
1645
- for (const path of Object.keys(HOOK_ENGINES)) {
1646
- const owned = previous.hookConfigs?.[path];
1647
- if (hookEngines.includes(HOOK_ENGINES[path])) {
1648
- hookConfigs[path] = planActiveHook(
1649
- root,
1650
- path,
1651
- owned,
1652
- previous.files.includes(path) || Boolean(owned),
1653
- plan
1654
- );
1655
- } else if (owned) {
1656
- const cleanup = planHookConfigCleanup(root, { [path]: owned });
1657
- plan.writes.push(...cleanup.writes);
1658
- plan.removals.push(...cleanup.removals);
1659
- plan.warnings.push(...cleanup.warnings);
921
+ function defaultPackageDir() {
922
+ const here = dirname3(fileURLToPath(import.meta.url));
923
+ if (existsSync6(join7(here, "skills"))) return here;
924
+ return resolve3(here, "..");
925
+ }
926
+ function planInit(args) {
927
+ const engines = resolveEngineList(args.engines);
928
+ const packageDir = args.packageDir ?? defaultPackageDir();
929
+ const harness = loadHarness(packageDir);
930
+ const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
931
+ const projectSkills = loadProjectSkills(args.targetDir);
932
+ const hasQualityDoc = existsSync6(join7(args.targetDir, QUALITY_DOC_PATH));
933
+ const output = render({ harness, engines, overrides, projectSkills, hasQualityDoc });
934
+ return { engines, output };
935
+ }
936
+
937
+ // src/linters/generated-fresh.ts
938
+ var FIX = "run `npx @vaubaan/harness update .` and commit the result";
939
+ var generatedFresh = {
940
+ id: "lint:generated-fresh",
941
+ pillars: ["repo-root"],
942
+ defaultSeverity: "error",
943
+ run(repoRoot) {
944
+ const issue = (file, message) => ({
945
+ linter: this.id,
946
+ severity: "error",
947
+ file,
948
+ message
949
+ });
950
+ let manifest;
951
+ try {
952
+ manifest = readManifest(repoRoot);
953
+ } catch (error) {
954
+ const reason = error instanceof Error ? error.message : String(error);
955
+ return [issue(".harness-manifest.json", `invalid harness manifest: ${reason}`)];
956
+ }
957
+ if (!manifest) return [];
958
+ const overridesParent = manifest.overridesDir ? resolve4(repoRoot, manifest.overridesDir) : repoRoot;
959
+ const hasOverrides = existsSync7(join8(overridesParent, ".harness-overrides"));
960
+ let rendered;
961
+ try {
962
+ rendered = planInit({
963
+ targetDir: repoRoot,
964
+ engines: manifest.engines,
965
+ overridesDir: hasOverrides ? overridesParent : void 0
966
+ });
967
+ } catch (error) {
968
+ const reason = error instanceof Error ? error.message : String(error);
969
+ return [issue(".harness-manifest.json", `cannot render the harness: ${reason}`)];
970
+ }
971
+ const preserved = new Set(manifest.preservedFiles ?? []);
972
+ const issues = [];
973
+ const renderedPaths = /* @__PURE__ */ new Set();
974
+ for (const file of rendered.output.files) {
975
+ if (preserved.has(file.path)) continue;
976
+ renderedPaths.add(file.path);
977
+ const full = join8(repoRoot, file.path);
978
+ if (!existsSync7(full)) {
979
+ issues.push(issue(file.path, `generated file is missing; ${FIX}`));
980
+ } else if (readFileSync5(full, "utf8") !== file.content) {
981
+ issues.push(
982
+ issue(
983
+ file.path,
984
+ `generated file differs from the current render; edit its source in docs/ or .harness-overrides/, then ${FIX}`
985
+ )
986
+ );
987
+ }
988
+ }
989
+ for (const path of manifest.files) {
990
+ if (renderedPaths.has(path) || preserved.has(path) || RELEASED_PATHS.includes(path)) continue;
991
+ if (existsSync7(join8(repoRoot, path))) {
992
+ issues.push(issue(path, `stale generated file, no longer rendered; ${FIX}`));
993
+ }
1660
994
  }
995
+ return issues;
1661
996
  }
1662
- if (Object.values(hookConfigs).some(Boolean)) plan.hookConfigs = hookConfigs;
1663
- if (hookEngines.includes("opencode")) {
1664
- const plugin = getRenderer("opencode").renderStopHook();
1665
- plan.writes.push(...plugin.files);
1666
- plan.ownedFiles.push(...plugin.files.map((file) => file.path));
1667
- plan.warnings.push(...plugin.warnings);
997
+ };
998
+
999
+ // src/linters/gitignore-harness.ts
1000
+ var REQUIRED_GITIGNORE_ENTRIES = [
1001
+ ".harness-overrides/",
1002
+ ".vaubaan/"
1003
+ ];
1004
+ var FORBIDDEN_GITIGNORE_ENTRIES = [
1005
+ "AGENTS.md",
1006
+ "CLAUDE.md",
1007
+ ".claude/",
1008
+ ".codex/",
1009
+ ".agents/",
1010
+ ".opencode/",
1011
+ ".harness-manifest.json"
1012
+ ];
1013
+ function gitignoreEntries(text) {
1014
+ const entries = /* @__PURE__ */ new Set();
1015
+ for (const raw of text.split("\n")) {
1016
+ const line = raw.trim();
1017
+ if (!line || line.startsWith("#")) continue;
1018
+ entries.add(line.replace(/^\//, "").replace(/\/$/, ""));
1668
1019
  }
1669
- return plan;
1020
+ return entries;
1670
1021
  }
1671
-
1672
- // src/cli/manifest.ts
1673
- var MANIFEST_FILENAME = ".harness-manifest.json";
1674
- var MANIFEST_VERSION = "6";
1675
- var ManifestSchema = z3.object({
1676
- version: z3.enum(["4", "5", MANIFEST_VERSION]),
1677
- engines: z3.array(z3.string()),
1678
- renderedAt: z3.string(),
1679
- files: z3.array(z3.string()),
1680
- stopHookInstalled: z3.boolean().optional(),
1681
- stopHookEngines: z3.array(z3.string()).optional(),
1682
- opencodeConfig: OpenCodeConfigOwnershipSchema.optional(),
1683
- /** Entries the harness added to `.mcp.json` (Claude Code). */
1684
- mcpConfig: OpenCodeConfigOwnershipSchema.optional(),
1685
- hookConfigs: HookConfigsOwnershipSchema.optional(),
1686
- harnessVersion: z3.string().optional(),
1687
- overridesDir: z3.string().optional(),
1688
- fileHashes: z3.record(z3.string().regex(/^[a-f0-9]{64}$/)).optional(),
1689
- preservedFiles: z3.array(z3.string()).optional()
1690
- });
1691
- function manifestPath(targetDir) {
1692
- return join8(targetDir, MANIFEST_FILENAME);
1022
+ function normalize(entry) {
1023
+ return entry.replace(/\/$/, "");
1693
1024
  }
1694
- function hashContent(content) {
1695
- return createHash("sha256").update(content).digest("hex");
1025
+ function missingGitignoreEntries(text) {
1026
+ const lines = gitignoreEntries(text);
1027
+ return REQUIRED_GITIGNORE_ENTRIES.filter((entry) => !lines.has(normalize(entry)));
1696
1028
  }
1697
- function readManifest(targetDir) {
1698
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
1699
- const path = manifestPath(targetDir);
1700
- if (!existsSync7(path)) return null;
1701
- const raw = JSON.parse(readFileSync5(path, "utf8"));
1702
- return ManifestSchema.parse(raw);
1029
+ function forbiddenGitignoreEntries(text) {
1030
+ const lines = gitignoreEntries(text);
1031
+ return FORBIDDEN_GITIGNORE_ENTRIES.filter((entry) => lines.has(normalize(entry)));
1703
1032
  }
1033
+ var gitignoreHarness = {
1034
+ id: "lint:gitignore-harness",
1035
+ pillars: ["repo-root"],
1036
+ defaultSeverity: "error",
1037
+ run(repoRoot) {
1038
+ if (!fileExists(repoRoot, ".gitignore")) {
1039
+ return [
1040
+ {
1041
+ linter: this.id,
1042
+ severity: "error",
1043
+ file: ".gitignore",
1044
+ message: ".gitignore is missing at repo root"
1045
+ }
1046
+ ];
1047
+ }
1048
+ const text = readText(repoRoot, ".gitignore");
1049
+ const issues = [];
1050
+ for (const entry of missingGitignoreEntries(text)) {
1051
+ issues.push({
1052
+ linter: this.id,
1053
+ severity: "error",
1054
+ file: ".gitignore",
1055
+ message: `.gitignore must contain "${entry}"`
1056
+ });
1057
+ }
1058
+ for (const entry of forbiddenGitignoreEntries(text)) {
1059
+ issues.push({
1060
+ linter: this.id,
1061
+ severity: "error",
1062
+ file: ".gitignore",
1063
+ message: `.gitignore must not contain "${entry}": files the harness generates are committed`
1064
+ });
1065
+ }
1066
+ return issues;
1067
+ }
1068
+ };
1704
1069
 
1705
- // src/cli/plan-render.ts
1706
- import { existsSync as existsSync9 } from "fs";
1707
- import { dirname as dirname3, join as join10, resolve as resolve3 } from "path";
1708
- import { fileURLToPath } from "url";
1709
-
1710
- // src/loader.ts
1711
- import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs";
1712
- import { join as join9 } from "path";
1713
- import fg6 from "fast-glob";
1714
- import { z as z5 } from "zod";
1715
-
1716
- // src/parser/common.ts
1717
- import { readFileSync as readFileSync6 } from "fs";
1718
- import matter2 from "gray-matter";
1719
-
1720
- // src/parser/schemas.ts
1721
- import { z as z4 } from "zod";
1722
- var IdSchema = z4.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
1723
- var SkillFrontmatterSchema = z4.object({
1724
- id: IdSchema,
1725
- description: z4.string().min(1),
1726
- engines: z4.array(z4.enum(ENGINES)).min(1).optional(),
1727
- requires: z4.array(z4.enum(CAPABILITIES)).optional(),
1728
- tags: z4.array(z4.string()).optional()
1729
- }).strict();
1730
- var CmdArgEnumSchema = z4.object({
1731
- name: z4.string().min(1),
1732
- type: z4.literal("enum"),
1733
- values: z4.array(z4.string()).min(1),
1734
- default: z4.string().optional()
1735
- }).strict();
1736
- var CmdArgStringSchema = z4.object({
1737
- name: z4.string().min(1),
1738
- type: z4.literal("string"),
1739
- default: z4.string().optional()
1740
- }).strict();
1741
- var CmdArgSchema = z4.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
1742
- var CmdFrontmatterSchema = z4.object({
1743
- id: IdSchema,
1744
- trigger: z4.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
1745
- invokes_skill: IdSchema,
1746
- args: z4.array(CmdArgSchema).optional(),
1747
- description: z4.string().min(1)
1748
- }).strict();
1749
- var AgentFrontmatterSchema = z4.object({
1750
- id: z4.enum(AGENT_IDS),
1751
- description: z4.string().min(1)
1752
- }).strict();
1753
- var Schemas = {
1754
- Skill: SkillFrontmatterSchema,
1755
- Cmd: CmdFrontmatterSchema,
1756
- Agent: AgentFrontmatterSchema
1070
+ // src/linters/orphan-decisions.ts
1071
+ import { basename as basename2 } from "path";
1072
+ import fg5 from "fast-glob";
1073
+ var orphanDecisions = {
1074
+ id: "lint:orphan-decisions",
1075
+ pillars: ["decisions"],
1076
+ defaultSeverity: "warning",
1077
+ suggestedSkills: ["/handbook"],
1078
+ run(repoRoot, ctx) {
1079
+ const extra = ctx?.config.ignore ?? [];
1080
+ const issues = [];
1081
+ const adrs = listMarkdown(repoRoot, "docs/decisions");
1082
+ if (adrs.length === 0) return issues;
1083
+ const otherDocs = fg5.sync("**/*.md", {
1084
+ cwd: repoRoot,
1085
+ absolute: false,
1086
+ ignore: [
1087
+ "**/node_modules/**",
1088
+ "**/dist/**",
1089
+ ".harness-overrides/**",
1090
+ "docs/decisions/**",
1091
+ "skills/**",
1092
+ "agents/**",
1093
+ "commands/**",
1094
+ "templates/**",
1095
+ ...extra
1096
+ ]
1097
+ });
1098
+ const referenceCorpus = otherDocs.map((f) => readText(repoRoot, f)).join("\n");
1099
+ for (const adr of adrs) {
1100
+ const filename = basename2(adr);
1101
+ const stem = filename.replace(/\.md$/, "");
1102
+ const referenced = referenceCorpus.includes(filename) || referenceCorpus.includes(stem);
1103
+ if (!referenced) {
1104
+ issues.push({
1105
+ linter: this.id,
1106
+ severity: "warning",
1107
+ file: adr,
1108
+ message: "ADR is not referenced by any other doc file (orphan)"
1109
+ });
1110
+ }
1111
+ }
1112
+ return issues;
1113
+ }
1757
1114
  };
1758
- var ParseError = class extends Error {
1759
- constructor(file, issues) {
1760
- const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
1761
- super(`Frontmatter validation failed for ${file}:
1762
- ${messages}`);
1763
- this.file = file;
1764
- this.issues = issues;
1765
- this.name = "ParseError";
1115
+
1116
+ // src/linters/quality-schema.ts
1117
+ var QUALITY_DIR = "docs/quality";
1118
+ var CARDINAL_FILE = `${QUALITY_DIR}/code-quality.md`;
1119
+ var REQUIRED_SECTIONS2 = [
1120
+ {
1121
+ label: "Mechanical checks",
1122
+ pattern: /^##\s+(Mechanical\s+checks|V[ée]rifications\s+m[ée]caniques)\s*$/im
1123
+ },
1124
+ { label: "Project rules", pattern: /^##\s+(Project\s+rules|R[èe]gles\s+du\s+projet)\s*$/im },
1125
+ {
1126
+ label: "Accepted deviations",
1127
+ pattern: /^##\s+(Accepted\s+deviations|[ÉE]carts\s+assum[ée]s)\s*$/im
1128
+ }
1129
+ ];
1130
+ var qualitySchema = {
1131
+ id: "lint:quality-schema",
1132
+ pillars: ["quality"],
1133
+ defaultSeverity: "error",
1134
+ run(repoRoot) {
1135
+ if (!dirExists(repoRoot, QUALITY_DIR)) return [];
1136
+ if (!fileExists(repoRoot, CARDINAL_FILE)) {
1137
+ return [
1138
+ {
1139
+ linter: this.id,
1140
+ severity: "error",
1141
+ file: CARDINAL_FILE,
1142
+ message: `missing required cardinal file: ${CARDINAL_FILE}`
1143
+ }
1144
+ ];
1145
+ }
1146
+ const text = readText(repoRoot, CARDINAL_FILE);
1147
+ return REQUIRED_SECTIONS2.filter(({ pattern }) => !pattern.test(text)).map(({ label }) => ({
1148
+ linter: this.id,
1149
+ severity: "error",
1150
+ file: CARDINAL_FILE,
1151
+ message: `missing required section: "${label}"`
1152
+ }));
1766
1153
  }
1767
- file;
1768
- issues;
1769
1154
  };
1770
1155
 
1771
- // src/parser/common.ts
1772
- function parseWithSchema(filePath, source, schema) {
1773
- const parsed = matter2(source);
1774
- const result = schema.safeParse(parsed.data);
1775
- if (!result.success) {
1776
- throw new ParseError(filePath, result.error.issues);
1156
+ // src/linters/readme-presence.ts
1157
+ var readmePresence = {
1158
+ id: "lint:readme-presence",
1159
+ pillars: ["readme"],
1160
+ defaultSeverity: "error",
1161
+ suggestedSkills: ["/readme"],
1162
+ run(repoRoot) {
1163
+ if (fileExists(repoRoot, "README.md")) return [];
1164
+ return [
1165
+ {
1166
+ linter: this.id,
1167
+ severity: "error",
1168
+ file: "README.md",
1169
+ message: "README.md is missing at repo root"
1170
+ }
1171
+ ];
1777
1172
  }
1778
- return {
1779
- meta: result.data,
1780
- body: parsed.content.trim(),
1781
- sourcePath: filePath
1782
- };
1783
- }
1784
-
1785
- // src/parser/agent.ts
1786
- function parseAgent(filePath, source) {
1787
- return parseWithSchema(filePath, source, Schemas.Agent);
1788
- }
1789
-
1790
- // src/parser/cmd.ts
1791
- function parseCmd(filePath, source) {
1792
- return parseWithSchema(filePath, source, Schemas.Cmd);
1793
- }
1173
+ };
1794
1174
 
1795
- // src/parser/skill.ts
1796
- function parseSkill(filePath, source) {
1797
- return parseWithSchema(filePath, source, Schemas.Skill);
1798
- }
1175
+ // src/linters/readme-sections.ts
1176
+ var REQUIRED_SECTIONS3 = [
1177
+ /^#\s+\S/m,
1178
+ /^##?\s+(What is this|Quick start)/im,
1179
+ /^##?\s+(Quick start|Install|Getting started)/im
1180
+ ];
1181
+ var REQUIRED_LABELS = ["title (# H1)", "What is this / intro", "Quick start / Install"];
1182
+ var readmeSections = {
1183
+ id: "lint:readme-sections",
1184
+ pillars: ["readme"],
1185
+ defaultSeverity: "error",
1186
+ suggestedSkills: ["/readme"],
1187
+ run(repoRoot) {
1188
+ if (!fileExists(repoRoot, "README.md")) return [];
1189
+ const text = readText(repoRoot, "README.md");
1190
+ const issues = [];
1191
+ for (let i = 0; i < REQUIRED_SECTIONS3.length; i++) {
1192
+ const pattern = REQUIRED_SECTIONS3[i];
1193
+ const label = REQUIRED_LABELS[i];
1194
+ if (pattern && !pattern.test(text)) {
1195
+ issues.push({
1196
+ linter: this.id,
1197
+ severity: "error",
1198
+ file: "README.md",
1199
+ message: `missing required section: ${label}`
1200
+ });
1201
+ }
1202
+ }
1203
+ return issues;
1204
+ }
1205
+ };
1799
1206
 
1800
- // src/util/yaml.ts
1801
- import { parse as yamlParse } from "yaml";
1802
- function parseYAML(source) {
1803
- return yamlParse(source);
1804
- }
1207
+ // src/linters/spec-has-content.ts
1208
+ var specHasContent = {
1209
+ id: "lint:spec-has-content",
1210
+ pillars: ["spec"],
1211
+ defaultSeverity: "warning",
1212
+ suggestedSkills: ["/spec"],
1213
+ run(repoRoot) {
1214
+ if (!dirExists(repoRoot, "docs/spec")) return [];
1215
+ const files = listMarkdown(repoRoot, "docs/spec");
1216
+ if (files.length > 0) return [];
1217
+ return [
1218
+ {
1219
+ linter: this.id,
1220
+ severity: "warning",
1221
+ file: "docs/spec",
1222
+ message: "docs/spec/ has no markdown files \u2014 write at least one spec document"
1223
+ }
1224
+ ];
1225
+ }
1226
+ };
1805
1227
 
1806
- // src/loader.ts
1807
- var DisableYamlSchema = z5.object({ disable: z5.array(z5.string()).optional() }).passthrough();
1808
- function loadHarness(packageDir, opts = {}) {
1809
- const agentsDir = opts.agentsDir ?? join9(packageDir, "agents");
1810
- const skillsDir = opts.skillsDir ?? join9(packageDir, "skills");
1811
- const commandsDir = opts.commandsDir ?? join9(packageDir, "commands");
1812
- const agentFiles = fg6.sync("*.agent.md", { cwd: agentsDir, absolute: true });
1813
- const skillFiles = fg6.sync("*.skill.md", { cwd: skillsDir, absolute: true });
1814
- const cmdFiles = fg6.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
1815
- return {
1816
- agents: agentFiles.map((f) => parseAgent(f, readFileSync7(f, "utf8"))),
1817
- skills: skillFiles.map((f) => parseSkill(f, readFileSync7(f, "utf8"))),
1818
- cmds: cmdFiles.map((f) => parseCmd(f, readFileSync7(f, "utf8")))
1819
- };
1820
- }
1821
- function loadProjectSkills(targetDir) {
1822
- const skillsDir = join9(targetDir, "docs", "skills");
1823
- if (!existsSync8(skillsDir)) return [];
1824
- const skillFiles = fg6.sync("*.skill.md", { cwd: skillsDir, absolute: true });
1825
- return skillFiles.map((f) => parseSkill(f, readFileSync7(f, "utf8")));
1228
+ // src/linters/spec-tech-agnostic.ts
1229
+ function maskFencedBlocks(text) {
1230
+ return text.replace(/```[\s\S]*?```/g, (m) => m.replace(/[^\n]/g, " "));
1826
1231
  }
1827
- function loadOverrides(worktreeDir) {
1828
- const overridesDir = join9(worktreeDir, ".harness-overrides");
1829
- if (!existsSync8(overridesDir)) return void 0;
1830
- const added = loadHarness(overridesDir, {
1831
- agentsDir: join9(overridesDir, "agents"),
1832
- skillsDir: join9(overridesDir, "skills"),
1833
- commandsDir: join9(overridesDir, "commands")
1834
- });
1835
- const disablePath = join9(overridesDir, "disable.yaml");
1836
- let disable = [];
1837
- if (existsSync8(disablePath)) {
1838
- try {
1839
- const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync7(disablePath, "utf8")));
1840
- if (parsed.success && parsed.data.disable) {
1841
- disable = parsed.data.disable;
1232
+ var TECH_BLOCKLIST = [
1233
+ { pattern: /\bNext\.?js\b/i, keyword: "Next.js" },
1234
+ { pattern: /\bSupabase\b/i, keyword: "Supabase" },
1235
+ { pattern: /\bVercel\b/i, keyword: "Vercel" },
1236
+ { pattern: /\bReact\b/, keyword: "React" },
1237
+ { pattern: /\bTypeScript\b/, keyword: "TypeScript" },
1238
+ { pattern: /\bDocker\b/, keyword: "Docker" },
1239
+ { pattern: /\bKubernetes\b/i, keyword: "Kubernetes" },
1240
+ { pattern: /\bPostgres(QL)?\b/i, keyword: "Postgres" },
1241
+ { pattern: /\bMySQL\b/i, keyword: "MySQL" },
1242
+ { pattern: /\bRedis\b/i, keyword: "Redis" },
1243
+ { pattern: /\bnpm\b/, keyword: "npm" },
1244
+ { pattern: /\bpnpm\b/, keyword: "pnpm" },
1245
+ { pattern: /\byarn\b/, keyword: "yarn" }
1246
+ ];
1247
+ var specTechAgnostic = {
1248
+ id: "lint:spec-tech-agnostic",
1249
+ pillars: ["spec"],
1250
+ defaultSeverity: "error",
1251
+ suggestedSkills: ["/spec"],
1252
+ run(repoRoot) {
1253
+ const issues = [];
1254
+ const files = listMarkdown(repoRoot, "docs/spec");
1255
+ for (const f of files) {
1256
+ const text = maskFencedBlocks(readText(repoRoot, f));
1257
+ for (const { pattern, keyword } of TECH_BLOCKLIST) {
1258
+ if (pattern.test(text)) {
1259
+ const issue = {
1260
+ linter: this.id,
1261
+ severity: "error",
1262
+ file: f,
1263
+ message: `forbidden tech keyword "${keyword}" \u2014 should be in handbook/ or decisions/`
1264
+ };
1265
+ const line = findLineNumber(text, pattern);
1266
+ if (line !== void 0) issue.line = line;
1267
+ issues.push(issue);
1268
+ }
1842
1269
  }
1843
- } catch {
1844
1270
  }
1271
+ return issues;
1845
1272
  }
1846
- return { add: added, disable };
1847
- }
1273
+ };
1848
1274
 
1849
- // src/mcp.ts
1850
- var MCP_SERVER_IDS = ["context7"];
1851
- var MCP_SERVERS = {
1852
- context7: {
1853
- id: "context7",
1854
- description: "Upstash Context7 \u2014 fetches up-to-date library docs via resolve-library-id + get-library-docs.",
1855
- command: "npx",
1856
- args: ["-y", "@upstash/context7-mcp"]
1275
+ // src/linters/tracks-drift.ts
1276
+ import fg6 from "fast-glob";
1277
+ var TRACKED_DIRS2 = ["docs/handbook", "docs/tests", "docs/workflow"];
1278
+ var DEFAULT_DRIFT_THRESHOLD = 10;
1279
+ function expandGlob(repoRoot, pattern) {
1280
+ if (pattern.includes("*")) {
1281
+ return fg6.sync(pattern, { cwd: repoRoot, absolute: false });
1857
1282
  }
1858
- };
1859
- function resolveMcpIds(requested) {
1860
- return requested.map((id) => {
1861
- if (!MCP_SERVER_IDS.includes(id)) {
1862
- throw new Error(`unknown MCP server: ${id} (expected one of ${MCP_SERVER_IDS.join(", ")})`);
1863
- }
1864
- return id;
1865
- });
1283
+ return [pattern];
1866
1284
  }
1867
-
1868
- // src/render.ts
1869
- var RenderError = class extends Error {
1870
- constructor(message) {
1871
- super(message);
1872
- this.name = "RenderError";
1285
+ var tracksDrift = {
1286
+ id: "lint:tracks-drift",
1287
+ pillars: ["handbook", "tests", "workflow"],
1288
+ defaultSeverity: "warning",
1289
+ suggestedSkills: ["/drift", "/handbook"],
1290
+ run(repoRoot) {
1291
+ const issues = [];
1292
+ for (const dir of TRACKED_DIRS2) {
1293
+ const files = listMarkdown(repoRoot, dir);
1294
+ for (const f of files) {
1295
+ const text = readText(repoRoot, f);
1296
+ const { data } = parseFrontmatter(text);
1297
+ if (!Array.isArray(data.tracks)) continue;
1298
+ const docCommit = gitLastCommitForPath(repoRoot, f);
1299
+ if (!docCommit) continue;
1300
+ const threshold = typeof data.driftThreshold === "number" && data.driftThreshold > 0 ? data.driftThreshold : DEFAULT_DRIFT_THRESHOLD;
1301
+ let driftCount = 0;
1302
+ for (const tracked of data.tracks) {
1303
+ if (typeof tracked !== "string") continue;
1304
+ const targets = expandGlob(repoRoot, tracked);
1305
+ for (const t of targets.length > 0 ? targets : [tracked]) {
1306
+ driftCount += gitCommitsSince(repoRoot, t, docCommit.hash);
1307
+ }
1308
+ }
1309
+ if (driftCount > threshold) {
1310
+ issues.push({
1311
+ linter: this.id,
1312
+ severity: "warning",
1313
+ file: f,
1314
+ message: `tracked files changed in ${driftCount} commits since doc last edit (threshold ${threshold})`
1315
+ });
1316
+ }
1317
+ }
1318
+ }
1319
+ return issues;
1873
1320
  }
1874
1321
  };
1875
- function mergeById(stock, added) {
1876
- const result = /* @__PURE__ */ new Map();
1877
- for (const item of stock) result.set(item.meta.id, item);
1878
- if (added) {
1879
- for (const item of added) result.set(item.meta.id, item);
1322
+
1323
+ // src/linters/index.ts
1324
+ var ALL_LINTERS = [
1325
+ readmePresence,
1326
+ readmeSections,
1327
+ docLayout,
1328
+ cardinalFiles,
1329
+ decisionSchema,
1330
+ adrNoTracks,
1331
+ frontmatterTracks,
1332
+ tracksDrift,
1333
+ specTechAgnostic,
1334
+ specHasContent,
1335
+ crossLinks,
1336
+ orphanDecisions,
1337
+ gitignoreHarness,
1338
+ qualitySchema,
1339
+ generatedFresh
1340
+ ];
1341
+ function runLinters(repoRoot, opts = {}) {
1342
+ const config = loadLintConfig(repoRoot);
1343
+ const ctx = { repoRoot, config };
1344
+ const filtered = ALL_LINTERS.filter((l) => {
1345
+ if (opts.only && !opts.only.includes(l.id)) return false;
1346
+ if (opts.pillar && !l.pillars.includes(opts.pillar) && !l.pillars.includes("all")) return false;
1347
+ return true;
1348
+ });
1349
+ const issues = [];
1350
+ for (const linter of filtered) {
1351
+ try {
1352
+ issues.push(...linter.run(repoRoot, ctx));
1353
+ } catch (err) {
1354
+ issues.push({
1355
+ linter: linter.id,
1356
+ severity: "error",
1357
+ file: "<internal>",
1358
+ message: `linter crashed: ${err instanceof Error ? err.message : String(err)}`
1359
+ });
1360
+ }
1880
1361
  }
1881
- return Array.from(result.values());
1882
- }
1883
- function removeByIds(items, disabled) {
1884
- if (disabled.length === 0) return [...items];
1885
- const disabledSet = new Set(disabled);
1886
- return items.filter((item) => !disabledSet.has(item.meta.id));
1887
- }
1888
- function applyOverrides(harness, overrides) {
1889
- const disabled = overrides?.disable ?? [];
1362
+ const errors = issues.filter((i) => i.severity === "error").length;
1363
+ const warnings = issues.filter((i) => i.severity === "warning").length;
1890
1364
  return {
1891
- agents: removeByIds(mergeById(harness.agents, overrides?.add?.agents), disabled),
1892
- skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
1893
- cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
1365
+ version: 1,
1366
+ summary: { errors, warnings, pass: errors === 0 },
1367
+ issues
1894
1368
  };
1895
1369
  }
1896
- var CLAUDE_MD_STUB = "@AGENTS.md\n";
1897
- function opencodeLast(engines) {
1898
- return [...engines].sort((a, b) => Number(a === "opencode") - Number(b === "opencode"));
1370
+ function suggestedSkillsFor(linterId) {
1371
+ const linter = ALL_LINTERS.find((l) => l.id === linterId);
1372
+ return linter?.suggestedSkills ?? [];
1899
1373
  }
1900
- function render(input) {
1901
- const { engines } = input;
1902
- if (engines.length === 0) {
1903
- throw new RenderError("at least one engine must be selected");
1374
+ function formatReportText(report) {
1375
+ const lines = [];
1376
+ for (const issue of report.issues) {
1377
+ const location = issue.line !== void 0 ? `:${issue.line}` : "";
1378
+ lines.push(`${issue.file}${location}: ${issue.severity}[${issue.linter}]
1379
+ ${issue.message}`);
1380
+ const hints = suggestedSkillsFor(issue.linter);
1381
+ if (hints.length > 0) {
1382
+ lines.push(` \u2192 Try: ${hints.join(", ")}`);
1383
+ }
1904
1384
  }
1905
- const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
1906
- const harness = applyOverrides(base, input.overrides);
1907
- if (harness.agents.length === 0) {
1908
- throw new RenderError("No agents found in harness");
1385
+ const { errors, warnings, pass } = report.summary;
1386
+ lines.push("");
1387
+ lines.push(
1388
+ `${errors} ${errors === 1 ? "error" : "errors"}, ${warnings} ${warnings === 1 ? "warning" : "warnings"}. ${pass ? "\u2714 CI passes." : "\u2718 CI fails."}`
1389
+ );
1390
+ return lines.join("\n");
1391
+ }
1392
+
1393
+ // src/cli/check.ts
1394
+ import { existsSync as existsSync8, readFileSync as readFileSync6 } from "fs";
1395
+ import { join as join9 } from "path";
1396
+ var REQUIRED_DIRS2 = [
1397
+ "docs/spec",
1398
+ "docs/decisions",
1399
+ "docs/handbook",
1400
+ "docs/tests",
1401
+ "docs/workflow"
1402
+ ];
1403
+ function checkCommand(repoRoot) {
1404
+ const issues = [];
1405
+ if (!existsSync8(join9(repoRoot, "README.md"))) {
1406
+ issues.push("README.md missing at repo root");
1909
1407
  }
1910
- const files = [];
1911
- const warnings = [];
1912
- const exposedSkills = /* @__PURE__ */ new Map();
1913
- const exposedCmds = /* @__PURE__ */ new Map();
1914
- for (const engine of opencodeLast(engines)) {
1915
- const renderer = getRenderer(engine);
1916
- const renderedSkills = [];
1917
- for (const skill of harness.skills) {
1918
- const result = renderer.renderSkill(skill);
1919
- warnings.push(...result.warnings);
1920
- if (result.files.length > 0) {
1921
- const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
1922
- if (!alreadyVisible) files.push(...result.files);
1923
- renderedSkills.push(skill);
1924
- exposedSkills.set(skill.meta.id, skill);
1925
- }
1926
- }
1927
- const renderedSkillIds = new Set(renderedSkills.map((s) => s.meta.id));
1928
- const renderedCmds = [];
1929
- for (const cmd of harness.cmds) {
1930
- if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
1931
- const result = renderer.renderCmd(cmd);
1932
- warnings.push(...result.warnings);
1933
- if (result.files.length > 0) {
1934
- files.push(...result.files);
1935
- renderedCmds.push(cmd);
1936
- exposedCmds.set(cmd.meta.id, cmd);
1937
- }
1408
+ for (const d of REQUIRED_DIRS2) {
1409
+ if (!existsSync8(join9(repoRoot, d))) {
1410
+ issues.push(`missing directory: ${d}/`);
1938
1411
  }
1939
- const agentsResult = renderer.renderAgents(harness.agents);
1940
- warnings.push(...agentsResult.warnings);
1941
- files.push(...agentsResult.files);
1942
- if (input.mcpServers && input.mcpServers.length > 0) {
1943
- const specs = input.mcpServers.map((id) => MCP_SERVERS[id]);
1944
- const mcpResult = renderer.renderMcp(specs);
1945
- warnings.push(...mcpResult.warnings);
1946
- files.push(...mcpResult.files);
1412
+ }
1413
+ const gitignorePath = join9(repoRoot, ".gitignore");
1414
+ if (!existsSync8(gitignorePath)) {
1415
+ issues.push(".gitignore missing at repo root");
1416
+ } else {
1417
+ const text = readFileSync6(gitignorePath, "utf8");
1418
+ for (const entry of missingGitignoreEntries(text)) {
1419
+ issues.push(`.gitignore missing entry: ${entry}`);
1947
1420
  }
1948
- if (input.withStopHook !== false) {
1949
- const hookResult = renderer.renderStopHook();
1950
- warnings.push(...hookResult.warnings);
1951
- files.push(...hookResult.files);
1421
+ for (const entry of forbiddenGitignoreEntries(text)) {
1422
+ issues.push(`.gitignore must not ignore generated file: ${entry}`);
1952
1423
  }
1953
1424
  }
1954
- const hasProjectSkills = (input.projectSkills?.length ?? 0) > 0;
1955
- const umbrellaContent = buildUmbrellaBody(harness.agents, {
1956
- availableSkills: Array.from(exposedSkills.values()),
1957
- availableCommands: Array.from(exposedCmds.values()),
1958
- hasProjectSkills,
1959
- hasQualityDoc: input.hasQualityDoc === true
1960
- });
1961
- files.push({ path: "AGENTS.md", content: umbrellaContent });
1962
- if (engines.includes("claude-code")) {
1963
- files.push({ path: "CLAUDE.md", content: CLAUDE_MD_STUB });
1964
- }
1965
- return { files, warnings };
1425
+ return { pass: issues.length === 0, issues };
1966
1426
  }
1967
1427
 
1968
- // src/cli/plan-render.ts
1969
- var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
1970
- function resolveEngineList(requested) {
1971
- if (!requested) return [...ENGINES];
1972
- if (requested.length === 0) throw new Error("no engine selected");
1973
- const engines = requested.map((e) => {
1974
- if (!ENGINES.includes(e)) {
1975
- throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
1976
- }
1977
- return e;
1978
- });
1979
- return [...new Set(engines)];
1980
- }
1981
- function defaultPackageDir() {
1982
- const here = dirname3(fileURLToPath(import.meta.url));
1983
- if (existsSync9(join10(here, "agents"))) return here;
1984
- return resolve3(here, "..");
1985
- }
1986
- function planInit(args) {
1987
- const engines = resolveEngineList(args.engines);
1988
- const packageDir = args.packageDir ?? defaultPackageDir();
1989
- const harness = loadHarness(packageDir);
1990
- const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
1991
- const projectSkills = loadProjectSkills(args.targetDir);
1992
- const hasQualityDoc = existsSync9(join10(args.targetDir, QUALITY_DOC_PATH));
1993
- const mcpServers = args.mcpServers ? resolveMcpIds(args.mcpServers) : void 0;
1994
- const stopHookInstalled = args.withStopHook !== false;
1995
- const output = render({
1996
- harness,
1997
- engines,
1998
- overrides,
1999
- projectSkills,
2000
- hasQualityDoc,
2001
- mcpServers,
2002
- withStopHook: stopHookInstalled
2003
- });
2004
- return { engines, output, stopHookInstalled };
2005
- }
1428
+ // src/cli/init.ts
1429
+ import { existsSync as existsSync12, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
1430
+ import { dirname as dirname7, join as join14, resolve as resolve8 } from "path";
2006
1431
 
2007
1432
  // src/cli/uninstall.ts
2008
- import {
2009
- existsSync as existsSync10,
2010
- readFileSync as readFileSync8,
2011
- readdirSync,
2012
- rmdirSync,
2013
- unlinkSync,
2014
- writeFileSync as writeFileSync2
2015
- } from "fs";
2016
- import { dirname as dirname4, join as join11, relative as relative2, resolve as resolve4 } from "path";
1433
+ import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync, rmdirSync, unlinkSync } from "fs";
1434
+ import { dirname as dirname4, join as join10, relative as relative2, resolve as resolve5 } from "path";
2017
1435
  function uninstallCommand(args) {
2018
- const root = resolve4(args.targetDir);
1436
+ const root = resolve5(args.targetDir);
2019
1437
  const warnings = [];
2020
1438
  assertManagedPaths(root, [MANIFEST_FILENAME]);
2021
1439
  const manifest = readManifest(root);
@@ -2023,36 +1441,20 @@ function uninstallCommand(args) {
2023
1441
  warnings.push(`no manifest found at ${manifestPath(root)} \u2014 nothing to uninstall`);
2024
1442
  return { filesRemoved: [], dirsPruned: [], warnings };
2025
1443
  }
2026
- assertManagedPaths(root, [
2027
- ...manifest.files,
2028
- ...manifest.opencodeConfig ? [OPENCODE_CONFIG_PATH] : [],
2029
- ...manifest.mcpConfig ? [CLAUDE_MCP_PATH] : [],
2030
- ...Object.keys(manifest.hookConfigs ?? {})
2031
- ]);
2032
- const config = planOpenCodeConfig(root, void 0, manifest.opencodeConfig);
2033
- const mcp = planClaudeMcpConfig(root, void 0, manifest.mcpConfig);
2034
- const hooks = planHookConfigCleanup(root, manifest.hookConfigs);
2035
- const sharedHooks = new Set(Object.keys(manifest.hookConfigs ?? {}));
2036
- const modified = manifest.files.filter((file) => {
2037
- const hash2 = manifest.fileHashes?.[file];
2038
- const full = join11(root, file);
2039
- return hash2 !== void 0 && existsSync10(full) && hashContent(readFileSync8(full)) !== hash2;
1444
+ const released = manifest.files.filter((file) => RELEASED_PATHS.includes(file));
1445
+ const files = manifest.files.filter((file) => !released.includes(file));
1446
+ assertManagedPaths(root, files);
1447
+ const modified = files.filter((file) => {
1448
+ const hash = manifest.fileHashes?.[file];
1449
+ const full = join10(root, file);
1450
+ return hash !== void 0 && existsSync9(full) && hashContent(readFileSync7(full)) !== hash;
2040
1451
  });
2041
- const ownedFiles = manifest.files.filter(
2042
- (file) => file !== OPENCODE_CONFIG_PATH && !(manifest.mcpConfig && file === CLAUDE_MCP_PATH) && !sharedHooks.has(file) && !modified.includes(file)
2043
- );
2044
- if (config.remove) ownedFiles.push(OPENCODE_CONFIG_PATH);
2045
- if (mcp.remove) ownedFiles.push(CLAUDE_MCP_PATH);
2046
- ownedFiles.push(...hooks.removals);
1452
+ const ownedFiles = files.filter((file) => !modified.includes(file));
2047
1453
  const { filesRemoved, dirsPruned, missing } = removeRenderedFiles(root, ownedFiles);
2048
- for (const file of [config.write, mcp.write, ...hooks.writes]) {
2049
- if (file) writeFileSync2(join11(root, file.path), file.content);
1454
+ for (const file of released) {
1455
+ warnings.push(`no longer managed by the harness, left in place: ${file}`);
2050
1456
  }
2051
- warnings.push(...config.warnings, ...mcp.warnings, ...hooks.warnings);
2052
1457
  for (const file of modified) warnings.push(`kept modified harness file: ${file}`);
2053
- if (manifest.files.includes(OPENCODE_CONFIG_PATH) && !manifest.opencodeConfig) {
2054
- warnings.push(`preserved legacy shared configuration: ${OPENCODE_CONFIG_PATH}`);
2055
- }
2056
1458
  for (const rel of missing) warnings.push(`file in manifest is already missing: ${rel}`);
2057
1459
  unlinkSync(manifestPath(root));
2058
1460
  return { filesRemoved, dirsPruned, warnings };
@@ -2063,8 +1465,8 @@ function removeRenderedFiles(root, files) {
2063
1465
  const missing = [];
2064
1466
  const dirsToConsider = /* @__PURE__ */ new Set();
2065
1467
  for (const rel of files) {
2066
- const full = join11(root, rel);
2067
- if (existsSync10(full)) {
1468
+ const full = join10(root, rel);
1469
+ if (existsSync9(full)) {
2068
1470
  unlinkSync(full);
2069
1471
  filesRemoved.push(rel);
2070
1472
  dirsToConsider.add(dirname4(full));
@@ -2086,7 +1488,7 @@ function pruneEmptyDirs(root, leaves) {
2086
1488
  const pruned = [];
2087
1489
  const sorted = [...candidates].sort((a, b) => b.length - a.length);
2088
1490
  for (const dir of sorted) {
2089
- if (!existsSync10(dir)) continue;
1491
+ if (!existsSync9(dir)) continue;
2090
1492
  if (readdirSync(dir).length > 0) continue;
2091
1493
  rmdirSync(dir);
2092
1494
  pruned.push(relative2(root, dir));
@@ -2103,33 +1505,25 @@ import {
2103
1505
  lstatSync as lstatSync2,
2104
1506
  mkdirSync,
2105
1507
  openSync,
2106
- readFileSync as readFileSync9,
1508
+ readFileSync as readFileSync8,
2107
1509
  readdirSync as readdirSync2,
2108
1510
  realpathSync as realpathSync2,
2109
1511
  rmdirSync as rmdirSync2,
2110
1512
  unlinkSync as unlinkSync2,
2111
- writeFileSync as writeFileSync3
1513
+ writeFileSync as writeFileSync2
2112
1514
  } from "fs";
2113
1515
  import { homedir } from "os";
2114
- import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute3, join as join12, relative as relative3, resolve as resolve5, sep } from "path";
1516
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute3, join as join11, relative as relative3, resolve as resolve6, sep } from "path";
2115
1517
  var MANIFEST_PATH = ".harness-manifest.json";
2116
- var PRIVATE_FILES = /* @__PURE__ */ new Set([
2117
- MANIFEST_PATH,
2118
- ".mcp.json",
2119
- ".codex/config.toml",
2120
- ".codex/hooks.json",
2121
- ".claude/settings.json",
2122
- ".opencode/opencode.json",
2123
- ".opencode/mcp.json"
2124
- ]);
1518
+ var PRIVATE_FILES = /* @__PURE__ */ new Set([MANIFEST_PATH]);
2125
1519
  function canonicalRoot(root) {
2126
- let ancestor = resolve5(root);
1520
+ let ancestor = resolve6(root);
2127
1521
  const missing = [];
2128
1522
  while (!lstatSync2(ancestor, { throwIfNoEntry: false })) {
2129
1523
  missing.unshift(basename3(ancestor));
2130
1524
  ancestor = dirname5(ancestor);
2131
1525
  }
2132
- return join12(realpathSync2(ancestor), ...missing);
1526
+ return join11(realpathSync2(ancestor), ...missing);
2133
1527
  }
2134
1528
  function contains(parent, child) {
2135
1529
  const path = relative3(parent, child);
@@ -2169,7 +1563,7 @@ function writeBackupFile(path, content) {
2169
1563
  createDirectories(dirname5(path), [], 448);
2170
1564
  const fd = openSync(path, "wx", 384);
2171
1565
  try {
2172
- writeFileSync3(fd, content);
1566
+ writeFileSync2(fd, content);
2173
1567
  fsyncSync(fd);
2174
1568
  } finally {
2175
1569
  closeSync(fd);
@@ -2180,14 +1574,14 @@ function saveSnapshot(root, paths, backup) {
2180
1574
  createDirectories(dirname5(backup), [], 448);
2181
1575
  mkdirSync(backup, { mode: 448 });
2182
1576
  for (const path of paths) {
2183
- const full = join12(root, path);
1577
+ const full = join11(root, path);
2184
1578
  const info = lstatSync2(full, { throwIfNoEntry: false });
2185
1579
  if (!info) {
2186
1580
  entries.push({ path, exists: false });
2187
1581
  continue;
2188
1582
  }
2189
- const content = readFileSync9(full);
2190
- writeBackupFile(join12(backup, "files", path), content);
1583
+ const content = readFileSync8(full);
1584
+ writeBackupFile(join11(backup, "files", path), content);
2191
1585
  entries.push({
2192
1586
  path,
2193
1587
  exists: true,
@@ -2196,7 +1590,7 @@ function saveSnapshot(root, paths, backup) {
2196
1590
  });
2197
1591
  }
2198
1592
  writeBackupFile(
2199
- join12(backup, "snapshot.json"),
1593
+ join11(backup, "snapshot.json"),
2200
1594
  `${JSON.stringify({ version: 1, root, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries }, null, 2)}
2201
1595
  `
2202
1596
  );
@@ -2211,16 +1605,16 @@ function rollback(root, backup, entries, touched, createdDirectories) {
2211
1605
  try {
2212
1606
  assertManagedPaths(root, [path]);
2213
1607
  const entry = entries.get(path);
2214
- const full = join12(root, path);
1608
+ const full = join11(root, path);
2215
1609
  const current = lstatSync2(full, { throwIfNoEntry: false });
2216
1610
  if (!entry?.exists) {
2217
1611
  if (current) unlinkSync2(full);
2218
1612
  continue;
2219
1613
  }
2220
- const original = readFileSync9(join12(backup, "files", path));
2221
- if (!current || !readFileSync9(full).equals(original)) {
1614
+ const original = readFileSync8(join11(backup, "files", path));
1615
+ if (!current || !readFileSync8(full).equals(original)) {
2222
1616
  if (current) unlinkSync2(full);
2223
- writeFileSync3(full, original, { mode: 384 });
1617
+ writeFileSync2(full, original, { mode: 384 });
2224
1618
  }
2225
1619
  chmodSync2(full, entry.mode);
2226
1620
  } catch (error) {
@@ -2240,8 +1634,8 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
2240
1634
  const paths = [.../* @__PURE__ */ new Set([...removals, ...writes.map((file) => file.path)])];
2241
1635
  assertManagedPaths(root, paths);
2242
1636
  const target = canonicalRoot(root);
2243
- const backup = resolve5(
2244
- backupDir ?? join12(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
1637
+ const backup = resolve6(
1638
+ backupDir ?? join11(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
2245
1639
  );
2246
1640
  assertBackupLocation(target, backup);
2247
1641
  let snapshot;
@@ -2259,18 +1653,18 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
2259
1653
  try {
2260
1654
  assertManagedPaths(target, paths);
2261
1655
  for (const path of removals) {
2262
- if (!lstatSync2(join12(target, path), { throwIfNoEntry: false })) continue;
1656
+ if (!lstatSync2(join11(target, path), { throwIfNoEntry: false })) continue;
2263
1657
  touched.add(path);
2264
- unlinkSync2(join12(target, path));
1658
+ unlinkSync2(join11(target, path));
2265
1659
  }
2266
1660
  for (const file of writes) {
2267
- const full = join12(target, file.path);
1661
+ const full = join11(target, file.path);
2268
1662
  createDirectories(dirname5(full), createdDirectories);
2269
1663
  touched.add(file.path);
2270
1664
  const entry = entries.get(file.path);
2271
1665
  const mode = file.path === MANIFEST_PATH ? 384 : entry?.exists ? entry.mode : PRIVATE_FILES.has(file.path) ? 384 : 420;
2272
1666
  if (entry?.exists && file.path === MANIFEST_PATH) chmodSync2(full, mode);
2273
- writeFileSync3(full, file.content, { mode });
1667
+ writeFileSync2(full, file.content, { mode });
2274
1668
  if (entry?.exists) chmodSync2(full, mode);
2275
1669
  }
2276
1670
  } catch (error) {
@@ -2284,36 +1678,28 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
2284
1678
  }
2285
1679
 
2286
1680
  // src/cli/update.ts
2287
- import { existsSync as existsSync12, readFileSync as readFileSync11 } from "fs";
2288
- import { join as join14, resolve as resolve6 } from "path";
2289
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
1681
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
1682
+ import { dirname as dirname6, join as join13, resolve as resolve7 } from "path";
1683
+ import { isDeepStrictEqual } from "util";
2290
1684
 
2291
1685
  // src/cli/update-manifest.ts
2292
- import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
2293
- import { join as join13 } from "path";
2294
- import { z as z6 } from "zod";
2295
- var EngineSchema = z6.enum(ENGINES);
2296
- var LegacySchema = z6.object({
2297
- version: z6.enum(["1", "2", "3"]),
1686
+ import { existsSync as existsSync10, readFileSync as readFileSync9 } from "fs";
1687
+ import { join as join12 } from "path";
1688
+ import { z as z4 } from "zod";
1689
+ var EngineSchema = z4.enum(ENGINES);
1690
+ var LegacySchema = z4.object({
1691
+ version: z4.enum(["1", "2", "3"]),
2298
1692
  engine: EngineSchema.optional(),
2299
- engines: z6.array(EngineSchema).nonempty().optional(),
2300
- renderedAt: z6.string(),
2301
- files: z6.array(z6.string())
1693
+ engines: z4.array(EngineSchema).nonempty().optional(),
1694
+ renderedAt: z4.string(),
1695
+ files: z4.array(z4.string())
2302
1696
  });
2303
- var HOOK_PATHS = {
2304
- "claude-code": [".claude/settings.json"],
2305
- "codex-cli": [".codex/hooks.json"],
2306
- opencode: [
2307
- ".opencode/plugins/harness-stop-hook/index.ts",
2308
- ".opencode/plugins/harness-stop-hook.ts"
2309
- ]
2310
- };
2311
1697
  function readUpdateInstallation(root) {
2312
1698
  assertManagedPaths(root, [MANIFEST_FILENAME]);
2313
- if (!existsSync11(join13(root, MANIFEST_FILENAME))) {
1699
+ if (!existsSync10(join12(root, MANIFEST_FILENAME))) {
2314
1700
  throw new Error("no harness manifest found; use init for a new installation");
2315
1701
  }
2316
- const raw = JSON.parse(readFileSync10(join13(root, MANIFEST_FILENAME), "utf8"));
1702
+ const raw = JSON.parse(readFileSync9(join12(root, MANIFEST_FILENAME), "utf8"));
2317
1703
  const sourceVersion = String(raw?.version);
2318
1704
  let manifest;
2319
1705
  if (["1", "2", "3"].includes(sourceVersion)) {
@@ -2321,7 +1707,7 @@ function readUpdateInstallation(root) {
2321
1707
  const engines2 = legacy.version === "1" ? [EngineSchema.parse(legacy.engine)] : legacy.engines;
2322
1708
  manifest = {
2323
1709
  version: "4",
2324
- engines: z6.array(EngineSchema).nonempty().parse(engines2),
1710
+ engines: z4.array(EngineSchema).nonempty().parse(engines2),
2325
1711
  files: legacy.files,
2326
1712
  renderedAt: legacy.renderedAt
2327
1713
  };
@@ -2330,40 +1716,28 @@ function readUpdateInstallation(root) {
2330
1716
  if (!current) throw new Error("harness manifest disappeared during planning");
2331
1717
  manifest = current;
2332
1718
  }
2333
- const engines = [...new Set(z6.array(EngineSchema).nonempty().parse(manifest.engines))];
2334
- const hookEngines = manifest.stopHookInstalled === false ? [] : manifest.stopHookEngines !== void 0 ? z6.array(EngineSchema).parse(manifest.stopHookEngines) : manifest.stopHookInstalled === true ? engines : engines.filter(
2335
- (engine) => HOOK_PATHS[engine].some((path) => manifest.files.includes(path))
2336
- );
2337
- if (hookEngines.some((engine) => !engines.includes(engine))) {
2338
- throw new Error("manifest stopHookEngines must be a subset of installed engines");
2339
- }
2340
- return { manifest, sourceVersion, engines, hookEngines: [...new Set(hookEngines)] };
1719
+ const engines = [...new Set(z4.array(EngineSchema).nonempty().parse(manifest.engines))];
1720
+ return { manifest, sourceVersion, engines };
2341
1721
  }
2342
1722
 
2343
1723
  // src/cli/update.ts
2344
- var CODEX_CONFIG_PATH = ".codex/config.toml";
1724
+ var LEGACY_HOOK_FILES = [".claude/settings.json", ".codex/hooks.json"];
1725
+ var LEGACY_HOOK_MARKER = "@vaubaan/harness stop-hook";
2345
1726
  function currentContent(root, path) {
2346
- return existsSync12(join14(root, path)) ? readFileSync11(join14(root, path), "utf8") : void 0;
2347
- }
2348
- function ownedUnchanged(root, previous, path) {
2349
- const content = currentContent(root, path);
2350
- if (content === void 0 || !previous.files.includes(path)) return false;
2351
- const hash2 = previous.fileHashes?.[path];
2352
- return hash2 === void 0 || hash2 === hashContent(content);
1727
+ return existsSync11(join13(root, path)) ? readFileSync10(join13(root, path), "utf8") : void 0;
2353
1728
  }
2354
1729
  function checkArtifactConflicts(root, previous, writes, removals) {
2355
1730
  const desired = new Map(writes.map((file) => [file.path, file.content]));
2356
1731
  const conflicts = [];
2357
1732
  for (const path of [...desired.keys(), ...removals]) {
2358
- if (SHARED_CONFIG_PATHS.includes(path)) continue;
2359
1733
  const content = currentContent(root, path);
2360
1734
  if (content === void 0 || content === desired.get(path)) continue;
2361
1735
  if (!previous.files.includes(path)) {
2362
1736
  conflicts.push(`existing file outside harness manifest: ${path}`);
2363
1737
  continue;
2364
1738
  }
2365
- const hash2 = previous.fileHashes?.[path];
2366
- if (hash2 && hash2 !== hashContent(content)) conflicts.push(`modified harness file: ${path}`);
1739
+ const hash = previous.fileHashes?.[path];
1740
+ if (hash && hash !== hashContent(content)) conflicts.push(`modified harness file: ${path}`);
2367
1741
  }
2368
1742
  if (conflicts.length) {
2369
1743
  throw new Error(
@@ -2372,92 +1746,47 @@ move their content to docs/ or .harness-overrides/, or keep them as yours with -
2372
1746
  );
2373
1747
  }
2374
1748
  }
2375
- function legacyMcpOwnership(root, previous) {
2376
- if (!ownedUnchanged(root, previous, CLAUDE_MCP_PATH)) return void 0;
2377
- try {
2378
- const servers = JSON.parse(currentContent(root, CLAUDE_MCP_PATH) ?? "").mcpServers;
2379
- if (!servers || typeof servers !== "object" || Array.isArray(servers)) return void 0;
2380
- return { createdFile: true, addedMcp: true, addedSchema: false, entries: servers };
2381
- } catch {
2382
- return void 0;
1749
+ function releaseLegacyPaths(previous, warnings) {
1750
+ const released = previous.files.filter((path) => RELEASED_PATHS.includes(path));
1751
+ for (const path of released) {
1752
+ warnings.push(`no longer managed by the harness, left in place: ${path}`);
2383
1753
  }
1754
+ if (released.length === 0) return previous;
1755
+ return { ...previous, files: previous.files.filter((path) => !released.includes(path)) };
2384
1756
  }
2385
- function planMcp(root, settings, rendered, pendingWrites) {
2386
- const { previous } = settings;
2387
- const plan = {
2388
- writes: [],
2389
- removals: [],
2390
- owned: [],
2391
- plannedOpenCode: false,
2392
- warnings: []
2393
- };
2394
- const claudeOwnership = previous.mcpConfig ?? legacyMcpOwnership(root, previous);
2395
- const codexOwned = ownedUnchanged(root, previous, CODEX_CONFIG_PATH);
2396
- if (settings.mcpServers === void 0) {
2397
- if (codexOwned) plan.owned.push(CODEX_CONFIG_PATH);
2398
- plan.mcpConfig = claudeOwnership;
2399
- return plan;
2400
- }
2401
- const desired = (path) => rendered.find((file) => file.path === path);
2402
- if (!pendingWrites.some((file) => file.path === OPENCODE_CONFIG_PATH)) {
2403
- plan.plannedOpenCode = true;
2404
- if (previous.files.includes(OPENCODE_CONFIG_PATH) && !previous.opencodeConfig) {
2405
- plan.warnings.push(`preserved legacy shared configuration: ${OPENCODE_CONFIG_PATH}`);
1757
+ function legacyHookWarnings(root) {
1758
+ const warnings = [];
1759
+ for (const path of LEGACY_HOOK_FILES) {
1760
+ const content = currentContent(root, path);
1761
+ if (content?.includes(LEGACY_HOOK_MARKER)) {
1762
+ warnings.push(
1763
+ `remove the harness Stop hook entry from ${path}: the Stop hook was removed in 2.0, run \`npx @vaubaan/harness lint\` in CI and pre-commit instead`
1764
+ );
2406
1765
  }
2407
- const opencode = planOpenCodeConfig(
2408
- root,
2409
- desired(OPENCODE_CONFIG_PATH),
2410
- previous.opencodeConfig
2411
- );
2412
- if (opencode.write) plan.writes.push(opencode.write);
2413
- if (opencode.remove) plan.removals.push(OPENCODE_CONFIG_PATH);
2414
- plan.opencodeConfig = opencode.ownership;
2415
- plan.warnings.push(...opencode.warnings);
2416
- }
2417
- const claude = planClaudeMcpConfig(root, desired(CLAUDE_MCP_PATH), claudeOwnership);
2418
- if (claude.write) plan.writes.push(claude.write);
2419
- if (claude.remove) plan.removals.push(CLAUDE_MCP_PATH);
2420
- plan.mcpConfig = claude.ownership;
2421
- plan.warnings.push(...claude.warnings);
2422
- const codex = desired(CODEX_CONFIG_PATH);
2423
- const codexExists = existsSync12(join14(root, CODEX_CONFIG_PATH));
2424
- if (codex && (!codexExists || codexOwned)) {
2425
- plan.writes.push(codex);
2426
- plan.owned.push(CODEX_CONFIG_PATH);
2427
- } else if (codex) {
2428
- plan.warnings.push(
2429
- `left ${CODEX_CONFIG_PATH} unchanged; add this block to it to enable MCP in Codex:
2430
- ${codex.content.trimEnd()}`
2431
- );
2432
- } else if (codexOwned) {
2433
- plan.removals.push(CODEX_CONFIG_PATH);
2434
1766
  }
2435
- return plan;
1767
+ return warnings;
2436
1768
  }
2437
1769
  function planInstallation(args, settings) {
2438
- const root = resolve6(args.targetDir);
2439
- const { previous, engines, hookEngines } = settings;
1770
+ const root = resolve7(args.targetDir);
1771
+ const { engines } = settings;
1772
+ const warnings = [];
1773
+ const previous = releaseLegacyPaths(settings.previous, warnings);
2440
1774
  const preserved = [
2441
1775
  .../* @__PURE__ */ new Set([...previous.preservedFiles ?? [], ...args.preserveFiles ?? []])
2442
1776
  ].sort();
2443
1777
  if (preserved.includes(MANIFEST_FILENAME))
2444
1778
  throw new Error("cannot preserve the harness manifest");
2445
- if (preserved.some((path) => SHARED_CONFIG_PATHS.includes(path))) {
2446
- throw new Error(
2447
- "--preserve applies to generated artifacts; shared configurations use entry-level preservation"
2448
- );
2449
- }
2450
- assertManagedPaths(root, [...previous.files, ...preserved, ...SHARED_CONFIG_PATHS]);
1779
+ assertManagedPaths(root, [...previous.files, ...preserved]);
2451
1780
  const requestedOverrides = args.overridesDir ?? previous.overridesDir;
2452
- const overridesDir = args.overridesDir ? resolve6(args.overridesDir) : previous.overridesDir ? resolve6(root, previous.overridesDir) : root;
2453
- if (requestedOverrides && !existsSync12(join14(overridesDir, ".harness-overrides"))) {
1781
+ const overridesDir = args.overridesDir ? resolve7(args.overridesDir) : previous.overridesDir ? resolve7(root, previous.overridesDir) : root;
1782
+ if (requestedOverrides && !existsSync11(join13(overridesDir, ".harness-overrides"))) {
2454
1783
  throw new Error(`recorded overrides are missing: ${overridesDir}/.harness-overrides`);
2455
1784
  }
2456
- const hasOverrides = existsSync12(join14(overridesDir, ".harness-overrides"));
2457
- const disablePath = join14(overridesDir, ".harness-overrides", "disable.yaml");
2458
- if (existsSync12(disablePath)) {
1785
+ const hasOverrides = existsSync11(join13(overridesDir, ".harness-overrides"));
1786
+ const disablePath = join13(overridesDir, ".harness-overrides", "disable.yaml");
1787
+ if (existsSync11(disablePath)) {
2459
1788
  try {
2460
- DisableYamlSchema.parse(parseYAML(readFileSync11(disablePath, "utf8")));
1789
+ DisableYamlSchema.parse(parseYAML(readFileSync10(disablePath, "utf8")));
2461
1790
  } catch {
2462
1791
  throw new Error(`invalid override selection: ${disablePath}`);
2463
1792
  }
@@ -2466,40 +1795,16 @@ function planInstallation(args, settings) {
2466
1795
  targetDir: root,
2467
1796
  packageDir: args.packageDir,
2468
1797
  engines,
2469
- overridesDir: hasOverrides ? overridesDir : void 0,
2470
- mcpServers: settings.mcpServers,
2471
- withStopHook: false
1798
+ overridesDir: hasOverrides ? overridesDir : void 0
2472
1799
  });
2473
- const generated = rendered.output.files.filter(
2474
- (file) => !SHARED_CONFIG_PATHS.includes(file.path)
1800
+ const output = rendered.output.files.filter((file) => !preserved.includes(file.path));
1801
+ const owned = output.map((file) => file.path).sort();
1802
+ const removals = previous.files.filter(
1803
+ (file) => !owned.includes(file) && !preserved.includes(file)
2475
1804
  );
2476
- const config = planUpdateConfigs(root, previous, hookEngines);
2477
- const mcp = planMcp(root, settings, rendered.output.files, config.writes);
2478
- const output = [...generated, ...config.writes, ...mcp.writes].filter(
2479
- (file) => !preserved.includes(file.path)
2480
- );
2481
- const owned = [
2482
- .../* @__PURE__ */ new Set([...generated.map((file) => file.path), ...config.ownedFiles, ...mcp.owned])
2483
- ].filter((file) => !preserved.includes(file)).sort();
2484
- const removals = [
2485
- .../* @__PURE__ */ new Set([
2486
- ...previous.files.filter(
2487
- (file) => !owned.includes(file) && !SHARED_CONFIG_PATHS.includes(file)
2488
- ),
2489
- ...config.removals,
2490
- ...mcp.removals
2491
- ])
2492
- ].filter((file) => !preserved.includes(file));
2493
- assertManagedPaths(root, [...output.map((file) => file.path), ...removals]);
1805
+ assertManagedPaths(root, [...owned, ...removals]);
2494
1806
  checkArtifactConflicts(root, previous, output, removals);
2495
- const hashes = Object.fromEntries(
2496
- owned.map((path) => {
2497
- const content = output.find((file) => file.path === path)?.content ?? currentContent(root, path);
2498
- if (content === void 0) throw new Error(`missing planned harness file: ${path}`);
2499
- return [path, hashContent(content)];
2500
- })
2501
- );
2502
- const opencodeConfig = mcp.plannedOpenCode ? mcp.opencodeConfig : config.opencodeConfig;
1807
+ const hashes = Object.fromEntries(output.map((file) => [file.path, hashContent(file.content)]));
2503
1808
  const manifest = {
2504
1809
  version: MANIFEST_VERSION,
2505
1810
  harnessVersion: VERSION,
@@ -2507,37 +1812,30 @@ function planInstallation(args, settings) {
2507
1812
  renderedAt: previous.renderedAt,
2508
1813
  files: owned,
2509
1814
  fileHashes: hashes,
2510
- stopHookInstalled: hookEngines.length > 0,
2511
- stopHookEngines: [...hookEngines].sort(),
2512
1815
  ...hasOverrides ? { overridesDir: overridesDir === root ? "." : overridesDir } : {},
2513
- ...preserved.length ? { preservedFiles: preserved } : {},
2514
- ...opencodeConfig ? { opencodeConfig } : {},
2515
- ...mcp.mcpConfig ? { mcpConfig: mcp.mcpConfig } : {},
2516
- ...config.hookConfigs ? { hookConfigs: config.hookConfigs } : {}
1816
+ ...preserved.length ? { preservedFiles: preserved } : {}
2517
1817
  };
2518
1818
  const writes = output.filter((file) => currentContent(root, file.path) !== file.content);
2519
- const existingRemovals = removals.filter((path) => existsSync12(join14(root, path)));
2520
- if (writes.length || existingRemovals.length || !isDeepStrictEqual3(previous, manifest)) {
1819
+ const existingRemovals = removals.filter((path) => existsSync11(join13(root, path)));
1820
+ if (writes.length || existingRemovals.length || !isDeepStrictEqual(settings.previous, manifest)) {
2521
1821
  manifest.renderedAt = (/* @__PURE__ */ new Date()).toISOString();
2522
1822
  writes.push({ path: MANIFEST_FILENAME, content: `${JSON.stringify(manifest, null, 2)}
2523
1823
  ` });
2524
1824
  }
2525
- const warnings = [...rendered.output.warnings, ...config.warnings, ...mcp.warnings];
1825
+ warnings.push(...rendered.output.warnings, ...legacyHookWarnings(root));
2526
1826
  if (preserved.length) warnings.push(`preserved user-owned artifacts: ${preserved.join(", ")}`);
2527
1827
  return { writes, removals: existingRemovals, owned, manifest, warnings };
2528
1828
  }
2529
1829
  function planUpdate(args) {
2530
- const root = resolve6(args.targetDir);
2531
- const { manifest: previous, sourceVersion, engines, hookEngines } = readUpdateInstallation(root);
2532
- const plan = planInstallation(args, { previous, sourceVersion, engines, hookEngines });
1830
+ const root = resolve7(args.targetDir);
1831
+ const { manifest: previous, sourceVersion, engines } = readUpdateInstallation(root);
1832
+ const plan = planInstallation(args, { previous, sourceVersion, engines });
2533
1833
  const warnings = [...plan.warnings];
2534
1834
  if (!previous.fileHashes) {
2535
1835
  warnings.push(
2536
1836
  "legacy manifest has no file fingerprints: managed artifacts will be regenerated; backup preserves their previous contents"
2537
1837
  );
2538
1838
  }
2539
- if (engines.includes("codex-cli"))
2540
- warnings.push("ensure .agents/ is ignored by Git (run harness check)");
2541
1839
  return {
2542
1840
  writes: plan.writes,
2543
1841
  removals: plan.removals,
@@ -2556,12 +1854,9 @@ function planUpdate(args) {
2556
1854
  function updateCommand(args) {
2557
1855
  const plan = planUpdate(args);
2558
1856
  if (args.dryRun || plan.result.upToDate) return plan.result;
2559
- const { backupDir } = applyUpdateTransaction(
2560
- resolve6(args.targetDir),
2561
- plan.writes,
2562
- plan.removals,
2563
- args.backupDir
2564
- );
1857
+ const root = resolve7(args.targetDir);
1858
+ const { backupDir } = applyUpdateTransaction(root, plan.writes, plan.removals, args.backupDir);
1859
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname6(join13(root, path)))));
2565
1860
  return { ...plan.result, backupDir };
2566
1861
  }
2567
1862
 
@@ -2570,9 +1865,8 @@ function emptyManifest(engines) {
2570
1865
  return { version: MANIFEST_VERSION, engines: [...engines], renderedAt: "", files: [] };
2571
1866
  }
2572
1867
  function initCommand(args) {
2573
- const root = resolve7(args.targetDir);
1868
+ const root = resolve8(args.targetDir);
2574
1869
  const engines = resolveEngineList(args.engines);
2575
- const stopHookInstalled = args.withStopHook !== false;
2576
1870
  const previous = readManifest(root) ?? emptyManifest(engines);
2577
1871
  const plan = planInstallation(
2578
1872
  {
@@ -2581,16 +1875,10 @@ function initCommand(args) {
2581
1875
  overridesDir: args.overridesDir,
2582
1876
  preserveFiles: args.preserveFiles
2583
1877
  },
2584
- {
2585
- previous,
2586
- sourceVersion: previous.version,
2587
- engines,
2588
- hookEngines: stopHookInstalled ? engines : [],
2589
- mcpServers: args.mcpServers ?? []
2590
- }
1878
+ { previous, sourceVersion: previous.version, engines }
2591
1879
  );
2592
1880
  const touchedExisting = [...plan.writes.map((file) => file.path), ...plan.removals].some(
2593
- (path) => path !== MANIFEST_FILENAME && existsSync13(join15(root, path))
1881
+ (path) => path !== MANIFEST_FILENAME && existsSync12(join14(root, path))
2594
1882
  );
2595
1883
  let backupDir;
2596
1884
  if (plan.writes.length || plan.removals.length) {
@@ -2599,289 +1887,34 @@ function initCommand(args) {
2599
1887
  rmSync(backupDir, { recursive: true, force: true });
2600
1888
  backupDir = void 0;
2601
1889
  }
2602
- pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname6(join15(root, path)))));
1890
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname7(join14(root, path)))));
2603
1891
  }
2604
- const sharedWritten = plan.writes.map((file) => file.path).filter((path) => SHARED_CONFIG_PATHS.includes(path) && !plan.owned.includes(path));
2605
1892
  return {
2606
- filesWritten: [...plan.owned, ...sharedWritten],
1893
+ filesWritten: plan.owned,
2607
1894
  staleFilesRemoved: plan.removals,
2608
1895
  warnings: plan.warnings,
2609
- stopHookInstalled,
2610
1896
  engines,
2611
1897
  ...backupDir ? { backupDir } : {}
2612
1898
  };
2613
1899
  }
2614
1900
 
2615
1901
  // src/cli/render.ts
2616
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
2617
- import { dirname as dirname7, join as join16 } from "path";
1902
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
1903
+ import { dirname as dirname8, join as join15 } from "path";
2618
1904
  function renderCommand(args) {
2619
- const engineList = args.engines && args.engines.length > 0 ? args.engines.map((e) => {
2620
- if (!ENGINES.includes(e)) {
2621
- throw new Error(`unknown engine: ${e}`);
2622
- }
2623
- return e;
2624
- }) : [...ENGINES];
1905
+ const engines = resolveEngineList(args.engines);
2625
1906
  const harness = loadHarness(args.packageDir);
2626
- const mcpServers = args.mcpServers ? resolveMcpIds(args.mcpServers) : void 0;
2627
- const output = render({
2628
- harness,
2629
- engines: engineList,
2630
- mcpServers,
2631
- withStopHook: args.withStopHook !== false
2632
- });
1907
+ const output = render({ harness, engines });
2633
1908
  const filesWritten = [];
2634
1909
  for (const f of output.files) {
2635
- const full = join16(args.outDir, f.path);
2636
- mkdirSync3(dirname7(full), { recursive: true });
2637
- writeFileSync5(full, f.content);
1910
+ const full = join15(args.outDir, f.path);
1911
+ mkdirSync3(dirname8(full), { recursive: true });
1912
+ writeFileSync4(full, f.content);
2638
1913
  filesWritten.push(f.path);
2639
1914
  }
2640
1915
  return { filesWritten, warnings: output.warnings };
2641
1916
  }
2642
1917
 
2643
- // src/cli/stop-hook.ts
2644
- import { readFileSync as readFileSync13 } from "fs";
2645
- import { resolve as resolve8 } from "path";
2646
-
2647
- // src/stop-hook/adapters/claude.ts
2648
- var claudeAdapter = {
2649
- parseInput(stdin) {
2650
- const parsed = stdin.trim() === "" ? {} : JSON.parse(stdin);
2651
- return {
2652
- sessionId: typeof parsed.session_id === "string" ? parsed.session_id : "default",
2653
- stopHookActive: parsed.stop_hook_active === true
2654
- };
2655
- },
2656
- respond(decision) {
2657
- if (decision.kind === "inject") {
2658
- return {
2659
- stdout: `${JSON.stringify({ decision: "block", reason: decision.reason ?? "" })}
2660
- `,
2661
- stderr: "",
2662
- exitCode: 0
2663
- };
2664
- }
2665
- if (decision.kind === "terminate") {
2666
- return {
2667
- stdout: "",
2668
- stderr: `${decision.reason ?? ""}
2669
- `,
2670
- exitCode: 0
2671
- };
2672
- }
2673
- return { stdout: "", stderr: "", exitCode: 0 };
2674
- }
2675
- };
2676
-
2677
- // src/stop-hook/adapters/codex.ts
2678
- var codexAdapter = {
2679
- parseInput(stdin) {
2680
- const parsed = stdin.trim() === "" ? {} : JSON.parse(stdin);
2681
- return {
2682
- sessionId: typeof parsed.session_id === "string" ? parsed.session_id : "default",
2683
- stopHookActive: parsed.stop_hook_active === true
2684
- };
2685
- },
2686
- respond(decision) {
2687
- if (decision.kind === "inject") {
2688
- return {
2689
- stdout: `${JSON.stringify({ decision: "block", reason: decision.reason ?? "" })}
2690
- `,
2691
- stderr: "",
2692
- exitCode: 0
2693
- };
2694
- }
2695
- if (decision.kind === "terminate") {
2696
- return {
2697
- stdout: "",
2698
- stderr: `${decision.reason ?? ""}
2699
- `,
2700
- exitCode: 0
2701
- };
2702
- }
2703
- return { stdout: "", stderr: "", exitCode: 0 };
2704
- }
2705
- };
2706
-
2707
- // src/stop-hook/adapters/opencode.ts
2708
- var opencodeAdapter = {
2709
- parseInput(stdin) {
2710
- const parsed = stdin.trim() === "" ? {} : JSON.parse(stdin);
2711
- const sessionId = typeof parsed.sessionID === "string" ? parsed.sessionID : typeof parsed.session_id === "string" ? parsed.session_id : "default";
2712
- return { sessionId, stopHookActive: false };
2713
- },
2714
- respond(decision) {
2715
- if (decision.kind === "inject") {
2716
- return { stdout: "", stderr: `${decision.reason ?? ""}
2717
- `, exitCode: 2 };
2718
- }
2719
- if (decision.kind === "terminate") {
2720
- return { stdout: "", stderr: `${decision.reason ?? ""}
2721
- `, exitCode: 0 };
2722
- }
2723
- return { stdout: "", stderr: "", exitCode: 0 };
2724
- }
2725
- };
2726
-
2727
- // src/stop-hook/adapters/index.ts
2728
- var ADAPTERS = {
2729
- claude: claudeAdapter,
2730
- codex: codexAdapter,
2731
- opencode: opencodeAdapter
2732
- };
2733
- function getAdapter(engine) {
2734
- return ADAPTERS[engine];
2735
- }
2736
-
2737
- // src/stop-hook/core.ts
2738
- import { execFileSync as execFileSync2 } from "child_process";
2739
- import { createHash as createHash3 } from "crypto";
2740
-
2741
- // src/stop-hook/state.ts
2742
- import { existsSync as existsSync14, mkdirSync as mkdirSync4, readFileSync as readFileSync12, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
2743
- import { dirname as dirname8, join as join17 } from "path";
2744
- import { z as z7 } from "zod";
2745
- var LintStateSchema = z7.object({
2746
- attempts: z7.number().int().nonnegative(),
2747
- lastLintHash: z7.string(),
2748
- updatedAt: z7.string()
2749
- });
2750
- var STATE_DIR = ".harness/state";
2751
- function safeSessionId(sessionId) {
2752
- return sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 80) || "default";
2753
- }
2754
- function statePath(cwd, sessionId) {
2755
- return join17(cwd, STATE_DIR, `lint-${safeSessionId(sessionId)}.json`);
2756
- }
2757
- function readState(cwd, sessionId) {
2758
- const path = statePath(cwd, sessionId);
2759
- if (!existsSync14(path)) return null;
2760
- try {
2761
- const raw = JSON.parse(readFileSync12(path, "utf8"));
2762
- return LintStateSchema.parse(raw);
2763
- } catch {
2764
- return null;
2765
- }
2766
- }
2767
- function writeState(cwd, sessionId, state) {
2768
- const path = statePath(cwd, sessionId);
2769
- mkdirSync4(dirname8(path), { recursive: true });
2770
- writeFileSync6(path, `${JSON.stringify(state, null, 2)}
2771
- `);
2772
- }
2773
- function resetState(cwd, sessionId) {
2774
- const path = statePath(cwd, sessionId);
2775
- if (existsSync14(path)) rmSync2(path, { force: true });
2776
- }
2777
-
2778
- // src/stop-hook/types.ts
2779
- var STOP_HOOK_ENGINES = ["claude", "codex", "opencode"];
2780
- var DEFAULT_MAX_ATTEMPTS = 3;
2781
-
2782
- // src/stop-hook/core.ts
2783
- function exhaustedReason(attempts, lintOutput) {
2784
- return `Harness lint: still failing after ${attempts} attempts.
2785
-
2786
- ${lintOutput}`;
2787
- }
2788
- function noProgressReason(lintOutput) {
2789
- return `Harness lint: no progress between attempts.
2790
-
2791
- ${lintOutput}`;
2792
- }
2793
- function hash(s) {
2794
- return createHash3("sha256").update(s).digest("hex").slice(0, 16);
2795
- }
2796
- function maxAttempts(env) {
2797
- const raw = env.HARNESS_LINT_MAX_ATTEMPTS;
2798
- if (!raw) return DEFAULT_MAX_ATTEMPTS;
2799
- const n = Number.parseInt(raw, 10);
2800
- return Number.isFinite(n) && n > 0 ? n : DEFAULT_MAX_ATTEMPTS;
2801
- }
2802
- function defaultGitStatus(cwd) {
2803
- try {
2804
- return execFileSync2("git", ["status", "--porcelain"], {
2805
- cwd,
2806
- encoding: "utf8",
2807
- stdio: ["ignore", "pipe", "ignore"]
2808
- });
2809
- } catch {
2810
- return "";
2811
- }
2812
- }
2813
- function defaultRunLint(cwd) {
2814
- const report = runLinters(cwd);
2815
- return { pass: report.summary.pass, output: formatReportText(report) };
2816
- }
2817
- function decide(payload, coreEnv) {
2818
- if (coreEnv.env.HARNESS_LINT_DISABLE === "1") {
2819
- return { kind: "passthrough" };
2820
- }
2821
- if (payload.stopHookActive) {
2822
- return { kind: "passthrough" };
2823
- }
2824
- const dirty = coreEnv.gitStatus(coreEnv.cwd);
2825
- if (dirty.trim() === "") {
2826
- resetState(coreEnv.cwd, payload.sessionId);
2827
- return { kind: "passthrough" };
2828
- }
2829
- const lintResult = coreEnv.runLint(coreEnv.cwd);
2830
- if (lintResult.pass) {
2831
- resetState(coreEnv.cwd, payload.sessionId);
2832
- return { kind: "passthrough" };
2833
- }
2834
- const lintHash = hash(lintResult.output);
2835
- const prev = readState(coreEnv.cwd, payload.sessionId);
2836
- if (prev && prev.attempts > 0 && prev.lastLintHash === lintHash) {
2837
- resetState(coreEnv.cwd, payload.sessionId);
2838
- return { kind: "terminate", reason: noProgressReason(lintResult.output) };
2839
- }
2840
- const nextAttempts = (prev?.attempts ?? 0) + 1;
2841
- const limit = maxAttempts(coreEnv.env);
2842
- if (nextAttempts > limit) {
2843
- resetState(coreEnv.cwd, payload.sessionId);
2844
- return { kind: "terminate", reason: exhaustedReason(limit, lintResult.output) };
2845
- }
2846
- writeState(coreEnv.cwd, payload.sessionId, {
2847
- attempts: nextAttempts,
2848
- lastLintHash: lintHash,
2849
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2850
- });
2851
- return { kind: "inject", reason: lintResult.output };
2852
- }
2853
-
2854
- // src/cli/stop-hook.ts
2855
- function readStdinSync() {
2856
- try {
2857
- return readFileSync13(0, "utf8");
2858
- } catch {
2859
- return "";
2860
- }
2861
- }
2862
- function assertEngine(engine) {
2863
- if (!STOP_HOOK_ENGINES.includes(engine)) {
2864
- throw new Error(`unknown engine: ${engine} (expected one of ${STOP_HOOK_ENGINES.join(", ")})`);
2865
- }
2866
- return engine;
2867
- }
2868
- function stopHookCommand(args, stdin) {
2869
- const engine = assertEngine(args.engine);
2870
- const cwd = resolve8(args.cwd ?? ".");
2871
- const adapter = getAdapter(engine);
2872
- const payload = adapter.parseInput(stdin, process.env);
2873
- const decision = decide(payload, {
2874
- cwd,
2875
- env: process.env,
2876
- gitStatus: defaultGitStatus,
2877
- runLint: defaultRunLint
2878
- });
2879
- return adapter.respond(decision);
2880
- }
2881
- function stopHookCommandFromStdin(args) {
2882
- return stopHookCommand(args, readStdinSync());
2883
- }
2884
-
2885
1918
  // src/cli/index.ts
2886
1919
  function resolvePackageDir() {
2887
1920
  const here = dirname9(fileURLToPath2(import.meta.url));
@@ -2891,33 +1924,20 @@ function parseList(raw) {
2891
1924
  if (raw === void 0) return void 0;
2892
1925
  return raw.split(",").map((item) => item.trim()).filter(Boolean);
2893
1926
  }
1927
+ var ENGINES_HELP = "comma-separated engines to render: claude-code, codex-cli, opencode";
2894
1928
  var program = new Command();
2895
1929
  program.name("vaubaan-harness").description(
2896
- "Vaubaan harness \u2014 render skills, commands, and all agent personas into a target directory"
1930
+ "Vaubaan harness \u2014 keep a project's docs alive: render the doc skills into each engine's native layout, lint the docs in CI"
2897
1931
  ).version(VERSION);
2898
1932
  program.command("init").description(
2899
- "Render the harness (all agents, skills, commands) into a target directory. Defaults to all engines."
2900
- ).argument("<target-dir>", "directory to render harness into").option(
2901
- "--engines <list>",
2902
- "comma-separated subset of engines (claude-code, codex-cli, opencode) \u2014 defaults to all 3"
2903
- ).option("--overrides-dir <dir>", "directory containing .harness-overrides/").option("--package-dir <dir>", "override harness package directory (for dev/test)").option(
2904
- "--with-mcp <list>",
2905
- "comma-separated MCP servers to render config for (context7) \u2014 opt-in"
2906
- ).option(
2907
- "--no-stop-hook",
2908
- "skip rendering the Stop-hook configs that run lint at end of each agent turn"
2909
- ).option("--preserve <paths>", "comma-separated generated files to leave under user ownership").option("--backup-dir <dir>", "new backup directory outside the project").action((targetDir, opts) => {
1933
+ "Render the harness (doc skills, commands, AGENTS.md) into a project. Commit the result."
1934
+ ).argument("<target-dir>", "directory to render harness into").requiredOption("--engines <list>", ENGINES_HELP).option("--overrides-dir <dir>", "directory containing .harness-overrides/").option("--package-dir <dir>", "override harness package directory (for dev/test)").option("--preserve <paths>", "comma-separated generated files to leave under user ownership").option("--backup-dir <dir>", "new backup directory outside the project").action((targetDir, opts) => {
2910
1935
  const packageDir = opts.packageDir ?? resolvePackageDir();
2911
- const engines = parseList(opts.engines);
2912
- const withMcpRaw = opts.withMcp;
2913
- const mcpServers = withMcpRaw ? withMcpRaw.split(",").map((s) => s.trim()) : void 0;
2914
1936
  const result = initCommand({
2915
1937
  targetDir,
2916
- engines,
1938
+ engines: parseList(opts.engines) ?? [],
2917
1939
  overridesDir: opts.overridesDir,
2918
1940
  packageDir,
2919
- mcpServers,
2920
- withStopHook: opts.stopHook !== false,
2921
1941
  preserveFiles: parseList(opts.preserve),
2922
1942
  backupDir: opts.backupDir
2923
1943
  });
@@ -2929,22 +1949,15 @@ program.command("init").description(
2929
1949
  `
2930
1950
  );
2931
1951
  }
2932
- if (result.stopHookInstalled) {
2933
- process.stdout.write("stop-hook installed (runs lint at end-of-turn)\n");
2934
- if (result.engines.includes("codex-cli")) {
2935
- process.stdout.write(
2936
- "codex: the hook runs once you trust this project and approve the hook (startup review or /hooks)\n"
2937
- );
2938
- }
2939
- }
2940
1952
  if (result.backupDir) process.stdout.write(`backup: ${result.backupDir}
2941
1953
  `);
2942
1954
  for (const w of result.warnings) process.stderr.write(`warning: ${w}
2943
1955
  `);
1956
+ process.stdout.write(
1957
+ "next: commit the generated files, then run `npx @vaubaan/harness lint` before each commit (add it to your pre-commit hook and CI)\n"
1958
+ );
2944
1959
  });
2945
- program.command("update").description(
2946
- "Migrate an existing harness installation, retaining its engines and project settings"
2947
- ).argument("[target-dir]", "project directory", ".").option("--dry-run", "preview changes without writing files or backups").option("--json", "print the migration summary as JSON").option("--backup-dir <dir>", "new backup directory outside the project").option("--overrides-dir <dir>", "directory containing .harness-overrides/").option("--preserve <paths>", "comma-separated generated files to leave under user ownership").action((targetDir, opts) => {
1960
+ program.command("update").description("Re-render an existing installation with this version, keeping its engines").argument("[target-dir]", "project directory", ".").option("--dry-run", "preview changes without writing files or backups").option("--json", "print the migration summary as JSON").option("--backup-dir <dir>", "new backup directory outside the project").option("--overrides-dir <dir>", "directory containing .harness-overrides/").option("--preserve <paths>", "comma-separated generated files to leave under user ownership").action((targetDir, opts) => {
2948
1961
  const result = updateCommand({
2949
1962
  targetDir,
2950
1963
  packageDir: resolvePackageDir(),
@@ -2969,6 +1982,9 @@ program.command("update").description(
2969
1982
  `);
2970
1983
  for (const warning of result.warnings) process.stderr.write(`warning: ${warning}
2971
1984
  `);
1985
+ if (!result.dryRun && !result.upToDate) {
1986
+ process.stdout.write("next: commit the generated files\n");
1987
+ }
2972
1988
  });
2973
1989
  program.command("uninstall").description("Remove all files previously written by `init` into a target directory").argument("<target-dir>", "directory to uninstall harness from").action((targetDir) => {
2974
1990
  const result = uninstallCommand({ targetDir });
@@ -2979,7 +1995,7 @@ program.command("uninstall").description("Remove all files previously written by
2979
1995
  for (const w of result.warnings) process.stderr.write(`warning: ${w}
2980
1996
  `);
2981
1997
  });
2982
- program.command("check").description("Verify repo layout: 6 pillars present and .gitignore correct").argument("<repo>", "path to repo to check").action((repo) => {
1998
+ program.command("check").description("Verify repo layout: doc pillars present and .gitignore correct").argument("<repo>", "path to repo to check").action((repo) => {
2983
1999
  const result = checkCommand(repo);
2984
2000
  if (result.pass) {
2985
2001
  process.stdout.write("\u2714 layout OK\n");
@@ -2992,9 +2008,13 @@ program.command("check").description("Verify repo layout: 6 pillars present and
2992
2008
  program.command("lint").description("Run all mechanical linters and exit non-zero on errors").option(
2993
2009
  "--pillar <pillar>",
2994
2010
  "filter by pillar (spec, decisions, handbook, tests, workflow, quality)"
2995
- ).option("--format <fmt>", "text | json", "text").option("--cwd <dir>", "repo root", ".").action((opts) => {
2011
+ ).option("--only <ids>", "comma-separated linter ids to run (e.g. lint:cross-links)").option("--format <fmt>", "text | json", "text").option("--cwd <dir>", "repo root", ".").action((opts) => {
2996
2012
  const repoRoot = resolve9(opts.cwd ?? ".");
2997
- const lintOpts = opts.pillar ? { pillar: opts.pillar } : {};
2013
+ const only = parseList(opts.only);
2014
+ const lintOpts = {
2015
+ ...opts.pillar ? { pillar: opts.pillar } : {},
2016
+ ...only && only.length > 0 ? { only } : {}
2017
+ };
2998
2018
  const report = runLinters(repoRoot, lintOpts);
2999
2019
  if (opts.format === "json") {
3000
2020
  process.stdout.write(`${JSON.stringify(report, null, 2)}
@@ -3005,39 +2025,23 @@ program.command("lint").description("Run all mechanical linters and exit non-zer
3005
2025
  }
3006
2026
  process.exit(report.summary.pass ? 0 : 1);
3007
2027
  });
3008
- program.command("render").description("Render harness for preview (no overrides applied). Defaults to all engines.").option(
3009
- "--engines <list>",
3010
- "comma-separated subset of engines (claude-code, codex-cli, opencode) \u2014 defaults to all 3"
3011
- ).requiredOption("--out <dir>", "output directory").option("--package-dir <dir>", "override harness package directory").option(
3012
- "--with-mcp <list>",
3013
- "comma-separated MCP servers to render config for (context7) \u2014 opt-in"
3014
- ).option("--no-stop-hook", "skip rendering the Stop-hook configs").action((opts) => {
2028
+ program.command("render").description("Render harness for preview (no overrides applied)").requiredOption("--engines <list>", ENGINES_HELP).requiredOption("--out <dir>", "output directory").option("--package-dir <dir>", "override harness package directory").action((opts) => {
3015
2029
  const packageDir = opts.packageDir ?? resolvePackageDir();
3016
- const engines = parseList(opts.engines);
3017
- const withMcpRaw = opts.withMcp;
3018
- const mcpServers = withMcpRaw ? withMcpRaw.split(",").map((s) => s.trim()) : void 0;
3019
2030
  const result = renderCommand({
3020
- engines,
2031
+ engines: parseList(opts.engines) ?? [],
3021
2032
  outDir: opts.out,
3022
- packageDir,
3023
- mcpServers,
3024
- withStopHook: opts.stopHook !== false
2033
+ packageDir
3025
2034
  });
3026
2035
  process.stdout.write(`rendered ${result.filesWritten.length} files to ${opts.out}
3027
2036
  `);
3028
2037
  for (const w of result.warnings) process.stderr.write(`warning: ${w}
3029
2038
  `);
3030
2039
  });
3031
- program.command("stop-hook").description(
3032
- "Stop-hook entrypoint invoked by each engine's hook config \u2014 runs lint and decides whether to inject the report into the running session, terminate, or passthrough"
3033
- ).requiredOption("--engine <engine>", "claude | codex | opencode").option("--cwd <dir>", "repo root", ".").action((opts) => {
3034
- const result = stopHookCommandFromStdin({
3035
- engine: opts.engine,
3036
- cwd: opts.cwd
3037
- });
3038
- if (result.stdout) process.stdout.write(result.stdout);
3039
- if (result.stderr) process.stderr.write(result.stderr);
3040
- process.exit(result.exitCode);
2040
+ program.command("stop-hook", { hidden: true }).description("deprecated no-op kept for Stop hook entries written by 1.x").option("--engine <engine>").option("--cwd <dir>").action(() => {
2041
+ process.stderr.write(
2042
+ "vaubaan-harness stop-hook was removed in 2.0: remove this entry from your engine settings and run `npx @vaubaan/harness lint` in CI and pre-commit instead\n"
2043
+ );
2044
+ process.exit(0);
3041
2045
  });
3042
2046
  program.parseAsync(process.argv).catch((err) => {
3043
2047
  process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}