@vaubaan/harness 1.4.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +301 -167
  2. package/dist/cli/index.js +886 -1882
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/commands/handbook.cmd.md +4 -3
  5. package/dist/commands/test-plan.cmd.md +4 -4
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +277 -1064
  8. package/dist/index.js.map +1 -1
  9. package/dist/init.d.ts +8 -23
  10. package/dist/init.js +270 -1036
  11. package/dist/init.js.map +1 -1
  12. package/dist/linters/index.js +687 -31
  13. package/dist/linters/index.js.map +1 -1
  14. package/dist/parser/index.d.ts +1 -26
  15. package/dist/parser/index.js +1 -17
  16. package/dist/parser/index.js.map +1 -1
  17. package/dist/{render-Cu2XrkkY.d.ts → render-C-FWmUfX.d.ts} +8 -15
  18. package/dist/render.d.ts +1 -1
  19. package/dist/render.js +18 -280
  20. package/dist/render.js.map +1 -1
  21. package/dist/skills/decision-record-writer.skill.md +93 -131
  22. package/dist/skills/doc-audit.skill.md +10 -10
  23. package/dist/skills/drift-detector.skill.md +6 -7
  24. package/dist/skills/handbook-writer.skill.md +68 -159
  25. package/dist/skills/readme-writer.skill.md +3 -3
  26. package/dist/skills/spec-writer.skill.md +111 -71
  27. package/dist/skills/test-plan-writer.skill.md +47 -54
  28. package/dist/skills/workflow-writer.skill.md +40 -6
  29. package/dist/templates/code-quality.md.tmpl +2 -2
  30. package/dist/templates/coding-workflow.md.tmpl +10 -0
  31. package/dist/templates/decision.md.tmpl +20 -47
  32. package/dist/templates/e2e-tests.md.tmpl +16 -45
  33. package/dist/templates/handbook.md.tmpl +20 -38
  34. package/dist/templates/integration-tests.md.tmpl +16 -34
  35. package/package.json +1 -1
  36. package/dist/agents/coding.agent.md +0 -182
  37. package/dist/agents/merge.agent.md +0 -139
  38. package/dist/agents/planning.agent.md +0 -194
  39. package/dist/agents/review.agent.md +0 -176
  40. package/dist/commands/clean-code.cmd.md +0 -26
  41. package/dist/skills/clean-code-guardian.skill.md +0 -391
package/dist/init.js CHANGED
@@ -1,21 +1,19 @@
1
1
  // src/cli/init.ts
2
- import { existsSync as existsSync9, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync4 } from "fs";
3
- import { dirname as dirname5, join as join11, resolve as resolve6 } from "path";
2
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
3
+ import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
4
4
 
5
5
  // src/cli/managed-paths.ts
6
6
  import { lstatSync, realpathSync, statSync } from "fs";
7
7
  import { basename, dirname, isAbsolute, join, resolve, win32 } from "path";
