@aiwg/cli 2026.10.16 → 2026.10.19

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 (155) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +51 -0
  2. package/agentic/code/providers/flue/README.md +62 -0
  3. package/agentic/code/providers/flue/templates/aiwg/tools.ts +120 -0
  4. package/agentic/code/providers/model-capabilities.v1.json +23 -0
  5. package/agentic/code/providers/model-catalog.v1.json +9 -0
  6. package/dist/src/artifacts/corpus-tools/resolve.js +28 -6
  7. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  8. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  9. package/dist/src/artifacts/query-engine-discover.js +285 -0
  10. package/dist/src/artifacts/query-engine-entries.js +188 -0
  11. package/dist/src/artifacts/query-engine-index.js +249 -0
  12. package/dist/src/artifacts/query-engine-matching.js +143 -0
  13. package/dist/src/artifacts/query-engine-options.js +2 -0
  14. package/dist/src/artifacts/query-engine-rules.js +202 -0
  15. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  16. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  17. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  18. package/dist/src/artifacts/query-engine-show.js +300 -0
  19. package/dist/src/artifacts/query-engine.js +7 -2576
  20. package/dist/src/cli/handlers/help.js +1 -1
  21. package/dist/src/cli/handlers/init.js +1 -0
  22. package/dist/src/cli/handlers/mc-agents.js +111 -0
  23. package/dist/src/cli/handlers/mc-args.js +54 -0
  24. package/dist/src/cli/handlers/mc-control.js +227 -0
  25. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  26. package/dist/src/cli/handlers/mc-help.js +171 -0
  27. package/dist/src/cli/handlers/mc-run.js +343 -0
  28. package/dist/src/cli/handlers/mc-session.js +138 -0
  29. package/dist/src/cli/handlers/mc-status.js +258 -0
  30. package/dist/src/cli/handlers/mc-summary.js +43 -0
  31. package/dist/src/cli/handlers/mc-types.js +3 -0
  32. package/dist/src/cli/handlers/mc-worker.js +205 -0
  33. package/dist/src/cli/handlers/mc.js +12 -1665
  34. package/dist/src/cli/handlers/models-refusal.js +13 -0
  35. package/dist/src/cli/handlers/models.js +2 -1
  36. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  37. package/dist/src/cli/handlers/remove-options.js +31 -0
  38. package/dist/src/cli/handlers/remove-user.js +174 -0
  39. package/dist/src/cli/handlers/remove.js +201 -0
  40. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  41. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  42. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  43. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  44. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  45. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  46. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  47. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  48. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  49. package/dist/src/cli/handlers/subcommands.js +18 -1984
  50. package/dist/src/cli/handlers/use.js +11 -5
  51. package/dist/src/cli/scope-resolver.js +1 -142
  52. package/dist/src/cli/services/deployment-verification.js +3 -0
  53. package/dist/src/cli/user-scope-mirror.js +173 -0
  54. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  55. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  56. package/dist/src/config/host-resource-report.d.mts +5 -0
  57. package/dist/src/config/host-resource-report.mjs +36 -6
  58. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  59. package/dist/src/config/host-resource-runtime.mjs +9 -6
  60. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  61. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  62. package/dist/src/decision/ensemble-study/gates.js +78 -0
  63. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  64. package/dist/src/decision/ensemble-study/score.js +3 -2
  65. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  66. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  67. package/dist/src/decision/sensitivity/comparative.js +18 -41
  68. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  69. package/dist/src/gates/evaluate.js +2 -358
  70. package/dist/src/gates/observations.js +363 -0
  71. package/dist/src/gates/pack-composition.js +270 -0
  72. package/dist/src/gates/pack-tightening.js +197 -0
  73. package/dist/src/gates/pack-validation.js +262 -0
  74. package/dist/src/gates/registry-error.js +5 -0
  75. package/dist/src/gates/registry.js +13 -685
  76. package/dist/src/mcp/json-document.mjs +29 -0
  77. package/dist/src/mcp/muse-native-config.mjs +1 -28
  78. package/dist/src/memory/provider-memory-adapter.js +1 -0
  79. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  80. package/dist/src/models/model-capabilities.v1.json +23 -0
  81. package/dist/src/models/model-catalog.v1.json +9 -0
  82. package/dist/src/models/policy-resources.js +1 -1
  83. package/dist/src/models/worker-plan.js +5 -5
  84. package/dist/src/plugin/command-ownership.js +34 -0
  85. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  86. package/dist/src/plugin/skill-command-translator.js +6 -232
  87. package/dist/src/providers/capability-matrix.yaml +51 -0
  88. package/dist/src/providers/context-output-ownership.js +26 -0
  89. package/dist/src/providers/deployment-ownership.d.mts +20 -0
  90. package/dist/src/providers/deployment-ownership.mjs +236 -0
  91. package/dist/src/providers/deployment-removal.js +222 -0
  92. package/dist/src/providers/provider-context-contracts.js +8 -0
  93. package/dist/src/providers/provider-definition-schema.js +1 -0
  94. package/dist/src/providers/provider-definitions.js +1 -0
  95. package/dist/src/providers/provider-seeds-3.js +18 -0
  96. package/dist/src/providers/removal-transaction.js +86 -0
  97. package/dist/src/providers/settings-document.d.mts +3 -0
  98. package/dist/src/providers/settings-document.mjs +47 -0
  99. package/dist/src/providers/settings-removal.js +190 -0
  100. package/dist/src/providers/skill-ownership.d.mts +20 -2
  101. package/dist/src/providers/skill-ownership.mjs +12 -4
  102. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  103. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  104. package/dist/src/providers/transformation-receipt-source.js +194 -0
  105. package/dist/src/research/identity.js +8 -2
  106. package/dist/src/research/reference-match.js +66 -8
  107. package/dist/src/rules/activation.mjs +15 -6
  108. package/dist/src/rules/core-startup.mjs +2 -2
  109. package/dist/src/serve/mission-conductor.js +4 -0
  110. package/dist/src/serve/mission-summary.js +56 -0
  111. package/dist/src/skills/deployment-ownership.js +2 -2
  112. package/dist/src/skills/deployment-policy.js +9 -0
  113. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  114. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  115. package/dist/src/smiths/context-pipeline/flue-context.js +25 -0
  116. package/dist/src/smiths/context-pipeline/generator.js +7 -2
  117. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +9 -7
  118. package/dist/src/smiths/hook-bridge/index.js +9 -0
  119. package/package.json +5 -1
  120. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  121. package/tools/agents/deploy-agents.mjs +21 -680
  122. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  123. package/tools/agents/deploy-options.mjs +267 -0
  124. package/tools/agents/deploy-support.mjs +165 -0
  125. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  126. package/tools/agents/providers/base-behaviors.mjs +168 -0
  127. package/tools/agents/providers/base-context.mjs +205 -0
  128. package/tools/agents/providers/base-contract.mjs +116 -0
  129. package/tools/agents/providers/base-files.mjs +252 -0
  130. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  131. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  132. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  133. package/tools/agents/providers/base-inventory.mjs +269 -0
  134. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  135. package/tools/agents/providers/base-migrations.mjs +258 -0
  136. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  137. package/tools/agents/providers/base-rule-index.mjs +450 -0
  138. package/tools/agents/providers/base-runtime.mjs +60 -0
  139. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  140. package/tools/agents/providers/base.mjs +16 -3364
  141. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  142. package/tools/agents/providers/flue-project.mjs +79 -0
  143. package/tools/agents/providers/flue-specialists.mjs +64 -0
  144. package/tools/agents/providers/flue.mjs +50 -0
  145. package/tools/agents/providers/hermes-startup.mjs +0 -5
  146. package/tools/agents/providers/muse.mjs +7 -2
  147. package/tools/agents/providers/rule-delivery-surface.mjs +33 -5
  148. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  149. package/tools/agents/providers/rule-deployment-prepare.mjs +13 -3
  150. package/tools/agents/providers/rule-projection.mjs +3 -0
  151. package/tools/agents/providers/rule-startup.mjs +3 -3
  152. package/tools/agents/use-rule-selection.mjs +17 -0
  153. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  154. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  155. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -1,3364 +1,16 @@
