agents-inc 0.163.0 → 0.164.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 (28) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/{chunk-IAVEMTN4.js → chunk-2CQNPLVF.js} +3 -3
  3. package/dist/{chunk-SMSB6YZW.js → chunk-B6FSLXYN.js} +2 -2
  4. package/dist/{chunk-3CSK5CQN.js → chunk-G2JJ5BO5.js} +4 -4
  5. package/dist/{chunk-O664ITBD.js → chunk-JU4ZGJ7A.js} +14 -16
  6. package/dist/chunk-JU4ZGJ7A.js.map +1 -0
  7. package/dist/{chunk-PM3374E7.js → chunk-X37UYIE3.js} +5 -5
  8. package/dist/commands/build/plugins.js +1 -1
  9. package/dist/commands/compile.js +4 -4
  10. package/dist/commands/doctor.js +4 -4
  11. package/dist/commands/edit.js +4 -4
  12. package/dist/commands/eject.js +4 -4
  13. package/dist/commands/init.js +5 -5
  14. package/dist/commands/search.js +4 -4
  15. package/dist/commands/uninstall.js +4 -4
  16. package/dist/hooks/init.js +5 -5
  17. package/dist/{load-agent-defs-5J2MZLAA.js → load-agent-defs-7IM3GBEQ.js} +3 -3
  18. package/dist/{recompile-project-agents-FCJLHAE3.js → recompile-project-agents-VR4NLGOU.js} +4 -4
  19. package/dist/src/agents/meta/codex-keeper/playbook.md +20 -5
  20. package/package.json +1 -1
  21. package/src/agents/meta/codex-keeper/playbook.md +20 -5
  22. package/dist/chunk-O664ITBD.js.map +0 -1
  23. /package/dist/{chunk-IAVEMTN4.js.map → chunk-2CQNPLVF.js.map} +0 -0
  24. /package/dist/{chunk-SMSB6YZW.js.map → chunk-B6FSLXYN.js.map} +0 -0
  25. /package/dist/{chunk-3CSK5CQN.js.map → chunk-G2JJ5BO5.js.map} +0 -0
  26. /package/dist/{chunk-PM3374E7.js.map → chunk-X37UYIE3.js.map} +0 -0
  27. /package/dist/{load-agent-defs-5J2MZLAA.js.map → load-agent-defs-7IM3GBEQ.js.map} +0 -0
  28. /package/dist/{recompile-project-agents-FCJLHAE3.js.map → recompile-project-agents-VR4NLGOU.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,19 @@ Each release has detailed notes in its own file under [`changelogs/`](./changelo
7
7
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
8
8
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
9
9
 
10
+ ## [0.164.0] - 2026-09-06
11
+
12
+ **Every shipped sub-agent moves to the 2026-09-03 doctrine, the web skills say when to reach for them, and the editor takes the 2026-09-05 design refresh**
13
+
14
+ - All 18 shipped sub-agents now read in the doctrine's voice: 14,236 markdown lines down to 9,026 (−37%), 228 `**(You MUST …)**` down to 1 — the one that names the retired form in order to forbid it — and 26 `CRITICAL:` headings and 15 "Failure to follow…" closers to zero
15
+ - A `web-*` skill's `usageGuidance` names the situation it is for rather than restating its title. A third pass over the marketplace closed two surfaces the first two never reached, found by byte-comparing every file against the baseline rather than trusting an estimate: 38 files and 10,190 lines had never been opened, against an estimate of ~4,000
16
+ - The editor takes the third in-place design refresh — `selected` onto the skills hinge stating its own value, equal full-width domain cells at one type size, the first stack cell as the reset, a full-row assignment pulse, three action cells over Install, fullscreen and a splitter on the output preview, one icon set, receding disabled cells, a warmer column and an amber field on the active nav item (EDITOR-09)
17
+ - EDITOR-75: `pb-30` under a `sticky bottom-0` dock was not clearance — a sticky box is confined to its containing block's content box, so the padding lay entirely below anywhere the dock could rest, parking it 132px above the viewport floor with 132px of grid off-screen
18
+ - EDITOR-76: every bordered text field is now the whole of its own border. All five take the caret from every corner, and the caret lands where the pointer went rather than at the end — the half a `<label>` wrapper satisfies by accident
19
+ - EDITOR-79: the domain strip navigates rather than filters. Clicking `API` no longer hides `web`, `?domain=` is an anchor rather than a filter, and a tab reports `aria-current` instead of a pressed state it could never turn off
20
+
21
+ See [changelogs/0.164.0.md](./changelogs/0.164.0.md) for full details.
22
+
10
23
  ## [0.163.0] - 2026-09-04
11
24
 
12
25
  **Every compiled sub-agent gets a slimmer, cacheable prompt and a deterministic completion gate, and a skill's own trigger sentence finally reaches the agent that loads it**
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  loadAgentDefs
4
- } from "./chunk-SMSB6YZW.js";
4
+ } from "./chunk-B6FSLXYN.js";
5
5
  import {
6
6
  pruneStaleCompiledAgents,
7
7
  recompileAgents
8
- } from "./chunk-O664ITBD.js";
8
+ } from "./chunk-JU4ZGJ7A.js";
9
9
  import {
10
10
  buildAgentScopeMap,
11
11
  buildMarketplacePluginRef,
@@ -273,4 +273,4 @@ export {
273
273
  recompileRegisteredProjectAgents,
274
274
  recompilePropagatedProjectAgents
275
275
  };
276
- //# sourceMappingURL=chunk-IAVEMTN4.js.map
276
+ //# sourceMappingURL=chunk-2CQNPLVF.js.map
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  getAgentDefinitions
4
- } from "./chunk-O664ITBD.js";
4
+ } from "./chunk-JU4ZGJ7A.js";
5
5
  import {
6
6
  loadMergedAgents
7
7
  } from "./chunk-XPDVAJDH.js";
@@ -20,4 +20,4 @@ async function loadAgentDefs() {
20
20
  export {
21
21
  loadAgentDefs
22
22
  };
23
- //# sourceMappingURL=chunk-SMSB6YZW.js.map
23
+ //# sourceMappingURL=chunk-B6FSLXYN.js.map
@@ -26,14 +26,14 @@ import {
26
26
  compileAgentsAllScopes,
27
27
  loadSource,
28
28
  writeProjectConfig
29
- } from "./chunk-PM3374E7.js";
29
+ } from "./chunk-X37UYIE3.js";
30
30
  import {
31
31
  copyLocalSkills,
32
32
  discoverInstalledSkills
33
- } from "./chunk-IAVEMTN4.js";
33
+ } from "./chunk-2CQNPLVF.js";
34
34
  import {
35
35
  loadAgentDefs
36
- } from "./chunk-SMSB6YZW.js";
36
+ } from "./chunk-B6FSLXYN.js";
37
37
  import {
38
38
  render
39
39
  } from "./chunk-JFLVEFFP.js";
@@ -825,4 +825,4 @@ export {
825
825
  Init,
826
826
  getDashboardData
827
827
  };
828
- //# sourceMappingURL=chunk-3CSK5CQN.js.map
828
+ //# sourceMappingURL=chunk-G2JJ5BO5.js.map
@@ -83,21 +83,19 @@ function sanitizeHooks(hooks) {
83
83
  ...definition.matcher !== void 0 && {
84
84
  matcher: sanitizeLiquidSyntax(definition.matcher, "hook.matcher")
85
85
  },
86
- ...definition.hooks !== void 0 && {
87
- hooks: definition.hooks.map((action) => ({
88
- ...action,
89
- type: sanitizeLiquidSyntax(action.type, "hook.type"),
90
- ...action.command !== void 0 && {
91
- command: sanitizeLiquidSyntax(action.command, "hook.command")
92
- },
93
- ...action.script !== void 0 && {
94
- script: sanitizeLiquidSyntax(action.script, "hook.script")
95
- },
96
- ...action.prompt !== void 0 && {
97
- prompt: sanitizeLiquidSyntax(action.prompt, "hook.prompt")
98
- }
99
- }))
100
- }
86
+ hooks: definition.hooks.map((action) => ({
87
+ ...action,
88
+ type: sanitizeLiquidSyntax(action.type, "hook.type"),
89
+ ...action.command !== void 0 && {
90
+ command: sanitizeLiquidSyntax(action.command, "hook.command")
91
+ },
92
+ ...action.script !== void 0 && {
93
+ script: sanitizeLiquidSyntax(action.script, "hook.script")
94
+ },
95
+ ...action.prompt !== void 0 && {
96
+ prompt: sanitizeLiquidSyntax(action.prompt, "hook.prompt")
97
+ }
98
+ }))
101
99
  }))
102
100
  ])
103
101
  );
@@ -667,4 +665,4 @@ export {
667
665
  compileAllAgentPlugins,
668
666
  printAgentCompilationSummary
669
667
  };
