@aiwg/cli 2026.10.14 → 2026.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,535 @@
1
+ /** Scheduled jobs: deterministic owner operations plus explicit legacy agent actions. */
2
+
3
+ import { EventEmitter } from 'events';
4
+ import { fork } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { nextCronRun } from './cron-scheduler.mjs';
7
+ import { applyChildNiceness, normalizeResources } from './resource-bounds.mjs';
8
+ import { importImpl } from '../_resolve-impl.mjs';
9
+
10
+ const { signalChild } = await importImpl(import.meta.url, 'process/signal-child.mjs');
11
+
12
+ /**
13
+ * @typedef {'index.verify'|'index.reconcile'|'cache.retention'|'update.check'|'update.install'|'index.freshness'|'index.refresh'|'cache.prune'|'memory.audit'|'memory.recommend'|'memory.apply'} MaintenanceKind
14
+ * @typedef {Object} MaintenanceJob
15
+ * @property {string} id Stable configured job identity
16
+ * @property {MaintenanceKind} kind Closed owner operation; never a prompt
17
+ * @property {string} [cron] Five civil-time cron fields (alias: schedule)
18
+ * @property {string} [timezone] Named IANA timezone, defaults to UTC
19
+ * @property {'skip'|'run-once'} [missedRunPolicy] Downtime coalescing, defaults to skip
20
+ * @property {Object} [args] Owner-specific arguments, never arbitrary CLI tokens
21
+ * @property {number} [timeoutMs] Bounded worker deadline, defaults to 60000
22
+ * @property {0|1|2} [retries] Retries after the first attempt, defaults to 2
23
+ * @property {{baseMs: number, maxMs: number}} [backoff] Equal-jitter bounds
24
+ */
25
+ export const MAINTENANCE_KINDS = Object.freeze([
26
+ 'index.verify', 'index.reconcile', 'cache.retention', 'update.check',
27
+ 'index.freshness', 'index.refresh', 'cache.prune', 'update.install',
28
+ 'memory.audit', 'memory.recommend', 'memory.apply',
29
+ ]);
30
+
31
+ /** Equal jitter: [ceiling/2, ceiling], capped before jitter; retries never loop in a tick. */
32
+ export function retryDelay(attempt, { baseMs = 1000, maxMs = 300000 } = {}, rng = Math.random) {
33
+ const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt - 1, 30));
34
+ const sample = rng();
35
+ if (!Number.isFinite(sample) || sample < 0 || sample > 1) throw new Error('Invalid retry RNG');
36
+ return Math.floor(ceiling * (0.5 + sample * 0.5));
37
+ }
38
+
39
+ /** Await child exit, including on timeout: an uncertain exit is never safe to replay. */
40
+ export function executeMaintenanceOwner(job, { cwd = process.cwd(), onSpawn = () => {}, niceness = null, environment = process.env } = {}) {
41
+ return new Promise((resolve, reject) => {
42
+ const child = fork(fileURLToPath(new URL('./maintenance-owner.mjs', import.meta.url)), [], {
43
+ cwd, env: { ...environment, AIWG_MAINTENANCE_WORKER: '1', NO_UPDATE_NOTIFIER: '1' },
44
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
45
+ });
46
+ if (niceness !== null && niceness !== undefined) applyChildNiceness(child.pid, { niceness });
47
+ let receipt;
48
+ let timedOut = false;
49
+ const timeout = setTimeout(() => { timedOut = true; signalChild(child, 'SIGKILL'); }, job.timeoutMs || 60000);
50
+ child.once('message', result => { receipt = result; });
51
+ child.once('error', error => { clearTimeout(timeout); reject(error); });
52
+ child.once('exit', (code, signal) => {
53
+ clearTimeout(timeout);
54
+ if (timedOut || signal || !receipt) {
55
+ resolve({ exitStatus: code, state: 'deferred', uncertain: true,
56
+ summary: timedOut ? 'Owner timeout; inspect effects before recovery' : `Owner interrupted (${signal || code}); inspect effects before recovery` });
57
+ } else resolve(receipt);
58
+ });
59
+ try {
60
+ // Record the worker identity before sending it authority to execute.
61
+ onSpawn(child.pid);
62
+ child.send(job);
63
+ } catch (error) {
64
+ signalChild(child, 'SIGKILL');
65
+ clearTimeout(timeout);
66
+ reject(error);
67
+ }
68
+ });
69
+ }
70
+
71
+
72
+ /**
73
+ * Built-in action registry — maps action names to task prompts.
74
+ * Users can override these or add custom actions with a `prompt` field
75
+ * in their job config.
76
+ */
77
+ const BUILTIN_ACTIONS = {
78
+ doctor: {
79
+ prompt: 'Run `aiwg doctor` and report any issues found. If there are issues, suggest fixes.',
80
+ description: 'Health check',
81
+ },
82
+ 'validate-metadata': {
83
+ prompt: 'Run `aiwg validate-metadata` and report any validation errors in extension metadata.',
84
+ description: 'Artifact metadata audit',
85
+ },
86
+ 'doc-sync': {
87
+ prompt: 'Run `aiwg doc-sync code-to-docs --dry-run` and report any documentation-code drift found.',
88
+ description: 'Documentation sync check',
89
+ },
90
+ 'test-sync': {
91
+ prompt: 'Run `npm test` and report results. If any tests fail, identify the root cause.',
92
+ description: 'Test suite execution',
93
+ },
94
+ };
95
+
96
+ /**
97
+ * @typedef {Object} ScheduledTaskRunnerOptions
98
+ * @property {import('../ralph-external/daemon-supervisor.mjs').DaemonSupervisor} [supervisor]
99
+ * @property {import('./event-router.mjs').default} [eventRouter]
100
+ * @property {import('../messaging/room-manager.mjs').RoomManager} [roomManager]
101
+ * @property {import('./task-store.mjs').TaskStore} [taskStore] Required for maintenance jobs
102
+ * @property {() => number} [now] Epoch milliseconds
103
+ * @property {() => number} [rng] Random sample in [0,1]
104
+ * @property {Function} [executeOwner] Injectable deterministic executor returning an owner receipt
105
+ * @property {string} [cwd] Owner workspace
106
+ * @property {Object} [resources] Validated by resource-bounds.mjs (concurrency, queue, timeout ceiling, niceness)
107
+ */
108
+
109
+ export class ScheduledTaskRunner extends EventEmitter {
110
+ /** @type {import('../ralph-external/daemon-supervisor.mjs').DaemonSupervisor} */
111
+ #supervisor;
112
+
113
+ /** @type {import('./event-router.mjs').default} */
114
+ #eventRouter;
115
+
116
+ /** @type {import('../messaging/room-manager.mjs').RoomManager|null} */
117
+ #roomManager;
118
+
119
+ /** @type {Map<string, { action: string, lastRun: string|null, runCount: number }>} */
120
+ #jobHistory = new Map();
121
+
122
+ /** @type {boolean} */
123
+ #started = false;
124
+ #taskStore;
125
+ #now;
126
+ #rng;
127
+ #executeOwner;
128
+ #cwd;
129
+ #environment;
130
+ #listener;
131
+ #recoveryListener;
132
+
133
+
134
+ /**
135
+ * @param {ScheduledTaskRunnerOptions} options
136
+ */
137
+ constructor(options) {
138
+ super();
139
+ this.#supervisor = options.supervisor;
140
+ this.#eventRouter = options.eventRouter;
141
+ this.#roomManager = options.roomManager || null;
142
+ this.#taskStore = options.taskStore || null;
143
+ this.#now = options.now || Date.now;
144
+ this.#rng = options.rng || Math.random;
145
+ this.#executeOwner = options.executeOwner || executeMaintenanceOwner;
146
+ this.#cwd = options.cwd || process.cwd();
147
+ this.#environment = options.environment;
148
+ const { config, errors } = normalizeResources(options.resources);
149
+ if (errors.length > 0) throw new Error(`Invalid runner resources: ${errors.join('; ')}`);
150
+ this.resources = config;
151
+ this.inflight = 0;
152
+ this.waiters = [];
153
+ this.pendingRuns = 0;
154
+ this.overflowCount = 0;
155
+ }
156
+
157
+ /** FIFO slot for the concurrency bound; resolves when a run may execute. */
158
+ acquireSlot() {
159
+ if (this.inflight < this.resources.maxConcurrentJobs) {
160
+ this.inflight++;
161
+ return Promise.resolve();
162
+ }
163
+ return new Promise(resolve => { this.waiters.push(resolve); });
164
+ }
165
+
166
+ releaseSlot() {
167
+ const next = this.waiters.shift();
168
+ if (next) next();
169
+ else this.inflight = Math.max(0, this.inflight - 1);
170
+ }
171
+
172
+ /**
173
+ * Start listening for cron events.
174
+ */
175
+ start() {
176
+ if (this.#started) return;
177
+ this.#taskStore?.recoverSchedules();
178
+ this.#started = true;
179
+
180
+ this.#listener = event => {
181
+ if (!this.#started || event.source !== 'schedule' || event.type !== 'cron.fired') return;
182
+ const handling = event.payload?.kind && event.payload.kind !== 'agent.prompt'
183
+ ? this.runOnce({ ...event.payload, id: event.payload.job_id || event.payload.id }, { fireTime: event.payload.fireTime })
184
+ : this.#handleCronEvent(event);
185
+ handling.catch(error => this.emit('recovery-required', { event, error }));
186
+ };
187
+ this.#eventRouter.on('event', this.#listener);
188
+ this.#recoveryListener = ({ event, error }) => {
189
+ if (event.source === 'watch') {
190
+ this.emit('recovery-required', { event, error });
191
+ return;
192
+ }
193
+ const { job_id: jobId, fireTime, ...job } = event.payload;
194
+ job.id = jobId || job.id;
195
+ if (!this.#taskStore || !job.id) throw error;
196
+ this.#taskStore.ensureSchedule(job);
197
+ this.#taskStore.changeSchedule(job.id, record => {
198
+ record.state = 'blocked';
199
+ record.pendingFireTime ||= fireTime || new Date(this.#now()).toISOString();
200
+ record.lastReceipt = { jobId: job.id, fireTime: record.pendingFireTime, state: 'deferred',
201
+ reason: 'recovery-required', exitStatus: null, summary: error.message,
202
+ startedAt: new Date(this.#now()).toISOString(), finishedAt: new Date(this.#now()).toISOString(),
203
+ durationMs: 0, attemptCount: record.attemptCount, terminal: false };
204
+ record.receipts.push(record.lastReceipt);
205
+ return record;
206
+ });
207
+ this.emit('recovery-required', { event, error });
208
+ };
209
+ this.#eventRouter.on('schedule-recovery-required', this.#recoveryListener);
210
+ }
211
+
212
+ stop() {
213
+ this.#started = false;
214
+ if (this.#listener) this.#eventRouter.off('event', this.#listener);
215
+ if (this.#recoveryListener) this.#eventRouter.off('schedule-recovery-required', this.#recoveryListener);
216
+ }
217
+
218
+ /** One owner attempt, shared by cron and manual mode. Retried only after persisted retryAt. */
219
+ async runOnce(job, { fireTime } = {}) {
220
+ if (!this.#taskStore) throw new Error('Maintenance requires a persistent TaskStore');
221
+ if (!job.id) throw new Error('Maintenance requires a job ID');
222
+ if (job.kind?.startsWith('memory.')) {
223
+ const { validateMemoryJobArgs } = await importImpl(import.meta.url, 'housekeeper/daemon-config.js');
224
+ validateMemoryJobArgs(job.kind, job.args);
225
+ }
226
+ // Do not persist event envelope fields as configuration.
227
+ const { job_id: _jobId, fireTime: _fireTime, ...configuration } = job;
228
+ job = configuration;
229
+ const now = this.#now();
230
+ const timestamp = new Date(now).toISOString();
231
+ const expression = job.cron || job.schedule;
232
+ const nextRun = expression ? nextCronRun(expression, now, job.timezone).toISOString() : null;
233
+ this.#taskStore.recoverSchedules();
234
+ this.#taskStore.ensureSchedule(job, nextRun);
235
+ const existing = this.#taskStore.getSchedule(job.id);
236
+ fireTime ||= existing.pendingFireTime || new Date(Math.floor(now / 60000) * 60000).toISOString();
237
+ if (!Number.isFinite(Date.parse(fireTime))) throw new Error('Invalid fireTime');
238
+ fireTime = new Date(fireTime).toISOString();
239
+ let claim = false;
240
+ let response;
241
+ this.#taskStore.changeSchedule(job.id, record => {
242
+ const settled = record.receipts.find(receipt => receipt.fireTime === fireTime && receipt.terminal !== false);
243
+ if (settled) {
244
+ response = { ...settled, state: 'skipped', reason: 'already-settled' };
245
+ return record;
246
+ }
247
+ if (record.state === 'running' || record.state === 'blocked') {
248
+ let alive = false;
249
+ if (record.ownerPid) {
250
+ try { process.kill(record.ownerPid, 0); alive = true; }
251
+ catch (error) { if (error.code !== 'ESRCH') alive = true; }
252
+ }
253
+ if (!alive) record.state = 'blocked';
254
+ response = { jobId: job.id, fireTime, state: 'deferred', reason: alive ? 'lock-held' : 'recovery-required',
255
+ exitStatus: null, summary: 'Run outcome unresolved; inspect the retained intent', startedAt: timestamp,
256
+ finishedAt: timestamp, durationMs: 0, attemptCount: record.attemptCount, terminal: false };
257
+ record.lastReceipt = response;
258
+ return record;
259
+ }
260
+ if (record.pendingFireTime && record.pendingFireTime !== fireTime) {
261
+ response = { jobId: job.id, fireTime, state: 'deferred', reason: 'pending-run', summary: 'An earlier run is pending',
262
+ exitStatus: null, startedAt: timestamp, finishedAt: timestamp, durationMs: 0, attemptCount: record.attemptCount, terminal: false };
263
+ return record;
264
+ }
265
+ if (record.retryAt && Date.parse(record.retryAt) > now) {
266
+ response = { ...record.lastReceipt, state: 'deferred', reason: 'backoff' };
267
+ return record;
268
+ }
269
+ claim = true;
270
+ if (record.state === 'idle') record.attemptCount = 0;
271
+ record.state = 'running';
272
+ record.pendingFireTime = fireTime;
273
+ record.attemptCount++;
274
+ record.lastRun = timestamp;
275
+ record.ownerPid = process.pid;
276
+ record.workerPid = null;
277
+ record.nextRun = nextRun;
278
+ record.retryAt = null;
279
+ return record;
280
+ });
281
+ if (!claim) return response;
282
+
283
+ this.pendingRuns++;
284
+ try {
285
+ if (this.pendingRuns > this.resources.maxConcurrentJobs + this.resources.maxQueueDepth) {
286
+ return this.overflowRun(job, { fireTime, timestamp, expression });
287
+ }
288
+ return await this.executeClaimed(job, { fireTime, timestamp, expression, supported: MAINTENANCE_KINDS.includes(job.kind) });
289
+ } finally {
290
+ this.pendingRuns--;
291
+ }
292
+ }
293
+
294
+ /** Persisted queue-overflow report: the run is dropped, the next fire retries. */
295
+ overflowRun(job, { fireTime, timestamp, expression }) {
296
+ this.overflowCount++;
297
+ const finishedAt = new Date(this.#now()).toISOString();
298
+ let receipt;
299
+ this.#taskStore.changeSchedule(job.id, record => {
300
+ receipt = { jobId: job.id, fireTime, state: 'deferred', reason: 'queue-overflow',
301
+ exitStatus: null,
302
+ summary: `Run queue full (${this.resources.maxConcurrentJobs} concurrent, ${this.resources.maxQueueDepth} queued); run dropped, next fire retries`,
303
+ startedAt: timestamp, finishedAt, durationMs: 0, attemptCount: record.attemptCount, terminal: true };
304
+ record.receipts.push(receipt);
305
+ record.lastReceipt = receipt;
306
+ record.state = 'idle';
307
+ record.ownerPid = null;
308
+ record.workerPid = null;
309
+ record.pendingFireTime = null;
310
+ record.nextRun = expression ? nextCronRun(expression, this.#now(), record.timezone).toISOString() : null;
311
+ return record;
312
+ });
313
+ this.emit('job:overflow', receipt);
314
+ this.emit('job:receipt', receipt);
315
+ return receipt;
316
+ }
317
+
318
+ /** Execute a claimed run under the concurrency bound and timeout ceiling. */
319
+ async executeClaimed(job, { fireTime, timestamp, expression, supported }) {
320
+ const now = Date.parse(timestamp);
321
+ let result;
322
+ try {
323
+ if (!supported) result = { exitStatus: 2, summary: `Unsupported task kind: ${job.kind}` };
324
+ else if (job.prompt || job.args?.force || (job.args?.install && job.kind !== 'update.install')) {
325
+ result = { exitStatus: 2, summary: 'Maintenance cannot accept prompts, install, or force authority' };
326
+ } else {
327
+ // Mutation authority stays with each owner (including the exact
328
+ // reviewed memory plan). Clamp deadlines to the global ceiling.
329
+ const boundedJob = { ...job,
330
+ timeoutMs: Math.min(job.timeoutMs || 60000, this.resources.maxTimeoutMs) };
331
+ await this.acquireSlot();
332
+ try {
333
+ result = await this.#executeOwner(boundedJob, { cwd: this.#cwd,
334
+ environment: this.#environment,
335
+ niceness: this.resources.jobNiceness,
336
+ onSpawn: pid => {
337
+ this.#taskStore.changeSchedule(job.id, record => ({ ...record, workerPid: pid }));
338
+ } });
339
+ } finally {
340
+ this.releaseSlot();
341
+ }
342
+ }
343
+ if (!result || (result.exitStatus !== null && !Number.isInteger(result.exitStatus))) {
344
+ result = { exitStatus: null, uncertain: true, summary: 'Invalid owner receipt; inspect effects' };
345
+ }
346
+ // A mutating memory result must establish a complete, verified success.
347
+ // Even a definite owner refusal requires inspection rather than replay.
348
+ if (job.kind === 'memory.apply' && result.exitStatus !== 0
349
+ && !(result.state === 'deferred' && ['outside-maintenance-window', 'gate-denied'].includes(result.reason))) {
350
+ result = { ...result, uncertain: true };
351
+ }
352
+ } catch (error) {
353
+ // A thrown executor error does not establish whether it launched work.
354
+ result = { exitStatus: null, uncertain: true, summary: error.message };
355
+ }
356
+ const finishedAt = new Date(this.#now()).toISOString();
357
+ let receipt;
358
+ this.#taskStore.changeSchedule(job.id, record => {
359
+ const failed = result.exitStatus !== 0;
360
+ const maxAttempts = Math.min(3, Math.max(1, Number(job.retries ?? 2) + 1));
361
+ const retry = supported && failed && !result.uncertain && result.exitStatus !== 2
362
+ && result.state !== 'deferred' && record.attemptCount < maxAttempts;
363
+ // Owner gate refusals (e.g. update-install policy) carry their own
364
+ // machine-readable reason through to the persisted receipt.
365
+ const gateReason = !result.uncertain && result.state === 'deferred' && typeof result.reason === 'string'
366
+ ? result.reason : undefined;
367
+ receipt = { jobId: job.id, fireTime, state: result.uncertain ? 'deferred' : result.state || (failed ? 'failed' : 'ok'),
368
+ reason: result.uncertain ? 'recovery-required' : retry ? 'retry-pending' : gateReason,
369
+ exitStatus: result.exitStatus, summary: result.summary || '', detail: result.detail,
370
+ startedAt: timestamp, finishedAt, durationMs: Math.max(0, this.#now() - now),
371
+ attemptCount: record.attemptCount, terminal: !retry && !result.uncertain };
372
+ record.receipts.push(receipt);
373
+ record.lastReceipt = receipt;
374
+ record.state = result.uncertain ? 'blocked' : retry ? 'retry' : 'idle';
375
+ record.ownerPid = null;
376
+ if (!result.uncertain) record.workerPid = null;
377
+ record.retryAt = retry ? new Date(this.#now() + retryDelay(record.attemptCount, job.backoff, this.#rng)).toISOString() : null;
378
+ if (!retry && !result.uncertain) record.pendingFireTime = null;
379
+ // Completion advances past downtime too; never queue every slot missed during a slow run.
380
+ record.nextRun = expression ? nextCronRun(expression, this.#now(), record.timezone).toISOString() : null;
381
+ return record;
382
+ });
383
+ this.emit('job:receipt', receipt);
384
+ return receipt;
385
+ }
386
+
387
+ /**
388
+ * Handle a cron.fired event by submitting a task.
389
+ *
390
+ * @param {Object} event
391
+ */
392
+ async #handleCronEvent(event) {
393
+ const jobId = event.payload?.job_id || event.payload?.id;
394
+ const action = event.payload?.action;
395
+ const priority = event.payload?.priority ?? 1;
396
+
397
+ if (!action) {
398
+ this.emit('recovery-required', { event, error: new Error('Cron event missing action') });
399
+ return;
400
+ }
401
+
402
+ const prompt = this.#resolvePrompt(action, event.payload);
403
+ if (!prompt) {
404
+ this.emit('recovery-required', { event, error: new Error(`Unknown action: ${action}`) });
405
+ return;
406
+ }
407
+
408
+ console.log(`[scheduled-task-runner] Executing job ${jobId}: ${action}`);
409
+
410
+ try {
411
+ const result = await this.#supervisor.submit({
412
+ prompt,
413
+ priority,
414
+ metadata: {
415
+ source: 'scheduler',
416
+ jobId,
417
+ action,
418
+ },
419
+ });
420
+
421
+ // Track history
422
+ this.#jobHistory.set(jobId, {
423
+ action,
424
+ lastRun: new Date().toISOString(),
425
+ runCount: (this.#jobHistory.get(jobId)?.runCount || 0) + 1,
426
+ });
427
+
428
+ this.emit('job:submitted', { jobId, action, taskId: result?.loopId || result?.taskId });
429
+
430
+ // Notify notification-purpose rooms
431
+ if (this.#roomManager) {
432
+ const rooms = this.#roomManager.getBroadcastRooms();
433
+ if (rooms.length > 0) {
434
+ this.emit('notify', {
435
+ message: `Scheduled job "${jobId}" (${action}) submitted`,
436
+ rooms,
437
+ });
438
+ }
439
+ }
440
+ } catch (error) {
441
+ console.error(`[scheduled-task-runner] Failed to submit job ${jobId}: ${error.message}`);
442
+ this.emit('job:failed', { jobId, action, error: error.message });
443
+ this.emit('recovery-required', { event, error });
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Resolve action name to a prompt string.
449
+ *
450
+ * @param {string} action
451
+ * @param {Object} payload - Job payload (may contain custom `prompt`)
452
+ * @returns {string|null}
453
+ */
454
+ #resolvePrompt(action, payload) {
455
+ // Custom prompt in job config takes precedence
456
+ if (payload?.prompt) {
457
+ return payload.prompt;
458
+ }
459
+
460
+ // Built-in action
461
+ const builtin = BUILTIN_ACTIONS[action];
462
+ if (builtin) {
463
+ return builtin.prompt;
464
+ }
465
+
466
+ return null;
467
+ }
468
+
469
+ /**
470
+ * Register a custom action.
471
+ *
472
+ * @param {string} name
473
+ * @param {Object} config
474
+ * @param {string} config.prompt
475
+ * @param {string} [config.description]
476
+ */
477
+ registerAction(name, config) {
478
+ BUILTIN_ACTIONS[name] = config;
479
+ }
480
+
481
+ /**
482
+ * Get job execution history.
483
+ *
484
+ * @returns {Object[]}
485
+ */
486
+ getHistory() {
487
+ return [...this.#jobHistory.entries()].map(([jobId, info]) => ({
488
+ jobId,
489
+ ...info,
490
+ }));
491
+ }
492
+
493
+ /**
494
+ * Get status summary.
495
+ *
496
+ * @returns {Object}
497
+ */
498
+ getStatus() {
499
+ return {
500
+ started: this.#started,
501
+ registeredActions: Object.keys(BUILTIN_ACTIONS),
502
+ maintenanceKinds: [...MAINTENANCE_KINDS],
503
+ schedules: this.#taskStore?.getSchedules() || [],
504
+ jobHistory: this.getHistory(),
505
+ resources: { ...this.resources },
506
+ inflight: this.inflight,
507
+ queued: this.waiters.length,
508
+ overflowed: this.overflowCount,
509
+ };
510
+ }
511
+ }
512
+
513
+ export default ScheduledTaskRunner;
514
+
515
+ /** Existing daemon schedule surface, no IPC, watcher, supervisor, or background process. */
516
+ export async function runManualSchedule(flags, { now = Date.now, executeOwner } = {}) {
517
+ if (process.platform === 'win32') throw new Error('Scheduled maintenance unsupported on Windows; use WSL2');
518
+ const [{ Config }, { TaskStore }] = await Promise.all([import('./config.mjs'), import('./task-store.mjs')]);
519
+ if (typeof flags.job !== 'string') throw new Error('--run-once requires --job ID');
520
+ const config = new Config(flags.config || '.aiwg/daemon.json');
521
+ config.load();
522
+ const job = config.get('schedule.jobs')?.find(job => job.id === flags.job);
523
+ if (!job || !MAINTENANCE_KINDS.includes(job.kind)) throw new Error('Select a configured deterministic maintenance job');
524
+ const store = new TaskStore(flags['store-path'] || '.aiwg/daemon/tasks.json', { now });
525
+ await store.initialize();
526
+ let receipt;
527
+ if (flags.resolve) {
528
+ receipt = store.resolveSchedule(job.id, flags.resolve).lastReceipt;
529
+ } else {
530
+ const runner = new ScheduledTaskRunner({ taskStore: store, now, executeOwner, resources: config.get('resources') });
531
+ receipt = await runner.runOnce(job, { fireTime: flags['fire-time'] });
532
+ }
533
+ console.log(flags.json ? JSON.stringify(receipt) : `${receipt.jobId}: ${receipt.state}: ${receipt.summary}`);
534
+ return receipt.state === 'deferred' ? 3 : receipt.state === 'failed' ? 1 : 0;
535
+ }