@odarino/haren 1.2.2 → 1.3.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
@@ -406,10 +406,148 @@ var init_manifest = __esm(() => {
406
406
  YAML_SPECIAL_FLOAT = /^[-+]?\.(inf|nan)$/i;
407
407
  });
408
408
 
409
- // src/workspace/root-files.ts
409
+ // src/plugins/manifest.ts
410
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";
411
+ import { readFile } from "fs/promises";
412
+ import { isAbsolute, join as join3 } from "path";
413
+ function stringList(value, field) {
414
+ if (value === undefined)
415
+ return [];
416
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
417
+ throw new Error(`Plugin manifest: ${field} must be a list of strings`);
418
+ }
419
+ return value;
420
+ }
421
+ function relativePathList(value, field) {
422
+ const list = stringList(value, field);
423
+ for (const p of list) {
424
+ if (isAbsolute(p) || p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split(/[\\/]/).includes("..")) {
425
+ throw new Error(`Plugin manifest: ${field} path must stay inside the plugin: ${p}`);
426
+ }
427
+ }
428
+ return list;
429
+ }
430
+ function validateManifest(raw, packageVersion) {
431
+ if (!raw || typeof raw !== "object")
432
+ throw new Error("Plugin manifest must be a JSON object");
433
+ const m = raw;
434
+ if (typeof m.name !== "string" || !m.name)
435
+ throw new Error("Plugin manifest: name is required");
436
+ if (!NAME.test(m.name))
437
+ throw new Error(`Plugin manifest: name must be kebab-case: ${m.name}`);
438
+ if (m.harenApi !== HAREN_API) {
439
+ throw new Error(`Plugin manifest: this haren supports harenApi "${HAREN_API}", got ${JSON.stringify(m.harenApi)}`);
440
+ }
441
+ let version;
442
+ if (packageVersion !== undefined) {
443
+ if (m.version !== undefined && m.version !== packageVersion) {
444
+ throw new Error(`Plugin manifest: version ${m.version} differs from package.json ${packageVersion}`);
445
+ }
446
+ version = packageVersion;
447
+ } else {
448
+ if (typeof m.version !== "string" || !m.version)
449
+ throw new Error("Plugin manifest: version is required");
450
+ version = m.version;
451
+ }
452
+ const hooks = {};
453
+ if (m.hooks !== undefined) {
454
+ if (!m.hooks || typeof m.hooks !== "object")
455
+ throw new Error("Plugin manifest: hooks must be an object");
456
+ for (const [name, command] of Object.entries(m.hooks)) {
457
+ if (!HOOK_NAMES.includes(name))
458
+ throw new Error(`Plugin manifest: Unknown hook: ${name}`);
459
+ if (typeof command !== "string" || !command)
460
+ throw new Error(`Plugin manifest: hook ${name} needs a command`);
461
+ hooks[name] = command;
462
+ }
463
+ }
464
+ const requires = [];
465
+ if (m.requires !== undefined) {
466
+ if (!Array.isArray(m.requires))
467
+ throw new Error("Plugin manifest: requires must be a list");
468
+ for (const r of m.requires) {
469
+ if (!r || typeof r.bin !== "string" || !r.bin)
470
+ throw new Error("Plugin manifest: each requirement needs a bin");
471
+ if (r.version !== undefined && typeof r.version !== "string") {
472
+ throw new Error(`Plugin manifest: requirement ${r.bin} version must be a string`);
473
+ }
474
+ if (r.install !== undefined && typeof r.install !== "string") {
475
+ throw new Error(`Plugin manifest: requirement ${r.bin} install must be a string`);
476
+ }
477
+ requires.push({
478
+ bin: r.bin,
479
+ version: r.version,
480
+ install: r.install
481
+ });
482
+ }
483
+ }
484
+ const config = m.config ?? {};
485
+ if (typeof config !== "object" || Array.isArray(config))
486
+ throw new Error("Plugin manifest: config must be an object");
487
+ return {
488
+ name: m.name,
489
+ version,
490
+ harenApi: HAREN_API,
491
+ description: typeof m.description === "string" ? m.description : undefined,
492
+ requires,
493
+ setup: stringList(m.setup, "setup"),
494
+ hooks,
495
+ config,
496
+ skills: relativePathList(m.skills, "skills"),
497
+ agents: relativePathList(m.agents, "agents")
498
+ };
499
+ }
500
+ async function readInstalledManifest(dir) {
501
+ const raw = JSON.parse(await readFile(join3(dir, "haren-plugin.json"), "utf-8"));
502
+ let packageVersion;
503
+ const hasVersion = raw && typeof raw === "object" && raw.version !== undefined;
504
+ const pkgPath = join3(dir, "package.json");
505
+ if (!hasVersion && existsSync2(pkgPath)) {
506
+ try {
507
+ const v = JSON.parse(await readFile(pkgPath, "utf-8"))?.version;
508
+ if (typeof v === "string")
509
+ packageVersion = v;
510
+ } catch {}
511
+ }
512
+ return validateManifest(raw, packageVersion);
513
+ }
514
+ var HAREN_API = "1", HOOK_NAMES, NAME;
515
+ var init_manifest2 = __esm(() => {
516
+ HOOK_NAMES = ["session-start", "after-plan", "on-task-status"];
517
+ NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
518
+ });
519
+
520
+ // src/plugins/state.ts
521
+ import { existsSync as existsSync3 } from "fs";
522
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
523
+ import { join as join4 } from "path";
524
+ function pluginsPath(harenDir) {
525
+ return join4(harenDir, "plugins.json");
526
+ }
527
+ function pluginDir(harenDir, name) {
528
+ return join4(harenDir, ".plugins", name);
529
+ }
530
+ function pluginDataDir(harenDir, name) {
531
+ return join4(harenDir, ".plugin-data", name);
532
+ }
533
+ async function readPlugins(harenDir) {
534
+ const path = pluginsPath(harenDir);
535
+ if (!existsSync3(path))
536
+ return { version: 1, plugins: {} };
537
+ const data = JSON.parse(await readFile2(path, "utf-8"));
538
+ return { version: 1, plugins: data.plugins ?? {} };
539
+ }
540
+ async function writePlugins(harenDir, data) {
541
+ await mkdir2(harenDir, { recursive: true });
542
+ await writeFile2(pluginsPath(harenDir), `${JSON.stringify(data, null, 2)}
543
+ `);
544
+ }
545
+ var init_state = () => {};
546
+
547
+ // src/workspace/root-files.ts
548
+ import { existsSync as existsSync4 } from "fs";
549
+ import { mkdir as mkdir3, readdir, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
550
+ import { basename as basename2, dirname, join as join5, relative, resolve as resolve2, sep } from "path";
413
551
  function legacyRange(existing) {
414
552
  const start = existing.indexOf(LEGACY_HEADING);
415
553
  if (start === -1 || !existing.includes("haren/skill.md"))
@@ -508,16 +646,125 @@ function mergeCursorHooks(existing, command) {
508
646
  `;
509
647
  }
510
648
  async function readOrNull(path) {
511
- return existsSync2(path) ? readFile(path, "utf-8") : null;
649
+ return existsSync4(path) ? readFile3(path, "utf-8") : null;
650
+ }
651
+ function harenName(name) {
652
+ return name.startsWith("haren-") ? name : `haren-${name}`;
653
+ }
654
+ function withFrontmatterName(text, name) {
655
+ const fm = /^---\r?\n[\s\S]*?\r?\n---/.exec(text);
656
+ if (!fm)
657
+ return text;
658
+ const head = fm[0].replace(/^name:.*$/m, `name: ${name}`);
659
+ return head + text.slice(fm[0].length);
660
+ }
661
+ function frontmatterName(text) {
662
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
663
+ return fm?.[1]?.match(/^name:\s*(.+?)\s*$/m)?.[1]?.replace(/^["']|["']$/g, "");
664
+ }
665
+ async function listFiles(dir, prefix = "") {
666
+ const out = [];
667
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
668
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
669
+ if (entry.isDirectory())
670
+ out.push(...await listFiles(join5(dir, entry.name), rel));
671
+ else if (entry.isFile())
672
+ out.push(rel);
673
+ }
674
+ return out.sort();
675
+ }
676
+ async function frameworkFiles(harenDir, contentDir) {
677
+ let source = harenDir;
678
+ if (!existsSync4(join5(harenDir, "skills")) && !existsSync4(join5(harenDir, "agents"))) {
679
+ try {
680
+ source = contentDir ?? resolveContentDir();
681
+ } catch {
682
+ return [];
683
+ }
684
+ }
685
+ const files = [];
686
+ const skillsDir = join5(source, "skills");
687
+ if (existsSync4(skillsDir)) {
688
+ for (const entry of await readdir(skillsDir, { withFileTypes: true })) {
689
+ if (!entry.isDirectory())
690
+ continue;
691
+ const dir = join5(skillsDir, entry.name);
692
+ const main = await readOrNull(join5(dir, "SKILL.md"));
693
+ if (main === null)
694
+ continue;
695
+ const name = harenName(frontmatterName(main) ?? entry.name);
696
+ for (const rel of await listFiles(dir)) {
697
+ const text = await readFile3(join5(dir, rel), "utf-8");
698
+ files.push({
699
+ path: `skills/${name}/${rel}`,
700
+ content: rel === "SKILL.md" ? withFrontmatterName(text, name) : text,
701
+ group: "skills"
702
+ });
703
+ }
704
+ }
705
+ }
706
+ const agentsDir = join5(source, "agents");
707
+ if (existsSync4(agentsDir)) {
708
+ for (const file of (await readdir(agentsDir)).filter((f) => f.endsWith(".md")).sort()) {
709
+ const text = await readFile3(join5(agentsDir, file), "utf-8");
710
+ const name = harenName(frontmatterName(text) ?? file.slice(0, -3));
711
+ files.push({
712
+ path: `agents/${name}.md`,
713
+ content: withFrontmatterName(text, name),
714
+ group: "agents"
715
+ });
716
+ }
717
+ }
718
+ files.push(...await pluginFiles(harenDir));
719
+ return files.sort((x, y) => x.path.localeCompare(y.path));
512
720
  }
513
- async function readPackagedOnboard(contentDir) {
514
- let dir;
515
- try {
516
- dir = contentDir ?? resolveContentDir();
517
- } catch {
518
- return null;
721
+ async function pluginFiles(harenDir, only) {
722
+ const files = [];
723
+ const state = await readPlugins(harenDir);
724
+ for (const [plugin, entry] of Object.entries(state.plugins)) {
725
+ if (only !== undefined ? plugin !== only : !entry.enabled)
726
+ continue;
727
+ const dir = pluginDir(harenDir, plugin);
728
+ let manifest;
729
+ try {
730
+ manifest = await readInstalledManifest(dir);
731
+ } catch {
732
+ continue;
733
+ }
734
+ const prefixed = (n) => n.startsWith(`${plugin}-`) ? n : `${plugin}-${n}`;
735
+ const safeName = (n) => /^[A-Za-z0-9._-]+$/.test(n) && !n.includes("..");
736
+ for (const skill of manifest.skills) {
737
+ const skillDir = join5(dir, skill);
738
+ const main = await readOrNull(join5(skillDir, "SKILL.md"));
739
+ if (main === null)
740
+ continue;
741
+ const name = prefixed(frontmatterName(main) ?? basename2(skillDir));
742
+ if (!safeName(name))
743
+ continue;
744
+ for (const rel of await listFiles(skillDir)) {
745
+ const text = await readFile3(join5(skillDir, rel), "utf-8");
746
+ files.push({
747
+ path: `skills/${name}/${rel}`,
748
+ content: rel === "SKILL.md" ? withFrontmatterName(text, name) : text,
749
+ group: "skills"
750
+ });
751
+ }
752
+ }
753
+ for (const agent of manifest.agents) {
754
+ const text = await readOrNull(join5(dir, agent));
755
+ if (text === null)
756
+ continue;
757
+ const name = prefixed(frontmatterName(text) ?? basename2(agent, ".md"));
758
+ if (!safeName(name))
759
+ continue;
760
+ files.push({
761
+ path: `agents/${name}.md`,
762
+ content: withFrontmatterName(text, name),
763
+ group: "agents"
764
+ });
765
+ }
519
766
  }
520
- return readOrNull(join3(dir, "skills", "onboard", "SKILL.md"));
767
+ return files.sort((x, y) => x.path.localeCompare(y.path));
521
768
  }
522
769
  async function computeRootFiles(o) {
523
770
  const name = relative(o.workspaceDir, o.harenDir).split(sep).join("/");
@@ -525,8 +772,17 @@ async function computeRootFiles(o) {
525
772
  const useCursor = o.editor !== "claude-code";
526
773
  const command = gateCommand(name);
527
774
  const config = renderTemplate(editorConfigTemplate, name);
528
- const onboard = await readOrNull(join3(o.harenDir, "skills", "onboard", "SKILL.md")) ?? await readPackagedOnboard(o.contentDir);
775
+ const framework = await frameworkFiles(o.harenDir, o.contentDir);
529
776
  const specs = [];
777
+ const addFramework = (editorDir) => {
778
+ for (const f of framework) {
779
+ specs.push({
780
+ path: `${editorDir}/${f.path}`,
781
+ make: () => f.content,
782
+ group: `${editorDir}/${f.group}/`
783
+ });
784
+ }
785
+ };
530
786
  if (useClaude) {
531
787
  specs.push({
532
788
  path: "CLAUDE.md",
@@ -534,8 +790,7 @@ async function computeRootFiles(o) {
534
790
  markdown: true
535
791
  });
536
792
  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 });
793
+ addFramework(".claude");
539
794
  }
540
795
  if (useCursor) {
541
796
  specs.push({
@@ -548,37 +803,69 @@ async function computeRootFiles(o) {
548
803
  make: () => renderTemplate(cursorRuleTemplate, name)
549
804
  });
550
805
  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 });
806
+ addFramework(".cursor");
553
807
  }
554
808
  const files = [];
555
809
  for (const spec of specs) {
556
- const old = await readOrNull(join3(o.workspaceDir, spec.path));
810
+ const old = await readOrNull(join5(o.workspaceDir, spec.path));
557
811
  const content = spec.make(old);
558
812
  files.push({
559
813
  path: spec.path,
560
814
  content,
561
815
  existed: old !== null,
562
816
  changed: old !== content,
563
- userContent: spec.markdown ? hasUserContent(old) : false
817
+ userContent: spec.markdown ? hasUserContent(old) : false,
818
+ ...spec.group ? { group: spec.group } : {}
564
819
  });
565
820
  }
566
821
  return files;
567
822
  }
823
+ function summarizeRootFiles(files) {
824
+ const out = [];
825
+ const groups = new Map;
826
+ for (const file of files) {
827
+ if (!file.group) {
828
+ out.push(file);
829
+ continue;
830
+ }
831
+ const g = groups.get(file.group);
832
+ if (!g) {
833
+ const entry = { ...file, path: file.group, content: "", count: 1 };
834
+ groups.set(file.group, entry);
835
+ out.push(entry);
836
+ } else {
837
+ g.count += 1;
838
+ g.existed ||= file.existed;
839
+ g.changed ||= file.changed;
840
+ }
841
+ }
842
+ return out;
843
+ }
844
+ function isSafeRootPath(workspaceDir, path) {
845
+ const abs = resolve2(workspaceDir, path);
846
+ const root = resolve2(workspaceDir);
847
+ if (abs === join5(root, "CLAUDE.md") || abs === join5(root, ".cursorrules"))
848
+ return true;
849
+ return [".claude", ".cursor"].some((d) => abs.startsWith(join5(root, d) + sep));
850
+ }
568
851
  async function writeRootFiles(o) {
569
852
  const files = await computeRootFiles(o);
570
853
  for (const file of files) {
571
854
  if (!file.changed)
572
855
  continue;
573
- const abs = join3(o.workspaceDir, file.path);
574
- await mkdir2(dirname(abs), { recursive: true });
575
- await writeFile2(abs, file.content);
856
+ if (!isSafeRootPath(o.workspaceDir, file.path)) {
857
+ console.warn(` skipped unsafe path: ${file.path}`);
858
+ continue;
859
+ }
860
+ const abs = join5(o.workspaceDir, file.path);
861
+ await mkdir3(dirname(abs), { recursive: true });
862
+ await writeFile3(abs, file.content);
576
863
  }
577
864
  return files;
578
865
  }
579
866
  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"));
867
+ const claude = existsSync4(join5(workspaceDir, "CLAUDE.md")) || existsSync4(join5(workspaceDir, ".claude", "settings.json"));
868
+ const cursor = existsSync4(join5(workspaceDir, ".cursorrules")) || existsSync4(join5(workspaceDir, ".cursor"));
582
869
  if (claude && cursor)
583
870
  return "both";
584
871
  if (claude)
@@ -590,14 +877,16 @@ function detectEditor(workspaceDir) {
590
877
  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
878
  var init_root_files = __esm(() => {
592
879
  init_content_dir();
880
+ init_manifest2();
881
+ init_state();
593
882
  init_templates();
594
883
  LEGACY_HEADINGS = new Set([LEGACY_HEADING, "## Brainstorming Gate"]);
595
884
  });
596
885
 
597
886
  // 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";
887
+ import { existsSync as existsSync5 } from "fs";
888
+ import { mkdir as mkdir4, readdir as readdir2 } from "fs/promises";
889
+ import { dirname as dirname2, join as join6, resolve as resolve3 } from "path";
601
890
  function gitEnv(interactive = process.stdin.isTTY === true, base = process.env) {
602
891
  if (interactive)
603
892
  return { ...base };
@@ -626,7 +915,7 @@ async function runGit(args, cwd) {
626
915
  }
627
916
  }
628
917
  function hasGitDir(dir) {
629
- return existsSync3(join4(dir, ".git"));
918
+ return existsSync5(join6(dir, ".git"));
630
919
  }
631
920
  async function isInsideWorkTree(dir) {
632
921
  const result = await runGit(["rev-parse", "--is-inside-work-tree"], dir);
@@ -637,9 +926,9 @@ async function getRemoteUrl(dir) {
637
926
  return result.ok && result.stdout ? result.stdout : null;
638
927
  }
639
928
  async function cloneRepo(remote, dest) {
640
- const abs = resolve2(dest);
929
+ const abs = resolve3(dest);
641
930
  try {
642
- await mkdir3(dirname2(abs), { recursive: true });
931
+ await mkdir4(dirname2(abs), { recursive: true });
643
932
  } catch (err) {
644
933
  return { ok: false, stdout: "", stderr: String(err) };
645
934
  }
@@ -649,12 +938,12 @@ async function gitInit(dir) {
649
938
  return runGit(["init"], dir);
650
939
  }
651
940
  async function listChildRepos(dir) {
652
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
941
+ const entries = await readdir2(dir, { withFileTypes: true }).catch(() => []);
653
942
  const repos = [];
654
943
  for (const entry of entries) {
655
944
  if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
656
945
  continue;
657
- const path = join4(dir, entry.name);
946
+ const path = join6(dir, entry.name);
658
947
  if (!hasGitDir(path))
659
948
  continue;
660
949
  repos.push({ name: entry.name, path, remote: await getRemoteUrl(path) });
@@ -664,14 +953,14 @@ async function listChildRepos(dir) {
664
953
  var init_git = () => {};
665
954
 
666
955
  // 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";
956
+ import { existsSync as existsSync6 } from "fs";
957
+ import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
958
+ import { dirname as dirname3, join as join7, resolve as resolve4 } from "path";
670
959
  async function hasMarkedManifest(dir) {
671
- const path = join5(dir, "manifest.yaml");
672
- if (!existsSync4(path))
960
+ const path = join7(dir, "manifest.yaml");
961
+ if (!existsSync6(path))
673
962
  return false;
674
- const text = await readFile2(path, "utf-8").catch(() => null);
963
+ const text = await readFile4(path, "utf-8").catch(() => null);
675
964
  if (text === null)
676
965
  return false;
677
966
  try {
@@ -684,7 +973,7 @@ async function hasMarkedManifest(dir) {
684
973
  }
685
974
  }
686
975
  function isLegacyHarenDir(dir) {
687
- return existsSync4(join5(dir, "manifest.yaml")) && existsSync4(join5(dir, "skill.md"));
976
+ return existsSync6(join7(dir, "manifest.yaml")) && existsSync6(join7(dir, "skill.md"));
688
977
  }
689
978
  function location(harenDir, legacy) {
690
979
  return { harenDir, workspaceDir: dirname3(harenDir), legacy };
@@ -702,20 +991,20 @@ function harenDirFlag(args) {
702
991
  async function resolveHarenDir(cwd, opts = {}) {
703
992
  const explicit = opts.harenDir || opts.env?.HAREN_DIR;
704
993
  if (explicit) {
705
- const dir = resolve3(cwd, explicit);
706
- if (!existsSync4(join5(dir, "manifest.yaml"))) {
994
+ const dir = resolve4(cwd, explicit);
995
+ if (!existsSync6(join7(dir, "manifest.yaml"))) {
707
996
  throw new Error(`No manifest.yaml in ${dir}`);
708
997
  }
709
998
  return location(dir, !await hasMarkedManifest(dir));
710
999
  }
711
1000
  if (await hasMarkedManifest(cwd))
712
1001
  return location(cwd, false);
713
- const entries = await readdir2(cwd, { withFileTypes: true }).catch(() => []);
1002
+ const entries = await readdir3(cwd, { withFileTypes: true }).catch(() => []);
714
1003
  const matches = [];
715
1004
  for (const entry of entries) {
716
1005
  if (entry.name.startsWith(".") || entry.name === "node_modules")
717
1006
  continue;
718
- const dir = join5(cwd, entry.name);
1007
+ const dir = join7(cwd, entry.name);
719
1008
  const isDir = entry.isSymbolicLink() ? await stat(dir).then((st) => st.isDirectory(), () => false) : entry.isDirectory();
720
1009
  if (!isDir)
721
1010
  continue;
@@ -727,7 +1016,7 @@ async function resolveHarenDir(cwd, opts = {}) {
727
1016
  throw new MultipleHarenDirsError(matches);
728
1017
  if (matches.length === 1)
729
1018
  return location(matches[0], false);
730
- const legacyChild = join5(cwd, "haren");
1019
+ const legacyChild = join7(cwd, "haren");
731
1020
  if (isLegacyHarenDir(legacyChild))
732
1021
  return location(legacyChild, true);
733
1022
  if (isLegacyHarenDir(cwd))
@@ -751,7 +1040,7 @@ Pass --haren-dir <path> to choose one.`);
751
1040
  });
