@vaubaan/harness 0.0.0-stage → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +307 -2
  4. package/dist/agents/coding.agent.md +182 -0
  5. package/dist/agents/merge.agent.md +139 -0
  6. package/dist/agents/planning.agent.md +194 -0
  7. package/dist/agents/review.agent.md +176 -0
  8. package/dist/cli/index.d.ts +1 -0
  9. package/dist/cli/index.js +2924 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/commands/clean-code.cmd.md +26 -0
  12. package/dist/commands/decision.cmd.md +19 -0
  13. package/dist/commands/doc-audit.cmd.md +24 -0
  14. package/dist/commands/drift.cmd.md +18 -0
  15. package/dist/commands/handbook.cmd.md +21 -0
  16. package/dist/commands/readme.cmd.md +19 -0
  17. package/dist/commands/spec.cmd.md +20 -0
  18. package/dist/commands/test-plan.cmd.md +22 -0
  19. package/dist/commands/workflow.cmd.md +19 -0
  20. package/dist/index.d.ts +36 -0
  21. package/dist/index.js +1706 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/init.d.ts +42 -0
  24. package/dist/init.js +1088 -0
  25. package/dist/init.js.map +1 -0
  26. package/dist/linters/index.d.ts +43 -0
  27. package/dist/linters/index.js +727 -0
  28. package/dist/linters/index.js.map +1 -0
  29. package/dist/parser/index.d.ts +247 -0
  30. package/dist/parser/index.js +114 -0
  31. package/dist/parser/index.js.map +1 -0
  32. package/dist/render-B9_kNtQc.d.ts +50 -0
  33. package/dist/render.d.ts +3 -0
  34. package/dist/render.js +572 -0
  35. package/dist/render.js.map +1 -0
  36. package/dist/skills/clean-code-guardian.skill.md +391 -0
  37. package/dist/skills/decision-record-writer.skill.md +166 -0
  38. package/dist/skills/doc-audit.skill.md +257 -0
  39. package/dist/skills/drift-detector.skill.md +173 -0
  40. package/dist/skills/handbook-writer.skill.md +185 -0
  41. package/dist/skills/readme-writer.skill.md +131 -0
  42. package/dist/skills/spec-writer.skill.md +165 -0
  43. package/dist/skills/test-plan-writer.skill.md +179 -0
  44. package/dist/skills/workflow-writer.skill.md +168 -0
  45. package/dist/templates/code-quality.md.tmpl +57 -0
  46. package/dist/templates/coding-workflow.md.tmpl +88 -0
  47. package/dist/templates/decision.md.tmpl +60 -0
  48. package/dist/templates/e2e-tests.md.tmpl +62 -0
  49. package/dist/templates/handbook.md.tmpl +58 -0
  50. package/dist/templates/integration-tests.md.tmpl +50 -0
  51. package/dist/templates/readme.md.tmpl +51 -0
  52. package/dist/templates/spec.md.tmpl +64 -0
  53. package/package.json +82 -4
