@jaybeeuu/agent-cortex 1.38.1 → 1.40.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 (88) hide show
  1. package/.agents/skills/style-versioning/SKILL.md +1 -1
  2. package/.github/workflows/ci.yml +47 -14
  3. package/AGENTS.md +19 -3
  4. package/CHANGELOG.md +42 -0
  5. package/README.md +118 -63
  6. package/agents/README.md +13 -10
  7. package/agents/ralph-plan/agent.md +1 -1
  8. package/agents/ralph-plan.agent.md +1 -1
  9. package/bin/agent-cortex.mjs +29 -8
  10. package/bin/installers/claude.mjs +569 -105
  11. package/bin/installers/copilot.mjs +22 -12
  12. package/bin/installers/pi.mjs +37 -34
  13. package/docs/claude-hooks.md +3 -3
  14. package/docs/ideas/extension-manifests.md +75 -0
  15. package/docs/ideas/record-ideas-as-beads.md +115 -0
  16. package/docs/ideas/subagent-visibility.md +72 -0
  17. package/docs/ideas/task-session-context.md +89 -0
  18. package/docs/research/skill-design-research.md +4 -4
  19. package/docs/research/skill-improvements-analysis.md +1 -1
  20. package/docs/skills/skill-anatomy.md +38 -2
  21. package/docs/technical-direction/migration-execution-labels.md +132 -0
  22. package/extensions/agent-modes/README.md +3 -2
  23. package/extensions/agent-modes/discover.test.ts +30 -7
  24. package/extensions/agent-modes/discover.ts +1 -1
  25. package/extensions/skill-stats/index.test.ts +3 -2
  26. package/lib/cli.mjs +24 -6
  27. package/package.json +4 -4
  28. package/plugin.json +1 -1
  29. package/pnpm-workspace.yaml +1 -1
  30. package/scripts/build-copilot-agents.mjs +1 -1
  31. package/scripts/check-no-sync.mjs +49 -0
  32. package/scripts/lib/compose-agent.mjs +32 -14
  33. package/skills/engineering/design-an-interface/SKILL.md +78 -58
  34. package/skills/engineering/grill-with-docs/REFERENCE.md +78 -0
  35. package/skills/engineering/grill-with-docs/SKILL.md +66 -63
  36. package/skills/engineering/improve-codebase-architecture/SKILL.md +66 -48
  37. package/skills/engineering/technical-direction/FORMAT.md +38 -0
  38. package/skills/engineering/technical-direction/SKILL.md +70 -77
  39. package/skills/planning/classify-bead/SKILL.md +59 -35
  40. package/skills/planning/create-task/REFERENCE.md +40 -0
  41. package/skills/planning/create-task/SKILL.md +70 -66
  42. package/skills/planning/create-task/scripts/create-chores.ts +6 -1
  43. package/skills/planning/create-task/scripts/node_modules/.bin/tsc +21 -0
  44. package/skills/planning/create-task/scripts/node_modules/.bin/tsserver +21 -0
  45. package/skills/planning/create-task/scripts/node_modules/.bin/tsx +21 -0
  46. package/skills/planning/prd-to-tasks/REFERENCE.md +66 -0
  47. package/skills/planning/prd-to-tasks/SKILL.md +86 -170
  48. package/skills/planning/record-idea/FORMAT.md +44 -0
  49. package/skills/planning/record-idea/SKILL.md +70 -53
  50. package/skills/planning/request-refactor-plan/FORMAT.md +45 -0
  51. package/skills/planning/request-refactor-plan/SKILL.md +57 -46
  52. package/skills/planning/write-a-prd/FORMAT.md +54 -0
  53. package/skills/planning/write-a-prd/SKILL.md +49 -48
  54. package/skills/planning/write-a-ticket/SKILL.md +68 -53
  55. package/skills/productivity/handoff/SKILL.md +12 -0
  56. package/skills/productivity/init-beads/SKILL.md +48 -40
  57. package/skills/productivity/validate-agent-dir/scripts/node_modules/.bin/tsc +21 -0
  58. package/skills/productivity/validate-agent-dir/scripts/node_modules/.bin/tsserver +21 -0
  59. package/skills/productivity/validate-agent-dir/scripts/node_modules/.bin/tsx +21 -0
  60. package/skills/productivity/write-a-skill/SKILL.md +2 -1
  61. package/skills/review/maintain-agent-docs/SKILL.md +71 -51
  62. package/skills/workflow/hitl-collab/SKILL.md +86 -17
  63. package/skills/workflow/ralph/REFERENCE.md +22 -17
  64. package/skills/workflow/ralph/SKILL.md +88 -74
  65. package/skills/workflow/run-pipeline-stage/REFERENCE.md +22 -0
  66. package/skills/workflow/run-pipeline-stage/SKILL.md +91 -93
  67. package/skills/workflow/run-pipeline-stage/scripts/generate-progress.test.ts +6 -107
  68. package/skills/workflow/run-pipeline-stage/scripts/node_modules/.bin/tsc +21 -0
  69. package/skills/workflow/run-pipeline-stage/scripts/node_modules/.bin/tsserver +21 -0
  70. package/skills/workflow/run-pipeline-stage/scripts/node_modules/.bin/tsx +21 -0
  71. package/test/claude-installer.test.mjs +308 -0
  72. package/test/cli.test.mjs +40 -30
  73. package/test/copilot-installer.test.mjs +92 -82
  74. package/test/helpers/fake-claude.mjs +152 -0
  75. package/test/installer.test.mjs +309 -57
  76. package/test/pi-installer.test.mjs +115 -99
  77. package/token-map.README.md +21 -10
  78. package/token-map.json +7 -6
  79. package/.claude-plugin/marketplace.json +0 -16
  80. package/claude/.claude-plugin/plugin.json +0 -11
  81. package/claude/agents/plan.md +0 -58
  82. package/claude/agents/ralph-plan.md +0 -121
  83. package/claude/agents/ralph.md +0 -193
  84. package/claude/agents/strategy.md +0 -111
  85. package/claude/hooks/scripts/notify.mjs +0 -54
  86. package/claude/hooks.json +0 -38
  87. /package/{claude → claude-extras}/.mcp.json +0 -0
  88. /package/{claude → claude-extras}/scripts/statusline-command.sh +0 -0
