@odarino/haren 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/content/agents/architect.md +69 -0
  2. package/content/agents/developer.md +62 -0
  3. package/content/agents/feedback.md +42 -0
  4. package/content/agents/ideator.md +68 -0
  5. package/content/agents/planner.md +81 -0
  6. package/content/agents/qa-engineer.md +337 -0
  7. package/content/agents/researcher.md +57 -0
  8. package/content/agents/reviewer.md +74 -0
  9. package/content/skills/audit-workspace/SKILL.md +183 -0
  10. package/content/skills/create-artifact/SKILL.md +41 -0
  11. package/content/skills/decompose/SKILL.md +74 -0
  12. package/content/skills/discover/SKILL.md +54 -0
  13. package/content/skills/discover/blueprint.md +27 -0
  14. package/content/skills/discover/explore.md +33 -0
  15. package/content/skills/discover/inherit.md +34 -0
  16. package/content/skills/evaluate/SKILL.md +99 -0
  17. package/content/skills/extract-stories/SKILL.md +287 -0
  18. package/content/skills/generate-mockup/SKILL.md +140 -0
  19. package/content/skills/ideate/SKILL.md +150 -0
  20. package/content/skills/implement/SKILL.md +68 -0
  21. package/content/skills/plan/SKILL.md +138 -0
  22. package/content/skills/read-context/SKILL.md +84 -0
  23. package/content/skills/research/SKILL.md +44 -0
  24. package/content/skills/resolve-next-id/SKILL.md +27 -0
  25. package/content/skills/search-artifact/SKILL.md +30 -0
  26. package/content/skills/update-links/SKILL.md +35 -0
  27. package/content/skills/update-tracking/SKILL.md +68 -0
  28. package/content/skills/validate-artifact/SKILL.md +78 -0
  29. package/content/templates/architecture.md +51 -0
  30. package/content/templates/concept-brief.md +45 -0
  31. package/content/templates/context-brief.md +34 -0
  32. package/content/templates/design.md +25 -0
  33. package/content/templates/iteration.md +49 -0
  34. package/content/templates/module-map.md +25 -0
  35. package/content/templates/module.md +34 -0
  36. package/content/templates/research.md +33 -0
  37. package/content/templates/review.md +29 -0
  38. package/content/templates/session-log.md +21 -0
  39. package/content/templates/spec.md +50 -0
  40. package/content/templates/tasks.md +24 -0
  41. package/content/templates/team-workflow.md +203 -0
  42. package/dist/index.js +1458 -0
  43. package/package.json +49 -0
