@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,300 @@
1
+ // Own immutable input pools and serializable deployment plan state.
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { resolveAiwgRoot } from './base.mjs';
7
+ import { fileDigest, resolveProjectAiwgDir, trackTemporaryDirectory } from './rule-delivery-surface.mjs';
8
+
9
+ // Plans contain only JSON values and a scratch directory. The preparing process
10
+ // owns that directory until disposal; cross-process transfer needs a separate lease.
11
+ export const stagedCleanups = new Map();
12
+ export class RuleDeploymentStaleError extends Error {
13
+ constructor(message, paths = []) {
14
+ super(message);
15
+ this.name = 'RuleDeploymentStaleError';
16
+ this.code = 'AIWG_RULE_DEPLOYMENT_STALE';
17
+ this.paths = paths;
18
+ }
19
+ }
20
+ export function capturePreimage(file, ancestors = new Set()) {
21
+ let stat;
22
+ try { stat = fs.lstatSync(file); } catch (error) {
23
+ if (error.code === 'ENOENT') return { kind: 'missing' };
24
+ throw error;
25
+ }
26
+ const mode = stat.mode & 0o7777;
27
+ if (stat.isSymbolicLink()) {
28
+ const target = fs.readlinkSync(file);
29
+ const resolved = path.resolve(path.dirname(file), target);
30
+ if (ancestors.has(resolved)) throw new Error(`Cyclic deployment preimage: ${file}`);
31
+ return { kind: 'symlink', mode, target, resolved: capturePreimage(resolved, new Set([...ancestors, resolved])) };
32
+ }
33
+ if (stat.isFile()) return { kind: 'file', mode, digest: fileDigest(file) };
34
+ if (stat.isDirectory()) return { kind: 'directory', mode, entries: fs.readdirSync(file).sort().map(name => [name, capturePreimage(path.join(file, name), new Set([...ancestors, path.resolve(file)]))]) };
35
+ throw new Error(`Unsupported deployment preimage: ${file}`);
36
+ }
37
+ // cpSync materializes links; compare its output with the recursively resolved
38
+ // content while retaining the original link-shaped preimage for commit drift.
39
+ export function materializeInput(from, to, ancestors = new Set(), parentReady = false) {
40
+ let stat;
41
+ try { stat = fs.statSync(from); } catch (error) {
42
+ if (error.code === 'ENOENT') return;
43
+ throw error;
44
+ }
45
+ if (stat.isDirectory()) {
46
+ // Only directories can lead back to an ancestor. Resolve them once and
47
+ // share the immutable ancestry set with their children, including aliases.
48
+ const real = fs.realpathSync(from);
49
+ if (ancestors.has(real)) throw new Error(`Cyclic deployment input: ${from}`);
50
+ const children = new Set([...ancestors, real]);
51
+ fs.mkdirSync(to, { recursive: true });
52
+ for (const name of fs.readdirSync(from)) materializeInput(path.join(from, name), path.join(to, name), children, true);
53
+ fs.chmodSync(to, stat.mode & 0o7777);
54
+ } else if (stat.isFile()) {
55
+ if (!parentReady) fs.mkdirSync(path.dirname(to), { recursive: true });
56
+ fs.copyFileSync(from, to); fs.chmodSync(to, stat.mode & 0o7777);
57
+ } else throw new Error(`Unsupported deployment input: ${from}`);
58
+ }
59
+ export function materializedPreimage(state) {
60
+ if (state.kind === 'symlink') return materializedPreimage(state.resolved);
61
+ if (state.kind === 'directory') return { ...state, entries: state.entries.map(([name, child]) => [name, materializedPreimage(child)]) };
62
+ return state;
63
+ }
64
+ export function snapshotPreimages(paths) {
65
+ return [...new Set(paths.map(file => path.resolve(file)))].map(file => ({ path: file, state: capturePreimage(file) }));
66
+ }
67
+ export function planSeal(plan) { return createHash('sha256').update(JSON.stringify(plan)).digest('hex'); }
68
+ export function planOwner(plan) {
69
+ const owner = stagedCleanups.get(plan?.lease);
70
+ return owner && owner.seal === planSeal(plan) ? owner : null;
71
+ }
72
+ export function disposeRuleDeploymentPlan(plan) {
73
+ const owner = planOwner(plan);
74
+ if (owner) { stagedCleanups.delete(plan.lease); owner.cleanup(); }
75
+ }
76
+
77
+ /** Release process-local ownership while retaining a coordinator-owned stage. */
78
+ export function detachRuleDeploymentPlan(plan) {
79
+ const owner = planOwner(plan);
80
+ if (!owner || !owner.transferable) throw new Error('Rule deployment plan is not transferable');
81
+ stagedCleanups.delete(plan.lease);
82
+ owner.detach();
83
+ return plan;
84
+ }
85
+ export function captureAnchors(paths) {
86
+ const names = new Set();
87
+ for (const name of paths) {
88
+ let current = path.resolve(name);
89
+ for (;;) {
90
+ names.add(current);
91
+ const parent = path.dirname(current);
92
+ if (parent === current) break;
93
+ current = parent;
94
+ }
95
+ }
96
+ return [...names].sort().map(file => {
97
+ try {
98
+ const stat = fs.lstatSync(file, { bigint: true });
99
+ return { path: file, dev: String(stat.dev), ino: String(stat.ino), mode: String(stat.mode),
100
+ link: stat.isSymbolicLink() ? fs.readlinkSync(file) : null, real: fs.realpathSync(file) };
101
+ } catch (error) {
102
+ if (error.code === 'ENOENT') return { path: file, missing: true };
103
+ throw error;
104
+ }
105
+ });
106
+ }
107
+
108
+ // Opaque coordinator-owned input pool. A plan retains a lease until committed or
109
+ // disposed, so disposing the creator's handle cannot invalidate active stages.
110
+ export const inputPools = new WeakMap();
111
+ // Executable links are identity-bound but their installed code is trusted host
112
+ // state. Data files, modes, directory membership, and links are sealed in full.
113
+ export function poolInventory(file) {
114
+ let stat;
115
+ try { stat = fs.lstatSync(file); } catch (error) {
116
+ if (error.code === 'ENOENT') return { kind: 'missing' };
117
+ throw error;
118
+ }
119
+ const mode = stat.mode & 0o7777;
120
+ if (stat.isSymbolicLink()) return { kind: 'symlink', mode, target: fs.readlinkSync(file) };
121
+ if (stat.isFile()) return { kind: 'file', mode, digest: fileDigest(file) };
122
+ if (stat.isDirectory()) return { kind: 'directory', mode, entries: fs.readdirSync(file).sort().map(name => [name, poolInventory(path.join(file, name))]) };
123
+ throw new Error(`Unsupported shared input pool entry: ${file}`);
124
+ }
125
+ export function setPoolWritable(file, writable) {
126
+ let stat;
127
+ try { stat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
128
+ if (stat.isSymbolicLink()) return;
129
+ if (stat.isDirectory() && writable) fs.chmodSync(file, (stat.mode & 0o7777) | 0o700);
130
+ if (stat.isDirectory()) for (const name of fs.readdirSync(file)) setPoolWritable(path.join(file, name), writable);
131
+ if (!writable) fs.chmodSync(file, (stat.mode & 0o7777) & ~0o222);
132
+ }
133
+ export function verifyInputPool(pool) {
134
+ try {
135
+ if (planSeal(poolInventory(pool.snapshotRoot)) === pool.inventorySeal &&
136
+ JSON.stringify(captureAnchors(pool.execAnchors.map(anchor => anchor.path))) === JSON.stringify(pool.execAnchors)) return;
137
+ } catch (error) { throw new Error(`Shared input pool changed: ${error.message}`); }
138
+ throw new Error('Shared input pool changed');
139
+ }
140
+
141
+ export function createRuleDeploymentInputPool(srcRoot) {
142
+ const corpusRoot = resolveAiwgRoot(srcRoot) || srcRoot;
143
+ const sourceTree = fs.existsSync(path.join(corpusRoot, 'agentic', 'code')) ? path.join(corpusRoot, 'agentic', 'code') : srcRoot;
144
+ const isCorpusTree = path.relative(corpusRoot, sourceTree) === path.join('agentic', 'code');
145
+ const paths = [sourceTree, path.join(corpusRoot, 'prebuilt', 'framework-relations'), path.join(corpusRoot, 'package.json'), path.join(corpusRoot, 'schemas')];
146
+ const preimages = snapshotPreimages(paths);
147
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'aiwg-rule-input-'));
148
+ const cleanup = trackTemporaryDirectory(temp);
149
+ try {
150
+ const snapshotRoot = path.join(temp, 'input');
151
+ const snapshotTree = isCorpusTree ? path.join(snapshotRoot, 'agentic', 'code') : snapshotRoot;
152
+ materializeInput(sourceTree, snapshotTree);
153
+ if (JSON.stringify(capturePreimage(snapshotTree)) !== JSON.stringify(materializedPreimage(preimages[0].state))) throw new Error('Source changed while preparing immutable snapshot');
154
+ const trustedExec = [];
155
+ if (isCorpusTree) {
156
+ for (const rel of ['package.json', 'prebuilt/framework-relations', 'schemas']) {
157
+ const from = path.join(corpusRoot, rel), to = path.join(snapshotRoot, rel);
158
+ materializeInput(from, to);
159
+ const expected = preimages.find(item => item.path === path.resolve(from));
160
+ if (JSON.stringify(capturePreimage(to)) !== JSON.stringify(materializedPreimage(expected.state))) throw new Error(`Package input changed while preparing snapshot: ${from}`);
161
+ }
162
+ for (const rel of ['tools', 'dist', 'node_modules', 'src']) {
163
+ const from = path.join(corpusRoot, rel), to = path.join(snapshotRoot, rel);
164
+ if (fs.existsSync(from)) { fs.symlinkSync(from, to, 'dir'); trustedExec.push(from); }
165
+ }
166
+ }
167
+ setPoolWritable(snapshotRoot, false);
168
+ const inventorySeal = planSeal(poolInventory(snapshotRoot));
169
+ const execAnchors = captureAnchors(trustedExec);
170
+ const safeCleanup = () => { setPoolWritable(snapshotRoot, true); cleanup(); };
171
+ const token = Object.freeze({});
172
+ inputPools.set(token, { corpusRoot: path.resolve(corpusRoot), sourceTree: path.resolve(sourceTree), snapshotRoot, snapshotTree, isCorpusTree, preimages, inventorySeal, execAnchors, refs: 1, closed: false, cleanup: safeCleanup, transferable: true });
173
+ return token;
174
+ } catch (error) { setPoolWritable(path.join(temp, 'input'), true); cleanup(); throw error; }
175
+ }
176
+ export function releaseInputPool(pool) { if (--pool.refs === 0) pool.cleanup(); }
177
+ export function disposeRuleDeploymentInputPool(token) {
178
+ const pool = inputPools.get(token);
179
+ if (pool && !pool.closed) { pool.closed = true; releaseInputPool(pool); }
180
+ }
181
+
182
+ /** A descriptor contains immutable snapshot identity, never its cleanup lease. */
183
+ export function describeRuleDeploymentInputPool(token) {
184
+ const pool = inputPools.get(token);
185
+ if (!pool || pool.closed || !pool.transferable) throw new Error('Invalid or closed rule deployment input pool');
186
+ verifyInputPool(pool);
187
+ return {
188
+ version: 1,
189
+ corpusRoot: pool.corpusRoot,
190
+ sourceTree: pool.sourceTree,
191
+ snapshotRoot: pool.snapshotRoot,
192
+ snapshotTree: pool.snapshotTree,
193
+ isCorpusTree: pool.isCorpusTree,
194
+ inventorySeal: pool.inventorySeal,
195
+ execAnchors: pool.execAnchors,
196
+ };
197
+ }
198
+
199
+ /** Import a read-only pool view in a preparation worker. The coordinator keeps
200
+ * the only cleanup lease and later restores the live-source preimages. */
201
+ export function importRuleDeploymentInputPool(descriptor) {
202
+ if (!descriptor || descriptor.version !== 1 || typeof descriptor.inventorySeal !== 'string' ||
203
+ !Array.isArray(descriptor.execAnchors)) throw new Error('Invalid rule deployment input pool descriptor');
204
+ for (const key of ['corpusRoot', 'sourceTree', 'snapshotRoot', 'snapshotTree']) {
205
+ if (typeof descriptor[key] !== 'string' || !path.isAbsolute(descriptor[key])) throw new Error('Invalid rule deployment input pool descriptor');
206
+ }
207
+ const token = Object.freeze({});
208
+ const pool = { ...descriptor, corpusRoot: path.resolve(descriptor.corpusRoot), sourceTree: path.resolve(descriptor.sourceTree),
209
+ snapshotRoot: path.resolve(descriptor.snapshotRoot), snapshotTree: path.resolve(descriptor.snapshotTree), preimages: [],
210
+ refs: 1, closed: false, cleanup: () => {}, transferable: false };
211
+ verifyInputPool(pool);
212
+ inputPools.set(token, pool);
213
+ return token;
214
+ }
215
+
216
+ export function within(root, file) {
217
+ const relative = path.relative(path.resolve(root), path.resolve(file));
218
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
219
+ }
220
+
221
+ export function safeRelative(root, name) {
222
+ return typeof name === 'string' && name !== '' && name !== '.' && path.normalize(name) === name && !path.isAbsolute(name) && within(root, path.join(root, name));
223
+ }
224
+
225
+ export function exactObjectKeys(value, keys) {
226
+ return value && typeof value === 'object' && !Array.isArray(value) &&
227
+ JSON.stringify(Object.keys(value).sort()) === JSON.stringify([...keys].sort());
228
+ }
229
+
230
+ export function validPreimageState(state) {
231
+ if (!state || typeof state !== 'object' || Array.isArray(state) || typeof state.kind !== 'string') return false;
232
+ if (state.kind === 'missing') return Object.keys(state).length === 1;
233
+ if (!Number.isSafeInteger(state.mode) || state.mode < 0) return false;
234
+ if (state.kind === 'file') return Object.keys(state).length === 3 && /^[a-f0-9]{64}$/.test(state.digest);
235
+ if (state.kind === 'symlink') return Object.keys(state).length === 4 && typeof state.target === 'string' && validPreimageState(state.resolved);
236
+ return state.kind === 'directory' && Object.keys(state).length === 3 && Array.isArray(state.entries) && state.entries.every(entry =>
237
+ Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string' && entry[0] !== '' && !entry[0].includes(path.sep) && validPreimageState(entry[1]));
238
+ }
239
+
240
+ export function expectedAnchorPaths(paths) {
241
+ const names = new Set();
242
+ for (const name of paths) {
243
+ let current = path.resolve(name);
244
+ for (;;) {
245
+ names.add(current);
246
+ const parent = path.dirname(current);
247
+ if (parent === current) break;
248
+ current = parent;
249
+ }
250
+ }
251
+ return [...names].sort();
252
+ }
253
+
254
+ /** Adopt a detached worker plan into the coordinator's process-local lease. */
255
+ export function adoptRuleDeploymentPlan(detached, { scratch, target, inputPool, cleanup }) {
256
+ const invalid = () => { throw new Error('Invalid transferred rule deployment plan'); };
257
+ if (!exactObjectKeys(detached, ['version', 'lease', 'temp', 'target', 'stage', 'rootNames', 'workspaceDirs', 'preimages', 'poolSeal', 'anchors', 'snapshotRoot', 'corpusRoot', 'sourceMappings', 'staged', 'report', 'mappings', 'contextWrites']) ||
258
+ detached.version !== 1 || typeof detached.lease !== 'string' || !(detached.poolSeal === null || typeof detached.poolSeal === 'string') ||
259
+ !detached.report || typeof detached.report !== 'object' || Array.isArray(detached.report) || typeof scratch !== 'string' || typeof target !== 'string' || typeof cleanup !== 'function') invalid();
260
+ const root = path.resolve(scratch), expectedTarget = path.resolve(target);
261
+ if (path.resolve(detached.temp || '') !== root || path.resolve(detached.stage || '') !== path.join(root, 'project') || path.resolve(detached.target || '') !== expectedTarget) invalid();
262
+ if (!Array.isArray(detached.contextWrites) || detached.contextWrites.some(file => typeof file !== 'string' || !within(root, file)) || !Array.isArray(detached.staged) || !Array.isArray(detached.mappings) || !Array.isArray(detached.rootNames) || !Array.isArray(detached.preimages) ||
263
+ !Array.isArray(detached.workspaceDirs) || !Array.isArray(detached.anchors) || !Array.isArray(detached.sourceMappings) ||
264
+ typeof detached.snapshotRoot !== 'string' || !path.isAbsolute(detached.snapshotRoot) || typeof detached.corpusRoot !== 'string' || !path.isAbsolute(detached.corpusRoot)) invalid();
265
+ if (detached.rootNames.some(name => !safeRelative(expectedTarget, name))) invalid();
266
+ const pool = inputPool && inputPools.get(inputPool);
267
+ if (inputPool && (!pool || pool.closed || !pool.transferable)) invalid();
268
+ if (pool) {
269
+ verifyInputPool(pool);
270
+ if (detached.poolSeal !== pool.inventorySeal || path.resolve(detached.snapshotRoot || '') !== pool.snapshotRoot) invalid();
271
+ } else if (detached.poolSeal) invalid();
272
+ const expectedArtifactRoot = path.resolve(resolveProjectAiwgDir(expectedTarget));
273
+ const validSourceMapping = item => within(root, item.to) || (pool && within(pool.snapshotRoot, item.to)) ||
274
+ (path.resolve(item.from) === path.join(expectedTarget, '.aiwg') && path.resolve(item.to) === expectedArtifactRoot);
275
+ if (detached.workspaceDirs.some(name => !safeRelative(expectedTarget, name)) ||
276
+ detached.preimages.some(item => !item || Object.keys(item).length !== 2 || typeof item.path !== 'string' || !path.isAbsolute(item.path) || !validPreimageState(item.state)) ||
277
+ detached.staged.some(item => !item || Object.keys(item).length !== 2 || typeof item.path !== 'string' || !within(root, item.path) || !validPreimageState(item.state)) ||
278
+ detached.sourceMappings.some(item => !item || Object.keys(item).length !== 2 || typeof item.from !== 'string' || !path.isAbsolute(item.from) ||
279
+ typeof item.to !== 'string' || !path.isAbsolute(item.to) || !validSourceMapping(item)) ||
280
+ detached.mappings.some(item => !item || Object.keys(item).length !== 3 || typeof item.from !== 'string' || !path.isAbsolute(item.from) ||
281
+ typeof item.to !== 'string' || !within(root, item.to) || within(root, item.from) || !Array.isArray(item.before) || item.before.some(entry =>
282
+ !Array.isArray(entry) || entry.length !== 2 || !safeRelative(item.to, entry[0]) || !/^[a-f0-9]{64}$/.test(entry[1])))) invalid();
283
+ const expectedStaged = [path.join(root, 'project'), ...detached.mappings.map(item => path.resolve(item.to))].sort();
284
+ if (JSON.stringify(detached.staged.map(item => path.resolve(item.path)).sort()) !== JSON.stringify([...new Set(expectedStaged)])) invalid();
285
+ const anchorPaths = expectedAnchorPaths([expectedTarget, ...detached.mappings.map(item => item.from), ...detached.workspaceDirs.map(name => path.join(expectedTarget, name))]);
286
+ if (detached.anchors.some(item => !item || typeof item.path !== 'string' || !path.isAbsolute(item.path) ||
287
+ (item.missing === true ? Object.keys(item).length !== 2 : Object.keys(item).sort().join(',') !== 'dev,ino,link,mode,path,real' ||
288
+ !['dev', 'ino', 'mode', 'real'].every(key => typeof item[key] === 'string') || !(item.link === null || typeof item.link === 'string'))) ||
289
+ JSON.stringify(detached.anchors.map(item => path.resolve(item.path)).sort()) !== JSON.stringify(anchorPaths)) invalid();
290
+ const plan = structuredClone(detached);
291
+ plan.lease = randomUUID();
292
+ if (pool) {
293
+ const existing = new Set(plan.preimages.map(item => path.resolve(item.path)));
294
+ plan.preimages.unshift(...pool.preimages.filter(item => !existing.has(path.resolve(item.path))));
295
+ pool.refs++;
296
+ }
297
+ const ownerCleanup = () => { try { cleanup(); } finally { if (pool) releaseInputPool(pool); } };
298
+ stagedCleanups.set(plan.lease, { temp: root, cleanup: ownerCleanup, pool, seal: planSeal(plan), transferable: false, detach: () => {} });
299
+ return plan;
300
+ }
@@ -20,14 +20,23 @@ export function projectOnDemandReferences(rules, nativePaths = false) {
20
20
  });