670
- //# sourceMappingURL=chunk-O664ITBD.js.map
668
+ //# sourceMappingURL=chunk-JU4ZGJ7A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/lib/agents/list-compiled-agents.ts","../src/cli/lib/agents/agent-provenance.ts","../../compile/src/agent-source.ts","../src/cli/lib/agents/agent-fetcher.ts","../src/cli/lib/agents/agent-recompiler.ts","../src/cli/lib/agents/write-compiled-agents.ts","../src/cli/lib/compiler.ts","../src/cli/lib/agents/agent-plugin-compiler.ts"],"sourcesContent":["import path from \"path\";\nimport { partition } from \"remeda\";\nimport { glob, readFileOptional, remove } from \"../../utils/fs\";\nimport { isAgentName } from \"../../utils/type-guards\";\nimport { hasProvenanceMarker } from \"./agent-provenance\";\nimport type { AgentName } from \"../../types\";\n\n/** Compiled-agent basenames in a directory, split by whether this CLI compiled them. */\nexport type AgentProvenanceSplit = {\n /** Files carrying the provenance marker — provably written by this CLI. */\n marked: string[];\n /** Everything else in the directory, the user's own agents among them. */\n unmarked: string[];\n};\n\n/** Lists compiled-agent markdown filenames (e.g. \"web-developer.md\") in a directory. */\nexport async function listAgentMdFiles(agentsDir: string): Promise<string[]> {\n return glob(\"*.md\", agentsDir);\n}\n\n/**\n * Splits the agent files in a directory by the provenance marker each compiled agent carries.\n *\n * This is the only thing that identifies this CLI's own output once the configuration naming\n * it is gone, so the split errs one way by construction: a file that cannot be read yields no\n * marker and lands in `unmarked`, because \"cannot prove it is ours\" and \"is not ours\" call for\n * the same answer — leave it alone.\n */\nexport async function splitAgentsByProvenance(agentsDir: string): Promise<AgentProvenanceSplit> {\n const files = await listAgentMdFiles(agentsDir);\n const classified = await Promise.all(files.map((file) => readAgentProvenance(agentsDir, file)));\n const [marked, unmarked] = partition(classified, (agent) => agent.compiledHere);\n\n return { marked: marked.map(agentName), unmarked: unmarked.map(agentName) };\n}\n\ntype ClassifiedAgent = { name: string; compiledHere: boolean };\n\nasync function readAgentProvenance(agentsDir: string, file: string): Promise<ClassifiedAgent> {\n const content = await readFileOptional(path.join(agentsDir, file));\n return { name: path.basename(file, \".md\"), compiledHere: hasProvenanceMarker(content) };\n}\n\nfunction agentName(agent: ClassifiedAgent): string {\n return agent.name;\n}\n\n/** Lists compiled-agent names (filenames without the `.md` extension) in a directory. */\nexport async function listCompiledAgentNames(agentsDir: string): Promise<AgentName[]> {\n const files = await listAgentMdFiles(agentsDir);\n // Boundary cast: compiled .md filenames are agent names by convention; custom\n // agents from marketplace stacks may not be members of the AgentName union.\n return files.map((f) => path.basename(f, \".md\") as AgentName);\n}\n\n/**\n * Removes stale CLI-compiled agent files from `agentsDir`: deletes any `.md`\n * whose basename is a built-in CLI agent name (`isAgentName`) that is NOT in\n * `keep`. The built-in-name check protects hand-authored agents (whose basename\n * is not a built-in name) — it is never the removal criterion. Only call this\n * when `keep` is the COMPLETE set of agents that should live in `agentsDir`.\n */\nexport async function pruneStaleCompiledAgents(\n agentsDir: string,\n keep: ReadonlySet<AgentName>,\n): Promise<void> {\n // A non-built-in basename is a hand-authored agent — always preserved.\n const isStaleCompiledAgent = (file: string): boolean => {\n const name = path.basename(file, \".md\");\n return isAgentName(name) && !keep.has(name);\n };\n\n const files = await listAgentMdFiles(agentsDir);\n await Promise.all(\n files.filter(isStaleCompiledAgent).map((file) => remove(path.join(agentsDir, file))),\n );\n}\n","import path from \"path\";\nimport { z } from \"zod\";\n\nimport { PROJECT_ROOT, STANDARD_FILES } from \"../../consts\";\nimport { readFile } from \"../../utils/fs\";\n\n/** The one field the marker needs from this CLI's own manifest. */\nconst ownPackageJsonSchema = z.object({ version: z.string().min(1) });\n\n/**\n * The provenance marker every compiled agent carries lives in `@workspace/compile/agent-source`,\n * beside the renderer that stamps it — the editor's output preview draws the same first body line\n * and must not compute it a second way. What stays here is the half that reads this CLI's own\n * manifest, which a browser has no equivalent of.\n */\nexport {\n hasProvenanceMarker,\n provenanceMarker,\n stampProvenanceMarker,\n} from \"@workspace/compile/agent-source\";\n\nlet ownVersion: Promise<string> | undefined;\n\n/**\n * This CLI's own published version, read once per process from the package manifest beside\n * the code — the same `PROJECT_ROOT` the bundled agent partials and templates resolve from.\n *\n * It reaches a compiled agent as the `version` argument of `renderAgent`, which hands it to the\n * template as `generatorVersion`; `agent.liquid` renders it in the trailing `<system-reminder>`\n * block. Deliberately not the provenance marker above it — that line's bytes are constant across\n * releases, so a version bump no longer rewrites the first cacheable byte of every compiled agent.\n */\nexport function cliVersion(): Promise<string> {\n ownVersion ??= readOwnVersion();\n return ownVersion;\n}\n\nasync function readOwnVersion(): Promise<string> {\n const manifestPath = path.join(PROJECT_ROOT, STANDARD_FILES.PACKAGE_JSON);\n const raw: unknown = JSON.parse(await readFile(manifestPath));\n\n const parsed = ownPackageJsonSchema.safeParse(raw);\n if (!parsed.success) {\n throw new Error(`Could not read this CLI's own version from ${manifestPath}`);\n }\n return parsed.data.version;\n}\n","import type { Liquid } from \"liquidjs\"\n\nimport { diagnostics } from \"./diagnostics.js\"\nimport { DEFAULT_PLUGIN_NAME, EJECT_SOURCE } from \"./paths.js\"\nimport type {\n AgentConfig,\n CompiledAgentData,\n PluginSkillRef,\n Skill,\n} from \"./types.js\"\n\n/**\n * Everything that turns a resolved sub-agent into the markdown an install writes,\n * with two things left behind in the CLI because they read the machine: the five\n * `readFile`s that fetch an agent's partials off disk, and `cliVersion()`, which\n * reads the CLI's own manifest. Both arrive here as data — {@link AgentFiles} and\n * the `version` argument of {@link renderAgent} — which is what lets a browser\n * render the same bytes from the vendored corpus.\n */\n\n/** Pattern matching Liquid template delimiters that could enable template injection */\nconst LIQUID_SYNTAX_PATTERN = /\\{\\{|\\}\\}|\\{%|%\\}/g\n\n/**\n * Strips Liquid template syntax (`{{`, `}}`, `{%`, `%}`) from a string value.\n * Prevents template injection when user-controlled data is passed to the Liquid engine.\n *\n * @param value - Input string that may contain Liquid syntax\n * @param fieldName - Name of the field (for warning messages)\n * @returns Sanitized string with Liquid delimiters removed\n */\nexport function sanitizeLiquidSyntax<T extends string>(\n value: T,\n fieldName: string\n): T {\n if (!LIQUID_SYNTAX_PATTERN.test(value)) return value\n LIQUID_SYNTAX_PATTERN.lastIndex = 0\n const sanitized = value.replace(LIQUID_SYNTAX_PATTERN, \"\")\n diagnostics().warn(\n `Stripped Liquid template syntax from '${fieldName}' — possible template injection attempt`\n )\n // Boundary cast: .replace() widens the branded string T; stripping characters keeps it in T's domain\n return sanitized as T\n}\n\nfunction sanitizeStringArray(values: string[], fieldName: string): string[] {\n return values.map((v) => sanitizeLiquidSyntax(v, fieldName))\n}\n\n/**\n * Hook definitions with every author-supplied string stripped of Liquid syntax.\n *\n * These are the only fields on an agent that render as an EXECUTABLE: a `SubagentStop` hook's\n * `command` is a shell line Claude Code runs when the sub-agent finishes. An agent definition\n * can arrive from a marketplace, so the strings here are as author-controlled as `agent.name`\n * beside them — and they were the one part of the definition the sanitiser did not cover,\n * because until this release nothing rendered them.\n *\n * Sanitising is not a substitute for trusting the source: a marketplace whose agents you compile\n * can name any command it likes, and that is a property of installing an agent rather than of\n * this function. What this closes is the narrower hole of a hook string carrying template syntax\n * into a render.\n *\n * `hooks` is spread unconditionally where `matcher` beside it is guarded, because the two are\n * not both optional: a definition carrying no actions fires nothing, so `AgentHookDefinition`\n * requires the array and every schema that reads an agent refuses a definition without it.\n */\nfunction sanitizeHooks(\n hooks: NonNullable<AgentConfig[\"hooks\"]>\n): NonNullable<AgentConfig[\"hooks\"]> {\n return Object.fromEntries(\n Object.entries(hooks).map(([event, definitions]) => [\n sanitizeLiquidSyntax(event, \"hook.event\"),\n definitions.map((definition) => ({\n ...definition,\n ...(definition.matcher !== undefined && {\n matcher: sanitizeLiquidSyntax(definition.matcher, \"hook.matcher\"),\n }),\n hooks: definition.hooks.map((action) => ({\n ...action,\n type: sanitizeLiquidSyntax(action.type, \"hook.type\"),\n ...(action.command !== undefined && {\n command: sanitizeLiquidSyntax(action.command, \"hook.command\"),\n }),\n ...(action.script !== undefined && {\n script: sanitizeLiquidSyntax(action.script, \"hook.script\"),\n }),\n ...(action.prompt !== undefined && {\n prompt: sanitizeLiquidSyntax(action.prompt, \"hook.prompt\"),\n }),\n })),\n })),\n ])\n )\n}\n\n/**\n * Experimental frontmatter options with their author-supplied value stripped of\n * Liquid syntax.\n *\n * Here for the same reason {@link sanitizeHooks} is: the template renders the\n * field, and being rendered is what puts a field in this enumeration. That\n * `cacheTtl` is a closed vocabulary does not exempt it — `model`, `effort`,\n * `permissionMode` and `isolation` are closed vocabularies too and are all\n * sanitised, because a type says nothing about what reached the renderer.\n * {@link renderAgent} is also the editor's preview path, which arrives from a\n * browser without the CLI's Zod loader having parsed anything.\n */\nfunction sanitizeExperimental(\n experimental: NonNullable<AgentConfig[\"experimental\"]>\n): NonNullable<AgentConfig[\"experimental\"]> {\n return {\n ...experimental,\n ...(experimental.cacheTtl !== undefined && {\n cacheTtl: sanitizeLiquidSyntax(\n experimental.cacheTtl,\n \"agent.experimental.cacheTtl\"\n ),\n }),\n }\n}\n\nfunction sanitizeSkills(skills: Skill[]): Skill[] {\n return skills.map((s) => ({\n ...s,\n id: sanitizeLiquidSyntax(s.id, \"skill.id\"),\n description: sanitizeLiquidSyntax(s.description, \"skill.description\"),\n usage: sanitizeLiquidSyntax(s.usage, \"skill.usage\"),\n ...(s.pluginRef !== undefined && {\n pluginRef: sanitizeLiquidSyntax(s.pluginRef, \"skill.pluginRef\"),\n }),\n }))\n}\n\n/**\n * Sanitizes user-controlled metadata fields in compiled agent data to prevent\n * Liquid template injection. Strips `{{`, `}}`, `{%`, `%}` from agent\n * metadata and skill metadata before template rendering.\n *\n * Content fields (identity, playbook, output, criticalRequirementsTop,\n * criticalReminders) are passed through unchanged — LiquidJS does not\n * re-evaluate template syntax inside variable values, so double-curlies\n * in content (e.g. GitHub Actions `${{ secrets.X }}`) are safe.\n */\nexport function sanitizeCompiledAgentData(\n data: CompiledAgentData\n): CompiledAgentData {\n const sanitizedAgent: AgentConfig = {\n ...data.agent,\n name: sanitizeLiquidSyntax(data.agent.name, \"agent.name\"),\n title: sanitizeLiquidSyntax(data.agent.title, \"agent.title\"),\n description: sanitizeLiquidSyntax(\n data.agent.description,\n \"agent.description\"\n ),\n tools: sanitizeStringArray(data.agent.tools, \"agent.tools\"),\n ...(data.agent.disallowedTools !== undefined && {\n disallowedTools: sanitizeStringArray(\n data.agent.disallowedTools,\n \"agent.disallowedTools\"\n ),\n }),\n ...(data.agent.model !== undefined && {\n model: sanitizeLiquidSyntax(data.agent.model, \"agent.model\"),\n }),\n ...(data.agent.effort !== undefined && {\n effort: sanitizeLiquidSyntax(data.agent.effort, \"agent.effort\"),\n }),\n ...(data.agent.permissionMode !== undefined && {\n permissionMode: sanitizeLiquidSyntax(\n data.agent.permissionMode,\n \"agent.permissionMode\"\n ),\n }),\n ...(data.agent.isolation !== undefined && {\n isolation: sanitizeLiquidSyntax(data.agent.isolation, \"agent.isolation\"),\n }),\n ...(data.agent.experimental !== undefined && {\n experimental: sanitizeExperimental(data.agent.experimental),\n }),\n ...(data.agent.hooks !== undefined && {\n hooks: sanitizeHooks(data.agent.hooks),\n }),\n }\n\n const sanitizedSkills = sanitizeSkills(data.skills)\n const sanitizedPreloaded = sanitizeSkills(data.preloadedSkills)\n const sanitizedDynamic = sanitizeSkills(data.dynamicSkills)\n const sanitizedPreloadedIds = data.preloadedSkillIds.map((id) =>\n sanitizeLiquidSyntax(id, \"preloadedSkillId\")\n )\n\n return {\n agent: sanitizedAgent,\n identity: data.identity,\n playbook: data.playbook,\n output: data.output,\n criticalRequirementsTop: data.criticalRequirementsTop,\n criticalReminders: data.criticalReminders,\n skills: sanitizedSkills,\n preloadedSkills: sanitizedPreloaded,\n dynamicSkills: sanitizedDynamic,\n preloadedSkillIds: sanitizedPreloadedIds,\n }\n}\n\n/**\n * The tool that loads a skill.\n *\n * A sub-agent's `tools:` frontmatter is an ALLOWLIST: an agent that declares one\n * gets exactly what it names, where an agent that omits the key inherits every\n * tool the session has. Every agent compiled here declares one, and no\n * `metadata.yaml` names this — so every agent this product had ever written was\n * unable to invoke a skill, while being instructed in the strongest terms the\n * template can manage to do exactly that.\n *\n * The `skills:` key does not close that gap, which is the non-obvious half and\n * the reason the defect survived: it preloads skill content into the agent's\n * startup context and grants no tool, so a compiled agent can list skills, carry\n * the activation protocol, and still have no way to load one.\n *\n * Granted to every agent rather than only to those with dynamic skills. Skills\n * are this product's atom: an agent has to be able to reach one a user adds\n * after it was compiled, and one its own playbook names in prose. It is a\n * read-only capability — it loads instructions and grants no write access — so\n * the deliberately read-only researchers take it on the same terms.\n */\nconst SKILL_TOOL = \"Skill\"\n\n/**\n * The same definition with {@link SKILL_TOOL} among its tools exactly once.\n *\n * Idempotent and order-stable: a definition already naming it is returned\n * unchanged, by identity, and everything else keeps its declared order with the\n * grant appended. Both halves are about the next compile — a second entry, or a\n * reordered list, would diff the frontmatter of every agent on disk.\n */\nfunction withSkillTool(agent: AgentConfig): AgentConfig {\n if (agent.tools.includes(SKILL_TOOL)) return agent\n return { ...agent, tools: [...agent.tools, SKILL_TOOL] }\n}\n\n/** The five markdown partials a sub-agent is assembled from, however they were fetched. */\nexport type AgentFiles = Pick<\n CompiledAgentData,\n | \"identity\"\n | \"playbook\"\n | \"output\"\n | \"criticalRequirementsTop\"\n | \"criticalReminders\"\n>\n\n/**\n * The template context for one sub-agent.\n *\n * The single assembly point for both front doors — the CLI's write path and the\n * editor's output preview — which is why {@link withSkillTool} is applied here\n * rather than in the eighteen `metadata.yaml` files: a user-authored agent gets\n * the grant on the same terms as a shipped one.\n *\n * The preloaded/dynamic split PRESERVES the order `agent.skills` arrives in, and\n * that order is `config.ts`'s stack key order — so the emitted rows of the\n * sub-agent's skill-activation table are decided by the config writer's\n * canonicalisation rather than by anything here.\n */\nexport function buildAgentTemplateContext(\n name: string,\n agent: AgentConfig,\n files: AgentFiles,\n mapSkill: (skill: Skill) => Skill = (skill) => skill\n): CompiledAgentData {\n const skills = agent.skills.map(mapSkill)\n const preloadedSkills = skills.filter((s) => s.preloaded)\n const dynamicSkills = skills.filter((s) => !s.preloaded)\n const preloadedSkillIds = preloadedSkills.map((s) => s.pluginRef ?? s.id)\n\n diagnostics().verbose(\n `Skills for ${name}: ${preloadedSkills.length} preloaded, ${dynamicSkills.length} dynamic`\n )\n\n return {\n agent: withSkillTool(agent),\n ...files,\n skills,\n preloadedSkills,\n dynamicSkills,\n preloadedSkillIds,\n }\n}\n\n/**\n * The per-skill pluginRef decision. A skill renders as `${id}:${id}` only\n * when it has an explicit non-eject source on its SkillReference — i.e. it was\n * installed from a marketplace. `undefined` source (user-authored local skills\n * with no SkillConfig entry) and `\"eject\"` both fall through to bare id.\n */\nexport function pluginRefFor(skill: Skill): { pluginRef?: PluginSkillRef } {\n if (skill.source === undefined || skill.source === EJECT_SOURCE) return {}\n return { pluginRef: `${skill.id}:${skill.id}` as const }\n}\n\n/**\n * The provenance marker every compiled agent carries: an HTML comment on the first line\n * after the frontmatter, naming the generator and the fact that the file is rewritten\n * rather than edited.\n *\n * **A body comment, deliberately not a frontmatter field.** Claude Code documents its\n * supported frontmatter keys and says nothing about how it treats an unknown one, so a\n * stricter release could reject every agent this CLI has ever written. The body is free-form\n * by contract, which makes a marker there safe, greppable, and the do-not-edit notice at the\n * same time.\n *\n * **Its bytes are constant across releases, and that is the point.** A compiled agent IS a\n * sub-agent's system prompt, so this line is the first cacheable byte of every invocation of\n * it — and while it carried the CLI's version it moved on every release, invalidating the\n * whole prompt prefix of all eighteen agents for a string nothing reads back. The version\n * still travels, in the trailing volatile block where a change to it costs nothing.\n *\n * {@link hasProvenanceMarker} matched on SHAPE while the text varied and still does, so an\n * agent compiled by any release — before this change or after it — is recognised by any other.\n */\nconst MARKER_OPEN = `<!-- Generated by ${DEFAULT_PLUGIN_NAME}`\nconst MARKER_NOTICE = \" — do not edit; compile rewrites this file\"\nconst MARKER_CLOSE = \" -->\"\n\nconst FRONTMATTER_FENCE = \"---\"\n\nexport function provenanceMarker(): string {\n return `${MARKER_OPEN}${MARKER_NOTICE}${MARKER_CLOSE}`\n}\n\n/** Whether a line is a marker this CLI wrote, at any version and under any wording. */\nfunction isProvenanceMarker(line: string): boolean {\n return line.startsWith(MARKER_OPEN) && line.endsWith(MARKER_CLOSE)\n}\n\n/**\n * The index of the first body line: past the closing frontmatter fence when there is one,\n * and the top of the file when there is not — a template override may render no frontmatter,\n * and the marker still needs a defined home.\n */\nfunction bodyStartIndex(lines: readonly string[]): number {\n if (lines[0] !== FRONTMATTER_FENCE) return 0\n const closingFence = lines.indexOf(FRONTMATTER_FENCE, 1)\n if (closingFence === -1) return 0\n return closingFence + 1\n}\n\n/**\n * Whether this CLI compiled the agent file this content came from.\n *\n * The marker's POSITION is part of the claim: an agent that merely quotes the line further\n * down (a prompt about this very feature, say) is the user's, and a sweep reading that as\n * provenance would delete a file nothing here wrote.\n */\nexport function hasProvenanceMarker(content: string): boolean {\n const lines = content.split(\"\\n\")\n const firstBodyLine = lines[bodyStartIndex(lines)]\n return firstBodyLine !== undefined && isProvenanceMarker(firstBodyLine)\n}\n\n/**\n * The same content carrying exactly one provenance marker, on the first line after the\n * frontmatter.\n *\n * Idempotent by replacement rather than by insertion: content that already carries a marker\n * has that line rewritten rather than a second one stacked beside it. Since the marker's text\n * became constant that replacement is a no-op on anything this release wrote — but it is what\n * upgrades an agent stamped by a release that still spelled the version into the line.\n */\nexport function stampProvenanceMarker(content: string): string {\n const lines = content.split(\"\\n\")\n const bodyStart = bodyStartIndex(lines)\n const replacedLines = hasProvenanceMarker(content) ? 1 : 0\n\n return [\n ...lines.slice(0, bodyStart),\n provenanceMarker(),\n ...lines.slice(bodyStart + replacedLines),\n ].join(\"\\n\")\n}\n\n/** The template every compiled sub-agent is rendered from, by name rather than by path. */\nconst AGENT_TEMPLATE = \"agent\"\n\n/**\n * The deterministic completion gate every writing sub-agent stops against.\n *\n * A `SubagentStop` hook rather than a sentence in the prompt, because the two are different\n * kinds of claim: \"check your work before stopping\" is advice a model may decline to take, and\n * this is a process that runs whether it does or not. Exit 2 is the documented way to BLOCK the\n * stop, and the command's captured output goes to stderr, which is what Claude Code returns to\n * the sub-agent — so a failing typecheck comes back as the compiler's own output and the\n * agent iterates rather than reporting done.\n *\n * **Inert where it cannot be right.** A compiled agent is installed into someone else's\n * repository, and a gate that hard-blocks in a project with no npm — or no `typecheck` script —\n * would make every sub-agent unstoppable. So the first clause exits 0 unless there is both an\n * npm and a `package.json`, and `--if-present` exits 0 for a script the project does not\n * define. What is left is exactly the case the gate is for: a project that declares these\n * checks, failing one of them.\n *\n * **Typecheck only.** The gate runs the project's typecheck script; lint and test are\n * deliberately not in it. A type error means the work does not compile, which is the one\n * failure a stopping agent must not report as done. A lint finding or a failing test is the\n * project's own judgement to gate on, and a project that wants either declares its own `Stop`\n * hook — see {@link declaresOwnGate} — which replaces this one entirely rather than running\n * beside it.\n *\n * Composed for agents holding `Write` or `Edit` by {@link withCompletionGate}, which merges it\n * with whatever the agent declared rather than losing to it.\n */\nconst COMPLETION_GATE_COMMAND =\n \"command -v npm >/dev/null 2>&1 && [ -f package.json ] || exit 0; \" +\n \"out=$(npm run --if-present --silent typecheck 2>&1) \" +\n \"|| { printf '%s\\\\n' \\\"$out\\\" >&2; exit 2; }\"\n\n/** The tools whose presence makes an agent one the gate is for. */\nconst WRITING_TOOLS = [\"Write\", \"Edit\"]\n\n/**\n * The frontmatter spelling of the completion event, which is not the spelling that fires.\n *\n * Claude Code registers a sub-agent's frontmatter hooks through a function that walks its\n * event vocabulary and rewrites exactly one key — `Stop` becomes `SubagentStop`, logged as\n * \"Converting Stop hook to SubagentStop for agent X (subagents trigger SubagentStop)\". The\n * vocabulary contains `SubagentStop` verbatim, so EITHER spelling works when the agent is\n * invoked as a sub-agent.\n *\n * They diverge on the other path. An agent run as the main session through `--agent` has its\n * frontmatter hooks stored raw, with no such rewrite, and every dispatch looks the record up\n * by the event's own name — so a `SubagentStop` key is consulted only for an event a main\n * session never fires, while `Stop` fires natively. `Stop` is therefore correct in both modes\n * and `SubagentStop` in one, which is why this emits `Stop`.\n *\n * Read from the shipped binary at version 2.1.259 on 2026-09-03 rather than from published\n * documentation. Compiled agents written before that release carry `SubagentStop`; both are\n * live, and a reader seeing `Stop:` in frontmatter and `SubagentStop` in a log is seeing the\n * conversion rather than a mismatch.\n */\nconst GATE_EVENT = \"Stop\"\n\n/** The runtime spelling of {@link GATE_EVENT} — what a sub-agent's registration is rewritten to. */\nconst CONVERTED_GATE_EVENT = \"SubagentStop\"\n\n/**\n * The gate as its own hooks record — a fresh one per call.\n *\n * A factory rather than a const because the record is spread into an agent's own\n * hooks and the arrays inside it would otherwise be shared, by identity, with every\n * agent ever compiled in the process; `validResult()` in the CLI's\n * `lib/validation-result.ts` is the same shape for the same reason.\n */\nfunction completionGateHooks(): NonNullable<AgentConfig[\"hooks\"]> {\n return {\n [GATE_EVENT]: [\n { hooks: [{ type: \"command\", command: COMPLETION_GATE_COMMAND }] },\n ],\n }\n}\n\n/**\n * Whether the definition states a completion gate of its own, under either spelling.\n *\n * Both count, because the two ARE one event on the path a compiled agent is normally\n * invoked on — see {@link GATE_EVENT}. Keying only on `Stop` would emit this gate beside a\n * project's `SubagentStop`, and a sub-agent would then run both, which is the opposite of\n * the rule that a project's completion gate is its own to state. `SubagentStop` is also the\n * spelling every agent compiled before 2026-09-03 carries, so it is what a project that\n * copied its gate out of a compiled agent will have written.\n */\nfunction declaresOwnGate(hooks: AgentConfig[\"hooks\"]): boolean {\n if (hooks === undefined) return false\n const stated = [GATE_EVENT, CONVERTED_GATE_EVENT]\n return stated.some((event) => (hooks[event]?.length ?? 0) > 0)\n}\n\n/**\n * The same definition carrying the completion gate alongside whatever it declared.\n *\n * **Composition, not exclusion.** The template used to decide this with an\n * `{% if agent.hooks %}` / `{% elsif tools contains Write %}` pair, so an agent\n * declaring any hook at all — a `PostToolUse` formatter, say — silently lost the\n * completion gate, with nothing reporting it.\n *\n * Merged per EVENT: a declared completion gate replaces this one, because a project stating\n * its own is the rule this product has always documented; every other event is added beside\n * it. An agent holding neither `Write` nor `Edit` is returned unchanged, so the gate is still\n * emitted only where it can mean something.\n *\n * The gate is spread LAST rather than first, which matters only for the degenerate declaration\n * `Stop: []`. {@link declaresOwnGate} reads that as stating no gate, correctly — and spreading\n * the declared record over the gate would then let an empty array clobber it, emitting\n * `hooks: {\"Stop\":[]}` and losing the gate to a key that says nothing. Gate-last cannot lose to\n * a declaration this function has already established is not one.\n *\n * **Composed before the sanitiser, for a narrower reason than that ordering used to claim.** The\n * only value whose sanitisation depends on it is {@link COMPLETION_GATE_COMMAND}, a constant this\n * product authors. An author's own hooks are stripped under either order, because\n * {@link sanitizeCompiledAgentData} walks `agent.hooks` whether or not the gate has been composed\n * into them — measured by rendering a writing agent whose declared hook was poisoned in every\n * field, under both orders: one line of the two renders differed, and the marker in it was the\n * gate's own.\n *\n * Which is a rule nothing can hold, since no fixture can reach that constant. So it is structural\n * instead of remembered: this function is private, {@link prepareForRender} is the one expression\n * that composes with the sanitiser, and {@link renderAgent} has no order left to state.\n */\nfunction withCompletionGate(agent: AgentConfig): AgentConfig {\n const writes = WRITING_TOOLS.some((tool) => agent.tools.includes(tool))\n if (!writes || declaresOwnGate(agent.hooks)) return agent\n return { ...agent, hooks: { ...agent.hooks, ...completionGateHooks() } }\n}\n\n/**\n * The whole of what a render is handed: the completion gate composed into the\n * definition's own hooks, and every author-supplied string stripped of Liquid\n * syntax.\n *\n * The two steps have an order and this is the only expression allowed to state\n * it — written as one nested call rather than two statements, so getting it\n * wrong takes rewriting the expression rather than moving a line. That is worth\n * the indirection because the ordering is unfalsifiable: {@link withCompletionGate}\n * is the reason, and it explains which single value the order decides.\n */\nfunction prepareForRender(data: CompiledAgentData): CompiledAgentData {\n return sanitizeCompiledAgentData({\n ...data,\n agent: withCompletionGate(data.agent),\n })\n}\n\n/**\n * Renders the agent template and stamps the result with the provenance marker.\n *\n * Every compile entry point renders through here, so there is no path that writes a compiled\n * agent this CLI cannot later recognise as its own — which is what `uninstall` reads back\n * when the configuration naming the agents is gone. The stamp replaces rather than inserts,\n * so a template that emits the marker itself still produces exactly one.\n *\n * `version` is an argument because the CLI reads it from its own `package.json` and a browser\n * has no manifest to read; the editor passes `CORPUS_CLI_VERSION`, the release the corpus was\n * vendored at. It reaches the template as `generatorVersion` and renders inside the trailing\n * volatile block rather than into the provenance marker, so a release bump no longer rewrites\n * the first cacheable byte of every compiled agent.\n *\n * The completion gate is composed into the agent's own hooks before the render rather than\n * branched on in the template — see {@link prepareForRender} — so the template holds one\n * unconditional `hooks:` emission and the gate reaches `sanitizeHooks` like any other hook.\n */\nexport async function renderAgent(\n engine: Liquid,\n data: CompiledAgentData,\n version: string\n): Promise<string> {\n // Boundary cast: liquidjs types renderFile as `Promise<any>` because a template\n // can render to any value. The agent template renders a markdown file, and both\n // callers have declared `Promise<string>` since they were written.\n const rendered = (await engine.renderFile(AGENT_TEMPLATE, {\n ...prepareForRender(data),\n generatorVersion: sanitizeLiquidSyntax(version, \"generatorVersion\"),\n })) as string\n return stampProvenanceMarker(rendered)\n}\n","import path from \"path\";\nimport { directoryExists } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { PROJECT_ROOT, DIRS } from \"../../consts\";\nimport { fetchFromSource, type FetchOptions } from \"../loading\";\nimport { loadProjectSourceConfig } from \"../configuration\";\nimport type { AgentSourcePaths } from \"../../types\";\n\nexport async function getAgentDefinitions(remoteSource?: string): Promise<AgentSourcePaths> {\n if (remoteSource) {\n return fetchAgentDefinitionsFromRemote(remoteSource);\n }\n return getLocalAgentDefinitions();\n}\n\nexport async function getLocalAgentDefinitions(): Promise<AgentSourcePaths> {\n const agentsDir = path.join(PROJECT_ROOT, DIRS.agents);\n\n if (!(await directoryExists(agentsDir))) {\n throw new Error(\n `Agent partials not found at '${agentsDir}'. Ensure the CLI is properly installed.`,\n );\n }\n\n verbose(`Agent partials loaded from CLI: ${agentsDir}`);\n\n return {\n agentsDir,\n sourcePath: PROJECT_ROOT,\n };\n}\n\nexport async function fetchAgentDefinitionsFromRemote(\n source: string,\n options: FetchOptions & { agentsDir?: string } = {},\n): Promise<AgentSourcePaths> {\n verbose(`Fetching agent partials from remote: ${source}`);\n\n const result = await fetchFromSource(source, { subdir: \"\" });\n\n // ABORT on an unreadable config. It names the directory the fetched repository keeps its agent\n // partials in; defaulting past it compiles agents from whatever happens to sit at `DIRS.agents`,\n // or reports partials missing from a repository that has them.\n const sourceProjectConfig = options.agentsDir\n ? undefined\n : await loadProjectSourceConfig(result.path);\n if (sourceProjectConfig?.agentsDir) {\n verbose(`Using agentsDir from source config: ${sourceProjectConfig.agentsDir}`);\n }\n const agentsDirRelPath = options.agentsDir ?? sourceProjectConfig?.agentsDir ?? DIRS.agents;\n\n const agentsDir = path.join(result.path, agentsDirRelPath);\n\n if (!(await directoryExists(agentsDir))) {\n throw new Error(`Agent partials not found at '${agentsDir}'`);\n }\n\n verbose(`Agent partials fetched from: ${result.path}`);\n\n return {\n agentsDir,\n sourcePath: result.path,\n };\n}\n","import { partition } from \"remeda\";\nimport { writeCompiledAgentsByScope, type AgentWriteOutcome } from \"./write-compiled-agents\";\nimport { listCompiledAgentNames } from \"./list-compiled-agents\";\nimport path from \"path\";\n\nimport { getErrorMessage } from \"../../utils/errors\";\nimport type {\n AgentDefinition,\n AgentName,\n CompileAgentConfig,\n CompileConfig,\n ProjectConfig,\n SkillDefinitionMap,\n SkillScope,\n} from \"../../types\";\n\nimport { buildCompileAgents } from \"../installation/local-installer\";\nimport { ensureDir } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { typedEntries, typedFromEntries, typedKeys } from \"../../utils/typed-object\";\nimport { createLiquidEngine } from \"../compiler\";\nimport { loadProjectConfig, effectivelyExcludedSkillIds } from \"../configuration\";\nimport { loadAllAgents, loadProjectAgents } from \"../loading\";\nimport { getPluginAgentsDir } from \"../plugins\";\nimport { discoverAllPluginSkills } from \"../plugins/plugin-discovery\";\nimport { resolveAgents } from \"../resolver\";\n\nexport type RecompileAgentsOptions = {\n pluginDir: string;\n sourcePath: string;\n agents?: AgentName[];\n skills?: SkillDefinitionMap;\n projectDir?: string;\n outputDir?: string;\n /** When provided, routes agents by scope: global agents to ~/.claude/agents/, project agents to outputDir */\n agentScopeMap?: Map<AgentName, SkillScope>;\n};\n\nexport type RecompileAgentsResult = {\n compiled: AgentName[];\n /**\n * The subset of `compiled` whose file this pass actually wrote. `compiled` is\n * every agent that came through the pass with a correct file at the end of it;\n * `rewritten` is the ones whose content moved, so `compiled minus rewritten` is\n * the count a summary reports as unchanged.\n */\n rewritten: AgentName[];\n failed: AgentName[];\n warnings: string[];\n};\n\nasync function getExistingAgentNames(pluginDir: string): Promise<AgentName[]> {\n return listCompiledAgentNames(getPluginAgentsDir(pluginDir));\n}\n\ntype ResolveAgentNamesParams = {\n specifiedAgents?: AgentName[];\n projectConfig: ProjectConfig | null;\n allAgents: Partial<Record<AgentName, AgentDefinition>>;\n outputDir?: string;\n pluginDir: string;\n};\n\nasync function resolveAgentNames(params: ResolveAgentNamesParams): Promise<AgentName[]> {\n const { specifiedAgents, projectConfig, allAgents, outputDir, pluginDir } = params;\n\n if (specifiedAgents) {\n return specifiedAgents;\n }\n\n // A present config is authoritative over its agent roster — even when empty.\n // `agents: []` means \"no agents\", so it must NOT fall through to the\n // all-agents branch below; that branch exists only for the config-LESS case.\n if (projectConfig) {\n const agentNames = projectConfig.agents.map((a) => a.name);\n verbose(`Using agents from config: ${agentNames.join(\", \")}`);\n return agentNames;\n }\n\n if (outputDir) {\n const names = typedKeys<AgentName>(allAgents);\n verbose(`Using all available agents from source: ${names.join(\", \")}`);\n return names;\n }\n\n return getExistingAgentNames(pluginDir);\n}\n\n/** Splits write outcomes into the recompile result; logs each success at verbose level. */\nfunction buildRecompileResult(\n outcomes: AgentWriteOutcome[],\n priorWarnings: string[],\n): RecompileAgentsResult {\n const [succeeded, failedOutcomes] = partition(\n outcomes,\n (outcome): outcome is Extract<AgentWriteOutcome, { ok: true }> => outcome.ok,\n );\n succeeded.forEach((outcome) =>\n verbose(\n ` ${outcome.rewritten ? \"Rewrote\" : \"Unchanged\"}: ${outcome.name} (${outcome.scope} -> ${outcome.targetDir})`,\n ),\n );\n return {\n compiled: succeeded.map((outcome) => outcome.name),\n rewritten: succeeded.filter((outcome) => outcome.rewritten).map((outcome) => outcome.name),\n failed: failedOutcomes.map((outcome) => outcome.name),\n warnings: [\n ...priorWarnings,\n ...failedOutcomes.map(\n (outcome) => `Failed to compile ${outcome.name}: ${getErrorMessage(outcome.error)}`,\n ),\n ],\n };\n}\n\nexport function filterExcludedEntries(config: ProjectConfig): ProjectConfig {\n const excludedIds = effectivelyExcludedSkillIds(config.skills);\n const activeSkills = config.skills.filter((s) => !s.excluded);\n const activeAgents = config.agents.filter((a) => !a.excluded);\n\n // Also remove excluded skill refs from stack assignments. A config with no stack keeps\n // none — the key stays absent rather than becoming an explicit `undefined`.\n const filteredStack =\n config.stack === undefined\n ? {}\n : {\n stack: Object.fromEntries(\n typedEntries(config.stack).map(([agentName, agentStack]) => [\n agentName,\n Object.fromEntries(\n typedEntries(agentStack).map(([category, assignments]) => [\n category,\n assignments.filter((a) => !excludedIds.has(a.id)),\n ]),\n ),\n ]),\n ),\n };\n\n return { ...config, skills: activeSkills, agents: activeAgents, ...filteredStack };\n}\n\nexport async function recompileAgents(\n options: RecompileAgentsOptions,\n): Promise<RecompileAgentsResult> {\n const { pluginDir, sourcePath, skills: providedSkills, projectDir, outputDir } = options;\n\n const configDir = projectDir ?? pluginDir;\n const loadedConfig = await loadProjectConfig(configDir);\n const projectConfig = loadedConfig?.config ?? null;\n\n // Filter excluded entries once at the entry point — callees receive clean data\n const filteredConfig = projectConfig ? filterExcludedEntries(projectConfig) : null;\n\n const builtinAgents = await loadAllAgents(sourcePath);\n const projectAgents = projectDir ? await loadProjectAgents(projectDir) : {};\n\n // Priority: project agents > built-in agents\n const allAgents: Partial<Record<AgentName, AgentDefinition>> = {\n ...builtinAgents,\n ...projectAgents,\n };\n\n const agentNames = await resolveAgentNames({\n ...(options.agents !== undefined && { specifiedAgents: options.agents }),\n projectConfig: filteredConfig,\n allAgents,\n ...(outputDir !== undefined && { outputDir }),\n pluginDir,\n });\n\n if (agentNames.length === 0) {\n return { compiled: [], rewritten: [], failed: [], warnings: [\"No agents found to recompile\"] };\n }\n\n verbose(`Recompiling ${agentNames.length} agents in ${outputDir ?? pluginDir}`);\n\n // When skills are not provided, discover from all plugin directories.\n const pluginSkills: SkillDefinitionMap =\n providedSkills ?? (await discoverAllPluginSkills(projectDir ?? pluginDir));\n\n const allConfigAgents = filteredConfig ? buildCompileAgents(filteredConfig, allAgents) : {};\n\n // Restrict to only the agents we're compiling (agentNames).\n // buildCompileAgents returns entries for ALL agents in the config, but when\n // scopeFilter is active, we only want the agents matching that scope.\n // Without this filter, a project pass would compile global agents without\n // their stack (since the project config omits global agent stack entries)\n // and overwrite correctly compiled global agent files.\n const [knownAgents, missingAgents] = partition(agentNames, (name) =>\n Boolean(allConfigAgents[name] || allAgents[name]),\n );\n const missingWarnings = missingAgents.map(\n (name) => `Agent \"${name}\" not found in source definitions`,\n );\n const configAgents = typedFromEntries<AgentName, CompileAgentConfig>(\n knownAgents.map((name) => [name, allConfigAgents[name] ?? {}]),\n );\n\n const compileConfig: CompileConfig = {\n name: filteredConfig?.name || path.basename(pluginDir),\n description: filteredConfig?.description || \"Recompiled plugin\",\n agents: configAgents,\n };\n\n const engine = await createLiquidEngine(projectDir);\n const resolvedAgents = await resolveAgents(allAgents, pluginSkills, compileConfig, sourcePath);\n\n const agentsDir = outputDir ?? getPluginAgentsDir(pluginDir);\n await ensureDir(agentsDir);\n\n const outcomes = await writeCompiledAgentsByScope({\n resolvedAgents,\n sourcePath,\n engine,\n projectAgentsDir: agentsDir,\n ...(options.agentScopeMap !== undefined && { agentScopeMap: options.agentScopeMap }),\n });\n return buildRecompileResult(outcomes, missingWarnings);\n}\n","import os from \"os\";\nimport path from \"path\";\nimport type { Liquid } from \"liquidjs\";\nimport { compileAgentForPlugin } from \"../compiler.js\";\nimport { resolveInstallPaths } from \"../installation/install-base-dir.js\";\nimport { writeFile, fileExists, readFile } from \"../../utils/fs.js\";\nimport { typedEntries } from \"../../utils/typed-object.js\";\nimport type { AgentConfig, AgentName, SkillScope } from \"../../types/index.js\";\n\nexport type AgentWriteOutcome =\n | {\n name: AgentName;\n ok: true;\n scope: SkillScope;\n targetDir: string;\n /**\n * Whether this pass actually wrote the file. False means the compiled output\n * matched what was already on disk, so nothing was written — which is what\n * lets a recompile summary tell a real one from a no-op instead of counting\n * the roster it walked.\n */\n rewritten: boolean;\n }\n | { name: AgentName; ok: false; error: unknown };\n\n/**\n * Whether the target already holds exactly this content, making a write a no-op.\n *\n * Skipping that write is what gives \"unchanged\" a meaning a caller can check: an\n * agent reported unchanged keeps its mtime, and an mtime is the only trace a\n * rewrite-with-identical-bytes leaves anywhere.\n */\nasync function holdsExactly(filePath: string, content: string): Promise<boolean> {\n return (await fileExists(filePath)) && (await readFile(filePath)) === content;\n}\n\n/**\n * Where an agent goes when `agentScopeMap` has nothing to say about it — either because the caller\n * passed no map at all (`agents-inc update` recompiles that way) or because this agent is not in\n * the one it passed (a hand-authored agent under `.claude/agents/` has no config row).\n *\n * This is a ROUTING answer, not a selection default: `\"project\"` here means \"the directory the\n * caller named in `projectAgentsDir`\", which for an unrouted write is the only defensible target.\n * It is deliberately NOT `DEFAULT_SELECTION_OPTIONS.scope` from `@workspace/matrix` — that constant\n * says what an untouched *pick* installs as, and adopting it here would relocate the agents of every\n * caller that never asked for global routing into the user's `~/.claude/agents`.\n */\nconst UNROUTED_AGENT_SCOPE: SkillScope = \"project\";\n\n/**\n * Compiles each resolved agent and writes it to its scope's agents directory:\n * global agents to `~/.claude/agents/`, project agents to `projectAgentsDir`.\n * Per-agent failures are collected as outcomes — callers own the policy\n * (recompile reports and continues; install hard-errors).\n *\n * Neither directory is created up front. `writeFile` makes a target's parent on\n * the way past, so a directory appears exactly when an agent routes into it —\n * which is what keeps a wholly project-scoped pass from leaving an empty\n * `~/.claude/agents/` behind in a home that has no global install.\n */\nexport async function writeCompiledAgentsByScope(params: {\n resolvedAgents: Partial<Record<AgentName, AgentConfig>>;\n sourcePath: string;\n engine: Liquid;\n projectAgentsDir: string;\n agentScopeMap?: Map<AgentName, SkillScope>;\n}): Promise<AgentWriteOutcome[]> {\n const globalAgentsDir = resolveInstallPaths(os.homedir(), \"global\").agentsDir;\n\n const outcomes: AgentWriteOutcome[] = [];\n for (const [name, agent] of typedEntries<AgentName, AgentConfig>(params.resolvedAgents)) {\n try {\n const output = await compileAgentForPlugin(name, agent, params.sourcePath, params.engine);\n const scope = params.agentScopeMap?.get(name) ?? UNROUTED_AGENT_SCOPE;\n const targetDir = scope === \"global\" ? globalAgentsDir : params.projectAgentsDir;\n const targetPath = path.join(targetDir, `${name}.md`);\n const rewritten = !(await holdsExactly(targetPath, output));\n if (rewritten) await writeFile(targetPath, output);\n outcomes.push({ name, ok: true, scope, targetDir, rewritten });\n } catch (error) {\n outcomes.push({ name, ok: false, error });\n }\n }\n return outcomes;\n}\n","import { Liquid } from \"liquidjs\";\nimport path from \"path\";\nimport {\n buildAgentTemplateContext,\n pluginRefFor,\n renderAgent,\n type AgentFiles,\n} from \"@workspace/compile/agent-source\";\nimport { readFile, readFileOptional, directoryExists } from \"../utils/fs\";\nimport { verbose } from \"../utils/logger\";\nimport {\n CLAUDE_DIR,\n CLAUDE_SRC_DIR,\n DIRS,\n PROJECT_ROOT,\n STANDARD_FILES,\n STANDARD_DIRS,\n} from \"../consts\";\nimport { cliVersion } from \"./agents/agent-provenance\";\nimport \"./compile-seat.js\";\nimport type { AgentConfig, AgentName } from \"../types\";\n\n/**\n * What survives here is the half of a compile that reads the machine: the five `readFile`s that\n * fetch an agent's partials off disk, and the layered template roots a project can override. The\n * rendering itself — the template context, the injection sanitiser and the provenance stamp — is\n * `@workspace/compile/agent-source`, so the editor's output preview draws the bytes this writes\n * rather than a second implementation of them.\n */\nexport {\n buildAgentTemplateContext,\n sanitizeCompiledAgentData,\n sanitizeLiquidSyntax,\n} from \"@workspace/compile/agent-source\";\n\nasync function readAgentFiles(\n name: AgentName,\n agent: AgentConfig,\n projectRoot: string,\n): Promise<AgentFiles> {\n const agentSourceRoot = agent.sourceRoot || projectRoot;\n const agentBaseDir = agent.agentBaseDir || DIRS.agents;\n const agentDir = path.join(agentSourceRoot, agentBaseDir, agent.path || name);\n\n const identity = await readFile(path.join(agentDir, STANDARD_FILES.IDENTITY_MD));\n const playbook = await readFile(path.join(agentDir, STANDARD_FILES.PLAYBOOK_MD));\n const criticalRequirementsTop = await readFileOptional(\n path.join(agentDir, STANDARD_FILES.CRITICAL_REQUIREMENTS_MD),\n \"\",\n );\n const criticalReminders = await readFileOptional(\n path.join(agentDir, STANDARD_FILES.CRITICAL_REMINDERS_MD),\n \"\",\n );\n\n const agentPath = agent.path || name;\n const parts = agentPath.split(\"/\");\n const category = parts[0] || name;\n const categoryDir = path.join(agentSourceRoot, agentBaseDir, category);\n\n let output = await readFileOptional(path.join(agentDir, STANDARD_FILES.OUTPUT_MD), \"\");\n if (!output) {\n output = await readFileOptional(path.join(categoryDir, STANDARD_FILES.OUTPUT_MD), \"\");\n }\n\n return { identity, playbook, output, criticalRequirementsTop, criticalReminders };\n}\n\n/**\n * Creates a Liquid template engine with a layered template root hierarchy.\n *\n * Template resolution order (first match wins):\n * 1. Project-local templates: `{projectDir}/.claude-src/agents/_templates/`\n * 2. Legacy templates: `{projectDir}/.claude/templates/`\n * 3. Built-in templates: `{PROJECT_ROOT}/src/agents/_templates/`\n *\n * The browser-side twin is `createEngineFromTemplates` in `@workspace/compile/engine`, which\n * builds the same engine over the vendored corpus instead of over directories. Every option\n * below is duplicated there, because a render that resolved filters or variables differently\n * would produce a different file from the same data.\n *\n * @param projectDir - Optional project directory for local template overrides\n * @returns Configured Liquid engine with `.liquid` extension and strict filters\n */\nexport async function createLiquidEngine(projectDir?: string): Promise<Liquid> {\n const roots: string[] = [];\n\n if (projectDir) {\n const srcTemplatesDir = path.join(\n projectDir,\n CLAUDE_SRC_DIR,\n STANDARD_DIRS.AGENTS,\n path.basename(DIRS.templates),\n );\n if (await directoryExists(srcTemplatesDir)) {\n roots.push(srcTemplatesDir);\n verbose(`Using local templates from: ${srcTemplatesDir}`);\n }\n\n const legacyTemplatesDir = path.join(projectDir, CLAUDE_DIR, STANDARD_DIRS.TEMPLATES);\n if (await directoryExists(legacyTemplatesDir)) {\n roots.push(legacyTemplatesDir);\n verbose(`Using legacy templates from: ${legacyTemplatesDir}`);\n }\n }\n\n roots.push(path.join(PROJECT_ROOT, DIRS.templates));\n\n return new Liquid({\n root: roots,\n extname: \".liquid\",\n strictVariables: false,\n strictFilters: true,\n });\n}\n\nexport async function compileAgentForPlugin(\n name: AgentName,\n agent: AgentConfig,\n fallbackRoot: string,\n engine: Liquid,\n): Promise<string> {\n verbose(`Compiling agent: ${name}`);\n\n const files = await readAgentFiles(name, agent, fallbackRoot);\n\n // Per-skill pluginRef attachment. Each skill's own `source` decides\n // whether it renders as `${id}:${id}` (plugin-installed) or bare id (ejected).\n // This correctly handles mixed-mode agents where some skills are plugin and\n // others are ejected. Missing `source` (user-authored local skills with no\n // SkillConfig entry) falls through to bare id — the expected case, not a\n // silent fallback.\n const data = buildAgentTemplateContext(name, agent, files, (skill) => ({\n ...skill,\n ...pluginRefFor(skill),\n }));\n\n return renderAgent(engine, data, await cliVersion());\n}\n","import path from \"path\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { readFile, ensureDir, copy } from \"../../utils/fs\";\nimport { log, verbose, warn } from \"../../utils/logger\";\nimport {\n generateAgentPluginManifest,\n writePluginManifest,\n getPluginManifestPath,\n} from \"../plugins\";\nimport { listAgentMdFiles } from \"./list-compiled-agents\";\nimport { computeStringHash, determinePluginVersion, writeContentHash } from \"../versioning\";\nimport { extractFrontmatter } from \"../../utils/frontmatter\";\nimport type { AgentFrontmatter, PluginManifest } from \"../../types\";\nimport { agentFrontmatterValidationSchema, formatZodIssues } from \"../schemas\";\n\nexport type AgentPluginOptions = {\n agentPath: string;\n outputDir: string;\n};\n\nexport type CompiledAgentPlugin = {\n pluginPath: string;\n manifest: PluginManifest;\n agentName: string;\n};\n\n/**\n * The frontmatter a plugin build needs, or the reason it could not be had.\n *\n * The reason is carried out rather than discarded because the throw in\n * {@link compileAgentPlugin} is the only thing a `build` run surfaces for a failed agent, and it\n * used to name `name` and `description` whatever had actually gone wrong — so an agent rejected\n * for an unknown key or a bad enum value was reported as missing two fields it declared correctly.\n *\n * Nothing is warned here, deliberately. This function is private and has one caller, which throws\n * on every failure, and {@link compileAllAgentPlugins} catches that throw and warns the message —\n * so a warning here would print the same cause twice. The shared `parseFrontmatter` on the skill\n * side keeps its own warn for the opposite reason: most of its callers skip rather than throw.\n */\ntype AgentFrontmatterParse =\n | { ok: true; frontmatter: Pick<AgentFrontmatter, \"name\" | \"description\"> }\n | { ok: false; reason: string };\n\n/** The reason when there is no frontmatter block at all, as opposed to one the schema refused. */\nconst NO_FRONTMATTER_REASON = \"no YAML frontmatter block\";\n\nfunction parseAgentFrontmatter(content: string): AgentFrontmatterParse {\n const raw = extractFrontmatter(content);\n if (!raw) {\n return { ok: false, reason: NO_FRONTMATTER_REASON };\n }\n\n const result = agentFrontmatterValidationSchema.safeParse(raw);\n if (!result.success) {\n return { ok: false, reason: formatZodIssues(result.error.issues) };\n }\n\n return {\n ok: true,\n frontmatter: { name: result.data.name, description: result.data.description },\n };\n}\n\nexport async function compileAgentPlugin(\n options: AgentPluginOptions,\n): Promise<CompiledAgentPlugin> {\n const { agentPath, outputDir } = options;\n const fileName = path.basename(agentPath);\n\n const content = await readFile(agentPath);\n const parsed = parseAgentFrontmatter(content);\n\n if (!parsed.ok) {\n throw new Error(\n `Agent '${fileName}' has invalid or missing YAML frontmatter: ${parsed.reason}. ` +\n `File: ${agentPath}`,\n );\n }\n\n const agentName = parsed.frontmatter.name;\n\n verbose(`Compiling agent plugin: ${agentName} from ${agentPath}`);\n\n const pluginDir = path.join(outputDir, `agent-${agentName}`);\n const agentsDir = path.join(pluginDir, \"agents\");\n\n await ensureDir(pluginDir);\n await ensureDir(agentsDir);\n\n const newHash = computeStringHash(content);\n const { version, contentHash } = await determinePluginVersion(\n newHash,\n pluginDir,\n getPluginManifestPath,\n );\n\n const manifest = generateAgentPluginManifest({\n agentName,\n description: parsed.frontmatter.description,\n version,\n });\n\n await writePluginManifest(pluginDir, manifest);\n\n await writeContentHash(pluginDir, contentHash, getPluginManifestPath);\n\n verbose(` Wrote plugin.json for ${agentName} (v${version})`);\n\n await copy(agentPath, path.join(agentsDir, `${agentName}.md`));\n verbose(` Copied agent ${fileName} -> agents/${agentName}.md`);\n\n return {\n pluginPath: pluginDir,\n manifest,\n agentName,\n };\n}\n\nexport async function compileAllAgentPlugins(\n agentsDir: string,\n outputDir: string,\n): Promise<CompiledAgentPlugin[]> {\n const results: CompiledAgentPlugin[] = [];\n\n const agentMdFiles = await listAgentMdFiles(agentsDir);\n\n for (const agentFile of agentMdFiles) {\n const agentPath = path.join(agentsDir, agentFile);\n\n try {\n const result = await compileAgentPlugin({\n agentPath,\n outputDir,\n });\n results.push(result);\n log(` [OK] agent-${result.agentName}`);\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n warn(`Failed to compile agent from '${agentFile}': ${errorMessage}`);\n }\n }\n\n return results;\n}\n\nexport function printAgentCompilationSummary(results: CompiledAgentPlugin[]): void {\n log(`\\nCompiled ${results.length} agent plugins:`);\n for (const result of results) {\n log(` - agent-${result.agentName} (v${result.manifest.version})`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,SAAS,iBAAiB;;;ACD1B,OAAO,UAAU;AACjB,SAAS,SAAS;;;ACoBlB,IAAM,wBAAwB;AAUvB,SAAS,qBACd,OACA,WACG;AACH,MAAI,CAAC,sBAAsB,KAAK,KAAK,EAAG,QAAO;AAC/C,wBAAsB,YAAY;AAClC,QAAM,YAAY,MAAM,QAAQ,uBAAuB,EAAE;AACzD,cAAY,EAAE;AAAA,IACZ,yCAAyC,SAAS;AAAA,EACpD;AAEA,SAAO;AACT;AAEA,SAAS,oBAAoB,QAAkB,WAA6B;AAC1E,SAAO,OAAO,IAAI,CAAC,MAAM,qBAAqB,GAAG,SAAS,CAAC;AAC7D;AAoBA,SAAS,cACP,OACmC;AACnC,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,OAAO,WAAW,MA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,UAAiC,CAAC;AAExC,QAAM,eAAe,MAAM,iBAAiB,SAAS;AAErD,aAAW,aAAa,cAAc;AACpC,UAAM,YAAYD,MAAK,KAAK,WAAW,SAAS;AAEhD,QAAI;AACF,YAAM,SAAS,MAAM,mBAAmB;AAAA,QACtC;AAAA,QACA;AAAA,MACF,CAAC;AACD,cAAQ,KAAK,MAAM;AACnB,UAAI,gBAAgB,OAAO,SAAS,EAAE;AAAA,IACxC,SAAS,OAAO;AACd,YAAM,eAAe,gBAAgB,KAAK;AAC1C,WAAK,iCAAiC,SAAS,MAAM,YAAY,EAAE;AAAA,IACrE;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,6BAA6B,SAAsC;AACjF,MAAI;AAAA,WAAc,QAAQ,MAAM,iBAAiB;AACjD,aAAW,UAAU,SAAS;AAC5B,QAAI,aAAa,OAAO,SAAS,MAAM,OAAO,SAAS,OAAO,GAAG;AAAA,EACnE;AACF;","names":["path","path","path","path","partition","path","path","path","path","path","partition","agentName","path","path","path","agentName"]}
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  compileAgents,
4
4
  withCatalogueSeatedFor