8
- var MANAGED_FILES = /* @__PURE__ */ new Set([
9
- "AGENTS.md",
10
- "CLAUDE.md",
8
+ var MANAGED_FILES = /* @__PURE__ */ new Set(["AGENTS.md", "CLAUDE.md", ".harness-manifest.json"]);
9
+ var RELEASED_PATHS = [
11
10
  ".mcp.json",
12
- ".harness-manifest.json",
13
- ".claude/settings.json",
14
11
  ".codex/config.toml",
15
- ".codex/hooks.json",
16
12
  ".opencode/opencode.json",
17
- ".opencode/mcp.json"
18
- ]);
13
+ ".opencode/mcp.json",
14
+ ".claude/settings.json",
15
+ ".codex/hooks.json"
16
+ ];
19
17
  var MANAGED_DIRECTORIES = [
20
18
  ".claude/agents/",
21
19
  ".claude/commands/",
@@ -75,131 +73,59 @@ function assertManagedPaths(root, files) {
75
73
 
76
74
  // src/cli/manifest.ts
77
75
  import { createHash } from "crypto";
78
- import { chmodSync, existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync } from "fs";
79
- import { join as join4 } from "path";
80
- import { z as z3 } from "zod";
76
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "fs";
77
+ import { join as join2 } from "path";
78
+ import { z } from "zod";
81
79
 
82
80
  // src/version.ts
83
- var VERSION = "1.4.0";
81
+ var VERSION = "2.1.0";
84
82
 
85
- // src/cli/opencode-config.ts
86
- import { existsSync, readFileSync } from "fs";
87
- import { join as join2 } from "path";
88
- import { isDeepStrictEqual } from "util";
89
- import { z } from "zod";
90
- var OPENCODE_CONFIG_PATH = ".opencode/opencode.json";
91
- var CLAUDE_MCP_PATH = ".mcp.json";
92
- var OPENCODE_SCHEMA = "https://opencode.ai/config.json";
93
- var ObjectSchema = z.record(z.unknown());
94
- var OPENCODE_TARGET = {
95
- path: OPENCODE_CONFIG_PATH,
96
- key: "mcp",
97
- label: "OpenCode",
98
- schema: OPENCODE_SCHEMA
99
- };
100
- var CLAUDE_TARGET = {
101
- path: CLAUDE_MCP_PATH,
102
- key: "mcpServers",
103
- label: "Claude Code"
104
- };
105
- var OpenCodeConfigOwnershipSchema = z.object({
106
- createdFile: z.boolean(),
107
- addedMcp: z.boolean(),
108
- addedSchema: z.boolean(),
109
- entries: z.record(ObjectSchema)
83
+ // src/cli/manifest.ts
84
+ var MANIFEST_FILENAME = ".harness-manifest.json";
85
+ var MANIFEST_VERSION = "6";
86
+ var ManifestSchema = z.object({
87
+ version: z.enum(["4", "5", MANIFEST_VERSION]),
88
+ engines: z.array(z.string()),
89
+ renderedAt: z.string(),
90
+ files: z.array(z.string()),
91
+ harnessVersion: z.string().optional(),
92
+ overridesDir: z.string().optional(),
93
+ fileHashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)).optional(),
94
+ preservedFiles: z.array(z.string()).optional()
110
95
  });
111
- function parseConfig(target, content) {
112
- try {
113
- const config = ObjectSchema.parse(JSON.parse(content));
114
- if (Object.hasOwn(config, target.key)) ObjectSchema.parse(config[target.key]);
115
- return config;
116
- } catch {
117
- throw new Error(`invalid ${target.path}: expected a JSON object with an MCP object`);
118
- }
119
- }
120
- function removeOwnedEntries(target, config, ownership, warnings) {
121
- if (Object.hasOwn(config, target.key)) {
122
- const mcp = ObjectSchema.parse(config[target.key]);
123
- for (const [id, installed] of Object.entries(ownership.entries)) {
124
- if (!Object.hasOwn(mcp, id)) continue;
125
- if (isDeepStrictEqual(mcp[id], installed)) delete mcp[id];
126
- else warnings.push(`preserved modified ${target.label} MCP server: ${id}`);
127
- }
128
- config[target.key] = mcp;
129
- if (ownership.addedMcp && Object.keys(mcp).length === 0)
130
- Reflect.deleteProperty(config, target.key);
131
- }
132
- if (target.schema && ownership.addedSchema && config.$schema === target.schema)
133
- Reflect.deleteProperty(config, "$schema");
134
- }
135
- function addMissingEntries(target, config, desired, createdFile, warnings) {
136
- const requested = ObjectSchema.parse(parseConfig(target, desired.content)[target.key]);
137
- const mcp = ObjectSchema.parse(config[target.key] ?? {});
138
- const entries = {};
139
- for (const [id, entry] of Object.entries(requested)) {
140
- if (Object.hasOwn(mcp, id)) {
141
- if (!isDeepStrictEqual(mcp[id], entry)) {
142
- warnings.push(
143
- `preserved existing ${target.label} MCP server instead of replacing it: ${id}`
144
- );
145
- }
146
- continue;
147
- }
148
- entries[id] = ObjectSchema.parse(entry);
149
- mcp[id] = entry;
150
- }
151
- if (Object.keys(entries).length === 0) return void 0;
152
- const ownership = {
153
- createdFile,
154
- addedMcp: !Object.hasOwn(config, target.key),
155
- addedSchema: target.schema !== void 0 && !Object.hasOwn(config, "$schema"),
156
- entries
157
- };
158
- config[target.key] = mcp;
159
- if (target.schema && ownership.addedSchema) config.$schema = target.schema;
160
- return ownership;
161
- }
162
- function planMcpJson(target, root, desired, previous) {
163
- const warnings = [];
164
- if (!desired && !previous) return { remove: false, warnings };
165
- const path = join2(root, target.path);
166
- const existed = existsSync(path);
167
- if (!existed && !desired) return { remove: false, warnings };
168
- const original = existed ? readFileSync(path, "utf8") : void 0;
169
- const config = original === void 0 ? {} : parseConfig(target, original);
170
- const before = structuredClone(config);
171
- if (previous) removeOwnedEntries(target, config, previous, warnings);
172
- const createdFile = !existed || previous?.createdFile === true;
173
- const ownership = desired ? addMissingEntries(target, config, desired, createdFile, warnings) : void 0;
174
- if (!ownership && createdFile && Object.keys(config).length === 0) {
175
- return { remove: existed, warnings };
176
- }
177
- return {
178
- remove: false,
179
- ownership,
180
- warnings,
181
- ...!existed || !isDeepStrictEqual(before, config) ? { write: { path: target.path, content: `${JSON.stringify(config, null, 2)}
182
- ` } } : {}
183
- };
96
+ function manifestPath(targetDir) {
97
+ return join2(targetDir, MANIFEST_FILENAME);
184
98
  }
185
- function planOpenCodeConfig(root, desired, previous) {
186
- return planMcpJson(OPENCODE_TARGET, root, desired, previous);
99
+ function hashContent(content) {
100
+ return createHash("sha256").update(content).digest("hex");
187
101
  }
188
- function planClaudeMcpConfig(root, desired, previous) {
189
- return planMcpJson(CLAUDE_TARGET, root, desired, previous);
102
+ function readManifest(targetDir) {
103
+ assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
104
+ const path = manifestPath(targetDir);
105
+ if (!existsSync(path)) return null;
106
+ const raw = JSON.parse(readFileSync(path, "utf8"));
107
+ return ManifestSchema.parse(raw);
190
108
  }
191
109
 
192
- // src/cli/update-config.ts
193
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
110
+ // src/cli/plan-render.ts
111
+ import { existsSync as existsSync3 } from "fs";
112
+ import { dirname as dirname2, join as join4, resolve as resolve2 } from "path";
113
+ import { fileURLToPath } from "url";
114
+
115
+ // src/loader.ts
116
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
194
117
  import { join as join3 } from "path";
195
- import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
196
- import { z as z2 } from "zod";
118
+ import fg from "fast-glob";
119
+ import { z as z3 } from "zod";
197
120
 
198
- // src/renderers/common.ts
199
- import { stringify as yamlStringify } from "yaml";
121
+ // src/parser/common.ts
122
+ import { readFileSync as readFileSync2 } from "fs";
123
+ import matter from "gray-matter";
124
+
125
+ // src/parser/schemas.ts
126
+ import { z as z2 } from "zod";
200
127
 
201
128
  // src/types.ts
202
- var AGENT_IDS = ["coding", "review", "merge", "planning"];
203
129
  var ENGINES = ["claude-code", "codex-cli", "opencode"];
204
130
  var CAPABILITIES = ["multi-step", "slash-command", "inline-exec"];
205
131
  var CAPABILITIES_MATRIX = {
@@ -211,8 +137,122 @@ var DEGRADED_CAPABILITIES = {
211
137
  "codex-cli": ["multi-step"]
212
138
  };
213
139
 
140
+ // src/parser/schemas.ts
141
+ var IdSchema = z2.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
142
+ var SkillFrontmatterSchema = z2.object({
143
+ id: IdSchema,
144
+ description: z2.string().min(1),
145
+ engines: z2.array(z2.enum(ENGINES)).min(1).optional(),
146
+ requires: z2.array(z2.enum(CAPABILITIES)).optional(),
147
+ tags: z2.array(z2.string()).optional()
148
+ }).strict();
149
+ var CmdArgEnumSchema = z2.object({
150
+ name: z2.string().min(1),
151
+ type: z2.literal("enum"),
152
+ values: z2.array(z2.string()).min(1),
153
+ default: z2.string().optional()
154
+ }).strict();
155
+ var CmdArgStringSchema = z2.object({
156
+ name: z2.string().min(1),
157
+ type: z2.literal("string"),
158
+ default: z2.string().optional()
159
+ }).strict();
160
+ var CmdArgSchema = z2.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
161
+ var CmdFrontmatterSchema = z2.object({
162
+ id: IdSchema,
163
+ trigger: z2.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
164
+ invokes_skill: IdSchema,
165
+ args: z2.array(CmdArgSchema).optional(),
166
+ description: z2.string().min(1)
167
+ }).strict();
168
+ var Schemas = {
169
+ Skill: SkillFrontmatterSchema,
170
+ Cmd: CmdFrontmatterSchema
171
+ };
172
+ var ParseError = class extends Error {
173
+ constructor(file, issues) {
174
+ const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
175
+ super(`Frontmatter validation failed for ${file}:
176
+ ${messages}`);
177
+ this.file = file;
178
+ this.issues = issues;
179
+ this.name = "ParseError";
180
+ }
181
+ file;
182
+ issues;
183
+ };
184
+
185
+ // src/parser/common.ts
186
+ function parseWithSchema(filePath, source, schema) {
187
+ const parsed = matter(source);
188
+ const result = schema.safeParse(parsed.data);
189
+ if (!result.success) {
190
+ throw new ParseError(filePath, result.error.issues);
191
+ }
192
+ return {
193
+ meta: result.data,
194
+ body: parsed.content.trim(),
195
+ sourcePath: filePath
196
+ };
197
+ }
198
+
199
+ // src/parser/cmd.ts
200
+ function parseCmd(filePath, source) {
201
+ return parseWithSchema(filePath, source, Schemas.Cmd);
202
+ }
203
+
204
+ // src/parser/skill.ts
205
+ function parseSkill(filePath, source) {
206
+ return parseWithSchema(filePath, source, Schemas.Skill);
207
+ }
208
+
209
+ // src/util/yaml.ts
210
+ import { parse as yamlParse } from "yaml";
211
+ function parseYAML(source) {
212
+ return yamlParse(source);
213
+ }
214
+
215
+ // src/loader.ts
216
+ var DisableYamlSchema = z3.object({ disable: z3.array(z3.string()).optional() }).passthrough();
217
+ function loadHarness(packageDir, opts = {}) {
218
+ const skillsDir = opts.skillsDir ?? join3(packageDir, "skills");
219
+ const commandsDir = opts.commandsDir ?? join3(packageDir, "commands");
220
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
221
+ const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
222
+ return {
223
+ skills: skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8"))),
224
+ cmds: cmdFiles.map((f) => parseCmd(f, readFileSync3(f, "utf8")))
225
+ };
226
+ }
227
+ function loadProjectSkills(targetDir) {
228
+ const skillsDir = join3(targetDir, "docs", "skills");
229
+ if (!existsSync2(skillsDir)) return [];
230
+ const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
231
+ return skillFiles.map((f) => parseSkill(f, readFileSync3(f, "utf8")));
232
+ }
233
+ function loadOverrides(worktreeDir) {
234
+ const overridesDir = join3(worktreeDir, ".harness-overrides");
235
+ if (!existsSync2(overridesDir)) return void 0;
236
+ const added = loadHarness(overridesDir, {
237
+ skillsDir: join3(overridesDir, "skills"),
238
+ commandsDir: join3(overridesDir, "commands")
239
+ });
240
+ const disablePath = join3(overridesDir, "disable.yaml");
241
+ let disable = [];
242
+ if (existsSync2(disablePath)) {
243
+ try {
244
+ const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync3(disablePath, "utf8")));
245
+ if (parsed.success && parsed.data.disable) {
246
+ disable = parsed.data.disable;
247
+ }
248
+ } catch {
249
+ }
250
+ }
251
+ return { add: added, disable };
252
+ }
253
+
214
254
  // src/renderers/common.ts
215
- var STOP_HOOK_PACKAGE = "@vaubaan/harness";
255
+ import { stringify as yamlStringify } from "yaml";
216
256
  function checkSkillCapabilities(skill, engine) {
217
257
  const blockingWarnings = [];
218
258
  const degradedWarnings = [];
@@ -243,39 +283,6 @@ ${rendered}
243
283
  ---
244
284
  `;
245
285
  }
246
- var SCALAR_NEEDS_QUOTE = /[^a-zA-Z0-9_./-]/;
247
- function tomlEscapeString(s) {
248
- return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
249
- }
250
- function tomlValue(v) {
251
- if (Array.isArray(v)) {
252
- return `[${v.map((x) => tomlValue(x)).join(", ")}]`;
253
- }
254
- if (typeof v === "string") {
255
- if (v.includes("\n")) return tomlEscapeString(v);
256
- return SCALAR_NEEDS_QUOTE.test(v) ? tomlEscapeString(v) : `"${v}"`;
257
- }
258
- if (typeof v === "boolean" || typeof v === "number") {
259
- return String(v);
260
- }
261
- return tomlEscapeString(String(v));
262
- }
263
- function tomlMultilineString(s) {
264
- const escaped = s.replace(/\\/g, "\\\\").replace(/"""/g, '""\\"');
265
- return `"""
266
- ${escaped}
267
- """`;
268
- }
269
- function tomlQuoteString(s) {
270
- return tomlValue(s);
271
- }
272
- function tomlInlineArray(items) {
273
- return tomlValue([...items]);
274
- }
275
- function tomlInlineTable(table) {
276
- const entries = Object.entries(table).map(([k, v]) => `${k} = ${tomlValue(v)}`);
277
- return `{ ${entries.join(", ")} }`;
278
- }
279
286
  function frontmatterDataForSkill(skill) {
280
287
  const data = {
281
288
  name: skill.meta.id,
@@ -300,11 +307,7 @@ function frontmatterDataForCmd(cmd) {
300
307
  }
301
308
  return data;
302
309
  }
303
- function buildAgentBody(agent) {
304
- return `${agent.body.trim()}
305
- `;
306
- }
307
- function buildUmbrellaBody(_agents, extras) {
310
+ function buildUmbrellaBody(extras) {
308
311
  const triggerBySkill = new Map(
309
312
  extras.availableCommands.map((c) => [c.meta.invokes_skill, c.meta.trigger])
310
313
  );
@@ -322,10 +325,10 @@ function buildUmbrellaBody(_agents, extras) {
322
325
  "",
323
326
  "- `README.md` \u2014 pitch, quick start, scripts. Entry point.",
324
327
  "- `docs/spec/<subsystem>.md` \u2014 *what* and *why* (tech-agnostic).",
325
- "- `docs/handbook/<feature>.md` \u2014 *how it actually works* today.",
328
+ "- `docs/handbook/<feature>.md` \u2014 what the code does not say: entry points, traps, settings outside the repo, manual procedures.",
326
329
  "- `docs/decisions/<slug>.md` \u2014 ADRs: structural choices and rejected alternatives.",
327
- "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 core scenarios.",
328
- "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release.",
330
+ "- `docs/tests/integration-tests.md` & `e2e-tests.md` \u2014 test scope, stack, conventions, known gaps.",
331
+ "- `docs/workflow/coding-workflow.md` \u2014 CI, branches, PR, release. How this team works: follow it.",
329
332
  ...extras.hasProjectSkills ? ["- `docs/skills/*.skill.md` \u2014 the project's domain skills."] : [],
330
333
  ...extras.hasQualityDoc ? [
331
334
  "- `docs/quality/code-quality.md` \u2014 the project's code-quality rules: mechanical checks, judgment rules, accepted deviations. Read it before writing or auditing code."
@@ -338,7 +341,13 @@ function buildUmbrellaBody(_agents, extras) {
338
341
  "- Missing spec for a subsystem you touch \u2192 **do not code**, report the gap.",
339
342
  "- Implicit structural decision in your changes \u2192 an ADR (`/decision`).",
340
343
  "- Changed feature behavior \u2192 update the matching handbook (`/handbook`).",
341
- "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on."
344
+ "- Suspected code \u2194 doc drift \u2192 `/drift` before moving on.",
345
+ "",
346
+ "## Checks",
347
+ "",
348
+ "Run `npx @vaubaan/harness lint` before you commit; CI runs the same linters on every pull request. Fix what it reports with the skill it suggests.",
349
+ "",
350
+ "The files the harness generates (`AGENTS.md`, `CLAUDE.md`, the `.claude/`, `.agents/` and `.opencode/` folders, `.harness-manifest.json`) are committed. Never edit them by hand: change their source in `docs/` or `.harness-overrides/`, run `npx @vaubaan/harness update .`, and commit the result. The linter fails when a generated file no longer matches its render."
342
351
  ];
343
352
  if (skillLines.length > 0) {
344
353
  sections.push("", "## Doc-skills", "", skillLines.join("\n"));
@@ -379,60 +388,11 @@ ${cmd.body}
379
388
  files: [{ path: `${BASE}/commands/${cmd.meta.id}.md`, content }],
380
389
  warnings: []
381
390
  };
382
- },
383
- renderAgents(agents) {
384
- const files = [];
385
- for (const agent of agents) {
386
- const subagentFrontmatter = yamlFrontmatter({
387
- name: agent.meta.id,
388
- description: agent.meta.description
389
- });
390
- const body = buildAgentBody(agent);
391
- const content = `${subagentFrontmatter}
392
- ${body}`;
393
- files.push({ path: `${BASE}/agents/${agent.meta.id}.md`, content });
394
- }
395
- return { files, warnings: [] };
396
- },
397
- renderMcp(servers) {
398
- if (servers.length === 0) return { files: [], warnings: [] };
399
- const mcpServers = {};
400
- for (const s of servers) {
401
- const entry = { command: s.command, args: [...s.args] };
402
- if (s.env) entry.env = s.env;
403
- mcpServers[s.id] = entry;
404
- }
405
- const content = `${JSON.stringify({ mcpServers }, null, 2)}
406
- `;
407
- return { files: [{ path: ".mcp.json", content }], warnings: [] };
408
- },
409
- renderStopHook() {
410
- const settings = {
411
- hooks: {
412
- Stop: [
413
- {
414
- matcher: "",
415
- hooks: [
416
- {
417
- type: "command",
418
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine claude`
419
- }
420
- ]
421
- }
422
- ]
423
- }
424
- };
425
- return {
426
- files: [{ path: `${BASE}/settings.json`, content: `${JSON.stringify(settings, null, 2)}
427
- ` }],
428
- warnings: []
429
- };
430
391
  }
431
392
  };
432
393
 
433
394
  // src/renderers/codex-cli.ts
434
395
  var ENGINE2 = "codex-cli";
435
- var BASE2 = ".codex";
436
396
  var SKILLS_BASE = ".agents/skills";
437
397
  var codexCliRenderer = {
438
398
  engine: ENGINE2,
@@ -458,62 +418,12 @@ ${skill.body}
458
418
  // Codex custom prompts are deprecated in favour of skills: nothing to render.
459
419
  renderCmd(_cmd) {
460
420
  return { files: [], warnings: [] };
461
- },
462
- renderAgents(agents) {
463
- const files = [];
464
- for (const agent of agents) {
465
- const content = [
466
- `name = ${tomlQuoteString(agent.meta.id)}`,
467
- `description = ${tomlQuoteString(agent.meta.description)}`,
468
- `developer_instructions = ${tomlMultilineString(buildAgentBody(agent).trimEnd())}`,
469
- ""
470
- ].join("\n");
471
- files.push({ path: `${BASE2}/agents/${agent.meta.id}.toml`, content });
472
- }
473
- return { files, warnings: [] };
474
- },
475
- renderMcp(servers) {
476
- if (servers.length === 0) return { files: [], warnings: [] };
477
- const blocks = [];
478
- for (const s of servers) {
479
- const lines = [
480
- `[mcp_servers.${s.id}]`,
481
- `command = ${tomlQuoteString(s.command)}`,
482
- `args = ${tomlInlineArray([...s.args])}`
483
- ];
484
- if (s.env) lines.push(`env = ${tomlInlineTable(s.env)}`);
485
- blocks.push(lines.join("\n"));
486
- }
487
- const content = `${blocks.join("\n\n")}
488
- `;
489
- return { files: [{ path: `${BASE2}/config.toml`, content }], warnings: [] };
490
- },
491
- renderStopHook() {
492
- const hooks = {
493
- hooks: {
494
- Stop: [
495
- {
496
- hooks: [
497
- {
498
- type: "command",
499
- command: `npx -y ${STOP_HOOK_PACKAGE} stop-hook --engine codex`
500
- }
501
- ]
502
- }
503
- ]
504
- }
505
- };
506
- return {
507
- files: [{ path: `${BASE2}/hooks.json`, content: `${JSON.stringify(hooks, null, 2)}
508
- ` }],
509
- warnings: []
510
- };
511
421
  }
512
422
  };
513
423
 
514
424
  // src/renderers/opencode.ts
515
425
  var ENGINE3 = "opencode";
516
- var BASE3 = ".opencode";
426
+ var BASE2 = ".opencode";
517
427
  var opencodeRenderer = {
518
428
  engine: ENGINE3,
519
429
  renderSkill(skill) {
@@ -531,7 +441,7 @@ var opencodeRenderer = {
531
441
  ${skill.body}
532
442
  `;
533
443
  return {
534
- files: [{ path: `${BASE3}/skills/${skill.meta.id}/SKILL.md`, content }],
444
+ files: [{ path: `${BASE2}/skills/${skill.meta.id}/SKILL.md`, content }],
535
445
  warnings: check.degradedWarnings
536
446
  };
537
447
  },
@@ -540,106 +450,7 @@ ${skill.body}
540
450
  ${cmd.body}
541
451
  `;
542
452
  return {
543
- files: [{ path: `${BASE3}/commands/${cmd.meta.id}.md`, content }],
544
- warnings: []
545
- };
546
- },
547
- renderAgents(agents) {
548
- const files = [];
549
- for (const agent of agents) {
550
- const fm = yamlFrontmatter({
551
- description: agent.meta.description,
552
- mode: "all"
553
- });
554
- const body = buildAgentBody(agent);
555
- files.push({ path: `${BASE3}/agents/${agent.meta.id}.md`, content: `${fm}
556
- ${body}` });
557
- }
558
- return { files, warnings: [] };
559
- },
560
- renderMcp(servers) {
561
- if (servers.length === 0) return { files: [], warnings: [] };
562
- const mcp = {};
563
- for (const s of servers) {
564
- const entry = {
565
- type: "local",
566
- command: [s.command, ...s.args],
567
- enabled: true
568
- };
569
- if (s.env) entry.environment = s.env;
570
- mcp[s.id] = entry;
571
- }
572
- const config = { $schema: "https://opencode.ai/config.json", mcp };
573
- const content = `${JSON.stringify(config, null, 2)}
574
- `;
575
- return { files: [{ path: `${BASE3}/opencode.json`, content }], warnings: [] };
576
- },
577
- renderStopHook() {
578
- const content = `import { spawnSync } from "node:child_process";
579
-
580
- // Runs the harness lint and returns the report to inject, or "" when the
581
- // turn may end.
582
- const lintReport = (directory, sessionID) => {
583
- const r = spawnSync(
584
- "npx",
585
- ["-y", "${STOP_HOOK_PACKAGE}", "stop-hook", "--engine", "opencode", "--cwd", directory],
586
- { input: JSON.stringify({ sessionID }), encoding: "utf-8" },
587
- );
588
- const report = (r.stderr ?? "").trim();
589
- return r.status === 2 ? report : "";
590
- };
591
-
592
- // OpenCode 1.x entry point, exposed as server() below.
593
- const HarnessStopHook = async ({ client, directory }) => ({
594
- event: async ({ event }) => {
595
- if (event.type !== "session.idle") return;
596
- const sessionID = event.properties?.sessionID;
597
- if (!sessionID) return;
598
- const report = lintReport(directory, sessionID);
599
- if (report === "") return;
600
- // OpenCode defaults to its build agent when a prompt omits agent.
601
- // Preserve the last conversation persona, excluding compaction summaries.
602
- const history = await client.session.messages({ path: { id: sessionID } }).catch(() => undefined);
603
- if (history?.error || !Array.isArray(history?.data)) return;
604
- const current = history.data.findLast(({ info }) =>
605
- (info.role === "user" || (info.role === "assistant" && !info.summary)) &&
606
- typeof info.agent === "string" && info.agent.trim() !== "",
607
- );
608
- if (!current) return;
609
- await client.session.prompt({
610
- path: { id: sessionID },
611
- body: { agent: current.info.agent, parts: [{ type: "text", text: report }] },
612
- });
613
- },
614
- });
615
-
616
- // One default export for both majors: OpenCode 1.x calls server(),
617
- // OpenCode 2.x calls setup(). A V2 session keeps its agent, so the report
618
- // is sent without naming the persona.
619
- export default {
620
- id: "vaubaan-harness-stop-hook",
621
- server: HarnessStopHook,
622
- setup(context) {
623
- const directory = context.location.directory;
624
- const controller = new AbortController();
625
- const listen = async () => {
626
- for await (const event of context.event.subscribe({ signal: controller.signal })) {
627
- if (event.type !== "session.idle") continue;
628
- if (event.location?.directory && event.location.directory !== directory) continue;
629
- const sessionID = event.data?.sessionID;
630
- if (!sessionID) continue;
631
- const report = lintReport(directory, sessionID);
632
- if (report === "") continue;
633
- await context.session.prompt({ sessionID, text: report }).catch(() => undefined);
634
- }
635
- };
636
- listen().catch(() => undefined);
637
- return () => controller.abort();
638
- },
639
- };
640
- `;
641
- return {
642
- files: [{ path: `${BASE3}/plugins/harness-stop-hook.ts`, content }],
453
+ files: [{ path: `${BASE2}/commands/${cmd.meta.id}.md`, content }],
643
454
  warnings: []
644
455
  };
645
456
  }
@@ -655,450 +466,6 @@ function getRenderer(engine) {
655
466
  return RENDERERS[engine];
656
467
  }
657
468
 
658
- // src/cli/update-config.ts
659
- var LEGACY_OPENCODE_CONFIG = ".opencode/mcp.json";
660
- var SHARED_CONFIG_PATHS = [
661
- ".mcp.json",
662
- ".codex/config.toml",
663
- OPENCODE_CONFIG_PATH,
664
- LEGACY_OPENCODE_CONFIG,
665
- ".claude/settings.json",
666
- ".codex/hooks.json"
667
- ];
668
- var ObjectSchema2 = z2.record(z2.unknown());
669
- var HookEntrySchema = z2.object({ group: ObjectSchema2, hook: ObjectSchema2 });
670
- var HookConfigOwnershipSchema = z2.object({
671
- createdFile: z2.boolean(),
672
- addedHooks: z2.boolean(),
673
- addedStop: z2.boolean(),
674
- entries: z2.array(HookEntrySchema)
675
- });
676
- var HookConfigsOwnershipSchema = z2.object({
677
- ".claude/settings.json": HookConfigOwnershipSchema.optional(),
678
- ".codex/hooks.json": HookConfigOwnershipSchema.optional()
679
- }).strict();
680
- var HOOK_ENGINES = {
681
- ".claude/settings.json": "claude-code",
682
- ".codex/hooks.json": "codex-cli"
683
- };
684
- function parseObject(content, path) {
685
- try {
686
- return ObjectSchema2.parse(JSON.parse(content));
687
- } catch {
688
- throw new Error(`invalid shared configuration ${path}: expected a JSON object`);
689
- }
690
- }
691
- function asObject(value) {
692
- const parsed = ObjectSchema2.safeParse(value);
693
- return parsed.success ? parsed.data : void 0;
694
- }
695
- function stopHooks(config, path) {
696
- if (!Object.hasOwn(config, "hooks")) return [];
697
- const hooks = asObject(config.hooks);
698
- if (!hooks || Object.hasOwn(hooks, "Stop") && !Array.isArray(hooks.Stop)) {
699
- throw new Error(`invalid shared configuration ${path}: expected hooks.Stop to be an array`);
700
- }
701
- return Array.isArray(hooks.Stop) ? hooks.Stop : [];
702
- }
703
- function groupMetadata(group) {
704
- return Object.fromEntries(Object.entries(group).filter(([key]) => key !== "hooks"));
705
- }
706
- function sameEntry(left, right) {
707
- return isDeepStrictEqual2(left.group, right.group) && isDeepStrictEqual2(left.hook, right.hook);
708
- }
709
- function appendEntry(entries, entry) {
710
- if (!entries.some((existing) => sameEntry(existing, entry))) entries.push(entry);
711
- }
712
- function defaultStopGroup(engine) {
713
- const file = getRenderer(engine).renderStopHook().files[0];
714
- if (!file) throw new Error(`missing Stop hook renderer for ${engine}`);
715
- const group = asObject(stopHooks(parseObject(file.content, file.path), file.path)[0]);
716
- if (!group || !Array.isArray(group.hooks) || !asObject(group.hooks[0])) {
717
- throw new Error(`invalid Stop hook renderer for ${engine}`);
718
- }
719
- return group;
720
- }
721
- function normalizeHarnessHooks(groups, expected, previous, claimExisting, warnings, path) {
722
- const defaultHook = ObjectSchema2.parse(expected.hooks[0]);
723
- const entries = [...previous?.entries ?? []];
724
- let found = false;
725
- const normalized = groups.map((value) => {
726
- const group = asObject(value);
727
- if (!group) return value;
728
- const flat = group.type === "command" && group.command === defaultHook.command;
729
- const hooks = flat ? [group] : Array.isArray(group.hooks) ? group.hooks : [];
730
- const metadata = flat ? groupMetadata(expected) : groupMetadata(group);
731
- for (const value2 of hooks) {
732
- const hook = asObject(value2);
733
- if (!hook || hook.type !== "command" || hook.command !== defaultHook.command) continue;
734
- found = true;
735
- const entry = { group: metadata, hook };
736
- if (!claimExisting) continue;
737
- if (previous && !previous.entries.some((old) => sameEntry(old, entry))) {
738
- warnings.push(`preserved modified harness Stop hook: ${path}`);
739
- } else {
740
- appendEntry(entries, entry);
741
- }
742
- }
743
- return flat && claimExisting ? { ...metadata, hooks: [group] } : value;
744
- });
745
- if (!found && !previous?.entries.length) {
746
- normalized.push(expected);
747
- appendEntry(entries, { group: groupMetadata(expected), hook: defaultHook });
748
- } else if (!found) {
749
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
750
- }
751
- return { groups: normalized, entries };
752
- }
753
- function removeOwnedHooks(config, ownership, path, warnings) {
754
- const groups = stopHooks(config, path);
755
- const remaining = [];
756
- const matched = /* @__PURE__ */ new Set();
757
- for (const value of groups) {
758
- const group = asObject(value);
759
- if (!group || !Array.isArray(group.hooks)) {
760
- remaining.push(value);
761
- continue;
762
- }
763
- const metadata = groupMetadata(group);
764
- const hooks2 = group.hooks.filter((value2) => {
765
- const hook = asObject(value2);
766
- const entry = hook && ownership.entries.find((old) => sameEntry(old, { group: metadata, hook }));
767
- if (entry) matched.add(entry);
768
- return !entry;
769
- });
770
- if (hooks2.length > 0 || hooks2.length === group.hooks.length) {
771
- remaining.push({ ...group, hooks: hooks2 });
772
- }
773
- }
774
- if (matched.size < ownership.entries.length) {
775
- warnings.push(`preserved removed or modified harness Stop hook: ${path}`);
776
- }
777
- const hooks = asObject(config.hooks);
778
- if (!hooks) return;
779
- if (ownership.addedStop && remaining.length === 0) Reflect.deleteProperty(hooks, "Stop");
780
- else if (Object.hasOwn(hooks, "Stop")) hooks.Stop = remaining;
781
- if (ownership.addedHooks && Object.keys(hooks).length === 0)
782
- Reflect.deleteProperty(config, "hooks");
783
- else config.hooks = hooks;
784
- }
785
- function recordMutation(plan, path, before, after, createdFile) {
786
- if (createdFile && Object.keys(after).length === 0) {
787
- if (before) plan.removals.push(path);
788
- } else if (!isDeepStrictEqual2(before, after)) {
789
- plan.writes.push({ path, content: `${JSON.stringify(after, null, 2)}
790
- ` });
791
- }
792
- }
793
- function planHookConfigCleanup(root, ownership) {
794
- const plan = { writes: [], removals: [], warnings: [] };
795
- if (!ownership) return plan;
796
- const validated = HookConfigsOwnershipSchema.parse(ownership);
797
- assertManagedPaths(root, Object.keys(validated));
798
- for (const path of Object.keys(HOOK_ENGINES)) {
799
- const owned = validated[path];
800
- if (!owned || !existsSync2(join3(root, path))) continue;
801
- const before = parseObject(readFileSync2(join3(root, path), "utf8"), path);
802
- const config = structuredClone(before);
803
- removeOwnedHooks(config, owned, path, plan.warnings);
804
- recordMutation(plan, path, before, config, owned.createdFile);
805
- }
806
- return plan;
807
- }
808
- function planActiveHook(root, path, previous, claimExisting, plan) {
809
- assertManagedPaths(root, [path]);
810
- const existed = existsSync2(join3(root, path));
811
- if (!existed && previous?.entries.length) {
812
- plan.warnings.push(`preserved removed harness Stop hook configuration: ${path}`);
813
- return previous;
814
- }
815
- const before = existed ? parseObject(readFileSync2(join3(root, path), "utf8"), path) : void 0;
816
- const config = structuredClone(before ?? {});
817
- const groups = stopHooks(config, path);
818
- const hooks = asObject(config.hooks) ?? {};
819
- const normalized = normalizeHarnessHooks(
820
- groups,
821
- defaultStopGroup(HOOK_ENGINES[path]),
822
- previous,
823
- claimExisting,
824
- plan.warnings,
825
- path
826
- );
827
- const legacyWholeFile = !previous && claimExisting && existed;
828
- const ownership = {
829
- createdFile: !existed || previous?.createdFile === true || legacyWholeFile,
830
- addedHooks: previous?.addedHooks ?? (legacyWholeFile || !Object.hasOwn(config, "hooks")),
831
- addedStop: previous?.addedStop ?? (legacyWholeFile || !Object.hasOwn(hooks, "Stop")),
832
- entries: normalized.entries
833
- };
834
- if (!isDeepStrictEqual2(groups, normalized.groups)) {
835
- config.hooks = { ...hooks, Stop: normalized.groups };
836
- }
837
- recordMutation(plan, path, before, config, ownership.createdFile);
838
- return ownership.entries.length > 0 ? ownership : void 0;
839
- }
840
- function planLegacyOpenCode(root, previous, plan) {
841
- if (!previous.files.includes(LEGACY_OPENCODE_CONFIG)) return;
842
- const legacyPath = join3(root, LEGACY_OPENCODE_CONFIG);
843
- if (!existsSync2(legacyPath)) return;
844
- assertManagedPaths(root, [LEGACY_OPENCODE_CONFIG, OPENCODE_CONFIG_PATH]);
845
- const legacy = parseObject(readFileSync2(legacyPath, "utf8"), LEGACY_OPENCODE_CONFIG);
846
- if (!asObject(legacy.mcp)) {
847
- throw new Error(
848
- `invalid shared configuration ${LEGACY_OPENCODE_CONFIG}: expected an MCP object`
849
- );
850
- }
851
- const merged = planOpenCodeConfig(
852
- root,
853
- { path: OPENCODE_CONFIG_PATH, content: JSON.stringify(legacy) },
854
- void 0
855
- );
856
- if (merged.write) plan.writes.push(merged.write);
857
- plan.warnings.push(...merged.warnings);
858
- if (merged.ownership) {
859
- const old = previous.opencodeConfig;
860
- plan.opencodeConfig = {
861
- createdFile: merged.ownership.createdFile || old?.createdFile === true,
862
- addedMcp: merged.ownership.addedMcp || old?.addedMcp === true,
863
- addedSchema: merged.ownership.addedSchema || old?.addedSchema === true,
864
- entries: { ...old?.entries, ...merged.ownership.entries }
865
- };
866
- }
867
- plan.removals.push(LEGACY_OPENCODE_CONFIG);
868
- }
869
- function planUpdateConfigs(root, previous, hookEngines) {
870
- const plan = {
871
- writes: [],
872
- removals: [],
873
- ownedFiles: [],
874
- warnings: [],
875
- ...previous.opencodeConfig ? { opencodeConfig: previous.opencodeConfig } : {}
876
- };
877
- planLegacyOpenCode(root, previous, plan);
878
- const hookConfigs = {};
879
- for (const path of Object.keys(HOOK_ENGINES)) {
880
- const owned = previous.hookConfigs?.[path];
881
- if (hookEngines.includes(HOOK_ENGINES[path])) {
882
- hookConfigs[path] = planActiveHook(
883
- root,
884
- path,
885
- owned,
886
- previous.files.includes(path) || Boolean(owned),
887
- plan
888
- );
889
- } else if (owned) {
890
- const cleanup = planHookConfigCleanup(root, { [path]: owned });
891
- plan.writes.push(...cleanup.writes);
892
- plan.removals.push(...cleanup.removals);
893
- plan.warnings.push(...cleanup.warnings);
894
- }
895
- }
896
- if (Object.values(hookConfigs).some(Boolean)) plan.hookConfigs = hookConfigs;
897
- if (hookEngines.includes("opencode")) {
898
- const plugin = getRenderer("opencode").renderStopHook();
899
- plan.writes.push(...plugin.files);
900
- plan.ownedFiles.push(...plugin.files.map((file) => file.path));
901
- plan.warnings.push(...plugin.warnings);
902
- }
903
- return plan;
904
- }
905
-
906
- // src/cli/manifest.ts
907
- var MANIFEST_FILENAME = ".harness-manifest.json";
908
- var MANIFEST_VERSION = "6";
909
- var ManifestSchema = z3.object({
910
- version: z3.enum(["4", "5", MANIFEST_VERSION]),
911
- engines: z3.array(z3.string()),
912
- renderedAt: z3.string(),
913
- files: z3.array(z3.string()),
914
- stopHookInstalled: z3.boolean().optional(),
915
- stopHookEngines: z3.array(z3.string()).optional(),
916
- opencodeConfig: OpenCodeConfigOwnershipSchema.optional(),
917
- /** Entries the harness added to `.mcp.json` (Claude Code). */
918
- mcpConfig: OpenCodeConfigOwnershipSchema.optional(),
919
- hookConfigs: HookConfigsOwnershipSchema.optional(),
920
- harnessVersion: z3.string().optional(),
921
- overridesDir: z3.string().optional(),
922
- fileHashes: z3.record(z3.string().regex(/^[a-f0-9]{64}$/)).optional(),
923
- preservedFiles: z3.array(z3.string()).optional()
924
- });
925
- function manifestPath(targetDir) {
926
- return join4(targetDir, MANIFEST_FILENAME);
927
- }
928
- function hashContent(content) {
929
- return createHash("sha256").update(content).digest("hex");
930
- }
931
- function readManifest(targetDir) {
932
- assertManagedPaths(targetDir, [MANIFEST_FILENAME]);
933
- const path = manifestPath(targetDir);
934
- if (!existsSync3(path)) return null;
935
- const raw = JSON.parse(readFileSync3(path, "utf8"));
936
- return ManifestSchema.parse(raw);
937
- }
938
-
939
- // src/cli/plan-render.ts
940
- import { existsSync as existsSync5 } from "fs";
941
- import { dirname as dirname2, join as join6, resolve as resolve2 } from "path";
942
- import { fileURLToPath } from "url";
943
-
944
- // src/loader.ts
945
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
946
- import { join as join5 } from "path";
947
- import fg from "fast-glob";
948
- import { z as z5 } from "zod";
949
-
950
- // src/parser/common.ts
951
- import { readFileSync as readFileSync4 } from "fs";
952
- import matter from "gray-matter";
953
-
954
- // src/parser/schemas.ts
955
- import { z as z4 } from "zod";
956
- var IdSchema = z4.string().min(1).regex(/^[a-z][a-z0-9-]*$/, "id must be kebab-case (lowercase + digits + hyphens)");
957
- var SkillFrontmatterSchema = z4.object({
958
- id: IdSchema,
959
- description: z4.string().min(1),
960
- engines: z4.array(z4.enum(ENGINES)).min(1).optional(),
961
- requires: z4.array(z4.enum(CAPABILITIES)).optional(),
962
- tags: z4.array(z4.string()).optional()
963
- }).strict();
964
- var CmdArgEnumSchema = z4.object({
965
- name: z4.string().min(1),
966
- type: z4.literal("enum"),
967
- values: z4.array(z4.string()).min(1),
968
- default: z4.string().optional()
969
- }).strict();
970
- var CmdArgStringSchema = z4.object({
971
- name: z4.string().min(1),
972
- type: z4.literal("string"),
973
- default: z4.string().optional()
974
- }).strict();
975
- var CmdArgSchema = z4.discriminatedUnion("type", [CmdArgEnumSchema, CmdArgStringSchema]);
976
- var CmdFrontmatterSchema = z4.object({
977
- id: IdSchema,
978
- trigger: z4.string().regex(/^\/[a-z][a-z0-9-]*$/, "trigger must be /kebab-case"),
979
- invokes_skill: IdSchema,
980
- args: z4.array(CmdArgSchema).optional(),
981
- description: z4.string().min(1)
982
- }).strict();
983
- var AgentFrontmatterSchema = z4.object({
984
- id: z4.enum(AGENT_IDS),
985
- description: z4.string().min(1)
986
- }).strict();
987
- var Schemas = {
988
- Skill: SkillFrontmatterSchema,
989
- Cmd: CmdFrontmatterSchema,
990
- Agent: AgentFrontmatterSchema
991
- };
992
- var ParseError = class extends Error {
993
- constructor(file, issues) {
994
- const messages = issues.map((i) => ` - ${i.path.join(".") || "<root>"}: ${i.message}`).join("\n");
995
- super(`Frontmatter validation failed for ${file}:
996
- ${messages}`);
997
- this.file = file;
998
- this.issues = issues;
999
- this.name = "ParseError";
1000
- }
1001
- file;
1002
- issues;
1003
- };
1004
-
1005
- // src/parser/common.ts
1006
- function parseWithSchema(filePath, source, schema) {
1007
- const parsed = matter(source);
1008
- const result = schema.safeParse(parsed.data);
1009
- if (!result.success) {
1010
- throw new ParseError(filePath, result.error.issues);
1011
- }
1012
- return {
1013
- meta: result.data,
1014
- body: parsed.content.trim(),
1015
- sourcePath: filePath
1016
- };
1017
- }
1018
-
1019
- // src/parser/agent.ts
1020
- function parseAgent(filePath, source) {
1021
- return parseWithSchema(filePath, source, Schemas.Agent);
1022
- }
1023
-
1024
- // src/parser/cmd.ts
1025
- function parseCmd(filePath, source) {
1026
- return parseWithSchema(filePath, source, Schemas.Cmd);
1027
- }
1028
-
1029
- // src/parser/skill.ts
1030
- function parseSkill(filePath, source) {
1031
- return parseWithSchema(filePath, source, Schemas.Skill);
1032
- }
1033
-
1034
- // src/util/yaml.ts
1035
- import { parse as yamlParse } from "yaml";
1036
- function parseYAML(source) {
1037
- return yamlParse(source);
1038
- }
1039
-
1040
- // src/loader.ts
1041
- var DisableYamlSchema = z5.object({ disable: z5.array(z5.string()).optional() }).passthrough();
1042
- function loadHarness(packageDir, opts = {}) {
1043
- const agentsDir = opts.agentsDir ?? join5(packageDir, "agents");
1044
- const skillsDir = opts.skillsDir ?? join5(packageDir, "skills");
1045
- const commandsDir = opts.commandsDir ?? join5(packageDir, "commands");
1046
- const agentFiles = fg.sync("*.agent.md", { cwd: agentsDir, absolute: true });
1047
- const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
1048
- const cmdFiles = fg.sync("*.cmd.md", { cwd: commandsDir, absolute: true });
1049
- return {
1050
- agents: agentFiles.map((f) => parseAgent(f, readFileSync5(f, "utf8"))),
1051
- skills: skillFiles.map((f) => parseSkill(f, readFileSync5(f, "utf8"))),
1052
- cmds: cmdFiles.map((f) => parseCmd(f, readFileSync5(f, "utf8")))
1053
- };
1054
- }
1055
- function loadProjectSkills(targetDir) {
1056
- const skillsDir = join5(targetDir, "docs", "skills");
1057
- if (!existsSync4(skillsDir)) return [];
1058
- const skillFiles = fg.sync("*.skill.md", { cwd: skillsDir, absolute: true });
1059
- return skillFiles.map((f) => parseSkill(f, readFileSync5(f, "utf8")));
1060
- }
1061
- function loadOverrides(worktreeDir) {
1062
- const overridesDir = join5(worktreeDir, ".harness-overrides");
1063
- if (!existsSync4(overridesDir)) return void 0;
1064
- const added = loadHarness(overridesDir, {
1065
- agentsDir: join5(overridesDir, "agents"),
1066
- skillsDir: join5(overridesDir, "skills"),
1067
- commandsDir: join5(overridesDir, "commands")
1068
- });
1069
- const disablePath = join5(overridesDir, "disable.yaml");
1070
- let disable = [];
1071
- if (existsSync4(disablePath)) {
1072
- try {
1073
- const parsed = DisableYamlSchema.safeParse(parseYAML(readFileSync5(disablePath, "utf8")));
1074
- if (parsed.success && parsed.data.disable) {
1075
- disable = parsed.data.disable;
1076
- }
1077
- } catch {
1078
- }
1079
- }
1080
- return { add: added, disable };
1081
- }
1082
-
1083
- // src/mcp.ts
1084
- var MCP_SERVER_IDS = ["context7"];
1085
- var MCP_SERVERS = {
1086
- context7: {
1087
- id: "context7",
1088
- description: "Upstash Context7 \u2014 fetches up-to-date library docs via resolve-library-id + get-library-docs.",
1089
- command: "npx",
1090
- args: ["-y", "@upstash/context7-mcp"]
1091
- }
1092
- };
1093
- function resolveMcpIds(requested) {
1094
- return requested.map((id) => {
1095
- if (!MCP_SERVER_IDS.includes(id)) {
1096
- throw new Error(`unknown MCP server: ${id} (expected one of ${MCP_SERVER_IDS.join(", ")})`);
1097
- }
1098
- return id;
1099
- });
1100
- }
1101
-
1102
469
  // src/render.ts
1103
470
  var RenderError = class extends Error {
1104
471
  constructor(message) {
@@ -1122,7 +489,6 @@ function removeByIds(items, disabled) {
1122
489
  function applyOverrides(harness, overrides) {
1123
490
  const disabled = overrides?.disable ?? [];
1124
491
  return {
1125
- agents: removeByIds(mergeById(harness.agents, overrides?.add?.agents), disabled),
1126
492
  skills: removeByIds(mergeById(harness.skills, overrides?.add?.skills), disabled),
1127
493
  cmds: removeByIds(mergeById(harness.cmds, overrides?.add?.cmds), disabled)
1128
494
  };
@@ -1138,58 +504,37 @@ function render(input) {
1138
504
  }
1139
505
  const base = input.projectSkills?.length ? { ...input.harness, skills: mergeById(input.harness.skills, input.projectSkills) } : input.harness;
1140
506
  const harness = applyOverrides(base, input.overrides);
1141
- if (harness.agents.length === 0) {
1142
- throw new RenderError("No agents found in harness");
1143
- }
1144
507
  const files = [];
1145
508
  const warnings = [];
1146
509
  const exposedSkills = /* @__PURE__ */ new Map();
1147
510
  const exposedCmds = /* @__PURE__ */ new Map();
1148
511
  for (const engine of opencodeLast(engines)) {
1149
512
  const renderer = getRenderer(engine);
1150
- const renderedSkills = [];
513
+ const renderedSkillIds = /* @__PURE__ */ new Set();
1151
514
  for (const skill of harness.skills) {
1152
515
  const result = renderer.renderSkill(skill);
1153
516
  warnings.push(...result.warnings);
1154
517
  if (result.files.length > 0) {
1155
518
  const alreadyVisible = engine === "opencode" && exposedSkills.has(skill.meta.id);
1156
519
  if (!alreadyVisible) files.push(...result.files);
1157
- renderedSkills.push(skill);
520
+ renderedSkillIds.add(skill.meta.id);
1158
521
  exposedSkills.set(skill.meta.id, skill);
1159
522
  }
1160
523
  }
1161
- const renderedSkillIds = new Set(renderedSkills.map((s) => s.meta.id));
1162
- const renderedCmds = [];
1163
524
  for (const cmd of harness.cmds) {
1164
525
  if (!renderedSkillIds.has(cmd.meta.invokes_skill)) continue;
1165
526
  const result = renderer.renderCmd(cmd);
1166
527
  warnings.push(...result.warnings);
1167
528
  if (result.files.length > 0) {
1168
529
  files.push(...result.files);
1169
- renderedCmds.push(cmd);
1170
530
  exposedCmds.set(cmd.meta.id, cmd);
1171
531
  }
1172
532
  }
1173
- const agentsResult = renderer.renderAgents(harness.agents);
1174
- warnings.push(...agentsResult.warnings);
1175
- files.push(...agentsResult.files);
1176
- if (input.mcpServers && input.mcpServers.length > 0) {
1177
- const specs = input.mcpServers.map((id) => MCP_SERVERS[id]);
1178
- const mcpResult = renderer.renderMcp(specs);
1179
- warnings.push(...mcpResult.warnings);
1180
- files.push(...mcpResult.files);
1181
- }
1182
- if (input.withStopHook !== false) {
1183
- const hookResult = renderer.renderStopHook();
1184
- warnings.push(...hookResult.warnings);
1185
- files.push(...hookResult.files);
1186
- }
1187
533
  }
1188
- const hasProjectSkills = (input.projectSkills?.length ?? 0) > 0;
1189
- const umbrellaContent = buildUmbrellaBody(harness.agents, {
534
+ const umbrellaContent = buildUmbrellaBody({
1190
535
  availableSkills: Array.from(exposedSkills.values()),
1191
536
  availableCommands: Array.from(exposedCmds.values()),
1192
- hasProjectSkills,
537
+ hasProjectSkills: (input.projectSkills?.length ?? 0) > 0,
1193
538
  hasQualityDoc: input.hasQualityDoc === true
1194
539
  });
1195
540
  files.push({ path: "AGENTS.md", content: umbrellaContent });
@@ -1202,8 +547,11 @@ function render(input) {
1202
547
  // src/cli/plan-render.ts
1203
548
  var QUALITY_DOC_PATH = "docs/quality/code-quality.md";
1204
549
  function resolveEngineList(requested) {
1205
- if (!requested) return [...ENGINES];
1206
- if (requested.length === 0) throw new Error("no engine selected");
550
+ if (!requested || requested.length === 0) {
551
+ throw new Error(
552
+ `no engine selected: pass --engines=<list> with one or more of ${ENGINES.join(", ")}`
553
+ );
554
+ }
1207
555
  const engines = requested.map((e) => {
1208
556
  if (!ENGINES.includes(e)) {
1209
557
  throw new Error(`unknown engine: ${e} (expected one of ${ENGINES.join(", ")})`);
@@ -1214,7 +562,7 @@ function resolveEngineList(requested) {
1214
562
  }
1215
563
  function defaultPackageDir() {
1216
564
  const here = dirname2(fileURLToPath(import.meta.url));
1217
- if (existsSync5(join6(here, "agents"))) return here;
565
+ if (existsSync3(join4(here, "skills"))) return here;
1218
566
  return resolve2(here, "..");
1219
567
  }
1220
568
  function planInit(args) {
@@ -1223,31 +571,14 @@ function planInit(args) {
1223
571
  const harness = loadHarness(packageDir);
1224
572
  const overrides = args.overridesDir ? loadOverrides(args.overridesDir) : void 0;
1225
573
  const projectSkills = loadProjectSkills(args.targetDir);
1226
- const hasQualityDoc = existsSync5(join6(args.targetDir, QUALITY_DOC_PATH));
1227
- const mcpServers = args.mcpServers ? resolveMcpIds(args.mcpServers) : void 0;
1228
- const stopHookInstalled = args.withStopHook !== false;
1229
- const output = render({
1230
- harness,
1231
- engines,
1232
- overrides,
1233
- projectSkills,
1234
- hasQualityDoc,
1235
- mcpServers,
1236
- withStopHook: stopHookInstalled
1237
- });
1238
- return { engines, output, stopHookInstalled };
574
+ const hasQualityDoc = existsSync3(join4(args.targetDir, QUALITY_DOC_PATH));
575
+ const output = render({ harness, engines, overrides, projectSkills, hasQualityDoc });
576
+ return { engines, output };
1239
577
  }
1240
578
 
1241
579
  // src/cli/uninstall.ts
1242
- import {
1243
- existsSync as existsSync6,
1244
- readFileSync as readFileSync6,
1245
- readdirSync,
1246
- rmdirSync,
1247
- unlinkSync,
1248
- writeFileSync as writeFileSync2
1249
- } from "fs";
1250
- import { dirname as dirname3, join as join7, relative, resolve as resolve3 } from "path";
580
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, rmdirSync, unlinkSync } from "fs";
581
+ import { dirname as dirname3, join as join5, relative, resolve as resolve3 } from "path";
1251
582
  function pruneEmptyDirs(root, leaves) {
1252
583
  const candidates = /* @__PURE__ */ new Set();
1253
584
  for (const leaf of leaves) {
@@ -1260,7 +591,7 @@ function pruneEmptyDirs(root, leaves) {
1260
591
  const pruned = [];
1261
592
  const sorted = [...candidates].sort((a, b) => b.length - a.length);
1262
593
  for (const dir of sorted) {
1263
- if (!existsSync6(dir)) continue;
594
+ if (!existsSync4(dir)) continue;
1264
595
  if (readdirSync(dir).length > 0) continue;
1265
596
  rmdirSync(dir);
1266
597
  pruned.push(relative(root, dir));
@@ -1277,25 +608,17 @@ import {
1277
608
  lstatSync as lstatSync2,
1278
609
  mkdirSync,
1279
610
  openSync,
1280
- readFileSync as readFileSync7,
611
+ readFileSync as readFileSync5,
1281
612
  readdirSync as readdirSync2,
1282
613
  realpathSync as realpathSync2,
1283
614
  rmdirSync as rmdirSync2,
1284
615
  unlinkSync as unlinkSync2,
1285
- writeFileSync as writeFileSync3
616
+ writeFileSync as writeFileSync2
1286
617
  } from "fs";
1287
618
  import { homedir } from "os";
1288
- import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve4, sep } from "path";
619
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve4, sep } from "path";
1289
620
  var MANIFEST_PATH = ".harness-manifest.json";
1290
- var PRIVATE_FILES = /* @__PURE__ */ new Set([
1291
- MANIFEST_PATH,
1292
- ".mcp.json",
1293
- ".codex/config.toml",
1294
- ".codex/hooks.json",
1295
- ".claude/settings.json",
1296
- ".opencode/opencode.json",
1297
- ".opencode/mcp.json"
1298
- ]);
621
+ var PRIVATE_FILES = /* @__PURE__ */ new Set([MANIFEST_PATH]);
1299
622
  function canonicalRoot(root) {
1300
623
  let ancestor = resolve4(root);
1301
624
  const missing = [];
@@ -1303,7 +626,7 @@ function canonicalRoot(root) {
1303
626
  missing.unshift(basename2(ancestor));
1304
627
  ancestor = dirname4(ancestor);
1305
628
  }
1306
- return join8(realpathSync2(ancestor), ...missing);
629
+ return join6(realpathSync2(ancestor), ...missing);
1307
630
  }
1308
631
  function contains(parent, child) {
1309
632
  const path = relative2(parent, child);
@@ -1343,7 +666,7 @@ function writeBackupFile(path, content) {
1343
666
  createDirectories(dirname4(path), [], 448);
1344
667
  const fd = openSync(path, "wx", 384);
1345
668
  try {
1346
- writeFileSync3(fd, content);
669
+ writeFileSync2(fd, content);
1347
670
  fsyncSync(fd);
1348
671
  } finally {
1349
672
  closeSync(fd);
@@ -1354,14 +677,14 @@ function saveSnapshot(root, paths, backup) {
1354
677
  createDirectories(dirname4(backup), [], 448);
1355
678
  mkdirSync(backup, { mode: 448 });
1356
679
  for (const path of paths) {
1357
- const full = join8(root, path);
680
+ const full = join6(root, path);
1358
681
  const info = lstatSync2(full, { throwIfNoEntry: false });
1359
682
  if (!info) {
1360
683
  entries.push({ path, exists: false });
1361
684
  continue;
1362
685
  }
1363
- const content = readFileSync7(full);
1364
- writeBackupFile(join8(backup, "files", path), content);
686
+ const content = readFileSync5(full);
687
+ writeBackupFile(join6(backup, "files", path), content);
1365
688
  entries.push({
1366
689
  path,
1367
690
  exists: true,
@@ -1370,7 +693,7 @@ function saveSnapshot(root, paths, backup) {
1370
693
  });
1371
694
  }
1372
695
  writeBackupFile(
1373
- join8(backup, "snapshot.json"),
696
+ join6(backup, "snapshot.json"),
1374
697
  `${JSON.stringify({ version: 1, root, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries }, null, 2)}
1375
698
  `
1376
699
  );
@@ -1385,16 +708,16 @@ function rollback(root, backup, entries, touched, createdDirectories) {
1385
708
  try {
1386
709
  assertManagedPaths(root, [path]);
1387
710
  const entry = entries.get(path);
1388
- const full = join8(root, path);
711
+ const full = join6(root, path);
1389
712
  const current = lstatSync2(full, { throwIfNoEntry: false });
1390
713
  if (!entry?.exists) {
1391
714
  if (current) unlinkSync2(full);
1392
715
  continue;
1393
716
  }
1394
- const original = readFileSync7(join8(backup, "files", path));
1395
- if (!current || !readFileSync7(full).equals(original)) {
717
+ const original = readFileSync5(join6(backup, "files", path));
718
+ if (!current || !readFileSync5(full).equals(original)) {
1396
719
  if (current) unlinkSync2(full);
1397
- writeFileSync3(full, original, { mode: 384 });
720
+ writeFileSync2(full, original, { mode: 384 });
1398
721
  }
1399
722
  chmodSync2(full, entry.mode);
1400
723
  } catch (error) {
@@ -1415,7 +738,7 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1415
738
  assertManagedPaths(root, paths);
1416
739
  const target = canonicalRoot(root);
1417
740
  const backup = resolve4(
1418
- backupDir ?? join8(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
741
+ backupDir ?? join6(homedir(), ".local", "state", "vaubaan-harness", "backups", randomUUID())
1419
742
  );
1420
743
  assertBackupLocation(target, backup);
1421
744
  let snapshot;
@@ -1433,18 +756,18 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1433
756
  try {
1434
757
  assertManagedPaths(target, paths);
1435
758
  for (const path of removals) {
1436
- if (!lstatSync2(join8(target, path), { throwIfNoEntry: false })) continue;
759
+ if (!lstatSync2(join6(target, path), { throwIfNoEntry: false })) continue;
1437
760
  touched.add(path);
1438
- unlinkSync2(join8(target, path));
761
+ unlinkSync2(join6(target, path));
1439
762
  }
1440
763
  for (const file of writes) {
1441
- const full = join8(target, file.path);
764
+ const full = join6(target, file.path);
1442
765
  createDirectories(dirname4(full), createdDirectories);
1443
766
  touched.add(file.path);
1444
767
  const entry = entries.get(file.path);
1445
768
  const mode = file.path === MANIFEST_PATH ? 384 : entry?.exists ? entry.mode : PRIVATE_FILES.has(file.path) ? 384 : 420;
1446
769
  if (entry?.exists && file.path === MANIFEST_PATH) chmodSync2(full, mode);
1447
- writeFileSync3(full, file.content, { mode });
770
+ writeFileSync2(full, file.content, { mode });
1448
771
  if (entry?.exists) chmodSync2(full, mode);
1449
772
  }
1450
773
  } catch (error) {
@@ -1458,39 +781,33 @@ function applyUpdateTransaction(root, writes, removals, backupDir) {
1458
781
  }
1459
782
 
1460
783
  // src/cli/update.ts
1461
- import { existsSync as existsSync8, readFileSync as readFileSync9 } from "fs";
1462
- import { join as join10, resolve as resolve5 } from "path";
1463
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
784
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
785
+ import { dirname as dirname5, join as join8, resolve as resolve5 } from "path";
786
+ import { isDeepStrictEqual } from "util";
1464
787
 
1465
788
  // src/cli/update-manifest.ts
1466
- import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
1467
- import { join as join9 } from "path";
1468
- import { z as z6 } from "zod";
1469
- var EngineSchema = z6.enum(ENGINES);
1470
- var LegacySchema = z6.object({
1471
- version: z6.enum(["1", "2", "3"]),
789
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
790
+ import { join as join7 } from "path";
791
+ import { z as z4 } from "zod";
792
+ var EngineSchema = z4.enum(ENGINES);
793
+ var LegacySchema = z4.object({
794
+ version: z4.enum(["1", "2", "3"]),
1472
795
  engine: EngineSchema.optional(),
1473
- engines: z6.array(EngineSchema).nonempty().optional(),
1474
- renderedAt: z6.string(),
1475
- files: z6.array(z6.string())
796
+ engines: z4.array(EngineSchema).nonempty().optional(),
797
+ renderedAt: z4.string(),
798
+ files: z4.array(z4.string())
1476
799
  });
1477
800
 
1478
801
  // src/cli/update.ts
1479
- var CODEX_CONFIG_PATH = ".codex/config.toml";
802
+ var LEGACY_HOOK_FILES = [".claude/settings.json", ".codex/hooks.json"];
803
+ var LEGACY_HOOK_MARKER = "@vaubaan/harness stop-hook";
1480
804
  function currentContent(root, path) {
1481
- return existsSync8(join10(root, path)) ? readFileSync9(join10(root, path), "utf8") : void 0;
1482
- }
1483
- function ownedUnchanged(root, previous, path) {
1484
- const content = currentContent(root, path);
1485
- if (content === void 0 || !previous.files.includes(path)) return false;
1486
- const hash = previous.fileHashes?.[path];
1487
- return hash === void 0 || hash === hashContent(content);
805
+ return existsSync6(join8(root, path)) ? readFileSync7(join8(root, path), "utf8") : void 0;
1488
806
  }
1489
807
  function checkArtifactConflicts(root, previous, writes, removals) {
1490
808
  const desired = new Map(writes.map((file) => [file.path, file.content]));
1491
809
  const conflicts = [];
1492
810
  for (const path of [...desired.keys(), ...removals]) {
1493
- if (SHARED_CONFIG_PATHS.includes(path)) continue;
1494
811
  const content = currentContent(root, path);
1495
812
  if (content === void 0 || content === desired.get(path)) continue;
1496
813
  if (!previous.files.includes(path)) {
@@ -1507,92 +824,47 @@ move their content to docs/ or .harness-overrides/, or keep them as yours with -
1507
824
  );
1508
825
  }
1509
826
  }
1510
- function legacyMcpOwnership(root, previous) {
1511
- if (!ownedUnchanged(root, previous, CLAUDE_MCP_PATH)) return void 0;
1512
- try {
1513
- const servers = JSON.parse(currentContent(root, CLAUDE_MCP_PATH) ?? "").mcpServers;
1514
- if (!servers || typeof servers !== "object" || Array.isArray(servers)) return void 0;
1515
- return { createdFile: true, addedMcp: true, addedSchema: false, entries: servers };
1516
- } catch {
1517
- return void 0;
827
+ function releaseLegacyPaths(previous, warnings) {
828
+ const released = previous.files.filter((path) => RELEASED_PATHS.includes(path));
829
+ for (const path of released) {
830
+ warnings.push(`no longer managed by the harness, left in place: ${path}`);
1518
831
  }
832
+ if (released.length === 0) return previous;
833
+ return { ...previous, files: previous.files.filter((path) => !released.includes(path)) };
1519
834
  }
1520
- function planMcp(root, settings, rendered, pendingWrites) {
1521
- const { previous } = settings;
1522
- const plan = {
1523
- writes: [],
1524
- removals: [],
1525
- owned: [],
1526
- plannedOpenCode: false,
1527
- warnings: []
1528
- };
1529
- const claudeOwnership = previous.mcpConfig ?? legacyMcpOwnership(root, previous);
1530
- const codexOwned = ownedUnchanged(root, previous, CODEX_CONFIG_PATH);
1531
- if (settings.mcpServers === void 0) {
1532
- if (codexOwned) plan.owned.push(CODEX_CONFIG_PATH);
1533
- plan.mcpConfig = claudeOwnership;
1534
- return plan;
1535
- }
1536
- const desired = (path) => rendered.find((file) => file.path === path);
1537
- if (!pendingWrites.some((file) => file.path === OPENCODE_CONFIG_PATH)) {
1538
- plan.plannedOpenCode = true;
1539
- if (previous.files.includes(OPENCODE_CONFIG_PATH) && !previous.opencodeConfig) {
1540
- plan.warnings.push(`preserved legacy shared configuration: ${OPENCODE_CONFIG_PATH}`);
835
+ function legacyHookWarnings(root) {
836
+ const warnings = [];
837
+ for (const path of LEGACY_HOOK_FILES) {
838
+ const content = currentContent(root, path);
839
+ if (content?.includes(LEGACY_HOOK_MARKER)) {
840
+ warnings.push(
841
+ `remove the harness Stop hook entry from ${path}: the Stop hook was removed in 2.0, run \`npx @vaubaan/harness lint\` in CI and pre-commit instead`
842
+ );
1541
843
  }
1542
- const opencode = planOpenCodeConfig(
1543
- root,
1544
- desired(OPENCODE_CONFIG_PATH),
1545
- previous.opencodeConfig
1546
- );
1547
- if (opencode.write) plan.writes.push(opencode.write);
1548
- if (opencode.remove) plan.removals.push(OPENCODE_CONFIG_PATH);
1549
- plan.opencodeConfig = opencode.ownership;
1550
- plan.warnings.push(...opencode.warnings);
1551
- }
1552
- const claude = planClaudeMcpConfig(root, desired(CLAUDE_MCP_PATH), claudeOwnership);
1553
- if (claude.write) plan.writes.push(claude.write);
1554
- if (claude.remove) plan.removals.push(CLAUDE_MCP_PATH);
1555
- plan.mcpConfig = claude.ownership;
1556
- plan.warnings.push(...claude.warnings);
1557
- const codex = desired(CODEX_CONFIG_PATH);
1558
- const codexExists = existsSync8(join10(root, CODEX_CONFIG_PATH));
1559
- if (codex && (!codexExists || codexOwned)) {
1560
- plan.writes.push(codex);
1561
- plan.owned.push(CODEX_CONFIG_PATH);
1562
- } else if (codex) {
1563
- plan.warnings.push(
1564
- `left ${CODEX_CONFIG_PATH} unchanged; add this block to it to enable MCP in Codex:
1565
- ${codex.content.trimEnd()}`
1566
- );
1567
- } else if (codexOwned) {
1568
- plan.removals.push(CODEX_CONFIG_PATH);
1569
844
  }
1570
- return plan;
845
+ return warnings;
1571
846
  }
1572
847
  function planInstallation(args, settings) {
1573
848
  const root = resolve5(args.targetDir);
1574
- const { previous, engines, hookEngines } = settings;
849
+ const { engines } = settings;
850
+ const warnings = [];
851
+ const previous = releaseLegacyPaths(settings.previous, warnings);
1575
852
  const preserved = [
1576
853
  .../* @__PURE__ */ new Set([...previous.preservedFiles ?? [], ...args.preserveFiles ?? []])
1577
854
  ].sort();
1578
855
  if (preserved.includes(MANIFEST_FILENAME))
1579
856
  throw new Error("cannot preserve the harness manifest");
1580
- if (preserved.some((path) => SHARED_CONFIG_PATHS.includes(path))) {
1581
- throw new Error(
1582
- "--preserve applies to generated artifacts; shared configurations use entry-level preservation"
1583
- );
1584
- }
1585
- assertManagedPaths(root, [...previous.files, ...preserved, ...SHARED_CONFIG_PATHS]);
857
+ assertManagedPaths(root, [...previous.files, ...preserved]);
1586
858
  const requestedOverrides = args.overridesDir ?? previous.overridesDir;
1587
859
  const overridesDir = args.overridesDir ? resolve5(args.overridesDir) : previous.overridesDir ? resolve5(root, previous.overridesDir) : root;
1588
- if (requestedOverrides && !existsSync8(join10(overridesDir, ".harness-overrides"))) {
860
+ if (requestedOverrides && !existsSync6(join8(overridesDir, ".harness-overrides"))) {
1589
861
  throw new Error(`recorded overrides are missing: ${overridesDir}/.harness-overrides`);
1590
862
  }
1591
- const hasOverrides = existsSync8(join10(overridesDir, ".harness-overrides"));
1592
- const disablePath = join10(overridesDir, ".harness-overrides", "disable.yaml");
1593
- if (existsSync8(disablePath)) {
863
+ const hasOverrides = existsSync6(join8(overridesDir, ".harness-overrides"));
864
+ const disablePath = join8(overridesDir, ".harness-overrides", "disable.yaml");
865
+ if (existsSync6(disablePath)) {
1594
866
  try {
1595
- DisableYamlSchema.parse(parseYAML(readFileSync9(disablePath, "utf8")));
867
+ DisableYamlSchema.parse(parseYAML(readFileSync7(disablePath, "utf8")));
1596
868
  } catch {
1597
869
  throw new Error(`invalid override selection: ${disablePath}`);
1598
870
  }
@@ -1601,40 +873,16 @@ function planInstallation(args, settings) {
1601
873
  targetDir: root,
1602
874
  packageDir: args.packageDir,
1603
875
  engines,
1604
- overridesDir: hasOverrides ? overridesDir : void 0,
1605
- mcpServers: settings.mcpServers,
1606
- withStopHook: false
876
+ overridesDir: hasOverrides ? overridesDir : void 0
1607
877
  });
1608
- const generated = rendered.output.files.filter(
1609
- (file) => !SHARED_CONFIG_PATHS.includes(file.path)
1610
- );
1611
- const config = planUpdateConfigs(root, previous, hookEngines);
1612
- const mcp = planMcp(root, settings, rendered.output.files, config.writes);
1613
- const output = [...generated, ...config.writes, ...mcp.writes].filter(
1614
- (file) => !preserved.includes(file.path)
878
+ const output = rendered.output.files.filter((file) => !preserved.includes(file.path));
879
+ const owned = output.map((file) => file.path).sort();
880
+ const removals = previous.files.filter(
881
+ (file) => !owned.includes(file) && !preserved.includes(file)
1615
882
  );
1616
- const owned = [
1617
- .../* @__PURE__ */ new Set([...generated.map((file) => file.path), ...config.ownedFiles, ...mcp.owned])
1618
- ].filter((file) => !preserved.includes(file)).sort();
1619
- const removals = [
1620
- .../* @__PURE__ */ new Set([
1621
- ...previous.files.filter(
1622
- (file) => !owned.includes(file) && !SHARED_CONFIG_PATHS.includes(file)
1623
- ),
1624
- ...config.removals,
1625
- ...mcp.removals
1626
- ])
1627
- ].filter((file) => !preserved.includes(file));
1628
- assertManagedPaths(root, [...output.map((file) => file.path), ...removals]);
883
+ assertManagedPaths(root, [...owned, ...removals]);
1629
884
  checkArtifactConflicts(root, previous, output, removals);
1630
- const hashes = Object.fromEntries(
1631
- owned.map((path) => {
1632
- const content = output.find((file) => file.path === path)?.content ?? currentContent(root, path);
1633
- if (content === void 0) throw new Error(`missing planned harness file: ${path}`);
1634
- return [path, hashContent(content)];
1635
- })
1636
- );
1637
- const opencodeConfig = mcp.plannedOpenCode ? mcp.opencodeConfig : config.opencodeConfig;
885
+ const hashes = Object.fromEntries(output.map((file) => [file.path, hashContent(file.content)]));
1638
886
  const manifest = {
1639
887
  version: MANIFEST_VERSION,
1640
888
  harnessVersion: VERSION,
@@ -1642,22 +890,17 @@ function planInstallation(args, settings) {
1642
890
  renderedAt: previous.renderedAt,
1643
891
  files: owned,
1644
892
  fileHashes: hashes,
1645
- stopHookInstalled: hookEngines.length > 0,
1646
- stopHookEngines: [...hookEngines].sort(),
1647
893
  ...hasOverrides ? { overridesDir: overridesDir === root ? "." : overridesDir } : {},
1648
- ...preserved.length ? { preservedFiles: preserved } : {},
1649
- ...opencodeConfig ? { opencodeConfig } : {},
1650
- ...mcp.mcpConfig ? { mcpConfig: mcp.mcpConfig } : {},
1651
- ...config.hookConfigs ? { hookConfigs: config.hookConfigs } : {}
894
+ ...preserved.length ? { preservedFiles: preserved } : {}
1652
895
  };
1653
896
  const writes = output.filter((file) => currentContent(root, file.path) !== file.content);
1654
- const existingRemovals = removals.filter((path) => existsSync8(join10(root, path)));
1655
- if (writes.length || existingRemovals.length || !isDeepStrictEqual3(previous, manifest)) {
897
+ const existingRemovals = removals.filter((path) => existsSync6(join8(root, path)));
898
+ if (writes.length || existingRemovals.length || !isDeepStrictEqual(settings.previous, manifest)) {
1656
899
  manifest.renderedAt = (/* @__PURE__ */ new Date()).toISOString();
1657
900
  writes.push({ path: MANIFEST_FILENAME, content: `${JSON.stringify(manifest, null, 2)}
1658
901
  ` });
1659
902
  }
1660
- const warnings = [...rendered.output.warnings, ...config.warnings, ...mcp.warnings];
903
+ warnings.push(...rendered.output.warnings, ...legacyHookWarnings(root));
1661
904
  if (preserved.length) warnings.push(`preserved user-owned artifacts: ${preserved.join(", ")}`);
1662
905
  return { writes, removals: existingRemovals, owned, manifest, warnings };
1663
906
  }
@@ -1670,9 +913,9 @@ function writeFilesToTarget(files, targetDir) {
1670
913
  );
1671
914
  const written = [];
1672
915
  for (const f of files) {
1673
- const full = join11(targetDir, f.path);
1674
- mkdirSync2(dirname5(full), { recursive: true });
1675
- writeFileSync4(full, f.content);
916
+ const full = join9(targetDir, f.path);
917
+ mkdirSync2(dirname6(full), { recursive: true });
918
+ writeFileSync3(full, f.content);
1676
919
  written.push(f.path);
1677
920
  }
1678
921
  return written;
@@ -1683,7 +926,6 @@ function emptyManifest(engines) {
1683
926
  function initCommand(args) {
1684
927
  const root = resolve6(args.targetDir);
1685
928
  const engines = resolveEngineList(args.engines);
1686
- const stopHookInstalled = args.withStopHook !== false;
1687
929
  const previous = readManifest(root) ?? emptyManifest(engines);
1688
930
  const plan = planInstallation(
1689
931
  {
@@ -1692,16 +934,10 @@ function initCommand(args) {
1692
934
  overridesDir: args.overridesDir,
1693
935
  preserveFiles: args.preserveFiles
1694
936
  },
1695
- {
1696
- previous,
1697
- sourceVersion: previous.version,
1698
- engines,
1699
- hookEngines: stopHookInstalled ? engines : [],
1700
- mcpServers: args.mcpServers ?? []
1701
- }
937
+ { previous, sourceVersion: previous.version, engines }
1702
938
  );
1703
939
  const touchedExisting = [...plan.writes.map((file) => file.path), ...plan.removals].some(
1704
- (path) => path !== MANIFEST_FILENAME && existsSync9(join11(root, path))
940
+ (path) => path !== MANIFEST_FILENAME && existsSync7(join9(root, path))
1705
941
  );
1706
942
  let backupDir;
1707
943
  if (plan.writes.length || plan.removals.length) {
@@ -1710,14 +946,12 @@ function initCommand(args) {
1710
946
  rmSync(backupDir, { recursive: true, force: true });
1711
947
  backupDir = void 0;
1712
948
  }
1713
- pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname5(join11(root, path)))));
949
+ pruneEmptyDirs(root, new Set(plan.removals.map((path) => dirname6(join9(root, path)))));
1714
950
  }
1715
- const sharedWritten = plan.writes.map((file) => file.path).filter((path) => SHARED_CONFIG_PATHS.includes(path) && !plan.owned.includes(path));
1716
951
  return {
1717
- filesWritten: [...plan.owned, ...sharedWritten],
952
+ filesWritten: plan.owned,
1718
953
  staleFilesRemoved: plan.removals,
1719
954
  warnings: plan.warnings,
1720
- stopHookInstalled,
1721
955
  engines,
1722
956
  ...backupDir ? { backupDir } : {}
1723
957
  };