21
21
  }
22
22
 
23
- export function renderRuleKernelIndex(rules, nativePaths = false) {
23
+ export function renderRuleKernelIndex(rules, nativePaths = false, perRuleFetch = false, kernelFile) {
24
24
  const summary = rules.filter(rule => rule.tagged && (rule.canonicalActivation || rule.activation) === 'summary');
25
25
  const paths = rules.filter(rule => rule.tagged && (rule.canonicalActivation || rule.activation) === 'paths');
26
- const kernels = rules.filter(rule => rule.tagged && (rule.canonicalActivation || rule.activation) === 'kernel');
26
+ const kernels = rules.filter(rule => rule.tagged && (kernelFile || perRuleFetch ? rule.activation : rule.canonicalActivation || rule.activation) === 'kernel');
27
27
  if (!summary.length && !paths.length && !kernels.length) return '';
28
28
  const lines = ['# Rule kernel index', ''];
29
- for (const rule of kernels) lines.push(`- ${rule.name} — ${rule.summary || 'Fetch and follow the full rule before governed work.'} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`, '');
30
- for (const rule of summary) lines.push(`- ${rule.name} — ${rule.summary} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`, '');
29
+ // RULES-INDEX receipts are parsed by deployment accounting; retain their command format.
30
+ if (!perRuleFetch) lines.push("Fetch and follow each rule's full body before governed work: `aiwg show rule <name> --body`.", '');
31
+ if (kernelFile && kernels.length) lines.push('Read and follow every kernel file below before every task and subagent task.', '');
32
+ for (const rule of kernels) lines.push(kernelFile
33
+ ? `- ${rule.name} — ${rule.summary || 'Read and follow the complete kernel rule.'} Read and follow: [${kernelFile(rule)}](./${kernelFile(rule)}).`
34
+ : perRuleFetch
35
+ ? `- ${rule.name} — ${rule.summary || 'Fetch and follow the full rule before governed work.'} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`
36
+ : `- ${rule.name}${rule.summary ? ` — ${rule.summary}` : ''}`, '');
37
+ for (const rule of summary) lines.push(perRuleFetch
38
+ ? `- ${rule.name} — ${rule.summary} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`
39
+ : `- ${rule.name}${rule.summary ? ` — ${rule.summary}` : ''}`, '');
31
40
  if (paths.length) {
32
41
  lines.push(nativePaths ? '## Path rules (native)' : '## Path rules (prompt emulation)', '',
33
42
  nativePaths ? 'The provider loads these rules for matching paths; full contracts remain available through the commands below.' : 'Before reading or changing files, compare intended project-relative paths with the globs below and fetch matching rules before their first read/write. If paths are initially unknown, check when they become known. An agent-only task has no path match. This is prompt emulation, not a filesystem hook.', '');
@@ -0,0 +1,119 @@
1
+ /** Project activation-selected contracts into each harness's rules surface. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { stringify } from 'yaml';
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+ import { addManagedMarker, contentHash, stripTriggersFromContent } from './base.mjs';
7
+ import { projectOnDemandReferences, renderRuleKernelIndex } from './rule-presentation.mjs';
8
+ import { projectStartup } from './rule-startup.mjs';
9
+ import { writeContextFileSync } from './context-write.mjs';
10
+ export { inlineStartup } from './rule-startup.mjs';
11
+ const { parseRuleFrontmatter } = await importImpl(import.meta.url, 'rules/activation.mjs');
12
+ const { renderCoreStartup } = await importImpl(import.meta.url, 'rules/core-startup.mjs');
13
+ const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
14
+ const walk = dir => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
15
+ entry.isDirectory() ? walk(path.join(dir, entry.name)) : [path.join(dir, entry.name)]) : [];
16
+ const put = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); };
17
+ export const nativeRuleLoader = name => ['claude', 'cursor', 'grok-build', 'windsurf', 'opencode'].includes(name);
18
+ export const nativePathLoader = name => ['claude', 'cursor', 'windsurf'].includes(name);
19
+ export function ruleDirectory(opts, provider) {
20
+ // Muse has no declared rules path; use its existing .muse harness convention.
21
+ const dir = provider.paths.rules || (provider.name === 'grok-build' ? '.grok/rules' : `.${provider.name}/rules`);
22
+ return path.isAbsolute(dir) ? dir : path.join(opts.target, dir);
23
+ }
24
+ const ruleName = (rule, provider) => rule.behavior
25
+ ? `${['grok-build', 'windsurf'].includes(provider.name) ? 'behavior-' : 'behaviors/'}${path.basename(path.dirname(rule.file))}`
26
+ : path.basename(rule.file, '.md');
27
+ function nativeContent(provider, rule, content, opts) {
28
+ if (provider.name === 'cursor') return provider.transformRule(rule.file, content, opts);
29
+ if (provider.name === 'windsurf') {
30
+ const parsed = parseRuleFrontmatter(content);
31
+ const data = { ...parsed.data, trigger: rule.activation === 'paths' ? 'glob' : 'always_on' };
32
+ if (rule.activation === 'paths') data.glob = rule.paths.join(',');
33
+ return `---\n${stringify(data)}---\n${parsed.body}`;
34
+ }
35
+ return content;
36
+ }
37
+ function registerOpenCode(opts, provider, rulesDir) {
38
+ if (provider.name !== 'opencode') return;
39
+ const file = path.join(opts.target, 'opencode.json');
40
+ const config = JSON.parse(read(file) || '{}');
41
+ if (!config || Array.isArray(config) || typeof config !== 'object' ||
42
+ (config.instructions !== undefined && !Array.isArray(config.instructions))) {
43
+ throw new Error('OpenCode rule delivery requires an object with an instructions array in opencode.json');
44
+ }
45
+ const glob = `${path.relative(opts.target, rulesDir).replaceAll('\\', '/')}/*.md`;
46
+ config.instructions = [...new Set([...(config.instructions || []), 'AGENTS.md', 'AIWG.md', glob])];
47
+ writeContextFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
48
+ }
49
+ export function projectRules(opts, provider) {
50
+ const nativePaths = nativePathLoader(provider.name);
51
+ const rules = projectOnDemandReferences(opts.ruleDelivery.rules, nativePaths);
52
+ const rulesDir = ruleDirectory(opts, provider);
53
+ const tagged = rules.filter(rule => rule.tagged);
54
+ const extension = provider.name === 'cursor' ? '.mdc' : '.md';
55
+ const managed = content => addManagedMarker(content, opts.deployVersion, opts.deploySource || 'bundled');
56
+ const writeRule = (rule, content) => put(path.join(rulesDir, `${ruleName(rule, provider)}${extension}`), managed(content));
57
+ for (const file of walk(rulesDir)) {
58
+ if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file))) fs.rmSync(file);
59
+ }
60
+ const cores = [...new Map(tagged.filter(rule => rule.activation === 'core').map(rule => [rule.name, rule])).values()];
61
+ if (['claude', 'cursor'].includes(provider.name)) {
62
+ for (const rule of cores) {
63
+ const dest = path.join(rulesDir, `core-${path.basename(rule.file, '.md')}${extension}`);
64
+ if (fs.existsSync(dest) && !/aiwg:managed/.test(read(dest)) && !opts.force) {
65
+ console.warn(`Unmanaged core rule left in place: ${dest}. Re-run with --force to replace it.`);
66
+ continue;
67
+ }
68
+ put(dest, managed(provider.name === 'cursor' ? `---\nalwaysApply: true\n---\n${rule.coreBody}\n` : `${rule.coreBody}\n`));
69
+ }
70
+ }
71
+ for (const rule of tagged) {
72
+ if (rule.activation !== 'kernel' && !(nativePaths && rule.activation === 'paths')) continue;
73
+ let content = stripTriggersFromContent(rule.content);
74
+ if (rule.pinned) {
75
+ const parsed = parseRuleFrontmatter(content);
76
+ const data = { ...parsed.data, activation: 'kernel' };
77
+ delete data.paths; delete data.bound_to;
78
+ content = `---\n${stringify(data)}---\n${parsed.body}`;
79
+ }
80
+ writeRule(rule, nativeContent(provider, rule, content, opts));
81
+ }
82
+ for (const rule of rules.filter(rule => !rule.tagged && !rule.behavior)) {
83
+ const source = opts.logicalInputPath ? opts.logicalInputPath(rule.file) : rule.file;
84
+ if (/(?:^|\/)agentic\/code\//.test(source.replaceAll('\\', '/'))) continue;
85
+ writeRule(rule, nativeContent(provider, rule, stripTriggersFromContent(rule.content), opts));
86
+ }
87
+ const routes = [...new Set(opts.definitionRoutes || [])];
88
+ const routing = routes.length ? `## Invoked artifact definitions\n\nRead the complete definition before invoking its artifact:\n${routes.map(route => `- ${route}`).join('\n')}` : '';
89
+ const localKernels = !nativeRuleLoader(provider.name);
90
+ const index = [renderRuleKernelIndex(rules, nativePaths, true, localKernels ? rule => `${ruleName(rule, provider)}${extension}` : undefined), routing].filter(Boolean).join('\n\n');
91
+ const indexFile = path.join(rulesDir, `RULES-INDEX${extension}`);
92
+ if (index) put(indexFile, managed(nativeContent(provider, { activation: 'kernel', file: indexFile }, index, opts)));
93
+ const legacyDemand = rules.filter(rule => !rule.tagged && !rule.behavior && rule.activation === 'on-demand');
94
+ if (legacyDemand.length) put(path.join(rulesDir, `RULES-ONDEMAND${extension}`), managed([
95
+ '# On-demand rules', '', 'These rules require explicit activation metadata. Fetch the applicable full rule before governed work.', '',
96
+ ...legacyDemand.map(rule => `- \`${rule.name}\` — \`aiwg show rule ${rule.name} --body\``), '',
97
+ ].join('\n')));
98
+ const coreSection = renderCoreStartup(cores);
99
+ // Even an all-core install needs a real entry point rather than a dangling hook.
100
+ if (!index && (!['claude', 'cursor'].includes(provider.name) || tagged.length)) put(indexFile, managed(nativeContent(provider, { activation: 'kernel', file: indexFile }, '# Rule kernel index\n\nNo kernel or path rules selected.\n', opts)));
101
+ const startups = projectStartup(opts, provider, coreSection, indexFile);
102
+ registerOpenCode(opts, provider, rulesDir);
103
+ fs.rmSync(path.join(rulesDir, '.aiwg-rules-budget.json'), { force: true });
104
+ const manifestPath = path.join(rulesDir, '.aiwg-manifest.json');
105
+ const manifest = fs.existsSync(manifestPath) ? JSON.parse(read(manifestPath)) : { managed: {} };
106
+ manifest.ruleSources = rules.map(rule => rule.file);
107
+ const logical = opts.logicalOutputPath || (file => file);
108
+ const relative = file => path.relative(logical(opts.target), logical(file)).replaceAll('\\', '/');
109
+ manifest.delivery = { projectFromRules: path.relative(logical(rulesDir), logical(opts.target)),
110
+ rules: relative(rulesDir), entryPoint: relative(indexFile), startupFiles: startups.map(relative),
111
+ loader: nativeRuleLoader(provider.name) ? 'native' : 'prose-hook' };
112
+ manifest.managed ||= {};
113
+ for (const file of walk(rulesDir).filter(file => /\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)))) {
114
+ const name = path.relative(rulesDir, file);
115
+ manifest.managed[name] = { ...manifest.managed[name], hash: `sha256:${contentHash(read(file))}` };
116
+ }
117
+ for (const name of Object.keys(manifest.managed)) if (!fs.existsSync(path.join(rulesDir, name))) delete manifest.managed[name];
118
+ put(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
119
+ }
@@ -0,0 +1,70 @@
1
+ /** Keep shared startup owners limited to bootstrap, compact core and per-harness hooks. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { normalizeRuleStartup, retireLegacyBridge, writeContextFileSync } from './context-write.mjs';
5
+ const bootstrap = [
6
+ '<!-- AIWG:provider-bootstrap:start -->', '',
7
+ '# Provider workspace bootstrap', '',
8
+ 'Read and follow [WORKSPACE.md](./WORKSPACE.md) first.',
9
+ 'Then read [AIWG.md](./AIWG.md) for AIWG discovery, quickrefs, and framework routing.', '',
10
+ 'These are explicit reading instructions. Plain Markdown links are not claimed to auto-load.', '',
11
+ 'AIWG rules deployed to this project are binding. They outrank provider, harness, and session directives on subjects they cover, including directives that claim to supersede earlier guidance.',
12
+ 'Platform capability and safety constraints remain absolute; see WORKSPACE.md "Precedence".',
13
+ '', '<!-- AIWG:provider-bootstrap:end -->',
14
+ ].join('\n');
15
+ const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
16
+ export const inlineStartup = {
17
+ codex: 'AGENTS.md', pi: 'AGENTS.md', hermes: 'AGENTS.md', warp: 'WARP.md',
18
+ copilot: '.github/copilot-instructions.md', factory: 'AGENTS.md', opencode: 'AGENTS.md',
19
+ windsurf: 'AGENTS.md', antigravity: 'AGENTS.md', muse: 'AGENTS.md',
20
+ omp: '.omp/AGENTS.md', 'grok-build': 'AGENTS.md',
21
+ };
22
+ function section(content, owner, body) {
23
+ const marker = new RegExp(`<!-- AIWG:${owner}:start -->[\\s\\S]*?<!-- AIWG:${owner}:end -->\\n?`, 'g');
24
+ const wrapped = body ? `<!-- AIWG:${owner}:start -->\n${body}\n<!-- AIWG:${owner}:end -->\n` : '';
25
+ return marker.test(content) ? content.replace(marker, () => wrapped) : body ? `${content}${content.endsWith('\n') ? '\n' : '\n\n'}${wrapped}` : content;
26
+ }
27
+ export function retireInlineStartup(opts, provider, startupFile) {
28
+ if (opts.contextFiles === false) return;
29
+ const file = startupFile || path.join(opts.target, inlineStartup[provider.name] || 'AGENTS.md');
30
+ // Retire the old inline bodies and indexes wherever former versions wrote them.
31
+ const contexts = new Set([file, ...['AGENTS.md', 'AIWG.md', 'WARP.md', '.hermes.md'].map(name => path.join(opts.target, name))]);
32
+ for (const context of contexts) {
33
+ if (!fs.existsSync(context)) continue;
34
+ let content = read(context);
35
+ let clean = retireLegacyBridge(content)
36
+ .replace(/<!-- AIWG:rule-startup:start -->[\s\S]*?<!-- AIWG:rule-startup:end -->\n?/g, '')
37
+ .replace(/\n?<!-- AIWG:(?:hermes-(?:context|routing)|warp-context):start -->[\s\S]*?<!-- AIWG:(?:hermes-(?:context|routing)|warp-context):end -->\n?/g, '');
38
+ // Old Hermes releases emitted this unmarked section. Retire only its known
39
+ // heading/body through the next level-1/2 heading, preserving operator text.
40
+ clean = clean.replace(/^## CRITICAL Rules \(always apply\)\r?\n[\s\S]*?(?=^#{1,2} |^<!-- AIWG:|$(?![\s\S]))/gm, '');
41
+ const config = opts.config || JSON.parse(read(path.join(opts.target, '.aiwg/aiwg.config')) || '{}');
42
+ if (Array.isArray(config.providers)) {
43
+ const active = new Set([...config.providers, provider.name]);
44
+ clean = clean.replace(/<!-- AIWG:rule-hook-([\w-]+):start -->[\s\S]*?<!-- AIWG:rule-hook-\1:end -->\n?/g,
45
+ (block, name) => active.has(name) ? block : '');
46
+ }
47
+ if (clean !== content) writeContextFileSync(context, clean);
48
+ }
49
+ }
50
+ export function projectStartup(opts, provider, coreSection, indexFile) {
51
+ if (opts.contextFiles === false) return [];
52
+ const owner = inlineStartup[provider.name];
53
+ // Claude and Cursor retain their native loaders and compact core files.
54
+ if (!owner && ['claude', 'cursor'].includes(provider.name)) return [];
55
+ const file = provider.name === 'openclaw' ? path.join(opts.activeWorkspace, 'AGENTS.md')
56
+ : path.join(opts.target, owner || 'AGENTS.md');
57
+ retireInlineStartup(opts, provider, file);
58
+ const files = provider.name === 'hermes' ? [file, path.join(opts.target, '.hermes.md')] : [file];
59
+ for (const startup of files) {
60
+ let content = normalizeRuleStartup(read(startup), bootstrap, path.basename(startup) === 'AGENTS.md');
61
+ content = section(content, 'rule-core', coreSection.replace(/<!-- AIWG:(?:core-rules|rule-core):(?:start|end) -->\n?/g, '').trimEnd());
62
+ const logical = opts.logicalOutputPath || (file => file);
63
+ const location = path.relative(logical(opts.target), logical(indexFile)).replaceAll('\\', '/');
64
+ const hook = `${provider.name}: Before every task and subagent task, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
65
+ content = section(content, `rule-hook-${provider.name}`, hook);
66
+ fs.mkdirSync(path.dirname(startup), { recursive: true });
67
+ writeContextFileSync(startup, content);
68
+ }
69
+ return files;
70
+ }
@@ -0,0 +1,128 @@
1
+ /** Preserve projector-owned rules while pruning stale legacy flat artifacts. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { computeAllArtifactBasenames, computeAllSkillNames, pruneStaleAiwgFiles, resolveAiwgRoot } from './base.mjs';
5
+
6
+ /**
7
+ * After a deploy, prune AIWG-managed flat artifacts (agents/commands/rules)
8
+ * whose source no longer ships them — mirroring the skills holistic prune.
9
+ *
10
+ * Safety boundaries:
11
+ * - Runs ONLY for AIWG framework/addon deploys (default source = AIWG root,
12
+ * or `--source` under `<aiwgRoot>/agentic/code`). Project-local bundle
13
+ * deploys (`--source <bundle>`) are skipped so a bundle's just-deployed
14
+ * artifacts are never mistaken for stale framework files.
15
+ * - `pruneStaleAiwgFiles` itself only removes files carrying an AIWG
16
+ * ownership signal (sidecar entry or `aiwg:managed` marker) AND whose
17
+ * stem is absent from the global, mode-independent source set, so
18
+ * user-authored files and sibling-framework artifacts always survive.
19
+ * - Aggregate-file paths (e.g. `AGENTS.md`) and unset paths are skipped.
20
+ *
21
+ * @param {object} provider loaded provider module
22
+ * @param {string} target deploy target dir
23
+ * @param {string} srcRoot effective deploy source
24
+ * @param {object} opts deploy opts (dryRun/verbose/quiet + deploy flags)
25
+ * @param {string|null} explicitSource the raw `--source` value (null when unset)
26
+ */
27
+ /** Bundles whose deploy is itself the kernel-only bulk install. */
28
+ const BULK_INSTALL_BUNDLES = new Set(['all']);
29
+
30
+ /**
31
+ * True when the kernel-only bulk install is the only thing this project has
32
+ * deployed, so clearing leftover flat artifacts is a migration and not a
33
+ * deletion of another bundle's surface (#2508).
34
+ *
35
+ * A project with no readable `.aiwg/aiwg.config` has no recorded owner, so the
36
+ * pre-#152 migration cleanup still applies.
37
+ */
38
+ export function bulkInstallOwnsFlatArtifacts(target) {
39
+ let installed;
40
+ try {
41
+ const raw = fs.readFileSync(path.join(target, '.aiwg', 'aiwg.config'), 'utf8');
42
+ installed = JSON.parse(raw)?.installed;
43
+ } catch {
44
+ return true;
45
+ }
46
+ if (!installed || typeof installed !== 'object') return true;
47
+ return !Object.keys(installed).some(name => !BULK_INSTALL_BUNDLES.has(name));
48
+ }
49
+
50
+ export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explicitSource) {
51
+ if (opts.skillsOnly && !opts.kernelOnly) return; // skills run their own prune in the provider
52
+
53
+ const aiwgRoot = resolveAiwgRoot(srcRoot);
54
+ if (!aiwgRoot) return; // no AIWG tree → bundle/standalone deploy; never prune
55
+
56
+ // Gate: only framework/addon deploys are eligible. A default deploy (no
57
+ // --source) sources from the AIWG root. An explicit --source is eligible
58
+ // only when it lives under <aiwgRoot>/agentic/code (bundled fw/addon).
59
+ if (explicitSource) {
60
+ const codeRoot = path.join(aiwgRoot, 'agentic', 'code');
61
+ const rel = path.relative(codeRoot, path.resolve(explicitSource));
62
+ const underCode = !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
63
+ if (!underCode) return; // project-local bundle / external source → skip
64
+ }
65
+
66
+ if (opts.kernelOnly) {
67
+ // Kernel-only delivers skills and rules. The empty desired set below
68
+ // applies only to bulk agents/commands left by
69
+ // the pre-#152 bulk default, when the bulk install is the only thing this
70
+ // project ever deployed.
71
+ //
72
+ // #2508: applying it unconditionally deleted every artifact a sibling
73
+ // bundle owned — `aiwg use sdlc` followed by `aiwg use all` took
74
+ // .claude/agents from 139 to 0. When another bundle is installed, it owns
75
+ // this surface deliberately and the migration assumption does not hold.
76
+ if (!bulkInstallOwnsFlatArtifacts(target)) {
77
+ if (opts.verbose) {
78
+ console.log('skip kernel-only flat prune: another installed bundle owns agents/commands/rules');
79
+ }
80
+ return;
81
+ }
82
+ for (const type of ['agents', 'commands']) {
83
+ const relPath = provider.paths?.[type];
84
+ if (!relPath || relPath.endsWith('.md')) continue;
85
+ const destDir = path.isAbsolute(relPath) ? relPath : path.join(target, relPath);
86
+ pruneStaleAiwgFiles(destDir, new Set(), {
87
+ dryRun: opts.dryRun,
88
+ verbose: opts.verbose,
89
+ artifactExtensions: ['.md', '.mdc', '.toml'],
90
+ });
91
+ }
92
+ return;
93
+ }
94
+
95
+ const typesThisRun = [];
96
+ if (!opts.commandsOnly && !opts.rulesOnly) typesThisRun.push('agents');
97
+ if (opts.deployCommands || opts.commandsOnly) typesThisRun.push('commands');
98
+ if (opts.deployRules || opts.rulesOnly) typesThisRun.push('rules');
99
+
100
+ for (const type of typesThisRun) {
101
+ const relPath = provider.paths?.[type];
102
+ if (!relPath) continue; // type not file-deployed by provider
103
+ if (relPath.endsWith('.md')) continue; // aggregate file (e.g. AGENTS.md)
104
+
105
+ const desired = computeAllArtifactBasenames(srcRoot, type);
106
+ if (!desired) continue; // no global desired set → skip
107
+
108
+ const destDir = path.isAbsolute(relPath) ? relPath : path.join(target, relPath);
109
+ // Activation projection owns its complete selected rule set, including extensions.
110
+ // Its transactional replacement already removes retired managed rule files.
111
+ if (type === 'rules') {
112
+ const receipt = path.join(destDir, '.aiwg-manifest.json');
113
+ if (fs.existsSync(receipt) && JSON.parse(fs.readFileSync(receipt, 'utf8')).delivery) continue;
114
+ }
115
+ const removed = pruneStaleAiwgFiles(destDir, desired, {
116
+ dryRun: opts.dryRun,
117
+ verbose: opts.verbose,
118
+ // Retire wrappers whose source skill no longer ships (#2511). Only the
119
+ // command directory holds them; the kernel-only branch returns earlier,
120
+ // so a bulk install still cannot touch wrappers it did not write.
121
+ skillCommandStems: type === 'commands' ? computeAllSkillNames(srcRoot) : null,
122
+ });
123
+ if (removed.length > 0 && !opts.quiet) {
124
+ console.log(` Pruned: ${removed.length} stale AIWG ${type} file${removed.length === 1 ? '' : 's'}`);
125
+ }
126
+ }
127
+ }
128
+