package/dist/index.js ADDED
@@ -0,0 +1,1706 @@
1
+ // src/version.ts
2
+ var VERSION = "1.3.2";
3
+
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";
7
+ import { fileURLToPath } from "url";
8
+
9
+ // src/loader.ts
10
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
11
+ import { join } from "path";
12
+ import fg from "fast-glob";
13
+ import { z as z2 } from "zod";
14
+
15
+ // src/parser/common.ts
16
+ import { readFileSync } from "fs";
17
+ import matter from "gray-matter";
18
+
19
+ // src/parser/schemas.ts
20
+ import { z } from "zod";
21
+
22
+ // src/types.ts
23
+ var AGENT_IDS = ["coding", "review", "merge", "planning"];
24
+ var ENGINES = ["claude-code", "codex-cli", "opencode"];
25
+ var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
26
+ var CAPABILITIES_MATRIX = {
27
+ "claude-code": ["multi-step", "slash-command", "inline-exec"],
28
+ "codex-cli": ["multi-step", "slash-command", "inline-exec"],
29
+ opencode: ["multi-step", "slash-command", "inline-exec"]
30
+ };
31
+ var DEGRADED_CAPABILITIES = {
32
+ "codex-cli": ["multi-step"]
33
+ };
34
+
35
+ // 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({
38
+ 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()
43
+ }).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()
49
+ }).strict();
50
+ var CmdArgStringSchema = z.object({
51
+ name: z.string().min(1),
52
+ type: z.literal("string"),
53
+ default: z.string().optional()
54
+ }).strict();
55
+ var CmdArgSchema = z.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
56
+ var CmdFrontmatterSchema = z.object({
57
+ id: IdSchema,
58
+ trigger: z.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
59
+ 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)
66
+ }).strict();
67
+ var Schemas = {
68
+ Skill: SkillFrontmatterSchema,
69
+ Cmd: CmdFrontmatterSchema,
70
+ Agent: AgentFrontmatterSchema
71
+ };
72
+ var ParseError = class extends Error {
73
+ constructor(file, issues) {
74
+ const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
75
+ super(`Frontmatter validation failed for ${file}:
76
+ ${messages}`);
77
+ this.file = file;
78
+ this.issues = issues;
79
+ this.name = "ParseError";
80
+ }
81
+ file;
82
+ issues;
83
+ };
84
+
85
+ // src/parser/common.ts
86
+ function parseWithSchema(filePath, source, schema) {
87
+ const parsed = matter(source);
88
+ const result = schema.safeParse(parsed.data);
89
+ if (!result.success) {
90
+ throw new ParseError(filePath, result.error.issues);
91
+ }
92
+ return {
93
+ meta: result.data,
94
+ body: parsed.content.trim(),
95
+ sourcePath: filePath
96
+ };
97
+ }
98
+
99
+ // src/parser/agent.ts
100
+ function parseAgent(filePath, source) {
101
+ return parseWithSchema(filePath, source, Schemas.Agent);
102
+ }
103
+
104
+ // src/parser/cmd.ts
105
+ function parseCmd(filePath, source) {
106
+ return parseWithSchema(filePath, source, Schemas.Cmd);
107
+ }
108
+
109
+ // src/parser/skill.ts
110
+ function parseSkill(filePath, source) {
111
+ return parseWithSchema(filePath, source, Schemas.Skill);
112
+ }
113
+
114
+ // src/util/yaml.ts
115
+ import { parse as yamlParse } from "yaml";
116
+ function parseYAML(source) {
117
+ return yamlParse(source);
118
+ }
119
+
120
+ // src/loader.ts
121
+ var DisableYamlSchema = z2.object({ disable: z2.array(z2.string()).optional() }).passthrough();
122
+ 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 });
127
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
128
+ const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
129
+ 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")))
133
+ };
134
+ }
135
+ function loadProjectSkills(targetDir) {
136
+ const skillsDir = join(targetDir, "docs", "skills");
137
+ if (!existsSync(skillsDir)) return [];
138
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
139
+ return skillFiles.map((f) => parseSkill(f, readFileSync2(f, "utf8")));
140
+ }
141
+ function loadOverrides(worktreeDir) {
142
+ const overridesDir = join(worktreeDir, ".harness-overrides");
143
+ if (!existsSync(overridesDir)) return void 0;
144
+ const added = loadHarness(overridesDir, {
145
+ agentsDir: join(overridesDir, "agents"),
146
+ skillsDir: join(overridesDir, "skills"),
147
+ commandsDir: join(overridesDir, "commands")
148
+ });
149
+ const disablePath = join(overridesDir, "disable.yaml");
150
+ let disable = [];
151
+ if (existsSync(disablePath)) {
152
+ try {
153
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync2(disablePath, "utf8")));
154
+ if (parsed.success && parsed.data.disable) {
155
+ disable = parsed.data.disable;
156
+ }
157
+ } catch {
158
+ }
159
+ }
160
+ return { add: added, disable };
161
+ }
162
+
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
+ // src/renderers/common.ts
183
+ import { stringify as yamlStringify } from "yaml";
184
+ var STOP_HOOK_PACKAGE = "@vaubaan/harness";
185
+ function checkSkillCapabilities(skill, engine) {
186
+ const blockingWarnings = [];
187
+ const degradedWarnings = [];
188
+ const supported = CAPABILITIES_MATRIX[engine];
189
+ const degraded = DEGRADED_CAPABILITIES[engine] ?? [];
190
+ if (!skill.meta.requires) return { blockingWarnings, degradedWarnings };
191
+ for (const cap of skill.meta.requires) {
192
+ if (!supported.includes(cap)) {
193
+ blockingWarnings.push(
194
+ `skill "${skill.meta.id}" requires "${cap}" not supported by "${engine}" \u2014 skipped`
195
+ );
196
+ } else if (degraded.includes(cap)) {
197
+ degradedWarnings.push(
198
+ `skill "${skill.meta.id}" requires "${cap}" \u2014 supported by "${engine}" with degradation`
199
+ );
200
+ }
201
+ }
202
+ return { blockingWarnings, degradedWarnings };
203
+ }
204
+ function isSkillEngineAllowed(skill, engine) {
205
+ if (!skill.meta.engines) return true;
206
+ return skill.meta.engines.includes(engine);
207
+ }
208
+ function yamlFrontmatter(data) {
209
+ const rendered = yamlStringify(data, { lineWidth: 0 }).trimEnd();
210
+ return `---
211
+ ${rendered}
212
+ ---
213
+ `;
214
+ }
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
+ function frontmatterDataForSkill(skill) {
249
+ const data = {
250
+ name: skill.meta.id,
251
+ description: skill.meta.description
252
+ };
253
+ if (skill.meta.tags && skill.meta.tags.length > 0) data.tags = skill.meta.tags;
254
+ return data;
255
+ }
256
+ function frontmatterDataForCmd(cmd) {
257
+ const data = {
258
+ id: cmd.meta.id,
259
+ trigger: cmd.meta.trigger,
260
+ description: cmd.meta.description
261
+ };
262
+ if (cmd.meta.args && cmd.meta.args.length > 0) {
263
+ data.args = cmd.meta.args.map((a) => {
264
+ if (a.type === "enum") {
265
+ return a.default !== void 0 ? { name: a.name, type: a.type, values: a.values, default: a.default } : { name: a.name, type: a.type, values: a.values };
266
+ }
267
+ return a.default !== void 0 ? { name: a.name, type: a.type, default: a.default } : { name: a.name, type: a.type };
268
+ });
269
+ }
270
+ return data;
271
+ }
272
+ function buildAgentBody(agent) {
273
+ return `${agent.body.trim()}
274
+ `;
275
+ }
276
+ function buildUmbrellaBody(_agents, extras) {
277
+ const triggerBySkill = new Map(
278
+ extras.availableCommands.map((c) => [c.meta.invokes_skill, c.meta.trigger])
279
+ );
280
+ const skillLines = extras.availableSkills.map((s) => {
281
+ const trigger = triggerBySkill.get(s.meta.id);
282
+ const label = trigger ? `\`${s.meta.id}\` (\`${trigger}\`)` : `\`${s.meta.id}\``;
283
+ return `- ${label} \u2014 ${s.meta.description.split("\n")[0]}`;
284
+ });
285
+ const sections = [
286
+ "# How we work",
287
+ "",
288
+ "This file describes **how to work in this project**. The **business context** (what the project does, how to run it, which subsystems it contains) lives in `README.md` and `docs/`. Read them first.",
289
+ "",
290
+ "## Project map",
291
+ "",
292
+ "- `README.md` \u2014 pitch, quick start, scripts. Entry point.",
293
+ "- `docs/spec/<subsystem>.md` \u2014 *what* and *why* (tech-agnostic).",
294
+ "- `docs/handbook/<feature>.md` \u2014 *how it actually works* today.",
295
+ "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives.",
296
+ "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 core scenarios.",
297
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release.",
298
+ ...extras.hasProjectSkills ? ["- `docs/skills/*.skill.md` \u2014 the project's domain skills."] : [],
299
+ ...extras.hasQualityDoc ? [
300
+ "- `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."
301
+ ] : [],
302
+ "",
303
+ "## Doc-first",
304
+ "",
305
+ "The order is: **understand the docs \u2192 fill the gaps \u2192 code \u2192 update the docs \u2192 commit**. If the docs are silent or stale on something you change, fill the gap upfront with the doc-skill writers \u2014 not downstream, not after the fact.",
306
+ "",
307
+ "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
308
+ "- Implicit structural decision in your changes \u2192 an ADR (`/decision`).",
309
+ "- Changed feature behavior \u2192 update the matching handbook (`/handbook`).",
310
+ "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on."
311
+ ];
312
+ if (skillLines.length > 0) {
313
+ sections.push("", "## Doc-skills", "", skillLines.join("\n"));
314
+ }
315
+ return `${sections.join("\n")}
316
+ `;
317
+ }
318
+
319
+ // src/renderers/claude-code.ts
320
+ var ENGINE = "claude-code";
321
+ var BASE = ".claude";
322
+ var claudeCodeRenderer = {
323
+ engine: ENGINE,
324
+ renderSkill(skill) {
325
+ if (!isSkillEngineAllowed(skill, ENGINE)) {
326
+ return {
327
+ files: [],
328
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE}"`]
329
+ };
330
+ }
331
+ const check = checkSkillCapabilities(skill, ENGINE);
332
+ if (check.blockingWarnings.length > 0) {
333
+ return { files: [], warnings: check.blockingWarnings };
334
+ }
335
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
336
+ ${skill.body}
337
+ `;
338
+ return {
339
+ files: [{ path: `${BASE}/skills/${skill.meta.id}/SKILL.md`, content }],
340
+ warnings: check.degradedWarnings
341
+ };
342
+ },
343
+ renderCmd(cmd) {
344
+ const content = `${yamlFrontmatter(frontmatterDataForCmd(cmd))}
345
+ ${cmd.body}
346
+ `;
347
+ return {
348
+ files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
349
+ warnings: []
350
+ };
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
+ }
400
+ };
401
+
402
+ // src/renderers/codex-cli.ts
403
+ var ENGINE2 = "codex-cli";
404
+ var BASE2 = ".codex";
405
+ var SKILLS_BASE = ".agents/skills";
406
+ var codexCliRenderer = {
407
+ engine: ENGINE2,
408
+ renderSkill(skill) {
409
+ if (!isSkillEngineAllowed(skill, ENGINE2)) {
410
+ return {
411
+ files: [],
412
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE2}"`]
413
+ };
414
+ }
415
+ const check = checkSkillCapabilities(skill, ENGINE2);
416
+ if (check.blockingWarnings.length > 0) {
417
+ return { files: [], warnings: check.blockingWarnings };
418
+ }
419
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
420
+ ${skill.body}
421
+ `;
422
+ return {
423
+ files: [{ path: `${SKILLS_BASE}/${skill.meta.id}/SKILL.md`, content }],
424
+ warnings: check.degradedWarnings
425
+ };
426
+ },
427
+ // Codex custom prompts are deprecated in favour of skills: nothing to render.
428
+ renderCmd(_cmd) {
429
+ 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
+ }
481
+ };
482
+
483
+ // src/renderers/opencode.ts
484
+ var ENGINE3 = "opencode";
485
+ var BASE3 = ".opencode";
486
+ var opencodeRenderer = {
487
+ engine: ENGINE3,
488
+ renderSkill(skill) {
489
+ if (!isSkillEngineAllowed(skill, ENGINE3)) {
490
+ return {
491
+ files: [],
492
+ warnings: [`skill "${skill.meta.id}" excluded from engine "${ENGINE3}"`]
493
+ };
494
+ }
495
+ const check = checkSkillCapabilities(skill, ENGINE3);
496
+ if (check.blockingWarnings.length > 0) {
497
+ return { files: [], warnings: check.blockingWarnings };
498
+ }
499
+ const content = `${yamlFrontmatter(frontmatterDataForSkill(skill))}
500
+ ${skill.body}
501
+ `;
502
+ return {
503
+ files: [{ path: `${BASE3}/skills/${skill.meta.id}/SKILL.md`, content }],
504
+ warnings: check.degradedWarnings
505
+ };
506
+ },
507
+ renderCmd(cmd) {
508
+ const content = `${yamlFrontmatter({ description: cmd.meta.description })}
509
+ ${cmd.body}
510
+ `;
511
+ 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 }],
612
+ warnings: []
613
+ };
614
+ }
615
+ };
616
+
617
+ // src/renderers/index.ts
618
+ var RENDERERS = {
619
+ "claude-code": claudeCodeRenderer,
620
+ "codex-cli": codexCliRenderer,
621
+ opencode: opencodeRenderer
622
+ };
623
+ function getRenderer(engine) {
624
+ return RENDERERS[engine];
625
+ }
626
+
627
+ // src/render.ts
628
+ var RenderError = class extends Error {
629
+ constructor(message) {
630
+ super(message);
631
+ this.name = "RenderError";
632
+ }
633
+ };
634
+ function mergeById(stock, added) {
635
+ const result = /* @__PURE__ */ new Map();
636
+ for (const item of stock) result.set(item.meta.id, item);
637
+ if (added) {
638
+ for (const item of added) result.set(item.meta.id, item);
639
+ }
640
+ return Array.from(result.values());
641
+ }
642
+ function removeByIds(items, disabled) {
643
+ if (disabled.length === 0) return [...items];
644
+ const disabledSet = new Set(disabled);
645
+ return items.filter((item) => !disabledSet.has(item.meta.id));
646
+ }
647
+ function applyOverrides(harness, overrides) {
648
+ const disabled = overrides?.disable ?? [];
649
+ return {
650
+ agents: removeByIds(mergeById(harness.agents, overrides?.add?.agents), disabled),
651
+ skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
652
+ cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
653
+ };
654
+ }
655
+ var CLAUDE_MD_STUB = "@AGENTS.md\n";
656
+ function opencodeLast(engines) {
657
+ return [...engines].sort((a, b) => Number(a === "opencode") - Number(b === "opencode"));
658
+ }
659
+ function render(input) {
660
+ const { engines } = input;
661
+ if (engines.length === 0) {
662
+ throw new RenderError("at least one engine must be selected");
663
+ }
664
+ const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
665
+ const harness = applyOverrides(base, input.overrides);
666
+ if (harness.agents.length === 0) {
667
+ throw new RenderError("No agents found in harness");
668
+ }
669
+ const files = [];
670
+ const warnings = [];
671
+ const exposedSkills = /* @__PURE__ */ new Map();
672
+ const exposedCmds = /* @__PURE__ */ new Map();
673
+ for (const engine of opencodeLast(engines)) {
674
+ const renderer = getRenderer(engine);
675
+ const renderedSkills = [];
676
+ for (const skill of harness.skills) {
677
+ const result = renderer.renderSkill(skill);
678
+ warnings.push(...result.warnings);
679
+ if (result.files.length > 0) {
680
+ const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
681
+ if (!alreadyVisible) files.push(...result.files);
682
+ renderedSkills.push(skill);
683
+ exposedSkills.set(skill.meta.id, skill);
684
+ }
685
+ }
686
+ const renderedSkillIds = new Set(renderedSkills.map((s) => s.meta.id));
687
+ const renderedCmds = [];
688
+ for (const cmd of harness.cmds) {
689
+ if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
690
+ const result = renderer.renderCmd(cmd);
691
+ warnings.push(...result.warnings);
692
+ if (result.files.length > 0) {
693
+ files.push(...result.files);
694
+ renderedCmds.push(cmd);
695
+ exposedCmds.set(cmd.meta.id, cmd);
696
+ }
697
+ }
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
+ }
713
+ const hasProjectSkills = (input.projectSkills?.length ?? 0) > 0;
714
+ const umbrellaContent = buildUmbrellaBody(harness.agents, {
715
+ availableSkills: Array.from(exposedSkills.values()),
716
+ availableCommands: Array.from(exposedCmds.values()),
717
+ hasProjectSkills,
718
+ hasQualityDoc: input.hasQualityDoc === true
719
+ });
720
+ files.push({ path: "AGENTS.md", content: umbrellaContent });
721
+ if (engines.includes("claude-code")) {
722
+ files.push({ path: "CLAUDE.md", content: CLAUDE_MD_STUB });
723
+ }
724
+ return { files, warnings };
725
+ }
726
+
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)) {
1082
+ throw new Error(
1083
+ `invalid shared configuration ${LEGACY_OPENCODE_CONFIG}: expected an MCP object`
1084
+ );
1085
+ }
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);
1129
+ }
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 });
1183
+ }
1184
+ function hashContent(content) {
1185
+ return createHash("sha256").update(content).digest("hex");
1186
+ }
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);
1193
+ }
1194
+
1195
+ // 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
+ }
1215
+ function pruneEmptyDirs(root, leaves) {
1216
+ const candidates = /* @__PURE__ */ new Set();
1217
+ for (const leaf of leaves) {
1218
+ let cur = leaf;
1219
+ while (cur !== root && cur.startsWith(`${root}/`)) {
1220
+ candidates.add(cur);
1221
+ cur = dirname2(cur);
1222
+ }
1223
+ }
1224
+ const pruned = [];
1225
+ const sorted = [...candidates].sort((a, b) => b.length - a.length);
1226
+ for (const dir of sorted) {
1227
+ if (!existsSync5(dir)) continue;
1228
+ if (readdirSync(dir).length > 0) continue;
1229
+ rmdirSync(dir);
1230
+ pruned.push(relative(root, dir));
1231
+ }
1232
+ return pruned;
1233
+ }
1234
+
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
+ // src/cli/update-transaction.ts
1375
+ import { createHash as createHash2, randomUUID } from "crypto";
1376
+ import {
1377
+ chmodSync as chmodSync2,
1378
+ closeSync,
1379
+ fsyncSync,
1380
+ lstatSync as lstatSync2,
1381
+ mkdirSync as mkdirSync2,
1382
+ openSync,
1383
+ readFileSync as readFileSync7,
1384
+ readdirSync as readdirSync2,
1385
+ realpathSync as realpathSync2,
1386
+ rmdirSync as rmdirSync2,
1387
+ unlinkSync as unlinkSync2,
1388
+ writeFileSync as writeFileSync4
1389
+ } from "fs";
1390
+ 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";
1392
+ 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
+ ]);
1402
+ function canonicalRoot(root) {
1403
+ let ancestor = resolve4(root);
1404
+ const missing = [];
1405
+ while (!lstatSync2(ancestor, { throwIfNoEntry: false })) {
1406
+ missing.unshift(basename2(ancestor));
1407
+ ancestor = dirname4(ancestor);
1408
+ }
1409
+ return join9(realpathSync2(ancestor), ...missing);
1410
+ }
1411
+ function contains(parent, child) {
1412
+ const path = relative2(parent, child);
1413
+ return path === "" || !isAbsolute2(path) && path !== ".." && !path.startsWith(`..${sep}`);
1414
+ }
1415
+ function assertBackupLocation(root, backup) {
1416
+ if (contains(root, backup) || contains(backup, root)) {
1417
+ throw new Error(`update backup must be outside the target project: ${backup}`);
1418
+ }
1419
+ const ancestors = [];
1420
+ for (let path = backup; ; path = dirname4(path)) {
1421
+ ancestors.unshift(path);
1422
+ if (dirname4(path) === path) break;
1423
+ }
1424
+ for (const path of ancestors) {
1425
+ const info = lstatSync2(path, { throwIfNoEntry: false });
1426
+ if (!info) continue;
1427
+ if (info.isSymbolicLink() || !info.isDirectory()) {
1428
+ throw new Error(`unsafe update backup directory: ${path}`);
1429
+ }
1430
+ }
1431
+ if (lstatSync2(backup, { throwIfNoEntry: false })) {
1432
+ throw new Error(`update backup directory already exists: ${backup}`);
1433
+ }
1434
+ }
1435
+ function createDirectories(path, created, mode = 511) {
1436
+ const missing = [];
1437
+ for (let current = path; !lstatSync2(current, { throwIfNoEntry: false }); current = dirname4(current)) {
1438
+ missing.unshift(current);
1439
+ }
1440
+ for (const directory of missing) {
1441
+ mkdirSync2(directory, { mode });
1442
+ created.push(directory);
1443
+ }
1444
+ }
1445
+ function writeBackupFile(path, content) {
1446
+ createDirectories(dirname4(path), [], 448);
1447
+ const fd = openSync(path, "wx", 384);
1448
+ try {
1449
+ writeFileSync4(fd, content);
1450
+ fsyncSync(fd);
1451
+ } finally {
1452
+ closeSync(fd);
1453
+ }
1454
+ }
1455
+ function saveSnapshot(root, paths, backup) {
1456
+ const entries = [];
1457
+ createDirectories(dirname4(backup), [], 448);
1458
+ mkdirSync2(backup, { mode: 448 });
1459
+ for (const path of paths) {
1460
+ const full = join9(root, path);
1461
+ const info = lstatSync2(full, { throwIfNoEntry: false });
1462
+ if (!info) {
1463
+ entries.push({ path, exists: false });
1464
+ continue;
1465
+ }
1466
+ const content = readFileSync7(full);
1467
+ writeBackupFile(join9(backup, "files", path), content);
1468
+ entries.push({
1469
+ path,
1470
+ exists: true,
1471
+ mode: info.mode & 4095,
1472
+ sha256: createHash2("sha256").update(content).digest("hex")
1473
+ });
1474
+ }
1475
+ writeBackupFile(
1476
+ join9(backup, "snapshot.json"),
1477
+ `${JSON.stringify({ version: 1, root, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries }, null, 2)}
1478
+ `
1479
+ );
1480
+ return entries;
1481
+ }
1482
+ function errorMessage(error) {
1483
+ return error instanceof Error ? error.message : String(error);
1484
+ }
1485
+ function rollback(root, backup, entries, touched, createdDirectories) {
1486
+ const errors = [];
1487
+ for (const path of [...touched].reverse()) {
1488
+ try {
1489
+ assertManagedPaths(root, [path]);
1490
+ const entry = entries.get(path);
1491
+ const full = join9(root, path);
1492
+ const current = lstatSync2(full, { throwIfNoEntry: false });
1493
+ if (!entry?.exists) {
1494
+ if (current) unlinkSync2(full);
1495
+ continue;
1496
+ }
1497
+ const original = readFileSync7(join9(backup, "files", path));
1498
+ if (!current || !readFileSync7(full).equals(original)) {
1499
+ if (current) unlinkSync2(full);
1500
+ writeFileSync4(full, original, { mode: 384 });
1501
+ }
1502
+ chmodSync2(full, entry.mode);
1503
+ } catch (error) {
1504
+ errors.push(`${path}: ${errorMessage(error)}`);
1505
+ }
1506
+ }
1507
+ for (const directory of [...createdDirectories].reverse()) {
1508
+ try {
1509
+ if (readdirSync2(directory).length === 0) rmdirSync2(directory);
1510
+ } catch (error) {
1511
+ errors.push(`${directory}: ${errorMessage(error)}`);
1512
+ }
1513
+ }
1514
+ return errors;
1515
+ }
1516
+ function applyUpdateTransaction(root, writes, removals, backupDir) {
1517
+ const paths = [.../* @__PURE__ */ new Set([...removals, ...writes.map((file) => file.path)])];
1518
+ assertManagedPaths(root, paths);
1519
+ const target = canonicalRoot(root);
1520
+ const backup = resolve4(
1521
+ backupDir ?? join9(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
1522
+ );
1523
+ assertBackupLocation(target, backup);
1524
+ let snapshot;
1525
+ try {
1526
+ snapshot = saveSnapshot(target, paths, backup);
1527
+ } catch (error) {
1528
+ throw new Error(
1529
+ `could not prepare update backup at ${backup}; project unchanged: ${errorMessage(error)}`,
1530
+ { cause: error }
1531
+ );
1532
+ }
1533
+ const entries = new Map(snapshot.map((entry) => [entry.path, entry]));
1534
+ const touched = /* @__PURE__ */ new Set();
1535
+ const createdDirectories = [];
1536
+ try {
1537
+ assertManagedPaths(target, paths);
1538
+ for (const path of removals) {
1539
+ if (!lstatSync2(join9(target, path), { throwIfNoEntry: false })) continue;
1540
+ touched.add(path);
1541
+ unlinkSync2(join9(target, path));
1542
+ }
1543
+ for (const file of writes) {
1544
+ const full = join9(target, file.path);
1545
+ createDirectories(dirname4(full), createdDirectories);
1546
+ touched.add(file.path);
1547
+ const entry = entries.get(file.path);
1548
+ const mode = file.path === MANIFEST_PATH ? 384 : entry?.exists ? entry.mode : PRIVATE_FILES.has(file.path) ? 384 : 420;
1549
+ if (entry?.exists && file.path === MANIFEST_PATH) chmodSync2(full, mode);
1550
+ writeFileSync4(full, file.content, { mode });
1551
+ if (entry?.exists) chmodSync2(full, mode);
1552
+ }
1553
+ } catch (error) {
1554
+ const failures = rollback(target, backup, entries, touched, createdDirectories);
1555
+ const restoration = failures.length > 0 ? `rollback errors: ${failures.join("; ")}` : "rollback completed";
1556
+ throw new Error(`update failed; backup: ${backup}; ${restoration}: ${errorMessage(error)}`, {
1557
+ cause: error
1558
+ });
1559
+ }
1560
+ return { backupDir: backup };
1561
+ }
1562
+
1563
+ // src/cli/update.ts
1564
+ function currentContent(root, path) {
1565
+ return existsSync8(join10(root, path)) ? readFileSync8(join10(root, path), "utf8") : void 0;
1566
+ }
1567
+ function checkArtifactConflicts(root, previous, writes, removals) {
1568
+ const desired = new Map(writes.map((file) => [file.path, file.content]));
1569
+ for (const path of [...desired.keys(), ...removals]) {
1570
+ if (SHARED_CONFIG_PATHS.includes(path)) continue;
1571
+ const content = currentContent(root, path);
1572
+ if (content === void 0) continue;
1573
+ if (!previous.files.includes(path)) {
1574
+ throw new Error(
1575
+ `existing file outside harness manifest: ${path}; use overrides or --preserve`
1576
+ );
1577
+ }
1578
+ 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`);
1581
+ }
1582
+ }
1583
+ }
1584
+ function planUpdate(args) {
1585
+ const root = resolve5(args.targetDir);
1586
+ const { manifest: previous, sourceVersion, engines, hookEngines } = readUpdateInstallation(root);
1587
+ const preserved = [
1588
+ .../* @__PURE__ */ new Set([...previous.preservedFiles ?? [], ...args.preserveFiles ?? []])
1589
+ ].sort();
1590
+ if (preserved.includes(MANIFEST_FILENAME))
1591
+ 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]);
1598
+ const requestedOverrides = args.overridesDir ?? previous.overridesDir;
1599
+ const overridesDir = args.overridesDir ? resolve5(args.overridesDir) : previous.overridesDir ? resolve5(root, previous.overridesDir) : root;
1600
+ if (requestedOverrides && !existsSync8(join10(overridesDir, ".harness-overrides"))) {
1601
+ throw new Error(`recorded overrides are missing: ${overridesDir}/.harness-overrides`);
1602
+ }
1603
+ const hasOverrides = existsSync8(join10(overridesDir, ".harness-overrides"));
1604
+ const disablePath = join10(overridesDir, ".harness-overrides", "disable.yaml");
1605
+ if (existsSync8(disablePath)) {
1606
+ try {
1607
+ DisableYamlSchema.parse(parseYAML(readFileSync8(disablePath, "utf8")));
1608
+ } catch {
1609
+ throw new Error(`invalid override selection: ${disablePath}`);
1610
+ }
1611
+ }
1612
+ const rendered = planInit({
1613
+ targetDir: root,
1614
+ packageDir: args.packageDir,
1615
+ engines,
1616
+ overridesDir: hasOverrides ? overridesDir : void 0,
1617
+ withStopHook: false
1618
+ });
1619
+ const config = planUpdateConfigs(root, previous, hookEngines);
1620
+ const output = [...rendered.output.files, ...config.writes].filter(
1621
+ (file) => !preserved.includes(file.path)
1622
+ );
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]);
1635
+ 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
+ );
1643
+ const manifest = {
1644
+ version: MANIFEST_VERSION,
1645
+ harnessVersion: VERSION,
1646
+ engines: [...engines].sort(),
1647
+ renderedAt: previous.renderedAt,
1648
+ files: owned,
1649
+ fileHashes: hashes,
1650
+ stopHookInstalled: hookEngines.length > 0,
1651
+ stopHookEngines: [...hookEngines].sort(),
1652
+ ...hasOverrides ? { overridesDir: overridesDir === root ? "." : overridesDir } : {},
1653
+ ...preserved.length ? { preservedFiles: preserved } : {},
1654
+ ...config.opencodeConfig ? { opencodeConfig: config.opencodeConfig } : {},
1655
+ ...config.hookConfigs ? { hookConfigs: config.hookConfigs } : {}
1656
+ };
1657
+ 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)) {
1660
+ manifest.renderedAt = (/* @__PURE__ */ new Date()).toISOString();
1661
+ writes.push({ path: MANIFEST_FILENAME, content: `${JSON.stringify(manifest, null, 2)}
1662
+ ` });
1663
+ }
1664
+ const warnings = [...rendered.output.warnings, ...config.warnings];
1665
+ if (!previous.fileHashes) {
1666
+ warnings.push(
1667
+ "legacy manifest has no file fingerprints: managed artifacts will be regenerated; backup preserves their previous contents"
1668
+ );
1669
+ }
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
+ return {
1674
+ writes,
1675
+ removals: existingRemovals,
1676
+ result: {
1677
+ version: VERSION,
1678
+ fromManifestVersion: sourceVersion,
1679
+ dryRun: args.dryRun === true,
1680
+ upToDate: writes.length === 0 && existingRemovals.length === 0,
1681
+ filesToWrite: writes.map((file) => file.path),
1682
+ filesToRemove: existingRemovals,
1683
+ warnings
1684
+ }
1685
+ };
1686
+ }
1687
+ function updateCommand(args) {
1688
+ const plan = planUpdate(args);
1689
+ 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
+ );
1696
+ return { ...plan.result, backupDir };
1697
+ }
1698
+ export {
1699
+ VERSION,
1700
+ initCommand,
1701
+ planInit,
1702
+ planUpdate,
1703
+ updateCommand,
1704
+ writeFilesToTarget
1705
+ };
1706
+ //# sourceMappingURL=index.js.map