@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
@@ -1,4 +1,5 @@
1
- import { writeContextFileSync } from './context-file-safety.js';
1
+ import { maskCodeRegions } from './code-regions.js';
2
+ import { assertSafeContextFile, writeContextFileSync } from './context-file-safety.js';
2
3
  /**
3
4
  * Context-finalization pass for generated provider context files.
4
5
  *
@@ -8,7 +9,7 @@ import { writeContextFileSync } from './context-file-safety.js';
8
9
  */
9
10
  import { promises as fs } from 'node:fs';
10
11
  import * as path from 'node:path';
11
- import { projectAiwgPath, projectControlPath, resolveProjectAiwgDir, } from '../../config/project-artifacts.js';
12
+ import { projectControlPath, } from '../../config/project-artifacts.js';
12
13
  import { renderTrackerProtocol, resolveTrackerAuthority } from '../../tracker/capability-protocol.js';
13
14
  import { readConfig, readGitRemoteUrls } from '../../tracker/project-inputs.js';
14
15
  import { DECISION_COMPACT_ANCHOR, inspectDecisionOffloadActivation } from '../../decision/offload-activation.js';
@@ -46,8 +47,7 @@ export async function buildContextFinalizationBlock(projectPath, documentPath =
46
47
  const installed = Object.entries(config?.installed ?? {});
47
48
  const installedNames = installed.map(([name]) => name);
48
49
  const providerDeployments = new Set();
49
- const normalizedAiwgMdPath = displayProjectPath(projectPath, projectControlPath(projectPath, 'AIWG.md'));
50
- const normalizedAiwgMdLabel = `\`${normalizedAiwgMdPath}\``;
50
+ const notesPath = displayProjectPath(projectPath, projectControlPath(projectPath, 'AIWG.md'));
51
51
  for (const [, entry] of installed) {
52
52
  for (const provider of Object.keys(entry.deployedTo ?? {})) {
53
53
  providerDeployments.add(provider);
@@ -66,7 +66,7 @@ export async function buildContextFinalizationBlock(projectPath, documentPath =
66
66
  `- Configured providers: ${formatList(providers)}`,
67
67
  `- Installed frameworks/addons: ${formatList(installedNames)}`,
68
68
  `- Recorded deployments: ${formatList([...providerDeployments].sort())}`,
69
- `- Normalized project context: \`${normalizedAiwgMdPath}\``,
69
+ '- Generated framework context: `AIWG.md`',
70
70
  '',
71
71
  '### Capability Routing',
72
72
  '',
@@ -82,9 +82,10 @@ export async function buildContextFinalizationBlock(projectPath, documentPath =
82
82
  '',
83
83
  '### Source Model',
84
84
  '',
85
- `- ${normalizedAiwgMdLabel} is the normalized project-local context entry point.`,
86
- '- Root `AIWG.md` is the generated cross-provider companion loaded through `AGENTS.md` and provider twins.',
87
- `- \`AGENTS.md\`, \`WARP.md\`, \`.hermes.md\`, and \`.github/copilot-instructions.md\` are provider-facing bridges, not replacements for ${normalizedAiwgMdLabel}.`,
85
+ '- Root `AIWG.md` is the single generated framework context loaded through provider startup hooks.',
86
+ `- Optional \`${notesPath}\` contains only operator-authored notes, folded into root AIWG.md on regenerate.`,
87
+ '- Edit WORKSPACE.md Project Context for project conventions; edit .aiwg/AIWG.md only for optional framework notes, then run `aiwg regenerate`.',
88
+ '- `AGENTS.md`, `CLAUDE.md`, `WARP.md`, `.hermes.md`, and `.github/copilot-instructions.md` are provider-facing bridges.',
88
89
  ...(decision.shouldAnchor ? ['', '## Compact Instructions', '', DECISION_COMPACT_ANCHOR] : []),
89
90
  FINALIZATION_END,
90
91
  '',
@@ -99,53 +100,82 @@ export function replaceOrAppendFinalizationBlock(content, block) {
99
100
  const trimmed = content.replace(/\s+$/, '');
100
101
  return `${trimmed}\n\n${block}`;
101
102
  }
103
+ /** Compatibility renderer: normalized context now lives at the project root. */
102
104
  export async function buildNormalizedAiwgMd(projectPath, existing = '') {
103
- const normalizedDocumentPath = projectControlPath(projectPath, 'AIWG.md');
104
- const block = await buildContextFinalizationBlock(projectPath, normalizedDocumentPath);
105
- const externalLinksSection = await buildExternalLinksSection(projectPath);
106
- const normalizedAiwgMdPath = displayProjectPath(projectPath, projectControlPath(projectPath, 'AIWG.md'));
107
- const base = existing.trim().length > 0
108
- ? existing
109
- : [
110
- '# AIWG.md',
111
- AIWG_SIGNATURE_COMMENT,
112
- '<!-- Normalized project-local AIWG context. Operator notes may live outside AIWG-managed blocks. -->',
113
- '',
114
- `This file is the stable \`${normalizedAiwgMdPath}\` entry point for AIWG skills, rules, and generated provider context.`,
115
- '',
116
- ].join('\n');
117
- const signed = base.includes(AIWG_SIGNATURE_COMMENT)
118
- ? base
119
- : base.replace(/^([^\n]*)(\n|$)/, `$1\n${AIWG_SIGNATURE_COMMENT}\n`);
120
- const withFinalization = replaceOrAppendFinalizationBlock(signed, block);
121
- return replaceOrAppendExternalLinksBlock(withFinalization, externalLinksSection);
105
+ const block = await buildContextFinalizationBlock(projectPath);
106
+ const base = existing || '# AIWG.md\n<!-- aiwg-managed -->\n';
107
+ const signed = base.includes(AIWG_SIGNATURE_COMMENT) ? base : `${AIWG_SIGNATURE_COMMENT}\n${base}`;
108
+ return replaceOrAppendExternalLinksBlock(replaceOrAppendFinalizationBlock(signed, block), await buildExternalLinksSection(projectPath));
122
109
  }
123
- export async function writeNormalizedAiwgMd(projectPath) {
124
- const targetPath = projectControlPath(projectPath, 'AIWG.md');
125
- let existing = '';
126
- try {
127
- existing = await fs.readFile(targetPath, 'utf8');
128
- }
129
- catch (err) {
130
- if (err.code !== 'ENOENT')
131
- throw err;
110
+ /** Remove only the contiguous legacy wrapper at the head, never quoted body lines. */
111
+ function stripLegacyNotesHeader(content) {
112
+ const lines = content.replace(/^\uFEFF/, '').split(/(?<=\n)/);
113
+ const wrappers = [
114
+ /^# AIWG\.md$/,
115
+ /^<!-- aiwg-managed -->$/,
116
+ /^<!-- Normalized project-local AIWG context\. Operator notes may live outside AIWG-managed blocks\. -->$/,
117
+ /^This file is the stable `[^`]+` entry point for AIWG skills, rules, and generated provider context\.$/,
118
+ ];
119
+ const removed = new Set();
120
+ for (let i = 0; i < Math.min(lines.length, 12); i++) {
121
+ const line = lines[i].replace(/\r?\n$/, '');
122
+ if (!line.trim())
123
+ continue;
124
+ const wrapper = wrappers.findIndex(pattern => pattern.test(line));
125
+ if (wrapper < 0 || removed.has(wrapper))
126
+ break;
127
+ removed.add(wrapper);
128
+ lines[i] = '';
132
129
  }
133
- const content = await buildNormalizedAiwgMd(projectPath, existing);
134
- await fs.mkdir(path.dirname(targetPath), { recursive: true });
135
- const normalizedContent = content.endsWith('\n') ? content : `${content}\n`;
136
- writeContextFileSync(targetPath, normalizedContent, 'utf8');
137
- const artifactRoot = resolveProjectAiwgDir(projectPath);
138
- const artifactPath = projectAiwgPath(projectPath, 'AIWG.md');
139
- if (artifactPath !== targetPath) {
140
- try {
141
- await fs.access(artifactRoot);
142
- writeContextFileSync(artifactPath, normalizedContent, 'utf8');
143
- }
144
- catch (error) {
145
- if (error.code !== 'ENOENT')
146
- throw error;
130
+ return lines.join('');
131
+ }
132
+ /** Strip only known generated wrappers; unknown text always belongs to the operator. */
133
+ export function extractAiwgOperatorNotes(existing) {
134
+ if (!existing.includes(AIWG_SIGNATURE_COMMENT))
135
+ return existing;
136
+ let notes = stripLegacyNotesHeader(existing);
137
+ for (const [start, end] of [
138
+ [FINALIZATION_START, FINALIZATION_END],
139
+ ['<!-- aiwg-external-links:start -->', '<!-- aiwg-external-links:end -->'],
140
+ ]) {
141
+ const pattern = new RegExp(`${start}[\\s\\S]*?${end}\\r?\\n?`, 'g');
142
+ // Match in masked prose, then cut those exact offsets from the original.
143
+ const matches = [...maskCodeRegions(notes).matchAll(pattern)];
144
+ for (const match of matches.reverse()) {
145
+ notes = notes.slice(0, match.index) + notes.slice(match.index + match[0].length);
147
146
  }
148
147
  }
149
- return targetPath;
148
+ return notes.trim() ? notes.replace(/^(?:\r?\n)+/, '') : '';
149
+ }
150
+ export async function readAiwgOperatorNotes(projectPath) {
151
+ const target = projectControlPath(projectPath, 'AIWG.md');
152
+ await assertSafeContextFile(target);
153
+ let existing = null;
154
+ try {
155
+ existing = await fs.readFile(target, 'utf8');
156
+ }
157
+ catch (error) {
158
+ if (error.code !== 'ENOENT')
159
+ throw error;
160
+ }
161
+ return { path: target, existing, notes: extractAiwgOperatorNotes(existing ?? '') };
162
+ }
163
+ /** Keep legacy files notes-only; journal even an empty migration for rollback. */
164
+ export async function migrateAiwgOperatorNotes(projectPath) {
165
+ const { path: target, existing, notes } = await readAiwgOperatorNotes(projectPath);
166
+ if (existing !== null && existing !== notes)
167
+ writeContextFileSync(target, notes, 'utf8');
168
+ }
169
+ /** Compatibility writer used by init: emit only the generated root context. */
170
+ export async function writeNormalizedAiwgMd(projectPath, stagedClaudeMdContent) {
171
+ const target = path.join(projectPath, 'AIWG.md');
172
+ await assertSafeContextFile(target);
173
+ const { isOverwriteSafe } = await import('./generator.js');
174
+ if (!(await isOverwriteSafe(target)))
175
+ return target;
176
+ const { buildAiwgMdContent } = await import('./aiwg-md.js');
177
+ writeContextFileSync(target, await buildAiwgMdContent(projectPath, stagedClaudeMdContent), 'utf8');
178
+ await migrateAiwgOperatorNotes(projectPath);
179
+ return target;
150
180
  }
151
181
  //# sourceMappingURL=finalization.js.map
@@ -6,10 +6,10 @@ import * as path from 'node:path';
6
6
  import { readdirSync, readFileSync } from 'node:fs';
7
7
  import { sanitizeDescription, sanitizeTags } from './sanitizer.js';
8
8
  import { checkPathAllowed } from './allowlist.js';
9
- import { generateAiwgMd } from './aiwg-md.js';
9
+ import { generateAiwgMdForPipeline as generateAiwgMd } from './aiwg-md.js';
10
10
  import { injectSpilloverBlock } from './overflow.js';
11
- import { writeNormalizedAiwgMd } from './finalization.js';
12
- import { shouldEmitAgentsMd, shouldEmitAiwgMd, shouldEmitClaudeMdHook } from './provider-policy.js';
11
+ import { migrateAiwgOperatorNotes } from './finalization.js';
12
+ import { shouldEmitAgentsMd, shouldEmitClaudeMdHook } from './provider-policy.js';
13
13
  import { ensureClaudeMdHook } from './claude-hook.js';
14
14
  import { ensureManagedHook } from './managed-hook.js';
15
15
  import { assertSafeContextFile, writeContextFileSync } from './context-file-safety.js';
@@ -279,10 +279,9 @@ async function writeSpilloverBlock(projectPath, spilloverMarkdown, result) {
279
279
  /**
280
280
  * Generate the canonical graph and provider startup adapters.
281
281
  *
282
- * Skeleton implementation: emits AGENTS.md with link-index sections; AIWG.md
283
- * generation is wired in commit 3 alongside the first issue closure (#1104).
284
- * For now AIWG.md emission delegates to a copy of CLAUDE.md when the source
285
- * is present; otherwise it is skipped with a warning.
282
+ * Root AIWG.md is the single generated framework context, including optional
283
+ * operator notes. Provider adapters declare their supported startup loader;
284
+ * home-only providers can still read the root context explicitly.
286
285
  */
287
286
  export async function generate(opts) {
288
287
  // Check every startup/context output before writing the first one. A linked
@@ -291,7 +290,7 @@ export async function generate(opts) {
291
290
  const plannedFiles = [
292
291
  ...(!opts.skip?.workspaceMd ? ['WORKSPACE.md'] : []),
293
292
  ...(!opts.skip?.agentsMd && shouldEmitAgentsMd(opts.provider) ? ['AGENTS.md'] : []),
294
- ...(!opts.skip?.aiwgMd && shouldEmitAiwgMd(opts.provider) ? ['AIWG.md'] : []),
293
+ ...(!opts.skip?.aiwgMd ? ['AIWG.md'] : []),
295
294
  ...(shouldEmitClaudeMdHook(opts.provider) ? ['CLAUDE.md'] : []),
296
295
  ];
297
296
  for (const file of plannedFiles)
@@ -316,8 +315,6 @@ export async function generate(opts) {
316
315
  if (workspace.backupPath)
317
316
  result.backupPaths.push(workspace.backupPath);
318
317
  }
319
- const normalizedAiwgPath = await writeNormalizedAiwgMd(opts.projectPath);
320
- result.normalizedAiwgMdPath = normalizedAiwgPath;
321
318
  // AGENTS.md emission is gated on the provider's link-mechanism: codex/copilot/
322
319
  // cursor/windsurf/hermes/warp/factory/opencode use AGENTS.md as their bridge
323
320
  // to AIWG.md. Claude uses CLAUDE.md hook instead (#1437); openclaw is
@@ -371,7 +368,7 @@ export async function generate(opts) {
371
368
  // additive hook), so this runs whether or not AGENTS.md itself was rewritten.
372
369
  await writeTwinFiles(opts.provider, opts.projectPath, built.content, opts, result);
373
370
  }
374
- if (!opts.skip?.aiwgMd && shouldEmitAiwgMd(opts.provider)) {
371
+ if (!opts.skip?.aiwgMd) {
375
372
  const aiwgMdPath = path.join(opts.projectPath, 'AIWG.md');
376
373
  let canWrite = true;
377
374
  if (opts.detectExistingFiles && !opts.force) {
@@ -400,6 +397,8 @@ export async function generate(opts) {
400
397
  const content = await generateAiwgMd(opts.projectPath);
401
398
  await atomicWrite(aiwgMdPath, content);
402
399
  result.aiwgMdPath = aiwgMdPath;
400
+ result.normalizedAiwgMdPath = aiwgMdPath; // Compatibility alias: there is only one generated context.
401
+ await migrateAiwgOperatorNotes(opts.projectPath);
403
402
  }
404
403
  }
405
404
  // CLAUDE.md hook emission for the claude provider (#1437). Mirrors how
@@ -29,7 +29,7 @@ export function buildContextHookBlock(provider = 'codex') {
29
29
  '<!--',
30
30
  ' This block is managed by `aiwg regenerate` and `aiwg use`.',
31
31
  ' Operator content above and below this block is preserved on regenerate.',
32
- ' Edit .aiwg/AIWG.md (the normalized source) then run `aiwg regenerate`.',
32
+ ' Edit WORKSPACE.md Project Context or optional .aiwg/AIWG.md operator notes, then run `aiwg regenerate`.',
33
33
  '-->',
34
34
  '',
35
35
  CONTEXT_HOOK_END,
@@ -31,8 +31,8 @@ export function buildMuseBridgeText() {
31
31
  'Muse session so the bridge is read.',
32
32
  '',
33
33
  'Instruction order: this AGENTS.md first, then [WORKSPACE.md](./WORKSPACE.md)',
34
- 'for project/operator context, then [AIWG.md](./AIWG.md) (canonical source:',
35
- '`.aiwg/AIWG.md`) for AIWG discovery, quickrefs, and framework routing.',
34
+ 'for project/operator context, then [AIWG.md](./AIWG.md), the single generated',
35
+ 'context for AIWG discovery, quickrefs, and framework routing.',
36
36
  'Plain Markdown links are explicit reading instructions; AIWG does not',
37
37
  'claim Muse auto-loads any other AIWG path on its own.',
38
38
  '',
@@ -11,8 +11,8 @@
11
11
  * with the misleading rationale "claude uses CLAUDE.md natively." That
12
12
  * conflated two facts: claude DOES read CLAUDE.md without aiwg-side
13
13
  * wiring, but regenerate STILL needs to refresh AIWG.md and ensure the
14
- * `@AIWG.md` link is present in CLAUDE.md. The fix splits the policy
15
- * into three granular gates so each provider gets exactly what it needs.
14
+ * `@AIWG.md` link is present in CLAUDE.md. The provider hooks remain granular;
15
+ * root AIWG.md is now universal (#3762).
16
16
  *
17
17
  * @issue #1437
18
18
  */
@@ -27,19 +27,13 @@ import { getProviderDefinition, listProviderDefinitions } from '../../providers/
27
27
  export const AGENTS_MD_PROVIDERS = new Set(listProviderDefinitions()
28
28
  .filter((definition) => definition.paths.contextFiles.agentsMd)
29
29
  .map((definition) => definition.id));
30
- /**
31
- * Whether the context-pipeline has ANY work to do for this provider.
32
- * Returns false only for providers that have no project-local context
33
- * footprint: OpenClaw/OpenHuman (home-dir-only) and 'generic' (no specific provider).
34
- *
35
- * Claude returns TRUE — it needs AIWG.md + a CLAUDE.md hook update.
36
- */
30
+ /** Compatibility query: every registered provider receives root AIWG.md (#3762). */
37
31
  export function shouldEmitContextFiles(provider) {
38
- return shouldEmitAiwgMd(provider) || shouldEmitClaudeMdHook(provider);
32
+ return shouldEmitAiwgMd(provider);
39
33
  }
40
34
  /**
41
- * Whether to emit AIWG.md at project root. True for every project-local
42
- * provider; false only for home-dir-only providers and 'generic'.
35
+ * Compatibility query, no longer an emission gate. Root AIWG.md is always
36
+ * generated; only an explicit caller opt-out can suppress it (#3762).
43
37
  */
44
38
  export function shouldEmitAiwgMd(provider) {
45
39
  return getProviderDefinition(provider)?.paths.contextFiles.aiwgMd ?? false;
@@ -0,0 +1,299 @@
1
+ // Audit workspace instruction sources and directive overlap.
2
+ import { existsSync, promises as fs } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import * as path from 'node:path';
5
+ import { projectAiwgPath, resolveProjectAiwgDir } from '../../config/project-artifacts.js';
6
+ import { listProviderDefinitions } from '../../providers/provider-definitions.js';
7
+ import { isGeneratedRootContext, LEGACY_ROOT_FILES, readOptional, SCOPE_REVIEW_BYTES, sha256, stripGeneratedBlocks, WORKSPACE_OPERATOR_END, WORKSPACE_OPERATOR_START, WORKSPACE_SIGNATURE, } from './workspace-context-shared.js';
8
+ import { providerForPath } from './workspace-document.js';
9
+ import { extractExistingProjectContext } from './workspace-extraction.js';
10
+ import { projectOutputPath } from './workspace-migration.js';
11
+ export function directives(content) {
12
+ return [...new Set(content
13
+ .split('\n')
14
+ .map((line) => line.replace(/^\s*[-*+]\s+/, '').replace(/^#+\s+/, '').trim())
15
+ .filter((line) => line.length >= 8 && !line.startsWith('<!--') && !/^https?:\/\//i.test(line)))];
16
+ }
17
+ export function directiveKey(directive) {
18
+ if (!/^(always|never|must|do not|don't|required|prefer|use|avoid|keep|preserve)\b/i.test(directive))
19
+ return null;
20
+ return directive.toLowerCase()
21
+ .replace(/[^a-z0-9\s]/g, '')
22
+ .replace(/^(?:always|never|must|required|prefer|avoid|keep|preserve|do not|dont)\s+/, '')
23
+ .replace(/^use\s+/, '')
24
+ .split(/\s+/).slice(0, 5).join(' ');
25
+ }
26
+ export function directivePolarity(directive) {
27
+ return /^(?:never|do not|don't|avoid)\b/i.test(directive) ? 'negative' : 'positive';
28
+ }
29
+ export function sensitiveEvidence(content) {
30
+ const findings = [];
31
+ for (const line of content.split('\n')) {
32
+ if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(line)) {
33
+ findings.push(`private-key material (${sha256(line).slice(0, 12)})`);
34
+ }
35
+ if (/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*(?!<|\$\{|\*{3}|example|placeholder)["']?[A-Za-z0-9_\-/.+=]{12,}/i.test(line)) {
36
+ findings.push(`credential-like assignment (${sha256(line).slice(0, 12)})`);
37
+ }
38
+ }
39
+ return findings;
40
+ }
41
+ // Directory names the context-graph walk always skips, regardless of where
42
+ // the walk root is: VCS/build output that is never hand-authored project
43
+ // content (#277, pre-existing) plus two reserved, self-identifying names
44
+ // that are never legitimately a real project directory.
45
+ export const CONTEXT_WALK_ALWAYS_IGNORED_DIR_NAMES = new Set([
46
+ '.git', 'node_modules', 'dist', 'build', 'coverage', '.aiwg',
47
+ ]);
48
+ // Cache/registry directory names that are only skipped when the walk root
49
+ // is the home directory itself (#277 fix-round). A project subtree that
50
+ // happens to be named `.cache`, `target`, `.gradle`, etc. is NOT generated
51
+ // data and must still be scanned — these names are only reliably "cache,
52
+ // not project" when they sit directly under $HOME. `Library/Caches` and
53
+ // `.local/share` are two-segment (parent + name) patterns, handled
54
+ // separately below.
55
+ export const HOME_LEVEL_CACHE_DIR_NAMES = new Set([
56
+ '.cache', '.cargo', '.rustup', '.npm', '.nvm', '.pnpm-store',
57
+ '.gradle', '.m2', 'Trash',
58
+ ]);
59
+ /** True when `dirPath` contains `markerFile` — a cheap, synchronous, read-only check. */
60
+ export function hasMarkerFile(dirPath, markerFile) {
61
+ return existsSync(path.join(dirPath, markerFile));
62
+ }
63
+ /** A `target` directory is Cargo/build output only when it carries the
64
+ * standard `CACHEDIR.TAG` marker, or sits next to a `Cargo.toml` — not
65
+ * merely because it is named `target` (#277 fix-round). */
66
+ export function isGeneratedTargetDir(dirPath) {
67
+ if (hasMarkerFile(dirPath, 'CACHEDIR.TAG'))
68
+ return true;
69
+ return existsSync(path.join(path.dirname(dirPath), 'Cargo.toml'));
70
+ }
71
+ /** A `venv`/`.venv` directory is a Python virtualenv only when it carries
72
+ * `pyvenv.cfg` — not merely because of its name (#277 fix-round). */
73
+ export function isPythonVenvDir(dirPath) {
74
+ return hasMarkerFile(dirPath, 'pyvenv.cfg');
75
+ }
76
+ /**
77
+ * Whether the context-graph walk should skip `entryName` (a directory
78
+ * directly under `directory`) without descending into it.
79
+ *
80
+ * `isHomeRoot` gates the home-level cache list and the `Library/Caches` /
81
+ * `.local/share` two-segment patterns — they apply only when the overall
82
+ * walk root is $HOME, never for an arbitrary project subtree that happens
83
+ * to share one of those names (#277 fix-round).
84
+ */
85
+ export function shouldSkipContextWalkDir(directory, entryName, isHomeRoot) {
86
+ if (CONTEXT_WALK_ALWAYS_IGNORED_DIR_NAMES.has(entryName))
87
+ return true;
88
+ if (entryName.startsWith('.context-migration-'))
89
+ return true;
90
+ const childPath = path.join(directory, entryName);
91
+ if (entryName === 'target' && isGeneratedTargetDir(childPath))
92
+ return true;
93
+ if ((entryName === 'venv' || entryName === '.venv') && isPythonVenvDir(childPath))
94
+ return true;
95
+ // Codex's own plugin/temp scratch — a known, specific noise source named
96
+ // in the original report, not a broad `.tmp` exclusion (#277 fix-round).
97
+ if (entryName === '.tmp' && path.basename(directory) === '.codex')
98
+ return true;
99
+ if (isHomeRoot) {
100
+ if (HOME_LEVEL_CACHE_DIR_NAMES.has(entryName))
101
+ return true;
102
+ if (entryName === 'Caches' && path.basename(directory) === 'Library')
103
+ return true;
104
+ if (entryName === 'share' && path.basename(directory) === '.local')
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+ /** Walk depth/entry bounds for the context-graph walk (#277). A hit sets
110
+ * `truncated: true` on the result instead of silently stopping. Overridable
111
+ * via environment for tests that need to exercise the bound without
112
+ * building a correspondingly large fixture tree. */
113
+ export function readPositiveIntEnv(name, fallback) {
114
+ const raw = process.env[name];
115
+ if (!raw)
116
+ return fallback;
117
+ const parsed = Number.parseInt(raw, 10);
118
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
119
+ }
120
+ export const CONTEXT_WALK_MAX_DEPTH = readPositiveIntEnv('AIWG_CONTEXT_WALK_MAX_DEPTH', 10);
121
+ export const CONTEXT_WALK_MAX_DIRECTORIES = readPositiveIntEnv('AIWG_CONTEXT_WALK_MAX_DIRECTORIES', 20_000);
122
+ export async function nestedInstructionFiles(projectPath) {
123
+ const found = [];
124
+ const artifactRoot = path.resolve(resolveProjectAiwgDir(projectPath));
125
+ // Running from $HOME is the exact shape of #277: bound the walk to the
126
+ // top level and apply the home-level cache exclusions instead of
127
+ // recursing into every cache/registry/venv underneath it. A markerless
128
+ // but otherwise ordinary (non-home) project root keeps the full bounded
129
+ // walk — "no project marker" is not evidence the directory is generated
130
+ // data (#277 fix-round).
131
+ const isHomeDirectory = path.resolve(projectPath) === path.resolve(homedir());
132
+ const maxDepth = isHomeDirectory ? 1 : CONTEXT_WALK_MAX_DEPTH;
133
+ let visitedDirectories = 0;
134
+ let truncated = false;
135
+ async function walk(directory, depth) {
136
+ if (depth > maxDepth || visitedDirectories >= CONTEXT_WALK_MAX_DIRECTORIES) {
137
+ truncated = true;
138
+ return;
139
+ }
140
+ visitedDirectories += 1;
141
+ let entries;
142
+ try {
143
+ entries = await fs.readdir(directory, { withFileTypes: true });
144
+ }
145
+ catch {
146
+ return;
147
+ }
148
+ for (const entry of entries) {
149
+ // Dirent.isDirectory() is false for symlinks (it reflects the entry
150
+ // itself, not its target), so symlinked directories are never
151
+ // followed out of the root by this walk.
152
+ if (entry.isDirectory()) {
153
+ const child = path.join(directory, entry.name);
154
+ if (!shouldSkipContextWalkDir(directory, entry.name, isHomeDirectory)
155
+ && path.resolve(child) !== artifactRoot)
156
+ await walk(child, depth + 1);
157
+ }
158
+ else if (['AGENTS.md', 'CLAUDE.md', 'WARP.md'].includes(entry.name)) {
159
+ const relative = path.relative(projectPath, path.join(directory, entry.name)).replace(/\\/g, '/');
160
+ const segments = relative.split('/');
161
+ const generatedArtifactPath = segments.includes('templates') || segments.includes('fixtures');
162
+ if (!generatedArtifactPath && !LEGACY_ROOT_FILES.includes(relative))
163
+ found.push(relative);
164
+ }
165
+ }
166
+ }
167
+ await walk(projectPath, 1);
168
+ return { files: found.sort((a, b) => a.localeCompare(b)), truncated };
169
+ }
170
+ export async function migratedProviderFiles(projectPath) {
171
+ const directory = projectAiwgPath(projectPath, 'context', 'providers');
172
+ try {
173
+ return (await fs.readdir(directory, { withFileTypes: true }))
174
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
175
+ .map((entry) => projectOutputPath(projectPath, path.join(directory, entry.name)))
176
+ .sort();
177
+ }
178
+ catch {
179
+ return [];
180
+ }
181
+ }
182
+ export async function auditWorkspaceContext(projectPath) {
183
+ const extractedProject = await extractExistingProjectContext(projectPath);
184
+ const nested = await nestedInstructionFiles(projectPath);
185
+ const candidates = new Set([
186
+ 'WORKSPACE.md',
187
+ ...LEGACY_ROOT_FILES,
188
+ ...nested.files,
189
+ ...await migratedProviderFiles(projectPath),
190
+ ]);
191
+ const sources = [];
192
+ const sensitiveFindings = [...extractedProject.sensitiveFindings];
193
+ for (const relativePath of [...candidates].sort((a, b) => a.localeCompare(b))) {
194
+ const content = await readOptional(path.join(projectPath, relativePath));
195
+ if (content === null)
196
+ continue;
197
+ const operatorContent = relativePath === 'WORKSPACE.md'
198
+ ? (() => {
199
+ const start = content.indexOf(WORKSPACE_OPERATOR_START);
200
+ const end = content.indexOf(WORKSPACE_OPERATOR_END);
201
+ return start >= 0 && end > start
202
+ ? content.slice(start + WORKSPACE_OPERATOR_START.length, end).trim()
203
+ : stripGeneratedBlocks(content);
204
+ })()
205
+ : isGeneratedRootContext(relativePath, content)
206
+ ? ''
207
+ : stripGeneratedBlocks(content);
208
+ for (const evidence of sensitiveEvidence(operatorContent))
209
+ sensitiveFindings.push({ path: relativePath, evidence });
210
+ sources.push({
211
+ path: relativePath,
212
+ provider: providerForPath(relativePath),
213
+ scope: LEGACY_ROOT_FILES.includes(relativePath) || relativePath === 'WORKSPACE.md' ? 'root' : 'nested',
214
+ managed: content.includes(WORKSPACE_SIGNATURE) || content.includes('AIWG:context-hook:start') || content.includes('AIWG:claude-md-hook:start'),
215
+ operatorContent,
216
+ checksum: sha256(content),
217
+ });
218
+ }
219
+ const byDirective = new Map();
220
+ for (const source of sources) {
221
+ for (const directive of directives(source.operatorContent)) {
222
+ const paths = byDirective.get(directive) ?? [];
223
+ paths.push(source.path);
224
+ byDirective.set(directive, paths);
225
+ }
226
+ }
227
+ const identical = [...byDirective]
228
+ .filter(([, paths]) => paths.length > 1)
229
+ .map(([directive, paths]) => ({ sources: [...paths].sort(), directives: [directive] }));
230
+ const overlaps = [];
231
+ for (let index = 0; index < sources.length; index += 1) {
232
+ const left = new Set(directives(sources[index].operatorContent));
233
+ for (let rightIndex = index + 1; rightIndex < sources.length; rightIndex += 1) {
234
+ const common = directives(sources[rightIndex].operatorContent).filter((item) => left.has(item));
235
+ if (common.length > 0)
236
+ overlaps.push({ sources: [sources[index].path, sources[rightIndex].path], directives: common.sort() });
237
+ }
238
+ }
239
+ const conflictMap = new Map();
240
+ for (const source of sources) {
241
+ for (const directive of directives(source.operatorContent)) {
242
+ const key = directiveKey(directive);
243
+ if (!key)
244
+ continue;
245
+ const values = conflictMap.get(key) ?? [];
246
+ values.push({ path: source.path, directive, polarity: directivePolarity(directive) });
247
+ conflictMap.set(key, values);
248
+ }
249
+ }
250
+ const conflicts = [...conflictMap]
251
+ .filter(([, values]) => new Set(values.map((value) => value.polarity)).size > 1)
252
+ .map(([key, values]) => ({ key, sources: values.map(({ path: sourcePath, directive }) => ({ path: sourcePath, directive })).sort((a, b) => a.path.localeCompare(b.path)) }));
253
+ const rootOperator = sources.filter((source) => source.scope === 'root' && source.operatorContent.trim());
254
+ // Provider startup files (CLAUDE.md, AGENTS.md, WARP.md, …) are bootstrap
255
+ // surfaces: AIWG rewrites them to a managed bootstrap that `@`-imports
256
+ // WORKSPACE.md. The operator content they carried therefore ports into the
257
+ // WORKSPACE.md operator block, which every provider bootstrap loads and
258
+ // which `aiwg use` and `aiwg regenerate` preserve byte-for-byte. Routing
259
+ // it to `.aiwg/context/providers/` instead left it linked but never
260
+ // loaded, and a later `aiwg use` dropped even the link (#2558).
261
+ const neutralSources = rootOperator.map((source) => source.path);
262
+ const providerSources = [];
263
+ const providerOutputs = [];
264
+ const workspaceExists = sources.some((source) => source.path === 'WORKSPACE.md');
265
+ // Report volume and destination per source. A substantial provider-named
266
+ // body is still surfaced for review (#2537): it now lands where every
267
+ // provider reads it, so anything genuinely provider-only should be moved to
268
+ // `.aiwg/context/providers/` by the operator after migration.
269
+ const routing = rootOperator.map((source) => ({
270
+ source: source.path,
271
+ operatorBytes: Buffer.byteLength(source.operatorContent, 'utf8'),
272
+ destination: 'WORKSPACE.md',
273
+ scope: 'project-neutral',
274
+ provider: source.path === 'WORKSPACE.md' ? null : source.provider,
275
+ })).sort((a, b) => b.operatorBytes - a.operatorBytes);
276
+ const scopeReview = routing.filter((entry) => entry.source !== 'WORKSPACE.md' && entry.operatorBytes >= SCOPE_REVIEW_BYTES);
277
+ return {
278
+ version: 1,
279
+ projectPath,
280
+ workspaceExists,
281
+ legacyCompatible: !workspaceExists && sources.some((source) => LEGACY_ROOT_FILES.includes(source.path)),
282
+ sources,
283
+ identical,
284
+ overlaps,
285
+ conflicts,
286
+ sensitiveFindings,
287
+ contextWalkTruncated: nested.truncated,
288
+ plan: {
289
+ routing,
290
+ scopeReview,
291
+ neutralSources,
292
+ providerSources,
293
+ nestedSources: sources.filter((source) => source.scope === 'nested').map((source) => source.path),
294
+ projectSources: extractedProject.sources,
295
+ outputs: ['WORKSPACE.md', ...providerOutputs, ...listProviderDefinitions().flatMap((definition) => definition.context.bootstrapTargets)].filter((value, index, all) => all.indexOf(value) === index).sort(),
296
+ },
297
+ };
298
+ }
299
+ //# sourceMappingURL=workspace-audit.js.map