@odarino/haren 1.3.3 → 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.
Files changed (43) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +209 -33
  3. package/content/agents/architect.md +5 -2
  4. package/content/agents/developer.md +6 -6
  5. package/content/agents/ideator.md +2 -2
  6. package/content/agents/planner.md +4 -1
  7. package/content/agents/researcher.md +1 -1
  8. package/content/agents/reviewer.md +13 -4
  9. package/content/skills/audit-workspace/SKILL.md +2 -1
  10. package/content/skills/create-artifact/SKILL.md +2 -5
  11. package/content/skills/decompose/SKILL.md +10 -13
  12. package/content/skills/discover/SKILL.md +7 -2
  13. package/content/skills/discover/blueprint.md +1 -0
  14. package/content/skills/discover/explore.md +1 -0
  15. package/content/skills/discover/inherit.md +1 -0
  16. package/content/skills/discover/migration.md +38 -0
  17. package/content/skills/evaluate/SKILL.md +34 -3
  18. package/content/skills/extract/SKILL.md +43 -0
  19. package/content/skills/extract-stories/SKILL.md +1 -1
  20. package/content/skills/generate-mockup/SKILL.md +44 -5
  21. package/content/skills/ideate/SKILL.md +5 -3
  22. package/content/skills/implement/SKILL.md +21 -12
  23. package/content/skills/onboard/SKILL.md +17 -2
  24. package/content/skills/plan/SKILL.md +69 -6
  25. package/content/skills/read-context/SKILL.md +12 -1
  26. package/content/skills/release/SKILL.md +61 -0
  27. package/content/skills/research/SKILL.md +1 -1
  28. package/content/skills/resolve-next-id/SKILL.md +9 -1
  29. package/content/skills/ui-review/SKILL.md +64 -0
  30. package/content/skills/update-links/SKILL.md +1 -1
  31. package/content/skills/update-tracking/SKILL.md +77 -23
  32. package/content/skills/validate-artifact/SKILL.md +21 -0
  33. package/content/skills/visual-companion/SKILL.md +288 -0
  34. package/content/templates/design.md +28 -0
  35. package/content/templates/deviation-log.md +13 -0
  36. package/content/templates/legacy-semantics.md +11 -0
  37. package/content/templates/parity-evidence.md +32 -0
  38. package/content/templates/release-plan.md +29 -0
  39. package/content/templates/spec.md +10 -0
  40. package/content/templates/unit-map.md +20 -0
  41. package/content/templates/unit-spec.md +43 -0
  42. package/dist/index.js +3071 -128
  43. package/package.json +2 -2
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";
@@ -53,17 +66,15 @@ This workspace uses the Haren agentic SDLC framework.
53
66
  3. Read \`{{harenDir}}/manifest.yaml\` and \`{{harenDir}}/progress.json\` before taking any action
54
67
 
55
68
  All project documentation, specs, plans, and artifacts are managed inside \`{{harenDir}}/\`.
56
- Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`, or when the user explicitly asks.
69
+ Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`. For a change the user explicitly asks for, use the gate override (see below).
57
70
 
58
71
  ## Brainstorming Gate
59
72
 
60
73
  Before writing ANY code outside \`{{harenDir}}/\`:
61
- 1. Read \`{{harenDir}}/progress.json\`
62
- 2. At least one module MUST have status \`planned\`, \`implementing\`, \`evaluating\`, or \`completed\`
63
- 3. If NO module is at \`planned\` or later \u2192 STOP. Do not write code.
64
- - \`discovered\`, \`specified\`, \`decomposed\` do NOT allow implementation
65
- - Discovery docs and specs are NOT sufficient \u2014 planning must be completed first
66
- 4. If blocked, tell the user to run the plan phase before implementation
74
+ 1. Read \`{{harenDir}}/progress.json\` and \`{{harenDir}}/manifest.yaml\`
75
+ 2. Write code only inside the repos of a module with status \`planned\`, \`implementing\`, \`evaluating\`, \`completed\`, or \`released\` (the module's \`repos\` keys in progress.json)
76
+ 3. \`discovered\` and \`decomposed\` do NOT allow code. If no module is at \`planned\` or later, STOP and tell the user to run the plan phase.
77
+ 4. Exception: the user explicitly asks for a change (for example a hotfix). Run \`haren track override on --reason "<what the user asked>"\`, make the change, then run \`haren track override off\`.
67
78
 
68
79
  Design specs are written to Haren artifact folders, NOT to docs/superpowers/specs/.
69
80
  `, cursorRuleTemplate = `---
@@ -100,20 +111,19 @@ This applies to ALL phases \u2014 planning, designing, implementing, everything.
100
111
 
101
112
  ---
102
113
 
103
- ## RULE #2: Code Gate \u2014 No code outside \`{{harenDir}}/\` without \`planned\` status
114
+ ## RULE #2: Code Gate \u2014 code only in the repos of a \`planned\` module
104
115
 
105
- **BEFORE writing ANY file outside \`{{harenDir}}/\`, check \`{{harenDir}}/progress.json\`:**
116
+ **BEFORE writing ANY file outside \`{{harenDir}}/\`, read \`{{harenDir}}/progress.json\` and \`{{harenDir}}/manifest.yaml\`:**
106
117
 
107
- 1. The relevant module MUST have status \`planned\`, \`implementing\`, \`evaluating\`, or \`completed\`
108
- 2. **If NO \u2192 STOP. DO NOT WRITE CODE.**
109
- 3. \`discovered\`, \`specified\`, \`decomposed\` do NOT allow code changes
110
- 4. Discovery docs and specs are NOT sufficient
118
+ 1. Write code only inside the repos of a module with status \`planned\`, \`implementing\`, \`evaluating\`, \`completed\`, or \`released\`
119
+ 2. \`discovered\` and \`decomposed\` do NOT allow code. Discovery docs and specs are NOT sufficient.
120
+ 3. **If no such module owns the file \u2192 STOP. DO NOT WRITE CODE.**
111
121
 
112
122
  **When blocked, respond ONLY with:**
113
123
  - No modules: "No modules found. Run the discover phase first."
114
124
  - No planned modules: "No module has reached 'planned' status yet. Run the plan phase first."
115
125
 
116
- No exceptions. No rationalizing. STOP means STOP.
126
+ **Only exception:** the user explicitly asks for the change (for example a hotfix). Run \`haren track override on --reason "<what the user asked>"\`, make the change, then run \`haren track override off\`.
117
127
 
118
128
  ---
119
129
 
@@ -124,34 +134,40 @@ No exceptions. No rationalizing. STOP means STOP.
124
134
  3. Read \`{{harenDir}}/manifest.yaml\` and \`{{harenDir}}/progress.json\` before taking any action
125
135
 
126
136
  All project documentation, specs, plans, and artifacts are managed inside \`{{harenDir}}/\`.
127
- Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`, or when the user explicitly asks.
137
+ Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`. For a change the user explicitly asks for, use the gate override (see below).
128
138
 
129
139
  ## Phase Progression (MANDATORY)
130
140
 
131
141
  Modules MUST progress through phases in order. You CANNOT skip phases.
132
142
 
133
143
  \`\`\`
134
- discovered \u2192 specified \u2192 planned \u2192 implementing \u2192 evaluating \u2192 completed
144
+ discovered \u2192 decomposed \u2192 planned \u2192 implementing \u2192 evaluating \u2192 completed \u2192 released
135
145
  \`\`\`
136
146
 
137
147
  **Before taking ANY action on a module, read \`{{harenDir}}/progress.json\` and check the module's current status. Then follow the dispatch rules in \`{{harenDir}}/skill.md\`.**
138
148
 
139
149
  Key dispatch rules:
140
- - Module at \`specified\` \u2192 user says "plan" \u2192 you MUST run the \`plan/\` skill first (read \`{{harenDir}}/skills/plan/SKILL.md\`)
150
+ - Module at \`decomposed\` \u2192 user says "plan" \u2192 you MUST run the \`plan/\` skill first (read \`{{harenDir}}/skills/plan/SKILL.md\`)
141
151
  - Module at \`discovered\` or no module \u2192 user says "plan" or "build" \u2192 you MUST run \`discover/\` skill first (brainstorming)
142
152
  - Module at \`planned\` \u2192 user says "implement" or "build" \u2192 proceed with implementation
143
- - **You CANNOT jump from \`specified\` directly to \`implementing\`**
153
+ - **You CANNOT jump from \`decomposed\` directly to \`implementing\`**
144
154
  - **You CANNOT skip brainstorming/discovery for new features**
145
155
 
146
156
  ## Rules
147
157
 
148
158
  - Always read progress.json before taking action
149
- - Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`, or when the user explicitly asks.
159
+ - Write outside \`{{harenDir}}/\` only in the module's repos (see "Repos and Git" in \`{{harenDir}}/skill.md\`), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`. For a change the user explicitly asks for, use the gate override (see below).
150
160
  - Update progress.json after every phase transition
