@odarino/haren 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -49,8 +49,8 @@ import { join as join2 } from "path";
49
49
  function renderTemplate(template, harenDirName) {
50
50
  return template.replaceAll(HAREN_DIR_TOKEN, harenDirName);
51
51
  }
52
- function gateCommand(harenDirName) {
53
- return `bun ${harenDirName}/hooks/brainstorm-gate.ts`;
52
+ function gateCommand(harenDirName, host) {
53
+ return `bun ${harenDirName}/hooks/brainstorm-gate.ts${host ? ` --host ${host}` : ""}`;
54
54
  }
55
55
  async function writeGateScript(harenDir) {
56
56
  await mkdir(join2(harenDir, "hooks"), { recursive: true });
@@ -207,7 +207,15 @@ function inside(path: string, root: string): boolean {
207
207
  return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
208
208
  }
209
209
 
210
+ // apply_patch can touch several files: each target is checked, and allow()
211
+ // moves on to the next target until the last one.
212
+ class AllowNext extends Error {}
213
+ let deferAllow = false;
214
+
210
215
  function allow(): never {
216
+ if (deferAllow) throw new AllowNext();
217
+ // Claude-protocol hosts named by --host parse stdout JSON against their own schema: print nothing.
218
+ if (quietHost) process.exit(0);
211
219
  console.log(JSON.stringify({
212
220
  allow: true, // Claude Code
213
221
  permission: "allow", // Cursor
@@ -218,6 +226,39 @@ function allow(): never {
218
226
  // Set by readInput(). "unknown" writes both the Claude and the Cursor denial.
219
227
  let source: "claude" | "cursor" | "unknown" = "unknown";
220
228
 
229
+ // --host <id> in the hook command names the host exactly. Hosts with a
230
+ // Claude-style hook API (exit 2 + stderr) use the Claude output path.
231
+ const CLAUDE_STYLE_HOSTS = ["claude-code", "codex", "qwen-code"];
232
+ // codex and qwen-code: allow = exit 0 with no stdout, deny = exit 2 with stderr only.
233
+ const QUIET_HOSTS = ["codex", "qwen-code"];
234
+ const quietHost = (() => {
235
+ const i = process.argv.indexOf("--host");
236
+ return i >= 0 && QUIET_HOSTS.includes(process.argv[i + 1] ?? "");
237
+ })();
238
+
239
+ function hostArg(): typeof source | null {
240
+ const i = process.argv.indexOf("--host");
241
+ const id = i >= 0 ? process.argv[i + 1] : undefined;
242
+ if (!id) return null;
243
+ if (CLAUDE_STYLE_HOSTS.includes(id)) return "claude";
244
+ if (id === "cursor") return "cursor";
245
+ return null; // unknown value: fall back to the guess
246
+ }
247
+
248
+ // Qwen Code tool names: run_shell_command is a shell call; edit and write_file write a file.
249
+ const SHELL_TOOLS = ["Bash", "run_shell_command"];
250
+
251
+ // Codex apply_patch sends the patch text; its file headers (and Move to lines) name the targets.
252
+ // Unreadable patch text gives no target: the normal gate path runs (no silent allow).
253
+ function patchTargets(raw: unknown): string[] {
254
+ // The patch text can come as a string or as an argv array (["apply_patch", "<patch>"]).
255
+ const patch = Array.isArray(raw) ? raw.filter((x) => typeof x === "string").join("\\n") : raw;
256
+ if (typeof patch !== "string") return [];
257
+ const out: string[] = [];
258
+ for (const m of patch.matchAll(/^[ \\t]*\\*\\*\\* (?:(?:Add|Update|Delete) File|Move to): (.+?)\\r?$/gm)) out.push(m[1].trim());
259
+ return out;
260
+ }
261
+
221
262
  // Claude Code sends hook_event_name "PreToolUse" with session_id and transcript_path.
222
263
  // Cursor sends its own hook_event_name values (beforeShellExecution, preToolUse, ...).
223
264
  function detectSource(input: any): typeof source {
@@ -461,15 +502,21 @@ function shellWritesTo(command: string, startCwd: string, roots: string[], exclu
461
502
  }
462
503
 
463
504
  // shell: the payload is a shell event (Claude Bash, Cursor beforeShellExecution).
464
- interface HookInput { target: string; command: string | null; cwd: string; shell: boolean }
505
+ interface HookInput { target: string; targets?: string[]; command: string | null; cwd: string; shell: boolean }
465
506
 
466
507
  async function readInput(): Promise<HookInput> {
467
508
  try {
468
509
  const stdin = await Bun.stdin.text();
469
510
  if (!stdin) return { target: "", command: null, cwd: process.cwd(), shell: false };
470
511
  const input = JSON.parse(stdin);
471
- source = detectSource(input);
472
- const shell = input?.tool_name === "Bash"
512
+ source = hostArg() ?? detectSource(input);
513
+ const cwd0 = typeof input?.cwd === "string" && input.cwd ? input.cwd : process.cwd();
514
+ if (input?.tool_name === "apply_patch") {
515
+ const paths = patchTargets(input?.tool_input?.command)
516
+ .map((p) => realTarget(resolve(cwd0, p)));
517
+ return { target: paths[0] ?? "", targets: paths, command: null, cwd: cwd0, shell: false };
518
+ }
519
+ const shell = SHELL_TOOLS.includes(input?.tool_name)
473
520
  || input?.hook_event_name === "beforeShellExecution"
474
521
  || (input !== null && typeof input === "object" && "command" in input);
475
522
  const cwd = typeof input?.cwd === "string" && input.cwd ? input.cwd : process.cwd();
@@ -496,8 +543,8 @@ async function readInput(): Promise<HookInput> {
496
543
  const READ_ONLY_MESSAGE =
497
544
  "This repo is read-only (manifest readOnly: true). It is the legacy source of truth. The gate override does not lift this block.";
498
545
 
499
- async function main() {
500
- const { target, command, cwd, shell } = await readInput();
546
+ async function main(input: HookInput) {
547
+ const { target, command, cwd, shell } = input;
501
548
 
502
549
  // Shell commands: only the readOnly repo check applies. Everything else is allowed.
503
550
  // A shell event without a usable command is allowed too (not the Edit/Write gate).
@@ -534,6 +581,9 @@ async function main() {
534
581
 
535
582
  if (process.env.HAREN_GATE === "off") allow();
536
583
 
584
+ // A file outside the workspace (another project, temp files) is not ours to gate.
585
+ if (target && !inside(target, workspaceDir)) allow();
586
+
537
587
  const progressFile = Bun.file(resolve(harenDir, "progress.json"));
538
588
  if (!(await progressFile.exists())) allow();
539
589
 
@@ -553,8 +603,8 @@ async function main() {
553
603
  deny(message);
554
604
  }
555
605
 
556
- // No file path, or a file outside the workspace (temp files): legacy rule.
557
- if (!target || !inside(target, workspaceDir)) allow();
606
+ // No file path: legacy rule.
607
+ if (!target) allow();
558
608
 
559
609
  const repos = await readRepos();
560
610
  const roots: string[] = [];
@@ -584,7 +634,21 @@ async function main() {
584
634
 
585
635
  // Top-level await: on Windows, Bun exits early (code 0, no output) if main() is
586
636
  // not awaited while it waits on stdin, which would allow every write.
587
- await main().catch((err) => {
637
+ async function run() {
638
+ const input = await readInput();
639
+ const targets = input.targets?.length ? input.targets : [input.target];
640
+ for (let i = 0; i < targets.length; i++) {
641
+ deferAllow = i < targets.length - 1;
642
+ try {
643
+ await main({ ...input, target: targets[i] });
644
+ } catch (err) {
645
+ if (err instanceof AllowNext) continue;
646
+ throw err;
647
+ }
648
+ }
649
+ }
650
+
651
+ await run().catch((err) => {
588
652
  console.error("brainstorm-gate hook error:", err);
589
653
  process.exit(1);
590
654
  });
@@ -749,7 +813,7 @@ language: ${yamlScalar(o.language)}
749
813
 
750
814
  ${renderReposBlock(o.repos)}${o.mode === "migration" ? MIGRATION_SCAFFOLD(Object.keys(o.repos).length === 0) : ""}
751
815
  ui:
752
- mockups: ask # ask | ascii | browser
816
+ mockups: ask # ask | ascii | browser | artifact
753
817
 
754
818
  sources:
755
819
  # Mode-specific inputs
@@ -837,7 +901,199 @@ var init_manifest = __esm(() => {
837
901
  ];
838
902
  YAML_KEYWORDS = /^(true|false|null|yes|no|on|off|~)$/i;
839
903
  YAML_SPECIAL_FLOAT = /^[-+]?\.(inf|nan)$/i;
840
- UI_MODES = ["ask", "ascii", "browser"];
904
+ UI_MODES = ["ask", "ascii", "browser", "artifact"];
905
+ });
906
+
907
+ // src/workspace/experimental.ts
908
+ function stringList(value) {
909
+ if (!Array.isArray(value))
910
+ return;
911
+ return value.filter((v) => v !== null && v !== undefined).map((v) => String(v));
912
+ }
913
+ function readExperimental(m) {
914
+ const known = [];
915
+ const unknown = [];
916
+ for (const v of stringList(m.experimental) ?? []) {
917
+ if (EXPERIMENTAL_FEATURES.includes(v)) {
918
+ if (!known.includes(v))
919
+ known.push(v);
920
+ } else if (!unknown.includes(v)) {
921
+ unknown.push(v);
922
+ }
923
+ }
924
+ return { known, unknown };
925
+ }
926
+ function warnUnknownExperimental(m) {
927
+ for (const v of readExperimental(m).unknown) {
928
+ if (warned.has(v))
929
+ continue;
930
+ warned.add(v);
931
+ console.warn(` warning: unknown experimental feature "${v}" in manifest.yaml (known: ${EXPERIMENTAL_FEATURES.join(", ")}); ignored`);
932
+ }
933
+ }
934
+ function isExperimental(m, name) {
935
+ warnUnknownExperimental(m);
936
+ return readExperimental(m).known.includes(name);
937
+ }
938
+ function readHosts(m) {
939
+ return stringList(m.hosts);
940
+ }
941
+ function writeManifestList(text, key, values) {
942
+ return replaceTopLevelBlock(text, key, `${key}: [${values.join(", ")}]
943
+ `);
944
+ }
945
+ var EXPERIMENTAL_FEATURES, warned;
946
+ var init_experimental = __esm(() => {
947
+ init_manifest();
948
+ EXPERIMENTAL_FEATURES = ["multi-host", "multi-model"];
949
+ warned = new Set;
950
+ });
951
+
952
+ // src/workspace/resolve.ts
953
+ import { existsSync as existsSync2 } from "fs";
954
+ import { readdir, readFile, stat } from "fs/promises";
955
+ import { dirname, join as join3, resolve as resolve2 } from "path";
956
+ async function hasMarkedManifest(dir) {
957
+ const path = join3(dir, "manifest.yaml");
958
+ if (!existsSync2(path))
959
+ return false;
960
+ const text = await readFile(path, "utf-8").catch(() => null);
961
+ if (text === null)
962
+ return false;
963
+ try {
964
+ return hasMarker(parseManifest(text));
965
+ } catch (e) {
966
+ if (/^haren:/m.test(text)) {
967
+ throw new Error(`manifest.yaml in ${dir} is not valid YAML: ${e instanceof Error ? e.message : String(e)}. Fix the file or move it, then run again.`);
968
+ }
969
+ return false;
970
+ }
971
+ }
972
+ function isLegacyHarenDir(dir) {
973
+ return existsSync2(join3(dir, "manifest.yaml")) && existsSync2(join3(dir, "skill.md"));
974
+ }
975
+ function location(harenDir, legacy) {
976
+ return { harenDir, workspaceDir: dirname(harenDir), legacy };
977
+ }
978
+ function harenDirFlag(args) {
979
+ const i = args.indexOf("--haren-dir");
980
+ if (i === -1)
981
+ return;
982
+ const value = args[i + 1];
983
+ if (value === undefined || value === "" || value.startsWith("-")) {
984
+ throw new Error("--haren-dir needs a path");
985
+ }
986
+ return value;
987
+ }
988
+ async function resolveHarenDir(cwd, opts = {}) {
989
+ const explicit = opts.harenDir || opts.env?.HAREN_DIR;
990
+ if (explicit) {
991
+ const dir = resolve2(cwd, explicit);
992
+ if (!existsSync2(join3(dir, "manifest.yaml"))) {
993
+ throw new Error(`No manifest.yaml in ${dir}`);
994
+ }
995
+ return location(dir, !await hasMarkedManifest(dir));
996
+ }
997
+ if (await hasMarkedManifest(cwd))
998
+ return location(cwd, false);
999
+ const entries = await readdir(cwd, { withFileTypes: true }).catch(() => []);
1000
+ const matches = [];
1001
+ for (const entry of entries) {
1002
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
1003
+ continue;
1004
+ const dir = join3(cwd, entry.name);
1005
+ const isDir = entry.isSymbolicLink() ? await stat(dir).then((st) => st.isDirectory(), () => false) : entry.isDirectory();
1006
+ if (!isDir)
1007
+ continue;
1008
+ if (await hasMarkedManifest(dir))
1009
+ matches.push(dir);
1010
+ }
1011
+ matches.sort();
1012
+ if (matches.length > 1)
1013
+ throw new MultipleHarenDirsError(matches);
1014
+ if (matches.length === 1)
1015
+ return location(matches[0], false);
1016
+ const legacyChild = join3(cwd, "haren");
1017
+ if (isLegacyHarenDir(legacyChild))
1018
+ return location(legacyChild, true);
1019
+ if (isLegacyHarenDir(cwd))
1020
+ return location(cwd, true);
1021
+ return null;
1022
+ }
1023
+ var MultipleHarenDirsError;
1024
+ var init_resolve = __esm(() => {
1025
+ init_manifest();
1026
+ MultipleHarenDirsError = class MultipleHarenDirsError extends Error {
1027
+ matches;
1028
+ constructor(matches) {
1029
+ super(`Found more than one haren folder:
1030
+ ${matches.join(`
1031
+ `)}
1032
+ Pass --haren-dir <path> to choose one.`);
1033
+ this.matches = matches;
1034
+ this.name = "MultipleHarenDirsError";
1035
+ }
1036
+ };
1037
+ });
1038
+
1039
+ // src/commands/experimental.ts
1040
+ import { existsSync as existsSync3 } from "fs";
1041
+ import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
1042
+ import { join as join4 } from "path";
1043
+ function checkFeature(name) {
1044
+ if (!name || !EXPERIMENTAL_FEATURES.includes(name)) {
1045
+ throw new Error(`Unknown experimental feature '${name ?? ""}'. Known: ${EXPERIMENTAL_FEATURES.join(", ")}`);
1046
+ }
1047
+ return name;
1048
+ }
1049
+ async function experimental(args, cwd = process.cwd()) {
1050
+ const positional = args.filter((a, i) => !a.startsWith("--") && args[i - 1] !== "--haren-dir");
1051
+ const [sub, name] = positional;
1052
+ if (!sub) {
1053
+ console.log(USAGE);
1054
+ return;
1055
+ }
1056
+ if (sub !== "enable" && sub !== "disable" && sub !== "list") {
1057
+ throw new Error(`Unknown experimental command: ${sub}
1058
+ ${USAGE}`);
1059
+ }
1060
+ const location = await resolveHarenDir(cwd, { harenDir: harenDirFlag(args), env: process.env });
1061
+ if (!location)
1062
+ throw new Error("No haren folder found. Run `haren init` first.");
1063
+ const path = join4(location.harenDir, "manifest.yaml");
1064
+ if (!existsSync3(path))
1065
+ throw new Error(`No manifest.yaml in ${location.harenDir}`);
1066
+ const text = await readFile2(path, "utf-8");
1067
+ const m = parseManifest(text);
1068
+ warnUnknownExperimental(m);
1069
+ const { known } = readExperimental(m);
1070
+ if (sub === "list") {
1071
+ for (const f of EXPERIMENTAL_FEATURES) {
1072
+ console.log(` ${f.padEnd(12)} ${known.includes(f) ? "on" : "off"}`);
1073
+ }
1074
+ return;
1075
+ }
1076
+ const feature = checkFeature(name);
1077
+ if (sub === "enable") {
1078
+ if (known.includes(feature))
1079
+ return;
1080
+ await writeFile2(path, writeManifestList(text, "experimental", [...known, feature]));
1081
+ console.log(` Enabled experimental feature: ${feature}`);
1082
+ return;
1083
+ }
1084
+ if (!known.includes(feature))
1085
+ return;
1086
+ await writeFile2(path, writeManifestList(text, "experimental", known.filter((f) => f !== feature)));
1087
+ console.log(` Disabled experimental feature: ${feature}`);
1088
+ }
1089
+ var USAGE;
1090
+ var init_experimental2 = __esm(() => {
1091
+ init_experimental();
1092
+ init_manifest();
1093
+ init_resolve();
1094
+ USAGE = `Usage: haren experimental enable <name> | disable <name> | list
1095
+ Known features: ${EXPERIMENTAL_FEATURES.join(", ")}
1096
+ Options: --haren-dir <path>`;
841
1097
  });
842
1098
 
843
1099
  // src/plugins/paths.ts
@@ -909,10 +1165,10 @@ var init_adapter_spec = __esm(() => {
909
1165
  });
910
1166
 
911
1167
  // src/plugins/manifest.ts
912
- import { existsSync as existsSync2 } from "fs";
913
- import { readFile } from "fs/promises";
914
- import { join as join3 } from "path";
915
- function stringList(value, field) {
1168
+ import { existsSync as existsSync4 } from "fs";
1169
+ import { readFile as readFile3 } from "fs/promises";
1170
+ import { join as join5 } from "path";
1171
+ function stringList2(value, field) {
916
1172
  if (value === undefined)
917
1173
  return [];
918
1174
  if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
@@ -921,7 +1177,7 @@ function stringList(value, field) {
921
1177
  return value;
922
1178
  }
923
1179
  function relativePathList(value, field) {
924
- const list = stringList(value, field);
1180
+ const list = stringList2(value, field);
925
1181
  for (const p of list)
926
1182
  assertInsidePlugin(p, field);
927
1183
  return list;
@@ -992,7 +1248,7 @@ function validateManifest(raw, packageVersion) {
992
1248
  harenApi: m.harenApi,
993
1249
  description: typeof m.description === "string" ? m.description : undefined,
994
1250
  requires,
995
- setup: stringList(m.setup, "setup"),
1251
+ setup: stringList2(m.setup, "setup"),
996
1252
  hooks,
997
1253
  config,
998
1254
  skills: relativePathList(m.skills, "skills"),
@@ -1001,13 +1257,13 @@ function validateManifest(raw, packageVersion) {
1001
1257
  };
1002
1258
  }
1003
1259
  async function readInstalledManifest(dir) {
1004
- const raw = JSON.parse(await readFile(join3(dir, "haren-plugin.json"), "utf-8"));
1260
+ const raw = JSON.parse(await readFile3(join5(dir, "haren-plugin.json"), "utf-8"));
1005
1261
  let packageVersion;
1006
1262
  const hasVersion = raw && typeof raw === "object" && raw.version !== undefined;
1007
- const pkgPath = join3(dir, "package.json");
1008
- if (!hasVersion && existsSync2(pkgPath)) {
1263
+ const pkgPath = join5(dir, "package.json");
1264
+ if (!hasVersion && existsSync4(pkgPath)) {
1009
1265
  try {
1010
- const v = JSON.parse(await readFile(pkgPath, "utf-8"))?.version;
1266
+ const v = JSON.parse(await readFile3(pkgPath, "utf-8"))?.version;
1011
1267
  if (typeof v === "string")
1012
1268
  packageVersion = v;
1013
1269
  } catch {}
@@ -1024,25 +1280,25 @@ var init_manifest2 = __esm(() => {
1024
1280
  });
1025
1281
 
1026
1282
  // src/plugins/state.ts
1027
- import { existsSync as existsSync3 } from "fs";
1028
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
1029
- import { join as join4 } from "path";
1283
+ import { existsSync as existsSync5 } from "fs";
1284
+ import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
1285
+ import { join as join6 } from "path";
1030
1286
  function pluginsPath(harenDir) {
1031
- return join4(harenDir, "plugins.json");
1287
+ return join6(harenDir, "plugins.json");
1032
1288
  }
1033
1289
  function pluginDir(harenDir, name) {
1034
- return join4(harenDir, ".plugins", name);
1290
+ return join6(harenDir, ".plugins", name);
1035
1291
  }
1036
1292
  function pluginDataDir(harenDir, name) {
1037
- return join4(harenDir, ".plugin-data", name);
1293
+ return join6(harenDir, ".plugin-data", name);
1038
1294
  }
1039
1295
  async function readPlugins(harenDir) {
1040
1296
  const path = pluginsPath(harenDir);
1041
- if (!existsSync3(path))
1297
+ if (!existsSync5(path))
1042
1298
  return { version: 1, plugins: {} };
1043
1299
  let data;
1044
1300
  try {
1045
- data = JSON.parse(await readFile2(path, "utf-8"));
1301
+ data = JSON.parse(await readFile4(path, "utf-8"));
1046
1302
  } catch (e) {
1047
1303
  throw new Error(`plugins.json is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
1048
1304
  }
@@ -1050,15 +1306,359 @@ async function readPlugins(harenDir) {
1050
1306
  }
1051
1307
  async function writePlugins(harenDir, data) {
1052
1308
  await mkdir2(harenDir, { recursive: true });
1053
- await writeFile2(pluginsPath(harenDir), `${JSON.stringify(data, null, 2)}
1309
+ await writeFile3(pluginsPath(harenDir), `${JSON.stringify(data, null, 2)}
1054
1310
  `);
1055
1311
  }
1056
1312
  var init_state = () => {};
1057
1313
 
1314
+ // src/hosts/shared.ts
1315
+ function instructionBlock(file, ctx) {
1316
+ const config = renderTemplate(editorConfigTemplate, ctx.harenName);
1317
+ return { path: file, make: (old) => upsertBlock(old, config, file), markdown: true };
1318
+ }
1319
+ function frameworkCopies(dir, ctx) {
1320
+ return ctx.framework.map((f) => ({
1321
+ path: `${dir}/${f.path}`,
1322
+ make: () => f.content,
1323
+ group: `${dir}/${f.group}/`
1324
+ }));
1325
+ }
1326
+ function skillFiles(dir, ctx) {
1327
+ return frameworkCopies(dir, {
1328
+ ...ctx,
1329
+ framework: ctx.framework.filter((f) => f.group === "skills" && CORE_SKILLS.has(f.path.split("/")[1] ?? ""))
1330
+ });
1331
+ }
1332
+ function agentFiles(dir, ctx, convert = (c) => c, ext = "md") {
1333
+ return ctx.framework.filter((f) => f.group === "agents").map((f) => {
1334
+ const name = f.path.replace(/^agents\//, "").replace(/\.md$/, "");
1335
+ return {
1336
+ path: `${dir}/${name}.${ext}`,
1337
+ make: () => convert(f.content, name),
1338
+ group: `${dir}/`
1339
+ };
1340
+ });
1341
+ }
1342
+ function claudeStyleHook(path, matcher, command) {
1343
+ return { path, make: (old) => mergeClaudeStyleHook(old, path, matcher, command) };
1344
+ }
1345
+ function splitFrontmatter(text) {
1346
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
1347
+ if (!fm)
1348
+ return { data: {}, body: text };
1349
+ let data;
1350
+ try {
1351
+ data = Bun.YAML.parse(fm[1] ?? "");
1352
+ } catch {
1353
+ data = {};
1354
+ }
1355
+ return {
1356
+ data: data && typeof data === "object" ? data : {},
1357
+ body: text.slice(fm[0].length)
1358
+ };
1359
+ }
1360
+ function tomlString(value) {
1361
+ return JSON.stringify(value);
1362
+ }
1363
+ function tomlMultiline(value) {
1364
+ return `"""
1365
+ ${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"""`;
1366
+ }
1367
+ function agentToToml(content, name) {
1368
+ const { data, body } = splitFrontmatter(content);
1369
+ const lines = [`name = ${tomlString(name)}`];
1370
+ const description = typeof data.description === "string" ? data.description : name;
1371
+ lines.push(`description = ${tomlString(description)}`);
1372
+ if (typeof data.model === "string" && data.model)
1373
+ lines.push(`model = ${tomlString(data.model)}`);
1374
+ lines.push(`developer_instructions = ${tomlMultiline(body)}`);
1375
+ return `${lines.join(`
1376
+ `)}
1377
+ `;
1378
+ }
1379
+ function withFrontmatter(content, pick, name) {
1380
+ const { data, body } = splitFrontmatter(content);
1381
+ const fields = Object.entries(pick(data, name)).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join(`
1382
+ `);
1383
+ return `---
1384
+ ${fields}
1385
+ ---
1386
+ ${body}`;
1387
+ }
1388
+ var CORE_SKILLS, GATE_NOTE_NO_HOOK = "no workspace hook API; the brainstorming gate works only through the instructions in AGENTS.md.";
1389
+ var init_shared = __esm(() => {
1390
+ init_root_files();
1391
+ init_templates();
1392
+ CORE_SKILLS = new Set([
1393
+ "haren-ideate",
1394
+ "haren-discover",
1395
+ "haren-decompose",
1396
+ "haren-plan",
1397
+ "haren-implement",
1398
+ "haren-evaluate",
1399
+ "haren-extract",
1400
+ "haren-release",
1401
+ "haren-read-context",
1402
+ "haren-update-tracking",
1403
+ "haren-onboard"
1404
+ ]);
1405
+ });
1406
+
1407
+ // src/hosts/agents-md.ts
1408
+ import { existsSync as existsSync6 } from "fs";
1409
+ import { join as join7 } from "path";
1410
+ var GATE_NOTE_INSTRUCTIONS = "no hook API; the brainstorming gate works only through the instructions in AGENTS.md.", agentsMd;
1411
+ var init_agents_md = __esm(() => {
1412
+ init_shared();
1413
+ agentsMd = {
1414
+ id: "agents-md",
1415
+ label: "Any agent that reads AGENTS.md",
1416
+ experimental: true,
1417
+ level: 1,
1418
+ roots: ["AGENTS.md"],
1419
+ files: (ctx) => [instructionBlock("AGENTS.md", ctx)],
1420
+ detect: (ws) => existsSync6(join7(ws, "AGENTS.md")),
1421
+ gateNote: GATE_NOTE_INSTRUCTIONS
1422
+ };
1423
+ });
1424
+
1425
+ // src/hosts/claude-code.ts
1426
+ import { existsSync as existsSync7 } from "fs";
1427
+ import { join as join8 } from "path";
1428
+ var claudeCode;
1429
+ var init_claude_code = __esm(() => {
1430
+ init_root_files();
1431
+ init_templates();
1432
+ init_shared();
1433
+ claudeCode = {
1434
+ id: "claude-code",
1435
+ label: "Claude Code CLI / IDE extension",
1436
+ experimental: false,
1437
+ level: 3,
1438
+ roots: ["CLAUDE.md", ".claude/"],
1439
+ files(ctx) {
1440
+ const command = gateCommand(ctx.harenName);
1441
+ return [
1442
+ instructionBlock("CLAUDE.md", ctx),
1443
+ { path: ".claude/settings.json", make: (old) => mergeClaudeSettings(old, command) },
1444
+ ...frameworkCopies(".claude", ctx)
1445
+ ];
1446
+ },
1447
+ exec: ({ prompt: prompt2, model }) => ["claude", "-p", prompt2, ...model ? ["--model", model] : []],
1448
+ detect: (ws) => existsSync7(join8(ws, "CLAUDE.md")) || existsSync7(join8(ws, ".claude", "settings.json"))
1449
+ };
1450
+ });
1451
+
1452
+ // src/hosts/codex.ts
1453
+ import { existsSync as existsSync8 } from "fs";
1454
+ import { join as join9 } from "path";
1455
+ var codex;
1456
+ var init_codex = __esm(() => {
1457
+ init_templates();
1458
+ init_shared();
1459
+ codex = {
1460
+ id: "codex",
1461
+ label: "OpenAI Codex CLI",
1462
+ experimental: true,
1463
+ level: 3,
1464
+ roots: ["AGENTS.md", ".agents/", ".codex/"],
1465
+ files: (ctx) => [
1466
+ instructionBlock("AGENTS.md", ctx),
1467
+ ...skillFiles(".agents", ctx),
1468
+ ...agentFiles(".codex/agents", ctx, agentToToml, "toml"),
1469
+ claudeStyleHook(".codex/hooks.json", "Bash|apply_patch", gateCommand(ctx.harenName, "codex"))
1470
+ ],
1471
+ gateNote: "Codex runs a new project hook only after you review it. Run codex here once, open /hooks and trust the haren gate. Until then the gate works only through the instructions.",
1472
+ detect: (ws) => existsSync8(join9(ws, ".codex")),
1473
+ exec: ({ prompt: prompt2, cwd, model }) => [
1474
+ "codex",
1475
+ "exec",
1476
+ ...model ? ["-m", model] : [],
1477
+ "-C",
1478
+ cwd,
1479
+ "-s",
1480
+ "workspace-write",
1481
+ prompt2
1482
+ ]
1483
+ };
1484
+ });
1485
+
1486
+ // src/hosts/cursor.ts
1487
+ import { existsSync as existsSync9 } from "fs";
1488
+ import { join as join10 } from "path";
1489
+ var cursor;
1490
+ var init_cursor = __esm(() => {
1491
+ init_root_files();
1492
+ init_templates();
1493
+ init_shared();
1494
+ cursor = {
1495
+ id: "cursor",
1496
+ label: "Cursor AI editor",
1497
+ experimental: false,
1498
+ level: 3,
1499
+ roots: [".cursorrules", ".cursor/"],
1500
+ files(ctx) {
1501
+ const command = gateCommand(ctx.harenName);
1502
+ return [
1503
+ instructionBlock(".cursorrules", ctx),
1504
+ {
1505
+ path: ".cursor/rules/haren.mdc",
1506
+ make: () => renderTemplate(cursorRuleTemplate, ctx.harenName)
1507
+ },
1508
+ { path: ".cursor/hooks.json", make: (old) => mergeCursorHooks(old, command) },
1509
+ ...frameworkCopies(".cursor", ctx)
1510
+ ];
1511
+ },
1512
+ exec: ({ prompt: prompt2, model }) => [
1513
+ "agent",
1514
+ "--print",
1515
+ "--trust",
1516
+ ...model ? ["--model", model] : [],
1517
+ prompt2
1518
+ ],
1519
+ detect: (ws) => existsSync9(join10(ws, ".cursorrules")) || existsSync9(join10(ws, ".cursor"))
1520
+ };
1521
+ });
1522
+
1523
+ // src/hosts/kimi-code.ts
1524
+ import { existsSync as existsSync10 } from "fs";
1525
+ import { join as join11 } from "path";
1526
+ var kimiCode;
1527
+ var init_kimi_code = __esm(() => {
1528
+ init_shared();
1529
+ kimiCode = {
1530
+ id: "kimi-code",
1531
+ label: "Kimi Code CLI",
1532
+ experimental: true,
1533
+ level: 2,
1534
+ roots: ["AGENTS.md", ".agents/"],
1535
+ files: (ctx) => [
1536
+ instructionBlock("AGENTS.md", ctx),
1537
+ ...skillFiles(".agents", ctx),
1538
+ ...agentFiles(".agents/agents", ctx)
1539
+ ],
1540
+ detect: (ws) => existsSync10(join11(ws, ".agents", "agents")),
1541
+ exec: ({ prompt: prompt2, model }) => ["kimi", "-p", prompt2, ...model ? ["-m", model] : []],
1542
+ gateNote: GATE_NOTE_NO_HOOK
1543
+ };
1544
+ });
1545
+
1546
+ // src/hosts/opencode.ts
1547
+ import { existsSync as existsSync11 } from "fs";
1548
+ import { join as join12 } from "path";
1549
+ function toOpencodeAgent(content, name) {
1550
+ return withFrontmatter(content, (data) => ({
1551
+ description: typeof data.description === "string" ? data.description : name,
1552
+ mode: "subagent"
1553
+ }), name);
1554
+ }
1555
+ var opencode;
1556
+ var init_opencode = __esm(() => {
1557
+ init_shared();
1558
+ opencode = {
1559
+ id: "opencode",
1560
+ label: "OpenCode",
1561
+ experimental: true,
1562
+ level: 2,
1563
+ roots: ["AGENTS.md", ".agents/", ".opencode/"],
1564
+ files: (ctx) => [
1565
+ instructionBlock("AGENTS.md", ctx),
1566
+ ...skillFiles(".agents", ctx),
1567
+ ...agentFiles(".opencode/agents", ctx, toOpencodeAgent)
1568
+ ],
1569
+ detect: (ws) => existsSync11(join12(ws, ".opencode")),
1570
+ exec: ({ prompt: prompt2, model }) => ["opencode", "run", ...model ? ["--model", model] : [], prompt2],
1571
+ gateNote: GATE_NOTE_NO_HOOK
1572
+ };
1573
+ });
1574
+
1575
+ // src/hosts/qwen-code.ts
1576
+ import { existsSync as existsSync12 } from "fs";
1577
+ import { join as join13 } from "path";
1578
+ var qwenCode;
1579
+ var init_qwen_code = __esm(() => {
1580
+ init_templates();
1581
+ init_shared();
1582
+ qwenCode = {
1583
+ id: "qwen-code",
1584
+ label: "Qwen Code CLI",
1585
+ experimental: true,
1586
+ level: 3,
1587
+ roots: ["AGENTS.md", ".agents/", ".qwen/"],
1588
+ files: (ctx) => [
1589
+ instructionBlock("AGENTS.md", ctx),
1590
+ ...skillFiles(".agents", ctx),
1591
+ ...agentFiles(".qwen/agents", ctx),
1592
+ claudeStyleHook(".qwen/settings.json", "run_shell_command|edit|write_file", gateCommand(ctx.harenName, "qwen-code"))
1593
+ ],
1594
+ gateNote: "Qwen Code loads project hooks only in a trusted folder. Set security.folderTrust.enabled in ~/.qwen/settings.json and trust this folder, or run qwen here once and approve the hook. Until then the gate works only through the instructions.",
1595
+ detect: (ws) => existsSync12(join13(ws, ".qwen")),
1596
+ exec: ({ prompt: prompt2, model }) => [
1597
+ "qwen",
1598
+ "-p",
1599
+ prompt2,
1600
+ ...model ? ["-m", model] : [],
1601
+ "--approval-mode",
1602
+ "auto-edit"
1603
+ ]
1604
+ };
1605
+ });
1606
+
1607
+ // src/hosts/registry.ts
1608
+ function getHost(id) {
1609
+ return HOSTS.find((h) => h.id === id);
1610
+ }
1611
+ function listHosts() {
1612
+ return [...HOSTS];
1613
+ }
1614
+ function resolveHosts(ids, multiHost, hosts = HOSTS) {
1615
+ const known = hosts.map((h) => h.id).join(", ");
1616
+ const unique = [...new Set(ids.map((i) => i.trim()).filter(Boolean))];
1617
+ if (unique.length === 0)
1618
+ throw new Error(`No hosts given. Known: ${known}`);
1619
+ for (const id of unique) {
1620
+ const host = hosts.find((h) => h.id === id);
1621
+ if (!host)
1622
+ throw new Error(`Unknown host: ${id}. Known: ${known}`);
1623
+ if (host.experimental && !multiHost) {
1624
+ throw new Error(`Host '${id}' is experimental. Enable it first: haren experimental enable multi-host (or haren init --experimental multi-host)`);
1625
+ }
1626
+ }
1627
+ return unique;
1628
+ }
1629
+ function cliName(host) {
1630
+ return host.id === "claude-code" ? "claude" : host.id;
1631
+ }
1632
+ function hostForCli(cli) {
1633
+ return getHost(cli === "claude" ? "claude-code" : cli);
1634
+ }
1635
+ var HOSTS;
1636
+ var init_registry = __esm(() => {
1637
+ init_agents_md();
1638
+ init_claude_code();
1639
+ init_codex();
1640
+ init_cursor();
1641
+ init_kimi_code();
1642
+ init_opencode();
1643
+ init_qwen_code();
1644
+ HOSTS = [
1645
+ claudeCode,
1646
+ cursor,
1647
+ agentsMd,
1648
+ codex,
1649
+ qwenCode,
1650
+ opencode,
1651
+ kimiCode
1652
+ ];
1653
+ });
1654
+
1058
1655
  // src/workspace/root-files.ts
1059
- import { existsSync as existsSync4 } from "fs";
1060
- import { mkdir as mkdir3, readdir, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
1061
- import { basename as basename2, dirname, join as join5, relative, resolve as resolve2, sep } from "path";
1656
+ import { existsSync as existsSync13 } from "fs";
1657
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
1658
+ import { basename as basename2, dirname as dirname2, join as join14, relative, resolve as resolve3, sep } from "path";
1659
+ function editorHosts(editor) {
1660
+ return editor === "both" ? ["claude-code", "cursor"] : [editor];
1661
+ }
1062
1662
  function legacyRange(existing) {
1063
1663
  const start = existing.indexOf(LEGACY_HEADING);
1064
1664
  if (start === -1 || !existing.includes("haren/skill.md"))
@@ -1131,16 +1731,19 @@ function parseJson(existing, path) {
1131
1731
  function withoutGate(entries) {
1132
1732
  return (Array.isArray(entries) ? entries : []).filter((entry) => !JSON.stringify(entry).includes(GATE_SCRIPT));
1133
1733
  }
1134
- function mergeClaudeSettings(existing, command) {
1135
- const data = parseJson(existing, ".claude/settings.json");
1734
+ function mergeClaudeStyleHook(existing, path, matcher, command) {
1735
+ const data = parseJson(existing, path);
1136
1736
  data.hooks ??= {};
1137
1737
  data.hooks.PreToolUse = [
1138
1738
  ...withoutGate(data.hooks.PreToolUse),
1139
- { matcher: "Edit|Write|Bash", hooks: [{ type: "command", command }] }
1739
+ { matcher, hooks: [{ type: "command", command }] }
1140
1740
  ];
1141
1741
  return `${JSON.stringify(data, null, 2)}
1142
1742
  `;
1143
1743
  }
1744
+ function mergeClaudeSettings(existing, command) {
1745
+ return mergeClaudeStyleHook(existing, ".claude/settings.json", "Edit|Write|Bash", command);
1746
+ }
1144
1747
  function mergeCursorHooks(existing, command) {
1145
1748
  const data = parseJson(existing, ".cursor/hooks.json");
1146
1749
  data.version ??= 1;
@@ -1161,7 +1764,7 @@ function mergeCursorHooks(existing, command) {
1161
1764
  `;
1162
1765
  }
1163
1766
  async function readOrNull(path) {
1164
- return existsSync4(path) ? readFile3(path, "utf-8") : null;
1767
+ return existsSync13(path) ? readFile5(path, "utf-8") : null;
1165
1768
  }
1166
1769
  function harenName(name) {
1167
1770
  return name.startsWith("haren-") ? name : `haren-${name}`;
@@ -1179,10 +1782,10 @@ function frontmatterName(text) {
1179
1782
  }
1180
1783
  async function listFiles(dir, prefix = "") {
1181
1784
  const out = [];
1182
- for (const entry of await readdir(dir, { withFileTypes: true })) {
1785
+ for (const entry of await readdir2(dir, { withFileTypes: true })) {
1183
1786
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
1184
1787
  if (entry.isDirectory())
1185
- out.push(...await listFiles(join5(dir, entry.name), rel));
1788
+ out.push(...await listFiles(join14(dir, entry.name), rel));
1186
1789
  else if (entry.isFile())
1187
1790
  out.push(rel);
1188
1791
  }
@@ -1190,7 +1793,7 @@ async function listFiles(dir, prefix = "") {
1190
1793
  }
1191
1794
  async function frameworkFiles(harenDir, contentDir) {
1192
1795
  let source = harenDir;
1193
- if (!existsSync4(join5(harenDir, "skills")) && !existsSync4(join5(harenDir, "agents"))) {
1796
+ if (!existsSync13(join14(harenDir, "skills")) && !existsSync13(join14(harenDir, "agents"))) {
1194
1797
  try {
1195
1798
  source = contentDir ?? resolveContentDir();
1196
1799
  } catch {
@@ -1198,18 +1801,18 @@ async function frameworkFiles(harenDir, contentDir) {
1198
1801
  }
1199
1802
  }
1200
1803
  const files = [];
1201
- const skillsDir = join5(source, "skills");
1202
- if (existsSync4(skillsDir)) {
1203
- for (const entry of await readdir(skillsDir, { withFileTypes: true })) {
1804
+ const skillsDir = join14(source, "skills");
1805
+ if (existsSync13(skillsDir)) {
1806
+ for (const entry of await readdir2(skillsDir, { withFileTypes: true })) {
1204
1807
  if (!entry.isDirectory())
1205
1808
  continue;
1206
- const dir = join5(skillsDir, entry.name);
1207
- const main = await readOrNull(join5(dir, "SKILL.md"));
1809
+ const dir = join14(skillsDir, entry.name);
1810
+ const main = await readOrNull(join14(dir, "SKILL.md"));
1208
1811
  if (main === null)
1209
1812
  continue;
1210
1813
  const name = harenName(frontmatterName(main) ?? entry.name);
1211
1814
  for (const rel of await listFiles(dir)) {
1212
- const text = await readFile3(join5(dir, rel), "utf-8");
1815
+ const text = await readFile5(join14(dir, rel), "utf-8");
1213
1816
  files.push({
1214
1817
  path: `skills/${name}/${rel}`,
1215
1818
  content: rel === "SKILL.md" ? withFrontmatterName(text, name) : text,
@@ -1218,10 +1821,10 @@ async function frameworkFiles(harenDir, contentDir) {
1218
1821
  }
1219
1822
  }
1220
1823
  }
1221
- const agentsDir = join5(source, "agents");
1222
- if (existsSync4(agentsDir)) {
1223
- for (const file of (await readdir(agentsDir)).filter((f) => f.endsWith(".md")).sort()) {
1224
- const text = await readFile3(join5(agentsDir, file), "utf-8");
1824
+ const agentsDir = join14(source, "agents");
1825
+ if (existsSync13(agentsDir)) {
1826
+ for (const file of (await readdir2(agentsDir)).filter((f) => f.endsWith(".md")).sort()) {
1827
+ const text = await readFile5(join14(agentsDir, file), "utf-8");
1225
1828
  const name = harenName(frontmatterName(text) ?? file.slice(0, -3));
1226
1829
  files.push({
1227
1830
  path: `agents/${name}.md`,
@@ -1249,15 +1852,15 @@ async function pluginFiles(harenDir, only) {
1249
1852
  const prefixed = (n) => n.startsWith(`${plugin}-`) ? n : `${plugin}-${n}`;
1250
1853
  const safeName = (n) => /^[A-Za-z0-9._-]+$/.test(n) && !n.includes("..");
1251
1854
  for (const skill of manifest.skills) {
1252
- const skillDir = join5(dir, skill);
1253
- const main = await readOrNull(join5(skillDir, "SKILL.md"));
1855
+ const skillDir = join14(dir, skill);
1856
+ const main = await readOrNull(join14(skillDir, "SKILL.md"));
1254
1857
  if (main === null)
1255
1858
  continue;
1256
1859
  const name = prefixed(frontmatterName(main) ?? basename2(skillDir));
1257
1860
  if (!safeName(name))
1258
1861
  continue;
1259
1862
  for (const rel of await listFiles(skillDir)) {
1260
- const text = await readFile3(join5(skillDir, rel), "utf-8");
1863
+ const text = await readFile5(join14(skillDir, rel), "utf-8");
1261
1864
  files.push({
1262
1865
  path: `skills/${name}/${rel}`,
1263
1866
  content: rel === "SKILL.md" ? withFrontmatterName(text, name) : text,
@@ -1266,7 +1869,7 @@ async function pluginFiles(harenDir, only) {
1266
1869
  }
1267
1870
  }
1268
1871
  for (const agent of manifest.agents) {
1269
- const text = await readOrNull(join5(dir, agent));
1872
+ const text = await readOrNull(join14(dir, agent));
1270
1873
  if (text === null)
1271
1874
  continue;
1272
1875
  const name = prefixed(frontmatterName(text) ?? basename2(agent, ".md"));
@@ -1281,48 +1884,32 @@ async function pluginFiles(harenDir, only) {
1281
1884
  }
1282
1885
  return files.sort((x, y) => x.path.localeCompare(y.path));
1283
1886
  }
1887
+ function optionHosts(o) {
1888
+ return o.hosts ?? editorHosts(o.editor ?? "claude-code");
1889
+ }
1284
1890
  async function computeRootFiles(o) {
1285
- const name = relative(o.workspaceDir, o.harenDir).split(sep).join("/");
1286
- const useClaude = o.editor !== "cursor";
1287
- const useCursor = o.editor !== "claude-code";
1288
- const command = gateCommand(name);
1289
- const config = renderTemplate(editorConfigTemplate, name);
1290
- const framework = await frameworkFiles(o.harenDir, o.contentDir);
1891
+ const ctx = {
1892
+ workspaceDir: o.workspaceDir,
1893
+ harenDir: o.harenDir,
1894
+ harenName: relative(o.workspaceDir, o.harenDir).split(sep).join("/"),
1895
+ framework: await frameworkFiles(o.harenDir, o.contentDir)
1896
+ };
1291
1897
  const specs = [];
1292
- const addFramework = (editorDir) => {
1293
- for (const f of framework) {
1294
- specs.push({
1295
- path: `${editorDir}/${f.path}`,
1296
- make: () => f.content,
1297
- group: `${editorDir}/${f.group}/`
1298
- });
1898
+ const seen = new Set;
1899
+ for (const id of optionHosts(o)) {
1900
+ const host = getHost(id);
1901
+ if (!host)
1902
+ throw new Error(`Unknown host: ${id}`);
1903
+ for (const spec of host.files(ctx)) {
1904
+ if (seen.has(spec.path))
1905
+ continue;
1906
+ seen.add(spec.path);
1907
+ specs.push(spec);
1299
1908
  }
1300
- };
1301
- if (useClaude) {
1302
- specs.push({
1303
- path: "CLAUDE.md",
1304
- make: (old) => upsertBlock(old, config, "CLAUDE.md"),
1305
- markdown: true
1306
- });
1307
- specs.push({ path: ".claude/settings.json", make: (old) => mergeClaudeSettings(old, command) });
1308
- addFramework(".claude");
1309
- }
1310
- if (useCursor) {
1311
- specs.push({
1312
- path: ".cursorrules",
1313
- make: (old) => upsertBlock(old, config, ".cursorrules"),
1314
- markdown: true
1315
- });
1316
- specs.push({
1317
- path: ".cursor/rules/haren.mdc",
1318
- make: () => renderTemplate(cursorRuleTemplate, name)
1319
- });
1320
- specs.push({ path: ".cursor/hooks.json", make: (old) => mergeCursorHooks(old, command) });
1321
- addFramework(".cursor");
1322
1909
  }
1323
1910
  const files = [];
1324
1911
  for (const spec of specs) {
1325
- const old = await readOrNull(join5(o.workspaceDir, spec.path));
1912
+ const old = await readOrNull(join14(o.workspaceDir, spec.path));
1326
1913
  const content = spec.make(old);
1327
1914
  files.push({
1328
1915
  path: spec.path,
@@ -1357,11 +1944,9 @@ function summarizeRootFiles(files) {
1357
1944
  return out;
1358
1945
  }
1359
1946
  function isSafeRootPath(workspaceDir, path) {
1360
- const abs = resolve2(workspaceDir, path);
1361
- const root = resolve2(workspaceDir);
1362
- if (abs === join5(root, "CLAUDE.md") || abs === join5(root, ".cursorrules"))
1363
- return true;
1364
- return [".claude", ".cursor"].some((d) => abs.startsWith(join5(root, d) + sep));
1947
+ const abs = resolve3(workspaceDir, path);
1948
+ const root = resolve3(workspaceDir);
1949
+ return listHosts().flatMap((h) => h.roots).some((r) => r.endsWith("/") ? abs.startsWith(join14(root, r.slice(0, -1)) + sep) : abs === join14(root, r));
1365
1950
  }
1366
1951
  async function writeRootFiles(o) {
1367
1952
  const files = await computeRootFiles(o);
@@ -1372,15 +1957,15 @@ async function writeRootFiles(o) {
1372
1957
  console.warn(` skipped unsafe path: ${file.path}`);
1373
1958
  continue;
1374
1959
  }
1375
- const abs = join5(o.workspaceDir, file.path);
1376
- await mkdir3(dirname(abs), { recursive: true });
1377
- await writeFile3(abs, file.content);
1960
+ const abs = join14(o.workspaceDir, file.path);
1961
+ await mkdir3(dirname2(abs), { recursive: true });
1962
+ await writeFile4(abs, file.content);
1378
1963
  }
1379
1964
  return files;
1380
1965
  }
1381
1966
  function detectEditor(workspaceDir) {
1382
- const claude = existsSync4(join5(workspaceDir, "CLAUDE.md")) || existsSync4(join5(workspaceDir, ".claude", "settings.json"));
1383
- const cursor = existsSync4(join5(workspaceDir, ".cursorrules")) || existsSync4(join5(workspaceDir, ".cursor"));
1967
+ const claude = existsSync13(join14(workspaceDir, "CLAUDE.md")) || existsSync13(join14(workspaceDir, ".claude", "settings.json"));
1968
+ const cursor = existsSync13(join14(workspaceDir, ".cursorrules")) || existsSync13(join14(workspaceDir, ".cursor"));
1384
1969
  if (claude && cursor)
1385
1970
  return "both";
1386
1971
  if (claude)
@@ -1394,14 +1979,14 @@ var init_root_files = __esm(() => {
1394
1979
  init_content_dir();
1395
1980
  init_manifest2();
1396
1981
  init_state();
1397
- init_templates();
1982
+ init_registry();
1398
1983
  LEGACY_HEADINGS = new Set([LEGACY_HEADING, "## Brainstorming Gate"]);
1399
1984
  });
1400
1985
 
1401
1986
  // src/workspace/git.ts
1402
- import { existsSync as existsSync5 } from "fs";
1403
- import { mkdir as mkdir4, readdir as readdir2 } from "fs/promises";
1404
- import { dirname as dirname2, join as join6, resolve as resolve3 } from "path";
1987
+ import { existsSync as existsSync14 } from "fs";
1988
+ import { mkdir as mkdir4, readdir as readdir3 } from "fs/promises";
1989
+ import { dirname as dirname3, join as join15, resolve as resolve4 } from "path";
1405
1990
  function gitEnv(interactive = process.stdin.isTTY === true, base = process.env) {
1406
1991
  if (interactive)
1407
1992
  return { ...base };
@@ -1430,7 +2015,7 @@ async function runGit(args, cwd) {
1430
2015
  }
1431
2016
  }
1432
2017
  function hasGitDir(dir) {
1433
- return existsSync5(join6(dir, ".git"));
2018
+ return existsSync14(join15(dir, ".git"));
1434
2019
  }
1435
2020
  async function isInsideWorkTree(dir) {
1436
2021
  const result = await runGit(["rev-parse", "--is-inside-work-tree"], dir);
@@ -1441,24 +2026,24 @@ async function getRemoteUrl(dir) {
1441
2026
  return result.ok && result.stdout ? result.stdout : null;
1442
2027
  }
1443
2028
  async function cloneRepo(remote, dest) {
1444
- const abs = resolve3(dest);
2029
+ const abs = resolve4(dest);
1445
2030
  try {
1446
- await mkdir4(dirname2(abs), { recursive: true });
2031
+ await mkdir4(dirname3(abs), { recursive: true });
1447
2032
  } catch (err) {
1448
2033
  return { ok: false, stdout: "", stderr: String(err) };
1449
2034
  }
1450
- return runGit(["clone", remote, abs], dirname2(abs));
2035
+ return runGit(["clone", remote, abs], dirname3(abs));
1451
2036
  }
1452
2037
  async function gitInit(dir) {
1453
2038
  return runGit(["init"], dir);
1454
2039
  }
1455
2040
  async function listChildRepos(dir) {
1456
- const entries = await readdir2(dir, { withFileTypes: true }).catch(() => []);
2041
+ const entries = await readdir3(dir, { withFileTypes: true }).catch(() => []);
1457
2042
  const repos = [];
1458
2043
  for (const entry of entries) {
1459
2044
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
1460
2045
  continue;
1461
- const path = join6(dir, entry.name);
2046
+ const path = join15(dir, entry.name);
1462
2047
  if (!hasGitDir(path))
1463
2048
  continue;
1464
2049
  repos.push({ name: entry.name, path, remote: await getRemoteUrl(path) });
@@ -1467,95 +2052,8 @@ async function listChildRepos(dir) {
1467
2052
  }
1468
2053
  var init_git = () => {};
1469
2054
 
1470
- // src/workspace/resolve.ts
1471
- import { existsSync as existsSync6 } from "fs";
1472
- import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
1473
- import { dirname as dirname3, join as join7, resolve as resolve4 } from "path";
1474
- async function hasMarkedManifest(dir) {
1475
- const path = join7(dir, "manifest.yaml");
1476
- if (!existsSync6(path))
1477
- return false;
1478
- const text = await readFile4(path, "utf-8").catch(() => null);
1479
- if (text === null)
1480
- return false;
1481
- try {
1482
- return hasMarker(parseManifest(text));
1483
- } catch (e) {
1484
- if (/^haren:/m.test(text)) {
1485
- throw new Error(`manifest.yaml in ${dir} is not valid YAML: ${e instanceof Error ? e.message : String(e)}. Fix the file or move it, then run again.`);
1486
- }
1487
- return false;
1488
- }
1489
- }
1490
- function isLegacyHarenDir(dir) {
1491
- return existsSync6(join7(dir, "manifest.yaml")) && existsSync6(join7(dir, "skill.md"));
1492
- }
1493
- function location(harenDir, legacy) {
1494
- return { harenDir, workspaceDir: dirname3(harenDir), legacy };
1495
- }
1496
- function harenDirFlag(args) {
1497
- const i = args.indexOf("--haren-dir");
1498
- if (i === -1)
1499
- return;
1500
- const value = args[i + 1];
1501
- if (value === undefined || value === "" || value.startsWith("-")) {
1502
- throw new Error("--haren-dir needs a path");
1503
- }
1504
- return value;
1505
- }
1506
- async function resolveHarenDir(cwd, opts = {}) {
1507
- const explicit = opts.harenDir || opts.env?.HAREN_DIR;
1508
- if (explicit) {
1509
- const dir = resolve4(cwd, explicit);
1510
- if (!existsSync6(join7(dir, "manifest.yaml"))) {
1511
- throw new Error(`No manifest.yaml in ${dir}`);
1512
- }
1513
- return location(dir, !await hasMarkedManifest(dir));
1514
- }
1515
- if (await hasMarkedManifest(cwd))
1516
- return location(cwd, false);
1517
- const entries = await readdir3(cwd, { withFileTypes: true }).catch(() => []);
1518
- const matches = [];
1519
- for (const entry of entries) {
1520
- if (entry.name.startsWith(".") || entry.name === "node_modules")
1521
- continue;
1522
- const dir = join7(cwd, entry.name);
1523
- const isDir = entry.isSymbolicLink() ? await stat(dir).then((st) => st.isDirectory(), () => false) : entry.isDirectory();
1524
- if (!isDir)
1525
- continue;
1526
- if (await hasMarkedManifest(dir))
1527
- matches.push(dir);
1528
- }
1529
- matches.sort();
1530
- if (matches.length > 1)
1531
- throw new MultipleHarenDirsError(matches);
1532
- if (matches.length === 1)
1533
- return location(matches[0], false);
1534
- const legacyChild = join7(cwd, "haren");
1535
- if (isLegacyHarenDir(legacyChild))
1536
- return location(legacyChild, true);
1537
- if (isLegacyHarenDir(cwd))
1538
- return location(cwd, true);
1539
- return null;
1540
- }
1541
- var MultipleHarenDirsError;
1542
- var init_resolve = __esm(() => {
1543
- init_manifest();
1544
- MultipleHarenDirsError = class MultipleHarenDirsError extends Error {
1545
- matches;
1546
- constructor(matches) {
1547
- super(`Found more than one haren folder:
1548
- ${matches.join(`
1549
- `)}
1550
- Pass --haren-dir <path> to choose one.`);
1551
- this.matches = matches;
1552
- this.name = "MultipleHarenDirsError";
1553
- }
1554
- };
1555
- });
1556
-
1557
2055
  // src/workspace/detect.ts
1558
- import { existsSync as existsSync7 } from "fs";
2056
+ import { existsSync as existsSync15 } from "fs";
1559
2057
  import { dirname as dirname4 } from "path";
1560
2058
  async function inferLayout(dir) {
1561
2059
  if (hasGitDir(dir))
@@ -1564,7 +2062,7 @@ async function inferLayout(dir) {
1564
2062
  if (childRepos.length > 0)
1565
2063
  return { layout: "workspace", childRepos };
1566
2064
  let probe = dir;
1567
- while (!existsSync7(probe) && dirname4(probe) !== probe)
2065
+ while (!existsSync15(probe) && dirname4(probe) !== probe)
1568
2066
  probe = dirname4(probe);
1569
2067
  if (await isInsideWorkTree(probe))
1570
2068
  return { layout: "monorepo", childRepos: [] };
@@ -1587,7 +2085,7 @@ var init_detect = __esm(() => {
1587
2085
  });
1588
2086
 
1589
2087
  // src/workspace/plan.ts
1590
- import { existsSync as existsSync8 } from "fs";
2088
+ import { existsSync as existsSync16 } from "fs";
1591
2089
  import { basename as basename3, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
1592
2090
  async function buildPlan(input) {
1593
2091
  const items = [];
@@ -1595,7 +2093,8 @@ async function buildPlan(input) {
1595
2093
  const rootFiles = await computeRootFiles({
1596
2094
  workspaceDir: input.rootDir,
1597
2095
  harenDir: input.harenDir,
1598
- editor: input.editor
2096
+ editor: input.editor,
2097
+ hosts: input.hosts
1599
2098
  });
1600
2099
  for (const file of summarizeRootFiles(rootFiles)) {
1601
2100
  const count = file.count ? `(${file.count} files)` : undefined;
@@ -1614,7 +2113,7 @@ async function buildPlan(input) {
1614
2113
  for (const [key, repo] of Object.entries(input.repos)) {
1615
2114
  const abs = resolve5(input.harenDir, repo.path);
1616
2115
  const path = relative2(input.rootDir, abs).split(sep2).join("/") || key;
1617
- if (existsSync8(abs)) {
2116
+ if (existsSync16(abs)) {
1618
2117
  items.push(hasGitDir(abs) || input.layout === "monorepo" ? { path, action: "keep" } : { path, action: "warn", note: "! not a git repo" });
1619
2118
  } else if (input.layout === "monorepo") {
1620
2119
  items.push({ path, action: "warn", note: "! folder not found" });
@@ -1694,12 +2193,12 @@ var init_plan = __esm(() => {
1694
2193
  });
1695
2194
 
1696
2195
  // src/workspace/progress.ts
1697
- import { readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
2196
+ import { readFile as readFile6, writeFile as writeFile5 } from "fs/promises";
1698
2197
  function phaseForStatus(status) {
1699
2198
  return STATUS_TO_PHASE[status];
1700
2199
  }
1701
2200
  async function readProgress(path) {
1702
- const raw = await readFile5(path, "utf-8");
2201
+ const raw = await readFile6(path, "utf-8");
1703
2202
  const progress = JSON.parse(raw);
1704
2203
  progress.modules ??= {};
1705
2204
  for (const mod of Object.values(progress.modules)) {
@@ -1718,16 +2217,18 @@ function isObject(value) {
1718
2217
  return typeof value === "object" && value !== null && !Array.isArray(value);
1719
2218
  }
1720
2219
  async function writeProgress(path, progress) {
1721
- await writeFile4(path, JSON.stringify(progress, null, 2));
2220
+ await writeFile5(path, JSON.stringify(progress, null, 2));
1722
2221
  }
1723
2222
  function updateModuleStatus(progress, moduleName, newStatus) {
1724
2223
  const mod = progress.modules[moduleName];
1725
2224
  if (!mod) {
1726
2225
  throw new Error(`Module '${moduleName}' not found in progress`);
1727
2226
  }
1728
- const allowed = VALID_MODULE_TRANSITIONS[mod.status];
2227
+ const known = Object.hasOwn(VALID_MODULE_TRANSITIONS, mod.status);
2228
+ const allowed = known ? VALID_MODULE_TRANSITIONS[mod.status] : LEGACY_MODULE_EXITS;
1729
2229
  if (!allowed.includes(newStatus)) {
1730
- throw new Error(`Invalid module transition: ${mod.status} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
2230
+ const from = known ? mod.status : `${mod.status} (unknown status from an old progress file)`;
2231
+ throw new Error(`Invalid module transition: ${from} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1731
2232
  }
1732
2233
  return {
1733
2234
  ...progress,
@@ -1751,7 +2252,7 @@ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1751
2252
  if (currentStatus === undefined) {
1752
2253
  throw new Error(`Feature '${featureName}' not found in module '${moduleName}'`);
1753
2254
  }
1754
- const allowed = VALID_FEATURE_TRANSITIONS[currentStatus];
2255
+ const allowed = Object.hasOwn(VALID_FEATURE_TRANSITIONS, currentStatus) ? VALID_FEATURE_TRANSITIONS[currentStatus] : LEGACY_FEATURE_EXITS;
1755
2256
  if (!allowed.includes(newStatus)) {
1756
2257
  throw new Error(`Invalid feature transition: ${currentStatus} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1757
2258
  }
@@ -1836,7 +2337,7 @@ function migrateProgress(raw, repoKeyFor) {
1836
2337
  }
1837
2338
  return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
1838
2339
  }
1839
- var UNIT_LINE, UNIT_STATUSES, MODULE_STATUSES, FEATURE_STATUSES, VALID_MODULE_TRANSITIONS, STATUS_TO_PHASE, VALID_FEATURE_TRANSITIONS, VALID_UNIT_TRANSITIONS, PROGRESS_VERSION = 3;
2340
+ var UNIT_LINE, UNIT_STATUSES, MODULE_STATUSES, FEATURE_STATUSES, VALID_MODULE_TRANSITIONS, LEGACY_MODULE_EXITS, STATUS_TO_PHASE, LEGACY_FEATURE_EXITS, VALID_FEATURE_TRANSITIONS, VALID_UNIT_TRANSITIONS, PROGRESS_VERSION = 3;
1840
2341
  var init_progress = __esm(() => {
1841
2342
  UNIT_LINE = [
1842
2343
  "inventoried",
@@ -1876,6 +2377,7 @@ var init_progress = __esm(() => {
1876
2377
  released: [],
1877
2378
  blocked: ["implementing", "planned"]
1878
2379
  };
2380
+ LEGACY_MODULE_EXITS = ["decomposed", "planned"];
1879
2381
  STATUS_TO_PHASE = {
1880
2382
  discovered: "discover",
1881
2383
  decomposed: "decompose",
@@ -1886,6 +2388,7 @@ var init_progress = __esm(() => {
1886
2388
  released: "release",
1887
2389
  blocked: "blocked"
1888
2390
  };
2391
+ LEGACY_FEATURE_EXITS = ["pending", "in-progress"];
1889
2392
  VALID_FEATURE_TRANSITIONS = {
1890
2393
  pending: ["in-progress"],
1891
2394
  "in-progress": ["evaluating"],
@@ -1916,7 +2419,7 @@ var init_progress = __esm(() => {
1916
2419
  });
1917
2420
 
1918
2421
  // src/lib/version.ts
1919
- import { existsSync as existsSync9, readFileSync } from "fs";
2422
+ import { existsSync as existsSync17, readFileSync } from "fs";
1920
2423
  import { resolve as resolve6 } from "path";
1921
2424
  function readHarenVersion(candidates) {
1922
2425
  const probes = candidates ?? [
@@ -1924,7 +2427,7 @@ function readHarenVersion(candidates) {
1924
2427
  resolve6(import.meta.dir, "..", "..", "package.json")
1925
2428
  ];
1926
2429
  for (const path of probes) {
1927
- if (!existsSync9(path))
2430
+ if (!existsSync17(path))
1928
2431
  continue;
1929
2432
  try {
1930
2433
  const pkg = JSON.parse(readFileSync(path, "utf-8"));
@@ -1963,7 +2466,7 @@ function resolvePluginRef(ref) {
1963
2466
  return { source: entry.source, official: true };
1964
2467
  }
1965
2468
  var REGISTRY;
1966
- var init_registry = __esm(() => {
2469
+ var init_registry2 = __esm(() => {
1967
2470
  REGISTRY = [
1968
2471
  {
1969
2472
  name: "backlog",
@@ -1997,10 +2500,10 @@ async function checkRequirement(req, env = process.env) {
1997
2500
  }
1998
2501
 
1999
2502
  // src/plugins/source.ts
2000
- import { existsSync as existsSync10 } from "fs";
2001
- import { cp, mkdir as mkdir5, mkdtemp, readFile as readFile6, rm } from "fs/promises";
2503
+ import { existsSync as existsSync18 } from "fs";
2504
+ import { cp, mkdir as mkdir5, mkdtemp, readFile as readFile7, rm } from "fs/promises";
2002
2505
  import { tmpdir } from "os";
2003
- import { isAbsolute as isAbsolute2, join as join8, resolve as resolve7 } from "path";
2506
+ import { isAbsolute as isAbsolute2, join as join16, resolve as resolve7 } from "path";
2004
2507
  function parseSource(text) {
2005
2508
  const match = /^(npm|git|file):(.*)$/.exec(text);
2006
2509
  if (!match)
@@ -2026,31 +2529,31 @@ async function run(cmd, cwd) {
2026
2529
  }
2027
2530
  async function fetchPlugin(source, destDir, cwd) {
2028
2531
  const parsed = parseSource(source);
2029
- const work = await mkdtemp(join8(tmpdir(), "haren-plugin-"));
2532
+ const work = await mkdtemp(join16(tmpdir(), "haren-plugin-"));
2030
2533
  let root;
2031
2534
  try {
2032
2535
  if (parsed.kind === "file") {
2033
2536
  root = isAbsolute2(parsed.path) ? parsed.path : resolve7(cwd, parsed.path);
2034
2537
  } else if (parsed.kind === "git") {
2035
- root = join8(work, "repo");
2538
+ root = join16(work, "repo");
2036
2539
  const ref = parsed.ref ? ["--branch", parsed.ref] : [];
2037
2540
  await run(["git", "clone", "--depth", "1", "-q", ...ref, "--", parsed.url, root]);
2038
- await rm(join8(root, ".git"), { recursive: true, force: true });
2541
+ await rm(join16(root, ".git"), { recursive: true, force: true });
2039
2542
  } else {
2040
2543
  await run(["npm", "pack", "--silent", "--pack-destination", work, "--", parsed.spec], work);
2041
2544
  const tgz = (await Array.fromAsync(new Bun.Glob("*.tgz").scan(work)))[0];
2042
2545
  if (!tgz)
2043
2546
  throw new Error(`npm pack ${parsed.spec} produced no archive`);
2044
2547
  await run(["tar", "-xzf", tgz], work);
2045
- root = join8(work, "package");
2548
+ root = join16(work, "package");
2046
2549
  }
2047
- const manifestPath = join8(root, "haren-plugin.json");
2048
- if (!existsSync10(manifestPath))
2550
+ const manifestPath = join16(root, "haren-plugin.json");
2551
+ if (!existsSync18(manifestPath))
2049
2552
  throw new Error(`No haren-plugin.json in ${source}`);
2050
- const raw = JSON.parse(await readFile6(manifestPath, "utf-8"));
2553
+ const raw = JSON.parse(await readFile7(manifestPath, "utf-8"));
2051
2554
  let packageVersion;
2052
2555
  if (parsed.kind === "npm") {
2053
- packageVersion = JSON.parse(await readFile6(join8(root, "package.json"), "utf-8")).version;
2556
+ packageVersion = JSON.parse(await readFile7(join16(root, "package.json"), "utf-8")).version;
2054
2557
  }
2055
2558
  const manifest = validateManifest(raw, packageVersion);
2056
2559
  await rm(destDir, { recursive: true, force: true });
@@ -2066,9 +2569,9 @@ var init_source = __esm(() => {
2066
2569
  });
2067
2570
 
2068
2571
  // src/plugins/install.ts
2069
- import { existsSync as existsSync11 } from "fs";
2070
- import { readFile as readFile7, rename, rm as rm2 } from "fs/promises";
2071
- import { join as join9, relative as relative3, resolve as resolve8, sep as sep3 } from "path";
2572
+ import { existsSync as existsSync19 } from "fs";
2573
+ import { readFile as readFile8, rename, rm as rm2 } from "fs/promises";
2574
+ import { join as join17, relative as relative3, resolve as resolve8, sep as sep3 } from "path";
2072
2575
  async function sh(command, cwd) {
2073
2576
  const proc = Bun.spawn(["sh", "-c", command], { cwd, stdout: "inherit", stderr: "pipe" });
2074
2577
  const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
@@ -2077,11 +2580,11 @@ async function sh(command, cwd) {
2077
2580
  `).pop() ?? `exit ${code}`}`);
2078
2581
  }
2079
2582
  async function harenLayout(harenDir) {
2080
- const path = join9(harenDir, "manifest.yaml");
2081
- if (!existsSync11(path))
2583
+ const path = join17(harenDir, "manifest.yaml");
2584
+ if (!existsSync19(path))
2082
2585
  return "workspace";
2083
2586
  try {
2084
- return parseManifest(await readFile7(path, "utf-8")).layout ?? "workspace";
2587
+ return parseManifest(await readFile8(path, "utf-8")).layout ?? "workspace";
2085
2588
  } catch {
2086
2589
  return "workspace";
2087
2590
  }
@@ -2161,7 +2664,7 @@ async function removeEditorCopies(workspaceDir, files) {
2161
2664
  }
2162
2665
  async function missingPlugins(harenDir) {
2163
2666
  const state = await readPlugins(harenDir);
2164
- return Object.entries(state.plugins).filter(([name, e]) => e.enabled && !existsSync11(join9(pluginDir(harenDir, name), "haren-plugin.json"))).map(([name]) => name);
2667
+ return Object.entries(state.plugins).filter(([name, e]) => e.enabled && !existsSync19(join17(pluginDir(harenDir, name), "haren-plugin.json"))).map(([name]) => name);
2165
2668
  }
2166
2669
  async function restorePlugins(ctx, report) {
2167
2670
  const restored = [];
@@ -2211,17 +2714,17 @@ async function refreshPlugins(ctx, skip = []) {
2211
2714
  }
2212
2715
  var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming"), INSTALL_CANCELLED = "Plugin install cancelled";
2213
2716
  var init_install = __esm(() => {
2214
- init_registry();
2717
+ init_registry2();
2215
2718
  init_source();
2216
2719
  init_state();
2217
2720
  init_manifest();
2218
2721
  });
2219
2722
 
2220
2723
  // src/commands/init.ts
2221
- import { mkdir as mkdir6, writeFile as writeFile5, readdir as readdir4, copyFile, readFile as readFile8 } from "fs/promises";
2222
- import { existsSync as existsSync12, realpathSync } from "fs";
2724
+ import { mkdir as mkdir6, writeFile as writeFile6, readdir as readdir4, copyFile, readFile as readFile9 } from "fs/promises";
2725
+ import { existsSync as existsSync20, realpathSync } from "fs";
2223
2726
  import { homedir } from "os";
2224
- import { basename as basename4, join as join10, resolve as resolve9 } from "path";
2727
+ import { basename as basename4, join as join18, resolve as resolve9 } from "path";
2225
2728
  function readLine() {
2226
2729
  return new Promise((resolve) => {
2227
2730
  const stdin = process.stdin;
@@ -2369,6 +2872,7 @@ function getDirectories(iterations) {
2369
2872
  "skills/generate-mockup",
2370
2873
  "skills/visual-companion",
2371
2874
  "skills/ui-review",
2875
+ "skills/collect-components",
2372
2876
  "skills/onboard",
2373
2877
  "artifacts/_registry",
2374
2878
  "artifacts/00-baseline",
@@ -2391,8 +2895,8 @@ async function copyRecursive(src, dest) {
2391
2895
  const entries = await readdir4(src, { withFileTypes: true });
2392
2896
  await mkdir6(dest, { recursive: true });
2393
2897
  for (const entry of entries) {
2394
- const srcPath = join10(src, entry.name);
2395
- const destPath = join10(dest, entry.name);
2898
+ const srcPath = join18(src, entry.name);
2899
+ const destPath = join18(dest, entry.name);
2396
2900
  if (entry.isDirectory()) {
2397
2901
  await copyRecursive(srcPath, destPath);
2398
2902
  } else {
@@ -2402,9 +2906,9 @@ async function copyRecursive(src, dest) {
2402
2906
  }
2403
2907
  async function scaffoldWorkspace(targetDir, options) {
2404
2908
  for (const dir of getDirectories(!!options.iterations)) {
2405
- await mkdir6(join10(targetDir, dir), { recursive: true });
2909
+ await mkdir6(join18(targetDir, dir), { recursive: true });
2406
2910
  }
2407
- await writeFile5(join10(targetDir, "manifest.yaml"), buildManifestText({
2911
+ let manifestText = buildManifestText({
2408
2912
  version: HAREN_VERSION,
2409
2913
  layout: options.layout ?? "monorepo",
2410
2914
  project: options.project,
@@ -2412,7 +2916,13 @@ async function scaffoldWorkspace(targetDir, options) {
2412
2916
  language: options.language,
2413
2917
  repos: options.repos ?? {},
2414
2918
  iterations: options.iterations
2415
- }));
2919
+ });
2920
+ if (options.experimental?.length) {
2921
+ manifestText = writeManifestList(manifestText, "experimental", options.experimental);
2922
+ }
2923
+ const hosts = options.hosts ?? editorHosts(options.editor ?? "claude-code");
2924
+ manifestText = writeManifestList(manifestText, "hosts", hosts);
2925
+ await writeFile6(join18(targetDir, "manifest.yaml"), manifestText);
2416
2926
  const progressData = {
2417
2927
  project: options.project,
2418
2928
  version: PROGRESS_VERSION,
@@ -2424,24 +2934,24 @@ async function scaffoldWorkspace(targetDir, options) {
2424
2934
  if (options.iterations) {
2425
2935
  progressData.currentIteration = 1;
2426
2936
  }
2427
- await writeFile5(join10(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
2428
- await writeFile5(join10(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
2937
+ await writeFile6(join18(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
2938
+ await writeFile6(join18(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
2429
2939
 
2430
2940
  Append-only log of framework improvement suggestions captured during usage.
2431
2941
 
2432
2942
  ---
2433
2943
  `);
2434
- await writeFile5(join10(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
2944
+ await writeFile6(join18(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
2435
2945
 
2436
2946
  Master registry of all artifacts in this Haren workspace.
2437
2947
 
2438
2948
  | ID | Type | Module | Status | Path |
2439
2949
  |----|------|--------|--------|------|
2440
2950
  `);
2441
- await writeFile5(join10(targetDir, "events", "events.jsonl"), "");
2442
- const gitignore = join10(targetDir, ".gitignore");
2443
- if (!existsSync12(gitignore))
2444
- await writeFile5(gitignore, `.agent.json
2951
+ await writeFile6(join18(targetDir, "events", "events.jsonl"), "");
2952
+ const gitignore = join18(targetDir, ".gitignore");
2953
+ if (!existsSync20(gitignore))
2954
+ await writeFile6(gitignore, `.agent.json
2445
2955
  .agent.pid
2446
2956
  .plugins/
2447
2957
  .companion/
@@ -2449,18 +2959,46 @@ Master registry of all artifacts in this Haren workspace.
2449
2959
  await writeGateScript(targetDir);
2450
2960
  await scaffoldSkillMd(targetDir);
2451
2961
  const contentDir = resolveContentDir();
2452
- await copyRecursive(join10(contentDir, "agents"), join10(targetDir, "agents"));
2453
- await copyRecursive(join10(contentDir, "skills"), join10(targetDir, "skills"));
2454
- await copyRecursive(join10(contentDir, "templates"), join10(targetDir, "templates"));
2962
+ await copyRecursive(join18(contentDir, "agents"), join18(targetDir, "agents"));
2963
+ await copyRecursive(join18(contentDir, "skills"), join18(targetDir, "skills"));
2964
+ await copyRecursive(join18(contentDir, "templates"), join18(targetDir, "templates"));
2455
2965
  await options.beforeRootFiles?.();
2456
2966
  await writeRootFiles({
2457
2967
  workspaceDir: resolve9(targetDir, ".."),
2458
2968
  harenDir: targetDir,
2459
- editor: options.editor ?? "claude-code"
2969
+ hosts
2970
+ });
2971
+ printGateNotes(hosts);
2972
+ }
2973
+ function gateNotes(hosts) {
2974
+ return hosts.flatMap((id) => {
2975
+ const host = getHost(id);
2976
+ return host?.gateNote ? [`${host.label}: ${host.gateNote}`] : [];
2460
2977
  });
2461
2978
  }
2979
+ function printGateNotes(hosts) {
2980
+ for (const note of gateNotes(hosts))
2981
+ console.log(` \x1B[33m!\x1B[0m ${note}`);
2982
+ }
2983
+ function selectHosts(opts, multiHost) {
2984
+ if (opts.hosts)
2985
+ return resolveHosts(opts.hosts, multiHost);
2986
+ if (opts.editor)
2987
+ return editorHosts(opts.editor);
2988
+ return;
2989
+ }
2990
+ async function promptHosts(multiHost) {
2991
+ if (!multiHost) {
2992
+ const editor = await promptSelect("Which editors do you use?", EDITORS, EDITOR_DESCRIPTIONS, "claude-code");
2993
+ return editorHosts(editor);
2994
+ }
2995
+ const hosts = listHosts();
2996
+ const picked = await promptMultiSelect("Which coding agents do you use?", hosts.map((h) => `${h.id.padEnd(12)} ${h.label}${h.experimental ? " (experimental)" : ""}`), [0]);
2997
+ const ids = picked.map((i) => hosts[i].id);
2998
+ return ids.length > 0 ? ids : ["claude-code"];
2999
+ }
2462
3000
  async function scaffoldSkillMd(targetDir) {
2463
- await writeFile5(join10(targetDir, "skill.md"), `---
3001
+ await writeFile6(join18(targetDir, "skill.md"), `---
2464
3002
  name: haren
2465
3003
  description: Agentic SDLC framework \u2014 orchestrates AI agents through structured phases
2466
3004
  ---
@@ -2490,7 +3028,8 @@ You are operating within the Haren agentic SDLC framework.
2490
3028
  - Rewrite of a legacy system with parity as the bar \u2192 \`migration\`
2491
3029
  6. Suggest next action based on current state
2492
3030
 
2493
- Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | ascii | browser). See the visual-companion skill.
3031
+ Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | ascii | browser | artifact). See the visual-companion skill.
3032
+ Experimental features are listed in manifest.yaml \`experimental:\` (\`multi-host\`, \`multi-model\`); the installed coding agents are in \`hosts:\`.
2494
3033
 
2495
3034
  ## Available Actions
2496
3035
 
@@ -2511,6 +3050,7 @@ Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | asci
2511
3050
  | Draw a UI wireframe or compare screen options | generate-mockup/ | \u2014 |
2512
3051
  | Show mockups or options in a browser tab | visual-companion/ (\`haren companion\`) | \u2014 |
2513
3052
  | Review a screen against UX heuristics | ui-review/ | \u2014 |
3053
+ | Catalog common UI components, shared services and functions | collect-components/ | Developer |
2514
3054
  | Update status, artifacts, events | update-tracking/ (\`haren track\`) | \u2014 |
2515
3055
  | Onboard to the project / check the workspace | onboard/ (\`/haren-onboard\`) | \u2014 |
2516
3056
 
@@ -2546,6 +3086,8 @@ Change \`progress.json\`, \`events/events.jsonl\` and \`artifacts/_registry/arti
2546
3086
  | Module definition | Discover phase | \`artifacts/03-modules/{module}/module.md\` |
2547
3087
  | Design (architecture) | Dev | \`artifacts/04-plans/{module}/design.md\` |
2548
3088
  | Tasks (implementation) | Dev | \`artifacts/04-plans/{module}/[iteration-{N}/]tasks.md\` |
3089
+ | Implementation checklist | Dev | \`artifacts/04-plans/{module}/[iteration-{N}/]checklist.md\` |
3090
+ | Component catalog | Dev | \`artifacts/03-modules/component-catalog.md\` |
2549
3091
 
2550
3092
  ## Plan Paths
2551
3093
 
@@ -2563,7 +3105,7 @@ All skills that read or write plan artifacts MUST resolve paths using this conve
2563
3105
  - The plan skill writes to BOTH master and active paths (it is the only skill that does this)
2564
3106
 
2565
3107
  **If no \`iterations\` block in manifest.yaml:**
2566
- - **Active plan path:** \`artifacts/04-plans/{module}/\` \u2014 contains design.md, tasks.md
3108
+ - **Active plan path:** \`artifacts/04-plans/{module}/\` \u2014 contains design.md, tasks.md, checklist.md
2567
3109
  - **Master plan path:** (same as active)
2568
3110
 
2569
3111
  When a skill says "read the spec", it means from \`artifacts/03-modules/{module}/spec.md\`.
@@ -2638,6 +3180,15 @@ function parseInitArgs(args) {
2638
3180
  out.plugins.push(value);
2639
3181
  i++;
2640
3182
  break;
3183
+ case "--experimental": {
3184
+ if (value === undefined || value === "" || value.startsWith("-")) {
3185
+ throw new Error("--experimental needs a comma list, for example multi-host");
3186
+ }
3187
+ const names = value.split(",").map((v) => v.trim()).filter(Boolean);
3188
+ out.experimental = [...new Set(names.map(checkFeature))];
3189
+ i++;
3190
+ break;
3191
+ }
2641
3192
  case "--mode":
2642
3193
  if (!MODES.includes(value)) {
2643
3194
  throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, migration, or undecided.`);
@@ -2645,6 +3196,17 @@ function parseInitArgs(args) {
2645
3196
  out.mode = value;
2646
3197
  i++;
2647
3198
  break;
3199
+ case "--hosts":
3200
+ if (value === undefined || value === "" || value.startsWith("-")) {
3201
+ throw new Error("--hosts needs a comma list, for example claude-code,codex");
3202
+ }
3203
+ out.hosts = value.split(",").map((v) => v.trim()).filter(Boolean);
3204
+ if (out.hosts.length === 0)
3205
+ throw new Error("--hosts needs at least one host");
3206
+ for (const id of out.hosts)
3207
+ resolveHosts([id], true);
3208
+ i++;
3209
+ break;
2648
3210
  case "--editor":
2649
3211
  if (value !== "claude-code" && value !== "cursor" && value !== "both") {
2650
3212
  throw new Error(`Invalid editor: ${value}. Must be claude-code, cursor, or both.`);
@@ -2684,6 +3246,8 @@ function parseInitArgs(args) {
2684
3246
  break;
2685
3247
  }
2686
3248
  }
3249
+ if (out.editor && out.hosts)
3250
+ throw new Error("Use --editor or --hosts, not both.");
2687
3251
  return out;
2688
3252
  }
2689
3253
  async function applyClones(plan, rootDir) {
@@ -2692,7 +3256,7 @@ async function applyClones(plan, rootDir) {
2692
3256
  if (item.action !== "clone" || !item.remote)
2693
3257
  continue;
2694
3258
  console.log(` \x1B[36m\u2193\x1B[0m Cloning ${item.path} ...`);
2695
- const result = await cloneRepo(item.remote, join10(rootDir, item.path));
3259
+ const result = await cloneRepo(item.remote, join18(rootDir, item.path));
2696
3260
  if (!result.ok) {
2697
3261
  console.error(` \x1B[31m\u2717\x1B[0m ${item.path}: ${result.stderr.split(`
2698
3262
  `).pop()}`);
@@ -2800,24 +3364,42 @@ async function runSetup(location, opts) {
2800
3364
  console.log(" Run 'haren upgrade' to migrate it.");
2801
3365
  return;
2802
3366
  }
2803
- const manifest = parseManifest(await readFile8(join10(location.harenDir, "manifest.yaml"), "utf-8"));
3367
+ const manifestPath = join18(location.harenDir, "manifest.yaml");
3368
+ const manifestText = await readFile9(manifestPath, "utf-8");
3369
+ const manifest = parseManifest(manifestText);
2804
3370
  const layout = manifest.layout ?? "workspace";
2805
- let editor = opts.editor ?? detectEditor(location.workspaceDir);
2806
- if (!editor) {
2807
- editor = canPrompt(opts) ? await promptSelect("Which editors do you use?", EDITORS, EDITOR_DESCRIPTIONS, "claude-code") : "claude-code";
2808
- }
3371
+ const knownExp = readExperimental(manifest).known;
3372
+ const mergedExp = [...new Set([...knownExp, ...opts.experimental ?? []])];
3373
+ if (mergedExp.length !== knownExp.length)
3374
+ manifest.experimental = mergedExp;
3375
+ const multiHost = isExperimental(manifest, "multi-host");
3376
+ const saved = readHosts(manifest);
3377
+ const detected = detectEditor(location.workspaceDir);
3378
+ const hosts = selectHosts(opts, multiHost) ?? (saved ? resolveHosts(saved, multiHost) : undefined) ?? (detected ? editorHosts(detected) : undefined) ?? (canPrompt(opts) ? await promptHosts(multiHost) : ["claude-code"]);
3379
+ const saveManifest = async () => {
3380
+ let text = manifestText;
3381
+ if (mergedExp.length !== knownExp.length) {
3382
+ text = writeManifestList(text, "experimental", mergedExp);
3383
+ }
3384
+ if ((saved ?? []).join(",") !== hosts.join(","))
3385
+ text = writeManifestList(text, "hosts", hosts);
3386
+ if (text !== manifestText)
3387
+ await writeFile6(manifestPath, text);
3388
+ };
2809
3389
  const plan = await buildPlan({
2810
3390
  rootDir: location.workspaceDir,
2811
3391
  harenDir: location.harenDir,
2812
3392
  layout,
2813
3393
  createHaren: false,
2814
3394
  repos: normalizeRepos(manifest.repos),
2815
- editor
3395
+ hosts
2816
3396
  });
2817
3397
  console.log(` Found haren folder: ${location.harenDir}`);
2818
3398
  const missing = await missingPlugins(location.harenDir);
2819
3399
  if (isNoop(plan) && opts.plugins.length === 0) {
2820
3400
  if (missing.length === 0) {
3401
+ if (!opts.dryRun)
3402
+ await saveManifest();
2821
3403
  console.log(" Already set up. Run 'haren upgrade' to update framework files.");
2822
3404
  return;
2823
3405
  }
@@ -2825,11 +3407,12 @@ async function runSetup(location, opts) {
2825
3407
  console.log(` Plugins to restore: ${missing.join(", ")}`);
2826
3408
  return;
2827
3409
  }
3410
+ await saveManifest();
2828
3411
  await restoreMissing(opts, location, manifest.project ?? "");
2829
3412
  await writeRootFiles({
2830
3413
  workspaceDir: location.workspaceDir,
2831
3414
  harenDir: location.harenDir,
2832
- editor
3415
+ hosts
2833
3416
  });
2834
3417
  return;
2835
3418
  }
@@ -2840,14 +3423,16 @@ async function runSetup(location, opts) {
2840
3423
  return;
2841
3424
  if (await confirmOrExit(opts, false) === "no")
2842
3425
  return;
3426
+ await saveManifest();
2843
3427
  const failed = await applyClones(plan, location.workspaceDir);
2844
3428
  await restoreMissing(opts, location, manifest.project ?? "");
2845
3429
  await setupPlugins(opts, location.workspaceDir, location.harenDir, manifest.project ?? "");
2846
3430
  await writeRootFiles({
2847
3431
  workspaceDir: location.workspaceDir,
2848
3432
  harenDir: location.harenDir,
2849
- editor
3433
+ hosts
2850
3434
  });
3435
+ printGateNotes(hosts);
2851
3436
  printNextSteps();
2852
3437
  if (failed.length > 0) {
2853
3438
  console.error(` ${failed.length} repo(s) failed to clone: ${failed.join(", ")}. Run 'haren init' again to retry.`);
@@ -2887,7 +3472,7 @@ async function init(args) {
2887
3472
  process.exit(1);
2888
3473
  }
2889
3474
  printBanner();
2890
- const explicitHarenDir = opts.harenDir && existsSync12(join10(cwdRoot, opts.harenDir, "manifest.yaml")) ? opts.harenDir : undefined;
3475
+ const explicitHarenDir = opts.harenDir && existsSync20(join18(cwdRoot, opts.harenDir, "manifest.yaml")) ? opts.harenDir : undefined;
2891
3476
  let detection;
2892
3477
  try {
2893
3478
  detection = await detectLayout(cwdRoot, { harenDir: explicitHarenDir, env: process.env });
@@ -2904,7 +3489,7 @@ async function init(args) {
2904
3489
  let existingLayout;
2905
3490
  if (detection.kind === "existing" && detection.location) {
2906
3491
  const loc = detection.location;
2907
- existingManifest = parseManifest(await readFile8(join10(loc.harenDir, "manifest.yaml"), "utf-8"));
3492
+ existingManifest = parseManifest(await readFile9(join18(loc.harenDir, "manifest.yaml"), "utf-8"));
2908
3493
  existingRepos = normalizeRepos(existingManifest.repos);
2909
3494
  existingLayout = existingManifest.layout ?? (await inferLayout(loc.workspaceDir)).layout ?? "workspace";
2910
3495
  }
@@ -2918,7 +3503,7 @@ async function init(args) {
2918
3503
  console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
2919
3504
  console.log("");
2920
3505
  const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt2("haren folder name:", "haren") : "haren");
2921
- const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join10(rootDir, harenDirName);
3506
+ const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join18(rootDir, harenDirName);
2922
3507
  const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
2923
3508
  const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
2924
3509
  let selected = defaults;
@@ -2927,7 +3512,15 @@ async function init(args) {
2927
3512
  const mode = opts.mode ?? existingMode ?? (interactive ? await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided") : "undecided");
2928
3513
  const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt2("Preferred language:", "English") : "English");
2929
3514
  const iterations = opts.iterations ?? (existingManifest ? manifestIterations(existingManifest) : interactive ? await promptIterations() : undefined);
2930
- const editor = opts.editor ?? (existingLoc ? detectEditor(existingLoc.workspaceDir) ?? "claude-code" : undefined) ?? (interactive ? await promptSelect("Which editors do you use?", EDITORS, EDITOR_DESCRIPTIONS, "claude-code") : "claude-code");
3515
+ const multiHost = (opts.experimental ?? []).includes("multi-host") || (existingManifest ? isExperimental(existingManifest, "multi-host") : false);
3516
+ let hosts;
3517
+ try {
3518
+ const saved = existingManifest ? readHosts(existingManifest) : undefined;
3519
+ hosts = selectHosts(opts, multiHost) ?? (saved ? resolveHosts(saved, multiHost) : undefined) ?? (existingLoc ? editorHosts(detectEditor(existingLoc.workspaceDir) ?? "claude-code") : undefined) ?? (interactive ? await promptHosts(multiHost) : ["claude-code"]);
3520
+ } catch (err) {
3521
+ console.error(` ${err.message}`);
3522
+ process.exit(1);
3523
+ }
2931
3524
  while (true) {
2932
3525
  if (layout === "workspace" && children.length > 0 && interactive) {
2933
3526
  selected = await promptMultiSelect("Select code repos to track:", children.map((r) => `${r.name.padEnd(12)} ${r.remote ?? "(no remote)"}`), selected);
@@ -2943,7 +3536,7 @@ async function init(args) {
2943
3536
  layout,
2944
3537
  createHaren: true,
2945
3538
  repos,
2946
- editor,
3539
+ hosts,
2947
3540
  manifestPreview: `layout: ${layout}
2948
3541
  ${renderReposBlock(repos)}`
2949
3542
  });
@@ -2964,9 +3557,15 @@ ${renderReposBlock(repos)}`
2964
3557
  mode,
2965
3558
  language,
2966
3559
  iterations,
2967
- editor,
3560
+ hosts,
2968
3561
  layout,
2969
3562
  repos,
3563
+ experimental: [
3564
+ ...new Set([
3565
+ ...existingManifest ? readExperimental(existingManifest).known : [],
3566
+ ...opts.experimental ?? []
3567
+ ])
3568
+ ],
2970
3569
  beforeRootFiles: () => setupPlugins(opts, rootDir, harenDir, project)
2971
3570
  });
2972
3571
  if (layout === "workspace" && !hasGitDir(harenDir)) {
@@ -2990,14 +3589,17 @@ var init_init = __esm(() => {
2990
3589
  init_content_dir();
2991
3590
  init_templates();
2992
3591
  init_manifest();
3592
+ init_experimental2();
3593
+ init_experimental();
2993
3594
  init_root_files();
3595
+ init_registry();
2994
3596
  init_detect();
2995
3597
  init_plan();
2996
3598
  init_git();
2997
3599
  init_progress();
2998
3600
  init_version();
2999
3601
  init_install();
3000
- init_registry();
3602
+ init_registry2();
3001
3603
  MODES = ["blueprint", "explore", "inherit", "migration", "undecided"];
3002
3604
  EDITORS = ["claude-code", "cursor", "both"];
3003
3605
  EDITOR_DESCRIPTIONS = {
@@ -3014,21 +3616,80 @@ var init_init = __esm(() => {
3014
3616
  };
3015
3617
  });
3016
3618
 
3619
+ // src/lib/changelog.ts
3620
+ import { existsSync as existsSync21, readFileSync as readFileSync2 } from "fs";
3621
+ import { resolve as resolve10 } from "path";
3622
+ function readChangelog(candidates) {
3623
+ const probes = candidates ?? [
3624
+ resolve10(import.meta.dir, "..", "CHANGELOG.md"),
3625
+ resolve10(import.meta.dir, "..", "..", "..", "..", "CHANGELOG.md")
3626
+ ];
3627
+ for (const path of probes) {
3628
+ if (existsSync21(path))
3629
+ return readFileSync2(path, "utf-8");
3630
+ }
3631
+ return null;
3632
+ }
3633
+ function compareVersions(a, b) {
3634
+ const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
3635
+ const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
3636
+ for (let i = 0;i < 3; i++) {
3637
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
3638
+ if (d !== 0)
3639
+ return d;
3640
+ }
3641
+ return 0;
3642
+ }
3643
+ function parseChangelog(text) {
3644
+ const sections = [];
3645
+ let current = null;
3646
+ for (const line of text.split(/\r?\n/)) {
3647
+ const m = /^##\s+\[?v?(\d+\.\d+\.\d+)\]?/.exec(line);
3648
+ if (m) {
3649
+ current = { version: m[1], body: "" };
3650
+ sections.push(current);
3651
+ } else if (current) {
3652
+ current.body += `${line}
3653
+ `;
3654
+ }
3655
+ }
3656
+ for (const s of sections)
3657
+ s.body = s.body.trim();
3658
+ return sections;
3659
+ }
3660
+ function whatsNew(text, from, to) {
3661
+ return parseChangelog(text).filter((s) => compareVersions(s.version, to) <= 0).filter((s) => from ? compareVersions(s.version, from) > 0 : compareVersions(s.version, to) === 0).sort((a, b) => compareVersions(b.version, a.version));
3662
+ }
3663
+ var init_changelog = () => {};
3664
+
3017
3665
  // src/commands/upgrade.ts
3018
- import { mkdir as mkdir7, readdir as readdir5, copyFile as copyFile2, readFile as readFile9, stat as stat2, writeFile as writeFile6 } from "fs/promises";
3019
- import { join as join11, resolve as resolve10 } from "path";
3020
- import { existsSync as existsSync13 } from "fs";
3666
+ import { mkdir as mkdir7, readdir as readdir5, copyFile as copyFile2, readFile as readFile10, stat as stat2, writeFile as writeFile7 } from "fs/promises";
3667
+ import { join as join19, resolve as resolve11 } from "path";
3668
+ import { existsSync as existsSync22 } from "fs";
3021
3669
  async function moduleRepoKey(harenDir, moduleName) {
3022
- const path = join11(harenDir, "artifacts", "03-modules", moduleName, "module.md");
3023
- if (!existsSync13(path))
3670
+ const path = join19(harenDir, "artifacts", "03-modules", moduleName, "module.md");
3671
+ if (!existsSync22(path))
3024
3672
  return;
3025
- const match = (await readFile9(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
3673
+ const match = (await readFile10(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
3026
3674
  return match?.[1].split(",")[0]?.trim().replace(/^["']|["']$/g, "") || undefined;
3027
3675
  }
3676
+ function usableHosts(saved, multiHost) {
3677
+ const out = [];
3678
+ for (const id of saved) {
3679
+ const host = getHost(id);
3680
+ if (!host)
3681
+ console.warn(` warning: unknown host '${id}' in manifest.yaml hosts:; skipped`);
3682
+ else if (host.experimental && !multiHost) {
3683
+ console.warn(` warning: host '${id}' is experimental and multi-host is off; skipped. Run: haren experimental enable multi-host`);
3684
+ } else if (!out.includes(id))
3685
+ out.push(id);
3686
+ }
3687
+ return out;
3688
+ }
3028
3689
  async function planMigration(location) {
3029
3690
  const { harenDir, workspaceDir } = location;
3030
3691
  const steps = [];
3031
- const manifestBefore = await readFile9(join11(harenDir, "manifest.yaml"), "utf-8");
3692
+ const manifestBefore = await readFile10(join19(harenDir, "manifest.yaml"), "utf-8");
3032
3693
  const manifest = parseManifest(manifestBefore);
3033
3694
  const layout = manifest.layout ?? (await inferLayout(workspaceDir)).layout ?? "workspace";
3034
3695
  if (!hasMarker(manifest))
@@ -3044,7 +3705,7 @@ async function planMigration(location) {
3044
3705
  const map = {};
3045
3706
  let foundRemote = false;
3046
3707
  for (const [key, entry] of Object.entries(current)) {
3047
- const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve10(harenDir, entry.path)) : null);
3708
+ const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve11(harenDir, entry.path)) : null);
3048
3709
  if (remote && !entry.remote)
3049
3710
  foundRemote = true;
3050
3711
  map[key] = remote ? { ...entry, remote } : entry;
@@ -3054,15 +3715,22 @@ async function planMigration(location) {
3054
3715
  steps.push("manifest.yaml: convert repos to a map with remotes");
3055
3716
  }
3056
3717
  }
3057
- const manifestAfter = migrateManifestText(manifestBefore, {
3718
+ let manifestAfter = migrateManifestText(manifestBefore, {
3058
3719
  version: HAREN_VERSION,
3059
3720
  layout,
3060
3721
  repos
3061
3722
  });
3723
+ const detected = detectEditor(workspaceDir) ?? "claude-code";
3724
+ const saved = readHosts(manifest);
3725
+ const hosts = saved ? usableHosts(saved, isExperimental(manifest, "multi-host")) : editorHosts(detected);
3726
+ if (!saved) {
3727
+ manifestAfter = writeManifestList(manifestAfter, "hosts", hosts);
3728
+ steps.push(`manifest.yaml: add hosts: [${hosts.join(", ")}]`);
3729
+ }
3062
3730
  let progress = null;
3063
- const progressPath = join11(harenDir, "progress.json");
3064
- if (existsSync13(progressPath)) {
3065
- const before = await readFile9(progressPath, "utf-8");
3731
+ const progressPath = join19(harenDir, "progress.json");
3732
+ if (existsSync22(progressPath)) {
3733
+ const before = await readFile10(progressPath, "utf-8");
3066
3734
  let raw;
3067
3735
  try {
3068
3736
  raw = JSON.parse(before);
@@ -3084,8 +3752,8 @@ async function planMigration(location) {
3084
3752
  const gitignore = await planGitignore(harenDir);
3085
3753
  if (gitignore !== null)
3086
3754
  steps.push(`.gitignore: add ${IGNORED.join(", ")}`);
3087
- const editor = detectEditor(workspaceDir) ?? "claude-code";
3088
- const rootFiles = await computeRootFiles({ workspaceDir, harenDir, editor });
3755
+ const editor = detected;
3756
+ const rootFiles = await computeRootFiles({ workspaceDir, harenDir, hosts });
3089
3757
  for (const file of summarizeRootFiles(rootFiles).filter((f) => f.changed)) {
3090
3758
  const count = file.count ? ` (${file.count} files)` : "";
3091
3759
  steps.push(`${file.path}: ${file.existed ? "update" : "create"}${count}`);
@@ -3096,12 +3764,14 @@ async function planMigration(location) {
3096
3764
  gitignore,
3097
3765
  layout,
3098
3766
  editor,
3099
- steps
3767
+ hosts,
3768
+ steps,
3769
+ fromVersion: hasMarker(manifest) ? String(manifest.haren?.version) : undefined
3100
3770
  };
3101
3771
  }
3102
3772
  async function planGitignore(harenDir) {
3103
- const path = join11(harenDir, ".gitignore");
3104
- const before = existsSync13(path) ? await readFile9(path, "utf-8") : "";
3773
+ const path = join19(harenDir, ".gitignore");
3774
+ const before = existsSync22(path) ? await readFile10(path, "utf-8") : "";
3105
3775
  const lines = new Set(before.split(/\r?\n/).map((l) => l.trim()));
3106
3776
  const missing = IGNORED.filter((f) => !lines.has(f));
3107
3777
  if (missing.length === 0)
@@ -3118,8 +3788,8 @@ async function copyRecursive2(src, dest) {
3118
3788
  const entries = await readdir5(src, { withFileTypes: true });
3119
3789
  await mkdir7(dest, { recursive: true });
3120
3790
  for (const entry of entries) {
3121
- const srcPath = join11(src, entry.name);
3122
- const destPath = join11(dest, entry.name);
3791
+ const srcPath = join19(src, entry.name);
3792
+ const destPath = join19(dest, entry.name);
3123
3793
  if (entry.isDirectory()) {
3124
3794
  await copyRecursive2(srcPath, destPath);
3125
3795
  } else {
@@ -3132,7 +3802,7 @@ async function countFiles(dir) {
3132
3802
  const entries = await readdir5(dir, { withFileTypes: true });
3133
3803
  for (const entry of entries) {
3134
3804
  if (entry.isDirectory()) {
3135
- count += await countFiles(join11(dir, entry.name));
3805
+ count += await countFiles(join19(dir, entry.name));
3136
3806
  } else {
3137
3807
  count++;
3138
3808
  }
@@ -3176,8 +3846,8 @@ async function upgrade(args) {
3176
3846
  console.log("\x1B[2m Upgrading framework files:\x1B[0m");
3177
3847
  let totalFiles = 0;
3178
3848
  for (const dir of FRAMEWORK_DIRS) {
3179
- const srcDir = join11(contentDir, dir);
3180
- const destDir = join11(targetDir, dir);
3849
+ const srcDir = join19(contentDir, dir);
3850
+ const destDir = join19(targetDir, dir);
3181
3851
  const fileCount = await countFiles(srcDir);
3182
3852
  totalFiles += fileCount;
3183
3853
  console.log(` \x1B[36m\u2191\x1B[0m ${dir}/ \x1B[2m(${fileCount} files)\x1B[0m`);
@@ -3197,19 +3867,19 @@ async function upgrade(args) {
3197
3867
  return;
3198
3868
  }
3199
3869
  for (const dir of FRAMEWORK_DIRS) {
3200
- await copyRecursive2(join11(contentDir, dir), join11(targetDir, dir));
3870
+ await copyRecursive2(join19(contentDir, dir), join19(targetDir, dir));
3201
3871
  }
3202
3872
  await Promise.resolve().then(() => init_init());
3203
3873
  await scaffoldSkillMd(targetDir);
3204
3874
  await writeGateScript(targetDir);
3205
3875
  if (migration.manifest.after !== migration.manifest.before) {
3206
- await writeFile6(join11(targetDir, "manifest.yaml"), migration.manifest.after);
3876
+ await writeFile7(join19(targetDir, "manifest.yaml"), migration.manifest.after);
3207
3877
  }
3208
3878
  if (migration.progress) {
3209
- await writeFile6(join11(targetDir, "progress.json"), migration.progress.after);
3879
+ await writeFile7(join19(targetDir, "progress.json"), migration.progress.after);
3210
3880
  }
3211
3881
  if (migration.gitignore !== null) {
3212
- await writeFile6(join11(targetDir, ".gitignore"), migration.gitignore);
3882
+ await writeFile7(join19(targetDir, ".gitignore"), migration.gitignore);
3213
3883
  }
3214
3884
  const yes = args.includes("--yes") || args.includes("-y");
3215
3885
  const pluginCtx = {
@@ -3228,22 +3898,44 @@ async function upgrade(args) {
3228
3898
  await writeRootFiles({
3229
3899
  workspaceDir: location.workspaceDir,
3230
3900
  harenDir: targetDir,
3231
- editor: migration.editor
3901
+ hosts: migration.hosts
3232
3902
  });
3233
3903
  console.log(` \x1B[32m\u2713\x1B[0m Upgraded ${totalFiles + 2} framework files.`);
3234
3904
  console.log(` \x1B[2mYour artifacts are untouched. Manifest and progress were migrated if needed.\x1B[0m`);
3235
3905
  console.log("");
3906
+ printWhatsNew(migration.fromVersion, HAREN_VERSION);
3907
+ }
3908
+ function printWhatsNew(from, to, text = readChangelog(), log = console.log) {
3909
+ if (!text || from === to)
3910
+ return;
3911
+ const sections = whatsNew(text, from, to);
3912
+ if (!sections.length)
3913
+ return;
3914
+ log(`\x1B[36m What's new${from ? ` since ${from}` : ""}\x1B[0m`);
3915
+ for (const s of sections) {
3916
+ log("");
3917
+ log(` \x1B[1m${s.version}\x1B[0m`);
3918
+ for (const line of s.body.split(`
3919
+ `))
3920
+ log(line ? ` ${line}` : "");
3921
+ }
3922
+ log("");
3923
+ log(" \x1B[2mFull changelog: https://github.com/odarino/haren/blob/main/CHANGELOG.md\x1B[0m");
3924
+ log("");
3236
3925
  }
3237
3926
  var IGNORED, FRAMEWORK_DIRS, USER_FILES;
3238
3927
  var init_upgrade = __esm(() => {
3239
3928
  init_content_dir();
3240
3929
  init_version();
3930
+ init_changelog();
3241
3931
  init_git();
3242
3932
  init_detect();
3243
3933
  init_manifest();
3244
3934
  init_progress();
3245
3935
  init_resolve();
3246
3936
  init_root_files();
3937
+ init_registry();
3938
+ init_experimental();
3247
3939
  init_install();
3248
3940
  init_templates();
3249
3941
  IGNORED = [".agent.json", ".agent.pid", ".plugins/", ".companion/"];
@@ -3252,15 +3944,15 @@ var init_upgrade = __esm(() => {
3252
3944
  });
3253
3945
 
3254
3946
  // src/agent/config.ts
3255
- import { join as join12 } from "path";
3947
+ import { join as join20 } from "path";
3256
3948
  async function readAgentConfig(harenDir) {
3257
- const file = Bun.file(join12(harenDir, CONFIG_FILE));
3949
+ const file = Bun.file(join20(harenDir, CONFIG_FILE));
3258
3950
  if (!await file.exists())
3259
3951
  return null;
3260
3952
  return file.json();
3261
3953
  }
3262
3954
  async function writeAgentConfig(harenDir, config) {
3263
- const path = join12(harenDir, CONFIG_FILE);
3955
+ const path = join20(harenDir, CONFIG_FILE);
3264
3956
  await Bun.write(path, JSON.stringify(config, null, 2));
3265
3957
  }
3266
3958
  var CONFIG_FILE = ".agent.json";
@@ -3270,29 +3962,31 @@ var init_config = () => {};
3270
3962
  async function checkCLI(command) {
3271
3963
  return Bun.which(command) !== null;
3272
3964
  }
3965
+ function knownCLIs() {
3966
+ const hosts = listHosts().flatMap((h) => h.exec ? [{ name: cliName(h), binary: h.exec({ prompt: "", cwd: "." })[0] }] : []);
3967
+ return [...hosts, ...EXTRA_CLIS.map((c) => ({ name: c, binary: c }))];
3968
+ }
3273
3969
  async function detectCLIs() {
3274
- const results = await Promise.all(KNOWN_CLIS.map(async (cli) => ({
3275
- name: cli,
3276
- available: await checkCLI(cli)
3277
- })));
3970
+ const results = await Promise.all(knownCLIs().map(async (cli) => ({ name: cli.name, available: await checkCLI(cli.binary) })));
3278
3971
  return results.filter((r) => r.available).map((r) => r.name);
3279
3972
  }
3280
- var KNOWN_CLIS;
3973
+ var EXTRA_CLIS;
3281
3974
  var init_cli_detector = __esm(() => {
3282
- KNOWN_CLIS = ["claude", "cursor", "github-copilot-cli"];
3975
+ init_registry();
3976
+ EXTRA_CLIS = ["github-copilot-cli"];
3283
3977
  });
3284
3978
 
3285
3979
  // src/agent/artifact-reader.ts
3286
- import { join as join13 } from "path";
3980
+ import { join as join21 } from "path";
3287
3981
  import { readdir as readdir6 } from "fs/promises";
3288
3982
  async function readProgress2(harenDir) {
3289
- const file = Bun.file(join13(harenDir, "progress.json"));
3983
+ const file = Bun.file(join21(harenDir, "progress.json"));
3290
3984
  if (!await file.exists())
3291
3985
  return null;
3292
3986
  return file.json();
3293
3987
  }
3294
3988
  async function readArtifactTree(harenDir) {
3295
- const artifactsDir = join13(harenDir, "artifacts");
3989
+ const artifactsDir = join21(harenDir, "artifacts");
3296
3990
  try {
3297
3991
  return await buildTree(artifactsDir, "artifacts");
3298
3992
  } catch {
@@ -3303,9 +3997,9 @@ async function buildTree(dirPath, relativePath) {
3303
3997
  const entries = await readdir6(dirPath, { withFileTypes: true });
3304
3998
  const nodes = [];
3305
3999
  for (const entry of entries) {
3306
- const entryPath = join13(relativePath, entry.name);
4000
+ const entryPath = join21(relativePath, entry.name);
3307
4001
  if (entry.isDirectory()) {
3308
- const children = await buildTree(join13(dirPath, entry.name), entryPath);
4002
+ const children = await buildTree(join21(dirPath, entry.name), entryPath);
3309
4003
  nodes.push({
3310
4004
  name: entry.name,
3311
4005
  type: "directory",
@@ -3319,7 +4013,7 @@ async function buildTree(dirPath, relativePath) {
3319
4013
  return nodes.sort((a, b) => a.name.localeCompare(b.name));
3320
4014
  }
3321
4015
  async function readArtifact(harenDir, relativePath) {
3322
- const file = Bun.file(join13(harenDir, relativePath));
4016
+ const file = Bun.file(join21(harenDir, relativePath));
3323
4017
  if (!await file.exists())
3324
4018
  return null;
3325
4019
  return file.text();
@@ -3381,20 +4075,22 @@ async function executeCLI(cli, prompt2, onOutput) {
3381
4075
  }
3382
4076
  }
3383
4077
  function buildCLIArgs(cli, prompt2) {
4078
+ const host = hostForCli(cli);
4079
+ if (host?.exec)
4080
+ return host.exec({ prompt: prompt2, cwd: process.cwd() });
3384
4081
  switch (cli) {
3385
- case "claude":
3386
- return ["claude", "--print", prompt2];
3387
- case "cursor":
3388
- return ["cursor", "--prompt", prompt2];
3389
4082
  case "github-copilot-cli":
3390
4083
  return ["github-copilot-cli", prompt2];
3391
4084
  default:
3392
4085
  return [cli, prompt2];
3393
4086
  }
3394
4087
  }
4088
+ var init_cli_executor = __esm(() => {
4089
+ init_registry();
4090
+ });
3395
4091
 
3396
4092
  // src/workspace/events.ts
3397
- import { appendFile, readFile as readFile10 } from "fs/promises";
4093
+ import { appendFile, readFile as readFile11 } from "fs/promises";
3398
4094
  function isEventPhase(value) {
3399
4095
  return typeof value === "string" && EVENT_PHASES.includes(value);
3400
4096
  }
@@ -3471,10 +4167,11 @@ async function handleCommand(commandId, prompt2, cli, config, send) {
3471
4167
  }
3472
4168
  var init_request_handler = __esm(() => {
3473
4169
  init_artifact_reader();
4170
+ init_cli_executor();
3474
4171
  });
3475
4172
 
3476
4173
  // src/agent/connection.ts
3477
- import { join as join14 } from "path";
4174
+ import { join as join22 } from "path";
3478
4175
  function buildWsUrl(portalUrl) {
3479
4176
  return portalUrl.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws/agent";
3480
4177
  }
@@ -3488,7 +4185,7 @@ function buildAuthMessage(opts) {
3488
4185
  };
3489
4186
  }
3490
4187
  async function connectToPortal(config) {
3491
- await Bun.write(join14(config.harenDir, ".agent.pid"), process.pid.toString());
4188
+ await Bun.write(join22(config.harenDir, ".agent.pid"), process.pid.toString());
3492
4189
  setupCleanup(config.harenDir);
3493
4190
  try {
3494
4191
  await connectWebSocket(config);
@@ -3644,7 +4341,7 @@ async function connectPolling(config) {
3644
4341
  }
3645
4342
  }
3646
4343
  function setupCleanup(harenDir) {
3647
- const pidPath = join14(harenDir, ".agent.pid");
4344
+ const pidPath = join22(harenDir, ".agent.pid");
3648
4345
  const cleanup = async () => {
3649
4346
  console.log("Agent shutting down...");
3650
4347
  const { unlink } = await import("fs/promises");
@@ -3657,7 +4354,7 @@ function setupCleanup(harenDir) {
3657
4354
  var init_connection = () => {};
3658
4355
 
3659
4356
  // src/commands/agent.ts
3660
- import { join as join15 } from "path";
4357
+ import { join as join23 } from "path";
3661
4358
  function readLine2(question) {
3662
4359
  process.stdout.write(question);
3663
4360
  return new Promise((resolve) => {
@@ -3751,7 +4448,7 @@ async function startAgent(harenDir) {
3751
4448
  config = { portalUrl, teamCode, userId, userName };
3752
4449
  await writeAgentConfig(harenDir, config);
3753
4450
  console.log(`
3754
- Config saved to ${join15(harenDir, ".agent.json")}`);
4451
+ Config saved to ${join23(harenDir, ".agent.json")}`);
3755
4452
  }
3756
4453
  const gitRemoteUrl = await getRemoteUrl(harenDir);
3757
4454
  if (!gitRemoteUrl) {
@@ -3775,7 +4472,7 @@ Config saved to ${join15(harenDir, ".agent.json")}`);
3775
4472
  });
3776
4473
  }
3777
4474
  async function stopAgent(harenDir) {
3778
- const pidFile = Bun.file(join15(harenDir, ".agent.pid"));
4475
+ const pidFile = Bun.file(join23(harenDir, ".agent.pid"));
3779
4476
  if (!await pidFile.exists()) {
3780
4477
  console.log("Agent is not running.");
3781
4478
  return;
@@ -3788,7 +4485,7 @@ async function stopAgent(harenDir) {
3788
4485
  console.log("Agent process not found. Cleaning up.");
3789
4486
  }
3790
4487
  const { unlink } = await import("fs/promises");
3791
- await unlink(join15(harenDir, ".agent.pid")).catch(() => {});
4488
+ await unlink(join23(harenDir, ".agent.pid")).catch(() => {});
3792
4489
  }
3793
4490
  async function showStatus(harenDir) {
3794
4491
  const config = await readAgentConfig(harenDir);
@@ -3796,7 +4493,7 @@ async function showStatus(harenDir) {
3796
4493
  console.log("Agent is not configured. Run 'haren agent start' first.");
3797
4494
  return;
3798
4495
  }
3799
- const pidFile = Bun.file(join15(harenDir, ".agent.pid"));
4496
+ const pidFile = Bun.file(join23(harenDir, ".agent.pid"));
3800
4497
  const isRunning = await pidFile.exists();
3801
4498
  console.log(`Portal: ${config.portalUrl}`);
3802
4499
  console.log(`Team: ${config.teamCode}`);
@@ -3913,21 +4610,21 @@ var init_updates = __esm(() => {
3913
4610
  });
3914
4611
 
3915
4612
  // src/plugins/runner.ts
3916
- import { existsSync as existsSync14 } from "fs";
3917
- import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile11 } from "fs/promises";
3918
- import { isAbsolute as isAbsolute3, join as join16 } from "path";
4613
+ import { existsSync as existsSync23 } from "fs";
4614
+ import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile12 } from "fs/promises";
4615
+ import { isAbsolute as isAbsolute3, join as join24 } from "path";
3919
4616
  function tasksPath(input, harenDir) {
3920
4617
  if (typeof input.tasksFile !== "string")
3921
4618
  return;
3922
- return isAbsolute3(input.tasksFile) ? input.tasksFile : join16(harenDir, input.tasksFile);
4619
+ return isAbsolute3(input.tasksFile) ? input.tasksFile : join24(harenDir, input.tasksFile);
3923
4620
  }
3924
4621
  async function loadPlannedTasks(input, harenDir) {
3925
4622
  const path = tasksPath(input, harenDir);
3926
- if (!path || !existsSync14(path))
4623
+ if (!path || !existsSync23(path))
3927
4624
  return [];
3928
- const tasks = parseTasksFile(await readFile11(path, "utf-8"));
3929
- const progressPath = join16(harenDir, "progress.json");
3930
- if (typeof input.module !== "string" || !existsSync14(progressPath))
4625
+ const tasks = parseTasksFile(await readFile12(path, "utf-8"));
4626
+ const progressPath = join24(harenDir, "progress.json");
4627
+ if (typeof input.module !== "string" || !existsSync23(progressPath))
3931
4628
  return tasks;
3932
4629
  try {
3933
4630
  const mod = (await readProgress(progressPath)).modules[input.module];
@@ -3946,8 +4643,8 @@ async function buildPayload(hook, input, harenDir) {
3946
4643
  return payload;
3947
4644
  }
3948
4645
  async function addPlannedFeatures(input, harenDir) {
3949
- const progressPath = join16(harenDir, "progress.json");
3950
- if (typeof input.module !== "string" || !existsSync14(progressPath))
4646
+ const progressPath = join24(harenDir, "progress.json");
4647
+ if (typeof input.module !== "string" || !existsSync23(progressPath))
3951
4648
  return;
3952
4649
  const tasks = await loadPlannedTasks(input, harenDir);
3953
4650
  const progress = await readProgress(progressPath);
@@ -3965,7 +4662,7 @@ async function addPlannedFeatures(input, harenDir) {
3965
4662
  await writeProgress(progressPath, progress);
3966
4663
  }
3967
4664
  async function logError(dir, hook, error) {
3968
- await appendFile2(join16(dir, "errors.log"), `${new Date().toISOString()} ${hook}: ${error}
4665
+ await appendFile2(join24(dir, "errors.log"), `${new Date().toISOString()} ${hook}: ${error}
3969
4666
  `).catch(() => {});
3970
4667
  }
3971
4668
  async function runHook(hook, input, o) {
@@ -4097,8 +4794,8 @@ async function runHookAndApply(hook, input, o) {
4097
4794
  updates.push(...out.updates);
4098
4795
  }
4099
4796
  try {
4100
- const progressPath = join16(o.harenDir, "progress.json");
4101
- if (updates.length > 0 && existsSync14(progressPath)) {
4797
+ const progressPath = join24(o.harenDir, "progress.json");
4798
+ if (updates.length > 0 && existsSync23(progressPath)) {
4102
4799
  const result = applyUpdates(await readProgress(progressPath), updates);
4103
4800
  if (result.applied.length > 0)
4104
4801
  await writeProgress(progressPath, result.progress);
@@ -4120,12 +4817,12 @@ var init_runner = __esm(() => {
4120
4817
  });
4121
4818
 
4122
4819
  // src/commands/plugin.ts
4123
- import { readFile as readFile12 } from "fs/promises";
4124
- import { join as join17 } from "path";
4820
+ import { readFile as readFile13 } from "fs/promises";
4821
+ import { join as join25 } from "path";
4125
4822
  function parsePluginArgs(args) {
4126
4823
  const sub = args[0];
4127
4824
  if (!SUBS.includes(sub))
4128
- throw new Error(USAGE);
4825
+ throw new Error(USAGE2);
4129
4826
  const yes = args.includes("--yes") || args.includes("-y");
4130
4827
  const target = args[1] && !args[1].startsWith("-") ? args[1] : undefined;
4131
4828
  if ((sub === "add" || sub === "remove") && !target)
@@ -4201,7 +4898,7 @@ async function plugin(args) {
4201
4898
  process.exit(1);
4202
4899
  }
4203
4900
  const { workspaceDir, harenDir } = location;
4204
- const manifest = parseManifest(await readFile12(join17(harenDir, "manifest.yaml"), "utf-8"));
4901
+ const manifest = parseManifest(await readFile13(join25(harenDir, "manifest.yaml"), "utf-8"));
4205
4902
  const ctx = {
4206
4903
  workspaceDir,
4207
4904
  harenDir,
@@ -4256,7 +4953,7 @@ async function plugin(args) {
4256
4953
  } catch (err) {
4257
4954
  console.log(` ${name}: ${err.message}`);
4258
4955
  }
4259
- const log = Bun.file(join17(dir, "errors.log"));
4956
+ const log = Bun.file(join25(dir, "errors.log"));
4260
4957
  if (await log.exists()) {
4261
4958
  const last = (await log.text()).trim().split(`
4262
4959
  `).slice(-3);
@@ -4268,7 +4965,7 @@ async function plugin(args) {
4268
4965
  }
4269
4966
  }
4270
4967
  }
4271
- var SUBS, USAGE = "Usage: haren plugin add <name|source> | remove <name> | list | run <hook> [--payload <json>] | doctor";
4968
+ var SUBS, USAGE2 = "Usage: haren plugin add <name|source> | remove <name> | list | run <hook> [--payload <json>] | doctor";
4272
4969
  var init_plugin = __esm(() => {
4273
4970
  init_manifest2();
4274
4971
  init_install();
@@ -4281,8 +4978,8 @@ var init_plugin = __esm(() => {
4281
4978
  });
4282
4979
 
4283
4980
  // src/plugins/adapter-read.ts
4284
- import { existsSync as existsSync15 } from "fs";
4285
- import { join as join18 } from "path";
4981
+ import { existsSync as existsSync24 } from "fs";
4982
+ import { join as join26 } from "path";
4286
4983
  function adapterMissingMessage(name) {
4287
4984
  return `Adapter '${name}' is named in manifest.yaml but not installed. Run \`haren plugin add <source>\`, or remove migration.adapter to work by hand.`;
4288
4985
  }
@@ -4291,7 +4988,7 @@ async function readAdapter(harenDir, name) {
4291
4988
  if (!plugins[name])
4292
4989
  return null;
4293
4990
  const dir = pluginDir(harenDir, name);
4294
- if (!existsSync15(join18(dir, "haren-plugin.json")))
4991
+ if (!existsSync24(join26(dir, "haren-plugin.json")))
4295
4992
  return null;
4296
4993
  try {
4297
4994
  return (await readInstalledManifest(dir)).adapter ?? null;
@@ -4305,9 +5002,9 @@ var init_adapter_read = __esm(() => {
4305
5002
  });
4306
5003
 
4307
5004
  // src/commands/track.ts
4308
- import { existsSync as existsSync16 } from "fs";
4309
- import { mkdir as mkdir9, readdir as readdir7, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
4310
- import { dirname as dirname5, join as join19, relative as relative4, sep as sep4 } from "path";
5005
+ import { existsSync as existsSync25 } from "fs";
5006
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile14, writeFile as writeFile8 } from "fs/promises";
5007
+ import { dirname as dirname5, join as join27, relative as relative4, sep as sep4 } from "path";
4311
5008
  function parseTrackArgs(args) {
4312
5009
  const positional = [];
4313
5010
  const flags = {};
@@ -4316,6 +5013,10 @@ function parseTrackArgs(args) {
4316
5013
  if (arg.startsWith("--")) {
4317
5014
  const eq = arg.indexOf("=");
4318
5015
  const name = eq === -1 ? arg : arg.slice(0, eq);
5016
+ if (BOOL_FLAGS.includes(name) && eq === -1) {
5017
+ flags[name.slice(2)] = "true";
5018
+ continue;
5019
+ }
4319
5020
  if (!VALUE_FLAGS.includes(name))
4320
5021
  throw new Error(`Unknown option: ${name}`);
4321
5022
  const value = eq === -1 ? args[++i] : arg.slice(eq + 1);
@@ -4331,9 +5032,9 @@ function parseTrackArgs(args) {
4331
5032
  function pathsFor(harenDir) {
4332
5033
  return {
4333
5034
  harenDir,
4334
- progress: join19(harenDir, "progress.json"),
4335
- events: join19(harenDir, "events", "events.jsonl"),
4336
- registry: join19(harenDir, "artifacts", "_registry", "artifact-index.md")
5035
+ progress: join27(harenDir, "progress.json"),
5036
+ events: join27(harenDir, "events", "events.jsonl"),
5037
+ registry: join27(harenDir, "artifacts", "_registry", "artifact-index.md")
4337
5038
  };
4338
5039
  }
4339
5040
  async function emit(paths, event) {
@@ -4353,7 +5054,7 @@ function requireModule(progress, name) {
4353
5054
  }
4354
5055
  }
4355
5056
  async function loadProgress(paths) {
4356
- if (!existsSync16(paths.progress))
5057
+ if (!existsSync25(paths.progress))
4357
5058
  throw new Error(`No progress.json in ${paths.harenDir}`);
4358
5059
  return readProgress(paths.progress);
4359
5060
  }
@@ -4379,7 +5080,7 @@ async function track(args, cwd = process.cwd()) {
4379
5080
  case "unit":
4380
5081
  return trackUnit(paths, rest);
4381
5082
  case "commit":
4382
- return trackCommit(paths, rest);
5083
+ return trackCommit(paths, rest, flags);
4383
5084
  case "depends":
4384
5085
  return trackDepends(paths, rest);
4385
5086
  case "artifact":
@@ -4402,19 +5103,19 @@ async function trackUiMode(paths, rest) {
4402
5103
  if (!UI_MODES.includes(mode)) {
4403
5104
  throw new Error(`Invalid ui mode '${mode}'. Use ${UI_MODES.join(", ")}.`);
4404
5105
  }
4405
- const manifestPath = join19(paths.harenDir, "manifest.yaml");
4406
- if (!existsSync16(manifestPath))
5106
+ const manifestPath = join27(paths.harenDir, "manifest.yaml");
5107
+ if (!existsSync25(manifestPath))
4407
5108
  throw new Error(`No manifest.yaml in ${paths.harenDir}`);
4408
- const text = await readFile13(manifestPath, "utf-8");
4409
- await writeFile7(manifestPath, setUiModeText(text, mode));
5109
+ const text = await readFile14(manifestPath, "utf-8");
5110
+ await writeFile8(manifestPath, setUiModeText(text, mode));
4410
5111
  await emit(paths, { type: "ui-mode", mode });
4411
5112
  console.log(` UI mockups mode: ${mode}.`);
4412
5113
  }
4413
5114
  async function loadMigration(paths) {
4414
- const manifestPath = join19(paths.harenDir, "manifest.yaml");
4415
- if (!existsSync16(manifestPath))
5115
+ const manifestPath = join27(paths.harenDir, "manifest.yaml");
5116
+ if (!existsSync25(manifestPath))
4416
5117
  return null;
4417
- return readMigrationConfig(parseManifest(await readFile13(manifestPath, "utf-8")));
5118
+ return readMigrationConfig(parseManifest(await readFile14(manifestPath, "utf-8")));
4418
5119
  }
4419
5120
  async function adapterCommands(paths, migration) {
4420
5121
  if (!migration.adapter)
@@ -4464,17 +5165,25 @@ async function moduleMeta(paths, flags) {
4464
5165
  if (!repos.length)
4465
5166
  throw new Error(`Missing --repos <key1,key2>.
4466
5167
  ${TRACK_USAGE}`);
4467
- const manifestPath = join19(paths.harenDir, "manifest.yaml");
4468
- const manifest = existsSync16(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4469
- const declared = Object.keys(normalizeRepos(manifest.repos));
4470
- const unknown = repos.filter((r) => !declared.includes(r));
4471
- if (unknown.length) {
4472
- throw new Error(`Unknown repo key: ${unknown.join(", ")}. manifest.yaml repos: ${declared.length ? declared.join(", ") : "(none)"}`);
4473
- }
5168
+ await checkRepoKeys(paths, repos);
4474
5169
  meta.repos = repos;
4475
5170
  }
4476
5171
  return meta;
4477
5172
  }
5173
+ async function allowedRepoKeys(paths) {
5174
+ const manifestPath = join27(paths.harenDir, "manifest.yaml");
5175
+ const manifest = existsSync25(manifestPath) ? parseManifest(await readFile14(manifestPath, "utf-8")) : {};
5176
+ const declared = Object.keys(normalizeRepos(manifest.repos));
5177
+ return { allowed: declared.length ? declared : ["default"], empty: !declared.length };
5178
+ }
5179
+ async function checkRepoKeys(paths, keys) {
5180
+ const { allowed, empty } = await allowedRepoKeys(paths);
5181
+ const declared = empty ? [] : allowed;
5182
+ const unknown = keys.filter((k) => !allowed.includes(k));
5183
+ if (unknown.length) {
5184
+ throw new Error(`Unknown repo key: ${unknown.join(", ")}. Allowed: ${allowed.join(", ")}${declared.length ? "" : " (manifest.yaml repos is empty)"}`);
5185
+ }
5186
+ }
4478
5187
  async function trackStatus(paths, rest, flags) {
4479
5188
  const module = need(rest[0], "<module>");
4480
5189
  const to = need(rest[1], "<status>");
@@ -4565,10 +5274,13 @@ async function trackFeature(paths, rest) {
4565
5274
  await emit(paths, { type: "feature-status", module, feature, from, to: status });
4566
5275
  console.log(` ${module}/${feature}: ${from ?? "(new)"} \u2192 ${status}`);
4567
5276
  }
4568
- async function trackCommit(paths, rest) {
5277
+ async function trackCommit(paths, rest, flags = {}) {
4569
5278
  const module = need(rest[0], "<module>");
4570
5279
  const repo = need(rest[1], "<repoKey>");
5280
+ if (flags.remove)
5281
+ return removeCommitKey(paths, module, repo);
4571
5282
  const sha = need(rest[2], "<sha>");
5283
+ await checkRepoKeys(paths, [repo]);
4572
5284
  const progress = await loadProgress(paths);
4573
5285
  requireModule(progress, module);
4574
5286
  const mod = progress.modules[module];
@@ -4590,6 +5302,31 @@ async function trackCommit(paths, rest) {
4590
5302
  await emit(paths, { type: "commit", module, repo, sha });
4591
5303
  console.log(` ${module}: lastCommit.${repo} = ${sha}`);
4592
5304
  }
5305
+ async function removeCommitKey(paths, module, repo) {
5306
+ const progress = await loadProgress(paths);
5307
+ requireModule(progress, module);
5308
+ const mod = progress.modules[module];
5309
+ const lastCommit = { ...mod.lastCommit ?? {} };
5310
+ const had = Object.hasOwn(lastCommit, repo) || (mod.repos ?? []).includes(repo);
5311
+ if (!had)
5312
+ throw new Error(`Module '${module}' has no repo key '${repo}'.`);
5313
+ delete lastCommit[repo];
5314
+ const next = {
5315
+ ...progress,
5316
+ modules: {
5317
+ ...progress.modules,
5318
+ [module]: {
5319
+ ...mod,
5320
+ lastCommit,
5321
+ repos: (mod.repos ?? []).filter((r) => r !== repo),
5322
+ lastUpdated: new Date().toISOString()
5323
+ }
5324
+ }
5325
+ };
5326
+ await writeProgress(paths.progress, next);
5327
+ await emit(paths, { type: "commit", module, repo, sha: null, removed: true });
5328
+ console.log(` ${module}: removed repo key ${repo}`);
5329
+ }
4593
5330
  function findCycle(graph, module, deps) {
4594
5331
  const next = { ...graph, [module]: deps };
4595
5332
  const visited = new Set([module]);
@@ -4665,9 +5402,9 @@ async function trackArtifact(paths, rest, flags) {
4665
5402
  const progress = await loadProgress(paths);
4666
5403
  requireModule(progress, flags.module);
4667
5404
  }
4668
- const existing = existsSync16(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
5405
+ const existing = existsSync25(paths.registry) ? await readFile14(paths.registry, "utf-8") : "";
4669
5406
  await mkdir9(dirname5(paths.registry), { recursive: true });
4670
- await writeFile7(paths.registry, upsertArtifactRow(existing, [id, artifactType, module, status, path]));
5407
+ await writeFile8(paths.registry, upsertArtifactRow(existing, [id, artifactType, module, status, path]));
4671
5408
  await emit(paths, {
4672
5409
  type: "artifact",
4673
5410
  id,
@@ -4729,14 +5466,14 @@ async function trackOverride(paths, rest, flags) {
4729
5466
  }
4730
5467
  }
4731
5468
  async function listArtifactFiles(artifactsDir) {
4732
- if (!existsSync16(artifactsDir))
5469
+ if (!existsSync25(artifactsDir))
4733
5470
  return [];
4734
5471
  const out = [];
4735
5472
  const walk = async (dir) => {
4736
5473
  for (const entry of await readdir7(dir, { withFileTypes: true })) {
4737
5474
  if (entry.name.startsWith("."))
4738
5475
  continue;
4739
- const full = join19(dir, entry.name);
5476
+ const full = join27(dir, entry.name);
4740
5477
  if (entry.isDirectory()) {
4741
5478
  if (dir === artifactsDir && UNTRACKED_DIRS.has(entry.name))
4742
5479
  continue;
@@ -4770,14 +5507,15 @@ async function checkWorkspace(paths) {
4770
5507
  const errors = [];
4771
5508
  const warnings = [];
4772
5509
  const progress = await loadProgress(paths);
4773
- const manifestPath = join19(paths.harenDir, "manifest.yaml");
4774
- const manifest = existsSync16(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4775
- const declared = new Set(Object.keys(normalizeRepos(manifest.repos)));
5510
+ const manifestPath = join27(paths.harenDir, "manifest.yaml");
5511
+ const manifest = existsSync25(manifestPath) ? parseManifest(await readFile14(manifestPath, "utf-8")) : {};
5512
+ const { allowed: allowedKeys, empty: noRepos } = await allowedRepoKeys(paths);
5513
+ const declared = new Set(allowedKeys);
4776
5514
  for (const [name, mod] of Object.entries(progress.modules)) {
4777
5515
  const used = new Set([...mod.repos ?? [], ...Object.keys(mod.lastCommit ?? {})]);
4778
5516
  for (const key of used) {
4779
5517
  if (!declared.has(key)) {
4780
- errors.push(`module '${name}' uses repo '${key}', but manifest.yaml has no repos.${key} entry`);
5518
+ errors.push(`module '${name}' uses repo '${key}', but ${noRepos ? "manifest.yaml repos is empty, so the only key is 'default'" : `manifest.yaml has no repos.${key} entry`}. Remove a stale key with: haren track commit ${name} ${key} --remove`);
4781
5519
  }
4782
5520
  }
4783
5521
  }
@@ -4810,10 +5548,10 @@ async function checkWorkspace(paths) {
4810
5548
  errors.push(`module '${name}' unit '${unit}' does not match migration.unitId`);
4811
5549
  }
4812
5550
  if (mig.adapter && unitAtLeast(status, "spec-approved")) {
4813
- const gate = join19(paths.harenDir, "artifacts", "02-discovery", "units", unit, "gate.json");
5551
+ const gate = join27(paths.harenDir, "artifacts", "02-discovery", "units", unit, "gate.json");
4814
5552
  let ok = false;
4815
5553
  try {
4816
- ok = JSON.parse(await readFile13(gate, "utf-8")).pass === true;
5554
+ ok = JSON.parse(await readFile14(gate, "utf-8")).pass === true;
4817
5555
  } catch {
4818
5556
  ok = false;
4819
5557
  }
@@ -4824,10 +5562,10 @@ async function checkWorkspace(paths) {
4824
5562
  }
4825
5563
  }
4826
5564
  }
4827
- const registryText = existsSync16(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
5565
+ const registryText = existsSync25(paths.registry) ? await readFile14(paths.registry, "utf-8") : "";
4828
5566
  const rows = parseRegistryRows(registryText);
4829
5567
  const indexed = new Set(rows.map((r) => normalizeArtifactPath(r.path)));
4830
- const artifactsDir = join19(paths.harenDir, "artifacts");
5568
+ const artifactsDir = join27(paths.harenDir, "artifacts");
4831
5569
  for (const file of await listArtifactFiles(artifactsDir)) {
4832
5570
  const rel = relative4(artifactsDir, file).split(sep4).join("/");
4833
5571
  if (!indexed.has(rel)) {
@@ -4836,7 +5574,7 @@ async function checkWorkspace(paths) {
4836
5574
  }
4837
5575
  for (const row of rows) {
4838
5576
  const rel = normalizeArtifactPath(row.path);
4839
- if (!existsSync16(join19(artifactsDir, rel))) {
5577
+ if (!existsSync25(join27(artifactsDir, rel))) {
4840
5578
  errors.push(`index row ${row.id} points to missing file artifacts/${rel}`);
4841
5579
  }
4842
5580
  }
@@ -4864,14 +5602,15 @@ var TRACK_USAGE = `Usage:
4864
5602
  haren track feature <module> <feature> [status]
4865
5603
  haren track unit <module> <unit> <status>
4866
5604
  haren track commit <module> <repoKey> <sha>
5605
+ haren track commit <module> <repoKey> --remove
4867
5606
  haren track depends <module> [dep ...]
4868
5607
  haren track artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]
4869
5608
  haren track event <type> [--module m] [--phase p] [--feature f] [--data '<json object>']
4870
5609
  haren track override on --reason "<text>" [--hours <n>]
4871
5610
  haren track override off
4872
- haren track ui-mode <ask|ascii|browser>
5611
+ haren track ui-mode <ask|ascii|browser|artifact>
4873
5612
  haren track check
4874
- Options: --haren-dir <path>`, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
5613
+ Options: --haren-dir <path>`, BOOL_FLAGS, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
4875
5614
  |----|------|--------|--------|------|`, UNTRACKED_DIRS;
4876
5615
  var init_track = __esm(() => {
4877
5616
  init_manifest();
@@ -4879,6 +5618,7 @@ var init_track = __esm(() => {
4879
5618
  init_progress();
4880
5619
  init_adapter_read();
4881
5620
  init_resolve();
5621
+ BOOL_FLAGS = ["--remove"];
4882
5622
  VALUE_FLAGS = [
4883
5623
  "--haren-dir",
4884
5624
  "--type",
@@ -4959,9 +5699,9 @@ var init_adapter_run = __esm(() => {
4959
5699
  });
4960
5700
 
4961
5701
  // src/commands/migrate.ts
4962
- import { existsSync as existsSync17 } from "fs";
4963
- import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile8 } from "fs/promises";
4964
- import { dirname as dirname6, join as join20, resolve as resolve11 } from "path";
5702
+ import { existsSync as existsSync26 } from "fs";
5703
+ import { mkdir as mkdir10, readFile as readFile15, writeFile as writeFile9 } from "fs/promises";
5704
+ import { dirname as dirname6, join as join28, resolve as resolve12 } from "path";
4965
5705
  function parseMigrateArgs(args) {
4966
5706
  const positional = [];
4967
5707
  const flags = {};
@@ -5054,7 +5794,7 @@ async function loadContext(harenDir) {
5054
5794
  const migration = await loadMigration(paths);
5055
5795
  if (!migration)
5056
5796
  throw new Error("haren migrate needs mode: migration in manifest.yaml");
5057
- const manifest = parseManifest(await readFile14(join20(harenDir, "manifest.yaml"), "utf-8"));
5797
+ const manifest = parseManifest(await readFile15(join28(harenDir, "manifest.yaml"), "utf-8"));
5058
5798
  const legacy = legacyRepo(manifest);
5059
5799
  if (!legacy)
5060
5800
  throw new Error("haren migrate needs a repo with role: legacy in manifest.yaml");
@@ -5068,7 +5808,7 @@ async function loadContext(harenDir) {
5068
5808
  migration,
5069
5809
  adapterName: migration.adapter,
5070
5810
  adapter,
5071
- legacyRoot: resolve11(harenDir, legacy[1].path)
5811
+ legacyRoot: resolve12(harenDir, legacy[1].path)
5072
5812
  };
5073
5813
  }
5074
5814
  async function migrate(args, cwd = process.cwd()) {
@@ -5103,8 +5843,8 @@ async function inventory(ctx, moduleFlag) {
5103
5843
  const badIds = raw.units.filter((u) => !ctx.migration.unitId.test(u.id)).map((u) => u.id);
5104
5844
  const out = { units: raw.units.filter((u) => ctx.migration.unitId.test(u.id)) };
5105
5845
  const mapRel = "artifacts/02-discovery/unit-map.md";
5106
- const mapPath = join20(ctx.paths.harenDir, mapRel);
5107
- const previous = existsSync17(mapPath) ? await readFile14(mapPath, "utf-8") : "";
5846
+ const mapPath = join28(ctx.paths.harenDir, mapRel);
5847
+ const previous = existsSync26(mapPath) ? await readFile15(mapPath, "utf-8") : "";
5108
5848
  const known = parseUnitMap(previous);
5109
5849
  const moduleOf = {};
5110
5850
  const units = [];
@@ -5129,7 +5869,7 @@ async function inventory(ctx, moduleFlag) {
5129
5869
  moduleOf[id] = row.module;
5130
5870
  }
5131
5871
  await mkdir10(dirname6(mapPath), { recursive: true });
5132
- await writeFile8(mapPath, renderUnitMap(units, moduleOf, previous));
5872
+ await writeFile9(mapPath, renderUnitMap(units, moduleOf, previous));
5133
5873
  const added = [];
5134
5874
  const skipped = [];
5135
5875
  for (const u of out.units) {
@@ -5148,10 +5888,10 @@ async function inventory(ctx, moduleFlag) {
5148
5888
  for (const [module, unit] of added) {
5149
5889
  await emit(ctx.paths, { type: "unit-status", module, unit, from: null, to: "inventoried" });
5150
5890
  }
5151
- const registry = existsSync17(ctx.paths.registry) ? await readFile14(ctx.paths.registry, "utf-8") : "";
5891
+ const registry = existsSync26(ctx.paths.registry) ? await readFile15(ctx.paths.registry, "utf-8") : "";
5152
5892
  if (!/^\|\s*UNITMAP-001\s*\|/m.test(registry)) {
5153
5893
  await mkdir10(dirname6(ctx.paths.registry), { recursive: true });
5154
- await writeFile8(ctx.paths.registry, upsertArtifactRow(registry, ["UNITMAP-001", "unit-map", "-", "draft", mapRel]));
5894
+ await writeFile9(ctx.paths.registry, upsertArtifactRow(registry, ["UNITMAP-001", "unit-map", "-", "draft", mapRel]));
5155
5895
  }
5156
5896
  console.log(` inventory: ${fresh} new, ${out.units.length - fresh} known, ${gone.length} disappeared`);
5157
5897
  if (gone.length)
@@ -5190,8 +5930,8 @@ async function gate(ctx, unit, approve) {
5190
5930
  const progress = await readProgress(ctx.paths.progress);
5191
5931
  const module = moduleOfUnit(progress, unit);
5192
5932
  const unitDir = unitDirFor(ctx, unit);
5193
- const specPath = join20(unitDir, "spec.md");
5194
- if (!existsSync17(specPath))
5933
+ const specPath = join28(unitDir, "spec.md");
5934
+ if (!existsSync26(specPath))
5195
5935
  throw new Error(`No spec at ${specPath}. Write the spec first.`);
5196
5936
  const from = progress.modules[module].units[unit];
5197
5937
  if (from !== "spec-draft" && from !== "spec-approved") {
@@ -5204,7 +5944,7 @@ async function gate(ctx, unit, approve) {
5204
5944
  console.error(` adapter error: ${e instanceof Error ? e.message : String(e)}`);
5205
5945
  throw e;
5206
5946
  }
5207
- await writeFile8(join20(unitDir, "gate.json"), `${JSON.stringify({ ...out, ranAt: new Date().toISOString() }, null, 2)}
5947
+ await writeFile9(join28(unitDir, "gate.json"), `${JSON.stringify({ ...out, ranAt: new Date().toISOString() }, null, 2)}
5208
5948
  `);
5209
5949
  if (!out.pass) {
5210
5950
  for (const f of out.findings)
@@ -5242,7 +5982,7 @@ var MIGRATE_USAGE = `Usage:
5242
5982
  haren migrate extract <unit>
5243
5983
  haren migrate gate <unit> [--approve]
5244
5984
  Options: --haren-dir <path>`, UNIT_MAP_HEADER = `| Unit | Parent | Family | Title | Module |
5245
- |------|--------|--------|-------|--------|`, cell = (v) => v ? v.replaceAll("|", "\\|") : "-", unitDirFor = (ctx, unit) => join20(ctx.paths.harenDir, "artifacts", "02-discovery", "units", unit);
5985
+ |------|--------|--------|-------|--------|`, cell = (v) => v ? v.replaceAll("|", "\\|") : "-", unitDirFor = (ctx, unit) => join28(ctx.paths.harenDir, "artifacts", "02-discovery", "units", unit);
5246
5986
  var init_migrate = __esm(() => {
5247
5987
  init_manifest();
5248
5988
  init_progress();
@@ -5676,17 +6416,17 @@ import { randomBytes, timingSafeEqual } from "crypto";
5676
6416
  import {
5677
6417
  appendFileSync,
5678
6418
  chmodSync,
5679
- existsSync as existsSync18,
6419
+ existsSync as existsSync27,
5680
6420
  lstatSync,
5681
6421
  mkdirSync,
5682
6422
  readdirSync,
5683
- readFileSync as readFileSync2,
6423
+ readFileSync as readFileSync3,
5684
6424
  realpathSync as realpathSync2,
5685
6425
  rmSync,
5686
6426
  statSync,
5687
6427
  writeFileSync
5688
6428
  } from "fs";
5689
- import { basename as basename5, extname, join as join21, sep as sep5 } from "path";
6429
+ import { basename as basename5, extname, join as join29, sep as sep5 } from "path";
5690
6430
  function makePrivateDir(dir) {
5691
6431
  mkdirSync(dir, { recursive: true, mode: 448 });
5692
6432
  try {
@@ -5724,7 +6464,7 @@ function newestScreen(contentDir) {
5724
6464
  for (const name of names) {
5725
6465
  if (name.startsWith(".") || !name.endsWith(".html"))
5726
6466
  continue;
5727
- const fp = join21(contentDir, name);
6467
+ const fp = join29(contentDir, name);
5728
6468
  if (!isRegularFileInside(contentDir, fp))
5729
6469
  continue;
5730
6470
  const mtime = statSync(fp).mtimeMs;
@@ -5764,14 +6504,14 @@ function urlHostForHttp(host) {
5764
6504
  return host.includes(":") ? `[${host}]` : host;
5765
6505
  }
5766
6506
  async function startCompanion(opts) {
5767
- const contentDir = join21(opts.sessionDir, "content");
5768
- const stateDir = join21(opts.sessionDir, "state");
6507
+ const contentDir = join29(opts.sessionDir, "content");
6508
+ const stateDir = join29(opts.sessionDir, "state");
5769
6509
  for (const dir of [opts.sessionDir, contentDir, stateDir])
5770
6510
  makePrivateDir(dir);
5771
- const stoppedFile = join21(stateDir, "server-stopped");
5772
- const eventsFile = join21(stateDir, "events");
6511
+ const stoppedFile = join29(stateDir, "server-stopped");
6512
+ const eventsFile = join29(stateDir, "events");
5773
6513
  rmSync(stoppedFile, { force: true });
5774
- if (existsSync18(eventsFile))
6514
+ if (existsSync27(eventsFile))
5775
6515
  chmodSync(eventsFile, 384);
5776
6516
  const key = opts.key ?? randomBytes(16).toString("hex");
5777
6517
  const idleTimeoutMs = opts.idleTimeoutMs ?? 240 * 60000;
@@ -5818,7 +6558,7 @@ async function startCompanion(opts) {
5818
6558
  return respond("Not found", "text/plain", 404, extra);
5819
6559
  if (url.pathname === "/") {
5820
6560
  const screen = newestScreen(contentDir);
5821
- const raw = screen ? readFileSync2(screen, "utf-8") : null;
6561
+ const raw = screen ? readFileSync3(screen, "utf-8") : null;
5822
6562
  const html = raw === null ? wrapInFrame(WAITING_CONTENT) : isFullDocument(raw) ? injectHelper(raw) : wrapInFrame(raw);
5823
6563
  return respond(html, "text/html; charset=utf-8", 200, extra);
5824
6564
  }
@@ -5832,12 +6572,12 @@ async function startCompanion(opts) {
5832
6572
  } catch {
5833
6573
  return respond("Not found", "text/plain", 404, extra);
5834
6574
  }
5835
- const fp = join21(contentDir, name);
6575
+ const fp = join29(contentDir, name);
5836
6576
  if (!name || name.startsWith(".") || !isRegularFileInside(contentDir, fp)) {
5837
6577
  return respond("Not found", "text/plain", 404, extra);
5838
6578
  }
5839
6579
  const type = MIME_TYPES[extname(fp).toLowerCase()] ?? "application/octet-stream";
5840
- return respond(readFileSync2(fp), type, 200, extra);
6580
+ return respond(readFileSync3(fp), type, 200, extra);
5841
6581
  }
5842
6582
  return respond("Not found", "text/plain", 404, extra);
5843
6583
  },
@@ -5906,7 +6646,7 @@ async function startCompanion(opts) {
5906
6646
  screen_dir: contentDir,
5907
6647
  state_dir: stateDir
5908
6648
  };
5909
- writePrivateFile(join21(stateDir, "server-info"), `${JSON.stringify(info)}
6649
+ writePrivateFile(join29(stateDir, "server-info"), `${JSON.stringify(info)}
5910
6650
  `);
5911
6651
  async function stop(reason = "stopped") {
5912
6652
  if (stopped)
@@ -5915,7 +6655,7 @@ async function startCompanion(opts) {
5915
6655
  if (idleTimer)
5916
6656
  clearTimeout(idleTimer);
5917
6657
  clearInterval(poll);
5918
- if (existsSync18(stateDir)) {
6658
+ if (existsSync27(stateDir)) {
5919
6659
  writeFileSync(stoppedFile, `${JSON.stringify({ reason })}
5920
6660
  `);
5921
6661
  }
@@ -5958,16 +6698,16 @@ var init_server = __esm(() => {
5958
6698
  // src/commands/companion.ts
5959
6699
  import { randomBytes as randomBytes2 } from "crypto";
5960
6700
  import {
5961
- existsSync as existsSync19,
6701
+ existsSync as existsSync28,
5962
6702
  readdirSync as readdirSync2,
5963
- readFileSync as readFileSync3,
6703
+ readFileSync as readFileSync4,
5964
6704
  renameSync,
5965
6705
  rmSync as rmSync2,
5966
6706
  statSync as statSync2,
5967
6707
  writeFileSync as writeFileSync2
5968
6708
  } from "fs";
5969
6709
  import { spawnSync } from "child_process";
5970
- import { join as join22, resolve as resolve12 } from "path";
6710
+ import { join as join30, resolve as resolve13 } from "path";
5971
6711
  function flag(args, name) {
5972
6712
  const i = args.indexOf(name);
5973
6713
  if (i === -1)
@@ -5979,7 +6719,7 @@ function flag(args, name) {
5979
6719
  }
5980
6720
  function readJson(path) {
5981
6721
  try {
5982
- return JSON.parse(readFileSync3(path, "utf-8"));
6722
+ return JSON.parse(readFileSync4(path, "utf-8"));
5983
6723
  } catch {
5984
6724
  return null;
5985
6725
  }
@@ -5998,21 +6738,21 @@ function pidAlive(pid) {
5998
6738
  }
5999
6739
  function readPid(dir) {
6000
6740
  try {
6001
- const n = Number.parseInt(readFileSync3(join22(dir, "state", "pid"), "utf-8").trim(), 10);
6741
+ const n = Number.parseInt(readFileSync4(join30(dir, "state", "pid"), "utf-8").trim(), 10);
6002
6742
  return Number.isFinite(n) && n > 0 ? n : null;
6003
6743
  } catch {
6004
6744
  return null;
6005
6745
  }
6006
6746
  }
6007
6747
  function sessionOf(dir) {
6008
- const stateDir = join22(dir, "state");
6009
- const info = readJson(join22(stateDir, "server-info")) ?? readJson(join22(stateDir, "server-info.prev"));
6748
+ const stateDir = join30(dir, "state");
6749
+ const info = readJson(join30(stateDir, "server-info")) ?? readJson(join30(stateDir, "server-info.prev"));
6010
6750
  const pid = readPid(dir);
6011
- const running = info !== null && !existsSync19(join22(stateDir, "server-stopped")) && pid !== null && pidAlive(pid);
6751
+ const running = info !== null && !existsSync28(join30(stateDir, "server-stopped")) && pid !== null && pidAlive(pid);
6012
6752
  return { dir, info, running };
6013
6753
  }
6014
6754
  function latestSession(harenDir) {
6015
- const base = join22(harenDir, ".companion");
6755
+ const base = join30(harenDir, ".companion");
6016
6756
  let best = null;
6017
6757
  let names;
6018
6758
  try {
@@ -6021,7 +6761,7 @@ function latestSession(harenDir) {
6021
6761
  return null;
6022
6762
  }
6023
6763
  for (const name of names) {
6024
- const dir = join22(base, name);
6764
+ const dir = join30(base, name);
6025
6765
  try {
6026
6766
  const st = statSync2(dir);
6027
6767
  if (!st.isDirectory())
@@ -6046,7 +6786,7 @@ async function portFree(port, host) {
6046
6786
  function cliEntry() {
6047
6787
  const here = import.meta.path;
6048
6788
  if (/[\\/]commands[\\/]companion\.ts$/.test(here))
6049
- return resolve12(import.meta.dir, "..", "index.ts");
6789
+ return resolve13(import.meta.dir, "..", "index.ts");
6050
6790
  return here;
6051
6791
  }
6052
6792
  function openBrowser(url) {
@@ -6140,16 +6880,16 @@ async function serve(args) {
6140
6880
  if (graceText !== undefined && !(Number(graceText) > 0))
6141
6881
  badValue("--owner-grace-minutes must be a positive number");
6142
6882
  const graceMs = Number(graceText ?? DEFAULT_OWNER_GRACE_MINUTES) * 60000;
6143
- const stateDir = join22(sessionDir, "state");
6144
- for (const d of [sessionDir, join22(sessionDir, "content"), stateDir])
6883
+ const stateDir = join30(sessionDir, "state");
6884
+ for (const d of [sessionDir, join30(sessionDir, "content"), stateDir])
6145
6885
  makePrivateDir(d);
6146
- const keyPath = join22(stateDir, "key");
6886
+ const keyPath = join30(stateDir, "key");
6147
6887
  const keyFile = flag(args, "--key-file");
6148
6888
  let key = keyFile ? readKey(keyFile) : undefined;
6149
6889
  if (keyFile && !key)
6150
6890
  throw new Error(`No key in ${keyFile}`);
6151
6891
  key ??= randomBytes2(16).toString("hex");
6152
- if (!keyFile || resolve12(keyFile) !== resolve12(keyPath))
6892
+ if (!keyFile || resolve13(keyFile) !== resolve13(keyPath))
6153
6893
  writePrivateFile(keyPath, `${key}
6154
6894
  `);
6155
6895
  const opts = {
@@ -6168,10 +6908,10 @@ async function serve(args) {
6168
6908
  throw e;
6169
6909
  handle = await startCompanion({ ...opts, port: 0 });
6170
6910
  }
6171
- writePrivateFile(join22(stateDir, "pid"), `${process.pid}
6911
+ writePrivateFile(join30(stateDir, "pid"), `${process.pid}
6172
6912
  `);
6173
6913
  await new Promise((done) => {
6174
- const stopFile = join22(handle.info.state_dir, "server-stopped");
6914
+ const stopFile = join30(handle.info.state_dir, "server-stopped");
6175
6915
  let opened = !args.includes("--open");
6176
6916
  let lastOwnerCheck = Date.now();
6177
6917
  let ownerGoneAt = null;
@@ -6199,7 +6939,7 @@ async function serve(args) {
6199
6939
  return;
6200
6940
  }
6201
6941
  }
6202
- if (existsSync19(stopFile))
6942
+ if (existsSync28(stopFile))
6203
6943
  finish();
6204
6944
  }, 100);
6205
6945
  process.on("SIGTERM", onSignal);
@@ -6209,14 +6949,14 @@ async function serve(args) {
6209
6949
  }
6210
6950
  function readKey(path) {
6211
6951
  try {
6212
- return readFileSync3(path, "utf-8").trim() || undefined;
6952
+ return readFileSync4(path, "utf-8").trim() || undefined;
6213
6953
  } catch {
6214
6954
  return;
6215
6955
  }
6216
6956
  }
6217
6957
  function restoreInfo(dir) {
6218
- const infoPath = join22(dir, "state", "server-info");
6219
- if (!existsSync19(infoPath) && existsSync19(`${infoPath}.prev`))
6958
+ const infoPath = join30(dir, "state", "server-info");
6959
+ if (!existsSync28(infoPath) && existsSync28(`${infoPath}.prev`))
6220
6960
  renameSync(`${infoPath}.prev`, infoPath);
6221
6961
  }
6222
6962
  function keyOf(url) {
@@ -6267,7 +7007,7 @@ async function start(harenDir, args) {
6267
7007
  }
6268
7008
  const askedKey = flag(args, "--key");
6269
7009
  const restart = current?.info && askedPort === undefined && askedKey === undefined ? current : null;
6270
- const saved = restart ? readJson(join22(restart.dir, "state", "options.json")) : null;
7010
+ const saved = restart ? readJson(join30(restart.dir, "state", "options.json")) : null;
6271
7011
  const options = {
6272
7012
  host: flag(args, "--host") ?? saved?.host ?? "127.0.0.1",
6273
7013
  urlHost: flag(args, "--url-host") ?? saved?.urlHost,
@@ -6285,22 +7025,22 @@ async function start(harenDir, args) {
6285
7025
  reused = true;
6286
7026
  port = restart.info.port;
6287
7027
  }
6288
- const dir = restart ? restart.dir : join22(harenDir, ".companion", `${process.pid}-${Date.now()}`);
7028
+ const dir = restart ? restart.dir : join30(harenDir, ".companion", `${process.pid}-${Date.now()}`);
6289
7029
  const fresh = !restart;
6290
- const stateDir = join22(dir, "state");
6291
- for (const d of [dir, join22(dir, "content"), stateDir])
7030
+ const stateDir = join30(dir, "state");
7031
+ for (const d of [dir, join30(dir, "content"), stateDir])
6292
7032
  makePrivateDir(d);
6293
- const keyPath = join22(stateDir, "key");
7033
+ const keyPath = join30(stateDir, "key");
6294
7034
  const oldKey = restart ? readKey(keyPath) ?? keyOf(restart.info.url) : undefined;
6295
7035
  writePrivateFile(keyPath, `${askedKey ?? oldKey ?? randomBytes2(16).toString("hex")}
6296
7036
  `);
6297
7037
  if (restart) {
6298
- const stoppedAt = mtimeOf(join22(stateDir, "server-stopped"));
6299
- rmSync2(join22(stateDir, "server-stopped"), { force: true });
6300
- const infoPath = join22(stateDir, "server-info");
6301
- if (existsSync19(infoPath))
7038
+ const stoppedAt = mtimeOf(join30(stateDir, "server-stopped"));
7039
+ rmSync2(join30(stateDir, "server-stopped"), { force: true });
7040
+ const infoPath = join30(stateDir, "server-info");
7041
+ if (existsSync28(infoPath))
6302
7042
  renameSync(infoPath, `${infoPath}.prev`);
6303
- archiveScreens(join22(dir, "content"), stoppedAt);
7043
+ archiveScreens(join30(dir, "content"), stoppedAt);
6304
7044
  }
6305
7045
  const foreground = args.includes("--foreground");
6306
7046
  const serveArgs = buildServeArgs(dir, {
@@ -6321,15 +7061,15 @@ async function start(harenDir, args) {
6321
7061
  restoreInfo(dir);
6322
7062
  };
6323
7063
  const succeed = (info) => {
6324
- rmSync2(join22(stateDir, "server-info.prev"), { force: true });
6325
- writePrivateFile(join22(stateDir, "options.json"), `${JSON.stringify(options)}
7064
+ rmSync2(join30(stateDir, "server-info.prev"), { force: true });
7065
+ writePrivateFile(join30(stateDir, "options.json"), `${JSON.stringify(options)}
6326
7066
  `);
6327
7067
  notePortChange(restart, info);
6328
7068
  };
6329
7069
  if (foreground) {
6330
- const infoFile = join22(stateDir, "server-info");
7070
+ const infoFile = join30(stateDir, "server-info");
6331
7071
  const printer = setInterval(() => {
6332
- if (existsSync19(infoFile)) {
7072
+ if (existsSync28(infoFile)) {
6333
7073
  const info = readJson(infoFile);
6334
7074
  if (!info)
6335
7075
  return;
@@ -6349,12 +7089,12 @@ async function start(harenDir, args) {
6349
7089
  return;
6350
7090
  }
6351
7091
  const child = companionDeps.spawnServe(serveArgs);
6352
- writePrivateFile(join22(stateDir, "pid"), `${child.pid}
7092
+ writePrivateFile(join30(stateDir, "pid"), `${child.pid}
6353
7093
  `);
6354
7094
  const deadline = Date.now() + companionDeps.startTimeoutMs;
6355
7095
  while (Date.now() < deadline) {
6356
7096
  const s = sessionOf(dir);
6357
- if (s.info && s.running && existsSync19(join22(stateDir, "server-info"))) {
7097
+ if (s.info && s.running && existsSync28(join30(stateDir, "server-info"))) {
6358
7098
  succeed(s.info);
6359
7099
  console.log(JSON.stringify(s.info));
6360
7100
  return;
@@ -6380,7 +7120,7 @@ function archiveScreens(contentDir, stoppedAt) {
6380
7120
  names = readdirSync2(contentDir).filter((n) => {
6381
7121
  if (!n.endsWith(".html"))
6382
7122
  return false;
6383
- const st = statSync2(join22(contentDir, n));
7123
+ const st = statSync2(join30(contentDir, n));
6384
7124
  return st.isFile() && st.mtimeMs < stoppedAt;
6385
7125
  });
6386
7126
  } catch {
@@ -6388,11 +7128,11 @@ function archiveScreens(contentDir, stoppedAt) {
6388
7128
  }
6389
7129
  if (names.length === 0)
6390
7130
  return;
6391
- const target = join22(contentDir, "archive", String(Date.now()));
6392
- makePrivateDir(join22(contentDir, "archive"));
7131
+ const target = join30(contentDir, "archive", String(Date.now()));
7132
+ makePrivateDir(join30(contentDir, "archive"));
6393
7133
  makePrivateDir(target);
6394
7134
  for (const n of names)
6395
- renameSync(join22(contentDir, n), join22(target, n));
7135
+ renameSync(join30(contentDir, n), join30(target, n));
6396
7136
  }
6397
7137
  function status(harenDir) {
6398
7138
  const s = latestSession(harenDir);
@@ -6405,8 +7145,8 @@ screen_dir ${s.info.screen_dir}
6405
7145
  state_dir ${s.info.state_dir}`);
6406
7146
  }
6407
7147
  function markStopped(dir) {
6408
- const stopped = join22(dir, "state", "server-stopped");
6409
- if (existsSync19(join22(dir, "state")) && !existsSync19(stopped))
7148
+ const stopped = join30(dir, "state", "server-stopped");
7149
+ if (existsSync28(join30(dir, "state")) && !existsSync28(stopped))
6410
7150
  writeFileSync2(stopped, `${JSON.stringify({ reason: "stop" })}
6411
7151
  `);
6412
7152
  }
@@ -6428,7 +7168,7 @@ async function companion(args, cwd = process.cwd()) {
6428
7168
  if (sub === "__serve")
6429
7169
  return serve(rest);
6430
7170
  if (!sub || !["start", "status", "stop"].includes(sub)) {
6431
- console.log(USAGE2);
7171
+ console.log(USAGE3);
6432
7172
  if (sub)
6433
7173
  throw new ExitCode(1, `Unknown companion command: ${sub}`);
6434
7174
  return;
@@ -6443,7 +7183,7 @@ async function companion(args, cwd = process.cwd()) {
6443
7183
  return status(harenDir);
6444
7184
  return stop(harenDir);
6445
7185
  }
6446
- var USAGE2 = `Usage: haren companion <start|status|stop> [--haren-dir <path>]
7186
+ var USAGE3 = `Usage: haren companion <start|status|stop> [--haren-dir <path>]
6447
7187
  start [--foreground] [--open] [--port <n>] [--host <h>] [--url-host <u>] [--idle-timeout-minutes <m>]
6448
7188
  [--key <k>] [--no-owner-watch] [--owner-grace-minutes <m>]
6449
7189
  status print the URL of the running server (exit 1 when stopped)
@@ -6478,6 +7218,792 @@ var init_companion = __esm(() => {
6478
7218
  SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh", "tcsh", "csh", "env"]);
6479
7219
  });
6480
7220
 
7221
+ // src/exec/brief.ts
7222
+ function line(body, name) {
7223
+ const l = body.split(/\r?\n/).find((x) => x.startsWith(`**${name}:**`));
7224
+ return l?.slice(name.length + 5).trim() || undefined;
7225
+ }
7226
+ function renderBrief(template, input) {
7227
+ const { task } = input;
7228
+ const missing = [];
7229
+ const description = line(task.body, "Description");
7230
+ if (!description)
7231
+ missing.push("**Description:**");
7232
+ if (task.files.length === 0)
7233
+ missing.push("**Files:**");
7234
+ if (!task.test)
7235
+ missing.push("**Test:**");
7236
+ if (task.stories.length === 0)
7237
+ missing.push("**Story:**");
7238
+ if (missing.length > 0) {
7239
+ throw new Error(`Task ${task.number} has no ${missing.join(", ")} line; add it to tasks.md`);
7240
+ }
7241
+ const feedback = input.feedback?.trim() ? `
7242
+ ## Feedback from the last review
7243
+
7244
+ Fix these points first:
7245
+
7246
+ ${input.feedback.trim()}
7247
+ ` : "";
7248
+ const values = {
7249
+ number: String(task.number),
7250
+ title: task.title,
7251
+ description,
7252
+ stories: task.stories.join(", "),
7253
+ specPath: input.specPath,
7254
+ designPath: input.designPath,
7255
+ files: task.files.map((f) => `- \`${f}\``).join(`
7256
+ `),
7257
+ interfaces: line(task.body, "Interfaces") ?? "Follow the interfaces in the design and the spec.",
7258
+ test: task.test,
7259
+ harenDir: input.harenDir,
7260
+ feedback
7261
+ };
7262
+ return template.replace(/\{\{(\w+)\}\}/g, (m, k) => values[k] ?? m);
7263
+ }
7264
+
7265
+ // src/exec/config.ts
7266
+ function intInRange(value, def, min, max, field) {
7267
+ if (value === undefined || value === null)
7268
+ return def;
7269
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
7270
+ throw new Error(`manifest models.executor.${field} must be an integer in ${min}..${max}`);
7271
+ }
7272
+ return value;
7273
+ }
7274
+ function execRunners() {
7275
+ return listHosts().filter((h) => h.exec).map((h) => h.id);
7276
+ }
7277
+ function readExecutorConfig(m, lookup = getHost) {
7278
+ const models = m.models;
7279
+ const b = models && typeof models === "object" ? models.executor : undefined;
7280
+ if (!b || typeof b !== "object" || Array.isArray(b)) {
7281
+ throw new Error("manifest.yaml has no models.executor block; add models.executor with at least a runner");
7282
+ }
7283
+ const e = b;
7284
+ const runner = e.runner;
7285
+ const host = typeof runner === "string" ? lookup(runner) : undefined;
7286
+ if (!host?.exec) {
7287
+ throw new Error(`manifest models.executor.runner must be one of: ${execRunners().join(", ")}`);
7288
+ }
7289
+ if (e.model !== undefined && e.model !== null && typeof e.model !== "string") {
7290
+ throw new Error("manifest models.executor.model must be a string");
7291
+ }
7292
+ const env = {};
7293
+ if (e.env !== undefined && e.env !== null) {
7294
+ if (typeof e.env !== "object" || Array.isArray(e.env)) {
7295
+ throw new Error("manifest models.executor.env must be a map of string values");
7296
+ }
7297
+ for (const [k, v] of Object.entries(e.env)) {
7298
+ if (typeof v !== "string") {
7299
+ throw new Error(`manifest models.executor.env.${k} must be a string`);
7300
+ }
7301
+ if (SECRET_KEY.test(k) && !VAR_REF.test(v)) {
7302
+ throw new Error(`manifest models.executor.env.${k} looks like a secret; do not write it in manifest.yaml, use \${VAR} to read it from the environment`);
7303
+ }
7304
+ env[k] = v;
7305
+ }
7306
+ }
7307
+ return {
7308
+ runner: host.id,
7309
+ model: typeof e.model === "string" && e.model ? e.model : undefined,
7310
+ env,
7311
+ maxRetries: intInRange(e.maxRetries, 2, 0, 5, "maxRetries"),
7312
+ timeoutMinutes: intInRange(e.timeoutMinutes, 30, 1, 240, "timeoutMinutes")
7313
+ };
7314
+ }
7315
+ function resolveEnv(env, processEnv) {
7316
+ const missing = [];
7317
+ const out = {};
7318
+ for (const [k, v] of Object.entries(env)) {
7319
+ out[k] = v.replace(VAR_ANY, (_, name) => {
7320
+ const val = processEnv[name];
7321
+ if (val === undefined || val === "") {
7322
+ if (!missing.includes(name))
7323
+ missing.push(name);
7324
+ return "";
7325
+ }
7326
+ return val;
7327
+ });
7328
+ }
7329
+ if (missing.length > 0) {
7330
+ throw new Error(`missing environment variables for models.executor.env: ${missing.join(", ")}`);
7331
+ }
7332
+ return out;
7333
+ }
7334
+ function requireMultiModel(m) {
7335
+ const off = ["multi-host", "multi-model"].filter((f) => !isExperimental(m, f));
7336
+ if (off.length > 0) {
7337
+ throw new Error(`this command needs experimental features; run: ${off.map((f) => `haren experimental enable ${f}`).join(" && ")}`);
7338
+ }
7339
+ }
7340
+ function referencedVars(env) {
7341
+ const names = new Set;
7342
+ for (const v of Object.values(env))
7343
+ for (const m of v.matchAll(VAR_ANY))
7344
+ names.add(m[1] ?? "");
7345
+ return [...names].filter(Boolean);
7346
+ }
7347
+ var SECRET_KEY, VAR_REF, VAR_ANY;
7348
+ var init_config2 = __esm(() => {
7349
+ init_registry();
7350
+ init_experimental();
7351
+ SECRET_KEY = /KEY|TOKEN|SECRET/i;
7352
+ VAR_REF = /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/;
7353
+ VAR_ANY = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
7354
+ });
7355
+
7356
+ // src/exec/runs.ts
7357
+ import { mkdir as mkdir11, readdir as readdir8, writeFile as writeFile10 } from "fs/promises";
7358
+ import { join as join31 } from "path";
7359
+ function isPass(r) {
7360
+ return r.exitCode === 0 && !r.timedOut && r.tests.exitCode === 0 && r.violations.length === 0;
7361
+ }
7362
+ async function nextRun(dir) {
7363
+ let names;
7364
+ try {
7365
+ names = await readdir8(dir);
7366
+ } catch {
7367
+ return 1;
7368
+ }
7369
+ const used = names.map((n) => RUN_FILE_RE.exec(n)).filter((m) => m !== null);
7370
+ return 1 + Math.max(0, ...used.map((m) => Number(m[1])));
7371
+ }
7372
+ function checkRunAllowed(opts) {
7373
+ const { run, retry, maxRetries } = opts;
7374
+ if (!retry && run > 1) {
7375
+ throw new Error("Task already has a run. Use --retry --feedback <file> to run again, or --clean to start over.");
7376
+ }
7377
+ if (retry && run === 1)
7378
+ throw new Error("No earlier run to retry.");
7379
+ const limit = 1 + maxRetries;
7380
+ if (run > limit) {
7381
+ throw new Error(`Run ${run} is over the limit of ${limit} runs (maxRetries ${maxRetries})`);
7382
+ }
7383
+ }
7384
+ async function writeResult(dir, result) {
7385
+ await mkdir11(dir, { recursive: true });
7386
+ const path = join31(dir, `result-${result.run}.json`);
7387
+ await writeFile10(path, `${JSON.stringify(result, null, 2)}
7388
+ `);
7389
+ return path;
7390
+ }
7391
+ var RUN_FILE_RE;
7392
+ var init_runs = __esm(() => {
7393
+ RUN_FILE_RE = /^(?:result|brief|run)-(\d+)\.(?:json|md|log)$/;
7394
+ });
7395
+
7396
+ // src/exec/spawn.ts
7397
+ import { spawn } from "child_process";
7398
+ import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
7399
+ import { dirname as dirname7 } from "path";
7400
+ function killGroup(pid, signal) {
7401
+ try {
7402
+ process.kill(-pid, signal);
7403
+ return true;
7404
+ } catch {
7405
+ return false;
7406
+ }
7407
+ }
7408
+ function runWithTimeout(argv, opts) {
7409
+ const killGraceMs = opts.killGraceMs ?? 5000;
7410
+ mkdirSync2(dirname7(opts.logPath), { recursive: true });
7411
+ const log = createWriteStream(opts.logPath, { flags: "a" });
7412
+ return new Promise((resolve) => {
7413
+ let timedOut = false;
7414
+ let error;
7415
+ let settled = false;
7416
+ let termTimer;
7417
+ let killTimer;
7418
+ let child;
7419
+ const finish = (exitCode) => {
7420
+ if (settled)
7421
+ return;
7422
+ settled = true;
7423
+ if (timedOut && child?.pid !== undefined)
7424
+ killGroup(child.pid, "SIGKILL");
7425
+ if (termTimer)
7426
+ clearTimeout(termTimer);
7427
+ if (killTimer)
7428
+ clearTimeout(killTimer);
7429
+ const result = { exitCode, timedOut };
7430
+ if (error !== undefined)
7431
+ result.error = error;
7432
+ log.end(() => resolve(result));
7433
+ };
7434
+ const [cmd, ...args] = argv;
7435
+ if (!cmd) {
7436
+ error = "empty argv";
7437
+ log.write(`[spawn error] ${error}
7438
+ `);
7439
+ finish(null);
7440
+ return;
7441
+ }
7442
+ const env = { ...process.env, ...opts.env };
7443
+ for (const name of opts.unsetEnv ?? [])
7444
+ delete env[name];
7445
+ child = spawn(cmd, args, {
7446
+ cwd: opts.cwd,
7447
+ env,
7448
+ stdio: ["ignore", "pipe", "pipe"],
7449
+ detached: true
7450
+ });
7451
+ child.stdout?.pipe(log, { end: false });
7452
+ child.stderr?.pipe(log, { end: false });
7453
+ child.on("error", (err) => {
7454
+ error = err.message;
7455
+ log.write(`[spawn error] ${err.message}
7456
+ `);
7457
+ if (child.pid === undefined)
7458
+ finish(null);
7459
+ });
7460
+ child.on("close", (code) => finish(code));
7461
+ termTimer = setTimeout(() => {
7462
+ const pid = child.pid;
7463
+ if (pid === undefined)
7464
+ return;
7465
+ timedOut = true;
7466
+ killGroup(pid, "SIGTERM");
7467
+ killTimer = setTimeout(() => {
7468
+ killGroup(pid, "SIGKILL");
7469
+ }, killGraceMs);
7470
+ }, opts.timeoutMs);
7471
+ });
7472
+ }
7473
+ var init_spawn = () => {};
7474
+
7475
+ // src/exec/task.ts
7476
+ function findTask(tasksText, n) {
7477
+ const lines = tasksText.split(/\r?\n/);
7478
+ const heading = new RegExp(`^## Task ${n}:\\s*(.*)$`);
7479
+ const start = lines.findIndex((l) => heading.test(l));
7480
+ if (start === -1)
7481
+ return;
7482
+ const title = (lines[start].match(heading)?.[1] ?? "").trim();
7483
+ const bodyLines = [];
7484
+ for (const line of lines.slice(start + 1)) {
7485
+ if (line.startsWith("## ") || /^---\s*$/.test(line))
7486
+ break;
7487
+ bodyLines.push(line);
7488
+ }
7489
+ const body = bodyLines.join(`
7490
+ `).trim();
7491
+ const field = (name) => bodyLines.find((l) => l.startsWith(`**${name}:**`))?.slice(name.length + 5).trim();
7492
+ const stories = field("Story")?.match(/STORY-\d+/g) ?? [];
7493
+ const repo = field("Repo") || undefined;
7494
+ const testRaw = field("Test");
7495
+ const test = testRaw ? testRaw.replace(/^`+|`+$/g, "").trim() : undefined;
7496
+ const files = [];
7497
+ const filesAt = bodyLines.findIndex((l) => l.startsWith("**Files:**"));
7498
+ if (filesAt !== -1) {
7499
+ for (const line of bodyLines.slice(filesAt + 1)) {
7500
+ if (!/^\s*-\s/.test(line))
7501
+ break;
7502
+ for (const m of line.matchAll(/`([^`]+)`/g)) {
7503
+ if (!files.includes(m[1]))
7504
+ files.push(m[1]);
7505
+ }
7506
+ }
7507
+ }
7508
+ return {
7509
+ number: n,
7510
+ title,
7511
+ stories,
7512
+ ...repo ? { repo } : {},
7513
+ ...test ? { test } : {},
7514
+ files,
7515
+ body
7516
+ };
7517
+ }
7518
+ function resolveTaskRepo(task, moduleRepos) {
7519
+ const repos = moduleRepos.length > 0 ? moduleRepos : ["default"];
7520
+ if (task.repo) {
7521
+ if (repos.includes(task.repo))
7522
+ return task.repo;
7523
+ throw new Error(`Task ${task.number}: repo "${task.repo}" is not a repo of this module. Valid keys: ${repos.join(", ")}`);
7524
+ }
7525
+ if (repos.length === 1)
7526
+ return repos[0];
7527
+ throw new Error(`Task ${task.number} needs a **Repo:** line because the module has several repos: ${repos.join(", ")}`);
7528
+ }
7529
+
7530
+ // src/exec/violations.ts
7531
+ function under(p, dir) {
7532
+ return p === dir || p.startsWith(`${dir}/`);
7533
+ }
7534
+ function findViolations(paths, opts) {
7535
+ const harenDir = opts.harenDirRel?.replace(/^(\.\/)+/, "").replace(/\/+$/, "") || null;
7536
+ const out = [];
7537
+ for (const path of paths) {
7538
+ const p = path.replace(/^(\.\/)+/, "");
7539
+ let reason;
7540
+ if (p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p))
7541
+ reason = "absolute path";
7542
+ else if (p.split(/[\\/]/).includes(".."))
7543
+ reason = "outside the repo";
7544
+ else if (harenDir && under(p, harenDir))
7545
+ reason = "haren folder";
7546
+ else if (under(p, ".haren-worktrees"))
7547
+ reason = "worktree folder";
7548
+ if (reason)
7549
+ out.push({ path, reason });
7550
+ }
7551
+ return out;
7552
+ }
7553
+
7554
+ // src/exec/worktree.ts
7555
+ import { existsSync as existsSync29, realpathSync as realpathSync3 } from "fs";
7556
+ import { appendFile as appendFile3, mkdir as mkdir12, readFile as readFile16 } from "fs/promises";
7557
+ import { join as join32, resolve as resolve14 } from "path";
7558
+ function worktreePath(repo, module, n) {
7559
+ return join32(repo, WORKTREE_DIR, `${module}-${n}`);
7560
+ }
7561
+ function execBranch(module, n) {
7562
+ return `exec/${module}/${n}`;
7563
+ }
7564
+ async function git(args, cwd) {
7565
+ const r = await runGit(args, cwd);
7566
+ if (!r.ok)
7567
+ throw new Error(r.stderr || `git ${args.join(" ")} failed`);
7568
+ return r.stdout;
7569
+ }
7570
+ async function baseBranch(repo) {
7571
+ const r = await runGit(["symbolic-ref", "--short", "-q", "HEAD"], repo);
7572
+ if (r.ok && r.stdout)
7573
+ return r.stdout;
7574
+ throw new Error(`${repo} is on a detached HEAD. Check out a branch first, then run again.`);
7575
+ }
7576
+ async function assertClean(repo, ignoreDir) {
7577
+ const spec = ignoreDir ? ["--", ".", `:(exclude)${ignoreDir}`] : [];
7578
+ const out = await git(["status", "--porcelain", "--untracked-files=no", ...spec], repo);
7579
+ if (!out)
7580
+ return;
7581
+ const files = out.split(`
7582
+ `).map((l) => l.trim().replace(/^\S+\s+/, "")).filter(Boolean);
7583
+ throw new Error(`${repo} has uncommitted changes to tracked files: ${files.join(", ")}. Commit or stash them first.`);
7584
+ }
7585
+ async function branchExists(repo, branch) {
7586
+ return (await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], repo)).ok;
7587
+ }
7588
+ async function isRegisteredWorktree(repo, path) {
7589
+ const out = await git(["worktree", "list", "--porcelain"], repo);
7590
+ const want = resolve14(path);
7591
+ return out.split(`
7592
+ `).filter((l) => l.startsWith("worktree ")).some((l) => {
7593
+ const p = l.slice("worktree ".length);
7594
+ return resolve14(p) === want || resolveReal(p) === resolveReal(want);
7595
+ });
7596
+ }
7597
+ function resolveReal(p) {
7598
+ try {
7599
+ return realpathSync3(p);
7600
+ } catch {
7601
+ return resolve14(p);
7602
+ }
7603
+ }
7604
+ async function ensureExclude(repo) {
7605
+ const common = resolve14(repo, await git(["rev-parse", "--git-common-dir"], repo));
7606
+ const infoDir = join32(common, "info");
7607
+ const file = join32(infoDir, "exclude");
7608
+ const line = `${WORKTREE_DIR}/`;
7609
+ const current = existsSync29(file) ? await readFile16(file, "utf8") : "";
7610
+ if (current.split(`
7611
+ `).some((l) => l.trim() === line))
7612
+ return;
7613
+ await mkdir12(infoDir, { recursive: true });
7614
+ const prefix = current && !current.endsWith(`
7615
+ `) ? `
7616
+ ` : "";
7617
+ await appendFile3(file, `${prefix}${line}
7618
+ `);
7619
+ }
7620
+ async function ensureWorktree(repo, module, n, base) {
7621
+ const path = worktreePath(repo, module, n);
7622
+ const branch = execBranch(module, n);
7623
+ await ensureExclude(repo);
7624
+ if (existsSync29(path) && await isRegisteredWorktree(repo, path)) {
7625
+ return { path, branch, created: false };
7626
+ }
7627
+ await git(["worktree", "prune"], repo);
7628
+ if (await branchExists(repo, branch)) {
7629
+ await git(["worktree", "add", path, branch], repo);
7630
+ } else {
7631
+ await git(["worktree", "add", "-b", branch, path, base], repo);
7632
+ }
7633
+ return { path, branch, created: true };
7634
+ }
7635
+ async function commitAll(wt, message) {
7636
+ await git(["add", "-A"], wt);
7637
+ const diff = await runGit(["diff", "--cached", "--quiet"], wt);
7638
+ if (diff.ok)
7639
+ return null;
7640
+ const email = await runGit(["config", "user.email"], wt);
7641
+ const identity = email.ok && email.stdout ? [] : ["-c", "user.name=haren-exec", "-c", "user.email=exec@haren.local"];
7642
+ await git([...identity, "commit", "--no-verify", "-m", message], wt);
7643
+ return git(["rev-parse", "HEAD"], wt);
7644
+ }
7645
+ async function diffInfo(repo, base, branch) {
7646
+ const range = `${base}...${branch}`;
7647
+ const names = await git(["diff", "--name-only", "--no-renames", range], repo);
7648
+ const stat = await git(["diff", "--shortstat", "--no-renames", range], repo);
7649
+ const num = (re) => Number(stat.match(re)?.[1] ?? 0);
7650
+ return {
7651
+ paths: names ? names.split(`
7652
+ `).filter(Boolean) : [],
7653
+ files: num(/(\d+) files? changed/),
7654
+ insertions: num(/(\d+) insertions?\(\+\)/),
7655
+ deletions: num(/(\d+) deletions?\(-\)/)
7656
+ };
7657
+ }
7658
+ async function removeWorktree(repo, module, n) {
7659
+ const path = worktreePath(repo, module, n);
7660
+ const branch = execBranch(module, n);
7661
+ if (existsSync29(path) || await isRegisteredWorktree(repo, path)) {
7662
+ await git(["worktree", "remove", "--force", path], repo);
7663
+ }
7664
+ await git(["worktree", "prune"], repo);
7665
+ if (await branchExists(repo, branch)) {
7666
+ await git(["branch", "-D", branch], repo);
7667
+ }
7668
+ }
7669
+ var WORKTREE_DIR = ".haren-worktrees";
7670
+ var init_worktree = __esm(() => {
7671
+ init_git();
7672
+ });
7673
+
7674
+ // src/exec/run.ts
7675
+ import { existsSync as existsSync30, realpathSync as realpathSync4 } from "fs";
7676
+ import { mkdir as mkdir13, readFile as readFile17, readdir as readdir9, rename as rename2, stat as stat3, writeFile as writeFile11 } from "fs/promises";
7677
+ import { isAbsolute as isAbsolute4, join as join33, relative as relative5, resolve as resolve15 } from "path";
7678
+ async function readManifest(harenDir) {
7679
+ const path = join33(harenDir, "manifest.yaml");
7680
+ if (!existsSync30(path))
7681
+ throw new Error(`No manifest.yaml in ${harenDir}`);
7682
+ return parseManifest(await readFile17(path, "utf-8"));
7683
+ }
7684
+ function checkModuleStatus(progress, module) {
7685
+ const status = progress.modules?.[module]?.status;
7686
+ if (!status)
7687
+ throw new Error(`Module "${module}" is not in progress.json`);
7688
+ if (!RUN_STATUSES.includes(status)) {
7689
+ throw new Error(`Module "${module}" has status "${status}"; haren exec needs ${RUN_STATUSES.join(" or ")}. Run the plan phase first.`);
7690
+ }
7691
+ }
7692
+ function activePlanDir(harenDir, manifest, progress, module) {
7693
+ const root = join33(harenDir, "artifacts", "04-plans", module);
7694
+ const it = manifest.iterations;
7695
+ const n = progress.currentIteration;
7696
+ if (it && it.enabled === true && (typeof n === "number" || typeof n === "string")) {
7697
+ const dir = join33(root, `iteration-${n}`);
7698
+ if (existsSync30(join33(dir, "tasks.md")))
7699
+ return dir;
7700
+ }
7701
+ return root;
7702
+ }
7703
+ async function frontMatterRepos(harenDir, module) {
7704
+ const path = join33(harenDir, "artifacts", "03-modules", module, "module.md");
7705
+ if (!existsSync30(path))
7706
+ return [];
7707
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(await readFile17(path, "utf-8"));
7708
+ if (!m)
7709
+ return [];
7710
+ const data = Bun.YAML.parse(m[1]);
7711
+ const repos = data?.repos;
7712
+ if (Array.isArray(repos))
7713
+ return repos.filter((r) => typeof r === "string");
7714
+ if (repos && typeof repos === "object")
7715
+ return Object.keys(repos);
7716
+ return [];
7717
+ }
7718
+ async function moduleRepoKeys(harenDir, progress, module) {
7719
+ const fromProgress = progress.modules?.[module]?.repos;
7720
+ if (fromProgress && fromProgress.length > 0)
7721
+ return fromProgress;
7722
+ return frontMatterRepos(harenDir, module);
7723
+ }
7724
+ async function repoPath(harenDir, manifest, key) {
7725
+ const repos = normalizeRepos(manifest.repos);
7726
+ const entry = repos[key];
7727
+ if (entry)
7728
+ return resolve15(harenDir, entry.path);
7729
+ if (key !== "default")
7730
+ throw new Error(`Repo "${key}" is not in manifest.yaml repos`);
7731
+ const r = await runGit(["rev-parse", "--show-toplevel"], harenDir);
7732
+ if (!r.ok || !r.stdout) {
7733
+ throw new Error(`${harenDir} is not inside a git repository; add the module's repo to repos`);
7734
+ }
7735
+ return r.stdout;
7736
+ }
7737
+ async function loadTask(t, manifest, progress) {
7738
+ const planDir = activePlanDir(t.harenDir, manifest, progress, t.module);
7739
+ const tasksPath = join33(planDir, "tasks.md");
7740
+ if (!existsSync30(tasksPath))
7741
+ throw new Error(`No tasks.md at ${tasksPath}`);
7742
+ const task = findTask(await readFile17(tasksPath, "utf-8"), t.task);
7743
+ if (!task)
7744
+ throw new Error(`Task ${t.task} not found in ${tasksPath}`);
7745
+ const key = resolveTaskRepo(task, await moduleRepoKeys(t.harenDir, progress, t.module));
7746
+ const repo = await repoPath(t.harenDir, manifest, key);
7747
+ return { planDir, task, repo };
7748
+ }
7749
+ async function loadContext2(t) {
7750
+ const manifest = await readManifest(t.harenDir);
7751
+ const progress = await readProgress(join33(t.harenDir, "progress.json"));
7752
+ return { manifest, progress, ...await loadTask(t, manifest, progress) };
7753
+ }
7754
+ function execDir(harenDir, module, n) {
7755
+ return join33(harenDir, "artifacts", "05-exec", module, String(n));
7756
+ }
7757
+ async function briefTemplate(harenDir) {
7758
+ const local = join33(harenDir, "templates", "task-brief.md");
7759
+ if (existsSync30(local))
7760
+ return readFile17(local, "utf-8");
7761
+ return readFile17(join33(resolveContentDir(), "templates", "task-brief.md"), "utf-8");
7762
+ }
7763
+ function real(p) {
7764
+ try {
7765
+ return realpathSync4(p);
7766
+ } catch {
7767
+ return resolve15(p);
7768
+ }
7769
+ }
7770
+ function harenDirInRepo(repo, harenDir) {
7771
+ const rel = relative5(real(repo), real(harenDir));
7772
+ if (rel === "" || rel.startsWith("..") || isAbsolute4(rel))
7773
+ return null;
7774
+ return rel.split("\\").join("/");
7775
+ }
7776
+ async function writeBrief(opts, ctx, dir, run) {
7777
+ const feedback = opts.feedbackPath ? await readFile17(opts.feedbackPath, "utf-8") : undefined;
7778
+ const brief = renderBrief(await briefTemplate(opts.harenDir), {
7779
+ task: ctx.task,
7780
+ specPath: join33(opts.harenDir, "artifacts", "03-modules", opts.module, "spec.md"),
7781
+ designPath: join33(ctx.planDir, "design.md"),
7782
+ harenDir: harenDirInRepo(ctx.repo, opts.harenDir) ?? opts.harenDir,
7783
+ feedback
7784
+ });
7785
+ await mkdir13(dir, { recursive: true });
7786
+ await writeFile11(join33(dir, `brief-${run}.md`), brief);
7787
+ return brief;
7788
+ }
7789
+ async function emit2(opts, type, data) {
7790
+ const dir = join33(opts.harenDir, "events");
7791
+ await mkdir13(dir, { recursive: true });
7792
+ await appendEvent(join33(dir, "events.jsonl"), {
7793
+ type,
7794
+ module: opts.module,
7795
+ feature: String(opts.task),
7796
+ phase: "implement",
7797
+ timestamp: (opts.now ?? (() => new Date))().toISOString(),
7798
+ data
7799
+ });
7800
+ }
7801
+ function loadConfig(manifest, opts) {
7802
+ requireMultiModel(manifest);
7803
+ const lookup = opts.resolveHost ?? getHost;
7804
+ const config = readExecutorConfig(manifest, lookup);
7805
+ const host = lookup(config.runner);
7806
+ if (!host?.exec)
7807
+ throw new Error(`Runner ${config.runner} has no exec()`);
7808
+ return { config, host };
7809
+ }
7810
+ async function prepareRun(opts, ctx, config) {
7811
+ if (!ctx.task.test)
7812
+ throw new Error(`Task ${ctx.task.number} has no **Test:** line`);
7813
+ const base = await baseBranch(ctx.repo);
7814
+ const dir = execDir(opts.harenDir, opts.module, opts.task);
7815
+ const run = await nextRun(dir);
7816
+ checkRunAllowed({ run, retry: opts.retry === true, maxRetries: config.maxRetries });
7817
+ const exists = existsSync30(worktreePath(ctx.repo, opts.module, opts.task));
7818
+ if (run === 1 || !exists)
7819
+ await assertClean(ctx.repo, harenDirInRepo(ctx.repo, opts.harenDir));
7820
+ const wt = await ensureWorktree(ctx.repo, opts.module, opts.task, base);
7821
+ return { base, dir, run, wt };
7822
+ }
7823
+ async function runExec(opts) {
7824
+ const manifest = await readManifest(opts.harenDir);
7825
+ const { config, host } = loadConfig(manifest, opts);
7826
+ const progress = await readProgress(join33(opts.harenDir, "progress.json"));
7827
+ checkModuleStatus(progress, opts.module);
7828
+ const ctx = { manifest, ...await loadTask(opts, manifest, progress) };
7829
+ const env = resolveEnv(config.env, opts.processEnv ?? process.env);
7830
+ const { base, dir, run, wt } = await prepareRun(opts, ctx, config);
7831
+ const brief = await writeBrief(opts, ctx, dir, run);
7832
+ const argv = host.exec({ prompt: brief, cwd: wt.path, model: config.model, env });
7833
+ await emit2(opts, "exec.started", { run, runner: config.runner, model: config.model ?? null });
7834
+ const logPath = join33(dir, `run-${run}.log`);
7835
+ const timeoutMs = opts.timeoutMs ?? config.timeoutMinutes * 60000;
7836
+ const spawnOpts = { cwd: wt.path, env, timeoutMs, logPath, killGraceMs: opts.killGraceMs };
7837
+ const before = await harenSnapshot(opts.harenDir);
7838
+ const exec = await runWithTimeout(argv, spawnOpts);
7839
+ const harenChanged = diffSnapshot(before, await harenSnapshot(opts.harenDir));
7840
+ const commit = await commitAll(wt.path, `exec(${opts.module}): task ${opts.task} run ${run}`);
7841
+ const test = ctx.task.test ?? "";
7842
+ const unsetEnv = referencedVars(config.env);
7843
+ const tests = await runWithTimeout(["sh", "-c", test], { ...spawnOpts, env: {}, unsetEnv });
7844
+ const diff = await diffInfo(ctx.repo, base, wt.branch);
7845
+ const violations = [
7846
+ ...findViolations(diff.paths, { harenDirRel: harenDirInRepo(ctx.repo, opts.harenDir) }),
7847
+ ...harenChanged.map((path) => ({ path, reason: "haren folder changed during the run" }))
7848
+ ];
7849
+ const partial = {
7850
+ run,
7851
+ runner: config.runner,
7852
+ ...config.model ? { model: config.model } : {},
7853
+ exitCode: exec.exitCode,
7854
+ timedOut: exec.timedOut,
7855
+ tests: { command: test, exitCode: tests.exitCode },
7856
+ violations,
7857
+ diffStat: { files: diff.files, insertions: diff.insertions, deletions: diff.deletions },
7858
+ baseBranch: base,
7859
+ branch: wt.branch,
7860
+ worktree: relative5(ctx.repo, wt.path),
7861
+ commit,
7862
+ log: relative5(opts.harenDir, logPath),
7863
+ retriesLeft: Math.max(0, 1 + config.maxRetries - run)
7864
+ };
7865
+ const result = { ...partial, pass: isPass(partial) };
7866
+ const resultPath = await writeResult(dir, result);
7867
+ await emit2(opts, "exec.finished", {
7868
+ run,
7869
+ runner: config.runner,
7870
+ pass: result.pass,
7871
+ timedOut: result.timedOut
7872
+ });
7873
+ return { result, resultPath };
7874
+ }
7875
+ async function cleanExec(opts) {
7876
+ const { repo } = await loadContext2(opts);
7877
+ await removeWorktree(repo, opts.module, opts.task);
7878
+ const dir = execDir(opts.harenDir, opts.module, opts.task);
7879
+ const runFiles = existsSync30(dir) ? (await readdir9(dir)).filter((n) => /^(?:result|brief|run|feedback)-\d+\./.test(n)) : [];
7880
+ if (runFiles.length === 0)
7881
+ return;
7882
+ const stamp = (opts.now ?? (() => new Date))().toISOString().replace(/[:.]/g, "-");
7883
+ const archive = join33(dir, `cleaned-${stamp}`);
7884
+ await mkdir13(archive, { recursive: true });
7885
+ for (const n of runFiles)
7886
+ await rename2(join33(dir, n), join33(archive, n));
7887
+ }
7888
+ async function harenSnapshot(harenDir) {
7889
+ const out = new Map;
7890
+ const skip = [join33("artifacts", "05-exec"), "events"];
7891
+ const walk = async (rel) => {
7892
+ if (skip.includes(rel))
7893
+ return;
7894
+ let names;
7895
+ try {
7896
+ names = await readdir9(join33(harenDir, rel));
7897
+ } catch {
7898
+ return;
7899
+ }
7900
+ for (const n of names) {
7901
+ const r = rel ? join33(rel, n) : n;
7902
+ const st = await stat3(join33(harenDir, r)).catch(() => null);
7903
+ if (!st)
7904
+ continue;
7905
+ if (st.isDirectory())
7906
+ await walk(r);
7907
+ else
7908
+ out.set(r, `${st.size}:${st.mtimeMs}`);
7909
+ }
7910
+ };
7911
+ await walk("");
7912
+ return out;
7913
+ }
7914
+ function diffSnapshot(a, b) {
7915
+ const changed = new Set;
7916
+ for (const [k, v] of a)
7917
+ if (b.get(k) !== v)
7918
+ changed.add(k);
7919
+ for (const k of b.keys())
7920
+ if (!a.has(k))
7921
+ changed.add(k);
7922
+ return [...changed].sort();
7923
+ }
7924
+ var RUN_STATUSES;
7925
+ var init_run = __esm(() => {
7926
+ init_registry();
7927
+ init_content_dir();
7928
+ init_events();
7929
+ init_git();
7930
+ init_manifest();
7931
+ init_progress();
7932
+ init_config2();
7933
+ init_runs();
7934
+ init_spawn();
7935
+ init_worktree();
7936
+ RUN_STATUSES = ["planned", "implementing"];
7937
+ });
7938
+
7939
+ // src/commands/exec.ts
7940
+ import { relative as relative6, resolve as resolve16 } from "path";
7941
+ function value(args, flag) {
7942
+ const i = args.indexOf(flag);
7943
+ if (i === -1)
7944
+ return;
7945
+ const v = args[i + 1];
7946
+ if (v === undefined || v === "" || v.startsWith("--"))
7947
+ throw new Error(`${flag} needs a value`);
7948
+ return v;
7949
+ }
7950
+ function parseExecArgs(args) {
7951
+ const module = value(args, "--module");
7952
+ if (!module)
7953
+ throw new Error(`--module is required
7954
+ ${EXEC_USAGE}`);
7955
+ const rawTask = value(args, "--task");
7956
+ if (!rawTask)
7957
+ throw new Error(`--task is required
7958
+ ${EXEC_USAGE}`);
7959
+ if (!/^[1-9]\d*$/.test(rawTask))
7960
+ throw new Error("--task must be a positive integer");
7961
+ const retry = args.includes("--retry");
7962
+ const feedback = value(args, "--feedback");
7963
+ if (retry !== (feedback !== undefined)) {
7964
+ throw new Error("--retry and --feedback <file> go together");
7965
+ }
7966
+ return {
7967
+ module,
7968
+ task: Number(rawTask),
7969
+ retry,
7970
+ clean: args.includes("--clean"),
7971
+ feedback,
7972
+ harenDir: harenDirFlag(args)
7973
+ };
7974
+ }
7975
+ async function exec(args, deps = {}) {
7976
+ const cwd = deps.cwd ?? process.cwd();
7977
+ const a = parseExecArgs(args);
7978
+ const location = await resolveHarenDir(cwd, { harenDir: a.harenDir, env: process.env });
7979
+ if (!location)
7980
+ throw new Error("No haren folder found. Run `haren init` first.");
7981
+ const target = {
7982
+ harenDir: location.harenDir,
7983
+ module: a.module,
7984
+ task: a.task,
7985
+ resolveHost: deps.resolveHost
7986
+ };
7987
+ if (a.clean) {
7988
+ await cleanExec(target);
7989
+ console.log(` Removed the worktree and branch of ${a.module} task ${a.task}; run files moved to cleaned-<time>/`);
7990
+ return;
7991
+ }
7992
+ const { result, resultPath } = await runExec({
7993
+ ...target,
7994
+ retry: a.retry,
7995
+ feedbackPath: a.feedback ? resolve16(cwd, a.feedback) : undefined,
7996
+ processEnv: deps.processEnv
7997
+ });
7998
+ console.log(` ${relative6(cwd, resultPath)}`);
7999
+ console.log(` ${result.pass ? "PASS" : "FAIL"}`);
8000
+ }
8001
+ var EXEC_USAGE = "Usage: haren exec --module <m> --task <n> [--retry --feedback <file>] [--clean] [--haren-dir <dir>]";
8002
+ var init_exec = __esm(() => {
8003
+ init_run();
8004
+ init_resolve();
8005
+ });
8006
+
6481
8007
  // src/index.ts
6482
8008
  init_exit_code();
6483
8009
  function parseArgs(args) {
@@ -6500,6 +8026,8 @@ function parseArgs(args) {
6500
8026
  case "track":
6501
8027
  case "migrate":
6502
8028
  case "companion":
8029
+ case "experimental":
8030
+ case "exec":
6503
8031
  return { command, args: rest };
6504
8032
  default:
6505
8033
  return { command: "unknown", args };
@@ -6544,6 +8072,16 @@ async function main() {
6544
8072
  await companion(parsed.args);
6545
8073
  break;
6546
8074
  }
8075
+ case "experimental": {
8076
+ await Promise.resolve().then(() => init_experimental2());
8077
+ await experimental(parsed.args);
8078
+ break;
8079
+ }
8080
+ case "exec": {
8081
+ await Promise.resolve().then(() => init_exec());
8082
+ await exec(parsed.args);
8083
+ break;
8084
+ }
6547
8085
  case "help":
6548
8086
  console.log("Usage:");
6549
8087
  console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
@@ -6551,6 +8089,7 @@ async function main() {
6551
8089
  console.log(" --mode <undecided|explore|blueprint|inherit|migration>");
6552
8090
  console.log(" --yes|-y --dry-run --force");
6553
8091
  console.log(" --plugin <name|source> (repeatable)");
8092
+ console.log(" --experimental <a,b> (experimental features to enable)");
6554
8093
  console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run, --yes)");
6555
8094
  console.log(" haren agent Manage local agent (start, stop, status)");
6556
8095
  console.log(" haren plugin Manage plugins (add, remove, list, run, doctor)");
@@ -6562,16 +8101,20 @@ async function main() {
6562
8101
  console.log(" artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]");
6563
8102
  console.log(" event <type> [--module m] [--phase p] [--feature f] [--data '<json>']");
6564
8103
  console.log(" unit <module> <unit> <status> (migration mode)");
6565
- console.log(" ui-mode <ask|ascii|browser>");
8104
+ console.log(" ui-mode <ask|ascii|browser|artifact>");
6566
8105
  console.log(' override on --reason "<text>" [--hours <n>] | override off');
6567
8106
  console.log(" haren migrate Run the migration adapter:");
6568
8107
  console.log(" inventory [--module <m>] | extract <unit> | gate <unit> [--approve]");
6569
8108
  console.log(" gate exit codes: 0 approved, 1 failed, 3 PASS but not approved yet");
8109
+ console.log(" haren experimental enable <name> | disable <name> | list (multi-host, multi-model)");
8110
+ console.log(" haren exec Run one planned task with the executor model (multi-model)");
8111
+ console.log(" --module <m> --task <n> [--retry --feedback <file>] [--clean] [--haren-dir <dir>]");
8112
+ console.log(" exit 0 when a result file is written (PASS or FAIL)");
6570
8113
  console.log(" haren companion Visual companion server: start [--foreground] [--open] | status | stop");
6571
8114
  break;
6572
8115
  case "unknown":
6573
8116
  console.error(`Unknown command: ${parsed.args[0]}`);
6574
- console.log("Usage: haren init | upgrade | agent | plugin | track | migrate | companion (haren --help)");
8117
+ console.log("Usage: haren init | upgrade | agent | plugin | track | migrate | companion | experimental | exec (haren --help)");
6575
8118
  process.exit(1);
6576
8119
  }
6577
8120
  }