1
- /**
2
- * Shared utilities for provider modules
3
- *
4
- * This module contains common functions used across all providers:
5
- * - File operations (ensureDir, listMdFiles, writeFile, etc.)
6
- * - Model configuration loading
7
- * - Frontmatter parsing
8
- * - Other shared utilities
9
- */
10
-
11
- import realFs from 'fs';
12
- import path from 'path';
13
- import os from 'os';
14
- import yaml from 'yaml';
15
- import { classifyModelRole } from './model-role.mjs';
16
- import { createHash } from 'crypto';
17
- import { createRequire } from 'module';
18
- import { importImpl } from '../../_resolve-impl.mjs';
19
-
20
- import { writeContextFileSync } from './context-write.mjs';
21
-
22
- const { parseRuleFrontmatter, inferRuleActivation } = await importImpl(import.meta.url, 'rules/activation.mjs');
23
- const { resolveRulesInlineBudget, DEFAULT_RULES_INLINE_BUDGET_TOKENS } = await importImpl(import.meta.url, 'rules/inline-budget.mjs');
24
- export { DEFAULT_RULES_INLINE_BUDGET_TOKENS, parseRuleFrontmatter as parseRuleActivation };
25
- const { boundedExecFileSync } = await importImpl(import.meta.url, 'process/bounded-child-process.mjs');
26
- const { helperEnvironment } = await importImpl(import.meta.url, 'process/cli-command.mjs');
27
- const { extractFrameworkSlug, sameSkillOwner, canDeploySkill, pruneRecordedSkillFiles, releaseSkillOwnership } =
28
- await importImpl(import.meta.url, 'providers/skill-ownership.mjs');
29
- export { extractFrameworkSlug, sameSkillOwner, pruneRecordedSkillFiles, releaseSkillOwnership };
30
-
31
- // Use graceful-fs to prevent EMFILE crashes on systems with low ulimit.
32
- // graceful-fs queues open() calls when FD pressure is detected and retries
33
- // after a backoff, transparently wrapping the native fs module.
34
- let fs;
35
- try {
36
- const require = createRequire(import.meta.url);
37
- const gracefulFs = require('graceful-fs');
38
- gracefulFs.gracefulify(realFs);
39
- fs = realFs;
40
- } catch {
41
- // graceful-fs not available — fall back to native fs
42
- fs = realFs;
43
- }
44
-
45
- // ============================================================================
46
- // File Operations
47
- // ============================================================================
48
-
49
- /**
50
- * Ensure a directory exists, creating it recursively if needed
51
- * @param {string} d - Directory path
52
- * @param {boolean} dryRun - If true, skip actual directory creation
53
- */
54
- export function ensureDir(d, dryRun = false) {
55
- if (dryRun) return;
56
- if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
57
- }
58
-
59
- const PROJECT_ARTIFACT_ENV_KEYS = [
60
- 'AIWG_ARTIFACTS_PATH',
61
- 'AIWG_PROJECT_ARTIFACTS_PATH',
62
- 'AIWG_PROJECT_AIWG_DIR',
63
- ];
64
-
65
- function expandProjectArtifactPath(value, projectDir) {
66
- const trimmed = value.trim();
67
- if (trimmed === '~') return os.homedir();
68
- if (trimmed.startsWith('~/')) return path.resolve(os.homedir(), trimmed.slice(2));
69
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(projectDir, trimmed);
70
- }
71
-
72
- function parseProjectArtifactLocation(contents) {
73
- for (const rawLine of contents.split(/\r?\n/)) {
74
- let line = rawLine.trim();
75
- if (!line || line.startsWith('#')) continue;
76
- if (line.startsWith('export ')) line = line.slice('export '.length).trim();
77
- const assignment = line.match(/^AIWG_ARTIFACTS_PATH\s*=\s*(.+)$/);
78
- if (assignment) line = assignment[1].trim();
79
- if ((line.startsWith('"') && line.endsWith('"')) || (line.startsWith("'") && line.endsWith("'"))) {
80
- line = line.slice(1, -1);
81
- }
82
- return line || null;
83
- }
84
- return null;
85
- }
86
-
87
- /** Resolve the artifact corpus root used for framework-generated workspace data. */
88
- export function resolveFrameworkWorkspaceRoot(projectDir, env = process.env) {
89
- for (const key of PROJECT_ARTIFACT_ENV_KEYS) {
90
- const value = env[key];
91
- if (typeof value === 'string' && value.trim()) return expandProjectArtifactPath(value, projectDir);
92
- }
93
- const pointer = path.join(projectDir, '.aiwg-location');
94
- if (fs.existsSync(pointer)) {
95
- const configured = parseProjectArtifactLocation(fs.readFileSync(pointer, 'utf8'));
96
- if (configured) return expandProjectArtifactPath(configured, projectDir);
97
- }
98
- return path.join(projectDir, '.aiwg');
99
- }
100
-
101
- /**
102
- * List markdown files in a directory (non-recursive)
103
- */
104
- export function listMdFiles(dir, excludePatterns = []) {
105
- if (!fs.existsSync(dir)) return [];
106
- const defaultExcluded = ['README.md', 'manifest.md', 'agent-template.md', 'openai-compat.md', 'factory-compat.md', 'windsurf-compat.md', 'DEVELOPMENT_GUIDE.md'];
107
- const excluded = [...defaultExcluded, ...excludePatterns];
108
- return fs
109
- .readdirSync(dir, { withFileTypes: true })
110
- .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.md') && !e.name.toLowerCase().endsWith('.soul.md') && !e.name.toLowerCase().endsWith('.core.md') && !excluded.includes(e.name))
111
- .map((e) => path.join(dir, e.name));
112
- }
113
-
114
- /**
115
- * List .soul.md companion files in a directory (non-recursive)
116
- */
117
- export function listSoulFiles(dir) {
118
- if (!fs.existsSync(dir)) return [];
119
- return fs
120
- .readdirSync(dir, { withFileTypes: true })
121
- .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.soul.md'))
122
- .map((e) => path.join(dir, e.name));
123
- }
124
-
125
- /**
126
- * List markdown files recursively
127
- */
128
- export function listMdFilesRecursive(dir, excludePatterns = []) {
129
- if (!fs.existsSync(dir)) return [];
130
- const defaultExcluded = ['README.md', 'manifest.md', 'agent-template.md', 'openai-compat.md', 'factory-compat.md', 'windsurf-compat.md', 'DEVELOPMENT_GUIDE.md'];
131
- const excluded = [...defaultExcluded, ...excludePatterns];
132
- const results = [];
133
-
134
- function scan(currentDir) {
135
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
136
- for (const entry of entries) {
137
- const fullPath = path.join(currentDir, entry.name);
138
- if (entry.isDirectory() && entry.name !== 'templates') {
139
- scan(fullPath);
140
- } else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md') && !excluded.includes(entry.name)) {
141
- results.push(fullPath);
142
- }
143
- }
144
- }
145
-
146
- scan(dir);
147
- return results;
148
- }
149
-
150
- /**
151
- * List skill directories (directories containing SKILL.md)
152
- */
153
- export function listSkillDirs(dir) {
154
- if (!fs.existsSync(dir)) return [];
155
- return fs
156
- .readdirSync(dir, { withFileTypes: true })
157
- .filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'SKILL.md')))
158
- .map((e) => path.join(dir, e.name));
159
- }
160
-
161
- /**
162
- * Write a file (with dry-run support)
163
- */
164
- export function writeFile(dest, data, dryRun) {
165
- if (dryRun) {
166
- console.log(`[dry-run] write ${dest}`);
167
- } else {
168
- fs.writeFileSync(dest, data, 'utf8');
169
- }
170
- }
171
-
172
- // ============================================================================
173
- // Deployment Manifest (File Ownership Tagging)
174
- // ============================================================================
175
-
176
- // Match either form so legacy-marker files are recognized as already-managed:
177
- // <!-- aiwg:managed v... ... (legacy, line 1, breaks YAML frontmatter parsing)
178
- // # aiwg:managed v... ... (current, inside frontmatter as a YAML comment)
179
- const MANAGED_MARKER_RE = /^(?:<!-- aiwg:managed |# aiwg:managed )/m;
180
- const MANIFEST_FILENAME = '.aiwg-manifest.json';
181
-
182
- /**
183
- * Add an `aiwg:managed vVERSION SOURCE` marker to deployed markdown content.
184
- *
185
- * For files with YAML frontmatter (start with `---\n`), inject the marker as
186
- * a YAML comment INSIDE the frontmatter. This keeps `---` on line 1, which
187
- * Claude Code (and other YAML frontmatter parsers) require to discover
188
- * agents/skills/commands. Issue #1059.
189
- *
190
- * For files without frontmatter, fall back to the legacy HTML-comment-at-top
191
- * form (no parser to break).
192
- *
193
- * Idempotent — skips if either form of the marker is already present.
194
- */
195
- export function addManagedMarker(content, version, source, style = 'markdown') {
196
- if (MANAGED_MARKER_RE.test(content)) return content;
197
- if (style === 'line-comment') {
198
- return `# aiwg:managed v${version} ${source}\n${content}`;
199
- }
200
- // Frontmatter present → inject as YAML comment after the opening `---\n`.
201
- if (content.startsWith('---\n')) {
202
- return content.replace(
203
- /^---\n/,
204
- `---\n# aiwg:managed v${version} ${source}\n`
205
- );
206
- }
207
- // No frontmatter → legacy HTML-comment-at-top form is safe.
208
- return `<!-- aiwg:managed v${version} ${source} -->\n${content}`;
209
- }
210
-
211
- /**
212
- * Compute SHA-256 hash of content (hex string).
213
- */
214
- export function contentHash(content) {
215
- return createHash('sha256').update(content).digest('hex');
216
- }
217
-
218
- /**
219
- * Read existing sidecar manifest from a deployment directory.
220
- * Returns `{ managed: { [filename]: { hash, source, version } } }` or null.
221
- */
222
- export function readSidecarManifest(dir) {
223
- const p = path.join(dir, MANIFEST_FILENAME);
224
- try {
225
- return JSON.parse(fs.readFileSync(p, 'utf8'));
226
- } catch {
227
- return null;
228
- }
229
- }
230
-
231
- /**
232
- * Write sidecar manifest to a deployment directory.
233
- */
234
- export function writeSidecarManifest(dir, manifest, dryRun) {
235
- if (dryRun) return;
236
- const p = path.join(dir, MANIFEST_FILENAME);
237
- fs.writeFileSync(p, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
238
- }
239
-
240
- /**
241
- * Update sidecar manifest entries for a batch of deployed files.
242
- * Merges into existing manifest if present.
243
- *
244
- * `frameworkSlug` (optional, per-entry) records which AIWG framework
245
- * the file came from (e.g., 'forensics-complete', 'sdlc-complete').
246
- * Used by the cross-framework collision guard (#1169) to detect
247
- * silent overwrites when two frameworks ship a file with the same
248
- * filename but different content.
249
- */
250
- export function updateSidecarManifest(dir, deployedEntries, opts) {
251
- const { dryRun = false, version = 'unknown', source = 'bundled' } = opts;
252
- const existing = readSidecarManifest(dir) || { managed: {} };
253
-
254
- for (const entry of deployedEntries) {
255
- const { filename, hash, frameworkSlug, kind, sourcePath } = entry;
256
- const sidecarEntry = { hash: `sha256:${hash}`, source, version };
257
- if (sourcePath) sidecarEntry.sourcePath = sourcePath;
258
- if (frameworkSlug) sidecarEntry.frameworkSlug = frameworkSlug;
259
- // `kind` marks artifacts whose lifecycle is governed elsewhere — currently
260
- // only `skill-command` wrappers, which follow their source skill (#2507).
261
- if (kind) sidecarEntry.kind = kind;
262
- existing.managed[filename] = sidecarEntry;
263
- }
264
-
265
- writeSidecarManifest(dir, existing, dryRun);
266
- }
267
-
268
- // ============================================================================
269
- // Model Configuration
270
- // ============================================================================
271
-
272
- /**
273
- * Load model configuration from models.json
274
- * Priority: Project models.json > User ~/.config/aiwg/models.json > AIWG defaults
275
- */
276
- export function loadModelConfig(srcRoot) {
277
- // An addon/framework/bundle `--source` is not the AIWG root, so resolve the
278
- // shipped defaults through the corpus root; otherwise addon deploys fell
279
- // through to the hardcoded fallback and deployed bare aliases (#2563).
280
- const aiwgRoot = (srcRoot && resolveAiwgRoot(srcRoot)) || srcRoot;
281
- const locations = [
282
- { path: path.join(process.cwd(), 'models.json'), label: 'project' },
283
- { path: path.join(process.env.HOME || process.env.USERPROFILE, '.config', 'aiwg', 'models.json'), label: 'user' },
284
- { path: path.join(aiwgRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'config', 'models.json'), label: 'AIWG defaults' }
285
- ];
286
-
287
- for (const loc of locations) {
288
- if (fs.existsSync(loc.path)) {
289
- try {
290
- const config = JSON.parse(fs.readFileSync(loc.path, 'utf8'));
291
- config._source = `${loc.label} (${loc.path})`;
292
- return config;
293
- } catch (err) {
294
- console.warn(`Warning: Could not parse models.json at ${loc.path}: ${err.message}`);
295
- }
296
- }
297
- }
298
-
299
- // Fallback to hardcoded defaults if no config found
300
- return {
301
- claude: {
302
- reasoning: { model: 'claude-opus-5' },
303
- coding: { model: 'claude-sonnet-5' },
304
- efficiency: { model: 'claude-haiku-4-5' }
305
- },
306
- factory: {
307
- reasoning: { model: 'heavy' },
308
- coding: { model: 'medium' },
309
- efficiency: { model: 'light' }
310
- },
311
- shorthand: {
312
- 'opus': 'claude-opus-5',
313
- 'sonnet': 'claude-sonnet-5',
314
- 'haiku': 'claude-haiku-4-5',
315
- 'inherit': 'inherit'
316
- },
317
- claude_shorthand: {
318
- 'opus': 'opus',
319
- 'opus-1m': 'opus[1m]',
320
- 'opus[1m]': 'opus[1m]',
321
- 'sonnet': 'sonnet',
322
- 'sonnet-1m': 'sonnet[1m]',
323
- 'sonnet[1m]': 'sonnet[1m]',
324
- 'haiku': 'haiku',
325
- 'inherit': 'inherit'
326
- }
327
- };
328
- }
329
-
330
- /**
331
- * Load a fresh dynamically-discovered model catalog when available, otherwise
332
- * use the committed catalog supplied by the caller. Refresh is performed by
333
- * `aiwg models refresh`; deployment itself never performs network access.
334
- */
335
- export function loadRuntimeModelCatalog(staticCatalog, options = {}) {
336
- if (process.env.VITEST && !options.cacheFile && !options.homeDir) return staticCatalog;
337
- const homeDir = options.homeDir || os.homedir();
338
- const cacheFile = options.cacheFile || path.join(homeDir, '.cache', 'aiwg', 'model-catalog.v1.json');
339
- const ttlMs = options.ttlMs ?? 24 * 60 * 60 * 1000;
340
- try {
341
- const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
342
- const fetchedAt = Date.parse(cached?.discovery?.fetchedAt || '');
343
- const age = Date.now() - fetchedAt;
344
- if (
345
- cached?.providers &&
346
- Number.isFinite(age) &&
347
- age >= 0 &&
348
- age <= ttlMs
349
- ) {
350
- return cached;
351
- }
352
- } catch {
353
- // Missing, stale, or malformed cache: deterministic static fallback.
354
- }
355
- return staticCatalog;
356
- }
357
-
358
- // ============================================================================
359
- // Frontmatter Utilities
360
- // ============================================================================
361
-
362
- /**
363
- * Maps provider names to the platform identifiers used in skill platforms: fields.
364
- * Skills use descriptive names (e.g. "claude-code") while providers use short names (e.g. "claude").
365
- */
366
- const PROVIDER_TO_PLATFORM = {
367
- 'claude': 'claude-code'
368
- };
369
-
370
- /**
371
- * Parse the platforms: field from a SKILL.md frontmatter block.
372
- * Accepts a string or a list of strings; all alone means unrestricted.
373
- * Returns null if platforms is missing, or no frontmatter is present.
374
- * Returns an empty array for malformed frontmatter or invalid platforms.
375
- */
376
- export function parseSkillPlatforms(content) {
377
- // A leading UTF-8 BOM must not hide the frontmatter (and its restrictions).
378
- if (content.charCodeAt(0) === 0xfeff) content = content.slice(1);
379
- const fmMatch = content.match(/^---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);
380
- if (!fmMatch || fmMatch.index !== 0) {
381
- return /^---[ \t]*(?:\r?\n|$)/.test(content) ? [] : null;
382
- }
383
-
384
- let metadata;
385
- try {
386
- const document = yaml.parseDocument(fmMatch[1]);
387
- if (document.errors.length > 0) return [];
388
- if (!document.contents) return null; // Empty frontmatter has no restrictions.
389
- metadata = document.toJS();
390
- } catch {
391
- return [];
392
- }
393
- if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return [];
394
- // The yaml package leaves merge keys unresolved, so platforms could arrive only
395
- // through `<<`; without an explicit key that is ambiguous, so fail closed.
396
- if (!Object.hasOwn(metadata, 'platforms')) return Object.hasOwn(metadata, '<<') ? [] : null;
397
-
398
- const platforms = metadata.platforms;
399
- const items = typeof platforms === 'string' ? [platforms] : platforms;
400
- if (!Array.isArray(items) || !items.every(item => typeof item === 'string')) return [];
401
- const normalized = items.map(item => item.trim());
402
- if (normalized.some(item => !item)) return [];
403
- return normalized.length === 1 && normalized[0] === 'all' ? null : normalized;
404
- }
405
-
406
- /**
407
- * Returns true if a skill (given its source content) should be deployed to the given provider.
408
- * If no provider is specified, always returns true.
409
- */
410
- export function skillMatchesProvider(content, provider) {
411
- if (!provider) return true;
412
-
413
- const platforms = parseSkillPlatforms(content);
414
- if (!platforms) return true; // No restriction
415
-
416
- const platformName = PROVIDER_TO_PLATFORM[provider] || provider;
417
- return platforms.includes(platformName) || platforms.includes(provider);
418
- }
419
-
420
- /**
421
- * Inject the target platform name into a SKILL.md frontmatter block.
422
- *
423
- * Source skills use platforms: [all] as a deployment token.
424
- * At deploy time this function replaces [all] with [<targetPlatform>] so
425
- * each deployed copy accurately reflects where it was installed.
426
- *
427
- * Explicit restriction lists (not [all]) are preserved as-is.
428
- * If no platforms: field is present, one is added.
429
- */
430
- export function injectPlatformInContent(content, targetPlatform) {
431
- if (!targetPlatform) return content;
432
-
433
- const fmMatch = content.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);
434
- if (!fmMatch) return content;
435
-
436
- const [, open, fm, close, body] = fmMatch;
437
-
438
- const injected = `platforms: [${targetPlatform}]`;
439
-
440
- // Case 1: inline [all] token → replace with target platform
441
- let updated = fm.replace(/^platforms:\s*\[all\]\n?/m, injected + '\n');
442
- if (updated !== fm) return open + updated + close + body;
443
-
444
- // Case 2: inline explicit restriction (not [all]) → leave as-is, do not inject
445
- if (/^platforms:\s*\[(?!all\])[^\]]+\]/m.test(fm)) {
446
- return content;
447
- }
448
-
449
- // Case 3: multi-line list → replace entire block with injected value
450
- updated = fm.replace(/^platforms:\s*\n(?:[ \t]+-[ \t]+\S[^\n]*\n?)*/m, injected + '\n');
451
- if (updated !== fm) return open + updated + close + body;
452
-
453
- // Case 4: bare `platforms:` with no value → replace
454
- updated = fm.replace(/^platforms:\s*$/m, injected);
455
- if (updated !== fm) return open + updated + close + body;
456
-
457
- // Case 5: no platforms: field at all → insert after the first frontmatter line
458
- const fmLines = fm.split('\n');
459
- fmLines.splice(1, 0, injected);
460
- return open + fmLines.join('\n') + close + body;
461
- }
462
-
463
- /**
464
- * Remove the `platforms:` field from a SKILL.md frontmatter block.
465
- *
466
- * Hermes (and other providers that treat `platforms:` as an OS gate —
467
- * linux / macos / windows) hide any skill whose value isn't a recognized
468
- * OS. AIWG source skills use the field as a *provider* restriction token
469
- * (`[all]`, provider names), which is the opposite meaning, so deployed
470
- * copies destined for such providers must drop the field entirely. An
471
- * absent field is the documented "compatible with all platforms" default.
472
- */
473
- /**
474
- * Remove the `triggers:` field from a deployed rule's frontmatter.
475
- *
476
- * Rules declare trigger phrases so `aiwg discover` can reach them by the
477
- * question an agent asks rather than by their policy name (#2544). That is
478
- * index-time metadata: no provider matches a *rule* by trigger, and the agent
479
- * reading the deployed rule gains nothing from the list. Shipping it spends
480
- * startup context on noise, which is exactly the budget #2540 is defending —
481
- * ~2KB across the 16 rules covered today, and ~16KB if every rule adopts.
482
- *
483
- * Skills are untouched: several providers do match skills by trigger.
484
- */
485
- export function stripTriggersFromContent(content) {
486
- const fmMatch = content.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))([\s\S]*)$/);
487
- if (!fmMatch) return content;
488
-
489
- const [, open, fm, close, body] = fmMatch;
490
- // Block list form:
491
- // triggers:
492
- // - "am I allowed to do this"
493
- let updated = fm.replace(
494
- /^triggers:[ \t]*\r?\n(?:[ \t]+-[ \t]+\S[^\r\n]*(?:\r?\n|$))*/m,
495
- '',
496
- );
497
- // Inline form: triggers: ["a", "b"]
498
- if (updated === fm) updated = fm.replace(/^triggers:[^\r\n]*(?:\r?\n|$)/m, '');
499
-
500
- if (updated === fm) return content;
501
- // An otherwise-empty frontmatter block is dropped rather than left as `---\n---`.
502
- if (updated.trim().length === 0) return body.replace(/^\r?\n/, '');
503
- // Removing a block mid-frontmatter can leave a trailing blank line before the
504
- // closing fence; the deployed file should not carry it.
505
- return open + updated.replace(/\s+$/, '') + close + body;
506
- }
507
-
508
- export function stripPlatformsFromContent(content) {
509
- const fmMatch = content.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))([\s\S]*)$/);
510
- if (!fmMatch) return content;
511
-
512
- const [, open, fm, close, body] = fmMatch;
513
- let updated = fm.replace(/^platforms:[^\r\n]*(?:\r?\n|$)/m, '');
514
-
515
- // Multi-line list form:
516
- // platforms:
517
- // - claude-code
518
- // - hermes
519
- if (updated === fm) {
520
- updated = fm.replace(
521
- /^platforms:[ \t]*\r?\n(?:[ \t]+-[ \t]+\S[^\r\n]*(?:\r?\n|$))*/m,
522
- '',
523
- );
524
- }
525
-
526
- if (updated === fm) return content;
527
- return open + updated + close + body;
528
- }
529
-
530
- /**
531
- * Parse YAML frontmatter from markdown content
532
- * Returns { frontmatter: string, body: string, metadata: object }
533
- */
534
- export function parseFrontmatter(content) {
535
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
536
- if (!fmMatch) {
537
- return { frontmatter: null, body: content, metadata: {} };
538
- }
539
-
540
- const [, frontmatter, body] = fmMatch;
541
-
542
- // Parse simple YAML key-value pairs
543
- const metadata = {};
544
- for (const line of frontmatter.split('\n')) {
545
- const match = line.match(/^(\w+):\s*(.+)$/);
546
- if (match) {
547
- metadata[match[1]] = match[2].trim();
548
- }
549
- }
550
-
551
- return { frontmatter, body, metadata };
552
- }
553
-
554
- /**
555
- * Create frontmatter string from metadata object
556
- */
557
- export function stringifyFrontmatter(metadata, body) {
558
- const lines = ['---'];
559
- for (const [key, value] of Object.entries(metadata)) {
560
- if (value !== undefined && value !== null) {
561
- lines.push(`${key}: ${value}`);
562
- }
563
- }
564
- lines.push('---');
565
- return lines.join('\n') + '\n\n' + body.trim();
566
- }
567
-
568
- // ============================================================================
569
- // String Utilities
570
- // ============================================================================
571
-
572
- /**
573
- * Convert a string to kebab-case
574
- * "Technical Researcher" -> "technical-researcher"
575
- */
576
- export function toKebabCase(str) {
577
- if (!str) return str;
578
- return str
579
- .toLowerCase()
580
- .replace(/[^a-z0-9]+/g, '-')
581
- .replace(/^-+|-+$/g, '');
582
- }
583
-
584
- /**
585
- * Strip JSON comments (JSONC) for parsing. Used by the Factory and Muse
586
- * settings and hooks merges, which write the parsed document back, so the
587
- * scanner tracks string literals: `//` in a URL or a slash-star sequence in
588
- * a glob matcher is data, not a comment. A regex-only stripper collapsed glob
589
- * matchers inside strings and rejected any settings file containing a URL.
590
- */
591
- export function stripJsonComments(jsonc) {
592
- const text = String(jsonc);
593
- let out = '';
594
- let i = 0;
595
- while (i < text.length) {
596
- const ch = text[i];
597
- if (ch === '"') {
598
- let j = i + 1;
599
- while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
600
- out += text.slice(i, j + 1);
601
- i = j + 1;
602
- } else if (ch === '/' && text[i + 1] === '/') {
603
- while (i < text.length && text[i] !== '\n') i++;
604
- } else if (ch === '/' && text[i + 1] === '*') {
605
- const end = text.indexOf('*/', i + 2);
606
- i = end === -1 ? text.length : end + 2;
607
- } else {
608
- out += ch;
609
- i++;
610
- }
611
- }
612
- return out;
613
- }
614
-
615
- // ============================================================================
616
- // Agent Category Inference
617
- // ============================================================================
618
-
619
- /**
620
- * Infer agent category from name and body content
621
- * Returns: 'analysis', 'documentation', 'planning', or 'implementation'
622
- */
623
- export function inferAgentCategory(name, body) {
624
- const normalizedName = (name || '').toLowerCase();
625
- const normalizedBody = (body || '').toLowerCase();
626
-
627
- // Analysis agents (read-only)
628
- if (normalizedName.includes('security') || normalizedName.includes('review') ||
629
- normalizedName.includes('analyst') || normalizedName.includes('auditor')) {
630
- return 'analysis';
631
- }
632
-
633
- // Documentation agents
634
- if (normalizedName.includes('writer') || normalizedName.includes('document') ||
635
- normalizedName.includes('archivist')) {
636
- return 'documentation';
637
- }
638
-
639
- // Planning agents
640
- if (normalizedName.includes('architect') || normalizedName.includes('planner') ||
641
- normalizedName.includes('requirements') || normalizedName.includes('designer')) {
642
- return 'planning';
643
- }
644
-
645
- // Implementation agents (full access)
646
- if (normalizedName.includes('implement') || normalizedName.includes('engineer') ||
647
- normalizedName.includes('developer') || normalizedName.includes('test')) {
648
- return 'implementation';
649
- }
650
-
651
- // Default to implementation for most flexibility
652
- return 'implementation';
653
- }
654
-
655
- // ============================================================================
656
- // Tool Parsing
657
- // ============================================================================
658
-
659
- /**
660
- * Parse tools string into array
661
- */
662
- export function parseTools(toolsString) {
663
- if (!toolsString) return [];
664
-
665
- if (toolsString.startsWith('[')) {
666
- try {
667
- return JSON.parse(toolsString);
668
- } catch (e) {
669
- return toolsString.replace(/[\[\]"']/g, '').split(/[,\s]+/).filter(Boolean);
670
- }
671
- }
672
- return toolsString.split(/[,\s]+/).filter(Boolean);
673
- }
674
-
675
- // ============================================================================
676
- // Skill-Command Collision Detection
677
- // ============================================================================
678
-
679
- /**
680
- * Filter out commands that share a name with a skill.
681
- * Skills are the richer format (triggers, NL routing, behavior spec) and take precedence.
682
- *
683
- * @param {string[]} commandFiles - Array of command file paths
684
- * @param {string[]} skillDirs - Array of skill directory paths
685
- * @returns {string[]} Filtered command files with collisions removed
686
- */
687
- export function filterCommandsAgainstSkills(commandFiles, skillDirs) {
688
- if (!skillDirs.length || !commandFiles.length) return commandFiles;
689
-
690
- // Build set of skill names (directory basenames, without extension)
691
- const skillNames = new Set(skillDirs.map(d => path.basename(d)));
692
-
693
- const filtered = [];
694
- for (const f of commandFiles) {
695
- // Command name is the filename without extension
696
- const commandName = path.basename(f).replace(/\.\w+$/, '');
697
- if (skillNames.has(commandName)) {
698
- console.log(`skip (skill precedence): command "${commandName}" — skill with same name takes precedence`);
699
- } else {
700
- filtered.push(f);
701
- }
702
- }
703
-
704
- return filtered;
705
- }
706
-
707
- function shouldReportDeployCollisions(opts = {}) {
708
- if (opts.reportCollisions === true) return true;
709
- if (opts.reportCollisions === false) return false;
710
- if (process.env.AIWG_REPORT_DEPLOY_COLLISIONS === '1') return true;
711
- if (process.env.VITEST) return false;
712
- if (process.env.NODE_ENV === 'test') return false;
713
- return true;
714
- }
715
-
716
- // ============================================================================
717
- // File Deployment
718
- // ============================================================================
719
-
720
- /**
721
- * Deploy files to destination directory
722
- * Handles transformation via provider's transform function
723
- */
724
- export function deployFiles(files, destDir, opts, transformFn) {
725
- const { force = false, dryRun = false, provider = 'claude', fileExtension = '.md', injectPlatform = false } = opts;
726
- const deployVersion = opts.deployVersion || 'unknown';
727
- const deploySource = opts.deploySource || 'bundled';
728
- // Map of dest path → first batch entry that claimed it. Used to detect
729
- // and report cross-framework collisions within a single deploy batch
730
- // (#1169). Each value: { src, frameworkSlug }
731
- const seen = new Map();
732
- const actions = [];
733
- // Collision report — one entry per detected cross-framework collision
734
- // (within-batch or against sidecar). Surfaced after the loop.
735
- const collisions = [];
736
-
737
- // Read sidecar manifest for hash-based skip-on-match (#749) and
738
- // cross-framework collision detection (#1169)
739
- const sidecar = readSidecarManifest(destDir);
740
- const sidecarManaged = sidecar?.managed || {};
741
-
742
- for (const f of files) {
743
- let base = path.basename(f);
744
-
745
- // Change extension if needed
746
- if (fileExtension !== '.md' && base.endsWith('.md')) {
747
- base = base.replace(/\.md$/, fileExtension);
748
- }
749
-
750
- let dest = path.join(destDir, base);
751
- const currentFrameworkSlug = extractFrameworkSlug(f);
752
-
753
- // Read and transform source content (needed for content-equality check
754
- // and the collision-vs-duplicate distinction)
755
- const srcContent = injectBoundRules(fs.readFileSync(f, 'utf8'), f, opts);
756
- let transformedContent = transformFn ? transformFn(f, srcContent, opts) : srcContent;
757
-
758
- // Rule triggers are index metadata, not something the reading agent needs.
759
- // Keyed on the source path so every provider's rule deploy gets it without
760
- // eight call sites opting in, and so skill triggers are never touched (#2544).
761
- if (/(?:^|[\\/])rules[\\/][^\\/]+$/.test(f)) {
762
- transformedContent = stripTriggersFromContent(transformedContent);
763
- }
764
-
765
- // Inject target platform into agent .md files that use platforms: [all]
766
- if (injectPlatform && provider && /platforms:\s*\[all\]/.test(transformedContent)) {
767
- const platformName = PROVIDER_TO_PLATFORM[provider] || provider;
768
- transformedContent = injectPlatformInContent(transformedContent, platformName);
769
- }
770
-
771
- // Add managed marker for provider artifacts (#749). TOML accepts `#`
772
- // comments, which lets doctor attribute transformed Codex agents even
773
- // though their YAML frontmatter is removed during serialization.
774
- if (base.endsWith('.md') || base.endsWith('.mdc')) {
775
- transformedContent = addManagedMarker(transformedContent, deployVersion, deploySource);
776
- } else if (base.endsWith('.toml')) {
777
- transformedContent = addManagedMarker(
778
- transformedContent,
779
- deployVersion,
780
- deploySource,
781
- 'line-comment',
782
- );
783
- }
784
-
785
- // Compute content hash for sidecar comparison
786
- const hash = contentHash(transformedContent);
787
-
788
- // Within-batch collision check (#1169). If a previous file in this
789
- // batch already claimed this dest, distinguish:
790
- // - Same content (transform/normalize is idempotent) → silent skip
791
- // - Same framework + different content → "duplicate" (legacy reason)
792
- // - Different framework + different content → "collision"
793
- if (seen.has(dest)) {
794
- const prev = seen.get(dest);
795
- const prevContent = prev.transformedContent;
796
- if (prevContent === transformedContent) {
797
- actions.push({ type: 'skip', src: f, dest, reason: 'duplicate-identical' });
798
- continue;
799
- }
800
- const prevSlug = prev.frameworkSlug;
801
- if (currentFrameworkSlug && prevSlug && currentFrameworkSlug !== prevSlug) {
802
- // Cross-framework collision within a single deploy batch — first
803
- // wins; second is skipped. `--force` keeps the first entry too,
804
- // since we have no principled way to pick a winner among peers.
805
- collisions.push({
806
- dest,
807
- filename: base,
808
- existingFramework: prevSlug,
809
- existingSrc: prev.src,
810
- incomingFramework: currentFrameworkSlug,
811
- incomingSrc: f,
812
- scope: 'within-batch',
813
- });
814
- actions.push({
815
- type: 'skip',
816
- src: f,
817
- dest,
818
- reason: 'collision',
819
- collidingFramework: prevSlug,
820
- });
821
- continue;
822
- }
823
- actions.push({ type: 'skip', src: f, dest, reason: 'duplicate' });
824
- continue;
825
- }
826
-
827
- // Skip-on-match: compare hash against sidecar manifest before reading dest file (#749)
828
- // Guard: only skip if the destination file still exists on disk. cleanupOldRuleFiles
829
- // may have deleted it before deployFiles runs, so the sidecar record is stale.
830
- if (!force && sidecarManaged[base]?.hash === `sha256:${hash}` && fs.existsSync(dest)) {
831
- actions.push({ type: 'skip', src: f, dest, reason: 'hash-match' });
832
- seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
833
- continue;
834
- }
835
-
836
- // Cross-batch collision check against sidecar (#1169). If the dest
837
- // file is already managed by a *different* framework than this deploy,
838
- // and the new content differs, refuse to silently overwrite.
839
- if (
840
- !force &&
841
- fs.existsSync(dest) &&
842
- sidecarManaged[base]?.frameworkSlug &&
843
- currentFrameworkSlug &&
844
- sidecarManaged[base].frameworkSlug !== currentFrameworkSlug
845
- ) {
846
- const destContent = fs.readFileSync(dest, 'utf8');
847
- if (destContent !== transformedContent) {
848
- collisions.push({
849
- dest,
850
- filename: base,
851
- existingFramework: sidecarManaged[base].frameworkSlug,
852
- existingSrc: null,
853
- incomingFramework: currentFrameworkSlug,
854
- incomingSrc: f,
855
- scope: 'cross-batch',
856
- });
857
- actions.push({
858
- type: 'skip',
859
- src: f,
860
- dest,
861
- reason: 'collision',
862
- collidingFramework: sidecarManaged[base].frameworkSlug,
863
- });
864
- // Don't claim the dest in `seen` — we did not deploy. The sidecar
865
- // entry already holds the previous framework's record and stays.
866
- continue;
867
- }
868
- }
869
-
870
- // Fallback: check destination file content directly
871
- if (!force && fs.existsSync(dest)) {
872
- const destContent = fs.readFileSync(dest, 'utf8');
873
- if (destContent === transformedContent) {
874
- actions.push({ type: 'skip', src: f, dest, reason: 'unchanged', hash });
875
- seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
876
- continue;
877
- }
878
- actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'changed', hash, frameworkSlug: currentFrameworkSlug });
879
- } else if (force && fs.existsSync(dest)) {
880
- actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'forced', hash, frameworkSlug: currentFrameworkSlug });
881
- } else {
882
- actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'new', hash, frameworkSlug: currentFrameworkSlug });
883
- }
884
- seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
885
- }
886
-
887
- const verbose = opts.verbose === true;
888
- const deployedEntries = [];
889
- for (const a of actions) {
890
- if (a.type === 'deploy') {
891
- if (dryRun) console.log(`[dry-run] deploy ${a.src} -> ${a.dest} (${a.reason})`);
892
- else writeFile(a.dest, a.content, false);
893
- if (verbose) console.log(`deployed ${path.basename(a.src)} -> ${path.relative(process.cwd(), opts.logicalOutputPath?.(a.dest) || a.dest)} (${a.reason})`);
894
- deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
895
- } else if (a.type === 'skip') {
896
- if (verbose) console.log(`skip (${a.reason}): ${path.basename(a.dest)}`);
897
- // Preserve existing sidecar entries for skipped files
898
- if (a.hash) deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash });
899
- }
900
- }
901
-
902
- // Surface cross-framework collisions to the operator (#1169). Always
903
- // visible (not gated on verbose) because silent loss is the failure
904
- // mode this guard exists to prevent.
905
- if (collisions.length > 0 && shouldReportDeployCollisions(opts)) {
906
- const tag = force ? 'override' : 'skip';
907
- console.warn(
908
- `\n⚠ Cross-framework deploy collision${collisions.length > 1 ? 's' : ''} detected (${collisions.length}):`,
909
- );
910
- for (const c of collisions) {
911
- console.warn(
912
- ` ${c.filename}: ${c.existingFramework} owns this slot; ${c.incomingFramework} skipped (${c.scope})`,
913
- );
914
- }
915
- if (!force) {
916
- console.warn(
917
- ` Re-run with --force to override (last-wins) or rename the colliding file at framework source.`,
918
- );
919
- }
920
- }
921
-
922
- // Update sidecar manifest with deployed file hashes (#749) including
923
- // framework slug for future collision detection (#1169).
924
- if (deployedEntries.length > 0) {
925
- updateSidecarManifest(destDir, deployedEntries, { dryRun, version: deployVersion, source: deploySource });
926
- }
927
-
928
- return actions;
929
- }
930
-
931
- /**
932
- * Deploy .soul.md companion files alongside agents.
933
- * Soul files are copied as-is (no transformation) to the same directory as agents.
934
- */
935
- export function deploySoulCompanions(soulFiles, destDir, opts) {
936
- if (!soulFiles || soulFiles.length === 0) return [];
937
- return deployFiles(soulFiles, destDir, opts, null);
938
- }
939
-
940
- /**
941
- * Read a skill's SKILL.md frontmatter and return whether it is a
942
- * "kernel" skill — always-loaded, deploys to the platform's native
943
- * skills directory rather than the AIWG-namespaced one. Per epic
944
- * #1212. A skill opts in by setting `kernel: true` in its frontmatter.
945
- *
946
- * Note: `parseFrontmatter` keeps values as strings (no YAML coercion).
947
- * Accept both the string `"true"` and the boolean `true` so callers
948
- * are not surprised if a future parser upgrade returns booleans.
949
- */
950
- export function isKernelSkill(skillDir) {
951
- const skillMdPath = path.join(skillDir, 'SKILL.md');
952
- if (!fs.existsSync(skillMdPath)) return false;
953
- const content = fs.readFileSync(skillMdPath, 'utf8');
954
- const { metadata } = parseFrontmatter(content);
955
- const v = metadata?.kernel;
956
- return v === true || v === 'true';
957
- }
958
-
959
- /**
960
- * Deploy skills with kernel-vs-standard routing (#1212/#1216/#1217).
961
- *
962
- * Partitions `skillDirs` into kernel skills (frontmatter `kernel: true`)
963
- * and standard skills.
964
- *
965
- * **Kernel skills** copy to `kernelDestDir` (platform-native dir,
966
- * always-loaded by the platform). Small set: currently 24 skills spanning
967
- * framework quickrefs, routing maps, and self-maintenance operations.
968
- *
969
- * **Standard skills** are NOT copied per-project (#1217). They live at
970
- * `$AIWG_ROOT/agentic/code/.../skills/<name>/` and `aiwg discover`
971
- * returns absolute paths anchored there. The agent reads them directly
972
- * via the `Read` tool — no per-project mirror, no stale-copy risk.
973
- * `standardDestDir` is retained as a fallback when `$AIWG_ROOT` is not
974
- * readable, and as the cleanup target for legacy `.aiwg/skills/`
975
- * directories from rc.13 and earlier deploys.
976
- *
977
- * @param skillDirs absolute paths to source skill directories
978
- * @param standardDestDir absolute path for standard skills (legacy
979
- * per-project mirror — used only as cleanup
980
- * target by default; populated if
981
- * `opts.copyStandardSkills` is true)
982
- * @param kernelDestDir absolute path for kernel skills
983
- * (e.g., `.cursor/skills`); pass null/undefined
984
- * to disable kernel routing
985
- * @param opts standard deploy opts forwarded to
986
- * `deploySkillDir`. New optional flags:
987
- * - `copyStandardSkills` (default: false) —
988
- * force per-project copy of standard skills
989
- * (used when $AIWG_ROOT is not readable from
990
- * the agent's working directory)
991
- *
992
- * @returns `{ kernel, standardCopied, prunedFromKernelDir,
993
- * prunedFromStandardDir, prunedKernelFromStandardDir }`
994
- * deployed/pruned counts
995
- *
996
- * Cleanup behavior:
997
- * - Kernel dir: prune any AIWG-shaped skill whose name now belongs
998
- * to the standard tier (rc.13 behavior, preserved).
999
- * - Standard dir: when standard copies are NOT being deployed this
1000
- * run, prune any AIWG-shaped skill that exists under
1001
- * `standardDestDir`. These are legacy per-project mirrors from
1002
- * rc.13 deploys; the canonical source is now `$AIWG_ROOT`.
1003
- * - User-authored skills (no SKILL.md, or names not in our deploy
1004
- * manifest) survive untouched in both directories.
1005
- */
1006
- export function deploySkillsWithKernelRouting(
1007
- skillDirs,
1008
- standardDestDir,
1009
- kernelDestDir,
1010
- opts,
1011
- ) {
1012
- // Caller opts in via `opts.copyStandardSkills` (set by `--copy-all`
1013
- // CLI flag, #1219). Default (#1217) is no-copy: standard skills stay
1014
- // at their source path under $AIWG_ROOT and are reached via the
1015
- // artifact index.
1016
- const copyStandardSkills = opts?.copyStandardSkills === true;
1017
-
1018
- const kernel = [];
1019
- const standard = [];
1020
- for (const dir of skillDirs) {
1021
- if (kernelDestDir && isKernelSkill(dir)) kernel.push(dir);
1022
- else standard.push(dir);
1023
- }
1024
-
1025
- // Names of skills in the deploy manifest — bound the cleanup to
1026
- // names AIWG manages so user-authored content survives.
1027
- const standardNames = new Set(standard.map(p => path.basename(p)));
1028
- const allSkillNames = new Set([...standardNames, ...kernel.map(p => path.basename(p))]);
1029
-
1030
- if (kernel.length > 0 && kernelDestDir) {
1031
- ensureDir(kernelDestDir, opts?.dryRun);
1032
- for (const dir of kernel) deploySkillDir(dir, kernelDestDir, opts);
1033
- }
1034
-
1035
- // Standard tier copy is OFF by default (#1217). Only fires when the
1036
- // operator explicitly opts in via `copyStandardSkills` — typically
1037
- // because $AIWG_ROOT isn't readable from the agent's working dir.
1038
- let standardCopied = 0;
1039
- if (copyStandardSkills && standard.length > 0) {
1040
- ensureDir(standardDestDir, opts?.dryRun);
1041
- for (const dir of standard) {
1042
- deploySkillDir(dir, standardDestDir, opts);
1043
- standardCopied++;
1044
- }
1045
- }
1046
-
1047
- // A skill promoted from standard → kernel may still have an older managed
1048
- // copy in the opt-in standard mirror. Remove that duplicate even when
1049
- // --copy-all remains enabled; otherwise providers that recursively scan
1050
- // both tiers can surface the same skill twice after a tier transition.
1051
- let prunedKernelFromStandardDir = 0;
1052
- if (
1053
- standardDestDir &&
1054
- fs.existsSync(standardDestDir) &&
1055
- !opts?.dryRun &&
1056
- kernel.length > 0
1057
- ) {
1058
- const kernelNames = new Set(kernel.map(p => path.basename(p)));
1059
- for (const entry of fs.readdirSync(standardDestDir, { withFileTypes: true })) {
1060
- if (!entry.isDirectory() || !kernelNames.has(entry.name)) continue;
1061
- const target = path.join(standardDestDir, entry.name);
1062
- const skillMd = path.join(target, 'SKILL.md');
1063
- if (!fs.existsSync(skillMd)) continue;
1064
- const marker = path.join(target, '.aiwg-managed');
1065
- let managed = fs.existsSync(marker);
1066
- if (!managed) {
1067
- try {
1068
- managed = /^\s*namespace:\s*["']?aiwg["']?\s*$/m.test(
1069
- parseFrontmatter(fs.readFileSync(skillMd, 'utf8')).frontmatter ?? '',
1070
- );
1071
- } catch { /* preserve unreadable/operator-owned content */ }
1072
- }
1073
- if (!managed) continue;
1074
- fs.rmSync(target, { recursive: true, force: true });
1075
- prunedKernelFromStandardDir++;
1076
- if (opts?.verbose) console.log(`pruned promoted kernel from standard dir: ${entry.name}`);
1077
- }
1078
- }
1079
-
1080
- // Kernel-dir cleanup: prune skills whose name moved to the standard
1081
- // tier (rc.13 logic). Holistic cleanup of orphaned skills (renamed or
1082
- // removed sources) happens in a separate post-all-deploys step
1083
- // (`pruneStaleAiwgSkills`) — running per-call here would race because
1084
- // `deploySkills` may be invoked multiple times in one orchestration.
1085
- let prunedFromKernelDir = 0;
1086
- if (kernelDestDir && fs.existsSync(kernelDestDir) && !opts?.dryRun) {
1087
- for (const entry of fs.readdirSync(kernelDestDir, { withFileTypes: true })) {
1088
- if (!entry.isDirectory()) continue;
1089
- const skillMd = path.join(kernelDestDir, entry.name, 'SKILL.md');
1090
- if (!fs.existsSync(skillMd)) continue;
1091
- if (!standardNames.has(entry.name)) continue;
1092
- const target = path.join(kernelDestDir, entry.name);
1093
- try {
1094
- fs.rmSync(target, { recursive: true, force: true });
1095
- prunedFromKernelDir++;
1096
- if (opts?.verbose) console.log(`pruned legacy from kernel dir: ${entry.name}`);
1097
- } catch (err) {
1098
- if (opts?.verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
1099
- }
1100
- }
1101
- }
1102
-
1103
- // Standard-dir cleanup (#1217): when we're NOT copying standard
1104
- // skills, anything AIWG-named under standardDestDir is a legacy
1105
- // mirror from a rc.13-or-earlier deploy. Prune to clean up.
1106
- let prunedFromStandardDir = pruneMissingStandardSkills(standardDestDir, opts);
1107
- if (
1108
- !copyStandardSkills &&
1109
- standardDestDir &&
1110
- fs.existsSync(standardDestDir) &&
1111
- !opts?.dryRun
1112
- ) {
1113
- for (const entry of fs.readdirSync(standardDestDir, { withFileTypes: true })) {
1114
- if (!entry.isDirectory()) continue;
1115
- const skillMd = path.join(standardDestDir, entry.name, 'SKILL.md');
1116
- if (!fs.existsSync(skillMd)) continue;
1117
- // Only prune skills AIWG manages — bound by the deploy manifest.
1118
- if (!allSkillNames.has(entry.name)) continue;
1119
- const target = path.join(standardDestDir, entry.name);
1120
- try {
1121
- fs.rmSync(target, { recursive: true, force: true });
1122
- prunedFromStandardDir++;
1123
- if (opts?.verbose) console.log(`pruned legacy from standard dir: ${entry.name}`);
1124
- } catch (err) {
1125
- if (opts?.verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
1126
- }
1127
- }
1128
- // Try to remove the now-empty standard dir + its parent .aiwg/
1129
- // wrapper if both end up empty. Best-effort.
1130
- try {
1131
- const remaining = fs.readdirSync(standardDestDir);
1132
- if (remaining.length === 0) {
1133
- fs.rmdirSync(standardDestDir);
1134
- const aiwgWrapper = path.dirname(standardDestDir);
1135
- if (path.basename(aiwgWrapper) === '.aiwg') {
1136
- const wrapperRemaining = fs.readdirSync(aiwgWrapper);
1137
- if (wrapperRemaining.length === 0) fs.rmdirSync(aiwgWrapper);
1138
- }
1139
- }
1140
- } catch { /* non-fatal */ }
1141
- }
1142
-
1143
- return {
1144
- kernel: kernel.length,
1145
- standardCopied,
1146
- prunedFromKernelDir,
1147
- prunedFromStandardDir,
1148
- prunedKernelFromStandardDir,
1149
- };
1150
- }
1151
-
1152
- /**
1153
- * Compute the global desired-kernel set by walking the entire AIWG
1154
- * source tree (frameworks + addons), regardless of which deploy mode
1155
- * is in flight. Used by `pruneStaleAiwgSkills` so cleanup never races
1156
- * with sibling deploy invocations (`aiwg use` runs `deploy-agents.mjs`
1157
- * multiple times — once per framework, once per addon batch).
1158
- *
1159
- * @param {string} srcRoot AIWG repo / install root
1160
- * @returns {string[]|null} basenames of every source skill dir whose
1161
- * SKILL.md frontmatter has `kernel: true`, or `null` when no AIWG
1162
- * framework/addon tree can be located. A `null` return signals the
1163
- * caller (`pruneStaleAiwgSkills`) to SKIP pruning rather than treat an
1164
- * empty set as "delete every AIWG skill" (#123). Mirrors the contract of
1165
- * `computeAllArtifactBasenames` (#1627).
1166
- */
1167
- export function computeAllKernelNames(srcRoot) {
1168
- const hasAiwgTree = (dir) =>
1169
- fs.existsSync(path.join(dir, 'agentic', 'code', 'frameworks')) &&
1170
- fs.existsSync(path.join(dir, 'agentic', 'code', 'addons'));
1171
- const isRootOrSourceDescendant = (candidate, original) => {
1172
- const root = path.resolve(candidate);
1173
- const source = path.resolve(original);
1174
- const agenticCode = path.join(root, 'agentic', 'code');
1175
- return source === root || source === agenticCode || source.startsWith(`${agenticCode}${path.sep}`);
1176
- };
1177
-
1178
- // Prefer an explicit AIWG_ROOT, but only when it actually points at a real
1179
- // AIWG tree — a stale/bogus env value must not silently yield an empty
1180
- // desired set. Otherwise walk up from srcRoot (the caller may pass an
1181
- // addon/framework/project-local-bundle path, not the install root).
1182
- let aiwgRoot = null;
1183
- if (process.env.AIWG_ROOT && hasAiwgTree(process.env.AIWG_ROOT)) {
1184
- aiwgRoot = process.env.AIWG_ROOT;
1185
- } else {
1186
- let cur = path.resolve(srcRoot);
1187
- for (let i = 0; i < 8; i++) {
1188
- if (hasAiwgTree(cur) && isRootOrSourceDescendant(cur, srcRoot)) { aiwgRoot = cur; break; }
1189
- const parent = path.dirname(cur);
1190
- if (parent === cur) break;
1191
- cur = parent;
1192
- }
1193
- }
1194
-
1195
- // No AIWG framework/addon tree found — e.g. deploying a project-local
1196
- // bundle with AIWG_ROOT unset. Return null so the prune is skipped.
1197
- if (!aiwgRoot) return null;
1198
-
1199
- const names = new Set();
1200
- const roots = [
1201
- path.join(aiwgRoot, 'agentic', 'code', 'frameworks'),
1202
- path.join(aiwgRoot, 'agentic', 'code', 'addons'),
1203
- ];
1204
- for (const root of roots) {
1205
- if (!fs.existsSync(root)) continue;
1206
- for (const componentEntry of fs.readdirSync(root, { withFileTypes: true })) {
1207
- if (!componentEntry.isDirectory()) continue;
1208
- const skillsDir = path.join(root, componentEntry.name, 'skills');
1209
- if (!fs.existsSync(skillsDir)) continue;
1210
- for (const skillEntry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
1211
- if (!skillEntry.isDirectory()) continue;
1212
- const fullPath = path.join(skillsDir, skillEntry.name);
1213
- if (isKernelSkill(fullPath)) names.add(skillEntry.name);
1214
- }
1215
- }
1216
- }
1217
- return Array.from(names);
1218
- }
1219
-
1220
- /**
1221
- * Holistic post-deploy cleanup of stale AIWG-managed skills.
1222
- *
1223
- * Run this AFTER all `deploySkills` invocations have completed for a
1224
- * given provider so the desired-name set reflects every kernel skill
1225
- * deployed across all frameworks/addons. Per-call cleanup races because
1226
- * `deploySkills` may be invoked multiple times in one orchestration —
1227
- * this function does the cleanup once at the end.
1228
- *
1229
- * Identifies AIWG-managed skills via:
1230
- * 1. `.aiwg-managed` marker file (preferred — set by `deploySkillDir`)
1231
- * 2. Frontmatter `namespace: aiwg` (migration fallback for pre-marker
1232
- * deploys; stops firing after one redeploy)
1233
- *
1234
- * Bounded to entries identified above, so user-authored skills next to
1235
- * AIWG-managed ones are never touched.
1236
- *
1237
- * @param {string} kernelDestDir absolute path to the platform's kernel
1238
- * skills dir (e.g. `<project>/.claude/skills/`)
1239
- * @param {string[]|null} desiredKernelNames names of every kernel skill that
1240
- * SHOULD remain (basenames of source dirs). When `null` (no AIWG tree
1241
- * located — see `computeAllKernelNames`), pruning is skipped entirely so a
1242
- * project-local-bundle deploy without AIWG_ROOT never empties the kernel
1243
- * skills directory (#123).
1244
- * @param {object} opts `{ dryRun, verbose, artifactExtensions }`
1245
- * @returns {number} count of pruned entries
1246
- */
1247
- export function pruneStaleAiwgSkills(kernelDestDir, desiredKernelNames, opts = {}) {
1248
- if (!kernelDestDir || !fs.existsSync(kernelDestDir)) return 0;
1249
- // No global desired set — skip pruning rather than delete everything (#123).
1250
- if (desiredKernelNames == null) return 0;
1251
- if (opts.dryRun) return 0;
1252
- const desired = new Set(desiredKernelNames);
1253
- let pruned = 0;
1254
- for (const entry of fs.readdirSync(kernelDestDir, { withFileTypes: true })) {
1255
- if (!entry.isDirectory()) continue;
1256
- if (desired.has(entry.name)) continue;
1257
-
1258
- const skillMd = path.join(kernelDestDir, entry.name, 'SKILL.md');
1259
- if (!fs.existsSync(skillMd)) continue;
1260
-
1261
- const marker = path.join(kernelDestDir, entry.name, '.aiwg-managed');
1262
- let isAiwgManaged = fs.existsSync(marker);
1263
- if (!isAiwgManaged) {
1264
- try {
1265
- const content = fs.readFileSync(skillMd, 'utf8');
1266
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
1267
- if (fmMatch && /^\s*namespace:\s*["']?aiwg["']?\s*$/m.test(fmMatch[1])) {
1268
- isAiwgManaged = true;
1269
- }
1270
- } catch { /* unreadable — leave alone */ }
1271
- }
1272
- if (!isAiwgManaged) continue;
1273
-
1274
- try {
1275
- fs.rmSync(path.join(kernelDestDir, entry.name), { recursive: true, force: true });
1276
- pruned++;
1277
- if (opts.verbose) console.log(`pruned stale AIWG skill: ${entry.name}`);
1278
- } catch (err) {
1279
- if (opts.verbose) console.warn(`Warning: could not prune ${entry.name}: ${err.message}`);
1280
- }
1281
- }
1282
- return pruned;
1283
- }
1284
-
1285
- // ============================================================================
1286
- // Flat-File Stale-Artifact Prune (agents / commands / rules) — #1627
1287
- // ============================================================================
1288
-
1289
- /**
1290
- * Reduce a deployed artifact filename to a provider-extension-agnostic stem.
1291
- *
1292
- * Different providers emit the same source rule/agent/command under different
1293
- * extensions (`.md`, `.mdc`, `.agent.md`, `.prompt.md`, `.instructions.md`).
1294
- * Matching by stem lets the stale-prune compare a source basename
1295
- * (`foo.md` → `foo`) against any provider's on-disk form (`foo.agent.md` →
1296
- * `foo`) without hard-coding the per-provider extension map.
1297
- *
1298
- * Strips a trailing `.md`/`.mdc`, then a secondary copilot-style
1299
- * `.agent`/`.prompt`/`.instructions` qualifier.
1300
- *
1301
- * @param {string} name basename
1302
- * @returns {string} extension-agnostic stem
1303
- */
1304
- export function artifactStem(name) {
1305
- return String(name)
1306
- .replace(/\.(md|mdc)$/i, '')
1307
- .replace(/\.(agent|prompt|instructions)$/i, '');
1308
- }
1309
-
1310
- /**
1311
- * Compute the global set of source-basename stems AIWG ships for a flat
1312
- * artifact type, across ALL frameworks and addons (mode-independent).
1313
- *
1314
- * Used as the "desired" set by `pruneStaleAiwgFiles`. Mode independence is
1315
- * deliberate and mirrors `computeAllKernelNames` for skills: `aiwg use sdlc`
1316
- * must not prune a marketing agent that a prior `aiwg use all` deployed and
1317
- * that is still a valid AIWG artifact. Only artifacts whose source no longer
1318
- * exists ANYWHERE in the tree (renamed/removed) fall out of this set and
1319
- * become prune-eligible.
1320
- *
1321
- * Anchors to the AIWG root (resolved by walking up from `srcRoot` for the
1322
- * `agentic/code/frameworks` + `agentic/code/addons` pair, or `AIWG_ROOT`),
1323
- * NOT the raw `srcRoot`. This matters because `deploy-agents.mjs` can be
1324
- * invoked with `--source <project-local-bundle>`; computing the desired set
1325
- * against a bundle dir would be empty and make every AIWG artifact look stale.
1326
- * Returns `null` when no AIWG framework/addon tree is found — the caller MUST
1327
- * then skip pruning (a bundle-only deploy has no global desired set).
1328
- *
1329
- * @param {string} srcRoot AIWG repo / install root (or a subdir of it)
1330
- * @param {'agents'|'commands'|'rules'} type artifact type
1331
- * @returns {Set<string>|null} stems of every source file of that type, or null
1332
- * if the AIWG framework/addon tree can't be located
1333
- */
1334
- export function computeAllArtifactBasenames(srcRoot, type) {
1335
- const aiwgRoot = resolveAiwgRoot(srcRoot);
1336
- if (!aiwgRoot) return null;
1337
-
1338
- const stems = new Set();
1339
- const add = (files) => {
1340
- for (const f of files) stems.add(artifactStem(path.basename(f)));
1341
- };
1342
-
1343
- const frameworkArtifacts = collectFrameworkArtifacts(aiwgRoot, 'all', {
1344
- includeAgents: type === 'agents',
1345
- includeCommands: type === 'commands',
1346
- includeRules: type === 'rules',
1347
- includeSkills: false,
1348
- recursiveCommands: true,
1349
- });
1350
-
1351
- if (type === 'agents') {
1352
- add(frameworkArtifacts.agents);
1353
- // Soul companions live alongside agents and are deployed with them —
1354
- // keep their stems in the desired set so the prune never removes them.
1355
- add(frameworkArtifacts.souls || []);
1356
- add(getAddonAgentFiles(aiwgRoot, [], { includeExplicit: true }));
1357
- } else if (type === 'commands') {
1358
- add(frameworkArtifacts.commands);
1359
- add(getAddonCommandFiles(aiwgRoot, [], { includeExplicit: true }));
1360
- } else if (type === 'rules') {
1361
- add(frameworkArtifacts.rules);
1362
- add(getAddonRuleFiles(aiwgRoot, [], { includeExplicit: true }));
1363
- }
1364
-
1365
- return stems;
1366
- }
1367
-
1368
- /**
1369
- * Resolve the AIWG install/repo root from a possibly-nested srcRoot.
1370
- *
1371
- * Mirrors the walk-up logic in `computeAllKernelNames`: honor `AIWG_ROOT`,
1372
- * else climb up to 8 levels looking for the directory that holds BOTH
1373
- * `agentic/code/frameworks` and `agentic/code/addons`. Returns `null` when
1374
- * no such root is found (e.g. a standalone project-local bundle).
1375
- *
1376
- * @param {string} srcRoot
1377
- * @returns {string|null}
1378
- */
1379
- export function resolveAiwgRoot(srcRoot) {
1380
- const hasTree = (dir) =>
1381
- fs.existsSync(path.join(dir, 'agentic', 'code', 'frameworks')) &&
1382
- fs.existsSync(path.join(dir, 'agentic', 'code', 'addons'));
1383
- const isRootOrSourceDescendant = (candidate, original) => {
1384
- const root = path.resolve(candidate);
1385
- const source = path.resolve(original);
1386
- const agenticCode = path.join(root, 'agentic', 'code');
1387
- return source === root || source === agenticCode || source.startsWith(`${agenticCode}${path.sep}`);
1388
- };
1389
-
1390
- if (process.env.AIWG_ROOT && hasTree(process.env.AIWG_ROOT)) {
1391
- return process.env.AIWG_ROOT;
1392
- }
1393
- let cur = path.resolve(srcRoot);
1394
- for (let i = 0; i < 8; i++) {
1395
- if (hasTree(cur) && isRootOrSourceDescendant(cur, srcRoot)) return cur;
1396
- const parent = path.dirname(cur);
1397
- if (parent === cur) break;
1398
- cur = parent;
1399
- }
1400
- return null;
1401
- }
1402
-
1403
- /**
1404
- * Names of every skill AIWG ships, kernel and standard alike (#2511).
1405
- *
1406
- * `computeAllKernelNames` filters to kernel skills, but skill-command wrappers
1407
- * are generated from both tiers, so retiring an orphaned wrapper needs the full
1408
- * set. Anchored to the AIWG root rather than `srcRoot` for the same reason
1409
- * `computeAllArtifactBasenames` is: a bundle-scoped deploy must not produce an
1410
- * empty desired set and retire everything.
1411
- *
1412
- * @param {string} srcRoot AIWG repo / install root (or a subdir of it)
1413
- * @returns {Set<string>|null} skill directory names, or null when no AIWG tree
1414
- * is found — callers MUST then skip pruning.
1415
- */
1416
- export function computeAllSkillNames(srcRoot) {
1417
- const aiwgRoot = resolveAiwgRoot(srcRoot);
1418
- if (!aiwgRoot) return null;
1419
-
1420
- const names = new Set();
1421
- for (const group of ['frameworks', 'addons']) {
1422
- const root = path.join(aiwgRoot, 'agentic', 'code', group);
1423
- if (!fs.existsSync(root)) continue;
1424
- for (const component of fs.readdirSync(root, { withFileTypes: true })) {
1425
- if (!component.isDirectory()) continue;
1426
- const skillsDir = path.join(root, component.name, 'skills');
1427
- if (!fs.existsSync(skillsDir)) continue;
1428
- for (const skill of fs.readdirSync(skillsDir, { withFileTypes: true })) {
1429
- if (skill.isDirectory()) names.add(skill.name);
1430
- }
1431
- }
1432
- }
1433
- return names;
1434
- }
1435
-
1436
- /**
1437
- * Holistic post-deploy prune of stale AIWG-managed flat artifacts
1438
- * (agents / commands / rules). The flat-file analogue of
1439
- * `pruneStaleAiwgSkills`.
1440
- *
1441
- * Removes a file from `destDir` only when ALL hold:
1442
- * 1. It has an allowed deployed-artifact extension (`.md` / `.mdc` by
1443
- * default; callers may include `.toml`), is not `RULES-INDEX.md`,
1444
- * and not the sidecar manifest.
1445
- * 2. Its stem is NOT in `desiredStems` (the source no longer ships it).
1446
- * 3. It carries an AIWG ownership signal — either a `.aiwg-manifest.json`
1447
- * sidecar entry, or an in-file `aiwg:managed` marker.
1448
- *
1449
- * User-authored files (no ownership signal) and current AIWG artifacts (stem
1450
- * in the desired set) are never touched. Pruned files also have their sidecar
1451
- * entry dropped so the manifest stays accurate.
1452
- *
1453
- * Safe to call on every deploy invocation: `desiredStems` is the global
1454
- * (mode-independent) source set, so sibling-framework files are never
1455
- * collateral.
1456
- *
1457
- * @param {string} destDir absolute path to the provider artifact dir
1458
- * @param {Set<string>|string[]} desiredStems stems that should remain
1459
- * @param {object} opts `{ dryRun, verbose }`
1460
- * @returns {string[]} removed (or would-be-removed) file paths
1461
- */
1462
- export function pruneStaleAiwgFiles(destDir, desiredStems, opts = {}) {
1463
- const { dryRun = false, verbose = false } = opts;
1464
- const artifactExtensions = opts.artifactExtensions || ['.md', '.mdc'];
1465
- // When supplied, skill-command wrappers are retired against the set of skills
1466
- // that still exist rather than exempted outright (#2511). `null`/absent keeps
1467
- // the blanket exemption, so callers without a skill inventory cannot retire a
1468
- // wrapper by accident.
1469
- const skillCommandStems = opts.skillCommandStems instanceof Set
1470
- ? opts.skillCommandStems
1471
- : Array.isArray(opts.skillCommandStems)
1472
- ? new Set(opts.skillCommandStems)
1473
- : null;
1474
- const removed = [];
1475
- if (!destDir || !fs.existsSync(destDir)) return removed;
1476
-
1477
- const desired = desiredStems instanceof Set ? desiredStems : new Set(desiredStems);
1478
- const sidecar = readSidecarManifest(destDir) || { managed: {} };
1479
- const managed = sidecar.managed || {};
1480
- let sidecarDirty = false;
1481
-
1482
- let entries;
1483
- try {
1484
- entries = fs.readdirSync(destDir, { withFileTypes: true });
1485
- } catch {
1486
- return removed;
1487
- }
1488
-
1489
- for (const entry of entries) {
1490
- if (!entry.isFile()) continue;
1491
- const name = entry.name;
1492
- if (name === MANIFEST_FILENAME) continue;
1493
- if (name === 'RULES-INDEX.md') continue;
1494
- if (name === 'RULES-ONDEMAND.md') continue; // generated on-demand index (#1673)
1495
- const lower = name.toLowerCase();
1496
- if (!artifactExtensions.some(extension => lower.endsWith(extension))) continue;
1497
-
1498
- if (desired.has(artifactStem(name))) continue;
1499
-
1500
- // Skill-command wrappers are named after skills, not command sources, so
1501
- // they are absent from the command desired set by construction — pruning
1502
- // them against it would delete wrappers the same deploy just wrote (#2507).
1503
- // They are retired against the skill inventory instead, when one is given
1504
- // (#2511); without one they stay exempt.
1505
- if (managed[name]?.kind === 'skill-command') {
1506
- if (!skillCommandStems || skillCommandStems.has(artifactStem(name))) continue;
1507
- }
1508
-
1509
- // Ownership gate — never delete a file AIWG didn't deploy.
1510
- let owned = Object.prototype.hasOwnProperty.call(managed, name);
1511
- if (!owned) {
1512
- try {
1513
- owned = MANAGED_MARKER_RE.test(fs.readFileSync(path.join(destDir, name), 'utf8'));
1514
- } catch {
1515
- owned = false; // unreadable → leave it alone
1516
- }
1517
- }
1518
- if (!owned) continue;
1519
-
1520
- const target = path.join(destDir, name);
1521
- removed.push(target);
1522
- if (dryRun) {
1523
- if (verbose) console.log(`[dry-run] would prune stale AIWG artifact: ${path.relative(process.cwd(), target)}`);
1524
- continue;
1525
- }
1526
- try {
1527
- fs.unlinkSync(target);
1528
- if (Object.prototype.hasOwnProperty.call(managed, name)) {
1529
- delete managed[name];
1530
- sidecarDirty = true;
1531
- }
1532
- if (verbose) console.log(`pruned stale AIWG artifact: ${path.relative(process.cwd(), target)}`);
1533
- } catch (err) {
1534
- removed.pop();
1535
- if (verbose) console.warn(`Warning: could not prune ${target}: ${err.message}`);
1536
- }
1537
- }
1538
-
1539
- if (sidecarDirty) writeSidecarManifest(destDir, sidecar, dryRun);
1540
- return removed;
1541
- }
1542
-
1543
- /** Source-scoped cleanup also works when a removed standard skill is absent from this deploy's input. */
1544
- function pruneMissingStandardSkills(destDir, opts) {
1545
- if (!destDir || !opts?.srcRoot || opts.dryRun || !fs.existsSync(destDir)) return 0;
1546
- const sourceRoot = path.resolve(opts.srcRoot);
1547
- let pruned = 0;
1548
- for (const entry of fs.readdirSync(destDir, { withFileTypes: true })) {
1549
- if (!entry.isDirectory()) continue;
1550
- const skillDir = path.join(destDir, entry.name);
1551
- const receipt = readSidecarManifest(skillDir);
1552
- if (!receipt?.skillSource || !receipt.managed?.['SKILL.md']) continue;
1553
- const relative = path.relative(sourceRoot, receipt.skillSource);
1554
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) continue;
1555
- try {
1556
- fs.statSync(path.join(receipt.skillSource, 'SKILL.md'));
1557
- continue;
1558
- } catch (error) {
1559
- if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') continue;
1560
- }
1561
- if (releaseSkillOwnership(skillDir, {
1562
- frameworkSlug: receipt.managed['SKILL.md'].frameworkSlug,
1563
- skillSource: receipt.skillSource,
1564
- }, opts)) pruned++;
1565
- }
1566
- return pruned;
1567
- }
1568
-
1569
- /**
1570
- * Deploy a skill directory (copy recursively).
1571
- *
1572
- * Platform handling (controlled by opts.provider):
1573
- * - If the skill's SKILL.md has platforms: [all] → deploy to all, inject [provider] in deployed copy
1574
- * - If no platforms: field → deploy to all, inject [provider] in deployed copy
1575
- * - If explicit restriction list → only deploy if opts.provider is in the list; keep list in deployed copy
1576
- */
1577
- export function deploySkillDir(skillDir, destDir, opts) {
1578
- const { force = false, dryRun = false, provider, transformSkillMd } = opts;
1579
- const verbose = opts.verbose === true;
1580
- const skillName = opts.skillName || path.basename(skillDir);
1581
-
1582
- // Check SKILL.md for explicit platform restriction before deploying anything
1583
- const skillMdPath = path.join(skillDir, 'SKILL.md');
1584
- if (provider && fs.existsSync(skillMdPath)) {
1585
- const skillContent = fs.readFileSync(skillMdPath, 'utf8');
1586
- if (!skillMatchesProvider(skillContent, provider)) {
1587
- if (verbose) console.log(`skip (platform restricted): ${skillName}`);
1588
- return;
1589
- }
1590
- }
1591
-
1592
- const destSkillDir = path.join(destDir, skillName);
1593
- const previous = readSidecarManifest(destSkillDir);
1594
- const frameworkSlug = extractFrameworkSlug(skillMdPath);
1595
- if (!canDeploySkill(previous, skillDir, opts)) return false;
1596
- const managed = {};
1597
- if (!dryRun) ensureDir(destSkillDir);
1598
-
1599
- function copyRecursive(src, dest) {
1600
- const entries = fs.readdirSync(src, { withFileTypes: true });
1601
- for (const entry of entries) {
1602
- const srcPath = path.join(src, entry.name);
1603
- const destPath = path.join(dest, entry.name);
1604
-
1605
- if (entry.isDirectory()) {
1606
- if (!dryRun) ensureDir(destPath);
1607
- copyRecursive(srcPath, destPath);
1608
- } else {
1609
- let srcContent = fs.readFileSync(srcPath, 'utf8');
1610
-
1611
- // Inject target platform into SKILL.md — replaces [all] token with [provider-name]
1612
- if (entry.name === 'SKILL.md' && provider) {
1613
- const platformName = PROVIDER_TO_PLATFORM[provider] || provider;
1614
- srcContent = injectPlatformInContent(srcContent, platformName);
1615
-
1616
- // Provider-specific frontmatter transform (e.g. Factory remaps
1617
- // commandHint.allowedTools / commandHint.model). Optional callback —
1618
- // most providers leave SKILL.md alone after platform injection.
1619
- if (typeof transformSkillMd === 'function') {
1620
- srcContent = transformSkillMd(srcContent, opts) || srcContent;
1621
- }
1622
- }
1623
-
1624
- if (entry.name === 'SKILL.md') srcContent = injectBoundRules(srcContent, srcPath, opts);
1625
-
1626
- const relative = path.relative(destSkillDir, destPath);
1627
- managed[relative] = {
1628
- hash: `sha256:${contentHash(srcContent)}`,
1629
- source: opts.deploySource || 'bundled',
1630
- version: opts.deployVersion || 'unknown',
1631
- ...(frameworkSlug ? { frameworkSlug } : {}),
1632
- };
1633
- if (fs.existsSync(destPath)) {
1634
- const destContent = fs.readFileSync(destPath, 'utf8');
1635
- if (destContent === srcContent && !force) {
1636
- if (verbose) console.log(`skip (unchanged): ${path.relative(destDir, destPath)}`);
1637
- continue;
1638
- }
1639
- }
1640
-
1641
- if (dryRun) {
1642
- console.log(`[dry-run] deploy ${srcPath} -> ${destPath}`);
1643
- } else {
1644
- fs.writeFileSync(destPath, srcContent, 'utf8');
1645
- if (verbose) console.log(`deployed ${entry.name} -> ${path.relative(process.cwd(), destPath)}`);
1646
- }
1647
- }
1648
- }
1649
- }
1650
-
1651
- copyRecursive(skillDir, destSkillDir);
1652
- pruneRecordedSkillFiles(destSkillDir, previous?.managed, new Set(Object.keys(managed)), opts);
1653
- writeSidecarManifest(destSkillDir, { managed, skillSource: path.resolve(skillDir) }, dryRun);
1654
-
1655
- // Drop a `.aiwg-managed` marker so future cleanup runs can identify
1656
- // AIWG-deployed skills regardless of frontmatter shape (some providers
1657
- // strip `namespace:` during transform). Cleanup keys off this presence
1658
- // to safely prune renamed/removed source skills.
1659
- if (!dryRun) {
1660
- try {
1661
- fs.writeFileSync(path.join(destSkillDir, '.aiwg-managed'), 'aiwg\n', 'utf8');
1662
- } catch { /* non-fatal */ }
1663
- }
1664
-
1665
- if (verbose) console.log(`deployed skill: ${skillName}`);
1666
- }
1667
-
1668
- // ============================================================================
1669
- // Workspace Initialization
1670
- // ============================================================================
1671
-
1672
- /**
1673
- * Initialize framework-scoped workspace structure
1674
- * Creates .aiwg/frameworks/{framework-id}/ directories
1675
- */
1676
- export function initializeFrameworkWorkspace(target, mode, dryRun, srcRoot = null) {
1677
- const aiwgBase = resolveFrameworkWorkspaceRoot(target);
1678
- const frameworksDir = path.join(aiwgBase, 'frameworks');
1679
- const sharedDir = path.join(aiwgBase, 'shared');
1680
-
1681
- const frameworkDirs = srcRoot
1682
- ? getFrameworksForMode(srcRoot, mode).map(fw => ({
1683
- id: fw.id,
1684
- path: fw.path,
1685
- subdirs: fw.workspaceSubdirs,
1686
- memoryCreates: Array.isArray(fw.manifest?.memory?.creates) ? fw.manifest.memory.creates : []
1687
- }))
1688
- : [];
1689
-
1690
- // Backward-compatible fallback when source root isn't provided.
1691
- if (frameworkDirs.length === 0) {
1692
- if (mode === 'sdlc' || mode === 'both' || mode === 'all') {
1693
- frameworkDirs.push({
1694
- id: 'sdlc-complete',
1695
- subdirs: ['repo', 'projects', 'working', 'archive']
1696
- });
1697
- }
1698
-
1699
- if (mode === 'marketing' || mode === 'all') {
1700
- frameworkDirs.push({
1701
- id: 'media-marketing-kit',
1702
- subdirs: ['repo', 'campaigns', 'working', 'archive']
1703
- });
1704
- }
1705
-
1706
- if (mode === 'media-curator' || mode === 'all') {
1707
- frameworkDirs.push({
1708
- id: 'media-curator',
1709
- subdirs: ['repo', 'library', 'working', 'archive']
1710
- });
1711
- }
1712
-
1713
- if (mode === 'research' || mode === 'all') {
1714
- frameworkDirs.push({
1715
- id: 'research-complete',
1716
- subdirs: ['repo', 'corpus', 'working', 'archive']
1717
- });
1718
- }
1719
- }
1720
-
1721
- if (frameworkDirs.length === 0) return;
1722
-
1723
- if (dryRun) {
1724
- console.log('\n[dry-run] Would create framework-scoped workspace structure:');
1725
- console.log(`[dry-run] ${aiwgBase}/`);
1726
- console.log(`[dry-run] ${frameworksDir}/`);
1727
- console.log(`[dry-run] ${sharedDir}/`);
1728
- for (const fw of frameworkDirs) {
1729
- for (const subdir of fw.subdirs) {
1730
- console.log(`[dry-run] ${path.join(frameworksDir, fw.id, subdir)}/`);
1731
- }
1732
- for (const entry of fw.memoryCreates || []) {
1733
- if (entry && typeof entry.path === 'string') {
1734
- console.log(`[dry-run] ${path.join(aiwgBase, entry.path.slice('.aiwg/'.length))}${entry.path.endsWith('/') ? '/' : ''}`);
1735
- }
1736
- }
1737
- }
1738
- return;
1739
- }
1740
-
1741
- ensureDir(aiwgBase);
1742
- ensureDir(frameworksDir);
1743
- ensureDir(sharedDir);
1744
-
1745
- for (const fw of frameworkDirs) {
1746
- const fwBase = path.join(frameworksDir, fw.id);
1747
- ensureDir(fwBase);
1748
- for (const subdir of fw.subdirs) {
1749
- ensureDir(path.join(fwBase, subdir));
1750
- }
1751
- initializeMemoryCreates(aiwgBase, fw.path, fw.memoryCreates);
1752
- }
1753
-
1754
- // Initialize registry.json if it doesn't exist
1755
- const registryPath = path.join(frameworksDir, 'registry.json');
1756
- if (!fs.existsSync(registryPath)) {
1757
- const registry = {
1758
- version: '1.0.0',
1759
- created: new Date().toISOString(),
1760
- frameworks: frameworkDirs.map(fw => ({
1761
- id: fw.id,
1762
- installed: new Date().toISOString(),
1763
- version: '1.0.0'
1764
- }))
1765
- };
1766
- fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), 'utf8');
1767
- console.log('Created framework registry at .aiwg/frameworks/registry.json');
1768
- }
1769
- }
1770
-
1771
-
1772
- function initializeMemoryCreates(aiwgBase, frameworkPath, creates) {
1773
- for (const entry of creates || []) {
1774
- if (!entry || typeof entry.path !== 'string') continue;
1775
- if (!entry.path.startsWith('.aiwg/')) continue;
1776
-
1777
- const targetPath = path.join(aiwgBase, entry.path.slice('.aiwg/'.length));
1778
- const isDirectory = entry.path.endsWith('/') || path.extname(entry.path) === '';
1779
- if (isDirectory) {
1780
- ensureDir(targetPath);
1781
- continue;
1782
- }
1783
-
1784
- ensureDir(path.dirname(targetPath));
1785
- if (fs.existsSync(targetPath)) continue;
1786
-
1787
- let content = null;
1788
- if (typeof entry.template === 'string' && frameworkPath) {
1789
- const templatePath = path.join(frameworkPath, entry.template);
1790
- if (fs.existsSync(templatePath)) {
1791
- content = fs.readFileSync(templatePath, 'utf8');
1792
- }
1793
- }
1794
-
1795
- if (content === null) {
1796
- const title = path.basename(entry.path, path.extname(entry.path))
1797
- .replace(/[-_]+/g, ' ')
1798
- .replace(/\b\w/g, c => c.toUpperCase());
1799
- content = '# ' + title + '\n\n';
1800
- }
1801
-
1802
- fs.writeFileSync(targetPath, content.endsWith('\n') ? content : content + '\n', 'utf8');
1803
- }
1804
- }
1805
-
1806
- // ============================================================================
1807
- // AGENTS.md Template Handling
1808
- // ============================================================================
1809
-
1810
- /**
1811
- * Build a Markdown "Repo Topology" block from .aiwg/aiwg.config remotes (#998).
1812
- *
1813
- * Returns an empty string when there's no `remotes` block configured — agents
1814
- * should fall back to the today-default behavior in that case.
1815
- *
1816
- * The output is a small Markdown section suitable for token substitution into
1817
- * AIWG.md / AGENTS.md / similar context files. URL resolution is best-effort:
1818
- * when `git remote get-url <name>` fails (not a git repo, missing remote), the
1819
- * remote name is shown without a URL.
1820
- *
1821
- * @param {string} targetDir - Project directory (the one that owns .aiwg/aiwg.config)
1822
- * @returns {string} Markdown block (with leading/trailing blank lines), or '' when absent
1823
- */
1824
- export function buildRemotesTopologyBlock(targetDir) {
1825
- const cfgPath = path.join(targetDir, '.aiwg', 'aiwg.config');
1826
- if (!fs.existsSync(cfgPath)) return '';
1827
-
1828
- let cfg;
1829
- try {
1830
- cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
1831
- } catch {
1832
- return '';
1833
- }
1834
- if (!cfg || !cfg.remotes) return '';
1835
-
1836
- // Apply the same defaults as resolveRemotes() in src/config/aiwg-config.ts.
1837
- // Inlined here so the deploy path doesn't depend on the compiled TS bundle.
1838
- const primary = cfg.remotes.primary || 'origin';
1839
- const issueTracker = cfg.remotes.issue_tracker || primary;
1840
- const ci = cfg.remotes.ci || primary;
1841
- const secondary = Array.isArray(cfg.remotes.secondary) ? cfg.remotes.secondary : [];
1842
-
1843
- function getUrl(remote) {
1844
- try {
1845
- return boundedExecFileSync('git', ['-C', targetDir, 'remote', 'get-url', '--', remote], 'quick', {
1846
- env: helperEnvironment(),
1847
- stdio: ['ignore', 'pipe', 'ignore'],
1848
- encoding: 'utf8',
1849
- }).trim();
1850
- } catch {
1851
- return '';
1852
- }
1853
- }
1854
-
1855
- const lines = [];
1856
- lines.push('## Repo Topology');
1857
- lines.push('');
1858
- lines.push('Agents: respect this when picking remotes/providers. From `.aiwg/aiwg.config` `remotes` block (#994).');
1859
- lines.push('');
1860
- const primaryUrl = getUrl(primary);
1861
- const primarySuffix = primaryUrl ? ` (${primaryUrl})` : '';
1862
- lines.push(`- **Primary**: \`${primary}\`${primarySuffix} — issues, PRs, CI live here`);
1863
- if (issueTracker !== primary) {
1864
- const u = getUrl(issueTracker);
1865
- lines.push(`- **Issue tracker**: \`${issueTracker}\`${u ? ` (${u})` : ''}`);
1866
- }
1867
- if (ci !== primary) {
1868
- const u = getUrl(ci);
1869
- lines.push(`- **CI**: \`${ci}\`${u ? ` (${u})` : ''}`);
1870
- }
1871
- for (const sec of secondary) {
1872
- if (!sec || !sec.name) continue;
1873
- const u = getUrl(sec.name);
1874
- const purpose = sec.purpose ? ` — ${sec.purpose}` : '';
1875
- const releaseTag = sec.push_on_release ? ' (push tags on release)' : '';
1876
- lines.push(`- **Secondary**: \`${sec.name}\`${u ? ` (${u})` : ''}${purpose}${releaseTag}`);
1877
- }
1878
- lines.push('');
1879
- return lines.join('\n');
1880
- }
1881
-
1882
- /**
1883
- * Substitute the topology + count tokens in template content. Shared by the
1884
- * Claude hook file and createAgentsMdFromTemplate so every consumer gets the
1885
- * same {{REMOTES_TOPOLOGY}} treatment without each provider reinventing it.
1886
- */
1887
- export function interpolateContextTokens(content, opts) {
1888
- const counts = opts?.counts || {};
1889
- const topology = opts?.topology || '';
1890
- const onDemandRules = opts?.onDemandRules || '';
1891
- return content
1892
- .replace(/\{\{AGENTS_COUNT\}\}/g, String(counts.agents || 0))
1893
- .replace(/\{\{COMMANDS_COUNT\}\}/g, String(counts.commands || 0))
1894
- .replace(/\{\{SKILLS_COUNT\}\}/g, String(counts.skills || 0))
1895
- .replace(/\{\{RULES_COUNT\}\}/g, String(counts.rules || 0))
1896
- .replace(/\{\{REMOTES_TOPOLOGY\}\}/g, topology)
1897
- .replace(/\{\{ON_DEMAND_RULES\}\}/g, onDemandRules);
1898
- }
1899
-
1900
- /**
1901
- * Create or update AGENTS.md from template
1902
- * Common logic used by multiple providers
1903
- */
1904
- // Managed-block markers (#1571). The AIWG SDLC section is wrapped in these so
1905
- // every later `aiwg use`/`aiwg refresh` can UPDATE it in place — append-once-and-
1906
- // skip meant existing AGENTS.md bridges never received content updates.
1907
- const AIWG_MD_BEGIN = '<!-- BEGIN AIWG-managed (auto-generated; edits between these markers are overwritten on redeploy) -->';
1908
- const AIWG_MD_END = '<!-- END AIWG-managed -->';
1909
-
1910
- /**
1911
- * Inject/update an AIWG-managed section in a workspace markdown file (AGENTS.md,
1912
- * SOUL.md, …) from a template. Wraps the section in BEGIN/END markers and updates
1913
- * in place on redeploy (no-op if unchanged), preserving operator content outside
1914
- * the markers and migrating legacy unmarked sections. (#1571 / #1572)
1915
- *
1916
- * @param {string} target - directory containing the dest file
1917
- * @param {string} destFilename - e.g. 'AGENTS.md' or 'SOUL.md'
1918
- * @param {string} srcRoot
1919
- * @param {string} templateSubpath - relative to sdlc-complete/templates
1920
- * @param {boolean} dryRun
1921
- * @param {{sectionMarker?: string, legacyHeading?: string}} [opts]
1922
- */
1923
- export function createManagedMdFromTemplate(target, destFilename, srcRoot, templateSubpath, dryRun, opts = {}) {
1924
- const sectionMarker = opts.sectionMarker || '<!-- AIWG SDLC Framework Integration -->';
1925
- const legacyHeading = opts.legacyHeading || '## AIWG SDLC Framework';
1926
- const templatePath = path.join(srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'templates', templateSubpath);
1927
- const destPath = path.join(target, destFilename);
1928
-
1929
- if (!fs.existsSync(templatePath)) {
1930
- console.warn(`${destFilename} template not found at ${templatePath}`);
1931
- return;
1932
- }
1933
-
1934
- let template = fs.readFileSync(templatePath, 'utf8');
1935
- // Token interpolation — gives every template-based provider {{REMOTES_TOPOLOGY}},
1936
- // {{ON_DEMAND_RULES}} (#1675), and the shared count tokens for free. The
1937
- // on-demand list is computed lazily only when the template references it.
1938
- template = interpolateContextTokens(template, {
1939
- topology: buildRemotesTopologyBlock(target),
1940
- onDemandRules: template.includes('{{ON_DEMAND_RULES}}')
1941
- ? renderOnDemandRuleSection(listOnDemandRuleFiles(srcRoot), { heading: '### On-Demand Rules' })
1942
- : '',
1943
- });
1944
-
1945
- // Extract the AIWG section from the template (everything from its section
1946
- // marker onward) and wrap it in managed markers so redeploys can update it.
1947
- const tmplMarker = template.indexOf(sectionMarker);
1948
- const aiwgSection = (tmplMarker !== -1 ? template.slice(tmplMarker) : template).trim();
1949
- const templatePrefix = tmplMarker !== -1 ? template.slice(0, tmplMarker).trim() : '';
1950
- const managedBlock = `${AIWG_MD_BEGIN}\n${aiwgSection}\n${AIWG_MD_END}`;
1951
-
1952
- const write = (content, verb) => {
1953
- if (dryRun) {
1954
- console.log(`[dry-run] Would ${verb} ${destFilename} AIWG-managed section`);
1955
- } else {
1956
- writeContextFileSync(destPath, content, 'utf8');
1957
- console.log(`${verb[0].toUpperCase()}${verb.slice(1)} ${destFilename} AIWG-managed section`);
1958
- }
1959
- };
1960
-
1961
- // 1. Fresh file — write prefix (if any) + managed block.
1962
- if (!fs.existsSync(destPath)) {
1963
- const out = (templatePrefix ? templatePrefix + '\n\n---\n\n' : '') + managedBlock + '\n';
1964
- write(out, 'create');
1965
- return;
1966
- }
1967
-
1968
- const existing = fs.readFileSync(destPath, 'utf8');
1969
- const begIdx = existing.indexOf(AIWG_MD_BEGIN);
1970
- const endIdx = existing.indexOf(AIWG_MD_END);
1971
-
1972
- // 2. Markers present — replace the managed block in place, preserve everything outside.
1973
- if (begIdx !== -1 && endIdx !== -1 && endIdx > begIdx) {
1974
- const updated = existing.slice(0, begIdx) + managedBlock + existing.slice(endIdx + AIWG_MD_END.length);
1975
- if (updated === existing) return; // already current — no-op
1976
- write(updated, 'update');
1977
- return;
1978
- }
1979
-
1980
- // 3. Legacy unmarked AIWG section — migrate to the managed block. The section
1981
- // is always EOF-appended, so the operator prefix is everything before it.
1982
- const legacyMarkerIdx = existing.indexOf(sectionMarker);
1983
- const legacyIdx = legacyMarkerIdx !== -1 ? legacyMarkerIdx : existing.indexOf(legacyHeading);
1984
- if (legacyIdx !== -1) {
1985
- const prefix = existing.slice(0, legacyIdx).replace(/\n+---\s*$/, '').trimEnd();
1986
- write(prefix + '\n\n---\n\n' + managedBlock + '\n', 'migrate');
1987
- return;
1988
- }
1989
-
1990
- // 4. No AIWG section at all — append the managed block.
1991
- write(existing.trimEnd() + '\n\n---\n\n' + managedBlock + '\n', 'append');
1992
- }
1993
-
1994
- /** AGENTS.md bridge — thin wrapper over createManagedMdFromTemplate (#1571). */
1995
- export function createAgentsMdFromTemplate(target, srcRoot, templateSubpath, dryRun) {
1996
- createManagedMdFromTemplate(target, 'AGENTS.md', srcRoot, templateSubpath, dryRun, {
1997
- sectionMarker: '<!-- AIWG SDLC Framework Integration -->',
1998
- legacyHeading: '## AIWG SDLC Framework',
1999
- });
2000
- }
2001
-
2002
- // ============================================================================
2003
- // Agent Filtering
2004
- // ============================================================================
2005
-
2006
- /**
2007
- * Check if an agent should be deployed based on filter options
2008
- * @param {string} agentPath - Path to agent file
2009
- * @param {object} metadata - Parsed frontmatter metadata
2010
- * @param {object} opts - Options including filter and filterRole
2011
- * @returns {boolean} - True if agent should be deployed
2012
- */
2013
- export function shouldDeployAgent(agentPath, metadata, opts) {
2014
- const { filter, filterRole } = opts;
2015
-
2016
- // No filters - deploy everything
2017
- if (!filter && !filterRole) return true;
2018
-
2019
- // Filter by role (model tier)
2020
- if (filterRole) {
2021
- const role = classifyModelRole(metadata.model, { defaultRole: 'coding' });
2022
- if (role !== filterRole.toLowerCase()) {
2023
- return false;
2024
- }
2025
- }
2026
-
2027
- // Filter by glob pattern
2028
- if (filter) {
2029
- const agentName = path.basename(agentPath, '.md');
2030
- if (!matchesGlob(agentName, filter)) {
2031
- return false;
2032
- }
2033
- }
2034
-
2035
- return true;
2036
- }
2037
-
2038
- /**
2039
- * Simple glob pattern matching
2040
- * Supports * (match any characters) and ? (match single character)
2041
- * @param {string} str - String to match
2042
- * @param {string} pattern - Glob pattern
2043
- * @returns {boolean} - True if matches
2044
- */
2045
- export function matchesGlob(str, pattern) {
2046
- // Convert glob to regex
2047
- const regexPattern = pattern
2048
- .replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape regex special chars except * and ?
2049
- .replace(/\*/g, '.*') // * matches any characters
2050
- .replace(/\?/g, '.'); // ? matches single character
2051
-
2052
- const regex = new RegExp(`^${regexPattern}$`, 'i');
2053
- return regex.test(str);
2054
- }
2055
-
2056
- /**
2057
- * Filter a list of agent files based on filter options
2058
- * @param {string[]} files - List of file paths
2059
- * @param {object} opts - Options including filter and filterRole
2060
- * @returns {string[]} - Filtered list of file paths
2061
- */
2062
- export function filterAgentFiles(files, opts) {
2063
- const { filter, filterRole } = opts;
2064
-
2065
- // No filters - return all
2066
- if (!filter && !filterRole) return files;
2067
-
2068
- return files.filter(filePath => {
2069
- // Read and parse frontmatter to get metadata
2070
- const content = fs.readFileSync(filePath, 'utf8');
2071
- const { metadata } = parseFrontmatter(content);
2072
- return shouldDeployAgent(filePath, metadata, opts);
2073
- });
2074
- }
2075
-
2076
- // ============================================================================
2077
- // Framework Discovery
2078
- // ============================================================================
2079
-
2080
- const MODE_ALIASES = {
2081
- writing: 'general',
2082
- mmk: 'marketing'
2083
- };
2084
-
2085
- const LEGACY_FRAMEWORK_MODE_ALIASES = {
2086
- 'sdlc-complete': ['sdlc'],
2087
- 'media-marketing-kit': ['marketing', 'mmk'],
2088
- 'media-curator': ['media-curator'],
2089
- 'research-complete': ['research']
2090
- };
2091
-
2092
- const DEFAULT_FRAMEWORK_SUBDIRS = {
2093
- 'sdlc-complete': ['repo', 'projects', 'working', 'archive'],
2094
- 'media-marketing-kit': ['repo', 'campaigns', 'working', 'archive'],
2095
- 'media-curator': ['repo', 'library', 'working', 'archive'],
2096
- 'research-complete': ['repo', 'corpus', 'working', 'archive']
2097
- };
2098
-
2099
- function normalizePathSegment(segment) {
2100
- return String(segment || '')
2101
- .replace(/^\/+/, '')
2102
- .replace(/\/+$/, '');
2103
- }
2104
-
2105
- function ensureStringArray(value) {
2106
- if (!value) return [];
2107
- return Array.isArray(value) ? value.map(v => String(v)) : [String(value)];
2108
- }
2109
-
2110
- function uniqueLower(values) {
2111
- const seen = new Set();
2112
- const out = [];
2113
- for (const raw of values) {
2114
- const v = String(raw || '').trim().toLowerCase();
2115
- if (!v || seen.has(v)) continue;
2116
- seen.add(v);
2117
- out.push(v);
2118
- }
2119
- return out;
2120
- }
2121
-
2122
- export function normalizeDeploymentMode(mode = 'all') {
2123
- const normalized = String(mode || 'all').toLowerCase();
2124
- return MODE_ALIASES[normalized] || normalized;
2125
- }
2126
-
2127
- function resolveFrameworkComponentDir(frameworkPath, manifest, component) {
2128
- const entry = manifest?.entry?.[component];
2129
- const relPath = normalizePathSegment(entry || component);
2130
- return path.join(frameworkPath, relPath);
2131
- }
2132
-
2133
- /**
2134
- * Discover framework roots under agentic/code/frameworks.
2135
- * Framework metadata is loaded from root manifest.json when present.
2136
- */
2137
- export function discoverFrameworks(srcRoot) {
2138
- const frameworksRoot = path.join(srcRoot, 'agentic', 'code', 'frameworks');
2139
- if (!fs.existsSync(frameworksRoot)) return [];
2140
-
2141
- const frameworks = [];
2142
- const entries = fs.readdirSync(frameworksRoot, { withFileTypes: true })
2143
- .filter(e => e.isDirectory())
2144
- .sort((a, b) => a.name.localeCompare(b.name));
2145
-
2146
- for (const entry of entries) {
2147
- const frameworkPath = path.join(frameworksRoot, entry.name);
2148
- const manifestPath = path.join(frameworkPath, 'manifest.json');
2149
- let manifest = {};
2150
-
2151
- if (fs.existsSync(manifestPath)) {
2152
- try {
2153
- manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
2154
- } catch (e) {
2155
- console.warn(`Warning: Could not parse framework manifest for ${entry.name}: ${e.message}`);
2156
- }
2157
- }
2158
-
2159
- const id = String(manifest.id || manifest.framework || entry.name);
2160
- const aliases = uniqueLower([
2161
- id,
2162
- entry.name,
2163
- ...ensureStringArray(manifest.modeAliases),
2164
- ...ensureStringArray(manifest.aliases),
2165
- ...(LEGACY_FRAMEWORK_MODE_ALIASES[id] || [])
2166
- ]);
2167
-
2168
- const workspaceSubdirs = ensureStringArray(
2169
- manifest.workspace?.subdirs || manifest.workspace?.directories
2170
- );
2171
-
2172
- const agentsDir = resolveFrameworkComponentDir(frameworkPath, manifest, 'agents');
2173
- const commandsDir = resolveFrameworkComponentDir(frameworkPath, manifest, 'commands');
2174
- const skillsDir = resolveFrameworkComponentDir(frameworkPath, manifest, 'skills');
2175
- const rulesDir = resolveFrameworkComponentDir(frameworkPath, manifest, 'rules');
2176
-
2177
- frameworks.push({
2178
- id,
2179
- name: manifest.name || entry.name,
2180
- path: frameworkPath,
2181
- manifest,
2182
- aliases,
2183
- workspaceSubdirs: workspaceSubdirs.length > 0
2184
- ? workspaceSubdirs
2185
- : (DEFAULT_FRAMEWORK_SUBDIRS[id] || ['repo', 'working', 'archive']),
2186
- components: {
2187
- agents: { path: agentsDir, exists: fs.existsSync(agentsDir) },
2188
- commands: { path: commandsDir, exists: fs.existsSync(commandsDir) },
2189
- skills: { path: skillsDir, exists: fs.existsSync(skillsDir) },
2190
- rules: { path: rulesDir, exists: fs.existsSync(rulesDir) }
2191
- }
2192
- });
2193
- }
2194
-
2195
- return frameworks;
2196
- }
2197
-
2198
- /**
2199
- * Select frameworks for a deployment mode.
2200
- */
2201
- export function getFrameworksForMode(srcRoot, mode) {
2202
- const normalizedMode = normalizeDeploymentMode(mode);
2203
- const frameworks = discoverFrameworks(srcRoot);
2204
-
2205
- if (normalizedMode === 'all') return frameworks;
2206
- if (normalizedMode === 'general') return [];
2207
- if (normalizedMode === 'both') {
2208
- return frameworks.filter(fw => fw.aliases.includes('sdlc'));
2209
- }
2210
-
2211
- return frameworks.filter(fw =>
2212
- fw.id.toLowerCase() === normalizedMode || fw.aliases.includes(normalizedMode)
2213
- );
2214
- }
2215
-
2216
- /**
2217
- * Collect framework artifacts for a deployment mode.
2218
- * @param {string} srcRoot - Source root directory
2219
- * @param {string} mode - Deployment mode
2220
- * @param {object} options - Collection options
2221
- * @param {boolean} options.includeAgents - Include agents
2222
- * @param {boolean} options.includeCommands - Include commands
2223
- * @param {boolean} options.includeSkills - Include skills
2224
- * @param {boolean} options.includeRules - Include rules
2225
- * @param {boolean} options.recursiveCommands - Use recursive command listing
2226
- * @param {boolean} options.consolidatedSdlcRules - Use RULES-INDEX for SDLC when available
2227
- * @returns {{frameworks: Array, agents: string[], commands: string[], skills: string[], rules: string[]}}
2228
- */
2229
- export function collectFrameworkArtifacts(srcRoot, mode, options = {}) {
2230
- const {
2231
- includeAgents = true,
2232
- includeCommands = true,
2233
- includeSkills = true,
2234
- includeRules = true,
2235
- recursiveCommands = true,
2236
- consolidatedSdlcRules = true
2237
- } = options;
2238
-
2239
- const frameworks = getFrameworksForMode(srcRoot, mode);
2240
- const artifacts = {
2241
- frameworks,
2242
- agents: [],
2243
- souls: [],
2244
- commands: [],
2245
- skills: [],
2246
- rules: []
2247
- };
2248
-
2249
- for (const framework of frameworks) {
2250
- if (includeAgents && framework.components.agents.exists) {
2251
- artifacts.agents.push(...listMdFiles(framework.components.agents.path));
2252
- artifacts.souls.push(...listSoulFiles(framework.components.agents.path));
2253
- }
2254
-
2255
- if (includeCommands && framework.components.commands.exists) {
2256
- const commandFiles = recursiveCommands
2257
- ? listMdFilesRecursive(framework.components.commands.path)
2258
- : listMdFiles(framework.components.commands.path);
2259
- artifacts.commands.push(...commandFiles);
2260
- }
2261
-
2262
- if (includeSkills && framework.components.skills.exists) {
2263
- artifacts.skills.push(...listSkillDirs(framework.components.skills.path));
2264
- }
2265
-
2266
- if (includeRules && framework.components.rules.exists) {
2267
- if (consolidatedSdlcRules && framework.id === 'sdlc-complete') {
2268
- const indexPath = getRulesIndexPath(srcRoot);
2269
- if (indexPath) {
2270
- artifacts.rules.push(indexPath);
2271
- // PUW-016 (#1117): also include individual rule files referenced
2272
- // by the index. RULES-INDEX.md links to per-rule files; if those
2273
- // files don't ship the links resolve to nowhere. Filter the
2274
- // index file itself out of listMdFiles so it isn't pushed twice.
2275
- const indexBase = indexPath.split('/').pop();
2276
- artifacts.rules.push(
2277
- ...listMdFiles(framework.components.rules.path)
2278
- .filter((f) => !f.endsWith(indexBase))
2279
- .filter(isAlwaysOnRule) // tier gate (#1673)
2280
- );
2281
- continue;
2282
- }
2283
- }
2284
- // tier gate (#1673): inline only always-on (CRITICAL/HIGH) rules
2285
- artifacts.rules.push(...listMdFiles(framework.components.rules.path).filter(isAlwaysOnRule));
2286
- }
2287
- }
2288
-
2289
- return artifacts;
2290
- }
2291
-
2292
- // ============================================================================
2293
- // Addon Discovery
2294
- // ============================================================================
2295
-
2296
- /**
2297
- * Discover all addons in the agentic/code/addons directory
2298
- * @param {string} srcRoot - Source root directory
2299
- * @param {{includeExplicit?: boolean}} [options] - includeExplicit also returns explicitInstall addons
2300
- * @returns {Array<{name: string, path: string, manifest: object}>} - Array of addon info
2301
- */
2302
- export function discoverAddons(srcRoot, { includeExplicit = false } = {}) {
2303
- const addonsDir = path.join(srcRoot, 'agentic', 'code', 'addons');
2304
- if (!fs.existsSync(addonsDir)) return [];
2305
-
2306
- const addons = [];
2307
- for (const entry of fs.readdirSync(addonsDir, { withFileTypes: true })) {
2308
- if (!entry.isDirectory()) continue;
2309
-
2310
- const addonPath = path.join(addonsDir, entry.name);
2311
- const manifestPath = path.join(addonPath, 'manifest.json');
2312
-
2313
- let manifest = {};
2314
- if (fs.existsSync(manifestPath)) {
2315
- try {
2316
- manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
2317
- } catch (e) {
2318
- console.warn(`Warning: Could not parse manifest for addon ${entry.name}: ${e.message}`);
2319
- }
2320
- }
2321
-
2322
- // Skip addons marked devOnly — they are contributor tools, not end-user deployables
2323
- if (manifest.devOnly === true) continue;
2324
- // explicitInstall addons deploy only when named (`aiwg use <addon>`), never
2325
- // as part of a framework or `all` bulk deploy (#2641).
2326
- // The stale-artifact prune passes includeExplicit so a named install's own
2327
- // files stay in its desired set and are not deleted right after deployment.
2328
- if (manifest.explicitInstall === true && !includeExplicit) continue;
2329
-
2330
- addons.push({
2331
- name: entry.name,
2332
- path: addonPath,
2333
- manifest
2334
- });
2335
- }
2336
-
2337
- return addons;
2338
- }
2339
-
2340
- /**
2341
- * Get all agent files from all addons
2342
- * @param {string} srcRoot - Source root directory
2343
- * @param {string[]} excludeAddons - Addon names to exclude (default: none)
2344
- * @returns {string[]} - Array of agent file paths
2345
- */
2346
- export function getAddonAgentFiles(srcRoot, excludeAddons = [], options = {}) {
2347
- const addons = discoverAddons(srcRoot, options);
2348
- const files = [];
2349
-
2350
- for (const addon of addons) {
2351
- if (excludeAddons.includes(addon.name)) continue;
2352
-
2353
- const agentsDir = path.join(addon.path, 'agents');
2354
- if (fs.existsSync(agentsDir)) {
2355
- files.push(...listMdFiles(agentsDir));
2356
- }
2357
- }
2358
-
2359
- return files;
2360
- }
2361
-
2362
- /**
2363
- * Get all command files from all addons
2364
- * @param {string} srcRoot - Source root directory
2365
- * @param {string[]} excludeAddons - Addon names to exclude (default: none)
2366
- * @returns {string[]} - Array of command file paths
2367
- */
2368
- export function getAddonCommandFiles(srcRoot, excludeAddons = [], options = {}) {
2369
- const addons = discoverAddons(srcRoot, options);
2370
- const files = [];
2371
-
2372
- for (const addon of addons) {
2373
- if (excludeAddons.includes(addon.name)) continue;
2374
-
2375
- const commandsDir = path.join(addon.path, 'commands');
2376
- if (fs.existsSync(commandsDir)) {
2377
- files.push(...listMdFiles(commandsDir));
2378
- }
2379
- }
2380
-
2381
- return files;
2382
- }
2383
-
2384
- /**
2385
- * Get skill directories from a direct addon/framework source or all addons
2386
- * @param {string} srcRoot - Source root directory
2387
- * @param {string[]} excludeAddons - Addon names to exclude (default: none)
2388
- * @returns {string[]} - Array of skill directory paths
2389
- */
2390
- export function getAddonSkillDirs(srcRoot, excludeAddons = []) {
2391
- const addons = discoverAddons(srcRoot);
2392
- const dirs = [];
2393
- const directDir = getDirectSourceDir(srcRoot, excludeAddons);
2394
- if (directDir) dirs.push(...listSkillDirs(directDir));
2395
-
2396
- for (const addon of addons) {
2397
- if (excludeAddons.includes(addon.name)) continue;
2398
-
2399
- const skillsDir = path.join(addon.path, 'skills');
2400
- if (fs.existsSync(skillsDir)) {
2401
- dirs.push(...listSkillDirs(skillsDir));
2402
- }
2403
- }
2404
-
2405
- return dirs;
2406
- }
2407
-
2408
- // `aiwg use <addon>` passes the component itself as --source. Keep bulk
2409
- // repository discovery unchanged, even if the repo has a top-level skills/.
2410
- function getDirectSourceDir(srcRoot, excludeAddons) {
2411
- if (fs.existsSync(path.join(srcRoot, 'agentic', 'code')) ||
2412
- excludeAddons.includes(path.basename(path.resolve(srcRoot)))) return null;
2413
- const dir = path.join(srcRoot, 'skills');
2414
- if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return null;
2415
- const relative = path.relative(fs.realpathSync(srcRoot), fs.realpathSync(dir));
2416
- if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
2417
- console.warn(`Warning: Skipping direct skills directory ${dir}: resolves outside source root ${srcRoot}`);
2418
- return null;
2419
- }
2420
- return dir;
2421
- }
2422
-
2423
- /**
2424
- * Get all rule files from all addons
2425
- * @param {string} srcRoot - Source root directory
2426
- * @param {string[]} excludeAddons - Addon names to exclude (default: none)
2427
- * @returns {string[]} - Array of rule file paths
2428
- */
2429
- /**
2430
- * Read a rule's enforcement level from its `enforcement:` frontmatter
2431
- * (#1673). Returns 'critical' | 'high' | 'medium' | 'low' | null.
2432
- */
2433
- export function ruleEnforcementLevel(content) {
2434
- const m = content.match(/^---\n([\s\S]*?)\n---/);
2435
- if (m) {
2436
- const e = m[1].match(/^enforcement:\s*([A-Za-z]+)/m);
2437
- if (e) return e[1].toLowerCase();
2438
- }
2439
- // Rules without frontmatter declare the level in the body header.
2440
- const body = content.match(/^\*\*Enforcement Level\*\*:\s*([A-Za-z]+)/m);
2441
- return body ? body[1].toLowerCase() : null;
2442
- }
2443
-
2444
- /**
2445
- * Default inline rule budget (#2562). Every inlined rule is loaded into every
2446
- * session AND every subagent dispatch, so the always-on set must leave room
2447
- * for the agent definition, the system prompt, and the task itself inside the
2448
- * standard 200K window. 64K tokens (~256 KB) keeps a full CRITICAL+HIGH
2449
- * deployment dispatchable; `AIWG_RULES_INLINE_BUDGET_TOKENS=0` disables the
2450
- * budget, any other value overrides it.
2451
- */
2452
- export function resolveRulesInlineBudgetTokens(env = process.env) {
2453
- return resolveRulesInlineBudget({}, env);
2454
- }
2455
-
2456
- /** Sidecar recording which rules the inline budget moved on demand (#2562). */
2457
- export const RULE_BUDGET_SIDECAR = '.aiwg-rules-budget.json';
2458
-
2459
- export function readRuleBudgetSidecar(destDir) {
2460
- try {
2461
- const parsed = JSON.parse(fs.readFileSync(path.join(destDir, RULE_BUDGET_SIDECAR), 'utf8'));
2462
- if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.demoted)) return null;
2463
- return { budgetTokens: Number(parsed.budgetTokens) || 0, demoted: parsed.demoted.map(String) };
2464
- } catch {
2465
- return null;
2466
- }
2467
- }
2468
-
2469
- // Compatibility exports: budgets never change selection or retain demotions.
2470
- export function reconcileInlineRuleBudget(destDir, budgetTokens, opts = {}) {
2471
- if (!opts.dryRun) fs.rmSync(path.join(destDir, RULE_BUDGET_SIDECAR), { force: true });
2472
- return { demoted: [], removed: [] };
2473
- }
2474
- export function applyInlineRuleBudget(ruleFiles) {
2475
- return { inline: [...(ruleFiles || [])], demoted: [] };
2476
- }
2477
-
2478
- /**
2479
- * Tier gate (#1673, enforcement-tiered deployment ADR). Only CRITICAL and HIGH
2480
- * rules are inlined into a provider's always-on rule directory; MEDIUM/LOW are
2481
- * left on-demand (reachable via `aiwg show rule <name> --body` and the assembled
2482
- * RULES-INDEX pointer index). Index files and rules with no enforcement marker
2483
- * default to always-on, so an un-triaged or structural file is never dropped.
2484
- */
2485
- export function isAlwaysOnRule(filePath) {
2486
- const base = path.basename(filePath);
2487
- if (base === 'RULES-INDEX.md' || base === 'RULES-ONDEMAND.md') return true;
2488
- try {
2489
- const content = fs.readFileSync(filePath, 'utf8');
2490
- const parsed = parseRuleFrontmatter(content);
2491
- if (!parsed.valid) throw new Error(`${filePath}: ${parsed.diagnostics.map(d => d.message).join('; ')}`);
2492
- const activation = parsed.rule.tagged ? parsed.rule.activation : inferRuleActivation(ruleEnforcementLevel(content));
2493
- return activation === 'kernel' || activation === 'paths';
2494
- } catch (error) {
2495
- if (error.code === 'ENOENT') return true;
2496
- throw error;
2497
- }
2498
- }
2499
-
2500
- /**
2501
- * Enumerate MEDIUM/LOW rule files for the whole installed AIWG corpus.
2502
- * `srcRoot` may be the repository root or a bundled framework/addon/extension
2503
- * root during a multi-pass deploy; normalize it before discovery so a later
2504
- * pass never truncates an index written by an earlier pass.
2505
- */
2506
- export function listOnDemandRuleFiles(srcRoot, excludeAddons = []) {
2507
- const out = [];
2508
- const aiwgRoot = resolveAiwgRoot(srcRoot) || srcRoot;
2509
- const consider = (dir) => {
2510
- if (!fs.existsSync(dir)) return;
2511
- for (const f of listMdFiles(dir)) {
2512
- const b = path.basename(f);
2513
- if (b === 'RULES-INDEX.md' || b === 'RULES-ONDEMAND.md') continue;
2514
- const parsed = parseRuleFrontmatter(fs.readFileSync(f, 'utf8'));
2515
- if (!parsed.valid) throw new Error(`${f}: invalid rule frontmatter`);
2516
- if (!parsed.rule.tagged && !isAlwaysOnRule(f)) out.push(f);
2517
- }
2518
- };
2519
- for (const addon of discoverAddons(aiwgRoot)) {
2520
- if (excludeAddons.includes(addon.name)) continue;
2521
- consider(path.join(addon.path, 'rules'));
2522
- }
2523
- const codeRoot = path.join(aiwgRoot, 'agentic', 'code');
2524
- for (const fwDir of ['frameworks', 'extensions']) {
2525
- const base = path.join(codeRoot, fwDir);
2526
- if (!fs.existsSync(base)) continue;
2527
- for (const entry of fs.readdirSync(base, { withFileTypes: true })) {
2528
- if (entry.isDirectory()) consider(path.join(base, entry.name, 'rules'));
2529
- }
2530
- }
2531
- return out;
2532
- }
2533
-
2534
- /**
2535
- * Sorted, de-duplicated rule names (basename minus `.md`) from a list of
2536
- * on-demand rule file paths. Shared by the discrete index writer and the
2537
- * aggregated-bridge section renderer so both stay in lock-step.
2538
- */
2539
- export function onDemandRuleNames(onDemandFiles, exclude = []) {
2540
- const skip = new Set(exclude);
2541
- return [...new Set((onDemandFiles || []).map((f) => path.basename(f).replace(/\.md$/, '')))]
2542
- .filter((n) => !skip.has(n))
2543
- .sort();
2544
- }
2545
-
2546
- /**
2547
- * Render the on-demand rule list as a markdown section (#1675) for aggregated
2548
- * providers whose rules live in a single bridge file (WARP.md, AGENTS.md)
2549
- * rather than a discrete `RULES-ONDEMAND.md`. Returns '' when nothing is
2550
- * on-demand so callers can skip the section entirely. `exclude` drops names
2551
- * already inlined verbatim in the bridge (e.g. Warp's aiwg-utils set).
2552
- */
2553
- export function renderOnDemandRuleSection(onDemandFiles, opts = {}) {
2554
- const names = onDemandRuleNames(onDemandFiles, opts.exclude || []);
2555
- if (names.length === 0) return '';
2556
- const heading = opts.heading || '## On-Demand Rules';
2557
- return [
2558
- heading,
2559
- '',
2560
- 'These MEDIUM/LOW-enforcement rules are not inlined here, to keep the',
2561
- 'always-on context small. They still apply when relevant — fetch any body',
2562
- 'on demand:',
2563
- '',
2564
- '```bash',
2565
- 'aiwg show rule <name> --body',
2566
- '```',
2567
- '',
2568
- ...names.map((n) => `- \`${n}\` — \`aiwg show rule ${n} --body\``),
2569
- ].join('\n');
2570
- }
2571
-
2572
- /**
2573
- * Write a compact on-demand rule index (#1673) into a provider's rule dir.
2574
- * Lists the MEDIUM/LOW rules that are NOT inlined at startup, with the
2575
- * `aiwg show rule <name> --body` fetch hint. Removes a stale index when empty.
2576
- */
2577
- export function writeOnDemandRuleIndex(destDir, onDemandFiles, opts = {}) {
2578
- const indexPath = path.join(destDir, 'RULES-ONDEMAND.md');
2579
- const demotedNames = [...new Set([...onDemandRuleNames(opts.demotedFiles || []), ...(opts.demotedNames || [])])].sort();
2580
- const names = onDemandRuleNames(onDemandFiles, demotedNames);
2581
- if (names.length === 0 && demotedNames.length === 0) {
2582
- try {
2583
- if (fs.existsSync(indexPath) && !opts.dryRun) fs.rmSync(indexPath);
2584
- } catch { /* ignore */ }
2585
- return 0;
2586
- }
2587
- const lines = [
2588
- '# On-Demand Rules (not inlined at startup)',
2589
- '',
2590
- 'These MEDIUM/LOW-enforcement rules are not loaded into every session, to keep',
2591
- 'the standard-context startup budget small. They still apply when relevant —',
2592
- 'fetch any rule body on demand:',
2593
- '',
2594
- '```bash',
2595
- 'aiwg show rule <name> --body',
2596
- '```',
2597
- '',
2598
- ...names.map((n) => `- \`${n}\` — \`aiwg show rule ${n} --body\``),
2599
- '',
2600
- ];
2601
- if (demotedNames.length > 0) {
2602
- // HIGH rules that did not fit the inline budget (#2562). They remain
2603
- // binding; they are fetched on demand so subagent dispatch keeps working.
2604
- lines.push(
2605
- '## Binding rules moved on demand to fit the inline budget',
2606
- '',
2607
- 'These HIGH-enforcement rules still apply in full. They are not inlined because the',
2608
- `always-on rule set would otherwise exceed the ${(opts.inlineBudgetTokens ?? DEFAULT_RULES_INLINE_BUDGET_TOKENS).toLocaleString()}-token inline budget`,
2609
- '(AIWG_RULES_INLINE_BUDGET_TOKENS) and break subagent dispatch with "Prompt is too long".',
2610
- 'Fetch any of them before work they govern:',
2611
- '',
2612
- ...demotedNames.map((n) => `- \`${n}\` — \`aiwg show rule ${n} --body\``),
2613
- '',
2614
- );
2615
- }
2616
- let content = lines.join('\n');
2617
- content = addManagedMarker(content, opts.deployVersion || 'unknown', opts.deploySource || 'bundled');
2618
- if (!opts.dryRun) fs.writeFileSync(indexPath, content, 'utf8');
2619
- return names.length + demotedNames.length;
2620
- }
2621
-
2622
- export function getAddonRuleFiles(srcRoot, excludeAddons = [], options = {}) {
2623
- const addons = discoverAddons(srcRoot, options);
2624
- const files = [];
2625
-
2626
- for (const addon of addons) {
2627
- if (excludeAddons.includes(addon.name)) continue;
2628
-
2629
- const rulesDir = path.join(addon.path, 'rules');
2630
- if (fs.existsSync(rulesDir)) {
2631
- for (const file of listMdFiles(rulesDir)) {
2632
- // Consolidation remains a legacy inventory policy. Explicit activation
2633
- // owns delivery, including the desired set used by the outer prune.
2634
- if (addon.manifest?.consolidation?.deployIndexOnly) {
2635
- const parsed = parseRuleFrontmatter(fs.readFileSync(file, 'utf8'));
2636
- if (!parsed.valid) throw new Error(`${file}: invalid rule frontmatter`);
2637
- if (!parsed.rule.tagged) continue;
2638
- }
2639
- files.push(file);
2640
- }
2641
- }
2642
- }
2643
-
2644
- // Activation selects bodies; only untagged rules use the old severity tier.
2645
- // The deploy enumeration and prune desired set must select the same bodies.
2646
- return files.filter(isAlwaysOnRule);
2647
- }
2648
-
2649
- /**
2650
- * List behavior directories (directories containing BEHAVIOR.md).
2651
- */
2652
- export function listBehaviorDirs(dir) {
2653
- if (!fs.existsSync(dir)) return [];
2654
- return fs
2655
- .readdirSync(dir, { withFileTypes: true })
2656
- .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, 'BEHAVIOR.md')))
2657
- .map((entry) => path.join(dir, entry.name));
2658
- }
2659
-
2660
- /**
2661
- * Collect behavior directories from all supported source shapes:
2662
- * - direct component source: <srcRoot>/behaviors/
2663
- * - cross-framework: agentic/code/behaviors/
2664
- * - per-addon: agentic/code/addons/<name>/behaviors/
2665
- * - per-framework: agentic/code/frameworks/<name>/behaviors/
2666
- */
2667
- export function collectBehaviorDirs(srcRoot) {
2668
- const dirs = [];
2669
- const seen = new Set();
2670
- const addDirs = (items) => {
2671
- for (const dir of items) {
2672
- if (seen.has(dir)) continue;
2673
- seen.add(dir);
2674
- dirs.push(dir);
2675
- }
2676
- };
2677
-
2678
- addDirs(listBehaviorDirs(path.join(srcRoot, 'behaviors')));
2679
- addDirs(listBehaviorDirs(path.join(srcRoot, 'agentic', 'code', 'behaviors')));
2680
-
2681
- const addonsDir = path.join(srcRoot, 'agentic', 'code', 'addons');
2682
- if (fs.existsSync(addonsDir)) {
2683
- for (const entry of fs.readdirSync(addonsDir, { withFileTypes: true })) {
2684
- if (!entry.isDirectory()) continue;
2685
- addDirs(listBehaviorDirs(path.join(addonsDir, entry.name, 'behaviors')));
2686
- }
2687
- }
2688
-
2689
- const frameworksDir = path.join(srcRoot, 'agentic', 'code', 'frameworks');
2690
- if (fs.existsSync(frameworksDir)) {
2691
- for (const entry of fs.readdirSync(frameworksDir, { withFileTypes: true })) {
2692
- if (!entry.isDirectory()) continue;
2693
- addDirs(listBehaviorDirs(path.join(frameworksDir, entry.name, 'behaviors')));
2694
- }
2695
- }
2696
-
2697
- return dirs;
2698
- }
2699
-
2700
- const BEHAVIOR_EMULATION_TARGETS = {
2701
- claude: { dir: '.claude/rules/behaviors', extension: '.md', surface: 'Claude Code rules' },
2702
- codex: { dir: '.codex/rules/behaviors', extension: '.md', surface: 'Codex rules' },
2703
- copilot: { dir: '.github/instructions/aiwg-behaviors', extension: '.instructions.md', surface: 'GitHub Copilot instructions' },
2704
- cursor: { dir: '.cursor/rules/behaviors', extension: '.md', surface: 'Cursor rules' },
2705
- factory: { dir: '.factory/rules/behaviors', extension: '.md', surface: 'Factory rules' },
2706
- opencode: { dir: '.opencode/rule/behaviors', extension: '.md', surface: 'OpenCode rules' },
2707
- warp: { dir: '.warp/rules/behaviors', extension: '.md', surface: 'Warp rules/context surface' },
2708
- windsurf: { dir: '.windsurf/rules/behaviors', extension: '.md', surface: 'Windsurf rules' },
2709
- hermes: { dir: '.hermes/behaviors', extension: '.md', surface: 'Hermes behavior context' },
2710
- };
2711
-
2712
- function renderBehaviorEmulation(behaviorDir, provider, target) {
2713
- const behaviorName = path.basename(behaviorDir);
2714
- const behaviorPath = path.join(behaviorDir, 'BEHAVIOR.md');
2715
- const content = fs.readFileSync(behaviorPath, 'utf8');
2716
- const { metadata } = parseFrontmatter(content);
2717
- const description = metadata?.description || `AIWG behavior ${behaviorName}`;
2718
-
2719
- return `# AIWG Behavior: ${behaviorName}
2720
-
2721
- Provider surface: ${target.surface}
2722
- Provider: ${provider}
2723
- Native source: ${path.relative(process.cwd(), behaviorPath)}
2724
-
2725
- ${description}
2726
-
2727
- This provider does not expose OpenClaw-style native behavior directories. AIWG installs this generated behavior rule so the provider still receives the behavior contract instead of silently skipping it.
2728
-
2729
- ## Activation
2730
-
2731
- Apply this behavior whenever the session, daemon, chat bridge, Mission Control loop, or provider runtime sees a matching trigger from the source behavior metadata. If a trigger cannot be observed natively, treat this file as provider-context guidance for the closest available rule, instruction, hook, or AGENTS-style surface.
2732
-
2733
- ## Source Behavior
2734
-
2735
- \`\`\`markdown
2736
- ${content.trim()}
2737
- \`\`\`
2738
- `;
2739
- }
2740
-
2741
- /**
2742
- * Deploy provider-specific emulated behavior artifacts for providers that do
2743
- * not have a native OpenClaw-style behavior loader.
2744
- */
2745
- export function deployEmulatedBehaviors(behaviorDirs, providerName, targetDir, opts = {}) {
2746
- if (!behaviorDirs || behaviorDirs.length === 0) return 0;
2747
- const provider = providerName === 'openai' ? 'codex' : providerName;
2748
- if (provider === 'openclaw') return 0;
2749
- const target = BEHAVIOR_EMULATION_TARGETS[provider];
2750
- if (!target) {
2751
- if (opts.verbose) console.warn(`No behavior emulation target registered for provider ${provider}`);
2752
- return 0;
2753
- }
2754
-
2755
- const destDir = path.isAbsolute(target.dir) ? target.dir : path.join(targetDir, target.dir);
2756
- ensureDir(destDir, opts.dryRun);
2757
- let count = 0;
2758
-
2759
- for (const behaviorDir of behaviorDirs) {
2760
- const behaviorName = path.basename(behaviorDir);
2761
- const filename = `${behaviorName}${target.extension}`;
2762
- const dest = path.join(destDir, filename);
2763
- const rendered = renderBehaviorEmulation(behaviorDir, provider, target);
2764
- const content = addManagedMarker(rendered, opts.deployVersion || 'unknown', opts.deploySource || 'bundled');
2765
- if (opts.dryRun) {
2766
- console.log(`[dry-run] deploy behavior emulation ${behaviorName} -> ${dest}`);
2767
- } else {
2768
- writeFile(dest, content, false);
2769
- }
2770
- if (opts.verbose) console.log(`deployed behavior emulation ${behaviorName} -> ${path.relative(process.cwd(), dest)}`);
2771
- count++;
2772
- }
2773
-
2774
- return count;
2775
- }
2776
-
2777
- /**
2778
- * Get addon files by category (agents, commands, skills, rules)
2779
- * @param {string} srcRoot - Source root directory
2780
- * @param {object} options - Options
2781
- * @param {string[]} options.excludeAddons - Addon names to exclude
2782
- * @param {boolean} options.includeAgents - Include agent files (default: true)
2783
- * @param {boolean} options.includeCommands - Include command files (default: true)
2784
- * @param {boolean} options.includeSkills - Include skill directories (default: true)
2785
- * @param {boolean} options.includeRules - Include rule files (default: true)
2786
- * @returns {{agents: string[], commands: string[], skills: string[], rules: string[]}}
2787
- */
2788
- export function getAddonFiles(srcRoot, options = {}) {
2789
- const {
2790
- excludeAddons = [],
2791
- includeAgents = true,
2792
- includeCommands = true,
2793
- includeSkills = true,
2794
- includeRules = true
2795
- } = options;
2796
-
2797
- return {
2798
- agents: includeAgents ? getAddonAgentFiles(srcRoot, excludeAddons) : [],
2799
- commands: includeCommands ? getAddonCommandFiles(srcRoot, excludeAddons) : [],
2800
- skills: includeSkills ? getAddonSkillDirs(srcRoot, excludeAddons) : [],
2801
- rules: includeRules ? getAddonRuleFiles(srcRoot, excludeAddons) : []
2802
- };
2803
- }
2804
-
2805
- // ============================================================================
2806
- // Consolidated Rules Deployment
2807
- // ============================================================================
2808
-
2809
- /**
2810
- * Load rules manifest from source directory.
2811
- * Inventory metadata only: delivery is decided by rule `activation` (rule-delivery.mjs);
2812
- * the former manifest `tiers` deploy policy was never consulted and was removed (#3450).
2813
- * @param {string} srcRoot - Source root directory
2814
- * @returns {object|null} - Parsed manifest or null if not found
2815
- */
2816
- export function loadRulesManifest(srcRoot) {
2817
- const manifestPath = path.join(srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'rules', 'manifest.json');
2818
- if (!fs.existsSync(manifestPath)) return null;
2819
- try {
2820
- return JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
2821
- } catch (e) {
2822
- console.warn(`Warning: Could not parse rules manifest: ${e.message}`);
2823
- return null;
2824
- }
2825
- }
2826
-
2827
- /**
2828
- * Group rules by tier
2829
- * @param {Array} rules - Array of rule objects from manifest
2830
- * @returns {{core: Array, sdlc: Array, research: Array}}
2831
- */
2832
- export function groupRulesByTier(rules) {
2833
- const groups = { core: [], sdlc: [], research: [] };
2834
- for (const rule of rules) {
2835
- const tier = rule.tier || 'sdlc';
2836
- if (groups[tier]) {
2837
- groups[tier].push(rule);
2838
- }
2839
- }
2840
- return groups;
2841
- }
2842
-
2843
- /**
2844
- * Group rules by enforcement level within a tier
2845
- * @param {Array} rules - Array of rule objects
2846
- * @returns {{critical: Array, high: Array, medium: Array}}
2847
- */
2848
- export function groupByEnforcement(rules) {
2849
- const groups = { critical: [], high: [], medium: [] };
2850
- for (const rule of rules) {
2851
- const level = (rule.enforcement || 'medium').toLowerCase();
2852
- if (groups[level]) {
2853
- groups[level].push(rule);
2854
- }
2855
- }
2856
- return groups;
2857
- }
2858
-
2859
- /**
2860
- * Get the RULES-INDEX.md path for a component (framework or addon).
2861
- * Checks the component's manifest.json for consolidation.rulesIndex.
2862
- * @param {string} componentPath - Path to the component directory
2863
- * @returns {string|null} - Path to the component's RULES-INDEX.md or null
2864
- */
2865
- export function getComponentRulesIndexPath(componentPath) {
2866
- const manifestPath = path.join(componentPath, 'manifest.json');
2867
- if (!fs.existsSync(manifestPath)) return null;
2868
-
2869
- try {
2870
- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
2871
- const rulesIndex = manifest.consolidation?.rulesIndex;
2872
- if (!rulesIndex) return null;
2873
-
2874
- const indexPath = path.join(componentPath, rulesIndex);
2875
- return fs.existsSync(indexPath) ? indexPath : null;
2876
- } catch (e) {
2877
- return null;
2878
- }
2879
- }
2880
-
2881
- /**
2882
- * Assemble the deployed RULES-INDEX.md from the global template and all
2883
- * installed component indexes.
2884
- *
2885
- * Flow:
2886
- * 1. Read global template from agentic/code/RULES-INDEX.md
2887
- * 2. For each component with consolidation support, read its RULES-INDEX.md
2888
- * 3. Concatenate: global header + component indexes + global quick reference
2889
- *
2890
- * @param {string} srcRoot - Source root directory
2891
- * @returns {string|null} - Assembled content or null if global template missing
2892
- */
2893
- export function assembleRulesIndex(srcRoot) {
2894
- const globalPath = path.join(srcRoot, 'agentic', 'code', 'RULES-INDEX.md');
2895
- if (!fs.existsSync(globalPath)) return null;
2896
-
2897
- const globalContent = fs.readFileSync(globalPath, 'utf8');
2898
-
2899
- // Find the Quick Reference section in the global template
2900
- const qrMarker = '## Quick Reference by Context';
2901
- const qrIndex = globalContent.indexOf(qrMarker);
2902
-
2903
- // Split global into header (before Quick Reference) and footer (Quick Reference + rest)
2904
- let header, footer;
2905
- if (qrIndex >= 0) {
2906
- header = globalContent.substring(0, qrIndex).trimEnd();
2907
- footer = globalContent.substring(qrIndex);
2908
- } else {
2909
- header = globalContent;
2910
- footer = '';
2911
- }
2912
-
2913
- // Collect component indexes
2914
- const componentSections = [];
2915
-
2916
- // 1. Framework indexes (sdlc-complete, etc.)
2917
- const frameworksDir = path.join(srcRoot, 'agentic', 'code', 'frameworks');
2918
- if (fs.existsSync(frameworksDir)) {
2919
- for (const entry of fs.readdirSync(frameworksDir, { withFileTypes: true })) {
2920
- if (!entry.isDirectory()) continue;
2921
- const fwPath = path.join(frameworksDir, entry.name);
2922
- const indexPath = getComponentRulesIndexPath(fwPath);
2923
- if (indexPath) {
2924
- componentSections.push(fs.readFileSync(indexPath, 'utf8').trim());
2925
- }
2926
- }
2927
- }
2928
-
2929
- // 2. Addon indexes
2930
- const addons = discoverAddons(srcRoot);
2931
- for (const addon of addons) {
2932
- const indexPath = getComponentRulesIndexPath(addon.path);
2933
- if (indexPath) {
2934
- componentSections.push(fs.readFileSync(indexPath, 'utf8').trim());
2935
- }
2936
- }
2937
-
2938
- // Assemble: header + component indexes + footer
2939
- const parts = [header];
2940
- if (componentSections.length > 0) {
2941
- parts.push('');
2942
- parts.push(componentSections.join('\n\n'));
2943
- }
2944
- if (footer) {
2945
- parts.push('');
2946
- parts.push(footer);
2947
- }
2948
-
2949
- return parts.join('\n');
2950
- }
2951
-
2952
- /**
2953
- * Get the RULES-INDEX.md file path from source
2954
- * @param {string} srcRoot - Source root directory
2955
- * @returns {string|null} - Path to RULES-INDEX.md or null
2956
- */
2957
- export function getRulesIndexPath(srcRoot) {
2958
- const indexPath = path.join(srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'rules', 'RULES-INDEX.md');
2959
- return fs.existsSync(indexPath) ? indexPath : null;
2960
- }
2961
-
2962
- /**
2963
- * Generate consolidated rules content from manifest for a specific provider.
2964
- * Used by content-injection providers (copilot, warp, windsurf) that need
2965
- * the rules content inline rather than as a file.
2966
- *
2967
- * @param {string} srcRoot - Source root directory
2968
- * @param {string} provider - Provider name (for @-link formatting)
2969
- * @param {string[]} [addonRuleFiles] - Optional addon rule file paths
2970
- * @returns {string|null} - Generated content or null if manifest/index missing
2971
- */
2972
- export function generateConsolidatedRulesContent(srcRoot, provider, addonRuleFiles = []) {
2973
- // Try assembled index first (new multi-component assembly)
2974
- const assembled = assembleRulesIndex(srcRoot);
2975
- if (assembled) {
2976
- let content = assembled;
2977
- // Append any remaining non-consolidated addon rules
2978
- if (addonRuleFiles.length > 0) {
2979
- content += '\n\n---\n\n## Additional Addon Rules\n\n';
2980
- for (const ruleFile of addonRuleFiles) {
2981
- const ruleName = path.basename(ruleFile, '.md');
2982
- content += `- **${ruleName}**: @${path.relative(srcRoot, ruleFile)}\n`;
2983
- }
2984
- }
2985
- return content;
2986
- }
2987
-
2988
- // Fallback: legacy single-index behavior
2989
- const indexPath = getRulesIndexPath(srcRoot);
2990
- if (!indexPath) return null;
2991
-
2992
- let content = fs.readFileSync(indexPath, 'utf8');
2993
-
2994
- if (addonRuleFiles.length > 0) {
2995
- content += '\n\n---\n\n## Addon Rules\n\n';
2996
- for (const ruleFile of addonRuleFiles) {
2997
- const ruleName = path.basename(ruleFile, '.md');
2998
- content += `- **${ruleName}**: @${path.relative(srcRoot, ruleFile)}\n`;
2999
- }
3000
- }
3001
-
3002
- return content;
3003
- }
3004
-
3005
- /**
3006
- * Clean up old individually-deployed rule files from target directory.
3007
- * Removes any .md files that are NOT RULES-INDEX.md.
3008
- *
3009
- * @param {string} rulesDir - Target rules directory
3010
- * @param {object} opts - Options
3011
- * @param {boolean} opts.dryRun - If true, log but don't delete
3012
- * @returns {string[]} - List of removed (or would-be-removed) file paths
3013
- */
3014
- /**
3015
- * Remove stale rule files from a deploy directory before writing fresh ones.
3016
- *
3017
- * Per #1143 + #1117: addon deploys run as separate `deploy-agents.mjs`
3018
- * invocations after the main framework, and the previous "wipe all non-index
3019
- * .md before writing" behavior caused the main framework's rules to be
3020
- * silently destroyed by every subsequent addon deploy (whether or not the
3021
- * addon shipped any rules of its own).
3022
- *
3023
- * The fix: cleanup only fires when the operator explicitly asks via
3024
- * `opts.cleanRules: true`. The deploy-time cleanup is replaced by a
3025
- * dedicated `aiwg refresh --clean-rules` operator flow (follow-up issue).
3026
- *
3027
- * Existing callers that pass `incomingFiles: []` still get a no-op; existing
3028
- * callers that pass nothing get the legacy (now-disabled) cleanup as a no-op
3029
- * by default.
3030
- *
3031
- * @param {string} rulesDir
3032
- * @param {object} opts
3033
- * @param {boolean} [opts.dryRun]
3034
- * @param {boolean} [opts.cleanRules] explicit opt-in to remove stale files
3035
- * @param {string[]} [opts.incomingFiles] when cleanRules=true, only files NOT
3036
- * in this list are removed
3037
- */
3038
- export function cleanupOldRuleFiles(rulesDir, opts = {}) {
3039
- const { dryRun = false, cleanRules = false, incomingFiles } = opts;
3040
- const removed = [];
3041
-
3042
- if (!fs.existsSync(rulesDir)) return removed;
3043
- if (!cleanRules) return removed;
3044
- if (Array.isArray(incomingFiles) && incomingFiles.length === 0) return removed;
3045
-
3046
- // Only `.md` rules are eligible for generic cleanup — `.mdc` (native Cursor
3047
- // rules) and non-rule files (config.json, …) are preserved. AIWG's own legacy
3048
- // `.md`→`.mdc` migration is handled explicitly by the Cursor provider's
3049
- // deployRulesInline (marker-gated), not here, so operator `.mdc` stay safe.
3050
- const incomingBasenames = new Set(
3051
- Array.isArray(incomingFiles)
3052
- ? incomingFiles.map((f) => path.basename(f))
3053
- : []
3054
- );
3055
-
3056
- // Ownership gate (#1627): only AIWG-managed rule files are eligible for
3057
- // removal. A rule the operator dropped into the dir (no sidecar entry, no
3058
- // `aiwg:managed` marker) is preserved even when cleanRules is on.
3059
- const sidecarManaged = readSidecarManifest(rulesDir)?.managed || {};
3060
-
3061
- const entries = fs.readdirSync(rulesDir, { withFileTypes: true });
3062
- for (const entry of entries) {
3063
- if (!entry.isFile()) continue;
3064
- if (!entry.name.toLowerCase().endsWith('.md')) continue;
3065
- if (entry.name === 'RULES-INDEX.md') continue;
3066
- if (entry.name === 'RULES-ONDEMAND.md') continue; // generated on-demand index (#1675) — protected like RULES-INDEX
3067
- if (incomingBasenames.has(entry.name)) continue;
3068
-
3069
- const filePath = path.join(rulesDir, entry.name);
3070
-
3071
- let owned = Object.prototype.hasOwnProperty.call(sidecarManaged, entry.name);
3072
- if (!owned) {
3073
- try {
3074
- owned = MANAGED_MARKER_RE.test(fs.readFileSync(filePath, 'utf8'));
3075
- } catch {
3076
- owned = false; // unreadable → leave it alone
3077
- }
3078
- }
3079
- if (!owned) continue; // user-authored rule — preserve
3080
-
3081
- removed.push(filePath);
3082
-
3083
- if (dryRun) {
3084
- console.log(`[dry-run] would remove old rule: ${entry.name}`);
3085
- } else {
3086
- fs.unlinkSync(filePath);
3087
- console.log(`removed old rule: ${entry.name}`);
3088
- }
3089
- }
3090
-
3091
- if (removed.length > 0) {
3092
- console.log(`cleaned up ${removed.length} old rule file(s) from ${rulesDir}`);
3093
- }
3094
-
3095
- return removed;
3096
- }
3097
-
3098
- /**
3099
- * Migrate commands directory by removing stale AIWG command files before
3100
- * skills deployment.
3101
- *
3102
- * AIWG migrated from commands to skills. If old AIWG command files are left
3103
- * in place alongside newly deployed skills, the provider TUI (e.g. Claude
3104
- * Code's command palette) shows duplicate entries — one from the stale
3105
- * command file and one from the skill. This removes those duplicates.
3106
- *
3107
- * Removal is bounded to AIWG-managed command files (#1627): a command the
3108
- * operator authored (no sidecar entry, no `aiwg:managed` marker) is preserved.
3109
- * Subdirectories and non-command files are left untouched. The directory is
3110
- * removed only if it ends up empty after pruning AIWG files.
3111
- *
3112
- * Home-directory providers (codex, openclaw) are excluded by the caller: their
3113
- * commands paths are shared across all projects and must not be touched.
3114
- *
3115
- * @param {string} commandsDir - Full path to the provider's commands directory
3116
- * @param {object} opts
3117
- * @param {boolean} opts.dryRun - Log but don't delete
3118
- * @param {boolean} opts.skipCommandsMigration - User opted out; warn about duplicates instead
3119
- * @returns {boolean} true if any AIWG command file was removed (or would be in dry-run)
3120
- */
3121
- /**
3122
- * Commands directories already warned about this process. The stale-command
3123
- * condition belongs to the directory, not to each deployed framework/addon, so
3124
- * `aiwg use all` must not repeat it once per unit (#2541).
3125
- */
3126
- const warnedCommandsDirs = new Set();
3127
-
3128
- /**
3129
- * AIWG-managed command filenames in a directory — sidecar entries or files
3130
- * carrying the managed marker. Operator-authored commands and current
3131
- * skill-command wrappers are excluded.
3132
- */
3133
- function listManagedCommandFiles(commandsDir) {
3134
- let entries;
3135
- try {
3136
- entries = fs.readdirSync(commandsDir, { withFileTypes: true });
3137
- } catch {
3138
- return [];
3139
- }
3140
- const sidecar = readSidecarManifest(commandsDir) || { managed: {} };
3141
- const managed = sidecar.managed || {};
3142
- const names = [];
3143
- for (const entry of entries) {
3144
- if (!entry.isFile()) continue;
3145
- if (!entry.name.toLowerCase().endsWith('.md')) continue;
3146
- if (managed[entry.name]?.kind === 'skill-command') continue;
3147
- let owned = Object.prototype.hasOwnProperty.call(managed, entry.name);
3148
- if (!owned) {
3149
- try {
3150
- owned = MANAGED_MARKER_RE.test(fs.readFileSync(path.join(commandsDir, entry.name), 'utf8'));
3151
- } catch {
3152
- owned = false;
3153
- }
3154
- }
3155
- if (owned) names.push(entry.name);
3156
- }
3157
- return names;
3158
- }
3159
-
3160
- export function migrateCommandsDirectory(commandsDir, opts = {}) {
3161
- const { dryRun = false, skipCommandsMigration = false, verbose = false, warnOnSkip = true } = opts;
3162
-
3163
- if (!fs.existsSync(commandsDir)) return false;
3164
-
3165
- const entries = fs.readdirSync(commandsDir, { withFileTypes: true });
3166
- if (entries.length === 0) return false;
3167
-
3168
- if (skipCommandsMigration) {
3169
- // Structural opt-outs (project-local addon bundles) skip the migration because
3170
- // it does not apply to them, not because the operator declined it. Warning
3171
- // there is noise, and it fired once per bundle (#2541).
3172
- if (!warnOnSkip) return false;
3173
-
3174
- const rel = path.relative(process.cwd(), commandsDir);
3175
- // The condition is a property of the directory, not of each deployed unit;
3176
- // emit it once per run no matter how many units pass through.
3177
- const warned = opts.warnedCommandsDirs || warnedCommandsDirs;
3178
- if (warned.has(commandsDir)) return false;
3179
- warned.add(commandsDir);
3180
-
3181
- const stale = listManagedCommandFiles(commandsDir);
3182
- if (stale.length === 0) return false;
3183
-
3184
- console.warn(`\nWarning: commands migration skipped for ${rel}`);
3185
- console.warn(' Duplicate entries may appear in the command palette because these old');
3186
- console.warn(' AIWG command files overlap with newly deployed skills:');
3187
- for (const name of stale) console.warn(` ${path.join(rel, name)}`);
3188
- console.warn(' Resolve automatically by re-running without --skip-commands-migration,');
3189
- console.warn(' or remove them directly:');
3190
- console.warn(` rm ${stale.map((name) => path.join(rel, name)).join(' ')}`);
3191
- return false;
3192
- }
3193
-
3194
- // Bound removal to AIWG-managed command files; preserve operator files.
3195
- const sidecar = readSidecarManifest(commandsDir) || { managed: {} };
3196
- const managed = sidecar.managed || {};
3197
- let sidecarDirty = false;
3198
- const rel = path.relative(process.cwd(), commandsDir);
3199
-
3200
- const managedNames = [];
3201
- for (const entry of entries) {
3202
- if (!entry.isFile()) continue;
3203
- const lower = entry.name.toLowerCase();
3204
- if (!lower.endsWith('.md')) continue; // only command markdown files
3205
- const filePath = path.join(commandsDir, entry.name);
3206
- // Skill-command wrappers ARE the current skill surface, not legacy command
3207
- // files superseded by it. Migrating them away deletes what the same deploy
3208
- // just wrote — and on a kernel-only run, which does not re-translate, they
3209
- // are never restored (#2507).
3210
- if (managed[entry.name]?.kind === 'skill-command') continue;
3211
- let owned = Object.prototype.hasOwnProperty.call(managed, entry.name);
3212
- if (!owned) {
3213
- try {
3214
- owned = MANAGED_MARKER_RE.test(fs.readFileSync(filePath, 'utf8'));
3215
- } catch {
3216
- owned = false;
3217
- }
3218
- }
3219
- if (owned) managedNames.push(entry.name);
3220
- }
3221
-
3222
- if (managedNames.length === 0) return false;
3223
-
3224
- if (dryRun) {
3225
- console.log(`[dry-run] would remove ${managedNames.length} AIWG command file(s) from ${rel}`);
3226
- return true;
3227
- }
3228
-
3229
- for (const name of managedNames) {
3230
- try {
3231
- fs.unlinkSync(path.join(commandsDir, name));
3232
- if (Object.prototype.hasOwnProperty.call(managed, name)) {
3233
- delete managed[name];
3234
- sidecarDirty = true;
3235
- }
3236
- if (verbose) console.log(` removed AIWG command file: ${name}`);
3237
- } catch (err) {
3238
- if (verbose) console.warn(` Warning: could not remove ${name}: ${err.message}`);
3239
- }
3240
- }
3241
-
3242
- if (sidecarDirty) writeSidecarManifest(commandsDir, sidecar, dryRun);
3243
- console.log(` Removed ${managedNames.length} old AIWG command file(s) from ${rel} (now served as skills)`);
3244
-
3245
- // Remove the directory only if AIWG files were the only contents.
3246
- try {
3247
- const remaining = fs.readdirSync(commandsDir).filter((n) => n !== MANIFEST_FILENAME);
3248
- if (remaining.length === 0) {
3249
- fs.rmSync(commandsDir, { recursive: true, force: true });
3250
- }
3251
- } catch { /* non-fatal */ }
3252
-
3253
- return true;
3254
- }
3255
-
3256
- // ============================================================================
3257
- // Provider Interface
3258
- // ============================================================================
3259
-
3260
- /**
3261
- * Base provider interface - all providers should implement these methods
3262
- */
3263
- export const ProviderInterface = {
3264
- name: 'base',
3265
- aliases: [],
3266
-
3267
- // ── Path Configuration ──────────────────────────────────────────────
3268
- // Paths describe native or conventional deployment only. Empty paths mean
3269
- // indexed access via aiwg discover/show, not an unavailable artifact class.
3270
- paths: {
3271
- agents: null,
3272
- commands: null,
3273
- skills: null,
3274
- rules: null
3275
- },
3276
-
3277
- // ── Support Level per Artifact Type ─────────────────────────────────
3278
- // Distinguishes native platform support from AIWG conventional directories.
3279
- // 'native' - Platform natively discovers and uses these files
3280
- // 'conventional' - AIWG directory convention; available for @-mention context loading
3281
- // 'aggregated' - Content included in aggregated file AND deployed as discrete files
3282
- // 'indexed' - Full source body available via aiwg discover/show without a native loader
3283
- support: {
3284
- agents: 'conventional',
3285
- commands: 'conventional',
3286
- skills: 'conventional',
3287
- rules: 'conventional'
3288
- },
3289
-
3290
- // ── Provider Capabilities ───────────────────────────────────────────
3291
- capabilities: {
3292
- skills: false,
3293
- rules: false,
3294
- aggregatedOutput: false,
3295
- yamlFormat: false,
3296
- mdcFormat: false,
3297
- homeDirectoryDeploy: false,
3298
- projectLocalMirror: false
3299
- },
3300
-
3301
- // ── Home Directory Paths (Codex-specific) ───────────────────────────
3302
- // Only populated for providers that deploy to home directory.
3303
- homePaths: {
3304
- commands: null,
3305
- skills: null
3306
- },
3307
-
3308
- // ── Artifact Transformation ─────────────────────────────────────────
3309
- transformAgent(srcPath, content, opts) { return content; },
3310
- transformCommand(srcPath, content, opts) { return content; },
3311
- transformSkill(srcPath, content, opts) { return content; },
3312
- transformRule(srcPath, content, opts) { return content; },
3313
-
3314
- // ── Model Mapping ──────────────────────────────────────────────────
3315
- mapModel(shorthand, modelCfg, modelsConfig) { return shorthand; },
3316
-
3317
- // ── Deployment Functions ────────────────────────────────────────────
3318
- // All four deploy functions are available. Providers override as needed.
3319
- deployAgents(agentFiles, targetDir, opts) {},
3320
- deployCommands(commandFiles, targetDir, opts) {},
3321
- deploySkills(skillDirs, targetDir, opts) {},
3322
- deployRules(ruleFiles, targetDir, opts) {},
3323
-
3324
- // ── Aggregation (for Warp, Windsurf) ────────────────────────────────
3325
- aggregate(artifacts, targetDir, opts) {},
3326
-
3327
- // ── Create/update AGENTS.md ────────────────────────────────────────
3328
- createAgentsMd(target, srcRoot, dryRun) {
3329
- // Override in provider
3330
- },
3331
-
3332
- // ── Post-deployment hook ───────────────────────────────────────────
3333
- async postDeploy(targetDir, opts) {
3334
- // Override in provider if needed
3335
- },
3336
-
3337
- // ── File Extension ────────────────────────────────────────────────
3338
- getFileExtension(type) { return '.md'; }
3339
- };
3340
-
3341
- /** Replace only the generated binding block; keep authored bytes intact. */
3342
- export function replaceBoundRulesBlock(content, rules = []) {
3343
- const clean = content.replace(/\n?<!-- AIWG:bound-rules:start -->[\s\S]*?<!-- AIWG:bound-rules:end -->\n?/g, '');
3344
- if (!rules.length) return clean;
3345
- const unique = [...new Map(rules.map(rule => [rule.name, rule])).values()]
3346
- .sort((a, b) => a.name.localeCompare(b.name));
3347
- return `${clean}${clean.endsWith('\n') ? '' : '\n'}\n<!-- AIWG:bound-rules:start -->\n## Bound rules\n\nRequired reading on every invocation: fetch and follow every bound rule below before starting governed work. A summary or discovery pointer does not discharge this obligation.\n\n${unique.map(rule =>
3348
- `- ${rule.name} — ${rule.summary}\n Fetch and follow before governed work: \`aiwg show rule ${rule.name} --body\`.`
3349
- ).join('\n')}\n<!-- AIWG:bound-rules:end -->\n`;
3350
- }
3351
-
3352
- export function injectBoundRules(content, source, opts = {}) {
3353
- if (!opts.ruleDelivery) return content;
3354
- return replaceBoundRulesBlock(content, opts.ruleDelivery.bindings.get(path.resolve(source)) || []);
3355
- }
3356
-
3357
- /** Rule delivery stages output and guards startup before promotion. Deferred
3358
- * kernel passes leave rule delivery to the final source in the invocation. */
3359
- export async function withRuleDeployment(opts, provider, deploy) {
3360
- if (opts.kernelOnly && opts.deferRuleProjection && provider.name !== 'warp'
3361
- && !globalThis[Symbol.for('aiwg.provider-preparation-hook.v1')]) return deploy(opts);
3362
- const { deployWithRuleDelivery } = await import('./rule-delivery.mjs');
3363
- return deployWithRuleDelivery(opts, provider, deploy);
3364
- }
1
+ // Stable public facade for focused provider deployment utilities.
2
+ export { DEFAULT_RULES_INLINE_BUDGET_TOKENS, parseRuleFrontmatter as parseRuleActivation, extractFrameworkSlug, sameSkillOwner, pruneRecordedSkillFiles, releaseSkillOwnership } from './base-runtime.mjs';
3
+ export { ensureDir, resolveFrameworkWorkspaceRoot, listMdFiles, listSoulFiles, listMdFilesRecursive, listSkillDirs, writeFile, addManagedMarker, contentHash, readSidecarManifest, writeSidecarManifest, updateSidecarManifest } from './base-files.mjs';
4
+ export { loadModelConfig, loadRuntimeModelCatalog, parseSkillPlatforms, skillMatchesProvider, injectPlatformInContent, stripTriggersFromContent, stripPlatformsFromContent } from './base-models-platforms.mjs';
5
+ export { parseFrontmatter, stringifyFrontmatter, toKebabCase, stripJsonComments, inferAgentCategory, parseTools, filterCommandsAgainstSkills } from './base-frontmatter.mjs';
6
+ export { deployFiles, deploySoulCompanions } from './base-flat-artifacts.mjs';
7
+ export { isKernelSkill, deploySkillsWithKernelRouting, computeAllKernelNames, pruneStaleAiwgSkills } from './base-kernel-skills.mjs';
8
+ export { artifactStem, computeAllArtifactBasenames, resolveAiwgRoot, computeAllSkillNames, pruneStaleAiwgFiles } from './base-inventory.mjs';
9
+ export { deploySkillDir, initializeFrameworkWorkspace } from './base-skill-copy.mjs';
10
+ export { buildRemotesTopologyBlock, interpolateContextTokens, createManagedMdFromTemplate, createAgentsMdFromTemplate } from './base-context.mjs';
11
+ export { shouldDeployAgent, matchesGlob, filterAgentFiles, normalizeDeploymentMode, discoverFrameworks, getFrameworksForMode, collectFrameworkArtifacts } from './base-framework-discovery.mjs';
12
+ export { discoverAddons, getAddonAgentFiles, getAddonCommandFiles, getAddonSkillDirs } from './base-addon-discovery.mjs';
13
+ export { ruleEnforcementLevel, resolveRulesInlineBudgetTokens, RULE_BUDGET_SIDECAR, readRuleBudgetSidecar, reconcileInlineRuleBudget, applyInlineRuleBudget, isAlwaysOnRule, listOnDemandRuleFiles, onDemandRuleNames, renderOnDemandRuleSection, writeOnDemandRuleIndex, getAddonRuleFiles, loadRulesManifest, groupRulesByTier, groupByEnforcement, getComponentRulesIndexPath, assembleRulesIndex, getRulesIndexPath, generateConsolidatedRulesContent } from './base-rule-index.mjs';
14
+ export { listBehaviorDirs, collectBehaviorDirs, deployEmulatedBehaviors, getAddonFiles } from './base-behaviors.mjs';
15
+ export { cleanupOldRuleFiles, migrateCommandsDirectory } from './base-migrations.mjs';
16
+ export { ProviderInterface, replaceBoundRulesBlock, injectBoundRules, withRuleDeployment } from './base-contract.mjs';