@aiwg/cli 2026.10.15 → 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 (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,139 @@
1
+ // Shared provider addon discovery utilities.
2
+ import { fs, path } from './base-runtime.mjs';
3
+ import { listMdFiles, listSkillDirs } from './base-files.mjs';
4
+
5
+
6
+ // ============================================================================
7
+ // Addon Discovery
8
+ // ============================================================================
9
+
10
+ /**
11
+ * Discover all addons in the agentic/code/addons directory
12
+ * @param {string} srcRoot - Source root directory
13
+ * @param {{includeExplicit?: boolean}} [options] - includeExplicit also returns explicitInstall addons
14
+ * @returns {Array<{name: string, path: string, manifest: object}>} - Array of addon info
15
+ */
16
+ export function discoverAddons(srcRoot, { includeExplicit = false } = {}) {
17
+ const addonsDir = path.join(srcRoot, 'agentic', 'code', 'addons');
18
+ if (!fs.existsSync(addonsDir)) return [];
19
+
20
+ const addons = [];
21
+ for (const entry of fs.readdirSync(addonsDir, { withFileTypes: true })) {
22
+ if (!entry.isDirectory()) continue;
23
+
24
+ const addonPath = path.join(addonsDir, entry.name);
25
+ const manifestPath = path.join(addonPath, 'manifest.json');
26
+
27
+ let manifest = {};
28
+ if (fs.existsSync(manifestPath)) {
29
+ try {
30
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
31
+ } catch (e) {
32
+ console.warn(`Warning: Could not parse manifest for addon ${entry.name}: ${e.message}`);
33
+ }
34
+ }
35
+
36
+ // Skip addons marked devOnly — they are contributor tools, not end-user deployables
37
+ if (manifest.devOnly === true) continue;
38
+ // explicitInstall addons deploy only when named (`aiwg use <addon>`), never
39
+ // as part of a framework or `all` bulk deploy (#2641).
40
+ // The stale-artifact prune passes includeExplicit so a named install's own
41
+ // files stay in its desired set and are not deleted right after deployment.
42
+ if (manifest.explicitInstall === true && !includeExplicit) continue;
43
+
44
+ addons.push({
45
+ name: entry.name,
46
+ path: addonPath,
47
+ manifest
48
+ });
49
+ }
50
+
51
+ return addons;
52
+ }
53
+
54
+
55
+ /**
56
+ * Get all agent files from all addons
57
+ * @param {string} srcRoot - Source root directory
58
+ * @param {string[]} excludeAddons - Addon names to exclude (default: none)
59
+ * @returns {string[]} - Array of agent file paths
60
+ */
61
+ export function getAddonAgentFiles(srcRoot, excludeAddons = [], options = {}) {
62
+ const addons = discoverAddons(srcRoot, options);
63
+ const files = [];
64
+
65
+ for (const addon of addons) {
66
+ if (excludeAddons.includes(addon.name)) continue;
67
+
68
+ const agentsDir = path.join(addon.path, 'agents');
69
+ if (fs.existsSync(agentsDir)) {
70
+ files.push(...listMdFiles(agentsDir));
71
+ }
72
+ }
73
+
74
+ return files;
75
+ }
76
+
77
+
78
+ /**
79
+ * Get all command files from all addons
80
+ * @param {string} srcRoot - Source root directory
81
+ * @param {string[]} excludeAddons - Addon names to exclude (default: none)
82
+ * @returns {string[]} - Array of command file paths
83
+ */
84
+ export function getAddonCommandFiles(srcRoot, excludeAddons = [], options = {}) {
85
+ const addons = discoverAddons(srcRoot, options);
86
+ const files = [];
87
+
88
+ for (const addon of addons) {
89
+ if (excludeAddons.includes(addon.name)) continue;
90
+
91
+ const commandsDir = path.join(addon.path, 'commands');
92
+ if (fs.existsSync(commandsDir)) {
93
+ files.push(...listMdFiles(commandsDir));
94
+ }
95
+ }
96
+
97
+ return files;
98
+ }
99
+
100
+
101
+ /**
102
+ * Get skill directories from a direct addon/framework source or all addons
103
+ * @param {string} srcRoot - Source root directory
104
+ * @param {string[]} excludeAddons - Addon names to exclude (default: none)
105
+ * @returns {string[]} - Array of skill directory paths
106
+ */
107
+ export function getAddonSkillDirs(srcRoot, excludeAddons = []) {
108
+ const addons = discoverAddons(srcRoot);
109
+ const dirs = [];
110
+ const directDir = getDirectSourceDir(srcRoot, excludeAddons);
111
+ if (directDir) dirs.push(...listSkillDirs(directDir));
112
+
113
+ for (const addon of addons) {
114
+ if (excludeAddons.includes(addon.name)) continue;
115
+
116
+ const skillsDir = path.join(addon.path, 'skills');
117
+ if (fs.existsSync(skillsDir)) {
118
+ dirs.push(...listSkillDirs(skillsDir));
119
+ }
120
+ }
121
+
122
+ return dirs;
123
+ }
124
+
125
+
126
+ // `aiwg use <addon>` passes the component itself as --source. Keep bulk
127
+ // repository discovery unchanged, even if the repo has a top-level skills/.
128
+ export function getDirectSourceDir(srcRoot, excludeAddons) {
129
+ if (fs.existsSync(path.join(srcRoot, 'agentic', 'code')) ||
130
+ excludeAddons.includes(path.basename(path.resolve(srcRoot)))) return null;
131
+ const dir = path.join(srcRoot, 'skills');
132
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return null;
133
+ const relative = path.relative(fs.realpathSync(srcRoot), fs.realpathSync(dir));
134
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
135
+ console.warn(`Warning: Skipping direct skills directory ${dir}: resolves outside source root ${srcRoot}`);
136
+ return null;
137
+ }
138
+ return dir;
139
+ }
@@ -0,0 +1,168 @@
1
+ // Shared provider behaviors utilities.
2
+ import { fs, path } from './base-runtime.mjs';
3
+ import { parseFrontmatter } from './base-frontmatter.mjs';
4
+ import { addManagedMarker, ensureDir, writeFile } from './base-files.mjs';
5
+ import { getAddonAgentFiles, getAddonCommandFiles, getAddonSkillDirs } from './base-addon-discovery.mjs';
6
+ import { getAddonRuleFiles } from './base-rule-index.mjs';
7
+
8
+
9
+ /**
10
+ * List behavior directories (directories containing BEHAVIOR.md).
11
+ */
12
+ export function listBehaviorDirs(dir) {
13
+ if (!fs.existsSync(dir)) return [];
14
+ return fs
15
+ .readdirSync(dir, { withFileTypes: true })
16
+ .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, 'BEHAVIOR.md')))
17
+ .map((entry) => path.join(dir, entry.name));
18
+ }
19
+
20
+
21
+ /**
22
+ * Collect behavior directories from all supported source shapes:
23
+ * - direct component source: <srcRoot>/behaviors/
24
+ * - cross-framework: agentic/code/behaviors/
25
+ * - per-addon: agentic/code/addons/<name>/behaviors/
26
+ * - per-framework: agentic/code/frameworks/<name>/behaviors/
27
+ */
28
+ export function collectBehaviorDirs(srcRoot) {
29
+ const dirs = [];
30
+ const seen = new Set();
31
+ const addDirs = (items) => {
32
+ for (const dir of items) {
33
+ if (seen.has(dir)) continue;
34
+ seen.add(dir);
35
+ dirs.push(dir);
36
+ }
37
+ };
38
+
39
+ addDirs(listBehaviorDirs(path.join(srcRoot, 'behaviors')));
40
+ addDirs(listBehaviorDirs(path.join(srcRoot, 'agentic', 'code', 'behaviors')));
41
+
42
+ const addonsDir = path.join(srcRoot, 'agentic', 'code', 'addons');
43
+ if (fs.existsSync(addonsDir)) {
44
+ for (const entry of fs.readdirSync(addonsDir, { withFileTypes: true })) {
45
+ if (!entry.isDirectory()) continue;
46
+ addDirs(listBehaviorDirs(path.join(addonsDir, entry.name, 'behaviors')));
47
+ }
48
+ }
49
+
50
+ const frameworksDir = path.join(srcRoot, 'agentic', 'code', 'frameworks');
51
+ if (fs.existsSync(frameworksDir)) {
52
+ for (const entry of fs.readdirSync(frameworksDir, { withFileTypes: true })) {
53
+ if (!entry.isDirectory()) continue;
54
+ addDirs(listBehaviorDirs(path.join(frameworksDir, entry.name, 'behaviors')));
55
+ }
56
+ }
57
+
58
+ return dirs;
59
+ }
60
+
61
+
62
+ export const BEHAVIOR_EMULATION_TARGETS = {
63
+ claude: { dir: '.claude/rules/behaviors', extension: '.md', surface: 'Claude Code rules' },
64
+ codex: { dir: '.codex/rules/behaviors', extension: '.md', surface: 'Codex rules' },
65
+ copilot: { dir: '.github/instructions/aiwg-behaviors', extension: '.instructions.md', surface: 'GitHub Copilot instructions' },
66
+ cursor: { dir: '.cursor/rules/behaviors', extension: '.md', surface: 'Cursor rules' },
67
+ factory: { dir: '.factory/rules/behaviors', extension: '.md', surface: 'Factory rules' },
68
+ opencode: { dir: '.opencode/rule/behaviors', extension: '.md', surface: 'OpenCode rules' },
69
+ warp: { dir: '.warp/rules/behaviors', extension: '.md', surface: 'Warp rules/context surface' },
70
+ windsurf: { dir: '.windsurf/rules/behaviors', extension: '.md', surface: 'Windsurf rules' },
71
+ hermes: { dir: '.hermes/behaviors', extension: '.md', surface: 'Hermes behavior context' },
72
+ };
73
+
74
+
75
+ export function renderBehaviorEmulation(behaviorDir, provider, target) {
76
+ const behaviorName = path.basename(behaviorDir);
77
+ const behaviorPath = path.join(behaviorDir, 'BEHAVIOR.md');
78
+ const content = fs.readFileSync(behaviorPath, 'utf8');
79
+ const { metadata } = parseFrontmatter(content);
80
+ const description = metadata?.description || `AIWG behavior ${behaviorName}`;
81
+
82
+ return `# AIWG Behavior: ${behaviorName}
83
+
84
+ Provider surface: ${target.surface}
85
+ Provider: ${provider}
86
+ Native source: ${path.relative(process.cwd(), behaviorPath)}
87
+
88
+ ${description}
89
+
90
+ 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.
91
+
92
+ ## Activation
93
+
94
+ 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.
95
+
96
+ ## Source Behavior
97
+
98
+ \`\`\`markdown
99
+ ${content.trim()}
100
+ \`\`\`
101
+ `;
102
+ }
103
+
104
+
105
+ /**
106
+ * Deploy provider-specific emulated behavior artifacts for providers that do
107
+ * not have a native OpenClaw-style behavior loader.
108
+ */
109
+ export function deployEmulatedBehaviors(behaviorDirs, providerName, targetDir, opts = {}) {
110
+ if (!behaviorDirs || behaviorDirs.length === 0) return 0;
111
+ const provider = providerName === 'openai' ? 'codex' : providerName;
112
+ if (provider === 'openclaw') return 0;
113
+ const target = BEHAVIOR_EMULATION_TARGETS[provider];
114
+ if (!target) {
115
+ if (opts.verbose) console.warn(`No behavior emulation target registered for provider ${provider}`);
116
+ return 0;
117
+ }
118
+
119
+ const destDir = path.isAbsolute(target.dir) ? target.dir : path.join(targetDir, target.dir);
120
+ ensureDir(destDir, opts.dryRun);
121
+ let count = 0;
122
+
123
+ for (const behaviorDir of behaviorDirs) {
124
+ const behaviorName = path.basename(behaviorDir);
125
+ const filename = `${behaviorName}${target.extension}`;
126
+ const dest = path.join(destDir, filename);
127
+ const rendered = renderBehaviorEmulation(behaviorDir, provider, target);
128
+ const content = addManagedMarker(rendered, opts.deployVersion || 'unknown', opts.deploySource || 'bundled');
129
+ if (opts.dryRun) {
130
+ console.log(`[dry-run] deploy behavior emulation ${behaviorName} -> ${dest}`);
131
+ } else {
132
+ writeFile(dest, content, false);
133
+ }
134
+ if (opts.verbose) console.log(`deployed behavior emulation ${behaviorName} -> ${path.relative(process.cwd(), dest)}`);
135
+ count++;
136
+ }
137
+
138
+ return count;
139
+ }
140
+
141
+
142
+ /**
143
+ * Get addon files by category (agents, commands, skills, rules)
144
+ * @param {string} srcRoot - Source root directory
145
+ * @param {object} options - Options
146
+ * @param {string[]} options.excludeAddons - Addon names to exclude
147
+ * @param {boolean} options.includeAgents - Include agent files (default: true)
148
+ * @param {boolean} options.includeCommands - Include command files (default: true)
149
+ * @param {boolean} options.includeSkills - Include skill directories (default: true)
150
+ * @param {boolean} options.includeRules - Include rule files (default: true)
151
+ * @returns {{agents: string[], commands: string[], skills: string[], rules: string[]}}
152
+ */
153
+ export function getAddonFiles(srcRoot, options = {}) {
154
+ const {
155
+ excludeAddons = [],
156
+ includeAgents = true,
157
+ includeCommands = true,
158
+ includeSkills = true,
159
+ includeRules = true
160
+ } = options;
161
+
162
+ return {
163
+ agents: includeAgents ? getAddonAgentFiles(srcRoot, excludeAddons) : [],
164
+ commands: includeCommands ? getAddonCommandFiles(srcRoot, excludeAddons) : [],
165
+ skills: includeSkills ? getAddonSkillDirs(srcRoot, excludeAddons) : [],
166
+ rules: includeRules ? getAddonRuleFiles(srcRoot, excludeAddons) : []
167
+ };
168
+ }
@@ -0,0 +1,205 @@
1
+ // Shared provider context utilities.
2
+ import { boundedExecFileSync, fs, helperEnvironment, path, writeContextFileSync } from './base-runtime.mjs';
3
+ import { listOnDemandRuleFiles, renderOnDemandRuleSection } from './base-rule-index.mjs';
4
+
5
+
6
+ // ============================================================================
7
+ // AGENTS.md Template Handling
8
+ // ============================================================================
9
+
10
+ /**
11
+ * Build a Markdown "Repo Topology" block from .aiwg/aiwg.config remotes (#998).
12
+ *
13
+ * Returns an empty string when there's no `remotes` block configured — agents
14
+ * should fall back to the today-default behavior in that case.
15
+ *
16
+ * The output is a small Markdown section suitable for token substitution into
17
+ * AIWG.md / AGENTS.md / similar context files. URL resolution is best-effort:
18
+ * when `git remote get-url <name>` fails (not a git repo, missing remote), the
19
+ * remote name is shown without a URL.
20
+ *
21
+ * @param {string} targetDir - Project directory (the one that owns .aiwg/aiwg.config)
22
+ * @returns {string} Markdown block (with leading/trailing blank lines), or '' when absent
23
+ */
24
+ export function buildRemotesTopologyBlock(targetDir) {
25
+ const cfgPath = path.join(targetDir, '.aiwg', 'aiwg.config');
26
+ if (!fs.existsSync(cfgPath)) return '';
27
+
28
+ let cfg;
29
+ try {
30
+ cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
31
+ } catch {
32
+ return '';
33
+ }
34
+ if (!cfg || !cfg.remotes) return '';
35
+
36
+ // Apply the same defaults as resolveRemotes() in src/config/aiwg-config.ts.
37
+ // Inlined here so the deploy path doesn't depend on the compiled TS bundle.
38
+ const primary = cfg.remotes.primary || 'origin';
39
+ const issueTracker = cfg.remotes.issue_tracker || primary;
40
+ const ci = cfg.remotes.ci || primary;
41
+ const secondary = Array.isArray(cfg.remotes.secondary) ? cfg.remotes.secondary : [];
42
+
43
+ function getUrl(remote) {
44
+ try {
45
+ return boundedExecFileSync('git', ['-C', targetDir, 'remote', 'get-url', '--', remote], 'quick', {
46
+ env: helperEnvironment(),
47
+ stdio: ['ignore', 'pipe', 'ignore'],
48
+ encoding: 'utf8',
49
+ }).trim();
50
+ } catch {
51
+ return '';
52
+ }
53
+ }
54
+
55
+ const lines = [];
56
+ lines.push('## Repo Topology');
57
+ lines.push('');
58
+ lines.push('Agents: respect this when picking remotes/providers. From `.aiwg/aiwg.config` `remotes` block (#994).');
59
+ lines.push('');
60
+ const primaryUrl = getUrl(primary);
61
+ const primarySuffix = primaryUrl ? ` (${primaryUrl})` : '';
62
+ lines.push(`- **Primary**: \`${primary}\`${primarySuffix} — issues, PRs, CI live here`);
63
+ if (issueTracker !== primary) {
64
+ const u = getUrl(issueTracker);
65
+ lines.push(`- **Issue tracker**: \`${issueTracker}\`${u ? ` (${u})` : ''}`);
66
+ }
67
+ if (ci !== primary) {
68
+ const u = getUrl(ci);
69
+ lines.push(`- **CI**: \`${ci}\`${u ? ` (${u})` : ''}`);
70
+ }
71
+ for (const sec of secondary) {
72
+ if (!sec || !sec.name) continue;
73
+ const u = getUrl(sec.name);
74
+ const purpose = sec.purpose ? ` — ${sec.purpose}` : '';
75
+ const releaseTag = sec.push_on_release ? ' (push tags on release)' : '';
76
+ lines.push(`- **Secondary**: \`${sec.name}\`${u ? ` (${u})` : ''}${purpose}${releaseTag}`);
77
+ }
78
+ lines.push('');
79
+ return lines.join('\n');
80
+ }
81
+
82
+
83
+ /**
84
+ * Substitute the topology + count tokens in template content. Shared by the
85
+ * Claude hook file and createAgentsMdFromTemplate so every consumer gets the
86
+ * same {{REMOTES_TOPOLOGY}} treatment without each provider reinventing it.
87
+ */
88
+ export function interpolateContextTokens(content, opts) {
89
+ const counts = opts?.counts || {};
90
+ const topology = opts?.topology || '';
91
+ const onDemandRules = opts?.onDemandRules || '';
92
+ return content
93
+ .replace(/\{\{AGENTS_COUNT\}\}/g, String(counts.agents || 0))
94
+ .replace(/\{\{COMMANDS_COUNT\}\}/g, String(counts.commands || 0))
95
+ .replace(/\{\{SKILLS_COUNT\}\}/g, String(counts.skills || 0))
96
+ .replace(/\{\{RULES_COUNT\}\}/g, String(counts.rules || 0))
97
+ .replace(/\{\{REMOTES_TOPOLOGY\}\}/g, topology)
98
+ .replace(/\{\{ON_DEMAND_RULES\}\}/g, onDemandRules);
99
+ }
100
+
101
+
102
+ /**
103
+ * Create or update AGENTS.md from template
104
+ * Common logic used by multiple providers
105
+ */
106
+ // Managed-block markers (#1571). The AIWG SDLC section is wrapped in these so
107
+ // every later `aiwg use`/`aiwg refresh` can UPDATE it in place — append-once-and-
108
+ // skip meant existing AGENTS.md bridges never received content updates.
109
+ export const AIWG_MD_BEGIN = '<!-- BEGIN AIWG-managed (auto-generated; edits between these markers are overwritten on redeploy) -->';
110
+
111
+ export const AIWG_MD_END = '<!-- END AIWG-managed -->';
112
+
113
+
114
+ /**
115
+ * Inject/update an AIWG-managed section in a workspace markdown file (AGENTS.md,
116
+ * SOUL.md, …) from a template. Wraps the section in BEGIN/END markers and updates
117
+ * in place on redeploy (no-op if unchanged), preserving operator content outside
118
+ * the markers and migrating legacy unmarked sections. (#1571 / #1572)
119
+ *
120
+ * @param {string} target - directory containing the dest file
121
+ * @param {string} destFilename - e.g. 'AGENTS.md' or 'SOUL.md'
122
+ * @param {string} srcRoot
123
+ * @param {string} templateSubpath - relative to sdlc-complete/templates
124
+ * @param {boolean} dryRun
125
+ * @param {{sectionMarker?: string, legacyHeading?: string}} [opts]
126
+ */
127
+ export function createManagedMdFromTemplate(target, destFilename, srcRoot, templateSubpath, dryRun, opts = {}) {
128
+ const sectionMarker = opts.sectionMarker || '<!-- AIWG SDLC Framework Integration -->';
129
+ const legacyHeading = opts.legacyHeading || '## AIWG SDLC Framework';
130
+ const templatePath = path.join(srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'templates', templateSubpath);
131
+ const destPath = path.join(target, destFilename);
132
+
133
+ if (!fs.existsSync(templatePath)) {
134
+ console.warn(`${destFilename} template not found at ${templatePath}`);
135
+ return;
136
+ }
137
+
138
+ let template = fs.readFileSync(templatePath, 'utf8');
139
+ // Token interpolation — gives every template-based provider {{REMOTES_TOPOLOGY}},
140
+ // {{ON_DEMAND_RULES}} (#1675), and the shared count tokens for free. The
141
+ // on-demand list is computed lazily only when the template references it.
142
+ template = interpolateContextTokens(template, {
143
+ topology: buildRemotesTopologyBlock(target),
144
+ onDemandRules: template.includes('{{ON_DEMAND_RULES}}')
145
+ ? renderOnDemandRuleSection(listOnDemandRuleFiles(srcRoot), { heading: '### On-Demand Rules' })
146
+ : '',
147
+ });
148
+
149
+ // Extract the AIWG section from the template (everything from its section
150
+ // marker onward) and wrap it in managed markers so redeploys can update it.
151
+ const tmplMarker = template.indexOf(sectionMarker);
152
+ const aiwgSection = (tmplMarker !== -1 ? template.slice(tmplMarker) : template).trim();
153
+ const templatePrefix = tmplMarker !== -1 ? template.slice(0, tmplMarker).trim() : '';
154
+ const managedBlock = `${AIWG_MD_BEGIN}\n${aiwgSection}\n${AIWG_MD_END}`;
155
+
156
+ const write = (content, verb) => {
157
+ if (dryRun) {
158
+ console.log(`[dry-run] Would ${verb} ${destFilename} AIWG-managed section`);
159
+ } else {
160
+ writeContextFileSync(destPath, content, 'utf8');
161
+ console.log(`${verb[0].toUpperCase()}${verb.slice(1)} ${destFilename} AIWG-managed section`);
162
+ }
163
+ };
164
+
165
+ // 1. Fresh file — write prefix (if any) + managed block.
166
+ if (!fs.existsSync(destPath)) {
167
+ const out = (templatePrefix ? templatePrefix + '\n\n---\n\n' : '') + managedBlock + '\n';
168
+ write(out, 'create');
169
+ return;
170
+ }
171
+
172
+ const existing = fs.readFileSync(destPath, 'utf8');
173
+ const begIdx = existing.indexOf(AIWG_MD_BEGIN);
174
+ const endIdx = existing.indexOf(AIWG_MD_END);
175
+
176
+ // 2. Markers present — replace the managed block in place, preserve everything outside.
177
+ if (begIdx !== -1 && endIdx !== -1 && endIdx > begIdx) {
178
+ const updated = existing.slice(0, begIdx) + managedBlock + existing.slice(endIdx + AIWG_MD_END.length);
179
+ if (updated === existing) return; // already current — no-op
180
+ write(updated, 'update');
181
+ return;
182
+ }
183
+
184
+ // 3. Legacy unmarked AIWG section — migrate to the managed block. The section
185
+ // is always EOF-appended, so the operator prefix is everything before it.
186
+ const legacyMarkerIdx = existing.indexOf(sectionMarker);
187
+ const legacyIdx = legacyMarkerIdx !== -1 ? legacyMarkerIdx : existing.indexOf(legacyHeading);
188
+ if (legacyIdx !== -1) {
189
+ const prefix = existing.slice(0, legacyIdx).replace(/\n+---\s*$/, '').trimEnd();
190
+ write(prefix + '\n\n---\n\n' + managedBlock + '\n', 'migrate');
191
+ return;
192
+ }
193
+
194
+ // 4. No AIWG section at all — append the managed block.
195
+ write(existing.trimEnd() + '\n\n---\n\n' + managedBlock + '\n', 'append');
196
+ }
197
+
198
+
199
+ /** AGENTS.md bridge — thin wrapper over createManagedMdFromTemplate (#1571). */
200
+ export function createAgentsMdFromTemplate(target, srcRoot, templateSubpath, dryRun) {
201
+ createManagedMdFromTemplate(target, 'AGENTS.md', srcRoot, templateSubpath, dryRun, {
202
+ sectionMarker: '<!-- AIWG SDLC Framework Integration -->',
203
+ legacyHeading: '## AIWG SDLC Framework',
204
+ });
205
+ }
@@ -0,0 +1,116 @@
1
+ // Shared provider contract utilities.
2
+ import { path } from './base-runtime.mjs';
3
+
4
+
5
+ // ============================================================================
6
+ // Provider Interface
7
+ // ============================================================================
8
+
9
+ /**
10
+ * Base provider interface - all providers should implement these methods
11
+ */
12
+ export const ProviderInterface = {
13
+ name: 'base',
14
+ aliases: [],
15
+
16
+ // ── Path Configuration ──────────────────────────────────────────────
17
+ // Paths describe native or conventional deployment only. Empty paths mean
18
+ // indexed access via aiwg discover/show, not an unavailable artifact class.
19
+ paths: {
20
+ agents: null,
21
+ commands: null,
22
+ skills: null,
23
+ rules: null
24
+ },
25
+
26
+ // ── Support Level per Artifact Type ─────────────────────────────────
27
+ // Distinguishes native platform support from AIWG conventional directories.
28
+ // 'native' - Platform natively discovers and uses these files
29
+ // 'conventional' - AIWG directory convention; available for @-mention context loading
30
+ // 'aggregated' - Content included in aggregated file AND deployed as discrete files
31
+ // 'indexed' - Full source body available via aiwg discover/show without a native loader
32
+ support: {
33
+ agents: 'conventional',
34
+ commands: 'conventional',
35
+ skills: 'conventional',
36
+ rules: 'conventional'
37
+ },
38
+
39
+ // ── Provider Capabilities ───────────────────────────────────────────
40
+ capabilities: {
41
+ skills: false,
42
+ rules: false,
43
+ aggregatedOutput: false,
44
+ yamlFormat: false,
45
+ mdcFormat: false,
46
+ homeDirectoryDeploy: false,
47
+ projectLocalMirror: false
48
+ },
49
+
50
+ // ── Home Directory Paths (Codex-specific) ───────────────────────────
51
+ // Only populated for providers that deploy to home directory.
52
+ homePaths: {
53
+ commands: null,
54
+ skills: null
55
+ },
56
+
57
+ // ── Artifact Transformation ─────────────────────────────────────────
58
+ transformAgent(srcPath, content, opts) { return content; },
59
+ transformCommand(srcPath, content, opts) { return content; },
60
+ transformSkill(srcPath, content, opts) { return content; },
61
+ transformRule(srcPath, content, opts) { return content; },
62
+
63
+ // ── Model Mapping ──────────────────────────────────────────────────
64
+ mapModel(shorthand, modelCfg, modelsConfig) { return shorthand; },
65
+
66
+ // ── Deployment Functions ────────────────────────────────────────────
67
+ // All four deploy functions are available. Providers override as needed.
68
+ deployAgents(agentFiles, targetDir, opts) {},
69
+ deployCommands(commandFiles, targetDir, opts) {},
70
+ deploySkills(skillDirs, targetDir, opts) {},
71
+ deployRules(ruleFiles, targetDir, opts) {},
72
+
73
+ // ── Aggregation (for Warp, Windsurf) ────────────────────────────────
74
+ aggregate(artifacts, targetDir, opts) {},
75
+
76
+ // ── Create/update AGENTS.md ────────────────────────────────────────
77
+ createAgentsMd(target, srcRoot, dryRun) {
78
+ // Override in provider
79
+ },
80
+
81
+ // ── Post-deployment hook ───────────────────────────────────────────
82
+ async postDeploy(targetDir, opts) {
83
+ // Override in provider if needed
84
+ },
85
+
86
+ // ── File Extension ────────────────────────────────────────────────
87
+ getFileExtension(type) { return '.md'; }
88
+ };
89
+
90
+
91
+ /** Replace only the generated binding block; keep authored bytes intact. */
92
+ export function replaceBoundRulesBlock(content, rules = []) {
93
+ const clean = content.replace(/\n?<!-- AIWG:bound-rules:start -->[\s\S]*?<!-- AIWG:bound-rules:end -->\n?/g, '');
94
+ if (!rules.length) return clean;
95
+ const unique = [...new Map(rules.map(rule => [rule.name, rule])).values()]
96
+ .sort((a, b) => a.name.localeCompare(b.name));
97
+ 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 =>
98
+ `- ${rule.name} — ${rule.summary}\n Fetch and follow before governed work: \`aiwg show rule ${rule.name} --body\`.`
99
+ ).join('\n')}\n<!-- AIWG:bound-rules:end -->\n`;
100
+ }
101
+
102
+
103
+ export function injectBoundRules(content, source, opts = {}) {
104
+ if (!opts.ruleDelivery) return content;
105
+ return replaceBoundRulesBlock(content, opts.ruleDelivery.bindings.get(path.resolve(source)) || []);
106
+ }
107
+
108
+
109
+ /** Rule delivery stages output and guards startup before promotion. Deferred
110
+ * kernel passes leave rule delivery to the final source in the invocation. */
111
+ export async function withRuleDeployment(opts, provider, deploy) {
112
+ if (opts.kernelOnly && opts.deferRuleProjection && provider.name !== 'warp'
113
+ && !globalThis[Symbol.for('aiwg.provider-preparation-hook.v1')]) return deploy(opts);
114
+ const { deployWithRuleDelivery } = await import('./rule-delivery.mjs');
115
+ return deployWithRuleDelivery(opts, provider, deploy);
116
+ }