@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/index.js CHANGED
@@ -1,26 +1,129 @@
1
1
  // src/version.ts
2
- var VERSION = "1.3.2";
2
+ var VERSION = "2.0.0";
3
3
 
4
4
  // src/cli/init.ts
5
- import { existsSync as existsSync6, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
6
- import { dirname as dirname3, join as join7, resolve as resolve3 } from "path";
5
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
6
+ import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
7
+
8
+ // src/cli/managed-paths.ts
9
+ import { lstatSync, realpathSync, statSync } from "fs";
10
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from "path";
11
+ var MANAGED_FILES = /* @__PURE__ */ new Set(["AGENTS.md", "CLAUDE.md", ".harness-manifest.json"]);
12
+ var RELEASED_PATHS = [
13
+ ".mcp.json",
14
+ ".codex/config.toml",
15
+ ".opencode/opencode.json",
16
+ ".opencode/mcp.json",
17
+ ".claude/settings.json",
18
+ ".codex/hooks.json"
19
+ ];
20
+ var MANAGED_DIRECTORIES = [
21
+ ".claude/agents/",
22
+ ".claude/commands/",
23
+ ".claude/skills/",
24
+ ".codex/agents/",
25
+ ".codex/commands/",
26
+ ".codex/skills/",
27
+ ".agents/skills/",
28
+ ".opencode/agents/",
29
+ ".opencode/commands/",
30
+ ".opencode/skills/",
31
+ ".opencode/plugins/"
32
+ ];
33
+ function canonicalTargetRoot(root) {
34
+ let ancestor = resolve(root);
35
+ const missing = [];
36
+ while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
37
+ missing.unshift(basename(ancestor));
38
+ ancestor = dirname(ancestor);
39
+ }
40
+ const canonical = realpathSync(ancestor);
41
+ if (!statSync(canonical).isDirectory()) {
42
+ throw new Error(`harness target is not a directory: ${root}`);
43
+ }
44
+ return join(canonical, ...missing);
45
+ }
46
+ function assertManagedLocation(path) {
47
+ const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
48
+ if (isAbsolute(path) || win32.isAbsolute(path) || path.includes("\\") || path.includes("\0") || invalidSegment) {
49
+ throw new Error(`unsafe harness path: ${path}`);
50
+ }
51
+ if (!MANAGED_FILES.has(path) && !MANAGED_DIRECTORIES.some((prefix) => path.startsWith(prefix))) {
52
+ throw new Error(`path is outside harness-managed locations: ${path}`);
53
+ }
54
+ }
55
+ function assertNoSymbolicComponents(root, path) {
56
+ const parts = path.split("/");
57
+ let current = root;
58
+ for (const [index, part] of parts.entries()) {
59
+ current = join(current, part);
60
+ const info = lstatSync(current, { throwIfNoEntry: false });
61
+ if (!info) return;
62
+ if (info.isSymbolicLink()) {
63
+ throw new Error(`symbolic link in harness path: ${path}`);
64
+ }
65
+ const isLeaf = index === parts.length - 1;
66
+ if (isLeaf ? !info.isFile() : !info.isDirectory()) {
67
+ throw new Error(`unexpected file type in harness path: ${path}`);
68
+ }
69
+ }
70
+ }
71
+ function assertManagedPaths(root, files) {
72
+ for (const path of files) assertManagedLocation(path);
73
+ const canonicalRoot2 = canonicalTargetRoot(root);
74
+ for (const path of files) assertNoSymbolicComponents(canonicalRoot2, path);
75
+ }
76
+
77
+ // src/cli/manifest.ts
78
+ import { createHash } from "crypto";
79
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "fs";
80
+ import { join as join2 } from "path";
81
+ import { z } from "zod";
82
+ var MANIFEST_FILENAME = ".harness-manifest.json";
83
+ var MANIFEST_VERSION = "6";
84
+ var ManifestSchema = z.object({
85
+ version: z.enum(["4", "5", MANIFEST_VERSION]),
86
+ engines: z.array(z.string()),
87
+ renderedAt: z.string(),
88
+ files: z.array(z.string()),
89
+ harnessVersion: z.string().optional(),
90
+ overridesDir: z.string().optional(),
91
+ fileHashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)).optional(),
92
+ preservedFiles: z.array(z.string()).optional()
93
+ });
94
+ function manifestPath(targetDir) {
95
+ return join2(targetDir, MANIFEST_FILENAME);
96
+ }
97
+ function hashContent(content) {
98
+ return createHash("sha256").update(content).digest("hex");
99
+ }
100
+ function readManifest(targetDir) {
101
+ assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
102
+ const path = manifestPath(targetDir);
103
+ if (!existsSync(path)) return null;
104
+ const raw = JSON.parse(readFileSync(path, "utf8"));
105
+ return ManifestSchema.parse(raw);
106
+ }
107
+
108
+ // src/cli/plan-render.ts
109
+ import { existsSync as existsSync3 } from "fs";
110
+ import { dirname as dirname2, join as join4, resolve as resolve2 } from "path";
7
111
  import { fileURLToPath } from "url";
8
112
 
9
113
  // src/loader.ts
10
- import { existsSync, readFileSync as readFileSync2 } from "fs";
11
- import { join } from "path";
114
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
115
+ import { join as join3 } from "path";
12
116
  import fg from "fast-glob";
13
- import { z as z2 } from "zod";
117
+ import { z as z3 } from "zod";
14
118
 
15
119
  // src/parser/common.ts
16
- import { readFileSync } from "fs";
120
+ import { readFileSync as readFileSync2 } from "fs";
17
121
  import matter from "gray-matter";
18
122
 
19
123
  // src/parser/schemas.ts
20
- import { z } from "zod";
124
+ import { z as z2 } from "zod";
21
125
 
22
126
  // src/types.ts
23
- var AGENT_IDS = ["coding", "review", "merge", "planning"];
24
127
  var ENGINES = ["claude-code", "codex-cli", "opencode"];
25
128
  var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
