@odarino/haren 1.1.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,32 +1,16 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var __create = Object.create;
4
- var __getProtoOf = Object.getPrototypeOf;
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __toESM = (mod, isNodeMode, target) => {
9
- target = mod != null ? __create(__getProtoOf(mod)) : {};
10
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
- for (let key of __getOwnPropNames(mod))
12
- if (!__hasOwnProp.call(to, key))
13
- __defProp(to, key, {
14
- get: () => mod[key],
15
- enumerable: true
16
- });
17
- return to;
18
- };
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, {
22
- get: all[name],
23
- enumerable: true,
24
- configurable: true,
25
- set: (newValue) => all[name] = () => newValue
26
- });
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
27
13
  };
28
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
29
- var __require = import.meta.require;
30
14
 
31
15
  // src/lib/content-dir.ts
32
16
  import { existsSync } from "fs";
@@ -46,24 +30,925 @@ function resolveContentDir(candidates) {
46
30
  }
47
31
  var init_content_dir = () => {};
48
32
 
49
- // src/commands/init.ts
50
- var exports_init = {};
51
- __export(exports_init, {
52
- scaffoldWorkspace: () => scaffoldWorkspace,
53
- scaffoldSkillMd: () => scaffoldSkillMd,
54
- init: () => init
33
+ // src/workspace/templates.ts
34
+ import { mkdir, writeFile } from "fs/promises";
35
+ import { join as join2 } from "path";
36
+ function renderTemplate(template, harenDirName) {
37
+ return template.replaceAll(HAREN_DIR_TOKEN, harenDirName);
38
+ }
39
+ function gateCommand(harenDirName) {
40
+ return `bun ${harenDirName}/hooks/brainstorm-gate.ts`;
41
+ }
42
+ async function writeGateScript(harenDir) {
43
+ await mkdir(join2(harenDir, "hooks"), { recursive: true });
44
+ await writeFile(join2(harenDir, GATE_SCRIPT_PATH), brainstormGateScript);
45
+ }
46
+ var HAREN_DIR_TOKEN = "{{harenDir}}", editorConfigTemplate = `## Haren Framework
47
+
48
+ This workspace uses the Haren agentic SDLC framework.
49
+
50
+ **On every session start, you MUST:**
51
+ 1. Read \`{{harenDir}}/skill.md\` \u2014 this is your operating manual
52
+ 2. Follow its instructions for session orientation
53
+ 3. Read \`{{harenDir}}/manifest.yaml\` and \`{{harenDir}}/progress.json\` before taking any action
54
+
55
+ 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.
57
+
58
+ ## Brainstorming Gate
59
+
60
+ 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
67
+
68
+ Design specs are written to Haren artifact folders, NOT to docs/superpowers/specs/.
69
+ `, cursorRuleTemplate = `---
70
+ description: Haren agentic SDLC framework - project workflow and artifact management
71
+ globs:
72
+ - {{harenDir}}/**
73
+ - .cursorrules
74
+ alwaysApply: true
75
+ ---
76
+
77
+ # Haren Framework \u2014 MANDATORY RULES
78
+
79
+ ## RULE #1: NEVER WRITE WITHOUT ASKING (highest priority)
80
+
81
+ **You MUST ask the user questions and get answers BEFORE writing ANY artifact or code.**
82
+
83
+ This applies to ALL phases \u2014 planning, designing, implementing, everything.
84
+
85
+ **The process is ALWAYS:**
86
+ 1. Read existing artifacts (spec.md, module.md, context-brief.md, architecture.md)
87
+ 2. Identify unresolved decisions
88
+ 3. **ASK the user one question at a time \u2014 present 2-3 options with trade-offs**
89
+ 4. **WAIT for the user's answer**
90
+ 5. Repeat until ALL decisions are resolved
91
+ 6. **ONLY THEN write files**
92
+
93
+ **NEVER do this:**
94
+ - Write artifacts first, then say "let me know if you want changes" \u2014 WRONG
95
+ - Make assumptions about technical decisions \u2014 WRONG
96
+ - Dump all questions at once \u2014 WRONG, ask ONE at a time
97
+ - Skip asking because you think the answer is obvious \u2014 WRONG
98
+
99
+ **If you are about to call the write/edit tool and you have not asked the user any questions yet in this conversation, STOP. You are violating this rule.**
100
+
101
+ ---
102
+
103
+ ## RULE #2: Code Gate \u2014 No code outside \`{{harenDir}}/\` without \`planned\` status
104
+
105
+ **BEFORE writing ANY file outside \`{{harenDir}}/\`, check \`{{harenDir}}/progress.json\`:**
106
+
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
111
+
112
+ **When blocked, respond ONLY with:**
113
+ - No modules: "No modules found. Run the discover phase first."
114
+ - No planned modules: "No module has reached 'planned' status yet. Run the plan phase first."
115
+
116
+ No exceptions. No rationalizing. STOP means STOP.
117
+
118
+ ---
119
+
120
+ ## On Every Session Start
121
+
122
+ 1. Read \`{{harenDir}}/skill.md\` \u2014 this is your operating manual
123
+ 2. Follow its instructions for session orientation
124
+ 3. Read \`{{harenDir}}/manifest.yaml\` and \`{{harenDir}}/progress.json\` before taking any action
125
+
126
+ 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.
128
+
129
+ ## Phase Progression (MANDATORY)
130
+
131
+ Modules MUST progress through phases in order. You CANNOT skip phases.
132
+
133
+ \`\`\`
134
+ discovered \u2192 specified \u2192 planned \u2192 implementing \u2192 evaluating \u2192 completed
135
+ \`\`\`
136
+
137
+ **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
+
139
+ 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\`)
141
+ - Module at \`discovered\` or no module \u2192 user says "plan" or "build" \u2192 you MUST run \`discover/\` skill first (brainstorming)
142
+ - Module at \`planned\` \u2192 user says "implement" or "build" \u2192 proceed with implementation
143
+ - **You CANNOT jump from \`specified\` directly to \`implementing\`**
144
+ - **You CANNOT skip brainstorming/discovery for new features**
145
+
146
+ ## Rules
147
+
148
+ - 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.
150
+ - Update progress.json after every phase transition
151
+ - Append to FEEDBACK.md when you encounter framework friction
152
+ `, GATE_SCRIPT_PATH = "hooks/brainstorm-gate.ts", brainstormGateScript = `/**
153
+ * Brainstorm Gate Hook
154
+ * Blocks Edit/Write tool use if no module has reached 'planned' status.
155
+ *
156
+ * Works with both Claude Code and Cursor:
157
+ * - Exit 0 = allow
158
+ * - Exit 2 = block
159
+ * - Other exit codes = hook failure, action proceeds (fail-open)
160
+ */
161
+
162
+ import { existsSync, realpathSync } from "fs";
163
+ import { basename, dirname, join, resolve, sep } from "path";
164
+
165
+ // The hook lives in <harenDir>/hooks/, so the haren folder is one level up.
166
+ // This works for any folder name. Use the real path so symlinks compare equal.
167
+ const harenDir = realpathSync(resolve(import.meta.dir, ".."));
168
+
169
+ // Editors send logical paths that can go through symlinks. Resolve the nearest
170
+ // existing ancestor to its real path, then add back the missing segments.
171
+ function realTarget(abs: string): string {
172
+ const rest: string[] = [];
173
+ let dir = abs;
174
+ while (!existsSync(dir) && dirname(dir) !== dir) {
175
+ rest.unshift(basename(dir));
176
+ dir = dirname(dir);
177
+ }
178
+ try {
179
+ return join(realpathSync(dir), ...rest);
180
+ } catch {
181
+ return abs;
182
+ }
183
+ }
184
+
185
+ function allow() {
186
+ console.log(JSON.stringify({
187
+ allow: true, // Claude Code
188
+ permission: "allow", // Cursor
189
+ }));
190
+ process.exit(0);
191
+ }
192
+
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
+ }));
200
+ process.exit(2);
201
+ }
202
+
203
+ async function main() {
204
+ // Allow writes inside the haren folder \u2014 planning/discovery phases write artifacts there
205
+ 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
+ }
219
+ }
220
+ }
221
+ } catch {
222
+ // stdin parse failed \u2014 continue with gate check
223
+ }
224
+
225
+ const progressPath = resolve(harenDir, "progress.json");
226
+ const progressFile = Bun.file(progressPath);
227
+
228
+ if (!(await progressFile.exists())) {
229
+ allow();
230
+ }
231
+
232
+ const progress = await progressFile.json();
233
+ const modules = progress.modules || {};
234
+ const hasModules = Object.keys(modules).length > 0;
235
+
236
+ const implementablePhases = ["planned", "implementing", "evaluating", "completed"];
237
+ const hasImplementableModule = Object.values(modules).some(
238
+ (m: any) => implementablePhases.includes(m.status || m.currentPhase)
239
+ );
240
+
241
+ if (hasImplementableModule) {
242
+ allow();
243
+ }
244
+
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.";
249
+
250
+ deny(message);
251
+ }
252
+
253
+ // Top-level await: on Windows, Bun exits early (code 0, no output) if main() is
254
+ // not awaited while it waits on stdin, which would allow every write.
255
+ await main().catch((err) => {
256
+ console.error("brainstorm-gate hook error:", err);
257
+ process.exit(1);
258
+ });
259
+ `;
260
+ var init_templates = () => {};
261
+
262
+ // src/workspace/manifest.ts
263
+ import { basename } from "path";
264
+ function parseManifest(text) {
265
+ const data = Bun.YAML.parse(text);
266
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
267
+ }
268
+ function hasMarker(m) {
269
+ if (typeof m.haren !== "object" || m.haren === null)
270
+ return false;
271
+ const v = m.haren.version;
272
+ return typeof v === "string" && v !== "" || typeof v === "number";
273
+ }
274
+ function normalizeRepos(repos) {
275
+ const out = {};
276
+ if (Array.isArray(repos)) {
277
+ for (const item of repos) {
278
+ const path = typeof item === "string" ? item : item?.path;
279
+ if (typeof path === "string" && path)
280
+ out[basename(path)] = { path };
281
+ }
282
+ return out;
283
+ }
284
+ if (repos && typeof repos === "object") {
285
+ for (const [key, value] of Object.entries(repos)) {
286
+ if (typeof value === "string") {
287
+ out[key] = { path: value };
288
+ } else if (value && typeof value === "object" && typeof value.path === "string") {
289
+ out[key] = value;
290
+ }
291
+ }
292
+ }
293
+ return out;
294
+ }
295
+ function yamlScalar(value) {
296
+ const plain = /^[A-Za-z_.\/-][\w.\/@-]*$/.test(value) && !YAML_KEYWORDS.test(value) && !YAML_SPECIAL_FLOAT.test(value) && !/^[-+]?\.?\d/.test(value) && value !== "-";
297
+ return plain ? value : JSON.stringify(value);
298
+ }
299
+ function renderReposBlock(repos) {
300
+ const keys = Object.keys(repos);
301
+ if (keys.length === 0) {
302
+ return `repos:
303
+ # Add repos here. Paths are relative to this folder.
304
+ # backend:
305
+ # path: ../backend
306
+ `;
307
+ }
308
+ let out = `repos:
309
+ `;
310
+ for (const key of keys) {
311
+ out += ` ${yamlScalar(key)}:
312
+ `;
313
+ for (const field of REPO_FIELDS) {
314
+ const value = repos[key][field];
315
+ if (value)
316
+ out += ` ${field}: ${yamlScalar(value)}
317
+ `;
318
+ }
319
+ }
320
+ return out;
321
+ }
322
+ function eolOf(text) {
323
+ return text.includes(`\r
324
+ `) ? `\r
325
+ ` : `
326
+ `;
327
+ }
328
+ function toLf(text) {
329
+ return text.replace(/\r\n/g, `
330
+ `);
331
+ }
332
+ function replaceTopLevelBlockLf(text, key, block) {
333
+ const lines = text.split(`
334
+ `);
335
+ const start = lines.findIndex((line) => line === `${key}:` || line.startsWith(`${key}: `) || line.startsWith(`${key}: `));
336
+ if (start === -1) {
337
+ const body = text.endsWith(`
338
+ `) ? text : `${text}
339
+ `;
340
+ return `${body}
341
+ ${block}`;
342
+ }
343
+ let end = start + 1;
344
+ while (end < lines.length && (lines[end] === "" || /^\s/.test(lines[end])))
345
+ end++;
346
+ while (end > start + 1 && lines[end - 1] === "")
347
+ end--;
348
+ lines.splice(start, end - start, ...block.replace(/\n$/, "").split(`
349
+ `));
350
+ return lines.join(`
351
+ `);
352
+ }
353
+ function migrateManifestText(text, mig) {
354
+ const eol = eolOf(text);
355
+ const lf = toLf(text);
356
+ const m = parseManifest(lf);
357
+ const validLayout = m.layout === "monorepo" || m.layout === "workspace";
358
+ const hasLayoutLine = /^layout:/m.test(lf);
359
+ const head = `haren:
360
+ version: ${JSON.stringify(mig.version)}
361
+ ` + (hasLayoutLine ? "" : `layout: ${mig.layout}
362
+ `);
363
+ let out = /^haren:/m.test(lf) ? replaceTopLevelBlockLf(lf, "haren", head) : head + lf;
364
+ if (hasLayoutLine && !validLayout) {
365
+ out = replaceTopLevelBlockLf(out, "layout", `layout: ${mig.layout}
366
+ `);
367
+ }
368
+ if (mig.repos)
369
+ out = replaceTopLevelBlockLf(out, "repos", renderReposBlock(mig.repos));
370
+ return eol === `
371
+ ` ? out : out.replace(/\n/g, `\r
372
+ `);
373
+ }
374
+ function buildManifestText(o) {
375
+ let text = `haren:
376
+ version: ${JSON.stringify(o.version)}
377
+ layout: ${o.layout}
378
+ project: ${yamlScalar(o.project)}
379
+ mode: ${yamlScalar(o.mode)}
380
+ language: ${yamlScalar(o.language)}
381
+
382
+ ${renderReposBlock(o.repos)}
383
+ sources:
384
+ # Mode-specific inputs
385
+ # docs: ./artifacts/00-baseline/requirements.pdf
386
+
387
+ hooks:
388
+ # on-phase-complete:
389
+ # - echo "Module \${MODULE} completed \${PHASE}"
390
+ `;
391
+ if (o.iterations) {
392
+ text += `
393
+ iterations:
394
+ enabled: true
395
+ duration: ${yamlScalar(o.iterations.duration)}
396
+ start_date: ${yamlScalar(o.iterations.startDate)}
397
+ demo_day: ${yamlScalar(o.iterations.demoDay)}
398
+ `;
399
+ }
400
+ return text;
401
+ }
402
+ var REPO_FIELDS, YAML_KEYWORDS, YAML_SPECIAL_FLOAT;
403
+ var init_manifest = __esm(() => {
404
+ REPO_FIELDS = ["path", "remote", "default_branch", "role", "stack", "test_cmd"];
405
+ YAML_KEYWORDS = /^(true|false|null|yes|no|on|off|~)$/i;
406
+ YAML_SPECIAL_FLOAT = /^[-+]?\.(inf|nan)$/i;
407
+ });
408
+
409
+ // src/workspace/root-files.ts
410
+ import { existsSync as existsSync2 } from "fs";
411
+ import { mkdir as mkdir2, readFile, writeFile as writeFile2 } from "fs/promises";
412
+ import { dirname, join as join3, relative, sep } from "path";
413
+ function legacyRange(existing) {
414
+ const start = existing.indexOf(LEGACY_HEADING);
415
+ if (start === -1 || !existing.includes("haren/skill.md"))
416
+ return null;
417
+ const last = existing.indexOf(LEGACY_LAST_LINE, start);
418
+ if (last !== -1) {
419
+ const newline = existing.indexOf(`
420
+ `, last);
421
+ return { start, end: newline === -1 ? existing.length : newline + 1 };
422
+ }
423
+ const heading = /^## .*$/gm;
424
+ heading.lastIndex = start + LEGACY_HEADING.length;
425
+ for (let m = heading.exec(existing);m; m = heading.exec(existing)) {
426
+ if (!LEGACY_HEADINGS.has(m[0].trimEnd()))
427
+ return { start, end: m.index };
428
+ }
429
+ return { start, end: existing.length };
430
+ }
431
+ function upsertBlock(existing, body, file = "The file") {
432
+ const block = `${BLOCK_BEGIN}
433
+ ${body.trimEnd()}
434
+ ${BLOCK_END}
435
+ `;
436
+ if (existing === null || existing.trim() === "")
437
+ return `# Project Instructions
438
+
439
+ ${block}`;
440
+ const begin = existing.indexOf(BLOCK_BEGIN);
441
+ const end = existing.indexOf(BLOCK_END);
442
+ if (begin === -1 !== (end === -1) || begin !== -1 && end < begin) {
443
+ throw new Error(`${file} has a broken haren block (${BLOCK_BEGIN} / ${BLOCK_END}). Fix or remove the markers and run again.`);
444
+ }
445
+ if (begin !== -1) {
446
+ const after = existing.slice(end + BLOCK_END.length).replace(/^\n/, "");
447
+ return existing.slice(0, begin) + block + after;
448
+ }
449
+ const legacy = legacyRange(existing);
450
+ if (legacy) {
451
+ const after = existing.slice(legacy.end).replace(/^\n+/, "");
452
+ return existing.slice(0, legacy.start) + block + (after ? `
453
+ ${after}` : "");
454
+ }
455
+ return `${existing.trimEnd()}
456
+
457
+ ${block}`;
458
+ }
459
+ function hasUserContent(existing) {
460
+ if (existing === null)
461
+ return false;
462
+ const begin = existing.indexOf(BLOCK_BEGIN);
463
+ const end = existing.indexOf(BLOCK_END);
464
+ const legacy = legacyRange(existing);
465
+ const outside = begin !== -1 && end > begin ? existing.slice(0, begin) + existing.slice(end + BLOCK_END.length) : legacy ? existing.slice(0, legacy.start) + existing.slice(legacy.end) : existing;
466
+ return outside.replace("# Project Instructions", "").trim().length > 0;
467
+ }
468
+ function parseJson(existing, path) {
469
+ if (existing === null || existing.trim() === "")
470
+ return {};
471
+ let data;
472
+ try {
473
+ data = JSON.parse(existing);
474
+ } catch (err) {
475
+ throw new Error(`Invalid JSON in ${path}: ${err.message}. Fix the file and run again.`);
476
+ }
477
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
478
+ throw new Error(`Invalid JSON in ${path}: expected an object. Fix the file and run again.`);
479
+ }
480
+ return data;
481
+ }
482
+ function withoutGate(entries) {
483
+ return (Array.isArray(entries) ? entries : []).filter((entry) => !JSON.stringify(entry).includes(GATE_SCRIPT));
484
+ }
485
+ function mergeClaudeSettings(existing, command) {
486
+ const data = parseJson(existing, ".claude/settings.json");
487
+ data.hooks ??= {};
488
+ data.hooks.PreToolUse = [
489
+ ...withoutGate(data.hooks.PreToolUse),
490
+ { matcher: "Edit|Write", hooks: [{ type: "command", command }] }
491
+ ];
492
+ return `${JSON.stringify(data, null, 2)}
493
+ `;
494
+ }
495
+ function mergeCursorHooks(existing, command) {
496
+ const data = parseJson(existing, ".cursor/hooks.json");
497
+ data.version ??= 1;
498
+ data.hooks ??= {};
499
+ data.hooks.beforeFileEdit = [
500
+ ...withoutGate(data.hooks.beforeFileEdit),
501
+ { command, type: "command", timeout: 10 }
502
+ ];
503
+ data.hooks.preToolUse = [
504
+ ...withoutGate(data.hooks.preToolUse),
505
+ { command, matcher: "write", type: "command", timeout: 10 }
506
+ ];
507
+ return `${JSON.stringify(data, null, 2)}
508
+ `;
509
+ }
510
+ async function readOrNull(path) {
511
+ return existsSync2(path) ? readFile(path, "utf-8") : null;
512
+ }
513
+ async function readPackagedOnboard(contentDir) {
514
+ let dir;
515
+ try {
516
+ dir = contentDir ?? resolveContentDir();
517
+ } catch {
518
+ return null;
519
+ }
520
+ return readOrNull(join3(dir, "skills", "onboard", "SKILL.md"));
521
+ }
522
+ async function computeRootFiles(o) {
523
+ const name = relative(o.workspaceDir, o.harenDir).split(sep).join("/");
524
+ const useClaude = o.editor !== "cursor";
525
+ const useCursor = o.editor !== "claude-code";
526
+ const command = gateCommand(name);
527
+ const config = renderTemplate(editorConfigTemplate, name);
528
+ const onboard = await readOrNull(join3(o.harenDir, "skills", "onboard", "SKILL.md")) ?? await readPackagedOnboard(o.contentDir);
529
+ const specs = [];
530
+ if (useClaude) {
531
+ specs.push({
532
+ path: "CLAUDE.md",
533
+ make: (old) => upsertBlock(old, config, "CLAUDE.md"),
534
+ markdown: true
535
+ });
536
+ specs.push({ path: ".claude/settings.json", make: (old) => mergeClaudeSettings(old, command) });
537
+ if (onboard !== null)
538
+ specs.push({ path: ".claude/skills/haren-onboard/SKILL.md", make: () => onboard });
539
+ }
540
+ if (useCursor) {
541
+ specs.push({
542
+ path: ".cursorrules",
543
+ make: (old) => upsertBlock(old, config, ".cursorrules"),
544
+ markdown: true
545
+ });
546
+ specs.push({
547
+ path: ".cursor/rules/haren.mdc",
548
+ make: () => renderTemplate(cursorRuleTemplate, name)
549
+ });
550
+ specs.push({ path: ".cursor/hooks.json", make: (old) => mergeCursorHooks(old, command) });
551
+ if (onboard !== null)
552
+ specs.push({ path: ".cursor/skills/haren-onboard/SKILL.md", make: () => onboard });
553
+ }
554
+ const files = [];
555
+ for (const spec of specs) {
556
+ const old = await readOrNull(join3(o.workspaceDir, spec.path));
557
+ const content = spec.make(old);
558
+ files.push({
559
+ path: spec.path,
560
+ content,
561
+ existed: old !== null,
562
+ changed: old !== content,
563
+ userContent: spec.markdown ? hasUserContent(old) : false
564
+ });
565
+ }
566
+ return files;
567
+ }
568
+ async function writeRootFiles(o) {
569
+ const files = await computeRootFiles(o);
570
+ for (const file of files) {
571
+ if (!file.changed)
572
+ continue;
573
+ const abs = join3(o.workspaceDir, file.path);
574
+ await mkdir2(dirname(abs), { recursive: true });
575
+ await writeFile2(abs, file.content);
576
+ }
577
+ return files;
578
+ }
579
+ function detectEditor(workspaceDir) {
580
+ const claude = existsSync2(join3(workspaceDir, "CLAUDE.md")) || existsSync2(join3(workspaceDir, ".claude", "settings.json"));
581
+ const cursor = existsSync2(join3(workspaceDir, ".cursorrules")) || existsSync2(join3(workspaceDir, ".cursor"));
582
+ if (claude && cursor)
583
+ return "both";
584
+ if (claude)
585
+ return "claude-code";
586
+ if (cursor)
587
+ return "cursor";
588
+ return null;
589
+ }
590
+ var BLOCK_BEGIN = "<!-- haren:begin -->", BLOCK_END = "<!-- haren:end -->", LEGACY_HEADING = "## Haren Framework", GATE_SCRIPT = "brainstorm-gate.ts", LEGACY_LAST_LINE = "Design specs are written to Haren artifact folders, NOT to docs/superpowers/specs/.", LEGACY_HEADINGS;
591
+ var init_root_files = __esm(() => {
592
+ init_content_dir();
593
+ init_templates();
594
+ LEGACY_HEADINGS = new Set([LEGACY_HEADING, "## Brainstorming Gate"]);
55
595
  });
56
- import { mkdir, writeFile, readFile, readdir, copyFile } from "fs/promises";
57
- import { join as join2, resolve as resolve2 } from "path";
596
+
597
+ // src/workspace/git.ts
598
+ import { existsSync as existsSync3 } from "fs";
599
+ import { mkdir as mkdir3, readdir } from "fs/promises";
600
+ import { dirname as dirname2, join as join4, resolve as resolve2 } from "path";
601
+ function gitEnv(interactive = process.stdin.isTTY === true, base = process.env) {
602
+ if (interactive)
603
+ return { ...base };
604
+ return {
605
+ ...base,
606
+ GIT_TERMINAL_PROMPT: "0",
607
+ GIT_SSH_COMMAND: base.GIT_SSH_COMMAND ?? "ssh -o BatchMode=yes"
608
+ };
609
+ }
610
+ async function runGit(args, cwd) {
611
+ try {
612
+ const proc = Bun.spawn(["git", ...args], {
613
+ cwd,
614
+ env: gitEnv(),
615
+ stdout: "pipe",
616
+ stderr: "pipe"
617
+ });
618
+ const [stdout, stderr, code] = await Promise.all([
619
+ new Response(proc.stdout).text(),
620
+ new Response(proc.stderr).text(),
621
+ proc.exited
622
+ ]);
623
+ return { ok: code === 0, stdout: stdout.trim(), stderr: stderr.trim() };
624
+ } catch (err) {
625
+ return { ok: false, stdout: "", stderr: String(err) };
626
+ }
627
+ }
628
+ function hasGitDir(dir) {
629
+ return existsSync3(join4(dir, ".git"));
630
+ }
631
+ async function isInsideWorkTree(dir) {
632
+ const result = await runGit(["rev-parse", "--is-inside-work-tree"], dir);
633
+ return result.ok && result.stdout === "true";
634
+ }
635
+ async function getRemoteUrl(dir) {
636
+ const result = await runGit(["remote", "get-url", "origin"], dir);
637
+ return result.ok && result.stdout ? result.stdout : null;
638
+ }
639
+ async function cloneRepo(remote, dest) {
640
+ const abs = resolve2(dest);
641
+ try {
642
+ await mkdir3(dirname2(abs), { recursive: true });
643
+ } catch (err) {
644
+ return { ok: false, stdout: "", stderr: String(err) };
645
+ }
646
+ return runGit(["clone", remote, abs], dirname2(abs));
647
+ }
648
+ async function gitInit(dir) {
649
+ return runGit(["init"], dir);
650
+ }
651
+ async function listChildRepos(dir) {
652
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
653
+ const repos = [];
654
+ for (const entry of entries) {
655
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
656
+ continue;
657
+ const path = join4(dir, entry.name);
658
+ if (!hasGitDir(path))
659
+ continue;
660
+ repos.push({ name: entry.name, path, remote: await getRemoteUrl(path) });
661
+ }
662
+ return repos.sort((a, b) => a.name.localeCompare(b.name));
663
+ }
664
+ var init_git = () => {};
665
+
666
+ // src/workspace/resolve.ts
667
+ import { existsSync as existsSync4 } from "fs";
668
+ import { readdir as readdir2, readFile as readFile2, stat } from "fs/promises";
669
+ import { dirname as dirname3, join as join5, resolve as resolve3 } from "path";
670
+ async function hasMarkedManifest(dir) {
671
+ const path = join5(dir, "manifest.yaml");
672
+ if (!existsSync4(path))
673
+ return false;
674
+ const text = await readFile2(path, "utf-8").catch(() => null);
675
+ if (text === null)
676
+ return false;
677
+ try {
678
+ return hasMarker(parseManifest(text));
679
+ } catch (e) {
680
+ if (/^haren:/m.test(text)) {
681
+ throw new Error(`manifest.yaml in ${dir} is not valid YAML: ${e instanceof Error ? e.message : String(e)}. Fix the file or move it, then run again.`);
682
+ }
683
+ return false;
684
+ }
685
+ }
686
+ function isLegacyHarenDir(dir) {
687
+ return existsSync4(join5(dir, "manifest.yaml")) && existsSync4(join5(dir, "skill.md"));
688
+ }
689
+ function location(harenDir, legacy) {
690
+ return { harenDir, workspaceDir: dirname3(harenDir), legacy };
691
+ }
692
+ function harenDirFlag(args) {
693
+ const i = args.indexOf("--haren-dir");
694
+ if (i === -1)
695
+ return;
696
+ const value = args[i + 1];
697
+ if (value === undefined || value === "" || value.startsWith("-")) {
698
+ throw new Error("--haren-dir needs a path");
699
+ }
700
+ return value;
701
+ }
702
+ async function resolveHarenDir(cwd, opts = {}) {
703
+ const explicit = opts.harenDir || opts.env?.HAREN_DIR;
704
+ if (explicit) {
705
+ const dir = resolve3(cwd, explicit);
706
+ if (!existsSync4(join5(dir, "manifest.yaml"))) {
707
+ throw new Error(`No manifest.yaml in ${dir}`);
708
+ }
709
+ return location(dir, !await hasMarkedManifest(dir));
710
+ }
711
+ if (await hasMarkedManifest(cwd))
712
+ return location(cwd, false);
713
+ const entries = await readdir2(cwd, { withFileTypes: true }).catch(() => []);
714
+ const matches = [];
715
+ for (const entry of entries) {
716
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
717
+ continue;
718
+ const dir = join5(cwd, entry.name);
719
+ const isDir = entry.isSymbolicLink() ? await stat(dir).then((st) => st.isDirectory(), () => false) : entry.isDirectory();
720
+ if (!isDir)
721
+ continue;
722
+ if (await hasMarkedManifest(dir))
723
+ matches.push(dir);
724
+ }
725
+ matches.sort();
726
+ if (matches.length > 1)
727
+ throw new MultipleHarenDirsError(matches);
728
+ if (matches.length === 1)
729
+ return location(matches[0], false);
730
+ const legacyChild = join5(cwd, "haren");
731
+ if (isLegacyHarenDir(legacyChild))
732
+ return location(legacyChild, true);
733
+ if (isLegacyHarenDir(cwd))
734
+ return location(cwd, true);
735
+ return null;
736
+ }
737
+ var MultipleHarenDirsError;
738
+ var init_resolve = __esm(() => {
739
+ init_manifest();
740
+ MultipleHarenDirsError = class MultipleHarenDirsError extends Error {
741
+ matches;
742
+ constructor(matches) {
743
+ super(`Found more than one haren folder:
744
+ ${matches.join(`
745
+ `)}
746
+ Pass --haren-dir <path> to choose one.`);
747
+ this.matches = matches;
748
+ this.name = "MultipleHarenDirsError";
749
+ }
750
+ };
751
+ });
752
+
753
+ // src/workspace/detect.ts
754
+ import { existsSync as existsSync5 } from "fs";
755
+ import { dirname as dirname4 } from "path";
756
+ async function inferLayout(dir) {
757
+ if (hasGitDir(dir))
758
+ return { layout: "monorepo", childRepos: [] };
759
+ const childRepos = await listChildRepos(dir);
760
+ if (childRepos.length > 0)
761
+ return { layout: "workspace", childRepos };
762
+ let probe = dir;
763
+ while (!existsSync5(probe) && dirname4(probe) !== probe)
764
+ probe = dirname4(probe);
765
+ if (await isInsideWorkTree(probe))
766
+ return { layout: "monorepo", childRepos: [] };
767
+ return { layout: null, childRepos: [] };
768
+ }
769
+ async function detectLayout(dir, opts = {}) {
770
+ const location = await resolveHarenDir(dir, opts);
771
+ if (location)
772
+ return { kind: "existing", location, childRepos: [] };
773
+ const { layout, childRepos } = await inferLayout(dir);
774
+ if (layout === "monorepo")
775
+ return { kind: "monorepo", location: null, childRepos: [] };
776
+ if (layout === "workspace")
777
+ return { kind: "workspace-new", location: null, childRepos };
778
+ return { kind: "unknown", location: null, childRepos: [] };
779
+ }
780
+ var init_detect = __esm(() => {
781
+ init_git();
782
+ init_resolve();
783
+ });
784
+
785
+ // src/workspace/plan.ts
786
+ import { existsSync as existsSync6 } from "fs";
787
+ import { basename as basename2, relative as relative2, resolve as resolve4, sep as sep2 } from "path";
788
+ async function buildPlan(input) {
789
+ const items = [];
790
+ const generatedNote = input.layout === "workspace" ? "(generated, not versioned)" : undefined;
791
+ for (const file of await computeRootFiles({
792
+ workspaceDir: input.rootDir,
793
+ harenDir: input.harenDir,
794
+ editor: input.editor
795
+ })) {
796
+ if (!file.existed)
797
+ items.push({ path: file.path, action: "create", note: generatedNote });
798
+ else if (file.changed)
799
+ items.push({
800
+ path: file.path,
801
+ action: "modify",
802
+ note: file.userContent ? "(haren block only)" : undefined
803
+ });
804
+ else
805
+ items.push({ path: file.path, action: "keep" });
806
+ }
807
+ for (const [key, repo] of Object.entries(input.repos)) {
808
+ const abs = resolve4(input.harenDir, repo.path);
809
+ const path = relative2(input.rootDir, abs).split(sep2).join("/") || key;
810
+ if (existsSync6(abs)) {
811
+ items.push(hasGitDir(abs) || input.layout === "monorepo" ? { path, action: "keep" } : { path, action: "warn", note: "! not a git repo" });
812
+ } else if (input.layout === "monorepo") {
813
+ items.push({ path, action: "warn", note: "! folder not found" });
814
+ } else if (repo.remote) {
815
+ items.push({ path, action: "clone", remote: repo.remote });
816
+ } else {
817
+ items.push({ path, action: "warn", note: "! cannot clone, no remote" });
818
+ }
819
+ }
820
+ return {
821
+ rootDir: input.rootDir,
822
+ harenDirName: basename2(input.harenDir),
823
+ layout: input.layout,
824
+ createHaren: input.createHaren,
825
+ items,
826
+ manifestPreview: input.manifestPreview
827
+ };
828
+ }
829
+ function row(width, prefix, name, action, note) {
830
+ return ` ${prefix}${name.padEnd(width - prefix.length)} ${MARKS[action].padEnd(10)} ${note ?? ""}`.trimEnd();
831
+ }
832
+ function renderPlan(plan) {
833
+ const rootSep = plan.rootDir.includes("\\") ? "\\" : "/";
834
+ const lines = ["Plan:", ` ${plan.rootDir}${rootSep}`];
835
+ const rows = [];
836
+ if (plan.createHaren) {
837
+ rows.push({
838
+ name: `${plan.harenDirName}/`,
839
+ action: "create",
840
+ note: plan.layout === "workspace" ? "(git init, own repo)" : undefined,
841
+ children: [
842
+ { name: "manifest.yaml", action: "create", note: `layout: ${plan.layout}` },
843
+ { name: "artifacts/", action: "create" },
844
+ { name: "hooks/", action: "create" }
845
+ ]
846
+ });
847
+ }
848
+ for (const item of plan.items) {
849
+ const note = item.action === "clone" ? `from ${item.remote}` : item.note;
850
+ rows.push({ name: item.path, action: item.action, note });
851
+ }
852
+ const width = Math.max(MIN_NAME_WIDTH, ...rows.flatMap((r) => [
853
+ 4 + r.name.length,
854
+ ...(r.children ?? []).map((c) => 8 + c.name.length)
855
+ ]));
856
+ rows.forEach((r, i) => {
857
+ const last = i === rows.length - 1;
858
+ lines.push(row(width, last ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ", r.name, r.action, r.note));
859
+ r.children?.forEach((c, j) => {
860
+ const branch = j === r.children.length - 1 ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
861
+ lines.push(row(width, `${last ? " " : "\u2502 "}${branch}`, c.name, c.action, c.note));
862
+ });
863
+ });
864
+ if (plan.manifestPreview) {
865
+ lines.push("", " manifest.yaml preview:");
866
+ for (const line of plan.manifestPreview.trimEnd().split(`
867
+ `))
868
+ lines.push(` ${line}`);
869
+ }
870
+ return lines.join(`
871
+ `);
872
+ }
873
+ function isNoop(plan) {
874
+ return !plan.createHaren && plan.items.every((item) => item.action === "keep" || item.action === "warn");
875
+ }
876
+ var MARKS, MIN_NAME_WIDTH = 28;
877
+ var init_plan = __esm(() => {
878
+ init_git();
879
+ init_root_files();
880
+ MARKS = {
881
+ create: "+ create",
882
+ modify: "~ modify",
883
+ keep: "= keep",
884
+ clone: "\u2193 clone",
885
+ warn: "! warn"
886
+ };
887
+ });
888
+
889
+ // src/workspace/progress.ts
890
+ function migrateProgress(raw, repoKeyFor) {
891
+ if (!raw || typeof raw !== "object")
892
+ return { progress: raw, changed: false };
893
+ const data = raw;
894
+ if ((data.version ?? 1) >= PROGRESS_VERSION)
895
+ return { progress: raw, changed: false };
896
+ const modules = {};
897
+ for (const [name, mod] of Object.entries(data.modules ?? {})) {
898
+ const old = mod?.lastCommit;
899
+ let lastCommit = {};
900
+ if (typeof old === "string" && old)
901
+ lastCommit = { [repoKeyFor(name) || "default"]: old };
902
+ else if (old && typeof old === "object" && !Array.isArray(old) && Object.values(old).every((v) => typeof v === "string")) {
903
+ lastCommit = old;
904
+ }
905
+ modules[name] = { ...mod, lastCommit };
906
+ }
907
+ return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
908
+ }
909
+ var PROGRESS_VERSION = 2;
910
+ var init_progress = () => {};
911
+
912
+ // src/lib/version.ts
913
+ import { existsSync as existsSync7, readFileSync } from "fs";
914
+ import { resolve as resolve5 } from "path";
915
+ function readHarenVersion(candidates) {
916
+ const probes = candidates ?? [
917
+ resolve5(import.meta.dir, "..", "package.json"),
918
+ resolve5(import.meta.dir, "..", "..", "package.json")
919
+ ];
920
+ for (const path of probes) {
921
+ if (!existsSync7(path))
922
+ continue;
923
+ try {
924
+ const pkg = JSON.parse(readFileSync(path, "utf-8"));
925
+ if (pkg?.name === "@odarino/haren" && typeof pkg.version === "string")
926
+ return pkg.version;
927
+ } catch {
928
+ continue;
929
+ }
930
+ }
931
+ return "0.0.0";
932
+ }
933
+ var HAREN_VERSION;
934
+ var init_version = __esm(() => {
935
+ HAREN_VERSION = readHarenVersion();
936
+ });
937
+
938
+ // src/commands/init.ts
939
+ import { mkdir as mkdir4, writeFile as writeFile3, readdir as readdir3, copyFile, readFile as readFile3 } from "fs/promises";
940
+ import { existsSync as existsSync8, realpathSync } from "fs";
941
+ import { homedir } from "os";
942
+ import { basename as basename3, join as join6, resolve as resolve6 } from "path";
58
943
  function readLine() {
59
- return new Promise((resolve3) => {
944
+ return new Promise((resolve) => {
60
945
  const stdin = process.stdin;
61
946
  stdin.resume();
62
947
  stdin.setEncoding("utf-8");
63
948
  const onData = (data) => {
64
949
  stdin.removeListener("data", onData);
65
950
  stdin.pause();
66
- resolve3(data.toString().trim());
951
+ resolve(data.toString().trim());
67
952
  };
68
953
  stdin.on("data", onData);
69
954
  });
@@ -91,6 +976,45 @@ async function promptSelect(question, options, descriptions, defaultValue) {
91
976
  process.stdout.write(` \x1B[31m!\x1B[0m Invalid. Choose: ${options.join(", ")} `);
92
977
  }
93
978
  }
979
+ function parseRepoSelection(value, count, defaults) {
980
+ const answer = value.trim().toLowerCase();
981
+ if (!answer)
982
+ return defaults;
983
+ if (answer === "0" || answer === "none")
984
+ return [];
985
+ const picked = answer.split(",").map((s) => Number(s.trim()) - 1);
986
+ if (!picked.every((n) => Number.isInteger(n) && n >= 0 && n < count))
987
+ return null;
988
+ return [...new Set(picked)];
989
+ }
990
+ async function promptMultiSelect(question, labels, defaults) {
991
+ console.log(` \x1B[36m?\x1B[0m ${question}`);
992
+ labels.forEach((label, i) => {
993
+ const mark = defaults.includes(i) ? "\x1B[36m\u25C9\x1B[0m" : "\u25EF";
994
+ console.log(` ${mark} ${i + 1}. ${label}`);
995
+ });
996
+ process.stdout.write(` \x1B[2m numbers, comma-separated; 0 or none = no repos (enter = keep defaults):\x1B[0m `);
997
+ while (true) {
998
+ const picked = parseRepoSelection(await readLine(), labels.length, defaults);
999
+ if (picked)
1000
+ return picked;
1001
+ process.stdout.write(` \x1B[31m!\x1B[0m Invalid. Use numbers 1-${labels.length}, or 0 for none: `);
1002
+ }
1003
+ }
1004
+ async function promptConfirm(allowEdit) {
1005
+ const choices = allowEdit ? "(Y)es / (n)o / (e)dit selection" : "(Y)es / (n)o";
1006
+ process.stdout.write(` \x1B[36m?\x1B[0m Apply this plan? ${choices} `);
1007
+ while (true) {
1008
+ const value = (await readLine()).toLowerCase();
1009
+ if (value === "" || value === "y" || value === "yes")
1010
+ return "yes";
1011
+ if (value === "n" || value === "no")
1012
+ return "no";
1013
+ if (allowEdit && (value === "e" || value === "edit"))
1014
+ return "edit";
1015
+ process.stdout.write(` \x1B[31m!\x1B[0m Choose ${choices}: `);
1016
+ }
1017
+ }
94
1018
  function getDirectories(iterations) {
95
1019
  const dirs = [
96
1020
  "agents",
@@ -108,6 +1032,7 @@ function getDirectories(iterations) {
108
1032
  "skills/update-links",
109
1033
  "skills/update-tracking",
110
1034
  "skills/generate-mockup",
1035
+ "skills/onboard",
111
1036
  "artifacts/_registry",
112
1037
  "artifacts/00-baseline",
113
1038
  "artifacts/01-research",
@@ -126,11 +1051,11 @@ function getDirectories(iterations) {
126
1051
  return dirs;
127
1052
  }
128
1053
  async function copyRecursive(src, dest) {
129
- const entries = await readdir(src, { withFileTypes: true });
130
- await mkdir(dest, { recursive: true });
1054
+ const entries = await readdir3(src, { withFileTypes: true });
1055
+ await mkdir4(dest, { recursive: true });
131
1056
  for (const entry of entries) {
132
- const srcPath = join2(src, entry.name);
133
- const destPath = join2(dest, entry.name);
1057
+ const srcPath = join6(src, entry.name);
1058
+ const destPath = join6(dest, entry.name);
134
1059
  if (entry.isDirectory()) {
135
1060
  await copyRecursive(srcPath, destPath);
136
1061
  } else {
@@ -140,37 +1065,20 @@ async function copyRecursive(src, dest) {
140
1065
  }
141
1066
  async function scaffoldWorkspace(targetDir, options) {
142
1067
  for (const dir of getDirectories(!!options.iterations)) {
143
- await mkdir(join2(targetDir, dir), { recursive: true });
1068
+ await mkdir4(join6(targetDir, dir), { recursive: true });
144
1069
  }
145
- let manifestContent = `project: ${options.project}
146
- mode: ${options.mode}
147
- language: ${options.language}
148
-
149
- repos:
150
- # Add your repos here (relative paths from this directory)
151
- # example: ../my-repo
152
-
153
- sources:
154
- # Mode-specific inputs
155
- # docs: ./artifacts/00-baseline/requirements.pdf
156
-
157
- hooks:
158
- # on-phase-complete:
159
- # - echo "Module \${MODULE} completed \${PHASE}"
160
- `;
161
- if (options.iterations) {
162
- manifestContent += `
163
- iterations:
164
- enabled: true
165
- duration: ${options.iterations.duration}
166
- start_date: ${options.iterations.startDate}
167
- demo_day: ${options.iterations.demoDay}
168
- `;
169
- }
170
- await writeFile(join2(targetDir, "manifest.yaml"), manifestContent);
1070
+ await writeFile3(join6(targetDir, "manifest.yaml"), buildManifestText({
1071
+ version: HAREN_VERSION,
1072
+ layout: options.layout ?? "monorepo",
1073
+ project: options.project,
1074
+ mode: options.mode,
1075
+ language: options.language,
1076
+ repos: options.repos ?? {},
1077
+ iterations: options.iterations
1078
+ }));
171
1079
  const progressData = {
172
1080
  project: options.project,
173
- version: 1,
1081
+ version: PROGRESS_VERSION,
174
1082
  phase: "init",
175
1083
  status: "active",
176
1084
  modules: {},
@@ -179,194 +1087,40 @@ iterations:
179
1087
  if (options.iterations) {
180
1088
  progressData.currentIteration = 1;
181
1089
  }
182
- await writeFile(join2(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
183
- await writeFile(join2(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
1090
+ await writeFile3(join6(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
1091
+ await writeFile3(join6(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
184
1092
 
185
1093
  Append-only log of framework improvement suggestions captured during usage.
186
1094
 
187
1095
  ---
188
1096
  `);
189
- await writeFile(join2(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
1097
+ await writeFile3(join6(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
190
1098
 
191
1099
  Master registry of all artifacts in this Haren workspace.
192
1100
 
193
1101
  | ID | Type | Module | Status | Path |
194
1102
  |----|------|--------|--------|------|
195
1103
  `);
196
- await writeFile(join2(targetDir, "events", "events.jsonl"), "");
197
- await writeFile(join2(targetDir, "hooks", "brainstorm-gate.ts"), `/**
198
- * Brainstorm Gate Hook
199
- * Blocks Edit/Write tool use if no module has reached 'planned' status.
200
- *
201
- * Works with both Claude Code and Cursor:
202
- * - Exit 0 = allow
203
- * - Exit 2 = block
204
- * - Other exit codes = hook failure, action proceeds (fail-open)
205
- */
206
-
207
- const harenDir = import.meta.dir.replace(/\\/hooks$/, "");
208
-
209
- function allow() {
210
- console.log(JSON.stringify({
211
- allow: true, // Claude Code
212
- permission: "allow", // Cursor
213
- }));
214
- process.exit(0);
215
- }
216
-
217
- function deny(message: string) {
218
- console.log(JSON.stringify({
219
- error: message, // Claude Code
220
- permission: "deny", // Cursor
221
- user_message: message, // Cursor \u2014 shown in UI
222
- agent_message: message, // Cursor \u2014 sent to model
223
- }));
224
- process.exit(2);
225
- }
226
-
227
- async function main() {
228
- // Allow writes inside haren/ \u2014 planning/discovery phases need to write artifacts
229
- try {
230
- const stdin = await Bun.stdin.text();
231
- if (stdin) {
232
- const input = JSON.parse(stdin);
233
- const filePath = input?.tool_input?.file_path
234
- || input?.tool_input?.path
235
- || input?.file_path
236
- || input?.path
237
- || "";
238
- if (filePath.includes("/haren/") || filePath.startsWith("haren/")) {
239
- allow();
240
- }
241
- }
242
- } catch {
243
- // stdin parse failed \u2014 continue with gate check
244
- }
245
-
246
- const progressPath = \`\${harenDir}/progress.json\`;
247
- const progressFile = Bun.file(progressPath);
248
-
249
- if (!(await progressFile.exists())) {
250
- allow();
251
- }
252
-
253
- const progress = await progressFile.json();
254
- const modules = progress.modules || {};
255
- const hasModules = Object.keys(modules).length > 0;
256
-
257
- const implementablePhases = ["planned", "implementing", "evaluating", "completed"];
258
- const hasImplementableModule = Object.values(modules).some(
259
- (m: any) => implementablePhases.includes(m.status || m.currentPhase)
260
- );
261
-
262
- if (hasImplementableModule) {
263
- allow();
264
- }
265
-
266
- // No module is ready for implementation \u2014 block unconditionally
267
- const message = !hasModules
268
- ? "No modules or discovery found. Run the discover phase first. Say \\"let's build X\\" or \\"start discovery\\" to begin."
269
- : "No module has reached 'planned' status yet. Run the plan phase on a module before writing code.";
270
-
271
- deny(message);
272
- }
273
-
274
- main().catch((err) => {
275
- console.error("brainstorm-gate hook error:", err);
276
- process.exit(1);
277
- });
1104
+ await writeFile3(join6(targetDir, "events", "events.jsonl"), "");
1105
+ const gitignore = join6(targetDir, ".gitignore");
1106
+ if (!existsSync8(gitignore))
1107
+ await writeFile3(gitignore, `.agent.json
1108
+ .agent.pid
278
1109
  `);
1110
+ await writeGateScript(targetDir);
279
1111
  await scaffoldSkillMd(targetDir);
280
1112
  const contentDir = resolveContentDir();
281
- await copyRecursive(join2(contentDir, "agents"), join2(targetDir, "agents"));
282
- await copyRecursive(join2(contentDir, "skills"), join2(targetDir, "skills"));
283
- await copyRecursive(join2(contentDir, "templates"), join2(targetDir, "templates"));
284
- const workspaceDir = resolve2(targetDir, "..");
285
- const editor = options.editor || "claude-code";
286
- if (editor === "claude-code" || editor === "both") {
287
- const claudeMdPath = join2(workspaceDir, "CLAUDE.md");
288
- const claudeMdExists = await Bun.file(claudeMdPath).exists();
289
- if (!claudeMdExists) {
290
- await writeFile(claudeMdPath, `# Project Instructions
291
-
292
- ${harenEditorConfig}`);
293
- } else {
294
- const existing = await readFile(claudeMdPath, "utf-8");
295
- if (!existing.includes("haren/skill.md")) {
296
- await writeFile(claudeMdPath, existing + `
297
-
298
- ${harenEditorConfig}`);
299
- }
300
- }
301
- }
302
- if (editor === "cursor" || editor === "both") {
303
- const cursorrulesPath = join2(workspaceDir, ".cursorrules");
304
- const cursorrulesExists = await Bun.file(cursorrulesPath).exists();
305
- if (!cursorrulesExists) {
306
- await writeFile(cursorrulesPath, `# Project Instructions
307
-
308
- ${harenEditorConfig}`);
309
- } else {
310
- const existing = await readFile(cursorrulesPath, "utf-8");
311
- if (!existing.includes("haren/skill.md")) {
312
- await writeFile(cursorrulesPath, existing + `
313
-
314
- ${harenEditorConfig}`);
315
- }
316
- }
317
- }
318
- if (editor === "claude-code" || editor === "both") {
319
- const claudeDir = join2(workspaceDir, ".claude");
320
- await mkdir(claudeDir, { recursive: true });
321
- await writeFile(join2(claudeDir, "settings.json"), JSON.stringify({
322
- hooks: {
323
- PreToolUse: [
324
- {
325
- matcher: "Edit|Write",
326
- hooks: [
327
- {
328
- type: "command",
329
- command: "bun haren/hooks/brainstorm-gate.ts"
330
- }
331
- ]
332
- }
333
- ]
334
- }
335
- }, null, 2));
336
- }
337
- if (editor === "cursor" || editor === "both") {
338
- const cursorDir = join2(workspaceDir, ".cursor");
339
- const cursorRulesDir = join2(cursorDir, "rules");
340
- await mkdir(cursorRulesDir, { recursive: true });
341
- const harenMdcPath = join2(cursorRulesDir, "haren.mdc");
342
- const harenMdcExists = await Bun.file(harenMdcPath).exists();
343
- if (!harenMdcExists) {
344
- await writeFile(harenMdcPath, cursorHarenRule);
345
- }
346
- await writeFile(join2(cursorDir, "hooks.json"), JSON.stringify({
347
- version: 1,
348
- hooks: {
349
- beforeFileEdit: [
350
- {
351
- command: "bun haren/hooks/brainstorm-gate.ts",
352
- type: "command",
353
- timeout: 10
354
- }
355
- ],
356
- preToolUse: [
357
- {
358
- command: "bun haren/hooks/brainstorm-gate.ts",
359
- matcher: "write",
360
- type: "command",
361
- timeout: 10
362
- }
363
- ]
364
- }
365
- }, null, 2));
366
- }
1113
+ await copyRecursive(join6(contentDir, "agents"), join6(targetDir, "agents"));
1114
+ await copyRecursive(join6(contentDir, "skills"), join6(targetDir, "skills"));
1115
+ await copyRecursive(join6(contentDir, "templates"), join6(targetDir, "templates"));
1116
+ await writeRootFiles({
1117
+ workspaceDir: resolve6(targetDir, ".."),
1118
+ harenDir: targetDir,
1119
+ editor: options.editor ?? "claude-code"
1120
+ });
367
1121
  }
368
1122
  async function scaffoldSkillMd(targetDir) {
369
- await writeFile(join2(targetDir, "skill.md"), `---
1123
+ await writeFile3(join6(targetDir, "skill.md"), `---
370
1124
  name: haren
371
1125
  description: Agentic SDLC framework \u2014 orchestrates AI agents through structured phases
372
1126
  ---
@@ -409,6 +1163,7 @@ You are operating within the Haren agentic SDLC framework.
409
1163
  | Check project status | read-context/ | \u2014 |
410
1164
  | Search artifacts | search-artifact/ | \u2014 |
411
1165
  | Draw a UI wireframe | generate-mockup/ | \u2014 |
1166
+ | Onboard to the project / check the workspace | onboard/ (\`/haren-onboard\`) | \u2014 |
412
1167
 
413
1168
  ## How to dispatch
414
1169
 
@@ -420,6 +1175,7 @@ You are operating within the Haren agentic SDLC framework.
420
1175
  - User says "status" or "where are we?" \u2192 read-context/ skill
421
1176
  - User says "start" or "init" \u2192 discover/ skill
422
1177
  - User asks about an artifact \u2192 search-artifact/ skill
1178
+ - User runs \`/haren-onboard\`, is new to the project, or asks "is my workspace set up?" \u2192 onboard/ skill
423
1179
 
424
1180
  ## Artifact Ownership
425
1181
 
@@ -453,82 +1209,137 @@ When a skill says "read the spec", it means from \`artifacts/03-modules/{module}
453
1209
  When a skill says "read tasks" or "read design", it means from the **active plan path**.
454
1210
  When a skill says "read the master plan" or needs full module context, it means from the **master plan path**.
455
1211
 
1212
+ ## Repos and Git
1213
+
1214
+ \`manifest.yaml\` has \`layout\` (\`monorepo\` or \`workspace\`) and a \`repos\` map. Each repo has a \`path\` relative to this haren folder (for example \`../backend\`). A repo can also have \`remote\`, \`default_branch\`, \`role\` (\`frontend\`, \`backend\`, \`e2e\` or \`other\`), \`stack\` and \`test_cmd\`.
1215
+
1216
+ - **Repo folder:** \`<this haren folder>/<path>\`. Run git with \`git -C <repo folder> ...\`.
1217
+ - **Workspace layout:** each repo is its own git repository, and this haren folder is one more. Commit code in the code repo. Commit artifacts, session logs and \`progress.json\` in the haren repo.
1218
+ - **Monorepo layout:** the repos and this haren folder share one git repository and one module branch. Commit code first, then commit the haren files (session log, \`progress.json\`, \`events/events.jsonl\`) as a second commit on the same branch. Make one code commit for all repo keys. Stage only paths outside this haren folder (for example \`git -C <repo root> add -- . ':(exclude)<haren folder>'\`, where \`<haren folder>\` is relative to the repo root). Record that one SHA under each repo key the feature changed.
1219
+ - **Module repos:** the \`repos:\` keys in the module's \`module.md\` front matter. Copy them to \`progress.json\` \`modules.<module>.repos\`.
1220
+ - **No repos listed:** if \`repos\` is empty, or the module's \`module.md\` lists no repos (common in the monorepo layout), use the git repository that holds this haren folder as the module's only repo, with the key \`default\`. In the workspace layout, this haren folder is its own repo and holds no code: ask the user which repo to use, and add it to \`repos\`.
1221
+ - **Branch:** a module uses the branch \`feat/<module-slug>\` in every repo it touches. Record it in \`modules.<module>.branch\`.
1222
+ - **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.
1223
+ - Never push. Never create pull requests unless the user asks. Never clone repos \u2014 tell the user to run \`haren init\`.
1224
+
456
1225
  ## Rules
457
1226
 
458
- - Always read progress.json before taking action
459
- - Never write outside the haren/ directory unless user explicitly asks
460
- - Update progress.json after every phase transition
461
- - Append to FEEDBACK.md when you encounter framework friction
462
- - Validate artifacts before phase transitions (validate-artifact/ skill)
463
- `);
464
- }
465
- async function init(args) {
466
- let project;
467
- let mode;
468
- let language;
469
- let iterations;
470
- let editor;
471
- const force = args.includes("--force");
472
- for (let i = 0;i < args.length; i++) {
473
- if (args[i] === "--project" && args[i + 1]) {
474
- project = args[i + 1];
475
- i++;
476
- }
477
- if (args[i] === "--mode" && args[i + 1]) {
478
- const m = args[i + 1];
479
- if (m === "blueprint" || m === "explore" || m === "inherit" || m === "undecided") {
480
- mode = m;
481
- } else {
482
- console.error(`Invalid mode: ${m}. Must be blueprint, explore, inherit, or undecided.`);
483
- process.exit(1);
484
- }
485
- i++;
486
- }
487
- if (args[i] === "--language" && args[i + 1]) {
488
- language = args[i + 1];
489
- i++;
490
- }
491
- if (args[i] === "--iterations") {
492
- iterations = {
493
- enabled: true,
494
- duration: "2 weeks",
495
- startDate: new Date().toISOString().split("T")[0],
496
- demoDay: "Friday"
497
- };
498
- }
499
- if (args[i] === "--duration" && args[i + 1]) {
500
- if (iterations)
501
- iterations.duration = args[i + 1];
502
- i++;
503
- }
504
- if (args[i] === "--start-date" && args[i + 1]) {
505
- if (iterations)
506
- iterations.startDate = args[i + 1];
507
- i++;
508
- }
509
- if (args[i] === "--demo-day" && args[i + 1]) {
510
- if (iterations)
511
- iterations.demoDay = args[i + 1];
512
- i++;
1227
+ - Always read progress.json before taking action
1228
+ - 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
1229
+ - Update progress.json after every phase transition
1230
+ - Append to FEEDBACK.md when you encounter framework friction
1231
+ - Validate artifacts before phase transitions (validate-artifact/ skill)
1232
+ `);
1233
+ }
1234
+ function parseInitArgs(args) {
1235
+ const out = {
1236
+ force: args.includes("--force"),
1237
+ yes: args.includes("--yes") || args.includes("-y"),
1238
+ dryRun: args.includes("--dry-run")
1239
+ };
1240
+ for (let i = 0;i < args.length; i++) {
1241
+ const value = args[i + 1];
1242
+ switch (args[i]) {
1243
+ case "--project":
1244
+ out.project = value;
1245
+ i++;
1246
+ break;
1247
+ case "--language":
1248
+ out.language = value;
1249
+ i++;
1250
+ break;
1251
+ case "--dir":
1252
+ out.dir = value;
1253
+ i++;
1254
+ break;
1255
+ case "--haren-dir":
1256
+ if (value === undefined || value === "" || value.startsWith("-")) {
1257
+ throw new Error("--haren-dir needs a path");
1258
+ }
1259
+ out.harenDir = value;
1260
+ i++;
1261
+ break;
1262
+ case "--mode":
1263
+ if (!MODES.includes(value)) {
1264
+ throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, or undecided.`);
1265
+ }
1266
+ out.mode = value;
1267
+ i++;
1268
+ break;
1269
+ case "--editor":
1270
+ if (value !== "claude-code" && value !== "cursor" && value !== "both") {
1271
+ throw new Error(`Invalid editor: ${value}. Must be claude-code, cursor, or both.`);
1272
+ }
1273
+ out.editor = value;
1274
+ i++;
1275
+ break;
1276
+ case "--layout":
1277
+ if (value !== "monorepo" && value !== "workspace") {
1278
+ throw new Error(`Invalid layout: ${value}. Must be monorepo or workspace.`);
1279
+ }
1280
+ out.layout = value;
1281
+ i++;
1282
+ break;
1283
+ case "--iterations":
1284
+ out.iterations = {
1285
+ enabled: true,
1286
+ duration: "2 weeks",
1287
+ startDate: new Date().toISOString().split("T")[0],
1288
+ demoDay: "Friday"
1289
+ };
1290
+ break;
1291
+ case "--duration":
1292
+ if (out.iterations)
1293
+ out.iterations.duration = value;
1294
+ i++;
1295
+ break;
1296
+ case "--start-date":
1297
+ if (out.iterations)
1298
+ out.iterations.startDate = value;
1299
+ i++;
1300
+ break;
1301
+ case "--demo-day":
1302
+ if (out.iterations)
1303
+ out.iterations.demoDay = value;
1304
+ i++;
1305
+ break;
513
1306
  }
514
- if (args[i] === "--editor" && args[i + 1]) {
515
- const e = args[i + 1];
516
- if (e === "claude-code" || e === "cursor" || e === "both") {
517
- editor = e;
518
- } else {
519
- console.error(`Invalid editor: ${e}. Must be claude-code, cursor, or both.`);
520
- process.exit(1);
521
- }
522
- i++;
1307
+ }
1308
+ return out;
1309
+ }
1310
+ async function applyClones(plan, rootDir) {
1311
+ const failed = [];
1312
+ for (const item of plan.items) {
1313
+ if (item.action !== "clone" || !item.remote)
1314
+ continue;
1315
+ console.log(` \x1B[36m\u2193\x1B[0m Cloning ${item.path} ...`);
1316
+ const result = await cloneRepo(item.remote, join6(rootDir, item.path));
1317
+ if (!result.ok) {
1318
+ console.error(` \x1B[31m\u2717\x1B[0m ${item.path}: ${result.stderr.split(`
1319
+ `).pop()}`);
1320
+ failed.push(item.path);
523
1321
  }
524
1322
  }
525
- const targetDir = join2(process.cwd(), "haren");
526
- const manifestExists = await Bun.file(join2(targetDir, "manifest.yaml")).exists();
527
- if (manifestExists && !force) {
528
- console.error("Haren workspace already exists here (haren/manifest.yaml found).");
529
- console.error("Use --force to overwrite.");
1323
+ return failed;
1324
+ }
1325
+ function canPrompt(opts) {
1326
+ return !opts.yes && process.stdin.isTTY === true;
1327
+ }
1328
+ async function confirmOrExit(opts, allowEdit) {
1329
+ if (opts.yes)
1330
+ return "yes";
1331
+ if (!process.stdin.isTTY) {
1332
+ console.error(" No terminal to confirm the plan. Re-run with --yes to apply.");
530
1333
  process.exit(1);
531
1334
  }
1335
+ return promptConfirm(allowEdit);
1336
+ }
1337
+ function printNextSteps() {
1338
+ console.log("");
1339
+ console.log(" \x1B[36mNext:\x1B[0m open the workspace root in your editor and run \x1B[1m/haren-onboard\x1B[0m.");
1340
+ console.log("");
1341
+ }
1342
+ function printBanner() {
532
1343
  console.log("");
533
1344
  console.log("\x1B[36m" + `
534
1345
  \u2571\\
@@ -546,192 +1357,214 @@ async function init(args) {
546
1357
  \u2588\u2588\u2551 \u2551\u2588\u2588\u2551 \u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551
547
1358
  \u255A\u2550\u255D \u255A\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D
548
1359
  ` + "\x1B[0m");
549
- console.log("\x1B[2m Agentic SDLC Framework v1.1.0\x1B[0m");
1360
+ console.log(`\x1B[2m Agentic SDLC Framework v${HAREN_VERSION}\x1B[0m`);
550
1361
  console.log("");
551
- const cwdName = process.cwd().split("/").pop() || "my-project";
552
- if (!project) {
553
- project = await prompt("Project name:", cwdName);
554
- }
555
- if (!mode) {
556
- const selected = await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided");
557
- mode = selected;
558
- }
559
- if (!language) {
560
- language = await prompt("Preferred language:", "English");
561
- }
562
- if (iterations === undefined) {
563
- const enableIterations = await promptSelect("Enable iteration planning?", ["no", "yes"], {
564
- no: "flat planning, one pass per module",
565
- yes: "iteration-based planning with scoped deliverables"
566
- }, "no");
567
- if (enableIterations === "yes") {
568
- const duration = await prompt("Iteration duration:", "2 weeks");
569
- const today = new Date().toISOString().split("T")[0];
570
- const startDate = await prompt("Start date:", today);
571
- const demoDay = await prompt("Demo day:", "Friday");
572
- iterations = { enabled: true, duration, startDate, demoDay };
573
- }
1362
+ }
1363
+ async function promptIterations() {
1364
+ const enable = await promptSelect("Enable iteration planning?", ["no", "yes"], {
1365
+ no: "flat planning, one pass per module",
1366
+ yes: "iteration-based planning with scoped deliverables"
1367
+ }, "no");
1368
+ if (enable !== "yes")
1369
+ return;
1370
+ const duration = await prompt("Iteration duration:", "2 weeks");
1371
+ const today = new Date().toISOString().split("T")[0];
1372
+ const startDate = await prompt("Start date:", today);
1373
+ const demoDay = await prompt("Demo day:", "Friday");
1374
+ return { enabled: true, duration, startDate, demoDay };
1375
+ }
1376
+ async function runSetup(location, opts) {
1377
+ if (location.legacy) {
1378
+ console.log(` Found a haren folder without a version marker: ${location.harenDir}`);
1379
+ console.log(" Run 'haren upgrade' to migrate it.");
1380
+ return;
574
1381
  }
575
- if (editor === undefined) {
576
- const selected = await promptSelect("Which editors do you use?", ["claude-code", "cursor", "both"], {
577
- "claude-code": "Claude Code CLI / IDE extension",
578
- cursor: "Cursor AI editor",
579
- both: "Both Claude Code and Cursor"
580
- }, "claude-code");
581
- editor = selected;
1382
+ const manifest = parseManifest(await readFile3(join6(location.harenDir, "manifest.yaml"), "utf-8"));
1383
+ const layout = manifest.layout ?? "workspace";
1384
+ let editor = opts.editor ?? detectEditor(location.workspaceDir);
1385
+ if (!editor) {
1386
+ editor = canPrompt(opts) ? await promptSelect("Which editors do you use?", EDITORS, EDITOR_DESCRIPTIONS, "claude-code") : "claude-code";
582
1387
  }
583
- console.log("");
584
- await mkdir(targetDir, { recursive: true });
585
- await scaffoldWorkspace(targetDir, {
586
- project,
587
- mode,
588
- language,
589
- iterations,
1388
+ const plan = await buildPlan({
1389
+ rootDir: location.workspaceDir,
1390
+ harenDir: location.harenDir,
1391
+ layout,
1392
+ createHaren: false,
1393
+ repos: normalizeRepos(manifest.repos),
590
1394
  editor
591
1395
  });
592
- console.log(` \x1B[32m+\x1B[0m Project: \x1B[1m${project}\x1B[0m`);
593
- console.log(` \x1B[32m+\x1B[0m Mode: \x1B[1m${mode}\x1B[0m`);
594
- console.log(` \x1B[32m+\x1B[0m Language: \x1B[1m${language}\x1B[0m`);
595
- console.log(` \x1B[32m+\x1B[0m Path: \x1B[1mharen/\x1B[0m`);
596
- if (iterations) {
597
- console.log(` \x1B[32m+\x1B[0m Iterations: \x1B[1menabled\x1B[0m (${iterations.duration}, demo: ${iterations.demoDay})`);
1396
+ console.log(` Found haren folder: ${location.harenDir}`);
1397
+ if (isNoop(plan)) {
1398
+ console.log(" Already set up. Run 'haren upgrade' to update framework files.");
1399
+ return;
598
1400
  }
599
- console.log(` \x1B[32m+\x1B[0m Editor: \x1B[1m${editor}\x1B[0m`);
600
1401
  console.log("");
601
- console.log("\x1B[2m Files created in haren/:\x1B[0m");
1402
+ console.log(renderPlan(plan));
602
1403
  console.log("");
603
- console.log(" manifest.yaml \x1B[2m\u2014\x1B[0m project config");
604
- console.log(" progress.json \x1B[2m\u2014\x1B[0m auto-managed state");
605
- console.log(" skill.md \x1B[2m\u2014\x1B[0m LLM entry point");
606
- console.log(" agents/ \x1B[2m\u2014\x1B[0m 6 agent definitions");
607
- console.log(" skills/ \x1B[2m\u2014\x1B[0m 13 skill definitions");
608
- console.log(" templates/ \x1B[2m\u2014\x1B[0m 9 artifact templates");
609
- console.log(" artifacts/ \x1B[2m\u2014\x1B[0m phase outputs (empty)");
610
- console.log("");
611
- if (editor === "claude-code" || editor === "both") {
612
- console.log(` \x1B[32m+\x1B[0m CLAUDE.md + .claude/settings.json created`);
1404
+ if (opts.dryRun)
1405
+ return;
1406
+ if (await confirmOrExit(opts, false) === "no")
1407
+ return;
1408
+ const failed = await applyClones(plan, location.workspaceDir);
1409
+ await writeRootFiles({
1410
+ workspaceDir: location.workspaceDir,
1411
+ harenDir: location.harenDir,
1412
+ editor
1413
+ });
1414
+ printNextSteps();
1415
+ if (failed.length > 0) {
1416
+ console.error(` ${failed.length} repo(s) failed to clone: ${failed.join(", ")}. Run 'haren init' again to retry.`);
1417
+ process.exit(1);
1418
+ }
1419
+ }
1420
+ function manifestIterations(manifest) {
1421
+ const it = manifest.iterations;
1422
+ if (!it || typeof it !== "object" || it.enabled !== true)
1423
+ return;
1424
+ const text = (v, fallback) => typeof v === "string" && v ? v : v instanceof Date ? v.toISOString().split("T")[0] : fallback;
1425
+ return {
1426
+ enabled: true,
1427
+ duration: text(it.duration, "2 weeks"),
1428
+ startDate: text(it.start_date, new Date().toISOString().split("T")[0]),
1429
+ demoDay: text(it.demo_day, "Friday")
1430
+ };
1431
+ }
1432
+ function realPath(path) {
1433
+ try {
1434
+ return realpathSync(path);
1435
+ } catch {
1436
+ return resolve6(path);
1437
+ }
1438
+ }
1439
+ async function init(args) {
1440
+ let opts;
1441
+ try {
1442
+ opts = parseInitArgs(args);
1443
+ } catch (err) {
1444
+ console.error(` ${err.message}`);
1445
+ process.exit(1);
613
1446
  }
614
- if (editor === "cursor" || editor === "both") {
615
- console.log(` \x1B[32m+\x1B[0m .cursorrules + .cursor/rules/haren.mdc created`);
1447
+ const cwdRoot = resolve6(opts.dir?.replace(/^~(?=$|\/)/, process.env.HOME ?? "~") ?? process.cwd());
1448
+ if (!opts.force && realPath(cwdRoot) === realPath(homedir())) {
1449
+ console.error(" Refusing to set up haren in your home folder. Choose a project folder, for example ~/my-project (or pass --force).");
1450
+ process.exit(1);
616
1451
  }
1452
+ printBanner();
1453
+ const explicitHarenDir = opts.harenDir && existsSync8(join6(cwdRoot, opts.harenDir, "manifest.yaml")) ? opts.harenDir : undefined;
1454
+ let detection;
1455
+ try {
1456
+ detection = await detectLayout(cwdRoot, { harenDir: explicitHarenDir, env: process.env });
1457
+ } catch (err) {
1458
+ console.error(` ${err.message}`);
1459
+ process.exit(1);
1460
+ }
1461
+ if (detection.kind === "existing" && !opts.force) {
1462
+ await runSetup(detection.location, opts);
1463
+ return;
1464
+ }
1465
+ let existingManifest;
1466
+ let existingRepos;
1467
+ let existingLayout;
1468
+ if (detection.kind === "existing" && detection.location) {
1469
+ const loc = detection.location;
1470
+ existingManifest = parseManifest(await readFile3(join6(loc.harenDir, "manifest.yaml"), "utf-8"));
1471
+ existingRepos = normalizeRepos(existingManifest.repos);
1472
+ existingLayout = existingManifest.layout ?? (await inferLayout(loc.workspaceDir)).layout ?? "workspace";
1473
+ }
1474
+ const existingLoc = detection.kind === "existing" ? detection.location : null;
1475
+ const rootDir = existingLoc ? existingLoc.workspaceDir : cwdRoot;
1476
+ const interactive = canPrompt(opts);
1477
+ const layout = opts.layout ?? existingLayout ?? (detection.kind === "monorepo" ? "monorepo" : detection.kind === "workspace-new" ? "workspace" : interactive ? await promptSelect("Layout:", ["workspace", "monorepo"], {
1478
+ workspace: "several git repos side by side; haren is its own repo",
1479
+ monorepo: "one git repo; haren is a folder inside it"
1480
+ }, "workspace") : "workspace");
1481
+ console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
617
1482
  console.log("");
618
- console.log("\x1B[2m \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m");
619
- console.log("");
620
- const editorName = editor === "cursor" ? "Cursor" : editor === "both" ? "your editor" : "Claude Code";
621
- console.log(` \x1B[36mNext:\x1B[0m Open this workspace in ${editorName}`);
622
- console.log(` and say \x1B[1m"what's next?"\x1B[0m to begin.`);
623
- console.log("");
1483
+ const harenDirName = opts.harenDir ?? (existingLoc ? basename3(existingLoc.harenDir) : interactive ? await prompt("haren folder name:", "haren") : "haren");
1484
+ const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join6(rootDir, harenDirName);
1485
+ const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
1486
+ const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
1487
+ let selected = defaults;
1488
+ const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt("Project name:", basename3(rootDir)) : basename3(rootDir));
1489
+ const existingMode = MODES.find((m) => m === existingManifest?.mode);
1490
+ const mode = opts.mode ?? existingMode ?? (interactive ? await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided") : "undecided");
1491
+ const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt("Preferred language:", "English") : "English");
1492
+ const iterations = opts.iterations ?? (existingManifest ? manifestIterations(existingManifest) : interactive ? await promptIterations() : undefined);
1493
+ 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");
1494
+ while (true) {
1495
+ if (layout === "workspace" && children.length > 0 && interactive) {
1496
+ selected = await promptMultiSelect("Select code repos to track:", children.map((r) => `${r.name.padEnd(12)} ${r.remote ?? "(no remote)"}`), selected);
1497
+ }
1498
+ const repos = { ...existingRepos };
1499
+ for (const i of selected) {
1500
+ const child = children[i];
1501
+ repos[child.name] = child.remote ? { path: `../${child.name}`, remote: child.remote } : { path: `../${child.name}` };
1502
+ }
1503
+ const plan = await buildPlan({
1504
+ rootDir,
1505
+ harenDir,
1506
+ layout,
1507
+ createHaren: true,
1508
+ repos,
1509
+ editor,
1510
+ manifestPreview: `layout: ${layout}
1511
+ ${renderReposBlock(repos)}`
1512
+ });
1513
+ console.log("");
1514
+ console.log(renderPlan(plan));
1515
+ console.log("");
1516
+ if (opts.dryRun)
1517
+ return;
1518
+ const answer = await confirmOrExit(opts, layout === "workspace" && children.length > 0);
1519
+ if (answer === "no")
1520
+ return;
1521
+ if (answer === "edit")
1522
+ continue;
1523
+ const failed = layout === "workspace" ? await applyClones(plan, rootDir) : [];
1524
+ await mkdir4(harenDir, { recursive: true });
1525
+ await scaffoldWorkspace(harenDir, {
1526
+ project,
1527
+ mode,
1528
+ language,
1529
+ iterations,
1530
+ editor,
1531
+ layout,
1532
+ repos
1533
+ });
1534
+ if (layout === "workspace" && !hasGitDir(harenDir)) {
1535
+ const result = await gitInit(harenDir);
1536
+ if (!result.ok) {
1537
+ console.error(` git init failed in ${harenDir}: ${result.stderr}`);
1538
+ process.exit(1);
1539
+ }
1540
+ }
1541
+ console.log(` \x1B[32m\u2713\x1B[0m Created ${harenDirName}/ (${layout})`);
1542
+ printNextSteps();
1543
+ if (failed.length > 0) {
1544
+ console.error(` ${failed.length} repo(s) failed to clone: ${failed.join(", ")}. Run 'haren init' again to retry.`);
1545
+ process.exit(1);
1546
+ }
1547
+ return;
1548
+ }
624
1549
  }
625
- var MODES, MODE_DESCRIPTIONS, harenEditorConfig = `## Haren Framework
626
-
627
- This workspace uses the Haren agentic SDLC framework.
628
-
629
- **On every session start, you MUST:**
630
- 1. Read \`haren/skill.md\` \u2014 this is your operating manual
631
- 2. Follow its instructions for session orientation
632
- 3. Read \`haren/manifest.yaml\` and \`haren/progress.json\` before taking any action
633
-
634
- All project documentation, specs, plans, and artifacts are managed inside \`haren/\`.
635
- Never write outside \`haren/\` unless explicitly asked.
636
-
637
- ## Brainstorming Gate
638
-
639
- Before writing ANY code outside \`haren/\`:
640
- 1. Read \`haren/progress.json\`
641
- 2. At least one module MUST have status \`planned\`, \`implementing\`, \`evaluating\`, or \`completed\`
642
- 3. If NO module is at \`planned\` or later \u2192 STOP. Do not write code.
643
- - \`discovered\`, \`specified\`, \`decomposed\` do NOT allow implementation
644
- - Discovery docs and specs are NOT sufficient \u2014 planning must be completed first
645
- 4. If blocked, tell the user to run the plan phase before implementation
646
-
647
- Design specs are written to Haren artifact folders, NOT to docs/superpowers/specs/.
648
- `, cursorHarenRule = `---
649
- description: Haren agentic SDLC framework - project workflow and artifact management
650
- globs:
651
- - haren/**
652
- - .cursorrules
653
- alwaysApply: true
654
- ---
655
-
656
- # Haren Framework \u2014 MANDATORY RULES
657
-
658
- ## RULE #1: NEVER WRITE WITHOUT ASKING (highest priority)
659
-
660
- **You MUST ask the user questions and get answers BEFORE writing ANY artifact or code.**
661
-
662
- This applies to ALL phases \u2014 planning, designing, implementing, everything.
663
-
664
- **The process is ALWAYS:**
665
- 1. Read existing artifacts (spec.md, module.md, context-brief.md, architecture.md)
666
- 2. Identify unresolved decisions
667
- 3. **ASK the user one question at a time \u2014 present 2-3 options with trade-offs**
668
- 4. **WAIT for the user's answer**
669
- 5. Repeat until ALL decisions are resolved
670
- 6. **ONLY THEN write files**
671
-
672
- **NEVER do this:**
673
- - Write artifacts first, then say "let me know if you want changes" \u2014 WRONG
674
- - Make assumptions about technical decisions \u2014 WRONG
675
- - Dump all questions at once \u2014 WRONG, ask ONE at a time
676
- - Skip asking because you think the answer is obvious \u2014 WRONG
677
-
678
- **If you are about to call the write/edit tool and you have not asked the user any questions yet in this conversation, STOP. You are violating this rule.**
679
-
680
- ---
681
-
682
- ## RULE #2: Code Gate \u2014 No code outside \`haren/\` without \`planned\` status
683
-
684
- **BEFORE writing ANY file outside \`haren/\`, check \`haren/progress.json\`:**
685
-
686
- 1. The relevant module MUST have status \`planned\`, \`implementing\`, \`evaluating\`, or \`completed\`
687
- 2. **If NO \u2192 STOP. DO NOT WRITE CODE.**
688
- 3. \`discovered\`, \`specified\`, \`decomposed\` do NOT allow code changes
689
- 4. Discovery docs and specs are NOT sufficient
690
-
691
- **When blocked, respond ONLY with:**
692
- - No modules: "No modules found. Run the discover phase first."
693
- - No planned modules: "No module has reached 'planned' status yet. Run the plan phase first."
694
-
695
- No exceptions. No rationalizing. STOP means STOP.
696
-
697
- ---
698
-
699
- ## On Every Session Start
700
-
701
- 1. Read \`haren/skill.md\` \u2014 this is your operating manual
702
- 2. Follow its instructions for session orientation
703
- 3. Read \`haren/manifest.yaml\` and \`haren/progress.json\` before taking any action
704
-
705
- All project documentation, specs, plans, and artifacts are managed inside \`haren/\`.
706
- Never write outside \`haren/\` unless explicitly asked.
707
-
708
- ## Phase Progression (MANDATORY)
709
-
710
- Modules MUST progress through phases in order. You CANNOT skip phases.
711
-
712
- \`\`\`
713
- discovered \u2192 specified \u2192 planned \u2192 implementing \u2192 evaluating \u2192 completed
714
- \`\`\`
715
-
716
- **Before taking ANY action on a module, read \`haren/progress.json\` and check the module's current status. Then follow the dispatch rules in \`haren/skill.md\`.**
717
-
718
- Key dispatch rules:
719
- - Module at \`specified\` \u2192 user says "plan" \u2192 you MUST run the \`plan/\` skill first (read \`haren/skills/plan/SKILL.md\`)
720
- - Module at \`discovered\` or no module \u2192 user says "plan" or "build" \u2192 you MUST run \`discover/\` skill first (brainstorming)
721
- - Module at \`planned\` \u2192 user says "implement" or "build" \u2192 proceed with implementation
722
- - **You CANNOT jump from \`specified\` directly to \`implementing\`**
723
- - **You CANNOT skip brainstorming/discovery for new features**
724
-
725
- ## Rules
726
-
727
- - Always read progress.json before taking action
728
- - Never write outside the haren/ directory unless user explicitly asks
729
- - Update progress.json after every phase transition
730
- - Append to FEEDBACK.md when you encounter framework friction
731
- `;
1550
+ var MODES, EDITORS, EDITOR_DESCRIPTIONS, MODE_DESCRIPTIONS;
732
1551
  var init_init = __esm(() => {
733
1552
  init_content_dir();
1553
+ init_templates();
1554
+ init_manifest();
1555
+ init_root_files();
1556
+ init_detect();
1557
+ init_plan();
1558
+ init_git();
1559
+ init_progress();
1560
+ init_version();
734
1561
  MODES = ["blueprint", "explore", "inherit", "undecided"];
1562
+ EDITORS = ["claude-code", "cursor", "both"];
1563
+ EDITOR_DESCRIPTIONS = {
1564
+ "claude-code": "Claude Code CLI / IDE extension",
1565
+ cursor: "Cursor AI editor",
1566
+ both: "Both Claude Code and Cursor"
1567
+ };
735
1568
  MODE_DESCRIPTIONS = {
736
1569
  blueprint: "Greenfield project with existing docs",
737
1570
  explore: "Greenfield project from scratch",
@@ -741,18 +1574,110 @@ var init_init = __esm(() => {
741
1574
  });
742
1575
 
743
1576
  // src/commands/upgrade.ts
744
- var exports_upgrade = {};
745
- __export(exports_upgrade, {
746
- upgrade: () => upgrade
747
- });
748
- import { mkdir as mkdir2, readdir as readdir2, copyFile as copyFile2, stat } from "fs/promises";
749
- import { join as join3 } from "path";
1577
+ import { mkdir as mkdir5, readdir as readdir4, copyFile as copyFile2, readFile as readFile4, stat as stat2, writeFile as writeFile4 } from "fs/promises";
1578
+ import { join as join7, resolve as resolve7 } from "path";
1579
+ import { existsSync as existsSync9 } from "fs";
1580
+ async function moduleRepoKey(harenDir, moduleName) {
1581
+ const path = join7(harenDir, "artifacts", "03-modules", moduleName, "module.md");
1582
+ if (!existsSync9(path))
1583
+ return;
1584
+ const match = (await readFile4(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
1585
+ return match?.[1].split(",")[0]?.trim().replace(/^["']|["']$/g, "") || undefined;
1586
+ }
1587
+ async function planMigration(location) {
1588
+ const { harenDir, workspaceDir } = location;
1589
+ const steps = [];
1590
+ const manifestBefore = await readFile4(join7(harenDir, "manifest.yaml"), "utf-8");
1591
+ const manifest = parseManifest(manifestBefore);
1592
+ const layout = manifest.layout ?? (await inferLayout(workspaceDir)).layout ?? "workspace";
1593
+ if (!hasMarker(manifest))
1594
+ steps.push("manifest.yaml: add version marker");
1595
+ else if (String(manifest.haren?.version) !== HAREN_VERSION)
1596
+ steps.push("manifest.yaml: update version marker");
1597
+ if (!manifest.layout)
1598
+ steps.push(`manifest.yaml: add layout: ${layout}`);
1599
+ let repos;
1600
+ const current = normalizeRepos(manifest.repos);
1601
+ const needsRemote = layout === "workspace" && Object.values(current).some((r) => !r.remote);
1602
+ if (Array.isArray(manifest.repos) || needsRemote) {
1603
+ const map = {};
1604
+ let foundRemote = false;
1605
+ for (const [key, entry] of Object.entries(current)) {
1606
+ const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve7(harenDir, entry.path)) : null);
1607
+ if (remote && !entry.remote)
1608
+ foundRemote = true;
1609
+ map[key] = remote ? { ...entry, remote } : entry;
1610
+ }
1611
+ if (Array.isArray(manifest.repos) || foundRemote) {
1612
+ repos = map;
1613
+ steps.push("manifest.yaml: convert repos to a map with remotes");
1614
+ }
1615
+ }
1616
+ const manifestAfter = migrateManifestText(manifestBefore, {
1617
+ version: HAREN_VERSION,
1618
+ layout,
1619
+ repos
1620
+ });
1621
+ let progress = null;
1622
+ const progressPath = join7(harenDir, "progress.json");
1623
+ if (existsSync9(progressPath)) {
1624
+ const before = await readFile4(progressPath, "utf-8");
1625
+ let raw;
1626
+ try {
1627
+ raw = JSON.parse(before);
1628
+ } catch (err) {
1629
+ throw new Error(`Invalid JSON in ${progressPath}: ${err.message}. Fix the file and run again.`);
1630
+ }
1631
+ const firstRepo = Object.keys(repos ?? current)[0];
1632
+ const keys = {};
1633
+ for (const name of Object.keys(raw.modules ?? {})) {
1634
+ keys[name] = await moduleRepoKey(harenDir, name) ?? firstRepo;
1635
+ }
1636
+ const result = migrateProgress(raw, (name) => keys[name]);
1637
+ if (result.changed) {
1638
+ progress = { before, after: `${JSON.stringify(result.progress, null, 2)}
1639
+ ` };
1640
+ steps.push("progress.json: migrate to version 2 (lastCommit per repo)");
1641
+ }
1642
+ }
1643
+ const gitignore = await planGitignore(harenDir);
1644
+ if (gitignore !== null)
1645
+ steps.push(`.gitignore: add ${AGENT_FILES.join(", ")}`);
1646
+ const editor = detectEditor(workspaceDir) ?? "claude-code";
1647
+ const rootFiles = await computeRootFiles({ workspaceDir, harenDir, editor });
1648
+ for (const file of rootFiles.filter((f) => f.changed)) {
1649
+ steps.push(`${file.path}: ${file.existed ? "update" : "create"}`);
1650
+ }
1651
+ return {
1652
+ manifest: { before: manifestBefore, after: manifestAfter },
1653
+ progress,
1654
+ gitignore,
1655
+ layout,
1656
+ editor,
1657
+ steps
1658
+ };
1659
+ }
1660
+ async function planGitignore(harenDir) {
1661
+ const path = join7(harenDir, ".gitignore");
1662
+ const before = existsSync9(path) ? await readFile4(path, "utf-8") : "";
1663
+ const lines = new Set(before.split(/\r?\n/).map((l) => l.trim()));
1664
+ const missing = AGENT_FILES.filter((f) => !lines.has(f));
1665
+ if (missing.length === 0)
1666
+ return null;
1667
+ const eol = before.includes(`\r
1668
+ `) ? `\r
1669
+ ` : `
1670
+ `;
1671
+ const base = before === "" || before.endsWith(`
1672
+ `) ? before : `${before}${eol}`;
1673
+ return `${base}${missing.join(eol)}${eol}`;
1674
+ }
750
1675
  async function copyRecursive2(src, dest) {
751
- const entries = await readdir2(src, { withFileTypes: true });
752
- await mkdir2(dest, { recursive: true });
1676
+ const entries = await readdir4(src, { withFileTypes: true });
1677
+ await mkdir5(dest, { recursive: true });
753
1678
  for (const entry of entries) {
754
- const srcPath = join3(src, entry.name);
755
- const destPath = join3(dest, entry.name);
1679
+ const srcPath = join7(src, entry.name);
1680
+ const destPath = join7(dest, entry.name);
756
1681
  if (entry.isDirectory()) {
757
1682
  await copyRecursive2(srcPath, destPath);
758
1683
  } else {
@@ -762,10 +1687,10 @@ async function copyRecursive2(src, dest) {
762
1687
  }
763
1688
  async function countFiles(dir) {
764
1689
  let count = 0;
765
- const entries = await readdir2(dir, { withFileTypes: true });
1690
+ const entries = await readdir4(dir, { withFileTypes: true });
766
1691
  for (const entry of entries) {
767
1692
  if (entry.isDirectory()) {
768
- count += await countFiles(join3(dir, entry.name));
1693
+ count += await countFiles(join7(dir, entry.name));
769
1694
  } else {
770
1695
  count++;
771
1696
  }
@@ -773,18 +1698,25 @@ async function countFiles(dir) {
773
1698
  return count;
774
1699
  }
775
1700
  async function upgrade(args) {
776
- let targetDir = process.cwd();
777
- const hasCurrent = await Bun.file(join3(targetDir, "manifest.yaml")).exists();
778
- const hasChild = await Bun.file(join3(targetDir, "haren", "manifest.yaml")).exists();
779
- if (!hasCurrent && hasChild) {
780
- targetDir = join3(targetDir, "haren");
781
- } else if (!hasCurrent && !hasChild) {
782
- console.error("No Haren workspace found. Run 'haren init' first.");
1701
+ let location;
1702
+ try {
1703
+ location = await resolveHarenDir(process.cwd(), {
1704
+ harenDir: harenDirFlag(args),
1705
+ env: process.env
1706
+ });
1707
+ } catch (err) {
1708
+ console.error(err instanceof MultipleHarenDirsError ? err.message : String(err));
783
1709
  process.exit(1);
784
1710
  }
1711
+ if (!location) {
1712
+ console.error("No haren folder found. Run 'haren init' first.");
1713
+ process.exit(1);
1714
+ }
1715
+ const targetDir = location.harenDir;
1716
+ const migration = await planMigration(location);
785
1717
  const contentDir = resolveContentDir();
786
1718
  try {
787
- await stat(contentDir);
1719
+ await stat2(contentDir);
788
1720
  } catch {
789
1721
  console.error("Could not find Haren package content directory.");
790
1722
  process.exit(1);
@@ -802,52 +1734,76 @@ async function upgrade(args) {
802
1734
  console.log("\x1B[2m Upgrading framework files:\x1B[0m");
803
1735
  let totalFiles = 0;
804
1736
  for (const dir of FRAMEWORK_DIRS) {
805
- const srcDir = join3(contentDir, dir);
806
- const destDir = join3(targetDir, dir);
1737
+ const srcDir = join7(contentDir, dir);
1738
+ const destDir = join7(targetDir, dir);
807
1739
  const fileCount = await countFiles(srcDir);
808
1740
  totalFiles += fileCount;
809
1741
  console.log(` \x1B[36m\u2191\x1B[0m ${dir}/ \x1B[2m(${fileCount} files)\x1B[0m`);
810
1742
  }
811
1743
  console.log(` \x1B[36m\u2191\x1B[0m skill.md \x1B[2m(entry point)\x1B[0m`);
1744
+ console.log(` \x1B[36m\u2191\x1B[0m ${GATE_SCRIPT_PATH} \x1B[2m(brainstorm gate)\x1B[0m`);
812
1745
  console.log("");
1746
+ if (migration.steps.length > 0) {
1747
+ console.log("\x1B[2m Migration:\x1B[0m");
1748
+ for (const step of migration.steps)
1749
+ console.log(` \x1B[33m~\x1B[0m ${step}`);
1750
+ console.log("");
1751
+ }
813
1752
  if (dry) {
814
- console.log(`\x1B[33m Dry run \u2014 ${totalFiles + 1} files would be updated. No changes made.\x1B[0m`);
1753
+ console.log(`\x1B[33m Dry run \u2014 ${totalFiles + 2} files would be updated. No changes made.\x1B[0m`);
815
1754
  console.log("");
816
1755
  return;
817
1756
  }
818
1757
  for (const dir of FRAMEWORK_DIRS) {
819
- await copyRecursive2(join3(contentDir, dir), join3(targetDir, dir));
1758
+ await copyRecursive2(join7(contentDir, dir), join7(targetDir, dir));
820
1759
  }
821
- const { scaffoldSkillMd: scaffoldSkillMd2 } = await Promise.resolve().then(() => (init_init(), exports_init));
822
- await scaffoldSkillMd2(targetDir);
823
- console.log(` \x1B[32m\u2713\x1B[0m Upgraded ${totalFiles + 1} framework files.`);
824
- console.log(` \x1B[2mYour artifacts, progress, and manifest are untouched.\x1B[0m`);
1760
+ await Promise.resolve().then(() => init_init());
1761
+ await scaffoldSkillMd(targetDir);
1762
+ await writeGateScript(targetDir);
1763
+ if (migration.manifest.after !== migration.manifest.before) {
1764
+ await writeFile4(join7(targetDir, "manifest.yaml"), migration.manifest.after);
1765
+ }
1766
+ if (migration.progress) {
1767
+ await writeFile4(join7(targetDir, "progress.json"), migration.progress.after);
1768
+ }
1769
+ if (migration.gitignore !== null) {
1770
+ await writeFile4(join7(targetDir, ".gitignore"), migration.gitignore);
1771
+ }
1772
+ await writeRootFiles({
1773
+ workspaceDir: location.workspaceDir,
1774
+ harenDir: targetDir,
1775
+ editor: migration.editor
1776
+ });
1777
+ console.log(` \x1B[32m\u2713\x1B[0m Upgraded ${totalFiles + 2} framework files.`);
1778
+ console.log(` \x1B[2mYour artifacts are untouched. Manifest and progress were migrated if needed.\x1B[0m`);
825
1779
  console.log("");
826
1780
  }
827
- var FRAMEWORK_DIRS, USER_FILES;
1781
+ var AGENT_FILES, FRAMEWORK_DIRS, USER_FILES;
828
1782
  var init_upgrade = __esm(() => {
829
1783
  init_content_dir();
1784
+ init_version();
1785
+ init_git();
1786
+ init_detect();
1787
+ init_manifest();
1788
+ init_progress();
1789
+ init_resolve();
1790
+ init_root_files();
1791
+ init_templates();
1792
+ AGENT_FILES = [".agent.json", ".agent.pid"];
830
1793
  FRAMEWORK_DIRS = ["agents", "skills", "templates"];
831
- USER_FILES = [
832
- "manifest.yaml",
833
- "progress.json",
834
- "skill.md",
835
- "FEEDBACK.md",
836
- "artifacts/",
837
- "events/"
838
- ];
1794
+ USER_FILES = ["FEEDBACK.md", "artifacts/", "events/"];
839
1795
  });
840
1796
 
841
1797
  // src/agent/config.ts
842
- import { join as join4 } from "path";
1798
+ import { join as join8 } from "path";
843
1799
  async function readAgentConfig(harenDir) {
844
- const file = Bun.file(join4(harenDir, CONFIG_FILE));
1800
+ const file = Bun.file(join8(harenDir, CONFIG_FILE));
845
1801
  if (!await file.exists())
846
1802
  return null;
847
1803
  return file.json();
848
1804
  }
849
1805
  async function writeAgentConfig(harenDir, config) {
850
- const path = join4(harenDir, CONFIG_FILE);
1806
+ const path = join8(harenDir, CONFIG_FILE);
851
1807
  await Bun.write(path, JSON.stringify(config, null, 2));
852
1808
  }
853
1809
  var CONFIG_FILE = ".agent.json";
@@ -855,16 +1811,7 @@ var init_config = () => {};
855
1811
 
856
1812
  // src/agent/cli-detector.ts
857
1813
  async function checkCLI(command) {
858
- try {
859
- const proc = Bun.spawn(["which", command], {
860
- stdout: "pipe",
861
- stderr: "pipe"
862
- });
863
- await proc.exited;
864
- return proc.exitCode === 0;
865
- } catch {
866
- return false;
867
- }
1814
+ return Bun.which(command) !== null;
868
1815
  }
869
1816
  async function detectCLIs() {
870
1817
  const results = await Promise.all(KNOWN_CLIS.map(async (cli) => ({
@@ -879,16 +1826,16 @@ var init_cli_detector = __esm(() => {
879
1826
  });
880
1827
 
881
1828
  // src/agent/artifact-reader.ts
882
- import { join as join5 } from "path";
883
- import { readdir as readdir3 } from "fs/promises";
1829
+ import { join as join9 } from "path";
1830
+ import { readdir as readdir5 } from "fs/promises";
884
1831
  async function readProgress(harenDir) {
885
- const file = Bun.file(join5(harenDir, "progress.json"));
1832
+ const file = Bun.file(join9(harenDir, "progress.json"));
886
1833
  if (!await file.exists())
887
1834
  return null;
888
1835
  return file.json();
889
1836
  }
890
1837
  async function readArtifactTree(harenDir) {
891
- const artifactsDir = join5(harenDir, "artifacts");
1838
+ const artifactsDir = join9(harenDir, "artifacts");
892
1839
  try {
893
1840
  return await buildTree(artifactsDir, "artifacts");
894
1841
  } catch {
@@ -896,12 +1843,12 @@ async function readArtifactTree(harenDir) {
896
1843
  }
897
1844
  }
898
1845
  async function buildTree(dirPath, relativePath) {
899
- const entries = await readdir3(dirPath, { withFileTypes: true });
1846
+ const entries = await readdir5(dirPath, { withFileTypes: true });
900
1847
  const nodes = [];
901
1848
  for (const entry of entries) {
902
- const entryPath = join5(relativePath, entry.name);
1849
+ const entryPath = join9(relativePath, entry.name);
903
1850
  if (entry.isDirectory()) {
904
- const children = await buildTree(join5(dirPath, entry.name), entryPath);
1851
+ const children = await buildTree(join9(dirPath, entry.name), entryPath);
905
1852
  nodes.push({
906
1853
  name: entry.name,
907
1854
  type: "directory",
@@ -915,29 +1862,36 @@ async function buildTree(dirPath, relativePath) {
915
1862
  return nodes.sort((a, b) => a.name.localeCompare(b.name));
916
1863
  }
917
1864
  async function readArtifact(harenDir, relativePath) {
918
- const file = Bun.file(join5(harenDir, relativePath));
1865
+ const file = Bun.file(join9(harenDir, relativePath));
919
1866
  if (!await file.exists())
920
1867
  return null;
921
1868
  return file.text();
922
1869
  }
923
- async function readGitLog(maxCount = 50) {
924
- try {
925
- const proc = Bun.spawn(["git", "log", `--max-count=${maxCount}`, "--format=%H|%s|%aI|%aN", "--", "haren/"], { stdout: "pipe", stderr: "pipe" });
926
- const text = await new Response(proc.stdout).text();
927
- return text.trim().split(`
928
- `).filter(Boolean).map((line) => {
929
- const [hash, message, date, author] = line.split("|");
930
- return { hash, message, date, author };
931
- });
932
- } catch {
1870
+ async function readGitLog(harenDir, maxCount = 50) {
1871
+ const result = await runGit([
1872
+ "-C",
1873
+ harenDir,
1874
+ "log",
1875
+ `--max-count=${maxCount}`,
1876
+ "--format=%H%x1f%s%x1f%aI%x1f%aN",
1877
+ "--",
1878
+ "."
1879
+ ], harenDir);
1880
+ if (!result.ok || !result.stdout)
933
1881
  return [];
934
- }
1882
+ return result.stdout.split(`
1883
+ `).map((line) => {
1884
+ const [hash, message, date, author] = line.split("\x1F");
1885
+ return { hash, message, date, author };
1886
+ });
935
1887
  }
936
- var init_artifact_reader = () => {};
1888
+ var init_artifact_reader = __esm(() => {
1889
+ init_git();
1890
+ });
937
1891
 
938
1892
  // src/agent/cli-executor.ts
939
- async function executeCLI(cli, prompt2, onOutput) {
940
- const args = buildCLIArgs(cli, prompt2);
1893
+ async function executeCLI(cli, prompt, onOutput) {
1894
+ const args = buildCLIArgs(cli, prompt);
941
1895
  try {
942
1896
  const proc = Bun.spawn(args, {
943
1897
  stdout: "pipe",
@@ -969,49 +1923,29 @@ async function executeCLI(cli, prompt2, onOutput) {
969
1923
  onOutput("", true);
970
1924
  }
971
1925
  }
972
- function buildCLIArgs(cli, prompt2) {
1926
+ function buildCLIArgs(cli, prompt) {
973
1927
  switch (cli) {
974
1928
  case "claude":
975
- return ["claude", "--print", prompt2];
1929
+ return ["claude", "--print", prompt];
976
1930
  case "cursor":
977
- return ["cursor", "--prompt", prompt2];
1931
+ return ["cursor", "--prompt", prompt];
978
1932
  case "github-copilot-cli":
979
- return ["github-copilot-cli", prompt2];
1933
+ return ["github-copilot-cli", prompt];
980
1934
  default:
981
- return [cli, prompt2];
1935
+ return [cli, prompt];
982
1936
  }
983
1937
  }
984
1938
 
985
1939
  // src/workspace/events.ts
986
- var exports_events = {};
987
- __export(exports_events, {
988
- readEvents: () => readEvents,
989
- appendEvent: () => appendEvent
990
- });
991
- import { appendFile, readFile as readFile3 } from "fs/promises";
1940
+ import { appendFile, readFile as readFile5 } from "fs/promises";
992
1941
  async function appendEvent(path, event) {
993
1942
  const line = JSON.stringify(event) + `
994
1943
  `;
995
1944
  await appendFile(path, line);
996
1945
  }
997
- async function readEvents(path) {
998
- try {
999
- const raw = await readFile3(path, "utf-8");
1000
- if (!raw.trim())
1001
- return [];
1002
- return raw.trim().split(`
1003
- `).map((line) => JSON.parse(line));
1004
- } catch {
1005
- return [];
1006
- }
1007
- }
1008
1946
  var init_events = () => {};
1009
1947
 
1010
1948
  // src/agent/request-handler.ts
1011
- var exports_request_handler = {};
1012
- __export(exports_request_handler, {
1013
- handleServerMessage: () => handleServerMessage
1014
- });
1015
1949
  function handleServerMessage(msg, config, send) {
1016
1950
  switch (msg.type) {
1017
1951
  case "data-request":
@@ -1035,7 +1969,7 @@ async function handleDataRequest(requestId, path, harenDir, send) {
1035
1969
  data = await readArtifactTree(harenDir);
1036
1970
  break;
1037
1971
  case "git-log":
1038
- data = await readGitLog();
1972
+ data = await readGitLog(harenDir);
1039
1973
  break;
1040
1974
  default:
1041
1975
  if (path.startsWith("artifacts/")) {
@@ -1046,19 +1980,19 @@ async function handleDataRequest(requestId, path, harenDir, send) {
1046
1980
  }
1047
1981
  send({ type: "data-response", requestId, data });
1048
1982
  }
1049
- async function handleCommand(commandId, prompt2, cli, config, send) {
1050
- const { mkdir: mkdir3 } = await import("fs/promises");
1051
- await mkdir3(`${config.harenDir}/events`, { recursive: true });
1052
- const { appendEvent: appendEvent2 } = await Promise.resolve().then(() => (init_events(), exports_events));
1983
+ async function handleCommand(commandId, prompt, cli, config, send) {
1984
+ const { mkdir } = await import("fs/promises");
1985
+ await mkdir(`${config.harenDir}/events`, { recursive: true });
1986
+ await Promise.resolve().then(() => init_events());
1053
1987
  const eventsPath = `${config.harenDir}/events/agent-commands.jsonl`;
1054
- await appendEvent2(eventsPath, {
1988
+ await appendEvent(eventsPath, {
1055
1989
  type: "agent-command",
1056
1990
  timestamp: new Date().toISOString(),
1057
1991
  cli,
1058
- prompt: prompt2,
1992
+ prompt,
1059
1993
  commandId
1060
1994
  });
1061
- await executeCLI(cli, prompt2, (chunk, done) => {
1995
+ await executeCLI(cli, prompt, (chunk, done) => {
1062
1996
  send({ type: "command-output", commandId, chunk, done });
1063
1997
  });
1064
1998
  }
@@ -1067,13 +2001,7 @@ var init_request_handler = __esm(() => {
1067
2001
  });
1068
2002
 
1069
2003
  // src/agent/connection.ts
1070
- var exports_connection = {};
1071
- __export(exports_connection, {
1072
- connectToPortal: () => connectToPortal,
1073
- buildWsUrl: () => buildWsUrl,
1074
- buildAuthMessage: () => buildAuthMessage
1075
- });
1076
- import { join as join6 } from "path";
2004
+ import { join as join10 } from "path";
1077
2005
  function buildWsUrl(portalUrl) {
1078
2006
  return portalUrl.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws/agent";
1079
2007
  }
@@ -1087,7 +2015,7 @@ function buildAuthMessage(opts) {
1087
2015
  };
1088
2016
  }
1089
2017
  async function connectToPortal(config) {
1090
- await Bun.write(join6(config.harenDir, ".agent.pid"), process.pid.toString());
2018
+ await Bun.write(join10(config.harenDir, ".agent.pid"), process.pid.toString());
1091
2019
  setupCleanup(config.harenDir);
1092
2020
  try {
1093
2021
  await connectWebSocket(config);
@@ -1105,7 +2033,7 @@ async function connectToPortal(config) {
1105
2033
  }
1106
2034
  async function connectWebSocket(config) {
1107
2035
  const wsUrl = buildWsUrl(config.portalUrl);
1108
- return new Promise((resolve3, reject) => {
2036
+ return new Promise((resolve, reject) => {
1109
2037
  const ws = new WebSocket(wsUrl);
1110
2038
  const timeout = setTimeout(() => {
1111
2039
  ws.close();
@@ -1121,14 +2049,14 @@ async function connectWebSocket(config) {
1121
2049
  if (msg.type === "auth-ok") {
1122
2050
  console.log(`Connected! Session: ${msg.sessionId}`);
1123
2051
  startHeartbeat(ws);
1124
- const { handleServerMessage: handleServerMessage2 } = await Promise.resolve().then(() => (init_request_handler(), exports_request_handler));
1125
- ws.onmessage = (event2) => {
1126
- const innerMsg = JSON.parse(event2.data);
1127
- handleServerMessage2(innerMsg, config, (response) => {
2052
+ await Promise.resolve().then(() => init_request_handler());
2053
+ ws.onmessage = (event) => {
2054
+ const innerMsg = JSON.parse(event.data);
2055
+ handleServerMessage(innerMsg, config, (response) => {
1128
2056
  ws.send(JSON.stringify(response));
1129
2057
  });
1130
2058
  };
1131
- resolve3();
2059
+ resolve();
1132
2060
  } else if (msg.type === "auth-fail") {
1133
2061
  clearTimeout(timeout);
1134
2062
  console.error(`Auth failed: ${msg.reason}`);
@@ -1177,7 +2105,7 @@ async function connectSSE(config) {
1177
2105
  throw new Error("SSE auth failed");
1178
2106
  const { sessionId } = await authRes.json();
1179
2107
  console.log(`Connected via SSE! Session: ${sessionId}`);
1180
- const { handleServerMessage: handleServerMessage2 } = await Promise.resolve().then(() => (init_request_handler(), exports_request_handler));
2108
+ await Promise.resolve().then(() => init_request_handler());
1181
2109
  const streamRes = await fetch(`${config.portalUrl}/sse/agent/stream?sessionId=${sessionId}`);
1182
2110
  const reader = streamRes.body?.getReader();
1183
2111
  if (!reader)
@@ -1202,7 +2130,7 @@ async function connectSSE(config) {
1202
2130
  const data = line.slice(6);
1203
2131
  try {
1204
2132
  const msg = JSON.parse(data);
1205
- handleServerMessage2(msg, config, sendResponse);
2133
+ handleServerMessage(msg, config, sendResponse);
1206
2134
  } catch {}
1207
2135
  }
1208
2136
  }
@@ -1223,7 +2151,7 @@ async function connectPolling(config) {
1223
2151
  throw new Error("Polling auth failed");
1224
2152
  const { sessionId } = await authRes.json();
1225
2153
  console.log(`Connected via polling! Session: ${sessionId}`);
1226
- const { handleServerMessage: handleServerMessage2 } = await Promise.resolve().then(() => (init_request_handler(), exports_request_handler));
2154
+ await Promise.resolve().then(() => init_request_handler());
1227
2155
  const sendResponse = async (response) => {
1228
2156
  await fetch(`${config.portalUrl}/poll/agent/send?sessionId=${sessionId}`, {
1229
2157
  method: "POST",
@@ -1236,14 +2164,14 @@ async function connectPolling(config) {
1236
2164
  const res = await fetch(`${config.portalUrl}/poll/agent/messages?sessionId=${sessionId}`);
1237
2165
  const { messages } = await res.json();
1238
2166
  for (const msg of messages) {
1239
- handleServerMessage2(msg, config, sendResponse);
2167
+ handleServerMessage(msg, config, sendResponse);
1240
2168
  }
1241
2169
  } catch {}
1242
2170
  await Bun.sleep(2000);
1243
2171
  }
1244
2172
  }
1245
2173
  function setupCleanup(harenDir) {
1246
- const pidPath = join6(harenDir, ".agent.pid");
2174
+ const pidPath = join10(harenDir, ".agent.pid");
1247
2175
  const cleanup = async () => {
1248
2176
  console.log("Agent shutting down...");
1249
2177
  const { unlink } = await import("fs/promises");
@@ -1256,45 +2184,43 @@ function setupCleanup(harenDir) {
1256
2184
  var init_connection = () => {};
1257
2185
 
1258
2186
  // src/commands/agent.ts
1259
- var exports_agent = {};
1260
- __export(exports_agent, {
1261
- agent: () => agent
1262
- });
1263
- import { join as join7 } from "path";
1264
- async function findHarenDir() {
1265
- const cwd = process.cwd();
1266
- const harenDir = join7(cwd, "haren");
1267
- const manifestFile = Bun.file(join7(harenDir, "manifest.yaml"));
1268
- if (await manifestFile.exists())
1269
- return harenDir;
1270
- return null;
1271
- }
1272
- async function getGitRemoteUrl() {
1273
- try {
1274
- const proc = Bun.spawn(["git", "remote", "get-url", "origin"], {
1275
- stdout: "pipe",
1276
- stderr: "pipe"
1277
- });
1278
- const text = await new Response(proc.stdout).text();
1279
- return text.trim() || null;
1280
- } catch {
1281
- return null;
1282
- }
1283
- }
2187
+ import { join as join11 } from "path";
1284
2188
  function readLine2(question) {
1285
2189
  process.stdout.write(question);
1286
- return new Promise((resolve3) => {
2190
+ return new Promise((resolve) => {
1287
2191
  let data = "";
1288
2192
  process.stdin.resume();
1289
2193
  process.stdin.once("data", (chunk) => {
1290
2194
  data = chunk.toString().trim();
1291
2195
  process.stdin.pause();
1292
- resolve3(data);
2196
+ resolve(data);
1293
2197
  });
1294
2198
  });
1295
2199
  }
2200
+ function parseAgentArgs(args) {
2201
+ const harenDir = harenDirFlag(args);
2202
+ let subcommand;
2203
+ for (let i = 0;i < args.length; i++) {
2204
+ if (args[i] === "--haren-dir") {
2205
+ i++;
2206
+ continue;
2207
+ }
2208
+ if (args[i].startsWith("-"))
2209
+ continue;
2210
+ subcommand = args[i];
2211
+ break;
2212
+ }
2213
+ return { subcommand, harenDir };
2214
+ }
1296
2215
  async function agent(args) {
1297
- const subcommand = args[0];
2216
+ let parsed;
2217
+ try {
2218
+ parsed = parseAgentArgs(args);
2219
+ } catch (err) {
2220
+ console.error(err.message);
2221
+ process.exit(1);
2222
+ }
2223
+ const { subcommand } = parsed;
1298
2224
  if (!subcommand || subcommand === "help") {
1299
2225
  console.log("Usage:");
1300
2226
  console.log(" haren agent start Start the local agent");
@@ -1302,9 +2228,19 @@ async function agent(args) {
1302
2228
  console.log(" haren agent status Show agent connection status");
1303
2229
  return;
1304
2230
  }
1305
- const harenDir = await findHarenDir();
1306
- if (!harenDir) {
1307
- console.error("No haren/ directory found. Run 'haren init' first.");
2231
+ let harenDir;
2232
+ try {
2233
+ const location = await resolveHarenDir(process.cwd(), {
2234
+ harenDir: parsed.harenDir,
2235
+ env: process.env
2236
+ });
2237
+ if (!location) {
2238
+ console.error("No haren folder found. Run 'haren init' first.");
2239
+ process.exit(1);
2240
+ }
2241
+ harenDir = location.harenDir;
2242
+ } catch (err) {
2243
+ console.error(err instanceof MultipleHarenDirsError ? err.message : String(err));
1308
2244
  process.exit(1);
1309
2245
  }
1310
2246
  switch (subcommand) {
@@ -1342,19 +2278,20 @@ async function startAgent(harenDir) {
1342
2278
  config = { portalUrl, teamCode, userId, userName };
1343
2279
  await writeAgentConfig(harenDir, config);
1344
2280
  console.log(`
1345
- Config saved to haren/.agent.json`);
2281
+ Config saved to ${join11(harenDir, ".agent.json")}`);
1346
2282
  }
1347
- const gitRemoteUrl = await getGitRemoteUrl();
2283
+ const gitRemoteUrl = await getRemoteUrl(harenDir);
1348
2284
  if (!gitRemoteUrl) {
1349
- console.error("Could not detect git remote URL. Is this a git repository?");
2285
+ console.error(`Could not read the git remote of ${harenDir}.`);
2286
+ console.error(`Add one with: git -C ${harenDir} remote add origin <url>`);
1350
2287
  process.exit(1);
1351
2288
  }
1352
2289
  const projectName = gitRemoteUrl.split("/").pop()?.replace(".git", "") ?? "unknown";
1353
2290
  const clis = await detectCLIs();
1354
2291
  console.log(`Available CLIs: ${clis.length > 0 ? clis.join(", ") : "none"}`);
1355
- const { connectToPortal: connectToPortal2 } = await Promise.resolve().then(() => (init_connection(), exports_connection));
2292
+ await Promise.resolve().then(() => init_connection());
1356
2293
  console.log(`Connecting to ${config.portalUrl}...`);
1357
- await connectToPortal2({
2294
+ await connectToPortal({
1358
2295
  portalUrl: config.portalUrl,
1359
2296
  teamCode: config.teamCode,
1360
2297
  userId: config.userId,
@@ -1365,7 +2302,7 @@ Config saved to haren/.agent.json`);
1365
2302
  });
1366
2303
  }
1367
2304
  async function stopAgent(harenDir) {
1368
- const pidFile = Bun.file(join7(harenDir, ".agent.pid"));
2305
+ const pidFile = Bun.file(join11(harenDir, ".agent.pid"));
1369
2306
  if (!await pidFile.exists()) {
1370
2307
  console.log("Agent is not running.");
1371
2308
  return;
@@ -1378,7 +2315,7 @@ async function stopAgent(harenDir) {
1378
2315
  console.log("Agent process not found. Cleaning up.");
1379
2316
  }
1380
2317
  const { unlink } = await import("fs/promises");
1381
- await unlink(join7(harenDir, ".agent.pid")).catch(() => {});
2318
+ await unlink(join11(harenDir, ".agent.pid")).catch(() => {});
1382
2319
  }
1383
2320
  async function showStatus(harenDir) {
1384
2321
  const config = await readAgentConfig(harenDir);
@@ -1386,7 +2323,7 @@ async function showStatus(harenDir) {
1386
2323
  console.log("Agent is not configured. Run 'haren agent start' first.");
1387
2324
  return;
1388
2325
  }
1389
- const pidFile = Bun.file(join7(harenDir, ".agent.pid"));
2326
+ const pidFile = Bun.file(join11(harenDir, ".agent.pid"));
1390
2327
  const isRunning = await pidFile.exists();
1391
2328
  console.log(`Portal: ${config.portalUrl}`);
1392
2329
  console.log(`Team: ${config.teamCode}`);
@@ -1400,6 +2337,8 @@ async function showStatus(harenDir) {
1400
2337
  var init_agent = __esm(() => {
1401
2338
  init_config();
1402
2339
  init_cli_detector();
2340
+ init_resolve();
2341
+ init_git();
1403
2342
  });
1404
2343
 
1405
2344
  // src/index.ts
@@ -1409,7 +2348,13 @@ function parseArgs(args) {
1409
2348
  }
1410
2349
  const command = args[0];
1411
2350
  const rest = args.slice(1);
2351
+ if (rest.includes("--help") || rest.includes("-h")) {
2352
+ return { command: "help", args: [] };
2353
+ }
1412
2354
  switch (command) {
2355
+ case "--help":
2356
+ case "-h":
2357
+ return { command: "help", args: [] };
1413
2358
  case "init":
1414
2359
  case "upgrade":
1415
2360
  case "agent":
@@ -1423,24 +2368,26 @@ async function main() {
1423
2368
  const parsed = parseArgs(args);
1424
2369
  switch (parsed.command) {
1425
2370
  case "init": {
1426
- const { init: init2 } = await Promise.resolve().then(() => (init_init(), exports_init));
1427
- await init2(parsed.args);
2371
+ await Promise.resolve().then(() => init_init());
2372
+ await init(parsed.args);
1428
2373
  break;
1429
2374
  }
1430
2375
  case "upgrade": {
1431
- const { upgrade: upgrade2 } = await Promise.resolve().then(() => (init_upgrade(), exports_upgrade));
1432
- await upgrade2(parsed.args);
2376
+ await Promise.resolve().then(() => init_upgrade());
2377
+ await upgrade(parsed.args);
1433
2378
  break;
1434
2379
  }
1435
2380
  case "agent": {
1436
- const { agent: agent2 } = await Promise.resolve().then(() => (init_agent(), exports_agent));
1437
- await agent2(parsed.args);
2381
+ await Promise.resolve().then(() => init_agent());
2382
+ await agent(parsed.args);
1438
2383
  break;
1439
2384
  }
1440
2385
  case "help":
1441
2386
  console.log("Usage:");
1442
- console.log(" haren init Create a new Haren workspace");
1443
- console.log(" haren upgrade Upgrade framework files (agents, skills, templates)");
2387
+ console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
2388
+ console.log(" --dir <path> --layout monorepo|workspace --haren-dir <name>");
2389
+ console.log(" --yes|-y --dry-run --force");
2390
+ console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run)");
1444
2391
  console.log(" haren agent Manage local agent (start, stop, status)");
1445
2392
  break;
1446
2393
  case "unknown":
@@ -1450,7 +2397,9 @@ async function main() {
1450
2397
  }
1451
2398
  }
1452
2399
  main().catch((err) => {
1453
- console.error(err);
2400
+ const debug = process.env.HAREN_DEBUG === "1";
2401
+ const message = err instanceof Error ? debug && err.stack || err.message : String(err);
2402
+ console.error(` ${message}`);
1454
2403
  process.exit(1);
1455
2404
  });
1456
2405
  export {