@odarino/haren 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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,28 +299,239 @@ 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
 
283
537
  const progressFile = Bun.file(resolve(harenDir, "progress.json"));
@@ -390,9 +644,14 @@ function renderReposBlock(repos) {
390
644
  `;
391
645
  for (const field of REPO_FIELDS) {
392
646
  const value = repos[key][field];
393
- if (value)
647
+ if (typeof value === "boolean") {
648
+ if (value)
649
+ out += ` ${field}: true
650
+ `;
651
+ } else if (value) {
394
652
  out += ` ${field}: ${yamlScalar(value)}
395
653
  `;
654
+ }
396
655
  }
397
656
  }
398
657
  return out;
@@ -407,6 +666,13 @@ function toLf(text) {
407
666
  return text.replace(/\r\n/g, `
408
667
  `);
409
668
  }
669
+ function replaceTopLevelBlock(text, key, block) {
670
+ const eol = eolOf(text);
671
+ const out = replaceTopLevelBlockLf(toLf(text), key, toLf(block));
672
+ return eol === `
673
+ ` ? out : out.replace(/\n/g, `\r
674
+ `);
675
+ }
410
676
  function replaceTopLevelBlockLf(text, key, block) {
411
677
  const lines = text.split(`
412
678
  `);
@@ -428,6 +694,30 @@ ${block}`;
428
694
  return lines.join(`
429
695
  `);
430
696
  }
697
+ function setUiModeText(text, mode) {
698
+ const lines = text.split(`
699
+ `);
700
+ const start = lines.findIndex((l) => /^ui:\s*(#.*)?\r?$/.test(l));
701
+ if (start === -1)
702
+ return replaceTopLevelBlock(text, "ui", `ui:
703
+ mockups: ${mode}
704
+ `);
705
+ let end = start + 1;
706
+ while (end < lines.length && (/^\r?$/.test(lines[end]) || /^\s/.test(lines[end])))
707
+ end++;
708
+ for (let i = start + 1;i < end; i++) {
709
+ const m = /^(\s+mockups:\s*)([^\s#]*)(.*)$/.exec(lines[i]);
710
+ if (m) {
711
+ lines[i] = `${m[1]}${mode}${m[3]}`;
712
+ return lines.join(`
713
+ `);
714
+ }
715
+ }
716
+ const cr = lines[start].endsWith("\r") ? "\r" : "";
717
+ lines.splice(start + 1, 0, ` mockups: ${mode}${cr}`);
718
+ return lines.join(`
719
+ `);
720
+ }
431
721
  function migrateManifestText(text, mig) {
432
722
  const eol = eolOf(text);
433
723
  const lf = toLf(text);
@@ -457,7 +747,10 @@ project: ${yamlScalar(o.project)}
457
747
  mode: ${yamlScalar(o.mode)}
458
748
  language: ${yamlScalar(o.language)}
459
749
 
460
- ${renderReposBlock(o.repos)}
750
+ ${renderReposBlock(o.repos)}${o.mode === "migration" ? MIGRATION_SCAFFOLD(Object.keys(o.repos).length === 0) : ""}
751
+ ui:
752
+ mockups: ask # ask | ascii | browser
753
+
461
754
  sources:
462
755
  # Mode-specific inputs
463
756
  # docs: ./artifacts/00-baseline/requirements.pdf
@@ -477,17 +770,148 @@ iterations:
477
770
  }
478
771
  return text;
479
772
  }
480
- var REPO_FIELDS, YAML_KEYWORDS, YAML_SPECIAL_FLOAT;
773
+ function regex(value, field) {
774
+ if (typeof value !== "string" || !value) {
775
+ throw new Error(`manifest migration.${field} must be a regex string`);
776
+ }
777
+ try {
778
+ return new RegExp(value);
779
+ } catch {
780
+ throw new Error(`manifest migration.${field} is not a valid regex: ${value}`);
781
+ }
782
+ }
783
+ function readMigrationConfig(m) {
784
+ if (m.mode !== "migration")
785
+ return null;
786
+ const b = m.migration;
787
+ if (!b || typeof b !== "object") {
788
+ throw new Error("mode: migration needs a migration block in manifest.yaml");
789
+ }
790
+ if (Array.isArray(b))
791
+ throw new Error("manifest migration block must be a mapping");
792
+ if (b.adapter !== undefined && b.adapter !== null && typeof b.adapter !== "string") {
793
+ throw new Error("manifest migration.adapter must be a plugin name string");
794
+ }
795
+ if (b.liveLegacy !== undefined && b.liveLegacy !== null && typeof b.liveLegacy !== "boolean") {
796
+ throw new Error("manifest migration.liveLegacy must be true or false");
797
+ }
798
+ const acceptance = b.acceptance ?? "parity";
799
+ if (acceptance !== "parity" && acceptance !== "parity-with-approved-deviations") {
800
+ throw new Error("manifest migration.acceptance must be parity or parity-with-approved-deviations");
801
+ }
802
+ return {
803
+ adapter: typeof b.adapter === "string" && b.adapter ? b.adapter : undefined,
804
+ unitId: regex(b.unitId, "unitId"),
805
+ parentOf: b.parentOf === undefined ? undefined : regex(b.parentOf, "parentOf"),
806
+ acceptance,
807
+ liveLegacy: b.liveLegacy === true
808
+ };
809
+ }
810
+ function legacyRepo(m) {
811
+ const found = Object.entries(normalizeRepos(m.repos)).filter(([, r]) => r.role === "legacy");
812
+ if (found.length > 1) {
813
+ throw new Error(`manifest.yaml has more than one repo with role: legacy (${found.map(([k]) => k).join(", ")}); keep one`);
814
+ }
815
+ return found[0] ?? null;
816
+ }
817
+ var REPO_FIELDS, YAML_KEYWORDS, YAML_SPECIAL_FLOAT, UI_MODES, MIGRATION_SCAFFOLD = (withLegacyExample) => `${withLegacyExample ? ` # Add the read-only legacy repo, then remove the # marks:
818
+ # legacy_src: { path: ../legacy_src, role: legacy, readOnly: true }
819
+ ` : ""}
820
+ migration:
821
+ # repo paths are relative to this folder
822
+ # adapter: <plugin-name> # optional: a plugin that provides inventory, extract and gate
823
+ unitId: '^SCR_[A-Z]\\d{3}(_P\\d+)?$' # change it to match your legacy unit ids; change or remove parentOf below to match
824
+ parentOf: '^(SCR_[A-Z]\\d{3})_P\\d+$'
825
+ acceptance: parity-with-approved-deviations
826
+ liveLegacy: false
827
+ `;
481
828
  var init_manifest = __esm(() => {
482
- REPO_FIELDS = ["path", "remote", "default_branch", "role", "stack", "test_cmd"];
829
+ REPO_FIELDS = [
830
+ "path",
831
+ "remote",
832
+ "default_branch",
833
+ "role",
834
+ "stack",
835
+ "test_cmd",
836
+ "readOnly"
837
+ ];
483
838
  YAML_KEYWORDS = /^(true|false|null|yes|no|on|off|~)$/i;
484
839
  YAML_SPECIAL_FLOAT = /^[-+]?\.(inf|nan)$/i;
840
+ UI_MODES = ["ask", "ascii", "browser"];
841
+ });
842
+
843
+ // src/plugins/paths.ts
844
+ import { isAbsolute } from "path";
845
+ function assertInsidePlugin(p, field) {
846
+ if (isAbsolute(p) || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split(/[\\/]/).includes("..")) {
847
+ throw new Error(`Plugin manifest: ${field} path must stay inside the plugin: ${p}`);
848
+ }
849
+ }
850
+ var init_paths = () => {};
851
+
852
+ // src/plugins/adapter-spec.ts
853
+ function validateAdapter(raw) {
854
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
855
+ throw new Error("Plugin manifest: adapter must be an object");
856
+ }
857
+ const a = raw;
858
+ if (typeof a.unitKind !== "string" || !a.unitKind) {
859
+ throw new Error("Plugin manifest: adapter.unitKind is required");
860
+ }
861
+ const commands = {};
862
+ if (a.commands !== undefined) {
863
+ if (!a.commands || typeof a.commands !== "object" || Array.isArray(a.commands)) {
864
+ throw new Error("Plugin manifest: adapter.commands must be an object");
865
+ }
866
+ for (const [name, command] of Object.entries(a.commands)) {
867
+ if (!ADAPTER_COMMANDS.includes(name)) {
868
+ throw new Error(`Plugin manifest: Unknown adapter command: ${name}`);
869
+ }
870
+ if (typeof command !== "string" || !command) {
871
+ throw new Error(`Plugin manifest: adapter command ${name} needs a command string`);
872
+ }
873
+ for (const [, key] of command.matchAll(/\{([^{}]*)\}/g)) {
874
+ if (!PLACEHOLDERS.includes(key)) {
875
+ throw new Error(`Plugin manifest: adapter command ${name} has unknown placeholder {${key}}`);
876
+ }
877
+ }
878
+ commands[name] = command;
879
+ }
880
+ }
881
+ const skills = {};
882
+ if (a.skills !== undefined) {
883
+ if (!a.skills || typeof a.skills !== "object" || Array.isArray(a.skills)) {
884
+ throw new Error("Plugin manifest: adapter.skills must be an object");
885
+ }
886
+ const spec = a.skills.spec;
887
+ if (spec !== undefined) {
888
+ if (typeof spec !== "string" || !spec) {
889
+ throw new Error("Plugin manifest: adapter.skills.spec must be a string");
890
+ }
891
+ skills.spec = spec;
892
+ }
893
+ }
894
+ let semantics;
895
+ if (a.semantics !== undefined) {
896
+ if (typeof a.semantics !== "string" || !a.semantics) {
897
+ throw new Error("Plugin manifest: adapter.semantics must be a path string");
898
+ }
899
+ assertInsidePlugin(a.semantics, "adapter.semantics");
900
+ semantics = a.semantics;
901
+ }
902
+ return { unitKind: a.unitKind, commands, skills, semantics };
903
+ }
904
+ var ADAPTER_COMMANDS, PLACEHOLDERS;
905
+ var init_adapter_spec = __esm(() => {
906
+ init_paths();
907
+ ADAPTER_COMMANDS = ["inventory", "extract", "gate"];
908
+ PLACEHOLDERS = ["legacyRoot", "unit", "unitDir", "specPath"];
485
909
  });
486
910
 
487
911
  // src/plugins/manifest.ts
488
912
  import { existsSync as existsSync2 } from "fs";
489
913
  import { readFile } from "fs/promises";
490
- import { isAbsolute, join as join3 } from "path";
914
+ import { join as join3 } from "path";
491
915
  function stringList(value, field) {
492
916
  if (value === undefined)
493
917
  return [];
@@ -498,11 +922,8 @@ function stringList(value, field) {
498
922
  }
499
923
  function relativePathList(value, field) {
500
924
  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
- }
925
+ for (const p of list)
926
+ assertInsidePlugin(p, field);
506
927
  return list;
507
928
  }
508
929
  function validateManifest(raw, packageVersion) {
@@ -513,8 +934,11 @@ function validateManifest(raw, packageVersion) {
513
934
  throw new Error("Plugin manifest: name is required");
514
935
  if (!NAME.test(m.name))
515
936
  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)}`);
937
+ if (typeof m.harenApi !== "string" || !HAREN_APIS.includes(m.harenApi)) {
938
+ throw new Error(`Plugin manifest: this haren supports harenApi ${HAREN_APIS.map((v) => `"${v}"`).join(" or ")}, got ${JSON.stringify(m.harenApi)}`);
939
+ }
940
+ if (m.adapter !== undefined && m.harenApi !== "2") {
941
+ throw new Error('Plugin manifest: adapter needs harenApi "2"');
518
942
  }
519
943
  let version;
520
944
  if (packageVersion !== undefined) {
@@ -565,14 +989,15 @@ function validateManifest(raw, packageVersion) {
565
989
  return {
566
990
  name: m.name,
567
991
  version,
568
- harenApi: HAREN_API,
992
+ harenApi: m.harenApi,
569
993
  description: typeof m.description === "string" ? m.description : undefined,
570
994
  requires,
571
995
  setup: stringList(m.setup, "setup"),
572
996
  hooks,
573
997
  config,
574
998
  skills: relativePathList(m.skills, "skills"),
575
- agents: relativePathList(m.agents, "agents")
999
+ agents: relativePathList(m.agents, "agents"),
1000
+ ...m.adapter !== undefined ? { adapter: validateAdapter(m.adapter) } : {}
576
1001
  };
577
1002
  }
578
1003
  async function readInstalledManifest(dir) {
@@ -589,8 +1014,11 @@ async function readInstalledManifest(dir) {
589
1014
  }
590
1015
  return validateManifest(raw, packageVersion);
591
1016
  }
592
- var HAREN_API = "1", HOOK_NAMES, NAME;
1017
+ var HAREN_APIS, HOOK_NAMES, NAME;
593
1018
  var init_manifest2 = __esm(() => {
1019
+ init_adapter_spec();
1020
+ init_paths();
1021
+ HAREN_APIS = ["1", "2"];
594
1022
  HOOK_NAMES = ["session-start", "after-plan", "on-task-status"];
595
1023
  NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
596
1024
  });
@@ -612,7 +1040,12 @@ async function readPlugins(harenDir) {
612
1040
  const path = pluginsPath(harenDir);
613
1041
  if (!existsSync3(path))
614
1042
  return { version: 1, plugins: {} };
615
- const data = JSON.parse(await readFile2(path, "utf-8"));
1043
+ let data;
1044
+ try {
1045
+ data = JSON.parse(await readFile2(path, "utf-8"));
1046
+ } catch (e) {
1047
+ throw new Error(`plugins.json is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
1048
+ }
616
1049
  return { version: 1, plugins: data.plugins ?? {} };
617
1050
  }
618
1051
  async function writePlugins(harenDir, data) {
@@ -703,7 +1136,7 @@ function mergeClaudeSettings(existing, command) {
703
1136
  data.hooks ??= {};
704
1137
  data.hooks.PreToolUse = [
705
1138
  ...withoutGate(data.hooks.PreToolUse),
706
- { matcher: "Edit|Write", hooks: [{ type: "command", command }] }
1139
+ { matcher: "Edit|Write|Bash", hooks: [{ type: "command", command }] }
707
1140
  ];
708
1141
  return `${JSON.stringify(data, null, 2)}
709
1142
  `;
@@ -716,6 +1149,10 @@ function mergeCursorHooks(existing, command) {
716
1149
  ...withoutGate(data.hooks.beforeFileEdit),
717
1150
  { command, type: "command", timeout: 10 }
718
1151
  ];
1152
+ data.hooks.beforeShellExecution = [
1153
+ ...withoutGate(data.hooks.beforeShellExecution),
1154
+ { command, type: "command", timeout: 10 }
1155
+ ];
719
1156
  data.hooks.preToolUse = [
720
1157
  ...withoutGate(data.hooks.preToolUse),
721
1158
  { command, matcher: "write", type: "command", timeout: 10 }
@@ -1270,6 +1707,10 @@ async function readProgress(path) {
1270
1707
  mod.features = {};
1271
1708
  if (!isObject(mod.lastCommit))
1272
1709
  mod.lastCommit = {};
1710
+ if (!isObject(mod.units))
1711
+ mod.units = {};
1712
+ for (const [unit, status] of Object.entries(mod.units))
1713
+ assertUnitStatus(unit, status);
1273
1714
  }
1274
1715
  return progress;
1275
1716
  }
@@ -1329,27 +1770,84 @@ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1329
1770
  }
1330
1771
  };
1331
1772
  }