@@ -5,7 +5,7 @@
5
5
  import { describe, it } from "node:test";
6
6
  import assert from "node:assert/strict";
7
7
  import { execFile } from "node:child_process";
8
- import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync, readdirSync, statSync } from "node:fs";
8
+ import { mkdtemp, mkdir, writeFile, rm, readFile, readdir, stat } from "node:fs/promises";
9
9
  import { tmpdir } from "node:os";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { join, dirname } from "node:path";
@@ -15,6 +15,16 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
15
15
  const ROOT = join(__dirname, "..");
16
16
  const CLI_PATH = join(ROOT, "bin", "agent-cortex.mjs");
17
17
 
18
+ /** True when a path exists (stat succeeds). */
19
+ async function pathExists(p) {
20
+ try {
21
+ await stat(p);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
18
28
  function runCli(args) {
19
29
  return new Promise((resolve) => {
20
30
  execFile(process.execPath, [CLI_PATH, ...args], (error, stdout, stderr) => {
@@ -43,28 +53,28 @@ function tokenMap() {
43
53
  };
44
54
  }
45
55
 
46
- function makeFixture() {
47
- const root = mkdtempSync(join(tmpdir(), "copilot-installer-"));
56
+ async function makeFixture() {
57
+ const root = await mkdtemp(join(tmpdir(), "copilot-installer-"));
48
58
  return {
49
59
  root,
50
60
  output: join(root, "generated"),
51
- cleanup: () => rmSync(root, { recursive: true, force: true }),
61
+ cleanup: async () => rm(root, { recursive: true, force: true }),
52
62
  };
53
63
  }
54
64
 
55
- function writeFixture(fx, relPath, content) {
65
+ async function writeFixture(fx, relPath, content) {
56
66
  const p = join(fx.root, relPath);
57
- mkdirSync(dirname(p), { recursive: true });
58
- writeFileSync(p, content);
67
+ await mkdir(dirname(p), { recursive: true });
68
+ await writeFile(p, content);
59
69
  }
60
70
 
61
71
  /** Seed a minimal but realistic package tree (agents + token-map). */
62
- function seedCopilotPackage(fx, opts = {}) {
72
+ async function seedCopilotPackage(fx, opts = {}) {
63
73
  const { agents = {} } = opts;
64
- writeFixture(fx, "token-map.json", JSON.stringify(tokenMap()));
74
+ await writeFixture(fx, "token-map.json", JSON.stringify(tokenMap()));
65
75
  for (const [name, def] of Object.entries(agents)) {
66
- writeFixture(fx, `agents/${name}/agent.md`, def.body ?? `# ${name}\nBody of ${name}.`);
67
- writeFixture(
76
+ await writeFixture(fx, `agents/${name}/agent.md`, def.body ?? `# ${name}\nBody of ${name}.`);
77
+ await writeFixture(
68
78
  fx,
69
79
  `agents/${name}/copilot/frontmatter.json`,
70
80
  JSON.stringify(
@@ -77,34 +87,34 @@ function seedCopilotPackage(fx, opts = {}) {
77
87
  ),
78
88
  );
79
89
  for (const [section, content] of Object.entries(def.sections ?? {})) {
80
- writeFixture(fx, `agents/${name}/copilot/${section}.md`, content);
90
+ await writeFixture(fx, `agents/${name}/copilot/${section}.md`, content);
81
91
  }
82
92
  }
83
93
  }
84
94
 
85
95
  /** Deterministic snapshot of a directory: relative paths + byte content. */
86
- function snapshot(dir) {
96
+ async function snapshot(dir) {
87
97
  const entries = [];
88
- const walk = (p) => {
89
- for (const e of readdirSync(p, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
98
+ const walk = async (p) => {
99
+ for (const e of (await readdir(p, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
90
100
  const full = join(p, e.name);
91
101
  if (e.isDirectory()) {
92
102
  entries.push([e.name, "dir"]);
93
- walk(full);
94
- } else entries.push([e.name, "file", readFileSync(full, "utf-8")]);
103
+ await walk(full);
104
+ } else entries.push([e.name, "file", await readFile(full, "utf-8")]);
95
105
  }
96
106
  };
97
- walk(dir);
107
+ await walk(dir);
98
108
  return entries;
99
109
  }
100
110
 
101
111
  // ─── Agent composition ───────────────────────────────────────────────────────
102
112
 
103
113
  describe("installCopilot — agent composition", () => {
104
- it("writes one flat <name>.agent.md per composable agent dir with copilot frontmatter and no leftover tokens", () => {
105
- const fx = makeFixture();
114
+ it("writes one flat <name>.agent.md per composable agent dir with copilot frontmatter and no leftover tokens", async () => {
115
+ const fx = await makeFixture();
106
116
  try {
107
- seedCopilotPackage(fx, {
117
+ await seedCopilotPackage(fx, {
108
118
  agents: {
109
119
  alpha: {
110
120
  body: "# alpha\nUse {{TOOL:view}} to read.\n{{SECTION:polling}}\nRead {{PATH:agents_dir}}.",
@@ -119,11 +129,11 @@ describe("installCopilot — agent composition", () => {
119
129
  },
120
130
  });
121
131
 
122
- const result = installCopilot({ root: fx.root, output: fx.output });
132
+ const result = await installCopilot({ root: fx.root, output: fx.output });
123
133
 
124
134
  const file = join(fx.output, "alpha.agent.md");
125
- assert.ok(existsSync(file), "flat agent file written");
126
- const content = readFileSync(file, "utf-8");
135
+ assert.ok(await pathExists(file), "flat agent file written");
136
+ const content = await readFile(file, "utf-8");
127
137
  assert.ok(content.startsWith("---\n"), "yaml frontmatter");
128
138
  assert.ok(content.includes("# GENERATED from agents/alpha/ by scripts/build-copilot-agents.mjs — DO NOT EDIT."));
129
139
  // Committed flat-file field order: description, name, tools (YAML array), argument-hint.
@@ -138,64 +148,64 @@ describe("installCopilot — agent composition", () => {
138
148
  assert.deepEqual(result.agents, ["alpha"]);
139
149
  assert.equal(result.output, fx.output);
140
150
  } finally {
141
- fx.cleanup();
151
+ await fx.cleanup();
142
152
  }
143
153
  });
144
154
 
145
- it("skips non-composable entries in agents/ and never clobbers composable sources", () => {
146
- const fx = makeFixture();
155
+ it("skips non-composable entries in agents/ and never clobbers composable sources", async () => {
156
+ const fx = await makeFixture();
147
157
  try {
148
- seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
149
- writeFixture(fx, "agents/README.md", "# agents dir docs\n");
158
+ await seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
159
+ await writeFixture(fx, "agents/README.md", "# agents dir docs\n");
150
160
 
151
- const result = installCopilot({ root: fx.root, output: fx.output });
161
+ const result = await installCopilot({ root: fx.root, output: fx.output });
152
162
 
153
- assert.deepEqual(readdirSync(fx.output).sort(), ["alpha.agent.md"], "no README, no subdirectories written");
163
+ assert.deepEqual((await readdir(fx.output)).sort(), ["alpha.agent.md"], "no README, no subdirectories written");
154
164
  assert.deepEqual(result.agents, ["alpha"]);
155
165
  // The composable source dir next to the generated file stays untouched.
156
- assert.ok(existsSync(join(fx.root, "agents", "alpha", "agent.md")), "composable source preserved");
157
- assert.ok(existsSync(join(fx.root, "agents", "alpha", "copilot", "frontmatter.json")), "harness dir preserved");
166
+ assert.ok(await pathExists(join(fx.root, "agents", "alpha", "agent.md")), "composable source preserved");
167
+ assert.ok(await pathExists(join(fx.root, "agents", "alpha", "copilot", "frontmatter.json")), "harness dir preserved");
158
168
  } finally {
159
- fx.cleanup();
169
+ await fx.cleanup();
160
170
  }
161
171
  });
162
172
 
163
- it("throws when a composable dir lacks copilot/frontmatter.json", () => {
164
- const fx = makeFixture();
173
+ it("throws when a composable dir lacks copilot/frontmatter.json", async () => {
174
+ const fx = await makeFixture();
165
175
  try {
166
- seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
167
- rmSync(join(fx.root, "agents", "alpha", "copilot"), { recursive: true, force: true });
168
- assert.throws(
169
- () => installCopilot({ root: fx.root, output: fx.output }),
176
+ await seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
177
+ await rm(join(fx.root, "agents", "alpha", "copilot"), { recursive: true, force: true });
178
+ await assert.rejects(
179
+ installCopilot({ root: fx.root, output: fx.output }),
170
180
  /without copilot\/frontmatter\.json/,
171
181
  );
172
182
  } finally {
173
- fx.cleanup();
183
+ await fx.cleanup();
174
184
  }
175
185
  });
176
186
 
177
- it("defaults to the plugin-scanned agents/ dir of the package root (plugin.json \"agents\": \"agents/\")", () => {
178
- const fx = makeFixture();
187
+ it("defaults to the plugin-scanned agents/ dir of the package root (plugin.json \"agents\": \"agents/\")", async () => {
188
+ const fx = await makeFixture();
179
189
  try {
180
- seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
190
+ await seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
181
191
 
182
- const result = installCopilot({ root: fx.root });
192
+ const result = await installCopilot({ root: fx.root });
183
193
 
184
194
  assert.equal(result.output, join(fx.root, "agents"), "default output is the dir plugin.json scans");
185
- assert.ok(existsSync(join(fx.root, "agents", "alpha.agent.md")), "flat file lands next to the composable dir");
186
- assert.ok(existsSync(join(fx.root, "agents", "alpha", "agent.md")), "composable source untouched");
195
+ assert.ok(await pathExists(join(fx.root, "agents", "alpha.agent.md")), "flat file lands next to the composable dir");
196
+ assert.ok(await pathExists(join(fx.root, "agents", "alpha", "agent.md")), "composable source untouched");
187
197
  } finally {
188
- fx.cleanup();
198
+ await fx.cleanup();
189
199
  }
190
200
  });
191
201
 
192
- it("throws on an unknown tool token", () => {
193
- const fx = makeFixture();
202
+ it("throws on an unknown tool token", async () => {
203
+ const fx = await makeFixture();
194
204
  try {
195
- seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha\nUse {{TOOL:nope}} now." } } });
196
- assert.throws(() => installCopilot({ root: fx.root, output: fx.output }), /unknown tool token {{TOOL:nope}}/);
205
+ await seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha\nUse {{TOOL:nope}} now." } } });
206
+ await assert.rejects(installCopilot({ root: fx.root, output: fx.output }), /unknown tool token {{TOOL:nope}}/);
197
207
  } finally {
198
- fx.cleanup();
208
+ await fx.cleanup();
199
209
  }
200
210
  });
201
211
  });
@@ -203,37 +213,37 @@ describe("installCopilot — agent composition", () => {
203
213
  // ─── Output / dry-run ────────────────────────────────────────────────────────
204
214
 
205
215
  describe("installCopilot — output & dry-run", () => {
206
- it("dry-run reports the plan without writing anything", () => {
207
- const fx = makeFixture();
216
+ it("dry-run reports the plan without writing anything", async () => {
217
+ const fx = await makeFixture();
208
218
  try {
209
- seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
219
+ await seedCopilotPackage(fx, { agents: { alpha: { body: "# alpha" } } });
210
220
 
211
- const result = installCopilot({ root: fx.root, output: fx.output, dryRun: true });
221
+ const result = await installCopilot({ root: fx.root, output: fx.output, dryRun: true });
212
222
 
213
223
  assert.equal(result.dryRun, true);
214
- assert.equal(existsSync(fx.output), false, "no output dir created in dry-run");
224
+ assert.equal(await pathExists(fx.output), false, "no output dir created in dry-run");
215
225
  assert.deepEqual(result.agents, ["alpha"], "planned files still reported");
216
226
  } finally {
217
- fx.cleanup();
227
+ await fx.cleanup();
218
228
  }
219
229
  });
220
230
 
221
- it("is deterministic across repeated installs into the same output", () => {
222
- const fx = makeFixture();
231
+ it("is deterministic across repeated installs into the same output", async () => {
232
+ const fx = await makeFixture();
223
233
  try {
224
- seedCopilotPackage(fx, {
234
+ await seedCopilotPackage(fx, {
225
235
  agents: {
226
236
  alpha: { body: "# alpha\n{{SECTION:polling}}", sections: { polling: "Poll with {{TOOL:task}}." } },
227
237
  beta: { body: "# beta" },
228
238
  },
229
239
  });
230
240
 
231
- installCopilot({ root: fx.root, output: fx.output });
232
- const first = snapshot(fx.output);
233
- installCopilot({ root: fx.root, output: fx.output });
234
- assert.deepEqual(snapshot(fx.output), first);
241
+ await installCopilot({ root: fx.root, output: fx.output });
242
+ const first = await snapshot(fx.output);
243
+ await installCopilot({ root: fx.root, output: fx.output });
244
+ assert.deepEqual(await snapshot(fx.output), first);
235
245
  } finally {
236
- fx.cleanup();
246
+ await fx.cleanup();
237
247
  }
238
248
  });
239
249
  });
@@ -241,19 +251,19 @@ describe("installCopilot — output & dry-run", () => {
241
251
  // ─── Integration against the real repo ───────────────────────────────────────
242
252
 
243
253
  describe("installCopilot — real repo integration", () => {
244
- it("regenerates byte-identical copies of the committed agents/*.agent.md files", () => {
245
- const fx = makeFixture();
254
+ it("regenerates byte-identical copies of the committed agents/*.agent.md files", async () => {
255
+ const fx = await makeFixture();
246
256
  try {
247
- const result = installCopilot({ root: ROOT, output: fx.output });
257
+ const result = await installCopilot({ root: ROOT, output: fx.output });
248
258
 
249
259
  assert.deepEqual(result.agents.sort(), ["plan", "ralph", "ralph-plan", "strategy"]);
250
260
  for (const name of result.agents) {
251
- const generated = readFileSync(join(fx.output, `${name}.agent.md`), "utf-8");
252
- const committed = readFileSync(join(ROOT, "agents", `${name}.agent.md`), "utf-8");
261
+ const generated = await readFile(join(fx.output, `${name}.agent.md`), "utf-8");
262
+ const committed = await readFile(join(ROOT, "agents", `${name}.agent.md`), "utf-8");
253
263
  assert.equal(generated, committed, `${name}.agent.md must match the committed flat file (CI drift check)`);
254
264
  }
255
265
  } finally {
256
- fx.cleanup();
266
+ await fx.cleanup();
257
267
  }
258
268
  });
259
269
  });
@@ -262,37 +272,37 @@ describe("installCopilot — real repo integration", () => {
262
272
 
263
273
  describe("CLI integration", () => {
264
274
  it("exits 0 for install copilot --output <tmp> and writes the flat files", async () => {
265
- const fx = makeFixture();
275
+ const fx = await makeFixture();
266
276
  try {
267
277
  const { exitCode, stdout } = await runCli(["install", "copilot", "--output", fx.output]);
268
278
  assert.equal(exitCode, 0);
269
279
  assert.ok(stdout.includes("copilot"), "prints the harness name");
270
280
  assert.ok(stdout.includes("Generated"), "prints the generation summary");
271
- assert.ok(existsSync(join(fx.output, "ralph.agent.md")), "agent files written");
272
- assert.ok(existsSync(join(fx.output, "plan.agent.md")));
281
+ assert.ok(await pathExists(join(fx.output, "ralph.agent.md")), "agent files written");
282
+ assert.ok(await pathExists(join(fx.output, "plan.agent.md")));
273
283
  } finally {
274
- fx.cleanup();
284
+ await fx.cleanup();
275
285
  }
276
286
  });
277
287
 
278
288
  it("exits 0 for install copilot --dry-run and writes nothing", async () => {
279
- const fx = makeFixture();
289
+ const fx = await makeFixture();
280
290
  try {
281
291
  const { exitCode, stdout } = await runCli(["install", "copilot", "--output", fx.output, "--dry-run"]);
282
292
  assert.equal(exitCode, 0);
283
293
  assert.ok(/dry-run/i.test(stdout));
284
- assert.equal(existsSync(fx.output), false, "no files written in dry-run");
294
+ assert.equal(await pathExists(fx.output), false, "no files written in dry-run");
285
295
  } finally {
286
- fx.cleanup();
296
+ await fx.cleanup();
287
297
  }
288
298
  });
289
299
 
290
300
  it("exits 0 for install copilot (default output) without touching committed files", async () => {
291
- const before = readFileSync(join(ROOT, "agents", "ralph.agent.md"), "utf-8");
301
+ const before = await readFile(join(ROOT, "agents", "ralph.agent.md"), "utf-8");
292
302
  const { exitCode } = await runCli(["install", "copilot"]);
293
303
  assert.equal(exitCode, 0);
294
304
  // Default output regenerates the shared agents/ dir in place — output must
295
305
  // stay byte-identical to what is committed.
296
- assert.equal(readFileSync(join(ROOT, "agents", "ralph.agent.md"), "utf-8"), before);
306
+ assert.equal(await readFile(join(ROOT, "agents", "ralph.agent.md"), "utf-8"), before);
297
307
  });
298
308
  });
@@ -0,0 +1,152 @@
1
+ // Shared test helper: a stateful fake `claude` binary for the `claude plugin`
2
+ // CLI. The real CLI is a genuine external system (and its home config must
3
+ // never be touched by tests), so tests drive this fake instead. It records
4
+ // every invocation to `calls.log` (argv, space-joined, one line each) and
5
+ // simulates just enough real behaviour for idempotency assertions:
6
+ //
7
+ // plugin --help → exit 0 (availability probe)
8
+ // plugin marketplace list --json → registered marketplaces as JSON
9
+ // plugin marketplace add <root> → registers <root> (name read from its
10
+ // .claude-plugin/marketplace.json)
11
+ // plugin marketplace update <m> → exit 0
12
+ // plugin list --json → installed plugins as JSON
13
+ // plugin install <id> -y → records id at the version published by
14
+ // the marketplace source's plugin.json
15
+ // plugin update <name> -y → re-reads the version from the source
16
+ //
17
+ // State lives in `state.json` next to the binary, so a test can re-run the CLI
18
+ // against the same fake and observe the update path. `failWhen` makes any
19
+ // invocation whose argv contains the substring exit 1 (probe/command failures).
20
+ //
21
+ // Written async throughout (the fake is a child process and the helper's own
22
+ // I/O is test code) — the repo's check-no-sync lint scans test/ for *Sync.
23
+
24
+ import { chmod, writeFile } from "node:fs/promises";
25
+ import { join } from "node:path";
26
+
27
+ const FAKE_CLAUDE_SCRIPT = [
28
+ "#!/usr/bin/env node",
29
+ "// Stateful fake for the `claude plugin` CLI (test/helpers/fake-claude.mjs).",
30
+ "const fs = require('node:fs/promises');",
31
+ "const path = require('node:path');",
32
+ "",
33
+ "const dir = __dirname;",
34
+ "const stateFile = path.join(dir, 'state.json');",
35
+ "const logFile = path.join(dir, 'calls.log');",
36
+ "const failWhenFile = path.join(dir, 'failWhen.txt');",
37
+ "",
38
+ "(async () => {",
39
+ " const argv = process.argv.slice(2);",
40
+ " const joined = argv.join(' ');",
41
+ " await fs.appendFile(logFile, joined + '\\n');",
42
+ "",
43
+ " const failWhen = await fs.readFile(failWhenFile, 'utf8').catch(() => null);",
44
+ " if (failWhen && joined.includes(failWhen)) process.exit(1);",
45
+ "",
46
+ " if (argv[0] !== 'plugin') process.exit(0);",
47
+ "",
48
+ " const readState = async () => {",
49
+ " try {",
50
+ " return JSON.parse(await fs.readFile(stateFile, 'utf8'));",
51
+ " } catch {",
52
+ " return { markets: [], installed: [] };",
53
+ " }",
54
+ " };",
55
+ " const writeState = (state) => fs.writeFile(stateFile, JSON.stringify(state));",
56
+ "",
57
+ " // Real claude resolves the plugin version from the marketplace source's",
58
+ " // plugin.json; the fake mirrors that by reading <source>/claude/.claude-plugin/plugin.json.",
59
+ " const pluginJsonVersion = async (marketPath) => {",
60
+ " try {",
61
+ " return JSON.parse(await fs.readFile(path.join(marketPath, 'claude', '.claude-plugin', 'plugin.json'), 'utf8')).version;",
62
+ " } catch {",
63
+ " return undefined;",
64
+ " }",
65
+ " };",
66
+ " const marketplaceName = async (source) => {",
67
+ " try {",
68
+ " return JSON.parse(await fs.readFile(path.join(source, '.claude-plugin', 'marketplace.json'), 'utf8')).name;",
69
+ " } catch {",
70
+ " return undefined;",
71
+ " }",
72
+ " };",
73
+ "",
74
+ " const state = await readState();",
75
+ " const [sub, ...rest] = argv.slice(1);",
76
+ "",
77
+ " if (sub === '--help') process.exit(0);",
78
+ "",
79
+ " if (sub === 'marketplace') {",
80
+ " const [op, ...opArgs] = rest;",
81
+ " if (op === 'list') {",
82
+ " console.log(JSON.stringify(state.markets));",
83
+ " process.exit(0);",
84
+ " }",
85
+ " if (op === 'add') {",
86
+ " const source = path.resolve(opArgs[0]);",
87
+ " const name = (await marketplaceName(source)) ?? 'market-' + state.markets.length;",
88
+ " if (!state.markets.some((m) => m.name === name)) state.markets.push({ name, path: source });",
89
+ " await writeState(state);",
90
+ " process.exit(0);",
91
+ " }",
92
+ " if (op === 'update') process.exit(0);",
93
+ " process.exit(0);",
94
+ " }",
95
+ "",
96
+ " if (sub === 'list') {",
97
+ " console.log(JSON.stringify(state.installed));",
98
+ " process.exit(0);",
99
+ " }",
100
+ "",
101
+ " if (sub === 'install') {",
102
+ " const id = rest[0];",
103
+ " if (!state.installed.some((i) => i.id === id)) {",
104
+ " const [name, market] = id.split('@');",
105
+ " const m = state.markets.find((x) => x.name === market);",
106
+ " state.installed.push({ id, version: m ? (await pluginJsonVersion(m.path)) ?? '0.0.0' : '0.0.0' });",
107
+ " await writeState(state);",
108
+ " }",
109
+ " process.exit(0);",
110
+ " }",
111
+ "",
112
+ " if (sub === 'update') {",
113
+ " const name = rest[0];",
114
+ " const entry = state.installed.find((i) => i.id.startsWith(name + '@'));",
115
+ " if (entry) {",
116
+ " const m = state.markets.find((x) => x.name === entry.id.split('@')[1]);",
117
+ " const v = m ? await pluginJsonVersion(m.path) : undefined;",
118
+ " if (v) entry.version = v;",
119
+ " await writeState(state);",
120
+ " }",
121
+ " process.exit(0);",
122
+ " }",
123
+ "",
124
+ " process.exit(0);",
125
+ "})().catch((err) => {",
126
+ " console.error(err);",
127
+ " process.exit(1);",
128
+ "});",
129
+ ].join("\n");
130
+
131
+ /** Create a stateful fake `claude` binary in `dir`.
132
+ * @param {string} dir Directory to hold bin, calls.log, state.json
133
+ * @param {{ failWhen?: string|null }} [options] Invocations whose argv contains
134
+ * failWhen exit 1
135
+ * @returns {Promise<{ bin: string, log: string, state: string }>} */
136
+ export async function makeFakeClaude(dir, { failWhen = null } = {}) {
137
+ const bin = join(dir, "claude");
138
+ const log = join(dir, "calls.log");
139
+ const state = join(dir, "state.json");
140
+ await writeFile(bin, FAKE_CLAUDE_SCRIPT + "\n");
141
+ await chmod(bin, 0o755);
142
+ await writeFile(state, JSON.stringify({ markets: [], installed: [] }));
143
+ if (failWhen) await writeFile(join(dir, "failWhen.txt"), failWhen);
144
+ return { bin, log, state };
145
+ }
146
+
147
+ /** Registration actions from a fake call log: probes and state queries dropped.
148
+ * @param {string[]} lines Raw call-log lines
149
+ * @returns {string[]} Action lines (marketplace add/update, install, update) */
150
+ export function registrationActions(lines) {
151
+ return lines.filter((c) => !c.startsWith("plugin --help") && !c.includes("--json"));
152
+ }