151
161
  - Append to FEEDBACK.md when you encounter framework friction
152
162
  `, GATE_SCRIPT_PATH = "hooks/brainstorm-gate.ts", brainstormGateScript = `/**
153
163
  * Brainstorm Gate Hook
154
- * Blocks Edit/Write tool use if no module has reached 'planned' status.
164
+ * Blocks Edit/Write tool use outside the haren folder unless a module that
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).
167
+ *
168
+ * Override (for a fix the user asked for): HAREN_GATE=off, or
169
+ * progress.json "gateOverride": { "reason": "...", "until": "<ISO>" }
170
+ * (set it with: haren track override on --reason "...").
155
171
  *
156
172
  * Works with both Claude Code and Cursor:
157
173
  * - Exit 0 = allow
@@ -165,6 +181,11 @@ import { basename, dirname, join, resolve, sep } from "path";
165
181
  // The hook lives in <harenDir>/hooks/, so the haren folder is one level up.
166
182
  // This works for any folder name. Use the real path so symlinks compare equal.
167
183
  const harenDir = realpathSync(resolve(import.meta.dir, ".."));
184
+ const workspaceDir = dirname(harenDir);
185
+
186
+ const IMPLEMENTABLE = ["planned", "implementing", "evaluating", "completed", "released"];
187
+ const OVERRIDE_HINT =
188
+ "If the user explicitly asked for this change, run \`haren track override on --reason \\"...\\"\` (or set HAREN_GATE=off) and try again.";
168
189
 
169
190
  // Editors send logical paths that can go through symlinks. Resolve the nearest
170
191
  // existing ancestor to its real path, then add back the missing segments.
@@ -182,7 +203,11 @@ function realTarget(abs: string): string {
182
203
  }
183
204
  }
184
205
 
185
- function allow() {
206
+ function inside(path: string, root: string): boolean {
207
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
208
+ }
209
+
210
+ function allow(): never {
186
211
  console.log(JSON.stringify({
187
212
  allow: true, // Claude Code
188
213
  permission: "allow", // Cursor
@@ -190,64 +215,371 @@ function allow() {
190
215
  process.exit(0);
191
216
  }
192
217
 
193
- function deny(message: string) {
194
- console.log(JSON.stringify({
195
- error: message, // Claude Code
196
- permission: "deny", // Cursor
197
- user_message: message, // Cursor \u2014 shown in UI
198
- agent_message: message, // Cursor \u2014 sent to model
199
- }));
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
+
231
+ function deny(message: string): never {
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
+ }
200
243
  process.exit(2);
201
244
  }
202
245
 
203
- async function main() {
204
- // Allow writes inside the haren folder \u2014 planning/discovery phases write artifacts there
246
+ interface Repo { path: string; role?: string; readOnly?: boolean }
247
+
248
+ // Same rules as the CLI: repos is a map key -> {path} | key -> string, or an array.
249
+ function normalizeRepos(repos: unknown): Record<string, Repo> {
250
+ const out: Record<string, Repo> = {};
251
+ if (Array.isArray(repos)) {
252
+ for (const item of repos) {
253
+ const path = typeof item === "string" ? item : item?.path;
254
+ if (typeof path === "string" && path) out[basename(path)] = { path, role: item?.role, readOnly: item?.readOnly === true };
255
+ }
256
+ } else if (repos && typeof repos === "object") {
257
+ for (const [key, value] of Object.entries(repos as Record<string, any>)) {
258
+ if (typeof value === "string") out[key] = { path: value };
259
+ else if (value && typeof value === "object" && typeof value.path === "string") {
260
+ out[key] = { path: value.path, role: value.role, readOnly: value.readOnly === true };
261
+ }
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+
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 = "";
205
275
  try {
206
- const stdin = await Bun.stdin.text();
207
- if (stdin) {
208
- const input = JSON.parse(stdin);
209
- const filePath = input?.tool_input?.file_path
210
- || input?.tool_input?.path
211
- || input?.file_path
212
- || input?.path
213
- || "";
214
- if (filePath) {
215
- const real = realTarget(resolve(process.cwd(), filePath));
216
- if (real === harenDir || real.startsWith(harenDir + sep)) {
217
- allow();
218
- }
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 };
280
+ } catch {
281
+ return { repos: {}, brokenReadOnly: /readOnly\\s*:\\s*true/.test(text) };
282
+ }
283
+ }
284
+
285
+ async function readRepos(): Promise<Record<string, Repo>> {
286
+ return (await readManifest()).repos;
287
+ }
288
+
289
+ function realRoot(path: string): string {
290
+ return realTarget(resolve(harenDir, path));
291
+ }
292
+
293
+ function overrideActive(progress: any): boolean {
294
+ if (process.env.HAREN_GATE === "off") return true;
295
+ const o = progress?.gateOverride;
296
+ if (!o || typeof o !== "object" || typeof o.reason !== "string") return false;
297
+ if (o.until === undefined || o.until === null || o.until === "") return true;
298
+ const until = Date.parse(o.until);
299
+ return !Number.isNaN(until) && until > Date.now();
300
+ }
301
+
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;
219
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;
220
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> {
467
+ try {
468
+ const stdin = await Bun.stdin.text();
469
+ if (!stdin) return { target: "", command: null, cwd: process.cwd(), shell: false };
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;
480
+ const filePath = input?.tool_input?.file_path
481
+ || input?.tool_input?.path
482
+ || input?.file_path
483
+ || input?.path
484
+ || "";
485
+ return {
486
+ target: filePath ? realTarget(resolve(cwd, filePath)) : "",
487
+ command: filePath ? null : command,
488
+ cwd,
489
+ shell: shell && !filePath,
490
+ };
221
491
  } catch {
222
- // 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
223
493
  }
494
+ }
224
495
 
225
- const progressPath = resolve(harenDir, "progress.json");
226
- const progressFile = Bun.file(progressPath);
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
+
499
+ async function main() {
500
+ const { target, command, cwd, shell } = await readInput();
227
501
 
228
- if (!(await progressFile.exists())) {
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
+ }
229
518
  allow();
230
519
  }
231
520
 
521
+ // Allow writes inside the haren folder \u2014 planning/discovery phases write artifacts there
522
+ if (target && inside(target, harenDir)) allow();
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
+
535
+ if (process.env.HAREN_GATE === "off") allow();
536
+
537
+ const progressFile = Bun.file(resolve(harenDir, "progress.json"));
538
+ if (!(await progressFile.exists())) allow();
539
+
232
540
  const progress = await progressFile.json();
233
- const modules = progress.modules || {};
234
- const hasModules = Object.keys(modules).length > 0;
541
+ if (overrideActive(progress)) allow();
235
542
 
236
- const implementablePhases = ["planned", "implementing", "evaluating", "completed"];
237
- const hasImplementableModule = Object.values(modules).some(
238
- (m: any) => implementablePhases.includes(m.status || m.currentPhase)
543
+ const modules: Record<string, any> = progress.modules || {};
544
+ const hasModules = Object.keys(modules).length > 0;
545
+ const active = Object.entries(modules).filter(([, m]) =>
546
+ IMPLEMENTABLE.includes(m?.status || m?.currentPhase),
239
547
  );
240
548
 
241
- if (hasImplementableModule) {
242
- allow();
549
+ if (active.length === 0) {
550
+ const message = !hasModules
551
+ ? "No modules or discovery found. Run the discover phase first. Say \\"let's build X\\" or \\"start discovery\\" to begin. " + OVERRIDE_HINT
552
+ : "No module has reached 'planned' status yet. Run the plan phase on a module before writing code. " + OVERRIDE_HINT;
553
+ deny(message);
554
+ }
555
+
556
+ // No file path, or a file outside the workspace (temp files): legacy rule.
557
+ if (!target || !inside(target, workspaceDir)) allow();
558
+
559
+ const repos = await readRepos();
560
+ const roots: string[] = [];
561
+ const described: string[] = [];
562
+ for (const [name, m] of active) {
563
+ const keys: unknown = m?.repos;
564
+ if (!Array.isArray(keys) || keys.length === 0) allow(); // no repo info: allow all
565
+ const paths: string[] = [];
566
+ for (const key of keys) {
567
+ if (key === "default" || typeof key !== "string" || !repos[key]) allow();
568
+ paths.push(repos[key].path);
569
+ roots.push(realRoot(repos[key].path));
570
+ }
571
+ described.push(name + " (" + paths.join(", ") + ")");
572
+ }
573
+ for (const repo of Object.values(repos)) {
574
+ if (repo.role === "e2e") roots.push(realRoot(repo.path));
243
575
  }
244
576
 
245
- // No module is ready for implementation \u2014 block unconditionally
246
- const message = !hasModules
247
- ? "No modules or discovery found. Run the discover phase first. Say \\"let's build X\\" or \\"start discovery\\" to begin."
248
- : "No module has reached 'planned' status yet. Run the plan phase on a module before writing code.";
577
+ if (roots.some((root) => inside(target, root))) allow();
249
578
 
250
- deny(message);
579
+ deny(
580
+ "This file is outside the repos of the modules at 'planned' or later. Active modules: " +
581
+ described.join("; ") + ". " + OVERRIDE_HINT,
582
+ );
251
583
  }
252
584
 
253
585
  // Top-level await: on Windows, Bun exits early (code 0, no output) if main() is
@@ -312,9 +644,14 @@ function renderReposBlock(repos) {
312
644
  `;
313
645
  for (const field of REPO_FIELDS) {
314
646
  const value = repos[key][field];
315
- if (value)
647
+ if (typeof value === "boolean") {
648
+ if (value)
649
+ out += ` ${field}: true
650
+ `;
651
+ } else if (value) {
316
652
  out += ` ${field}: ${yamlScalar(value)}
317
653
  `;
654
+ }
318
655
  }
319
656
  }
320
657
  return out;
@@ -329,6 +666,13 @@ function toLf(text) {
329
666
  return text.replace(/\r\n/g, `
330
667
  `);
331
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
+ }
332
676
  function replaceTopLevelBlockLf(text, key, block) {
333
677
  const lines = text.split(`
334
678
  `);
@@ -350,6 +694,30 @@ ${block}`;
350
694
  return lines.join(`
351
695
  `);
352
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
+ }
353
721
  function migrateManifestText(text, mig) {
354
722
  const eol = eolOf(text);
355
723
  const lf = toLf(text);
@@ -379,7 +747,10 @@ project: ${yamlScalar(o.project)}
379
747
  mode: ${yamlScalar(o.mode)}
380
748
  language: ${yamlScalar(o.language)}
381
749
 
382
- ${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
+
383
754
  sources:
384
755
  # Mode-specific inputs
385
756
  # docs: ./artifacts/00-baseline/requirements.pdf
@@ -399,17 +770,148 @@ iterations:
399
770
  }
400
771
  return text;
401
772
  }
402
- 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
+ `;
403
828
  var init_manifest = __esm(() => {
404
- 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
+ ];
405
838
  YAML_KEYWORDS = /^(true|false|null|yes|no|on|off|~)$/i;
406
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"];
407
909
  });
408
910
 
409
911
  // src/plugins/manifest.ts
410
912
  import { existsSync as existsSync2 } from "fs";
411
913
  import { readFile } from "fs/promises";
412
- import { isAbsolute, join as join3 } from "path";
914
+ import { join as join3 } from "path";
413
915
  function stringList(value, field) {
414
916
  if (value === undefined)
415
917
  return [];
@@ -420,11 +922,8 @@ function stringList(value, field) {
420
922
  }
421
923
  function relativePathList(value, field) {
422
924
  const list = stringList(value, field);
423
- for (const p of list) {
424
- if (isAbsolute(p) || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split(/[\\/]/).includes("..")) {
425
- throw new Error(`Plugin manifest: ${field} path must stay inside the plugin: ${p}`);
426
- }
427
- }
925
+ for (const p of list)
926
+ assertInsidePlugin(p, field);
428
927
  return list;
429
928
  }
430
929
  function validateManifest(raw, packageVersion) {
@@ -435,8 +934,11 @@ function validateManifest(raw, packageVersion) {
435
934
  throw new Error("Plugin manifest: name is required");
436
935
  if (!NAME.test(m.name))
437
936
  throw new Error(`Plugin manifest: name must be kebab-case: ${m.name}`);
438
- if (m.harenApi !== HAREN_API) {
439
- 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"');
440
942
  }
441
943
  let version;
442
944
  if (packageVersion !== undefined) {
@@ -487,14 +989,15 @@ function validateManifest(raw, packageVersion) {
487
989
  return {
488
990
  name: m.name,
489
991
  version,
490
- harenApi: HAREN_API,
992
+ harenApi: m.harenApi,
491
993
  description: typeof m.description === "string" ? m.description : undefined,
492
994
  requires,
493
995
  setup: stringList(m.setup, "setup"),
494
996
  hooks,
495
997
  config,
496
998
  skills: relativePathList(m.skills, "skills"),
497
- agents: relativePathList(m.agents, "agents")
999
+ agents: relativePathList(m.agents, "agents"),
1000
+ ...m.adapter !== undefined ? { adapter: validateAdapter(m.adapter) } : {}
498
1001
  };
499
1002
  }
500
1003
  async function readInstalledManifest(dir) {
@@ -511,8 +1014,11 @@ async function readInstalledManifest(dir) {
511
1014
  }
512
1015
  return validateManifest(raw, packageVersion);
513
1016
  }
514
- var HAREN_API = "1", HOOK_NAMES, NAME;
1017
+ var HAREN_APIS, HOOK_NAMES, NAME;
515
1018
  var init_manifest2 = __esm(() => {
1019
+ init_adapter_spec();
1020
+ init_paths();
1021
+ HAREN_APIS = ["1", "2"];
516
1022
  HOOK_NAMES = ["session-start", "after-plan", "on-task-status"];
517
1023
  NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
518
1024
  });
@@ -534,7 +1040,12 @@ async function readPlugins(harenDir) {
534
1040
  const path = pluginsPath(harenDir);
535
1041
  if (!existsSync3(path))
536
1042
  return { version: 1, plugins: {} };
537
- 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
+ }
538
1049
  return { version: 1, plugins: data.plugins ?? {} };
539
1050
  }
540
1051
  async function writePlugins(harenDir, data) {
@@ -625,7 +1136,7 @@ function mergeClaudeSettings(existing, command) {
625
1136
  data.hooks ??= {};
626
1137
  data.hooks.PreToolUse = [
627
1138
  ...withoutGate(data.hooks.PreToolUse),
628
- { matcher: "Edit|Write", hooks: [{ type: "command", command }] }
1139
+ { matcher: "Edit|Write|Bash", hooks: [{ type: "command", command }] }
629
1140
  ];
630
1141
  return `${JSON.stringify(data, null, 2)}
631
1142
  `;
@@ -638,6 +1149,10 @@ function mergeCursorHooks(existing, command) {
638
1149
  ...withoutGate(data.hooks.beforeFileEdit),
639
1150
  { command, type: "command", timeout: 10 }
640
1151
  ];
1152
+ data.hooks.beforeShellExecution = [
1153
+ ...withoutGate(data.hooks.beforeShellExecution),
1154
+ { command, type: "command", timeout: 10 }
1155
+ ];
641
1156
  data.hooks.preToolUse = [
642
1157
  ...withoutGate(data.hooks.preToolUse),
643
1158
  { command, matcher: "write", type: "command", timeout: 10 }
@@ -1180,6 +1695,9 @@ var init_plan = __esm(() => {
1180
1695
 
1181
1696
  // src/workspace/progress.ts
1182
1697
  import { readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
1698
+ function phaseForStatus(status) {
1699
+ return STATUS_TO_PHASE[status];
1700
+ }
1183
1701
  async function readProgress(path) {
1184
1702
  const raw = await readFile5(path, "utf-8");
1185
1703
  const progress = JSON.parse(raw);
@@ -1189,6 +1707,10 @@ async function readProgress(path) {
1189
1707
  mod.features = {};
1190
1708
  if (!isObject(mod.lastCommit))
1191
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);
1192
1714
  }
1193
1715
  return progress;
1194
1716
  }
@@ -1198,6 +1720,28 @@ function isObject(value) {
1198
1720
  async function writeProgress(path, progress) {
1199
1721
  await writeFile4(path, JSON.stringify(progress, null, 2));
1200
1722
  }
1723
+ function updateModuleStatus(progress, moduleName, newStatus) {
1724
+ const mod = progress.modules[moduleName];
1725
+ if (!mod) {
1726
+ throw new Error(`Module '${moduleName}' not found in progress`);
1727
+ }
1728
+ const allowed = VALID_MODULE_TRANSITIONS[mod.status];
1729
+ if (!allowed.includes(newStatus)) {
1730
+ throw new Error(`Invalid module transition: ${mod.status} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1731
+ }
1732
+ return {
1733
+ ...progress,
1734
+ modules: {
1735
+ ...progress.modules,
1736
+ [moduleName]: {
1737
+ ...mod,
1738
+ status: newStatus,
1739
+ currentPhase: STATUS_TO_PHASE[newStatus],
1740
+ lastUpdated: new Date().toISOString()
1741
+ }
1742
+ }
1743
+ };
1744
+ }
1201
1745
  function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1202
1746
  const mod = progress.modules[moduleName];
1203
1747
  if (!mod) {
@@ -1226,27 +1770,122 @@ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1226
1770
  }
1227
1771
  };
1228
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
+ }
1229
1818
  function migrateProgress(raw, repoKeyFor) {
1230
1819
  if (!raw || typeof raw !== "object")
1231
1820
  return { progress: raw, changed: false };
1232
1821
  const data = raw;
1233
- if ((data.version ?? 1) >= PROGRESS_VERSION)
1822
+ const version = data.version ?? 1;
1823
+ if (version >= PROGRESS_VERSION)
1234
1824
  return { progress: raw, changed: false };
1235
1825
  const modules = {};
1236
1826
  for (const [name, mod] of Object.entries(data.modules ?? {})) {
1237
1827
  const old = mod?.lastCommit;
1238
1828
  let lastCommit = {};
1239
- if (typeof old === "string" && old)
1829
+ if (version < 2 && typeof old === "string" && old) {
1240
1830
  lastCommit = { [repoKeyFor(name) || "default"]: old };
1241
- 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")) {
1242
1832
  lastCommit = old;
1243
1833
  }
1244
- modules[name] = { ...mod, lastCommit };
1834
+ const units = isObject(mod?.units) ? mod.units : {};
1835
+ modules[name] = { ...isObject(mod) ? mod : {}, lastCommit, units };
1245
1836
  }
1246
1837
  return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
1247
1838
  }
1248
- var 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;
1249
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"];
1851
+ MODULE_STATUSES = [
1852
+ "discovered",
1853
+ "decomposed",
1854
+ "planned",
1855
+ "implementing",
1856
+ "evaluating",
1857
+ "completed",
1858
+ "released",
1859
+ "blocked"
1860
+ ];
1861
+ FEATURE_STATUSES = [
1862
+ "pending",
1863
+ "in-progress",
1864
+ "evaluating",
1865
+ "passing",
1866
+ "fixing",
1867
+ "blocked"
1868
+ ];
1869
+ VALID_MODULE_TRANSITIONS = {
1870
+ discovered: ["decomposed"],
1871
+ decomposed: ["planned"],
1872
+ planned: ["implementing"],
1873
+ implementing: ["evaluating", "blocked"],
1874
+ evaluating: ["implementing", "completed", "blocked"],
1875
+ completed: ["released"],
1876
+ released: [],
1877
+ blocked: ["implementing", "planned"]
1878
+ };
1879
+ STATUS_TO_PHASE = {
1880
+ discovered: "discover",
1881
+ decomposed: "decompose",
1882
+ planned: "plan",
1883
+ implementing: "implement",
1884
+ evaluating: "evaluate",
1885
+ completed: "evaluate",
1886
+ released: "release",
1887
+ blocked: "blocked"
1888
+ };
1250
1889
  VALID_FEATURE_TRANSITIONS = {
1251
1890
  pending: ["in-progress"],
1252
1891
  "in-progress": ["evaluating"],
@@ -1255,6 +1894,25 @@ var init_progress = __esm(() => {
1255
1894
  passing: [],
1256
1895
  blocked: ["in-progress"]
1257
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
+ };
1258
1916
  });
1259
1917
 
1260
1918
  // src/lib/version.ts
@@ -1442,7 +2100,7 @@ async function installPlugin(ref, ctx) {
1442
2100
  if (!official) {
1443
2101
  ctx.io.log("This plugin is not in the haren registry. Its hooks run as code with your user permissions.");
1444
2102
  if (!await ctx.io.confirm("Install it?"))
1445
- throw new Error("Plugin install cancelled");
2103
+ throw new Error(INSTALL_CANCELLED);
1446
2104
  }
1447
2105
  const manifest = await stage(source, ctx);
1448
2106
  try {
@@ -1519,7 +2177,7 @@ async function restorePlugins(ctx, report) {
1519
2177
  restored.push(manifest.name);
1520
2178
  } catch (err) {
1521
2179
  const message = err.message;
1522
- if (message === "Plugin install cancelled") {
2180
+ if (message === INSTALL_CANCELLED) {
1523
2181
  report.warn(`plugin ${name}: skipped, not confirmed. Run again with --yes to install it.`);
1524
2182
  } else {
1525
2183
  report.error(`plugin ${name}: ${message}`);
@@ -1551,7 +2209,7 @@ async function refreshPlugins(ctx, skip = []) {
1551
2209
  await writePlugins(ctx.harenDir, state);
1552
2210
  return warnings;
1553
2211
  }
1554
- var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming");
2212
+ var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming"), INSTALL_CANCELLED = "Plugin install cancelled";
1555
2213
  var init_install = __esm(() => {
1556
2214
  init_registry();
1557
2215
  init_source();
@@ -1577,7 +2235,7 @@ function readLine() {
1577
2235
  stdin.on("data", onData);
1578
2236
  });
1579
2237
  }
1580
- async function prompt(question, defaultValue) {
2238
+ async function prompt2(question, defaultValue) {
1581
2239
  const suffix = defaultValue ? ` \x1B[2m(${defaultValue})\x1B[0m` : "";
1582
2240
  process.stdout.write(` \x1B[36m?\x1B[0m ${question}${suffix} `);
1583
2241
  const value = await readLine();
@@ -1709,6 +2367,8 @@ function getDirectories(iterations) {
1709
2367
  "skills/update-links",
1710
2368
  "skills/update-tracking",
1711
2369
  "skills/generate-mockup",
2370
+ "skills/visual-companion",
2371
+ "skills/ui-review",
1712
2372
  "skills/onboard",
1713
2373
  "artifacts/_registry",
1714
2374
  "artifacts/00-baseline",
@@ -1784,6 +2444,7 @@ Master registry of all artifacts in this Haren workspace.
1784
2444
  await writeFile5(gitignore, `.agent.json
1785
2445
  .agent.pid
1786
2446
  .plugins/
2447
+ .companion/
1787
2448
  `);
1788
2449
  await writeGateScript(targetDir);
1789
2450
  await scaffoldSkillMd(targetDir);
@@ -1813,6 +2474,7 @@ You are operating within the Haren agentic SDLC framework.
1813
2474
  1. Read \`manifest.yaml\` to understand the project
1814
2475
  2. Read \`progress.json\` to understand current state
1815
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
1816
2478
  4. **Scan \`artifacts/00-baseline/\`** for documents (PDFs, docs, markdown, etc.)
1817
2479
  - If docs found and mode is \`undecided\` \u2192 auto-recommend \`blueprint\` mode
1818
2480
  - If docs found and discovery hasn't started \u2192 suggest starting discover phase
@@ -1825,8 +2487,11 @@ You are operating within the Haren agentic SDLC framework.
1825
2487
  - Has docs/specs \u2192 tell them to drop docs in \`artifacts/00-baseline/\` then \`blueprint\`
1826
2488
  - Starting from scratch, just an idea \u2192 \`explore\`
1827
2489
  - Has existing code \u2192 \`inherit\`
2490
+ - Rewrite of a legacy system with parity as the bar \u2192 \`migration\`
1828
2491
  6. Suggest next action based on current state
1829
2492
 
2493
+ Visual questions follow the ui mode in manifest.yaml (\`ui.mockups\`: ask | ascii | browser). See the visual-companion skill.
2494
+
1830
2495
  ## Available Actions
1831
2496
 
1832
2497
  | Intent | Skill | Agent |
@@ -1834,6 +2499,7 @@ You are operating within the Haren agentic SDLC framework.
1834
2499
  | Design a feature | discover/ (brainstorming) | Researcher |
1835
2500
  | Start a new project | discover/ | Researcher |
1836
2501
  | Research a topic | research/ | Researcher |
2502
+ | Extract legacy units into specs (migration) | extract/ | Researcher |
1837
2503
  | Break into modules | decompose/ | Architect |
1838
2504
  | Extract stories from docs | extract-stories/ | Researcher |
1839
2505
  | Plan a module | plan/ | Planner |
@@ -1841,21 +2507,37 @@ You are operating within the Haren agentic SDLC framework.
1841
2507
  | Evaluate a module | evaluate/ | Reviewer |
1842
2508
  | Check project status | read-context/ | \u2014 |
1843
2509
  | Search artifacts | search-artifact/ | \u2014 |
1844
- | Draw a UI wireframe | generate-mockup/ | \u2014 |
2510
+ | Release completed modules | release/ | Architect |
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 |
2514
+ | Update status, artifacts, events | update-tracking/ (\`haren track\`) | \u2014 |
1845
2515
  | Onboard to the project / check the workspace | onboard/ (\`/haren-onboard\`) | \u2014 |
1846
2516
 
1847
2517
  ## How to dispatch
1848
2518
 
1849
2519
  - User says "let's build X" or describes a new feature \u2192 discover/ skill (triggers brainstorming)
1850
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
1851
2522
  - User says "extract stories" or "break down the PRD" or "create stories from docs" \u2192 extract-stories/ skill
1852
2523
  - User says "let's work on {module}" \u2192 check module phase \u2192 dispatch appropriate skill
1853
2524
  - User says "I need to research X" \u2192 research/ skill
1854
2525
  - User says "status" or "where are we?" \u2192 read-context/ skill
1855
2526
  - User says "start" or "init" \u2192 discover/ skill
1856
2527
  - User asks about an artifact \u2192 search-artifact/ skill
2528
+ - User says "release", "deploy" or "ship {module}" \u2192 release/ skill (plans the order; never deploys by itself)
1857
2529
  - User runs \`/haren-onboard\`, is new to the project, or asks "is my workspace set up?" \u2192 onboard/ skill
1858
2530
 
2531
+ ## Phases
2532
+
2533
+ \`ideate\` \u2192 \`discover\` \u2192 \`research\` \u2192 \`decompose\` \u2192 \`plan\` \u2192 \`implement\` \u2192 \`evaluate\` \u2192 \`release\`. A module that is stuck is in \`blocked\`. These are also the allowed \`phase\` values in \`events/events.jsonl\`.
2534
+
2535
+ Module status: \`discovered \u2192 decomposed \u2192 planned \u2192 implementing \u2192 evaluating \u2192 completed \u2192 released\`.
2536
+
2537
+ ## Tracking
2538
+
2539
+ Change \`progress.json\`, \`events/events.jsonl\` and \`artifacts/_registry/artifact-index.md\` only with \`haren track\` (see update-tracking/ skill). Never edit them by hand, with sed or with jq.
2540
+
1859
2541
  ## Artifact Ownership
1860
2542
 
1861
2543
  | Artifact | Owner | Location |
@@ -1901,11 +2583,21 @@ When a skill says "read the master plan" or needs full module context, it means
1901
2583
  - **lastCommit:** \`modules.<module>.lastCommit\` maps a repo key to the last commit SHA that haren recorded, for example \`{ "backend": "abc1234" }\`. It is never a plain string. The key \`default\` comes from an old progress file. In the monorepo layout, it means the repo that holds this haren folder. In the workspace layout, it means the module's first repo.
1902
2584
  - Never push. Never create pull requests unless the user asks. Never clone repos \u2014 tell the user to run \`haren init\`.
1903
2585
 
2586
+ ### Dependent modules
2587
+
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:
2589
+
2590
+ - **A is merged:** create \`feat/<B>\` from the default branch as usual.
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.
2592
+ - **Monorepo layout:** both modules share one repository. When possible, merge A before you start B, so that B starts from the default branch.
2593
+ - Never merge B before A.
2594
+
1904
2595
  ## Rules
1905
2596
 
1906
2597
  - Always read progress.json before taking action
1907
- - Write outside this haren folder only in the module's repos (see "Repos and Git"), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`, or when the user explicitly asks
1908
- - Update progress.json after every phase transition
2598
+ - Write outside this haren folder only in the module's repos (see "Repos and Git"), only from the \`planned\` status on (implement phase) or when qa-engineer writes tests in \`$E2E\`, or when the user explicitly asks. For a user request outside the module flow (for example a hotfix), first run \`haren track override on --reason "<what the user asked>"\`, and run \`haren track override off\` when the change is done
2599
+ - The code gate allows code only inside the repos of modules at \`planned\` or later. Do not edit other repos without the override
2600
+ - Update progress.json after every phase transition with \`haren track status\`
1909
2601
  - Append to FEEDBACK.md when you encounter framework friction
1910
2602
  - Validate artifacts before phase transitions (validate-artifact/ skill)
1911
2603
  `);
@@ -1948,7 +2640,7 @@ function parseInitArgs(args) {
1948
2640
  break;
1949
2641
  case "--mode":
1950
2642
  if (!MODES.includes(value)) {
1951
- 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.`);
1952
2644
  }
1953
2645
  out.mode = value;
1954
2646
  i++;
@@ -2096,10 +2788,10 @@ async function promptIterations() {
2096
2788
  }, "no");
2097
2789
  if (enable !== "yes")
2098
2790
  return;
2099
- const duration = await prompt("Iteration duration:", "2 weeks");
2791
+ const duration = await prompt2("Iteration duration:", "2 weeks");
2100
2792
  const today = new Date().toISOString().split("T")[0];
2101
- const startDate = await prompt("Start date:", today);
2102
- const demoDay = await prompt("Demo day:", "Friday");
2793
+ const startDate = await prompt2("Start date:", today);
2794
+ const demoDay = await prompt2("Demo day:", "Friday");
2103
2795
  return { enabled: true, duration, startDate, demoDay };
2104
2796
  }
2105
2797
  async function runSetup(location, opts) {
@@ -2225,15 +2917,15 @@ async function init(args) {
2225
2917
  }, "workspace") : "workspace");
2226
2918
  console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
2227
2919
  console.log("");
2228
- 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");
2229
2921
  const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join10(rootDir, harenDirName);
2230
2922
  const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
2231
2923
  const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
2232
2924
  let selected = defaults;
2233
- 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));
2234
2926
  const existingMode = MODES.find((m) => m === existingManifest?.mode);
2235
2927
  const mode = opts.mode ?? existingMode ?? (interactive ? await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided") : "undecided");
2236
- 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");
2237
2929
  const iterations = opts.iterations ?? (existingManifest ? manifestIterations(existingManifest) : interactive ? await promptIterations() : undefined);
2238
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");
2239
2931
  while (true) {
@@ -2306,7 +2998,7 @@ var init_init = __esm(() => {
2306
2998
  init_version();
2307
2999
  init_install();
2308
3000
  init_registry();
2309
- MODES = ["blueprint", "explore", "inherit", "undecided"];
3001
+ MODES = ["blueprint", "explore", "inherit", "migration", "undecided"];
2310
3002
  EDITORS = ["claude-code", "cursor", "both"];
2311
3003
  EDITOR_DESCRIPTIONS = {
2312
3004
  "claude-code": "Claude Code CLI / IDE extension",
@@ -2317,6 +3009,7 @@ var init_init = __esm(() => {
2317
3009
  blueprint: "Greenfield project with existing docs",
2318
3010
  explore: "Greenfield project from scratch",
2319
3011
  inherit: "Brownfield project with existing code",
3012
+ migration: "Rewrite of a legacy system with parity as the bar",
2320
3013
  undecided: "Decide later \u2014 LLM will help you choose"
2321
3014
  };
2322
3015
  });
@@ -2385,7 +3078,7 @@ async function planMigration(location) {
2385
3078
  if (result.changed) {
2386
3079
  progress = { before, after: `${JSON.stringify(result.progress, null, 2)}
2387
3080
  ` };
2388
- 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)");
2389
3082
  }
2390
3083
  }
2391
3084
  const gitignore = await planGitignore(harenDir);
@@ -2553,7 +3246,7 @@ var init_upgrade = __esm(() => {
2553
3246
  init_root_files();
2554
3247
  init_install();
2555
3248
  init_templates();
2556
- IGNORED = [".agent.json", ".agent.pid", ".plugins/"];
3249
+ IGNORED = [".agent.json", ".agent.pid", ".plugins/", ".companion/"];
2557
3250
  FRAMEWORK_DIRS = ["agents", "skills", "templates"];
2558
3251
  USER_FILES = ["FEEDBACK.md", "artifacts/", "events/"];
2559
3252
  });
@@ -2654,8 +3347,8 @@ var init_artifact_reader = __esm(() => {
2654
3347
  });
2655
3348
 
2656
3349
  // src/agent/cli-executor.ts
2657
- async function executeCLI(cli, prompt, onOutput) {
2658
- const args = buildCLIArgs(cli, prompt);
3350
+ async function executeCLI(cli, prompt2, onOutput) {
3351
+ const args = buildCLIArgs(cli, prompt2);
2659
3352
  try {
2660
3353
  const proc = Bun.spawn(args, {
2661
3354
  stdout: "pipe",
@@ -2687,27 +3380,43 @@ async function executeCLI(cli, prompt, onOutput) {
2687
3380
  onOutput("", true);
2688
3381
  }
2689
3382
  }
2690
- function buildCLIArgs(cli, prompt) {
3383
+ function buildCLIArgs(cli, prompt2) {
2691
3384
  switch (cli) {
2692
3385
  case "claude":
2693
- return ["claude", "--print", prompt];
3386
+ return ["claude", "--print", prompt2];
2694
3387
  case "cursor":
2695
- return ["cursor", "--prompt", prompt];
3388
+ return ["cursor", "--prompt", prompt2];
2696
3389
  case "github-copilot-cli":
2697
- return ["github-copilot-cli", prompt];
3390
+ return ["github-copilot-cli", prompt2];
2698
3391
  default:
2699
- return [cli, prompt];
3392
+ return [cli, prompt2];
2700
3393
  }
2701
3394
  }
2702
3395
 
2703
3396
  // src/workspace/events.ts
2704
3397
  import { appendFile, readFile as readFile10 } from "fs/promises";
3398
+ function isEventPhase(value) {
3399
+ return typeof value === "string" && EVENT_PHASES.includes(value);
3400
+ }
2705
3401
  async function appendEvent(path, event) {
2706
3402
  const line = JSON.stringify(event) + `
2707
3403
  `;
2708
3404
  await appendFile(path, line);
2709
3405
  }
2710
- var init_events = () => {};
3406
+ var EVENT_PHASES;
3407
+ var init_events = __esm(() => {
3408
+ EVENT_PHASES = [
3409
+ "ideate",
3410
+ "discover",
3411
+ "research",
3412
+ "decompose",
3413
+ "plan",
3414
+ "implement",
3415
+ "evaluate",
3416
+ "release",
3417
+ "blocked"
3418
+ ];
3419
+ });
2711
3420
 
2712
3421
  // src/agent/request-handler.ts
2713
3422
  function handleServerMessage(msg, config, send) {
@@ -2744,7 +3453,7 @@ async function handleDataRequest(requestId, path, harenDir, send) {
2744
3453
  }
2745
3454
  send({ type: "data-response", requestId, data });
2746
3455
  }
2747
- async function handleCommand(commandId, prompt, cli, config, send) {
3456
+ async function handleCommand(commandId, prompt2, cli, config, send) {
2748
3457
  const { mkdir } = await import("fs/promises");
2749
3458
  await mkdir(`${config.harenDir}/events`, { recursive: true });
2750
3459
  await Promise.resolve().then(() => init_events());
@@ -2753,10 +3462,10 @@ async function handleCommand(commandId, prompt, cli, config, send) {
2753
3462
  type: "agent-command",
2754
3463
  timestamp: new Date().toISOString(),
2755
3464
  cli,
2756
- prompt,
3465
+ prompt: prompt2,
2757
3466
  commandId
2758
3467
  });
2759
- await executeCLI(cli, prompt, (chunk, done) => {
3468
+ await executeCLI(cli, prompt2, (chunk, done) => {
2760
3469
  send({ type: "command-output", commandId, chunk, done });
2761
3470
  });
2762
3471
  }
@@ -3505,7 +4214,8 @@ async function plugin(args) {
3505
4214
  try {
3506
4215
  await installPlugin(opts.target, ctx);
3507
4216
  } catch (err) {
3508
- 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}`);
3509
4219
  process.exit(1);
3510
4220
  }
3511
4221
  await syncEditors();
@@ -3570,24 +4280,2226 @@ var init_plugin = __esm(() => {
3570
4280
  SUBS = ["add", "remove", "list", "run", "doctor"];
3571
4281
  });
3572
4282
 
3573
- // src/index.ts
3574
- function parseArgs(args) {
3575
- if (args.length === 0) {
3576
- return { command: "help", args: [] };
3577
- }
3578
- const command = args[0];
3579
- const rest = args.slice(1);
3580
- if (rest.includes("--help") || rest.includes("-h")) {
3581
- return { command: "help", args: [] };
4283
+ // src/plugins/adapter-read.ts
4284
+ import { existsSync as existsSync15 } from "fs";
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)}`);
3582
4300
  }
3583
- switch (command) {
3584
- case "--help":
3585
- case "-h":
3586
- return { command: "help", args: [] };
3587
- case "init":
3588
- case "upgrade":
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";
4311
+ function parseTrackArgs(args) {
4312
+ const positional = [];
4313
+ const flags = {};
4314
+ for (let i = 0;i < args.length; i++) {
4315
+ const arg = args[i];
4316
+ if (arg.startsWith("--")) {
4317
+ const eq = arg.indexOf("=");
4318
+ const name = eq === -1 ? arg : arg.slice(0, eq);
4319
+ if (!VALUE_FLAGS.includes(name))
4320
+ throw new Error(`Unknown option: ${name}`);
4321
+ const value = eq === -1 ? args[++i] : arg.slice(eq + 1);
4322
+ if (value === undefined)
4323
+ throw new Error(`${name} needs a value`);
4324
+ flags[name.slice(2)] = value;
4325
+ } else {
4326
+ positional.push(arg);
4327
+ }
4328
+ }
4329
+ return { positional, flags };
4330
+ }
4331
+ function pathsFor(harenDir) {
4332
+ return {
4333
+ harenDir,
4334
+ progress: join19(harenDir, "progress.json"),
4335
+ events: join19(harenDir, "events", "events.jsonl"),
4336
+ registry: join19(harenDir, "artifacts", "_registry", "artifact-index.md")
4337
+ };
4338
+ }
4339
+ async function emit(paths, event) {
4340
+ await mkdir9(dirname5(paths.events), { recursive: true });
4341
+ await appendEvent(paths.events, { ...event, timestamp: new Date().toISOString() });
4342
+ }
4343
+ function need(value, what) {
4344
+ if (value === undefined || value === "")
4345
+ throw new Error(`Missing ${what}.
4346
+ ${TRACK_USAGE}`);
4347
+ return value;
4348
+ }
4349
+ function requireModule(progress, name) {
4350
+ if (!progress.modules[name]) {
4351
+ const known = Object.keys(progress.modules);
4352
+ throw new Error(`Unknown module '${name}'. Known modules: ${known.length ? known.join(", ") : "(none)"}`);
4353
+ }
4354
+ }
4355
+ async function loadProgress(paths) {
4356
+ if (!existsSync16(paths.progress))
4357
+ throw new Error(`No progress.json in ${paths.harenDir}`);
4358
+ return readProgress(paths.progress);
4359
+ }
4360
+ async function track(args, cwd = process.cwd()) {
4361
+ const { positional, flags } = parseTrackArgs(args);
4362
+ const [sub, ...rest] = positional;
4363
+ if (!sub) {
4364
+ console.log(TRACK_USAGE);
4365
+ return;
4366
+ }
4367
+ const location = await resolveHarenDir(cwd, {
4368
+ harenDir: harenDirFlag(args),
4369
+ env: process.env
4370
+ });
4371
+ if (!location)
4372
+ throw new Error("No haren folder found. Run `haren init` first.");
4373
+ const paths = pathsFor(location.harenDir);
4374
+ switch (sub) {
4375
+ case "status":
4376
+ return trackStatus(paths, rest, flags);
4377
+ case "feature":
4378
+ return trackFeature(paths, rest);
4379
+ case "unit":
4380
+ return trackUnit(paths, rest);
4381
+ case "commit":
4382
+ return trackCommit(paths, rest);
4383
+ case "depends":
4384
+ return trackDepends(paths, rest);
4385
+ case "artifact":
4386
+ return trackArtifact(paths, rest, flags);
4387
+ case "event":
4388
+ return trackEvent(paths, rest, flags);
4389
+ case "override":
4390
+ return trackOverride(paths, rest, flags);
4391
+ case "ui-mode":
4392
+ return trackUiMode(paths, rest);
4393
+ case "check":
4394
+ return trackCheck(paths);
4395
+ default:
4396
+ throw new Error(`Unknown track command: ${sub}
4397
+ ${TRACK_USAGE}`);
4398
+ }
4399
+ }
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) {
4479
+ const module = need(rest[0], "<module>");
4480
+ const to = need(rest[1], "<status>");
4481
+ if (!MODULE_STATUSES.includes(to)) {
4482
+ throw new Error(`Invalid module status '${to}'. Allowed: ${MODULE_STATUSES.join(", ")}`);
4483
+ }
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
+ }
4497
+ let next;
4498
+ let from = null;
4499
+ if (!progress.modules[module]) {
4500
+ if (to !== "discovered" && to !== "decomposed") {
4501
+ throw new Error(`Unknown module '${module}'. A new module can start only at 'discovered' or 'decomposed'.`);
4502
+ }
4503
+ next = {
4504
+ ...progress,
4505
+ modules: {
4506
+ ...progress.modules,
4507
+ [module]: {
4508
+ status: to,
4509
+ currentPhase: phaseForStatus(to),
4510
+ features: {},
4511
+ lastCommit: {},
4512
+ ...meta,
4513
+ lastUpdated: new Date().toISOString()
4514
+ }
4515
+ }
4516
+ };
4517
+ } else {
4518
+ from = progress.modules[module].status;
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
+ };
4527
+ }
4528
+ await writeProgress(paths.progress, next);
4529
+ await emit(paths, { type: "module-status", module, from, to, phase: phaseForStatus(to) });
4530
+ console.log(` ${module}: ${from ?? "(new)"} \u2192 ${to}`);
4531
+ }
4532
+ async function trackFeature(paths, rest) {
4533
+ const module = need(rest[0], "<module>");
4534
+ const feature = need(rest[1], "<feature>");
4535
+ const to = rest[2];
4536
+ const progress = await loadProgress(paths);
4537
+ requireModule(progress, module);
4538
+ const mod = progress.modules[module];
4539
+ let next;
4540
+ let from = null;
4541
+ if (to === undefined) {
4542
+ if (mod.features[feature] !== undefined) {
4543
+ throw new Error(`Feature '${feature}' already exists in module '${module}'`);
4544
+ }
4545
+ next = {
4546
+ ...progress,
4547
+ modules: {
4548
+ ...progress.modules,
4549
+ [module]: {
4550
+ ...mod,
4551
+ features: { ...mod.features, [feature]: "pending" },
4552
+ lastUpdated: new Date().toISOString()
4553
+ }
4554
+ }
4555
+ };
4556
+ } else {
4557
+ if (!FEATURE_STATUSES.includes(to)) {
4558
+ throw new Error(`Invalid feature status '${to}'. Allowed: ${FEATURE_STATUSES.join(", ")}`);
4559
+ }
4560
+ from = mod.features[feature] ?? null;
4561
+ next = updateFeatureStatus(progress, module, feature, to);
4562
+ }
4563
+ const status = to ?? "pending";
4564
+ await writeProgress(paths.progress, next);
4565
+ await emit(paths, { type: "feature-status", module, feature, from, to: status });
4566
+ console.log(` ${module}/${feature}: ${from ?? "(new)"} \u2192 ${status}`);
4567
+ }
4568
+ async function trackCommit(paths, rest) {
4569
+ const module = need(rest[0], "<module>");
4570
+ const repo = need(rest[1], "<repoKey>");
4571
+ const sha = need(rest[2], "<sha>");
4572
+ const progress = await loadProgress(paths);
4573
+ requireModule(progress, module);
4574
+ const mod = progress.modules[module];
4575
+ const repos = Array.isArray(mod.repos) ? mod.repos : [];
4576
+ const next = {
4577
+ ...progress,
4578
+ modules: {
4579
+ ...progress.modules,
4580
+ [module]: {
4581
+ ...mod,
4582
+ lastCommit: { ...mod.lastCommit, [repo]: sha },
4583
+ branch: mod.branch || `feat/${module}`,
4584
+ repos: repos.includes(repo) ? repos : [...repos, repo],
4585
+ lastUpdated: new Date().toISOString()
4586
+ }
4587
+ }
4588
+ };
4589
+ await writeProgress(paths.progress, next);
4590
+ await emit(paths, { type: "commit", module, repo, sha });
4591
+ console.log(` ${module}: lastCommit.${repo} = ${sha}`);
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
+ }
4629
+ function upsertArtifactRow(text, cells) {
4630
+ const row = `| ${cells.map((c) => c.replaceAll("|", "\\|")).join(" | ")} |`;
4631
+ const lines = text.split(`
4632
+ `);
4633
+ let lastRow = -1;
4634
+ for (let i = 0;i < lines.length; i++) {
4635
+ const line = lines[i].trim();
4636
+ if (!line.startsWith("|"))
4637
+ continue;
4638
+ lastRow = i;
4639
+ const id = line.slice(1).split("|")[0].trim();
4640
+ if (id === cells[0]) {
4641
+ lines[i] = row;
4642
+ return lines.join(`
4643
+ `);
4644
+ }
4645
+ }
4646
+ if (lastRow === -1) {
4647
+ const base = text.trimEnd();
4648
+ return `${base ? base + `
4649
+
4650
+ ` : ""}${REGISTRY_HEADER}
4651
+ ${row}
4652
+ `;
4653
+ }
4654
+ lines.splice(lastRow + 1, 0, row);
4655
+ return lines.join(`
4656
+ `);
4657
+ }
4658
+ async function trackArtifact(paths, rest, flags) {
4659
+ const id = need(rest[0], "<id>");
4660
+ const artifactType = need(flags.type, "--type <type>");
4661
+ const path = need(flags.path, "--path <path>");
4662
+ const module = flags.module ?? "-";
4663
+ const status = flags.status ?? "draft";
4664
+ if (flags.module) {
4665
+ const progress = await loadProgress(paths);
4666
+ requireModule(progress, flags.module);
4667
+ }
4668
+ const existing = existsSync16(paths.registry) ? await readFile13(paths.registry, "utf-8") : "";
4669
+ await mkdir9(dirname5(paths.registry), { recursive: true });
4670
+ await writeFile7(paths.registry, upsertArtifactRow(existing, [id, artifactType, module, status, path]));
4671
+ await emit(paths, {
4672
+ type: "artifact",
4673
+ id,
4674
+ artifactType,
4675
+ path,
4676
+ status,
4677
+ ...flags.module ? { module: flags.module } : {}
4678
+ });
4679
+ console.log(` artifact ${id} \u2192 ${path}`);
4680
+ }
4681
+ async function trackEvent(paths, rest, flags) {
4682
+ const type = need(rest[0], "<type>");
4683
+ if (flags.phase !== undefined && !isEventPhase(flags.phase)) {
4684
+ throw new Error(`Invalid phase '${flags.phase}'. Allowed: ${EVENT_PHASES.join(", ")}`);
4685
+ }
4686
+ let data = {};
4687
+ if (flags.data !== undefined) {
4688
+ let parsed;
4689
+ try {
4690
+ parsed = JSON.parse(flags.data);
4691
+ } catch {
4692
+ throw new Error("--data must be a JSON object");
4693
+ }
4694
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
4695
+ throw new Error("--data must be a JSON object");
4696
+ }
4697
+ data = parsed;
4698
+ }
4699
+ const event = { ...data, type };
4700
+ if (flags.module)
4701
+ event.module = flags.module;
4702
+ if (flags.phase)
4703
+ event.phase = flags.phase;
4704
+ if (flags.feature)
4705
+ event.feature = flags.feature;
4706
+ await emit(paths, event);
4707
+ console.log(` event ${type}`);
4708
+ }
4709
+ async function trackOverride(paths, rest, flags) {
4710
+ const action = need(rest[0], "on|off");
4711
+ const progress = await loadProgress(paths);
4712
+ if (action === "on") {
4713
+ const reason = need(flags.reason, '--reason "<text>"');
4714
+ const hours = flags.hours === undefined ? 2 : Number(flags.hours);
4715
+ if (!Number.isFinite(hours) || hours <= 0) {
4716
+ throw new Error("--hours must be a positive number");
4717
+ }
4718
+ const until = new Date(Date.now() + hours * 3600000).toISOString();
4719
+ await writeProgress(paths.progress, { ...progress, gateOverride: { reason, until } });
4720
+ await emit(paths, { type: "gate-override", action: "on", reason, until });
4721
+ console.log(` Gate override on until ${until}. Run \`haren track override off\` when done.`);
4722
+ } else if (action === "off") {
4723
+ const { gateOverride: _removed, ...next } = progress;
4724
+ await writeProgress(paths.progress, next);
4725
+ await emit(paths, { type: "gate-override", action: "off" });
4726
+ console.log(" Gate override off.");
4727
+ } else {
4728
+ throw new Error(`Unknown override action '${action}'. Use on or off.`);
4729
+ }
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
+ }
4862
+ var TRACK_USAGE = `Usage:
4863
+ haren track status <module> <status> [--branch <name>] [--repos <key1,key2>]
4864
+ haren track feature <module> <feature> [status]
4865
+ haren track unit <module> <unit> <status>
4866
+ haren track commit <module> <repoKey> <sha>
4867
+ haren track depends <module> [dep ...]
4868
+ haren track artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]
4869
+ haren track event <type> [--module m] [--phase p] [--feature f] [--data '<json object>']
4870
+ haren track override on --reason "<text>" [--hours <n>]
4871
+ haren track override off
4872
+ haren track ui-mode <ask|ascii|browser>
4873
+ haren track check
4874
+ Options: --haren-dir <path>`, VALUE_FLAGS, REGISTRY_HEADER = `| ID | Type | Module | Status | Path |
4875
+ |----|------|--------|--------|------|`, UNTRACKED_DIRS;
4876
+ var init_track = __esm(() => {
4877
+ init_manifest();
4878
+ init_events();
4879
+ init_progress();
4880
+ init_adapter_read();
4881
+ init_resolve();
4882
+ VALUE_FLAGS = [
4883
+ "--haren-dir",
4884
+ "--type",
4885
+ "--path",
4886
+ "--module",
4887
+ "--status",
4888
+ "--phase",
4889
+ "--feature",
4890
+ "--data",
4891
+ "--reason",
4892
+ "--hours",
4893
+ "--branch",
4894
+ "--repos"
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"]);
6479
+ });
6480
+
6481
+ // src/index.ts
6482
+ init_exit_code();
6483
+ function parseArgs(args) {
6484
+ if (args.length === 0) {
6485
+ return { command: "help", args: [] };
6486
+ }
6487
+ const command = args[0];
6488
+ const rest = args.slice(1);
6489
+ if (rest.includes("--help") || rest.includes("-h")) {
6490
+ return { command: "help", args: [] };
6491
+ }
6492
+ switch (command) {
6493
+ case "--help":
6494
+ case "-h":
6495
+ return { command: "help", args: [] };
6496
+ case "init":
6497
+ case "upgrade":
3589
6498
  case "agent":
3590
6499
  case "plugin":
6500
+ case "track":
6501
+ case "migrate":
6502
+ case "companion":
3591
6503
  return { command, args: rest };
3592
6504
  default:
3593
6505
  return { command: "unknown", args };
@@ -3617,27 +6529,58 @@ async function main() {
3617
6529
  await plugin(parsed.args);
3618
6530
  break;
3619
6531
  }
6532
+ case "track": {
6533
+ await Promise.resolve().then(() => init_track());
6534
+ await track(parsed.args);
6535
+ break;
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
+ }
3620
6547
  case "help":
3621
6548
  console.log("Usage:");
3622
6549
  console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
3623
6550
  console.log(" --dir <path> --layout monorepo|workspace --haren-dir <name>");
6551
+ console.log(" --mode <undecided|explore|blueprint|inherit|migration>");
3624
6552
  console.log(" --yes|-y --dry-run --force");
3625
6553
  console.log(" --plugin <name|source> (repeatable)");
3626
6554
  console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run, --yes)");
3627
6555
  console.log(" haren agent Manage local agent (start, stop, status)");
3628
6556
  console.log(" haren plugin Manage plugins (add, remove, list, run, doctor)");
6557
+ console.log(" haren track Record progress and events:");
6558
+ console.log(" status <module> <status> [--branch <name>] [--repos <key1,key2>]");
6559
+ console.log(" feature <module> <feature> [status]");
6560
+ console.log(" commit <module> <repoKey> <sha>");
6561
+ console.log(" depends <module> [dep ...] (replace the dependency list)");
6562
+ console.log(" artifact <id> --type <type> --path <path> [--module <m>] [--status <s>]");
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>");
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");
3629
6571
  break;
3630
6572
  case "unknown":
3631
6573
  console.error(`Unknown command: ${parsed.args[0]}`);
3632
- console.log("Usage: haren init | haren upgrade");
6574
+ console.log("Usage: haren init | upgrade | agent | plugin | track | migrate | companion (haren --help)");
3633
6575
  process.exit(1);
3634
6576
  }
3635
6577
  }
3636
6578
  main().catch((err) => {
3637
6579
  const debug = process.env.HAREN_DEBUG === "1";
3638
6580
  const message = err instanceof Error ? debug && err.stack || err.message : String(err);
3639
- console.error(` ${message}`);
3640
- process.exit(1);
6581
+ if (message)
6582
+ console.error(` ${message}`);
6583
+ process.exit(err instanceof ExitCode ? err.code : 1);
3641
6584
  });
3642
6585
  export {
3643
6586
  parseArgs