5
- } from "./chunk-IAVEMTN4.js";
5
+ } from "./chunk-2CQNPLVF.js";
6
6
  import {
7
7
  loadAgentDefs
8
- } from "./chunk-SMSB6YZW.js";
8
+ } from "./chunk-B6FSLXYN.js";
9
9
  import {
10
10
  ConfigLoadError,
11
11
  GlobalPairWriteViolation,
@@ -1094,7 +1094,7 @@ var NOTHING_RECOMPILED = {
1094
1094
  };
1095
1095
  async function recompilePropagated(projectDirs) {
1096
1096
  if (projectDirs.length === 0) return NOTHING_RECOMPILED;
1097
- const { recompilePropagatedProjectAgents: recompilePropagatedProjectAgents2 } = await import("./recompile-project-agents-FCJLHAE3.js");
1097
+ const { recompilePropagatedProjectAgents: recompilePropagatedProjectAgents2 } = await import("./recompile-project-agents-VR4NLGOU.js");
1098
1098
  return recompilePropagatedProjectAgents2(projectDirs);
1099
1099
  }
1100
1100
 
@@ -1132,7 +1132,7 @@ function lazyGateDeps(projectDir) {
1132
1132
  return matrix2;
1133
1133
  },
1134
1134
  loadAgents: async () => {
1135
- const { loadAgentDefs: loadAgentDefs2 } = await import("./load-agent-defs-5J2MZLAA.js");
1135
+ const { loadAgentDefs: loadAgentDefs2 } = await import("./load-agent-defs-7IM3GBEQ.js");
1136
1136
  return (await loadAgentDefs2()).agents;
1137
1137
  }
1138
1138
  };
