@vaubaan/harness 1.3.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/init.js CHANGED
@@ -1,23 +1,131 @@
1
1
  // src/cli/init.ts
2
- import { existsSync as existsSync6, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
3
- import { dirname as dirname3, join as join7, resolve as resolve3 } from "path";
2
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
3
+ import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
4
+
5
+ // src/cli/managed-paths.ts
6
+ import { lstatSync, realpathSync, statSync } from "fs";
7
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from "path";
8
+ var MANAGED_FILES = /* @__PURE__ */ new Set(["AGENTS.md", "CLAUDE.md", ".harness-manifest.json"]);
9
+ var RELEASED_PATHS = [
10
+ ".mcp.json",
11
+ ".codex/config.toml",
12
+ ".opencode/opencode.json",
13
+ ".opencode/mcp.json",
14
+ ".claude/settings.json",
15
+ ".codex/hooks.json"
16
+ ];
17
+ var MANAGED_DIRECTORIES = [
18
+ ".claude/agents/",
19
+ ".claude/commands/",
20
+ ".claude/skills/",
21
+ ".codex/agents/",
22
+ ".codex/commands/",
23
+ ".codex/skills/",
24
+ ".agents/skills/",
25
+ ".opencode/agents/",
26
+ ".opencode/commands/",
27
+ ".opencode/skills/",
28
+ ".opencode/plugins/"
29
+ ];
30
+ function canonicalTargetRoot(root) {
31
+ let ancestor = resolve(root);
32
+ const missing = [];
33
+ while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
34
+ missing.unshift(basename(ancestor));
35
+ ancestor = dirname(ancestor);
36
+ }
37
+ const canonical = realpathSync(ancestor);
38
+ if (!statSync(canonical).isDirectory()) {
39
+ throw new Error(`harness target is not a directory: ${root}`);
40
+ }
41
+ return join(canonical, ...missing);
42
+ }
43
+ function assertManagedLocation(path) {
44
+ const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
45
+ if (isAbsolute(path) || win32.isAbsolute(path) || path.includes("\\") || path.includes("\0") || invalidSegment) {
46
+ throw new Error(`unsafe harness path: ${path}`);
47
+ }
48
+ if (!MANAGED_FILES.has(path) && !MANAGED_DIRECTORIES.some((prefix) => path.startsWith(prefix))) {
49
+ throw new Error(`path is outside harness-managed locations: ${path}`);
50
+ }
51
+ }
52
+ function assertNoSymbolicComponents(root, path) {
53
+ const parts = path.split("/");
54
+ let current = root;
55
+ for (const [index, part] of parts.entries()) {
56
+ current = join(current, part);
57
+ const info = lstatSync(current, { throwIfNoEntry: false });
58
+ if (!info) return;
59
+ if (info.isSymbolicLink()) {
60
+ throw new Error(`symbolic link in harness path: ${path}`);
61
+ }
62
+ const isLeaf = index === parts.length - 1;
63
+ if (isLeaf ? !info.isFile() : !info.isDirectory()) {
64
+ throw new Error(`unexpected file type in harness path: ${path}`);
65
+ }
66
+ }
67
+ }
68
+ function assertManagedPaths(root, files) {
69
+ for (const path of files) assertManagedLocation(path);
70
+ const canonicalRoot2 = canonicalTargetRoot(root);
71
+ for (const path of files) assertNoSymbolicComponents(canonicalRoot2, path);
72
+ }
73
+
74
+ // src/cli/manifest.ts
75
+ import { createHash } from "crypto";
76
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "fs";
77
+ import { join as join2 } from "path";
78
+ import { z } from "zod";
79
+
80
+ // src/version.ts
81
+ var VERSION = "2.0.0";
82
+
83
+ // src/cli/manifest.ts
84
+ var MANIFEST_FILENAME = ".harness-manifest.json";
85
+ var MANIFEST_VERSION = "6";
86
+ var ManifestSchema = z.object({
87
+ version: z.enum(["4", "5", MANIFEST_VERSION]),
88
+ engines: z.array(z.string()),
89
+ renderedAt: z.string(),
90
+ files: z.array(z.string()),
91
+ harnessVersion: z.string().optional(),
92
+ overridesDir: z.string().optional(),
93
+ fileHashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)).optional(),
94
+ preservedFiles: z.array(z.string()).optional()
95
+ });
96
+ function manifestPath(targetDir) {
97
+ return join2(targetDir, MANIFEST_FILENAME);
98
+ }
99
+ function hashContent(content) {
100
+ return createHash("sha256").update(content).digest("hex");
101
+ }
102
+ function readManifest(targetDir) {
103
+ assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
104
+ const path = manifestPath(targetDir);
105
+ if (!existsSync(path)) return null;
106
+ const raw = JSON.parse(readFileSync(path, "utf8"));
107
+ return ManifestSchema.parse(raw);
108
+ }
109
+
110
+ // src/cli/plan-render.ts
111
+ import { existsSync as existsSync3 } from "fs";
112
+ import { dirname as dirname2, join as join4, resolve as resolve2 } from "path";
4
113
  import { fileURLToPath } from "url";
5
114
 
6
115
  // src/loader.ts
7
- import { existsSync, readFileSync as readFileSync2 } from "fs";
8
- import { join } from "path";
116
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
117
+ import { join as join3 } from "path";
9
118
  import fg from "fast-glob";
10
- import { z as z2 } from "zod";
119
+ import { z as z3 } from "zod";
11
120
 
12
121
  // src/parser/common.ts
13
- import { readFileSync } from "fs";
122
+ import { readFileSync as readFileSync2 } from "fs";
14
123
  import matter from "gray-matter";
15
124
 
16
125
  // src/parser/schemas.ts
17
- import { z } from "zod";
126
+ import { z as z2 } from "zod";
18
127
 
19
128
  // src/types.ts
20
- var AGENT_IDS = ["coding", "review", "merge", "planning"];
21
129
  var ENGINES = ["claude-code", "codex-cli", "opencode"];
22
130
  var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