1773
+ function assertUnitStatus(unit, status) {
1774
+ if (!UNIT_STATUSES.includes(status)) {
1775
+ throw new Error(`Unknown unit status '${String(status)}' for unit '${unit}'`);
1776
+ }
1777
+ }
1778
+ function unitRank(s) {
1779
+ if (s === "static-review-only")
1780
+ return UNIT_LINE.indexOf("built");
1781
+ if (s === "blocked")
1782
+ return -1;
1783
+ return UNIT_LINE.indexOf(s);
1784
+ }
1785
+ function unitAtLeast(status, floor) {
1786
+ return unitRank(status) >= unitRank(floor);
1787
+ }
1788
+ function unitsBelow(mod, floor) {
1789
+ return Object.entries(mod.units ?? {}).filter(([, s]) => !unitAtLeast(s, floor)).map(([u]) => u);
1790
+ }
1791
+ function updateUnitStatus(progress, moduleName, unit, to) {
1792
+ const mod = progress.modules[moduleName];
1793
+ if (!mod)
1794
+ throw new Error(`Module '${moduleName}' not found`);
1795
+ const units = mod.units ?? {};
1796
+ const from = units[unit];
1797
+ if (from !== undefined)
1798
+ assertUnitStatus(unit, from);
1799
+ if (from === undefined) {
1800
+ if (to !== "inventoried") {
1801
+ throw new Error(`A new unit can start only at 'inventoried' (got '${to}')`);
1802
+ }
1803
+ } else if (!VALID_UNIT_TRANSITIONS[from].includes(to)) {
1804
+ throw new Error(`Invalid unit transition: ${from} \u2192 ${to}. Allowed: ${VALID_UNIT_TRANSITIONS[from].join(", ")}`);
1805
+ }
1806
+ return {
1807
+ ...progress,
1808
+ modules: {
1809
+ ...progress.modules,
1810
+ [moduleName]: {
1811
+ ...mod,
1812
+ units: { ...units, [unit]: to },
1813
+ lastUpdated: new Date().toISOString()
1814
+ }
1815
+ }
1816
+ };
1817
+ }
1332
1818
  function migrateProgress(raw, repoKeyFor) {
1333
1819
  if (!raw || typeof raw !== "object")
1334
1820
  return { progress: raw, changed: false };
1335
1821
  const data = raw;
1336
- if ((data.version ?? 1) >= PROGRESS_VERSION)
1822
+ const version = data.version ?? 1;
1823
+ if (version >= PROGRESS_VERSION)
1337
1824
  return { progress: raw, changed: false };
1338
1825
  const modules = {};
1339
1826
  for (const [name, mod] of Object.entries(data.modules ?? {})) {
1340
1827
  const old = mod?.lastCommit;
1341
1828
  let lastCommit = {};
1342
- if (typeof old === "string" && old)
1829
+ if (version < 2 && typeof old === "string" && old) {
1343
1830
  lastCommit = { [repoKeyFor(name) || "default"]: old };
1344
- else if (old && typeof old === "object" && !Array.isArray(old) && Object.values(old).every((v) => typeof v === "string")) {
1831
+ } else if (isObject(old) && Object.values(old).every((v) => typeof v === "string")) {
1345
1832
  lastCommit = old;
1346
1833
  }
1347
- modules[name] = { ...mod, lastCommit };
1834
+ const units = isObject(mod?.units) ? mod.units : {};
1835
+ modules[name] = { ...isObject(mod) ? mod : {}, lastCommit, units };
1348
1836
  }
1349
1837
  return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
1350
1838
  }
1351
- var MODULE_STATUSES, FEATURE_STATUSES, VALID_MODULE_TRANSITIONS, STATUS_TO_PHASE, VALID_FEATURE_TRANSITIONS, PROGRESS_VERSION = 2;
1839
+ var UNIT_LINE, UNIT_STATUSES, MODULE_STATUSES, FEATURE_STATUSES, VALID_MODULE_TRANSITIONS, STATUS_TO_PHASE, VALID_FEATURE_TRANSITIONS, VALID_UNIT_TRANSITIONS, PROGRESS_VERSION = 3;
1352
1840
  var init_progress = __esm(() => {
1841
+ UNIT_LINE = [
1842
+ "inventoried",
1843
+ "extracted",
1844
+ "spec-draft",
1845
+ "spec-approved",
1846
+ "built",
1847
+ "verified",
1848
+ "parity-signed"
1849
+ ];
1850
+ UNIT_STATUSES = [...UNIT_LINE, "blocked", "static-review-only"];
1353
1851
  MODULE_STATUSES = [
1354
1852
  "discovered",
1355
1853
  "decomposed",
@@ -1396,6 +1894,25 @@ var init_progress = __esm(() => {
1396
1894
  passing: [],
1397
1895
  blocked: ["in-progress"]
1398
1896
  };
1897
+ VALID_UNIT_TRANSITIONS = {
1898
+ inventoried: ["extracted", "blocked"],
1899
+ extracted: ["spec-draft", "blocked"],
1900
+ "spec-draft": ["spec-approved", "extracted", "blocked"],
1901
+ "spec-approved": ["built", "spec-draft", "blocked"],
1902
+ built: ["verified", "static-review-only", "blocked"],
1903
+ "static-review-only": ["verified", "built", "blocked"],
1904
+ verified: ["parity-signed", "built", "blocked"],
1905
+ "parity-signed": ["built"],
1906
+ blocked: [
1907
+ "inventoried",
1908
+ "extracted",
1909
+ "spec-draft",
1910
+ "spec-approved",
1911
+ "built",
1912
+ "static-review-only",
1913
+ "verified"
1914
+ ]
1915
+ };
1399
1916
  });
1400
1917
 
1401
1918
  // src/lib/version.ts
@@ -1583,7 +2100,7 @@ async function installPlugin(ref, ctx) {
1583
2100
  if (!official) {
1584
2101
  ctx.io.log("This plugin is not in the haren registry. Its hooks run as code with your user permissions.");
1585
2102
  if (!await ctx.io.confirm("Install it?"))
1586
- throw new Error("Plugin install cancelled");
2103
+ throw new Error(INSTALL_CANCELLED);
1587
2104
  }
1588
2105
  const manifest = await stage(source, ctx);
1589
2106
  try {
@@ -1660,7 +2177,7 @@ async function restorePlugins(ctx, report) {
1660
2177
  restored.push(manifest.name);
1661
2178
  } catch (err) {
1662
2179
  const message = err.message;
1663
- if (message === "Plugin install cancelled") {
2180
+ if (message === INSTALL_CANCELLED) {
1664
2181
  report.warn(`plugin ${name}: skipped, not confirmed. Run again with --yes to install it.`);
1665
2182
  } else {
1666
2183
  report.error(`plugin ${name}: ${message}`);
@@ -1692,7 +2209,7 @@ async function refreshPlugins(ctx, skip = []) {
1692
2209
  await writePlugins(ctx.harenDir, state);
1693
2210
  return warnings;
1694
2211
  }
1695
- var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming");
2212
+ var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming"), INSTALL_CANCELLED = "Plugin install cancelled";
1696
2213
  var init_install = __esm(() => {
1697
2214
  init_registry();
1698
2215
  init_source();
@@ -1718,7 +2235,7 @@ function readLine() {
1718
2235
  stdin.on("data", onData);
1719
2236
  });
1720
2237
  }
1721
- async function prompt(question, defaultValue) {
2238
+ async function prompt2(question, defaultValue) {
1722
2239
  const suffix = defaultValue ? ` \x1B[2m(${defaultValue})\x1B[0m` : "";
1723
2240
  process.stdout.write(` \x1B[36m?\x1B[0m ${question}${suffix} `);
1724
2241
  const value = await readLine();
@@ -1850,6 +2367,8 @@ function getDirectories(iterations) {
1850
2367
  "skills/update-links",
1851
2368
  "skills/update-tracking",
1852
2369
  "skills/generate-mockup",
2370
+ "skills/visual-companion",
2371
+ "skills/ui-review",
1853
2372
  "skills/onboard",
1854
2373
  "artifacts/_registry",
1855
2374
  "artifacts/00-baseline",
@@ -1925,6 +2444,7 @@ Master registry of all artifacts in this Haren workspace.
1925
2444
  await writeFile5(gitignore, `.agent.json
1926
2445
  .agent.pid
1927
2446
  .plugins/
2447
+ .companion/
1928
2448
  `);
1929
2449
  await writeGateScript(targetDir);
1930
2450
  await scaffoldSkillMd(targetDir);
@@ -1954,6 +2474,7 @@ You are operating within the Haren agentic SDLC framework.
1954
2474
  1. Read \`manifest.yaml\` to understand the project
1955
2475
  2. Read \`progress.json\` to understand current state
1956
2476
  3. Read \`artifacts/_registry/artifact-index.md\` for artifact inventory
2477
+ - 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
2478
  4. **Scan \`artifacts/00-baseline/\`** for documents (PDFs, docs, markdown, etc.)
1958
2479
  - If docs found and mode is \`undecided\` \u2192 auto-recommend \`blueprint\` mode
1959
2480
  - If docs found and discovery hasn't started \u2192 suggest starting discover phase
@@ -1966,8 +2487,11 @@ You are operating within the Haren agentic SDLC framework.
1966
2487
  - Has docs/specs \u2192 tell them to drop docs in \`artifacts/00-baseline/\` then \`blueprint\`
1967
2488
  - Starting from scratch, just an idea \u2192 \`explore\`
1968
2489
  - Has existing code \u2192 \`inherit\`
2490
+ - Rewrite of a legacy system with parity as the bar \u2192 \`migration\`
1969
2491
  6. Suggest next action based on current state
1970
2492
 
2493
+ Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | ascii | browser). See the visual-companion skill.
2494
+
1971
2495
  ## Available Actions
1972
2496
 
1973
2497
  | Intent | Skill | Agent |
@@ -1975,6 +2499,7 @@ You are operating within the Haren agentic SDLC framework.
1975
2499
  | Design a feature | discover/ (brainstorming) | Researcher |
1976
2500
  | Start a new project | discover/ | Researcher |
1977
2501
  | Research a topic | research/ | Researcher |
2502
+ | Extract legacy units into specs (migration) | extract/ | Researcher |
1978
2503
  | Break into modules | decompose/ | Architect |
1979
2504
  | Extract stories from docs | extract-stories/ | Researcher |
1980
2505
  | Plan a module | plan/ | Planner |
@@ -1984,6 +2509,8 @@ You are operating within the Haren agentic SDLC framework.
1984
2509
  | Search artifacts | search-artifact/ | \u2014 |
1985
2510
  | Release completed modules | release/ | Architect |
1986
2511
  | Draw a UI wireframe or compare screen options | generate-mockup/ | \u2014 |
2512
+ | Show mockups or options in a browser tab | visual-companion/ (\`haren companion\`) | \u2014 |
2513
+ | Review a screen against UX heuristics | ui-review/ | \u2014 |
1987
2514
  | Update status, artifacts, events | update-tracking/ (\`haren track\`) | \u2014 |
1988
2515
  | Onboard to the project / check the workspace | onboard/ (\`/haren-onboard\`) | \u2014 |
1989
2516
 
@@ -1991,6 +2518,7 @@ You are operating within the Haren agentic SDLC framework.
1991
2518
 
1992
2519
  - User says "let's build X" or describes a new feature \u2192 discover/ skill (triggers brainstorming)
1993
2520
  - User says "what's next?" \u2192 read \`progress.json\` \u2192 suggest action
2521
+ - User says "extract <unit>" or "spec the legacy screen" (migration mode) \u2192 extract/ skill
1994
2522
  - User says "extract stories" or "break down the PRD" or "create stories from docs" \u2192 extract-stories/ skill
1995
2523
  - User says "let's work on {module}" \u2192 check module phase \u2192 dispatch appropriate skill
1996
2524
  - User says "I need to research X" \u2192 research/ skill
@@ -2057,7 +2585,7 @@ When a skill says "read the master plan" or needs full module context, it means
2057
2585
 
2058
2586
  ### Dependent modules
2059
2587
 
2060
- The decompose skill records module dependencies in \`progress.json\` \`dependencies\` (for example \`"web": ["api"]\`). If module B depends on module A:
2588
+ 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
2589
 
2062
2590
  - **A is merged:** create \`feat/<B>\` from the default branch as usual.
2063
2591
  - **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 +2640,7 @@ function parseInitArgs(args) {
2112
2640
  break;
2113
2641
  case "--mode":
2114
2642
  if (!MODES.includes(value)) {
2115
- throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, or undecided.`);
2643
+ throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, migration, or undecided.`);
2116
2644
  }
2117
2645
  out.mode = value;
2118
2646
  i++;
@@ -2260,10 +2788,10 @@ async function promptIterations() {
2260
2788
  }, "no");
2261
2789
  if (enable !== "yes")
2262
2790
  return;
2263
- const duration = await prompt("Iteration duration:", "2 weeks");
2791
+ const duration = await prompt2("Iteration duration:", "2 weeks");
2264
2792
  const today = new Date().toISOString().split("T")[0];
2265
- const startDate = await prompt("Start date:", today);
2266
- const demoDay = await prompt("Demo day:", "Friday");
2793
+ const startDate = await prompt2("Start date:", today);
2794
+ const demoDay = await prompt2("Demo day:", "Friday");
2267
2795
  return { enabled: true, duration, startDate, demoDay };
2268
2796
  }
2269
2797
  async function runSetup(location, opts) {
@@ -2389,15 +2917,15 @@ async function init(args) {
2389
2917
  }, "workspace") : "workspace");
2390
2918
  console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
2391
2919
  console.log("");
2392
- const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt("haren folder name:", "haren") : "haren");
2920
+ const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt2("haren folder name:", "haren") : "haren");
2393
2921
  const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join10(rootDir, harenDirName);
2394
2922
  const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
2395
2923
  const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
2396
2924
  let selected = defaults;
2397
- const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt("Project name:", basename4(rootDir)) : basename4(rootDir));
2925
+ const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt2("Project name:", basename4(rootDir)) : basename4(rootDir));
2398
2926
  const existingMode = MODES.find((m) => m === existingManifest?.mode);
2399
2927
  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");
2928
+ const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt2("Preferred language:", "English") : "English");
2401
2929
  const iterations = opts.iterations ?? (existingManifest ? manifestIterations(existingManifest) : interactive ? await promptIterations() : undefined);
2402
2930
  const editor = opts.editor ?? (existingLoc ? detectEditor(existingLoc.workspaceDir) ?? "claude-code" : undefined) ?? (interactive ? await promptSelect("Which editors do you use?", EDITORS, EDITOR_DESCRIPTIONS, "claude-code") : "claude-code");
2403
2931
  while (true) {
@@ -2470,7 +2998,7 @@ var init_init = __esm(() => {
2470
2998
  init_version();
2471
2999
  init_install();
2472
3000
  init_registry();
2473
- MODES = ["blueprint", "explore", "inherit", "undecided"];
3001
+ MODES = ["blueprint", "explore", "inherit", "migration", "undecided"];
2474
3002
  EDITORS = ["claude-code", "cursor", "both"];
2475
3003
  EDITOR_DESCRIPTIONS = {
2476
3004
  "claude-code": "Claude Code CLI / IDE extension",
@@ -2481,6 +3009,7 @@ var init_init = __esm(() => {
2481
3009
  blueprint: "Greenfield project with existing docs",
2482
3010
  explore: "Greenfield project from scratch",
2483
3011
  inherit: "Brownfield project with existing code",
3012
+ migration: "Rewrite of a legacy system with parity as the bar",
2484
3013
  undecided: "Decide later \u2014 LLM will help you choose"
2485
3014
  };
2486
3015
  });
@@ -2549,7 +3078,7 @@ async function planMigration(location) {
2549
3078
  if (result.changed) {
2550
3079
  progress = { before, after: `${JSON.stringify(result.progress, null, 2)}
2551
3080
  ` };
2552
- steps.push("progress.json: migrate to version 2 (lastCommit per repo)");
3081
+ steps.push(raw.version === 2 ? "progress.json: migrate to version 3 (units)" : "progress.json: migrate to version 3 (lastCommit per repo, units)");
2553
3082
  }
2554
3083
  }
2555
3084
  const gitignore = await planGitignore(harenDir);
@@ -2717,7 +3246,7 @@ var init_upgrade = __esm(() => {
2717
3246
  init_root_files();
2718
3247
  init_install();
2719
3248
  init_templates();
2720
- IGNORED = [".agent.json", ".agent.pid", ".plugins/"];
3249
+ IGNORED = [".agent.json", ".agent.pid", ".plugins/", ".companion/"];
2721
3250
  FRAMEWORK_DIRS = ["agents", "skills", "templates"];
2722
3251
  USER_FILES = ["FEEDBACK.md", "artifacts/", "events/"];
2723
3252
  });
@@ -2818,8 +3347,8 @@ var init_artifact_reader = __esm(() => {
2818
3347
  });
2819
3348
 
2820
3349
  // src/agent/cli-executor.ts
2821
- async function executeCLI(cli, prompt, onOutput) {
2822
- const args = buildCLIArgs(cli, prompt);
3350
+ async function executeCLI(cli, prompt2, onOutput) {
3351
+ const args = buildCLIArgs(cli, prompt2);
2823
3352
  try {
2824
3353
  const proc = Bun.spawn(args, {
2825
3354
  stdout: "pipe",
@@ -2851,16 +3380,16 @@ async function executeCLI(cli, prompt, onOutput) {
2851
3380
  onOutput("", true);
2852
3381
  }
2853
3382
  }
2854
- function buildCLIArgs(cli, prompt) {
3383
+ function buildCLIArgs(cli, prompt2) {
2855
3384
  switch (cli) {
2856
3385
  case "claude":
2857
- return ["claude", "--print", prompt];
3386
+ return ["claude", "--print", prompt2];
2858
3387
  case "cursor":
2859
- return ["cursor", "--prompt", prompt];
3388
+ return ["cursor", "--prompt", prompt2];
2860
3389
  case "github-copilot-cli":
2861
- return ["github-copilot-cli", prompt];
3390
+ return ["github-copilot-cli", prompt2];
2862
3391
  default:
2863
- return [cli, prompt];
3392
+ return [cli, prompt2];
2864
3393
  }
2865
3394
  }
2866
3395
 
@@ -2924,7 +3453,7 @@ async function handleDataRequest(requestId, path, harenDir, send) {
2924
3453
  }
2925
3454
  send({ type: "data-response", requestId, data });
2926
3455
  }
2927
- async function handleCommand(commandId, prompt, cli, config, send) {
3456
+ async function handleCommand(commandId, prompt2, cli, config, send) {
2928
3457
  const { mkdir } = await import("fs/promises");
2929
3458
  await mkdir(`${config.harenDir}/events`, { recursive: true });
2930
3459
  await Promise.resolve().then(() => init_events());
@@ -2933,10 +3462,10 @@ async function handleCommand(commandId, prompt, cli, config, send) {
2933
3462
  type: "agent-command",
2934
3463
  timestamp: new Date().toISOString(),
2935
3464
  cli,
2936
- prompt,
3465
+ prompt: prompt2,
2937
3466
  commandId
2938
3467
  });
2939
- await executeCLI(cli, prompt, (chunk, done) => {
3468
+ await executeCLI(cli, prompt2, (chunk, done) => {
2940
3469
  send({ type: "command-output", commandId, chunk, done });
2941
3470
  });
2942
3471
  }
@@ -3685,7 +4214,8 @@ async function plugin(args) {
3685
4214
  try {
3686
4215
  await installPlugin(opts.target, ctx);
3687
4216
  } catch (err) {
3688
- console.error(` ${err.message}`);
4217
+ const message = err.message;
4218
+ 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
4219
  process.exit(1);
3690
4220
  }
3691
4221
  await syncEditors();
@@ -3750,10 +4280,34 @@ var init_plugin = __esm(() => {
3750
4280
  SUBS = ["add", "remove", "list", "run", "doctor"];
3751
4281
  });
3752
4282
 
3753
- // src/commands/track.ts
4283
+ // src/plugins/adapter-read.ts
3754
4284
  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";
4285
+ import { join as join18 } from "path";
4286
+ function adapterMissingMessage(name) {
4287
+ return `Adapter '${name}' is named in manifest.yaml but not installed. Run \`haren plugin add <source>\`, or remove migration.adapter to work by hand.`;
4288
+ }
4289
+ async function readAdapter(harenDir, name) {
4290
+ const { plugins } = await readPlugins(harenDir);
4291
+ if (!plugins[name])
4292
+ return null;
4293
+ const dir = pluginDir(harenDir, name);
4294
+ if (!existsSync15(join18(dir, "haren-plugin.json")))
4295
+ return null;
4296
+ try {
4297
+ return (await readInstalledManifest(dir)).adapter ?? null;
4298
+ } catch (e) {
4299
+ throw new Error(`Adapter plugin '${name}': ${e instanceof Error ? e.message : String(e)}`);
4300
+ }
4301
+ }
4302
+ var init_adapter_read = __esm(() => {
4303
+ init_manifest2();
4304
+ init_state();
4305
+ });
4306
+
4307
+ // src/commands/track.ts
4308
+ import { existsSync as existsSync16 } from "fs";
4309
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
4310
+ import { dirname as dirname5, join as join19, relative as relative4, sep as sep4 } from "path";
3757
4311
  function parseTrackArgs(args) {
3758
4312
  const positional = [];
3759
4313
  const flags = {};
@@ -3777,9 +4331,9 @@ function parseTrackArgs(args) {
3777
4331
  function pathsFor(harenDir) {
3778
4332
  return {
3779
4333
  harenDir,
3780
- progress: join18(harenDir, "progress.json"),
3781
- events: join18(harenDir, "events", "events.jsonl"),
3782
- registry: join18(harenDir, "artifacts", "_registry", "artifact-index.md")
4334
+ progress: join19(harenDir, "progress.json"),
4335
+ events: join19(harenDir, "events", "events.jsonl"),
4336
+ registry: join19(harenDir, "artifacts", "_registry", "artifact-index.md")
3783
4337
  };
3784
4338
  }
3785
4339
  async function emit(paths, event) {
@@ -3799,7 +4353,7 @@ function requireModule(progress, name) {
3799
4353
  }
3800
4354
  }
3801
4355
  async function loadProgress(paths) {
3802
- if (!existsSync15(paths.progress))
4356
+ if (!existsSync16(paths.progress))
3803
4357
  throw new Error(`No progress.json in ${paths.harenDir}`);
3804
4358
  return readProgress(paths.progress);
3805
4359
  }
@@ -3819,29 +4373,127 @@ async function track(args, cwd = process.cwd()) {
3819
4373
  const paths = pathsFor(location.harenDir);
3820
4374
  switch (sub) {
3821
4375
  case "status":
3822
- return trackStatus(paths, rest);
4376
+ return trackStatus(paths, rest, flags);
3823
4377
  case "feature":
3824
4378
  return trackFeature(paths, rest);
4379
+ case "unit":
4380
+ return trackUnit(paths, rest);
3825
4381
  case "commit":
3826
4382
  return trackCommit(paths, rest);
4383
+ case "depends":
4384
+ return trackDepends(paths, rest);
3827
4385
  case "artifact":
3828
4386
  return trackArtifact(paths, rest, flags);
3829
4387
  case "event":
3830
4388
  return trackEvent(paths, rest, flags);
3831
4389
  case "override":
3832
4390
  return trackOverride(paths, rest, flags);
4391
+ case "ui-mode":
4392
+ return trackUiMode(paths, rest);
4393
+ case "check":
4394
+ return trackCheck(paths);
3833
4395
  default:
3834
4396
  throw new Error(`Unknown track command: ${sub}
3835
4397
  ${TRACK_USAGE}`);
3836
4398
  }
3837
4399
  }
3838
- async function trackStatus(paths, rest) {
4400
+ async function trackUiMode(paths, rest) {
4401
+ const mode = need(rest[0], "ui mode");
4402
+ if (!UI_MODES.includes(mode)) {
4403
+ throw new Error(`Invalid ui mode '${mode}'. Use ${UI_MODES.join(", ")}.`);
4404
+ }
4405
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4406
+ if (!existsSync16(manifestPath))
4407
+ throw new Error(`No manifest.yaml in ${paths.harenDir}`);
4408
+ const text = await readFile13(manifestPath, "utf-8");
4409
+ await writeFile7(manifestPath, setUiModeText(text, mode));
4410
+ await emit(paths, { type: "ui-mode", mode });
4411
+ console.log(` UI mockups mode: ${mode}.`);
4412
+ }
4413
+ async function loadMigration(paths) {
4414
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4415
+ if (!existsSync16(manifestPath))
4416
+ return null;
4417
+ return readMigrationConfig(parseManifest(await readFile13(manifestPath, "utf-8")));
4418
+ }
4419
+ async function adapterCommands(paths, migration) {
4420
+ if (!migration.adapter)
4421
+ return new Set;
4422
+ const adapter = await readAdapter(paths.harenDir, migration.adapter);
4423
+ if (!adapter)
4424
+ return null;
4425
+ return new Set(Object.keys(adapter.commands));
4426
+ }
4427
+ async function trackUnit(paths, rest) {
4428
+ const module = need(rest[0], "<module>");
4429
+ const unit = need(rest[1], "<unit>");
4430
+ const to = need(rest[2], "<status>");
4431
+ const migration = await loadMigration(paths);
4432
+ if (!migration)
4433
+ throw new Error("track unit needs mode: migration in manifest.yaml");
4434
+ if (!UNIT_STATUSES.includes(to)) {
4435
+ throw new Error(`Invalid unit status '${to}'. Allowed: ${UNIT_STATUSES.join(", ")}`);
4436
+ }
4437
+ if (!migration.unitId.test(unit)) {
4438
+ throw new Error(`Unit '${unit}' does not match migration.unitId`);
4439
+ }
4440
+ const commands = await adapterCommands(paths, migration);
4441
+ if (!commands) {
4442
+ if (to === "extracted" || to === "spec-approved") {
4443
+ throw new Error(adapterMissingMessage(migration.adapter));
4444
+ }
4445
+ } else if (to === "extracted" && commands.has("extract") || to === "spec-approved" && commands.has("gate")) {
4446
+ throw new Error("Use haren migrate extract|gate; the adapter owns this step");
4447
+ }
4448
+ const progress = await loadProgress(paths);
4449
+ requireModule(progress, module);
4450
+ const from = progress.modules[module].units?.[unit] ?? null;
4451
+ const next = updateUnitStatus(progress, module, unit, to);
4452
+ await writeProgress(paths.progress, next);
4453
+ await emit(paths, { type: "unit-status", module, unit, from, to });
4454
+ console.log(` ${module}/${unit}: ${from ?? "(new)"} \u2192 ${to}`);
4455
+ }
4456
+ async function moduleMeta(paths, flags) {
4457
+ const meta = {};
4458
+ if (flags.branch !== undefined)
4459
+ meta.branch = need(flags.branch, "--branch <name>");
4460
+ if (flags.repos !== undefined) {
4461
+ const repos = [
4462
+ ...new Set(flags.repos.split(",").map((r) => r.trim()).filter(Boolean))
4463
+ ];
4464
+ if (!repos.length)
4465
+ throw new Error(`Missing --repos <key1,key2>.
4466
+ ${TRACK_USAGE}`);
4467
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4468
+ const manifest = existsSync16(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4469
+ const declared = Object.keys(normalizeRepos(manifest.repos));
4470
+ const unknown = repos.filter((r) => !declared.includes(r));
4471
+ if (unknown.length) {
4472
+ throw new Error(`Unknown repo key: ${unknown.join(", ")}. manifest.yaml repos: ${declared.length ? declared.join(", ") : "(none)"}`);
4473
+ }
4474
+ meta.repos = repos;
4475
+ }
4476
+ return meta;
4477
+ }
4478
+ async function trackStatus(paths, rest, flags) {
3839
4479
  const module = need(rest[0], "<module>");
3840
4480
  const to = need(rest[1], "<status>");
3841
4481
  if (!MODULE_STATUSES.includes(to)) {
3842
4482
  throw new Error(`Invalid module status '${to}'. Allowed: ${MODULE_STATUSES.join(", ")}`);
3843
4483
  }
3844
4484
  const progress = await loadProgress(paths);
4485
+ const meta = await moduleMeta(paths, flags);
4486
+ const metaOnly = progress.modules[module]?.status === to && Object.keys(meta).length > 0;
4487
+ const migration = await loadMigration(paths);
4488
+ if (migration && progress.modules[module] && !metaOnly) {
4489
+ const floor = to === "planned" ? "spec-approved" : to === "completed" ? "parity-signed" : null;
4490
+ if (floor) {
4491
+ const below = unitsBelow(progress.modules[module], floor);
4492
+ if (below.length) {
4493
+ throw new Error(`Module '${module}' cannot be '${to}': units below '${floor}': ${below.join(", ")}`);
4494
+ }
4495
+ }
4496
+ }
3845
4497
  let next;
3846
4498
  let from = null;
3847
4499
  if (!progress.modules[module]) {
@@ -3857,13 +4509,21 @@ async function trackStatus(paths, rest) {
3857
4509
  currentPhase: phaseForStatus(to),
3858
4510
  features: {},
3859
4511
  lastCommit: {},
4512
+ ...meta,
3860
4513
  lastUpdated: new Date().toISOString()
3861
4514
  }
3862
4515
  }
3863
4516
  };
3864
4517
  } else {
3865
4518
  from = progress.modules[module].status;
3866
- next = updateModuleStatus(progress, module, to);
4519
+ next = metaOnly ? progress : updateModuleStatus(progress, module, to);
4520
+ next = {
4521
+ ...next,
4522
+ modules: {
4523
+ ...next.modules,
4524
+ [module]: { ...next.modules[module], ...meta, lastUpdated: new Date().toISOString() }
4525
+ }
4526
+ };
3867
4527
  }
3868
4528
  await writeProgress(paths.progress, next);
3869
4529
  await emit(paths, { type: "module-status", module, from, to, phase: phaseForStatus(to) });
@@ -3930,6 +4590,42 @@ async function trackCommit(paths, rest) {
3930
4590
  await emit(paths, { type: "commit", module, repo, sha });
3931
4591
  console.log(` ${module}: lastCommit.${repo} = ${sha}`);
3932
4592
  }
4593
+ function findCycle(graph, module, deps) {
4594
+ const next = { ...graph, [module]: deps };
4595
+ const visited = new Set([module]);
4596
+ const visit = (node, path) => {
4597
+ for (const dep of next[node] ?? []) {
4598
+ if (dep === module)
4599
+ return [...path, dep];
4600
+ if (visited.has(dep))
4601
+ continue;
4602
+ visited.add(dep);
4603
+ const found = visit(dep, [...path, dep]);
4604
+ if (found)
4605
+ return found;
4606
+ }
4607
+ return null;
4608
+ };
4609
+ return visit(module, [module]);
4610
+ }
4611
+ async function trackDepends(paths, rest) {
4612
+ const module = need(rest[0], "<module>");
4613
+ const deps = [...new Set(rest.slice(1))];
4614
+ const progress = await loadProgress(paths);
4615
+ requireModule(progress, module);
4616
+ for (const dep of deps)
4617
+ requireModule(progress, dep);
4618
+ const graph = progress.dependencies ?? {};
4619
+ const cycle = findCycle(graph, module, deps);
4620
+ if (cycle)
4621
+ throw new Error(`Dependency cycle: ${cycle.join(" \u2192 ")}`);
4622
+ await writeProgress(paths.progress, {
4623
+ ...progress,
4624
+ dependencies: { ...graph, [module]: deps }
4625
+ });
4626
+ await emit(paths, { type: "dependencies", module, dependsOn: deps });
4627
+ console.log(` ${module} depends on: ${deps.length ? deps.join(", ") : "(none)"}`);
4628
+ }
3933
4629
  function upsertArtifactRow(text, cells) {
3934
4630
  const row = `| ${cells.map((c) => c.replaceAll("|", "\\|")).join(" | ")} |`;
3935
4631
  const lines = text.split(`
@@ -3969,7 +4665,7 @@ async function trackArtifact(paths, rest, flags) {
3969
4665
  const progress = await loadProgress(paths);
3970
4666
  requireModule(progress, flags.module);
3971
4667
  }
3972
- const existing = existsSync15(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
4668
+ const existing = existsSync16(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
3973
4669
  await mkdir9(dirname5(paths.registry), { recursive: true });
3974
4670
  await writeFile7(paths.registry, upsertArtifactRow(existing, [id, artifactType, module, status, path]));
3975
4671
  await emit(paths, {
@@ -4032,19 +4728,156 @@ async function trackOverride(paths, rest, flags) {
4032
4728
  throw new Error(`Unknown override action '${action}'. Use on or off.`);
4033
4729
  }
4034
4730
  }
4731
+ async function listArtifactFiles(artifactsDir) {
4732
+ if (!existsSync16(artifactsDir))
4733
+ return [];
4734
+ const out = [];
4735
+ const walk = async (dir) => {
4736
+ for (const entry of await readdir7(dir, { withFileTypes: true })) {
4737
+ if (entry.name.startsWith("."))
4738
+ continue;
4739
+ const full = join19(dir, entry.name);
4740
+ if (entry.isDirectory()) {
4741
+ if (dir === artifactsDir && UNTRACKED_DIRS.has(entry.name))
4742
+ continue;
4743
+ await walk(full);
4744
+ } else if (entry.name.endsWith(".md") && entry.name.toLowerCase() !== "readme.md") {
4745
+ out.push(full);
4746
+ }
4747
+ }
4748
+ };
4749
+ await walk(artifactsDir);
4750
+ return out;
4751
+ }
4752
+ function parseRegistryRows(text) {
4753
+ const rows = [];
4754
+ for (const raw of text.split(`
4755
+ `)) {
4756
+ const line = raw.trim();
4757
+ if (!line.startsWith("|"))
4758
+ continue;
4759
+ const cells = line.slice(1, line.endsWith("|") ? -1 : undefined).split("|").map((c) => c.trim());
4760
+ if (cells.length < 5 || cells[0] === "ID" || /^-+$/.test(cells[0]))
4761
+ continue;
4762
+ rows.push({ id: cells[0], module: cells[2], path: cells[4] });
4763
+ }
4764
+ return rows;
4765
+ }
4766
+ function normalizeArtifactPath(p) {
4767
+ return p.replace(/^\.\//, "").replace(/^artifacts\//, "").replaceAll("\\", "/");
4768
+ }
4769
+ async function checkWorkspace(paths) {
4770
+ const errors = [];
4771
+ const warnings = [];
4772
+ const progress = await loadProgress(paths);
4773
+ const manifestPath = join19(paths.harenDir, "manifest.yaml");
4774
+ const manifest = existsSync16(manifestPath) ? parseManifest(await readFile13(manifestPath, "utf-8")) : {};
4775
+ const declared = new Set(Object.keys(normalizeRepos(manifest.repos)));
4776
+ for (const [name, mod] of Object.entries(progress.modules)) {
4777
+ const used = new Set([...mod.repos ?? [], ...Object.keys(mod.lastCommit ?? {})]);
4778
+ for (const key of used) {
4779
+ if (!declared.has(key)) {
4780
+ errors.push(`module '${name}' uses repo '${key}', but manifest.yaml has no repos.${key} entry`);
4781
+ }
4782
+ }
4783
+ }
4784
+ let mig = null;
4785
+ try {
4786
+ mig = readMigrationConfig(manifest);
4787
+ } catch (e) {
4788
+ errors.push(e.message);
4789
+ }
4790
+ if (manifest.mode === "migration" && mig) {
4791
+ try {
4792
+ if (!legacyRepo(manifest)) {
4793
+ 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 }");
4794
+ }
4795
+ } catch (e) {
4796
+ errors.push(e.message);
4797
+ }
4798
+ if (mig.adapter) {
4799
+ try {
4800
+ if (!await readAdapter(paths.harenDir, mig.adapter)) {
4801
+ errors.push(adapterMissingMessage(mig.adapter));
4802
+ }
4803
+ } catch (e) {
4804
+ errors.push(e.message);
4805
+ }
4806
+ }
4807
+ for (const [name, mod] of Object.entries(progress.modules)) {
4808
+ for (const [unit, status] of Object.entries(mod.units ?? {})) {
4809
+ if (!mig.unitId.test(unit)) {
4810
+ errors.push(`module '${name}' unit '${unit}' does not match migration.unitId`);
4811
+ }
4812
+ if (mig.adapter && unitAtLeast(status, "spec-approved")) {
4813
+ const gate = join19(paths.harenDir, "artifacts", "02-discovery", "units", unit, "gate.json");
4814
+ let ok = false;
4815
+ try {
4816
+ ok = JSON.parse(await readFile13(gate, "utf-8")).pass === true;
4817
+ } catch {
4818
+ ok = false;
4819
+ }
4820
+ if (!ok) {
4821
+ errors.push(`unit '${unit}' is ${status} but artifacts/02-discovery/units/${unit}/gate.json is missing or not pass`);
4822
+ }
4823
+ }
4824
+ }
4825
+ }
4826
+ }
4827
+ const registryText = existsSync16(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
4828
+ const rows = parseRegistryRows(registryText);
4829
+ const indexed = new Set(rows.map((r) => normalizeArtifactPath(r.path)));
4830
+ const artifactsDir = join19(paths.harenDir, "artifacts");
4831
+ for (const file of await listArtifactFiles(artifactsDir)) {
4832
+ const rel = relative4(artifactsDir, file).split(sep4).join("/");
4833
+ if (!indexed.has(rel)) {
4834
+ errors.push(`artifacts/${rel} has no row in artifact-index.md (run haren track artifact)`);
4835
+ }
4836
+ }
4837
+ for (const row of rows) {
4838
+ const rel = normalizeArtifactPath(row.path);
4839
+ if (!existsSync16(join19(artifactsDir, rel))) {
4840
+ errors.push(`index row ${row.id} points to missing file artifacts/${rel}`);
4841
+ }
4842
+ }
4843
+ const modulesWithRows = new Set(rows.map((r) => r.module));
4844
+ for (const [name, mod] of Object.entries(progress.modules)) {
4845
+ if (mod.status !== "discovered" && !modulesWithRows.has(name)) {
4846
+ warnings.push(`module '${name}' (${mod.status}) has no artifact in the index`);
4847
+ }
4848
+ }
4849
+ return { errors, warnings };
4850
+ }
4851
+ async function trackCheck(paths) {
4852
+ const { errors, warnings } = await checkWorkspace(paths);
4853
+ for (const w of warnings)
4854
+ console.log(` warn: ${w}`);
4855
+ if (errors.length) {
4856
+ throw new Error(`Workspace check FAIL:
4857
+ ${errors.map((e) => ` - ${e}`).join(`
4858
+ `)}`);
4859
+ }
4860
+ console.log(" Workspace check PASS");
4861
+ }
4035
4862
  var TRACK_USAGE = `Usage:
4036
- haren track status <module> <status>
4863
+ haren track status <module> <status> [--branch <name>] [--repos <key1,key2>]
4037
4864
  haren track feature <module> <feature> [status]
4865
+ haren track unit <module> <unit> <status>
4038
4866
  haren track commit <module> <repoKey> <sha>
4867
+ haren track depends <module> [dep ...]
4039
4868
  haren track artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]
4040
4869
  haren track event <type> [--module m] [--phase p] [--feature f] [--data '<json object>']
4041
4870
  haren track override on --reason "<text>" [--hours <n>]
4042
4871
  haren track override off
4872
+ haren track ui-mode <ask|ascii|browser>
4873
+ haren track check
4043
4874
  Options: --haren-dir <path>`, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
4044
- |----|------|--------|--------|------|`;
4875
+ |----|------|--------|--------|------|`, UNTRACKED_DIRS;
4045
4876
  var init_track = __esm(() => {
4877
+ init_manifest();
4046
4878
  init_events();
4047
4879
  init_progress();
4880
+ init_adapter_read();
4048
4881
  init_resolve();
4049
4882
  VALUE_FLAGS = [
4050
4883
  "--haren-dir",
@@ -4056,11 +4889,1597 @@ var init_track = __esm(() => {
4056
4889
  "--feature",
4057
4890
  "--data",
4058
4891
  "--reason",
4059
- "--hours"
4892
+ "--hours",
4893
+ "--branch",
4894
+ "--repos"
4060
4895
  ];
4896
+ UNTRACKED_DIRS = new Set(["_registry", "00-baseline"]);
4897
+ });
4898
+
4899
+ // src/plugins/adapter-run.ts
4900
+ function buildArgv(template, values) {
4901
+ return template.trim().split(/\s+/).map((tok) => tok.replace(/\{(\w+)\}/g, (_, k) => {
4902
+ if (!Object.hasOwn(values, k))
4903
+ throw new AdapterError(`No value for placeholder {${k}}`);
4904
+ return values[k];
4905
+ }));
4906
+ }
4907
+ function spawnAdapter(command, argv, cwd) {
4908
+ try {
4909
+ return Bun.spawn(argv, { cwd, stdout: "pipe", stderr: "pipe" });
4910
+ } catch (e) {
4911
+ throw new AdapterError(`adapter ${command} could not start: ${e instanceof Error ? e.message : String(e)}`);
4912
+ }
4913
+ }
4914
+ function adapterTimeoutMs() {
4915
+ const n = Number(process.env.HAREN_ADAPTER_TIMEOUT_MS);
4916
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_ADAPTER_TIMEOUT_MS;
4917
+ }
4918
+ async function runAdapter(command, template, values, cwd) {
4919
+ const proc = spawnAdapter(command, buildArgv(template, values), cwd);
4920
+ const timeoutMs = adapterTimeoutMs();
4921
+ let timer;
4922
+ const timeout = new Promise((done) => {
4923
+ timer = setTimeout(() => {
4924
+ proc.kill("SIGKILL");
4925
+ done("timeout");
4926
+ }, timeoutMs);
4927
+ });
4928
+ const result = await Promise.race([
4929
+ Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]),
4930
+ timeout
4931
+ ]).finally(() => clearTimeout(timer));
4932
+ if (result === "timeout") {
4933
+ throw new AdapterError(`adapter ${command} timed out after ${timeoutMs / 1000}s`);
4934
+ }
4935
+ const [out, err, code] = result;
4936
+ if (code !== 0)
4937
+ throw new AdapterError(`adapter ${command} exited ${code}: ${err.trim().slice(0, 500)}`);
4938
+ let parsed;
4939
+ try {
4940
+ parsed = JSON.parse(out);
4941
+ } catch {
4942
+ throw new AdapterError(`adapter ${command} printed non-JSON output (schema)`);
4943
+ }
4944
+ if (!VALIDATORS[command](parsed)) {
4945
+ throw new AdapterError(`adapter ${command} output does not match the schema`);
4946
+ }
4947
+ return parsed;
4948
+ }
4949
+ var AdapterError, isStr = (v) => typeof v === "string" && v.length > 0, optStr = (v) => v === undefined || typeof v === "string", VALIDATORS, DEFAULT_ADAPTER_TIMEOUT_MS = 300000;
4950
+ var init_adapter_run = __esm(() => {
4951
+ AdapterError = class AdapterError extends Error {
4952
+ name = "AdapterError";
4953
+ };
4954
+ VALIDATORS = {
4955
+ 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)),
4956
+ extract: (o) => isStr(o?.unit) && Array.isArray(o.files) && o.files.every(isStr),
4957
+ 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))
4958
+ };
4959
+ });
4960
+
4961
+ // src/commands/migrate.ts
4962
+ import { existsSync as existsSync17 } from "fs";
4963
+ import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile8 } from "fs/promises";
4964
+ import { dirname as dirname6, join as join20, resolve as resolve11 } from "path";
4965
+ function parseMigrateArgs(args) {
4966
+ const positional = [];
4967
+ const flags = {};
4968
+ for (let i = 0;i < args.length; i++) {
4969
+ const arg = args[i];
4970
+ if (arg === "--approve")
4971
+ flags.approve = true;
4972
+ else if (arg === "--module" || arg === "--haren-dir") {
4973
+ const value = args[++i];
4974
+ if (value === undefined)
4975
+ throw new Error(`${arg} needs a value`);
4976
+ flags[arg.slice(2)] = value;
4977
+ } else if (arg.startsWith("--haren-dir="))
4978
+ flags["haren-dir"] = arg.split("=", 2)[1];
4979
+ else if (arg.startsWith("--module="))
4980
+ flags.module = arg.split("=", 2)[1];
4981
+ else if (arg.startsWith("--"))
4982
+ throw new Error(`Unknown option: ${arg}`);
4983
+ else
4984
+ positional.push(arg);
4985
+ }
4986
+ return { positional, flags };
4987
+ }
4988
+ function renderUnitMap(units, moduleOf, previous = "") {
4989
+ const rows = units.map((u) => `| ${cell(u.id)} | ${cell(u.parent)} | ${cell(u.family)} | ${cell(u.title)} | ${cell(moduleOf[u.id])} |`);
4990
+ const tail = afterUnitTable(previous);
4991
+ return `# Unit Map
4992
+
4993
+ ${UNIT_MAP_HEADER}
4994
+ ${rows.join(`
4995
+ `)}
4996
+ ${tail ? `
4997
+ ${tail}
4998
+ ` : ""}`;
4999
+ }
5000
+ function afterUnitTable(text) {
5001
+ const lines = text.split(`
5002
+ `);
5003
+ const start = lines.findIndex((l) => /^\|\s*Unit\s*\|/.test(l.trim()));
5004
+ if (start < 0)
5005
+ return "";
5006
+ let end = start;
5007
+ while (end < lines.length && lines[end].trim().startsWith("|"))
5008
+ end++;
5009
+ return lines.slice(end).join(`
5010
+ `).trim();
5011
+ }
5012
+ function parseUnitMap(text) {
5013
+ const rows = new Map;
5014
+ for (const line of text.split(`
5015
+ `)) {
5016
+ const t = line.trim();
5017
+ if (!t.startsWith("|"))
5018
+ continue;
5019
+ const c = t.slice(1, -1).split(/(?<!\\)\|/).map((s) => s.trim().replaceAll("\\|", "|"));
5020
+ if (c.length < 5 || c[0] === "Unit" || /^-+$/.test(c[0]))
5021
+ continue;
5022
+ const v = (s) => s === "-" ? undefined : s;
5023
+ rows.set(c[0], {
5024
+ unit: { id: c[0], parent: v(c[1]) ?? null, family: v(c[2]), title: v(c[3]) },
5025
+ module: v(c[4]) ?? ""
5026
+ });
5027
+ }
5028
+ return rows;
5029
+ }
5030
+ function moduleOfUnit(progress, unit) {
5031
+ for (const [name, mod] of Object.entries(progress.modules)) {
5032
+ if (mod.units && unit in mod.units)
5033
+ return name;
5034
+ }
5035
+ throw new Error(`Unit '${unit}' is not in progress.json. Run haren migrate inventory first.`);
5036
+ }
5037
+ function commandFor(ctx, cmd) {
5038
+ const template = ctx.adapter.commands[cmd];
5039
+ if (!template)
5040
+ throw new Error(`Adapter has no ${cmd} command. Do this step by hand (see skill extract)`);
5041
+ return template;
5042
+ }
5043
+ function checkUnitId(ctx, unit) {
5044
+ if (!unit)
5045
+ throw new Error(`Missing <unit>.
5046
+ ${MIGRATE_USAGE}`);
5047
+ if (!ctx.migration.unitId.test(unit)) {
5048
+ throw new Error(`Unit '${unit}' does not match migration.unitId`);
5049
+ }
5050
+ return unit;
5051
+ }
5052
+ async function loadContext(harenDir) {
5053
+ const paths = pathsFor(harenDir);
5054
+ const migration = await loadMigration(paths);
5055
+ if (!migration)
5056
+ throw new Error("haren migrate needs mode: migration in manifest.yaml");
5057
+ const manifest = parseManifest(await readFile14(join20(harenDir, "manifest.yaml"), "utf-8"));
5058
+ const legacy = legacyRepo(manifest);
5059
+ if (!legacy)
5060
+ throw new Error("haren migrate needs a repo with role: legacy in manifest.yaml");
5061
+ if (!migration.adapter)
5062
+ throw new Error("manifest migration.adapter is not set");
5063
+ const adapter = await readAdapter(harenDir, migration.adapter);
5064
+ if (!adapter)
5065
+ throw new Error(adapterMissingMessage(migration.adapter));
5066
+ return {
5067
+ paths,
5068
+ migration,
5069
+ adapterName: migration.adapter,
5070
+ adapter,
5071
+ legacyRoot: resolve11(harenDir, legacy[1].path)
5072
+ };
5073
+ }
5074
+ async function migrate(args, cwd = process.cwd()) {
5075
+ const { positional, flags } = parseMigrateArgs(args);
5076
+ const [sub, unitArg] = positional;
5077
+ if (!sub) {
5078
+ console.log(MIGRATE_USAGE);
5079
+ return;
5080
+ }
5081
+ if (!["inventory", "extract", "gate"].includes(sub)) {
5082
+ throw new Error(`Unknown migrate command: ${sub}
5083
+ ${MIGRATE_USAGE}`);
5084
+ }
5085
+ const location = await resolveHarenDir(cwd, { harenDir: harenDirFlag(args), env: process.env });
5086
+ if (!location)
5087
+ throw new Error("No haren folder found. Run `haren init` first.");
5088
+ const ctx = await loadContext(location.harenDir);
5089
+ if (sub === "inventory")
5090
+ return inventory(ctx, flags.module);
5091
+ const unit = checkUnitId(ctx, unitArg);
5092
+ if (sub === "extract")
5093
+ return extract(ctx, unit);
5094
+ return gate(ctx, unit, flags.approve === true);
5095
+ }
5096
+ async function inventory(ctx, moduleFlag) {
5097
+ const template = commandFor(ctx, "inventory");
5098
+ let progress = await readProgress(ctx.paths.progress);
5099
+ if (moduleFlag && !progress.modules[moduleFlag]) {
5100
+ throw new Error(`Unknown module '${moduleFlag}'`);
5101
+ }
5102
+ const raw = await runAdapter("inventory", template, { legacyRoot: ctx.legacyRoot }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5103
+ const badIds = raw.units.filter((u) => !ctx.migration.unitId.test(u.id)).map((u) => u.id);
5104
+ const out = { units: raw.units.filter((u) => ctx.migration.unitId.test(u.id)) };
5105
+ const mapRel = "artifacts/02-discovery/unit-map.md";
5106
+ const mapPath = join20(ctx.paths.harenDir, mapRel);
5107
+ const previous = existsSync17(mapPath) ? await readFile14(mapPath, "utf-8") : "";
5108
+ const known = parseUnitMap(previous);
5109
+ const moduleOf = {};
5110
+ const units = [];
5111
+ const seen = new Set;
5112
+ let fresh = 0;
5113
+ for (const u of out.units) {
5114
+ seen.add(u.id);
5115
+ units.push(u);
5116
+ const prev = known.get(u.id);
5117
+ if (prev)
5118
+ moduleOf[u.id] = prev.module;
5119
+ else {
5120
+ fresh++;
5121
+ if (moduleFlag)
5122
+ moduleOf[u.id] = moduleFlag;
5123
+ }
5124
+ }
5125
+ const gone = [...known.keys()].filter((id) => !seen.has(id));
5126
+ for (const id of gone) {
5127
+ const row = known.get(id);
5128
+ units.push(row.unit);
5129
+ moduleOf[id] = row.module;
5130
+ }
5131
+ await mkdir10(dirname6(mapPath), { recursive: true });
5132
+ await writeFile8(mapPath, renderUnitMap(units, moduleOf, previous));
5133
+ const added = [];
5134
+ const skipped = [];
5135
+ for (const u of out.units) {
5136
+ const mod = moduleOf[u.id];
5137
+ if (mod && !progress.modules[mod])
5138
+ skipped.push({ unit: u.id, module: mod });
5139
+ if (!mod || !progress.modules[mod])
5140
+ continue;
5141
+ if (progress.modules[mod].units?.[u.id] !== undefined)
5142
+ continue;
5143
+ progress = updateUnitStatus(progress, mod, u.id, "inventoried");
5144
+ added.push([mod, u.id]);
5145
+ }
5146
+ if (added.length)
5147
+ await writeProgress(ctx.paths.progress, progress);
5148
+ for (const [module, unit] of added) {
5149
+ await emit(ctx.paths, { type: "unit-status", module, unit, from: null, to: "inventoried" });
5150
+ }
5151
+ const registry = existsSync17(ctx.paths.registry) ? await readFile14(ctx.paths.registry, "utf-8") : "";
5152
+ if (!/^\|\s*UNITMAP-001\s*\|/m.test(registry)) {
5153
+ await mkdir10(dirname6(ctx.paths.registry), { recursive: true });
5154
+ await writeFile8(ctx.paths.registry, upsertArtifactRow(registry, ["UNITMAP-001", "unit-map", "-", "draft", mapRel]));
5155
+ }
5156
+ console.log(` inventory: ${fresh} new, ${out.units.length - fresh} known, ${gone.length} disappeared`);
5157
+ if (gone.length)
5158
+ console.log(` disappeared (kept): ${gone.join(", ")}`);
5159
+ if (badIds.length) {
5160
+ console.log(` warning: dropped, id does not match migration.unitId: ${badIds.join(", ")}`);
5161
+ }
5162
+ if (skipped.length) {
5163
+ const missing = [...new Set(skipped.map((s) => s.module))];
5164
+ 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.`);
5165
+ }
5166
+ }
5167
+ async function extract(ctx, unit) {
5168
+ const template = commandFor(ctx, "extract");
5169
+ const progress = await readProgress(ctx.paths.progress);
5170
+ const module = moduleOfUnit(progress, unit);
5171
+ const unitDir = unitDirFor(ctx, unit);
5172
+ await mkdir10(unitDir, { recursive: true });
5173
+ const out = await runAdapter("extract", template, { unit, legacyRoot: ctx.legacyRoot, unitDir }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5174
+ if (out.unit !== unit) {
5175
+ throw new AdapterError(`adapter extract returned unit '${out.unit}', expected '${unit}'`);
5176
+ }
5177
+ const from = progress.modules[module].units[unit];
5178
+ if (UNIT_LINE.indexOf(from) > UNIT_LINE.indexOf("extracted")) {
5179
+ console.log(` ${module}/${unit}: re-extracted (${out.files.length} files), status stays ${from}`);
5180
+ return;
5181
+ }
5182
+ if (from !== "extracted") {
5183
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "extracted"));
5184
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "extracted" });
5185
+ }
5186
+ console.log(` ${module}/${unit}: ${from} \u2192 extracted (${out.files.length} files)`);
5187
+ }
5188
+ async function gate(ctx, unit, approve) {
5189
+ const template = commandFor(ctx, "gate");
5190
+ const progress = await readProgress(ctx.paths.progress);
5191
+ const module = moduleOfUnit(progress, unit);
5192
+ const unitDir = unitDirFor(ctx, unit);
5193
+ const specPath = join20(unitDir, "spec.md");
5194
+ if (!existsSync17(specPath))
5195
+ throw new Error(`No spec at ${specPath}. Write the spec first.`);
5196
+ const from = progress.modules[module].units[unit];
5197
+ if (from !== "spec-draft" && from !== "spec-approved") {
5198
+ throw new Error(`Unit '${unit}' is '${from}'; gate needs spec-draft`);
5199
+ }
5200
+ let out;
5201
+ try {
5202
+ out = await runAdapter("gate", template, { specPath, unitDir }, pluginDir(ctx.paths.harenDir, ctx.adapterName));
5203
+ } catch (e) {
5204
+ console.error(` adapter error: ${e instanceof Error ? e.message : String(e)}`);
5205
+ throw e;
5206
+ }
5207
+ await writeFile8(join20(unitDir, "gate.json"), `${JSON.stringify({ ...out, ranAt: new Date().toISOString() }, null, 2)}
5208
+ `);
5209
+ if (!out.pass) {
5210
+ for (const f of out.findings)
5211
+ console.log(` [${f.severity}] ${f.rule}: ${f.message}`);
5212
+ if (from === "spec-approved") {
5213
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "spec-draft"));
5214
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "spec-draft" });
5215
+ console.log(` ${module}/${unit}: spec-approved \u2192 spec-draft`);
5216
+ throw new Error(`gate FAIL for ${unit}: ${out.findings.length} finding(s). Status is now spec-draft.`);
5217
+ }
5218
+ throw new Error(`gate FAIL for ${unit}: ${out.findings.length} finding(s). Status stays ${from}.`);
5219
+ }
5220
+ for (const f of out.findings)
5221
+ console.log(` [${f.severity}] ${f.rule}: ${f.message}`);
5222
+ console.log(` gate PASS for ${unit}`);
5223
+ if (!approve) {
5224
+ if (!process.stdin.isTTY) {
5225
+ throw new ExitCode(3, "Gate PASS. Not approved yet. Review the spec, then re-run with --approve.");
5226
+ }
5227
+ const answer = prompt(` Approve the spec of ${unit}? [y/N]`);
5228
+ if (answer?.trim().toLowerCase() !== "y") {
5229
+ console.log(` Not approved. Status stays ${from}.`);
5230
+ return;
5231
+ }
5232
+ }
5233
+ if (from !== "spec-approved") {
5234
+ await writeProgress(ctx.paths.progress, updateUnitStatus(progress, module, unit, "spec-approved"));
5235
+ await emit(ctx.paths, { type: "unit-status", module, unit, from, to: "spec-approved" });
5236
+ }
5237
+ await emit(ctx.paths, { type: "unit-gate", module, unit, pass: true, approvedBy: "user" });
5238
+ console.log(` ${module}/${unit}: ${from} \u2192 spec-approved`);
5239
+ }
5240
+ var MIGRATE_USAGE = `Usage:
5241
+ haren migrate inventory [--module <m>]
5242
+ haren migrate extract <unit>
5243
+ haren migrate gate <unit> [--approve]
5244
+ Options: --haren-dir <path>`, UNIT_MAP_HEADER = `| Unit | Parent | Family | Title | Module |
5245
+ |------|--------|--------|-------|--------|`, cell = (v) => v ? v.replaceAll("|", "\\|") : "-", unitDirFor = (ctx, unit) => join20(ctx.paths.harenDir, "artifacts", "02-discovery", "units", unit);
5246
+ var init_migrate = __esm(() => {
5247
+ init_manifest();
5248
+ init_progress();
5249
+ init_adapter_read();
5250
+ init_adapter_run();
5251
+ init_exit_code();
5252
+ init_state();
5253
+ init_resolve();
5254
+ init_track();
5255
+ });
5256
+
5257
+ // src/companion/frame-template.html
5258
+ var frame_template_default = `<!DOCTYPE html>
5259
+ <html>
5260
+ <head>
5261
+ <meta charset="utf-8">
5262
+ <title>haren companion</title>
5263
+ <style>
5264
+ /*
5265
+ * BRAINSTORM COMPANION FRAME TEMPLATE
5266
+ *
5267
+ * This template provides a consistent frame with:
5268
+ * - OS-aware light/dark theming
5269
+ * - Header branding and connection status
5270
+ * - Scrollable main content area
5271
+ * - CSS helpers for common UI patterns
5272
+ *
5273
+ * Content is injected via placeholder comment in #frame-content.
5274
+ */
5275
+
5276
+ * { box-sizing: border-box; margin: 0; padding: 0; }
5277
+ html, body { height: 100%; overflow: hidden; }
5278
+
5279
+ /* ===== THEME VARIABLES ===== */
5280
+ :root {
5281
+ --bg-primary: #f5f5f7;
5282
+ --bg-secondary: #ffffff;
5283
+ --bg-tertiary: #e5e5e7;
5284
+ --border: #d1d1d6;
5285
+ --text-primary: #1d1d1f;
5286
+ --text-secondary: #86868b;
5287
+ --text-tertiary: #aeaeb2;
5288
+ --accent: #0071e3;
5289
+ --accent-hover: #0077ed;
5290
+ --success: #34c759;
5291
+ --warning: #ff9f0a;
5292
+ --error: #ff3b30;
5293
+ --selected-bg: #e8f4fd;
5294
+ --selected-border: #0071e3;
5295
+ }
5296
+
5297
+ @media (prefers-color-scheme: dark) {
5298
+ :root {
5299
+ --bg-primary: #1d1d1f;
5300
+ --bg-secondary: #2d2d2f;
5301
+ --bg-tertiary: #3d3d3f;
5302
+ --border: #424245;
5303
+ --text-primary: #f5f5f7;
5304
+ --text-secondary: #86868b;
5305
+ --text-tertiary: #636366;
5306
+ --accent: #0a84ff;
5307
+ --accent-hover: #409cff;
5308
+ --selected-bg: rgba(10, 132, 255, 0.15);
5309
+ --selected-border: #0a84ff;
5310
+ }
5311
+ }
5312
+
5313
+ body {
5314
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
5315
+ background: var(--bg-primary);
5316
+ color: var(--text-primary);
5317
+ display: flex;
5318
+ flex-direction: column;
5319
+ line-height: 1.5;
5320
+ }
5321
+
5322
+ /* ===== FRAME STRUCTURE ===== */
5323
+ .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; color: var(--text-secondary); line-height: 1; }
5324
+ .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
5325
+ .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
5326
+ .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; flex-shrink: 0; filter: invert(1); }
5327
+ @media (prefers-color-scheme: dark) {
5328
+ .brand-logo { filter: none; }
5329
+ }
5330
+ .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; }
5331
+ .status::before { content: ''; width: 6px; height: 6px; background: var(--status-color, var(--success)); border-radius: 50%; }
5332
+
5333
+ .main { flex: 1; overflow-y: auto; }
5334
+ #frame-content { padding: 2rem; min-height: 100%; }
5335
+
5336
+ .header {
5337
+ background: var(--bg-secondary);
5338
+ border-bottom: 1px solid var(--border);
5339
+ padding: 0.5rem 1.5rem;
5340
+ flex-shrink: 0;
5341
+ display: grid;
5342
+ grid-template-columns: minmax(0, 1fr) auto;
5343
+ align-items: center;
5344
+ gap: 1rem;
5345
+ min-height: 42px;
5346
+ }
5347
+ .header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; }
5348
+ .header .status { grid-column: 2; line-height: 1; }
5349
+ .header span {
5350
+ font-size: 0.75rem;
5351
+ color: var(--text-secondary);
5352
+ }
5353
+ .header .selected-text {
5354
+ color: var(--accent);
5355
+ font-weight: 500;
5356
+ }
5357
+
5358
+ /* ===== TYPOGRAPHY ===== */
5359
+ h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
5360
+ h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
5361
+ .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
5362
+ .section { margin-bottom: 2rem; }
5363
+ .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
5364
+
5365
+ /* ===== OPTIONS (for A/B/C choices) ===== */
5366
+ .options { display: flex; flex-direction: column; gap: 0.75rem; }
5367
+ .option {
5368
+ background: var(--bg-secondary);
5369
+ border: 2px solid var(--border);
5370
+ border-radius: 12px;
5371
+ padding: 1rem 1.25rem;
5372
+ cursor: pointer;
5373
+ transition: all 0.15s ease;
5374
+ display: flex;
5375
+ align-items: flex-start;
5376
+ gap: 1rem;
5377
+ }
5378
+ .option:hover { border-color: var(--accent); }
5379
+ .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
5380
+ .option .letter {
5381
+ background: var(--bg-tertiary);
5382
+ color: var(--text-secondary);
5383
+ width: 1.75rem; height: 1.75rem;
5384
+ border-radius: 6px;
5385
+ display: flex; align-items: center; justify-content: center;
5386
+ font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
5387
+ }
5388
+ .option.selected .letter { background: var(--accent); color: white; }
5389
+ .option .content { flex: 1; }
5390
+ .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
5391
+ .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
5392
+
5393
+ /* ===== CARDS (for showing designs/mockups) ===== */
5394
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
5395
+ .card {
5396
+ background: var(--bg-secondary);
5397
+ border: 1px solid var(--border);
5398
+ border-radius: 12px;
5399
+ overflow: hidden;
5400
+ cursor: pointer;
5401
+ transition: all 0.15s ease;
5402
+ }
5403
+ .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
5404
+ .card.selected { border-color: var(--selected-border); border-width: 2px; }
5405
+ .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
5406
+ .card-body { padding: 1rem; }
5407
+ .card-body h3 { margin-bottom: 0.25rem; }
5408
+ .card-body p { color: var(--text-secondary); font-size: 0.85rem; }
5409
+
5410
+ /* ===== MOCKUP CONTAINER ===== */
5411
+ .mockup {
5412
+ background: var(--bg-secondary);
5413
+ border: 1px solid var(--border);
5414
+ border-radius: 12px;
5415
+ overflow: hidden;
5416
+ margin-bottom: 1.5rem;
5417
+ }
5418
+ .mockup-header {
5419
+ background: var(--bg-tertiary);
5420
+ padding: 0.5rem 1rem;
5421
+ font-size: 0.75rem;
5422
+ color: var(--text-secondary);
5423
+ border-bottom: 1px solid var(--border);
5424
+ }
5425
+ .mockup-body { padding: 1.5rem; }
5426
+
5427
+ /* ===== SPLIT VIEW (side-by-side comparison) ===== */
5428
+ .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
5429
+ @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
5430
+
5431
+ /* ===== PROS/CONS ===== */
5432
+ .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
5433
+ .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
5434
+ .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
5435
+ .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
5436
+ .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
5437
+ .pros li, .cons li { margin-bottom: 0.25rem; }
5438
+
5439
+ /* ===== PLACEHOLDER (for mockup areas) ===== */
5440
+ .placeholder {
5441
+ background: var(--bg-tertiary);
5442
+ border: 2px dashed var(--border);
5443
+ border-radius: 8px;
5444
+ padding: 2rem;
5445
+ text-align: center;
5446
+ color: var(--text-tertiary);
5447
+ }
5448
+
5449
+ /* ===== INLINE MOCKUP ELEMENTS ===== */
5450
+ .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
5451
+ .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
5452
+ .mock-content { padding: 1.5rem; flex: 1; }
5453
+ .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
5454
+ .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
5455
+ /* haren: side-by-side compare with pass/fail verdict */
5456
+ .compare { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
5457
+ .compare .pane { border: 1px solid var(--border); border-radius: 8px; padding: 0.75rem; overflow: auto; }
5458
+ .compare .pane img { max-width: 100%; display: block; }
5459
+ .verdict { display: flex; gap: 0.75rem; margin-top: 1rem; }
5460
+ .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); }
5461
+ .pass:hover, .pass.selected { background: var(--success); color: white; }
5462
+ .fail:hover, .fail.selected { background: var(--error); color: white; }
5463
+ /* haren: review findings by severity */
5464
+ .findings { list-style: none; padding: 0; margin: 1rem 0; }
5465
+ .findings li { border-left: 4px solid var(--border); padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; background: var(--bg-secondary); border-radius: 4px; }
5466
+ .findings .blocker { border-left-color: var(--error); }
5467
+ .findings .major { border-left-color: var(--warning); }
5468
+ .findings .minor { border-left-color: var(--text-tertiary); }
5469
+ </style>
5470
+ </head>
5471
+ <body>
5472
+ <div class="header">
5473
+ <div class="brand"><span class="brand-copy">haren companion</span></div>
5474
+ <div class="status">Connecting\u2026</div>
5475
+ </div>
5476
+
5477
+ <div class="main">
5478
+ <div id="frame-content">
5479
+ <!-- CONTENT -->
5480
+ </div>
5481
+ </div>
5482
+
5483
+ <script src="/helper.js"></script>
5484
+ </body>
5485
+ </html>
5486
+ `;
5487
+ var init_frame_template = () => {};
5488
+
5489
+ // src/companion/helper.js
5490
+ var helper_default = `(function() {
5491
+ const MIN_RECONNECT_MS = 500;
5492
+ const MAX_RECONNECT_MS = 5000; // a restarted server is found within 5 s
5493
+ const MAX_LABEL_CHARS = 200;
5494
+ const TOMBSTONE_AFTER_MS = 15000; // show the "paused" overlay after this long disconnected
5495
+
5496
+ // Pure: next backoff delay (doubles, capped). Exported for unit tests.
5497
+ function nextReconnectDelay(current, max) {
5498
+ return Math.min(current * 2, max);
5499
+ }
5500
+ // Pure: collapse whitespace to single spaces and trim.
5501
+ function cleanText(s) {
5502
+ return String(s || '').replace(/\\s+/g, ' ').trim();
5503
+ }
5504
+
5505
+ // Pure (uses only querySelector and text): a short label for a clicked choice element.
5506
+ // The heading of an option or card, else the letter and title, else the text cut to 200 chars.
5507
+ function choiceLabel(el) {
5508
+ const text = (sel) => {
5509
+ const node = el.querySelector(sel);
5510
+ return node ? cleanText(node.textContent) : '';
5511
+ };
5512
+ const heading = text('.content h3') || text('.card-body h3');
5513
+ if (heading) return heading.slice(0, MAX_LABEL_CHARS);
5514
+ const letter = text('.letter');
5515
+ const title = text('.title');
5516
+ if (letter && title) return (letter + ' ' + title).slice(0, MAX_LABEL_CHARS);
5517
+ return cleanText(el.innerText || el.textContent).slice(0, MAX_LABEL_CHARS);
5518
+ }
5519
+
5520
+ if (typeof module !== 'undefined' && module.exports) {
5521
+ module.exports = {
5522
+ nextReconnectDelay, choiceLabel, cleanText,
5523
+ MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS
5524
+ };
5525
+ }
5526
+
5527
+ // Everything below is browser-only; bail out when loaded in Node (tests).
5528
+ if (typeof window === 'undefined') return;
5529
+
5530
+ let ws = null;
5531
+ let eventQueue = [];
5532
+ let reconnectDelay = MIN_RECONNECT_MS;
5533
+ let reconnectTimer = null;
5534
+ let disconnectedSince = null;
5535
+ let everConnected = false;
5536
+ let tombstoneShown = false;
5537
+
5538
+ // The server injects the session key below when it serves this file.
5539
+ const COMPANION_KEY = '__COMPANION_KEY__';
5540
+
5541
+ function websocketUrl() {
5542
+ return 'ws://' + window.location.host + '/ws?key=' + encodeURIComponent(COMPANION_KEY);
5543
+ }
5544
+
5545
+ function reloadAfterRecovery() {
5546
+ window.location.replace('/?key=' + encodeURIComponent(COMPANION_KEY));
5547
+ }
5548
+
5549
+ // Reflect connection state in the frame's status pill (absent on full-doc screens).
5550
+ function setStatus(state) {
5551
+ const el = document.querySelector('.status');
5552
+ if (!el) return;
5553
+ const map = {
5554
+ connecting: ['Connecting\u2026', 'var(--text-tertiary)'],
5555
+ connected: ['Connected', 'var(--success)'],
5556
+ reconnecting: ['Reconnecting\u2026', 'var(--warning)'],
5557
+ disconnected: ['Disconnected', 'var(--error)']
5558
+ };
5559
+ const [text, color] = map[state] || map.disconnected;
5560
+ el.textContent = text;
5561
+ el.style.setProperty('--status-color', color);
5562
+ }
5563
+
5564
+ // Self-styled so it works on framed and full-document screens alike.
5565
+ function showTombstone() {
5566
+ if (tombstoneShown) return;
5567
+ tombstoneShown = true;
5568
+ const el = document.createElement('div');
5569
+ el.id = 'bs-tombstone';
5570
+ el.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;' +
5571
+ 'align-items:center;justify-content:center;padding:2rem;text-align:center;' +
5572
+ 'background:rgba(20,20,22,0.92);color:#f5f5f7;font-family:system-ui,sans-serif';
5573
+ el.innerHTML = '<div style="max-width:480px">' +
5574
+ '<h2 style="margin:0 0 .5rem;font-weight:600">Companion paused. Reconnecting\u2026</h2>' +
5575
+ '<p style="margin:0;opacity:.85">This page connects again when the server comes back. ' +
5576
+ 'If it does not, ask your coding agent to start the companion.</p></div>';
5577
+ if (document.body) document.body.appendChild(el);
5578
+ }
5579
+
5580
+ function connect() {
5581
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
5582
+ setStatus(everConnected ? 'reconnecting' : 'connecting');
5583
+ ws = new WebSocket(websocketUrl());
5584
+
5585
+ ws.onopen = () => {
5586
+ const recovered = tombstoneShown;
5587
+ everConnected = true;
5588
+ disconnectedSince = null;
5589
+ reconnectDelay = MIN_RECONNECT_MS;
5590
+ tombstoneShown = false;
5591
+ setStatus('connected');
5592
+ eventQueue.forEach(e => ws.send(JSON.stringify(e)));
5593
+ eventQueue = [];
5594
+ // Recovered from a tombstoned outage (e.g. the server restarted on the same
5595
+ // port) \u2014 reload through the keyed bootstrap when possible so the cookie is
5596
+ // refreshed before the visible URL returns to bare /.
5597
+ if (recovered) reloadAfterRecovery();
5598
+ };
5599
+
5600
+ ws.onmessage = (msg) => {
5601
+ let data;
5602
+ try { data = JSON.parse(msg.data); } catch (e) { return; }
5603
+ if (data.type === 'reload') window.location.reload();
5604
+ };
5605
+
5606
+ ws.onclose = () => {
5607
+ ws = null;
5608
+ if (disconnectedSince === null) disconnectedSince = Date.now();
5609
+ if (Date.now() - disconnectedSince >= TOMBSTONE_AFTER_MS) {
5610
+ setStatus('disconnected');
5611
+ showTombstone();
5612
+ } else {
5613
+ setStatus('reconnecting');
5614
+ }
5615
+ reconnectTimer = setTimeout(connect, reconnectDelay);
5616
+ reconnectDelay = nextReconnectDelay(reconnectDelay, MAX_RECONNECT_MS);
5617
+ };
5618
+
5619
+ // Let onclose own reconnection so we don't schedule it twice.
5620
+ ws.onerror = () => { try { ws.close(); } catch (e) {} };
5621
+ }
5622
+
5623
+ function sendEvent(event) {
5624
+ event.timestamp = Date.now();
5625
+ if (ws && ws.readyState === WebSocket.OPEN) {
5626
+ ws.send(JSON.stringify(event));
5627
+ } else {
5628
+ eventQueue.push(event);
5629
+ }
5630
+ }
5631
+
5632
+ // Capture clicks on choice elements
5633
+ document.addEventListener('click', (e) => {
5634
+ const target = e.target.closest('[data-choice]');
5635
+ if (!target) return;
5636
+
5637
+ sendEvent({
5638
+ type: 'click',
5639
+ text: choiceLabel(target),
5640
+ choice: target.dataset.choice,
5641
+ id: target.id || null
5642
+ });
5643
+
5644
+ });
5645
+
5646
+ // Frame UI: selection tracking
5647
+ window.selectedChoice = null;
5648
+
5649
+ window.toggleSelect = function(el) {
5650
+ const container = el.closest('.options') || el.closest('.cards') || el.closest('.verdict');
5651
+ const multi = container && container.dataset.multiselect !== undefined;
5652
+ if (container && !multi) {
5653
+ container.querySelectorAll('.option, .card, .pass, .fail').forEach(o => o.classList.remove('selected'));
5654
+ }
5655
+ if (multi) {
5656
+ el.classList.toggle('selected');
5657
+ } else {
5658
+ el.classList.add('selected');
5659
+ }
5660
+ window.selectedChoice = el.dataset.choice;
5661
+ };
5662
+
5663
+ // Expose API for explicit use
5664
+ window.companion = {
5665
+ send: sendEvent,
5666
+ choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
5667
+ };
5668
+
5669
+ connect();
5670
+ })();
5671
+ `;
5672
+ var init_helper = () => {};
5673
+
5674
+ // src/companion/server.ts
5675
+ import { randomBytes, timingSafeEqual } from "crypto";
5676
+ import {
5677
+ appendFileSync,
5678
+ chmodSync,
5679
+ existsSync as existsSync18,
5680
+ lstatSync,
5681
+ mkdirSync,
5682
+ readdirSync,
5683
+ readFileSync as readFileSync2,
5684
+ realpathSync as realpathSync2,
5685
+ rmSync,
5686
+ statSync,
5687
+ writeFileSync
5688
+ } from "fs";
5689
+ import { basename as basename5, extname, join as join21, sep as sep5 } from "path";
5690
+ function makePrivateDir(dir) {
5691
+ mkdirSync(dir, { recursive: true, mode: 448 });
5692
+ try {
5693
+ chmodSync(dir, 448);
5694
+ } catch {}
5695
+ }
5696
+ function writePrivateFile(path, data) {
5697
+ writeFileSync(path, data, { mode: 384 });
5698
+ try {
5699
+ chmodSync(path, 384);
5700
+ } catch {}
5701
+ }
5702
+ function isFullDocument(html) {
5703
+ const t = html.trimStart().toLowerCase();
5704
+ return t.startsWith("<!doctype") || t.startsWith("<html");
5705
+ }
5706
+ function isRegularFileInside(dir, filePath) {
5707
+ try {
5708
+ const st = lstatSync(filePath);
5709
+ if (st.isSymbolicLink() || !st.isFile() || st.nlink !== 1)
5710
+ return false;
5711
+ return realpathSync2(filePath).startsWith(realpathSync2(dir) + sep5);
5712
+ } catch {
5713
+ return false;
5714
+ }
5715
+ }
5716
+ function newestScreen(contentDir) {
5717
+ let names;
5718
+ try {
5719
+ names = readdirSync(contentDir);
5720
+ } catch {
5721
+ return null;
5722
+ }
5723
+ let best = null;
5724
+ for (const name of names) {
5725
+ if (name.startsWith(".") || !name.endsWith(".html"))
5726
+ continue;
5727
+ const fp = join21(contentDir, name);
5728
+ if (!isRegularFileInside(contentDir, fp))
5729
+ continue;
5730
+ const mtime = statSync(fp).mtimeMs;
5731
+ if (!best || mtime > best.mtime)
5732
+ best = { path: fp, mtime };
5733
+ }
5734
+ return best ? best.path : null;
5735
+ }
5736
+ function safeEqual(a, b) {
5737
+ const ab = Buffer.from(a);
5738
+ const bb = Buffer.from(b);
5739
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
5740
+ }
5741
+ function cookieValue(header, name) {
5742
+ if (!header)
5743
+ return null;
5744
+ for (const part of header.split(";")) {
5745
+ const eq = part.indexOf("=");
5746
+ if (eq >= 0 && part.slice(0, eq).trim() === name)
5747
+ return part.slice(eq + 1).trim();
5748
+ }
5749
+ return null;
5750
+ }
5751
+ function wrapInFrame(content) {
5752
+ return frameTemplate.replace("<!-- CONTENT -->", () => content);
5753
+ }
5754
+ function injectHelper(html) {
5755
+ if (html.includes(HELPER_TAG))
5756
+ return html;
5757
+ const re = /<\/body>/i;
5758
+ return re.test(html) ? html.replace(re, (m) => `${HELPER_TAG}
5759
+ ${m}`) : html + HELPER_TAG;
5760
+ }
5761
+ function urlHostForHttp(host) {
5762
+ if (host.startsWith("[") && host.endsWith("]"))
5763
+ return host;
5764
+ return host.includes(":") ? `[${host}]` : host;
5765
+ }
5766
+ async function startCompanion(opts) {
5767
+ const contentDir = join21(opts.sessionDir, "content");
5768
+ const stateDir = join21(opts.sessionDir, "state");
5769
+ for (const dir of [opts.sessionDir, contentDir, stateDir])
5770
+ makePrivateDir(dir);
5771
+ const stoppedFile = join21(stateDir, "server-stopped");
5772
+ const eventsFile = join21(stateDir, "events");
5773
+ rmSync(stoppedFile, { force: true });
5774
+ if (existsSync18(eventsFile))
5775
+ chmodSync(eventsFile, 384);
5776
+ const key = opts.key ?? randomBytes(16).toString("hex");
5777
+ const idleTimeoutMs = opts.idleTimeoutMs ?? 240 * 60000;
5778
+ const helperScript = helperSource.replaceAll("'__COMPANION_KEY__'", () => JSON.stringify(key));
5779
+ const clients = new Set;
5780
+ let idleTimer = null;
5781
+ let stopped = false;
5782
+ let lastActivity = Date.now();
5783
+ const touch = () => {
5784
+ if (stopped)
5785
+ return;
5786
+ lastActivity = Date.now();
5787
+ if (idleTimer)
5788
+ clearTimeout(idleTimer);
5789
+ idleTimer = setTimeout(() => void stop("idle"), idleTimeoutMs);
5790
+ };
5791
+ const keyFromRequest = (req, url) => {
5792
+ const q = url.searchParams.get("key");
5793
+ if (q !== null)
5794
+ return { ok: q !== "" && safeEqual(q, key), viaQuery: true };
5795
+ const c = cookieValue(req.headers.get("cookie"), COOKIE_NAME);
5796
+ return { ok: c !== null && safeEqual(c, key), viaQuery: false };
5797
+ };
5798
+ const respond = (body, type, status = 200, extra = {}) => new Response(body, {
5799
+ status,
5800
+ headers: { ...SECURITY_HEADERS, "Content-Type": type, ...extra }
5801
+ });
5802
+ const server = Bun.serve({
5803
+ hostname: opts.host ?? "127.0.0.1",
5804
+ port: opts.port ?? 0,
5805
+ fetch(req, srv) {
5806
+ const url = new URL(req.url);
5807
+ const auth = keyFromRequest(req, url);
5808
+ if (!auth.ok)
5809
+ return respond(FORBIDDEN_PAGE, "text/html; charset=utf-8", 403);
5810
+ touch();
5811
+ if (url.pathname === "/ws") {
5812
+ if (srv.upgrade(req, { data: undefined }))
5813
+ return;
5814
+ return respond("WebSocket upgrade expected", "text/plain", 400);
5815
+ }
5816
+ const extra = auth.viaQuery ? { "Set-Cookie": `${COOKIE_NAME}=${key}; HttpOnly; SameSite=Strict; Path=/` } : {};
5817
+ if (req.method !== "GET")
5818
+ return respond("Not found", "text/plain", 404, extra);
5819
+ if (url.pathname === "/") {
5820
+ const screen = newestScreen(contentDir);
5821
+ const raw = screen ? readFileSync2(screen, "utf-8") : null;
5822
+ const html = raw === null ? wrapInFrame(WAITING_CONTENT) : isFullDocument(raw) ? injectHelper(raw) : wrapInFrame(raw);
5823
+ return respond(html, "text/html; charset=utf-8", 200, extra);
5824
+ }
5825
+ if (url.pathname === "/helper.js") {
5826
+ return respond(helperScript, "application/javascript", 200, extra);
5827
+ }
5828
+ if (url.pathname.startsWith("/files/")) {
5829
+ let name;
5830
+ try {
5831
+ name = basename5(decodeURIComponent(url.pathname.slice("/files/".length)));
5832
+ } catch {
5833
+ return respond("Not found", "text/plain", 404, extra);
5834
+ }
5835
+ const fp = join21(contentDir, name);
5836
+ if (!name || name.startsWith(".") || !isRegularFileInside(contentDir, fp)) {
5837
+ return respond("Not found", "text/plain", 404, extra);
5838
+ }
5839
+ const type = MIME_TYPES[extname(fp).toLowerCase()] ?? "application/octet-stream";
5840
+ return respond(readFileSync2(fp), type, 200, extra);
5841
+ }
5842
+ return respond("Not found", "text/plain", 404, extra);
5843
+ },
5844
+ websocket: {
5845
+ open(ws) {
5846
+ clients.add(ws);
5847
+ touch();
5848
+ },
5849
+ close(ws) {
5850
+ clients.delete(ws);
5851
+ touch();
5852
+ },
5853
+ message(_ws, message) {
5854
+ touch();
5855
+ let event;
5856
+ try {
5857
+ event = JSON.parse(String(message));
5858
+ } catch {
5859
+ return;
5860
+ }
5861
+ if (!event || typeof event !== "object" || event.type !== "click")
5862
+ return;
5863
+ const { choice, text = "" } = event;
5864
+ if (typeof choice !== "string" || typeof text !== "string")
5865
+ return;
5866
+ const line = {
5867
+ type: "click",
5868
+ choice,
5869
+ text: text.slice(0, MAX_CLICK_TEXT),
5870
+ timestamp: Math.floor(Date.now() / 1000)
5871
+ };
5872
+ appendFileSync(eventsFile, `${JSON.stringify(line)}
5873
+ `, { mode: 384 });
5874
+ }
5875
+ }
5876
+ });
5877
+ const signature = (p) => {
5878
+ if (!p)
5879
+ return "";
5880
+ try {
5881
+ return `${p}:${statSync(p).mtimeMs}`;
5882
+ } catch {
5883
+ return "";
5884
+ }
5885
+ };
5886
+ let lastPath = newestScreen(contentDir);
5887
+ let lastSig = signature(lastPath);
5888
+ const poll = setInterval(() => {
5889
+ const current = newestScreen(contentDir);
5890
+ const sig = signature(current);
5891
+ if (sig === lastSig)
5892
+ return;
5893
+ if (current !== lastPath)
5894
+ writePrivateFile(eventsFile, "");
5895
+ lastPath = current;
5896
+ lastSig = sig;
5897
+ const msg = JSON.stringify({ type: "reload" });
5898
+ for (const ws of clients)
5899
+ ws.send(msg);
5900
+ }, POLL_MS);
5901
+ const port = server.port;
5902
+ const info = {
5903
+ type: "server-started",
5904
+ port,
5905
+ url: `http://${urlHostForHttp(opts.urlHost ?? "localhost")}:${port}/?key=${key}`,
5906
+ screen_dir: contentDir,
5907
+ state_dir: stateDir
5908
+ };
5909
+ writePrivateFile(join21(stateDir, "server-info"), `${JSON.stringify(info)}
5910
+ `);
5911
+ async function stop(reason = "stopped") {
5912
+ if (stopped)
5913
+ return;
5914
+ stopped = true;
5915
+ if (idleTimer)
5916
+ clearTimeout(idleTimer);
5917
+ clearInterval(poll);
5918
+ if (existsSync18(stateDir)) {
5919
+ writeFileSync(stoppedFile, `${JSON.stringify({ reason })}
5920
+ `);
5921
+ }
5922
+ await server.stop(true);
5923
+ }
5924
+ touch();
5925
+ return { info, stop, clientCount: () => clients.size, lastActivity: () => lastActivity };
5926
+ }
5927
+ var frameTemplate, helperSource, COOKIE_NAME = "companion_key", POLL_MS = 500, MAX_CLICK_TEXT = 200, MIME_TYPES, SECURITY_HEADERS, FORBIDDEN_PAGE = `<!DOCTYPE html>
5928
+ <html><head><meta charset="utf-8"><title>Session key required</title></head>
5929
+ <body><h1>Session key required</h1>
5930
+ <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>
5931
+ <p class="subtitle">Waiting for the agent to push a screen...</p>`, HELPER_TAG = '<script src="/helper.js"></script>';
5932
+ var init_server = __esm(() => {
5933
+ init_frame_template();
5934
+ init_helper();
5935
+ frameTemplate = frame_template_default;
5936
+ helperSource = helper_default;
5937
+ MIME_TYPES = {
5938
+ ".html": "text/html",
5939
+ ".css": "text/css",
5940
+ ".js": "application/javascript",
5941
+ ".json": "application/json",
5942
+ ".png": "image/png",
5943
+ ".jpg": "image/jpeg",
5944
+ ".jpeg": "image/jpeg",
5945
+ ".gif": "image/gif",
5946
+ ".svg": "image/svg+xml",
5947
+ ".txt": "text/plain"
5948
+ };
5949
+ SECURITY_HEADERS = {
5950
+ "Referrer-Policy": "no-referrer",
5951
+ "Cache-Control": "no-store",
5952
+ "X-Frame-Options": "DENY",
5953
+ "Content-Security-Policy": "frame-ancestors 'none'",
5954
+ "Cross-Origin-Resource-Policy": "same-origin"
5955
+ };
5956
+ });
5957
+
5958
+ // src/commands/companion.ts
5959
+ import { randomBytes as randomBytes2 } from "crypto";
5960
+ import {
5961
+ existsSync as existsSync19,
5962
+ readdirSync as readdirSync2,
5963
+ readFileSync as readFileSync3,
5964
+ renameSync,
5965
+ rmSync as rmSync2,
5966
+ statSync as statSync2,
5967
+ writeFileSync as writeFileSync2
5968
+ } from "fs";
5969
+ import { spawnSync } from "child_process";
5970
+ import { join as join22, resolve as resolve12 } from "path";
5971
+ function flag(args, name) {
5972
+ const i = args.indexOf(name);
5973
+ if (i === -1)
5974
+ return;
5975
+ const value = args[i + 1];
5976
+ if (value === undefined || value.startsWith("--"))
5977
+ throw new Error(`${name} needs a value`);
5978
+ return value;
5979
+ }
5980
+ function readJson(path) {
5981
+ try {
5982
+ return JSON.parse(readFileSync3(path, "utf-8"));
5983
+ } catch {
5984
+ return null;
5985
+ }
5986
+ }
5987
+ function savedMinutes(value) {
5988
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
5989
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : undefined;
5990
+ }
5991
+ function pidAlive(pid) {
5992
+ try {
5993
+ process.kill(pid, 0);
5994
+ return true;
5995
+ } catch (e) {
5996
+ return e.code === "EPERM";
5997
+ }
5998
+ }
5999
+ function readPid(dir) {
6000
+ try {
6001
+ const n = Number.parseInt(readFileSync3(join22(dir, "state", "pid"), "utf-8").trim(), 10);
6002
+ return Number.isFinite(n) && n > 0 ? n : null;
6003
+ } catch {
6004
+ return null;
6005
+ }
6006
+ }
6007
+ function sessionOf(dir) {
6008
+ const stateDir = join22(dir, "state");
6009
+ const info = readJson(join22(stateDir, "server-info")) ?? readJson(join22(stateDir, "server-info.prev"));
6010
+ const pid = readPid(dir);
6011
+ const running = info !== null && !existsSync19(join22(stateDir, "server-stopped")) && pid !== null && pidAlive(pid);
6012
+ return { dir, info, running };
6013
+ }
6014
+ function latestSession(harenDir) {
6015
+ const base = join22(harenDir, ".companion");
6016
+ let best = null;
6017
+ let names;
6018
+ try {
6019
+ names = readdirSync2(base);
6020
+ } catch {
6021
+ return null;
6022
+ }
6023
+ for (const name of names) {
6024
+ const dir = join22(base, name);
6025
+ try {
6026
+ const st = statSync2(dir);
6027
+ if (!st.isDirectory())
6028
+ continue;
6029
+ const epoch = Number(name.split("-")[1]);
6030
+ const t = Number.isFinite(epoch) ? epoch : st.mtimeMs;
6031
+ if (!best || t > best.mtime)
6032
+ best = { dir, mtime: t };
6033
+ } catch {}
6034
+ }
6035
+ return best ? sessionOf(best.dir) : null;
6036
+ }
6037
+ async function portFree(port, host) {
6038
+ try {
6039
+ const s = Bun.serve({ hostname: host, port, fetch: () => new Response("") });
6040
+ await s.stop(true);
6041
+ return true;
6042
+ } catch {
6043
+ return false;
6044
+ }
6045
+ }
6046
+ function cliEntry() {
6047
+ const here = import.meta.path;
6048
+ if (/[\\/]commands[\\/]companion\.ts$/.test(here))
6049
+ return resolve12(import.meta.dir, "..", "index.ts");
6050
+ return here;
6051
+ }
6052
+ function openBrowser(url) {
6053
+ try {
6054
+ const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
6055
+ Bun.spawn(cmd, { stdio: ["ignore", "ignore", "ignore"] }).unref();
6056
+ } catch {}
6057
+ }
6058
+ function badValue(message) {
6059
+ console.log(JSON.stringify({ error: message }));
6060
+ throw new ExitCode(1, message);
6061
+ }
6062
+ function checkPort(value) {
6063
+ if (value === undefined)
6064
+ return;
6065
+ const n = Number(value);
6066
+ if (!/^\d+$/.test(value) || n > 65535)
6067
+ badValue("--port must be an integer from 0 to 65535");
6068
+ }
6069
+ function readPs(pid) {
6070
+ try {
6071
+ const r = spawnSync("ps", ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf-8" });
6072
+ const m = /^\s*(\d+)\s+(.+?)\s*$/.exec(String(r.stdout));
6073
+ return m ? { ppid: Number(m[1]), comm: m[2] } : null;
6074
+ } catch {
6075
+ return null;
6076
+ }
6077
+ }
6078
+ function isShell(comm) {
6079
+ const base = comm.split("/").pop() ?? comm;
6080
+ return SHELLS.has(base.replace(/^-/, ""));
6081
+ }
6082
+ function pickOwnerPid(start, ps = readPs) {
6083
+ let pid = start;
6084
+ for (let hops = 0;pid > 1 && hops < 64; hops++) {
6085
+ const e = ps(pid);
6086
+ if (!e)
6087
+ break;
6088
+ if (!isShell(e.comm))
6089
+ return pid;
6090
+ pid = e.ppid;
6091
+ }
6092
+ const gp = ps(start)?.ppid;
6093
+ if (gp !== undefined && gp > 1)
6094
+ return gp;
6095
+ return start > 1 ? start : undefined;
6096
+ }
6097
+ function ownerPid() {
6098
+ if (process.platform === "win32")
6099
+ return;
6100
+ return pickOwnerPid(process.ppid);
6101
+ }
6102
+ function buildServeArgs(dir, o) {
6103
+ const args = ["__serve", "--session", dir, "--port", String(o.port), "--host", o.host];
6104
+ args.push("--key-file", o.keyFile);
6105
+ if (o.urlHost !== undefined)
6106
+ args.push("--url-host", o.urlHost);
6107
+ if (o.idleTimeoutMinutes !== undefined)
6108
+ args.push("--idle-timeout-minutes", String(o.idleTimeoutMinutes));
6109
+ if (o.ownerPid !== undefined)
6110
+ args.push("--owner-pid", String(o.ownerPid));
6111
+ if (o.ownerGraceMinutes !== undefined)
6112
+ args.push("--owner-grace-minutes", String(o.ownerGraceMinutes));
6113
+ if (o.open)
6114
+ args.push("--open");
6115
+ if (o.portFallback)
6116
+ args.push("--port-fallback");
6117
+ return args;
6118
+ }
6119
+ function checkMinutes(name, value) {
6120
+ if (value !== undefined && (!/^\d+$/.test(value) || Number(value) < 1))
6121
+ badValue(`${name} must be a positive integer`);
6122
+ }
6123
+ async function serve(args) {
6124
+ const sessionDir = flag(args, "--session");
6125
+ if (!sessionDir)
6126
+ throw new Error("__serve needs --session <dir>");
6127
+ const portText = flag(args, "--port") ?? "0";
6128
+ checkPort(portText);
6129
+ const port = Number(portText);
6130
+ const minutes = flag(args, "--idle-timeout-minutes");
6131
+ if (minutes !== undefined && !(Number(minutes) > 0))
6132
+ badValue("--idle-timeout-minutes must be a positive number");
6133
+ const ownerText = flag(args, "--owner-pid");
6134
+ let owner = ownerText === undefined ? undefined : Number(ownerText);
6135
+ if (owner !== undefined && !(Number.isInteger(owner) && owner > 0))
6136
+ badValue("--owner-pid must be a positive integer");
6137
+ if (owner !== undefined && !pidAlive(owner))
6138
+ owner = undefined;
6139
+ const graceText = flag(args, "--owner-grace-minutes");
6140
+ if (graceText !== undefined && !(Number(graceText) > 0))
6141
+ badValue("--owner-grace-minutes must be a positive number");
6142
+ const graceMs = Number(graceText ?? DEFAULT_OWNER_GRACE_MINUTES) * 60000;
6143
+ const stateDir = join22(sessionDir, "state");
6144
+ for (const d of [sessionDir, join22(sessionDir, "content"), stateDir])
6145
+ makePrivateDir(d);
6146
+ const keyPath = join22(stateDir, "key");
6147
+ const keyFile = flag(args, "--key-file");
6148
+ let key = keyFile ? readKey(keyFile) : undefined;
6149
+ if (keyFile && !key)
6150
+ throw new Error(`No key in ${keyFile}`);
6151
+ key ??= randomBytes2(16).toString("hex");
6152
+ if (!keyFile || resolve12(keyFile) !== resolve12(keyPath))
6153
+ writePrivateFile(keyPath, `${key}
6154
+ `);
6155
+ const opts = {
6156
+ sessionDir,
6157
+ port,
6158
+ key,
6159
+ host: flag(args, "--host"),
6160
+ urlHost: flag(args, "--url-host"),
6161
+ idleTimeoutMs: minutes ? Number(minutes) * 60000 : undefined
6162
+ };
6163
+ let handle;
6164
+ try {
6165
+ handle = await startCompanion(opts);
6166
+ } catch (e) {
6167
+ if (!args.includes("--port-fallback") || port === 0)
6168
+ throw e;
6169
+ handle = await startCompanion({ ...opts, port: 0 });
6170
+ }
6171
+ writePrivateFile(join22(stateDir, "pid"), `${process.pid}
6172
+ `);
6173
+ await new Promise((done) => {
6174
+ const stopFile = join22(handle.info.state_dir, "server-stopped");
6175
+ let opened = !args.includes("--open");
6176
+ let lastOwnerCheck = Date.now();
6177
+ let ownerGoneAt = null;
6178
+ const finish = () => {
6179
+ clearInterval(timer);
6180
+ process.off("SIGTERM", onSignal);
6181
+ process.off("SIGINT", onSignal);
6182
+ done();
6183
+ };
6184
+ const onSignal = () => void handle.stop("stop").then(finish);
6185
+ const timer = setInterval(() => {
6186
+ if (!opened && newestScreen(handle.info.screen_dir)) {
6187
+ opened = true;
6188
+ openBrowser(handle.info.url);
6189
+ }
6190
+ if (owner !== undefined && Date.now() - lastOwnerCheck >= OWNER_CHECK_MS) {
6191
+ lastOwnerCheck = Date.now();
6192
+ if (ownerGoneAt === null && !pidAlive(owner))
6193
+ ownerGoneAt = Date.now();
6194
+ }
6195
+ if (ownerGoneAt !== null && handle.clientCount() === 0) {
6196
+ const quietSince = Math.max(ownerGoneAt, handle.lastActivity());
6197
+ if (Date.now() - quietSince >= graceMs) {
6198
+ handle.stop("owner-exited").then(finish);
6199
+ return;
6200
+ }
6201
+ }
6202
+ if (existsSync19(stopFile))
6203
+ finish();
6204
+ }, 100);
6205
+ process.on("SIGTERM", onSignal);
6206
+ process.on("SIGINT", onSignal);
6207
+ });
6208
+ await handle.stop("stop");
6209
+ }
6210
+ function readKey(path) {
6211
+ try {
6212
+ return readFileSync3(path, "utf-8").trim() || undefined;
6213
+ } catch {
6214
+ return;
6215
+ }
6216
+ }
6217
+ function restoreInfo(dir) {
6218
+ const infoPath = join22(dir, "state", "server-info");
6219
+ if (!existsSync19(infoPath) && existsSync19(`${infoPath}.prev`))
6220
+ renameSync(`${infoPath}.prev`, infoPath);
6221
+ }
6222
+ function keyOf(url) {
6223
+ try {
6224
+ return new URL(url).searchParams.get("key") ?? undefined;
6225
+ } catch {
6226
+ return;
6227
+ }
6228
+ }
6229
+ function notePortChange(restart, info) {
6230
+ if (restart?.info && restart.info.port !== info.port) {
6231
+ console.error(`The companion port changed from ${restart.info.port} to ${info.port}: port changed, give the user the new URL.`);
6232
+ }
6233
+ }
6234
+ async function waitExit(pid, ms) {
6235
+ const deadline = Date.now() + ms;
6236
+ while (pidAlive(pid) && Date.now() < deadline)
6237
+ await Bun.sleep(25);
6238
+ return !pidAlive(pid);
6239
+ }
6240
+ async function terminate(pid, waitMs) {
6241
+ try {
6242
+ process.kill(pid, "SIGTERM");
6243
+ } catch {}
6244
+ if (await waitExit(pid, waitMs))
6245
+ return false;
6246
+ try {
6247
+ process.kill(pid, "SIGKILL");
6248
+ } catch {}
6249
+ await waitExit(pid, 1000);
6250
+ return true;
6251
+ }
6252
+ async function start(harenDir, args) {
6253
+ const askedPort = flag(args, "--port");
6254
+ checkPort(askedPort);
6255
+ const askedMinutes = flag(args, "--idle-timeout-minutes");
6256
+ checkMinutes("--idle-timeout-minutes", askedMinutes);
6257
+ const askedGrace = flag(args, "--owner-grace-minutes");
6258
+ checkMinutes("--owner-grace-minutes", askedGrace);
6259
+ const current = latestSession(harenDir);
6260
+ if (current?.running && current.info) {
6261
+ const ignored = START_FLAGS.filter((f) => args.includes(f));
6262
+ if (ignored.length > 0) {
6263
+ console.error(`A companion session is already running; reused it and ignored ${ignored.join(", ")}.`);
6264
+ }
6265
+ console.log(JSON.stringify(current.info));
6266
+ return;
6267
+ }
6268
+ const askedKey = flag(args, "--key");
6269
+ const restart = current?.info && askedPort === undefined && askedKey === undefined ? current : null;
6270
+ const saved = restart ? readJson(join22(restart.dir, "state", "options.json")) : null;
6271
+ const options = {
6272
+ host: flag(args, "--host") ?? saved?.host ?? "127.0.0.1",
6273
+ urlHost: flag(args, "--url-host") ?? saved?.urlHost,
6274
+ idleTimeoutMinutes: askedMinutes !== undefined ? Number(askedMinutes) : savedMinutes(saved?.idleTimeoutMinutes),
6275
+ ownerGraceMinutes: askedGrace !== undefined ? Number(askedGrace) : savedMinutes(saved?.ownerGraceMinutes)
6276
+ };
6277
+ let port = 0;
6278
+ let reused = false;
6279
+ if (askedPort !== undefined)
6280
+ port = Number(askedPort);
6281
+ else if (current?.info && await portFree(current.info.port, options.host)) {
6282
+ port = current.info.port;
6283
+ reused = true;
6284
+ } else if (restart) {
6285
+ reused = true;
6286
+ port = restart.info.port;
6287
+ }
6288
+ const dir = restart ? restart.dir : join22(harenDir, ".companion", `${process.pid}-${Date.now()}`);
6289
+ const fresh = !restart;
6290
+ const stateDir = join22(dir, "state");
6291
+ for (const d of [dir, join22(dir, "content"), stateDir])
6292
+ makePrivateDir(d);
6293
+ const keyPath = join22(stateDir, "key");
6294
+ const oldKey = restart ? readKey(keyPath) ?? keyOf(restart.info.url) : undefined;
6295
+ writePrivateFile(keyPath, `${askedKey ?? oldKey ?? randomBytes2(16).toString("hex")}
6296
+ `);
6297
+ if (restart) {
6298
+ const stoppedAt = mtimeOf(join22(stateDir, "server-stopped"));
6299
+ rmSync2(join22(stateDir, "server-stopped"), { force: true });
6300
+ const infoPath = join22(stateDir, "server-info");
6301
+ if (existsSync19(infoPath))
6302
+ renameSync(infoPath, `${infoPath}.prev`);
6303
+ archiveScreens(join22(dir, "content"), stoppedAt);
6304
+ }
6305
+ const foreground = args.includes("--foreground");
6306
+ const serveArgs = buildServeArgs(dir, {
6307
+ port,
6308
+ host: options.host,
6309
+ keyFile: keyPath,
6310
+ urlHost: options.urlHost,
6311
+ idleTimeoutMinutes: options.idleTimeoutMinutes,
6312
+ ownerGraceMinutes: options.ownerGraceMinutes,
6313
+ open: args.includes("--open"),
6314
+ portFallback: reused,
6315
+ ownerPid: foreground || args.includes("--no-owner-watch") ? undefined : ownerPid()
6316
+ });
6317
+ const fail = () => {
6318
+ if (fresh)
6319
+ rmSync2(dir, { recursive: true, force: true });
6320
+ else
6321
+ restoreInfo(dir);
6322
+ };
6323
+ const succeed = (info) => {
6324
+ rmSync2(join22(stateDir, "server-info.prev"), { force: true });
6325
+ writePrivateFile(join22(stateDir, "options.json"), `${JSON.stringify(options)}
6326
+ `);
6327
+ notePortChange(restart, info);
6328
+ };
6329
+ if (foreground) {
6330
+ const infoFile = join22(stateDir, "server-info");
6331
+ const printer = setInterval(() => {
6332
+ if (existsSync19(infoFile)) {
6333
+ const info = readJson(infoFile);
6334
+ if (!info)
6335
+ return;
6336
+ clearInterval(printer);
6337
+ succeed(info);
6338
+ console.log(JSON.stringify(info));
6339
+ }
6340
+ }, 50);
6341
+ try {
6342
+ await serve(serveArgs);
6343
+ } catch (e) {
6344
+ fail();
6345
+ throw e;
6346
+ } finally {
6347
+ clearInterval(printer);
6348
+ }
6349
+ return;
6350
+ }
6351
+ const child = companionDeps.spawnServe(serveArgs);
6352
+ writePrivateFile(join22(stateDir, "pid"), `${child.pid}
6353
+ `);
6354
+ const deadline = Date.now() + companionDeps.startTimeoutMs;
6355
+ while (Date.now() < deadline) {
6356
+ const s = sessionOf(dir);
6357
+ if (s.info && s.running && existsSync19(join22(stateDir, "server-info"))) {
6358
+ succeed(s.info);
6359
+ console.log(JSON.stringify(s.info));
6360
+ return;
6361
+ }
6362
+ if (child.exitCode !== null)
6363
+ break;
6364
+ await Bun.sleep(50);
6365
+ }
6366
+ await terminate(child.pid, companionDeps.startKillWaitMs);
6367
+ fail();
6368
+ throw new Error(`The companion server did not start within ${companionDeps.startTimeoutMs / 1000} s.`);
6369
+ }
6370
+ function mtimeOf(path) {
6371
+ try {
6372
+ return statSync2(path).mtimeMs;
6373
+ } catch {
6374
+ return Number.POSITIVE_INFINITY;
6375
+ }
6376
+ }
6377
+ function archiveScreens(contentDir, stoppedAt) {
6378
+ let names;
6379
+ try {
6380
+ names = readdirSync2(contentDir).filter((n) => {
6381
+ if (!n.endsWith(".html"))
6382
+ return false;
6383
+ const st = statSync2(join22(contentDir, n));
6384
+ return st.isFile() && st.mtimeMs < stoppedAt;
6385
+ });
6386
+ } catch {
6387
+ return;
6388
+ }
6389
+ if (names.length === 0)
6390
+ return;
6391
+ const target = join22(contentDir, "archive", String(Date.now()));
6392
+ makePrivateDir(join22(contentDir, "archive"));
6393
+ makePrivateDir(target);
6394
+ for (const n of names)
6395
+ renameSync(join22(contentDir, n), join22(target, n));
6396
+ }
6397
+ function status(harenDir) {
6398
+ const s = latestSession(harenDir);
6399
+ if (!s?.running || !s.info) {
6400
+ console.log("The companion server is not running.");
6401
+ throw new ExitCode(1, "");
6402
+ }
6403
+ console.log(`running ${s.info.url}
6404
+ screen_dir ${s.info.screen_dir}
6405
+ state_dir ${s.info.state_dir}`);
6406
+ }
6407
+ function markStopped(dir) {
6408
+ const stopped = join22(dir, "state", "server-stopped");
6409
+ if (existsSync19(join22(dir, "state")) && !existsSync19(stopped))
6410
+ writeFileSync2(stopped, `${JSON.stringify({ reason: "stop" })}
6411
+ `);
6412
+ }
6413
+ async function stop(harenDir) {
6414
+ const s = latestSession(harenDir);
6415
+ if (!s?.running) {
6416
+ if (s)
6417
+ markStopped(s.dir);
6418
+ console.log("No companion server is running.");
6419
+ return;
6420
+ }
6421
+ const pid = readPid(s.dir);
6422
+ const forced = pid !== null && await terminate(pid, companionDeps.stopWaitMs);
6423
+ markStopped(s.dir);
6424
+ console.log(forced ? "stopped (forced)" : "stopped");
6425
+ }
6426
+ async function companion(args, cwd = process.cwd()) {
6427
+ const [sub, ...rest] = args;
6428
+ if (sub === "__serve")
6429
+ return serve(rest);
6430
+ if (!sub || !["start", "status", "stop"].includes(sub)) {
6431
+ console.log(USAGE2);
6432
+ if (sub)
6433
+ throw new ExitCode(1, `Unknown companion command: ${sub}`);
6434
+ return;
6435
+ }
6436
+ const location = await resolveHarenDir(cwd, { harenDir: harenDirFlag(args), env: process.env });
6437
+ if (!location)
6438
+ throw new Error("No haren folder found. Run `haren init` first.");
6439
+ const harenDir = location.harenDir;
6440
+ if (sub === "start")
6441
+ return start(harenDir, rest);
6442
+ if (sub === "status")
6443
+ return status(harenDir);
6444
+ return stop(harenDir);
6445
+ }
6446
+ var USAGE2 = `Usage: haren companion <start|status|stop> [--haren-dir <path>]
6447
+ start [--foreground] [--open] [--port <n>] [--host <h>] [--url-host <u>] [--idle-timeout-minutes <m>]
6448
+ [--key <k>] [--no-owner-watch] [--owner-grace-minutes <m>]
6449
+ status print the URL of the running server (exit 1 when stopped)
6450
+ stop stop the running server`, START_FLAGS, companionDeps, SHELLS, OWNER_CHECK_MS = 1000, DEFAULT_OWNER_GRACE_MINUTES = 10;
6451
+ var init_companion = __esm(() => {
6452
+ init_server();
6453
+ init_exit_code();
6454
+ init_resolve();
6455
+ START_FLAGS = [
6456
+ "--port",
6457
+ "--open",
6458
+ "--key",
6459
+ "--idle-timeout-minutes",
6460
+ "--host",
6461
+ "--url-host",
6462
+ "--no-owner-watch",
6463
+ "--owner-grace-minutes"
6464
+ ];
6465
+ companionDeps = {
6466
+ startTimeoutMs: 5000,
6467
+ startKillWaitMs: 1000,
6468
+ stopWaitMs: 3000,
6469
+ spawnServe(serveArgs) {
6470
+ const child = Bun.spawn([process.execPath, cliEntry(), "companion", ...serveArgs], {
6471
+ stdio: ["ignore", "ignore", "ignore"],
6472
+ detached: true
6473
+ });
6474
+ child.unref();
6475
+ return child;
6476
+ }
6477
+ };
6478
+ SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh", "tcsh", "csh", "env"]);
4061
6479
  });
4062
6480
 
4063
6481
  // src/index.ts
6482
+ init_exit_code();
4064
6483
  function parseArgs(args) {
4065
6484
  if (args.length === 0) {
4066
6485
  return { command: "help", args: [] };
@@ -4079,6 +6498,8 @@ function parseArgs(args) {
4079
6498
  case "agent":
4080
6499
  case "plugin":
4081
6500
  case "track":
6501
+ case "migrate":
6502
+ case "companion":
4082
6503
  return { command, args: rest };
4083
6504
  default:
4084
6505
  return { command: "unknown", args };
@@ -4113,34 +6534,53 @@ async function main() {
4113
6534
  await track(parsed.args);
4114
6535
  break;
4115
6536
  }
6537
+ case "migrate": {
6538
+ await Promise.resolve().then(() => init_migrate());
6539
+ await migrate(parsed.args);
6540
+ break;
6541
+ }
6542
+ case "companion": {
6543
+ await Promise.resolve().then(() => init_companion());
6544
+ await companion(parsed.args);
6545
+ break;
6546
+ }
4116
6547
  case "help":
4117
6548
  console.log("Usage:");
4118
6549
  console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
4119
6550
  console.log(" --dir <path> --layout monorepo|workspace --haren-dir <name>");
6551
+ console.log(" --mode <undecided|explore|blueprint|inherit|migration>");
4120
6552
  console.log(" --yes|-y --dry-run --force");
4121
6553
  console.log(" --plugin <name|source> (repeatable)");
4122
6554
  console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run, --yes)");
4123
6555
  console.log(" haren agent Manage local agent (start, stop, status)");
4124
6556
  console.log(" haren plugin Manage plugins (add, remove, list, run, doctor)");
4125
6557
  console.log(" haren track Record progress and events:");
4126
- console.log(" status <module> <status>");
6558
+ console.log(" status <module> <status> [--branch <name>] [--repos <key1,key2>]");
4127
6559
  console.log(" feature <module> <feature> [status]");
4128
6560
  console.log(" commit <module> <repoKey> <sha>");
6561
+ console.log(" depends <module> [dep ...] (replace the dependency list)");
4129
6562
  console.log(" artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]");
4130
6563
  console.log(" event <type> [--module m] [--phase p] [--feature f] [--data '<json>']");
6564
+ console.log(" unit <module> <unit> <status> (migration mode)");
6565
+ console.log(" ui-mode <ask|ascii|browser>");
4131
6566
  console.log(' override on --reason "<text>" [--hours <n>] | override off');
6567
+ console.log(" haren migrate Run the migration adapter:");
6568
+ console.log(" inventory [--module <m>] | extract <unit> | gate <unit> [--approve]");
6569
+ console.log(" gate exit codes: 0 approved, 1 failed, 3 PASS but not approved yet");
6570
+ console.log(" haren companion Visual companion server: start [--foreground] [--open] | status | stop");
4132
6571
  break;
4133
6572
  case "unknown":
4134
6573
  console.error(`Unknown command: ${parsed.args[0]}`);
4135
- console.log("Usage: haren init | upgrade | agent | plugin | track (haren --help)");
6574
+ console.log("Usage: haren init | upgrade | agent | plugin | track | migrate | companion (haren --help)");
4136
6575
  process.exit(1);
4137
6576
  }
4138
6577
  }
4139
6578
  main().catch((err) => {
4140
6579
  const debug = process.env.HAREN_DEBUG === "1";
4141
6580
  const message = err instanceof Error ? debug && err.stack || err.message : String(err);
4142
- console.error(` ${message}`);
4143
- process.exit(1);
6581
+ if (message)
6582
+ console.error(` ${message}`);
6583
+ process.exit(err instanceof ExitCode ? err.code : 1);
4144
6584
  });
4145
6585
  export {
4146
6586
  parseArgs