@@ -1436,4 +1436,4 @@ export {
1436
1436
  writeProjectConfig,
1437
1437
  compileAgentsAllScopes
1438
1438
  };
1439
- //# sourceMappingURL=chunk-PM3374E7.js.map
1439
+ //# sourceMappingURL=chunk-X37UYIE3.js.map
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  compileAllAgentPlugins,
4
4
  printAgentCompilationSummary
5
- } from "../../chunk-O664ITBD.js";
5
+ } from "../../chunk-JU4ZGJ7A.js";
6
6
  import {
7
7
  BaseCommand
8
8
  } from "../../chunk-JIERYE6B.js";
@@ -2,15 +2,15 @@
2
2
  import {
3
3
  detectBothInstallations,
4
4
  reconcileTypesFromDisk
5
- } from "../chunk-PM3374E7.js";
5
+ } from "../chunk-X37UYIE3.js";
6
6
  import {
7
7
  compileAgents,
8
8
  discoverInstalledSkills
9
- } from "../chunk-IAVEMTN4.js";
9
+ } from "../chunk-2CQNPLVF.js";
10
10
  import {
11
11
  loadAgentDefs
12
- } from "../chunk-SMSB6YZW.js";
13
- import "../chunk-O664ITBD.js";
12
+ } from "../chunk-B6FSLXYN.js";
13
+ import "../chunk-JU4ZGJ7A.js";
14
14
  import {
15
15
  BaseCommand,
16
16
  EXIT_CODES
@@ -2,14 +2,14 @@
2
2
  import {
3
3
  detectProject,
4
4
  loadSource
5
- } from "../chunk-PM3374E7.js";
6
- import "../chunk-IAVEMTN4.js";
7
- import "../chunk-SMSB6YZW.js";
5
+ } from "../chunk-X37UYIE3.js";
6
+ import "../chunk-2CQNPLVF.js";
7
+ import "../chunk-B6FSLXYN.js";
8
8
  import {
9
9
  filterExcludedEntries,
10
10
  listAgentMdFiles,
11
11
  splitAgentsByProvenance
12
- } from "../chunk-O664ITBD.js";
12
+ } from "../chunk-JU4ZGJ7A.js";
13
13
  import {
14
14
  BaseCommand,
15
15
  EXIT_CODES
@@ -56,17 +56,17 @@ import {
56
56
  mutateGlobal,
57
57
  normalizeProjectPath,
58
58
  writeProjectConfig
59
- } from "../chunk-PM3374E7.js";
59
+ } from "../chunk-X37UYIE3.js";
60
60
  import {
61
61
  copyLocalSkills,
62
62
  discoverInstalledSkills,
63
63
  removeCompiledAgents,
64
64
  uninstallPluginSkills
65
- } from "../chunk-IAVEMTN4.js";
65
+ } from "../chunk-2CQNPLVF.js";
66
66
  import {
67
67
  loadAgentDefs
68
- } from "../chunk-SMSB6YZW.js";
69
- import "../chunk-O664ITBD.js";
68
+ } from "../chunk-B6FSLXYN.js";
69
+ import "../chunk-JU4ZGJ7A.js";
70
70
  import "../chunk-B3Y3QMWI.js";