package/dist/index.js ADDED
@@ -0,0 +1,1458 @@
1
+ #!/usr/bin/env bun
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
+ });
27
+ };
28
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
29
+ var __require = import.meta.require;
30
+
31
+ // src/lib/content-dir.ts
32
+ import { existsSync } from "fs";
33
+ import { join, resolve } from "path";
34
+ function resolveContentDir(candidates) {
35
+ const probes = candidates ?? [
36
+ resolve(import.meta.dir, "..", "content"),
37
+ resolve(import.meta.dir, "..", "..", "..", "..", "content")
38
+ ];
39
+ for (const dir of probes) {
40
+ if (existsSync(join(dir, "agents")))
41
+ return dir;
42
+ }
43
+ throw new Error(`Could not locate the Haren content directory. Tried:
44
+ ${probes.join(`
45
+ `)}`);
46
+ }
47
+ var init_content_dir = () => {};
48
+
49
+ // src/commands/init.ts
50
+ var exports_init = {};
51
+ __export(exports_init, {
52
+ scaffoldWorkspace: () => scaffoldWorkspace,
53
+ scaffoldSkillMd: () => scaffoldSkillMd,
54
+ init: () => init
55
+ });
56
+ import { mkdir, writeFile, readFile, readdir, copyFile } from "fs/promises";
57
+ import { join as join2, resolve as resolve2 } from "path";
58
+ function readLine() {
59
+ return new Promise((resolve3) => {
60
+ const stdin = process.stdin;
61
+ stdin.resume();
62
+ stdin.setEncoding("utf-8");
63
+ const onData = (data) => {
64
+ stdin.removeListener("data", onData);
65
+ stdin.pause();
66
+ resolve3(data.toString().trim());
67
+ };
68
+ stdin.on("data", onData);
69
+ });
70
+ }
71
+ async function prompt(question, defaultValue) {
72
+ const suffix = defaultValue ? ` \x1B[2m(${defaultValue})\x1B[0m` : "";
73
+ process.stdout.write(` \x1B[36m?\x1B[0m ${question}${suffix} `);
74
+ const value = await readLine();
75
+ return value || defaultValue || "";
76
+ }
77
+ async function promptSelect(question, options, descriptions, defaultValue) {
78
+ console.log(` \x1B[36m?\x1B[0m ${question}`);
79
+ for (const opt of options) {
80
+ const marker = opt === defaultValue ? "\x1B[36m>\x1B[0m" : " ";
81
+ const label = opt === defaultValue ? `\x1B[1m${opt}\x1B[0m` : opt;
82
+ console.log(` ${marker} ${label} \x1B[2m\u2014 ${descriptions[opt]}\x1B[0m`);
83
+ }
84
+ process.stdout.write(` \x1B[2m enter choice:\x1B[0m `);
85
+ while (true) {
86
+ const value = (await readLine()).toLowerCase();
87
+ if (!value)
88
+ return defaultValue;
89
+ if (options.includes(value))
90
+ return value;
91
+ process.stdout.write(` \x1B[31m!\x1B[0m Invalid. Choose: ${options.join(", ")} `);
92
+ }
93
+ }
94
+ function getDirectories(iterations) {
95
+ const dirs = [
96
+ "agents",
97
+ "skills/research",
98
+ "skills/discover",
99
+ "skills/decompose",
100
+ "skills/plan",
101
+ "skills/implement",
102
+ "skills/evaluate",
103
+ "skills/read-context",
104
+ "skills/create-artifact",
105
+ "skills/validate-artifact",
106
+ "skills/search-artifact",
107
+ "skills/resolve-next-id",
108
+ "skills/update-links",
109
+ "skills/update-tracking",
110
+ "skills/generate-mockup",
111
+ "artifacts/_registry",
112
+ "artifacts/00-baseline",
113
+ "artifacts/01-research",
114
+ "artifacts/02-discovery",
115
+ "artifacts/03-modules",
116
+ "artifacts/04-plans",
117
+ "artifacts/05-implementation",
118
+ "artifacts/06-evaluation",
119
+ "events",
120
+ "templates",
121
+ "hooks"
122
+ ];
123
+ if (iterations) {
124
+ dirs.push("artifacts/07-iterations");
125
+ }
126
+ return dirs;
127
+ }
128
+ async function copyRecursive(src, dest) {
129
+ const entries = await readdir(src, { withFileTypes: true });
130
+ await mkdir(dest, { recursive: true });
131
+ for (const entry of entries) {
132
+ const srcPath = join2(src, entry.name);
133
+ const destPath = join2(dest, entry.name);
134
+ if (entry.isDirectory()) {
135
+ await copyRecursive(srcPath, destPath);
136
+ } else {
137
+ await copyFile(srcPath, destPath);
138
+ }
139
+ }
140
+ }
141
+ async function scaffoldWorkspace(targetDir, options) {
142
+ for (const dir of getDirectories(!!options.iterations)) {
143
+ await mkdir(join2(targetDir, dir), { recursive: true });
144
+ }
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);
171
+ const progressData = {
172
+ project: options.project,
173
+ version: 1,
174
+ phase: "init",
175
+ status: "active",
176
+ modules: {},
177
+ dependencies: {}
178
+ };
179
+ if (options.iterations) {
180
+ progressData.currentIteration = 1;
181
+ }
182
+ await writeFile(join2(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
183
+ await writeFile(join2(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
184
+
185
+ Append-only log of framework improvement suggestions captured during usage.
186
+
187
+ ---
188
+ `);
189
+ await writeFile(join2(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
190
+
191
+ Master registry of all artifacts in this Haren workspace.
192
+
193
+ | ID | Type | Module | Status | Path |
194
+ |----|------|--------|--------|------|
195
+ `);
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
+ });
278
+ `);
279
+ await scaffoldSkillMd(targetDir);
280
+ 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
+ }
367
+ }
368
+ async function scaffoldSkillMd(targetDir) {
369
+ await writeFile(join2(targetDir, "skill.md"), `---
370
+ name: haren
371
+ description: Agentic SDLC framework \u2014 orchestrates AI agents through structured phases
372
+ ---
373
+
374
+ # Haren
375
+
376
+ You are operating within the Haren agentic SDLC framework.
377
+
378
+ ## On Session Start
379
+
380
+ 1. Read \`manifest.yaml\` to understand the project
381
+ 2. Read \`progress.json\` to understand current state
382
+ 3. Read \`artifacts/_registry/artifact-index.md\` for artifact inventory
383
+ 4. **Scan \`artifacts/00-baseline/\`** for documents (PDFs, docs, markdown, etc.)
384
+ - If docs found and mode is \`undecided\` \u2192 auto-recommend \`blueprint\` mode
385
+ - If docs found and discovery hasn't started \u2192 suggest starting discover phase
386
+ - If new docs added since last session \u2192 flag them and ask about re-discovery
387
+ 5. **If mode is "undecided" and no baseline docs found:** Help the user choose a mode. Ask them:
388
+ - What do you want to build? (get a brief description)
389
+ - Do you already have documentation or specs for it?
390
+ - Do you have an existing codebase to build on?
391
+ Based on their answers, recommend a mode and update \`manifest.yaml\`:
392
+ - Has docs/specs \u2192 tell them to drop docs in \`artifacts/00-baseline/\` then \`blueprint\`
393
+ - Starting from scratch, just an idea \u2192 \`explore\`
394
+ - Has existing code \u2192 \`inherit\`
395
+ 6. Suggest next action based on current state
396
+
397
+ ## Available Actions
398
+
399
+ | Intent | Skill | Agent |
400
+ |--------|-------|-------|
401
+ | Design a feature | discover/ (brainstorming) | Researcher |
402
+ | Start a new project | discover/ | Researcher |
403
+ | Research a topic | research/ | Researcher |
404
+ | Break into modules | decompose/ | Architect |
405
+ | Extract stories from docs | extract-stories/ | Researcher |
406
+ | Plan a module | plan/ | Planner |
407
+ | Implement a module | implement/ | Developer |
408
+ | Evaluate a module | evaluate/ | Reviewer |
409
+ | Check project status | read-context/ | \u2014 |
410
+ | Search artifacts | search-artifact/ | \u2014 |
411
+ | Draw a UI wireframe | generate-mockup/ | \u2014 |
412
+
413
+ ## How to dispatch
414
+
415
+ - User says "let's build X" or describes a new feature \u2192 discover/ skill (triggers brainstorming)
416
+ - User says "what's next?" \u2192 read \`progress.json\` \u2192 suggest action
417
+ - User says "extract stories" or "break down the PRD" or "create stories from docs" \u2192 extract-stories/ skill
418
+ - User says "let's work on {module}" \u2192 check module phase \u2192 dispatch appropriate skill
419
+ - User says "I need to research X" \u2192 research/ skill
420
+ - User says "status" or "where are we?" \u2192 read-context/ skill
421
+ - User says "start" or "init" \u2192 discover/ skill
422
+ - User asks about an artifact \u2192 search-artifact/ skill
423
+
424
+ ## Artifact Ownership
425
+
426
+ | Artifact | Owner | Location |
427
+ |----------|-------|----------|
428
+ | Spec (requirements, stories) | BA | \`artifacts/03-modules/{module}/spec.md\` |
429
+ | Module definition | Discover phase | \`artifacts/03-modules/{module}/module.md\` |
430
+ | Design (architecture) | Dev | \`artifacts/04-plans/{module}/design.md\` |
431
+ | Tasks (implementation) | Dev | \`artifacts/04-plans/{module}/[iteration-{N}/]tasks.md\` |
432
+
433
+ ## Plan Paths
434
+
435
+ All skills that read or write plan artifacts MUST resolve paths using this convention:
436
+
437
+ **Spec path (BA-owned, always the same):**
438
+ - \`artifacts/03-modules/{module}/spec.md\` \u2014 requirements, user stories (STORY-IDs), acceptance criteria
439
+ - BA updates this file and adds a row to the Changelog table
440
+ - Devs read this but never write to it
441
+
442
+ **If \`manifest.yaml\` has \`iterations.enabled: true\`:**
443
+ - Read \`currentIteration\` from \`progress.json\`
444
+ - **Active plan path:** \`artifacts/04-plans/{module}/iteration-{N}/\` \u2014 design + tasks for current iteration
445
+ - **Master plan path:** \`artifacts/04-plans/{module}/\` \u2014 full module design
446
+ - The plan skill writes to BOTH master and active paths (it is the only skill that does this)
447
+
448
+ **If no \`iterations\` block in manifest.yaml:**
449
+ - **Active plan path:** \`artifacts/04-plans/{module}/\` \u2014 contains design.md, tasks.md
450
+ - **Master plan path:** (same as active)
451
+
452
+ When a skill says "read the spec", it means from \`artifacts/03-modules/{module}/spec.md\`.
453
+ When a skill says "read tasks" or "read design", it means from the **active plan path**.
454
+ When a skill says "read the master plan" or needs full module context, it means from the **master plan path**.
455
+
456
+ ## Rules
457
+
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++;
513
+ }
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++;
523
+ }
524
+ }
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.");
530
+ process.exit(1);
531
+ }
532
+ console.log("");
533
+ console.log("\x1B[36m" + `
534
+ \u2571\\
535
+ \u2571 \\
536
+ \u2571 \u25C6 \\
537
+ \u2571 \u2571 \u2572 \\
538
+ \u2571 \u2571 \u2572 \\
539
+ \u2571\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2567\u2550\u2550\\
540
+ \u2551 \u2551
541
+ \u2551 \u2551
542
+ \u2588\u2588\u2557 \u2551\u2588\u2588\u2557 \u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
543
+ \u2588\u2588\u2551 \u2551\u2588\u2588\u2551 \u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551
544
+ \u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
545
+ \u2588\u2588\u2554\u2550\u2550\u2551\u2588\u2588\u2551 \u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551
546
+ \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
+ \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
+ ` + "\x1B[0m");
549
+ console.log("\x1B[2m Agentic SDLC Framework v1.1.0\x1B[0m");
550
+ 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
+ }
574
+ }
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;
582
+ }
583
+ console.log("");
584
+ await mkdir(targetDir, { recursive: true });
585
+ await scaffoldWorkspace(targetDir, {
586
+ project,
587
+ mode,
588
+ language,
589
+ iterations,
590
+ editor
591
+ });
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})`);
598
+ }
599
+ console.log(` \x1B[32m+\x1B[0m Editor: \x1B[1m${editor}\x1B[0m`);
600
+ console.log("");
601
+ console.log("\x1B[2m Files created in haren/:\x1B[0m");
602
+ 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`);
613
+ }
614
+ if (editor === "cursor" || editor === "both") {
615
+ console.log(` \x1B[32m+\x1B[0m .cursorrules + .cursor/rules/haren.mdc created`);
616
+ }
617
+ 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("");
624
+ }
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
+ `;
732
+ var init_init = __esm(() => {
733
+ init_content_dir();
734
+ MODES = ["blueprint", "explore", "inherit", "undecided"];
735
+ MODE_DESCRIPTIONS = {
736
+ blueprint: "Greenfield project with existing docs",
737
+ explore: "Greenfield project from scratch",
738
+ inherit: "Brownfield project with existing code",
739
+ undecided: "Decide later \u2014 LLM will help you choose"
740
+ };
741
+ });
742
+
743
+ // 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";
750
+ async function copyRecursive2(src, dest) {
751
+ const entries = await readdir2(src, { withFileTypes: true });
752
+ await mkdir2(dest, { recursive: true });
753
+ for (const entry of entries) {
754
+ const srcPath = join3(src, entry.name);
755
+ const destPath = join3(dest, entry.name);
756
+ if (entry.isDirectory()) {
757
+ await copyRecursive2(srcPath, destPath);
758
+ } else {
759
+ await copyFile2(srcPath, destPath);
760
+ }
761
+ }
762
+ }
763
+ async function countFiles(dir) {
764
+ let count = 0;
765
+ const entries = await readdir2(dir, { withFileTypes: true });
766
+ for (const entry of entries) {
767
+ if (entry.isDirectory()) {
768
+ count += await countFiles(join3(dir, entry.name));
769
+ } else {
770
+ count++;
771
+ }
772
+ }
773
+ return count;
774
+ }
775
+ 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.");
783
+ process.exit(1);
784
+ }
785
+ const contentDir = resolveContentDir();
786
+ try {
787
+ await stat(contentDir);
788
+ } catch {
789
+ console.error("Could not find Haren package content directory.");
790
+ process.exit(1);
791
+ }
792
+ const dry = args.includes("--dry-run");
793
+ console.log("");
794
+ console.log("\x1B[36m Haren Upgrade\x1B[0m");
795
+ console.log(`\x1B[2m Workspace: ${targetDir}\x1B[0m`);
796
+ console.log("");
797
+ console.log("\x1B[2m Protected (not modified):\x1B[0m");
798
+ for (const f of USER_FILES) {
799
+ console.log(` \x1B[32m\u2713\x1B[0m ${f}`);
800
+ }
801
+ console.log("");
802
+ console.log("\x1B[2m Upgrading framework files:\x1B[0m");
803
+ let totalFiles = 0;
804
+ for (const dir of FRAMEWORK_DIRS) {
805
+ const srcDir = join3(contentDir, dir);
806
+ const destDir = join3(targetDir, dir);
807
+ const fileCount = await countFiles(srcDir);
808
+ totalFiles += fileCount;
809
+ console.log(` \x1B[36m\u2191\x1B[0m ${dir}/ \x1B[2m(${fileCount} files)\x1B[0m`);
810
+ }
811
+ console.log(` \x1B[36m\u2191\x1B[0m skill.md \x1B[2m(entry point)\x1B[0m`);
812
+ console.log("");
813
+ if (dry) {
814
+ console.log(`\x1B[33m Dry run \u2014 ${totalFiles + 1} files would be updated. No changes made.\x1B[0m`);
815
+ console.log("");
816
+ return;
817
+ }
818
+ for (const dir of FRAMEWORK_DIRS) {
819
+ await copyRecursive2(join3(contentDir, dir), join3(targetDir, dir));
820
+ }
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`);
825
+ console.log("");
826
+ }
827
+ var FRAMEWORK_DIRS, USER_FILES;
828
+ var init_upgrade = __esm(() => {
829
+ init_content_dir();
830
+ 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
+ ];
839
+ });
840
+
841
+ // src/agent/config.ts
842
+ import { join as join4 } from "path";
843
+ async function readAgentConfig(harenDir) {
844
+ const file = Bun.file(join4(harenDir, CONFIG_FILE));
845
+ if (!await file.exists())
846
+ return null;
847
+ return file.json();
848
+ }
849
+ async function writeAgentConfig(harenDir, config) {
850
+ const path = join4(harenDir, CONFIG_FILE);
851
+ await Bun.write(path, JSON.stringify(config, null, 2));
852
+ }
853
+ var CONFIG_FILE = ".agent.json";
854
+ var init_config = () => {};
855
+
856
+ // src/agent/cli-detector.ts
857
+ 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
+ }
868
+ }
869
+ async function detectCLIs() {
870
+ const results = await Promise.all(KNOWN_CLIS.map(async (cli) => ({
871
+ name: cli,
872
+ available: await checkCLI(cli)
873
+ })));
874
+ return results.filter((r) => r.available).map((r) => r.name);
875
+ }
876
+ var KNOWN_CLIS;
877
+ var init_cli_detector = __esm(() => {
878
+ KNOWN_CLIS = ["claude", "cursor", "github-copilot-cli"];
879
+ });
880
+
881
+ // src/agent/artifact-reader.ts
882
+ import { join as join5 } from "path";
883
+ import { readdir as readdir3 } from "fs/promises";
884
+ async function readProgress(harenDir) {
885
+ const file = Bun.file(join5(harenDir, "progress.json"));
886
+ if (!await file.exists())
887
+ return null;
888
+ return file.json();
889
+ }
890
+ async function readArtifactTree(harenDir) {
891
+ const artifactsDir = join5(harenDir, "artifacts");
892
+ try {
893
+ return await buildTree(artifactsDir, "artifacts");
894
+ } catch {
895
+ return [];
896
+ }
897
+ }
898
+ async function buildTree(dirPath, relativePath) {
899
+ const entries = await readdir3(dirPath, { withFileTypes: true });
900
+ const nodes = [];
901
+ for (const entry of entries) {
902
+ const entryPath = join5(relativePath, entry.name);
903
+ if (entry.isDirectory()) {
904
+ const children = await buildTree(join5(dirPath, entry.name), entryPath);
905
+ nodes.push({
906
+ name: entry.name,
907
+ type: "directory",
908
+ path: entryPath,
909
+ children
910
+ });
911
+ } else {
912
+ nodes.push({ name: entry.name, type: "file", path: entryPath });
913
+ }
914
+ }
915
+ return nodes.sort((a, b) => a.name.localeCompare(b.name));
916
+ }
917
+ async function readArtifact(harenDir, relativePath) {
918
+ const file = Bun.file(join5(harenDir, relativePath));
919
+ if (!await file.exists())
920
+ return null;
921
+ return file.text();
922
+ }
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 {
933
+ return [];
934
+ }
935
+ }
936
+ var init_artifact_reader = () => {};
937
+
938
+ // src/agent/cli-executor.ts
939
+ async function executeCLI(cli, prompt2, onOutput) {
940
+ const args = buildCLIArgs(cli, prompt2);
941
+ try {
942
+ const proc = Bun.spawn(args, {
943
+ stdout: "pipe",
944
+ stderr: "pipe",
945
+ cwd: process.cwd()
946
+ });
947
+ const reader = proc.stdout.getReader();
948
+ const decoder = new TextDecoder;
949
+ while (true) {
950
+ const { done, value } = await reader.read();
951
+ if (done)
952
+ break;
953
+ const chunk = decoder.decode(value);
954
+ onOutput(chunk, false);
955
+ }
956
+ const stderrReader = proc.stderr.getReader();
957
+ while (true) {
958
+ const { done, value } = await stderrReader.read();
959
+ if (done)
960
+ break;
961
+ const chunk = decoder.decode(value);
962
+ onOutput(chunk, false);
963
+ }
964
+ await proc.exited;
965
+ onOutput("", true);
966
+ } catch (err) {
967
+ onOutput(`Error executing ${cli}: ${err}
968
+ `, false);
969
+ onOutput("", true);
970
+ }
971
+ }
972
+ function buildCLIArgs(cli, prompt2) {
973
+ switch (cli) {
974
+ case "claude":
975
+ return ["claude", "--print", prompt2];
976
+ case "cursor":
977
+ return ["cursor", "--prompt", prompt2];
978
+ case "github-copilot-cli":
979
+ return ["github-copilot-cli", prompt2];
980
+ default:
981
+ return [cli, prompt2];
982
+ }
983
+ }
984
+
985
+ // 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";
992
+ async function appendEvent(path, event) {
993
+ const line = JSON.stringify(event) + `
994
+ `;
995
+ await appendFile(path, line);
996
+ }
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
+ var init_events = () => {};
1009
+
1010
+ // src/agent/request-handler.ts
1011
+ var exports_request_handler = {};
1012
+ __export(exports_request_handler, {
1013
+ handleServerMessage: () => handleServerMessage
1014
+ });
1015
+ function handleServerMessage(msg, config, send) {
1016
+ switch (msg.type) {
1017
+ case "data-request":
1018
+ handleDataRequest(msg.requestId, msg.path, config.harenDir, send);
1019
+ break;
1020
+ case "command":
1021
+ handleCommand(msg.commandId, msg.prompt, msg.cli, config, send);
1022
+ break;
1023
+ case "auth-ok":
1024
+ case "auth-fail":
1025
+ break;
1026
+ }
1027
+ }
1028
+ async function handleDataRequest(requestId, path, harenDir, send) {
1029
+ let data;
1030
+ switch (path) {
1031
+ case "progress":
1032
+ data = await readProgress(harenDir);
1033
+ break;
1034
+ case "artifacts":
1035
+ data = await readArtifactTree(harenDir);
1036
+ break;
1037
+ case "git-log":
1038
+ data = await readGitLog();
1039
+ break;
1040
+ default:
1041
+ if (path.startsWith("artifacts/")) {
1042
+ data = await readArtifact(harenDir, path);
1043
+ } else {
1044
+ data = null;
1045
+ }
1046
+ }
1047
+ send({ type: "data-response", requestId, data });
1048
+ }
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));
1053
+ const eventsPath = `${config.harenDir}/events/agent-commands.jsonl`;
1054
+ await appendEvent2(eventsPath, {
1055
+ type: "agent-command",
1056
+ timestamp: new Date().toISOString(),
1057
+ cli,
1058
+ prompt: prompt2,
1059
+ commandId
1060
+ });
1061
+ await executeCLI(cli, prompt2, (chunk, done) => {
1062
+ send({ type: "command-output", commandId, chunk, done });
1063
+ });
1064
+ }
1065
+ var init_request_handler = __esm(() => {
1066
+ init_artifact_reader();
1067
+ });
1068
+
1069
+ // 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";
1077
+ function buildWsUrl(portalUrl) {
1078
+ return portalUrl.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws/agent";
1079
+ }
1080
+ function buildAuthMessage(opts) {
1081
+ return {
1082
+ type: "auth",
1083
+ teamCode: opts.teamCode,
1084
+ gitRemoteUrl: opts.gitRemoteUrl,
1085
+ projectName: opts.projectName,
1086
+ userId: opts.userId
1087
+ };
1088
+ }
1089
+ async function connectToPortal(config) {
1090
+ await Bun.write(join6(config.harenDir, ".agent.pid"), process.pid.toString());
1091
+ setupCleanup(config.harenDir);
1092
+ try {
1093
+ await connectWebSocket(config);
1094
+ return;
1095
+ } catch {
1096
+ console.log("WebSocket failed, trying SSE...");
1097
+ }
1098
+ try {
1099
+ await connectSSE(config);
1100
+ return;
1101
+ } catch {
1102
+ console.log("SSE failed, trying polling...");
1103
+ }
1104
+ await connectPolling(config);
1105
+ }
1106
+ async function connectWebSocket(config) {
1107
+ const wsUrl = buildWsUrl(config.portalUrl);
1108
+ return new Promise((resolve3, reject) => {
1109
+ const ws = new WebSocket(wsUrl);
1110
+ const timeout = setTimeout(() => {
1111
+ ws.close();
1112
+ reject(new Error("WebSocket connection timeout"));
1113
+ }, 1e4);
1114
+ ws.onopen = () => {
1115
+ clearTimeout(timeout);
1116
+ const authMsg = buildAuthMessage(config);
1117
+ ws.send(JSON.stringify(authMsg));
1118
+ };
1119
+ ws.onmessage = async (event) => {
1120
+ const msg = JSON.parse(event.data);
1121
+ if (msg.type === "auth-ok") {
1122
+ console.log(`Connected! Session: ${msg.sessionId}`);
1123
+ 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) => {
1128
+ ws.send(JSON.stringify(response));
1129
+ });
1130
+ };
1131
+ resolve3();
1132
+ } else if (msg.type === "auth-fail") {
1133
+ clearTimeout(timeout);
1134
+ console.error(`Auth failed: ${msg.reason}`);
1135
+ ws.close();
1136
+ reject(new Error(msg.reason));
1137
+ }
1138
+ };
1139
+ let retryCount = 0;
1140
+ ws.onclose = () => {
1141
+ if (retryCount >= 10) {
1142
+ console.error("Max reconnection attempts reached. Run 'haren agent start' to retry.");
1143
+ return;
1144
+ }
1145
+ retryCount++;
1146
+ const delay = Math.min(1000 * 2 ** (retryCount - 1), 30000);
1147
+ console.log(`Disconnected. Reconnecting in ${delay / 1000}s...`);
1148
+ setTimeout(() => connectToPortal(config).catch(() => {}), delay);
1149
+ };
1150
+ ws.onerror = () => {
1151
+ clearTimeout(timeout);
1152
+ reject(new Error("WebSocket error"));
1153
+ };
1154
+ });
1155
+ }
1156
+ function startHeartbeat(ws) {
1157
+ const interval = setInterval(() => {
1158
+ if (ws.readyState === WebSocket.OPEN) {
1159
+ ws.send(JSON.stringify({ type: "heartbeat" }));
1160
+ } else {
1161
+ clearInterval(interval);
1162
+ }
1163
+ }, 30000);
1164
+ }
1165
+ async function connectSSE(config) {
1166
+ const authRes = await fetch(`${config.portalUrl}/sse/agent/auth`, {
1167
+ method: "POST",
1168
+ headers: { "Content-Type": "application/json" },
1169
+ body: JSON.stringify({
1170
+ teamCode: config.teamCode,
1171
+ gitRemoteUrl: config.gitRemoteUrl,
1172
+ projectName: config.projectName,
1173
+ userId: config.userId
1174
+ })
1175
+ });
1176
+ if (!authRes.ok)
1177
+ throw new Error("SSE auth failed");
1178
+ const { sessionId } = await authRes.json();
1179
+ console.log(`Connected via SSE! Session: ${sessionId}`);
1180
+ const { handleServerMessage: handleServerMessage2 } = await Promise.resolve().then(() => (init_request_handler(), exports_request_handler));
1181
+ const streamRes = await fetch(`${config.portalUrl}/sse/agent/stream?sessionId=${sessionId}`);
1182
+ const reader = streamRes.body?.getReader();
1183
+ if (!reader)
1184
+ throw new Error("No SSE stream");
1185
+ const decoder = new TextDecoder;
1186
+ const sendResponse = async (response) => {
1187
+ await fetch(`${config.portalUrl}/sse/agent/send?sessionId=${sessionId}`, {
1188
+ method: "POST",
1189
+ headers: { "Content-Type": "application/json" },
1190
+ body: JSON.stringify(response)
1191
+ });
1192
+ };
1193
+ while (true) {
1194
+ const { done, value } = await reader.read();
1195
+ if (done)
1196
+ break;
1197
+ const text = decoder.decode(value);
1198
+ const lines = text.split(`
1199
+ `);
1200
+ for (const line of lines) {
1201
+ if (line.startsWith("data: ")) {
1202
+ const data = line.slice(6);
1203
+ try {
1204
+ const msg = JSON.parse(data);
1205
+ handleServerMessage2(msg, config, sendResponse);
1206
+ } catch {}
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1211
+ async function connectPolling(config) {
1212
+ const authRes = await fetch(`${config.portalUrl}/poll/agent/auth`, {
1213
+ method: "POST",
1214
+ headers: { "Content-Type": "application/json" },
1215
+ body: JSON.stringify({
1216
+ teamCode: config.teamCode,
1217
+ gitRemoteUrl: config.gitRemoteUrl,
1218
+ projectName: config.projectName,
1219
+ userId: config.userId
1220
+ })
1221
+ });
1222
+ if (!authRes.ok)
1223
+ throw new Error("Polling auth failed");
1224
+ const { sessionId } = await authRes.json();
1225
+ console.log(`Connected via polling! Session: ${sessionId}`);
1226
+ const { handleServerMessage: handleServerMessage2 } = await Promise.resolve().then(() => (init_request_handler(), exports_request_handler));
1227
+ const sendResponse = async (response) => {
1228
+ await fetch(`${config.portalUrl}/poll/agent/send?sessionId=${sessionId}`, {
1229
+ method: "POST",
1230
+ headers: { "Content-Type": "application/json" },
1231
+ body: JSON.stringify(response)
1232
+ });
1233
+ };
1234
+ while (true) {
1235
+ try {
1236
+ const res = await fetch(`${config.portalUrl}/poll/agent/messages?sessionId=${sessionId}`);
1237
+ const { messages } = await res.json();
1238
+ for (const msg of messages) {
1239
+ handleServerMessage2(msg, config, sendResponse);
1240
+ }
1241
+ } catch {}
1242
+ await Bun.sleep(2000);
1243
+ }
1244
+ }
1245
+ function setupCleanup(harenDir) {
1246
+ const pidPath = join6(harenDir, ".agent.pid");
1247
+ const cleanup = async () => {
1248
+ console.log("Agent shutting down...");
1249
+ const { unlink } = await import("fs/promises");
1250
+ await unlink(pidPath).catch(() => {});
1251
+ process.exit(0);
1252
+ };
1253
+ process.on("SIGTERM", cleanup);
1254
+ process.on("SIGINT", cleanup);
1255
+ }
1256
+ var init_connection = () => {};
1257
+
1258
+ // 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
+ }
1284
+ function readLine2(question) {
1285
+ process.stdout.write(question);
1286
+ return new Promise((resolve3) => {
1287
+ let data = "";
1288
+ process.stdin.resume();
1289
+ process.stdin.once("data", (chunk) => {
1290
+ data = chunk.toString().trim();
1291
+ process.stdin.pause();
1292
+ resolve3(data);
1293
+ });
1294
+ });
1295
+ }
1296
+ async function agent(args) {
1297
+ const subcommand = args[0];
1298
+ if (!subcommand || subcommand === "help") {
1299
+ console.log("Usage:");
1300
+ console.log(" haren agent start Start the local agent");
1301
+ console.log(" haren agent stop Stop the local agent");
1302
+ console.log(" haren agent status Show agent connection status");
1303
+ return;
1304
+ }
1305
+ const harenDir = await findHarenDir();
1306
+ if (!harenDir) {
1307
+ console.error("No haren/ directory found. Run 'haren init' first.");
1308
+ process.exit(1);
1309
+ }
1310
+ switch (subcommand) {
1311
+ case "start":
1312
+ await startAgent(harenDir);
1313
+ break;
1314
+ case "stop":
1315
+ await stopAgent(harenDir);
1316
+ break;
1317
+ case "status":
1318
+ await showStatus(harenDir);
1319
+ break;
1320
+ default:
1321
+ console.error(`Unknown agent subcommand: ${subcommand}`);
1322
+ process.exit(1);
1323
+ }
1324
+ }
1325
+ async function startAgent(harenDir) {
1326
+ let config = await readAgentConfig(harenDir);
1327
+ if (!config) {
1328
+ console.log(`First-time agent setup
1329
+ `);
1330
+ const portalUrl = await readLine2("Portal URL (default: https://portal.example.com): ") || "https://portal.example.com";
1331
+ const teamCode = await readLine2("Team code: ");
1332
+ if (!teamCode) {
1333
+ console.error("Team code is required.");
1334
+ process.exit(1);
1335
+ }
1336
+ const userName = await readLine2("Your name: ");
1337
+ if (!userName) {
1338
+ console.error("Name is required.");
1339
+ process.exit(1);
1340
+ }
1341
+ const userId = crypto.randomUUID();
1342
+ config = { portalUrl, teamCode, userId, userName };
1343
+ await writeAgentConfig(harenDir, config);
1344
+ console.log(`
1345
+ Config saved to haren/.agent.json`);
1346
+ }
1347
+ const gitRemoteUrl = await getGitRemoteUrl();
1348
+ if (!gitRemoteUrl) {
1349
+ console.error("Could not detect git remote URL. Is this a git repository?");
1350
+ process.exit(1);
1351
+ }
1352
+ const projectName = gitRemoteUrl.split("/").pop()?.replace(".git", "") ?? "unknown";
1353
+ const clis = await detectCLIs();
1354
+ console.log(`Available CLIs: ${clis.length > 0 ? clis.join(", ") : "none"}`);
1355
+ const { connectToPortal: connectToPortal2 } = await Promise.resolve().then(() => (init_connection(), exports_connection));
1356
+ console.log(`Connecting to ${config.portalUrl}...`);
1357
+ await connectToPortal2({
1358
+ portalUrl: config.portalUrl,
1359
+ teamCode: config.teamCode,
1360
+ userId: config.userId,
1361
+ gitRemoteUrl,
1362
+ projectName,
1363
+ harenDir,
1364
+ availableCLIs: clis
1365
+ });
1366
+ }
1367
+ async function stopAgent(harenDir) {
1368
+ const pidFile = Bun.file(join7(harenDir, ".agent.pid"));
1369
+ if (!await pidFile.exists()) {
1370
+ console.log("Agent is not running.");
1371
+ return;
1372
+ }
1373
+ const pid = Number.parseInt(await pidFile.text(), 10);
1374
+ try {
1375
+ process.kill(pid, "SIGTERM");
1376
+ console.log(`Agent (PID ${pid}) stopped.`);
1377
+ } catch {
1378
+ console.log("Agent process not found. Cleaning up.");
1379
+ }
1380
+ const { unlink } = await import("fs/promises");
1381
+ await unlink(join7(harenDir, ".agent.pid")).catch(() => {});
1382
+ }
1383
+ async function showStatus(harenDir) {
1384
+ const config = await readAgentConfig(harenDir);
1385
+ if (!config) {
1386
+ console.log("Agent is not configured. Run 'haren agent start' first.");
1387
+ return;
1388
+ }
1389
+ const pidFile = Bun.file(join7(harenDir, ".agent.pid"));
1390
+ const isRunning = await pidFile.exists();
1391
+ console.log(`Portal: ${config.portalUrl}`);
1392
+ console.log(`Team: ${config.teamCode}`);
1393
+ console.log(`User: ${config.userName}`);
1394
+ console.log(`Status: ${isRunning ? "Running" : "Stopped"}`);
1395
+ if (isRunning) {
1396
+ const pid = Number.parseInt(await pidFile.text(), 10);
1397
+ console.log(`PID: ${pid}`);
1398
+ }
1399
+ }
1400
+ var init_agent = __esm(() => {
1401
+ init_config();
1402
+ init_cli_detector();
1403
+ });
1404
+
1405
+ // src/index.ts
1406
+ function parseArgs(args) {
1407
+ if (args.length === 0) {
1408
+ return { command: "help", args: [] };
1409
+ }
1410
+ const command = args[0];
1411
+ const rest = args.slice(1);
1412
+ switch (command) {
1413
+ case "init":
1414
+ case "upgrade":
1415
+ case "agent":
1416
+ return { command, args: rest };
1417
+ default:
1418
+ return { command: "unknown", args };
1419
+ }
1420
+ }
1421
+ async function main() {
1422
+ const args = process.argv.slice(2);
1423
+ const parsed = parseArgs(args);
1424
+ switch (parsed.command) {
1425
+ case "init": {
1426
+ const { init: init2 } = await Promise.resolve().then(() => (init_init(), exports_init));
1427
+ await init2(parsed.args);
1428
+ break;
1429
+ }
1430
+ case "upgrade": {
1431
+ const { upgrade: upgrade2 } = await Promise.resolve().then(() => (init_upgrade(), exports_upgrade));
1432
+ await upgrade2(parsed.args);
1433
+ break;
1434
+ }
1435
+ case "agent": {
1436
+ const { agent: agent2 } = await Promise.resolve().then(() => (init_agent(), exports_agent));
1437
+ await agent2(parsed.args);
1438
+ break;
1439
+ }
1440
+ case "help":
1441
+ console.log("Usage:");
1442
+ console.log(" haren init Create a new Haren workspace");
1443
+ console.log(" haren upgrade Upgrade framework files (agents, skills, templates)");
1444
+ console.log(" haren agent Manage local agent (start, stop, status)");
1445
+ break;
1446
+ case "unknown":
1447
+ console.error(`Unknown command: ${parsed.args[0]}`);
1448
+ console.log("Usage: haren init | haren upgrade");
1449
+ process.exit(1);
1450
+ }
1451
+ }
1452
+ main().catch((err) => {
1453
+ console.error(err);
1454
+ process.exit(1);
1455
+ });
1456
+ export {
1457
+ parseArgs
1458
+ };