@odarino/haren 1.4.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +1 -1
  3. package/README.md +108 -9
  4. package/content/agents/architect.md +1 -1
  5. package/content/agents/developer.md +4 -3
  6. package/content/agents/planner.md +3 -1
  7. package/content/agents/reviewer.md +2 -0
  8. package/content/skills/audit-workspace/SKILL.md +2 -1
  9. package/content/skills/collect-components/SKILL.md +81 -0
  10. package/content/skills/decompose/SKILL.md +10 -16
  11. package/content/skills/discover/SKILL.md +6 -2
  12. package/content/skills/discover/blueprint.md +1 -0
  13. package/content/skills/discover/explore.md +1 -0
  14. package/content/skills/discover/inherit.md +1 -0
  15. package/content/skills/discover/migration.md +38 -0
  16. package/content/skills/evaluate/SKILL.md +24 -0
  17. package/content/skills/extract/SKILL.md +43 -0
  18. package/content/skills/generate-mockup/SKILL.md +41 -5
  19. package/content/skills/ideate/SKILL.md +2 -0
  20. package/content/skills/implement/SKILL.md +20 -11
  21. package/content/skills/plan/SKILL.md +57 -9
  22. package/content/skills/read-context/SKILL.md +12 -1
  23. package/content/skills/resolve-next-id/SKILL.md +9 -1
  24. package/content/skills/ui-review/SKILL.md +64 -0
  25. package/content/skills/update-tracking/SKILL.md +11 -1
  26. package/content/skills/validate-artifact/SKILL.md +34 -0
  27. package/content/skills/visual-companion/SKILL.md +285 -0
  28. package/content/templates/checklist.md +26 -0
  29. package/content/templates/component-catalog.md +41 -0
  30. package/content/templates/design.md +15 -0
  31. package/content/templates/deviation-log.md +13 -0
  32. package/content/templates/legacy-semantics.md +11 -0
  33. package/content/templates/parity-evidence.md +32 -0
  34. package/content/templates/unit-map.md +20 -0
  35. package/content/templates/unit-spec.md +43 -0
  36. package/dist/index.js +2681 -120
  37. package/package.json +4 -3
package/dist/index.js CHANGED
@@ -12,6 +12,19 @@ var __esm = (fn, res, err) => () => {
12
12
  return res;
13
13
  };
14
14
 
15
+ // src/lib/exit-code.ts
16
+ var ExitCode;
17
+ var init_exit_code = __esm(() => {
18
+ ExitCode = class ExitCode extends Error {
19
+ code;
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.code = code;
23
+ this.name = "ExitCode";
24
+ }
25
+ };
26
+ });
27
+
15
28
  // src/lib/content-dir.ts
16
29
  import { existsSync } from "fs";
17
30
  import { join, resolve } from "path";
@@ -150,6 +163,7 @@ Key dispatch rules:
150
163
  * Brainstorm Gate Hook
151
164
  * Blocks Edit/Write tool use outside the haren folder unless a module that
152
165
  * owns the target repo has reached 'planned' status (or later).
166
+ * For shell commands (Bash) it only blocks writes into readOnly repos (best effort).
153
167
  *
154
168
  * Override (for a fix the user asked for): HAREN_GATE=off, or
155
169
  * progress.json "gateOverride": { "reason": "...", "until": "<ISO>" }
@@ -201,17 +215,35 @@ function allow(): never {
201
215
  process.exit(0);
202
216
  }
203
217
 
218
+ // Set by readInput(). "unknown" writes both the Claude and the Cursor denial.
219
+ let source: "claude" | "cursor" | "unknown" = "unknown";
220
+
221
+ // Claude Code sends hook_event_name "PreToolUse" with session_id and transcript_path.
222
+ // Cursor sends its own hook_event_name values (beforeShellExecution, preToolUse, ...).
223
+ function detectSource(input: any): typeof source {
224
+ const event = input?.hook_event_name;
225
+ if (event === "PreToolUse") return "claude";
226
+ if (typeof event === "string" && event) return "cursor";
227
+ if (typeof input?.session_id === "string" && typeof input?.transcript_path === "string") return "claude";
228
+ return "unknown";
229
+ }
230
+
204
231
  function deny(message: string): never {
205
- console.log(JSON.stringify({
206
- error: message, // Claude Code
207
- permission: "deny", // Cursor
208
- user_message: message, // Cursor \u2014 shown in UI
209
- agent_message: message, // Cursor \u2014 sent to model
210
- }));
232
+ if (source !== "cursor") {
233
+ // Claude Code reads stderr on exit 2 and shows it to the model.
234
+ console.error(message);
235
+ }
236
+ if (source !== "claude") {
237
+ console.log(JSON.stringify({
238
+ permission: "deny", // Cursor
239
+ user_message: message, // Cursor \u2014 shown in UI
240
+ agent_message: message, // Cursor \u2014 sent to model
241
+ }));
242
+ }
211
243
  process.exit(2);
212
244
  }
213
245
 
214
- interface Repo { path: string; role?: string }
246
+ interface Repo { path: string; role?: string; readOnly?: boolean }
215
247
 
216
248
  // Same rules as the CLI: repos is a map key -> {path} | key -> string, or an array.