71
71
  import {
72
72
  render
@@ -5,10 +5,10 @@ import {
5
5
  loadSource,
6
6
  mutateGlobal,
7
7
  writeProjectPartial
8
- } from "../chunk-PM3374E7.js";
9
- import "../chunk-IAVEMTN4.js";
10
- import "../chunk-SMSB6YZW.js";
11
- import "../chunk-O664ITBD.js";
8
+ } from "../chunk-X37UYIE3.js";
9
+ import "../chunk-2CQNPLVF.js";
10
+ import "../chunk-B6FSLXYN.js";
11
+ import "../chunk-JU4ZGJ7A.js";
12
12
  import {
13
13
  BaseCommand,
14
14
  EXIT_CODES
@@ -7,7 +7,7 @@ import {
7
7
  getDashboardData,
8
8
  runDashboardFlow,
9
9
  showDashboard
10
- } from "../chunk-3CSK5CQN.js";
10
+ } from "../chunk-G2JJ5BO5.js";
11
11
  import "../chunk-7REKOTKG.js";
12
12
  import "../chunk-7ANJQLPJ.js";
13
13
  import "../chunk-RGYDFBCT.js";
@@ -37,10 +37,10 @@ import "../chunk-WTJ3AY33.js";
37
37
  import "../chunk-ABAZMMG4.js";
38
38
  import "../chunk-X4SSJZLY.js";
39
39
  import "../chunk-JCPANDNR.js";
40
- import "../chunk-PM3374E7.js";
41
- import "../chunk-IAVEMTN4.js";
42
- import "../chunk-SMSB6YZW.js";
43
- import "../chunk-O664ITBD.js";
40
+ import "../chunk-X37UYIE3.js";
41
+ import "../chunk-2CQNPLVF.js";
42
+ import "../chunk-B6FSLXYN.js";
43
+ import "../chunk-JU4ZGJ7A.js";
44
44
  import "../chunk-B3Y3QMWI.js";
45
45
  import "../chunk-JFLVEFFP.js";
46
46
  import "../chunk-K5ITEA3I.js";
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  loadSource
4
- } from "../chunk-PM3374E7.js";
5
- import "../chunk-IAVEMTN4.js";
6
- import "../chunk-SMSB6YZW.js";
7
- import "../chunk-O664ITBD.js";
4
+ } from "../chunk-X37UYIE3.js";
5
+ import "../chunk-2CQNPLVF.js";
6
+ import "../chunk-B6FSLXYN.js";
7
+ import "../chunk-JU4ZGJ7A.js";
8
8
  import {
9
9
  BaseCommand
10
10
  } from "../chunk-JIERYE6B.js";
@@ -10,15 +10,15 @@ import {
10
10
  lazyGateDeps,
11
11
  mutateGlobal,
12
12
  propagateGlobalRemoval
13
- } from "../chunk-PM3374E7.js";
14
- import "../chunk-IAVEMTN4.js";
13
+ } from "../chunk-X37UYIE3.js";
14
+ import "../chunk-2CQNPLVF.js";
15
15
  import {
16
16
  loadAgentDefs
17
- } from "../chunk-SMSB6YZW.js";
17
+ } from "../chunk-B6FSLXYN.js";
18
18
  import {
19
19
  listAgentMdFiles,
20
20
  splitAgentsByProvenance
21
- } from "../chunk-O664ITBD.js";
21
+ } from "../chunk-JU4ZGJ7A.js";
22
22
  import "../chunk-JFLVEFFP.js";
23
23
  import {
24
24
  BaseCommand,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runDashboardFlow
4
- } from "../chunk-3CSK5CQN.js";
4
+ } from "../chunk-G2JJ5BO5.js";
5
5
  import "../chunk-7REKOTKG.js";
6
6
  import "../chunk-7ANJQLPJ.js";
7
7
  import "../chunk-RGYDFBCT.js";
@@ -31,10 +31,10 @@ import "../chunk-WTJ3AY33.js";
31
31
  import "../chunk-ABAZMMG4.js";
32
32
  import "../chunk-X4SSJZLY.js";
33
33
  import "../chunk-JCPANDNR.js";
34
- import "../chunk-PM3374E7.js";
35
- import "../chunk-IAVEMTN4.js";
36
- import "../chunk-SMSB6YZW.js";
37
- import "../chunk-O664ITBD.js";
34
+ import "../chunk-X37UYIE3.js";
35
+ import "../chunk-2CQNPLVF.js";
36
+ import "../chunk-B6FSLXYN.js";
37
+ import "../chunk-JU4ZGJ7A.js";
38
38
  import "../chunk-B3Y3QMWI.js";
39
39
  import "../chunk-JFLVEFFP.js";
40
40
  import "../chunk-K5ITEA3I.js";
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  loadAgentDefs
4
- } from "./chunk-SMSB6YZW.js";
5
- import "./chunk-O664ITBD.js";
4
+ } from "./chunk-B6FSLXYN.js";
5
+ import "./chunk-JU4ZGJ7A.js";
6
6
  import "./chunk-XPDVAJDH.js";
7
7
  import "./chunk-AVK2HEKB.js";
8
8
  import "./chunk-UITEKY2R.js";
@@ -10,4 +10,4 @@ import "./chunk-OI2H6M5I.js";
10
10
  export {
11
11
  loadAgentDefs
12
12
  };
13
- //# sourceMappingURL=load-agent-defs-5J2MZLAA.js.map
13
+ //# sourceMappingURL=load-agent-defs-7IM3GBEQ.js.map
@@ -2,9 +2,9 @@
2
2
  import {
3
3
  recompilePropagatedProjectAgents,
4
4
  recompileRegisteredProjectAgents
5
- } from "./chunk-IAVEMTN4.js";
6
- import "./chunk-SMSB6YZW.js";
7
- import "./chunk-O664ITBD.js";
5
+ } from "./chunk-2CQNPLVF.js";
6
+ import "./chunk-B6FSLXYN.js";
7
+ import "./chunk-JU4ZGJ7A.js";
8
8
  import "./chunk-NKGYKOB7.js";
9
9
  import "./chunk-XPDVAJDH.js";
10
10
  import "./chunk-AVK2HEKB.js";
@@ -14,4 +14,4 @@ export {
14
14
  recompilePropagatedProjectAgents,
15
15
  recompileRegisteredProjectAgents
16
16
  };
17
- //# sourceMappingURL=recompile-project-agents-FCJLHAE3.js.map
17
+ //# sourceMappingURL=recompile-project-agents-VR4NLGOU.js.map
@@ -65,8 +65,8 @@ rather than restating it; a second copy of a count can only drift from the first
65
65
  create it as an index of areas, most of them not yet started.
66
66
  2. **Pick the mode and the target area**, from the map's gaps or from the user's request.
67
67
  3. **Investigate**, per the section above.
68
- 4. **Write the document**, in the shape the next section gives. New documents open with
69
- `last_validated:` frontmatter carrying today's date.
68
+ 4. **Write the document**, in the shape the next section gives, frontmatter included, with
69
+ `last_validated:` carrying today's date.
70
70
  5. **Update the map** — one row added for a document created, one row deleted for a document
71
71
  removed, and a corrected "covers" description where a document's scope moved.
72
72
  6. **Check your own output** before reporting: every path and symbol resolves, every pattern names
@@ -84,9 +84,24 @@ rather than restating it; a second copy of a count can only drift from the first
84
84
 
85
85
  ## What a Reference Document Carries
86
86
 
87
- **Every document opens with `last_validated:` frontmatter, a one-line purpose, and the entry point
88
- into the area** — the file an agent reads first. After that the sections follow the area rather than
89
- a template, and these are the shapes that recur:
87
+ **Open the document nearest your area in `.ai-docs/reference/` before writing a new one, and give
88
+ yours the same frontmatter block.** The block is the part of a document's shape that nothing else in
89
+ the document restates, so the tree carries it rather than this prompt. Where the tree holds no
90
+ document yet, these five fields, in this order, are the default:
91
+
92
+ | Field | Carries |
93
+ | ---------------- | -------------------------------------------------------------------------------- |
94
+ | `scope` | `reference`, separating these documents from `standards/` and `agent-findings/` |
95
+ | `area` | the topic group, which the subdirectory under `reference/` usually names |
96
+ | `keywords` | the symbols and terms the document cites, so a search for one of them reaches it |
97
+ | `related` | the sibling documents, by path — resolve each one before you write it |
98
+ | `last_validated` | the date the whole document was last re-derived from source |
99
+
100
+ `related:` is where the cross-referencing above lands: a fact a neighbouring document owns is a path
101
+ in that field rather than a second copy in this one.
102
+
103
+ **Then a one-line purpose and the entry point into the area** — the file an agent reads first. The
104
+ sections after that follow the area rather than a template, and these are the shapes that recur:
90
105
 
91
106
  | Kind | The sections that make it useful |
92
107
  | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-inc",
3
- "version": "0.163.0",
3
+ "version": "0.164.0",
4
4
  "description": "CLI for managing Agents Inc. skills, stacks, and agents for Claude Code",
5
5
  "//generate": "The write path for all three generators, in dependency order: generate:types reads the skills marketplace and writes src/cli/types/generated/, then generate:schemas copies SKILL_SLUGS and CATEGORIES out of it into metadata.schema.json's enums, then generate:matrix vendors the same directory into packages/matrix. A marketplace change drifts all three, so every caller runs all three — .github/workflows/regenerate-catalog.yml spells the sequence out step by step and could call this instead. It replaces the write path only: the :check variants stay separate because CI deliberately runs different subsets of them in different jobs.",
6
6
  "//no-shared-vitest-config": "A three-project suite — unit, integration and commands, each with its own include and the retry that separates them — behind one root config that also carries vitest.setup.ts, disableConsoleIntercept for @oclif/test and ink-testing-library, and its own timeouts. @workspace/vitest-config is a single-project node config that turns globals off, which this suite needs on, so merging it in would contradict as much as it contributed. e2e/vitest.config.ts stands under the same decision. Read by scripts/check-shared-vitest-config.ts in packages/cli.",
@@ -65,8 +65,8 @@ rather than restating it; a second copy of a count can only drift from the first
65
65
  create it as an index of areas, most of them not yet started.
66
66
  2. **Pick the mode and the target area**, from the map's gaps or from the user's request.
67
67
  3. **Investigate**, per the section above.
68
- 4. **Write the document**, in the shape the next section gives. New documents open with
69
- `last_validated:` frontmatter carrying today's date.
68
+ 4. **Write the document**, in the shape the next section gives, frontmatter included, with
69
+ `last_validated:` carrying today's date.
70
70
  5. **Update the map** — one row added for a document created, one row deleted for a document
71
71
  removed, and a corrected "covers" description where a document's scope moved.
72
72
  6. **Check your own output** before reporting: every path and symbol resolves, every pattern names
@@ -84,9 +84,24 @@ rather than restating it; a second copy of a count can only drift from the first
84
84
 
85
85
  ## What a Reference Document Carries
86
86
 
87
- **Every document opens with `last_validated:` frontmatter, a one-line purpose, and the entry point
88
- into the area** — the file an agent reads first. After that the sections follow the area rather than
89
- a template, and these are the shapes that recur:
87
+ **Open the document nearest your area in `.ai-docs/reference/` before writing a new one, and give
88
+ yours the same frontmatter block.** The block is the part of a document's shape that nothing else in
89
+ the document restates, so the tree carries it rather than this prompt. Where the tree holds no
90
+ document yet, these five fields, in this order, are the default:
91
+
92
+ | Field | Carries |
93
+ | ---------------- | -------------------------------------------------------------------------------- |
94
+ | `scope` | `reference`, separating these documents from `standards/` and `agent-findings/` |
95
+ | `area` | the topic group, which the subdirectory under `reference/` usually names |
96
+ | `keywords` | the symbols and terms the document cites, so a search for one of them reaches it |
97
+ | `related` | the sibling documents, by path — resolve each one before you write it |
98
+ | `last_validated` | the date the whole document was last re-derived from source |
99
+
100
+ `related:` is where the cross-referencing above lands: a fact a neighbouring document owns is a path
101
+ in that field rather than a second copy in this one.
102
+
103
+ **Then a one-line purpose and the entry point into the area** — the file an agent reads first. The
104
+ sections after that follow the area rather than a template, and these are the shapes that recur:
90
105
 
91
106
  | Kind | The sections that make it useful |