23
131
  var CAPABILITIES_MATRIX = {
@@ -30,41 +138,36 @@ var DEGRADED_CAPABILITIES = {
30
138
  };
31
139
 
32
140
  // src/parser/schemas.ts
33
- var IdSchema = z.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
34
- var SkillFrontmatterSchema = z.object({
141
+ var IdSchema = z2.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
142
+ var SkillFrontmatterSchema = z2.object({
35
143
  id: IdSchema,
36
- description: z.string().min(1),
37
- engines: z.array(z.enum(ENGINES)).min(1).optional(),
38
- requires: z.array(z.enum(CAPABILITIES)).optional(),
39
- tags: z.array(z.string()).optional()
144
+ description: z2.string().min(1),
145
+ engines: z2.array(z2.enum(ENGINES)).min(1).optional(),
146
+ requires: z2.array(z2.enum(CAPABILITIES)).optional(),
147
+ tags: z2.array(z2.string()).optional()
40
148
  }).strict();
41
- var CmdArgEnumSchema = z.object({
42
- name: z.string().min(1),
43
- type: z.literal("enum"),
44
- values: z.array(z.string()).min(1),
45
- default: z.string().optional()
149
+ var CmdArgEnumSchema = z2.object({
150
+ name: z2.string().min(1),
151
+ type: z2.literal("enum"),
152
+ values: z2.array(z2.string()).min(1),
153
+ default: z2.string().optional()
46
154
  }).strict();
47
- var CmdArgStringSchema = z.object({
48
- name: z.string().min(1),
49
- type: z.literal("string"),
50
- default: z.string().optional()
155
+ var CmdArgStringSchema = z2.object({
156
+ name: z2.string().min(1),
157
+ type: z2.literal("string"),
158
+ default: z2.string().optional()
51
159
  }).strict();
52
- var CmdArgSchema = z.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
53
- var CmdFrontmatterSchema = z.object({
160
+ var CmdArgSchema = z2.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
161
+ var CmdFrontmatterSchema = z2.object({
54
162
  id: IdSchema,
55
- trigger: z.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
163
+ trigger: z2.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
56
164
  invokes_skill: IdSchema,
57
- args: z.array(CmdArgSchema).optional(),
58
- description: z.string().min(1)
59
- }).strict();
60
- var AgentFrontmatterSchema = z.object({
61
- id: z.enum(AGENT_IDS),
62
- description: z.string().min(1)
165
+ args: z2.array(CmdArgSchema).optional(),
166
+ description: z2.string().min(1)
63
167
  }).strict();
64
168
  var Schemas = {
65
169
  Skill: SkillFrontmatterSchema,
66
- Cmd: CmdFrontmatterSchema,
67
- Agent: AgentFrontmatterSchema
170
+ Cmd: CmdFrontmatterSchema
68
171
  };
69
172
  var ParseError = class extends Error {
70
173
  constructor(file, issues) {
@@ -93,11 +196,6 @@ function parseWithSchema(filePath, source, schema) {
93
196
  };
94
197
  }
95
198
 
96
- // src/parser/agent.ts
97
- function parseAgent(filePath, source) {
98
- return parseWithSchema(filePath, source, Schemas.Agent);
99
- }
100
-
101
199
  // src/parser/cmd.ts
102
200
  function parseCmd(filePath, source) {
103
201
  return parseWithSchema(filePath, source, Schemas.Cmd);
@@ -115,39 +213,35 @@ function parseYAML(source) {
115
213
  }
116
214
 
117
215
  // src/loader.ts
118
- var DisableYamlSchema = z2.object({ disable: z2.array(z2.string()).optional() }).passthrough();
216
+ var DisableYamlSchema = z3.object({ disable: z3.array(z3.string()).optional() }).passthrough();
119
217
  function loadHarness(packageDir, opts = {}) {
120
- const agentsDir = opts.agentsDir ?? join(packageDir, "agents");
121
- const skillsDir = opts.skillsDir ?? join(packageDir, "skills");
122
- const commandsDir = opts.commandsDir ?? join(packageDir, "commands");
123
- const agentFiles = fg.sync("*.agent.md", { cwd: agentsDir, absolute: true });
218
+ const skillsDir = opts.skillsDir ?? join3(packageDir, "skills");
219
+ const commandsDir = opts.commandsDir ?? join3(packageDir, "commands");
124
220
  const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
125
221
  const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
126
222
  return {
127
- agents: agentFiles.map((f) => parseAgent(f, readFileSync2(f, "utf8"))),
128
- skills: skillFiles.map((f) => parseSkill(f, readFileSync2(f, "utf8"))),
129
- cmds: cmdFiles.map((f) => parseCmd(f, readFileSync2(f, "utf8")))
223
+ skills: skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8"))),
224
+ cmds: cmdFiles.map((f) => parseCmd(f, readFileSync3(f, "utf8")))
130
225
  };
131
226
  }
132
227
  function loadProjectSkills(targetDir) {
133
- const skillsDir = join(targetDir, "docs", "skills");
134
- if (!existsSync(skillsDir)) return [];
228
+ const skillsDir = join3(targetDir, "docs", "skills");
229
+ if (!existsSync2(skillsDir)) return [];
135
230
  const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
136
- return skillFiles.map((f) => parseSkill(f, readFileSync2(f, "utf8")));
231
+ return skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8")));
137
232
  }
138
233
  function loadOverrides(worktreeDir) {
139
- const overridesDir = join(worktreeDir, ".harness-overrides");
140
- if (!existsSync(overridesDir)) return void 0;
234
+ const overridesDir = join3(worktreeDir, ".harness-overrides");
235
+ if (!existsSync2(overridesDir)) return void 0;
141
236
  const added = loadHarness(overridesDir, {
142
- agentsDir: join(overridesDir, "agents"),
143
- skillsDir: join(overridesDir, "skills"),
144
- commandsDir: join(overridesDir, "commands")
237
+ skillsDir: join3(overridesDir, "skills"),
238
+ commandsDir: join3(overridesDir, "commands")
145
239
  });
146
- const disablePath = join(overridesDir, "disable.yaml");
240
+ const disablePath = join3(overridesDir, "disable.yaml");
147
241
  let disable = [];
148
- if (existsSync(disablePath)) {
242
+ if (existsSync2(disablePath)) {
149
243
  try {
150
- const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync2(disablePath, "utf8")));
244
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync3(disablePath, "utf8")));
151
245
  if (parsed.success && parsed.data.disable) {
152
246
  disable = parsed.data.disable;
153
247
  }
@@ -157,28 +251,8 @@ function loadOverrides(worktreeDir) {
157
251
  return { add: added, disable };
158
252
  }
159
253
 
160
- // src/mcp.ts
161
- var MCP_SERVER_IDS = ["context7"];
162
- var MCP_SERVERS = {
163
- context7: {
164
- id: "context7",
165
- description: "Upstash Context7 \u2014 fetches up-to-date library docs via resolve-library-id + get-library-docs.",
166
- command: "npx",
167
- args: ["-y", "@upstash/context7-mcp"]
168
- }
169
- };
170
- function resolveMcpIds(requested) {
171
- return requested.map((id) => {
172
- if (!MCP_SERVER_IDS.includes(id)) {
173
- throw new Error(`unknown MCP server: ${id} (expected one of ${MCP_SERVER_IDS.join(", ")})`);
174
- }
175
- return id;
176
- });
177
- }
178
-
179
254
  // src/renderers/common.ts
180
255
  import { stringify as yamlStringify } from "yaml";
181
- var STOP_HOOK_PACKAGE = "@vaubaan/harness";
182
256
  function checkSkillCapabilities(skill, engine) {
183
257
  const blockingWarnings = [];
184
258
  const degradedWarnings = [];
@@ -209,39 +283,6 @@ ${rendered}
209
283
  ---
210
284
  `;
211
285
  }
212
- var SCALAR_NEEDS_QUOTE = /[^a-zA-Z0-9_./-]/;
213
- function tomlEscapeString(s) {
214
- return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
215
- }
216
- function tomlValue(v) {
217
- if (Array.isArray(v)) {
218
- return `[${v.map((x) => tomlValue(x)).join(", ")}]`;
219
- }
220
- if (typeof v === "string") {
221
- if (v.includes("\n")) return tomlEscapeString(v);
222
- return SCALAR_NEEDS_QUOTE.test(v) ? tomlEscapeString(v) : `"${v}"`;
223
- }
224
- if (typeof v === "boolean" || typeof v === "number") {
225
- return String(v);
226
- }
227
- return tomlEscapeString(String(v));
228
- }
229
- function tomlMultilineString(s) {
230
- const escaped = s.replace(/\\/g, "\\\\").replace(/"""/g, '""\\"');
231
- return `"""
232
- ${escaped}
233
- """`;
234
- }
235
- function tomlQuoteString(s) {
236
- return tomlValue(s);
237
- }
238
- function tomlInlineArray(items) {
239
- return tomlValue([...items]);
240
- }
241
- function tomlInlineTable(table) {
242
- const entries = Object.entries(table).map(([k, v]) => `${k} = ${tomlValue(v)}`);
243
- return `{ ${entries.join(", ")} }`;
244
- }
245
286
  function frontmatterDataForSkill(skill) {
246
287
  const data = {
247
288
  name: skill.meta.id,
@@ -266,11 +307,7 @@ function frontmatterDataForCmd(cmd) {
266
307
  }
267
308
  return data;
268
309
  }
269
- function buildAgentBody(agent) {
270
- return `${agent.body.trim()}
271
- `;
272
- }
273
- function buildUmbrellaBody(_agents, extras) {
310
+ function buildUmbrellaBody(extras) {
274
311
  const triggerBySkill = new Map(
275
312
  extras.availableCommands.map((c) => [c.meta.invokes_skill, c.meta.trigger])
276
313
  );
@@ -291,7 +328,7 @@ function buildUmbrellaBody(_agents, extras) {
291
328
  "- `docs/handbook/<feature>.md` \u2014 *how it actually works* today.",
292
329
  "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives.",
293
330
  "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 core scenarios.",
294
- "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release.",
331
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release. How this team works: follow it.",
295
332
  ...extras.hasProjectSkills ? ["- `docs/skills/*.skill.md` \u2014 the project's domain skills."] : [],
296
333
  ...extras.hasQualityDoc ? [
297
334
  "- `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."
@@ -304,7 +341,13 @@ function buildUmbrellaBody(_agents, extras) {
304
341
  "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
305
342
  "- Implicit structural decision in your changes \u2192 an ADR (`/decision`).",
306
343
  "- Changed feature behavior \u2192 update the matching handbook (`/handbook`).",
307
- "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on."
344
+ "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on.",
345
+ "",
346
+ "## Checks",
347
+ "",
348
+ "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.",
349
+ "",
350
+ "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."
308
351
  ];
309
352
  if (skillLines.length > 0) {
310
353
  sections.push("", "## Doc-skills", "", skillLines.join("\n"));
@@ -345,60 +388,11 @@ ${cmd.body}
345
388
  files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
346
389
  warnings: []
347
390
  };
348
- },
349
- renderAgents(agents) {
350
- const files = [];
351
- for (const agent of agents) {
352
- const subagentFrontmatter = yamlFrontmatter({
353
- name: agent.meta.id,
354
- description: agent.meta.description
355
- });
356
- const body = buildAgentBody(agent);
357
- const content = `${subagentFrontmatter}
358
- ${body}`;
359
- files.push({ path: `${BASE}/agents/${agent.meta.id}.md`, content });
360
- }
361
- return { files, warnings: [] };
362
- },
363
- renderMcp(servers) {
364
- if (servers.length === 0) return { files: [], warnings: [] };
365
- const mcpServers = {};
366
- for (const s of servers) {
367
- const entry = { command: s.command, args: [...s.args] };
368
- if (s.env) entry.env = s.env;
369
- mcpServers[s.id] = entry;
370
- }
371
- const content = `${JSON.stringify({ mcpServers }, null, 2)}
372
- `;
373
- return { files: [{ path: ".mcp.json", content }], warnings: [] };
374
- },
375
- renderStopHook() {
376
- const settings = {
377
- hooks: {
378
- Stop: [
379
- {
380
- matcher: "",
381
- hooks: [
382
- {
383
- type: "command",
384
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine claude`
385
- }
386
- ]
387
- }
388
- ]
389
- }
390
- };
391
- return {
392
- files: [{ path: `${BASE}/settings.json`, content: `${JSON.stringify(settings, null, 2)}
393
- ` }],
394
- warnings: []
395
- };
396
391
  }
397
392
  };
398
393
 
399
394
  // src/renderers/codex-cli.ts
400
395
  var ENGINE2 = "codex-cli";
401
- var BASE2 = ".codex";
402
396
  var SKILLS_BASE = ".agents/skills";
403
397
  var codexCliRenderer = {
404
398
  engine: ENGINE2,
@@ -424,62 +418,12 @@ ${skill.body}
424
418
  // Codex custom prompts are deprecated in favour of skills: nothing to render.
425
419
  renderCmd(_cmd) {
426
420
  return { files: [], warnings: [] };
427
- },
428
- renderAgents(agents) {
429
- const files = [];
430
- for (const agent of agents) {
431
- const content = [
432
- `name = ${tomlQuoteString(agent.meta.id)}`,
433
- `description = ${tomlQuoteString(agent.meta.description)}`,
434
- `developer_instructions = ${tomlMultilineString(buildAgentBody(agent).trimEnd())}`,
435
- ""
436
- ].join("\n");
437
- files.push({ path: `${BASE2}/agents/${agent.meta.id}.toml`, content });
438
- }
439
- return { files, warnings: [] };
440
- },
441
- renderMcp(servers) {
442
- if (servers.length === 0) return { files: [], warnings: [] };
443
- const blocks = [];
444
- for (const s of servers) {
445
- const lines = [
446
- `[mcp_servers.${s.id}]`,
447
- `command = ${tomlQuoteString(s.command)}`,
448
- `args = ${tomlInlineArray([...s.args])}`
449
- ];
450
- if (s.env) lines.push(`env = ${tomlInlineTable(s.env)}`);
451
- blocks.push(lines.join("\n"));
452
- }
453
- const content = `${blocks.join("\n\n")}
454
- `;
455
- return { files: [{ path: `${BASE2}/config.toml`, content }], warnings: [] };
456
- },
457
- renderStopHook() {
458
- const hooks = {
459
- hooks: {
460
- Stop: [
461
- {
462
- hooks: [
463
- {
464
- type: "command",
465
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine codex`
466
- }
467
- ]
468
- }
469
- ]
470
- }
471
- };
472
- return {
473
- files: [{ path: `${BASE2}/hooks.json`, content: `${JSON.stringify(hooks, null, 2)}
474
- ` }],
475
- warnings: []
476
- };
477
421
  }
478
422
  };
479
423
 
480
424
  // src/renderers/opencode.ts
481
425
  var ENGINE3 = "opencode";
482
- var BASE3 = ".opencode";
426
+ var BASE2 = ".opencode";
483
427
  var opencodeRenderer = {
484
428
  engine: ENGINE3,
485
429
  renderSkill(skill) {
@@ -497,7 +441,7 @@ var opencodeRenderer = {
497
441
  ${skill.body}
498
442
  `;
499
443
  return {
500
- files: [{ path: `${BASE3}/skills/${skill.meta.id}/SKILL.md`, content }],
444
+ files: [{ path: `${BASE2}/skills/${skill.meta.id}/SKILL.md`, content }],
501
445
  warnings: check.degradedWarnings
502
446
  };
503
447
  },
@@ -506,106 +450,7 @@ ${skill.body}
506
450
  ${cmd.body}
507
451
  `;
508
452
  return {
509
- files: [{ path: `${BASE3}/commands/${cmd.meta.id}.md`, content }],
510
- warnings: []
511
- };
512
- },
513
- renderAgents(agents) {
514
- const files = [];
515
- for (const agent of agents) {
516
- const fm = yamlFrontmatter({
517
- description: agent.meta.description,
518
- mode: "all"
519
- });
520
- const body = buildAgentBody(agent);
521
- files.push({ path: `${BASE3}/agents/${agent.meta.id}.md`, content: `${fm}
522
- ${body}` });
523
- }
524
- return { files, warnings: [] };
525
- },
526
- renderMcp(servers) {
527
- if (servers.length === 0) return { files: [], warnings: [] };
528
- const mcp = {};
529
- for (const s of servers) {
530
- const entry = {
531
- type: "local",
532
- command: [s.command, ...s.args],
533
- enabled: true
534
- };
535
- if (s.env) entry.environment = s.env;
536
- mcp[s.id] = entry;
537
- }
538
- const config = { $schema: "https://opencode.ai/config.json", mcp };
539
- const content = `${JSON.stringify(config, null, 2)}
540
- `;
541
- return { files: [{ path: `${BASE3}/opencode.json`, content }], warnings: [] };
542
- },
543
- renderStopHook() {
544
- const content = `import { spawnSync } from "node:child_process";
545
-
546
- // Runs the harness lint and returns the report to inject, or "" when the
547
- // turn may end.
548
- const lintReport = (directory, sessionID) => {
549
- const r = spawnSync(
550
- "npx",
551
- ["-y", "${STOP_HOOK_PACKAGE}", "stop-hook", "--engine", "opencode", "--cwd", directory],
552
- { input: JSON.stringify({ sessionID }), encoding: "utf-8" },
553
- );
554
- const report = (r.stderr ?? "").trim();
555
- return r.status === 2 ? report : "";
556
- };
557
-
558
- // OpenCode 1.x entry point, exposed as server() below.
559
- const HarnessStopHook = async ({ client, directory }) => ({
560
- event: async ({ event }) => {
561
- if (event.type !== "session.idle") return;
562
- const sessionID = event.properties?.sessionID;
563
- if (!sessionID) return;
564
- const report = lintReport(directory, sessionID);
565
- if (report === "") return;
566
- // OpenCode defaults to its build agent when a prompt omits agent.
567
- // Preserve the last conversation persona, excluding compaction summaries.
568
- const history = await client.session.messages({ path: { id: sessionID } }).catch(() => undefined);
569
- if (history?.error || !Array.isArray(history?.data)) return;
570
- const current = history.data.findLast(({ info }) =>
571
- (info.role === "user" || (info.role === "assistant" && !info.summary)) &&
572
- typeof info.agent === "string" && info.agent.trim() !== "",
573
- );
574
- if (!current) return;
575
- await client.session.prompt({
576
- path: { id: sessionID },
577
- body: { agent: current.info.agent, parts: [{ type: "text", text: report }] },
578
- });
579
- },
580
- });
581
-
582
- // One default export for both majors: OpenCode 1.x calls server(),
583
- // OpenCode 2.x calls setup(). A V2 session keeps its agent, so the report
584
- // is sent without naming the persona.
585
- export default {
586
- id: "vaubaan-harness-stop-hook",
587
- server: HarnessStopHook,
588
- setup(context) {
589
- const directory = context.location.directory;
590
- const controller = new AbortController();
591
- const listen = async () => {
592
- for await (const event of context.event.subscribe({ signal: controller.signal })) {
593
- if (event.type !== "session.idle") continue;
594
- if (event.location?.directory && event.location.directory !== directory) continue;
595
- const sessionID = event.data?.sessionID;
596
- if (!sessionID) continue;
597
- const report = lintReport(directory, sessionID);
598
- if (report === "") continue;
599
- await context.session.prompt({ sessionID, text: report }).catch(() => undefined);
600
- }
601
- };
602
- listen().catch(() => undefined);
603
- return () => controller.abort();
604
- },
605
- };
606
- `;
607
- return {
608
- files: [{ path: `${BASE3}/plugins/harness-stop-hook.ts`, content }],
453
+ files: [{ path: `${BASE2}/commands/${cmd.meta.id}.md`, content }],
609
454
  warnings: []
610
455
  };
611
456
  }
@@ -644,7 +489,6 @@ function removeByIds(items, disabled) {
644
489
  function applyOverrides(harness, overrides) {
645
490
  const disabled = overrides?.disable ?? [];
646
491
  return {
647
- agents: removeByIds(mergeById(harness.agents, overrides?.add?.agents), disabled),
648
492
  skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
649
493
  cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
650
494
  };
@@ -660,58 +504,37 @@ function render(input) {
660
504
  }
661
505
  const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
662
506
  const harness = applyOverrides(base, input.overrides);
663
- if (harness.agents.length === 0) {
664
- throw new RenderError("No agents found in harness");
665
- }
666
507
  const files = [];
667
508
  const warnings = [];
668
509
  const exposedSkills = /* @__PURE__ */ new Map();
669
510
  const exposedCmds = /* @__PURE__ */ new Map();
670
511
  for (const engine of opencodeLast(engines)) {
671
512
  const renderer = getRenderer(engine);
672
- const renderedSkills = [];
513
+ const renderedSkillIds = /* @__PURE__ */ new Set();
673
514
  for (const skill of harness.skills) {
674
515
  const result = renderer.renderSkill(skill);
675
516
  warnings.push(...result.warnings);
676
517
  if (result.files.length > 0) {
677
518
  const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
678
519
  if (!alreadyVisible) files.push(...result.files);
679
- renderedSkills.push(skill);
520
+ renderedSkillIds.add(skill.meta.id);
680
521
  exposedSkills.set(skill.meta.id, skill);
681
522
  }
682
523
  }
683
- const renderedSkillIds = new Set(renderedSkills.map((s) => s.meta.id));
684
- const renderedCmds = [];
685
524
  for (const cmd of harness.cmds) {
686
525
  if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
687
526
  const result = renderer.renderCmd(cmd);
688
527
  warnings.push(...result.warnings);
689
528
  if (result.files.length > 0) {
690
529
  files.push(...result.files);
691
- renderedCmds.push(cmd);
692
530
  exposedCmds.set(cmd.meta.id, cmd);
693
531
  }
694
532
  }
695
- const agentsResult = renderer.renderAgents(harness.agents);
696
- warnings.push(...agentsResult.warnings);
697
- files.push(...agentsResult.files);
698
- if (input.mcpServers && input.mcpServers.length > 0) {
699
- const specs = input.mcpServers.map((id) => MCP_SERVERS[id]);
700
- const mcpResult = renderer.renderMcp(specs);
701
- warnings.push(...mcpResult.warnings);
702
- files.push(...mcpResult.files);
703
- }
704
- if (input.withStopHook !== false) {
705
- const hookResult = renderer.renderStopHook();
706
- warnings.push(...hookResult.warnings);
707
- files.push(...hookResult.files);
708
- }
709
533
  }
710
- const hasProjectSkills = (input.projectSkills?.length ?? 0) > 0;
711
- const umbrellaContent = buildUmbrellaBody(harness.agents, {
534
+ const umbrellaContent = buildUmbrellaBody({
712
535
  availableSkills: Array.from(exposedSkills.values()),
713
536
  availableCommands: Array.from(exposedCmds.values()),
714
- hasProjectSkills,
537
+ hasProjectSkills: (input.projectSkills?.length ?? 0) > 0,
715
538
  hasQualityDoc: input.hasQualityDoc === true
716
539
  });
717
540
  files.push({ path: "AGENTS.md", content: umbrellaContent });
@@ -721,320 +544,368 @@ function render(input) {
721
544
  return { files, warnings };
722
545
  }
723
546
 
724
- // src/cli/managed-paths.ts
725
- import { lstatSync, realpathSync, statSync } from "fs";
726
- import { basename, dirname, isAbsolute, join as join2, resolve, win32 } from "path";
727
- var MANAGED_FILES = /* @__PURE__ */ new Set([
728
- "AGENTS.md",
729
- "CLAUDE.md",
730
- ".mcp.json",
731
- ".harness-manifest.json",
732
- ".claude/settings.json",
733
- ".codex/config.toml",
734
- ".codex/hooks.json",
735
- ".opencode/opencode.json",
736
- ".opencode/mcp.json"
737
- ]);
738
- var MANAGED_DIRECTORIES = [
739
- ".claude/agents/",
740
- ".claude/commands/",
741
- ".claude/skills/",
742
- ".codex/agents/",
743
- ".codex/commands/",
744
- ".codex/skills/",
745
- ".agents/skills/",
746
- ".opencode/agents/",
747
- ".opencode/commands/",
748
- ".opencode/skills/",
749
- ".opencode/plugins/"
750
- ];
751
- function canonicalTargetRoot(root) {
752
- let ancestor = resolve(root);
753
- const missing = [];
754
- while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
755
- missing.unshift(basename(ancestor));
756
- ancestor = dirname(ancestor);
757
- }
758
- const canonical = realpathSync(ancestor);
759
- if (!statSync(canonical).isDirectory()) {
760
- throw new Error(`harness target is not a directory: ${root}`);
547
+ // src/cli/plan-render.ts
548
+ var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
549
+ function resolveEngineList(requested) {
550
+ if (!requested || requested.length === 0) {
551
+ throw new Error(
552
+ `no engine selected: pass --engines=<list> with one or more of ${ENGINES.join(", ")}`
553
+ );
761
554
  }
762
- return join2(canonical, ...missing);
555
+ const engines = requested.map((e) => {
556
+ if (!ENGINES.includes(e)) {
557
+ throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
558
+ }
559
+ return e;
560
+ });
561
+ return [...new Set(engines)];
763
562
  }
764
- function assertManagedLocation(path) {
765
- const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
766
- if (isAbsolute(path) || win32.isAbsolute(path) || path.includes("\\") || path.includes("\0") || invalidSegment) {
767
- throw new Error(`unsafe harness path: ${path}`);
563
+ function defaultPackageDir() {
564
+ const here = dirname2(fileURLToPath(import.meta.url));
565
+ if (existsSync3(join4(here, "skills"))) return here;
566
+ return resolve2(here, "..");
567
+ }
568
+ function planInit(args) {
569
+ const engines = resolveEngineList(args.engines);
570
+ const packageDir = args.packageDir ?? defaultPackageDir();
571
+ const harness = loadHarness(packageDir);
572
+ const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
573
+ const projectSkills = loadProjectSkills(args.targetDir);
574
+ const hasQualityDoc = existsSync3(join4(args.targetDir, QUALITY_DOC_PATH));
575
+ const output = render({ harness, engines, overrides, projectSkills, hasQualityDoc });
576
+ return { engines, output };
577
+ }
578
+
579
+ // src/cli/uninstall.ts
580
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, rmdirSync, unlinkSync } from "fs";
581
+ import { dirname as dirname3, join as join5, relative, resolve as resolve3 } from "path";
582
+ function pruneEmptyDirs(root, leaves) {
583
+ const candidates = /* @__PURE__ */ new Set();
584
+ for (const leaf of leaves) {
585
+ let cur = leaf;
586
+ while (cur !== root && cur.startsWith(`${root}/`)) {
587
+ candidates.add(cur);
588
+ cur = dirname3(cur);
589
+ }
768
590
  }
769
- if (!MANAGED_FILES.has(path) && !MANAGED_DIRECTORIES.some((prefix) => path.startsWith(prefix))) {
770
- throw new Error(`path is outside harness-managed locations: ${path}`);
591
+ const pruned = [];
592
+ const sorted = [...candidates].sort((a, b) => b.length - a.length);
593
+ for (const dir of sorted) {
594
+ if (!existsSync4(dir)) continue;
595
+ if (readdirSync(dir).length > 0) continue;
596
+ rmdirSync(dir);
597
+ pruned.push(relative(root, dir));
771
598
  }
599
+ return pruned;
772
600
  }
773
- function assertNoSymbolicComponents(root, path) {
774
- const parts = path.split("/");
775
- let current = root;
776
- for (const [index, part] of parts.entries()) {
777
- current = join2(current, part);
778
- const info = lstatSync(current, { throwIfNoEntry: false });
779
- if (!info) return;
780
- if (info.isSymbolicLink()) {
781
- throw new Error(`symbolic link in harness path: ${path}`);
782
- }
783
- const isLeaf = index === parts.length - 1;
784
- if (isLeaf ? !info.isFile() : !info.isDirectory()) {
785
- throw new Error(`unexpected file type in harness path: ${path}`);
601
+
602
+ // src/cli/update-transaction.ts
603
+ import { createHash as createHash2, randomUUID } from "crypto";
604
+ import {
605
+ chmodSync as chmodSync2,
606
+ closeSync,
607
+ fsyncSync,
608
+ lstatSync as lstatSync2,
609
+ mkdirSync,
610
+ openSync,
611
+ readFileSync as readFileSync5,
612
+ readdirSync as readdirSync2,
613
+ realpathSync as realpathSync2,
614
+ rmdirSync as rmdirSync2,
615
+ unlinkSync as unlinkSync2,
616
+ writeFileSync as writeFileSync2
617
+ } from "fs";
618
+ import { homedir } from "os";
619
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve4, sep } from "path";
620
+ var MANIFEST_PATH = ".harness-manifest.json";
621
+ var PRIVATE_FILES = /* @__PURE__ */ new Set([MANIFEST_PATH]);
622
+ function canonicalRoot(root) {
623
+ let ancestor = resolve4(root);
624
+ const missing = [];
625
+ while (!lstatSync2(ancestor, { throwIfNoEntry: false })) {
626
+ missing.unshift(basename2(ancestor));
627
+ ancestor = dirname4(ancestor);
628
+ }
629
+ return join6(realpathSync2(ancestor), ...missing);
630
+ }
631
+ function contains(parent, child) {
632
+ const path = relative2(parent, child);
633
+ return path === "" || !isAbsolute2(path) && path !== ".." && !path.startsWith(`..${sep}`);
634
+ }
635
+ function assertBackupLocation(root, backup) {
636
+ if (contains(root, backup) || contains(backup, root)) {
637
+ throw new Error(`update backup must be outside the target project: ${backup}`);
638
+ }
639
+ const ancestors = [];
640
+ for (let path = backup; ; path = dirname4(path)) {
641
+ ancestors.unshift(path);
642
+ if (dirname4(path) === path) break;
643
+ }
644
+ for (const path of ancestors) {
645
+ const info = lstatSync2(path, { throwIfNoEntry: false });
646
+ if (!info) continue;
647
+ if (info.isSymbolicLink() || !info.isDirectory()) {
648
+ throw new Error(`unsafe update backup directory: ${path}`);
786
649
  }
787
650
  }
651
+ if (lstatSync2(backup, { throwIfNoEntry: false })) {
652
+ throw new Error(`update backup directory already exists: ${backup}`);
653
+ }
788
654
  }
789
- function assertManagedPaths(root, files) {
790
- for (const path of files) assertManagedLocation(path);
791
- const canonicalRoot = canonicalTargetRoot(root);
792
- for (const path of files) assertNoSymbolicComponents(canonicalRoot, path);
793
- }
794
-
795
- // src/cli/manifest.ts
796
- import { createHash } from "crypto";
797
- import { chmodSync, existsSync as existsSync4, readFileSync as readFileSync5, writeFileSync } from "fs";
798
- import { join as join5 } from "path";
799
- import { z as z5 } from "zod";
800
-
801
- // src/version.ts
802
- var VERSION = "1.3.2";
803
-
804
- // src/cli/opencode-config.ts
805
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
806
- import { join as join3 } from "path";
807
- import { isDeepStrictEqual } from "util";
808
- import { z as z3 } from "zod";
809
- var OPENCODE_CONFIG_PATH = ".opencode/opencode.json";
810
- var OPENCODE_SCHEMA = "https://opencode.ai/config.json";
811
- var ObjectSchema = z3.record(z3.unknown());
812
- var OpenCodeConfigOwnershipSchema = z3.object({
813
- createdFile: z3.boolean(),
814
- addedMcp: z3.boolean(),
815
- addedSchema: z3.boolean(),
816
- entries: z3.record(ObjectSchema)
817
- });
818
- function parseConfig(content) {
819
- try {
820
- const config = ObjectSchema.parse(JSON.parse(content));
821
- if (Object.hasOwn(config, "mcp")) ObjectSchema.parse(config.mcp);
822
- return config;
823
- } catch {
824
- throw new Error(`invalid ${OPENCODE_CONFIG_PATH}: expected a JSON object with an MCP object`);
655
+ function createDirectories(path, created, mode = 511) {
656
+ const missing = [];
657
+ for (let current = path; !lstatSync2(current, { throwIfNoEntry: false }); current = dirname4(current)) {
658
+ missing.unshift(current);
659
+ }
660
+ for (const directory of missing) {
661
+ mkdirSync(directory, { mode });
662
+ created.push(directory);
825
663
  }
826
664
  }
827
- function removeOwnedEntries(config, ownership, warnings) {
828
- if (Object.hasOwn(config, "mcp")) {
829
- const mcp = ObjectSchema.parse(config.mcp);
830
- for (const [id, installed] of Object.entries(ownership.entries)) {
831
- if (!Object.hasOwn(mcp, id)) continue;
832
- if (isDeepStrictEqual(mcp[id], installed)) delete mcp[id];
833
- else warnings.push(`preserved modified OpenCode MCP server: ${id}`);
665
+ function writeBackupFile(path, content) {
666
+ createDirectories(dirname4(path), [], 448);
667
+ const fd = openSync(path, "wx", 384);
668
+ try {
669
+ writeFileSync2(fd, content);
670
+ fsyncSync(fd);
671
+ } finally {
672
+ closeSync(fd);
673
+ }
674
+ }
675
+ function saveSnapshot(root, paths, backup) {
676
+ const entries = [];
677
+ createDirectories(dirname4(backup), [], 448);
678
+ mkdirSync(backup, { mode: 448 });
679
+ for (const path of paths) {
680
+ const full = join6(root, path);
681
+ const info = lstatSync2(full, { throwIfNoEntry: false });
682
+ if (!info) {
683
+ entries.push({ path, exists: false });
684
+ continue;
834
685
  }
835
- config.mcp = mcp;
836
- if (ownership.addedMcp && Object.keys(mcp).length === 0) Reflect.deleteProperty(config, "mcp");
686
+ const content = readFileSync5(full);
687
+ writeBackupFile(join6(backup, "files", path), content);
688
+ entries.push({
689
+ path,
690
+ exists: true,
691
+ mode: info.mode & 4095,
692
+ sha256: createHash2("sha256").update(content).digest("hex")
693
+ });
837
694
  }
838
- if (ownership.addedSchema && config.$schema === OPENCODE_SCHEMA)
839
- Reflect.deleteProperty(config, "$schema");
695
+ writeBackupFile(
696
+ join6(backup, "snapshot.json"),
697
+ `${JSON.stringify({ version: 1, root, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries }, null, 2)}
698
+ `
699
+ );
700
+ return entries;
701
+ }
702
+ function errorMessage(error) {
703
+ return error instanceof Error ? error.message : String(error);
840
704
  }
841
- function addMissingEntries(config, desired, createdFile, warnings) {
842
- const requested = ObjectSchema.parse(parseConfig(desired.content).mcp);
843
- const mcp = ObjectSchema.parse(config.mcp ?? {});
844
- const entries = {};
845
- for (const [id, entry] of Object.entries(requested)) {
846
- if (Object.hasOwn(mcp, id)) {
847
- if (!isDeepStrictEqual(mcp[id], entry)) {
848
- warnings.push(`preserved existing OpenCode MCP server instead of replacing it: ${id}`);
705
+ function rollback(root, backup, entries, touched, createdDirectories) {
706
+ const errors = [];
707
+ for (const path of [...touched].reverse()) {
708
+ try {
709
+ assertManagedPaths(root, [path]);
710
+ const entry = entries.get(path);
711
+ const full = join6(root, path);
712
+ const current = lstatSync2(full, { throwIfNoEntry: false });
713
+ if (!entry?.exists) {
714
+ if (current) unlinkSync2(full);
715
+ continue;
849
716
  }
850
- continue;
717
+ const original = readFileSync5(join6(backup, "files", path));
718
+ if (!current || !readFileSync5(full).equals(original)) {
719
+ if (current) unlinkSync2(full);
720
+ writeFileSync2(full, original, { mode: 384 });
721
+ }
722
+ chmodSync2(full, entry.mode);
723
+ } catch (error) {
724
+ errors.push(`${path}: ${errorMessage(error)}`);
851
725
  }
852
- entries[id] = ObjectSchema.parse(entry);
853
- mcp[id] = entry;
854
726
  }
855
- if (Object.keys(entries).length === 0) return void 0;
856
- const ownership = {
857
- createdFile,
858
- addedMcp: !Object.hasOwn(config, "mcp"),
859
- addedSchema: !Object.hasOwn(config, "$schema"),
860
- entries
861
- };
862
- config.mcp = mcp;
863
- if (ownership.addedSchema) config.$schema = OPENCODE_SCHEMA;
864
- return ownership;
727
+ for (const directory of [...createdDirectories].reverse()) {
728
+ try {
729
+ if (readdirSync2(directory).length === 0) rmdirSync2(directory);
730
+ } catch (error) {
731
+ errors.push(`${directory}: ${errorMessage(error)}`);
732
+ }
733
+ }
734
+ return errors;
865
735
  }
866
- function planOpenCodeConfig(root, desired, previous) {
867
- const warnings = [];
868
- if (!desired && !previous) return { remove: false, warnings };
869
- const path = join3(root, OPENCODE_CONFIG_PATH);
870
- const existed = existsSync2(path);
871
- if (!existed && !desired) return { remove: false, warnings };
872
- const original = existed ? readFileSync3(path, "utf8") : void 0;
873
- const config = original === void 0 ? {} : parseConfig(original);
874
- const before = structuredClone(config);
875
- if (previous) removeOwnedEntries(config, previous, warnings);
876
- const createdFile = !existed || previous?.createdFile === true;
877
- const ownership = desired ? addMissingEntries(config, desired, createdFile, warnings) : void 0;
878
- if (!ownership && createdFile && Object.keys(config).length === 0) {
879
- return { remove: existed, warnings };
736
+ function applyUpdateTransaction(root, writes, removals, backupDir) {
737
+ const paths = [.../* @__PURE__ */ new Set([...removals, ...writes.map((file) => file.path)])];
738
+ assertManagedPaths(root, paths);
739
+ const target = canonicalRoot(root);
740
+ const backup = resolve4(
741
+ backupDir ?? join6(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
742
+ );
743
+ assertBackupLocation(target, backup);
744
+ let snapshot;
745
+ try {
746
+ snapshot = saveSnapshot(target, paths, backup);
747
+ } catch (error) {
748
+ throw new Error(
749
+ `could not prepare update backup at ${backup}; project unchanged: ${errorMessage(error)}`,
750
+ { cause: error }
751
+ );
880
752
  }
881
- return {
882
- remove: false,
883
- ownership,
884
- warnings,
885
- ...!existed || !isDeepStrictEqual(before, config) ? { write: { path: OPENCODE_CONFIG_PATH, content: `${JSON.stringify(config, null, 2)}
886
- ` } } : {}
887
- };
753
+ const entries = new Map(snapshot.map((entry) => [entry.path, entry]));
754
+ const touched = /* @__PURE__ */ new Set();
755
+ const createdDirectories = [];
756
+ try {
757
+ assertManagedPaths(target, paths);
758
+ for (const path of removals) {
759
+ if (!lstatSync2(join6(target, path), { throwIfNoEntry: false })) continue;
760
+ touched.add(path);
761
+ unlinkSync2(join6(target, path));
762
+ }
763
+ for (const file of writes) {
764
+ const full = join6(target, file.path);
765
+ createDirectories(dirname4(full), createdDirectories);
766
+ touched.add(file.path);
767
+ const entry = entries.get(file.path);
768
+ const mode = file.path === MANIFEST_PATH ? 384 : entry?.exists ? entry.mode : PRIVATE_FILES.has(file.path) ? 384 : 420;
769
+ if (entry?.exists && file.path === MANIFEST_PATH) chmodSync2(full, mode);
770
+ writeFileSync2(full, file.content, { mode });
771
+ if (entry?.exists) chmodSync2(full, mode);
772
+ }
773
+ } catch (error) {
774
+ const failures = rollback(target, backup, entries, touched, createdDirectories);
775
+ const restoration = failures.length > 0 ? `rollback errors: ${failures.join("; ")}` : "rollback completed";
776
+ throw new Error(`update failed; backup: ${backup}; ${restoration}: ${errorMessage(error)}`, {
777
+ cause: error
778
+ });
779
+ }
780
+ return { backupDir: backup };
888
781
  }
889
782
 
890
- // src/cli/update-config.ts
891
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
892
- import { join as join4 } from "path";
893
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
783
+ // src/cli/update.ts
784
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
785
+ import { dirname as dirname5, join as join8, resolve as resolve5 } from "path";
786
+ import { isDeepStrictEqual } from "util";
787
+
788
+ // src/cli/update-manifest.ts
789
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
790
+ import { join as join7 } from "path";
894
791
  import { z as z4 } from "zod";
895
- var ObjectSchema2 = z4.record(z4.unknown());
896
- var HookEntrySchema = z4.object({ group: ObjectSchema2, hook: ObjectSchema2 });
897
- var HookConfigOwnershipSchema = z4.object({
898
- createdFile: z4.boolean(),
899
- addedHooks: z4.boolean(),
900
- addedStop: z4.boolean(),
901
- entries: z4.array(HookEntrySchema)
792
+ var EngineSchema = z4.enum(ENGINES);
793
+ var LegacySchema = z4.object({
794
+ version: z4.enum(["1", "2", "3"]),
795
+ engine: EngineSchema.optional(),
796
+ engines: z4.array(EngineSchema).nonempty().optional(),
797
+ renderedAt: z4.string(),
798
+ files: z4.array(z4.string())
902
799
  });
903
- var HookConfigsOwnershipSchema = z4.object({
904
- ".claude/settings.json": HookConfigOwnershipSchema.optional(),
905
- ".codex/hooks.json": HookConfigOwnershipSchema.optional()
906
- }).strict();
907
800
 
908
- // src/cli/manifest.ts
909
- var MANIFEST_FILENAME = ".harness-manifest.json";
910
- var MANIFEST_VERSION = "6";
911
- var ManifestSchema = z5.object({
912
- version: z5.enum(["4", "5", MANIFEST_VERSION]),
913
- engines: z5.array(z5.string()),
914
- renderedAt: z5.string(),
915
- files: z5.array(z5.string()),
916
- stopHookInstalled: z5.boolean().optional(),
917
- stopHookEngines: z5.array(z5.string()).optional(),
918
- opencodeConfig: OpenCodeConfigOwnershipSchema.optional(),
919
- hookConfigs: HookConfigsOwnershipSchema.optional(),
920
- harnessVersion: z5.string().optional(),
921
- overridesDir: z5.string().optional(),
922
- fileHashes: z5.record(z5.string().regex(/^[a-f0-9]{64}$/)).optional(),
923
- preservedFiles: z5.array(z5.string()).optional()
924
- });
925
- function manifestPath(targetDir) {
926
- return join5(targetDir, MANIFEST_FILENAME);
927
- }
928
- function writeManifest(targetDir, engines, files, extras = {}) {
929
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
930
- const manifest = {
931
- version: MANIFEST_VERSION,
932
- harnessVersion: VERSION,
933
- engines: [...engines].sort(),
934
- renderedAt: (/* @__PURE__ */ new Date()).toISOString(),
935
- files: [...files].sort(),
936
- fileHashes: Object.fromEntries(
937
- files.filter((file) => existsSync4(join5(targetDir, file))).sort().map((file) => [file, hashContent(readFileSync5(join5(targetDir, file)))])
938
- ),
939
- ...extras.overridesDir ? { overridesDir: extras.overridesDir } : {},
940
- ...extras.preservedFiles ? { preservedFiles: extras.preservedFiles } : {},
941
- ...extras.hookConfigs ? { hookConfigs: extras.hookConfigs } : {},
942
- ...extras.opencodeConfig ? { opencodeConfig: extras.opencodeConfig } : {},
943
- ...extras.stopHookInstalled !== void 0 ? { stopHookInstalled: extras.stopHookInstalled } : {},
944
- ...extras.stopHookEngines !== void 0 ? { stopHookEngines: [...extras.stopHookEngines].sort() } : {}
945
- };
946
- const path = manifestPath(targetDir);
947
- if (existsSync4(path)) chmodSync(path, 384);
948
- writeFileSync(path, `${JSON.stringify(manifest, null, 2)}
949
- `, { mode: 384 });
950
- }
951
- function hashContent(content) {
952
- return createHash("sha256").update(content).digest("hex");
801
+ // src/cli/update.ts
802
+ var LEGACY_HOOK_FILES = [".claude/settings.json", ".codex/hooks.json"];
803
+ var LEGACY_HOOK_MARKER = "@vaubaan/harness stop-hook";
804
+ function currentContent(root, path) {
805
+ return existsSync6(join8(root, path)) ? readFileSync7(join8(root, path), "utf8") : void 0;
806
+ }
807
+ function checkArtifactConflicts(root, previous, writes, removals) {
808
+ const desired = new Map(writes.map((file) => [file.path, file.content]));
809
+ const conflicts = [];
810
+ for (const path of [...desired.keys(), ...removals]) {
811
+ const content = currentContent(root, path);
812
+ if (content === void 0 || content === desired.get(path)) continue;
813
+ if (!previous.files.includes(path)) {
814
+ conflicts.push(`existing file outside harness manifest: ${path}`);
815
+ continue;
816
+ }
817
+ const hash = previous.fileHashes?.[path];
818
+ if (hash && hash !== hashContent(content)) conflicts.push(`modified harness file: ${path}`);
819
+ }
820
+ if (conflicts.length) {
821
+ throw new Error(
822
+ `${conflicts.join("\n")}
823
+ move their content to docs/ or .harness-overrides/, or keep them as yours with --preserve <path>`
824
+ );
825
+ }
953
826
  }
954
- function readManifest(targetDir) {
955
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
956
- const path = manifestPath(targetDir);
957
- if (!existsSync4(path)) return null;
958
- const raw = JSON.parse(readFileSync5(path, "utf8"));
959
- return ManifestSchema.parse(raw);
827
+ function releaseLegacyPaths(previous, warnings) {
828
+ const released = previous.files.filter((path) => RELEASED_PATHS.includes(path));
829
+ for (const path of released) {
830
+ warnings.push(`no longer managed by the harness, left in place: ${path}`);
831
+ }
832
+ if (released.length === 0) return previous;
833
+ return { ...previous, files: previous.files.filter((path) => !released.includes(path)) };
960
834
  }
961
-
962
- // src/cli/uninstall.ts
963
- import { existsSync as existsSync5, readdirSync, rmdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
964
- import { dirname as dirname2, join as join6, relative, resolve as resolve2 } from "path";
965
- function removeRenderedFiles(root, files) {
966
- assertManagedPaths(root, files);
967
- const filesRemoved = [];
968
- const missing = [];
969
- const dirsToConsider = /* @__PURE__ */ new Set();
970
- for (const rel of files) {
971
- const full = join6(root, rel);
972
- if (existsSync5(full)) {
973
- unlinkSync(full);
974
- filesRemoved.push(rel);
975
- dirsToConsider.add(dirname2(full));
976
- } else {
977
- missing.push(rel);
835
+ function legacyHookWarnings(root) {
836
+ const warnings = [];
837
+ for (const path of LEGACY_HOOK_FILES) {
838
+ const content = currentContent(root, path);
839
+ if (content?.includes(LEGACY_HOOK_MARKER)) {
840
+ warnings.push(
841
+ `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`
842
+ );
978
843
  }
979
844
  }
980
- return { filesRemoved, dirsPruned: pruneEmptyDirs(root, dirsToConsider), missing };
845
+ return warnings;
981
846
  }
982
- function pruneEmptyDirs(root, leaves) {
983
- const candidates = /* @__PURE__ */ new Set();
984
- for (const leaf of leaves) {
985
- let cur = leaf;
986
- while (cur !== root && cur.startsWith(`${root}/`)) {
987
- candidates.add(cur);
988
- cur = dirname2(cur);
847
+ function planInstallation(args, settings) {
848
+ const root = resolve5(args.targetDir);
849
+ const { engines } = settings;
850
+ const warnings = [];
851
+ const previous = releaseLegacyPaths(settings.previous, warnings);
852
+ const preserved = [
853
+ .../* @__PURE__ */ new Set([...previous.preservedFiles ?? [], ...args.preserveFiles ?? []])
854
+ ].sort();
855
+ if (preserved.includes(MANIFEST_FILENAME))
856
+ throw new Error("cannot preserve the harness manifest");
857
+ assertManagedPaths(root, [...previous.files, ...preserved]);
858
+ const requestedOverrides = args.overridesDir ?? previous.overridesDir;
859
+ const overridesDir = args.overridesDir ? resolve5(args.overridesDir) : previous.overridesDir ? resolve5(root, previous.overridesDir) : root;
860
+ if (requestedOverrides && !existsSync6(join8(overridesDir, ".harness-overrides"))) {
861
+ throw new Error(`recorded overrides are missing: ${overridesDir}/.harness-overrides`);
862
+ }
863
+ const hasOverrides = existsSync6(join8(overridesDir, ".harness-overrides"));
864
+ const disablePath = join8(overridesDir, ".harness-overrides", "disable.yaml");
865
+ if (existsSync6(disablePath)) {
866
+ try {
867
+ DisableYamlSchema.parse(parseYAML(readFileSync7(disablePath, "utf8")));
868
+ } catch {
869
+ throw new Error(`invalid override selection: ${disablePath}`);
989
870
  }
990
871
  }
991
- const pruned = [];
992
- const sorted = [...candidates].sort((a, b) => b.length - a.length);
993
- for (const dir of sorted) {
994
- if (!existsSync5(dir)) continue;
995
- if (readdirSync(dir).length > 0) continue;
996
- rmdirSync(dir);
997
- pruned.push(relative(root, dir));
872
+ const rendered = planInit({
873
+ targetDir: root,
874
+ packageDir: args.packageDir,
875
+ engines,
876
+ overridesDir: hasOverrides ? overridesDir : void 0
877
+ });
878
+ const output = rendered.output.files.filter((file) => !preserved.includes(file.path));
879
+ const owned = output.map((file) => file.path).sort();
880
+ const removals = previous.files.filter(
881
+ (file) => !owned.includes(file) && !preserved.includes(file)
882
+ );
883
+ assertManagedPaths(root, [...owned, ...removals]);
884
+ checkArtifactConflicts(root, previous, output, removals);
885
+ const hashes = Object.fromEntries(output.map((file) => [file.path, hashContent(file.content)]));
886
+ const manifest = {
887
+ version: MANIFEST_VERSION,
888
+ harnessVersion: VERSION,
889
+ engines: [...engines].sort(),
890
+ renderedAt: previous.renderedAt,
891
+ files: owned,
892
+ fileHashes: hashes,
893
+ ...hasOverrides ? { overridesDir: overridesDir === root ? "." : overridesDir } : {},
894
+ ...preserved.length ? { preservedFiles: preserved } : {}
895
+ };
896
+ const writes = output.filter((file) => currentContent(root, file.path) !== file.content);
897
+ const existingRemovals = removals.filter((path) => existsSync6(join8(root, path)));
898
+ if (writes.length || existingRemovals.length || !isDeepStrictEqual(settings.previous, manifest)) {
899
+ manifest.renderedAt = (/* @__PURE__ */ new Date()).toISOString();
900
+ writes.push({ path: MANIFEST_FILENAME, content: `${JSON.stringify(manifest, null, 2)}
901
+ ` });
998
902
  }
999
- return pruned;
903
+ warnings.push(...rendered.output.warnings, ...legacyHookWarnings(root));
904
+ if (preserved.length) warnings.push(`preserved user-owned artifacts: ${preserved.join(", ")}`);
905
+ return { writes, removals: existingRemovals, owned, manifest, warnings };
1000
906
  }
1001
907
 
1002
908
  // src/cli/init.ts
1003
- var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
1004
- function resolveEngineList(requested) {
1005
- if (!requested || requested.length === 0) return [...ENGINES];
1006
- return requested.map((e) => {
1007
- if (!ENGINES.includes(e)) {
1008
- throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
1009
- }
1010
- return e;
1011
- });
1012
- }
1013
- function defaultPackageDir() {
1014
- const here = dirname3(fileURLToPath(import.meta.url));
1015
- if (existsSync6(join7(here, "agents"))) return here;
1016
- return resolve3(here, "..");
1017
- }
1018
- function planInit(args) {
1019
- const engines = resolveEngineList(args.engines);
1020
- const packageDir = args.packageDir ?? defaultPackageDir();
1021
- const harness = loadHarness(packageDir);
1022
- const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
1023
- const projectSkills = loadProjectSkills(args.targetDir);
1024
- const hasQualityDoc = existsSync6(join7(args.targetDir, QUALITY_DOC_PATH));
1025
- const mcpServers = args.mcpServers ? resolveMcpIds(args.mcpServers) : void 0;
1026
- const stopHookInstalled = args.withStopHook !== false;
1027
- const output = render({
1028
- harness,
1029
- engines,
1030
- overrides,
1031
- projectSkills,
1032
- hasQualityDoc,
1033
- mcpServers,
1034
- withStopHook: stopHookInstalled
1035
- });
1036
- return { engines, output, stopHookInstalled };
1037
- }
1038
909
  function writeFilesToTarget(files, targetDir) {
1039
910
  assertManagedPaths(
1040
911
  targetDir,
@@ -1042,43 +913,48 @@ function writeFilesToTarget(files, targetDir) {
1042
913
  );
1043
914
  const written = [];
1044
915
  for (const f of files) {
1045
- const full = join7(targetDir, f.path);
1046
- mkdirSync(dirname3(full), { recursive: true });
916
+ const full = join9(targetDir, f.path);
917
+ mkdirSync2(dirname6(full), { recursive: true });
1047
918
  writeFileSync3(full, f.content);
1048
919
  written.push(f.path);
1049
920
  }
1050
921
  return written;
1051
922
  }
923
+ function emptyManifest(engines) {
924
+ return { version: MANIFEST_VERSION, engines: [...engines], renderedAt: "", files: [] };
925
+ }
1052
926
  function initCommand(args) {
1053
- const { engines, output, stopHookInstalled } = planInit(args);
1054
- const previous = readManifest(args.targetDir);
1055
- assertManagedPaths(args.targetDir, [
1056
- MANIFEST_FILENAME,
1057
- ...previous?.files ?? [],
1058
- ...output.files.map((file) => file.path),
1059
- ...previous?.opencodeConfig ? [OPENCODE_CONFIG_PATH] : []
1060
- ]);
1061
- const desiredConfig = output.files.find((file) => file.path === OPENCODE_CONFIG_PATH);
1062
- const config = planOpenCodeConfig(args.targetDir, desiredConfig, previous?.opencodeConfig);
1063
- const next = new Set(output.files.map((f) => f.path));
1064
- const stale = (previous?.files ?? []).filter((f) => !next.has(f) && f !== OPENCODE_CONFIG_PATH);
1065
- if (config.remove) stale.push(OPENCODE_CONFIG_PATH);
1066
- const staleFilesRemoved = removeRenderedFiles(resolve3(args.targetDir), stale).filesRemoved;
1067
- const ownedFiles = output.files.filter((file) => file.path !== OPENCODE_CONFIG_PATH);
1068
- const filesWritten = writeFilesToTarget(ownedFiles, args.targetDir);
1069
- if (config.write) writeFilesToTarget([config.write], args.targetDir);
1070
- writeManifest(args.targetDir, engines, filesWritten, {
1071
- stopHookInstalled,
1072
- stopHookEngines: stopHookInstalled ? engines : void 0,
1073
- opencodeConfig: config.ownership,
1074
- overridesDir: args.overridesDir ? resolve3(args.overridesDir) === resolve3(args.targetDir) ? "." : resolve3(args.overridesDir) : void 0
1075
- });
1076
- if (config.write) filesWritten.push(OPENCODE_CONFIG_PATH);
1077
- const warnings = [...output.warnings, ...config.warnings];
1078
- if (previous?.files.includes(OPENCODE_CONFIG_PATH) && !previous.opencodeConfig) {
1079
- warnings.push(`preserved legacy shared configuration: ${OPENCODE_CONFIG_PATH}`);
927
+ const root = resolve6(args.targetDir);
928
+ const engines = resolveEngineList(args.engines);
929
+ const previous = readManifest(root) ?? emptyManifest(engines);
930
+ const plan = planInstallation(
931
+ {
932
+ targetDir: root,
933
+ packageDir: args.packageDir,
934
+ overridesDir: args.overridesDir,
935
+ preserveFiles: args.preserveFiles
936
+ },
937
+ { previous, sourceVersion: previous.version, engines }
938
+ );
939
+ const touchedExisting = [...plan.writes.map((file) => file.path), ...plan.removals].some(
940
+ (path) => path !== MANIFEST_FILENAME && existsSync7(join9(root, path))
941
+ );
942
+ let backupDir;
943
+ if (plan.writes.length || plan.removals.length) {
944
+ backupDir = applyUpdateTransaction(root, plan.writes, plan.removals, args.backupDir).backupDir;
945
+ if (!touchedExisting && !args.backupDir) {
946
+ rmSync(backupDir, { recursive: true, force: true });
947
+ backupDir = void 0;
948
+ }
949
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname6(join9(root, path)))));
1080
950
  }
1081
- return { filesWritten, staleFilesRemoved, warnings, stopHookInstalled };
951
+ return {
952
+ filesWritten: plan.owned,
953
+ staleFilesRemoved: plan.removals,
954
+ warnings: plan.warnings,
955
+ engines,
956
+ ...backupDir ? { backupDir } : {}
957
+ };
1082
958
  }
1083
959
  export {
1084
960
  initCommand,