@aiwg/cli 2026.10.15 → 2026.10.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,517 @@
1
+ /**
2
+ * Opt-in update-install policy for the `update.install` maintenance job
3
+ * (epic #3353 slice B6; decision D3: installs are check-only by default).
4
+ *
5
+ * `update.check` stays check-only. `update.install` proceeds only when every
6
+ * gate passes, in order: explicit per-job opt-in (`args.install === true`),
7
+ * valid policy, maintenance window, available update, version policy (never a
8
+ * major unless explicitly allowed), no active AIWG work, and installer
9
+ * preflight (the installer's own dry-run checks). Any failed gate returns a
10
+ * `deferred` receipt with a machine-readable reason and never installs.
11
+ *
12
+ * Package install and provider redeployment are separate explicit steps: this
13
+ * module only performs the package step (`updateInstallation`) and never
14
+ * redeploys providers. An uncertain outcome (installer threw, receipt
15
+ * malformed) is reported with `uncertain: true` so the runner routes it to
16
+ * the existing `schedule-recovery-required` path instead of retrying it.
17
+ */
18
+
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { importImpl } from '../_resolve-impl.mjs';
22
+
23
+ export const UPDATE_CHANNELS = Object.freeze(['stable', 'edge']);
24
+ export const VERSION_POLICIES = Object.freeze(['patch', 'minor', 'any']);
25
+
26
+ const TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
27
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
28
+ const formatters = new Map();
29
+
30
+ function civilParts(ms, timezone) {
31
+ if (!formatters.has(timezone)) {
32
+ // Same named-zone civil-time approach as cron-scheduler.mjs: the Intl
33
+ // wall clock is the source of truth, so DST folds/gaps behave the same.
34
+ formatters.set(timezone, new Intl.DateTimeFormat('en-US', {
35
+ timeZone: timezone, weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
36
+ }));
37
+ }
38
+ const parts = Object.fromEntries(formatters.get(timezone).formatToParts(ms).map(p => [p.type, p.value]));
39
+ return { weekday: WEEKDAYS.indexOf(parts.weekday), minutes: Number(parts.hour) * 60 + Number(parts.minute) };
40
+ }
41
+
42
+ /**
43
+ * Validate the per-job update policy (`job.args` for `update.install`).
44
+ * Returns an array of human-readable errors; empty means valid.
45
+ */
46
+ export function validateUpdatePolicy(args = {}) {
47
+ const errors = [];
48
+ if (args.channel !== undefined && !UPDATE_CHANNELS.includes(args.channel)) {
49
+ errors.push(`channel must be one of: ${UPDATE_CHANNELS.join(', ')}`);
50
+ }
51
+ if (args.versionPolicy !== undefined && !VERSION_POLICIES.includes(args.versionPolicy)) {
52
+ errors.push(`versionPolicy must be one of: ${VERSION_POLICIES.join(', ')}`);
53
+ }
54
+ if (args.allowMajor !== undefined && typeof args.allowMajor !== 'boolean') {
55
+ errors.push('allowMajor must be a boolean');
56
+ }
57
+ if (args.install !== undefined && typeof args.install !== 'boolean') {
58
+ errors.push('install must be a boolean');
59
+ }
60
+ if (args.windows !== undefined) {
61
+ if (!Array.isArray(args.windows) || args.windows.length === 0) {
62
+ errors.push('windows must be a non-empty array of { start, end, days?, timezone? }');
63
+ } else {
64
+ args.windows.forEach((window, index) => {
65
+ const label = `windows[${index}]`;
66
+ if (!window || typeof window !== 'object') { errors.push(`${label} must be an object`); return; }
67
+ for (const key of ['start', 'end']) {
68
+ if (typeof window[key] !== 'string' || !TIME_RE.test(window[key])) {
69
+ errors.push(`${label}.${key} must be HH:MM (24h)`);
70
+ }
71
+ }
72
+ if (window.days !== undefined) {
73
+ if (!Array.isArray(window.days) || window.days.length === 0 ||
74
+ window.days.some(d => !Number.isInteger(d) || d < 0 || d > 6)) {
75
+ errors.push(`${label}.days must be a non-empty array of 0 (Sun) through 6 (Sat)`);
76
+ }
77
+ }
78
+ if (window.timezone !== undefined) {
79
+ try { new Intl.DateTimeFormat('en', { timeZone: window.timezone }); }
80
+ catch { errors.push(`${label}.timezone is not a known IANA zone`); }
81
+ }
82
+ });
83
+ }
84
+ }
85
+ return errors;
86
+ }
87
+
88
+ function parseTriple(version) {
89
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version || ''));
90
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
91
+ }
92
+
93
+ /** Classify the bump from current to latest: none|patch|minor|major|unknown. */
94
+ export function classifyBump(current, latest) {
95
+ const from = parseTriple(current);
96
+ const to = parseTriple(latest);
97
+ if (!from || !to) return 'unknown';
98
+ if (to[0] !== from[0]) return 'major';
99
+ if (to[1] !== from[1]) return 'minor';
100
+ if (to[2] !== from[2]) return 'patch';
101
+ return 'none';
102
+ }
103
+
104
+ /** Version-policy gate: patch < minor < any; major always needs allowMajor. */
105
+ export function versionAllowed(current, latest, { versionPolicy = 'patch', allowMajor = false } = {}) {
106
+ const bump = classifyBump(current, latest);
107
+ if (bump === 'none' || bump === 'unknown') return { allowed: false, bump, reason: `no-${bump}-upgrade` };
108
+ if (bump === 'major' && !allowMajor) return { allowed: false, bump, reason: 'major-not-allowed' };
109
+ if (bump === 'major') return { allowed: true, bump, reason: 'major-explicitly-allowed' };
110
+ const rank = { patch: 0, minor: 1, any: 2 };
111
+ const ceiling = rank[versionPolicy] ?? 0;
112
+ if (rank[bump] <= ceiling) return { allowed: true, bump, reason: `within-${versionPolicy}-policy` };
113
+ return { allowed: false, bump, reason: 'version-policy' };
114
+ }
115
+
116
+ /**
117
+ * Maintenance-window gate. `windows` entries are
118
+ * `{ start: 'HH:MM', end: 'HH:MM', days?: [0-6 Sun-Sat], timezone? }`; ranges
119
+ * wrap past midnight. No windows configured means installs are allowed at any
120
+ * time (the `install: true` opt-in remains the safety gate).
121
+ */
122
+ export function inMaintenanceWindow(nowMs, windows, fallbackTimezone = 'UTC') {
123
+ if (!windows || windows.length === 0) return { inside: true, reason: 'no-window-configured' };
124
+ for (const window of windows) {
125
+ const timezone = window.timezone || fallbackTimezone;
126
+ let parts;
127
+ try { parts = civilParts(nowMs, timezone); }
128
+ catch { continue; }
129
+ if (parts.weekday < 0) continue;
130
+ if (window.days && !window.days.includes(parts.weekday)) continue;
131
+ const [sh, sm] = window.start.split(':').map(Number);
132
+ const [eh, em] = window.end.split(':').map(Number);
133
+ const start = sh * 60 + sm;
134
+ const end = eh * 60 + em;
135
+ const inside = start <= end
136
+ ? parts.minutes >= start && parts.minutes < end
137
+ : parts.minutes >= start || parts.minutes < end;
138
+ if (inside) return { inside: true, reason: `in-window:${window.start}-${window.end}@${timezone}` };
139
+ }
140
+ return { inside: false, reason: 'outside-maintenance-window' };
141
+ }
142
+
143
+ /**
144
+ * Read-only view of the daemon task store for active-work detection.
145
+ * Fail-closed: only a missing file (ENOENT) means "no daemon work". Any
146
+ * other read or parse error yields `unavailable`, which `detectActiveWork`
147
+ * turns into an active `work-detection-unavailable:<reason>` entry.
148
+ */
149
+ export function readStoreWork(cwd) {
150
+ const file = path.join(cwd, '.aiwg', 'daemon', 'tasks.json');
151
+ let raw;
152
+ try {
153
+ raw = fs.readFileSync(file, 'utf8');
154
+ } catch (error) {
155
+ if (error?.code === 'ENOENT') return { busySchedules: [], busyTasks: [], unavailable: null };
156
+ return { busySchedules: [], busyTasks: [], unavailable: `work-detection-unavailable:${error.message}` };
157
+ }
158
+ try {
159
+ const parsed = JSON.parse(raw);
160
+ const schedules = Array.isArray(parsed.schedules) ? parsed.schedules : [];
161
+ const tasks = Array.isArray(parsed.tasks) ? parsed.tasks : [];
162
+ return {
163
+ busySchedules: schedules
164
+ .filter(s => ['running', 'blocked', 'retry', 'pending'].includes(s?.state))
165
+ .map(s => s?.job?.id || '?'),
166
+ busyTasks: tasks
167
+ .filter(t => ['running', 'queued'].includes(t?.state))
168
+ .map(t => t?.id || '?'),
169
+ unavailable: null,
170
+ };
171
+ } catch (error) {
172
+ return { busySchedules: [], busyTasks: [], unavailable: `work-detection-unavailable:${error.message}` };
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Live ralph loops via the existing launcher registry reader
178
+ * (`getLoopStatuses` in `src/cli/handlers/ralph-launcher.ts`), which already
179
+ * folds process liveness into each entry. Falls back to reading the same
180
+ * registry file directly when the compiled reader is unavailable.
181
+ */
182
+ export async function readActiveLoops(cwd) {
183
+ try {
184
+ const { getLoopStatuses } = await importImpl(import.meta.url, 'cli/handlers/ralph-launcher.js');
185
+ return getLoopStatuses(cwd)
186
+ .filter(entry => entry?.status === 'running')
187
+ .map(entry => entry?.loopId || '?');
188
+ } catch {
189
+ try {
190
+ const raw = fs.readFileSync(path.join(cwd, '.aiwg', 'ralph-external', 'launcher-registry.json'), 'utf8');
191
+ const loops = JSON.parse(raw).loops || {};
192
+ return Object.entries(loops)
193
+ .filter(([, entry]) => entry?.status === 'running' && isAlive(entry?.pid))
194
+ .map(([loopId]) => loopId);
195
+ } catch {
196
+ return [];
197
+ }
198
+ }
199
+ }
200
+
201
+ function isAlive(pid) {
202
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
203
+ try { process.kill(pid, 0); return true; }
204
+ catch { return false; }
205
+ }
206
+
207
+ /**
208
+ * Direct-worker run directories known to AIWG launchers. There is no shared
209
+ * default `--runs-root`: every launcher records a per-worker `--run-dir`
210
+ * (Mission Control writes `<root>/.aiwg/ralph-external/mc/sessions/<session>/<mission>.run`;
211
+ * loop launches record `managedWorker.runDir` in the launcher registry).
212
+ * Missing roots mean "no workers"; any other discovery error throws so the
213
+ * caller fails closed.
214
+ */
215
+ export function defaultWorkerRunDirs(cwd) {
216
+ const runDirs = [];
217
+ const sessionsDir = path.join(cwd, '.aiwg', 'ralph-external', 'mc', 'sessions');
218
+ let sessions;
219
+ try {
220
+ sessions = fs.readdirSync(sessionsDir, { withFileTypes: true });
221
+ } catch (error) {
222
+ if (error?.code !== 'ENOENT') throw error;
223
+ }
224
+ if (sessions) {
225
+ for (const session of sessions) {
226
+ if (!session.isDirectory()) continue;
227
+ let children;
228
+ try {
229
+ children = fs.readdirSync(path.join(sessionsDir, session.name), { withFileTypes: true });
230
+ } catch (error) {
231
+ if (error?.code === 'ENOENT') continue;
232
+ throw error;
233
+ }
234
+ for (const child of children) {
235
+ if (child.isDirectory() && child.name.endsWith('.run')) {
236
+ runDirs.push(path.join(sessionsDir, session.name, child.name));
237
+ }
238
+ }
239
+ }
240
+ }
241
+ const registryFile = path.join(cwd, '.aiwg', 'ralph-external', 'launcher-registry.json');
242
+ let registryRaw;
243
+ try {
244
+ registryRaw = fs.readFileSync(registryFile, 'utf8');
245
+ } catch (error) {
246
+ if (error?.code !== 'ENOENT') throw error;
247
+ }
248
+ if (registryRaw !== undefined) {
249
+ const loops = JSON.parse(registryRaw).loops || {};
250
+ for (const entry of Object.values(loops)) {
251
+ if (typeof entry?.managedWorker?.runDir === 'string' && entry.managedWorker.runDir) {
252
+ runDirs.push(path.resolve(cwd, entry.managedWorker.runDir));
253
+ }
254
+ }
255
+ }
256
+ return [...new Set(runDirs)];
257
+ }
258
+
259
+ /** Default `sampleWorkerStatus` entry point (same reader `aiwg ralph-external --status --workers` uses). */
260
+ async function defaultSampleWorker({ runDir }) {
261
+ const { sampleWorkerStatus } = await import('../ralph-external/process-monitor.mjs');
262
+ return sampleWorkerStatus({ runDir });
263
+ }
264
+
265
+ /**
266
+ * Live direct workers via the existing `sampleWorkerStatus` reader. Any
267
+ * worker row whose `terminal` flag is not true (launching/started/active/
268
+ * quiet/stalled/hung, plus unreadable rows) counts as active work.
269
+ * An incomplete sample or a sampler failure throws `work-detection-unavailable`
270
+ * so the caller fails closed. `runDirs`/`sample` are injectable; production
271
+ * passes absolute run dirs discovered by `defaultWorkerRunDirs`.
272
+ */
273
+ export async function readActiveWorkers(cwd, { runDirs = null, sample = null } = {}) {
274
+ const dirs = runDirs ?? defaultWorkerRunDirs(cwd);
275
+ const sampler = sample ?? defaultSampleWorker;
276
+ const active = [];
277
+ for (const runDir of dirs) {
278
+ let report;
279
+ try {
280
+ report = await sampler({ runDir });
281
+ } catch (error) {
282
+ throw new Error(`work-detection-unavailable:${error.message}`);
283
+ }
284
+ for (const row of report?.workers || []) {
285
+ if (row?.terminal !== true) active.push(`direct-worker:${row?.invocationId || '?'}`);
286
+ }
287
+ if (!report || report.complete !== true) {
288
+ const hint = report?.findings?.[0] || 'incomplete-sample';
289
+ throw new Error(`work-detection-unavailable:${hint}`);
290
+ }
291
+ }
292
+ return active;
293
+ }
294
+
295
+ /** Mission statuses that no longer block an install (`MissionStatus` in `src/cli/handlers/mc.ts`). */
296
+ const MISSION_TERMINAL_STATUSES = new Set(['done', 'failed', 'aborted']);
297
+
298
+ /**
299
+ * Non-terminal Mission Control missions. There is no exported reusable
300
+ * mission reader (`readSession`/`listSessions` are private to
301
+ * `src/cli/handlers/mc.ts`, behind `aiwg mc status/list`), so this reads the
302
+ * same store those commands read — `.aiwg/ralph-external/mc/sessions/*\/session.json`
303
+ * — directly, mirroring the launcher-registry fallback in `readActiveLoops`.
304
+ * Queued, running, and paused missions all block: a paused mission still
305
+ * holds reservations and resumes. A missing sessions root means "no
306
+ * missions"; any other read or parse error throws so the caller fails
307
+ * closed.
308
+ */
309
+ export function readActiveMissions(cwd) {
310
+ const sessionsDir = path.join(cwd, '.aiwg', 'ralph-external', 'mc', 'sessions');
311
+ let sessions;
312
+ try {
313
+ sessions = fs.readdirSync(sessionsDir, { withFileTypes: true });
314
+ } catch (error) {
315
+ if (error?.code === 'ENOENT') return [];
316
+ throw new Error(`work-detection-unavailable:${error.message}`);
317
+ }
318
+ const active = [];
319
+ for (const session of sessions) {
320
+ if (!session.isDirectory()) continue;
321
+ const file = path.join(sessionsDir, session.name, 'session.json');
322
+ let raw;
323
+ try {
324
+ raw = fs.readFileSync(file, 'utf8');
325
+ } catch (error) {
326
+ if (error?.code === 'ENOENT') continue;
327
+ throw new Error(`work-detection-unavailable:${error.message}`);
328
+ }
329
+ let parsed;
330
+ try {
331
+ parsed = JSON.parse(raw);
332
+ } catch (error) {
333
+ throw new Error(`work-detection-unavailable:${error.message}`);
334
+ }
335
+ for (const mission of Array.isArray(parsed?.missions) ? parsed.missions : []) {
336
+ if (!MISSION_TERMINAL_STATUSES.has(mission?.status)) active.push(`mission:${mission?.id || '?'}`);
337
+ }
338
+ }
339
+ return active;
340
+ }
341
+
342
+ /**
343
+ * Active-work gate. Reuses the existing detectors only: daemon task-store
344
+ * schedules/agent tasks, ralph loop liveness, direct-worker status, and
345
+ * Mission Control missions. Returns `{ active, reasons }`. Every reader
346
+ * failure (other than "store/reader simply absent") reports
347
+ * `active: true` with a `work-detection-unavailable:<reason>` entry.
348
+ */
349
+ export async function detectActiveWork({ cwd = process.cwd(), taskStore = null, readLoops = readActiveLoops, readWorkers = readActiveWorkers, readMissions = readActiveMissions } = {}) {
350
+ const reasons = [];
351
+ const store = taskStore
352
+ ? {
353
+ busySchedules: (taskStore.getSchedules?.() || [])
354
+ .filter(s => ['running', 'blocked', 'retry', 'pending'].includes(s?.state))
355
+ .map(s => s?.job?.id || '?'),
356
+ busyTasks: (taskStore.getTasks?.() || [])
357
+ .filter(t => ['running', 'queued'].includes(t?.state))
358
+ .map(t => t?.id || '?'),
359
+ unavailable: null,
360
+ }
361
+ : readStoreWork(cwd);
362
+ for (const id of store.busySchedules) reasons.push(`daemon-task:${id}`);
363
+ for (const id of store.busyTasks) reasons.push(`agent-task:${id}`);
364
+ if (store.unavailable) reasons.push(store.unavailable);
365
+ for (const [reader, prefix] of [[readLoops, 'ralph-loop:'], [readWorkers, ''], [readMissions, '']]) {
366
+ try {
367
+ const ids = await reader(cwd);
368
+ for (const id of ids || []) reasons.push(prefix ? `${prefix}${id}` : id);
369
+ } catch (error) {
370
+ const reason = String(error?.message || error);
371
+ reasons.push(reason.startsWith('work-detection-unavailable:') ? reason : `work-detection-unavailable:${reason}`);
372
+ return { active: true, reasons };
373
+ }
374
+ }
375
+ return { active: reasons.length > 0, reasons };
376
+ }
377
+
378
+ // Injectable seams for tests. Production always uses the lazy defaults, which
379
+ // resolve the checker's check-only probe and the installer's own preflight and
380
+ // install entry points — never a copy of their logic.
381
+ const testSeams = {};
382
+ export function setUpdateInstallSeams(seams) { Object.assign(testSeams, seams); }
383
+ export function resetUpdateInstallSeams() { for (const key of Object.keys(testSeams)) delete testSeams[key]; }
384
+
385
+ /**
386
+ * Resolve the owner entry points, loading the real checker/installer only for
387
+ * keys the caller did not inject. Tests inject every seam, so they never
388
+ * perform a probe or install and never need a built dist/.
389
+ */
390
+ async function resolveDeps(overrides = {}) {
391
+ const merged = { now: Date.now, detectActiveWork, ...testSeams, ...overrides };
392
+ if (!merged.checkUpdateStatus || !merged.detectInstallMode || !merged.dryRunInstall || !merged.performInstall) {
393
+ const [{ checkUpdateStatus }, service] = await Promise.all([
394
+ importImpl(import.meta.url, 'update/checker.mjs'),
395
+ importImpl(import.meta.url, 'update/service.mjs'),
396
+ ]);
397
+ merged.checkUpdateStatus ??= checkUpdateStatus;
398
+ merged.detectInstallMode ??= service.detectInstallMode;
399
+ merged.dryRunInstall ??= options => service.updateInstallation({ ...options, dryRun: true });
400
+ merged.performInstall ??= options => service.updateInstallation(options);
401
+ }
402
+ return merged;
403
+ }
404
+
405
+ function deferred(reason, summary, detail) {
406
+ return { exitStatus: 2, state: 'deferred', reason, summary, detail };
407
+ }
408
+
409
+ /**
410
+ * Run one `update.install` job through every gate. Returns an owner receipt:
411
+ * `{ exitStatus, state?, reason?, summary, detail?, uncertain? }`.
412
+ */
413
+ export async function runUpdateInstall(job, overrides = {}) {
414
+ const args = job?.args || {};
415
+ const channel = args.channel || 'stable';
416
+
417
+ // These gates need no owner entry points, so refusals never load them.
418
+ if (args.install !== true) {
419
+ return deferred('install-not-enabled',
420
+ 'Refusing update.install: installs are check-only by default (decision D3); enable per job with args.install: true',
421
+ { channel, checkOnly: true });
422
+ }
423
+ const policyErrors = validateUpdatePolicy(args);
424
+ if (policyErrors.length > 0) {
425
+ return deferred('invalid-policy', `Refusing update.install: ${policyErrors.join('; ')}`, { channel });
426
+ }
427
+ const clock = overrides.now || testSeams.now || Date.now;
428
+ const window = inMaintenanceWindow(clock(), args.windows, job.timezone || 'UTC');
429
+ if (!window.inside) {
430
+ return deferred('outside-maintenance-window',
431
+ `Refusing update.install: ${window.reason}; no install is attempted outside a maintenance window`,
432
+ { channel, window: window.reason });
433
+ }
434
+ const configured = await resolveDeps(overrides);
435
+
436
+ let status;
437
+ try {
438
+ status = await configured.checkUpdateStatus({ channel });
439
+ } catch (error) {
440
+ return { exitStatus: null, uncertain: true, summary: `Update probe failed; inspect before recovery: ${error.message}` };
441
+ }
442
+ if (!status || status.status === 'unsupported') {
443
+ return deferred('unsupported-channel',
444
+ `Deferring update.install: channel '${channel}' has no read-only probe; edge installs stay manual`,
445
+ { channel, checkOnly: true });
446
+ }
447
+ if (!status.available) {
448
+ return { exitStatus: 0, summary: `Already current on ${channel} (${status.current})`,
449
+ detail: { ...status, rollback: null, redeploy: 'not-performed' } };
450
+ }
451
+ const gate = versionAllowed(status.current, status.latest, args);
452
+ if (!gate.allowed) {
453
+ return deferred(gate.reason,
454
+ `Refusing update.install ${status.current} → ${status.latest} (${gate.bump}): ${gate.reason}; adjust versionPolicy/allowMajor explicitly to proceed`,
455
+ { ...status, bump: gate.bump });
456
+ }
457
+
458
+ const work = await configured.detectActiveWork({ cwd: overrides.cwd || process.cwd() });
459
+ if (work.active) {
460
+ return deferred('active-work',
461
+ `Deferring update.install: active AIWG work detected (${work.reasons.join(', ')}); installs never run alongside live work`,
462
+ { ...status, activeWork: work.reasons });
463
+ }
464
+
465
+ let preflight;
466
+ try {
467
+ preflight = await configured.dryRunInstall({ channel });
468
+ } catch (error) {
469
+ return deferred('preflight-failed',
470
+ `Refusing update.install: installer preflight failed: ${error.message}`,
471
+ { ...status });
472
+ }
473
+ if (preflight?.status === 'manual') {
474
+ return deferred('install-manual-required',
475
+ `Deferring update.install: ${preflight.message}`,
476
+ { ...status, installMode: preflight.mode });
477
+ }
478
+ if (preflight?.status === 'unsupported-offline') {
479
+ return deferred('preflight-failed',
480
+ `Deferring update.install: installer is offline: ${preflight.message}`,
481
+ { ...status });
482
+ }
483
+
484
+ let result;
485
+ try {
486
+ result = await configured.performInstall({ channel });
487
+ } catch (error) {
488
+ // The installer threw mid-flight: effects are unknown, so this goes to
489
+ // the schedule-recovery-required path and is never auto-retried.
490
+ return { exitStatus: null, uncertain: true,
491
+ summary: `Update install outcome uncertain; inspect effects before recovery: ${error.message}`,
492
+ detail: { ...status, attemptedInstall: true } };
493
+ }
494
+ if (!result || typeof result !== 'object' || (result.changed !== true && result.status !== 'updated')) {
495
+ return { exitStatus: null, uncertain: true,
496
+ summary: 'Update install returned an unrecognized receipt; inspect effects before recovery',
497
+ detail: { ...status, installerResult: result || null } };
498
+ }
499
+ const rollback = rollbackGuidance(result, status);
500
+ return { exitStatus: 0,
501
+ summary: `Updated ${status.current} → ${result.version || status.latest} on ${channel}; provider redeploy NOT performed`,
502
+ detail: { ...status, oldVersion: status.current, newVersion: result.version || status.latest,
503
+ installMode: result.mode, rollback, redeploy: 'not-performed',
504
+ redeployHint: 'Re-deploy providers separately when ready: aiwg update --skip-check' } };
505
+ }
506
+
507
+ function rollbackGuidance(result, status) {
508
+ if (result.mode === 'npm' && result.command) {
509
+ const manager = result.command.split(' ')[0];
510
+ return { how: `Re-install the previous version: ${manager} install --global aiwg@${status.current}`,
511
+ command: `${manager} install --global aiwg@${status.current}` };
512
+ }
513
+ if (result.mode === 'web') {
514
+ return { how: 'Re-resolve the previous signed web resource release for this channel; verified cached resources remain available offline.' };
515
+ }
516
+ return { how: 'Manual installation: restore the previous checkout or package from your own backup before re-running.' };
517
+ }