92
107
  | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/lib/agents/list-compiled-agents.ts","../src/cli/lib/agents/agent-provenance.ts","../../compile/src/agent-source.ts","../src/cli/lib/agents/agent-fetcher.ts","../src/cli/lib/agents/agent-recompiler.ts","../src/cli/lib/agents/write-compiled-agents.ts","../src/cli/lib/compiler.ts","../src/cli/lib/agents/agent-plugin-compiler.ts"],"sourcesContent":["import path from \"path\";\nimport { partition } from \"remeda\";\nimport { glob, readFileOptional, remove } from \"../../utils/fs\";\nimport { isAgentName } from \"../../utils/type-guards\";\nimport { hasProvenanceMarker } from \"./agent-provenance\";\nimport type { AgentName } from \"../../types\";\n\n/** Compiled-agent basenames in a directory, split by whether this CLI compiled them. */\nexport type AgentProvenanceSplit = {\n /** Files carrying the provenance marker — provably written by this CLI. */\n marked: string[];\n /** Everything else in the directory, the user's own agents among them. */\n unmarked: string[];\n};\n\n/** Lists compiled-agent markdown filenames (e.g. \"web-developer.md\") in a directory. */\nexport async function listAgentMdFiles(agentsDir: string): Promise<string[]> {\n return glob(\"*.md\", agentsDir);\n}\n\n/**\n * Splits the agent files in a directory by the provenance marker each compiled agent carries.\n *\n * This is the only thing that identifies this CLI's own output once the configuration naming\n * it is gone, so the split errs one way by construction: a file that cannot be read yields no\n * marker and lands in `unmarked`, because \"cannot prove it is ours\" and \"is not ours\" call for\n * the same answer — leave it alone.\n */\nexport async function splitAgentsByProvenance(agentsDir: string): Promise<AgentProvenanceSplit> {\n const files = await listAgentMdFiles(agentsDir);\n const classified = await Promise.all(files.map((file) => readAgentProvenance(agentsDir, file)));\n const [marked, unmarked] = partition(classified, (agent) => agent.compiledHere);\n\n return { marked: marked.map(agentName), unmarked: unmarked.map(agentName) };\n}\n\ntype ClassifiedAgent = { name: string; compiledHere: boolean };\n\nasync function readAgentProvenance(agentsDir: string, file: string): Promise<ClassifiedAgent> {\n const content = await readFileOptional(path.join(agentsDir, file));\n return { name: path.basename(file, \".md\"), compiledHere: hasProvenanceMarker(content) };\n}\n\nfunction agentName(agent: ClassifiedAgent): string {\n return agent.name;\n}\n\n/** Lists compiled-agent names (filenames without the `.md` extension) in a directory. */\nexport async function listCompiledAgentNames(agentsDir: string): Promise<AgentName[]> {\n const files = await listAgentMdFiles(agentsDir);\n // Boundary cast: compiled .md filenames are agent names by convention; custom\n // agents from marketplace stacks may not be members of the AgentName union.\n return files.map((f) => path.basename(f, \".md\") as AgentName);\n}\n\n/**\n * Removes stale CLI-compiled agent files from `agentsDir`: deletes any `.md`\n * whose basename is a built-in CLI agent name (`isAgentName`) that is NOT in\n * `keep`. The built-in-name check protects hand-authored agents (whose basename\n * is not a built-in name) — it is never the removal criterion. Only call this\n * when `keep` is the COMPLETE set of agents that should live in `agentsDir`.\n */\nexport async function pruneStaleCompiledAgents(\n agentsDir: string,\n keep: ReadonlySet<AgentName>,\n): Promise<void> {\n // A non-built-in basename is a hand-authored agent — always preserved.\n const isStaleCompiledAgent = (file: string): boolean => {\n const name = path.basename(file, \".md\");\n return isAgentName(name) && !keep.has(name);\n };\n\n const files = await listAgentMdFiles(agentsDir);\n await Promise.all(\n files.filter(isStaleCompiledAgent).map((file) => remove(path.join(agentsDir, file))),\n );\n}\n","import path from \"path\";\nimport { z } from \"zod\";\n\nimport { PROJECT_ROOT, STANDARD_FILES } from \"../../consts\";\nimport { readFile } from \"../../utils/fs\";\n\n/** The one field the marker needs from this CLI's own manifest. */\nconst ownPackageJsonSchema = z.object({ version: z.string().min(1) });\n\n/**\n * The provenance marker every compiled agent carries lives in `@workspace/compile/agent-source`,\n * beside the renderer that stamps it — the editor's output preview draws the same first body line\n * and must not compute it a second way. What stays here is the half that reads this CLI's own\n * manifest, which a browser has no equivalent of.\n */\nexport {\n hasProvenanceMarker,\n provenanceMarker,\n stampProvenanceMarker,\n} from \"@workspace/compile/agent-source\";\n\nlet ownVersion: Promise<string> | undefined;\n\n/**\n * This CLI's own published version, read once per process from the package manifest beside\n * the code — the same `PROJECT_ROOT` the bundled agent partials and templates resolve from.\n *\n * It reaches a compiled agent as the `version` argument of `renderAgent`, which hands it to the\n * template as `generatorVersion`; `agent.liquid` renders it in the trailing `<system-reminder>`\n * block. Deliberately not the provenance marker above it — that line's bytes are constant across\n * releases, so a version bump no longer rewrites the first cacheable byte of every compiled agent.\n */\nexport function cliVersion(): Promise<string> {\n ownVersion ??= readOwnVersion();\n return ownVersion;\n}\n\nasync function readOwnVersion(): Promise<string> {\n const manifestPath = path.join(PROJECT_ROOT, STANDARD_FILES.PACKAGE_JSON);\n const raw: unknown = JSON.parse(await readFile(manifestPath));\n\n const parsed = ownPackageJsonSchema.safeParse(raw);\n if (!parsed.success) {\n throw new Error(`Could not read this CLI's own version from ${manifestPath}`);\n }\n return parsed.data.version;\n}\n","import type { Liquid } from \"liquidjs\"\n\nimport { diagnostics } from \"./diagnostics.js\"\nimport { DEFAULT_PLUGIN_NAME, EJECT_SOURCE } from \"./paths.js\"\nimport type {\n AgentConfig,\n CompiledAgentData,\n PluginSkillRef,\n Skill,\n} from \"./types.js\"\n\n/**\n * Everything that turns a resolved sub-agent into the markdown an install writes,\n * with two things left behind in the CLI because they read the machine: the five\n * `readFile`s that fetch an agent's partials off disk, and `cliVersion()`, which\n * reads the CLI's own manifest. Both arrive here as data — {@link AgentFiles} and\n * the `version` argument of {@link renderAgent} — which is what lets a browser\n * render the same bytes from the vendored corpus.\n */\n\n/** Pattern matching Liquid template delimiters that could enable template injection */\nconst LIQUID_SYNTAX_PATTERN = /\\{\\{|\\}\\}|\\{%|%\\}/g\n\n/**\n * Strips Liquid template syntax (`{{`, `}}`, `{%`, `%}`) from a string value.\n * Prevents template injection when user-controlled data is passed to the Liquid engine.\n *\n * @param value - Input string that may contain Liquid syntax\n * @param fieldName - Name of the field (for warning messages)\n * @returns Sanitized string with Liquid delimiters removed\n */\nexport function sanitizeLiquidSyntax<T extends string>(\n value: T,\n fieldName: string\n): T {\n if (!LIQUID_SYNTAX_PATTERN.test(value)) return value\n LIQUID_SYNTAX_PATTERN.lastIndex = 0\n const sanitized = value.replace(LIQUID_SYNTAX_PATTERN, \"\")\n diagnostics().warn(\n `Stripped Liquid template syntax from '${fieldName}' — possible template injection attempt`\n )\n // Boundary cast: .replace() widens the branded string T; stripping characters keeps it in T's domain\n return sanitized as T\n}\n\nfunction sanitizeStringArray(values: string[], fieldName: string): string[] {\n return values.map((v) => sanitizeLiquidSyntax(v, fieldName))\n}\n\n/**\n * Hook definitions with every author-supplied string stripped of Liquid syntax.\n *\n * These are the only fields on an agent that render as an EXECUTABLE: a `SubagentStop` hook's\n * `command` is a shell line Claude Code runs when the sub-agent finishes. An agent definition\n * can arrive from a marketplace, so the strings here are as author-controlled as `agent.name`\n * beside them — and they were the one part of the definition the sanitiser did not cover,\n * because until this release nothing rendered them.\n *\n * Sanitising is not a substitute for trusting the source: a marketplace whose agents you compile\n * can name any command it likes, and that is a property of installing an agent rather than of\n * this function. What this closes is the narrower hole of a hook string carrying template syntax\n * into a render.\n */\nfunction sanitizeHooks(\n hooks: NonNullable<AgentConfig[\"hooks\"]>\n): NonNullable<AgentConfig[\"hooks\"]> {\n return Object.fromEntries(\n Object.entries(hooks).map(([event, definitions]) => [\n sanitizeLiquidSyntax(event, \"hook.event\"),\n definitions.map((definition) => ({\n ...definition,\n ...(definition.matcher !== undefined && {\n matcher: sanitizeLiquidSyntax(definition.matcher, \"hook.matcher\"),\n }),\n ...(definition.hooks !== undefined && {\n hooks: definition.hooks.map((action) => ({\n ...action,\n type: sanitizeLiquidSyntax(action.type, \"hook.type\"),\n ...(action.command !== undefined && {\n command: sanitizeLiquidSyntax(action.command, \"hook.command\"),\n }),\n ...(action.script !== undefined && {\n script: sanitizeLiquidSyntax(action.script, \"hook.script\"),\n }),\n ...(action.prompt !== undefined && {\n prompt: sanitizeLiquidSyntax(action.prompt, \"hook.prompt\"),\n }),\n })),\n }),\n })),\n ])\n )\n}\n\n/**\n * Experimental frontmatter options with their author-supplied value stripped of\n * Liquid syntax.\n *\n * Here for the same reason {@link sanitizeHooks} is: the template renders the\n * field, and being rendered is what puts a field in this enumeration. That\n * `cacheTtl` is a closed vocabulary does not exempt it — `model`, `effort`,\n * `permissionMode` and `isolation` are closed vocabularies too and are all\n * sanitised, because a type says nothing about what reached the renderer.\n * {@link renderAgent} is also the editor's preview path, which arrives from a\n * browser without the CLI's Zod loader having parsed anything.\n */\nfunction sanitizeExperimental(\n experimental: NonNullable<AgentConfig[\"experimental\"]>\n): NonNullable<AgentConfig[\"experimental\"]> {\n return {\n ...experimental,\n ...(experimental.cacheTtl !== undefined && {\n cacheTtl: sanitizeLiquidSyntax(\n experimental.cacheTtl,\n \"agent.experimental.cacheTtl\"\n ),\n }),\n }\n}\n\nfunction sanitizeSkills(skills: Skill[]): Skill[] {\n return skills.map((s) => ({\n ...s,\n id: sanitizeLiquidSyntax(s.id, \"skill.id\"),\n description: sanitizeLiquidSyntax(s.description, \"skill.description\"),\n usage: sanitizeLiquidSyntax(s.usage, \"skill.usage\"),\n ...(s.pluginRef !== undefined && {\n pluginRef: sanitizeLiquidSyntax(s.pluginRef, \"skill.pluginRef\"),\n }),\n }))\n}\n\n/**\n * Sanitizes user-controlled metadata fields in compiled agent data to prevent\n * Liquid template injection. Strips `{{`, `}}`, `{%`, `%}` from agent\n * metadata and skill metadata before template rendering.\n *\n * Content fields (identity, playbook, output, criticalRequirementsTop,\n * criticalReminders) are passed through unchanged — LiquidJS does not\n * re-evaluate template syntax inside variable values, so double-curlies\n * in content (e.g. GitHub Actions `${{ secrets.X }}`) are safe.\n */\nexport function sanitizeCompiledAgentData(\n data: CompiledAgentData\n): CompiledAgentData {\n const sanitizedAgent: AgentConfig = {\n ...data.agent,\n name: sanitizeLiquidSyntax(data.agent.name, \"agent.name\"),\n title: sanitizeLiquidSyntax(data.agent.title, \"agent.title\"),\n description: sanitizeLiquidSyntax(\n data.agent.description,\n \"agent.description\"\n ),\n tools: sanitizeStringArray(data.agent.tools, \"agent.tools\"),\n ...(data.agent.disallowedTools !== undefined && {\n disallowedTools: sanitizeStringArray(\n data.agent.disallowedTools,\n \"agent.disallowedTools\"\n ),\n }),\n ...(data.agent.model !== undefined && {\n model: sanitizeLiquidSyntax(data.agent.model, \"agent.model\"),\n }),\n ...(data.agent.effort !== undefined && {\n effort: sanitizeLiquidSyntax(data.agent.effort, \"agent.effort\"),\n }),\n ...(data.agent.permissionMode !== undefined && {\n permissionMode: sanitizeLiquidSyntax(\n data.agent.permissionMode,\n \"agent.permissionMode\"\n ),\n }),\n ...(data.agent.isolation !== undefined && {\n isolation: sanitizeLiquidSyntax(data.agent.isolation, \"agent.isolation\"),\n }),\n ...(data.agent.experimental !== undefined && {\n experimental: sanitizeExperimental(data.agent.experimental),\n }),\n ...(data.agent.hooks !== undefined && {\n hooks: sanitizeHooks(data.agent.hooks),\n }),\n }\n\n const sanitizedSkills = sanitizeSkills(data.skills)\n const sanitizedPreloaded = sanitizeSkills(data.preloadedSkills)\n const sanitizedDynamic = sanitizeSkills(data.dynamicSkills)\n const sanitizedPreloadedIds = data.preloadedSkillIds.map((id) =>\n sanitizeLiquidSyntax(id, \"preloadedSkillId\")\n )\n\n return {\n agent: sanitizedAgent,\n identity: data.identity,\n playbook: data.playbook,\n output: data.output,\n criticalRequirementsTop: data.criticalRequirementsTop,\n criticalReminders: data.criticalReminders,\n skills: sanitizedSkills,\n preloadedSkills: sanitizedPreloaded,\n dynamicSkills: sanitizedDynamic,\n preloadedSkillIds: sanitizedPreloadedIds,\n }\n}\n\n/**\n * The tool that loads a skill.\n *\n * A sub-agent's `tools:` frontmatter is an ALLOWLIST: an agent that declares one\n * gets exactly what it names, where an agent that omits the key inherits every\n * tool the session has. Every agent compiled here declares one, and no\n * `metadata.yaml` names this — so every agent this product had ever written was\n * unable to invoke a skill, while being instructed in the strongest terms the\n * template can manage to do exactly that.\n *\n * The `skills:` key does not close that gap, which is the non-obvious half and\n * the reason the defect survived: it preloads skill content into the agent's\n * startup context and grants no tool, so a compiled agent can list skills, carry\n * the activation protocol, and still have no way to load one.\n *\n * Granted to every agent rather than only to those with dynamic skills. Skills\n * are this product's atom: an agent has to be able to reach one a user adds\n * after it was compiled, and one its own playbook names in prose. It is a\n * read-only capability — it loads instructions and grants no write access — so\n * the deliberately read-only researchers take it on the same terms.\n */\nconst SKILL_TOOL = \"Skill\"\n\n/**\n * The same definition with {@link SKILL_TOOL} among its tools exactly once.\n *\n * Idempotent and order-stable: a definition already naming it is returned\n * unchanged, by identity, and everything else keeps its declared order with the\n * grant appended. Both halves are about the next compile — a second entry, or a\n * reordered list, would diff the frontmatter of every agent on disk.\n */\nfunction withSkillTool(agent: AgentConfig): AgentConfig {\n if (agent.tools.includes(SKILL_TOOL)) return agent\n return { ...agent, tools: [...agent.tools, SKILL_TOOL] }\n}\n\n/** The five markdown partials a sub-agent is assembled from, however they were fetched. */\nexport type AgentFiles = Pick<\n CompiledAgentData,\n | \"identity\"\n | \"playbook\"\n | \"output\"\n | \"criticalRequirementsTop\"\n | \"criticalReminders\"\n>\n\n/**\n * The template context for one sub-agent.\n *\n * The single assembly point for both front doors — the CLI's write path and the\n * editor's output preview — which is why {@link withSkillTool} is applied here\n * rather than in the eighteen `metadata.yaml` files: a user-authored agent gets\n * the grant on the same terms as a shipped one.\n *\n * The preloaded/dynamic split PRESERVES the order `agent.skills` arrives in, and\n * that order is `config.ts`'s stack key order — so the emitted rows of the\n * sub-agent's skill-activation table are decided by the config writer's\n * canonicalisation rather than by anything here.\n */\nexport function buildAgentTemplateContext(\n name: string,\n agent: AgentConfig,\n files: AgentFiles,\n mapSkill: (skill: Skill) => Skill = (skill) => skill\n): CompiledAgentData {\n const skills = agent.skills.map(mapSkill)\n const preloadedSkills = skills.filter((s) => s.preloaded)\n const dynamicSkills = skills.filter((s) => !s.preloaded)\n const preloadedSkillIds = preloadedSkills.map((s) => s.pluginRef ?? s.id)\n\n diagnostics().verbose(\n `Skills for ${name}: ${preloadedSkills.length} preloaded, ${dynamicSkills.length} dynamic`\n )\n\n return {\n agent: withSkillTool(agent),\n ...files,\n skills,\n preloadedSkills,\n dynamicSkills,\n preloadedSkillIds,\n }\n}\n\n/**\n * The per-skill pluginRef decision. A skill renders as `${id}:${id}` only\n * when it has an explicit non-eject source on its SkillReference — i.e. it was\n * installed from a marketplace. `undefined` source (user-authored local skills\n * with no SkillConfig entry) and `\"eject\"` both fall through to bare id.\n */\nexport function pluginRefFor(skill: Skill): { pluginRef?: PluginSkillRef } {\n if (skill.source === undefined || skill.source === EJECT_SOURCE) return {}\n return { pluginRef: `${skill.id}:${skill.id}` as const }\n}\n\n/**\n * The provenance marker every compiled agent carries: an HTML comment on the first line\n * after the frontmatter, naming the generator and the fact that the file is rewritten\n * rather than edited.\n *\n * **A body comment, deliberately not a frontmatter field.** Claude Code documents its\n * supported frontmatter keys and says nothing about how it treats an unknown one, so a\n * stricter release could reject every agent this CLI has ever written. The body is free-form\n * by contract, which makes a marker there safe, greppable, and the do-not-edit notice at the\n * same time.\n *\n * **Its bytes are constant across releases, and that is the point.** A compiled agent IS a\n * sub-agent's system prompt, so this line is the first cacheable byte of every invocation of\n * it — and while it carried the CLI's version it moved on every release, invalidating the\n * whole prompt prefix of all eighteen agents for a string nothing reads back. The version\n * still travels, in the trailing volatile block where a change to it costs nothing.\n *\n * {@link hasProvenanceMarker} matched on SHAPE while the text varied and still does, so an\n * agent compiled by any release — before this change or after it — is recognised by any other.\n */\nconst MARKER_OPEN = `<!-- Generated by ${DEFAULT_PLUGIN_NAME}`\nconst MARKER_NOTICE = \" — do not edit; compile rewrites this file\"\nconst MARKER_CLOSE = \" -->\"\n\nconst FRONTMATTER_FENCE = \"---\"\n\nexport function provenanceMarker(): string {\n return `${MARKER_OPEN}${MARKER_NOTICE}${MARKER_CLOSE}`\n}\n\n/** Whether a line is a marker this CLI wrote, at any version and under any wording. */\nfunction isProvenanceMarker(line: string): boolean {\n return line.startsWith(MARKER_OPEN) && line.endsWith(MARKER_CLOSE)\n}\n\n/**\n * The index of the first body line: past the closing frontmatter fence when there is one,\n * and the top of the file when there is not — a template override may render no frontmatter,\n * and the marker still needs a defined home.\n */\nfunction bodyStartIndex(lines: readonly string[]): number {\n if (lines[0] !== FRONTMATTER_FENCE) return 0\n const closingFence = lines.indexOf(FRONTMATTER_FENCE, 1)\n if (closingFence === -1) return 0\n return closingFence + 1\n}\n\n/**\n * Whether this CLI compiled the agent file this content came from.\n *\n * The marker's POSITION is part of the claim: an agent that merely quotes the line further\n * down (a prompt about this very feature, say) is the user's, and a sweep reading that as\n * provenance would delete a file nothing here wrote.\n */\nexport function hasProvenanceMarker(content: string): boolean {\n const lines = content.split(\"\\n\")\n const firstBodyLine = lines[bodyStartIndex(lines)]\n return firstBodyLine !== undefined && isProvenanceMarker(firstBodyLine)\n}\n\n/**\n * The same content carrying exactly one provenance marker, on the first line after the\n * frontmatter.\n *\n * Idempotent by replacement rather than by insertion: content that already carries a marker\n * has that line rewritten rather than a second one stacked beside it. Since the marker's text\n * became constant that replacement is a no-op on anything this release wrote — but it is what\n * upgrades an agent stamped by a release that still spelled the version into the line.\n */\nexport function stampProvenanceMarker(content: string): string {\n const lines = content.split(\"\\n\")\n const bodyStart = bodyStartIndex(lines)\n const replacedLines = hasProvenanceMarker(content) ? 1 : 0\n\n return [\n ...lines.slice(0, bodyStart),\n provenanceMarker(),\n ...lines.slice(bodyStart + replacedLines),\n ].join(\"\\n\")\n}\n\n/** The template every compiled sub-agent is rendered from, by name rather than by path. */\nconst AGENT_TEMPLATE = \"agent\"\n\n/**\n * The deterministic completion gate every writing sub-agent stops against.\n *\n * A `SubagentStop` hook rather than a sentence in the prompt, because the two are different\n * kinds of claim: \"check your work before stopping\" is advice a model may decline to take, and\n * this is a process that runs whether it does or not. Exit 2 is the documented way to BLOCK the\n * stop, and the command's captured output goes to stderr, which is what Claude Code returns to\n * the sub-agent — so a failing typecheck comes back as the compiler's own output and the\n * agent iterates rather than reporting done.\n *\n * **Inert where it cannot be right.** A compiled agent is installed into someone else's\n * repository, and a gate that hard-blocks in a project with no npm — or no `typecheck` script —\n * would make every sub-agent unstoppable. So the first clause exits 0 unless there is both an\n * npm and a `package.json`, and `--if-present` exits 0 for a script the project does not\n * define. What is left is exactly the case the gate is for: a project that declares these\n * checks, failing one of them.\n *\n * **Typecheck only.** The gate runs the project's typecheck script; lint and test are\n * deliberately not in it. A type error means the work does not compile, which is the one\n * failure a stopping agent must not report as done. A lint finding or a failing test is the\n * project's own judgement to gate on, and a project that wants either declares its own `Stop`\n * hook — see {@link declaresOwnGate} — which replaces this one entirely rather than running\n * beside it.\n *\n * Composed for agents holding `Write` or `Edit` by {@link withCompletionGate}, which merges it\n * with whatever the agent declared rather than losing to it.\n */\nconst COMPLETION_GATE_COMMAND =\n \"command -v npm >/dev/null 2>&1 && [ -f package.json ] || exit 0; \" +\n \"out=$(npm run --if-present --silent typecheck 2>&1) \" +\n \"|| { printf '%s\\\\n' \\\"$out\\\" >&2; exit 2; }\"\n\n/** The tools whose presence makes an agent one the gate is for. */\nconst WRITING_TOOLS = [\"Write\", \"Edit\"]\n\n/**\n * The frontmatter spelling of the completion event, which is not the spelling that fires.\n *\n * Claude Code registers a sub-agent's frontmatter hooks through a function that walks its\n * event vocabulary and rewrites exactly one key — `Stop` becomes `SubagentStop`, logged as\n * \"Converting Stop hook to SubagentStop for agent X (subagents trigger SubagentStop)\". The\n * vocabulary contains `SubagentStop` verbatim, so EITHER spelling works when the agent is\n * invoked as a sub-agent.\n *\n * They diverge on the other path. An agent run as the main session through `--agent` has its\n * frontmatter hooks stored raw, with no such rewrite, and every dispatch looks the record up\n * by the event's own name — so a `SubagentStop` key is consulted only for an event a main\n * session never fires, while `Stop` fires natively. `Stop` is therefore correct in both modes\n * and `SubagentStop` in one, which is why this emits `Stop`.\n *\n * Read from the shipped binary at version 2.1.259 on 2026-09-03 rather than from published\n * documentation. Compiled agents written before that release carry `SubagentStop`; both are\n * live, and a reader seeing `Stop:` in frontmatter and `SubagentStop` in a log is seeing the\n * conversion rather than a mismatch.\n */\nconst GATE_EVENT = \"Stop\"\n\n/** The runtime spelling of {@link GATE_EVENT} — what a sub-agent's registration is rewritten to. */\nconst CONVERTED_GATE_EVENT = \"SubagentStop\"\n\n/**\n * The gate as its own hooks record — a fresh one per call.\n *\n * A factory rather than a const because the record is spread into an agent's own\n * hooks and the arrays inside it would otherwise be shared, by identity, with every\n * agent ever compiled in the process; `validResult()` in the CLI's\n * `lib/validation-result.ts` is the same shape for the same reason.\n */\nfunction completionGateHooks(): NonNullable<AgentConfig[\"hooks\"]> {\n return {\n [GATE_EVENT]: [\n { hooks: [{ type: \"command\", command: COMPLETION_GATE_COMMAND }] },\n ],\n }\n}\n\n/**\n * Whether the definition states a completion gate of its own, under either spelling.\n *\n * Both count, because the two ARE one event on the path a compiled agent is normally\n * invoked on — see {@link GATE_EVENT}. Keying only on `Stop` would emit this gate beside a\n * project's `SubagentStop`, and a sub-agent would then run both, which is the opposite of\n * the rule that a project's completion gate is its own to state. `SubagentStop` is also the\n * spelling every agent compiled before 2026-09-03 carries, so it is what a project that\n * copied its gate out of a compiled agent will have written.\n */\nfunction declaresOwnGate(hooks: AgentConfig[\"hooks\"]): boolean {\n if (hooks === undefined) return false\n const stated = [GATE_EVENT, CONVERTED_GATE_EVENT]\n return stated.some((event) => (hooks[event]?.length ?? 0) > 0)\n}\n\n/**\n * The same definition carrying the completion gate alongside whatever it declared.\n *\n * **Composition, not exclusion.** The template used to decide this with an\n * `{% if agent.hooks %}` / `{% elsif tools contains Write %}` pair, so an agent\n * declaring any hook at all — a `PostToolUse` formatter, say — silently lost the\n * completion gate, with nothing reporting it.\n *\n * Merged per EVENT: a declared completion gate replaces this one, because a project stating\n * its own is the rule this product has always documented; every other event is added beside\n * it. An agent holding neither `Write` nor `Edit` is returned unchanged, so the gate is still\n * emitted only where it can mean something.\n *\n * The gate is spread LAST rather than first, which matters only for the degenerate declaration\n * `Stop: []`. {@link declaresOwnGate} reads that as stating no gate, correctly — and spreading\n * the declared record over the gate would then let an empty array clobber it, emitting\n * `hooks: {\"Stop\":[]}` and losing the gate to a key that says nothing. Gate-last cannot lose to\n * a declaration this function has already established is not one.\n *\n * **Composed before the sanitiser, for a narrower reason than that ordering used to claim.** The\n * only value whose sanitisation depends on it is {@link COMPLETION_GATE_COMMAND}, a constant this\n * product authors. An author's own hooks are stripped under either order, because\n * {@link sanitizeCompiledAgentData} walks `agent.hooks` whether or not the gate has been composed\n * into them — measured by rendering a writing agent whose declared hook was poisoned in every\n * field, under both orders: one line of the two renders differed, and the marker in it was the\n * gate's own.\n *\n * Which is a rule nothing can hold, since no fixture can reach that constant. So it is structural\n * instead of remembered: this function is private, {@link prepareForRender} is the one expression\n * that composes with the sanitiser, and {@link renderAgent} has no order left to state.\n */\nfunction withCompletionGate(agent: AgentConfig): AgentConfig {\n const writes = WRITING_TOOLS.some((tool) => agent.tools.includes(tool))\n if (!writes || declaresOwnGate(agent.hooks)) return agent\n return { ...agent, hooks: { ...agent.hooks, ...completionGateHooks() } }\n}\n\n/**\n * The whole of what a render is handed: the completion gate composed into the\n * definition's own hooks, and every author-supplied string stripped of Liquid\n * syntax.\n *\n * The two steps have an order and this is the only expression allowed to state\n * it — written as one nested call rather than two statements, so getting it\n * wrong takes rewriting the expression rather than moving a line. That is worth\n * the indirection because the ordering is unfalsifiable: {@link withCompletionGate}\n * is the reason, and it explains which single value the order decides.\n */\nfunction prepareForRender(data: CompiledAgentData): CompiledAgentData {\n return sanitizeCompiledAgentData({\n ...data,\n agent: withCompletionGate(data.agent),\n })\n}\n\n/**\n * Renders the agent template and stamps the result with the provenance marker.\n *\n * Every compile entry point renders through here, so there is no path that writes a compiled\n * agent this CLI cannot later recognise as its own — which is what `uninstall` reads back\n * when the configuration naming the agents is gone. The stamp replaces rather than inserts,\n * so a template that emits the marker itself still produces exactly one.\n *\n * `version` is an argument because the CLI reads it from its own `package.json` and a browser\n * has no manifest to read; the editor passes `CORPUS_CLI_VERSION`, the release the corpus was\n * vendored at. It reaches the template as `generatorVersion` and renders inside the trailing\n * volatile block rather than into the provenance marker, so a release bump no longer rewrites\n * the first cacheable byte of every compiled agent.\n *\n * The completion gate is composed into the agent's own hooks before the render rather than\n * branched on in the template — see {@link prepareForRender} — so the template holds one\n * unconditional `hooks:` emission and the gate reaches `sanitizeHooks` like any other hook.\n */\nexport async function renderAgent(\n engine: Liquid,\n data: CompiledAgentData,\n version: string\n): Promise<string> {\n // Boundary cast: liquidjs types renderFile as `Promise<any>` because a template\n // can render to any value. The agent template renders a markdown file, and both\n // callers have declared `Promise<string>` since they were written.\n const rendered = (await engine.renderFile(AGENT_TEMPLATE, {\n ...prepareForRender(data),\n generatorVersion: sanitizeLiquidSyntax(version, \"generatorVersion\"),\n })) as string\n return stampProvenanceMarker(rendered)\n}\n","import path from \"path\";\nimport { directoryExists } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { PROJECT_ROOT, DIRS } from \"../../consts\";\nimport { fetchFromSource, type FetchOptions } from \"../loading\";\nimport { loadProjectSourceConfig } from \"../configuration\";\nimport type { AgentSourcePaths } from \"../../types\";\n\nexport async function getAgentDefinitions(remoteSource?: string): Promise<AgentSourcePaths> {\n if (remoteSource) {\n return fetchAgentDefinitionsFromRemote(remoteSource);\n }\n return getLocalAgentDefinitions();\n}\n\nexport async function getLocalAgentDefinitions(): Promise<AgentSourcePaths> {\n const agentsDir = path.join(PROJECT_ROOT, DIRS.agents);\n\n if (!(await directoryExists(agentsDir))) {\n throw new Error(\n `Agent partials not found at '${agentsDir}'. Ensure the CLI is properly installed.`,\n );\n }\n\n verbose(`Agent partials loaded from CLI: ${agentsDir}`);\n\n return {\n agentsDir,\n sourcePath: PROJECT_ROOT,\n };\n}\n\nexport async function fetchAgentDefinitionsFromRemote(\n source: string,\n options: FetchOptions & { agentsDir?: string } = {},\n): Promise<AgentSourcePaths> {\n verbose(`Fetching agent partials from remote: ${source}`);\n\n const result = await fetchFromSource(source, { subdir: \"\" });\n\n // ABORT on an unreadable config. It names the directory the fetched repository keeps its agent\n // partials in; defaulting past it compiles agents from whatever happens to sit at `DIRS.agents`,\n // or reports partials missing from a repository that has them.\n const sourceProjectConfig = options.agentsDir\n ? undefined\n : await loadProjectSourceConfig(result.path);\n if (sourceProjectConfig?.agentsDir) {\n verbose(`Using agentsDir from source config: ${sourceProjectConfig.agentsDir}`);\n }\n const agentsDirRelPath = options.agentsDir ?? sourceProjectConfig?.agentsDir ?? DIRS.agents;\n\n const agentsDir = path.join(result.path, agentsDirRelPath);\n\n if (!(await directoryExists(agentsDir))) {\n throw new Error(`Agent partials not found at '${agentsDir}'`);\n }\n\n verbose(`Agent partials fetched from: ${result.path}`);\n\n return {\n agentsDir,\n sourcePath: result.path,\n };\n}\n","import { partition } from \"remeda\";\nimport { writeCompiledAgentsByScope, type AgentWriteOutcome } from \"./write-compiled-agents\";\nimport { listCompiledAgentNames } from \"./list-compiled-agents\";\nimport path from \"path\";\n\nimport { getErrorMessage } from \"../../utils/errors\";\nimport type {\n AgentDefinition,\n AgentName,\n CompileAgentConfig,\n CompileConfig,\n ProjectConfig,\n SkillDefinitionMap,\n SkillScope,\n} from \"../../types\";\n\nimport { buildCompileAgents } from \"../installation/local-installer\";\nimport { ensureDir } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { typedEntries, typedFromEntries, typedKeys } from \"../../utils/typed-object\";\nimport { createLiquidEngine } from \"../compiler\";\nimport { loadProjectConfig, effectivelyExcludedSkillIds } from \"../configuration\";\nimport { loadAllAgents, loadProjectAgents } from \"../loading\";\nimport { getPluginAgentsDir } from \"../plugins\";\nimport { discoverAllPluginSkills } from \"../plugins/plugin-discovery\";\nimport { resolveAgents } from \"../resolver\";\n\nexport type RecompileAgentsOptions = {\n pluginDir: string;\n sourcePath: string;\n agents?: AgentName[];\n skills?: SkillDefinitionMap;\n projectDir?: string;\n outputDir?: string;\n /** When provided, routes agents by scope: global agents to ~/.claude/agents/, project agents to outputDir */\n agentScopeMap?: Map<AgentName, SkillScope>;\n};\n\nexport type RecompileAgentsResult = {\n compiled: AgentName[];\n /**\n * The subset of `compiled` whose file this pass actually wrote. `compiled` is\n * every agent that came through the pass with a correct file at the end of it;\n * `rewritten` is the ones whose content moved, so `compiled minus rewritten` is\n * the count a summary reports as unchanged.\n */\n rewritten: AgentName[];\n failed: AgentName[];\n warnings: string[];\n};\n\nasync function getExistingAgentNames(pluginDir: string): Promise<AgentName[]> {\n return listCompiledAgentNames(getPluginAgentsDir(pluginDir));\n}\n\ntype ResolveAgentNamesParams = {\n specifiedAgents?: AgentName[];\n projectConfig: ProjectConfig | null;\n allAgents: Partial<Record<AgentName, AgentDefinition>>;\n outputDir?: string;\n pluginDir: string;\n};\n\nasync function resolveAgentNames(params: ResolveAgentNamesParams): Promise<AgentName[]> {\n const { specifiedAgents, projectConfig, allAgents, outputDir, pluginDir } = params;\n\n if (specifiedAgents) {\n return specifiedAgents;\n }\n\n // A present config is authoritative over its agent roster — even when empty.\n // `agents: []` means \"no agents\", so it must NOT fall through to the\n // all-agents branch below; that branch exists only for the config-LESS case.\n if (projectConfig) {\n const agentNames = projectConfig.agents.map((a) => a.name);\n verbose(`Using agents from config: ${agentNames.join(\", \")}`);\n return agentNames;\n }\n\n if (outputDir) {\n const names = typedKeys<AgentName>(allAgents);\n verbose(`Using all available agents from source: ${names.join(\", \")}`);\n return names;\n }\n\n return getExistingAgentNames(pluginDir);\n}\n\n/** Splits write outcomes into the recompile result; logs each success at verbose level. */\nfunction buildRecompileResult(\n outcomes: AgentWriteOutcome[],\n priorWarnings: string[],\n): RecompileAgentsResult {\n const [succeeded, failedOutcomes] = partition(\n outcomes,\n (outcome): outcome is Extract<AgentWriteOutcome, { ok: true }> => outcome.ok,\n );\n succeeded.forEach((outcome) =>\n verbose(\n ` ${outcome.rewritten ? \"Rewrote\" : \"Unchanged\"}: ${outcome.name} (${outcome.scope} -> ${outcome.targetDir})`,\n ),\n );\n return {\n compiled: succeeded.map((outcome) => outcome.name),\n rewritten: succeeded.filter((outcome) => outcome.rewritten).map((outcome) => outcome.name),\n failed: failedOutcomes.map((outcome) => outcome.name),\n warnings: [\n ...priorWarnings,\n ...failedOutcomes.map(\n (outcome) => `Failed to compile ${outcome.name}: ${getErrorMessage(outcome.error)}`,\n ),\n ],\n };\n}\n\nexport function filterExcludedEntries(config: ProjectConfig): ProjectConfig {\n const excludedIds = effectivelyExcludedSkillIds(config.skills);\n const activeSkills = config.skills.filter((s) => !s.excluded);\n const activeAgents = config.agents.filter((a) => !a.excluded);\n\n // Also remove excluded skill refs from stack assignments. A config with no stack keeps\n // none — the key stays absent rather than becoming an explicit `undefined`.\n const filteredStack =\n config.stack === undefined\n ? {}\n : {\n stack: Object.fromEntries(\n typedEntries(config.stack).map(([agentName, agentStack]) => [\n agentName,\n Object.fromEntries(\n typedEntries(agentStack).map(([category, assignments]) => [\n category,\n assignments.filter((a) => !excludedIds.has(a.id)),\n ]),\n ),\n ]),\n ),\n };\n\n return { ...config, skills: activeSkills, agents: activeAgents, ...filteredStack };\n}\n\nexport async function recompileAgents(\n options: RecompileAgentsOptions,\n): Promise<RecompileAgentsResult> {\n const { pluginDir, sourcePath, skills: providedSkills, projectDir, outputDir } = options;\n\n const configDir = projectDir ?? pluginDir;\n const loadedConfig = await loadProjectConfig(configDir);\n const projectConfig = loadedConfig?.config ?? null;\n\n // Filter excluded entries once at the entry point — callees receive clean data\n const filteredConfig = projectConfig ? filterExcludedEntries(projectConfig) : null;\n\n const builtinAgents = await loadAllAgents(sourcePath);\n const projectAgents = projectDir ? await loadProjectAgents(projectDir) : {};\n\n // Priority: project agents > built-in agents\n const allAgents: Partial<Record<AgentName, AgentDefinition>> = {\n ...builtinAgents,\n ...projectAgents,\n };\n\n const agentNames = await resolveAgentNames({\n ...(options.agents !== undefined && { specifiedAgents: options.agents }),\n projectConfig: filteredConfig,\n allAgents,\n ...(outputDir !== undefined && { outputDir }),\n pluginDir,\n });\n\n if (agentNames.length === 0) {\n return { compiled: [], rewritten: [], failed: [], warnings: [\"No agents found to recompile\"] };\n }\n\n verbose(`Recompiling ${agentNames.length} agents in ${outputDir ?? pluginDir}`);\n\n // When skills are not provided, discover from all plugin directories.\n const pluginSkills: SkillDefinitionMap =\n providedSkills ?? (await discoverAllPluginSkills(projectDir ?? pluginDir));\n\n const allConfigAgents = filteredConfig ? buildCompileAgents(filteredConfig, allAgents) : {};\n\n // Restrict to only the agents we're compiling (agentNames).\n // buildCompileAgents returns entries for ALL agents in the config, but when\n // scopeFilter is active, we only want the agents matching that scope.\n // Without this filter, a project pass would compile global agents without\n // their stack (since the project config omits global agent stack entries)\n // and overwrite correctly compiled global agent files.\n const [knownAgents, missingAgents] = partition(agentNames, (name) =>\n Boolean(allConfigAgents[name] || allAgents[name]),\n );\n const missingWarnings = missingAgents.map(\n (name) => `Agent \"${name}\" not found in source definitions`,\n );\n const configAgents = typedFromEntries<AgentName, CompileAgentConfig>(\n knownAgents.map((name) => [name, allConfigAgents[name] ?? {}]),\n );\n\n const compileConfig: CompileConfig = {\n name: filteredConfig?.name || path.basename(pluginDir),\n description: filteredConfig?.description || \"Recompiled plugin\",\n agents: configAgents,\n };\n\n const engine = await createLiquidEngine(projectDir);\n const resolvedAgents = await resolveAgents(allAgents, pluginSkills, compileConfig, sourcePath);\n\n const agentsDir = outputDir ?? getPluginAgentsDir(pluginDir);\n await ensureDir(agentsDir);\n\n const outcomes = await writeCompiledAgentsByScope({\n resolvedAgents,\n sourcePath,\n engine,\n projectAgentsDir: agentsDir,\n ...(options.agentScopeMap !== undefined && { agentScopeMap: options.agentScopeMap }),\n });\n return buildRecompileResult(outcomes, missingWarnings);\n}\n","import os from \"os\";\nimport path from \"path\";\nimport type { Liquid } from \"liquidjs\";\nimport { compileAgentForPlugin } from \"../compiler.js\";\nimport { resolveInstallPaths } from \"../installation/install-base-dir.js\";\nimport { writeFile, fileExists, readFile } from \"../../utils/fs.js\";\nimport { typedEntries } from \"../../utils/typed-object.js\";\nimport type { AgentConfig, AgentName, SkillScope } from \"../../types/index.js\";\n\nexport type AgentWriteOutcome =\n | {\n name: AgentName;\n ok: true;\n scope: SkillScope;\n targetDir: string;\n /**\n * Whether this pass actually wrote the file. False means the compiled output\n * matched what was already on disk, so nothing was written — which is what\n * lets a recompile summary tell a real one from a no-op instead of counting\n * the roster it walked.\n */\n rewritten: boolean;\n }\n | { name: AgentName; ok: false; error: unknown };\n\n/**\n * Whether the target already holds exactly this content, making a write a no-op.\n *\n * Skipping that write is what gives \"unchanged\" a meaning a caller can check: an\n * agent reported unchanged keeps its mtime, and an mtime is the only trace a\n * rewrite-with-identical-bytes leaves anywhere.\n */\nasync function holdsExactly(filePath: string, content: string): Promise<boolean> {\n return (await fileExists(filePath)) && (await readFile(filePath)) === content;\n}\n\n/**\n * Where an agent goes when `agentScopeMap` has nothing to say about it — either because the caller\n * passed no map at all (`agents-inc update` recompiles that way) or because this agent is not in\n * the one it passed (a hand-authored agent under `.claude/agents/` has no config row).\n *\n * This is a ROUTING answer, not a selection default: `\"project\"` here means \"the directory the\n * caller named in `projectAgentsDir`\", which for an unrouted write is the only defensible target.\n * It is deliberately NOT `DEFAULT_SELECTION_OPTIONS.scope` from `@workspace/matrix` — that constant\n * says what an untouched *pick* installs as, and adopting it here would relocate the agents of every\n * caller that never asked for global routing into the user's `~/.claude/agents`.\n */\nconst UNROUTED_AGENT_SCOPE: SkillScope = \"project\";\n\n/**\n * Compiles each resolved agent and writes it to its scope's agents directory:\n * global agents to `~/.claude/agents/`, project agents to `projectAgentsDir`.\n * Per-agent failures are collected as outcomes — callers own the policy\n * (recompile reports and continues; install hard-errors).\n *\n * Neither directory is created up front. `writeFile` makes a target's parent on\n * the way past, so a directory appears exactly when an agent routes into it —\n * which is what keeps a wholly project-scoped pass from leaving an empty\n * `~/.claude/agents/` behind in a home that has no global install.\n */\nexport async function writeCompiledAgentsByScope(params: {\n resolvedAgents: Partial<Record<AgentName, AgentConfig>>;\n sourcePath: string;\n engine: Liquid;\n projectAgentsDir: string;\n agentScopeMap?: Map<AgentName, SkillScope>;\n}): Promise<AgentWriteOutcome[]> {\n const globalAgentsDir = resolveInstallPaths(os.homedir(), \"global\").agentsDir;\n\n const outcomes: AgentWriteOutcome[] = [];\n for (const [name, agent] of typedEntries<AgentName, AgentConfig>(params.resolvedAgents)) {\n try {\n const output = await compileAgentForPlugin(name, agent, params.sourcePath, params.engine);\n const scope = params.agentScopeMap?.get(name) ?? UNROUTED_AGENT_SCOPE;\n const targetDir = scope === \"global\" ? globalAgentsDir : params.projectAgentsDir;\n const targetPath = path.join(targetDir, `${name}.md`);\n const rewritten = !(await holdsExactly(targetPath, output));\n if (rewritten) await writeFile(targetPath, output);\n outcomes.push({ name, ok: true, scope, targetDir, rewritten });\n } catch (error) {\n outcomes.push({ name, ok: false, error });\n }\n }\n return outcomes;\n}\n","import { Liquid } from \"liquidjs\";\nimport path from \"path\";\nimport {\n buildAgentTemplateContext,\n pluginRefFor,\n renderAgent,\n type AgentFiles,\n} from \"@workspace/compile/agent-source\";\nimport { readFile, readFileOptional, directoryExists } from \"../utils/fs\";\nimport { verbose } from \"../utils/logger\";\nimport {\n CLAUDE_DIR,\n CLAUDE_SRC_DIR,\n DIRS,\n PROJECT_ROOT,\n STANDARD_FILES,\n STANDARD_DIRS,\n} from \"../consts\";\nimport { cliVersion } from \"./agents/agent-provenance\";\nimport \"./compile-seat.js\";\nimport type { AgentConfig, AgentName } from \"../types\";\n\n/**\n * What survives here is the half of a compile that reads the machine: the five `readFile`s that\n * fetch an agent's partials off disk, and the layered template roots a project can override. The\n * rendering itself — the template context, the injection sanitiser and the provenance stamp — is\n * `@workspace/compile/agent-source`, so the editor's output preview draws the bytes this writes\n * rather than a second implementation of them.\n */\nexport {\n buildAgentTemplateContext,\n sanitizeCompiledAgentData,\n sanitizeLiquidSyntax,\n} from \"@workspace/compile/agent-source\";\n\nasync function readAgentFiles(\n name: AgentName,\n agent: AgentConfig,\n projectRoot: string,\n): Promise<AgentFiles> {\n const agentSourceRoot = agent.sourceRoot || projectRoot;\n const agentBaseDir = agent.agentBaseDir || DIRS.agents;\n const agentDir = path.join(agentSourceRoot, agentBaseDir, agent.path || name);\n\n const identity = await readFile(path.join(agentDir, STANDARD_FILES.IDENTITY_MD));\n const playbook = await readFile(path.join(agentDir, STANDARD_FILES.PLAYBOOK_MD));\n const criticalRequirementsTop = await readFileOptional(\n path.join(agentDir, STANDARD_FILES.CRITICAL_REQUIREMENTS_MD),\n \"\",\n );\n const criticalReminders = await readFileOptional(\n path.join(agentDir, STANDARD_FILES.CRITICAL_REMINDERS_MD),\n \"\",\n );\n\n const agentPath = agent.path || name;\n const parts = agentPath.split(\"/\");\n const category = parts[0] || name;\n const categoryDir = path.join(agentSourceRoot, agentBaseDir, category);\n\n let output = await readFileOptional(path.join(agentDir, STANDARD_FILES.OUTPUT_MD), \"\");\n if (!output) {\n output = await readFileOptional(path.join(categoryDir, STANDARD_FILES.OUTPUT_MD), \"\");\n }\n\n return { identity, playbook, output, criticalRequirementsTop, criticalReminders };\n}\n\n/**\n * Creates a Liquid template engine with a layered template root hierarchy.\n *\n * Template resolution order (first match wins):\n * 1. Project-local templates: `{projectDir}/.claude-src/agents/_templates/`\n * 2. Legacy templates: `{projectDir}/.claude/templates/`\n * 3. Built-in templates: `{PROJECT_ROOT}/src/agents/_templates/`\n *\n * The browser-side twin is `createEngineFromTemplates` in `@workspace/compile/engine`, which\n * builds the same engine over the vendored corpus instead of over directories. Every option\n * below is duplicated there, because a render that resolved filters or variables differently\n * would produce a different file from the same data.\n *\n * @param projectDir - Optional project directory for local template overrides\n * @returns Configured Liquid engine with `.liquid` extension and strict filters\n */\nexport async function createLiquidEngine(projectDir?: string): Promise<Liquid> {\n const roots: string[] = [];\n\n if (projectDir) {\n const srcTemplatesDir = path.join(\n projectDir,\n CLAUDE_SRC_DIR,\n STANDARD_DIRS.AGENTS,\n path.basename(DIRS.templates),\n );\n if (await directoryExists(srcTemplatesDir)) {\n roots.push(srcTemplatesDir);\n verbose(`Using local templates from: ${srcTemplatesDir}`);\n }\n\n const legacyTemplatesDir = path.join(projectDir, CLAUDE_DIR, STANDARD_DIRS.TEMPLATES);\n if (await directoryExists(legacyTemplatesDir)) {\n roots.push(legacyTemplatesDir);\n verbose(`Using legacy templates from: ${legacyTemplatesDir}`);\n }\n }\n\n roots.push(path.join(PROJECT_ROOT, DIRS.templates));\n\n return new Liquid({\n root: roots,\n extname: \".liquid\",\n strictVariables: false,\n strictFilters: true,\n });\n}\n\nexport async function compileAgentForPlugin(\n name: AgentName,\n agent: AgentConfig,\n fallbackRoot: string,\n engine: Liquid,\n): Promise<string> {\n verbose(`Compiling agent: ${name}`);\n\n const files = await readAgentFiles(name, agent, fallbackRoot);\n\n // Per-skill pluginRef attachment. Each skill's own `source` decides\n // whether it renders as `${id}:${id}` (plugin-installed) or bare id (ejected).\n // This correctly handles mixed-mode agents where some skills are plugin and\n // others are ejected. Missing `source` (user-authored local skills with no\n // SkillConfig entry) falls through to bare id — the expected case, not a\n // silent fallback.\n const data = buildAgentTemplateContext(name, agent, files, (skill) => ({\n ...skill,\n ...pluginRefFor(skill),\n }));\n\n return renderAgent(engine, data, await cliVersion());\n}\n","import path from \"path\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { readFile, ensureDir, copy } from \"../../utils/fs\";\nimport { log, verbose, warn } from \"../../utils/logger\";\nimport {\n generateAgentPluginManifest,\n writePluginManifest,\n getPluginManifestPath,\n} from \"../plugins\";\nimport { listAgentMdFiles } from \"./list-compiled-agents\";\nimport { computeStringHash, determinePluginVersion, writeContentHash } from \"../versioning\";\nimport { extractFrontmatter } from \"../../utils/frontmatter\";\nimport type { AgentFrontmatter, PluginManifest } from \"../../types\";\nimport { agentFrontmatterValidationSchema, formatZodIssues } from \"../schemas\";\n\nexport type AgentPluginOptions = {\n agentPath: string;\n outputDir: string;\n};\n\nexport type CompiledAgentPlugin = {\n pluginPath: string;\n manifest: PluginManifest;\n agentName: string;\n};\n\n/**\n * The frontmatter a plugin build needs, or the reason it could not be had.\n *\n * The reason is carried out rather than discarded because the throw in\n * {@link compileAgentPlugin} is the only thing a `build` run surfaces for a failed agent, and it\n * used to name `name` and `description` whatever had actually gone wrong — so an agent rejected\n * for an unknown key or a bad enum value was reported as missing two fields it declared correctly.\n *\n * Nothing is warned here, deliberately. This function is private and has one caller, which throws\n * on every failure, and {@link compileAllAgentPlugins} catches that throw and warns the message —\n * so a warning here would print the same cause twice. The shared `parseFrontmatter` on the skill\n * side keeps its own warn for the opposite reason: most of its callers skip rather than throw.\n */\ntype AgentFrontmatterParse =\n | { ok: true; frontmatter: Pick<AgentFrontmatter, \"name\" | \"description\"> }\n | { ok: false; reason: string };\n\n/** The reason when there is no frontmatter block at all, as opposed to one the schema refused. */\nconst NO_FRONTMATTER_REASON = \"no YAML frontmatter block\";\n\nfunction parseAgentFrontmatter(content: string): AgentFrontmatterParse {\n const raw = extractFrontmatter(content);\n if (!raw) {\n return { ok: false, reason: NO_FRONTMATTER_REASON };\n }\n\n const result = agentFrontmatterValidationSchema.safeParse(raw);\n if (!result.success) {\n return { ok: false, reason: formatZodIssues(result.error.issues) };\n }\n\n return {\n ok: true,\n frontmatter: { name: result.data.name, description: result.data.description },\n };\n}\n\nexport async function compileAgentPlugin(\n options: AgentPluginOptions,\n): Promise<CompiledAgentPlugin> {\n const { agentPath, outputDir } = options;\n const fileName = path.basename(agentPath);\n\n const content = await readFile(agentPath);\n const parsed = parseAgentFrontmatter(content);\n\n if (!parsed.ok) {\n throw new Error(\n `Agent '${fileName}' has invalid or missing YAML frontmatter: ${parsed.reason}. ` +\n `File: ${agentPath}`,\n );\n }\n\n const agentName = parsed.frontmatter.name;\n\n verbose(`Compiling agent plugin: ${agentName} from ${agentPath}`);\n\n const pluginDir = path.join(outputDir, `agent-${agentName}`);\n const agentsDir = path.join(pluginDir, \"agents\");\n\n await ensureDir(pluginDir);\n await ensureDir(agentsDir);\n\n const newHash = computeStringHash(content);\n const { version, contentHash } = await determinePluginVersion(\n newHash,\n pluginDir,\n getPluginManifestPath,\n );\n\n const manifest = generateAgentPluginManifest({\n agentName,\n description: parsed.frontmatter.description,\n version,\n });\n\n await writePluginManifest(pluginDir, manifest);\n\n await writeContentHash(pluginDir, contentHash, getPluginManifestPath);\n\n verbose(` Wrote plugin.json for ${agentName} (v${version})`);\n\n await copy(agentPath, path.join(agentsDir, `${agentName}.md`));\n verbose(` Copied agent ${fileName} -> agents/${agentName}.md`);\n\n return {\n pluginPath: pluginDir,\n manifest,\n agentName,\n };\n}\n\nexport async function compileAllAgentPlugins(\n agentsDir: string,\n outputDir: string,\n): Promise<CompiledAgentPlugin[]> {\n const results: CompiledAgentPlugin[] = [];\n\n const agentMdFiles = await listAgentMdFiles(agentsDir);\n\n for (const agentFile of agentMdFiles) {\n const agentPath = path.join(agentsDir, agentFile);\n\n try {\n const result = await compileAgentPlugin({\n agentPath,\n outputDir,\n });\n results.push(result);\n log(` [OK] agent-${result.agentName}`);\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n warn(`Failed to compile agent from '${agentFile}': ${errorMessage}`);\n }\n }\n\n return results;\n}\n\nexport function printAgentCompilationSummary(results: CompiledAgentPlugin[]): void {\n log(`\\nCompiled ${results.length} agent plugins:`);\n for (const result of results) {\n log(` - agent-${result.agentName} (v${result.manifest.version})`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,SAAS,iBAAiB;;;ACD1B,OAAO,UAAU;AACjB,SAAS,SAAS;;;ACoBlB,IAAM,wBAAwB;AAUvB,SAAS,qBACd,OACA,WACG;AACH,MAAI,CAAC,sBAAsB,KAAK,KAAK,EAAG,QAAO;AAC/C,wBAAsB,YAAY;AAClC,QAAM,YAAY,MAAM,QAAQ,uBAAuB,EAAE;AACzD,cAAY,EAAE;AAAA,IACZ,yCAAyC,SAAS;AAAA,EACpD;AAEA,SAAO;AACT;AAEA,SAAS,oBAAoB,QAAkB,WAA6B;AAC1E,SAAO,OAAO,IAAI,CAAC,MAAM,qBAAqB,GAAG,SAAS,CAAC;AAC7D;AAgBA,SAAS,cACP,OACmC;AACnC,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,OAAO,WAAW,MAAM;AAAA,MAClD,qBAAqB,OAAO,YAAY;AAAA,MACxC,YAAY,IAAI,CAAC,gBAAgB;AAAA,QAC/B,GAAG;AAAA,QACH,GAAI,WAAW,YAAY,UAAa;AAAA,UACtC,SAAS,qBAAqB,WAAW,SAAS,cAAc;AAAA,QAClE;AAAA,QACA,GAAI,WAAW,UAAU,UAAa;AAAA,UACpC,OAAO,WAAW,MAAM,IAAI,CAAC,YAAY;AAAA,YACvC,GAAG;AAAA,YACH,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AAO,SAAS,EAAE;AAAA,IACxC,SAAS,OAAO;AACd,YAAM,eAAe,gBAAgB,KAAK;AAC1C,WAAK,iCAAiC,SAAS,MAAM,YAAY,EAAE;AAAA,IACrE;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,6BAA6B,SAAsC;AACjF,MAAI;AAAA,WAAc,QAAQ,MAAM,iBAAiB;AACjD,aAAW,UAAU,SAAS;AAC5B,QAAI,aAAa,OAAO,SAAS,MAAM,OAAO,SAAS,OAAO,GAAG;AAAA,EACnE;AACF;","names":["path","path","path","path","partition","path","path","path","path","path","partition","agentName","path","path","path","agentName"]}