@aiwg/cli 2026.10.16 → 2026.10.18

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 (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,252 @@
1
+ // Shared provider files utilities.
2
+ import { mergeArtifactOwnership } from './base-runtime.mjs';
3
+ import { createHash, fs, os, path } from './base-runtime.mjs';
4
+
5
+
6
+ // ============================================================================
7
+ // File Operations
8
+ // ============================================================================
9
+
10
+ /**
11
+ * Ensure a directory exists, creating it recursively if needed
12
+ * @param {string} d - Directory path
13
+ * @param {boolean} dryRun - If true, skip actual directory creation
14
+ */
15
+ export function ensureDir(d, dryRun = false) {
16
+ if (dryRun) return;
17
+ if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
18
+ }
19
+
20
+
21
+ export const PROJECT_ARTIFACT_ENV_KEYS = [
22
+ 'AIWG_ARTIFACTS_PATH',
23
+ 'AIWG_PROJECT_ARTIFACTS_PATH',
24
+ 'AIWG_PROJECT_AIWG_DIR',
25
+ ];
26
+
27
+
28
+ export function expandProjectArtifactPath(value, projectDir) {
29
+ const trimmed = value.trim();
30
+ if (trimmed === '~') return os.homedir();
31
+ if (trimmed.startsWith('~/')) return path.resolve(os.homedir(), trimmed.slice(2));
32
+ return path.isAbsolute(trimmed) ? trimmed : path.resolve(projectDir, trimmed);
33
+ }
34
+
35
+
36
+ export function parseProjectArtifactLocation(contents) {
37
+ for (const rawLine of contents.split(/\r?\n/)) {
38
+ let line = rawLine.trim();
39
+ if (!line || line.startsWith('#')) continue;
40
+ if (line.startsWith('export ')) line = line.slice('export '.length).trim();
41
+ const assignment = line.match(/^AIWG_ARTIFACTS_PATH\s*=\s*(.+)$/);
42
+ if (assignment) line = assignment[1].trim();
43
+ if ((line.startsWith('"') && line.endsWith('"')) || (line.startsWith("'") && line.endsWith("'"))) {
44
+ line = line.slice(1, -1);
45
+ }
46
+ return line || null;
47
+ }
48
+ return null;
49
+ }
50
+
51
+
52
+ /** Resolve the artifact corpus root used for framework-generated workspace data. */
53
+ export function resolveFrameworkWorkspaceRoot(projectDir, env = process.env) {
54
+ for (const key of PROJECT_ARTIFACT_ENV_KEYS) {
55
+ const value = env[key];
56
+ if (typeof value === 'string' && value.trim()) return expandProjectArtifactPath(value, projectDir);
57
+ }
58
+ const pointer = path.join(projectDir, '.aiwg-location');
59
+ if (fs.existsSync(pointer)) {
60
+ const configured = parseProjectArtifactLocation(fs.readFileSync(pointer, 'utf8'));
61
+ if (configured) return expandProjectArtifactPath(configured, projectDir);
62
+ }
63
+ return path.join(projectDir, '.aiwg');
64
+ }
65
+
66
+
67
+ /**
68
+ * List markdown files in a directory (non-recursive)
69
+ */
70
+ export function listMdFiles(dir, excludePatterns = []) {
71
+ if (!fs.existsSync(dir)) return [];
72
+ const defaultExcluded = ['README.md', 'manifest.md', 'agent-template.md', 'openai-compat.md', 'factory-compat.md', 'windsurf-compat.md', 'DEVELOPMENT_GUIDE.md'];
73
+ const excluded = [...defaultExcluded, ...excludePatterns];
74
+ return fs
75
+ .readdirSync(dir, { withFileTypes: true })
76
+ .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))
77
+ .map((e) => path.join(dir, e.name));
78
+ }
79
+
80
+
81
+ /**
82
+ * List .soul.md companion files in a directory (non-recursive)
83
+ */
84
+ export function listSoulFiles(dir) {
85
+ if (!fs.existsSync(dir)) return [];
86
+ return fs
87
+ .readdirSync(dir, { withFileTypes: true })
88
+ .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.soul.md'))
89
+ .map((e) => path.join(dir, e.name));
90
+ }
91
+
92
+
93
+ /**
94
+ * List markdown files recursively
95
+ */
96
+ export function listMdFilesRecursive(dir, excludePatterns = []) {
97
+ if (!fs.existsSync(dir)) return [];
98
+ const defaultExcluded = ['README.md', 'manifest.md', 'agent-template.md', 'openai-compat.md', 'factory-compat.md', 'windsurf-compat.md', 'DEVELOPMENT_GUIDE.md'];
99
+ const excluded = [...defaultExcluded, ...excludePatterns];
100
+ const results = [];
101
+
102
+ function scan(currentDir) {
103
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
104
+ for (const entry of entries) {
105
+ const fullPath = path.join(currentDir, entry.name);
106
+ if (entry.isDirectory() && entry.name !== 'templates') {
107
+ scan(fullPath);
108
+ } else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md') && !excluded.includes(entry.name)) {
109
+ results.push(fullPath);
110
+ }
111
+ }
112
+ }
113
+
114
+ scan(dir);
115
+ return results;
116
+ }
117
+
118
+
119
+ /**
120
+ * List skill directories (directories containing SKILL.md)
121
+ */
122
+ export function listSkillDirs(dir) {
123
+ if (!fs.existsSync(dir)) return [];
124
+ return fs
125
+ .readdirSync(dir, { withFileTypes: true })
126
+ .filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'SKILL.md')))
127
+ .map((e) => path.join(dir, e.name));
128
+ }
129
+
130
+
131
+ /**
132
+ * Write a file (with dry-run support)
133
+ */
134
+ export function writeFile(dest, data, dryRun) {
135
+ if (dryRun) {
136
+ console.log(`[dry-run] write ${dest}`);
137
+ } else {
138
+ fs.writeFileSync(dest, data, 'utf8');
139
+ }
140
+ }
141
+
142
+
143
+ // ============================================================================
144
+ // Deployment Manifest (File Ownership Tagging)
145
+ // ============================================================================
146
+
147
+ // Match either form so legacy-marker files are recognized as already-managed:
148
+ // <!-- aiwg:managed v... ... (legacy, line 1, breaks YAML frontmatter parsing)
149
+ // # aiwg:managed v... ... (current, inside frontmatter as a YAML comment)
150
+ export const MANAGED_MARKER_RE = /^(?:<!-- aiwg:managed |# aiwg:managed )/m;
151
+
152
+ export const MANIFEST_FILENAME = '.aiwg-manifest.json';
153
+
154
+
155
+ /**
156
+ * Add an `aiwg:managed vVERSION SOURCE` marker to deployed markdown content.
157
+ *
158
+ * For files with YAML frontmatter (start with `---\n`), inject the marker as
159
+ * a YAML comment INSIDE the frontmatter. This keeps `---` on line 1, which
160
+ * Claude Code (and other YAML frontmatter parsers) require to discover
161
+ * agents/skills/commands. Issue #1059.
162
+ *
163
+ * For files without frontmatter, fall back to the legacy HTML-comment-at-top
164
+ * form (no parser to break).
165
+ *
166
+ * Idempotent — skips if either form of the marker is already present.
167
+ */
168
+ export function addManagedMarker(content, version, source, style = 'markdown') {
169
+ if (MANAGED_MARKER_RE.test(content)) return content;
170
+ if (style === 'line-comment') {
171
+ return `# aiwg:managed v${version} ${source}\n${content}`;
172
+ }
173
+ // Frontmatter present → inject as YAML comment after the opening `---\n`.
174
+ if (content.startsWith('---\n')) {
175
+ return content.replace(
176
+ /^---\n/,
177
+ `---\n# aiwg:managed v${version} ${source}\n`
178
+ );
179
+ }
180
+ // No frontmatter → legacy HTML-comment-at-top form is safe.
181
+ return `<!-- aiwg:managed v${version} ${source} -->\n${content}`;
182
+ }
183
+
184
+
185
+ /**
186
+ * Compute SHA-256 hash of content (hex string).
187
+ */
188
+ export function contentHash(content) {
189
+ return createHash('sha256').update(content).digest('hex');
190
+ }
191
+
192
+
193
+ /**
194
+ * Read existing sidecar manifest from a deployment directory.
195
+ * Returns `{ managed: { [filename]: { hash, source, version } } }` or null.
196
+ */
197
+ export function readSidecarManifest(dir) {
198
+ const p = path.join(dir, MANIFEST_FILENAME);
199
+ try {
200
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+
206
+
207
+ /**
208
+ * Write sidecar manifest to a deployment directory.
209
+ */
210
+ export function writeSidecarManifest(dir, manifest, dryRun) {
211
+ if (dryRun) return;
212
+ const p = path.join(dir, MANIFEST_FILENAME);
213
+ const previous = readSidecarManifest(dir);
214
+ for (const [name, record] of Object.entries(manifest.managed || {})) {
215
+ const prior = previous?.managed?.[name];
216
+ const owner = record.frameworkSlug;
217
+ if (owner) manifest.managed[name] = mergeArtifactOwnership(prior, record, owner);
218
+ else if (prior?.hash === record.hash) manifest.managed[name] = { ...prior, ...record };
219
+ }
220
+ fs.writeFileSync(p, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
221
+ }
222
+
223
+
224
+ /**
225
+ * Update sidecar manifest entries for a batch of deployed files.
226
+ * Merges into existing manifest if present.
227
+ *
228
+ * `frameworkSlug` (optional, per-entry) records which AIWG framework
229
+ * the file came from (e.g., 'forensics-complete', 'sdlc-complete').
230
+ * Used by the cross-framework collision guard (#1169) to detect
231
+ * silent overwrites when two frameworks ship a file with the same
232
+ * filename but different content.
233
+ */
234
+ export function updateSidecarManifest(dir, deployedEntries, opts) {
235
+ const { dryRun = false, version = 'unknown', source = 'bundled' } = opts;
236
+ const existing = readSidecarManifest(dir) || { managed: {} };
237
+
238
+ for (const entry of deployedEntries) {
239
+ const { filename, hash, frameworkSlug, kind, sourcePath } = entry;
240
+ const prior = existing.managed[filename];
241
+ const digest = `sha256:${hash}`;
242
+ const sidecarEntry = { ...(prior?.hash === digest ? prior : {}), hash: digest, source, version };
243
+ if (sourcePath) sidecarEntry.sourcePath = sourcePath;
244
+ if (frameworkSlug) sidecarEntry.frameworkSlug = frameworkSlug;
245
+ // `kind` marks artifacts whose lifecycle is governed elsewhere — currently
246
+ // only `skill-command` wrappers, which follow their source skill (#2507).
247
+ if (kind) sidecarEntry.kind = kind;
248
+ existing.managed[filename] = frameworkSlug ? mergeArtifactOwnership(prior, sidecarEntry, frameworkSlug) : sidecarEntry;
249
+ }
250
+
251
+ writeSidecarManifest(dir, existing, dryRun);
252
+ }
@@ -0,0 +1,233 @@
1
+ // Shared provider flat artifacts utilities.
2
+ import { addManagedMarker, contentHash, readSidecarManifest, updateSidecarManifest, writeFile } from './base-files.mjs';
3
+ import { extractFrameworkSlug, fs, path } from './base-runtime.mjs';
4
+ import { injectBoundRules } from './base-contract.mjs';
5
+ import { PROVIDER_TO_PLATFORM, injectPlatformInContent, stripTriggersFromContent } from './base-models-platforms.mjs';
6
+ import { shouldReportDeployCollisions } from './base-frontmatter.mjs';
7
+
8
+
9
+ // ============================================================================
10
+ // File Deployment
11
+ // ============================================================================
12
+
13
+ /**
14
+ * Deploy files to destination directory
15
+ * Handles transformation via provider's transform function
16
+ */
17
+ export function deployFiles(files, destDir, opts, transformFn) {
18
+ const { force = false, dryRun = false, provider = 'claude', fileExtension = '.md', injectPlatform = false } = opts;
19
+ const deployVersion = opts.deployVersion || 'unknown';
20
+ const deploySource = opts.deploySource || 'bundled';
21
+ // Map of dest path → first batch entry that claimed it. Used to detect
22
+ // and report cross-framework collisions within a single deploy batch
23
+ // (#1169). Each value: { src, frameworkSlug }
24
+ const seen = new Map();
25
+ const actions = [];
26
+ // Collision report — one entry per detected cross-framework collision
27
+ // (within-batch or against sidecar). Surfaced after the loop.
28
+ const collisions = [];
29
+
30
+ // Read sidecar manifest for hash-based skip-on-match (#749) and
31
+ // cross-framework collision detection (#1169)
32
+ const sidecar = readSidecarManifest(destDir);
33
+ const sidecarManaged = sidecar?.managed || {};
34
+
35
+ for (const f of files) {
36
+ let base = path.basename(f);
37
+
38
+ // Change extension if needed
39
+ if (fileExtension !== '.md' && base.endsWith('.md')) {
40
+ base = base.replace(/\.md$/, fileExtension);
41
+ }
42
+
43
+ let dest = path.join(destDir, base);
44
+ const currentFrameworkSlug = extractFrameworkSlug(opts.logicalInputPath?.(f) || f);
45
+
46
+ // Read and transform source content (needed for content-equality check
47
+ // and the collision-vs-duplicate distinction)
48
+ const srcContent = injectBoundRules(fs.readFileSync(f, 'utf8'), f, opts);
49
+ let transformedContent = transformFn ? transformFn(f, srcContent, opts) : srcContent;
50
+
51
+ // Rule triggers are index metadata, not something the reading agent needs.
52
+ // Keyed on the source path so every provider's rule deploy gets it without
53
+ // eight call sites opting in, and so skill triggers are never touched (#2544).
54
+ if (/(?:^|[\\/])rules[\\/][^\\/]+$/.test(f)) {
55
+ transformedContent = stripTriggersFromContent(transformedContent);
56
+ }
57
+
58
+ // Inject target platform into agent .md files that use platforms: [all]
59
+ if (injectPlatform && provider && /platforms:\s*\[all\]/.test(transformedContent)) {
60
+ const platformName = PROVIDER_TO_PLATFORM[provider] || provider;
61
+ transformedContent = injectPlatformInContent(transformedContent, platformName);
62
+ }
63
+
64
+ // Add managed marker for provider artifacts (#749). TOML accepts `#`
65
+ // comments, which lets doctor attribute transformed Codex agents even
66
+ // though their YAML frontmatter is removed during serialization.
67
+ if (base.endsWith('.md') || base.endsWith('.mdc')) {
68
+ transformedContent = addManagedMarker(transformedContent, deployVersion, deploySource);
69
+ } else if (base.endsWith('.toml')) {
70
+ transformedContent = addManagedMarker(
71
+ transformedContent,
72
+ deployVersion,
73
+ deploySource,
74
+ 'line-comment',
75
+ );
76
+ }
77
+
78
+ // Compute content hash for sidecar comparison
79
+ const hash = contentHash(transformedContent);
80
+
81
+ // Within-batch collision check (#1169). If a previous file in this
82
+ // batch already claimed this dest, distinguish:
83
+ // - Same content (transform/normalize is idempotent) → silent skip
84
+ // - Same framework + different content → "duplicate" (legacy reason)
85
+ // - Different framework + different content → "collision"
86
+ if (seen.has(dest)) {
87
+ const prev = seen.get(dest);
88
+ const prevContent = prev.transformedContent;
89
+ if (prevContent === transformedContent) {
90
+ actions.push({ type: 'skip', src: f, dest, reason: 'duplicate-identical', hash, frameworkSlug: currentFrameworkSlug });
91
+ continue;
92
+ }
93
+ const prevSlug = prev.frameworkSlug;
94
+ if (currentFrameworkSlug && prevSlug && currentFrameworkSlug !== prevSlug) {
95
+ // Cross-framework collision within a single deploy batch — first
96
+ // wins; second is skipped. `--force` keeps the first entry too,
97
+ // since we have no principled way to pick a winner among peers.
98
+ collisions.push({
99
+ dest,
100
+ filename: base,
101
+ existingFramework: prevSlug,
102
+ existingSrc: prev.src,
103
+ incomingFramework: currentFrameworkSlug,
104
+ incomingSrc: f,
105
+ scope: 'within-batch',
106
+ });
107
+ actions.push({
108
+ type: 'skip',
109
+ src: f,
110
+ dest,
111
+ reason: 'collision',
112
+ collidingFramework: prevSlug,
113
+ });
114
+ continue;
115
+ }
116
+ actions.push({ type: 'skip', src: f, dest, reason: 'duplicate' });
117
+ continue;
118
+ }
119
+
120
+ // Skip-on-match: compare hash against sidecar manifest before reading dest file (#749)
121
+ // Guard: only skip if the destination file still exists on disk. cleanupOldRuleFiles
122
+ // may have deleted it before deployFiles runs, so the sidecar record is stale.
123
+ if (!force && sidecarManaged[base]?.hash === `sha256:${hash}` && fs.existsSync(dest)) {
124
+ const verified = contentHash(fs.readFileSync(dest)) === hash;
125
+ actions.push({ type: 'skip', src: f, dest, reason: 'hash-match', ...(verified ? { hash, frameworkSlug: currentFrameworkSlug } : {}) });
126
+ seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
127
+ continue;
128
+ }
129
+
130
+ // Cross-batch collision check against sidecar (#1169). If the dest
131
+ // file is already managed by a *different* framework than this deploy,
132
+ // and the new content differs, refuse to silently overwrite.
133
+ if (
134
+ !force &&
135
+ fs.existsSync(dest) &&
136
+ sidecarManaged[base]?.frameworkSlug &&
137
+ currentFrameworkSlug &&
138
+ sidecarManaged[base].frameworkSlug !== currentFrameworkSlug
139
+ ) {
140
+ const destContent = fs.readFileSync(dest, 'utf8');
141
+ if (destContent !== transformedContent) {
142
+ collisions.push({
143
+ dest,
144
+ filename: base,
145
+ existingFramework: sidecarManaged[base].frameworkSlug,
146
+ existingSrc: null,
147
+ incomingFramework: currentFrameworkSlug,
148
+ incomingSrc: f,
149
+ scope: 'cross-batch',
150
+ });
151
+ actions.push({
152
+ type: 'skip',
153
+ src: f,
154
+ dest,
155
+ reason: 'collision',
156
+ collidingFramework: sidecarManaged[base].frameworkSlug,
157
+ });
158
+ // Don't claim the dest in `seen` — we did not deploy. The sidecar
159
+ // entry already holds the previous framework's record and stays.
160
+ continue;
161
+ }
162
+ }
163
+
164
+ // Fallback: check destination file content directly
165
+ if (!force && fs.existsSync(dest)) {
166
+ const destContent = fs.readFileSync(dest, 'utf8');
167
+ if (destContent === transformedContent) {
168
+ actions.push({ type: 'skip', src: f, dest, reason: 'unchanged', hash, frameworkSlug: currentFrameworkSlug });
169
+ seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
170
+ continue;
171
+ }
172
+ actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'changed', hash, frameworkSlug: currentFrameworkSlug });
173
+ } else if (force && fs.existsSync(dest)) {
174
+ actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'forced', hash, frameworkSlug: currentFrameworkSlug });
175
+ } else {
176
+ actions.push({ type: 'deploy', src: f, dest, content: transformedContent, reason: 'new', hash, frameworkSlug: currentFrameworkSlug });
177
+ }
178
+ seen.set(dest, { src: f, frameworkSlug: currentFrameworkSlug, transformedContent });
179
+ }
180
+
181
+ const verbose = opts.verbose === true;
182
+ const deployedEntries = [];
183
+ for (const a of actions) {
184
+ if (a.type === 'deploy') {
185
+ if (dryRun) console.log(`[dry-run] deploy ${a.src} -> ${a.dest} (${a.reason})`);
186
+ else writeFile(a.dest, a.content, false);
187
+ if (verbose) console.log(`deployed ${path.basename(a.src)} -> ${path.relative(process.cwd(), opts.logicalOutputPath?.(a.dest) || a.dest)} (${a.reason})`);
188
+ deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
189
+ } else if (a.type === 'skip') {
190
+ if (verbose) console.log(`skip (${a.reason}): ${path.basename(a.dest)}`);
191
+ // Preserve existing sidecar entries for skipped files
192
+ if (a.hash) deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
193
+ }
194
+ }
195
+
196
+ // Surface cross-framework collisions to the operator (#1169). Always
197
+ // visible (not gated on verbose) because silent loss is the failure
198
+ // mode this guard exists to prevent.
199
+ if (collisions.length > 0 && shouldReportDeployCollisions(opts)) {
200
+ const tag = force ? 'override' : 'skip';
201
+ console.warn(
202
+ `\n⚠ Cross-framework deploy collision${collisions.length > 1 ? 's' : ''} detected (${collisions.length}):`,
203
+ );
204
+ for (const c of collisions) {
205
+ console.warn(
206
+ ` ${c.filename}: ${c.existingFramework} owns this slot; ${c.incomingFramework} skipped (${c.scope})`,
207
+ );
208
+ }
209
+ if (!force) {
210
+ console.warn(
211
+ ` Re-run with --force to override (last-wins) or rename the colliding file at framework source.`,
212
+ );
213
+ }
214
+ }
215
+
216
+ // Update sidecar manifest with deployed file hashes (#749) including
217
+ // framework slug for future collision detection (#1169).
218
+ if (deployedEntries.length > 0) {
219
+ updateSidecarManifest(destDir, deployedEntries, { dryRun, version: deployVersion, source: deploySource });
220
+ }
221
+
222
+ return actions;
223
+ }
224
+
225
+
226
+ /**
227
+ * Deploy .soul.md companion files alongside agents.
228
+ * Soul files are copied as-is (no transformation) to the same directory as agents.
229
+ */
230
+ export function deploySoulCompanions(soulFiles, destDir, opts) {
231
+ if (!soulFiles || soulFiles.length === 0) return [];
232
+ return deployFiles(soulFiles, destDir, opts, null);
233
+ }