217
249
  function normalizeRepos(repos: unknown): Record<string, Repo> {
@@ -219,30 +251,41 @@ function normalizeRepos(repos: unknown): Record<string, Repo> {
219
251
  if (Array.isArray(repos)) {
220
252
  for (const item of repos) {
221
253
  const path = typeof item === "string" ? item : item?.path;
222
- if (typeof path === "string" && path) out[basename(path)] = { path, role: item?.role };
254
+ if (typeof path === "string" && path) out[basename(path)] = { path, role: item?.role, readOnly: item?.readOnly === true };
223
255
  }
224
256
  } else if (repos && typeof repos === "object") {
225
257
  for (const [key, value] of Object.entries(repos as Record<string, any>)) {
226
258
  if (typeof value === "string") out[key] = { path: value };
227
259
  else if (value && typeof value === "object" && typeof value.path === "string") {
228
- out[key] = { path: value.path, role: value.role };
260
+ out[key] = { path: value.path, role: value.role, readOnly: value.readOnly === true };
229
261
  }
230
262
  }
231
263
  }
232
264
  return out;
233
265
  }
234
266
 
235
- async function readRepos(): Promise<Record<string, Repo>> {
267
+ const BROKEN_MANIFEST_MESSAGE =
268
+ "manifest.yaml does not parse and declares a readOnly repo. Fix manifest.yaml first.";
269
+
270
+ // brokenReadOnly: the manifest does not parse but its text declares a readOnly repo.
271
+ // Then writes outside the haren folder are blocked (fail-closed). Otherwise fail-open.
272
+ async function readManifest(): Promise<{ repos: Record<string, Repo>; brokenReadOnly: boolean }> {
273
+ const file = Bun.file(join(harenDir, "manifest.yaml"));
274
+ let text = "";
236
275
  try {
237
- const file = Bun.file(join(harenDir, "manifest.yaml"));
238
- if (!(await file.exists())) return {};
239
- const data: any = Bun.YAML.parse(await file.text());
240
- return normalizeRepos(data?.repos);
276
+ if (!(await file.exists())) return { repos: {}, brokenReadOnly: false };
277
+ text = await file.text();
278
+ const data: any = Bun.YAML.parse(text);
279
+ return { repos: normalizeRepos(data?.repos), brokenReadOnly: false };
241
280
  } catch {
242
- return {}; // fail-open: malformed manifest means no repo info
281
+ return { repos: {}, brokenReadOnly: /readOnly\\s*:\\s*true/.test(text) };
243
282
  }
244
283
  }
245
284
 
285
+ async function readRepos(): Promise<Record<string, Repo>> {
286
+ return (await readManifest()).repos;
287
+ }
288
+
246
289
  function realRoot(path: string): string {
247
290
  return realTarget(resolve(harenDir, path));
248
291
  }
@@ -256,30 +299,244 @@ function overrideActive(progress: any): boolean {
256
299
  return !Number.isNaN(until) && until > Date.now();
257
300
  }
258
301
 
259
- async function readTarget(): Promise<string> {
302
+ // --- Shell commands (Bash tool, Cursor beforeShellExecution) ---
303
+ // Best effort: only the readOnly repo check applies to shell commands. It looks
304
+ // for a write signal that touches a readOnly repo. A shell can always hide a write,
305
+ // so keep the legacy repo read-only at the filesystem or git level too.
306
+
307
+ const GIT_WRITES = ["commit", "add", "rm", "mv", "checkout", "reset", "apply", "am", "stash", "clean", "restore"];
308
+ const PKG_MANAGERS = ["npm", "bun", "pnpm", "yarn"];
309
+ const PLAIN_WRITERS = ["rm", "rmdir", "mv", "touch", "mkdir", "chmod", "chown", "ln", "truncate", "tee"];
310
+
311
+ interface Segment { words: string[]; redirects: string[] }
312
+
313
+ // Splits a command into segments (&&, ||, ;, |, &, newline) with quote awareness.
314
+ // Quotes are removed from words. Redirect targets (> f, >> f, 2> f) go to redirects;
315
+ // fd duplications (>&2, 2>&1) are dropped.
316
+ function parseShell(command: string): Segment[] {
317
+ const segments: Segment[] = [];
318
+ let seg: Segment = { words: [], redirects: [] };
319
+ let word = "";
320
+ let hasWord = false;
321
+ let quote = "";
322
+ let redirectNext = false;
323
+ const endWord = () => {
324
+ if (hasWord) {
325
+ if (redirectNext) seg.redirects.push(word);
326
+ else seg.words.push(word);
327
+ redirectNext = false;
328
+ }
329
+ word = "";
330
+ hasWord = false;
331
+ };
332
+ const endSegment = () => {
333
+ endWord();
334
+ redirectNext = false;
335
+ if (seg.words.length || seg.redirects.length) segments.push(seg);
336
+ seg = { words: [], redirects: [] };
337
+ };
338
+ for (let i = 0; i < command.length; i++) {
339
+ const c = command[i];
340
+ if (quote) {
341
+ if (c === quote) quote = "";
342
+ else word += c;
343
+ continue;
344
+ }
345
+ if (c === "'" || c === '"') {
346
+ quote = c;
347
+ hasWord = true;
348
+ continue;
349
+ }
350
+ if (c === "\\\\" && i + 1 < command.length) {
351
+ word += command[++i];
352
+ hasWord = true;
353
+ continue;
354
+ }
355
+ if (c === ";" || c === "\\n" || c === "|" || c === "&") {
356
+ if (c === "&" && command[i - 1] === ">") continue;
357
+ if ((c === "|" || c === "&") && command[i + 1] === c) i++;
358
+ endSegment();
359
+ continue;
360
+ }
361
+ if (c === ">") {
362
+ if (/^\\d+$/.test(word)) {
363
+ word = "";
364
+ hasWord = false;
365
+ } else endWord();
366
+ if (command[i + 1] === ">") i++;
367
+ if (command[i + 1] === "&") {
368
+ // fd duplication: skip the fd target.
369
+ i++;
370
+ while (i + 1 < command.length && /[\\w-]/.test(command[i + 1])) i++;
371
+ continue;
372
+ }
373
+ redirectNext = true;
374
+ continue;
375
+ }
376
+ if (c === " " || c === "\\t" || c === "<") {
377
+ endWord();
378
+ continue;
379
+ }
380
+ word += c;
381
+ hasWord = true;
382
+ }
383
+ endSegment();
384
+ return segments;
385
+ }
386
+
387
+ // A token refers to a root only when it resolves (relative to cwd) into the root
388
+ // and not into an excluded folder.
389
+ function makeRefersTo(roots: string[], exclude: string[] = []) {
390
+ return (token: string, cwd: string): boolean => {
391
+ if (!token || token.startsWith("-")) return false;
392
+ const abs = realTarget(resolve(cwd, token));
393
+ if (exclude.some((dir) => inside(abs, dir))) return false;
394
+ return roots.some((root) => inside(abs, root));
395
+ };
396
+ }
397
+
398
+ // Drops git commit message values (-m/--message/-F/--file and their = forms).
399
+ // -C/-c <commit> (reuse the message of a commit) take a commit, not a path.
400
+ function gitPathArgs(sub: string, args: string[]): string[] {
401
+ if (sub !== "commit") return args;
402
+ const out: string[] = [];
403
+ for (let i = 0; i < args.length; i++) {
404
+ const a = args[i];
405
+ if (a === "-m" || a === "--message" || a === "-F" || a === "--file" || a === "-C" || a === "-c") i++;
406
+ else if (/^(-m|-F)./.test(a) || /^--(message|file)=/.test(a)) continue;
407
+ else out.push(a);
408
+ }
409
+ return out;
410
+ }
411
+
412
+ /** True when the command looks like it writes into one of the roots. */
413
+ function shellWritesTo(command: string, startCwd: string, roots: string[], exclude: string[] = []): boolean {
414
+ const refersTo = makeRefersTo(roots, exclude);
415
+ let cwd = startCwd;
416
+ let cwdInRoot = refersTo(cwd, cwd);
417
+ for (const segment of parseShell(command)) {
418
+ if (segment.redirects.some((target) => refersTo(target, cwd))) return true;
419
+ let words = segment.words;
420
+ while (words.length && (/^\\w+=/.test(words[0]) || words[0] === "sudo" || words[0] === "env")) words = words.slice(1);
421
+ if (!words.length) continue;
422
+ const [cmd, ...args] = words;
423
+ const name = basename(cmd);
424
+ const anyArg = () => args.some((a) => refersTo(a, cwd));
425
+ if (name === "cd") {
426
+ if (args[0]) {
427
+ cwdInRoot = refersTo(args[0], cwd);
428
+ cwd = resolve(cwd, args[0]);
429
+ }
430
+ continue;
431
+ }
432
+ if (PLAIN_WRITERS.includes(name) && anyArg()) return true;
433
+ if (name === "cp") {
434
+ const operands = args.filter((a) => !a.startsWith("-"));
435
+ const t = args.indexOf("-t");
436
+ const target = t >= 0 ? args[t + 1] : operands[operands.length - 1];
437
+ if (target && refersTo(target, cwd)) return true;
438
+ }
439
+ if (name === "sed" && args.some((a) => a === "--in-place" || /^-[a-zA-Z]*i/.test(a)) && anyArg()) return true;
440
+ if (name === "perl" && args.some((a) => /^-[a-zA-Z]*i/.test(a)) && anyArg()) return true;
441
+ if (name === "dd" && args.some((a) => a.startsWith("of=") && refersTo(a.slice(3), cwd))) return true;
442
+ if (name === "git") {
443
+ let dir = cwd;
444
+ let inLegacy = cwdInRoot;
445
+ let i = 0;
446
+ while (i < args.length && args[i].startsWith("-")) {
447
+ if (args[i] === "-C" && args[i + 1]) {
448
+ inLegacy = refersTo(args[i + 1], dir);
449
+ dir = resolve(dir, args[i + 1]);
450
+ i += 2;
451
+ } else i += 1;
452
+ }
453
+ const sub = args[i] || "";
454
+ if (GIT_WRITES.includes(sub) && (inLegacy || gitPathArgs(sub, args.slice(i + 1)).some((a) => refersTo(a, dir)))) return true;
455
+ }
456
+ if (PKG_MANAGERS.includes(name) && (args.includes("install") || args.includes("i"))) {
457
+ if (cwdInRoot || anyArg()) return true;
458
+ }
459
+ }
460
+ return false;
461
+ }
462
+
463
+ // shell: the payload is a shell event (Claude Bash, Cursor beforeShellExecution).
464
+ interface HookInput { target: string; command: string | null; cwd: string; shell: boolean }
465
+
466
+ async function readInput(): Promise<HookInput> {
260
467
  try {
261
468
  const stdin = await Bun.stdin.text();
262
- if (!stdin) return "";
469
+ if (!stdin) return { target: "", command: null, cwd: process.cwd(), shell: false };
263
470
  const input = JSON.parse(stdin);
471
+ source = detectSource(input);
472
+ const shell = input?.tool_name === "Bash"
473
+ || input?.hook_event_name === "beforeShellExecution"
474
+ || (input !== null && typeof input === "object" && "command" in input);
475
+ const cwd = typeof input?.cwd === "string" && input.cwd ? input.cwd : process.cwd();
476
+ // Claude Code Bash: tool_input.command. Cursor beforeShellExecution: command.
477
+ const command = typeof input?.tool_input?.command === "string"
478
+ ? input.tool_input.command
479
+ : typeof input?.command === "string" ? input.command : null;
264
480
  const filePath = input?.tool_input?.file_path
265
481
  || input?.tool_input?.path
266
482
  || input?.file_path
267
483
  || input?.path
268
484
  || "";
269
- return filePath ? realTarget(resolve(process.cwd(), filePath)) : "";
485
+ return {
486
+ target: filePath ? realTarget(resolve(cwd, filePath)) : "",
487
+ command: filePath ? null : command,
488
+ cwd,
489
+ shell: shell && !filePath,
490
+ };
270
491
  } catch {
271
- return ""; // stdin parse failed \u2014 continue with gate check
492
+ return { target: "", command: null, cwd: process.cwd(), shell: false }; // stdin parse failed \u2014 continue with gate check
272
493
  }
273
494
  }
274
495
 
496
+ const READ_ONLY_MESSAGE =
497
+ "This repo is read-only (manifest readOnly: true). It is the legacy source of truth. The gate override does not lift this block.";
498
+
275
499
  async function main() {
276
- const target = await readTarget();
500
+ const { target, command, cwd, shell } = await readInput();
501
+
502
+ // Shell commands: only the readOnly repo check applies. Everything else is allowed.
503
+ // A shell event without a usable command is allowed too (not the Edit/Write gate).
504
+ if (command !== null || shell) {
505
+ if (command === null) allow();
506
+ const manifest = await readManifest();
507
+ const roots = Object.values(manifest.repos)
508
+ .filter((repo) => repo.readOnly)
509
+ .map((repo) => realRoot(repo.path));
510
+ // Broken manifest with a readOnly repo: the repo can be anywhere, so any write
511
+ // outside the haren folder (and /dev) is blocked.
512
+ if (manifest.brokenReadOnly && shellWritesTo(command, cwd, [resolve("/")], [harenDir, realTarget("/dev")])) {
513
+ deny(BROKEN_MANIFEST_MESSAGE);
514
+ }
515
+ if (roots.length && shellWritesTo(command, cwd, roots)) {
516
+ deny(READ_ONLY_MESSAGE + " Shell commands that write into it are blocked too.");
517
+ }
518
+ allow();
519
+ }
277
520
 
278
521
  // Allow writes inside the haren folder \u2014 planning/discovery phases write artifacts there
279
522
  if (target && inside(target, harenDir)) allow();
280
523
 
524
+ if ((await readManifest()).brokenReadOnly) deny(BROKEN_MANIFEST_MESSAGE);
525
+
526
+ // Read-only repos (legacy source of truth) are blocked before any override check.
527
+ if (target) {
528
+ for (const repo of Object.values(await readRepos())) {
529
+ if (repo.readOnly && inside(target, realRoot(repo.path))) {
530
+ deny(READ_ONLY_MESSAGE);
531
+ }
532
+ }
533
+ }
534
+
281
535
  if (process.env.HAREN_GATE === "off") allow();
282
536
 
537
+ // A file outside the workspace (another project, temp files) is not ours to gate.
538
+ if (target && !inside(target, workspaceDir)) allow();
539
+
283
540
  const progressFile = Bun.file(resolve(harenDir, "progress.json"));
284
541
  if (!(await progressFile.exists())) allow();
285
542
 
@@ -299,8 +556,8 @@ async function main() {
299
556
  deny(message);
300
557
  }
301
558
 
302
- // No file path, or a file outside the workspace (temp files): legacy rule.
303
- if (!target || !inside(target, workspaceDir)) allow();
559
+ // No file path: legacy rule.
560
+ if (!target) allow();
304
561
 
305
562
  const repos = await readRepos();
306
563
  const roots: string[] = [];
@@ -390,9 +647,14 @@ function renderReposBlock(repos) {
390
647
  `;
391
648
  for (const field of REPO_FIELDS) {
392
649
  const value = repos[key][field];
393
- if (value)
650
+ if (typeof value === "boolean") {
651
+ if (value)
652
+ out += ` ${field}: true
653
+ `;
654
+ } else if (value) {
394
655
  out += ` ${field}: ${yamlScalar(value)}
395
656
  `;
657
+ }
396
658
  }
397
659
  }
398
660
  return out;
@@ -407,6 +669,13 @@ function toLf(text) {
407
669
  return text.replace(/\r\n/g, `
408
670
  `);
409
671
  }
672
+ function replaceTopLevelBlock(text, key, block) {
673
+ const eol = eolOf(text);
674
+ const out = replaceTopLevelBlockLf(toLf(text), key, toLf(block));
675
+ return eol === `
676
+ ` ? out : out.replace(/\n/g, `\r
677
+ `);
678
+ }
410
679
  function replaceTopLevelBlockLf(text, key, block) {
411
680
  const lines = text.split(`
412
681
  `);
@@ -428,6 +697,30 @@ ${block}`;
428
697
  return lines.join(`
429
698
  `);
430
699
  }
700
+ function setUiModeText(text, mode) {
701
+ const lines = text.split(`
702
+ `);
703
+ const start = lines.findIndex((l) => /^ui:\s*(#.*)?\r?$/.test(l));
704
+ if (start === -1)
705
+ return replaceTopLevelBlock(text, "ui", `ui:
706
+ mockups: ${mode}
707
+ `);
708
+ let end = start + 1;
709
+ while (end < lines.length && (/^\r?$/.test(lines[end]) || /^\s/.test(lines[end])))
710
+ end++;
711
+ for (let i = start + 1;i < end; i++) {
712
+ const m = /^(\s+mockups:\s*)([^\s#]*)(.*)$/.exec(lines[i]);
713
+ if (m) {
714
+ lines[i] = `${m[1]}${mode}${m[3]}`;
715
+ return lines.join(`
716
+ `);
717
+ }
718
+ }
719
+ const cr = lines[start].endsWith("\r") ? "\r" : "";
720
+ lines.splice(start + 1, 0, ` mockups: ${mode}${cr}`);
721
+ return lines.join(`
722
+ `);
723
+ }
431
724
  function migrateManifestText(text, mig) {
432
725
  const eol = eolOf(text);
433
726
  const lf = toLf(text);
@@ -457,7 +750,10 @@ project: ${yamlScalar(o.project)}
457
750
  mode: ${yamlScalar(o.mode)}
458
751
  language: ${yamlScalar(o.language)}
459
752
 
460
- ${renderReposBlock(o.repos)}
753
+ ${renderReposBlock(o.repos)}${o.mode === "migration" ? MIGRATION_SCAFFOLD(Object.keys(o.repos).length === 0) : ""}
754
+ ui:
755
+ mockups: ask # ask | ascii | browser | artifact
756
+
461
757
  sources:
462
758
  # Mode-specific inputs
463
759
  # docs: ./artifacts/00-baseline/requirements.pdf
@@ -477,17 +773,148 @@ iterations:
477
773
  }
478
774
  return text;
479
775
  }
480
- var REPO_FIELDS, YAML_KEYWORDS, YAML_SPECIAL_FLOAT;
776
+ function regex(value, field) {
777
+ if (typeof value !== "string" || !value) {
778
+ throw new Error(`manifest migration.${field} must be a regex string`);
779
+ }
780
+ try {
781
+ return new RegExp(value);
782
+ } catch {
783
+ throw new Error(`manifest migration.${field} is not a valid regex: ${value}`);
784
+ }
785
+ }
786
+ function readMigrationConfig(m) {
787
+ if (m.mode !== "migration")
788
+ return null;
789
+ const b = m.migration;
790
+ if (!b || typeof b !== "object") {
791
+ throw new Error("mode: migration needs a migration block in manifest.yaml");
792
+ }
793
+ if (Array.isArray(b))
794
+ throw new Error("manifest migration block must be a mapping");
795
+ if (b.adapter !== undefined && b.adapter !== null && typeof b.adapter !== "string") {
796
+ throw new Error("manifest migration.adapter must be a plugin name string");
797
+ }
798
+ if (b.liveLegacy !== undefined && b.liveLegacy !== null && typeof b.liveLegacy !== "boolean") {
799
+ throw new Error("manifest migration.liveLegacy must be true or false");
800
+ }
801
+ const acceptance = b.acceptance ?? "parity";
802
+ if (acceptance !== "parity" && acceptance !== "parity-with-approved-deviations") {
803
+ throw new Error("manifest migration.acceptance must be parity or parity-with-approved-deviations");
804
+ }
805
+ return {
806
+ adapter: typeof b.adapter === "string" && b.adapter ? b.adapter : undefined,
807
+ unitId: regex(b.unitId, "unitId"),
808
+ parentOf: b.parentOf === undefined ? undefined : regex(b.parentOf, "parentOf"),
809
+ acceptance,
810
+ liveLegacy: b.liveLegacy === true
811
+ };
812
+ }
813
+ function legacyRepo(m) {
814
+ const found = Object.entries(normalizeRepos(m.repos)).filter(([, r]) => r.role === "legacy");
815
+ if (found.length > 1) {
816
+ throw new Error(`manifest.yaml has more than one repo with role: legacy (${found.map(([k]) => k).join(", ")}); keep one`);
817
+ }
818
+ return found[0] ?? null;
819
+ }
820
+ var REPO_FIELDS, YAML_KEYWORDS, YAML_SPECIAL_FLOAT, UI_MODES, MIGRATION_SCAFFOLD = (withLegacyExample) => `${withLegacyExample ? ` # Add the read-only legacy repo, then remove the # marks:
821
+ # legacy_src: { path: ../legacy_src, role: legacy, readOnly: true }
822
+ ` : ""}
823
+ migration:
824
+ # repo paths are relative to this folder
825
+ # adapter: <plugin-name> # optional: a plugin that provides inventory, extract and gate
826
+ unitId: '^SCR_[A-Z]\\d{3}(_P\\d+)?$' # change it to match your legacy unit ids; change or remove parentOf below to match
827
+ parentOf: '^(SCR_[A-Z]\\d{3})_P\\d+$'
828
+ acceptance: parity-with-approved-deviations
829
+ liveLegacy: false
830
+ `;
481
831
  var init_manifest = __esm(() => {
482
- REPO_FIELDS = ["path", "remote", "default_branch", "role", "stack", "test_cmd"];
832
+ REPO_FIELDS = [
833
+ "path",
834
+ "remote",
835
+ "default_branch",
836
+ "role",
837
+ "stack",
838
+ "test_cmd",
839
+ "readOnly"
840
+ ];
483
841
  YAML_KEYWORDS = /^(true|false|null|yes|no|on|off|~)$/i;
484
842
  YAML_SPECIAL_FLOAT = /^[-+]?\.(inf|nan)$/i;
843
+ UI_MODES = ["ask", "ascii", "browser", "artifact"];
844
+ });
845
+
846
+ // src/plugins/paths.ts
847
+ import { isAbsolute } from "path";
848
+ function assertInsidePlugin(p, field) {
849
+ if (isAbsolute(p) || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split(/[\\/]/).includes("..")) {
850
+ throw new Error(`Plugin manifest: ${field} path must stay inside the plugin: ${p}`);
851
+ }
852
+ }
853
+ var init_paths = () => {};
854
+
855
+ // src/plugins/adapter-spec.ts
856
+ function validateAdapter(raw) {
857
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
858
+ throw new Error("Plugin manifest: adapter must be an object");
859
+ }
860
+ const a = raw;
861
+ if (typeof a.unitKind !== "string" || !a.unitKind) {
862
+ throw new Error("Plugin manifest: adapter.unitKind is required");
863
+ }
864
+ const commands = {};
865
+ if (a.commands !== undefined) {
866
+ if (!a.commands || typeof a.commands !== "object" || Array.isArray(a.commands)) {
867
+ throw new Error("Plugin manifest: adapter.commands must be an object");
868
+ }
869
+ for (const [name, command] of Object.entries(a.commands)) {
870
+ if (!ADAPTER_COMMANDS.includes(name)) {
871
+ throw new Error(`Plugin manifest: Unknown adapter command: ${name}`);
872
+ }
873
+ if (typeof command !== "string" || !command) {
874
+ throw new Error(`Plugin manifest: adapter command ${name} needs a command string`);
875
+ }
876
+ for (const [, key] of command.matchAll(/\{([^{}]*)\}/g)) {
877
+ if (!PLACEHOLDERS.includes(key)) {
878
+ throw new Error(`Plugin manifest: adapter command ${name} has unknown placeholder {${key}}`);
879
+ }
880
+ }
881
+ commands[name] = command;
882
+ }
883
+ }
884
+ const skills = {};
885
+ if (a.skills !== undefined) {
886
+ if (!a.skills || typeof a.skills !== "object" || Array.isArray(a.skills)) {
887
+ throw new Error("Plugin manifest: adapter.skills must be an object");
888
+ }
889
+ const spec = a.skills.spec;
890
+ if (spec !== undefined) {
891
+ if (typeof spec !== "string" || !spec) {
892
+ throw new Error("Plugin manifest: adapter.skills.spec must be a string");
893
+ }
894
+ skills.spec = spec;
895
+ }
896
+ }
897
+ let semantics;
898
+ if (a.semantics !== undefined) {
899
+ if (typeof a.semantics !== "string" || !a.semantics) {
900
+ throw new Error("Plugin manifest: adapter.semantics must be a path string");
901
+ }
902
+ assertInsidePlugin(a.semantics, "adapter.semantics");
903
+ semantics = a.semantics;
904
+ }
905
+ return { unitKind: a.unitKind, commands, skills, semantics };
906
+ }
907
+ var ADAPTER_COMMANDS, PLACEHOLDERS;
908
+ var init_adapter_spec = __esm(() => {
909
+ init_paths();
910
+ ADAPTER_COMMANDS = ["inventory", "extract", "gate"];
911
+ PLACEHOLDERS = ["legacyRoot", "unit", "unitDir", "specPath"];
485
912
  });
486
913
 
487
914
  // src/plugins/manifest.ts
488
915
  import { existsSync as existsSync2 } from "fs";
489
916
  import { readFile } from "fs/promises";
490
- import { isAbsolute, join as join3 } from "path";
917
+ import { join as join3 } from "path";
491
918
  function stringList(value, field) {
492
919
  if (value === undefined)
493
920
  return [];
@@ -498,11 +925,8 @@ function stringList(value, field) {
498
925
  }
499
926
  function relativePathList(value, field) {
500
927
  const list = stringList(value, field);
501
- for (const p of list) {
502
- if (isAbsolute(p) || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split(/[\\/]/).includes("..")) {
503
- throw new Error(`Plugin manifest: ${field} path must stay inside the plugin: ${p}`);
504
- }
505
- }
928
+ for (const p of list)
929
+ assertInsidePlugin(p, field);
506
930
  return list;
507
931
  }
508
932
  function validateManifest(raw, packageVersion) {
@@ -513,8 +937,11 @@ function validateManifest(raw, packageVersion) {
513
937
  throw new Error("Plugin manifest: name is required");
514
938
  if (!NAME.test(m.name))
515
939
  throw new Error(`Plugin manifest: name must be kebab-case: ${m.name}`);
516
- if (m.harenApi !== HAREN_API) {
517
- throw new Error(`Plugin manifest: this haren supports harenApi "${HAREN_API}", got ${JSON.stringify(m.harenApi)}`);
940
+ if (typeof m.harenApi !== "string" || !HAREN_APIS.includes(m.harenApi)) {
941
+ throw new Error(`Plugin manifest: this haren supports harenApi ${HAREN_APIS.map((v) => `"${v}"`).join(" or ")}, got ${JSON.stringify(m.harenApi)}`);
942
+ }
943
+ if (m.adapter !== undefined && m.harenApi !== "2") {
944
+ throw new Error('Plugin manifest: adapter needs harenApi "2"');
518
945
  }
519
946
  let version;
520
947
  if (packageVersion !== undefined) {
@@ -565,14 +992,15 @@ function validateManifest(raw, packageVersion) {
565
992
  return {
566
993
  name: m.name,
567
994
  version,
568
- harenApi: HAREN_API,
995
+ harenApi: m.harenApi,
569
996
  description: typeof m.description === "string" ? m.description : undefined,
570
997
  requires,
571
998
  setup: stringList(m.setup, "setup"),
572
999
  hooks,
573
1000
  config,
574
1001
  skills: relativePathList(m.skills, "skills"),
575
- agents: relativePathList(m.agents, "agents")
1002
+ agents: relativePathList(m.agents, "agents"),
1003
+ ...m.adapter !== undefined ? { adapter: validateAdapter(m.adapter) } : {}
576
1004
  };
577
1005
  }
578
1006
  async function readInstalledManifest(dir) {
@@ -589,8 +1017,11 @@ async function readInstalledManifest(dir) {
589
1017
  }
590
1018
  return validateManifest(raw, packageVersion);
591
1019
  }
592
- var HAREN_API = "1", HOOK_NAMES, NAME;
1020
+ var HAREN_APIS, HOOK_NAMES, NAME;
593
1021
  var init_manifest2 = __esm(() => {
1022
+ init_adapter_spec();
1023
+ init_paths();
1024
+ HAREN_APIS = ["1", "2"];
594
1025
  HOOK_NAMES = ["session-start", "after-plan", "on-task-status"];
595
1026
  NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
596
1027
  });
@@ -612,7 +1043,12 @@ async function readPlugins(harenDir) {
612
1043
  const path = pluginsPath(harenDir);
613
1044
  if (!existsSync3(path))
614
1045
  return { version: 1, plugins: {} };
615
- const data = JSON.parse(await readFile2(path, "utf-8"));
1046
+ let data;
1047
+ try {
1048
+ data = JSON.parse(await readFile2(path, "utf-8"));
1049
+ } catch (e) {
1050
+ throw new Error(`plugins.json is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
1051
+ }
616
1052
  return { version: 1, plugins: data.plugins ?? {} };
617
1053
  }
618
1054
  async function writePlugins(harenDir, data) {
@@ -703,7 +1139,7 @@ function mergeClaudeSettings(existing, command) {
703
1139
  data.hooks ??= {};
704
1140
  data.hooks.PreToolUse = [
705
1141
  ...withoutGate(data.hooks.PreToolUse),
706
- { matcher: "Edit|Write", hooks: [{ type: "command", command }] }
1142
+ { matcher: "Edit|Write|Bash", hooks: [{ type: "command", command }] }
707
1143
  ];
708
1144
  return `${JSON.stringify(data, null, 2)}
709
1145
  `;
@@ -716,6 +1152,10 @@ function mergeCursorHooks(existing, command) {
716
1152
  ...withoutGate(data.hooks.beforeFileEdit),
717
1153
  { command, type: "command", timeout: 10 }
718
1154
  ];
1155
+ data.hooks.beforeShellExecution = [
1156
+ ...withoutGate(data.hooks.beforeShellExecution),
1157
+ { command, type: "command", timeout: 10 }
1158
+ ];
719
1159
  data.hooks.preToolUse = [
720
1160
  ...withoutGate(data.hooks.preToolUse),
721
1161
  { command, matcher: "write", type: "command", timeout: 10 }
@@ -1270,6 +1710,10 @@ async function readProgress(path) {
1270
1710
  mod.features = {};
1271
1711
  if (!isObject(mod.lastCommit))
1272
1712
  mod.lastCommit = {};
1713
+ if (!isObject(mod.units))
1714
+ mod.units = {};
1715
+ for (const [unit, status] of Object.entries(mod.units))
1716
+ assertUnitStatus(unit, status);
1273
1717
  }
1274
1718
  return progress;
1275
1719
  }
@@ -1284,9 +1728,11 @@ function updateModuleStatus(progress, moduleName, newStatus) {
1284
1728
  if (!mod) {
1285
1729
  throw new Error(`Module '${moduleName}' not found in progress`);
1286
1730
  }
1287
- const allowed = VALID_MODULE_TRANSITIONS[mod.status];
1731
+ const known = Object.hasOwn(VALID_MODULE_TRANSITIONS, mod.status);
1732
+ const allowed = known ? VALID_MODULE_TRANSITIONS[mod.status] : LEGACY_MODULE_EXITS;
1288
1733
  if (!allowed.includes(newStatus)) {
1289
- throw new Error(`Invalid module transition: ${mod.status} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1734
+ const from = known ? mod.status : `${mod.status} (unknown status from an old progress file)`;
1735
+ throw new Error(`Invalid module transition: ${from} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1290
1736
  }
1291
1737
  return {
1292
1738
  ...progress,
@@ -1310,7 +1756,7 @@ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1310
1756
  if (currentStatus === undefined) {
1311
1757
  throw new Error(`Feature '${featureName}' not found in module '${moduleName}'`);
1312
1758
  }
1313
- const allowed = VALID_FEATURE_TRANSITIONS[currentStatus];
1759
+ const allowed = Object.hasOwn(VALID_FEATURE_TRANSITIONS, currentStatus) ? VALID_FEATURE_TRANSITIONS[currentStatus] : LEGACY_FEATURE_EXITS;
1314
1760
  if (!allowed.includes(newStatus)) {
1315
1761
  throw new Error(`Invalid feature transition: ${currentStatus} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1316
1762
  }
@@ -1329,27 +1775,84 @@ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1329
1775
  }
1330
1776
  };
1331
1777
  }
1778
+ function assertUnitStatus(unit, status) {
1779
+ if (!UNIT_STATUSES.includes(status)) {
1780
+ throw new Error(`Unknown unit status '${String(status)}' for unit '${unit}'`);
1781
+ }
1782
+ }
1783
+ function unitRank(s) {
1784
+ if (s === "static-review-only")
1785
+ return UNIT_LINE.indexOf("built");
1786
+ if (s === "blocked")
1787
+ return -1;
1788
+ return UNIT_LINE.indexOf(s);
1789
+ }
1790
+ function unitAtLeast(status, floor) {
1791
+ return unitRank(status) >= unitRank(floor);
1792
+ }
1793
+ function unitsBelow(mod, floor) {
1794
+ return Object.entries(mod.units ?? {}).filter(([, s]) => !unitAtLeast(s, floor)).map(([u]) => u);
1795
+ }
1796
+ function updateUnitStatus(progress, moduleName, unit, to) {
1797
+ const mod = progress.modules[moduleName];
1798
+ if (!mod)
1799
+ throw new Error(`Module '${moduleName}' not found`);
1800
+ const units = mod.units ?? {};
1801
+ const from = units[unit];
1802
+ if (from !== undefined)
1803
+ assertUnitStatus(unit, from);
1804
+ if (from === undefined) {
1805
+ if (to !== "inventoried") {
1806
+ throw new Error(`A new unit can start only at 'inventoried' (got '${to}')`);
1807
+ }
1808
+ } else if (!VALID_UNIT_TRANSITIONS[from].includes(to)) {
1809
+ throw new Error(`Invalid unit transition: ${from} \u2192 ${to}. Allowed: ${VALID_UNIT_TRANSITIONS[from].join(", ")}`);
1810
+ }
1811
+ return {
1812
+ ...progress,
1813
+ modules: {
1814
+ ...progress.modules,
1815
+ [moduleName]: {
1816
+ ...mod,
1817
+ units: { ...units, [unit]: to },
1818
+ lastUpdated: new Date().toISOString()
1819
+ }
1820
+ }
1821
+ };
1822
+ }
1332
1823
  function migrateProgress(raw, repoKeyFor) {
1333
1824
  if (!raw || typeof raw !== "object")
1334
1825
  return { progress: raw, changed: false };
1335
1826
  const data = raw;
1336
- if ((data.version ?? 1) >= PROGRESS_VERSION)
1827
+ const version = data.version ?? 1;
1828
+ if (version >= PROGRESS_VERSION)
1337
1829
  return { progress: raw, changed: false };
1338
1830
  const modules = {};
1339
1831
  for (const [name, mod] of Object.entries(data.modules ?? {})) {
1340
1832
  const old = mod?.lastCommit;
1341
1833
  let lastCommit = {};
1342
- if (typeof old === "string" && old)
1834
+ if (version < 2 && typeof old === "string" && old) {
1343
1835
  lastCommit = { [repoKeyFor(name) || "default"]: old };
1344
- else if (old && typeof old === "object" && !Array.isArray(old) && Object.values(old).every((v) => typeof v === "string")) {
1836
+ } else if (isObject(old) && Object.values(old).every((v) => typeof v === "string")) {
1345
1837
  lastCommit = old;
1346
1838
  }
1347
- modules[name] = { ...mod, lastCommit };
1839
+ const units = isObject(mod?.units) ? mod.units : {};
1840
+ modules[name] = { ...isObject(mod) ? mod : {}, lastCommit, units };
1348
1841
  }
1349
1842
  return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
1350
1843
  }
1351
- var MODULE_STATUSES, FEATURE_STATUSES, VALID_MODULE_TRANSITIONS, STATUS_TO_PHASE, VALID_FEATURE_TRANSITIONS, PROGRESS_VERSION = 2;
1844
+ 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;
1352
1845
  var init_progress = __esm(() => {
1846
+ UNIT_LINE = [
1847
+ "inventoried",
1848
+ "extracted",
1849
+ "spec-draft",
1850
+ "spec-approved",
1851
+ "built",
1852
+ "verified",
1853
+ "parity-signed"
1854
+ ];
1855
+ UNIT_STATUSES = [...UNIT_LINE, "blocked", "static-review-only"];
1353
1856
  MODULE_STATUSES = [
1354
1857
  "discovered",
1355
1858
  "decomposed",
@@ -1378,6 +1881,7 @@ var init_progress = __esm(() => {
1378
1881
  released: [],
1379
1882
  blocked: ["implementing", "planned"]
1380
1883
  };
1884
+ LEGACY_MODULE_EXITS = ["decomposed", "planned"];
1381
1885
  STATUS_TO_PHASE = {
1382
1886
  discovered: "discover",
1383
1887
  decomposed: "decompose",
@@ -1388,6 +1892,7 @@ var init_progress = __esm(() => {
1388
1892
  released: "release",
1389
1893
  blocked: "blocked"
1390
1894
  };
1895
+ LEGACY_FEATURE_EXITS = ["pending", "in-progress"];
1391
1896
  VALID_FEATURE_TRANSITIONS = {
1392
1897
  pending: ["in-progress"],
1393
1898
  "in-progress": ["evaluating"],
@@ -1396,6 +1901,25 @@ var init_progress = __esm(() => {
1396
1901
  passing: [],
1397
1902
  blocked: ["in-progress"]
1398
1903
  };
1904
+ VALID_UNIT_TRANSITIONS = {
1905
+ inventoried: ["extracted", "blocked"],
1906
+ extracted: ["spec-draft", "blocked"],
1907
+ "spec-draft": ["spec-approved", "extracted", "blocked"],
1908
+ "spec-approved": ["built", "spec-draft", "blocked"],
1909
+ built: ["verified", "static-review-only", "blocked"],
1910
+ "static-review-only": ["verified", "built", "blocked"],
1911
+ verified: ["parity-signed", "built", "blocked"],
1912
+ "parity-signed": ["built"],
1913
+ blocked: [
1914
+ "inventoried",
1915
+ "extracted",
1916
+ "spec-draft",
1917
+ "spec-approved",
1918
+ "built",
1919
+ "static-review-only",
1920
+ "verified"
1921
+ ]
1922
+ };
1399
1923
  });
1400
1924
 
1401
1925
  // src/lib/version.ts
@@ -1583,7 +2107,7 @@ async function installPlugin(ref, ctx) {
1583
2107
  if (!official) {
1584
2108
  ctx.io.log("This plugin is not in the haren registry. Its hooks run as code with your user permissions.");
1585
2109
  if (!await ctx.io.confirm("Install it?"))
1586
- throw new Error("Plugin install cancelled");
2110
+ throw new Error(INSTALL_CANCELLED);
1587
2111
  }
1588
2112
  const manifest = await stage(source, ctx);
1589
2113
  try {
@@ -1660,7 +2184,7 @@ async function restorePlugins(ctx, report) {
1660
2184
  restored.push(manifest.name);
1661
2185
  } catch (err) {
1662
2186
  const message = err.message;
1663
- if (message === "Plugin install cancelled") {
2187
+ if (message === INSTALL_CANCELLED) {
1664
2188
  report.warn(`plugin ${name}: skipped, not confirmed. Run again with --yes to install it.`);
1665
2189
  } else {
1666
2190
  report.error(`plugin ${name}: ${message}`);
@@ -1692,7 +2216,7 @@ async function refreshPlugins(ctx, skip = []) {
1692
2216
  await writePlugins(ctx.harenDir, state);
1693
2217
  return warnings;
1694
2218
  }
1695
- var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming");
2219
+ var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming"), INSTALL_CANCELLED = "Plugin install cancelled";
1696
2220
  var init_install = __esm(() => {
1697
2221
  init_registry();
1698
2222
  init_source();
@@ -1718,7 +2242,7 @@ function readLine() {
1718
2242
  stdin.on("data", onData);
1719
2243
  });
1720
2244
  }
1721
- async function prompt(question, defaultValue) {
2245
+ async function prompt2(question, defaultValue) {
1722
2246
  const suffix = defaultValue ? ` \x1B[2m(${defaultValue})\x1B[0m` : "";
1723
2247
  process.stdout.write(` \x1B[36m?\x1B[0m ${question}${suffix} `);
1724
2248
  const value = await readLine();
@@ -1850,6 +2374,9 @@ function getDirectories(iterations) {
1850
2374
  "skills/update-links",
1851
2375
  "skills/update-tracking",
1852
2376
  "skills/generate-mockup",
2377
+ "skills/visual-companion",
2378
+ "skills/ui-review",
2379
+ "skills/collect-components",
1853
2380
  "skills/onboard",
1854
2381
  "artifacts/_registry",
1855
2382
  "artifacts/00-baseline",
@@ -1925,6 +2452,7 @@ Master registry of all artifacts in this Haren workspace.
1925
2452
  await writeFile5(gitignore, `.agent.json
1926
2453
  .agent.pid
1927
2454
  .plugins/
2455
+ .companion/
1928
2456
  `);
1929
2457
  await writeGateScript(targetDir);
1930
2458
  await scaffoldSkillMd(targetDir);
@@ -1954,6 +2482,7 @@ You are operating within the Haren agentic SDLC framework.
1954
2482
  1. Read \`manifest.yaml\` to understand the project
1955
2483
  2. Read \`progress.json\` to understand current state
1956
2484
  3. Read \`artifacts/_registry/artifact-index.md\` for artifact inventory
2485
+ - Run \`haren track check\`. It reports repo keys missing from \`manifest.yaml\` and artifacts missing from the index. Tell the user about each FAIL line before other work
1957
2486
  4. **Scan \`artifacts/00-baseline/\`** for documents (PDFs, docs, markdown, etc.)
1958
2487
  - If docs found and mode is \`undecided\` \u2192 auto-recommend \`blueprint\` mode
1959
2488
  - If docs found and discovery hasn't started \u2192 suggest starting discover phase
@@ -1966,8 +2495,11 @@ You are operating within the Haren agentic SDLC framework.
1966
2495
  - Has docs/specs \u2192 tell them to drop docs in \`artifacts/00-baseline/\` then \`blueprint\`
1967
2496
  - Starting from scratch, just an idea \u2192 \`explore\`
1968
2497
  - Has existing code \u2192 \`inherit\`
2498
+ - Rewrite of a legacy system with parity as the bar \u2192 \`migration\`
1969
2499
  6. Suggest next action based on current state
1970
2500
 
2501
+ Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | ascii | browser | artifact). See the visual-companion skill.
2502
+
1971
2503
  ## Available Actions
1972
2504
 
1973
2505
  | Intent | Skill | Agent |
@@ -1975,6 +2507,7 @@ You are operating within the Haren agentic SDLC framework.
1975
2507
  | Design a feature | discover/ (brainstorming) | Researcher |
1976
2508
  | Start a new project | discover/ | Researcher |
1977
2509
  | Research a topic | research/ | Researcher |
2510
+ | Extract legacy units into specs (migration) | extract/ | Researcher |
1978
2511
  | Break into modules | decompose/ | Architect |
1979
2512
  | Extract stories from docs | extract-stories/ | Researcher |
1980
2513
  | Plan a module | plan/ | Planner |
@@ -1984,6 +2517,9 @@ You are operating within the Haren agentic SDLC framework.
1984
2517
  | Search artifacts | search-artifact/ | \u2014 |
1985
2518
  | Release completed modules | release/ | Architect |
1986
2519
  | Draw a UI wireframe or compare screen options | generate-mockup/ | \u2014 |
2520
+ | Show mockups or options in a browser tab | visual-companion/ (\`haren companion\`) | \u2014 |
2521
+ | Review a screen against UX heuristics | ui-review/ | \u2014 |
2522
+ | Catalog common UI components, shared services and functions | collect-components/ | Developer |
1987
2523
  | Update status, artifacts, events | update-tracking/ (\`haren track\`) | \u2014 |
1988
2524
  | Onboard to the project / check the workspace | onboard/ (\`/haren-onboard\`) | \u2014 |
1989
2525
 
@@ -1991,6 +2527,7 @@ You are operating within the Haren agentic SDLC framework.
1991
2527
 
1992
2528
  - User says "let's build X" or describes a new feature \u2192 discover/ skill (triggers brainstorming)
1993
2529
  - User says "what's next?" \u2192 read \`progress.json\` \u2192 suggest action
2530
+ - User says "extract <unit>" or "spec the legacy screen" (migration mode) \u2192 extract/ skill
1994
2531
  - User says "extract stories" or "break down the PRD" or "create stories from docs" \u2192 extract-stories/ skill
1995
2532
  - User says "let's work on {module}" \u2192 check module phase \u2192 dispatch appropriate skill
1996
2533
  - User says "I need to research X" \u2192 research/ skill
@@ -2018,6 +2555,8 @@ Change \`progress.json\`, \`events/events.jsonl\` and \`artifacts/_registry/arti
2018
2555
  | Module definition | Discover phase | \`artifacts/03-modules/{module}/module.md\` |
2019
2556
  | Design (architecture) | Dev | \`artifacts/04-plans/{module}/design.md\` |
2020
2557
  | Tasks (implementation) | Dev | \`artifacts/04-plans/{module}/[iteration-{N}/]tasks.md\` |
2558
+ | Implementation checklist | Dev | \`artifacts/04-plans/{module}/[iteration-{N}/]checklist.md\` |
2559
+ | Component catalog | Dev | \`artifacts/03-modules/component-catalog.md\` |
2021
2560
 
2022
2561
  ## Plan Paths
2023
2562
 
@@ -2035,7 +2574,7 @@ All skills that read or write plan artifacts MUST resolve paths using this conve
2035
2574
  - The plan skill writes to BOTH master and active paths (it is the only skill that does this)
2036
2575
 
2037
2576
  **If no \`iterations\` block in manifest.yaml:**
2038
- - **Active plan path:** \`artifacts/04-plans/{module}/\` \u2014 contains design.md, tasks.md
2577
+ - **Active plan path:** \`artifacts/04-plans/{module}/\` \u2014 contains design.md, tasks.md, checklist.md
2039
2578
  - **Master plan path:** (same as active)
2040
2579
 
2041
2580
  When a skill says "read the spec", it means from \`artifacts/03-modules/{module}/spec.md\`.
@@ -2057,7 +2596,7 @@ When a skill says "read the master plan" or needs full module context, it means
2057
2596
 
2058
2597
  ### Dependent modules
2059
2598
 
2060
- The decompose skill records module dependencies in \`progress.json\` \`dependencies\` (for example \`"web": ["api"]\`). If module B depends on module A:
2599
+ The decompose skill records module dependencies with \`haren track depends <module> <dep>\` (for example \`haren track depends web api\`). They are stored in \`progress.json\` \`dependencies\`. If module B depends on module A:
2061
2600
 
2062
2601
  - **A is merged:** create \`feat/<B>\` from the default branch as usual.
2063
2602
  - **A is not merged yet:** create \`feat/<B>\` from \`feat/<A>\`. Record the base in the session log, for example "baseBranch: feat/<A>". Merge A into the default branch first. Then rebase or merge B onto the default branch, and only then merge B.
@@ -2112,7 +2651,7 @@ function parseInitArgs(args) {
2112
2651
  break;
2113
2652
  case "--mode":
2114
2653
  if (!MODES.includes(value)) {
2115
- throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, or undecided.`);
2654
+ throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, migration, or undecided.`);
2116
2655
  }
2117
2656
  out.mode = value;
2118
2657
  i++;
@@ -2260,10 +2799,10 @@ async function promptIterations() {
2260
2799
  }, "no");
2261
2800
  if (enable !== "yes")
2262
2801
  return;
2263
- const duration = await prompt("Iteration duration:", "2 weeks");
2802
+ const duration = await prompt2("Iteration duration:", "2 weeks");
2264
2803
  const today = new Date().toISOString().split("T")[0];
2265
- const startDate = await prompt("Start date:", today);
2266
- const demoDay = await prompt("Demo day:", "Friday");
2804
+ const startDate = await prompt2("Start date:", today);
2805
+ const demoDay = await prompt2("Demo day:", "Friday");
2267
2806
  return { enabled: true, duration, startDate, demoDay };
2268
2807
  }
2269
2808
  async function runSetup(location, opts) {
@@ -2389,15 +2928,15 @@ async function init(args) {
2389
2928
  }, "workspace") : "workspace");
2390
2929
  console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
2391
2930
  console.log("");
2392
- const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt("haren folder name:", "haren") : "haren");
2931
+ const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt2("haren folder name:", "haren") : "haren");
2393
2932
  const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join10(rootDir, harenDirName);
2394
2933
  const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
2395
2934
  const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
2396
2935
  let selected = defaults;
2397
- const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt("Project name:", basename4(rootDir)) : basename4(rootDir));
2936
+ const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt2("Project name:", basename4(rootDir)) : basename4(rootDir));
2398
2937
  const existingMode = MODES.find((m) => m === existingManifest?.mode);
2399
2938
  const mode = opts.mode ?? existingMode ?? (interactive ? await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided") : "undecided");
2400
- const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt("Preferred language:", "English") : "English");
2939
+ const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt2("Preferred language:", "English") : "English");
2401
2940
  const iterations = opts.iterations ?? (existingManifest ? manifestIterations(existingManifest) : interactive ? await promptIterations() : undefined);
2402
2941
  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");
2403
2942
  while (true) {
@@ -2470,7 +3009,7 @@ var init_init = __esm(() => {
2470
3009
  init_version();
2471
3010
  init_install();
2472
3011
  init_registry();
2473
- MODES = ["blueprint", "explore", "inherit", "undecided"];
3012
+ MODES = ["blueprint", "explore", "inherit", "migration", "undecided"];
2474
3013
  EDITORS = ["claude-code", "cursor", "both"];
2475
3014
  EDITOR_DESCRIPTIONS = {
2476
3015
  "claude-code": "Claude Code CLI / IDE extension",
@@ -2481,17 +3020,64 @@ var init_init = __esm(() => {
2481
3020
  blueprint: "Greenfield project with existing docs",
2482
3021
  explore: "Greenfield project from scratch",
2483
3022
  inherit: "Brownfield project with existing code",
3023
+ migration: "Rewrite of a legacy system with parity as the bar",
2484
3024
  undecided: "Decide later \u2014 LLM will help you choose"
2485
3025
  };
2486
3026
  });
2487
3027
 
3028
+ // src/lib/changelog.ts
3029
+ import { existsSync as existsSync13, readFileSync as readFileSync2 } from "fs";
3030
+ import { resolve as resolve10 } from "path";
3031
+ function readChangelog(candidates) {
3032
+ const probes = candidates ?? [
3033
+ resolve10(import.meta.dir, "..", "CHANGELOG.md"),
3034
+ resolve10(import.meta.dir, "..", "..", "..", "..", "CHANGELOG.md")
3035
+ ];
3036
+ for (const path of probes) {
3037
+ if (existsSync13(path))
3038
+ return readFileSync2(path, "utf-8");
3039
+ }
3040
+ return null;
3041
+ }
3042
+ function compareVersions(a, b) {
3043
+ const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
3044
+ const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
3045
+ for (let i = 0;i < 3; i++) {
3046
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
3047
+ if (d !== 0)
3048
+ return d;
3049
+ }
3050
+ return 0;
3051
+ }
3052
+ function parseChangelog(text) {
3053
+ const sections = [];
3054
+ let current = null;
3055
+ for (const line of text.split(/\r?\n/)) {
3056
+ const m = /^##\s+\[?v?(\d+\.\d+\.\d+)\]?/.exec(line);
3057
+ if (m) {
3058
+ current = { version: m[1], body: "" };
3059
+ sections.push(current);
3060
+ } else if (current) {
3061
+ current.body += `${line}
3062
+ `;
3063
+ }
3064
+ }
3065
+ for (const s of sections)
3066
+ s.body = s.body.trim();
3067
+ return sections;
3068
+ }
3069
+ function whatsNew(text, from, to) {
3070
+ 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));
3071
+ }
3072
+ var init_changelog = () => {};
3073
+
2488
3074
  // src/commands/upgrade.ts
2489
3075
  import { mkdir as mkdir7, readdir as readdir5, copyFile as copyFile2, readFile as readFile9, stat as stat2, writeFile as writeFile6 } from "fs/promises";
2490
- import { join as join11, resolve as resolve10 } from "path";
2491
- import { existsSync as existsSync13 } from "fs";
3076
+ import { join as join11, resolve as resolve11 } from "path";
3077
+ import { existsSync as existsSync14 } from "fs";
2492
3078
  async function moduleRepoKey(harenDir, moduleName) {
2493
3079
  const path = join11(harenDir, "artifacts", "03-modules", moduleName, "module.md");
2494
- if (!existsSync13(path))
3080
+ if (!existsSync14(path))
2495
3081
  return;
2496
3082
  const match = (await readFile9(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
2497
3083
  return match?.[1].split(",")[0]?.trim().replace(/^["']|["']$/g, "") || undefined;
@@ -2515,7 +3101,7 @@ async function planMigration(location) {
2515
3101
  const map = {};
2516
3102
  let foundRemote = false;
2517
3103
  for (const [key, entry] of Object.entries(current)) {
2518
- const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve10(harenDir, entry.path)) : null);
3104
+ const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve11(harenDir, entry.path)) : null);
2519
3105
  if (remote && !entry.remote)
2520
3106
  foundRemote = true;
2521
3107
  map[key] = remote ? { ...entry, remote } : entry;
@@ -2532,7 +3118,7 @@ async function planMigration(location) {
2532
3118
  });
2533
3119
  let progress = null;
2534
3120
  const progressPath = join11(harenDir, "progress.json");
2535
- if (existsSync13(progressPath)) {
3121
+ if (existsSync14(progressPath)) {
2536
3122
  const before = await readFile9(progressPath, "utf-8");
2537
3123
  let raw;
2538
3124
  try {
@@ -2549,7 +3135,7 @@ async function planMigration(location) {
2549
3135
  if (result.changed) {
2550
3136
  progress = { before, after: `${JSON.stringify(result.progress, null, 2)}
2551
3137
  ` };
2552
- steps.push("progress.json: migrate to version 2 (lastCommit per repo)");
3138
+ steps.push(raw.version === 2 ? "progress.json: migrate to version 3 (units)" : "progress.json: migrate to version 3 (lastCommit per repo, units)");
2553
3139
  }
2554
3140
  }
2555
3141
  const gitignore = await planGitignore(harenDir);
@@ -2567,12 +3153,13 @@ async function planMigration(location) {
2567
3153
  gitignore,
2568
3154
  layout,
2569
3155
  editor,
2570
- steps
3156
+ steps,
3157
+ fromVersion: hasMarker(manifest) ? String(manifest.haren?.version) : undefined
2571
3158
  };
2572
3159
  }
2573
3160
  async function planGitignore(harenDir) {
2574
3161
  const path = join11(harenDir, ".gitignore");
2575
- const before = existsSync13(path) ? await readFile9(path, "utf-8") : "";
3162
+ const before = existsSync14(path) ? await readFile9(path, "utf-8") : "";
2576
3163
  const lines = new Set(before.split(/\r?\n/).map((l) => l.trim()));
2577
3164
  const missing = IGNORED.filter((f) => !lines.has(f));
2578
3165
  if (missing.length === 0)
@@ -2704,11 +3291,31 @@ async function upgrade(args) {
2704
3291
  console.log(` \x1B[32m\u2713\x1B[0m Upgraded ${totalFiles + 2} framework files.`);
2705
3292
  console.log(` \x1B[2mYour artifacts are untouched. Manifest and progress were migrated if needed.\x1B[0m`);
2706
3293
  console.log("");
3294
+ printWhatsNew(migration.fromVersion, HAREN_VERSION);
3295
+ }
3296
+ function printWhatsNew(from, to, text = readChangelog(), log = console.log) {
3297
+ if (!text || from === to)
3298
+ return;
3299
+ const sections = whatsNew(text, from, to);
3300
+ if (!sections.length)
3301
+ return;
3302
+ log(`\x1B[36m What's new${from ? ` since ${from}` : ""}\x1B[0m`);
3303
+ for (const s of sections) {
3304
+ log("");
3305
+ log(` \x1B[1m${s.version}\x1B[0m`);
3306
+ for (const line of s.body.split(`
3307
+ `))
3308
+ log(line ? ` ${line}` : "");
3309
+ }
3310
+ log("");
3311
+ log(" \x1B[2mFull changelog: https://github.com/odarino/haren/blob/main/CHANGELOG.md\x1B[0m");
3312
+ log("");
2707
3313
  }
2708
3314
  var IGNORED, FRAMEWORK_DIRS, USER_FILES;
2709
3315
  var init_upgrade = __esm(() => {
2710
3316
  init_content_dir();
2711
3317
  init_version();
3318
+ init_changelog();
2712
3319
  init_git();
2713
3320
  init_detect();
2714
3321
  init_manifest();
@@ -2717,7 +3324,7 @@ var init_upgrade = __esm(() => {
2717
3324
  init_root_files();
2718
3325
  init_install();
2719
3326
  init_templates();
2720
- IGNORED = [".agent.json", ".agent.pid", ".plugins/"];
3327
+ IGNORED = [".agent.json", ".agent.pid", ".plugins/", ".companion/"];
2721
3328
  FRAMEWORK_DIRS = ["agents", "skills", "templates"];
2722
3329
  USER_FILES = ["FEEDBACK.md", "artifacts/", "events/"];
2723
3330
  });
@@ -2818,8 +3425,8 @@ var init_artifact_reader = __esm(() => {
2818
3425
  });
2819
3426
 
2820
3427
  // src/agent/cli-executor.ts
2821
- async function executeCLI(cli, prompt, onOutput) {
2822
- const args = buildCLIArgs(cli, prompt);
3428
+ async function executeCLI(cli, prompt2, onOutput) {
3429
+ const args = buildCLIArgs(cli, prompt2);
2823
3430
  try {
2824
3431
  const proc = Bun.spawn(args, {
2825
3432
  stdout: "pipe",
@@ -2851,16 +3458,16 @@ async function executeCLI(cli, prompt, onOutput) {
2851
3458
  onOutput("", true);
2852
3459
  }
2853
3460
  }
2854
- function buildCLIArgs(cli, prompt) {
3461
+ function buildCLIArgs(cli, prompt2) {
2855
3462
  switch (cli) {
2856
3463
  case "claude":
2857
- return ["claude", "--print", prompt];
3464
+ return ["claude", "--print", prompt2];
2858
3465
  case "cursor":
2859
- return ["cursor", "--prompt", prompt];
3466
+ return ["cursor", "--prompt", prompt2];
2860
3467
  case "github-copilot-cli":
2861
- return ["github-copilot-cli", prompt];
3468
+ return ["github-copilot-cli", prompt2];
2862
3469
  default:
2863
- return [cli, prompt];
3470
+ return [cli, prompt2];
2864
3471
  }
2865
3472
  }
2866
3473
 
@@ -2924,7 +3531,7 @@ async function handleDataRequest(requestId, path, harenDir, send) {
2924
3531
  }
2925
3532
  send({ type: "data-response", requestId, data });
2926
3533
  }
2927
- async function handleCommand(commandId, prompt, cli, config, send) {
3534
+ async function handleCommand(commandId, prompt2, cli, config, send) {
2928
3535
  const { mkdir } = await import("fs/promises");
2929
3536
  await mkdir(`${config.harenDir}/events`, { recursive: true });
2930
3537
  await Promise.resolve().then(() => init_events());
@@ -2933,10 +3540,10 @@ async function handleCommand(commandId, prompt, cli, config, send) {
2933
3540
  type: "agent-command",
2934
3541
  timestamp: new Date().toISOString(),
2935
3542
  cli,
2936
- prompt,
3543
+ prompt: prompt2,
2937
3544
  commandId
2938
3545
  });
2939
- await executeCLI(cli, prompt, (chunk, done) => {
3546
+ await executeCLI(cli, prompt2, (chunk, done) => {
2940
3547
  send({ type: "command-output", commandId, chunk, done });
2941
3548
  });
2942
3549
  }
@@ -3384,7 +3991,7 @@ var init_updates = __esm(() => {
3384
3991
  });
3385
3992
 
3386
3993
  // src/plugins/runner.ts
3387
- import { existsSync as existsSync14 } from "fs";
3994
+ import { existsSync as existsSync15 } from "fs";
3388
3995
  import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile11 } from "fs/promises";
3389
3996
  import { isAbsolute as isAbsolute3, join as join16 } from "path";
3390
3997
  function tasksPath(input, harenDir) {
@@ -3394,11 +4001,11 @@ function tasksPath(input, harenDir) {
3394
4001
  }
3395
4002
  async function loadPlannedTasks(input, harenDir) {
3396
4003
  const path = tasksPath(input, harenDir);
3397
- if (!path || !existsSync14(path))
4004
+ if (!path || !existsSync15(path))
3398
4005
  return [];
3399
4006
  const tasks = parseTasksFile(await readFile11(path, "utf-8"));
3400
4007
  const progressPath = join16(harenDir, "progress.json");
3401
- if (typeof input.module !== "string" || !existsSync14(progressPath))
4008
+ if (typeof input.module !== "string" || !existsSync15(progressPath))
3402
4009
  return tasks;
3403
4010
  try {
3404
4011
  const mod = (await readProgress(progressPath)).modules[input.module];
@@ -3418,7 +4025,7 @@ async function buildPayload(hook, input, harenDir) {
3418
4025
  }
3419
4026
  async function addPlannedFeatures(input, harenDir) {
3420
4027
  const progressPath = join16(harenDir, "progress.json");
3421
- if (typeof input.module !== "string" || !existsSync14(progressPath))
4028
+ if (typeof input.module !== "string" || !existsSync15(progressPath))
3422
4029
  return;
3423
4030
  const tasks = await loadPlannedTasks(input, harenDir);
3424
4031
  const progress = await readProgress(progressPath);
@@ -3569,7 +4176,7 @@ async function runHookAndApply(hook, input, o) {
3569
4176
  }
3570
4177
  try {
3571
4178
  const progressPath = join16(o.harenDir, "progress.json");
3572
- if (updates.length > 0 && existsSync14(progressPath)) {
4179
+ if (updates.length > 0 && existsSync15(progressPath)) {
3573
4180
  const result = applyUpdates(await readProgress(progressPath), updates);
3574
4181
  if (result.applied.length > 0)
3575
4182
  await writeProgress(progressPath, result.progress);
@@ -3685,7 +4292,8 @@ async function plugin(args) {
3685
4292
  try {
3686
4293
  await installPlugin(opts.target, ctx);
3687
4294
  } catch (err) {
3688
- console.error(` ${err.message}`);
4295
+ const message = err.message;
4296
+ console.error(` ${message === INSTALL_CANCELLED && !opts.yes && !process.stdin.isTTY ? "Plugin install cancelled: no TTY for the confirmation prompt. Re-run with --yes after you review the plugin." : message}`);
3689
4297
  process.exit(1);
3690
4298
  }
3691
4299
  await syncEditors();
@@ -3750,10 +4358,34 @@ var init_plugin = __esm(() => {
3750
4358
  SUBS = ["add", "remove", "list", "run", "doctor"];
3751
4359
  });
3752
4360
 
4361
+ // src/plugins/adapter-read.ts
4362
+ import { existsSync as existsSync16 } from "fs";
4363
+ import { join as join18 } from "path";
4364
+ function adapterMissingMessage(name) {
4365
+ return `Adapter '${name}' is named in manifest.yaml but not installed. Run \`haren plugin add <source>\`, or remove migration.adapter to work by hand.`;
4366
+ }
4367
+ async function readAdapter(harenDir, name) {
4368
+ const { plugins } = await readPlugins(harenDir);
4369
+ if (!plugins[name])
4370
+ return null;
4371
+ const dir = pluginDir(harenDir, name);
4372
+ if (!existsSync16(join18(dir, "haren-plugin.json")))
4373
+ return null;
4374
+ try {
4375
+ return (await readInstalledManifest(dir)).adapter ?? null;
4376
+ } catch (e) {
4377
+ throw new Error(`Adapter plugin '${name}': ${e instanceof Error ? e.message : String(e)}`);
4378
+ }
4379
+ }
4380
+ var init_adapter_read = __esm(() => {
4381
+ init_manifest2();
4382
+ init_state();
4383
+ });
4384
+
3753
4385
  // src/commands/track.ts
3754
- import { existsSync as existsSync15 } from "fs";
3755
- import { mkdir as mkdir9, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
3756
- import { dirname as dirname5, join as join18 } from "path";
4386
+ import { existsSync as existsSync17 } from "fs";
4387
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
4388
+ import { dirname as dirname5, join as join19, relative as relative4, sep as sep4 } from "path";
3757
4389
  function parseTrackArgs(args) {
3758
4390
  const positional = [];
3759
4391
  const flags = {};
@@ -3762,6 +4394,10 @@ function parseTrackArgs(args) {
3762
4394
  if (arg.startsWith("--")) {
3763
4395
  const eq = arg.indexOf("=");
3764
4396
  const name = eq === -1 ? arg : arg.slice(0, eq);
4397
+ if (BOOL_FLAGS.includes(name) && eq === -1) {
4398
+ flags[name.slice(2)] = "true";
4399
+ continue;
4400
+ }
3765
4401
  if (!VALUE_FLAGS.includes(name))
3766
4402
  throw new Error(`Unknown option: ${name}`);
3767
4403
  const value = eq === -1 ? args[++i] : arg.slice(eq + 1);
@@ -3777,9 +4413,9 @@ function parseTrackArgs(args) {
3777
4413
  function pathsFor(harenDir) {
3778
4414
  return {
3779
4415
  harenDir,
3780
- progress: join18(harenDir, "progress.json"),
3781
- events: join18(harenDir, "events", "events.jsonl"),
3782
- registry: join18(harenDir, "artifacts", "_registry", "artifact-index.md")
4416
+ progress: join19(harenDir, "progress.json"),
4417
+ events: join19(harenDir, "events", "events.jsonl"),
4418
+ registry: join19(harenDir, "artifacts", "_registry", "artifact-index.md")
3783
4419
  };
3784
4420
  }
3785
4421
  async function emit(paths, event) {
@@ -3799,7 +4435,7 @@ function requireModule(progress, name) {
3799
4435
  }
3800
4436
  }
3801
4437
  async function loadProgress(paths) {
3802
- if (!existsSync15(paths.progress))
4438
+ if (!existsSync17(paths.progress))
3803
4439
  throw new Error(`No progress.json in ${paths.harenDir}`);
3804
4440
  return readProgress(paths.progress);
3805
4441
  }
@@ -3819,29 +4455,135 @@ async function track(args, cwd = process.cwd()) {
3819
4455
  const paths = pathsFor(location.harenDir);
3820
4456
  switch (sub) {
3821
4457
  case "status":
3822
- return trackStatus(paths, rest);
4458
+ return trackStatus(paths, rest, flags);
3823
4459
  case "feature":
3824
4460
  return trackFeature(paths, rest);
4461
+ case "unit":
4462
+ return trackUnit(paths, rest);
3825
4463
  case "commit":
3826
- return trackCommit(paths, rest);
4464
+ return trackCommit(paths, rest, flags);
4465
+ case "depends":
4466
+ return trackDepends(paths, rest);
3827
4467
  case "artifact":
3828
4468
  return trackArtifact(paths, rest, flags);
3829
4469
  case "event":
3830
4470
  return trackEvent(paths, rest, flags);
3831
4471
  case "override":
3832
4472
  return trackOverride(paths, rest, flags);
4473
+ case "ui-mode":
4474
+ return trackUiMode(paths, rest);
4475
+ case "check":
4476
+ return trackCheck(paths);
3833
4477
  default:
3834
4478
  throw new Error(`Unknown track command: ${sub}
3835
4479
  ${TRACK_USAGE}`);
3836
4480
  }
3837
4481
  }
3838
- async function trackStatus(paths, rest) {
4482
+ async function trackUiMode(paths, rest) {
4483
+ const mode = need(rest[0], "ui mode");
4484
+ if (!UI_MODES.includes(mode)) {
4485
+ throw new Error(`Invalid ui mode '${mode}'. Use ${UI_MODES.join(", ")}.`);
4486
+ }
4487
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4488
+ if (!existsSync17(manifestPath))
4489
+ throw new Error(`No manifest.yaml in ${paths.harenDir}`);
4490
+ const text = await readFile13(manifestPath, "utf-8");
4491
+ await writeFile7(manifestPath, setUiModeText(text, mode));
4492
+ await emit(paths, { type: "ui-mode", mode });
4493
+ console.log(` UI mockups mode: ${mode}.`);
4494
+ }
4495
+ async function loadMigration(paths) {
4496
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4497
+ if (!existsSync17(manifestPath))
4498
+ return null;
4499
+ return readMigrationConfig(parseManifest(await readFile13(manifestPath, "utf-8")));
4500
+ }
4501
+ async function adapterCommands(paths, migration) {
4502
+ if (!migration.adapter)
4503
+ return new Set;
4504
+ const adapter = await readAdapter(paths.harenDir, migration.adapter);
4505
+ if (!adapter)
4506
+ return null;
4507
+ return new Set(Object.keys(adapter.commands));
4508
+ }
4509
+ async function trackUnit(paths, rest) {
4510
+ const module = need(rest[0], "<module>");
4511
+ const unit = need(rest[1], "<unit>");
4512
+ const to = need(rest[2], "<status>");
4513
+ const migration = await loadMigration(paths);
4514
+ if (!migration)
4515
+ throw new Error("track unit needs mode: migration in manifest.yaml");
4516
+ if (!UNIT_STATUSES.includes(to)) {
4517
+ throw new Error(`Invalid unit status '${to}'. Allowed: ${UNIT_STATUSES.join(", ")}`);
4518
+ }
4519
+ if (!migration.unitId.test(unit)) {
4520
+ throw new Error(`Unit '${unit}' does not match migration.unitId`);
4521
+ }
4522
+ const commands = await adapterCommands(paths, migration);
4523
+ if (!commands) {
4524
+ if (to === "extracted" || to === "spec-approved") {
4525
+ throw new Error(adapterMissingMessage(migration.adapter));
4526
+ }
4527
+ } else if (to === "extracted" && commands.has("extract") || to === "spec-approved" && commands.has("gate")) {
4528
+ throw new Error("Use haren migrate extract|gate; the adapter owns this step");
4529
+ }
4530
+ const progress = await loadProgress(paths);
4531
+ requireModule(progress, module);
4532
+ const from = progress.modules[module].units?.[unit] ?? null;
4533
+ const next = updateUnitStatus(progress, module, unit, to);
4534
+ await writeProgress(paths.progress, next);
4535
+ await emit(paths, { type: "unit-status", module, unit, from, to });
4536
+ console.log(` ${module}/${unit}: ${from ?? "(new)"} \u2192 ${to}`);
4537
+ }
4538
+ async function moduleMeta(paths, flags) {
4539
+ const meta = {};
4540
+ if (flags.branch !== undefined)
4541
+ meta.branch = need(flags.branch, "--branch <name>");
4542
+ if (flags.repos !== undefined) {
4543
+ const repos = [
4544
+ ...new Set(flags.repos.split(",").map((r) => r.trim()).filter(Boolean))
4545
+ ];
4546
+ if (!repos.length)
4547
+ throw new Error(`Missing --repos <key1,key2>.
4548
+ ${TRACK_USAGE}`);
4549
+ await checkRepoKeys(paths, repos);
4550
+ meta.repos = repos;
4551
+ }
4552
+ return meta;
4553
+ }
4554
+ async function allowedRepoKeys(paths) {
4555
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4556
+ const manifest = existsSync17(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4557
+ const declared = Object.keys(normalizeRepos(manifest.repos));
4558
+ return { allowed: declared.length ? declared : ["default"], empty: !declared.length };
4559
+ }
4560
+ async function checkRepoKeys(paths, keys) {
4561
+ const { allowed, empty } = await allowedRepoKeys(paths);
4562
+ const declared = empty ? [] : allowed;
4563
+ const unknown = keys.filter((k) => !allowed.includes(k));
4564
+ if (unknown.length) {
4565
+ throw new Error(`Unknown repo key: ${unknown.join(", ")}. Allowed: ${allowed.join(", ")}${declared.length ? "" : " (manifest.yaml repos is empty)"}`);
4566
+ }
4567
+ }
4568
+ async function trackStatus(paths, rest, flags) {
3839
4569
  const module = need(rest[0], "<module>");
3840
4570
  const to = need(rest[1], "<status>");
3841
4571
  if (!MODULE_STATUSES.includes(to)) {
3842
4572
  throw new Error(`Invalid module status '${to}'. Allowed: ${MODULE_STATUSES.join(", ")}`);
3843
4573
  }
3844
4574
  const progress = await loadProgress(paths);
4575
+ const meta = await moduleMeta(paths, flags);
4576
+ const metaOnly = progress.modules[module]?.status === to && Object.keys(meta).length > 0;
4577
+ const migration = await loadMigration(paths);
4578
+ if (migration && progress.modules[module] && !metaOnly) {
4579
+ const floor = to === "planned" ? "spec-approved" : to === "completed" ? "parity-signed" : null;
4580
+ if (floor) {
4581
+ const below = unitsBelow(progress.modules[module], floor);
4582
+ if (below.length) {
4583
+ throw new Error(`Module '${module}' cannot be '${to}': units below '${floor}': ${below.join(", ")}`);
4584
+ }
4585
+ }
4586
+ }
3845
4587
  let next;
3846
4588
  let from = null;
3847
4589
  if (!progress.modules[module]) {
@@ -3857,13 +4599,21 @@ async function trackStatus(paths, rest) {
3857
4599
  currentPhase: phaseForStatus(to),
3858
4600
  features: {},
3859
4601
  lastCommit: {},
4602
+ ...meta,
3860
4603
  lastUpdated: new Date().toISOString()
3861
4604
  }
3862
4605
  }
3863
4606
  };
3864
4607
  } else {
3865
4608
  from = progress.modules[module].status;
3866
- next = updateModuleStatus(progress, module, to);
4609
+ next = metaOnly ? progress : updateModuleStatus(progress, module, to);
4610
+ next = {
4611
+ ...next,
4612
+ modules: {
4613
+ ...next.modules,
4614
+ [module]: { ...next.modules[module], ...meta, lastUpdated: new Date().toISOString() }
4615
+ }
4616
+ };
3867
4617
  }
3868
4618
  await writeProgress(paths.progress, next);
3869
4619
  await emit(paths, { type: "module-status", module, from, to, phase: phaseForStatus(to) });
@@ -3905,10 +4655,13 @@ async function trackFeature(paths, rest) {
3905
4655
  await emit(paths, { type: "feature-status", module, feature, from, to: status });
3906
4656
  console.log(` ${module}/${feature}: ${from ?? "(new)"} \u2192 ${status}`);
3907
4657
  }
3908
- async function trackCommit(paths, rest) {
4658
+ async function trackCommit(paths, rest, flags = {}) {
3909
4659
  const module = need(rest[0], "<module>");
3910
4660
  const repo = need(rest[1], "<repoKey>");
4661
+ if (flags.remove)
4662
+ return removeCommitKey(paths, module, repo);
3911
4663
  const sha = need(rest[2], "<sha>");
4664
+ await checkRepoKeys(paths, [repo]);
3912
4665
  const progress = await loadProgress(paths);
3913
4666
  requireModule(progress, module);
3914
4667
  const mod = progress.modules[module];
@@ -3930,6 +4683,67 @@ async function trackCommit(paths, rest) {
3930
4683
  await emit(paths, { type: "commit", module, repo, sha });
3931
4684
  console.log(` ${module}: lastCommit.${repo} = ${sha}`);
3932
4685
  }
4686
+ async function removeCommitKey(paths, module, repo) {
4687
+ const progress = await loadProgress(paths);
4688
+ requireModule(progress, module);
4689
+ const mod = progress.modules[module];
4690
+ const lastCommit = { ...mod.lastCommit ?? {} };
4691
+ const had = Object.hasOwn(lastCommit, repo) || (mod.repos ?? []).includes(repo);
4692
+ if (!had)
4693
+ throw new Error(`Module '${module}' has no repo key '${repo}'.`);
4694
+ delete lastCommit[repo];
4695
+ const next = {
4696
+ ...progress,
4697
+ modules: {
4698
+ ...progress.modules,
4699
+ [module]: {
4700
+ ...mod,
4701
+ lastCommit,
4702
+ repos: (mod.repos ?? []).filter((r) => r !== repo),
4703
+ lastUpdated: new Date().toISOString()
4704
+ }
4705
+ }
4706
+ };
4707
+ await writeProgress(paths.progress, next);
4708
+ await emit(paths, { type: "commit", module, repo, sha: null, removed: true });
4709
+ console.log(` ${module}: removed repo key ${repo}`);
4710
+ }
4711
+ function findCycle(graph, module, deps) {
4712
+ const next = { ...graph, [module]: deps };
4713
+ const visited = new Set([module]);
4714
+ const visit = (node, path) => {
4715
+ for (const dep of next[node] ?? []) {
4716
+ if (dep === module)
4717
+ return [...path, dep];
4718
+ if (visited.has(dep))
4719
+ continue;
4720
+ visited.add(dep);
4721
+ const found = visit(dep, [...path, dep]);
4722
+ if (found)
4723
+ return found;
4724
+ }
4725
+ return null;
4726
+ };
4727
+ return visit(module, [module]);
4728
+ }
4729
+ async function trackDepends(paths, rest) {
4730
+ const module = need(rest[0], "<module>");
4731
+ const deps = [...new Set(rest.slice(1))];
4732
+ const progress = await loadProgress(paths);
4733
+ requireModule(progress, module);
4734
+ for (const dep of deps)
4735
+ requireModule(progress, dep);
4736
+ const graph = progress.dependencies ?? {};
4737
+ const cycle = findCycle(graph, module, deps);
4738
+ if (cycle)
4739
+ throw new Error(`Dependency cycle: ${cycle.join(" \u2192 ")}`);
4740
+ await writeProgress(paths.progress, {
4741
+ ...progress,
4742
+ dependencies: { ...graph, [module]: deps }
4743
+ });
4744
+ await emit(paths, { type: "dependencies", module, dependsOn: deps });
4745
+ console.log(` ${module} depends on: ${deps.length ? deps.join(", ") : "(none)"}`);
4746
+ }
3933
4747
  function upsertArtifactRow(text, cells) {
3934
4748
  const row = `| ${cells.map((c) => c.replaceAll("|", "\\|")).join(" | ")} |`;
3935
4749
  const lines = text.split(`
@@ -3969,7 +4783,7 @@ async function trackArtifact(paths, rest, flags) {
3969
4783
  const progress = await loadProgress(paths);
3970
4784
  requireModule(progress, flags.module);
3971
4785
  }
3972
- const existing = existsSync15(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
4786
+ const existing = existsSync17(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
3973
4787
  await mkdir9(dirname5(paths.registry), { recursive: true });
3974
4788
  await writeFile7(paths.registry, upsertArtifactRow(existing, [id, artifactType, module, status, path]));
3975
4789
  await emit(paths, {
@@ -4032,22 +4846,162 @@ async function trackOverride(paths, rest, flags) {
4032
4846
  throw new Error(`Unknown override action '${action}'. Use on or off.`);
4033
4847
  }
4034
4848
  }
4035
- var TRACK_USAGE = `Usage:
4036
- haren track status <module> <status>
4037
- haren track feature <module> <feature> [status]
4038
- haren track commit <module> <repoKey> <sha>
4039
- haren track artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]
4040
- haren track event <type> [--module m] [--phase p] [--feature f] [--data '<json object>']
4041
- haren track override on --reason "<text>" [--hours <n>]
4042
- haren track override off
4043
- Options: --haren-dir <path>`, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
4044
- |----|------|--------|--------|------|`;
4045
- var init_track = __esm(() => {
4046
- init_events();
4047
- init_progress();
4048
- init_resolve();
4049
- VALUE_FLAGS = [
4050
- "--haren-dir",
4849
+ async function listArtifactFiles(artifactsDir) {
4850
+ if (!existsSync17(artifactsDir))
4851
+ return [];
4852
+ const out = [];
4853
+ const walk = async (dir) => {
4854
+ for (const entry of await readdir7(dir, { withFileTypes: true })) {
4855
+ if (entry.name.startsWith("."))
4856
+ continue;
4857
+ const full = join19(dir, entry.name);
4858
+ if (entry.isDirectory()) {
4859
+ if (dir === artifactsDir && UNTRACKED_DIRS.has(entry.name))
4860
+ continue;
4861
+ await walk(full);
4862
+ } else if (entry.name.endsWith(".md") && entry.name.toLowerCase() !== "readme.md") {
4863
+ out.push(full);
4864
+ }
4865
+ }
4866
+ };
4867
+ await walk(artifactsDir);
4868
+ return out;
4869
+ }
4870
+ function parseRegistryRows(text) {
4871
+ const rows = [];
4872
+ for (const raw of text.split(`
4873
+ `)) {
4874
+ const line = raw.trim();
4875
+ if (!line.startsWith("|"))
4876
+ continue;
4877
+ const cells = line.slice(1, line.endsWith("|") ? -1 : undefined).split("|").map((c) => c.trim());
4878
+ if (cells.length < 5 || cells[0] === "ID" || /^-+$/.test(cells[0]))
4879
+ continue;
4880
+ rows.push({ id: cells[0], module: cells[2], path: cells[4] });
4881
+ }
4882
+ return rows;
4883
+ }
4884
+ function normalizeArtifactPath(p) {
4885
+ return p.replace(/^\.\//, "").replace(/^artifacts\//, "").replaceAll("\\", "/");
4886
+ }
4887
+ async function checkWorkspace(paths) {
4888
+ const errors = [];
4889
+ const warnings = [];
4890
+ const progress = await loadProgress(paths);
4891
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4892
+ const manifest = existsSync17(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4893
+ const { allowed: allowedKeys, empty: noRepos } = await allowedRepoKeys(paths);
4894
+ const declared = new Set(allowedKeys);
4895
+ for (const [name, mod] of Object.entries(progress.modules)) {
4896
+ const used = new Set([...mod.repos ?? [], ...Object.keys(mod.lastCommit ?? {})]);
4897
+ for (const key of used) {
4898
+ if (!declared.has(key)) {
4899
+ 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`);
4900
+ }
4901
+ }
4902
+ }
4903
+ let mig = null;
4904
+ try {
4905
+ mig = readMigrationConfig(manifest);
4906
+ } catch (e) {
4907
+ errors.push(e.message);
4908
+ }
4909
+ if (manifest.mode === "migration" && mig) {
4910
+ try {
4911
+ if (!legacyRepo(manifest)) {
4912
+ errors.push("mode: migration needs one repo with role: legacy in manifest.yaml. Add it under repos, for example: legacy_src: { path: ../legacy_src, role: legacy, readOnly: true }");
4913
+ }
4914
+ } catch (e) {
4915
+ errors.push(e.message);
4916
+ }
4917
+ if (mig.adapter) {
4918
+ try {
4919
+ if (!await readAdapter(paths.harenDir, mig.adapter)) {
4920
+ errors.push(adapterMissingMessage(mig.adapter));
4921
+ }
4922
+ } catch (e) {
4923
+ errors.push(e.message);
4924
+ }
4925
+ }
4926
+ for (const [name, mod] of Object.entries(progress.modules)) {
4927
+ for (const [unit, status] of Object.entries(mod.units ?? {})) {
4928
+ if (!mig.unitId.test(unit)) {
4929
+ errors.push(`module '${name}' unit '${unit}' does not match migration.unitId`);
4930
+ }
4931
+ if (mig.adapter && unitAtLeast(status, "spec-approved")) {
4932
+ const gate = join19(paths.harenDir, "artifacts", "02-discovery", "units", unit, "gate.json");
4933
+ let ok = false;
4934
+ try {
4935
+ ok = JSON.parse(await readFile13(gate, "utf-8")).pass === true;
4936
+ } catch {
4937
+ ok = false;
4938
+ }
4939
+ if (!ok) {
4940
+ errors.push(`unit '${unit}' is ${status} but artifacts/02-discovery/units/${unit}/gate.json is missing or not pass`);
4941
+ }
4942
+ }
4943
+ }
4944
+ }
4945
+ }
4946
+ const registryText = existsSync17(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
4947
+ const rows = parseRegistryRows(registryText);
4948
+ const indexed = new Set(rows.map((r) => normalizeArtifactPath(r.path)));
4949
+ const artifactsDir = join19(paths.harenDir, "artifacts");
4950
+ for (const file of await listArtifactFiles(artifactsDir)) {
4951
+ const rel = relative4(artifactsDir, file).split(sep4).join("/");
4952
+ if (!indexed.has(rel)) {
4953
+ errors.push(`artifacts/${rel} has no row in artifact-index.md (run haren track artifact)`);
4954
+ }
4955
+ }
4956
+ for (const row of rows) {
4957
+ const rel = normalizeArtifactPath(row.path);
4958
+ if (!existsSync17(join19(artifactsDir, rel))) {
4959
+ errors.push(`index row ${row.id} points to missing file artifacts/${rel}`);
4960
+ }
4961
+ }
4962
+ const modulesWithRows = new Set(rows.map((r) => r.module));
4963
+ for (const [name, mod] of Object.entries(progress.modules)) {
4964
+ if (mod.status !== "discovered" && !modulesWithRows.has(name)) {
4965
+ warnings.push(`module '${name}' (${mod.status}) has no artifact in the index`);
4966
+ }
4967
+ }
4968
+ return { errors, warnings };
4969
+ }
4970
+ async function trackCheck(paths) {
4971
+ const { errors, warnings } = await checkWorkspace(paths);
4972
+ for (const w of warnings)
4973
+ console.log(` warn: ${w}`);
4974
+ if (errors.length) {
4975
+ throw new Error(`Workspace check FAIL:
4976
+ ${errors.map((e) => ` - ${e}`).join(`
4977
+ `)}`);
4978
+ }
4979
+ console.log(" Workspace check PASS");
4980
+ }
4981
+ var TRACK_USAGE = `Usage:
4982
+ haren track status <module> <status> [--branch <name>] [--repos <key1,key2>]
4983
+ haren track feature <module> <feature> [status]
4984
+ haren track unit <module> <unit> <status>
4985
+ haren track commit <module> <repoKey> <sha>
4986
+ haren track commit <module> <repoKey> --remove
4987
+ haren track depends <module> [dep ...]
4988
+ haren track artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]
4989
+ haren track event <type> [--module m] [--phase p] [--feature f] [--data '<json object>']
4990
+ haren track override on --reason "<text>" [--hours <n>]
4991
+ haren track override off
4992
+ haren track ui-mode <ask|ascii|browser|artifact>
4993
+ haren track check
4994
+ Options: --haren-dir <path>`, BOOL_FLAGS, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
4995
+ |----|------|--------|--------|------|`, UNTRACKED_DIRS;
4996
+ var init_track = __esm(() => {
4997
+ init_manifest();
4998
+ init_events();
4999
+ init_progress();
5000
+ init_adapter_read();
5001
+ init_resolve();
5002
+ BOOL_FLAGS = ["--remove"];
5003
+ VALUE_FLAGS = [
5004
+ "--haren-dir",
4051
5005
  "--type",
4052
5006
  "--path",
4053
5007
  "--module",
@@ -4056,11 +5010,1597 @@ var init_track = __esm(() => {
4056
5010
  "--feature",
4057
5011
  "--data",
4058
5012
  "--reason",
4059
- "--hours"
5013
+ "--hours",
5014
+ "--branch",
5015
+ "--repos"
4060
5016
  ];
5017
+ UNTRACKED_DIRS = new Set(["_registry", "00-baseline"]);
5018
+ });
5019
+
5020
+ // src/plugins/adapter-run.ts
5021
+ function buildArgv(template, values) {
5022
+ return template.trim().split(/\s+/).map((tok) => tok.replace(/\{(\w+)\}/g, (_, k) => {
5023
+ if (!Object.hasOwn(values, k))
5024
+ throw new AdapterError(`No value for placeholder {${k}}`);
5025
+ return values[k];
5026
+ }));
5027
+ }
5028
+ function spawnAdapter(command, argv, cwd) {
5029
+ try {
5030
+ return Bun.spawn(argv, { cwd, stdout: "pipe", stderr: "pipe" });
5031
+ } catch (e) {
5032
+ throw new AdapterError(`adapter ${command} could not start: ${e instanceof Error ? e.message : String(e)}`);
5033
+ }
5034
+ }
5035
+ function adapterTimeoutMs() {
5036
+ const n = Number(process.env.HAREN_ADAPTER_TIMEOUT_MS);
5037
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_ADAPTER_TIMEOUT_MS;
5038
+ }
5039
+ async function runAdapter(command, template, values, cwd) {
5040
+ const proc = spawnAdapter(command, buildArgv(template, values), cwd);
5041
+ const timeoutMs = adapterTimeoutMs();
5042
+ let timer;
5043
+ const timeout = new Promise((done) => {
5044
+ timer = setTimeout(() => {
5045
+ proc.kill("SIGKILL");
5046
+ done("timeout");
5047
+ }, timeoutMs);
5048
+ });
5049
+ const result = await Promise.race([
5050
+ Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]),
5051
+ timeout
5052
+ ]).finally(() => clearTimeout(timer));
5053
+ if (result === "timeout") {
5054
+ throw new AdapterError(`adapter ${command} timed out after ${timeoutMs / 1000}s`);
5055
+ }
5056
+ const [out, err, code] = result;
5057
+ if (code !== 0)
5058
+ throw new AdapterError(`adapter ${command} exited ${code}: ${err.trim().slice(0, 500)}`);
5059
+ let parsed;
5060
+ try {
5061
+ parsed = JSON.parse(out);
5062
+ } catch {
5063
+ throw new AdapterError(`adapter ${command} printed non-JSON output (schema)`);
5064
+ }
5065
+ if (!VALIDATORS[command](parsed)) {
5066
+ throw new AdapterError(`adapter ${command} output does not match the schema`);
5067
+ }
5068
+ return parsed;
5069
+ }
5070
+ var AdapterError, isStr = (v) => typeof v === "string" && v.length > 0, optStr = (v) => v === undefined || typeof v === "string", VALIDATORS, DEFAULT_ADAPTER_TIMEOUT_MS = 300000;
5071
+ var init_adapter_run = __esm(() => {
5072
+ AdapterError = class AdapterError extends Error {
5073
+ name = "AdapterError";
5074
+ };
5075
+ VALIDATORS = {
5076
+ inventory: (o) => Array.isArray(o?.units) && o.units.every((u) => isStr(u?.id) && (u.parent === null || isStr(u.parent)) && optStr(u.family) && optStr(u.title)),
5077
+ extract: (o) => isStr(o?.unit) && Array.isArray(o.files) && o.files.every(isStr),
5078
+ gate: (o) => isStr(o?.unit) && typeof o.pass === "boolean" && Array.isArray(o.findings) && o.findings.every((f) => (f?.severity === "error" || f?.severity === "warning") && isStr(f.rule) && isStr(f.message))
5079
+ };
5080
+ });
5081
+
5082
+ // src/commands/migrate.ts
5083
+ import { existsSync as existsSync18 } from "fs";
5084
+ import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile8 } from "fs/promises";
5085
+ import { dirname as dirname6, join as join20, resolve as resolve12 } from "path";
5086
+ function parseMigrateArgs(args) {
5087
+ const positional = [];
5088
+ const flags = {};
5089
+ for (let i = 0;i < args.length; i++) {
5090
+ const arg = args[i];
5091
+ if (arg === "--approve")
5092
+ flags.approve = true;
5093
+ else if (arg === "--module" || arg === "--haren-dir") {
5094
+ const value = args[++i];
5095
+ if (value === undefined)
5096
+ throw new Error(`${arg} needs a value`);
5097
+ flags[arg.slice(2)] = value;
5098
+ } else if (arg.startsWith("--haren-dir="))
5099
+ flags["haren-dir"] = arg.split("=", 2)[1];
5100
+ else if (arg.startsWith("--module="))
5101
+ flags.module = arg.split("=", 2)[1];
5102
+ else if (arg.startsWith("--"))
5103
+ throw new Error(`Unknown option: ${arg}`);
5104
+ else
5105
+ positional.push(arg);
5106
+ }
5107
+ return { positional, flags };
5108
+ }
5109
+ function renderUnitMap(units, moduleOf, previous = "") {
5110
+ const rows = units.map((u) => `| ${cell(u.id)} | ${cell(u.parent)} | ${cell(u.family)} | ${cell(u.title)} | ${cell(moduleOf[u.id])} |`);
5111
+ const tail = afterUnitTable(previous);
5112
+ return `# Unit Map
5113
+
5114
+ ${UNIT_MAP_HEADER}
5115
+ ${rows.join(`
5116
+ `)}
5117
+ ${tail ? `
5118
+ ${tail}
5119
+ ` : ""}`;
5120
+ }
5121
+ function afterUnitTable(text) {
5122
+ const lines = text.split(`
5123
+ `);
5124
+ const start = lines.findIndex((l) => /^\|\s*Unit\s*\|/.test(l.trim()));
5125
+ if (start < 0)
5126
+ return "";
5127
+ let end = start;
5128
+ while (end < lines.length && lines[end].trim().startsWith("|"))
5129
+ end++;
5130
+ return lines.slice(end).join(`
5131
+ `).trim();
5132
+ }
5133
+ function parseUnitMap(text) {
5134
+ const rows = new Map;
5135
+ for (const line of text.split(`
5136
+ `)) {
5137
+ const t = line.trim();
5138
+ if (!t.startsWith("|"))
5139
+ continue;
5140
+ const c = t.slice(1, -1).split(/(?<!\\)\|/).map((s) => s.trim().replaceAll("\\|", "|"));
5141
+ if (c.length < 5 || c[0] === "Unit" || /^-+$/.test(c[0]))
5142
+ continue;
5143
+ const v = (s) => s === "-" ? undefined : s;
5144
+ rows.set(c[0], {
5145
+ unit: { id: c[0], parent: v(c[1]) ?? null, family: v(c[2]), title: v(c[3]) },
5146
+ module: v(c[4]) ?? ""
5147
+ });
5148
+ }
5149
+ return rows;
5150
+ }
5151
+ function moduleOfUnit(progress, unit) {
5152
+ for (const [name, mod] of Object.entries(progress.modules)) {
5153
+ if (mod.units && unit in mod.units)
5154
+ return name;
5155
+ }
5156
+ throw new Error(`Unit '${unit}' is not in progress.json. Run haren migrate inventory first.`);
5157
+ }
5158
+ function commandFor(ctx, cmd) {
5159
+ const template = ctx.adapter.commands[cmd];
5160
+ if (!template)
5161
+ throw new Error(`Adapter has no ${cmd} command. Do this step by hand (see skill extract)`);
5162
+ return template;
5163
+ }
5164
+ function checkUnitId(ctx, unit) {
5165
+ if (!unit)
5166
+ throw new Error(`Missing <unit>.
5167
+ ${MIGRATE_USAGE}`);
5168
+ if (!ctx.migration.unitId.test(unit)) {
5169
+ throw new Error(`Unit '${unit}' does not match migration.unitId`);
5170
+ }
5171
+ return unit;
5172
+ }
5173
+ async function loadContext(harenDir) {
5174
+ const paths = pathsFor(harenDir);
5175
+ const migration = await loadMigration(paths);
5176
+ if (!migration)
5177
+ throw new Error("haren migrate needs mode: migration in manifest.yaml");
5178
+ const manifest = parseManifest(await readFile14(join20(harenDir, "manifest.yaml"), "utf-8"));
5179
+ const legacy = legacyRepo(manifest);
5180
+ if (!legacy)
5181
+ throw new Error("haren migrate needs a repo with role: legacy in manifest.yaml");
5182
+ if (!migration.adapter)
5183
+ throw new Error("manifest migration.adapter is not set");
5184
+ const adapter = await readAdapter(harenDir, migration.adapter);
5185
+ if (!adapter)
5186
+ throw new Error(adapterMissingMessage(migration.adapter));
5187
+ return {
5188
+ paths,
5189
+ migration,
5190
+ adapterName: migration.adapter,
5191
+ adapter,
5192
+ legacyRoot: resolve12(harenDir, legacy[1].path)
5193
+ };
5194
+ }
5195
+ async function migrate(args, cwd = process.cwd()) {
5196
+ const { positional, flags } = parseMigrateArgs(args);
5197
+ const [sub, unitArg] = positional;
5198
+ if (!sub) {
5199
+ console.log(MIGRATE_USAGE);
5200
+ return;
5201
+ }
5202
+ if (!["inventory", "extract", "gate"].includes(sub)) {
5203
+ throw new Error(`Unknown migrate command: ${sub}
5204
+ ${MIGRATE_USAGE}`);
5205
+ }
5206
+ const location = await resolveHarenDir(cwd, { harenDir: harenDirFlag(args), env: process.env });
5207
+ if (!location)
5208
+ throw new Error("No haren folder found. Run `haren init` first.");
5209
+ const ctx = await loadContext(location.harenDir);
5210
+ if (sub === "inventory")
5211
+ return inventory(ctx, flags.module);
5212
+ const unit = checkUnitId(ctx, unitArg);
5213
+ if (sub === "extract")
5214
+ return extract(ctx, unit);
5215
+ return gate(ctx, unit, flags.approve === true);
5216
+ }
5217
+ async function inventory(ctx, moduleFlag) {
5218
+ const template = commandFor(ctx, "inventory");
5219
+ let progress = await readProgress(ctx.paths.progress);
5220
+ if (moduleFlag && !progress.modules[moduleFlag]) {
5221
+ throw new Error(`Unknown module '${moduleFlag}'`);
5222
+ }
5223
+ const raw = await runAdapter("inventory", template, { legacyRoot: ctx.legacyRoot }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5224
+ const badIds = raw.units.filter((u) => !ctx.migration.unitId.test(u.id)).map((u) => u.id);
5225
+ const out = { units: raw.units.filter((u) => ctx.migration.unitId.test(u.id)) };
5226
+ const mapRel = "artifacts/02-discovery/unit-map.md";
5227
+ const mapPath = join20(ctx.paths.harenDir, mapRel);
5228
+ const previous = existsSync18(mapPath) ? await readFile14(mapPath, "utf-8") : "";
5229
+ const known = parseUnitMap(previous);
5230
+ const moduleOf = {};
5231
+ const units = [];
5232
+ const seen = new Set;
5233
+ let fresh = 0;
5234
+ for (const u of out.units) {
5235
+ seen.add(u.id);
5236
+ units.push(u);
5237
+ const prev = known.get(u.id);
5238
+ if (prev)
5239
+ moduleOf[u.id] = prev.module;
5240
+ else {
5241
+ fresh++;
5242
+ if (moduleFlag)
5243
+ moduleOf[u.id] = moduleFlag;
5244
+ }
5245
+ }
5246
+ const gone = [...known.keys()].filter((id) => !seen.has(id));
5247
+ for (const id of gone) {
5248
+ const row = known.get(id);
5249
+ units.push(row.unit);
5250
+ moduleOf[id] = row.module;
5251
+ }
5252
+ await mkdir10(dirname6(mapPath), { recursive: true });
5253
+ await writeFile8(mapPath, renderUnitMap(units, moduleOf, previous));
5254
+ const added = [];
5255
+ const skipped = [];
5256
+ for (const u of out.units) {
5257
+ const mod = moduleOf[u.id];
5258
+ if (mod && !progress.modules[mod])
5259
+ skipped.push({ unit: u.id, module: mod });
5260
+ if (!mod || !progress.modules[mod])
5261
+ continue;
5262
+ if (progress.modules[mod].units?.[u.id] !== undefined)
5263
+ continue;
5264
+ progress = updateUnitStatus(progress, mod, u.id, "inventoried");
5265
+ added.push([mod, u.id]);
5266
+ }
5267
+ if (added.length)
5268
+ await writeProgress(ctx.paths.progress, progress);
5269
+ for (const [module, unit] of added) {
5270
+ await emit(ctx.paths, { type: "unit-status", module, unit, from: null, to: "inventoried" });
5271
+ }
5272
+ const registry = existsSync18(ctx.paths.registry) ? await readFile14(ctx.paths.registry, "utf-8") : "";
5273
+ if (!/^\|\s*UNITMAP-001\s*\|/m.test(registry)) {
5274
+ await mkdir10(dirname6(ctx.paths.registry), { recursive: true });
5275
+ await writeFile8(ctx.paths.registry, upsertArtifactRow(registry, ["UNITMAP-001", "unit-map", "-", "draft", mapRel]));
5276
+ }
5277
+ console.log(` inventory: ${fresh} new, ${out.units.length - fresh} known, ${gone.length} disappeared`);
5278
+ if (gone.length)
5279
+ console.log(` disappeared (kept): ${gone.join(", ")}`);
5280
+ if (badIds.length) {
5281
+ console.log(` warning: dropped, id does not match migration.unitId: ${badIds.join(", ")}`);
5282
+ }
5283
+ if (skipped.length) {
5284
+ const missing = [...new Set(skipped.map((s) => s.module))];
5285
+ console.log(` warning: skipped, module not in progress.json: ${skipped.map((s) => `${s.unit} (${s.module})`).join(", ")}. Run ${missing.map((m) => `\`haren track status ${m} decomposed\``).join(", ")}, or fix the Module cell in unit-map.md, then run inventory again.`);
5286
+ }
5287
+ }
5288
+ async function extract(ctx, unit) {
5289
+ const template = commandFor(ctx, "extract");
5290
+ const progress = await readProgress(ctx.paths.progress);
5291
+ const module = moduleOfUnit(progress, unit);
5292
+ const unitDir = unitDirFor(ctx, unit);
5293
+ await mkdir10(unitDir, { recursive: true });
5294
+ const out = await runAdapter("extract", template, { unit, legacyRoot: ctx.legacyRoot, unitDir }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5295
+ if (out.unit !== unit) {
5296
+ throw new AdapterError(`adapter extract returned unit '${out.unit}', expected '${unit}'`);
5297
+ }
5298
+ const from = progress.modules[module].units[unit];
5299
+ if (UNIT_LINE.indexOf(from) > UNIT_LINE.indexOf("extracted")) {
5300
+ console.log(` ${module}/${unit}: re-extracted (${out.files.length} files), status stays ${from}`);
5301
+ return;
5302
+ }
5303
+ if (from !== "extracted") {
5304
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "extracted"));
5305
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "extracted" });
5306
+ }
5307
+ console.log(` ${module}/${unit}: ${from} \u2192 extracted (${out.files.length} files)`);
5308
+ }
5309
+ async function gate(ctx, unit, approve) {
5310
+ const template = commandFor(ctx, "gate");
5311
+ const progress = await readProgress(ctx.paths.progress);
5312
+ const module = moduleOfUnit(progress, unit);
5313
+ const unitDir = unitDirFor(ctx, unit);
5314
+ const specPath = join20(unitDir, "spec.md");
5315
+ if (!existsSync18(specPath))
5316
+ throw new Error(`No spec at ${specPath}. Write the spec first.`);
5317
+ const from = progress.modules[module].units[unit];
5318
+ if (from !== "spec-draft" && from !== "spec-approved") {
5319
+ throw new Error(`Unit '${unit}' is '${from}'; gate needs spec-draft`);
5320
+ }
5321
+ let out;
5322
+ try {
5323
+ out = await runAdapter("gate", template, { specPath, unitDir }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5324
+ } catch (e) {
5325
+ console.error(` adapter error: ${e instanceof Error ? e.message : String(e)}`);
5326
+ throw e;
5327
+ }
5328
+ await writeFile8(join20(unitDir, "gate.json"), `${JSON.stringify({ ...out, ranAt: new Date().toISOString() }, null, 2)}
5329
+ `);
5330
+ if (!out.pass) {
5331
+ for (const f of out.findings)
5332
+ console.log(` [${f.severity}] ${f.rule}: ${f.message}`);
5333
+ if (from === "spec-approved") {
5334
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "spec-draft"));
5335
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "spec-draft" });
5336
+ console.log(` ${module}/${unit}: spec-approved \u2192 spec-draft`);
5337
+ throw new Error(`gate FAIL for ${unit}: ${out.findings.length} finding(s). Status is now spec-draft.`);
5338
+ }
5339
+ throw new Error(`gate FAIL for ${unit}: ${out.findings.length} finding(s). Status stays ${from}.`);
5340
+ }
5341
+ for (const f of out.findings)
5342
+ console.log(` [${f.severity}] ${f.rule}: ${f.message}`);
5343
+ console.log(` gate PASS for ${unit}`);
5344
+ if (!approve) {
5345
+ if (!process.stdin.isTTY) {
5346
+ throw new ExitCode(3, "Gate PASS. Not approved yet. Review the spec, then re-run with --approve.");
5347
+ }
5348
+ const answer = prompt(` Approve the spec of ${unit}? [y/N]`);
5349
+ if (answer?.trim().toLowerCase() !== "y") {
5350
+ console.log(` Not approved. Status stays ${from}.`);
5351
+ return;
5352
+ }
5353
+ }
5354
+ if (from !== "spec-approved") {
5355
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "spec-approved"));
5356
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "spec-approved" });
5357
+ }
5358
+ await emit(ctx.paths, { type: "unit-gate", module, unit, pass: true, approvedBy: "user" });
5359
+ console.log(` ${module}/${unit}: ${from} \u2192 spec-approved`);
5360
+ }
5361
+ var MIGRATE_USAGE = `Usage:
5362
+ haren migrate inventory [--module <m>]
5363
+ haren migrate extract <unit>
5364
+ haren migrate gate <unit> [--approve]
5365
+ Options: --haren-dir <path>`, UNIT_MAP_HEADER = `| Unit | Parent | Family | Title | Module |
5366
+ |------|--------|--------|-------|--------|`, cell = (v) => v ? v.replaceAll("|", "\\|") : "-", unitDirFor = (ctx, unit) => join20(ctx.paths.harenDir, "artifacts", "02-discovery", "units", unit);
5367
+ var init_migrate = __esm(() => {
5368
+ init_manifest();
5369
+ init_progress();
5370
+ init_adapter_read();
5371
+ init_adapter_run();
5372
+ init_exit_code();
5373
+ init_state();
5374
+ init_resolve();
5375
+ init_track();
5376
+ });
5377
+
5378
+ // src/companion/frame-template.html
5379
+ var frame_template_default = `<!DOCTYPE html>
5380
+ <html>
5381
+ <head>
5382
+ <meta charset="utf-8">
5383
+ <title>haren companion</title>
5384
+ <style>
5385
+ /*
5386
+ * BRAINSTORM COMPANION FRAME TEMPLATE
5387
+ *
5388
+ * This template provides a consistent frame with:
5389
+ * - OS-aware light/dark theming
5390
+ * - Header branding and connection status
5391
+ * - Scrollable main content area
5392
+ * - CSS helpers for common UI patterns
5393
+ *
5394
+ * Content is injected via placeholder comment in #frame-content.
5395
+ */
5396
+
5397
+ * { box-sizing: border-box; margin: 0; padding: 0; }
5398
+ html, body { height: 100%; overflow: hidden; }
5399
+
5400
+ /* ===== THEME VARIABLES ===== */
5401
+ :root {
5402
+ --bg-primary: #f5f5f7;
5403
+ --bg-secondary: #ffffff;
5404
+ --bg-tertiary: #e5e5e7;
5405
+ --border: #d1d1d6;
5406
+ --text-primary: #1d1d1f;
5407
+ --text-secondary: #86868b;
5408
+ --text-tertiary: #aeaeb2;
5409
+ --accent: #0071e3;
5410
+ --accent-hover: #0077ed;
5411
+ --success: #34c759;
5412
+ --warning: #ff9f0a;
5413
+ --error: #ff3b30;
5414
+ --selected-bg: #e8f4fd;
5415
+ --selected-border: #0071e3;
5416
+ }
5417
+
5418
+ @media (prefers-color-scheme: dark) {
5419
+ :root {
5420
+ --bg-primary: #1d1d1f;
5421
+ --bg-secondary: #2d2d2f;
5422
+ --bg-tertiary: #3d3d3f;
5423
+ --border: #424245;
5424
+ --text-primary: #f5f5f7;
5425
+ --text-secondary: #86868b;
5426
+ --text-tertiary: #636366;
5427
+ --accent: #0a84ff;
5428
+ --accent-hover: #409cff;
5429
+ --selected-bg: rgba(10, 132, 255, 0.15);
5430
+ --selected-border: #0a84ff;
5431
+ }
5432
+ }
5433
+
5434
+ body {
5435
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
5436
+ background: var(--bg-primary);
5437
+ color: var(--text-primary);
5438
+ display: flex;
5439
+ flex-direction: column;
5440
+ line-height: 1.5;
5441
+ }
5442
+
5443
+ /* ===== FRAME STRUCTURE ===== */
5444
+ .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; color: var(--text-secondary); line-height: 1; }
5445
+ .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
5446
+ .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
5447
+ .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; flex-shrink: 0; filter: invert(1); }
5448
+ @media (prefers-color-scheme: dark) {
5449
+ .brand-logo { filter: none; }
5450
+ }
5451
+ .status { font-size: 0.7rem; color: var(--status-color, var(--success)); display: flex; align-items: center; gap: 0.4rem; justify-self: end; white-space: nowrap; line-height: 1; }
5452
+ .status::before { content: ''; width: 6px; height: 6px; background: var(--status-color, var(--success)); border-radius: 50%; }
5453
+
5454
+ .main { flex: 1; overflow-y: auto; }
5455
+ #frame-content { padding: 2rem; min-height: 100%; }
5456
+
5457
+ .header {
5458
+ background: var(--bg-secondary);
5459
+ border-bottom: 1px solid var(--border);
5460
+ padding: 0.5rem 1.5rem;
5461
+ flex-shrink: 0;
5462
+ display: grid;
5463
+ grid-template-columns: minmax(0, 1fr) auto;
5464
+ align-items: center;
5465
+ gap: 1rem;
5466
+ min-height: 42px;
5467
+ }
5468
+ .header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; }
5469
+ .header .status { grid-column: 2; line-height: 1; }
5470
+ .header span {
5471
+ font-size: 0.75rem;
5472
+ color: var(--text-secondary);
5473
+ }
5474
+ .header .selected-text {
5475
+ color: var(--accent);
5476
+ font-weight: 500;
5477
+ }
5478
+
5479
+ /* ===== TYPOGRAPHY ===== */
5480
+ h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
5481
+ h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
5482
+ .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
5483
+ .section { margin-bottom: 2rem; }
5484
+ .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
5485
+
5486
+ /* ===== OPTIONS (for A/B/C choices) ===== */
5487
+ .options { display: flex; flex-direction: column; gap: 0.75rem; }
5488
+ .option {
5489
+ background: var(--bg-secondary);
5490
+ border: 2px solid var(--border);
5491
+ border-radius: 12px;
5492
+ padding: 1rem 1.25rem;
5493
+ cursor: pointer;
5494
+ transition: all 0.15s ease;
5495
+ display: flex;
5496
+ align-items: flex-start;
5497
+ gap: 1rem;
5498
+ }
5499
+ .option:hover { border-color: var(--accent); }
5500
+ .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
5501
+ .option .letter {
5502
+ background: var(--bg-tertiary);
5503
+ color: var(--text-secondary);
5504
+ width: 1.75rem; height: 1.75rem;
5505
+ border-radius: 6px;
5506
+ display: flex; align-items: center; justify-content: center;
5507
+ font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
5508
+ }
5509
+ .option.selected .letter { background: var(--accent); color: white; }
5510
+ .option .content { flex: 1; }
5511
+ .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
5512
+ .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
5513
+
5514
+ /* ===== CARDS (for showing designs/mockups) ===== */
5515
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
5516
+ .card {
5517
+ background: var(--bg-secondary);
5518
+ border: 1px solid var(--border);
5519
+ border-radius: 12px;
5520
+ overflow: hidden;
5521
+ cursor: pointer;
5522
+ transition: all 0.15s ease;
5523
+ }
5524
+ .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
5525
+ .card.selected { border-color: var(--selected-border); border-width: 2px; }
5526
+ .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
5527
+ .card-body { padding: 1rem; }
5528
+ .card-body h3 { margin-bottom: 0.25rem; }
5529
+ .card-body p { color: var(--text-secondary); font-size: 0.85rem; }
5530
+
5531
+ /* ===== MOCKUP CONTAINER ===== */
5532
+ .mockup {
5533
+ background: var(--bg-secondary);
5534
+ border: 1px solid var(--border);
5535
+ border-radius: 12px;
5536
+ overflow: hidden;
5537
+ margin-bottom: 1.5rem;
5538
+ }
5539
+ .mockup-header {
5540
+ background: var(--bg-tertiary);
5541
+ padding: 0.5rem 1rem;
5542
+ font-size: 0.75rem;
5543
+ color: var(--text-secondary);
5544
+ border-bottom: 1px solid var(--border);
5545
+ }
5546
+ .mockup-body { padding: 1.5rem; }
5547
+
5548
+ /* ===== SPLIT VIEW (side-by-side comparison) ===== */
5549
+ .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
5550
+ @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
5551
+
5552
+ /* ===== PROS/CONS ===== */
5553
+ .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
5554
+ .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
5555
+ .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
5556
+ .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
5557
+ .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
5558
+ .pros li, .cons li { margin-bottom: 0.25rem; }
5559
+
5560
+ /* ===== PLACEHOLDER (for mockup areas) ===== */
5561
+ .placeholder {
5562
+ background: var(--bg-tertiary);
5563
+ border: 2px dashed var(--border);
5564
+ border-radius: 8px;
5565
+ padding: 2rem;
5566
+ text-align: center;
5567
+ color: var(--text-tertiary);
5568
+ }
5569
+
5570
+ /* ===== INLINE MOCKUP ELEMENTS ===== */
5571
+ .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
5572
+ .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
5573
+ .mock-content { padding: 1.5rem; flex: 1; }
5574
+ .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
5575
+ .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
5576
+ /* haren: side-by-side compare with pass/fail verdict */
5577
+ .compare { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
5578
+ .compare .pane { border: 1px solid var(--border); border-radius: 8px; padding: 0.75rem; overflow: auto; }
5579
+ .compare .pane img { max-width: 100%; display: block; }
5580
+ .verdict { display: flex; gap: 0.75rem; margin-top: 1rem; }
5581
+ .pass, .fail { border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem 1.25rem; cursor: pointer; font-weight: 600; background: var(--bg-secondary); color: var(--text-primary); }
5582
+ .pass:hover, .pass.selected { background: var(--success); color: white; }
5583
+ .fail:hover, .fail.selected { background: var(--error); color: white; }
5584
+ /* haren: review findings by severity */
5585
+ .findings { list-style: none; padding: 0; margin: 1rem 0; }
5586
+ .findings li { border-left: 4px solid var(--border); padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; background: var(--bg-secondary); border-radius: 4px; }
5587
+ .findings .blocker { border-left-color: var(--error); }
5588
+ .findings .major { border-left-color: var(--warning); }
5589
+ .findings .minor { border-left-color: var(--text-tertiary); }
5590
+ </style>
5591
+ </head>
5592
+ <body>
5593
+ <div class="header">
5594
+ <div class="brand"><span class="brand-copy">haren companion</span></div>
5595
+ <div class="status">Connecting\u2026</div>
5596
+ </div>
5597
+
5598
+ <div class="main">
5599
+ <div id="frame-content">
5600
+ <!-- CONTENT -->
5601
+ </div>
5602
+ </div>
5603
+
5604
+ <script src="/helper.js"></script>
5605
+ </body>
5606
+ </html>
5607
+ `;
5608
+ var init_frame_template = () => {};
5609
+
5610
+ // src/companion/helper.js
5611
+ var helper_default = `(function() {
5612
+ const MIN_RECONNECT_MS = 500;
5613
+ const MAX_RECONNECT_MS = 5000; // a restarted server is found within 5 s
5614
+ const MAX_LABEL_CHARS = 200;
5615
+ const TOMBSTONE_AFTER_MS = 15000; // show the "paused" overlay after this long disconnected
5616
+
5617
+ // Pure: next backoff delay (doubles, capped). Exported for unit tests.
5618
+ function nextReconnectDelay(current, max) {
5619
+ return Math.min(current * 2, max);
5620
+ }
5621
+ // Pure: collapse whitespace to single spaces and trim.
5622
+ function cleanText(s) {
5623
+ return String(s || '').replace(/\\s+/g, ' ').trim();
5624
+ }
5625
+
5626
+ // Pure (uses only querySelector and text): a short label for a clicked choice element.
5627
+ // The heading of an option or card, else the letter and title, else the text cut to 200 chars.
5628
+ function choiceLabel(el) {
5629
+ const text = (sel) => {
5630
+ const node = el.querySelector(sel);
5631
+ return node ? cleanText(node.textContent) : '';
5632
+ };
5633
+ const heading = text('.content h3') || text('.card-body h3');
5634
+ if (heading) return heading.slice(0, MAX_LABEL_CHARS);
5635
+ const letter = text('.letter');
5636
+ const title = text('.title');
5637
+ if (letter && title) return (letter + ' ' + title).slice(0, MAX_LABEL_CHARS);
5638
+ return cleanText(el.innerText || el.textContent).slice(0, MAX_LABEL_CHARS);
5639
+ }
5640
+
5641
+ if (typeof module !== 'undefined' && module.exports) {
5642
+ module.exports = {
5643
+ nextReconnectDelay, choiceLabel, cleanText,
5644
+ MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS
5645
+ };
5646
+ }
5647
+
5648
+ // Everything below is browser-only; bail out when loaded in Node (tests).
5649
+ if (typeof window === 'undefined') return;
5650
+
5651
+ let ws = null;
5652
+ let eventQueue = [];
5653
+ let reconnectDelay = MIN_RECONNECT_MS;
5654
+ let reconnectTimer = null;
5655
+ let disconnectedSince = null;
5656
+ let everConnected = false;
5657
+ let tombstoneShown = false;
5658
+
5659
+ // The server injects the session key below when it serves this file.
5660
+ const COMPANION_KEY = '__COMPANION_KEY__';
5661
+
5662
+ function websocketUrl() {
5663
+ return 'ws://' + window.location.host + '/ws?key=' + encodeURIComponent(COMPANION_KEY);
5664
+ }
5665
+
5666
+ function reloadAfterRecovery() {
5667
+ window.location.replace('/?key=' + encodeURIComponent(COMPANION_KEY));
5668
+ }
5669
+
5670
+ // Reflect connection state in the frame's status pill (absent on full-doc screens).
5671
+ function setStatus(state) {
5672
+ const el = document.querySelector('.status');
5673
+ if (!el) return;
5674
+ const map = {
5675
+ connecting: ['Connecting\u2026', 'var(--text-tertiary)'],
5676
+ connected: ['Connected', 'var(--success)'],
5677
+ reconnecting: ['Reconnecting\u2026', 'var(--warning)'],
5678
+ disconnected: ['Disconnected', 'var(--error)']
5679
+ };
5680
+ const [text, color] = map[state] || map.disconnected;
5681
+ el.textContent = text;
5682
+ el.style.setProperty('--status-color', color);
5683
+ }
5684
+
5685
+ // Self-styled so it works on framed and full-document screens alike.
5686
+ function showTombstone() {
5687
+ if (tombstoneShown) return;
5688
+ tombstoneShown = true;
5689
+ const el = document.createElement('div');
5690
+ el.id = 'bs-tombstone';
5691
+ el.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;' +
5692
+ 'align-items:center;justify-content:center;padding:2rem;text-align:center;' +
5693
+ 'background:rgba(20,20,22,0.92);color:#f5f5f7;font-family:system-ui,sans-serif';
5694
+ el.innerHTML = '<div style="max-width:480px">' +
5695
+ '<h2 style="margin:0 0 .5rem;font-weight:600">Companion paused. Reconnecting\u2026</h2>' +
5696
+ '<p style="margin:0;opacity:.85">This page connects again when the server comes back. ' +
5697
+ 'If it does not, ask your coding agent to start the companion.</p></div>';
5698
+ if (document.body) document.body.appendChild(el);
5699
+ }
5700
+
5701
+ function connect() {
5702
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
5703
+ setStatus(everConnected ? 'reconnecting' : 'connecting');
5704
+ ws = new WebSocket(websocketUrl());
5705
+
5706
+ ws.onopen = () => {
5707
+ const recovered = tombstoneShown;
5708
+ everConnected = true;
5709
+ disconnectedSince = null;
5710
+ reconnectDelay = MIN_RECONNECT_MS;
5711
+ tombstoneShown = false;
5712
+ setStatus('connected');
5713
+ eventQueue.forEach(e => ws.send(JSON.stringify(e)));
5714
+ eventQueue = [];
5715
+ // Recovered from a tombstoned outage (e.g. the server restarted on the same
5716
+ // port) \u2014 reload through the keyed bootstrap when possible so the cookie is
5717
+ // refreshed before the visible URL returns to bare /.
5718
+ if (recovered) reloadAfterRecovery();
5719
+ };
5720
+
5721
+ ws.onmessage = (msg) => {
5722
+ let data;
5723
+ try { data = JSON.parse(msg.data); } catch (e) { return; }
5724
+ if (data.type === 'reload') window.location.reload();
5725
+ };
5726
+
5727
+ ws.onclose = () => {
5728
+ ws = null;
5729
+ if (disconnectedSince === null) disconnectedSince = Date.now();
5730
+ if (Date.now() - disconnectedSince >= TOMBSTONE_AFTER_MS) {
5731
+ setStatus('disconnected');
5732
+ showTombstone();
5733
+ } else {
5734
+ setStatus('reconnecting');
5735
+ }
5736
+ reconnectTimer = setTimeout(connect, reconnectDelay);
5737
+ reconnectDelay = nextReconnectDelay(reconnectDelay, MAX_RECONNECT_MS);
5738
+ };
5739
+
5740
+ // Let onclose own reconnection so we don't schedule it twice.
5741
+ ws.onerror = () => { try { ws.close(); } catch (e) {} };
5742
+ }
5743
+
5744
+ function sendEvent(event) {
5745
+ event.timestamp = Date.now();
5746
+ if (ws && ws.readyState === WebSocket.OPEN) {
5747
+ ws.send(JSON.stringify(event));
5748
+ } else {
5749
+ eventQueue.push(event);
5750
+ }
5751
+ }
5752
+
5753
+ // Capture clicks on choice elements
5754
+ document.addEventListener('click', (e) => {
5755
+ const target = e.target.closest('[data-choice]');
5756
+ if (!target) return;
5757
+
5758
+ sendEvent({
5759
+ type: 'click',
5760
+ text: choiceLabel(target),
5761
+ choice: target.dataset.choice,
5762
+ id: target.id || null
5763
+ });
5764
+
5765
+ });
5766
+
5767
+ // Frame UI: selection tracking
5768
+ window.selectedChoice = null;
5769
+
5770
+ window.toggleSelect = function(el) {
5771
+ const container = el.closest('.options') || el.closest('.cards') || el.closest('.verdict');
5772
+ const multi = container && container.dataset.multiselect !== undefined;
5773
+ if (container && !multi) {
5774
+ container.querySelectorAll('.option, .card, .pass, .fail').forEach(o => o.classList.remove('selected'));
5775
+ }
5776
+ if (multi) {
5777
+ el.classList.toggle('selected');
5778
+ } else {
5779
+ el.classList.add('selected');
5780
+ }
5781
+ window.selectedChoice = el.dataset.choice;
5782
+ };
5783
+
5784
+ // Expose API for explicit use
5785
+ window.companion = {
5786
+ send: sendEvent,
5787
+ choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
5788
+ };
5789
+
5790
+ connect();
5791
+ })();
5792
+ `;
5793
+ var init_helper = () => {};
5794
+
5795
+ // src/companion/server.ts
5796
+ import { randomBytes, timingSafeEqual } from "crypto";
5797
+ import {
5798
+ appendFileSync,
5799
+ chmodSync,
5800
+ existsSync as existsSync19,
5801
+ lstatSync,
5802
+ mkdirSync,
5803
+ readdirSync,
5804
+ readFileSync as readFileSync3,
5805
+ realpathSync as realpathSync2,
5806
+ rmSync,
5807
+ statSync,
5808
+ writeFileSync
5809
+ } from "fs";
5810
+ import { basename as basename5, extname, join as join21, sep as sep5 } from "path";
5811
+ function makePrivateDir(dir) {
5812
+ mkdirSync(dir, { recursive: true, mode: 448 });
5813
+ try {
5814
+ chmodSync(dir, 448);
5815
+ } catch {}
5816
+ }
5817
+ function writePrivateFile(path, data) {
5818
+ writeFileSync(path, data, { mode: 384 });
5819
+ try {
5820
+ chmodSync(path, 384);
5821
+ } catch {}
5822
+ }
5823
+ function isFullDocument(html) {
5824
+ const t = html.trimStart().toLowerCase();
5825
+ return t.startsWith("<!doctype") || t.startsWith("<html");
5826
+ }
5827
+ function isRegularFileInside(dir, filePath) {
5828
+ try {
5829
+ const st = lstatSync(filePath);
5830
+ if (st.isSymbolicLink() || !st.isFile() || st.nlink !== 1)
5831
+ return false;
5832
+ return realpathSync2(filePath).startsWith(realpathSync2(dir) + sep5);
5833
+ } catch {
5834
+ return false;
5835
+ }
5836
+ }
5837
+ function newestScreen(contentDir) {
5838
+ let names;
5839
+ try {
5840
+ names = readdirSync(contentDir);
5841
+ } catch {
5842
+ return null;
5843
+ }
5844
+ let best = null;
5845
+ for (const name of names) {
5846
+ if (name.startsWith(".") || !name.endsWith(".html"))
5847
+ continue;
5848
+ const fp = join21(contentDir, name);
5849
+ if (!isRegularFileInside(contentDir, fp))
5850
+ continue;
5851
+ const mtime = statSync(fp).mtimeMs;
5852
+ if (!best || mtime > best.mtime)
5853
+ best = { path: fp, mtime };
5854
+ }
5855
+ return best ? best.path : null;
5856
+ }
5857
+ function safeEqual(a, b) {
5858
+ const ab = Buffer.from(a);
5859
+ const bb = Buffer.from(b);
5860
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
5861
+ }
5862
+ function cookieValue(header, name) {
5863
+ if (!header)
5864
+ return null;
5865
+ for (const part of header.split(";")) {
5866
+ const eq = part.indexOf("=");
5867
+ if (eq >= 0 && part.slice(0, eq).trim() === name)
5868
+ return part.slice(eq + 1).trim();
5869
+ }
5870
+ return null;
5871
+ }
5872
+ function wrapInFrame(content) {
5873
+ return frameTemplate.replace("<!-- CONTENT -->", () => content);
5874
+ }
5875
+ function injectHelper(html) {
5876
+ if (html.includes(HELPER_TAG))
5877
+ return html;
5878
+ const re = /<\/body>/i;
5879
+ return re.test(html) ? html.replace(re, (m) => `${HELPER_TAG}
5880
+ ${m}`) : html + HELPER_TAG;
5881
+ }
5882
+ function urlHostForHttp(host) {
5883
+ if (host.startsWith("[") && host.endsWith("]"))
5884
+ return host;
5885
+ return host.includes(":") ? `[${host}]` : host;
5886
+ }
5887
+ async function startCompanion(opts) {
5888
+ const contentDir = join21(opts.sessionDir, "content");
5889
+ const stateDir = join21(opts.sessionDir, "state");
5890
+ for (const dir of [opts.sessionDir, contentDir, stateDir])
5891
+ makePrivateDir(dir);
5892
+ const stoppedFile = join21(stateDir, "server-stopped");
5893
+ const eventsFile = join21(stateDir, "events");
5894
+ rmSync(stoppedFile, { force: true });
5895
+ if (existsSync19(eventsFile))
5896
+ chmodSync(eventsFile, 384);
5897
+ const key = opts.key ?? randomBytes(16).toString("hex");
5898
+ const idleTimeoutMs = opts.idleTimeoutMs ?? 240 * 60000;
5899
+ const helperScript = helperSource.replaceAll("'__COMPANION_KEY__'", () => JSON.stringify(key));
5900
+ const clients = new Set;
5901
+ let idleTimer = null;
5902
+ let stopped = false;
5903
+ let lastActivity = Date.now();
5904
+ const touch = () => {
5905
+ if (stopped)
5906
+ return;
5907
+ lastActivity = Date.now();
5908
+ if (idleTimer)
5909
+ clearTimeout(idleTimer);
5910
+ idleTimer = setTimeout(() => void stop("idle"), idleTimeoutMs);
5911
+ };
5912
+ const keyFromRequest = (req, url) => {
5913
+ const q = url.searchParams.get("key");
5914
+ if (q !== null)
5915
+ return { ok: q !== "" && safeEqual(q, key), viaQuery: true };
5916
+ const c = cookieValue(req.headers.get("cookie"), COOKIE_NAME);
5917
+ return { ok: c !== null && safeEqual(c, key), viaQuery: false };
5918
+ };
5919
+ const respond = (body, type, status = 200, extra = {}) => new Response(body, {
5920
+ status,
5921
+ headers: { ...SECURITY_HEADERS, "Content-Type": type, ...extra }
5922
+ });
5923
+ const server = Bun.serve({
5924
+ hostname: opts.host ?? "127.0.0.1",
5925
+ port: opts.port ?? 0,
5926
+ fetch(req, srv) {
5927
+ const url = new URL(req.url);
5928
+ const auth = keyFromRequest(req, url);
5929
+ if (!auth.ok)
5930
+ return respond(FORBIDDEN_PAGE, "text/html; charset=utf-8", 403);
5931
+ touch();
5932
+ if (url.pathname === "/ws") {
5933
+ if (srv.upgrade(req, { data: undefined }))
5934
+ return;
5935
+ return respond("WebSocket upgrade expected", "text/plain", 400);
5936
+ }
5937
+ const extra = auth.viaQuery ? { "Set-Cookie": `${COOKIE_NAME}=${key}; HttpOnly; SameSite=Strict; Path=/` } : {};
5938
+ if (req.method !== "GET")
5939
+ return respond("Not found", "text/plain", 404, extra);
5940
+ if (url.pathname === "/") {
5941
+ const screen = newestScreen(contentDir);
5942
+ const raw = screen ? readFileSync3(screen, "utf-8") : null;
5943
+ const html = raw === null ? wrapInFrame(WAITING_CONTENT) : isFullDocument(raw) ? injectHelper(raw) : wrapInFrame(raw);
5944
+ return respond(html, "text/html; charset=utf-8", 200, extra);
5945
+ }
5946
+ if (url.pathname === "/helper.js") {
5947
+ return respond(helperScript, "application/javascript", 200, extra);
5948
+ }
5949
+ if (url.pathname.startsWith("/files/")) {
5950
+ let name;
5951
+ try {
5952
+ name = basename5(decodeURIComponent(url.pathname.slice("/files/".length)));
5953
+ } catch {
5954
+ return respond("Not found", "text/plain", 404, extra);
5955
+ }
5956
+ const fp = join21(contentDir, name);
5957
+ if (!name || name.startsWith(".") || !isRegularFileInside(contentDir, fp)) {
5958
+ return respond("Not found", "text/plain", 404, extra);
5959
+ }
5960
+ const type = MIME_TYPES[extname(fp).toLowerCase()] ?? "application/octet-stream";
5961
+ return respond(readFileSync3(fp), type, 200, extra);
5962
+ }
5963
+ return respond("Not found", "text/plain", 404, extra);
5964
+ },
5965
+ websocket: {
5966
+ open(ws) {
5967
+ clients.add(ws);
5968
+ touch();
5969
+ },
5970
+ close(ws) {
5971
+ clients.delete(ws);
5972
+ touch();
5973
+ },
5974
+ message(_ws, message) {
5975
+ touch();
5976
+ let event;
5977
+ try {
5978
+ event = JSON.parse(String(message));
5979
+ } catch {
5980
+ return;
5981
+ }
5982
+ if (!event || typeof event !== "object" || event.type !== "click")
5983
+ return;
5984
+ const { choice, text = "" } = event;
5985
+ if (typeof choice !== "string" || typeof text !== "string")
5986
+ return;
5987
+ const line = {
5988
+ type: "click",
5989
+ choice,
5990
+ text: text.slice(0, MAX_CLICK_TEXT),
5991
+ timestamp: Math.floor(Date.now() / 1000)
5992
+ };
5993
+ appendFileSync(eventsFile, `${JSON.stringify(line)}
5994
+ `, { mode: 384 });
5995
+ }
5996
+ }
5997
+ });
5998
+ const signature = (p) => {
5999
+ if (!p)
6000
+ return "";
6001
+ try {
6002
+ return `${p}:${statSync(p).mtimeMs}`;
6003
+ } catch {
6004
+ return "";
6005
+ }
6006
+ };
6007
+ let lastPath = newestScreen(contentDir);
6008
+ let lastSig = signature(lastPath);
6009
+ const poll = setInterval(() => {
6010
+ const current = newestScreen(contentDir);
6011
+ const sig = signature(current);
6012
+ if (sig === lastSig)
6013
+ return;
6014
+ if (current !== lastPath)
6015
+ writePrivateFile(eventsFile, "");
6016
+ lastPath = current;
6017
+ lastSig = sig;
6018
+ const msg = JSON.stringify({ type: "reload" });
6019
+ for (const ws of clients)
6020
+ ws.send(msg);
6021
+ }, POLL_MS);
6022
+ const port = server.port;
6023
+ const info = {
6024
+ type: "server-started",
6025
+ port,
6026
+ url: `http://${urlHostForHttp(opts.urlHost ?? "localhost")}:${port}/?key=${key}`,
6027
+ screen_dir: contentDir,
6028
+ state_dir: stateDir
6029
+ };
6030
+ writePrivateFile(join21(stateDir, "server-info"), `${JSON.stringify(info)}
6031
+ `);
6032
+ async function stop(reason = "stopped") {
6033
+ if (stopped)
6034
+ return;
6035
+ stopped = true;
6036
+ if (idleTimer)
6037
+ clearTimeout(idleTimer);
6038
+ clearInterval(poll);
6039
+ if (existsSync19(stateDir)) {
6040
+ writeFileSync(stoppedFile, `${JSON.stringify({ reason })}
6041
+ `);
6042
+ }
6043
+ await server.stop(true);
6044
+ }
6045
+ touch();
6046
+ return { info, stop, clientCount: () => clients.size, lastActivity: () => lastActivity };
6047
+ }
6048
+ var frameTemplate, helperSource, COOKIE_NAME = "companion_key", POLL_MS = 500, MAX_CLICK_TEXT = 200, MIME_TYPES, SECURITY_HEADERS, FORBIDDEN_PAGE = `<!DOCTYPE html>
6049
+ <html><head><meta charset="utf-8"><title>Session key required</title></head>
6050
+ <body><h1>Session key required</h1>
6051
+ <p>Open the full URL your coding agent gave you, including the <code>?key=&hellip;</code> part.</p></body></html>`, WAITING_CONTENT = `<h2>haren companion</h2>
6052
+ <p class="subtitle">Waiting for the agent to push a screen...</p>`, HELPER_TAG = '<script src="/helper.js"></script>';
6053
+ var init_server = __esm(() => {
6054
+ init_frame_template();
6055
+ init_helper();
6056
+ frameTemplate = frame_template_default;
6057
+ helperSource = helper_default;
6058
+ MIME_TYPES = {
6059
+ ".html": "text/html",
6060
+ ".css": "text/css",
6061
+ ".js": "application/javascript",
6062
+ ".json": "application/json",
6063
+ ".png": "image/png",
6064
+ ".jpg": "image/jpeg",
6065
+ ".jpeg": "image/jpeg",
6066
+ ".gif": "image/gif",
6067
+ ".svg": "image/svg+xml",
6068
+ ".txt": "text/plain"
6069
+ };
6070
+ SECURITY_HEADERS = {
6071
+ "Referrer-Policy": "no-referrer",
6072
+ "Cache-Control": "no-store",
6073
+ "X-Frame-Options": "DENY",
6074
+ "Content-Security-Policy": "frame-ancestors 'none'",
6075
+ "Cross-Origin-Resource-Policy": "same-origin"
6076
+ };
6077
+ });
6078
+
6079
+ // src/commands/companion.ts
6080
+ import { randomBytes as randomBytes2 } from "crypto";
6081
+ import {
6082
+ existsSync as existsSync20,
6083
+ readdirSync as readdirSync2,
6084
+ readFileSync as readFileSync4,
6085
+ renameSync,
6086
+ rmSync as rmSync2,
6087
+ statSync as statSync2,
6088
+ writeFileSync as writeFileSync2
6089
+ } from "fs";
6090
+ import { spawnSync } from "child_process";
6091
+ import { join as join22, resolve as resolve13 } from "path";
6092
+ function flag(args, name) {
6093
+ const i = args.indexOf(name);
6094
+ if (i === -1)
6095
+ return;
6096
+ const value = args[i + 1];
6097
+ if (value === undefined || value.startsWith("--"))
6098
+ throw new Error(`${name} needs a value`);
6099
+ return value;
6100
+ }
6101
+ function readJson(path) {
6102
+ try {
6103
+ return JSON.parse(readFileSync4(path, "utf-8"));
6104
+ } catch {
6105
+ return null;
6106
+ }
6107
+ }
6108
+ function savedMinutes(value) {
6109
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
6110
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : undefined;
6111
+ }
6112
+ function pidAlive(pid) {
6113
+ try {
6114
+ process.kill(pid, 0);
6115
+ return true;
6116
+ } catch (e) {
6117
+ return e.code === "EPERM";
6118
+ }
6119
+ }
6120
+ function readPid(dir) {
6121
+ try {
6122
+ const n = Number.parseInt(readFileSync4(join22(dir, "state", "pid"), "utf-8").trim(), 10);
6123
+ return Number.isFinite(n) && n > 0 ? n : null;
6124
+ } catch {
6125
+ return null;
6126
+ }
6127
+ }
6128
+ function sessionOf(dir) {
6129
+ const stateDir = join22(dir, "state");
6130
+ const info = readJson(join22(stateDir, "server-info")) ?? readJson(join22(stateDir, "server-info.prev"));
6131
+ const pid = readPid(dir);
6132
+ const running = info !== null && !existsSync20(join22(stateDir, "server-stopped")) && pid !== null && pidAlive(pid);
6133
+ return { dir, info, running };
6134
+ }
6135
+ function latestSession(harenDir) {
6136
+ const base = join22(harenDir, ".companion");
6137
+ let best = null;
6138
+ let names;
6139
+ try {
6140
+ names = readdirSync2(base);
6141
+ } catch {
6142
+ return null;
6143
+ }
6144
+ for (const name of names) {
6145
+ const dir = join22(base, name);
6146
+ try {
6147
+ const st = statSync2(dir);
6148
+ if (!st.isDirectory())
6149
+ continue;
6150
+ const epoch = Number(name.split("-")[1]);
6151
+ const t = Number.isFinite(epoch) ? epoch : st.mtimeMs;
6152
+ if (!best || t > best.mtime)
6153
+ best = { dir, mtime: t };
6154
+ } catch {}
6155
+ }
6156
+ return best ? sessionOf(best.dir) : null;
6157
+ }
6158
+ async function portFree(port, host) {
6159
+ try {
6160
+ const s = Bun.serve({ hostname: host, port, fetch: () => new Response("") });
6161
+ await s.stop(true);
6162
+ return true;
6163
+ } catch {
6164
+ return false;
6165
+ }
6166
+ }
6167
+ function cliEntry() {
6168
+ const here = import.meta.path;
6169
+ if (/[\\/]commands[\\/]companion\.ts$/.test(here))
6170
+ return resolve13(import.meta.dir, "..", "index.ts");
6171
+ return here;
6172
+ }
6173
+ function openBrowser(url) {
6174
+ try {
6175
+ const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
6176
+ Bun.spawn(cmd, { stdio: ["ignore", "ignore", "ignore"] }).unref();
6177
+ } catch {}
6178
+ }
6179
+ function badValue(message) {
6180
+ console.log(JSON.stringify({ error: message }));
6181
+ throw new ExitCode(1, message);
6182
+ }
6183
+ function checkPort(value) {
6184
+ if (value === undefined)
6185
+ return;
6186
+ const n = Number(value);
6187
+ if (!/^\d+$/.test(value) || n > 65535)
6188
+ badValue("--port must be an integer from 0 to 65535");
6189
+ }
6190
+ function readPs(pid) {
6191
+ try {
6192
+ const r = spawnSync("ps", ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf-8" });
6193
+ const m = /^\s*(\d+)\s+(.+?)\s*$/.exec(String(r.stdout));
6194
+ return m ? { ppid: Number(m[1]), comm: m[2] } : null;
6195
+ } catch {
6196
+ return null;
6197
+ }
6198
+ }
6199
+ function isShell(comm) {
6200
+ const base = comm.split("/").pop() ?? comm;
6201
+ return SHELLS.has(base.replace(/^-/, ""));
6202
+ }
6203
+ function pickOwnerPid(start, ps = readPs) {
6204
+ let pid = start;
6205
+ for (let hops = 0;pid > 1 && hops < 64; hops++) {
6206
+ const e = ps(pid);
6207
+ if (!e)
6208
+ break;
6209
+ if (!isShell(e.comm))
6210
+ return pid;
6211
+ pid = e.ppid;
6212
+ }
6213
+ const gp = ps(start)?.ppid;
6214
+ if (gp !== undefined && gp > 1)
6215
+ return gp;
6216
+ return start > 1 ? start : undefined;
6217
+ }
6218
+ function ownerPid() {
6219
+ if (process.platform === "win32")
6220
+ return;
6221
+ return pickOwnerPid(process.ppid);
6222
+ }
6223
+ function buildServeArgs(dir, o) {
6224
+ const args = ["__serve", "--session", dir, "--port", String(o.port), "--host", o.host];
6225
+ args.push("--key-file", o.keyFile);
6226
+ if (o.urlHost !== undefined)
6227
+ args.push("--url-host", o.urlHost);
6228
+ if (o.idleTimeoutMinutes !== undefined)
6229
+ args.push("--idle-timeout-minutes", String(o.idleTimeoutMinutes));
6230
+ if (o.ownerPid !== undefined)
6231
+ args.push("--owner-pid", String(o.ownerPid));
6232
+ if (o.ownerGraceMinutes !== undefined)
6233
+ args.push("--owner-grace-minutes", String(o.ownerGraceMinutes));
6234
+ if (o.open)
6235
+ args.push("--open");
6236
+ if (o.portFallback)
6237
+ args.push("--port-fallback");
6238
+ return args;
6239
+ }
6240
+ function checkMinutes(name, value) {
6241
+ if (value !== undefined && (!/^\d+$/.test(value) || Number(value) < 1))
6242
+ badValue(`${name} must be a positive integer`);
6243
+ }
6244
+ async function serve(args) {
6245
+ const sessionDir = flag(args, "--session");
6246
+ if (!sessionDir)
6247
+ throw new Error("__serve needs --session <dir>");
6248
+ const portText = flag(args, "--port") ?? "0";
6249
+ checkPort(portText);
6250
+ const port = Number(portText);
6251
+ const minutes = flag(args, "--idle-timeout-minutes");
6252
+ if (minutes !== undefined && !(Number(minutes) > 0))
6253
+ badValue("--idle-timeout-minutes must be a positive number");
6254
+ const ownerText = flag(args, "--owner-pid");
6255
+ let owner = ownerText === undefined ? undefined : Number(ownerText);
6256
+ if (owner !== undefined && !(Number.isInteger(owner) && owner > 0))
6257
+ badValue("--owner-pid must be a positive integer");
6258
+ if (owner !== undefined && !pidAlive(owner))
6259
+ owner = undefined;
6260
+ const graceText = flag(args, "--owner-grace-minutes");
6261
+ if (graceText !== undefined && !(Number(graceText) > 0))
6262
+ badValue("--owner-grace-minutes must be a positive number");
6263
+ const graceMs = Number(graceText ?? DEFAULT_OWNER_GRACE_MINUTES) * 60000;
6264
+ const stateDir = join22(sessionDir, "state");
6265
+ for (const d of [sessionDir, join22(sessionDir, "content"), stateDir])
6266
+ makePrivateDir(d);
6267
+ const keyPath = join22(stateDir, "key");
6268
+ const keyFile = flag(args, "--key-file");
6269
+ let key = keyFile ? readKey(keyFile) : undefined;
6270
+ if (keyFile && !key)
6271
+ throw new Error(`No key in ${keyFile}`);
6272
+ key ??= randomBytes2(16).toString("hex");
6273
+ if (!keyFile || resolve13(keyFile) !== resolve13(keyPath))
6274
+ writePrivateFile(keyPath, `${key}
6275
+ `);
6276
+ const opts = {
6277
+ sessionDir,
6278
+ port,
6279
+ key,
6280
+ host: flag(args, "--host"),
6281
+ urlHost: flag(args, "--url-host"),
6282
+ idleTimeoutMs: minutes ? Number(minutes) * 60000 : undefined
6283
+ };
6284
+ let handle;
6285
+ try {
6286
+ handle = await startCompanion(opts);
6287
+ } catch (e) {
6288
+ if (!args.includes("--port-fallback") || port === 0)
6289
+ throw e;
6290
+ handle = await startCompanion({ ...opts, port: 0 });
6291
+ }
6292
+ writePrivateFile(join22(stateDir, "pid"), `${process.pid}
6293
+ `);
6294
+ await new Promise((done) => {
6295
+ const stopFile = join22(handle.info.state_dir, "server-stopped");
6296
+ let opened = !args.includes("--open");
6297
+ let lastOwnerCheck = Date.now();
6298
+ let ownerGoneAt = null;
6299
+ const finish = () => {
6300
+ clearInterval(timer);
6301
+ process.off("SIGTERM", onSignal);
6302
+ process.off("SIGINT", onSignal);
6303
+ done();
6304
+ };
6305
+ const onSignal = () => void handle.stop("stop").then(finish);
6306
+ const timer = setInterval(() => {
6307
+ if (!opened && newestScreen(handle.info.screen_dir)) {
6308
+ opened = true;
6309
+ openBrowser(handle.info.url);
6310
+ }
6311
+ if (owner !== undefined && Date.now() - lastOwnerCheck >= OWNER_CHECK_MS) {
6312
+ lastOwnerCheck = Date.now();
6313
+ if (ownerGoneAt === null && !pidAlive(owner))
6314
+ ownerGoneAt = Date.now();
6315
+ }
6316
+ if (ownerGoneAt !== null && handle.clientCount() === 0) {
6317
+ const quietSince = Math.max(ownerGoneAt, handle.lastActivity());
6318
+ if (Date.now() - quietSince >= graceMs) {
6319
+ handle.stop("owner-exited").then(finish);
6320
+ return;
6321
+ }
6322
+ }
6323
+ if (existsSync20(stopFile))
6324
+ finish();
6325
+ }, 100);
6326
+ process.on("SIGTERM", onSignal);
6327
+ process.on("SIGINT", onSignal);
6328
+ });
6329
+ await handle.stop("stop");
6330
+ }
6331
+ function readKey(path) {
6332
+ try {
6333
+ return readFileSync4(path, "utf-8").trim() || undefined;
6334
+ } catch {
6335
+ return;
6336
+ }
6337
+ }
6338
+ function restoreInfo(dir) {
6339
+ const infoPath = join22(dir, "state", "server-info");
6340
+ if (!existsSync20(infoPath) && existsSync20(`${infoPath}.prev`))
6341
+ renameSync(`${infoPath}.prev`, infoPath);
6342
+ }
6343
+ function keyOf(url) {
6344
+ try {
6345
+ return new URL(url).searchParams.get("key") ?? undefined;
6346
+ } catch {
6347
+ return;
6348
+ }
6349
+ }
6350
+ function notePortChange(restart, info) {
6351
+ if (restart?.info && restart.info.port !== info.port) {
6352
+ console.error(`The companion port changed from ${restart.info.port} to ${info.port}: port changed, give the user the new URL.`);
6353
+ }
6354
+ }
6355
+ async function waitExit(pid, ms) {
6356
+ const deadline = Date.now() + ms;
6357
+ while (pidAlive(pid) && Date.now() < deadline)
6358
+ await Bun.sleep(25);
6359
+ return !pidAlive(pid);
6360
+ }
6361
+ async function terminate(pid, waitMs) {
6362
+ try {
6363
+ process.kill(pid, "SIGTERM");
6364
+ } catch {}
6365
+ if (await waitExit(pid, waitMs))
6366
+ return false;
6367
+ try {
6368
+ process.kill(pid, "SIGKILL");
6369
+ } catch {}
6370
+ await waitExit(pid, 1000);
6371
+ return true;
6372
+ }
6373
+ async function start(harenDir, args) {
6374
+ const askedPort = flag(args, "--port");
6375
+ checkPort(askedPort);
6376
+ const askedMinutes = flag(args, "--idle-timeout-minutes");
6377
+ checkMinutes("--idle-timeout-minutes", askedMinutes);
6378
+ const askedGrace = flag(args, "--owner-grace-minutes");
6379
+ checkMinutes("--owner-grace-minutes", askedGrace);
6380
+ const current = latestSession(harenDir);
6381
+ if (current?.running && current.info) {
6382
+ const ignored = START_FLAGS.filter((f) => args.includes(f));
6383
+ if (ignored.length > 0) {
6384
+ console.error(`A companion session is already running; reused it and ignored ${ignored.join(", ")}.`);
6385
+ }
6386
+ console.log(JSON.stringify(current.info));
6387
+ return;
6388
+ }
6389
+ const askedKey = flag(args, "--key");
6390
+ const restart = current?.info && askedPort === undefined && askedKey === undefined ? current : null;
6391
+ const saved = restart ? readJson(join22(restart.dir, "state", "options.json")) : null;
6392
+ const options = {
6393
+ host: flag(args, "--host") ?? saved?.host ?? "127.0.0.1",
6394
+ urlHost: flag(args, "--url-host") ?? saved?.urlHost,
6395
+ idleTimeoutMinutes: askedMinutes !== undefined ? Number(askedMinutes) : savedMinutes(saved?.idleTimeoutMinutes),
6396
+ ownerGraceMinutes: askedGrace !== undefined ? Number(askedGrace) : savedMinutes(saved?.ownerGraceMinutes)
6397
+ };
6398
+ let port = 0;
6399
+ let reused = false;
6400
+ if (askedPort !== undefined)
6401
+ port = Number(askedPort);
6402
+ else if (current?.info && await portFree(current.info.port, options.host)) {
6403
+ port = current.info.port;
6404
+ reused = true;
6405
+ } else if (restart) {
6406
+ reused = true;
6407
+ port = restart.info.port;
6408
+ }
6409
+ const dir = restart ? restart.dir : join22(harenDir, ".companion", `${process.pid}-${Date.now()}`);
6410
+ const fresh = !restart;
6411
+ const stateDir = join22(dir, "state");
6412
+ for (const d of [dir, join22(dir, "content"), stateDir])
6413
+ makePrivateDir(d);
6414
+ const keyPath = join22(stateDir, "key");
6415
+ const oldKey = restart ? readKey(keyPath) ?? keyOf(restart.info.url) : undefined;
6416
+ writePrivateFile(keyPath, `${askedKey ?? oldKey ?? randomBytes2(16).toString("hex")}
6417
+ `);
6418
+ if (restart) {
6419
+ const stoppedAt = mtimeOf(join22(stateDir, "server-stopped"));
6420
+ rmSync2(join22(stateDir, "server-stopped"), { force: true });
6421
+ const infoPath = join22(stateDir, "server-info");
6422
+ if (existsSync20(infoPath))
6423
+ renameSync(infoPath, `${infoPath}.prev`);
6424
+ archiveScreens(join22(dir, "content"), stoppedAt);
6425
+ }
6426
+ const foreground = args.includes("--foreground");
6427
+ const serveArgs = buildServeArgs(dir, {
6428
+ port,
6429
+ host: options.host,
6430
+ keyFile: keyPath,
6431
+ urlHost: options.urlHost,
6432
+ idleTimeoutMinutes: options.idleTimeoutMinutes,
6433
+ ownerGraceMinutes: options.ownerGraceMinutes,
6434
+ open: args.includes("--open"),
6435
+ portFallback: reused,
6436
+ ownerPid: foreground || args.includes("--no-owner-watch") ? undefined : ownerPid()
6437
+ });
6438
+ const fail = () => {
6439
+ if (fresh)
6440
+ rmSync2(dir, { recursive: true, force: true });
6441
+ else
6442
+ restoreInfo(dir);
6443
+ };
6444
+ const succeed = (info) => {
6445
+ rmSync2(join22(stateDir, "server-info.prev"), { force: true });
6446
+ writePrivateFile(join22(stateDir, "options.json"), `${JSON.stringify(options)}
6447
+ `);
6448
+ notePortChange(restart, info);
6449
+ };
6450
+ if (foreground) {
6451
+ const infoFile = join22(stateDir, "server-info");
6452
+ const printer = setInterval(() => {
6453
+ if (existsSync20(infoFile)) {
6454
+ const info = readJson(infoFile);
6455
+ if (!info)
6456
+ return;
6457
+ clearInterval(printer);
6458
+ succeed(info);
6459
+ console.log(JSON.stringify(info));
6460
+ }
6461
+ }, 50);
6462
+ try {
6463
+ await serve(serveArgs);
6464
+ } catch (e) {
6465
+ fail();
6466
+ throw e;
6467
+ } finally {
6468
+ clearInterval(printer);
6469
+ }
6470
+ return;
6471
+ }
6472
+ const child = companionDeps.spawnServe(serveArgs);
6473
+ writePrivateFile(join22(stateDir, "pid"), `${child.pid}
6474
+ `);
6475
+ const deadline = Date.now() + companionDeps.startTimeoutMs;
6476
+ while (Date.now() < deadline) {
6477
+ const s = sessionOf(dir);
6478
+ if (s.info && s.running && existsSync20(join22(stateDir, "server-info"))) {
6479
+ succeed(s.info);
6480
+ console.log(JSON.stringify(s.info));
6481
+ return;
6482
+ }
6483
+ if (child.exitCode !== null)
6484
+ break;
6485
+ await Bun.sleep(50);
6486
+ }
6487
+ await terminate(child.pid, companionDeps.startKillWaitMs);
6488
+ fail();
6489
+ throw new Error(`The companion server did not start within ${companionDeps.startTimeoutMs / 1000} s.`);
6490
+ }
6491
+ function mtimeOf(path) {
6492
+ try {
6493
+ return statSync2(path).mtimeMs;
6494
+ } catch {
6495
+ return Number.POSITIVE_INFINITY;
6496
+ }
6497
+ }
6498
+ function archiveScreens(contentDir, stoppedAt) {
6499
+ let names;
6500
+ try {
6501
+ names = readdirSync2(contentDir).filter((n) => {
6502
+ if (!n.endsWith(".html"))
6503
+ return false;
6504
+ const st = statSync2(join22(contentDir, n));
6505
+ return st.isFile() && st.mtimeMs < stoppedAt;
6506
+ });
6507
+ } catch {
6508
+ return;
6509
+ }
6510
+ if (names.length === 0)
6511
+ return;
6512
+ const target = join22(contentDir, "archive", String(Date.now()));
6513
+ makePrivateDir(join22(contentDir, "archive"));
6514
+ makePrivateDir(target);
6515
+ for (const n of names)
6516
+ renameSync(join22(contentDir, n), join22(target, n));
6517
+ }
6518
+ function status(harenDir) {
6519
+ const s = latestSession(harenDir);
6520
+ if (!s?.running || !s.info) {
6521
+ console.log("The companion server is not running.");
6522
+ throw new ExitCode(1, "");
6523
+ }
6524
+ console.log(`running ${s.info.url}
6525
+ screen_dir ${s.info.screen_dir}
6526
+ state_dir ${s.info.state_dir}`);
6527
+ }
6528
+ function markStopped(dir) {
6529
+ const stopped = join22(dir, "state", "server-stopped");
6530
+ if (existsSync20(join22(dir, "state")) && !existsSync20(stopped))
6531
+ writeFileSync2(stopped, `${JSON.stringify({ reason: "stop" })}
6532
+ `);
6533
+ }
6534
+ async function stop(harenDir) {
6535
+ const s = latestSession(harenDir);
6536
+ if (!s?.running) {
6537
+ if (s)
6538
+ markStopped(s.dir);
6539
+ console.log("No companion server is running.");
6540
+ return;
6541
+ }
6542
+ const pid = readPid(s.dir);
6543
+ const forced = pid !== null && await terminate(pid, companionDeps.stopWaitMs);
6544
+ markStopped(s.dir);
6545
+ console.log(forced ? "stopped (forced)" : "stopped");
6546
+ }
6547
+ async function companion(args, cwd = process.cwd()) {
6548
+ const [sub, ...rest] = args;
6549
+ if (sub === "__serve")
6550
+ return serve(rest);
6551
+ if (!sub || !["start", "status", "stop"].includes(sub)) {
6552
+ console.log(USAGE2);
6553
+ if (sub)
6554
+ throw new ExitCode(1, `Unknown companion command: ${sub}`);
6555
+ return;
6556
+ }
6557
+ const location = await resolveHarenDir(cwd, { harenDir: harenDirFlag(args), env: process.env });
6558
+ if (!location)
6559
+ throw new Error("No haren folder found. Run `haren init` first.");
6560
+ const harenDir = location.harenDir;
6561
+ if (sub === "start")
6562
+ return start(harenDir, rest);
6563
+ if (sub === "status")
6564
+ return status(harenDir);
6565
+ return stop(harenDir);
6566
+ }
6567
+ var USAGE2 = `Usage: haren companion <start|status|stop> [--haren-dir <path>]
6568
+ start [--foreground] [--open] [--port <n>] [--host <h>] [--url-host <u>] [--idle-timeout-minutes <m>]
6569
+ [--key <k>] [--no-owner-watch] [--owner-grace-minutes <m>]
6570
+ status print the URL of the running server (exit 1 when stopped)
6571
+ stop stop the running server`, START_FLAGS, companionDeps, SHELLS, OWNER_CHECK_MS = 1000, DEFAULT_OWNER_GRACE_MINUTES = 10;
6572
+ var init_companion = __esm(() => {
6573
+ init_server();
6574
+ init_exit_code();
6575
+ init_resolve();
6576
+ START_FLAGS = [
6577
+ "--port",
6578
+ "--open",
6579
+ "--key",
6580
+ "--idle-timeout-minutes",
6581
+ "--host",
6582
+ "--url-host",
6583
+ "--no-owner-watch",
6584
+ "--owner-grace-minutes"
6585
+ ];
6586
+ companionDeps = {
6587
+ startTimeoutMs: 5000,
6588
+ startKillWaitMs: 1000,
6589
+ stopWaitMs: 3000,
6590
+ spawnServe(serveArgs) {
6591
+ const child = Bun.spawn([process.execPath, cliEntry(), "companion", ...serveArgs], {
6592
+ stdio: ["ignore", "ignore", "ignore"],
6593
+ detached: true
6594
+ });
6595
+ child.unref();
6596
+ return child;
6597
+ }
6598
+ };
6599
+ SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh", "tcsh", "csh", "env"]);
4061
6600
  });
4062
6601
 
4063
6602
  // src/index.ts
6603
+ init_exit_code();
4064
6604
  function parseArgs(args) {
4065
6605
  if (args.length === 0) {
4066
6606
  return { command: "help", args: [] };
@@ -4079,6 +6619,8 @@ function parseArgs(args) {
4079
6619
  case "agent":
4080
6620
  case "plugin":
4081
6621
  case "track":
6622
+ case "migrate":
6623
+ case "companion":
4082
6624
  return { command, args: rest };
4083
6625
  default:
4084
6626
  return { command: "unknown", args };
@@ -4113,34 +6655,53 @@ async function main() {
4113
6655
  await track(parsed.args);
4114
6656
  break;
4115
6657
  }
6658
+ case "migrate": {
6659
+ await Promise.resolve().then(() => init_migrate());
6660
+ await migrate(parsed.args);
6661
+ break;
6662
+ }
6663
+ case "companion": {
6664
+ await Promise.resolve().then(() => init_companion());
6665
+ await companion(parsed.args);
6666
+ break;
6667
+ }
4116
6668
  case "help":
4117
6669
  console.log("Usage:");
4118
6670
  console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
4119
6671
  console.log(" --dir <path> --layout monorepo|workspace --haren-dir <name>");
6672
+ console.log(" --mode <undecided|explore|blueprint|inherit|migration>");
4120
6673
  console.log(" --yes|-y --dry-run --force");
4121
6674
  console.log(" --plugin <name|source> (repeatable)");
4122
6675
  console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run, --yes)");
4123
6676
  console.log(" haren agent Manage local agent (start, stop, status)");
4124
6677
  console.log(" haren plugin Manage plugins (add, remove, list, run, doctor)");
4125
6678
  console.log(" haren track Record progress and events:");
4126
- console.log(" status <module> <status>");
6679
+ console.log(" status <module> <status> [--branch <name>] [--repos <key1,key2>]");
4127
6680
  console.log(" feature <module> <feature> [status]");
4128
6681
  console.log(" commit <module> <repoKey> <sha>");
6682
+ console.log(" depends <module> [dep ...] (replace the dependency list)");
4129
6683
  console.log(" artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]");
4130
6684
  console.log(" event <type> [--module m] [--phase p] [--feature f] [--data '<json>']");
6685
+ console.log(" unit <module> <unit> <status> (migration mode)");
6686
+ console.log(" ui-mode <ask|ascii|browser|artifact>");
4131
6687
  console.log(' override on --reason "<text>" [--hours <n>] | override off');
6688
+ console.log(" haren migrate Run the migration adapter:");
6689
+ console.log(" inventory [--module <m>] | extract <unit> | gate <unit> [--approve]");
6690
+ console.log(" gate exit codes: 0 approved, 1 failed, 3 PASS but not approved yet");
6691
+ console.log(" haren companion Visual companion server: start [--foreground] [--open] | status | stop");
4132
6692
  break;
4133
6693
  case "unknown":
4134
6694
  console.error(`Unknown command: ${parsed.args[0]}`);
4135
- console.log("Usage: haren init | upgrade | agent | plugin | track (haren --help)");
6695
+ console.log("Usage: haren init | upgrade | agent | plugin | track | migrate | companion (haren --help)");
4136
6696
  process.exit(1);
4137
6697
  }
4138
6698
  }
4139
6699
  main().catch((err) => {
4140
6700
  const debug = process.env.HAREN_DEBUG === "1";
4141
6701
  const message = err instanceof Error ? debug && err.stack || err.message : String(err);
4142
- console.error(` ${message}`);
4143
- process.exit(1);
6702
+ if (message)
6703
+ console.error(` ${message}`);
6704
+ process.exit(err instanceof ExitCode ? err.code : 1);
4144
6705
  });
4145
6706
  export {
4146
6707
  parseArgs