26
129
  var CAPABILITIES_MATRIX = {
@@ -33,41 +136,36 @@ var DEGRADED_CAPABILITIES = {
33
136
  };
34
137
 
35
138
  // src/parser/schemas.ts
36
- var IdSchema = z.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
37
- var SkillFrontmatterSchema = z.object({
139
+ var IdSchema = z2.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
140
+ var SkillFrontmatterSchema = z2.object({
38
141
  id: IdSchema,
39
- description: z.string().min(1),
40
- engines: z.array(z.enum(ENGINES)).min(1).optional(),
41
- requires: z.array(z.enum(CAPABILITIES)).optional(),
42
- tags: z.array(z.string()).optional()
142
+ description: z2.string().min(1),
143
+ engines: z2.array(z2.enum(ENGINES)).min(1).optional(),
144
+ requires: z2.array(z2.enum(CAPABILITIES)).optional(),
145
+ tags: z2.array(z2.string()).optional()
43
146
  }).strict();
44
- var CmdArgEnumSchema = z.object({
45
- name: z.string().min(1),
46
- type: z.literal("enum"),
47
- values: z.array(z.string()).min(1),
48
- default: z.string().optional()
147
+ var CmdArgEnumSchema = z2.object({
148
+ name: z2.string().min(1),
149
+ type: z2.literal("enum"),
150
+ values: z2.array(z2.string()).min(1),
151
+ default: z2.string().optional()
49
152
  }).strict();
50
- var CmdArgStringSchema = z.object({
51
- name: z.string().min(1),
52
- type: z.literal("string"),
53
- default: z.string().optional()
153
+ var CmdArgStringSchema = z2.object({
154
+ name: z2.string().min(1),
155
+ type: z2.literal("string"),
156
+ default: z2.string().optional()
54
157
  }).strict();
55
- var CmdArgSchema = z.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
56
- var CmdFrontmatterSchema = z.object({
158
+ var CmdArgSchema = z2.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
159
+ var CmdFrontmatterSchema = z2.object({
57
160
  id: IdSchema,
58
- trigger: z.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
161
+ trigger: z2.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
59
162
  invokes_skill: IdSchema,
60
- args: z.array(CmdArgSchema).optional(),
61
- description: z.string().min(1)
62
- }).strict();
63
- var AgentFrontmatterSchema = z.object({
64
- id: z.enum(AGENT_IDS),
65
- description: z.string().min(1)
163
+ args: z2.array(CmdArgSchema).optional(),
164
+ description: z2.string().min(1)
66
165
  }).strict();
67
166
  var Schemas = {
68
167
  Skill: SkillFrontmatterSchema,
69
- Cmd: CmdFrontmatterSchema,
70
- Agent: AgentFrontmatterSchema
168
+ Cmd: CmdFrontmatterSchema
71
169
  };
72
170
  var ParseError = class extends Error {
73
171
  constructor(file, issues) {
@@ -96,11 +194,6 @@ function parseWithSchema(filePath, source, schema) {
96
194
  };
97
195
  }
98
196
 
99
- // src/parser/agent.ts
100
- function parseAgent(filePath, source) {
101
- return parseWithSchema(filePath, source, Schemas.Agent);
102
- }
103
-
104
197
  // src/parser/cmd.ts
105
198
  function parseCmd(filePath, source) {
106
199
  return parseWithSchema(filePath, source, Schemas.Cmd);
@@ -118,39 +211,35 @@ function parseYAML(source) {
118
211
  }
119
212
 
120
213
  // src/loader.ts
121
- var DisableYamlSchema = z2.object({ disable: z2.array(z2.string()).optional() }).passthrough();
214
+ var DisableYamlSchema = z3.object({ disable: z3.array(z3.string()).optional() }).passthrough();
122
215
  function loadHarness(packageDir, opts = {}) {
123
- const agentsDir = opts.agentsDir ?? join(packageDir, "agents");
124
- const skillsDir = opts.skillsDir ?? join(packageDir, "skills");
125
- const commandsDir = opts.commandsDir ?? join(packageDir, "commands");
126
- const agentFiles = fg.sync("*.agent.md", { cwd: agentsDir, absolute: true });
216
+ const skillsDir = opts.skillsDir ?? join3(packageDir, "skills");
217
+ const commandsDir = opts.commandsDir ?? join3(packageDir, "commands");
127
218
  const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
128
219
  const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
129
220
  return {
130
- agents: agentFiles.map((f) => parseAgent(f, readFileSync2(f, "utf8"))),
131
- skills: skillFiles.map((f) => parseSkill(f, readFileSync2(f, "utf8"))),
132
- cmds: cmdFiles.map((f) => parseCmd(f, readFileSync2(f, "utf8")))
221
+ skills: skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8"))),
222
+ cmds: cmdFiles.map((f) => parseCmd(f, readFileSync3(f, "utf8")))
133
223
  };
134
224
  }
135
225
  function loadProjectSkills(targetDir) {
136
- const skillsDir = join(targetDir, "docs", "skills");
137
- if (!existsSync(skillsDir)) return [];
226
+ const skillsDir = join3(targetDir, "docs", "skills");
227
+ if (!existsSync2(skillsDir)) return [];
138
228
  const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
139
- return skillFiles.map((f) => parseSkill(f, readFileSync2(f, "utf8")));
229
+ return skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8")));
140
230
  }
141
231
  function loadOverrides(worktreeDir) {
142
- const overridesDir = join(worktreeDir, ".harness-overrides");
143
- if (!existsSync(overridesDir)) return void 0;
232
+ const overridesDir = join3(worktreeDir, ".harness-overrides");
233
+ if (!existsSync2(overridesDir)) return void 0;
144
234
  const added = loadHarness(overridesDir, {
145
- agentsDir: join(overridesDir, "agents"),
146
- skillsDir: join(overridesDir, "skills"),
147
- commandsDir: join(overridesDir, "commands")
235
+ skillsDir: join3(overridesDir, "skills"),
236
+ commandsDir: join3(overridesDir, "commands")
148
237
  });
149
- const disablePath = join(overridesDir, "disable.yaml");
238
+ const disablePath = join3(overridesDir, "disable.yaml");
150
239
  let disable = [];
151
- if (existsSync(disablePath)) {
240
+ if (existsSync2(disablePath)) {
152
241
  try {
153
- const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync2(disablePath, "utf8")));
242
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync3(disablePath, "utf8")));
154
243
  if (parsed.success && parsed.data.disable) {
155
244
  disable = parsed.data.disable;
156
245
  }
@@ -160,28 +249,8 @@ function loadOverrides(worktreeDir) {
160
249
  return { add: added, disable };
161
250
  }
162
251
 
163
- // src/mcp.ts
164
- var MCP_SERVER_IDS = ["context7"];
165
- var MCP_SERVERS = {
166
- context7: {
167
- id: "context7",
168
- description: "Upstash Context7 \u2014 fetches up-to-date library docs via resolve-library-id + get-library-docs.",
169
- command: "npx",
170
- args: ["-y", "@upstash/context7-mcp"]
171
- }
172
- };
173
- function resolveMcpIds(requested) {
174
- return requested.map((id) => {
175
- if (!MCP_SERVER_IDS.includes(id)) {
176
- throw new Error(`unknown MCP server: ${id} (expected one of ${MCP_SERVER_IDS.join(", ")})`);
177
- }
178
- return id;
179
- });
180
- }
181
-
182
252
  // src/renderers/common.ts
183
253
  import { stringify as yamlStringify } from "yaml";
184
- var STOP_HOOK_PACKAGE = "@vaubaan/harness";
185
254
  function checkSkillCapabilities(skill, engine) {
186
255
  const blockingWarnings = [];
187
256
  const degradedWarnings = [];
@@ -212,39 +281,6 @@ ${rendered}
212
281
  ---
213
282
  `;
214
283
  }
215
- var SCALAR_NEEDS_QUOTE = /[^a-zA-Z0-9_./-]/;
216
- function tomlEscapeString(s) {
217
- return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
218
- }
219
- function tomlValue(v) {
220
- if (Array.isArray(v)) {
221
- return `[${v.map((x) => tomlValue(x)).join(", ")}]`;
222
- }
223
- if (typeof v === "string") {
224
- if (v.includes("\n")) return tomlEscapeString(v);
225
- return SCALAR_NEEDS_QUOTE.test(v) ? tomlEscapeString(v) : `"${v}"`;
226
- }
227
- if (typeof v === "boolean" || typeof v === "number") {
228
- return String(v);
229
- }
230
- return tomlEscapeString(String(v));
231
- }
232
- function tomlMultilineString(s) {
233
- const escaped = s.replace(/\\/g, "\\\\").replace(/"""/g, '""\\"');
234
- return `"""
235
- ${escaped}
236
- """`;
237
- }
238
- function tomlQuoteString(s) {
239
- return tomlValue(s);
240
- }
241
- function tomlInlineArray(items) {
242
- return tomlValue([...items]);
243
- }
244
- function tomlInlineTable(table) {
245
- const entries = Object.entries(table).map(([k, v]) => `${k} = ${tomlValue(v)}`);
246
- return `{ ${entries.join(", ")} }`;
247
- }
248
284
  function frontmatterDataForSkill(skill) {
249
285
  const data = {
250
286
  name: skill.meta.id,
@@ -269,11 +305,7 @@ function frontmatterDataForCmd(cmd) {
269
305
  }
270
306
  return data;
271
307
  }
272
- function buildAgentBody(agent) {
273
- return `${agent.body.trim()}
274
- `;
275
- }
276
- function buildUmbrellaBody(_agents, extras) {
308
+ function buildUmbrellaBody(extras) {
277
309
  const triggerBySkill = new Map(
278
310
  extras.availableCommands.map((c) => [c.meta.invokes_skill, c.meta.trigger])
279
311
  );
@@ -294,7 +326,7 @@ function buildUmbrellaBody(_agents, extras) {
294
326
  "- `docs/handbook/<feature>.md` \u2014 *how it actually works* today.",
295
327
  "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives.",
296
328
  "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 core scenarios.",
297
- "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release.",
329
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release. How this team works: follow it.",
298
330
  ...extras.hasProjectSkills ? ["- `docs/skills/*.skill.md` \u2014 the project's domain skills."] : [],
299
331
  ...extras.hasQualityDoc ? [
300
332
  "- `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."
@@ -307,7 +339,13 @@ function buildUmbrellaBody(_agents, extras) {
307
339
  "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
308
340
  "- Implicit structural decision in your changes \u2192 an ADR (`/decision`).",
309
341
  "- Changed feature behavior \u2192 update the matching handbook (`/handbook`).",
310
- "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on."
342
+ "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on.",
343
+ "",
344
+ "## Checks",
345
+ "",
346
+ "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.",
347
+ "",
348
+ "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."
311
349
  ];
312
350
  if (skillLines.length > 0) {
313
351
  sections.push("", "## Doc-skills", "", skillLines.join("\n"));
@@ -348,60 +386,11 @@ ${cmd.body}
348
386
  files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
349
387
  warnings: []
350
388
  };
351
- },
352
- renderAgents(agents) {
353
- const files = [];
354
- for (const agent of agents) {
355
- const subagentFrontmatter = yamlFrontmatter({
356
- name: agent.meta.id,
357
- description: agent.meta.description
358
- });
359
- const body = buildAgentBody(agent);
360
- const content = `${subagentFrontmatter}
361
- ${body}`;
362
- files.push({ path: `${BASE}/agents/${agent.meta.id}.md`, content });
363
- }
364
- return { files, warnings: [] };
365
- },
366
- renderMcp(servers) {
367
- if (servers.length === 0) return { files: [], warnings: [] };
368
- const mcpServers = {};
369
- for (const s of servers) {
370
- const entry = { command: s.command, args: [...s.args] };
371
- if (s.env) entry.env = s.env;
372
- mcpServers[s.id] = entry;
373
- }
374
- const content = `${JSON.stringify({ mcpServers }, null, 2)}
375
- `;
376
- return { files: [{ path: ".mcp.json", content }], warnings: [] };
377
- },
378
- renderStopHook() {
379
- const settings = {
380
- hooks: {
381
- Stop: [
382
- {
383
- matcher: "",
384
- hooks: [
385
- {
386
- type: "command",
387
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine claude`
388
- }
389
- ]
390
- }
391
- ]
392
- }
393
- };
394
- return {
395
- files: [{ path: `${BASE}/settings.json`, content: `${JSON.stringify(settings, null, 2)}
396
- ` }],
397
- warnings: []
398
- };
399
389
  }
400
390
  };
401
391
 
402
392
  // src/renderers/codex-cli.ts
403
393
  var ENGINE2 = "codex-cli";
404
- var BASE2 = ".codex";
405
394
  var SKILLS_BASE = ".agents/skills";
406
395
  var codexCliRenderer = {
407
396
  engine: ENGINE2,
@@ -427,62 +416,12 @@ ${skill.body}
427
416
  // Codex custom prompts are deprecated in favour of skills: nothing to render.
428
417
  renderCmd(_cmd) {
429
418
  return { files: [], warnings: [] };
430
- },
431
- renderAgents(agents) {
432
- const files = [];
433
- for (const agent of agents) {
434
- const content = [
435
- `name = ${tomlQuoteString(agent.meta.id)}`,
436
- `description = ${tomlQuoteString(agent.meta.description)}`,
437
- `developer_instructions = ${tomlMultilineString(buildAgentBody(agent).trimEnd())}`,
438
- ""
439
- ].join("\n");
440
- files.push({ path: `${BASE2}/agents/${agent.meta.id}.toml`, content });
441
- }
442
- return { files, warnings: [] };
443
- },
444
- renderMcp(servers) {
445
- if (servers.length === 0) return { files: [], warnings: [] };
446
- const blocks = [];
447
- for (const s of servers) {
448
- const lines = [
449
- `[mcp_servers.${s.id}]`,
450
- `command = ${tomlQuoteString(s.command)}`,
451
- `args = ${tomlInlineArray([...s.args])}`
452
- ];
453
- if (s.env) lines.push(`env = ${tomlInlineTable(s.env)}`);
454
- blocks.push(lines.join("\n"));
455
- }
456
- const content = `${blocks.join("\n\n")}
457
- `;
458
- return { files: [{ path: `${BASE2}/config.toml`, content }], warnings: [] };
459
- },
460
- renderStopHook() {
461
- const hooks = {
462
- hooks: {
463
- Stop: [
464
- {
465
- hooks: [
466
- {
467
- type: "command",
468
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine codex`
469
- }
470
- ]
471
- }
472
- ]
473
- }
474
- };
475
- return {
476
- files: [{ path: `${BASE2}/hooks.json`, content: `${JSON.stringify(hooks, null, 2)}
477
- ` }],
478
- warnings: []
479
- };
480
419
  }
481
420
  };
482
421
 
483
422
  // src/renderers/opencode.ts
484
423
  var ENGINE3 = "opencode";
485
- var BASE3 = ".opencode";
424
+ var BASE2 = ".opencode";
486
425
  var opencodeRenderer = {
487
426
  engine: ENGINE3,
488
427
  renderSkill(skill) {
@@ -500,7 +439,7 @@ var opencodeRenderer = {
500
439
  ${skill.body}
501
440
  `;
502
441
  return {
503
- files: [{ path: `${BASE3}/skills/${skill.meta.id}/SKILL.md`, content }],
442
+ files: [{ path: `${BASE2}/skills/${skill.meta.id}/SKILL.md`, content }],
504
443
  warnings: check.degradedWarnings
505
444
  };
506
445
  },
@@ -509,106 +448,7 @@ ${skill.body}
509
448
  ${cmd.body}
510
449
  `;
511
450
  return {
512
- files: [{ path: `${BASE3}/commands/${cmd.meta.id}.md`, content }],
513
- warnings: []
514
- };
515
- },
516
- renderAgents(agents) {
517
- const files = [];
518
- for (const agent of agents) {
519
- const fm = yamlFrontmatter({
520
- description: agent.meta.description,
521
- mode: "all"
522
- });
523
- const body = buildAgentBody(agent);
524
- files.push({ path: `${BASE3}/agents/${agent.meta.id}.md`, content: `${fm}
525
- ${body}` });
526
- }
527
- return { files, warnings: [] };
528
- },
529
- renderMcp(servers) {
530
- if (servers.length === 0) return { files: [], warnings: [] };
531
- const mcp = {};
532
- for (const s of servers) {
533
- const entry = {
534
- type: "local",
535
- command: [s.command, ...s.args],
536
- enabled: true
537
- };
538
- if (s.env) entry.environment = s.env;
539
- mcp[s.id] = entry;
540
- }
541
- const config = { $schema: "https://opencode.ai/config.json", mcp };
542
- const content = `${JSON.stringify(config, null, 2)}
543
- `;
544
- return { files: [{ path: `${BASE3}/opencode.json`, content }], warnings: [] };
545
- },
546
- renderStopHook() {
547
- const content = `import { spawnSync } from "node:child_process";
548
-
549
- // Runs the harness lint and returns the report to inject, or "" when the
550
- // turn may end.
551
- const lintReport = (directory, sessionID) => {
552
- const r = spawnSync(
553
- "npx",
554
- ["-y", "${STOP_HOOK_PACKAGE}", "stop-hook", "--engine", "opencode", "--cwd", directory],
555
- { input: JSON.stringify({ sessionID }), encoding: "utf-8" },
556
- );
557
- const report = (r.stderr ?? "").trim();
558
- return r.status === 2 ? report : "";
559
- };
560
-
561
- // OpenCode 1.x entry point, exposed as server() below.
562
- const HarnessStopHook = async ({ client, directory }) => ({
563
- event: async ({ event }) => {
564
- if (event.type !== "session.idle") return;
565
- const sessionID = event.properties?.sessionID;
566
- if (!sessionID) return;
567
- const report = lintReport(directory, sessionID);
568
- if (report === "") return;
569
- // OpenCode defaults to its build agent when a prompt omits agent.
570
- // Preserve the last conversation persona, excluding compaction summaries.
571
- const history = await client.session.messages({ path: { id: sessionID } }).catch(() => undefined);
572
- if (history?.error || !Array.isArray(history?.data)) return;
573
- const current = history.data.findLast(({ info }) =>
574
- (info.role === "user" || (info.role === "assistant" && !info.summary)) &&
575
- typeof info.agent === "string" && info.agent.trim() !== "",
576
- );
577
- if (!current) return;
578
- await client.session.prompt({
579
- path: { id: sessionID },
580
- body: { agent: current.info.agent, parts: [{ type: "text", text: report }] },
581
- });
582
- },
583
- });
584
-
585
- // One default export for both majors: OpenCode 1.x calls server(),
586
- // OpenCode 2.x calls setup(). A V2 session keeps its agent, so the report
587
- // is sent without naming the persona.
588
- export default {
589
- id: "vaubaan-harness-stop-hook",
590
- server: HarnessStopHook,
591
- setup(context) {
592
- const directory = context.location.directory;
593
- const controller = new AbortController();
594
- const listen = async () => {
595
- for await (const event of context.event.subscribe({ signal: controller.signal })) {
596
- if (event.type !== "session.idle") continue;
597
- if (event.location?.directory && event.location.directory !== directory) continue;
598
- const sessionID = event.data?.sessionID;
599
- if (!sessionID) continue;
600
- const report = lintReport(directory, sessionID);
601
- if (report === "") continue;
602
- await context.session.prompt({ sessionID, text: report }).catch(() => undefined);
603
- }
604
- };
605
- listen().catch(() => undefined);
606
- return () => controller.abort();
607
- },
608
- };
609
- `;
610
- return {
611
- files: [{ path: `${BASE3}/plugins/harness-stop-hook.ts`, content }],
451
+ files: [{ path: `${BASE2}/commands/${cmd.meta.id}.md`, content }],
612
452
  warnings: []
613
453
  };
614
454
  }
@@ -647,7 +487,6 @@ function removeByIds(items, disabled) {
647
487
  function applyOverrides(harness, overrides) {
648
488
  const disabled = overrides?.disable ?? [];
649
489
  return {
650
- agents: removeByIds(mergeById(harness.agents, overrides?.add?.agents), disabled),
651
490
  skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
652
491
  cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
653
492
  };
@@ -663,58 +502,37 @@ function render(input) {
663
502
  }
664
503
  const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
665
504
  const harness = applyOverrides(base, input.overrides);
666
- if (harness.agents.length === 0) {
667
- throw new RenderError("No agents found in harness");
668
- }
669
505
  const files = [];
670
506
  const warnings = [];
671
507
  const exposedSkills = /* @__PURE__ */ new Map();
672
508
  const exposedCmds = /* @__PURE__ */ new Map();
673
509
  for (const engine of opencodeLast(engines)) {
674
510
  const renderer = getRenderer(engine);
675
- const renderedSkills = [];
511
+ const renderedSkillIds = /* @__PURE__ */ new Set();
676
512
  for (const skill of harness.skills) {
677
513
  const result = renderer.renderSkill(skill);
678
514
  warnings.push(...result.warnings);
679
515
  if (result.files.length > 0) {
680
516
  const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
681
517
  if (!alreadyVisible) files.push(...result.files);
682
- renderedSkills.push(skill);
518
+ renderedSkillIds.add(skill.meta.id);
683
519
  exposedSkills.set(skill.meta.id, skill);
684
520
  }
685
521
  }
686
- const renderedSkillIds = new Set(renderedSkills.map((s) => s.meta.id));
687
- const renderedCmds = [];
688
522
  for (const cmd of harness.cmds) {
689
523
  if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
690
524
  const result = renderer.renderCmd(cmd);
691
525
  warnings.push(...result.warnings);
692
526
  if (result.files.length > 0) {
693
527
  files.push(...result.files);
694
- renderedCmds.push(cmd);
695
528
  exposedCmds.set(cmd.meta.id, cmd);
696
529
  }
697
530
  }
698
- const agentsResult = renderer.renderAgents(harness.agents);
699
- warnings.push(...agentsResult.warnings);
700
- files.push(...agentsResult.files);
701
- if (input.mcpServers && input.mcpServers.length > 0) {
702
- const specs = input.mcpServers.map((id) => MCP_SERVERS[id]);
703
- const mcpResult = renderer.renderMcp(specs);
704
- warnings.push(...mcpResult.warnings);
705
- files.push(...mcpResult.files);
706
- }
707
- if (input.withStopHook !== false) {
708
- const hookResult = renderer.renderStopHook();
709
- warnings.push(...hookResult.warnings);
710
- files.push(...hookResult.files);
711
- }
712
531
  }
713
- const hasProjectSkills = (input.projectSkills?.length ?? 0) > 0;
714
- const umbrellaContent = buildUmbrellaBody(harness.agents, {
532
+ const umbrellaContent = buildUmbrellaBody({
715
533
  availableSkills: Array.from(exposedSkills.values()),
716
534
  availableCommands: Array.from(exposedCmds.values()),
717
- hasProjectSkills,
535
+ hasProjectSkills: (input.projectSkills?.length ?? 0) > 0,
718
536
  hasQualityDoc: input.hasQualityDoc === true
719
537
  });
720
538
  files.push({ path: "AGENTS.md", content: umbrellaContent });
@@ -724,507 +542,54 @@ function render(input) {
724
542
  return { files, warnings };
725
543
  }
726
544
 
727
- // src/cli/managed-paths.ts
728
- import { lstatSync, realpathSync, statSync } from "fs";
729
- import { basename, dirname, isAbsolute, join as join2, resolve, win32 } from "path";
730
- var MANAGED_FILES = /* @__PURE__ */ new Set([
731
- "AGENTS.md",
732
- "CLAUDE.md",
733
- ".mcp.json",
734
- ".harness-manifest.json",
735
- ".claude/settings.json",
736
- ".codex/config.toml",
737
- ".codex/hooks.json",
738
- ".opencode/opencode.json",
739
- ".opencode/mcp.json"
740
- ]);
741
- var MANAGED_DIRECTORIES = [
742
- ".claude/agents/",
743
- ".claude/commands/",
744
- ".claude/skills/",
745
- ".codex/agents/",
746
- ".codex/commands/",
747
- ".codex/skills/",
748
- ".agents/skills/",
749
- ".opencode/agents/",
750
- ".opencode/commands/",
751
- ".opencode/skills/",
752
- ".opencode/plugins/"
753
- ];
754
- function canonicalTargetRoot(root) {
755
- let ancestor = resolve(root);
756
- const missing = [];
757
- while (!lstatSync(ancestor, { throwIfNoEntry: false })) {
758
- missing.unshift(basename(ancestor));
759
- ancestor = dirname(ancestor);
760
- }
761
- const canonical = realpathSync(ancestor);
762
- if (!statSync(canonical).isDirectory()) {
763
- throw new Error(`harness target is not a directory: ${root}`);
764
- }
765
- return join2(canonical, ...missing);
766
- }
767
- function assertManagedLocation(path) {
768
- const invalidSegment = path.split("/").some((part) => part === "" || part === "." || part === "..");
769
- if (isAbsolute(path) || win32.isAbsolute(path) || path.includes("\\") || path.includes("\0") || invalidSegment) {
770
- throw new Error(`unsafe harness path: ${path}`);
771
- }
772
- if (!MANAGED_FILES.has(path) && !MANAGED_DIRECTORIES.some((prefix) => path.startsWith(prefix))) {
773
- throw new Error(`path is outside harness-managed locations: ${path}`);
774
- }
775
- }
776
- function assertNoSymbolicComponents(root, path) {
777
- const parts = path.split("/");
778
- let current = root;
779
- for (const [index, part] of parts.entries()) {
780
- current = join2(current, part);
781
- const info = lstatSync(current, { throwIfNoEntry: false });
782
- if (!info) return;
783
- if (info.isSymbolicLink()) {
784
- throw new Error(`symbolic link in harness path: ${path}`);
785
- }
786
- const isLeaf = index === parts.length - 1;
787
- if (isLeaf ? !info.isFile() : !info.isDirectory()) {
788
- throw new Error(`unexpected file type in harness path: ${path}`);
789
- }
790
- }
791
- }
792
- function assertManagedPaths(root, files) {
793
- for (const path of files) assertManagedLocation(path);
794
- const canonicalRoot2 = canonicalTargetRoot(root);
795
- for (const path of files) assertNoSymbolicComponents(canonicalRoot2, path);
796
- }
797
-
798
- // src/cli/manifest.ts
799
- import { createHash } from "crypto";
800
- import { chmodSync, existsSync as existsSync4, readFileSync as readFileSync5, writeFileSync } from "fs";
801
- import { join as join5 } from "path";
802
- import { z as z5 } from "zod";
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`);
825
- }
826
- }
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}`);
834
- }
835
- config.mcp = mcp;
836
- if (ownership.addedMcp && Object.keys(mcp).length === 0) Reflect.deleteProperty(config, "mcp");
837
- }
838
- if (ownership.addedSchema && config.$schema === OPENCODE_SCHEMA)
839
- Reflect.deleteProperty(config, "$schema");
840
- }
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}`);
849
- }
850
- continue;
851
- }
852
- entries[id] = ObjectSchema.parse(entry);
853
- mcp[id] = entry;
854
- }
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;
865
- }
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 };
880
- }
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
- };
888
- }
889
-
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";
894
- import { z as z4 } from "zod";
895
- var LEGACY_OPENCODE_CONFIG = ".opencode/mcp.json";
896
- var SHARED_CONFIG_PATHS = [
897
- ".mcp.json",
898
- ".codex/config.toml",
899
- OPENCODE_CONFIG_PATH,
900
- LEGACY_OPENCODE_CONFIG,
901
- ".claude/settings.json",
902
- ".codex/hooks.json"
903
- ];
904
- var ObjectSchema2 = z4.record(z4.unknown());
905
- var HookEntrySchema = z4.object({ group: ObjectSchema2, hook: ObjectSchema2 });
906
- var HookConfigOwnershipSchema = z4.object({
907
- createdFile: z4.boolean(),
908
- addedHooks: z4.boolean(),
909
- addedStop: z4.boolean(),
910
- entries: z4.array(HookEntrySchema)
911
- });
912
- var HookConfigsOwnershipSchema = z4.object({
913
- ".claude/settings.json": HookConfigOwnershipSchema.optional(),
914
- ".codex/hooks.json": HookConfigOwnershipSchema.optional()
915
- }).strict();
916
- var HOOK_ENGINES = {
917
- ".claude/settings.json": "claude-code",
918
- ".codex/hooks.json": "codex-cli"
919
- };
920
- function parseObject(content, path) {
921
- try {
922
- return ObjectSchema2.parse(JSON.parse(content));
923
- } catch {
924
- throw new Error(`invalid shared configuration ${path}: expected a JSON object`);
925
- }
926
- }
927
- function asObject(value) {
928
- const parsed = ObjectSchema2.safeParse(value);
929
- return parsed.success ? parsed.data : void 0;
930
- }
931
- function stopHooks(config, path) {
932
- if (!Object.hasOwn(config, "hooks")) return [];
933
- const hooks = asObject(config.hooks);
934
- if (!hooks || Object.hasOwn(hooks, "Stop") && !Array.isArray(hooks.Stop)) {
935
- throw new Error(`invalid shared configuration ${path}: expected hooks.Stop to be an array`);
936
- }
937
- return Array.isArray(hooks.Stop) ? hooks.Stop : [];
938
- }
939
- function groupMetadata(group) {
940
- return Object.fromEntries(Object.entries(group).filter(([key]) => key !== "hooks"));
941
- }
942
- function sameEntry(left, right) {
943
- return isDeepStrictEqual2(left.group, right.group) && isDeepStrictEqual2(left.hook, right.hook);
944
- }
945
- function appendEntry(entries, entry) {
946
- if (!entries.some((existing) => sameEntry(existing, entry))) entries.push(entry);
947
- }
948
- function defaultStopGroup(engine) {
949
- const file = getRenderer(engine).renderStopHook().files[0];
950
- if (!file) throw new Error(`missing Stop hook renderer for ${engine}`);
951
- const group = asObject(stopHooks(parseObject(file.content, file.path), file.path)[0]);
952
- if (!group || !Array.isArray(group.hooks) || !asObject(group.hooks[0])) {
953
- throw new Error(`invalid Stop hook renderer for ${engine}`);
954
- }
955
- return group;
956
- }
957
- function normalizeHarnessHooks(groups, expected, previous, claimExisting, warnings, path) {
958
- const defaultHook = ObjectSchema2.parse(expected.hooks[0]);
959
- const entries = [...previous?.entries ?? []];
960
- let found = false;
961
- const normalized = groups.map((value) => {
962
- const group = asObject(value);
963
- if (!group) return value;
964
- const flat = group.type === "command" && group.command === defaultHook.command;
965
- const hooks = flat ? [group] : Array.isArray(group.hooks) ? group.hooks : [];
966
- const metadata = flat ? groupMetadata(expected) : groupMetadata(group);
967
- for (const value2 of hooks) {
968
- const hook = asObject(value2);
969
- if (!hook || hook.type !== "command" || hook.command !== defaultHook.command) continue;
970
- found = true;
971
- const entry = { group: metadata, hook };
972
- if (!claimExisting) continue;
973
- if (previous && !previous.entries.some((old) => sameEntry(old, entry))) {
974
- warnings.push(`preserved modified harness Stop hook: ${path}`);
975
- } else {
976
- appendEntry(entries, entry);
977
- }
978
- }
979
- return flat && claimExisting ? { ...metadata, hooks: [group] } : value;
980
- });
981
- if (!found && !previous?.entries.length) {
982
- normalized.push(expected);
983
- appendEntry(entries, { group: groupMetadata(expected), hook: defaultHook });
984
- } else if (!found) {
985
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
986
- }
987
- return { groups: normalized, entries };
988
- }
989
- function removeOwnedHooks(config, ownership, path, warnings) {
990
- const groups = stopHooks(config, path);
991
- const remaining = [];
992
- const matched = /* @__PURE__ */ new Set();
993
- for (const value of groups) {
994
- const group = asObject(value);
995
- if (!group || !Array.isArray(group.hooks)) {
996
- remaining.push(value);
997
- continue;
998
- }
999
- const metadata = groupMetadata(group);
1000
- const hooks2 = group.hooks.filter((value2) => {
1001
- const hook = asObject(value2);
1002
- const entry = hook && ownership.entries.find((old) => sameEntry(old, { group: metadata, hook }));
1003
- if (entry) matched.add(entry);
1004
- return !entry;
1005
- });
1006
- if (hooks2.length > 0 || hooks2.length === group.hooks.length) {
1007
- remaining.push({ ...group, hooks: hooks2 });
1008
- }
1009
- }
1010
- if (matched.size < ownership.entries.length) {
1011
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
1012
- }
1013
- const hooks = asObject(config.hooks);
1014
- if (!hooks) return;
1015
- if (ownership.addedStop && remaining.length === 0) Reflect.deleteProperty(hooks, "Stop");
1016
- else if (Object.hasOwn(hooks, "Stop")) hooks.Stop = remaining;
1017
- if (ownership.addedHooks && Object.keys(hooks).length === 0)
1018
- Reflect.deleteProperty(config, "hooks");
1019
- else config.hooks = hooks;
1020
- }
1021
- function recordMutation(plan, path, before, after, createdFile) {
1022
- if (createdFile && Object.keys(after).length === 0) {
1023
- if (before) plan.removals.push(path);
1024
- } else if (!isDeepStrictEqual2(before, after)) {
1025
- plan.writes.push({ path, content: `${JSON.stringify(after, null, 2)}
1026
- ` });
1027
- }
1028
- }
1029
- function planHookConfigCleanup(root, ownership) {
1030
- const plan = { writes: [], removals: [], warnings: [] };
1031
- if (!ownership) return plan;
1032
- const validated = HookConfigsOwnershipSchema.parse(ownership);
1033
- assertManagedPaths(root, Object.keys(validated));
1034
- for (const path of Object.keys(HOOK_ENGINES)) {
1035
- const owned = validated[path];
1036
- if (!owned || !existsSync3(join4(root, path))) continue;
1037
- const before = parseObject(readFileSync4(join4(root, path), "utf8"), path);
1038
- const config = structuredClone(before);
1039
- removeOwnedHooks(config, owned, path, plan.warnings);
1040
- recordMutation(plan, path, before, config, owned.createdFile);
1041
- }
1042
- return plan;
1043
- }
1044
- function planActiveHook(root, path, previous, claimExisting, plan) {
1045
- assertManagedPaths(root, [path]);
1046
- const existed = existsSync3(join4(root, path));
1047
- if (!existed && previous?.entries.length) {
1048
- plan.warnings.push(`preserved removed harness Stop hook configuration: ${path}`);
1049
- return previous;
1050
- }
1051
- const before = existed ? parseObject(readFileSync4(join4(root, path), "utf8"), path) : void 0;
1052
- const config = structuredClone(before ?? {});
1053
- const groups = stopHooks(config, path);
1054
- const hooks = asObject(config.hooks) ?? {};
1055
- const normalized = normalizeHarnessHooks(
1056
- groups,
1057
- defaultStopGroup(HOOK_ENGINES[path]),
1058
- previous,
1059
- claimExisting,
1060
- plan.warnings,
1061
- path
1062
- );
1063
- const ownership = {
1064
- createdFile: !existed || previous?.createdFile === true,
1065
- addedHooks: previous?.addedHooks ?? !Object.hasOwn(config, "hooks"),
1066
- addedStop: previous?.addedStop ?? !Object.hasOwn(hooks, "Stop"),
1067
- entries: normalized.entries
1068
- };
1069
- if (!isDeepStrictEqual2(groups, normalized.groups)) {
1070
- config.hooks = { ...hooks, Stop: normalized.groups };
1071
- }
1072
- recordMutation(plan, path, before, config, ownership.createdFile);
1073
- return ownership.entries.length > 0 ? ownership : void 0;
1074
- }
1075
- function planLegacyOpenCode(root, previous, plan) {
1076
- if (!previous.files.includes(LEGACY_OPENCODE_CONFIG)) return;
1077
- const legacyPath = join4(root, LEGACY_OPENCODE_CONFIG);
1078
- if (!existsSync3(legacyPath)) return;
1079
- assertManagedPaths(root, [LEGACY_OPENCODE_CONFIG, OPENCODE_CONFIG_PATH]);
1080
- const legacy = parseObject(readFileSync4(legacyPath, "utf8"), LEGACY_OPENCODE_CONFIG);
1081
- if (!asObject(legacy.mcp)) {
545
+ // src/cli/plan-render.ts
546
+ var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
547
+ function resolveEngineList(requested) {
548
+ if (!requested || requested.length === 0) {
1082
549
  throw new Error(
1083
- `invalid shared configuration ${LEGACY_OPENCODE_CONFIG}: expected an MCP object`
550
+ `no engine selected: pass --engines=<list> with one or more of ${ENGINES.join(", ")}`
1084
551
  );
1085
552
  }
1086
- const merged = planOpenCodeConfig(
1087
- root,
1088
- { path: OPENCODE_CONFIG_PATH, content: JSON.stringify(legacy) },
1089
- void 0
1090
- );
1091
- if (merged.write) plan.writes.push(merged.write);
1092
- plan.warnings.push(...merged.warnings);
1093
- if (merged.ownership) {
1094
- const old = previous.opencodeConfig;
1095
- plan.opencodeConfig = {
1096
- createdFile: merged.ownership.createdFile || old?.createdFile === true,
1097
- addedMcp: merged.ownership.addedMcp || old?.addedMcp === true,
1098
- addedSchema: merged.ownership.addedSchema || old?.addedSchema === true,
1099
- entries: { ...old?.entries, ...merged.ownership.entries }
1100
- };
1101
- }
1102
- plan.removals.push(LEGACY_OPENCODE_CONFIG);
1103
- }
1104
- function planUpdateConfigs(root, previous, hookEngines) {
1105
- const plan = {
1106
- writes: [],
1107
- removals: [],
1108
- ownedFiles: [],
1109
- warnings: [],
1110
- ...previous.opencodeConfig ? { opencodeConfig: previous.opencodeConfig } : {}
1111
- };
1112
- planLegacyOpenCode(root, previous, plan);
1113
- const hookConfigs = {};
1114
- for (const path of Object.keys(HOOK_ENGINES)) {
1115
- const owned = previous.hookConfigs?.[path];
1116
- if (hookEngines.includes(HOOK_ENGINES[path])) {
1117
- hookConfigs[path] = planActiveHook(
1118
- root,
1119
- path,
1120
- owned,
1121
- previous.files.includes(path) || Boolean(owned),
1122
- plan
1123
- );
1124
- } else if (owned) {
1125
- const cleanup = planHookConfigCleanup(root, { [path]: owned });
1126
- plan.writes.push(...cleanup.writes);
1127
- plan.removals.push(...cleanup.removals);
1128
- plan.warnings.push(...cleanup.warnings);
553
+ const engines = requested.map((e) => {
554
+ if (!ENGINES.includes(e)) {
555
+ throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
1129
556
  }
1130
- }
1131
- if (Object.values(hookConfigs).some(Boolean)) plan.hookConfigs = hookConfigs;
1132
- if (hookEngines.includes("opencode")) {
1133
- const plugin = getRenderer("opencode").renderStopHook();
1134
- plan.writes.push(...plugin.files);
1135
- plan.ownedFiles.push(...plugin.files.map((file) => file.path));
1136
- plan.warnings.push(...plugin.warnings);
1137
- }
1138
- return plan;
1139
- }
1140
-
1141
- // src/cli/manifest.ts
1142
- var MANIFEST_FILENAME = ".harness-manifest.json";
1143
- var MANIFEST_VERSION = "6";
1144
- var ManifestSchema = z5.object({
1145
- version: z5.enum(["4", "5", MANIFEST_VERSION]),
1146
- engines: z5.array(z5.string()),
1147
- renderedAt: z5.string(),
1148
- files: z5.array(z5.string()),
1149
- stopHookInstalled: z5.boolean().optional(),
1150
- stopHookEngines: z5.array(z5.string()).optional(),
1151
- opencodeConfig: OpenCodeConfigOwnershipSchema.optional(),
1152
- hookConfigs: HookConfigsOwnershipSchema.optional(),
1153
- harnessVersion: z5.string().optional(),
1154
- overridesDir: z5.string().optional(),
1155
- fileHashes: z5.record(z5.string().regex(/^[a-f0-9]{64}$/)).optional(),
1156
- preservedFiles: z5.array(z5.string()).optional()
1157
- });
1158
- function manifestPath(targetDir) {
1159
- return join5(targetDir, MANIFEST_FILENAME);
1160
- }
1161
- function writeManifest(targetDir, engines, files, extras = {}) {
1162
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
1163
- const manifest = {
1164
- version: MANIFEST_VERSION,
1165
- harnessVersion: VERSION,
1166
- engines: [...engines].sort(),
1167
- renderedAt: (/* @__PURE__ */ new Date()).toISOString(),
1168
- files: [...files].sort(),
1169
- fileHashes: Object.fromEntries(
1170
- files.filter((file) => existsSync4(join5(targetDir, file))).sort().map((file) => [file, hashContent(readFileSync5(join5(targetDir, file)))])
1171
- ),
1172
- ...extras.overridesDir ? { overridesDir: extras.overridesDir } : {},
1173
- ...extras.preservedFiles ? { preservedFiles: extras.preservedFiles } : {},
1174
- ...extras.hookConfigs ? { hookConfigs: extras.hookConfigs } : {},
1175
- ...extras.opencodeConfig ? { opencodeConfig: extras.opencodeConfig } : {},
1176
- ...extras.stopHookInstalled !== void 0 ? { stopHookInstalled: extras.stopHookInstalled } : {},
1177
- ...extras.stopHookEngines !== void 0 ? { stopHookEngines: [...extras.stopHookEngines].sort() } : {}
1178
- };
1179
- const path = manifestPath(targetDir);
1180
- if (existsSync4(path)) chmodSync(path, 384);
1181
- writeFileSync(path, `${JSON.stringify(manifest, null, 2)}
1182
- `, { mode: 384 });
557
+ return e;
558
+ });
559
+ return [...new Set(engines)];
1183
560
  }
1184
- function hashContent(content) {
1185
- return createHash("sha256").update(content).digest("hex");
561
+ function defaultPackageDir() {
562
+ const here = dirname2(fileURLToPath(import.meta.url));
563
+ if (existsSync3(join4(here, "skills"))) return here;
564
+ return resolve2(here, "..");
1186
565
  }
1187
- function readManifest(targetDir) {
1188
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
1189
- const path = manifestPath(targetDir);
1190
- if (!existsSync4(path)) return null;
1191
- const raw = JSON.parse(readFileSync5(path, "utf8"));
1192
- return ManifestSchema.parse(raw);
566
+ function planInit(args) {
567
+ const engines = resolveEngineList(args.engines);
568
+ const packageDir = args.packageDir ?? defaultPackageDir();
569
+ const harness = loadHarness(packageDir);
570
+ const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
571
+ const projectSkills = loadProjectSkills(args.targetDir);
572
+ const hasQualityDoc = existsSync3(join4(args.targetDir, QUALITY_DOC_PATH));
573
+ const output = render({ harness, engines, overrides, projectSkills, hasQualityDoc });
574
+ return { engines, output };
1193
575
  }
1194
576
 
1195
577
  // src/cli/uninstall.ts
1196
- import { existsSync as existsSync5, readdirSync, rmdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
1197
- import { dirname as dirname2, join as join6, relative, resolve as resolve2 } from "path";
1198
- function removeRenderedFiles(root, files) {
1199
- assertManagedPaths(root, files);
1200
- const filesRemoved = [];
1201
- const missing = [];
1202
- const dirsToConsider = /* @__PURE__ */ new Set();
1203
- for (const rel of files) {
1204
- const full = join6(root, rel);
1205
- if (existsSync5(full)) {
1206
- unlinkSync(full);
1207
- filesRemoved.push(rel);
1208
- dirsToConsider.add(dirname2(full));
1209
- } else {
1210
- missing.push(rel);
1211
- }
1212
- }
1213
- return { filesRemoved, dirsPruned: pruneEmptyDirs(root, dirsToConsider), missing };
1214
- }
578
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, rmdirSync, unlinkSync } from "fs";
579
+ import { dirname as dirname3, join as join5, relative, resolve as resolve3 } from "path";
1215
580
  function pruneEmptyDirs(root, leaves) {
1216
581
  const candidates = /* @__PURE__ */ new Set();
1217
582
  for (const leaf of leaves) {
1218
583
  let cur = leaf;
1219
584
  while (cur !== root && cur.startsWith(`${root}/`)) {
1220
585
  candidates.add(cur);
1221
- cur = dirname2(cur);
586
+ cur = dirname3(cur);
1222
587
  }
1223
588
  }
1224
589
  const pruned = [];
1225
590
  const sorted = [...candidates].sort((a, b) => b.length - a.length);
1226
591
  for (const dir of sorted) {
1227
- if (!existsSync5(dir)) continue;
592
+ if (!existsSync4(dir)) continue;
1228
593
  if (readdirSync(dir).length > 0) continue;
1229
594
  rmdirSync(dir);
1230
595
  pruned.push(relative(root, dir));
@@ -1232,145 +597,6 @@ function pruneEmptyDirs(root, leaves) {
1232
597
  return pruned;
1233
598
  }
1234
599
 
1235
- // src/cli/init.ts
1236
- var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
1237
- function resolveEngineList(requested) {
1238
- if (!requested || requested.length === 0) return [...ENGINES];
1239
- return requested.map((e) => {
1240
- if (!ENGINES.includes(e)) {
1241
- throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
1242
- }
1243
- return e;
1244
- });
1245
- }
1246
- function defaultPackageDir() {
1247
- const here = dirname3(fileURLToPath(import.meta.url));
1248
- if (existsSync6(join7(here, "agents"))) return here;
1249
- return resolve3(here, "..");
1250
- }
1251
- function planInit(args) {
1252
- const engines = resolveEngineList(args.engines);
1253
- const packageDir = args.packageDir ?? defaultPackageDir();
1254
- const harness = loadHarness(packageDir);
1255
- const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
1256
- const projectSkills = loadProjectSkills(args.targetDir);
1257
- const hasQualityDoc = existsSync6(join7(args.targetDir, QUALITY_DOC_PATH));
1258
- const mcpServers = args.mcpServers ? resolveMcpIds(args.mcpServers) : void 0;
1259
- const stopHookInstalled = args.withStopHook !== false;
1260
- const output = render({
1261
- harness,
1262
- engines,
1263
- overrides,
1264
- projectSkills,
1265
- hasQualityDoc,
1266
- mcpServers,
1267
- withStopHook: stopHookInstalled
1268
- });
1269
- return { engines, output, stopHookInstalled };
1270
- }
1271
- function writeFilesToTarget(files, targetDir) {
1272
- assertManagedPaths(
1273
- targetDir,
1274
- files.map((file) => file.path)
1275
- );
1276
- const written = [];
1277
- for (const f of files) {
1278
- const full = join7(targetDir, f.path);
1279
- mkdirSync(dirname3(full), { recursive: true });
1280
- writeFileSync3(full, f.content);
1281
- written.push(f.path);
1282
- }
1283
- return written;
1284
- }
1285
- function initCommand(args) {
1286
- const { engines, output, stopHookInstalled } = planInit(args);
1287
- const previous = readManifest(args.targetDir);
1288
- assertManagedPaths(args.targetDir, [
1289
- MANIFEST_FILENAME,
1290
- ...previous?.files ?? [],
1291
- ...output.files.map((file) => file.path),
1292
- ...previous?.opencodeConfig ? [OPENCODE_CONFIG_PATH] : []
1293
- ]);
1294
- const desiredConfig = output.files.find((file) => file.path === OPENCODE_CONFIG_PATH);
1295
- const config = planOpenCodeConfig(args.targetDir, desiredConfig, previous?.opencodeConfig);
1296
- const next = new Set(output.files.map((f) => f.path));
1297
- const stale = (previous?.files ?? []).filter((f) => !next.has(f) && f !== OPENCODE_CONFIG_PATH);
1298
- if (config.remove) stale.push(OPENCODE_CONFIG_PATH);
1299
- const staleFilesRemoved = removeRenderedFiles(resolve3(args.targetDir), stale).filesRemoved;
1300
- const ownedFiles = output.files.filter((file) => file.path !== OPENCODE_CONFIG_PATH);
1301
- const filesWritten = writeFilesToTarget(ownedFiles, args.targetDir);
1302
- if (config.write) writeFilesToTarget([config.write], args.targetDir);
1303
- writeManifest(args.targetDir, engines, filesWritten, {
1304
- stopHookInstalled,
1305
- stopHookEngines: stopHookInstalled ? engines : void 0,
1306
- opencodeConfig: config.ownership,
1307
- overridesDir: args.overridesDir ? resolve3(args.overridesDir) === resolve3(args.targetDir) ? "." : resolve3(args.overridesDir) : void 0
1308
- });
1309
- if (config.write) filesWritten.push(OPENCODE_CONFIG_PATH);
1310
- const warnings = [...output.warnings, ...config.warnings];
1311
- if (previous?.files.includes(OPENCODE_CONFIG_PATH) && !previous.opencodeConfig) {
1312
- warnings.push(`preserved legacy shared configuration: ${OPENCODE_CONFIG_PATH}`);
1313
- }
1314
- return { filesWritten, staleFilesRemoved, warnings, stopHookInstalled };
1315
- }
1316
-
1317
- // src/cli/update.ts
1318
- import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
1319
- import { join as join10, resolve as resolve5 } from "path";
1320
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
1321
-
1322
- // src/cli/update-manifest.ts
1323
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
1324
- import { join as join8 } from "path";
1325
- import { z as z6 } from "zod";
1326
- var EngineSchema = z6.enum(ENGINES);
1327
- var LegacySchema = z6.object({
1328
- version: z6.enum(["1", "2", "3"]),
1329
- engine: EngineSchema.optional(),
1330
- engines: z6.array(EngineSchema).nonempty().optional(),
1331
- renderedAt: z6.string(),
1332
- files: z6.array(z6.string())
1333
- });
1334
- var HOOK_PATHS = {
1335
- "claude-code": [".claude/settings.json"],
1336
- "codex-cli": [".codex/hooks.json"],
1337
- opencode: [
1338
- ".opencode/plugins/harness-stop-hook/index.ts",
1339
- ".opencode/plugins/harness-stop-hook.ts"
1340
- ]
1341
- };
1342
- function readUpdateInstallation(root) {
1343
- assertManagedPaths(root, [MANIFEST_FILENAME]);
1344
- if (!existsSync7(join8(root, MANIFEST_FILENAME))) {
1345
- throw new Error("no harness manifest found; use init for a new installation");
1346
- }
1347
- const raw = JSON.parse(readFileSync6(join8(root, MANIFEST_FILENAME), "utf8"));
1348
- const sourceVersion = String(raw?.version);
1349
- let manifest;
1350
- if (["1", "2", "3"].includes(sourceVersion)) {
1351
- const legacy = LegacySchema.parse(raw);
1352
- const engines2 = legacy.version === "1" ? [EngineSchema.parse(legacy.engine)] : legacy.engines;
1353
- manifest = {
1354
- version: "4",
1355
- engines: z6.array(EngineSchema).nonempty().parse(engines2),
1356
- files: legacy.files,
1357
- renderedAt: legacy.renderedAt
1358
- };
1359
- } else {
1360
- const current = readManifest(root);
1361
- if (!current) throw new Error("harness manifest disappeared during planning");
1362
- manifest = current;
1363
- }
1364
- const engines = [...new Set(z6.array(EngineSchema).nonempty().parse(manifest.engines))];
1365
- const hookEngines = manifest.stopHookInstalled === false ? [] : manifest.stopHookEngines !== void 0 ? z6.array(EngineSchema).parse(manifest.stopHookEngines) : manifest.stopHookInstalled === true ? engines : engines.filter(
1366
- (engine) => HOOK_PATHS[engine].some((path) => manifest.files.includes(path))
1367
- );
1368
- if (hookEngines.some((engine) => !engines.includes(engine))) {
1369
- throw new Error("manifest stopHookEngines must be a subset of installed engines");
1370
- }
1371
- return { manifest, sourceVersion, engines, hookEngines: [...new Set(hookEngines)] };
1372
- }
1373
-
1374
600
  // src/cli/update-transaction.ts
1375
601
  import { createHash as createHash2, randomUUID } from "crypto";
1376
602
  import {
@@ -1378,27 +604,19 @@ import {
1378
604
  closeSync,
1379
605
  fsyncSync,
1380
606
  lstatSync as lstatSync2,
1381
- mkdirSync as mkdirSync2,
607
+ mkdirSync,
1382
608
  openSync,
1383
- readFileSync as readFileSync7,
609
+ readFileSync as readFileSync5,
1384
610
  readdirSync as readdirSync2,
1385
611
  realpathSync as realpathSync2,
1386
612
  rmdirSync as rmdirSync2,
1387
613
  unlinkSync as unlinkSync2,
1388
- writeFileSync as writeFileSync4
614
+ writeFileSync as writeFileSync2
1389
615
  } from "fs";
1390
616
  import { homedir } from "os";
1391
- import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve4, sep } from "path";
617
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve4, sep } from "path";
1392
618
  var MANIFEST_PATH = ".harness-manifest.json";
1393
- var PRIVATE_FILES = /* @__PURE__ */ new Set([
1394
- MANIFEST_PATH,
1395
- ".mcp.json",
1396
- ".codex/config.toml",
1397
- ".codex/hooks.json",
1398
- ".claude/settings.json",
1399
- ".opencode/opencode.json",
1400
- ".opencode/mcp.json"
1401
- ]);
619
+ var PRIVATE_FILES = /* @__PURE__ */ new Set([MANIFEST_PATH]);
1402
620
  function canonicalRoot(root) {
1403
621
  let ancestor = resolve4(root);
1404
622
  const missing = [];
@@ -1406,7 +624,7 @@ function canonicalRoot(root) {
1406
624
  missing.unshift(basename2(ancestor));
1407
625
  ancestor = dirname4(ancestor);
1408
626
  }
1409
- return join9(realpathSync2(ancestor), ...missing);
627
+ return join6(realpathSync2(ancestor), ...missing);
1410
628
  }
1411
629
  function contains(parent, child) {
1412
630
  const path = relative2(parent, child);
@@ -1438,7 +656,7 @@ function createDirectories(path, created, mode = 511) {
1438
656
  missing.unshift(current);
1439
657
  }
1440
658
  for (const directory of missing) {
1441
- mkdirSync2(directory, { mode });
659
+ mkdirSync(directory, { mode });
1442
660
  created.push(directory);
1443
661
  }
1444
662
  }
@@ -1446,7 +664,7 @@ function writeBackupFile(path, content) {
1446
664
  createDirectories(dirname4(path), [], 448);
1447
665
  const fd = openSync(path, "wx", 384);
1448
666
  try {
1449
- writeFileSync4(fd, content);
667
+ writeFileSync2(fd, content);
1450
668
  fsyncSync(fd);
1451
669
  } finally {
1452
670
  closeSync(fd);
@@ -1455,16 +673,16 @@ function writeBackupFile(path, content) {
1455
673
  function saveSnapshot(root, paths, backup) {
1456
674
  const entries = [];
1457
675
  createDirectories(dirname4(backup), [], 448);
1458
- mkdirSync2(backup, { mode: 448 });
676
+ mkdirSync(backup, { mode: 448 });
1459
677
  for (const path of paths) {
1460
- const full = join9(root, path);
678
+ const full = join6(root, path);
1461
679
  const info = lstatSync2(full, { throwIfNoEntry: false });
1462
680
  if (!info) {
1463
681
  entries.push({ path, exists: false });
1464
682
  continue;
1465
683
  }
1466
- const content = readFileSync7(full);
1467
- writeBackupFile(join9(backup, "files", path), content);
684
+ const content = readFileSync5(full);
685
+ writeBackupFile(join6(backup, "files", path), content);
1468
686
  entries.push({
1469
687
  path,
1470
688
  exists: true,
@@ -1473,7 +691,7 @@ function saveSnapshot(root, paths, backup) {
1473
691
  });
1474
692
  }
1475
693
  writeBackupFile(
1476
- join9(backup, "snapshot.json"),
694
+ join6(backup, "snapshot.json"),
1477
695
  `${JSON.stringify({ version: 1, root, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries }, null, 2)}
1478
696
  `
1479
697
  );
@@ -1488,16 +706,16 @@ function rollback(root, backup, entries, touched, createdDirectories) {
1488
706
  try {
1489
707
  assertManagedPaths(root, [path]);
1490
708
  const entry = entries.get(path);
1491
- const full = join9(root, path);
709
+ const full = join6(root, path);
1492
710
  const current = lstatSync2(full, { throwIfNoEntry: false });
1493
711
  if (!entry?.exists) {
1494
712
  if (current) unlinkSync2(full);
1495
713
  continue;
1496
714
  }
1497
- const original = readFileSync7(join9(backup, "files", path));
1498
- if (!current || !readFileSync7(full).equals(original)) {
715
+ const original = readFileSync5(join6(backup, "files", path));
716
+ if (!current || !readFileSync5(full).equals(original)) {
1499
717
  if (current) unlinkSync2(full);
1500
- writeFileSync4(full, original, { mode: 384 });
718
+ writeFileSync2(full, original, { mode: 384 });
1501
719
  }
1502
720
  chmodSync2(full, entry.mode);
1503
721
  } catch (error) {
@@ -1518,7 +736,7 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1518
736
  assertManagedPaths(root, paths);
1519
737
  const target = canonicalRoot(root);
1520
738
  const backup = resolve4(
1521
- backupDir ?? join9(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
739
+ backupDir ?? join6(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
1522
740
  );
1523
741
  assertBackupLocation(target, backup);
1524
742
  let snapshot;
@@ -1536,18 +754,18 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1536
754
  try {
1537
755
  assertManagedPaths(target, paths);
1538
756
  for (const path of removals) {
1539
- if (!lstatSync2(join9(target, path), { throwIfNoEntry: false })) continue;
757
+ if (!lstatSync2(join6(target, path), { throwIfNoEntry: false })) continue;
1540
758
  touched.add(path);
1541
- unlinkSync2(join9(target, path));
759
+ unlinkSync2(join6(target, path));
1542
760
  }
1543
761
  for (const file of writes) {
1544
- const full = join9(target, file.path);
762
+ const full = join6(target, file.path);
1545
763
  createDirectories(dirname4(full), createdDirectories);
1546
764
  touched.add(file.path);
1547
765
  const entry = entries.get(file.path);
1548
766
  const mode = file.path === MANIFEST_PATH ? 384 : entry?.exists ? entry.mode : PRIVATE_FILES.has(file.path) ? 384 : 420;
1549
767
  if (entry?.exists && file.path === MANIFEST_PATH) chmodSync2(full, mode);
1550
- writeFileSync4(full, file.content, { mode });
768
+ writeFileSync2(full, file.content, { mode });
1551
769
  if (entry?.exists) chmodSync2(full, mode);
1552
770
  }
1553
771
  } catch (error) {
@@ -1561,50 +779,115 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1561
779
  }
1562
780
 
1563
781
  // src/cli/update.ts
782
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
783
+ import { dirname as dirname5, join as join8, resolve as resolve5 } from "path";
784
+ import { isDeepStrictEqual } from "util";
785
+
786
+ // src/cli/update-manifest.ts
787
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
788
+ import { join as join7 } from "path";
789
+ import { z as z4 } from "zod";
790
+ var EngineSchema = z4.enum(ENGINES);
791
+ var LegacySchema = z4.object({
792
+ version: z4.enum(["1", "2", "3"]),
793
+ engine: EngineSchema.optional(),
794
+ engines: z4.array(EngineSchema).nonempty().optional(),
795
+ renderedAt: z4.string(),
796
+ files: z4.array(z4.string())
797
+ });
798
+ function readUpdateInstallation(root) {
799
+ assertManagedPaths(root, [MANIFEST_FILENAME]);
800
+ if (!existsSync5(join7(root, MANIFEST_FILENAME))) {
801
+ throw new Error("no harness manifest found; use init for a new installation");
802
+ }
803
+ const raw = JSON.parse(readFileSync6(join7(root, MANIFEST_FILENAME), "utf8"));
804
+ const sourceVersion = String(raw?.version);
805
+ let manifest;
806
+ if (["1", "2", "3"].includes(sourceVersion)) {
807
+ const legacy = LegacySchema.parse(raw);
808
+ const engines2 = legacy.version === "1" ? [EngineSchema.parse(legacy.engine)] : legacy.engines;
809
+ manifest = {
810
+ version: "4",
811
+ engines: z4.array(EngineSchema).nonempty().parse(engines2),
812
+ files: legacy.files,
813
+ renderedAt: legacy.renderedAt
814
+ };
815
+ } else {
816
+ const current = readManifest(root);
817
+ if (!current) throw new Error("harness manifest disappeared during planning");
818
+ manifest = current;
819
+ }
820
+ const engines = [...new Set(z4.array(EngineSchema).nonempty().parse(manifest.engines))];
821
+ return { manifest, sourceVersion, engines };
822
+ }
823
+
824
+ // src/cli/update.ts
825
+ var LEGACY_HOOK_FILES = [".claude/settings.json", ".codex/hooks.json"];
826
+ var LEGACY_HOOK_MARKER = "@vaubaan/harness stop-hook";
1564
827
  function currentContent(root, path) {
1565
- return existsSync8(join10(root, path)) ? readFileSync8(join10(root, path), "utf8") : void 0;
828
+ return existsSync6(join8(root, path)) ? readFileSync7(join8(root, path), "utf8") : void 0;
1566
829
  }
1567
830
  function checkArtifactConflicts(root, previous, writes, removals) {
1568
831
  const desired = new Map(writes.map((file) => [file.path, file.content]));
832
+ const conflicts = [];
1569
833
  for (const path of [...desired.keys(), ...removals]) {
1570
- if (SHARED_CONFIG_PATHS.includes(path)) continue;
1571
834
  const content = currentContent(root, path);
1572
- if (content === void 0) continue;
835
+ if (content === void 0 || content === desired.get(path)) continue;
1573
836
  if (!previous.files.includes(path)) {
1574
- throw new Error(
1575
- `existing file outside harness manifest: ${path}; use overrides or --preserve`
1576
- );
837
+ conflicts.push(`existing file outside harness manifest: ${path}`);
838
+ continue;
1577
839
  }
1578
840
  const hash = previous.fileHashes?.[path];
1579
- if (hash && hash !== hashContent(content) && content !== desired.get(path)) {
1580
- throw new Error(`modified harness file: ${path}; move edits to overrides or use --preserve`);
841
+ if (hash && hash !== hashContent(content)) conflicts.push(`modified harness file: ${path}`);
842
+ }
843
+ if (conflicts.length) {
844
+ throw new Error(
845
+ `${conflicts.join("\n")}
846
+ move their content to docs/ or .harness-overrides/, or keep them as yours with --preserve <path>`
847
+ );
848
+ }
849
+ }
850
+ function releaseLegacyPaths(previous, warnings) {
851
+ const released = previous.files.filter((path) => RELEASED_PATHS.includes(path));
852
+ for (const path of released) {
853
+ warnings.push(`no longer managed by the harness, left in place: ${path}`);
854
+ }
855
+ if (released.length === 0) return previous;
856
+ return { ...previous, files: previous.files.filter((path) => !released.includes(path)) };
857
+ }
858
+ function legacyHookWarnings(root) {
859
+ const warnings = [];
860
+ for (const path of LEGACY_HOOK_FILES) {
861
+ const content = currentContent(root, path);
862
+ if (content?.includes(LEGACY_HOOK_MARKER)) {
863
+ warnings.push(
864
+ `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`
865
+ );
1581
866
  }
1582
867
  }
868
+ return warnings;
1583
869
  }
1584
- function planUpdate(args) {
870
+ function planInstallation(args, settings) {
1585
871
  const root = resolve5(args.targetDir);
1586
- const { manifest: previous, sourceVersion, engines, hookEngines } = readUpdateInstallation(root);
872
+ const { engines } = settings;
873
+ const warnings = [];
874
+ const previous = releaseLegacyPaths(settings.previous, warnings);
1587
875
  const preserved = [
1588
876
  .../* @__PURE__ */ new Set([...previous.preservedFiles ?? [], ...args.preserveFiles ?? []])
1589
877
  ].sort();
1590
878
  if (preserved.includes(MANIFEST_FILENAME))
1591
879
  throw new Error("cannot preserve the harness manifest");
1592
- if (preserved.some((path) => SHARED_CONFIG_PATHS.includes(path))) {
1593
- throw new Error(
1594
- "--preserve applies to generated artifacts; shared configurations use entry-level preservation"
1595
- );
1596
- }
1597
- assertManagedPaths(root, [...previous.files, ...preserved, ...SHARED_CONFIG_PATHS]);
880
+ assertManagedPaths(root, [...previous.files, ...preserved]);
1598
881
  const requestedOverrides = args.overridesDir ?? previous.overridesDir;
1599
882
  const overridesDir = args.overridesDir ? resolve5(args.overridesDir) : previous.overridesDir ? resolve5(root, previous.overridesDir) : root;
1600
- if (requestedOverrides && !existsSync8(join10(overridesDir, ".harness-overrides"))) {
883
+ if (requestedOverrides && !existsSync6(join8(overridesDir, ".harness-overrides"))) {
1601
884
  throw new Error(`recorded overrides are missing: ${overridesDir}/.harness-overrides`);
1602
885
  }
1603
- const hasOverrides = existsSync8(join10(overridesDir, ".harness-overrides"));
1604
- const disablePath = join10(overridesDir, ".harness-overrides", "disable.yaml");
1605
- if (existsSync8(disablePath)) {
886
+ const hasOverrides = existsSync6(join8(overridesDir, ".harness-overrides"));
887
+ const disablePath = join8(overridesDir, ".harness-overrides", "disable.yaml");
888
+ if (existsSync6(disablePath)) {
1606
889
  try {
1607
- DisableYamlSchema.parse(parseYAML(readFileSync8(disablePath, "utf8")));
890
+ DisableYamlSchema.parse(parseYAML(readFileSync7(disablePath, "utf8")));
1608
891
  } catch {
1609
892
  throw new Error(`invalid override selection: ${disablePath}`);
1610
893
  }
@@ -1613,33 +896,16 @@ function planUpdate(args) {
1613
896
  targetDir: root,
1614
897
  packageDir: args.packageDir,
1615
898
  engines,
1616
- overridesDir: hasOverrides ? overridesDir : void 0,
1617
- withStopHook: false
899
+ overridesDir: hasOverrides ? overridesDir : void 0
1618
900
  });
1619
- const config = planUpdateConfigs(root, previous, hookEngines);
1620
- const output = [...rendered.output.files, ...config.writes].filter(
1621
- (file) => !preserved.includes(file.path)
901
+ const output = rendered.output.files.filter((file) => !preserved.includes(file.path));
902
+ const owned = output.map((file) => file.path).sort();
903
+ const removals = previous.files.filter(
904
+ (file) => !owned.includes(file) && !preserved.includes(file)
1622
905
  );
1623
- const owned = [
1624
- .../* @__PURE__ */ new Set([...rendered.output.files.map((file) => file.path), ...config.ownedFiles])
1625
- ].filter((file) => !preserved.includes(file)).sort();
1626
- const removals = [
1627
- .../* @__PURE__ */ new Set([
1628
- ...previous.files.filter(
1629
- (file) => !owned.includes(file) && !SHARED_CONFIG_PATHS.includes(file)
1630
- ),
1631
- ...config.removals
1632
- ])
1633
- ].filter((file) => !preserved.includes(file));
1634
- assertManagedPaths(root, [...output.map((file) => file.path), ...removals]);
906
+ assertManagedPaths(root, [...owned, ...removals]);
1635
907
  checkArtifactConflicts(root, previous, output, removals);
1636
- const hashes = Object.fromEntries(
1637
- owned.map((path) => {
1638
- const content = output.find((file) => file.path === path)?.content ?? currentContent(root, path);
1639
- if (content === void 0) throw new Error(`missing planned harness file: ${path}`);
1640
- return [path, hashContent(content)];
1641
- })
1642
- );
908
+ const hashes = Object.fromEntries(output.map((file) => [file.path, hashContent(file.content)]));
1643
909
  const manifest = {
1644
910
  version: MANIFEST_VERSION,
1645
911
  harnessVersion: VERSION,
@@ -1647,39 +913,41 @@ function planUpdate(args) {
1647
913
  renderedAt: previous.renderedAt,
1648
914
  files: owned,
1649
915
  fileHashes: hashes,
1650
- stopHookInstalled: hookEngines.length > 0,
1651
- stopHookEngines: [...hookEngines].sort(),
1652
916
  ...hasOverrides ? { overridesDir: overridesDir === root ? "." : overridesDir } : {},
1653
- ...preserved.length ? { preservedFiles: preserved } : {},
1654
- ...config.opencodeConfig ? { opencodeConfig: config.opencodeConfig } : {},
1655
- ...config.hookConfigs ? { hookConfigs: config.hookConfigs } : {}
917
+ ...preserved.length ? { preservedFiles: preserved } : {}
1656
918
  };
1657
919
  const writes = output.filter((file) => currentContent(root, file.path) !== file.content);
1658
- const existingRemovals = removals.filter((path) => existsSync8(join10(root, path)));
1659
- if (writes.length || existingRemovals.length || !isDeepStrictEqual3(previous, manifest)) {
920
+ const existingRemovals = removals.filter((path) => existsSync6(join8(root, path)));
921
+ if (writes.length || existingRemovals.length || !isDeepStrictEqual(settings.previous, manifest)) {
1660
922
  manifest.renderedAt = (/* @__PURE__ */ new Date()).toISOString();
1661
923
  writes.push({ path: MANIFEST_FILENAME, content: `${JSON.stringify(manifest, null, 2)}
1662
924
  ` });
1663
925
  }
1664
- const warnings = [...rendered.output.warnings, ...config.warnings];
926
+ warnings.push(...rendered.output.warnings, ...legacyHookWarnings(root));
927
+ if (preserved.length) warnings.push(`preserved user-owned artifacts: ${preserved.join(", ")}`);
928
+ return { writes, removals: existingRemovals, owned, manifest, warnings };
929
+ }
930
+ function planUpdate(args) {
931
+ const root = resolve5(args.targetDir);
932
+ const { manifest: previous, sourceVersion, engines } = readUpdateInstallation(root);
933
+ const plan = planInstallation(args, { previous, sourceVersion, engines });
934
+ const warnings = [...plan.warnings];
1665
935
  if (!previous.fileHashes) {
1666
936
  warnings.push(
1667
937
  "legacy manifest has no file fingerprints: managed artifacts will be regenerated; backup preserves their previous contents"
1668
938
  );
1669
939
  }
1670
- if (preserved.length) warnings.push(`preserved user-owned artifacts: ${preserved.join(", ")}`);
1671
- if (engines.includes("codex-cli"))
1672
- warnings.push("ensure .agents/ is ignored by Git (run harness check)");
1673
940
  return {
1674
- writes,
1675
- removals: existingRemovals,
941
+ writes: plan.writes,
942
+ removals: plan.removals,
943
+ owned: plan.owned,
1676
944
  result: {
1677
945
  version: VERSION,
1678
946
  fromManifestVersion: sourceVersion,
1679
947
  dryRun: args.dryRun === true,
1680
- upToDate: writes.length === 0 && existingRemovals.length === 0,
1681
- filesToWrite: writes.map((file) => file.path),
1682
- filesToRemove: existingRemovals,
948
+ upToDate: plan.writes.length === 0 && plan.removals.length === 0,
949
+ filesToWrite: plan.writes.map((file) => file.path),
950
+ filesToRemove: plan.removals,
1683
951
  warnings
1684
952
  }
1685
953
  };
@@ -1687,14 +955,63 @@ function planUpdate(args) {
1687
955
  function updateCommand(args) {
1688
956
  const plan = planUpdate(args);
1689
957
  if (args.dryRun || plan.result.upToDate) return plan.result;
1690
- const { backupDir } = applyUpdateTransaction(
1691
- resolve5(args.targetDir),
1692
- plan.writes,
1693
- plan.removals,
1694
- args.backupDir
1695
- );
958
+ const root = resolve5(args.targetDir);
959
+ const { backupDir } = applyUpdateTransaction(root, plan.writes, plan.removals, args.backupDir);
960
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname5(join8(root, path)))));
1696
961
  return { ...plan.result, backupDir };
1697
962
  }
963
+
964
+ // src/cli/init.ts
965
+ function writeFilesToTarget(files, targetDir) {
966
+ assertManagedPaths(
967
+ targetDir,
968
+ files.map((file) => file.path)
969
+ );
970
+ const written = [];
971
+ for (const f of files) {
972
+ const full = join9(targetDir, f.path);
973
+ mkdirSync2(dirname6(full), { recursive: true });
974
+ writeFileSync3(full, f.content);
975
+ written.push(f.path);
976
+ }
977
+ return written;
978
+ }
979
+ function emptyManifest(engines) {
980
+ return { version: MANIFEST_VERSION, engines: [...engines], renderedAt: "", files: [] };
981
+ }
982
+ function initCommand(args) {
983
+ const root = resolve6(args.targetDir);
984
+ const engines = resolveEngineList(args.engines);
985
+ const previous = readManifest(root) ?? emptyManifest(engines);
986
+ const plan = planInstallation(
987
+ {
988
+ targetDir: root,
989
+ packageDir: args.packageDir,
990
+ overridesDir: args.overridesDir,
991
+ preserveFiles: args.preserveFiles
992
+ },
993
+ { previous, sourceVersion: previous.version, engines }
994
+ );
995
+ const touchedExisting = [...plan.writes.map((file) => file.path), ...plan.removals].some(
996
+ (path) => path !== MANIFEST_FILENAME && existsSync7(join9(root, path))
997
+ );
998
+ let backupDir;
999
+ if (plan.writes.length || plan.removals.length) {
1000
+ backupDir = applyUpdateTransaction(root, plan.writes, plan.removals, args.backupDir).backupDir;
1001
+ if (!touchedExisting && !args.backupDir) {
1002
+ rmSync(backupDir, { recursive: true, force: true });
1003
+ backupDir = void 0;
1004
+ }
1005
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname6(join9(root, path)))));
1006
+ }
1007
+ return {
1008
+ filesWritten: plan.owned,
1009
+ staleFilesRemoved: plan.removals,
1010
+ warnings: plan.warnings,
1011
+ engines,
1012
+ ...backupDir ? { backupDir } : {}
1013
+ };
1014
+ }
1698
1015
  export {
1699
1016
  VERSION,
1700
1017
  initCommand,