752
1041
 
753
1042
  // src/workspace/detect.ts
754
- import { existsSync as existsSync5 } from "fs";
1043
+ import { existsSync as existsSync7 } from "fs";
755
1044
  import { dirname as dirname4 } from "path";
756
1045
  async function inferLayout(dir) {
757
1046
  if (hasGitDir(dir))
@@ -760,7 +1049,7 @@ async function inferLayout(dir) {
760
1049
  if (childRepos.length > 0)
761
1050
  return { layout: "workspace", childRepos };
762
1051
  let probe = dir;
763
- while (!existsSync5(probe) && dirname4(probe) !== probe)
1052
+ while (!existsSync7(probe) && dirname4(probe) !== probe)
764
1053
  probe = dirname4(probe);
765
1054
  if (await isInsideWorkTree(probe))
766
1055
  return { layout: "monorepo", childRepos: [] };
@@ -783,31 +1072,34 @@ var init_detect = __esm(() => {
783
1072
  });
784
1073
 
785
1074
  // 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";
1075
+ import { existsSync as existsSync8 } from "fs";
1076
+ import { basename as basename3, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
788
1077
  async function buildPlan(input) {
789
1078
  const items = [];
790
1079
  const generatedNote = input.layout === "workspace" ? "(generated, not versioned)" : undefined;
791
- for (const file of await computeRootFiles({
1080
+ const rootFiles = await computeRootFiles({
792
1081
  workspaceDir: input.rootDir,
793
1082
  harenDir: input.harenDir,
794
1083
  editor: input.editor
795
- })) {
1084
+ });
1085
+ for (const file of summarizeRootFiles(rootFiles)) {
1086
+ const count = file.count ? `(${file.count} files)` : undefined;
1087
+ const join = (...notes) => notes.filter(Boolean).join(" ") || undefined;
796
1088
  if (!file.existed)
797
- items.push({ path: file.path, action: "create", note: generatedNote });
1089
+ items.push({ path: file.path, action: "create", note: join(count, generatedNote) });
798
1090
  else if (file.changed)
799
1091
  items.push({
800
1092
  path: file.path,
801
1093
  action: "modify",
802
- note: file.userContent ? "(haren block only)" : undefined
1094
+ note: file.userContent ? "(haren block only)" : count
803
1095
  });
804
1096
  else
805
- items.push({ path: file.path, action: "keep" });
1097
+ items.push({ path: file.path, action: "keep", note: count });
806
1098
  }
807
1099
  for (const [key, repo] of Object.entries(input.repos)) {
808
- const abs = resolve4(input.harenDir, repo.path);
1100
+ const abs = resolve5(input.harenDir, repo.path);
809
1101
  const path = relative2(input.rootDir, abs).split(sep2).join("/") || key;
810
- if (existsSync6(abs)) {
1102
+ if (existsSync8(abs)) {
811
1103
  items.push(hasGitDir(abs) || input.layout === "monorepo" ? { path, action: "keep" } : { path, action: "warn", note: "! not a git repo" });
812
1104
  } else if (input.layout === "monorepo") {
813
1105
  items.push({ path, action: "warn", note: "! folder not found" });
@@ -819,7 +1111,7 @@ async function buildPlan(input) {
819
1111
  }
820
1112
  return {
821
1113
  rootDir: input.rootDir,
822
- harenDirName: basename2(input.harenDir),
1114
+ harenDirName: basename3(input.harenDir),
823
1115
  layout: input.layout,
824
1116
  createHaren: input.createHaren,
825
1117
  items,
@@ -887,6 +1179,42 @@ var init_plan = __esm(() => {
887
1179
  });
888
1180
 
889
1181
  // src/workspace/progress.ts
1182
+ import { readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
1183
+ async function readProgress(path) {
1184
+ const raw = await readFile5(path, "utf-8");
1185
+ return JSON.parse(raw);
1186
+ }
1187
+ async function writeProgress(path, progress) {
1188
+ await writeFile4(path, JSON.stringify(progress, null, 2));
1189
+ }
1190
+ function updateFeatureStatus(progress, moduleName, featureName, newStatus) {
1191
+ const mod = progress.modules[moduleName];
1192
+ if (!mod) {
1193
+ throw new Error(`Module '${moduleName}' not found`);
1194
+ }
1195
+ const currentStatus = mod.features[featureName];
1196
+ if (currentStatus === undefined) {
1197
+ throw new Error(`Feature '${featureName}' not found in module '${moduleName}'`);
1198
+ }
1199
+ const allowed = VALID_FEATURE_TRANSITIONS[currentStatus];
1200
+ if (!allowed.includes(newStatus)) {
1201
+ throw new Error(`Invalid feature transition: ${currentStatus} \u2192 ${newStatus}. Allowed: ${allowed.join(", ")}`);
1202
+ }
1203
+ return {
1204
+ ...progress,
1205
+ modules: {
1206
+ ...progress.modules,
1207
+ [moduleName]: {
1208
+ ...mod,
1209
+ features: {
1210
+ ...mod.features,
1211
+ [featureName]: newStatus
1212
+ },
1213
+ lastUpdated: new Date().toISOString()
1214
+ }
1215
+ }
1216
+ };
1217
+ }
890
1218
  function migrateProgress(raw, repoKeyFor) {
891
1219
  if (!raw || typeof raw !== "object")
892
1220
  return { progress: raw, changed: false };
@@ -906,19 +1234,28 @@ function migrateProgress(raw, repoKeyFor) {
906
1234
  }
907
1235
  return { progress: { ...data, version: PROGRESS_VERSION, modules }, changed: true };
908
1236
  }
909
- var PROGRESS_VERSION = 2;
910
- var init_progress = () => {};
1237
+ var VALID_FEATURE_TRANSITIONS, PROGRESS_VERSION = 2;
1238
+ var init_progress = __esm(() => {
1239
+ VALID_FEATURE_TRANSITIONS = {
1240
+ pending: ["in-progress"],
1241
+ "in-progress": ["evaluating"],
1242
+ evaluating: ["passing", "fixing", "blocked"],
1243
+ fixing: ["evaluating"],
1244
+ passing: [],
1245
+ blocked: ["in-progress"]
1246
+ };
1247
+ });
911
1248
 
912
1249
  // src/lib/version.ts
913
- import { existsSync as existsSync7, readFileSync } from "fs";
914
- import { resolve as resolve5 } from "path";
1250
+ import { existsSync as existsSync9, readFileSync } from "fs";
1251
+ import { resolve as resolve6 } from "path";
915
1252
  function readHarenVersion(candidates) {
916
1253
  const probes = candidates ?? [
917
- resolve5(import.meta.dir, "..", "package.json"),
918
- resolve5(import.meta.dir, "..", "..", "package.json")
1254
+ resolve6(import.meta.dir, "..", "package.json"),
1255
+ resolve6(import.meta.dir, "..", "..", "package.json")
919
1256
  ];
920
1257
  for (const path of probes) {
921
- if (!existsSync7(path))
1258
+ if (!existsSync9(path))
922
1259
  continue;
923
1260
  try {
924
1261
  const pkg = JSON.parse(readFileSync(path, "utf-8"));
@@ -935,11 +1272,287 @@ var init_version = __esm(() => {
935
1272
  HAREN_VERSION = readHarenVersion();
936
1273
  });
937
1274
 
1275
+ // src/plugins/registry.ts
1276
+ function npmPackageName(spec) {
1277
+ const at = spec.indexOf("@", spec.startsWith("@") ? 1 : 0);
1278
+ return at === -1 ? spec : spec.slice(0, at);
1279
+ }
1280
+ function isOfficialSource(source) {
1281
+ if (source.startsWith("npm:")) {
1282
+ const name = npmPackageName(source.slice(4));
1283
+ return REGISTRY.some((e) => e.source.startsWith("npm:") && npmPackageName(e.source.slice(4)) === name);
1284
+ }
1285
+ return REGISTRY.some((e) => e.source === source);
1286
+ }
1287
+ function resolvePluginRef(ref) {
1288
+ if (/^(npm|git|file):/.test(ref)) {
1289
+ return { source: ref, official: isOfficialSource(ref) };
1290
+ }
1291
+ const entry = REGISTRY.find((e) => e.name === ref);
1292
+ if (!entry)
1293
+ throw new Error(`Unknown plugin: ${ref}. Use a registry name or npm:/git:/file: source.`);
1294
+ return { source: entry.source, official: true };
1295
+ }
1296
+ var REGISTRY;
1297
+ var init_registry = __esm(() => {
1298
+ REGISTRY = [
1299
+ {
1300
+ name: "backlog",
1301
+ source: "npm:@odarino/backlog.md",
1302
+ description: "Two-way sync between haren tasks and a Backlog.md board"
1303
+ }
1304
+ ];
1305
+ });
1306
+
1307
+ // src/plugins/requires.ts
1308
+ function extractVersion(text) {
1309
+ return /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(text)?.[1];
1310
+ }
1311
+ async function checkRequirement(req, env = process.env) {
1312
+ const path = Bun.which(req.bin, { PATH: env.PATH ?? "" });
1313
+ if (!path)
1314
+ return { ok: false, reason: "missing" };
1315
+ if (!req.version)
1316
+ return { ok: true };
1317
+ const proc = Bun.spawn([path, "--version"], {
1318
+ stdout: "pipe",
1319
+ stderr: "pipe",
1320
+ env
1321
+ });
1322
+ const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
1323
+ const version = extractVersion(out);
1324
+ if (!version || !Bun.semver.satisfies(version, req.version)) {
1325
+ return { ok: false, reason: "outdated", version: version ?? "unknown" };
1326
+ }
1327
+ return { ok: true, version };
1328
+ }
1329
+
1330
+ // src/plugins/source.ts
1331
+ import { existsSync as existsSync10 } from "fs";
1332
+ import { cp, mkdir as mkdir5, mkdtemp, readFile as readFile6, rm } from "fs/promises";
1333
+ import { tmpdir } from "os";
1334
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve7 } from "path";
1335
+ function parseSource(text) {
1336
+ const match = /^(npm|git|file):(.*)$/.exec(text);
1337
+ if (!match)
1338
+ throw new Error(`Plugin source must start with npm:, git:, or file: \u2014 got ${text}`);
1339
+ const [, kind, rest] = match;
1340
+ if (!rest)
1341
+ throw new Error(`Plugin source is empty: ${text}`);
1342
+ if (kind !== "file" && rest.startsWith("-"))
1343
+ throw new Error(`Plugin source must not start with "-": ${text}`);
1344
+ if (kind === "npm")
1345
+ return { kind, spec: rest };
1346
+ if (kind === "file")
1347
+ return { kind, path: rest };
1348
+ const hash = rest.lastIndexOf("#");
1349
+ return hash > 0 ? { kind, url: rest.slice(0, hash), ref: rest.slice(hash + 1) } : { kind, url: rest };
1350
+ }
1351
+ async function run(cmd, cwd) {
1352
+ const proc = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
1353
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
1354
+ if (code !== 0)
1355
+ throw new Error(`${cmd.join(" ")} failed: ${stderr.trim().split(`
1356
+ `).pop()}`);
1357
+ }
1358
+ async function fetchPlugin(source, destDir, cwd) {
1359
+ const parsed = parseSource(source);
1360
+ const work = await mkdtemp(join8(tmpdir(), "haren-plugin-"));
1361
+ let root;
1362
+ try {
1363
+ if (parsed.kind === "file") {
1364
+ root = isAbsolute2(parsed.path) ? parsed.path : resolve7(cwd, parsed.path);
1365
+ } else if (parsed.kind === "git") {
1366
+ root = join8(work, "repo");
1367
+ const ref = parsed.ref ? ["--branch", parsed.ref] : [];
1368
+ await run(["git", "clone", "--depth", "1", "-q", ...ref, "--", parsed.url, root]);
1369
+ await rm(join8(root, ".git"), { recursive: true, force: true });
1370
+ } else {
1371
+ await run(["npm", "pack", "--silent", "--pack-destination", work, "--", parsed.spec], work);
1372
+ const tgz = (await Array.fromAsync(new Bun.Glob("*.tgz").scan(work)))[0];
1373
+ if (!tgz)
1374
+ throw new Error(`npm pack ${parsed.spec} produced no archive`);
1375
+ await run(["tar", "-xzf", tgz], work);
1376
+ root = join8(work, "package");
1377
+ }
1378
+ const manifestPath = join8(root, "haren-plugin.json");
1379
+ if (!existsSync10(manifestPath))
1380
+ throw new Error(`No haren-plugin.json in ${source}`);
1381
+ const raw = JSON.parse(await readFile6(manifestPath, "utf-8"));
1382
+ let packageVersion;
1383
+ if (parsed.kind === "npm") {
1384
+ packageVersion = JSON.parse(await readFile6(join8(root, "package.json"), "utf-8")).version;
1385
+ }
1386
+ const manifest = validateManifest(raw, packageVersion);
1387
+ await rm(destDir, { recursive: true, force: true });
1388
+ await mkdir5(destDir, { recursive: true });
1389
+ await cp(root, destDir, { recursive: true });
1390
+ return manifest;
1391
+ } finally {
1392
+ await rm(work, { recursive: true, force: true });
1393
+ }
1394
+ }
1395
+ var init_source = __esm(() => {
1396
+ init_manifest2();
1397
+ });
1398
+
1399
+ // src/plugins/install.ts
1400
+ import { existsSync as existsSync11 } from "fs";
1401
+ import { readFile as readFile7, rename, rm as rm2 } from "fs/promises";
1402
+ import { join as join9, relative as relative3, resolve as resolve8, sep as sep3 } from "path";
1403
+ async function sh(command, cwd) {
1404
+ const proc = Bun.spawn(["sh", "-c", command], { cwd, stdout: "inherit", stderr: "pipe" });
1405
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
1406
+ if (code !== 0)
1407
+ throw new Error(`"${command}" failed: ${stderr.trim().split(`
1408
+ `).pop() ?? `exit ${code}`}`);
1409
+ }
1410
+ async function harenLayout(harenDir) {
1411
+ const path = join9(harenDir, "manifest.yaml");
1412
+ if (!existsSync11(path))
1413
+ return "workspace";
1414
+ try {
1415
+ return parseManifest(await readFile7(path, "utf-8")).layout ?? "workspace";
1416
+ } catch {
1417
+ return "workspace";
1418
+ }
1419
+ }
1420
+ async function stage(source, ctx) {
1421
+ await rm2(incomingDir(ctx), { recursive: true, force: true });
1422
+ return fetchPlugin(source, incomingDir(ctx), ctx.workspaceDir);
1423
+ }
1424
+ async function commit(manifest, ctx) {
1425
+ const dest = pluginDir(ctx.harenDir, manifest.name);
1426
+ await rm2(dest, { recursive: true, force: true });
1427
+ await rename(incomingDir(ctx), dest);
1428
+ }
1429
+ async function installPlugin(ref, ctx) {
1430
+ const { source, official } = resolvePluginRef(ref);
1431
+ if (!official) {
1432
+ ctx.io.log("This plugin is not in the haren registry. Its hooks run as code with your user permissions.");
1433
+ if (!await ctx.io.confirm("Install it?"))
1434
+ throw new Error("Plugin install cancelled");
1435
+ }
1436
+ const manifest = await stage(source, ctx);
1437
+ try {
1438
+ for (const req of manifest.requires) {
1439
+ let status = await checkRequirement(req, ctx.env);
1440
+ if (!status.ok && req.install && await ctx.io.confirm(`Run "${req.install}"?`)) {
1441
+ await sh(req.install, ctx.workspaceDir);
1442
+ status = await checkRequirement(req, ctx.env);
1443
+ }
1444
+ if (!status.ok)
1445
+ throw new Error(`${req.bin} is required: ${status.reason}`);
1446
+ }
1447
+ const harenRel = relative3(ctx.workspaceDir, ctx.harenDir).split(sep3).join("/");
1448
+ const layout = await harenLayout(ctx.harenDir);
1449
+ for (const command of manifest.setup) {
1450
+ await sh(command.replaceAll("{{project}}", ctx.project).replaceAll("{{harenDir}}", harenRel).replaceAll("{{layout}}", layout), ctx.workspaceDir);
1451
+ }
1452
+ await commit(manifest, ctx);
1453
+ } finally {
1454
+ await rm2(incomingDir(ctx), { recursive: true, force: true });
1455
+ }
1456
+ const state = await readPlugins(ctx.harenDir);
1457
+ state.plugins[manifest.name] = {
1458
+ source,
1459
+ version: manifest.version,
1460
+ enabled: true,
1461
+ config: state.plugins[manifest.name]?.config ?? {}
1462
+ };
1463
+ await writePlugins(ctx.harenDir, state);
1464
+ ctx.io.log(`Installed plugin ${manifest.name} ${manifest.version}`);
1465
+ return manifest;
1466
+ }
1467
+ async function removePlugin(name, ctx) {
1468
+ const state = await readPlugins(ctx.harenDir);
1469
+ if (!state.plugins[name])
1470
+ throw new Error(`Plugin ${name} is not installed`);
1471
+ delete state.plugins[name];
1472
+ await writePlugins(ctx.harenDir, state);
1473
+ await rm2(pluginDir(ctx.harenDir, name), { recursive: true, force: true });
1474
+ }
1475
+ async function removeEditorCopies(workspaceDir, files) {
1476
+ const targets = new Set;
1477
+ for (const f of files) {
1478
+ const [group, name] = f.path.split("/");
1479
+ if (!name)
1480
+ continue;
1481
+ targets.add(`${group}/${group === "skills" ? name : f.path.slice(group.length + 1)}`);
1482
+ }
1483
+ for (const editor of [".claude", ".cursor"]) {
1484
+ for (const t of targets) {
1485
+ const group = t.split("/")[0];
1486
+ const abs = resolve8(workspaceDir, editor, t);
1487
+ if (!abs.startsWith(resolve8(workspaceDir, editor, group) + sep3))
1488
+ continue;
1489
+ await rm2(abs, { recursive: true, force: true });
1490
+ }
1491
+ }
1492
+ }
1493
+ async function missingPlugins(harenDir) {
1494
+ const state = await readPlugins(harenDir);
1495
+ return Object.entries(state.plugins).filter(([name, e]) => e.enabled && !existsSync11(join9(pluginDir(harenDir, name), "haren-plugin.json"))).map(([name]) => name);
1496
+ }
1497
+ async function restorePlugins(ctx, report) {
1498
+ const restored = [];
1499
+ const state = await readPlugins(ctx.harenDir);
1500
+ for (const name of await missingPlugins(ctx.harenDir)) {
1501
+ const source = state.plugins[name].source;
1502
+ ctx.io.log(`Restoring plugin ${name} from ${source}`);
1503
+ try {
1504
+ const manifest = await installPlugin(source, ctx);
1505
+ if (manifest.name !== name) {
1506
+ report.warn(`plugin ${name}: source now installs ${manifest.name}`);
1507
+ }
1508
+ restored.push(manifest.name);
1509
+ } catch (err) {
1510
+ const message = err.message;
1511
+ if (message === "Plugin install cancelled") {
1512
+ report.warn(`plugin ${name}: skipped, not confirmed. Run again with --yes to install it.`);
1513
+ } else {
1514
+ report.error(`plugin ${name}: ${message}`);
1515
+ }
1516
+ }
1517
+ }
1518
+ return restored;
1519
+ }
1520
+ async function refreshPlugins(ctx, skip = []) {
1521
+ const warnings = [];
1522
+ const state = await readPlugins(ctx.harenDir);
1523
+ for (const [name, entry] of Object.entries(state.plugins)) {
1524
+ if (!entry.enabled || skip.includes(name))
1525
+ continue;
1526
+ try {
1527
+ const manifest = await stage(entry.source, ctx);
1528
+ if (manifest.name !== name) {
1529
+ warnings.push(`plugin ${name}: kept ${entry.version}: manifest name changed to ${manifest.name}`);
1530
+ continue;
1531
+ }
1532
+ await commit(manifest, ctx);
1533
+ entry.version = manifest.version;
1534
+ } catch (err) {
1535
+ warnings.push(`plugin ${name}: kept ${entry.version}: ${err.message}`);
1536
+ } finally {
1537
+ await rm2(incomingDir(ctx), { recursive: true, force: true });
1538
+ }
1539
+ }
1540
+ await writePlugins(ctx.harenDir, state);
1541
+ return warnings;
1542
+ }
1543
+ var incomingDir = (ctx) => pluginDir(ctx.harenDir, ".incoming");
1544
+ var init_install = __esm(() => {
1545
+ init_registry();
1546
+ init_source();
1547
+ init_state();
1548
+ init_manifest();
1549
+ });
1550
+
938
1551
  // 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";
1552
+ import { mkdir as mkdir6, writeFile as writeFile5, readdir as readdir4, copyFile, readFile as readFile8 } from "fs/promises";
1553
+ import { existsSync as existsSync12, realpathSync } from "fs";
941
1554
  import { homedir } from "os";
942
- import { basename as basename3, join as join6, resolve as resolve6 } from "path";
1555
+ import { basename as basename4, join as join10, resolve as resolve9 } from "path";
943
1556
  function readLine() {
944
1557
  return new Promise((resolve) => {
945
1558
  const stdin = process.stdin;
@@ -1104,11 +1717,11 @@ function getDirectories(iterations) {
1104
1717
  return dirs;
1105
1718
  }
1106
1719
  async function copyRecursive(src, dest) {
1107
- const entries = await readdir3(src, { withFileTypes: true });
1108
- await mkdir4(dest, { recursive: true });
1720
+ const entries = await readdir4(src, { withFileTypes: true });
1721
+ await mkdir6(dest, { recursive: true });
1109
1722
  for (const entry of entries) {
1110
- const srcPath = join6(src, entry.name);
1111
- const destPath = join6(dest, entry.name);
1723
+ const srcPath = join10(src, entry.name);
1724
+ const destPath = join10(dest, entry.name);
1112
1725
  if (entry.isDirectory()) {
1113
1726
  await copyRecursive(srcPath, destPath);
1114
1727
  } else {
@@ -1118,9 +1731,9 @@ async function copyRecursive(src, dest) {
1118
1731
  }
1119
1732
  async function scaffoldWorkspace(targetDir, options) {
1120
1733
  for (const dir of getDirectories(!!options.iterations)) {
1121
- await mkdir4(join6(targetDir, dir), { recursive: true });
1734
+ await mkdir6(join10(targetDir, dir), { recursive: true });
1122
1735
  }
1123
- await writeFile3(join6(targetDir, "manifest.yaml"), buildManifestText({
1736
+ await writeFile5(join10(targetDir, "manifest.yaml"), buildManifestText({
1124
1737
  version: HAREN_VERSION,
1125
1738
  layout: options.layout ?? "monorepo",
1126
1739
  project: options.project,
@@ -1140,40 +1753,42 @@ async function scaffoldWorkspace(targetDir, options) {
1140
1753
  if (options.iterations) {
1141
1754
  progressData.currentIteration = 1;
1142
1755
  }
1143
- await writeFile3(join6(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
1144
- await writeFile3(join6(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
1756
+ await writeFile5(join10(targetDir, "progress.json"), JSON.stringify(progressData, null, 2));
1757
+ await writeFile5(join10(targetDir, "FEEDBACK.md"), `# Haren Framework Feedback
1145
1758
 
1146
1759
  Append-only log of framework improvement suggestions captured during usage.
1147
1760
 
1148
1761
  ---
1149
1762
  `);
1150
- await writeFile3(join6(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
1763
+ await writeFile5(join10(targetDir, "artifacts", "_registry", "artifact-index.md"), `# Artifact Index
1151
1764
 
1152
1765
  Master registry of all artifacts in this Haren workspace.
1153
1766
 
1154
1767
  | ID | Type | Module | Status | Path |
1155
1768
  |----|------|--------|--------|------|
1156
1769
  `);
1157
- await writeFile3(join6(targetDir, "events", "events.jsonl"), "");
1158
- const gitignore = join6(targetDir, ".gitignore");
1159
- if (!existsSync8(gitignore))
1160
- await writeFile3(gitignore, `.agent.json
1770
+ await writeFile5(join10(targetDir, "events", "events.jsonl"), "");
1771
+ const gitignore = join10(targetDir, ".gitignore");
1772
+ if (!existsSync12(gitignore))
1773
+ await writeFile5(gitignore, `.agent.json
1161
1774
  .agent.pid
1775
+ .plugins/
1162
1776
  `);
1163
1777
  await writeGateScript(targetDir);
1164
1778
  await scaffoldSkillMd(targetDir);
1165
1779
  const contentDir = resolveContentDir();
1166
- await copyRecursive(join6(contentDir, "agents"), join6(targetDir, "agents"));
1167
- await copyRecursive(join6(contentDir, "skills"), join6(targetDir, "skills"));
1168
- await copyRecursive(join6(contentDir, "templates"), join6(targetDir, "templates"));
1780
+ await copyRecursive(join10(contentDir, "agents"), join10(targetDir, "agents"));
1781
+ await copyRecursive(join10(contentDir, "skills"), join10(targetDir, "skills"));
1782
+ await copyRecursive(join10(contentDir, "templates"), join10(targetDir, "templates"));
1783
+ await options.beforeRootFiles?.();
1169
1784
  await writeRootFiles({
1170
- workspaceDir: resolve6(targetDir, ".."),
1785
+ workspaceDir: resolve9(targetDir, ".."),
1171
1786
  harenDir: targetDir,
1172
1787
  editor: options.editor ?? "claude-code"
1173
1788
  });
1174
1789
  }
1175
1790
  async function scaffoldSkillMd(targetDir) {
1176
- await writeFile3(join6(targetDir, "skill.md"), `---
1791
+ await writeFile5(join10(targetDir, "skill.md"), `---
1177
1792
  name: haren
1178
1793
  description: Agentic SDLC framework \u2014 orchestrates AI agents through structured phases
1179
1794
  ---
@@ -1288,7 +1903,8 @@ function parseInitArgs(args) {
1288
1903
  const out = {
1289
1904
  force: args.includes("--force"),
1290
1905
  yes: args.includes("--yes") || args.includes("-y"),
1291
- dryRun: args.includes("--dry-run")
1906
+ dryRun: args.includes("--dry-run"),
1907
+ plugins: []
1292
1908
  };
1293
1909
  for (let i = 0;i < args.length; i++) {
1294
1910
  const value = args[i + 1];
@@ -1312,6 +1928,13 @@ function parseInitArgs(args) {
1312
1928
  out.harenDir = value;
1313
1929
  i++;
1314
1930
  break;
1931
+ case "--plugin":
1932
+ if (value === undefined || value === "" || value.startsWith("-")) {
1933
+ throw new Error("--plugin needs a name or source");
1934
+ }
1935
+ out.plugins.push(value);
1936
+ i++;
1937
+ break;
1315
1938
  case "--mode":
1316
1939
  if (!MODES.includes(value)) {
1317
1940
  throw new Error(`Invalid mode: ${value}. Must be blueprint, explore, inherit, or undecided.`);
@@ -1366,7 +1989,7 @@ async function applyClones(plan, rootDir) {
1366
1989
  if (item.action !== "clone" || !item.remote)
1367
1990
  continue;
1368
1991
  console.log(` \x1B[36m\u2193\x1B[0m Cloning ${item.path} ...`);
1369
- const result = await cloneRepo(item.remote, join6(rootDir, item.path));
1992
+ const result = await cloneRepo(item.remote, join10(rootDir, item.path));
1370
1993
  if (!result.ok) {
1371
1994
  console.error(` \x1B[31m\u2717\x1B[0m ${item.path}: ${result.stderr.split(`
1372
1995
  `).pop()}`);
@@ -1378,6 +2001,48 @@ async function applyClones(plan, rootDir) {
1378
2001
  function canPrompt(opts) {
1379
2002
  return !opts.yes && process.stdin.isTTY === true;
1380
2003
  }
2004
+ async function setupPlugins(opts, workspaceDir, harenDir, project) {
2005
+ let refs = opts.plugins;
2006
+ if (refs.length === 0 && canPrompt(opts) && REGISTRY.length > 0) {
2007
+ const picked = await promptMultiSelect("Install plugins?", REGISTRY.map((e) => `${e.name.padEnd(12)} ${e.description}`), []);
2008
+ refs = picked.map((i) => REGISTRY[i].name);
2009
+ }
2010
+ for (const ref of refs) {
2011
+ try {
2012
+ await installPlugin(ref, {
2013
+ workspaceDir,
2014
+ harenDir,
2015
+ project,
2016
+ io: {
2017
+ confirm: async (q) => {
2018
+ console.log(` ${q}`);
2019
+ return opts.yes || canPrompt(opts) && await promptConfirm(false) === "yes";
2020
+ },
2021
+ log: (l) => console.log(` ${l}`)
2022
+ }
2023
+ });
2024
+ } catch (err) {
2025
+ console.error(` \x1B[31m\u2717\x1B[0m plugin ${ref}: ${err.message}`);
2026
+ }
2027
+ }
2028
+ }
2029
+ async function restoreMissing(opts, location, project) {
2030
+ await restorePlugins({
2031
+ workspaceDir: location.workspaceDir,
2032
+ harenDir: location.harenDir,
2033
+ project,
2034
+ io: {
2035
+ confirm: async (q) => {
2036
+ console.log(` ${q}`);
2037
+ return opts.yes || canPrompt(opts) && await promptConfirm(false) === "yes";
2038
+ },
2039
+ log: (l) => console.log(` ${l}`)
2040
+ }
2041
+ }, {
2042
+ warn: (l) => console.warn(` \x1B[33m!\x1B[0m ${l}`),
2043
+ error: (l) => console.error(` \x1B[31m\u2717\x1B[0m ${l}`)
2044
+ });
2045
+ }
1381
2046
  async function confirmOrExit(opts, allowEdit) {
1382
2047
  if (opts.yes)
1383
2048
  return "yes";
@@ -1432,7 +2097,7 @@ async function runSetup(location, opts) {
1432
2097
  console.log(" Run 'haren upgrade' to migrate it.");
1433
2098
  return;
1434
2099
  }
1435
- const manifest = parseManifest(await readFile3(join6(location.harenDir, "manifest.yaml"), "utf-8"));
2100
+ const manifest = parseManifest(await readFile8(join10(location.harenDir, "manifest.yaml"), "utf-8"));
1436
2101
  const layout = manifest.layout ?? "workspace";
1437
2102
  let editor = opts.editor ?? detectEditor(location.workspaceDir);
1438
2103
  if (!editor) {
@@ -1447,8 +2112,22 @@ async function runSetup(location, opts) {
1447
2112
  editor
1448
2113
  });
1449
2114
  console.log(` Found haren folder: ${location.harenDir}`);
1450
- if (isNoop(plan)) {
1451
- console.log(" Already set up. Run 'haren upgrade' to update framework files.");
2115
+ const missing = await missingPlugins(location.harenDir);
2116
+ if (isNoop(plan) && opts.plugins.length === 0) {
2117
+ if (missing.length === 0) {
2118
+ console.log(" Already set up. Run 'haren upgrade' to update framework files.");
2119
+ return;
2120
+ }
2121
+ if (opts.dryRun) {
2122
+ console.log(` Plugins to restore: ${missing.join(", ")}`);
2123
+ return;
2124
+ }
2125
+ await restoreMissing(opts, location, manifest.project ?? "");
2126
+ await writeRootFiles({
2127
+ workspaceDir: location.workspaceDir,
2128
+ harenDir: location.harenDir,
2129
+ editor
2130
+ });
1452
2131
  return;
1453
2132
  }
1454
2133
  console.log("");
@@ -1459,6 +2138,8 @@ async function runSetup(location, opts) {
1459
2138
  if (await confirmOrExit(opts, false) === "no")
1460
2139
  return;
1461
2140
  const failed = await applyClones(plan, location.workspaceDir);
2141
+ await restoreMissing(opts, location, manifest.project ?? "");
2142
+ await setupPlugins(opts, location.workspaceDir, location.harenDir, manifest.project ?? "");
1462
2143
  await writeRootFiles({
1463
2144
  workspaceDir: location.workspaceDir,
1464
2145
  harenDir: location.harenDir,
@@ -1486,7 +2167,7 @@ function realPath(path) {
1486
2167
  try {
1487
2168
  return realpathSync(path);
1488
2169
  } catch {
1489
- return resolve6(path);
2170
+ return resolve9(path);
1490
2171
  }
1491
2172
  }
1492
2173
  async function init(args) {
@@ -1497,13 +2178,13 @@ async function init(args) {
1497
2178
  console.error(` ${err.message}`);
1498
2179
  process.exit(1);
1499
2180
  }
1500
- const cwdRoot = resolve6(opts.dir?.replace(/^~(?=$|\/)/, process.env.HOME ?? "~") ?? process.cwd());
2181
+ const cwdRoot = resolve9(opts.dir?.replace(/^~(?=$|\/)/, process.env.HOME ?? "~") ?? process.cwd());
1501
2182
  if (!opts.force && realPath(cwdRoot) === realPath(homedir())) {
1502
2183
  console.error(" Refusing to set up haren in your home folder. Choose a project folder, for example ~/my-project (or pass --force).");
1503
2184
  process.exit(1);
1504
2185
  }
1505
2186
  printBanner();
1506
- const explicitHarenDir = opts.harenDir && existsSync8(join6(cwdRoot, opts.harenDir, "manifest.yaml")) ? opts.harenDir : undefined;
2187
+ const explicitHarenDir = opts.harenDir && existsSync12(join10(cwdRoot, opts.harenDir, "manifest.yaml")) ? opts.harenDir : undefined;
1507
2188
  let detection;
1508
2189
  try {
1509
2190
  detection = await detectLayout(cwdRoot, { harenDir: explicitHarenDir, env: process.env });
@@ -1520,7 +2201,7 @@ async function init(args) {
1520
2201
  let existingLayout;
1521
2202
  if (detection.kind === "existing" && detection.location) {
1522
2203
  const loc = detection.location;
1523
- existingManifest = parseManifest(await readFile3(join6(loc.harenDir, "manifest.yaml"), "utf-8"));
2204
+ existingManifest = parseManifest(await readFile8(join10(loc.harenDir, "manifest.yaml"), "utf-8"));
1524
2205
  existingRepos = normalizeRepos(existingManifest.repos);
1525
2206
  existingLayout = existingManifest.layout ?? (await inferLayout(loc.workspaceDir)).layout ?? "workspace";
1526
2207
  }
@@ -1533,12 +2214,12 @@ async function init(args) {
1533
2214
  }, "workspace") : "workspace");
1534
2215
  console.log(` Layout detected: ${layout === "monorepo" ? "monorepo (inside a git repo)" : "multi-repo workspace (no .git at root)"}`);
1535
2216
  console.log("");
1536
- const harenDirName = opts.harenDir ?? (existingLoc ? basename3(existingLoc.harenDir) : interactive ? await prompt("haren folder name:", "haren") : "haren");
1537
- const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join6(rootDir, harenDirName);
2217
+ const harenDirName = opts.harenDir ?? (existingLoc ? basename4(existingLoc.harenDir) : interactive ? await prompt("haren folder name:", "haren") : "haren");
2218
+ const harenDir = existingLoc && !opts.harenDir ? existingLoc.harenDir : join10(rootDir, harenDirName);
1538
2219
  const children = (existingRepos ? [] : detection.childRepos).filter((r) => r.name !== harenDirName);
1539
2220
  const defaults = children.flatMap((r, i) => r.remote ? [i] : []);
1540
2221
  let selected = defaults;
1541
- const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt("Project name:", basename3(rootDir)) : basename3(rootDir));
2222
+ const project = opts.project ?? existingManifest?.project ?? (interactive ? await prompt("Project name:", basename4(rootDir)) : basename4(rootDir));
1542
2223
  const existingMode = MODES.find((m) => m === existingManifest?.mode);
1543
2224
  const mode = opts.mode ?? existingMode ?? (interactive ? await promptSelect("Mode:", MODES, MODE_DESCRIPTIONS, "undecided") : "undecided");
1544
2225
  const language = opts.language ?? existingManifest?.language ?? (interactive ? await prompt("Preferred language:", "English") : "English");
@@ -1574,7 +2255,7 @@ ${renderReposBlock(repos)}`
1574
2255
  if (answer === "edit")
1575
2256
  continue;
1576
2257
  const failed = layout === "workspace" ? await applyClones(plan, rootDir) : [];
1577
- await mkdir4(harenDir, { recursive: true });
2258
+ await mkdir6(harenDir, { recursive: true });
1578
2259
  await scaffoldWorkspace(harenDir, {
1579
2260
  project,
1580
2261
  mode,
@@ -1582,7 +2263,8 @@ ${renderReposBlock(repos)}`
1582
2263
  iterations,
1583
2264
  editor,
1584
2265
  layout,
1585
- repos
2266
+ repos,
2267
+ beforeRootFiles: () => setupPlugins(opts, rootDir, harenDir, project)
1586
2268
  });
1587
2269
  if (layout === "workspace" && !hasGitDir(harenDir)) {
1588
2270
  const result = await gitInit(harenDir);
@@ -1611,6 +2293,8 @@ var init_init = __esm(() => {
1611
2293
  init_git();
1612
2294
  init_progress();
1613
2295
  init_version();
2296
+ init_install();
2297
+ init_registry();
1614
2298
  MODES = ["blueprint", "explore", "inherit", "undecided"];
1615
2299
  EDITORS = ["claude-code", "cursor", "both"];
1616
2300
  EDITOR_DESCRIPTIONS = {
@@ -1627,20 +2311,20 @@ var init_init = __esm(() => {
1627
2311
  });
1628
2312
 
1629
2313
  // src/commands/upgrade.ts
1630
- import { mkdir as mkdir5, readdir as readdir4, copyFile as copyFile2, readFile as readFile4, stat as stat2, writeFile as writeFile4 } from "fs/promises";
1631
- import { join as join7, resolve as resolve7 } from "path";
1632
- import { existsSync as existsSync9 } from "fs";
2314
+ import { mkdir as mkdir7, readdir as readdir5, copyFile as copyFile2, readFile as readFile9, stat as stat2, writeFile as writeFile6 } from "fs/promises";
2315
+ import { join as join11, resolve as resolve10 } from "path";
2316
+ import { existsSync as existsSync13 } from "fs";
1633
2317
  async function moduleRepoKey(harenDir, moduleName) {
1634
- const path = join7(harenDir, "artifacts", "03-modules", moduleName, "module.md");
1635
- if (!existsSync9(path))
2318
+ const path = join11(harenDir, "artifacts", "03-modules", moduleName, "module.md");
2319
+ if (!existsSync13(path))
1636
2320
  return;
1637
- const match = (await readFile4(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
2321
+ const match = (await readFile9(path, "utf-8")).match(/^repos:\s*\[([^\]]*)\]/m);
1638
2322
  return match?.[1].split(",")[0]?.trim().replace(/^["']|["']$/g, "") || undefined;
1639
2323
  }
1640
2324
  async function planMigration(location) {
1641
2325
  const { harenDir, workspaceDir } = location;
1642
2326
  const steps = [];
1643
- const manifestBefore = await readFile4(join7(harenDir, "manifest.yaml"), "utf-8");
2327
+ const manifestBefore = await readFile9(join11(harenDir, "manifest.yaml"), "utf-8");
1644
2328
  const manifest = parseManifest(manifestBefore);
1645
2329
  const layout = manifest.layout ?? (await inferLayout(workspaceDir)).layout ?? "workspace";
1646
2330
  if (!hasMarker(manifest))
@@ -1656,7 +2340,7 @@ async function planMigration(location) {
1656
2340
  const map = {};
1657
2341
  let foundRemote = false;
1658
2342
  for (const [key, entry] of Object.entries(current)) {
1659
- const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve7(harenDir, entry.path)) : null);
2343
+ const remote = entry.remote ?? (layout === "workspace" ? await getRemoteUrl(resolve10(harenDir, entry.path)) : null);
1660
2344
  if (remote && !entry.remote)
1661
2345
  foundRemote = true;
1662
2346
  map[key] = remote ? { ...entry, remote } : entry;
@@ -1672,9 +2356,9 @@ async function planMigration(location) {
1672
2356
  repos
1673
2357
  });
1674
2358
  let progress = null;
1675
- const progressPath = join7(harenDir, "progress.json");
1676
- if (existsSync9(progressPath)) {
1677
- const before = await readFile4(progressPath, "utf-8");
2359
+ const progressPath = join11(harenDir, "progress.json");
2360
+ if (existsSync13(progressPath)) {
2361
+ const before = await readFile9(progressPath, "utf-8");
1678
2362
  let raw;
1679
2363
  try {
1680
2364
  raw = JSON.parse(before);
@@ -1695,11 +2379,12 @@ async function planMigration(location) {
1695
2379
  }
1696
2380
  const gitignore = await planGitignore(harenDir);
1697
2381
  if (gitignore !== null)
1698
- steps.push(`.gitignore: add ${AGENT_FILES.join(", ")}`);
2382
+ steps.push(`.gitignore: add ${IGNORED.join(", ")}`);
1699
2383
  const editor = detectEditor(workspaceDir) ?? "claude-code";
1700
2384
  const rootFiles = await computeRootFiles({ workspaceDir, harenDir, editor });
1701
- for (const file of rootFiles.filter((f) => f.changed)) {
1702
- steps.push(`${file.path}: ${file.existed ? "update" : "create"}`);
2385
+ for (const file of summarizeRootFiles(rootFiles).filter((f) => f.changed)) {
2386
+ const count = file.count ? ` (${file.count} files)` : "";
2387
+ steps.push(`${file.path}: ${file.existed ? "update" : "create"}${count}`);
1703
2388
  }
1704
2389
  return {
1705
2390
  manifest: { before: manifestBefore, after: manifestAfter },
@@ -1711,10 +2396,10 @@ async function planMigration(location) {
1711
2396
  };
1712
2397
  }
1713
2398
  async function planGitignore(harenDir) {
1714
- const path = join7(harenDir, ".gitignore");
1715
- const before = existsSync9(path) ? await readFile4(path, "utf-8") : "";
2399
+ const path = join11(harenDir, ".gitignore");
2400
+ const before = existsSync13(path) ? await readFile9(path, "utf-8") : "";
1716
2401
  const lines = new Set(before.split(/\r?\n/).map((l) => l.trim()));
1717
- const missing = AGENT_FILES.filter((f) => !lines.has(f));
2402
+ const missing = IGNORED.filter((f) => !lines.has(f));
1718
2403
  if (missing.length === 0)
1719
2404
  return null;
1720
2405
  const eol = before.includes(`\r
@@ -1726,11 +2411,11 @@ async function planGitignore(harenDir) {
1726
2411
  return `${base}${missing.join(eol)}${eol}`;
1727
2412
  }
1728
2413
  async function copyRecursive2(src, dest) {
1729
- const entries = await readdir4(src, { withFileTypes: true });
1730
- await mkdir5(dest, { recursive: true });
2414
+ const entries = await readdir5(src, { withFileTypes: true });
2415
+ await mkdir7(dest, { recursive: true });
1731
2416
  for (const entry of entries) {
1732
- const srcPath = join7(src, entry.name);
1733
- const destPath = join7(dest, entry.name);
2417
+ const srcPath = join11(src, entry.name);
2418
+ const destPath = join11(dest, entry.name);
1734
2419
  if (entry.isDirectory()) {
1735
2420
  await copyRecursive2(srcPath, destPath);
1736
2421
  } else {
@@ -1740,10 +2425,10 @@ async function copyRecursive2(src, dest) {
1740
2425
  }
1741
2426
  async function countFiles(dir) {
1742
2427
  let count = 0;
1743
- const entries = await readdir4(dir, { withFileTypes: true });
2428
+ const entries = await readdir5(dir, { withFileTypes: true });
1744
2429
  for (const entry of entries) {
1745
2430
  if (entry.isDirectory()) {
1746
- count += await countFiles(join7(dir, entry.name));
2431
+ count += await countFiles(join11(dir, entry.name));
1747
2432
  } else {
1748
2433
  count++;
1749
2434
  }
@@ -1787,8 +2472,8 @@ async function upgrade(args) {
1787
2472
  console.log("\x1B[2m Upgrading framework files:\x1B[0m");
1788
2473
  let totalFiles = 0;
1789
2474
  for (const dir of FRAMEWORK_DIRS) {
1790
- const srcDir = join7(contentDir, dir);
1791
- const destDir = join7(targetDir, dir);
2475
+ const srcDir = join11(contentDir, dir);
2476
+ const destDir = join11(targetDir, dir);
1792
2477
  const fileCount = await countFiles(srcDir);
1793
2478
  totalFiles += fileCount;
1794
2479
  console.log(` \x1B[36m\u2191\x1B[0m ${dir}/ \x1B[2m(${fileCount} files)\x1B[0m`);
@@ -1808,20 +2493,34 @@ async function upgrade(args) {
1808
2493
  return;
1809
2494
  }
1810
2495
  for (const dir of FRAMEWORK_DIRS) {
1811
- await copyRecursive2(join7(contentDir, dir), join7(targetDir, dir));
2496
+ await copyRecursive2(join11(contentDir, dir), join11(targetDir, dir));
1812
2497
  }
1813
2498
  await Promise.resolve().then(() => init_init());
1814
2499
  await scaffoldSkillMd(targetDir);
1815
2500
  await writeGateScript(targetDir);
1816
2501
  if (migration.manifest.after !== migration.manifest.before) {
1817
- await writeFile4(join7(targetDir, "manifest.yaml"), migration.manifest.after);
2502
+ await writeFile6(join11(targetDir, "manifest.yaml"), migration.manifest.after);
1818
2503
  }
1819
2504
  if (migration.progress) {
1820
- await writeFile4(join7(targetDir, "progress.json"), migration.progress.after);
2505
+ await writeFile6(join11(targetDir, "progress.json"), migration.progress.after);
1821
2506
  }
1822
2507
  if (migration.gitignore !== null) {
1823
- await writeFile4(join7(targetDir, ".gitignore"), migration.gitignore);
2508
+ await writeFile6(join11(targetDir, ".gitignore"), migration.gitignore);
1824
2509
  }
2510
+ const yes = args.includes("--yes") || args.includes("-y");
2511
+ const pluginCtx = {
2512
+ workspaceDir: location.workspaceDir,
2513
+ harenDir: targetDir,
2514
+ project: String(parseManifest(migration.manifest.after).project ?? ""),
2515
+ io: { confirm: async () => yes, log: (l) => console.log(` ${l}`) }
2516
+ };
2517
+ const restored = await restorePlugins(pluginCtx, {
2518
+ warn: (l) => console.warn(` \x1B[33m!\x1B[0m ${l}`),
2519
+ error: (l) => console.error(` \x1B[31m\u2717\x1B[0m ${l}`)
2520
+ });
2521
+ const pluginWarnings = await refreshPlugins({ ...pluginCtx, io: { ...pluginCtx.io, confirm: async () => false } }, restored);
2522
+ for (const w of pluginWarnings)
2523
+ console.warn(` \x1B[33m!\x1B[0m ${w}`);
1825
2524
  await writeRootFiles({
1826
2525
  workspaceDir: location.workspaceDir,
1827
2526
  harenDir: targetDir,
@@ -1831,7 +2530,7 @@ async function upgrade(args) {
1831
2530
  console.log(` \x1B[2mYour artifacts are untouched. Manifest and progress were migrated if needed.\x1B[0m`);
1832
2531
  console.log("");
1833
2532
  }
1834
- var AGENT_FILES, FRAMEWORK_DIRS, USER_FILES;
2533
+ var IGNORED, FRAMEWORK_DIRS, USER_FILES;
1835
2534
  var init_upgrade = __esm(() => {
1836
2535
  init_content_dir();
1837
2536
  init_version();
@@ -1841,22 +2540,23 @@ var init_upgrade = __esm(() => {
1841
2540
  init_progress();
1842
2541
  init_resolve();
1843
2542
  init_root_files();
2543
+ init_install();
1844
2544
  init_templates();
1845
- AGENT_FILES = [".agent.json", ".agent.pid"];
2545
+ IGNORED = [".agent.json", ".agent.pid", ".plugins/"];
1846
2546
  FRAMEWORK_DIRS = ["agents", "skills", "templates"];
1847
2547
  USER_FILES = ["FEEDBACK.md", "artifacts/", "events/"];
1848
2548
  });
1849
2549
 
1850
2550
  // src/agent/config.ts
1851
- import { join as join8 } from "path";
2551
+ import { join as join12 } from "path";
1852
2552
  async function readAgentConfig(harenDir) {
1853
- const file = Bun.file(join8(harenDir, CONFIG_FILE));
2553
+ const file = Bun.file(join12(harenDir, CONFIG_FILE));
1854
2554
  if (!await file.exists())
1855
2555
  return null;
1856
2556
  return file.json();
1857
2557
  }
1858
2558
  async function writeAgentConfig(harenDir, config) {
1859
- const path = join8(harenDir, CONFIG_FILE);
2559
+ const path = join12(harenDir, CONFIG_FILE);
1860
2560
  await Bun.write(path, JSON.stringify(config, null, 2));
1861
2561
  }
1862
2562
  var CONFIG_FILE = ".agent.json";
@@ -1879,16 +2579,16 @@ var init_cli_detector = __esm(() => {
1879
2579
  });
1880
2580
 
1881
2581
  // src/agent/artifact-reader.ts
1882
- import { join as join9 } from "path";
1883
- import { readdir as readdir5 } from "fs/promises";
1884
- async function readProgress(harenDir) {
1885
- const file = Bun.file(join9(harenDir, "progress.json"));
2582
+ import { join as join13 } from "path";
2583
+ import { readdir as readdir6 } from "fs/promises";
2584
+ async function readProgress2(harenDir) {
2585
+ const file = Bun.file(join13(harenDir, "progress.json"));
1886
2586
  if (!await file.exists())
1887
2587
  return null;
1888
2588
  return file.json();
1889
2589
  }
1890
2590
  async function readArtifactTree(harenDir) {
1891
- const artifactsDir = join9(harenDir, "artifacts");
2591
+ const artifactsDir = join13(harenDir, "artifacts");
1892
2592
  try {
1893
2593
  return await buildTree(artifactsDir, "artifacts");
1894
2594
  } catch {
@@ -1896,12 +2596,12 @@ async function readArtifactTree(harenDir) {
1896
2596
  }
1897
2597
  }
1898
2598
  async function buildTree(dirPath, relativePath) {
1899
- const entries = await readdir5(dirPath, { withFileTypes: true });
2599
+ const entries = await readdir6(dirPath, { withFileTypes: true });
1900
2600
  const nodes = [];
1901
2601
  for (const entry of entries) {
1902
- const entryPath = join9(relativePath, entry.name);
2602
+ const entryPath = join13(relativePath, entry.name);
1903
2603
  if (entry.isDirectory()) {
1904
- const children = await buildTree(join9(dirPath, entry.name), entryPath);
2604
+ const children = await buildTree(join13(dirPath, entry.name), entryPath);
1905
2605
  nodes.push({
1906
2606
  name: entry.name,
1907
2607
  type: "directory",
@@ -1915,7 +2615,7 @@ async function buildTree(dirPath, relativePath) {
1915
2615
  return nodes.sort((a, b) => a.name.localeCompare(b.name));
1916
2616
  }
1917
2617
  async function readArtifact(harenDir, relativePath) {
1918
- const file = Bun.file(join9(harenDir, relativePath));
2618
+ const file = Bun.file(join13(harenDir, relativePath));
1919
2619
  if (!await file.exists())
1920
2620
  return null;
1921
2621
  return file.text();
@@ -1990,7 +2690,7 @@ function buildCLIArgs(cli, prompt) {
1990
2690
  }
1991
2691
 
1992
2692
  // src/workspace/events.ts
1993
- import { appendFile, readFile as readFile5 } from "fs/promises";
2693
+ import { appendFile, readFile as readFile10 } from "fs/promises";
1994
2694
  async function appendEvent(path, event) {
1995
2695
  const line = JSON.stringify(event) + `
1996
2696
  `;
@@ -2016,7 +2716,7 @@ async function handleDataRequest(requestId, path, harenDir, send) {
2016
2716
  let data;
2017
2717
  switch (path) {
2018
2718
  case "progress":
2019
- data = await readProgress(harenDir);
2719
+ data = await readProgress2(harenDir);
2020
2720
  break;
2021
2721
  case "artifacts":
2022
2722
  data = await readArtifactTree(harenDir);
@@ -2054,7 +2754,7 @@ var init_request_handler = __esm(() => {
2054
2754
  });
2055
2755
 
2056
2756
  // src/agent/connection.ts
2057
- import { join as join10 } from "path";
2757
+ import { join as join14 } from "path";
2058
2758
  function buildWsUrl(portalUrl) {
2059
2759
  return portalUrl.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws/agent";
2060
2760
  }
@@ -2068,7 +2768,7 @@ function buildAuthMessage(opts) {
2068
2768
  };
2069
2769
  }
2070
2770
  async function connectToPortal(config) {
2071
- await Bun.write(join10(config.harenDir, ".agent.pid"), process.pid.toString());
2771
+ await Bun.write(join14(config.harenDir, ".agent.pid"), process.pid.toString());
2072
2772
  setupCleanup(config.harenDir);
2073
2773
  try {
2074
2774
  await connectWebSocket(config);
@@ -2224,7 +2924,7 @@ async function connectPolling(config) {
2224
2924
  }
2225
2925
  }
2226
2926
  function setupCleanup(harenDir) {
2227
- const pidPath = join10(harenDir, ".agent.pid");
2927
+ const pidPath = join14(harenDir, ".agent.pid");
2228
2928
  const cleanup = async () => {
2229
2929
  console.log("Agent shutting down...");
2230
2930
  const { unlink } = await import("fs/promises");
@@ -2237,7 +2937,7 @@ function setupCleanup(harenDir) {
2237
2937
  var init_connection = () => {};
2238
2938
 
2239
2939
  // src/commands/agent.ts
2240
- import { join as join11 } from "path";
2940
+ import { join as join15 } from "path";
2241
2941
  function readLine2(question) {
2242
2942
  process.stdout.write(question);
2243
2943
  return new Promise((resolve) => {
@@ -2331,7 +3031,7 @@ async function startAgent(harenDir) {
2331
3031
  config = { portalUrl, teamCode, userId, userName };
2332
3032
  await writeAgentConfig(harenDir, config);
2333
3033
  console.log(`
2334
- Config saved to ${join11(harenDir, ".agent.json")}`);
3034
+ Config saved to ${join15(harenDir, ".agent.json")}`);
2335
3035
  }
2336
3036
  const gitRemoteUrl = await getRemoteUrl(harenDir);
2337
3037
  if (!gitRemoteUrl) {
@@ -2355,7 +3055,7 @@ Config saved to ${join11(harenDir, ".agent.json")}`);
2355
3055
  });
2356
3056
  }
2357
3057
  async function stopAgent(harenDir) {
2358
- const pidFile = Bun.file(join11(harenDir, ".agent.pid"));
3058
+ const pidFile = Bun.file(join15(harenDir, ".agent.pid"));
2359
3059
  if (!await pidFile.exists()) {
2360
3060
  console.log("Agent is not running.");
2361
3061
  return;
@@ -2368,7 +3068,7 @@ async function stopAgent(harenDir) {
2368
3068
  console.log("Agent process not found. Cleaning up.");
2369
3069
  }
2370
3070
  const { unlink } = await import("fs/promises");
2371
- await unlink(join11(harenDir, ".agent.pid")).catch(() => {});
3071
+ await unlink(join15(harenDir, ".agent.pid")).catch(() => {});
2372
3072
  }
2373
3073
  async function showStatus(harenDir) {
2374
3074
  const config = await readAgentConfig(harenDir);
@@ -2376,7 +3076,7 @@ async function showStatus(harenDir) {
2376
3076
  console.log("Agent is not configured. Run 'haren agent start' first.");
2377
3077
  return;
2378
3078
  }
2379
- const pidFile = Bun.file(join11(harenDir, ".agent.pid"));
3079
+ const pidFile = Bun.file(join15(harenDir, ".agent.pid"));
2380
3080
  const isRunning = await pidFile.exists();
2381
3081
  console.log(`Portal: ${config.portalUrl}`);
2382
3082
  console.log(`Team: ${config.teamCode}`);
@@ -2394,6 +3094,471 @@ var init_agent = __esm(() => {
2394
3094
  init_git();
2395
3095
  });
2396
3096
 
3097
+ // src/plugins/tasks.ts
3098
+ function slugify(title) {
3099
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
3100
+ }
3101
+ function parseTasksFile(text) {
3102
+ const sections = text.split(/^## Task (\d+):[ \t]*(.+)$/m);
3103
+ const raw = [];
3104
+ for (let i = 1;i + 2 < sections.length; i += 3) {
3105
+ raw.push({
3106
+ number: Number(sections[i]),
3107
+ title: sections[i + 1].trim(),
3108
+ body: sections[i + 2] ?? ""
3109
+ });
3110
+ }
3111
+ const keyOf = new Map(raw.map((t) => [t.number, `task-${t.number}-${slugify(t.title)}`]));
3112
+ return raw.map((t) => {
3113
+ const field = (name) => new RegExp(`^\\*\\*${name}:\\*\\*[ \\t]*(.*)$`, "m").exec(t.body)?.[1]?.trim() ?? "";
3114
+ const deps = [...field("Dependencies").matchAll(/Task (\d+)/g)].map((m) => keyOf.get(Number(m[1]))).filter((k) => k !== undefined);
3115
+ return {
3116
+ key: keyOf.get(t.number),
3117
+ number: t.number,
3118
+ title: t.title,
3119
+ description: field("Description"),
3120
+ dependencies: deps
3121
+ };
3122
+ });
3123
+ }
3124
+ function alignTaskKeys(tasks, existing) {
3125
+ const aligned = new Map;
3126
+ for (const t of tasks) {
3127
+ const found = existing.find((k) => k.startsWith(`task-${t.number}-`));
3128
+ aligned.set(t.key, found ?? t.key);
3129
+ }
3130
+ return tasks.map((t) => ({
3131
+ ...t,
3132
+ key: aligned.get(t.key),
3133
+ dependencies: t.dependencies.map((d) => aligned.get(d) ?? d)
3134
+ }));
3135
+ }
3136
+
3137
+ // src/plugins/updates.ts
3138
+ function applyUpdates(progress, updates) {
3139
+ let current = progress;
3140
+ const applied = [];
3141
+ const skipped = [];
3142
+ for (const u of updates) {
3143
+ if (!u || typeof u !== "object") {
3144
+ skipped.push({ update: u, reason: "Update must be an object" });
3145
+ continue;
3146
+ }
3147
+ const extra = Object.keys(u).filter((k) => !KEYS.includes(k));
3148
+ if (extra.length > 0) {
3149
+ skipped.push({ update: u, reason: `Unknown field: ${extra.join(", ")}` });
3150
+ continue;
3151
+ }
3152
+ const { module, feature, status } = u;
3153
+ if (typeof module !== "string" || typeof feature !== "string") {
3154
+ skipped.push({ update: u, reason: "module and feature must be strings" });
3155
+ continue;
3156
+ }
3157
+ if (!STATUSES.includes(status)) {
3158
+ skipped.push({ update: u, reason: `Unknown status: ${String(status)}` });
3159
+ continue;
3160
+ }
3161
+ if (!Object.hasOwn(current.modules, module)) {
3162
+ skipped.push({ update: u, reason: `Unknown module: ${module}` });
3163
+ continue;
3164
+ }
3165
+ const mod = current.modules[module];
3166
+ if (!Object.hasOwn(mod.features, feature)) {
3167
+ skipped.push({ update: u, reason: `Unknown feature: ${module}/${feature}` });
3168
+ continue;
3169
+ }
3170
+ if (mod.features[feature] === status)
3171
+ continue;
3172
+ try {
3173
+ current = updateFeatureStatus(current, module, feature, status);
3174
+ applied.push({ module, feature, status });
3175
+ } catch (err) {
3176
+ skipped.push({ update: u, reason: err.message });
3177
+ }
3178
+ }
3179
+ return { progress: current, applied, skipped };
3180
+ }
3181
+ var STATUSES, KEYS;
3182
+ var init_updates = __esm(() => {
3183
+ init_progress();
3184
+ STATUSES = [
3185
+ "pending",
3186
+ "in-progress",
3187
+ "evaluating",
3188
+ "passing",
3189
+ "fixing",
3190
+ "blocked"
3191
+ ];
3192
+ KEYS = ["module", "feature", "status"];
3193
+ });
3194
+
3195
+ // src/plugins/runner.ts
3196
+ import { existsSync as existsSync14 } from "fs";
3197
+ import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile11 } from "fs/promises";
3198
+ import { isAbsolute as isAbsolute3, join as join16 } from "path";
3199
+ function tasksPath(input, harenDir) {
3200
+ if (typeof input.tasksFile !== "string")
3201
+ return;
3202
+ return isAbsolute3(input.tasksFile) ? input.tasksFile : join16(harenDir, input.tasksFile);
3203
+ }
3204
+ async function loadPlannedTasks(input, harenDir) {
3205
+ const path = tasksPath(input, harenDir);
3206
+ if (!path || !existsSync14(path))
3207
+ return [];
3208
+ const tasks = parseTasksFile(await readFile11(path, "utf-8"));
3209
+ const progressPath = join16(harenDir, "progress.json");
3210
+ if (typeof input.module !== "string" || !existsSync14(progressPath))
3211
+ return tasks;
3212
+ try {
3213
+ const mod = (await readProgress(progressPath)).modules[input.module];
3214
+ return mod ? alignTaskKeys(tasks, Object.keys(mod.features)) : tasks;
3215
+ } catch {
3216
+ return tasks;
3217
+ }
3218
+ }
3219
+ async function buildPayload(hook, input, harenDir) {
3220
+ const payload = { ...input, hook };
3221
+ const path = tasksPath(input, harenDir);
3222
+ if (hook === "after-plan" && path) {
3223
+ payload.tasksFile = path;
3224
+ payload.tasks = await loadPlannedTasks(input, harenDir);
3225
+ }
3226
+ return payload;
3227
+ }
3228
+ async function addPlannedFeatures(input, harenDir) {
3229
+ const progressPath = join16(harenDir, "progress.json");
3230
+ if (typeof input.module !== "string" || !existsSync14(progressPath))
3231
+ return;
3232
+ const tasks = await loadPlannedTasks(input, harenDir);
3233
+ const progress = await readProgress(progressPath);
3234
+ const mod = progress.modules[input.module];
3235
+ if (!mod)
3236
+ return;
3237
+ let changed = false;
3238
+ for (const t of tasks) {
3239
+ if (!(t.key in mod.features)) {
3240
+ mod.features[t.key] = "pending";
3241
+ changed = true;
3242
+ }
3243
+ }
3244
+ if (changed)
3245
+ await writeProgress(progressPath, progress);
3246
+ }
3247
+ async function logError(dir, hook, error) {
3248
+ await appendFile2(join16(dir, "errors.log"), `${new Date().toISOString()} ${hook}: ${error}
3249
+ `).catch(() => {});
3250
+ }
3251
+ async function runHook(hook, input, o) {
3252
+ const state = await readPlugins(o.harenDir);
3253
+ const payload = JSON.stringify(await buildPayload(hook, input, o.harenDir));
3254
+ const outcomes = [];
3255
+ for (const [name, entry] of Object.entries(state.plugins)) {
3256
+ if (!entry.enabled)
3257
+ continue;
3258
+ const dir = pluginDir(o.harenDir, name);
3259
+ const fail = async (error) => {
3260
+ outcomes.push({ plugin: name, ok: false, messages: [], updates: [], error });
3261
+ await logError(dir, hook, error);
3262
+ };
3263
+ let command;
3264
+ let config = {};
3265
+ try {
3266
+ const manifest = await readInstalledManifest(dir);
3267
+ command = manifest.hooks[hook];
3268
+ config = { ...manifest.config, ...entry.config };
3269
+ } catch (err) {
3270
+ await fail(`manifest unreadable: ${err.message}. Run 'haren plugin doctor'.`);
3271
+ continue;
3272
+ }
3273
+ if (!command)
3274
+ continue;
3275
+ const limit = o.timeoutMs ?? 30000;
3276
+ let timedOut = false;
3277
+ let timer;
3278
+ let stdout;
3279
+ let stderr;
3280
+ let code;
3281
+ try {
3282
+ const dataDir = pluginDataDir(o.harenDir, name);
3283
+ await mkdir8(dataDir, { recursive: true });
3284
+ const proc = Bun.spawn(["sh", "-c", command], {
3285
+ cwd: dir,
3286
+ stdin: new Blob([payload]),
3287
+ stdout: "pipe",
3288
+ stderr: "pipe",
3289
+ detached: true,
3290
+ env: {
3291
+ ...process.env,
3292
+ HAREN_ROOT: o.workspaceDir,
3293
+ HAREN_DIR: o.harenDir,
3294
+ HAREN_PLUGIN_DIR: dir,
3295
+ HAREN_PLUGIN_DATA: dataDir,
3296
+ HAREN_PLUGIN_CONFIG: JSON.stringify(config)
3297
+ }
3298
+ });
3299
+ const collected = Promise.all([
3300
+ new Response(proc.stdout).text(),
3301
+ new Response(proc.stderr).text(),
3302
+ proc.exited
3303
+ ]);
3304
+ collected.catch(() => {});
3305
+ const expired = new Promise((resolve) => {
3306
+ timer = setTimeout(() => {
3307
+ timedOut = true;
3308
+ try {
3309
+ process.kill(-proc.pid, "SIGKILL");
3310
+ } catch {
3311
+ try {
3312
+ proc.kill("SIGKILL");
3313
+ } catch {}
3314
+ }
3315
+ setTimeout(() => resolve(null), 500);
3316
+ }, limit);
3317
+ });
3318
+ const res = await Promise.race([collected, expired]);
3319
+ clearTimeout(timer);
3320
+ if (res === null) {
3321
+ await fail(`timed out after ${limit} ms`);
3322
+ continue;
3323
+ }
3324
+ [stdout, stderr, code] = res;
3325
+ } catch (err) {
3326
+ clearTimeout(timer);
3327
+ await fail(`could not start hook: ${err.message}`);
3328
+ continue;
3329
+ }
3330
+ if (timedOut) {
3331
+ await fail(`timed out after ${limit} ms`);
3332
+ continue;
3333
+ }
3334
+ if (code !== 0) {
3335
+ await fail(`exit ${code}: ${stderr.trim().split(`
3336
+ `).pop() ?? ""}`);
3337
+ continue;
3338
+ }
3339
+ let result;
3340
+ try {
3341
+ result = stdout.trim() ? JSON.parse(stdout) : {};
3342
+ } catch {
3343
+ await fail("invalid JSON on stdout");
3344
+ continue;
3345
+ }
3346
+ outcomes.push({
3347
+ plugin: name,
3348
+ ok: true,
3349
+ messages: Array.isArray(result.messages) ? result.messages.map(String) : [],
3350
+ updates: Array.isArray(result.updates) ? result.updates : []
3351
+ });
3352
+ }
3353
+ return outcomes;
3354
+ }
3355
+ async function runHookAndApply(hook, input, o) {
3356
+ const lines = [];
3357
+ let outcomes;
3358
+ if (hook === "after-plan") {
3359
+ try {
3360
+ await addPlannedFeatures(input, o.harenDir);
3361
+ } catch (err) {
3362
+ lines.push(`warning: could not add planned features: ${err.message}`);
3363
+ }
3364
+ }
3365
+ try {
3366
+ outcomes = await runHook(hook, input, o);
3367
+ } catch (err) {
3368
+ lines.push(`warning: could not run ${hook} hooks: ${err.message}`);
3369
+ return lines;
3370
+ }
3371
+ const updates = [];
3372
+ for (const out of outcomes) {
3373
+ for (const m of out.messages)
3374
+ lines.push(`[${out.plugin}] ${m}`);
3375
+ if (!out.ok)
3376
+ lines.push(`[${out.plugin}] warning: ${hook} failed: ${out.error}`);
3377
+ updates.push(...out.updates);
3378
+ }
3379
+ try {
3380
+ const progressPath = join16(o.harenDir, "progress.json");
3381
+ if (updates.length > 0 && existsSync14(progressPath)) {
3382
+ const result = applyUpdates(await readProgress(progressPath), updates);
3383
+ if (result.applied.length > 0)
3384
+ await writeProgress(progressPath, result.progress);
3385
+ for (const u of result.applied)
3386
+ lines.push(`updated ${u.module}/${u.feature} \u2192 ${u.status}`);
3387
+ for (const s of result.skipped)
3388
+ lines.push(`skipped update ${JSON.stringify(s.update)}: ${s.reason}`);
3389
+ }
3390
+ } catch (err) {
3391
+ lines.push(`warning: could not apply plugin updates: ${err.message}`);
3392
+ }
3393
+ return lines;
3394
+ }
3395
+ var init_runner = __esm(() => {
3396
+ init_progress();
3397
+ init_manifest2();
3398
+ init_state();
3399
+ init_updates();
3400
+ });
3401
+
3402
+ // src/commands/plugin.ts
3403
+ import { readFile as readFile12 } from "fs/promises";
3404
+ import { join as join17 } from "path";
3405
+ function parsePluginArgs(args) {
3406
+ const sub = args[0];
3407
+ if (!SUBS.includes(sub))
3408
+ throw new Error(USAGE);
3409
+ const yes = args.includes("--yes") || args.includes("-y");
3410
+ const target = args[1] && !args[1].startsWith("-") ? args[1] : undefined;
3411
+ if ((sub === "add" || sub === "remove") && !target)
3412
+ throw new Error(`haren plugin ${sub} needs a plugin`);
3413
+ if (sub === "run" && !HOOK_NAMES.includes(target ?? "")) {
3414
+ throw new Error(`Unknown hook: ${target ?? ""}. Hooks: ${HOOK_NAMES.join(", ")}`);
3415
+ }
3416
+ let payload = {};
3417
+ const i = args.indexOf("--payload");
3418
+ if (i >= 0) {
3419
+ try {
3420
+ payload = JSON.parse(args[i + 1] ?? "");
3421
+ } catch {
3422
+ throw new Error("--payload must be JSON");
3423
+ }
3424
+ }
3425
+ return { sub, target, payload, yes };
3426
+ }
3427
+ async function confirm(question, yes) {
3428
+ if (yes)
3429
+ return true;
3430
+ if (!process.stdin.isTTY)
3431
+ return false;
3432
+ process.stdout.write(` \x1B[36m?\x1B[0m ${question} (y/N) `);
3433
+ const answer = await new Promise((resolve) => {
3434
+ process.stdin.resume();
3435
+ process.stdin.once("data", (d) => {
3436
+ process.stdin.pause();
3437
+ resolve(d.toString().trim());
3438
+ });
3439
+ });
3440
+ return /^y(es)?$/i.test(answer);
3441
+ }
3442
+ async function plugin(args) {
3443
+ let opts;
3444
+ try {
3445
+ opts = parsePluginArgs(args);
3446
+ } catch (err) {
3447
+ console.error(` ${err.message}`);
3448
+ process.exit(1);
3449
+ }
3450
+ if (opts.sub === "run") {
3451
+ try {
3452
+ const loc = await resolveHarenDir(process.cwd(), {
3453
+ harenDir: harenDirFlag(args),
3454
+ env: process.env
3455
+ });
3456
+ if (!loc)
3457
+ throw new Error("No haren folder found");
3458
+ for (const line of await runHookAndApply(opts.target, opts.payload, {
3459
+ workspaceDir: loc.workspaceDir,
3460
+ harenDir: loc.harenDir
3461
+ })) {
3462
+ console.log(` ${line}`);
3463
+ }
3464
+ } catch (err) {
3465
+ console.log(` warning: plugin hook ${opts.target} skipped: ${err.message}`);
3466
+ }
3467
+ return;
3468
+ }
3469
+ let location;
3470
+ try {
3471
+ location = await resolveHarenDir(process.cwd(), {
3472
+ harenDir: harenDirFlag(args),
3473
+ env: process.env
3474
+ });
3475
+ } catch (err) {
3476
+ console.error(` ${err instanceof MultipleHarenDirsError ? err.message : String(err)}`);
3477
+ process.exit(1);
3478
+ }
3479
+ if (!location) {
3480
+ console.error(" No haren folder found. Run 'haren init' first.");
3481
+ process.exit(1);
3482
+ }
3483
+ const { workspaceDir, harenDir } = location;
3484
+ const manifest = parseManifest(await readFile12(join17(harenDir, "manifest.yaml"), "utf-8"));
3485
+ const ctx = {
3486
+ workspaceDir,
3487
+ harenDir,
3488
+ project: String(manifest.project ?? ""),
3489
+ io: { confirm: (q) => confirm(q, opts.yes), log: (l) => console.log(` ${l}`) }
3490
+ };
3491
+ const syncEditors = () => writeRootFiles({ workspaceDir, harenDir, editor: detectEditor(workspaceDir) ?? "claude-code" });
3492
+ switch (opts.sub) {
3493
+ case "add":
3494
+ try {
3495
+ await installPlugin(opts.target, ctx);
3496
+ } catch (err) {
3497
+ console.error(` ${err.message}`);
3498
+ process.exit(1);
3499
+ }
3500
+ await syncEditors();
3501
+ return;
3502
+ case "remove":
3503
+ try {
3504
+ const copies = await pluginFiles(harenDir, opts.target);
3505
+ await removePlugin(opts.target, ctx);
3506
+ await removeEditorCopies(workspaceDir, copies);
3507
+ } catch (err) {
3508
+ console.error(` ${err.message}`);
3509
+ process.exit(1);
3510
+ }
3511
+ await syncEditors();
3512
+ console.log(` Removed plugin ${opts.target}. Tool data in the project stays.`);
3513
+ return;
3514
+ case "list": {
3515
+ const state = await readPlugins(harenDir);
3516
+ const rows = Object.entries(state.plugins);
3517
+ if (rows.length === 0)
3518
+ console.log(" No plugins installed.");
3519
+ for (const [name, e] of rows) {
3520
+ console.log(` ${name} ${e.version} ${e.enabled ? "enabled" : "disabled"} ${e.source}`);
3521
+ }
3522
+ return;
3523
+ }
3524
+ case "doctor": {
3525
+ const state = await readPlugins(harenDir);
3526
+ for (const name of Object.keys(state.plugins)) {
3527
+ const dir = pluginDir(harenDir, name);
3528
+ try {
3529
+ const m = await readInstalledManifest(dir);
3530
+ console.log(` ${name}: manifest ok (${m.version})`);
3531
+ for (const req of m.requires) {
3532
+ const s = await checkRequirement(req);
3533
+ console.log(` ${req.bin}: ${s.ok ? `ok ${s.version ?? ""}` : s.reason}${!s.ok && req.install ? ` \u2014 run: ${req.install}` : ""}`);
3534
+ }
3535
+ } catch (err) {
3536
+ console.log(` ${name}: ${err.message}`);
3537
+ }
3538
+ const log = Bun.file(join17(dir, "errors.log"));
3539
+ if (await log.exists()) {
3540
+ const last = (await log.text()).trim().split(`
3541
+ `).slice(-3);
3542
+ for (const l of last)
3543
+ console.log(` last error: ${l}`);
3544
+ }
3545
+ }
3546
+ return;
3547
+ }
3548
+ }
3549
+ }
3550
+ var SUBS, USAGE = "Usage: haren plugin add <name|source> | remove <name> | list | run <hook> [--payload <json>] | doctor";
3551
+ var init_plugin = __esm(() => {
3552
+ init_manifest2();
3553
+ init_install();
3554
+ init_runner();
3555
+ init_state();
3556
+ init_manifest();
3557
+ init_root_files();
3558
+ init_resolve();
3559
+ SUBS = ["add", "remove", "list", "run", "doctor"];
3560
+ });
3561
+
2397
3562
  // src/index.ts
2398
3563
  function parseArgs(args) {
2399
3564
  if (args.length === 0) {
@@ -2411,6 +3576,7 @@ function parseArgs(args) {
2411
3576
  case "init":
2412
3577
  case "upgrade":
2413
3578
  case "agent":
3579
+ case "plugin":
2414
3580
  return { command, args: rest };
2415
3581
  default:
2416
3582
  return { command: "unknown", args };
@@ -2435,13 +3601,20 @@ async function main() {
2435
3601
  await agent(parsed.args);
2436
3602
  break;
2437
3603
  }
3604
+ case "plugin": {
3605
+ await Promise.resolve().then(() => init_plugin());
3606
+ await plugin(parsed.args);
3607
+ break;
3608
+ }
2438
3609
  case "help":
2439
3610
  console.log("Usage:");
2440
3611
  console.log(" haren init Set up haren (detects monorepo or multi-repo workspace)");
2441
3612
  console.log(" --dir <path> --layout monorepo|workspace --haren-dir <name>");
2442
3613
  console.log(" --yes|-y --dry-run --force");
2443
- console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run)");
3614
+ console.log(" --plugin <name|source> (repeatable)");
3615
+ console.log(" haren upgrade Upgrade framework files and migrate manifest/progress (--dry-run, --yes)");
2444
3616
  console.log(" haren agent Manage local agent (start, stop, status)");
3617
+ console.log(" haren plugin Manage plugins (add, remove, list, run, doctor)");
2445
3618
  break;
2446
3619
  case "unknown":
2447
3620
  console.error(`Unknown command: ${parsed.args[0]}`);