@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
@@ -12,8 +12,8 @@ export const RULE_ACTIVATIONS = Object.freeze(['core', 'kernel', 'summary', 'bou
12
12
  // `aiwg show rule <name>`, never an @ import.
13
13
  export const CORE_BODY_MAX_BYTES = 1024;
14
14
  export const CORE_TOTAL_MAX_BYTES = 6144;
15
- export const CORE_RULES_START = '<!-- AIWG:core-rules:start -->';
16
- export const CORE_RULES_END = '<!-- AIWG:core-rules:end -->';
15
+ export const CORE_RULES_START = '<!-- AIWG:rule-core:start -->';
16
+ export const CORE_RULES_END = '<!-- AIWG:rule-core:end -->';
17
17
  const AT_IMPORT = /(?:^|[\s(`"'])@[\w$.\/-]*[\/.][\w$.\/-]*/m;
18
18
 
19
19
  export const RULE_BINDING_TYPES = Object.freeze({ skills: 'skill', agents: 'agent', flows: 'flow' });
@@ -147,12 +147,21 @@ export function measureDeployedCoreRules(target, provider, rulesDir) {
147
147
  const file = path.join(target, name);
148
148
  if (!existsSync(file)) continue;
149
149
  const content = readFileSync(file, 'utf8');
150
- const start = content.indexOf(CORE_RULES_START);
151
- const end = content.indexOf(CORE_RULES_END);
152
- if (start >= 0 && end > start) {
153
- bodies.push({ name, bytes: Buffer.byteLength(content.slice(start + CORE_RULES_START.length, end).trim(), 'utf8') });
150
+ for (const [startMarker, endMarker] of [[CORE_RULES_START, CORE_RULES_END],
151
+ ['<!-- AIWG:core-rules:start -->', '<!-- AIWG:core-rules:end -->']]) {
152
+ const start = content.indexOf(startMarker);
153
+ const end = content.indexOf(endMarker);
154
+ if (start < 0 || end <= start) continue;
155
+ const section = content.slice(start + startMarker.length, end).trim();
156
+ const parts = section.replace(/^## Core rules\s*/, '').split(/(?=^# Core: )/m).filter(text => text.trim());
157
+ const named = parts.every(text => /^# Core: /m.test(text));
158
+ for (const text of named ? parts : [section]) {
159
+ const ruleName = text.match(/aiwg show rule ([\w-]+)/)?.[1];
160
+ bodies.push({ name: ruleName || name, bytes: Buffer.byteLength(text.trim(), 'utf8') });
161
+ }
154
162
  break;
155
163
  }
164
+ if (bodies.length) break;
156
165
  }
157
166
  }
158
167
  return { bodies, bytes: bodies.reduce((sum, item) => sum + item.bytes, 0), limit: CORE_TOTAL_MAX_BYTES };
@@ -3,13 +3,13 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { findPackageRoot } from '../cli/find-package-root.js';
6
- import { parseRuleFrontmatter, readCoreBody, validateCoreSet } from './activation.mjs';
6
+ import { parseRuleFrontmatter, readCoreBody, validateCoreSet, CORE_RULES_START, CORE_RULES_END } from './activation.mjs';
7
7
 
8
8
  export function renderCoreStartup(rules) {
9
9
  const cores = [...new Map(rules.filter(rule => rule.coreBody !== undefined).map(rule => [rule.name, rule])).values()];
10
10
  const errors = validateCoreSet(cores.map(rule => ({ name: rule.name, text: rule.coreBody })));
11
11
  if (errors.length) throw new Error(errors.join('; '));
12
- return cores.length ? `<!-- AIWG:rule-core:start -->\n## Core rules\n\n${cores.map(rule => rule.coreBody).join('\n\n')}\n<!-- AIWG:rule-core:end -->\n` : '';
12
+ return cores.length ? `${CORE_RULES_START}\n## Core rules\n\n${cores.map(rule => rule.coreBody).join('\n\n')}\n${CORE_RULES_END}\n` : '';
13
13
  }
14
14
 
15
15
  export function ensureCoreStartup(content) {
@@ -25,6 +25,10 @@
25
25
  import { routeMission } from './agent-router.js';
26
26
  import { StackAdapterRegistry } from './stack-adapters.js';
27
27
  import { assertMissionWorkerHandoff } from '../mission-protocol/codecs.js';
28
+ import { lookupEffect, reconcileEffect, recordIntent } from '../effects/ledger.js';
29
+ import { createVerifierRegistry } from '../effects/verifiers/registry.js';
30
+ import { fileDigestVerifier } from '../effects/verifiers/file.js';
31
+ export { summarizeMissionLedger } from './mission-summary.js';
28
32
  /**
29
33
  * The cross-stack Mission conductor. Decomposes a Mission into worker cycles,
30
34
  * dispatches each to an executor of the chosen runtime via `routeMission`, and
@@ -35,11 +39,13 @@ export class MissionConductor {
35
39
  runWorker;
36
40
  scoreOutput;
37
41
  scorerId;
42
+ effectLedger;
38
43
  constructor(opts = {}) {
39
44
  this.adapters = opts.adapters ?? new StackAdapterRegistry();
40
45
  this.runWorker = opts.runWorker;
41
46
  this.scoreOutput = opts.scoreOutput;
42
47
  this.scorerId = opts.scoreOutput ? (opts.scorerId ?? 'custom') : null;
48
+ this.effectLedger = opts.effectLedger;
43
49
  }
44
50
  /**
45
51
  * Conduct a Mission across the given executor pool. Returns the ledger.
@@ -152,11 +158,52 @@ export class MissionConductor {
152
158
  continue;
153
159
  }
154
160
  let output;
161
+ let workerResult;
155
162
  let cost = 0;
163
+ let reason = routing.selected.matchReason;
156
164
  try {
157
- const ran = await this.runWorker(cycle, executor, invocation);
158
- output = ran.output;
159
- cost = ran.cost ?? 0;
165
+ let intent;
166
+ let recovered = false;
167
+ const effects = this.effectLedger;
168
+ const reconcile = (id) => reconcileEffect(effects, id, {
169
+ verifiers: createVerifierRegistry([fileDigestVerifier({ root: effects.projectDir })]),
170
+ expected: { previousDigest: cycle.fileEffect.previousDigest ?? null },
171
+ });
172
+ if (cycle.fileEffect) {
173
+ if (!effects)
174
+ throw new Error('file effect requires a host-configured effect ledger');
175
+ const { target, payloadDigest, previousDigest } = cycle.fileEffect;
176
+ intent = await recordIntent(effects, {
177
+ kind: 'file.digest', target, payloadDigest,
178
+ context: { missionId: plan.missionId, cycleId: cycle.id,
179
+ ...(previousDigest === undefined ? {} : { previousDigest }) },
180
+ });
181
+ const recorded = await lookupEffect(effects, intent.effectId);
182
+ if (recorded.tombstoned || recorded.records.some(record => record.phase === 'failed')) {
183
+ throw new Error(`file effect ${intent.effectId} replay blocked: terminal outcome or tombstone`);
184
+ }
185
+ recovered = recorded.records.some(record => record.phase === 'completed');
186
+ if (!recovered) {
187
+ const checked = await reconcile(intent.effectId);
188
+ if (checked.result.verification.result === 'unknown') {
189
+ throw new Error(`file effect ${intent.effectId} replay blocked: ${checked.result.verification.reason}`);
190
+ }
191
+ recovered = checked.completed !== null;
192
+ }
193
+ if (recovered)
194
+ reason = `file effect ${intent.effectId} completed; worker replay skipped`;
195
+ }
196
+ if (!recovered) {
197
+ const ran = await this.runWorker(cycle, executor, invocation);
198
+ output = ran.output;
199
+ workerResult = ran.workerResult === undefined ? undefined : structuredClone(ran.workerResult);
200
+ cost = ran.cost ?? 0;
201
+ if (intent) {
202
+ const checked = await reconcile(intent.effectId);
203
+ if (!checked.completed)
204
+ throw new Error(`file effect ${intent.effectId} completion unverified: ${checked.result.verification.reason}`);
205
+ }
206
+ }
160
207
  }
161
208
  catch (err) {
162
209
  const result = {
@@ -180,8 +227,9 @@ export class MissionConductor {
180
227
  primitive: adapter.primitive,
181
228
  executorId: executor.executorId,
182
229
  routed: true,
183
- reason: routing.selected.matchReason,
230
+ reason,
184
231
  output,
232
+ ...(workerResult ? { workerResult } : {}),
185
233
  cost,
186
234
  ...(graph ? { graph } : {}),
187
235
  };
@@ -0,0 +1,56 @@
1
+ // Read-only classification of conductor checkpoints and existing verifier results.
2
+ import { validateWorkerPayload } from '../mission-protocol/codecs.js';
3
+ import { hasIndependentWorkerAcceptance } from '../mission-protocol/worker-review-gate.js';
4
+ function classify(ledger, cycle) {
5
+ const entry = (status, reason, evidence = []) => ({ cycleId: cycle.cycleId, status, reason, evidence: structuredClone(evidence) });
6
+ if (ledger.checkpoint.failed.includes(cycle.cycleId))
7
+ return entry('failed', 'Conductor recorded failure');
8
+ if (ledger.executionMode !== undefined && !['plan-only', 'executed'].includes(ledger.executionMode)) {
9
+ return entry('unknown', `Unrecognized execution mode: ${String(ledger.executionMode)}`);
10
+ }
11
+ if (ledger.executionMode === 'plan-only' || !cycle.routed
12
+ || !ledger.checkpoint.completed.includes(cycle.cycleId)
13
+ || ledger.checkpoint.pending.includes(cycle.cycleId)) {
14
+ return entry('unknown', 'No completed execution measurement');
15
+ }
16
+ const result = cycle.workerResult;
17
+ if (result !== undefined) {
18
+ const definition = result && typeof result === 'object' && 'mode' in result && result.mode === 'direct'
19
+ ? 'workerDirectResult' : 'workerResult';
20
+ if (!validateWorkerPayload(definition, result).valid || result.taskId !== cycle.cycleId) {
21
+ return entry('unknown', 'Invalid or unbound worker measurement');
22
+ }
23
+ if (result.execution.status === 'failed')
24
+ return entry('failed', 'Adapter recorded worker failure');
25
+ if (result.execution.status !== 'completed')
26
+ return entry('unknown', 'Worker execution is not complete');
27
+ // The result codec already requires confirmed, successful terminal execution
28
+ // and completed worker claims for an accepted verifier verdict.
29
+ if (Date.parse(result.execution.endedAt) >= Date.parse(result.execution.startedAt)
30
+ && hasIndependentWorkerAcceptance(result.verification)) {
31
+ return entry('accepted', 'Independent review accepted with evidence', result.verification.evidence);
32
+ }
33
+ }
34
+ else if (ledger.executionMode !== 'executed') {
35
+ return entry('unknown', 'Legacy checkpoint lacks an execution measurement');
36
+ }
37
+ return entry('completed', 'Worker finished; independent acceptance with evidence is unavailable');
38
+ }
39
+ /** Project existing observations only; no scoring, file reads, sync or writes. */
40
+ export function summarizeMissionLedger(ledger) {
41
+ const counts = { accepted: 0, completed: 0, failed: 0, unknown: 0 };
42
+ const cycles = ledger.cycles.map(cycle => classify(ledger, cycle));
43
+ const measured = new Set(cycles.map(cycle => cycle.cycleId));
44
+ const checkpointIds = new Set([
45
+ ...ledger.checkpoint.completed, ...ledger.checkpoint.failed, ...ledger.checkpoint.pending,
46
+ ]);
47
+ for (const cycleId of checkpointIds) {
48
+ if (!measured.has(cycleId))
49
+ cycles.push({ cycleId, status: 'unknown',
50
+ reason: 'Checkpoint has no retained cycle measurement', evidence: [] });
51
+ }
52
+ for (const cycle of cycles)
53
+ counts[cycle.status]++;
54
+ return { missionId: ledger.missionId, counts, cycles };
55
+ }
56
+ //# sourceMappingURL=mission-summary.js.map
@@ -15,6 +15,26 @@ export const GROK_BUILD_ACTIVE_SESSIONS_SCHEMA_VERSION = 1;
15
15
  export const GROK_BUILD_ACTIVE_FRESHNESS_MS = 120_000;
16
16
  export const GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES = 10_000;
17
17
  const ACTIVE_SESSIONS_MAX_BYTES = 1024 * 1024;
18
+ export function grokBuildNativeEnabled() {
19
+ return process.env.AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL === '1';
20
+ }
21
+ /** One availability message for native readers, discovery and CLI capability reports. */
22
+ export function grokBuildNativeAvailability() {
23
+ const enabled = grokBuildNativeEnabled();
24
+ return {
25
+ reasonCode: enabled ? 'GROK_BUILD_NATIVE_EXPERIMENTAL_ENABLED' : 'GROK_BUILD_NATIVE_EXPERIMENTAL_DISABLED',
26
+ remediation: `Grok Build native ingestion is experimental and ${enabled ? 'enabled but' : 'disabled by default because it is'} `
27
+ + 'unqualified: no released-binary schema or version range is qualified. '
28
+ + 'AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL=1 opts in to synthetic v1 chat_history.jsonl and active_sessions.json only; '
29
+ + 'authorize the sessions root separately with --grok-root and the optional registry file with --grok-active-sessions. '
30
+ + 'Use `grok export <session-id> <session-id>.md` and import the authorized Markdown file for the documented CLI path.',
31
+ };
32
+ }
33
+ export function assertGrokBuildNativeEnabled() {
34
+ if (!grokBuildNativeEnabled()) {
35
+ throw new SessionContractError('UNSUPPORTED_OPERATION', grokBuildNativeAvailability().remediation);
36
+ }
37
+ }
18
38
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
19
39
  // Synthetic native record shape (v1): one JSON object per line. Real
20
40
  // chat_history.jsonl schemas are unqualified (real stores are never read),
@@ -59,6 +79,7 @@ export function grokBuildNativeSessionId(locator) {
59
79
  }
60
80
  /** Enumerate documented `<root>/<url-encoded cwd>/<id>/chat_history.jsonl` paths. */
61
81
  export async function* discoverGrokBuildNativeChatHistories(root, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
82
+ assertGrokBuildNativeEnabled();
62
83
  const resolved = resolve(root);
63
84
  let workspaces;
64
85
  try {
@@ -125,6 +146,7 @@ export async function grokBuildSourceWorkspaceMatch(locator, workspacePath) {
125
146
  return matchSessionWorkspace(decoded, workspacePath);
126
147
  }
127
148
  export async function readGrokBuildNativeChatHistory(source, limits) {
149
+ assertGrokBuildNativeEnabled();
128
150
  const sessionId = grokBuildNativeSessionId(source.locator);
129
151
  if (source.locatorClass !== GROK_BUILD_NATIVE_LOCATOR_CLASS || !sessionId) {
130
152
  throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
@@ -205,6 +227,7 @@ export function toGrokBuildNativeRecord(sessionId, entry) {
205
227
  }
206
228
  /** Read and validate active_sessions.json (read-only, bounded); throws on misuse. */
207
229
  export async function readGrokBuildActiveRegistry(selectedPath, allowedRoots) {
230
+ assertGrokBuildNativeEnabled();
208
231
  const authorized = await authorizeSourceFile({
209
232
  selectedPath, allowedRoots, maxBytes: ACTIVE_SESSIONS_MAX_BYTES,
210
233
  });
@@ -1,19 +1,19 @@
1
1
  import { basename, extname } from 'node:path';
2
2
  import { SessionContractError, schemaIssueDetail, } from '../contracts.js';
3
3
  import { readBoundedText } from '../readers.js';
4
- import { discoverGrokBuildNativeChatHistories, GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES, GROK_BUILD_NATIVE_LOCATOR_CLASS, GROK_BUILD_NATIVE_SCHEMA_VERSION, grokBuildNativeSessionId, parseGrokBuildNativeCursor, readGrokBuildNativeChatHistory, toGrokBuildNativeRecord, } from './grok-build-native.js';
4
+ import { assertGrokBuildNativeEnabled, discoverGrokBuildNativeChatHistories, GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES, GROK_BUILD_NATIVE_LOCATOR_CLASS, GROK_BUILD_NATIVE_SCHEMA_VERSION, grokBuildNativeSessionId, grokBuildNativeEnabled, parseGrokBuildNativeCursor, readGrokBuildNativeChatHistory, toGrokBuildNativeRecord, } from './grok-build-native.js';
5
5
  export const GROK_BUILD_ADAPTER_VERSION = '1.0.0';
6
6
  export const GROK_BUILD_CLI_EXPORT_SCHEMA_VERSION = '1.0.0';
7
7
  export const GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS = 'grok-build-cli-markdown-export';
8
8
  /**
9
9
  * Imports the documented `grok export <session-id> <file>` surface plus the
10
- * native `chat_history.jsonl` store under an explicitly authorized
11
- * sessions root (`--grok-root`).
10
+ * experimental native `chat_history.jsonl` store with an explicit environment
11
+ * opt-in and an explicitly authorized sessions root (`--grok-root`).
12
12
  *
13
13
  * The public export contract is intentionally lossy. Native reads use the
14
14
  * synthetic v1 schema in grok-build-native.ts (real stores were never
15
- * inspected); anything outside it fails closed. AIWG never runs
16
- * `grok export` itself: export remains an operator-selected fallback.
15
+ * inspected); anything outside it fails closed. This adapter never invokes
16
+ * `grok export` automatically: CLI export remains operator-selected.
17
17
  */
18
18
  export class GrokBuildSessionAdapter {
19
19
  limits;
@@ -21,13 +21,18 @@ export class GrokBuildSessionAdapter {
21
21
  provider = 'grok-build';
22
22
  adapterVersion = GROK_BUILD_ADAPTER_VERSION;
23
23
  disposition = 'implemented';
24
- supportedOperations = ['discover', 'inspect', 'stream'];
25
- acquisitionModes = ['manual-export', 'jsonl'];
24
+ get supportedOperations() {
25
+ return grokBuildNativeEnabled() ? ['discover', 'inspect', 'stream'] : ['inspect', 'stream'];
26
+ }
27
+ get acquisitionModes() {
28
+ return grokBuildNativeEnabled() ? ['manual-export', 'jsonl'] : ['manual-export'];
29
+ }
26
30
  constructor(limits, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
27
31
  this.limits = limits;
28
32
  this.maxFiles = maxFiles;
29
33
  }
30
34
  async *discover(scope) {
35
+ assertGrokBuildNativeEnabled();
31
36
  if (scope.allowedRoots.length === 0) {
32
37
  throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native discovery requires an explicitly authorized sessions root; pass --grok-root.');
33
38
  }
@@ -53,6 +58,8 @@ export class GrokBuildSessionAdapter {
53
58
  }
54
59
  async *stream(source, cursor) {
55
60
  if (source.locatorClass === GROK_BUILD_NATIVE_LOCATOR_CLASS) {
61
+ // The experimental gate answers first, so a disabled gate never reports a locator error.
62
+ assertGrokBuildNativeEnabled();
56
63
  const sessionId = grokBuildNativeSessionId(source.locator);
57
64
  if (!sessionId) {
58
65
  throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
@@ -4,7 +4,7 @@ import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { inspectMuseNativeWorkspace } from './adapters/muse.js';
5
5
  import { readOmpSessionHeader } from './adapters/omp.js';
6
6
  import { grokbotConversationIdFromLocator } from './adapters/grokbot-locator.js';
7
- import { GROK_BUILD_ACTIVE_FRESHNESS_MS, grokBuildLiveState, grokBuildSourceWorkspaceMatch, readGrokBuildActiveRegistry, } from './adapters/grok-build-native.js';
7
+ import { GROK_BUILD_ACTIVE_FRESHNESS_MS, grokBuildLiveState, grokBuildNativeAvailability, grokBuildSourceWorkspaceMatch, readGrokBuildActiveRegistry, } from './adapters/grok-build-native.js';
8
8
  import { hermesSnapshotStagingDir } from './adapters/hermes-state-db.js';
9
9
  import { resolveOmpPaths } from '../providers/omp-paths.mjs';
10
10
  import { readAiwgConfig } from '../config/aiwg-config.js';
@@ -18,7 +18,7 @@ import { matchImportExclusion, nativeSessionIdFromLocator, resolveImportExclusio
18
18
  export const DISCOVERY_MANIFEST_VERSION = '1.0.0';
19
19
  const MANUAL_EXPORT_PROVIDERS = new Set([
20
20
  'copilot', 'opencode', 'openclaw', 'openhuman',
21
- 'warp', 'devin-desktop', 'generic',
21
+ 'warp', 'devin-desktop', 'generic', 'grok-build',
22
22
  ]);
23
23
  export async function discoverWorkspaceHistories(options) {
24
24
  const registry = options.registry ?? createSessionAdapterRegistry();
@@ -173,7 +173,7 @@ export async function discoverWorkspaceHistories(options) {
173
173
  || entry.provider === 'grokbot' || entry.provider === 'grok-build'
174
174
  || entry.provider === 'hermes')
175
175
  && entry.roots.length === 0;
176
- const expectedFlag = entry.provider === 'deepseek-harness' ? 'dsh' : entry.provider;
176
+ const expectedFlag = entry.provider === 'deepseek-harness' ? 'dsh' : entry.provider === 'grok-build' ? 'grok' : entry.provider;
177
177
  const rootKind = entry.provider === 'hermes' ? 'Hermes home (state.db is snapshotted read-only)' : 'sessions root';
178
178
  reports.set(entry.provider, providerReport(entry.provider, needsExplicitRoot ? 'export-required' : 'unavailable', needsExplicitRoot ? 'manual-export' : 'discoverable', [], needsExplicitRoot
179
179
  ? 'SHARED_ROOT_AUTHORIZATION_REQUIRED'
@@ -382,9 +382,9 @@ export async function discoverWorkspaceHistories(options) {
382
382
  continue;
383
383
  }
384
384
  const grokBuild = provider === 'grok-build';
385
- reports.set(provider, providerReport(provider, manual ? 'export-required' : 'not-checked', manual ? 'manual-export' : 'unsupported', [], grokBuild ? 'CLI_EXPORT_REQUIRED'
385
+ reports.set(provider, providerReport(provider, manual ? 'export-required' : 'not-checked', manual ? 'manual-export' : 'unsupported', [], grokBuild ? grokBuildNativeAvailability().reasonCode
386
386
  : manual ? 'EXPLICIT_EXPORT_REQUIRED' : 'PROVIDER_NOT_CHECKED', grokBuild
387
- ? 'Run `grok sessions list` or `grok sessions search`, then export an authorized session with `grok export <id> <id>.md`; Grok Build resolves $GROK_HOME itself.'
387
+ ? grokBuildNativeAvailability().remediation
388
388
  : manual
389
389
  ? `Select and authorize a supported ${provider} export before importing it.`
390
390
  : `No discovery strategy is registered for ${provider}.`));
@@ -1,22 +1,7 @@
1
- /**
2
- * AIWG.md generator — content-rich CLAUDE.md companion for non-Claude providers.
3
- *
4
- * Per ADR-1 §0.5: AIWG.md at project root has the same content shape as
5
- * CLAUDE.md. Both files `@`-reference the project's `.aiwg/AIWG.md` (the
6
- * source of truth). Non-Claude providers reach AIWG.md transitively via the
7
- * provider startup adapters. WORKSPACE.md and AIWG.md contain
8
- * identical framework prose; they exist as two named files because Claude
9
- * Code looks for `CLAUDE.md` and the seven AGENTS.md providers reach
10
- * AIWG.md via the AGENTS.md hook-up.
11
- *
12
- * Generation strategy: read the project's CLAUDE.md (which already exists in
13
- * a properly-configured repo) and emit AIWG.md as the same content with the
14
- * AIWG signature comment in place. If CLAUDE.md is absent (early-init repos),
15
- * fall back to a minimal stub that points readers at `.aiwg/AIWG.md`.
16
- */
1
+ // Render the single generated root framework context and fold in optional operator notes.
17
2
  import { promises as fs } from 'node:fs';
18
3
  import * as path from 'node:path';
19
- import { projectControlPath } from '../../config/project-artifacts.js';
4
+ import { readAiwgOperatorNotes } from './finalization.js';
20
5
  import { buildClaudeHookBlock, CLAUDE_HOOK_START, CLAUDE_HOOK_END } from './claude-hook.js';
21
6
  import { dedupeProviderBootstrap } from './workspace-context.js';
22
7
  import { dominantLineEnding, withLineEnding } from './line-endings.js';
@@ -24,18 +9,6 @@ import { buildParallelismSection, replaceOrAppendParallelismBlock } from './para
24
9
  import { buildContextFinalizationBlock, replaceOrAppendFinalizationBlock } from './finalization.js';
25
10
  import { buildExternalLinksSection, replaceOrAppendExternalLinksBlock, } from './external-links-section.js';
26
11
  const AIWG_SIGNATURE_COMMENT = '<!-- aiwg-managed -->';
27
- /**
28
- * Build the AIWG.md content for emission at project root.
29
- *
30
- * - When CLAUDE.md exists at project root: copy its content with the AIWG
31
- * signature comment inserted in the second line so future runs of the
32
- * generator know the file is AIWG-managed.
33
- * - When CLAUDE.md does not exist: emit a minimal stub directing readers to
34
- * the project's `.aiwg/AIWG.md` source.
35
- *
36
- * Returns the rendered content as a string. Caller is responsible for the
37
- * atomic-write emission and the operator-claimed-file detection.
38
- */
39
12
  export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
40
13
  let claudeMdContent = stagedClaudeMdContent;
41
14
  if (stagedClaudeMdContent === undefined) {
@@ -55,6 +28,11 @@ export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
55
28
  const parallelismSection = await buildParallelismSection(projectPath);
56
29
  const finalizationBlock = await buildContextFinalizationBlock(projectPath, path.join(projectPath, 'AIWG.md'));
57
30
  const externalLinksSection = await buildExternalLinksSection(projectPath);
31
+ const { notes } = await readAiwgOperatorNotes(projectPath);
32
+ const foldNotes = (content) => {
33
+ content = content.replace(/<!-- AIWG:operator-notes:start -->[\s\S]*?<!-- AIWG:operator-notes:end -->\r?\n?/g, '');
34
+ return notes.trim() ? `${content.trimEnd()}\n\n<!-- AIWG:operator-notes:start -->\n${notes}\n<!-- AIWG:operator-notes:end -->\n` : content;
35
+ };
58
36
  if (claudeMdContent) {
59
37
  // Insert the AIWG signature comment as the second line.
60
38
  // Top line is typically `# AIWG` or `# Project` heading; preserve it.
@@ -82,7 +60,7 @@ export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
82
60
  const CONFIG_IMPORT_PATTERN = /^\s*@\S*aiwg\.config\s*$/;
83
61
  const WORKSPACE_IMPORT_PATTERN = /^\s*@(?:\.\.\/)?WORKSPACE\.md\s*$/;
84
62
  const filtered = lines
85
- .filter((line) => !SELF_INCLUDE_PATTERN.test(line))
63
+ .filter((line) => !SELF_INCLUDE_PATTERN.test(line) && !/^\s*@(?:\.\/)?\.aiwg\/AIWG\.md\s*$/.test(line))
86
64
  .map((line) => {
87
65
  if (WORKSPACE_IMPORT_PATTERN.test(line)) {
88
66
  return 'WORKSPACE.md is the canonical project context (loaded by CLAUDE.md; read it first if your harness did not).';
@@ -102,29 +80,21 @@ export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
102
80
  : [
103
81
  firstLine,
104
82
  AIWG_SIGNATURE_COMMENT,
105
- '<!-- AIWG.md is the CLAUDE.md companion for non-Claude providers; same content. -->',
83
+ '<!-- Generated framework context shared by all providers. -->',
106
84
  ...rest,
107
85
  ].join('\n');
108
86
  const withParallelism = replaceOrAppendParallelismBlock(baseContent, parallelismSection);
109
87
  const withFinalization = replaceOrAppendFinalizationBlock(withParallelism, finalizationBlock);
110
- return replaceOrAppendExternalLinksBlock(withFinalization, externalLinksSection);
88
+ return foldNotes(replaceOrAppendExternalLinksBlock(withFinalization, externalLinksSection));
111
89
  }
112
- // Fallback stub.
113
- const normalizedPath = projectControlPath(projectPath, 'AIWG.md');
114
- const normalizedRelative = path.relative(projectPath, normalizedPath).replace(/\\/g, '/');
115
- const normalizedLink = normalizedRelative.startsWith('.') ? normalizedRelative : `./${normalizedRelative}`;
90
+ // A fresh non-Claude project has the same complete framework context.
116
91
  const stub = [
117
- '# AIWG.md',
118
- AIWG_SIGNATURE_COMMENT,
119
- '<!-- CLAUDE.md companion for non-Claude providers. -->',
120
- '',
121
- 'CLAUDE.md was not found at project root. AIWG.md normally mirrors that content.',
122
- `See [${normalizedRelative}](${normalizedLink}) for the project framework context.`,
123
- '',
92
+ '# AIWG.md', AIWG_SIGNATURE_COMMENT,
93
+ '<!-- Generated framework context. Project/operator context belongs in WORKSPACE.md. -->', '',
124
94
  ].join('\n');
125
95
  const withParallelism = replaceOrAppendParallelismBlock(stub, parallelismSection);
126
96
  const withFinalization = replaceOrAppendFinalizationBlock(withParallelism, finalizationBlock);
127
- return replaceOrAppendExternalLinksBlock(withFinalization, externalLinksSection);
97
+ return foldNotes(replaceOrAppendExternalLinksBlock(withFinalization, externalLinksSection));
128
98
  }
129
99
  /**
130
100
  * Public API: build AIWG.md content for a given project.
@@ -133,7 +103,30 @@ export async function buildAiwgMdContent(projectPath, stagedClaudeMdContent) {
133
103
  * AIWG.local.md operator overrides, etc.) have a single entry point in the
134
104
  * surface API without callers reaching into the implementation.
135
105
  */
136
- export async function generateAiwgMd(projectPath) {
137
- return buildAiwgMdContent(projectPath);
106
+ export async function generateAiwgMd(projectPath, stagedClaudeMdContent) {
107
+ return buildAiwgMdContent(projectPath, stagedClaudeMdContent);
108
+ }
109
+ /** Keep pipeline-owned startup boilerplate out of the shared context on redeploy. */
110
+ export async function generateAiwgMdForPipeline(projectPath) {
111
+ let claudeMdContent;
112
+ try {
113
+ claudeMdContent = await fs.readFile(path.join(projectPath, 'CLAUDE.md'), 'utf8');
114
+ }
115
+ catch (error) {
116
+ if (error.code !== 'ENOENT')
117
+ throw error;
118
+ claudeMdContent = null;
119
+ }
120
+ // A generated startup hook is not project prose. Mirroring it would change
121
+ // the initial shared-context stub on redeploy and duplicate provider policy.
122
+ if (claudeMdContent?.includes(CLAUDE_HOOK_START)) {
123
+ const prose = claudeMdContent
124
+ .replace(/<!-- AIWG:claude-md-hook:start -->[\s\S]*?<!-- AIWG:claude-md-hook:end -->/g, '')
125
+ .replace(/<!-- AIWG:(rule-core|rule-startup|rule-hook-[\w-]+):start -->[\s\S]*?<!-- AIWG:\1:end -->/g, '')
126
+ .replace(/^\s*<!-- aiwg-managed -->\s*$/gm, '');
127
+ if (!prose.trim())
128
+ claudeMdContent = null;
129
+ }
130
+ return buildAiwgMdContent(projectPath, claudeMdContent);
138
131
  }
139
132
  //# sourceMappingURL=aiwg-md.js.map
@@ -40,7 +40,7 @@ export function buildClaudeHookBlock(_policy = {}) {
40
40
  '<!--',
41
41
  ' This block is managed by `aiwg regenerate` and `aiwg use`.',
42
42
  ' Operator content above and below this block is preserved on regenerate.',
43
- ' To change AIWG.md content, edit .aiwg/AIWG.md (the normalized source)',
43
+ ' Edit WORKSPACE.md Project Context or optional .aiwg/AIWG.md operator notes,',
44
44
  ' then run `aiwg regenerate`.',
45
45
  '-->',
46
46
  '',
@@ -0,0 +1,28 @@
1
+ // Mask Markdown examples without changing source offsets.
2
+ /**
3
+ * Blank out fenced code blocks and inline code spans, preserving offsets and line
4
+ * structure, so link extraction sees only prose. Illustrative paths inside an
5
+ * example block are documentation, not context links the graph should resolve (#2536).
6
+ */
7
+ export function maskCodeRegions(content) {
8
+ const lines = content.split('\n');
9
+ let fence = null;
10
+ const masked = lines.map((line) => {
11
+ const openOrClose = /^\s{0,3}(`{3,}|~{3,})(.*)$/.exec(line);
12
+ if (fence) {
13
+ // A closing fence uses the same character, is at least as long, and carries no info string.
14
+ if (openOrClose && openOrClose[1][0] === fence.marker && openOrClose[1].length >= fence.length && openOrClose[2].trim() === '') {
15
+ fence = null;
16
+ }
17
+ return ' '.repeat(line.length);
18
+ }
19
+ if (openOrClose) {
20
+ fence = { marker: openOrClose[1][0], length: openOrClose[1].length };
21
+ return ' '.repeat(line.length);
22
+ }
23
+ // Inline code spans: a run of N backticks closes on the next run of exactly N.
24
+ return line.replace(/(`+)(?:[^`]|(?!\1)`)*?\1/g, (span) => ' '.repeat(span.length));
25
+ });
26
+ return masked.join('\n');
27
+ }
28
+ //# sourceMappingURL=code-regions.js.map
@@ -2,6 +2,7 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { createHash } from 'node:crypto';
5
+ import { refreshRecordedContextOutput } from '../../providers/context-output-ownership.js';
5
6
  import { trackTemporaryDirectory } from '../../utils/temporary-directory.js';
6
7
  const JOURNAL_ENV = 'AIWG_CONTEXT_WRITE_JOURNAL';
7
8
  export const CONTEXT_STAGE_ENV = 'AIWG_CONTEXT_STAGE_LOG';
@@ -201,6 +202,8 @@ export function writeContextFileSync(file, content, _encoding) {
201
202
  verifyTarget(anchored, result);
202
203
  if (!matches(state(fd), result))
203
204
  throw new Error(`Context changed during write: ${absolute}`);
205
+ if (!stageLog)
206
+ refreshRecordedContextOutput(absolute, prior?.hash, result.hash, writeContextFileSync);
204
207
  }
205
208
  }
206
209
  finally {