@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.
- package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
- package/dist/src/artifacts/citation-parser.js +7 -6
- package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
- package/dist/src/artifacts/corpus-tools/cli.js +8 -3
- package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
- package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
- package/dist/src/artifacts/corpus-tools/expand.js +16 -17
- package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
- package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
- package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
- package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
- package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
- package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
- package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
- package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
- package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
- package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
- package/dist/src/artifacts/graph-query.js +5 -3
- package/dist/src/artifacts/hybrid-query.js +11 -2
- package/dist/src/artifacts/index-refresh.js +2 -0
- package/dist/src/artifacts/query-engine-corpus.js +217 -0
- package/dist/src/artifacts/query-engine-discover-output.js +229 -0
- package/dist/src/artifacts/query-engine-discover.js +285 -0
- package/dist/src/artifacts/query-engine-entries.js +188 -0
- package/dist/src/artifacts/query-engine-index.js +249 -0
- package/dist/src/artifacts/query-engine-matching.js +143 -0
- package/dist/src/artifacts/query-engine-options.js +2 -0
- package/dist/src/artifacts/query-engine-rules.js +202 -0
- package/dist/src/artifacts/query-engine-scoring.js +436 -0
- package/dist/src/artifacts/query-engine-show-card.js +194 -0
- package/dist/src/artifacts/query-engine-show-load.js +211 -0
- package/dist/src/artifacts/query-engine-show.js +300 -0
- package/dist/src/artifacts/query-engine.js +7 -2576
- package/dist/src/cli/handlers/daemon.js +17 -1
- package/dist/src/cli/handlers/doctor-args.js +10 -5
- package/dist/src/cli/handlers/doctor-help.js +4 -1
- package/dist/src/cli/handlers/index.js +2 -2
- package/dist/src/cli/handlers/mc-agents.js +111 -0
- package/dist/src/cli/handlers/mc-args.js +54 -0
- package/dist/src/cli/handlers/mc-control.js +227 -0
- package/dist/src/cli/handlers/mc-dispatch.js +203 -0
- package/dist/src/cli/handlers/mc-help.js +171 -0
- package/dist/src/cli/handlers/mc-run.js +343 -0
- package/dist/src/cli/handlers/mc-session.js +138 -0
- package/dist/src/cli/handlers/mc-status.js +258 -0
- package/dist/src/cli/handlers/mc-summary.js +43 -0
- package/dist/src/cli/handlers/mc-types.js +3 -0
- package/dist/src/cli/handlers/mc-worker.js +205 -0
- package/dist/src/cli/handlers/mc.js +12 -1665
- package/dist/src/cli/handlers/models-refusal.js +13 -0
- package/dist/src/cli/handlers/models-resource-sample.js +10 -0
- package/dist/src/cli/handlers/models.js +5 -3
- package/dist/src/cli/handlers/regenerate.js +8 -16
- package/dist/src/cli/handlers/remove-bundled.js +133 -0
- package/dist/src/cli/handlers/remove-options.js +31 -0
- package/dist/src/cli/handlers/remove-user.js +174 -0
- package/dist/src/cli/handlers/remove.js +201 -0
- package/dist/src/cli/handlers/sessions.js +7 -7
- package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
- package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
- package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
- package/dist/src/cli/handlers/subcommands-list.js +250 -0
- package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
- package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
- package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
- package/dist/src/cli/handlers/subcommands-services.js +66 -0
- package/dist/src/cli/handlers/subcommands-storage.js +259 -0
- package/dist/src/cli/handlers/subcommands.js +18 -1976
- package/dist/src/cli/handlers/update.js +157 -0
- package/dist/src/cli/handlers/use.js +14 -4
- package/dist/src/cli/handlers/utilities.js +3 -560
- package/dist/src/cli/handlers/utility-doctor.js +412 -0
- package/dist/src/cli/scope-resolver.js +1 -142
- package/dist/src/cli/services/deployment-verification.js +0 -1
- package/dist/src/cli/user-scope-mirror.js +173 -0
- package/dist/src/config/aiwg-config.js +2 -1
- package/dist/src/config/authorization-cli.js +7 -3
- package/dist/src/config/dispatch-host-thresholds.js +2 -0
- package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
- package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
- package/dist/src/config/framework-aliases.js +12 -0
- package/dist/src/config/host-resource-report.d.mts +24 -0
- package/dist/src/config/host-resource-report.mjs +110 -0
- package/dist/src/config/host-resource-runtime.d.mts +37 -0
- package/dist/src/config/host-resource-runtime.mjs +296 -0
- package/dist/src/config/installed-selection.js +22 -0
- package/dist/src/config/worker-invocation-marker.d.mts +1 -0
- package/dist/src/config/worker-invocation-marker.mjs +2 -0
- package/dist/src/decision/ensemble-study/artifacts.js +7 -0
- package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
- package/dist/src/decision/ensemble-study/gates.js +78 -0
- package/dist/src/decision/ensemble-study/protocol.js +18 -21
- package/dist/src/decision/ensemble-study/score.js +3 -2
- package/dist/src/decision/ensemble-study/statistics.js +7 -26
- package/dist/src/decision/heldout/access.js +74 -0
- package/dist/src/decision/heldout/calibration.js +1 -0
- package/dist/src/decision/heldout/collector.js +8 -1
- package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
- package/dist/src/decision/sensitivity/comparative.js +18 -41
- package/dist/src/effects/verifiers/file.js +22 -5
- package/dist/src/extensions/claude-attribution.js +82 -0
- package/dist/src/extensions/claude-hooks-installer.js +133 -69
- package/dist/src/extensions/commands/daemon.js +109 -0
- package/dist/src/extensions/commands/definitions.js +5 -89
- package/dist/src/gates/evaluate.js +2 -358
- package/dist/src/gates/heldout.js +17 -7
- package/dist/src/gates/observations.js +363 -0
- package/dist/src/gates/pack-composition.js +270 -0
- package/dist/src/gates/pack-tightening.js +197 -0
- package/dist/src/gates/pack-validation.js +262 -0
- package/dist/src/gates/registry-error.js +5 -0
- package/dist/src/gates/registry.js +13 -685
- package/dist/src/lint/check-patterns.js +163 -0
- package/dist/src/lint/checks.js +268 -0
- package/dist/src/lint/reference-resolution.js +54 -0
- package/dist/src/lint/runner.js +3 -465
- package/dist/src/mcp/helpers.mjs +11 -1
- package/dist/src/mcp/json-document.mjs +29 -0
- package/dist/src/mcp/muse-native-config.mjs +1 -28
- package/dist/src/memory/project-registry.js +44 -4
- package/dist/src/mission-protocol/worker-review-gate.js +7 -0
- package/dist/src/models/worker-plan.js +36 -5
- package/dist/src/models/wrapper-deployment.js +25 -12
- package/dist/src/models/wrapper-enforcement.js +47 -7
- package/dist/src/network-analysis/research.js +2 -1
- package/dist/src/plugin/command-ownership.js +34 -0
- package/dist/src/plugin/skill-command-frontmatter.js +197 -0
- package/dist/src/plugin/skill-command-translator.js +6 -232
- package/dist/src/policy/hitl-check.js +14 -4
- package/dist/src/policy/hitl-consume.js +54 -0
- package/dist/src/policy/hitl-receipt.js +2 -0
- package/dist/src/policy/hitl.js +11 -3
- package/dist/src/providers/context-output-ownership.js +26 -0
- package/dist/src/providers/deployment-ownership.d.mts +19 -0
- package/dist/src/providers/deployment-ownership.mjs +226 -0
- package/dist/src/providers/deployment-removal.js +200 -0
- package/dist/src/providers/provider-context-contracts.js +162 -0
- package/dist/src/providers/provider-definition-schema.js +136 -0
- package/dist/src/providers/provider-definitions.js +8 -1298
- package/dist/src/providers/provider-seeds-1.js +360 -0
- package/dist/src/providers/provider-seeds-2.js +387 -0
- package/dist/src/providers/provider-seeds-3.js +262 -0
- package/dist/src/providers/removal-transaction.js +86 -0
- package/dist/src/providers/settings-document.d.mts +3 -0
- package/dist/src/providers/settings-document.mjs +47 -0
- package/dist/src/providers/settings-removal.js +190 -0
- package/dist/src/providers/skill-ownership.d.mts +19 -2
- package/dist/src/providers/skill-ownership.mjs +12 -4
- package/dist/src/providers/transformation-receipt-integration.js +15 -271
- package/dist/src/providers/transformation-receipt-outputs.js +99 -0
- package/dist/src/providers/transformation-receipt-source.js +194 -0
- package/dist/src/research/clients/arxiv.js +4 -30
- package/dist/src/research/clients/base.js +48 -22
- package/dist/src/research/identity.js +42 -4
- package/dist/src/research/query-cli.js +3 -87
- package/dist/src/research/query-options.js +87 -0
- package/dist/src/research/reference-match.js +105 -24
- package/dist/src/research/services/acquisition.js +9 -7
- package/dist/src/research/services/citation.js +5 -2
- package/dist/src/research/types.js +2 -0
- package/dist/src/rules/activation.mjs +15 -6
- package/dist/src/rules/core-startup.mjs +2 -2
- package/dist/src/serve/mission-conductor.js +52 -4
- package/dist/src/serve/mission-summary.js +56 -0
- package/dist/src/sessions/adapters/grok-build-native.js +23 -0
- package/dist/src/sessions/adapters/grok-build.js +14 -7
- package/dist/src/sessions/workspace-discovery.js +5 -5
- package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
- package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
- package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
- package/dist/src/smiths/context-pipeline/finalization.js +81 -51
- package/dist/src/smiths/context-pipeline/generator.js +10 -11
- package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
- package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
- package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
- package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
- package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
- package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
- package/dist/src/smiths/hook-bridge/index.js +9 -0
- package/package.json +13 -1
- package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +24 -675
- package/tools/agents/deploy-command-mirrors.mjs +229 -0
- package/tools/agents/deploy-options.mjs +258 -0
- package/tools/agents/deploy-support.mjs +165 -0
- package/tools/agents/providers/base-addon-discovery.mjs +139 -0
- package/tools/agents/providers/base-behaviors.mjs +168 -0
- package/tools/agents/providers/base-context.mjs +205 -0
- package/tools/agents/providers/base-contract.mjs +116 -0
- package/tools/agents/providers/base-files.mjs +252 -0
- package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
- package/tools/agents/providers/base-framework-discovery.mjs +309 -0
- package/tools/agents/providers/base-frontmatter.mjs +196 -0
- package/tools/agents/providers/base-inventory.mjs +269 -0
- package/tools/agents/providers/base-kernel-skills.mjs +354 -0
- package/tools/agents/providers/base-migrations.mjs +258 -0
- package/tools/agents/providers/base-models-platforms.mjs +273 -0
- package/tools/agents/providers/base-rule-index.mjs +450 -0
- package/tools/agents/providers/base-runtime.mjs +60 -0
- package/tools/agents/providers/base-skill-copy.mjs +273 -0
- package/tools/agents/providers/base.mjs +16 -3364
- package/tools/agents/providers/claude-post-deploy.mjs +20 -1
- package/tools/agents/providers/context-write.mjs +4 -0
- package/tools/agents/providers/hermes-startup.mjs +0 -5
- package/tools/agents/providers/muse.mjs +7 -2
- package/tools/agents/providers/pi.mjs +3 -1
- package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1144
- package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
- package/tools/agents/providers/rule-deployment-state.mjs +300 -0
- package/tools/agents/providers/rule-projection.mjs +3 -0
- package/tools/daemon/README.md +511 -0
- package/tools/daemon/adapters/base-adapter.mjs +84 -0
- package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
- package/tools/daemon/agent-supervisor.mjs +299 -0
- package/tools/daemon/automation-engine.mjs +310 -0
- package/tools/daemon/autonomous-engine.mjs +346 -0
- package/tools/daemon/behavior-loader.mjs +316 -0
- package/tools/daemon/behavior.mjs +174 -0
- package/tools/daemon/concierge/intent-router.mjs +401 -0
- package/tools/daemon/concierge/orchestrator.mjs +272 -0
- package/tools/daemon/concierge/response-translator.mjs +462 -0
- package/tools/daemon/config.mjs +377 -0
- package/tools/daemon/cron-scheduler.mjs +178 -0
- package/tools/daemon/daemon-main.mjs +1169 -0
- package/tools/daemon/event-router.mjs +84 -0
- package/tools/daemon/file-watcher.mjs +383 -0
- package/tools/daemon/index.mjs +1181 -0
- package/tools/daemon/init-profile.mjs +124 -0
- package/tools/daemon/ipc-client.mjs +197 -0
- package/tools/daemon/ipc-ops-handlers.mjs +236 -0
- package/tools/daemon/ipc-server.mjs +275 -0
- package/tools/daemon/maintenance-owner.mjs +79 -0
- package/tools/daemon/memory-manager.mjs +386 -0
- package/tools/daemon/message-router.mjs +194 -0
- package/tools/daemon/provider-watcher.mjs +585 -0
- package/tools/daemon/pty-adapter.mjs +420 -0
- package/tools/daemon/repl-chat.mjs +359 -0
- package/tools/daemon/resource-bounds.mjs +88 -0
- package/tools/daemon/sandbox-transport.mjs +295 -0
- package/tools/daemon/scheduled-task-runner.mjs +535 -0
- package/tools/daemon/task-store.mjs +450 -0
- package/tools/daemon/tmux-manager.mjs +324 -0
- package/tools/daemon/update-policy.mjs +517 -0
- package/tools/daemon/web-server.mjs +399 -0
- package/tools/daemon/web-ui/index.html +585 -0
- package/tools/daemon/web-ui/styles.css +156 -0
- package/tools/docker/Dockerfile.daemon +35 -0
- package/tools/docker/container-manager.mjs +291 -0
- package/tools/messaging/adapter-registry.mjs +230 -0
- package/tools/messaging/adapters/base.mjs +326 -0
- package/tools/messaging/adapters/discord.mjs +462 -0
- package/tools/messaging/adapters/slack.mjs +402 -0
- package/tools/messaging/adapters/telegram.mjs +552 -0
- package/tools/messaging/chat-handler.mjs +297 -0
- package/tools/messaging/command-router.mjs +269 -0
- package/tools/messaging/event-bus.mjs +199 -0
- package/tools/messaging/index.mjs +456 -0
- package/tools/messaging/message-formatter.mjs +320 -0
- package/tools/messaging/room-manager.mjs +277 -0
- package/tools/messaging/types.mjs +94 -0
- package/tools/providers/pi-bridge-policy.mjs +4 -0
- package/tools/ralph-external/daemon-supervisor.mjs +394 -0
- package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
- package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
- package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
- package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
- package/tools/ralph-external/lib/worker-termination.mjs +15 -8
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
- package/tools/ralph-external/session-launcher.mjs +7 -7
- package/tools/scripts/resource-preflight.mjs +3 -242
- package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task Store - JSON file persistence for agent tasks
|
|
3
|
+
*
|
|
4
|
+
* Tracks all spawned agent tasks with state, results, and history.
|
|
5
|
+
* Provides task queries and summary generation for session reattach.
|
|
6
|
+
*
|
|
7
|
+
* @implements @.aiwg/requirements/use-cases/UC-IPC-002.md
|
|
8
|
+
* @tests @test/unit/daemon/task-store.test.js
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
|
|
15
|
+
const TASK_STATES = ['queued', 'running', 'completed', 'failed', 'cancelled'];
|
|
16
|
+
|
|
17
|
+
export class TaskStore {
|
|
18
|
+
constructor(storePath, { now = Date.now } = {}) {
|
|
19
|
+
this.storePath = storePath;
|
|
20
|
+
this.now = now;
|
|
21
|
+
this.schedules = new Map();
|
|
22
|
+
this.persistenceError = null;
|
|
23
|
+
this.hasPersisted = false;
|
|
24
|
+
this.pendingOutputs = new Map();
|
|
25
|
+
this.tasks = new Map();
|
|
26
|
+
this.taskIdCounter = 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Initialize store - load existing tasks from disk
|
|
31
|
+
*/
|
|
32
|
+
async initialize() {
|
|
33
|
+
const dir = path.dirname(this.storePath);
|
|
34
|
+
if (!fs.existsSync(dir)) {
|
|
35
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
this._load();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
_load() {
|
|
42
|
+
if (!fs.existsSync(this.storePath)) {
|
|
43
|
+
if (!this.hasPersisted) return;
|
|
44
|
+
this.persistenceError = new Error(`TaskStore recovery required: persisted file disappeared: ${this.storePath}`);
|
|
45
|
+
throw this.persistenceError;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const data = JSON.parse(fs.readFileSync(this.storePath, 'utf8'));
|
|
49
|
+
if (!data || ![undefined, 1, 2].includes(data.version)
|
|
50
|
+
|| (data.tasks !== undefined && !Array.isArray(data.tasks))
|
|
51
|
+
|| (data.schedules !== undefined && !Array.isArray(data.schedules))
|
|
52
|
+
|| (data.version === 2 && (!Array.isArray(data.tasks) || !Array.isArray(data.schedules)))) {
|
|
53
|
+
throw new Error('Invalid task store schema');
|
|
54
|
+
}
|
|
55
|
+
const tasks = new Map();
|
|
56
|
+
const schedules = new Map();
|
|
57
|
+
for (const task of data.tasks || []) {
|
|
58
|
+
if (typeof task.id !== 'string' || tasks.has(task.id)) throw new Error('Invalid task ID');
|
|
59
|
+
if (this.pendingOutputs.has(task.id)) task.output = (task.output || '') + this.pendingOutputs.get(task.id);
|
|
60
|
+
tasks.set(task.id, task);
|
|
61
|
+
const numPart = parseInt(task.id.split('-').pop(), 10);
|
|
62
|
+
if (!isNaN(numPart)) this.taskIdCounter = Math.max(this.taskIdCounter, numPart + 1);
|
|
63
|
+
}
|
|
64
|
+
for (const record of data.schedules || []) {
|
|
65
|
+
if (!record.job?.id || schedules.has(record.job.id)) throw new Error('Invalid schedule ID');
|
|
66
|
+
const normalized = { timezone: 'UTC', nextRun: null, lastRun: null,
|
|
67
|
+
missedRunPolicy: 'skip', attemptCount: 0, lastReceipt: null, receipts: [],
|
|
68
|
+
state: 'idle', pendingFireTime: null, retryAt: null, ownerPid: null, workerPid: null, ...record };
|
|
69
|
+
if (!['idle', 'pending', 'running', 'retry', 'blocked'].includes(normalized.state)
|
|
70
|
+
|| !['skip', 'run-once'].includes(normalized.missedRunPolicy)
|
|
71
|
+
|| !Number.isInteger(normalized.attemptCount) || normalized.attemptCount < 0
|
|
72
|
+
|| !Array.isArray(normalized.receipts)
|
|
73
|
+
|| (normalized.state !== 'idle' && !normalized.pendingFireTime)) throw new Error('Invalid schedule state');
|
|
74
|
+
for (const pid of [normalized.ownerPid, normalized.workerPid]) {
|
|
75
|
+
if (pid !== null && (!Number.isSafeInteger(pid) || pid < 1)) throw new Error('Invalid owner PID');
|
|
76
|
+
}
|
|
77
|
+
for (const receipt of normalized.receipts) {
|
|
78
|
+
if (!receipt || receipt.jobId !== record.job.id || !Number.isFinite(Date.parse(receipt.fireTime))
|
|
79
|
+
|| !['ok', 'failed', 'skipped', 'deferred'].includes(receipt.state)) throw new Error('Invalid owner receipt');
|
|
80
|
+
}
|
|
81
|
+
for (const key of ['nextRun', 'lastRun', 'pendingFireTime', 'retryAt']) {
|
|
82
|
+
if (normalized[key] !== null && !Number.isFinite(Date.parse(normalized[key]))) {
|
|
83
|
+
throw new Error(`Invalid schedule ${key}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
schedules.set(record.job.id, normalized);
|
|
87
|
+
}
|
|
88
|
+
this.tasks = tasks;
|
|
89
|
+
this.schedules = schedules;
|
|
90
|
+
this.hasPersisted = true;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
this.persistenceError = new Error(`TaskStore recovery required at ${this.storePath}: ${error.message}. Preserve the file; restore a verified backup before retrying.`);
|
|
93
|
+
throw this.persistenceError;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Serialize short store transactions across daemon and manual writers.
|
|
98
|
+
* Never steal an existing lock: even a dead writer may have launched an owner.
|
|
99
|
+
*/
|
|
100
|
+
_locked(operation) {
|
|
101
|
+
if (this.persistenceError) throw this.persistenceError;
|
|
102
|
+
const lock = `${this.storePath}.lock`;
|
|
103
|
+
let fd;
|
|
104
|
+
try {
|
|
105
|
+
fd = fs.openSync(lock, 'wx', 0o600);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
throw new Error(`TaskStore lock-held/recovery-required: ${lock}: ${error.message}`);
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: new Date(this.now()).toISOString() }));
|
|
111
|
+
return operation();
|
|
112
|
+
} finally {
|
|
113
|
+
fs.closeSync(fd);
|
|
114
|
+
fs.unlinkSync(lock);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
getSchedule(id) { return structuredClone(this.schedules.get(id) || null); }
|
|
119
|
+
getSchedules() { return structuredClone([...this.schedules.values()]); }
|
|
120
|
+
|
|
121
|
+
/** All scheduled state changes reload under the same lock, then rename atomically. */
|
|
122
|
+
changeSchedule(id, change) {
|
|
123
|
+
return this._locked(() => {
|
|
124
|
+
this._load();
|
|
125
|
+
const before = this.getSchedule(id);
|
|
126
|
+
const record = change(structuredClone(before));
|
|
127
|
+
if (record) this.schedules.set(id, record);
|
|
128
|
+
if (JSON.stringify(before) !== JSON.stringify(record)) this._write();
|
|
129
|
+
return this.getSchedule(id);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
ensureSchedule(job, nextRun = null) {
|
|
134
|
+
if (job.retries !== undefined && (!Number.isInteger(job.retries) || job.retries < 0 || job.retries > 2)) {
|
|
135
|
+
throw new Error('retries must be 0, 1, or 2');
|
|
136
|
+
}
|
|
137
|
+
if (job.timeoutMs !== undefined && (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 1 || job.timeoutMs > 3600000)) {
|
|
138
|
+
throw new Error('timeoutMs must be between 1 and 3600000');
|
|
139
|
+
}
|
|
140
|
+
if (job.backoff && (!Number.isFinite(job.backoff.baseMs) || !Number.isFinite(job.backoff.maxMs)
|
|
141
|
+
|| job.backoff.baseMs < 1 || job.backoff.maxMs < job.backoff.baseMs || job.backoff.maxMs > 86400000)) {
|
|
142
|
+
throw new Error('backoff requires 1 <= baseMs <= maxMs <= 86400000');
|
|
143
|
+
}
|
|
144
|
+
return this.changeSchedule(job.id, current => {
|
|
145
|
+
const timezone = job.timezone || 'UTC';
|
|
146
|
+
new Intl.DateTimeFormat('en', { timeZone: timezone });
|
|
147
|
+
const missedRunPolicy = job.missedRunPolicy || 'skip';
|
|
148
|
+
if (!['skip', 'run-once'].includes(missedRunPolicy)) throw new Error('Invalid missedRunPolicy');
|
|
149
|
+
if (current) {
|
|
150
|
+
if (JSON.stringify(current.job) !== JSON.stringify(job)) {
|
|
151
|
+
if (current.state !== 'idle') throw new Error(`Schedule ${job.id} has unresolved work; retain its configuration`);
|
|
152
|
+
return { ...current, job, timezone, missedRunPolicy, nextRun };
|
|
153
|
+
}
|
|
154
|
+
if (!current.nextRun && current.state === 'idle' && nextRun) current.nextRun = nextRun;
|
|
155
|
+
return current;
|
|
156
|
+
}
|
|
157
|
+
return { job, timezone, missedRunPolicy, nextRun, lastRun: null,
|
|
158
|
+
state: 'idle', pendingFireTime: null, retryAt: null, attemptCount: 0,
|
|
159
|
+
ownerPid: null, workerPid: null, lastReceipt: null, receipts: [] };
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
recoverSchedules() {
|
|
164
|
+
for (const record of this.getSchedules()) {
|
|
165
|
+
if (record.state !== 'running') continue;
|
|
166
|
+
let alive = false;
|
|
167
|
+
if (record.ownerPid) {
|
|
168
|
+
try { process.kill(record.ownerPid, 0); alive = true; }
|
|
169
|
+
catch (error) { if (error.code !== 'ESRCH') alive = true; }
|
|
170
|
+
}
|
|
171
|
+
if (alive) continue;
|
|
172
|
+
this.changeSchedule(record.job.id, current => {
|
|
173
|
+
if (current.state !== 'running' || current.ownerPid !== record.ownerPid) return current;
|
|
174
|
+
const timestamp = new Date(this.now()).toISOString();
|
|
175
|
+
current.state = 'blocked';
|
|
176
|
+
current.lastReceipt = { jobId: current.job.id, fireTime: current.pendingFireTime,
|
|
177
|
+
state: 'deferred', reason: 'recovery-required', exitStatus: null,
|
|
178
|
+
summary: 'Interrupted owner run; inspect effects before acknowledgement',
|
|
179
|
+
startedAt: current.lastRun || timestamp, finishedAt: timestamp,
|
|
180
|
+
durationMs: Math.max(0, this.now() - Date.parse(current.lastRun || timestamp)),
|
|
181
|
+
attemptCount: current.attemptCount, terminal: false };
|
|
182
|
+
current.receipts.push(current.lastReceipt);
|
|
183
|
+
return current;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Explicit operator acknowledgement after inspecting owner effects. No automatic replay. */
|
|
189
|
+
resolveSchedule(id, summary) {
|
|
190
|
+
if (!summary?.trim()) throw new Error('Recovery requires an owner inspection summary');
|
|
191
|
+
return this.changeSchedule(id, record => {
|
|
192
|
+
if (!record || !['running', 'blocked'].includes(record.state)) throw new Error('No interrupted run to resolve');
|
|
193
|
+
for (const pid of [record.ownerPid, record.workerPid]) {
|
|
194
|
+
if (!pid) continue;
|
|
195
|
+
try { process.kill(pid, 0); throw new Error('Owner process may still be alive'); }
|
|
196
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
197
|
+
}
|
|
198
|
+
const finishedAt = new Date(this.now()).toISOString();
|
|
199
|
+
const receipt = { jobId: id, fireTime: record.pendingFireTime, state: 'skipped',
|
|
200
|
+
reason: 'operator-resolved', exitStatus: null, summary,
|
|
201
|
+
startedAt: record.lastRun || finishedAt, finishedAt,
|
|
202
|
+
durationMs: Math.max(0, this.now() - Date.parse(record.lastRun || finishedAt)),
|
|
203
|
+
attemptCount: record.attemptCount };
|
|
204
|
+
record.receipts.push(receipt);
|
|
205
|
+
return { ...record, state: 'idle', pendingFireTime: null, retryAt: null,
|
|
206
|
+
ownerPid: null, workerPid: null, lastReceipt: receipt };
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Create a new task
|
|
212
|
+
*/
|
|
213
|
+
createTask(options) {
|
|
214
|
+
const id = `task-${String(this.taskIdCounter++).padStart(4, '0')}`;
|
|
215
|
+
const task = {
|
|
216
|
+
id,
|
|
217
|
+
prompt: options.prompt,
|
|
218
|
+
agent: options.agent || null,
|
|
219
|
+
priority: options.priority || 0,
|
|
220
|
+
state: 'queued',
|
|
221
|
+
createdAt: new Date().toISOString(),
|
|
222
|
+
startedAt: null,
|
|
223
|
+
completedAt: null,
|
|
224
|
+
pid: null,
|
|
225
|
+
result: null,
|
|
226
|
+
error: null,
|
|
227
|
+
output: '',
|
|
228
|
+
metadata: options.metadata || {},
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
this.tasks.set(id, task);
|
|
232
|
+
this._persist();
|
|
233
|
+
return task;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Update task state
|
|
238
|
+
*/
|
|
239
|
+
updateTask(id, updates) {
|
|
240
|
+
const task = this.tasks.get(id);
|
|
241
|
+
if (!task) {
|
|
242
|
+
throw new Error(`Task not found: ${id}`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Validate state transitions
|
|
246
|
+
if (updates.state) {
|
|
247
|
+
if (!TASK_STATES.includes(updates.state)) {
|
|
248
|
+
throw new Error(`Invalid state: ${updates.state}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
Object.assign(task, updates);
|
|
253
|
+
this._persist();
|
|
254
|
+
return task;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Mark task as running
|
|
259
|
+
*/
|
|
260
|
+
startTask(id, pid) {
|
|
261
|
+
return this.updateTask(id, {
|
|
262
|
+
state: 'running',
|
|
263
|
+
startedAt: new Date().toISOString(),
|
|
264
|
+
pid,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Mark task as completed
|
|
270
|
+
*/
|
|
271
|
+
completeTask(id, result) {
|
|
272
|
+
return this.updateTask(id, {
|
|
273
|
+
state: 'completed',
|
|
274
|
+
completedAt: new Date().toISOString(),
|
|
275
|
+
result,
|
|
276
|
+
pid: null,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Mark task as failed
|
|
282
|
+
*/
|
|
283
|
+
failTask(id, error) {
|
|
284
|
+
return this.updateTask(id, {
|
|
285
|
+
state: 'failed',
|
|
286
|
+
completedAt: new Date().toISOString(),
|
|
287
|
+
error: typeof error === 'string' ? error : error.message,
|
|
288
|
+
pid: null,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Mark task as cancelled
|
|
294
|
+
*/
|
|
295
|
+
cancelTask(id) {
|
|
296
|
+
return this.updateTask(id, {
|
|
297
|
+
state: 'cancelled',
|
|
298
|
+
completedAt: new Date().toISOString(),
|
|
299
|
+
pid: null,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Append output to a task
|
|
305
|
+
*/
|
|
306
|
+
appendOutput(id, chunk) {
|
|
307
|
+
const task = this.tasks.get(id);
|
|
308
|
+
if (task) {
|
|
309
|
+
task.output += chunk;
|
|
310
|
+
this.pendingOutputs.set(id, (this.pendingOutputs.get(id) || '') + chunk);
|
|
311
|
+
// Don't persist on every chunk - too expensive
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Get a task by ID
|
|
317
|
+
*/
|
|
318
|
+
getTask(id) {
|
|
319
|
+
return this.tasks.get(id) || null;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Get all tasks, optionally filtered by state
|
|
324
|
+
*/
|
|
325
|
+
getTasks(filter = {}) {
|
|
326
|
+
let result = Array.from(this.tasks.values());
|
|
327
|
+
|
|
328
|
+
if (filter.state) {
|
|
329
|
+
result = result.filter(t => t.state === filter.state);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (filter.agent) {
|
|
333
|
+
result = result.filter(t => t.agent === filter.agent);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Sort by creation time, newest first
|
|
337
|
+
result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
|
|
338
|
+
|
|
339
|
+
if (filter.limit) {
|
|
340
|
+
result = result.slice(0, filter.limit);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return result;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Get summary statistics
|
|
348
|
+
*/
|
|
349
|
+
getStats() {
|
|
350
|
+
const tasks = Array.from(this.tasks.values());
|
|
351
|
+
return {
|
|
352
|
+
total: tasks.length,
|
|
353
|
+
queued: tasks.filter(t => t.state === 'queued').length,
|
|
354
|
+
running: tasks.filter(t => t.state === 'running').length,
|
|
355
|
+
completed: tasks.filter(t => t.state === 'completed').length,
|
|
356
|
+
failed: tasks.filter(t => t.state === 'failed').length,
|
|
357
|
+
cancelled: tasks.filter(t => t.state === 'cancelled').length,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Generate a summary for session reattach
|
|
363
|
+
*/
|
|
364
|
+
getSummary() {
|
|
365
|
+
const stats = this.getStats();
|
|
366
|
+
const running = this.getTasks({ state: 'running' });
|
|
367
|
+
const recent = this.getTasks({ limit: 5 });
|
|
368
|
+
|
|
369
|
+
return {
|
|
370
|
+
stats,
|
|
371
|
+
running: running.map(t => ({
|
|
372
|
+
id: t.id,
|
|
373
|
+
prompt: t.prompt.slice(0, 80),
|
|
374
|
+
agent: t.agent,
|
|
375
|
+
startedAt: t.startedAt,
|
|
376
|
+
})),
|
|
377
|
+
recent: recent.map(t => ({
|
|
378
|
+
id: t.id,
|
|
379
|
+
prompt: t.prompt.slice(0, 80),
|
|
380
|
+
state: t.state,
|
|
381
|
+
completedAt: t.completedAt,
|
|
382
|
+
})),
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Clean up old completed/failed tasks
|
|
388
|
+
*/
|
|
389
|
+
cleanup(maxAge = 7 * 24 * 60 * 60 * 1000) {
|
|
390
|
+
const cutoff = Date.now() - maxAge;
|
|
391
|
+
let removed = 0;
|
|
392
|
+
|
|
393
|
+
for (const [id, task] of this.tasks) {
|
|
394
|
+
if (
|
|
395
|
+
(task.state === 'completed' || task.state === 'failed' || task.state === 'cancelled') &&
|
|
396
|
+
task.completedAt &&
|
|
397
|
+
new Date(task.completedAt).getTime() < cutoff
|
|
398
|
+
) {
|
|
399
|
+
this.tasks.delete(id);
|
|
400
|
+
removed++;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (removed > 0) {
|
|
405
|
+
this._persist();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return removed;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Get count of tasks
|
|
413
|
+
*/
|
|
414
|
+
get size() {
|
|
415
|
+
return this.tasks.size;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// --- Private methods ---
|
|
419
|
+
|
|
420
|
+
_persist() {
|
|
421
|
+
return this._locked(() => {
|
|
422
|
+
// Agent-task writes must retain receipts written by a manual process.
|
|
423
|
+
const tasks = this.tasks;
|
|
424
|
+
this._load();
|
|
425
|
+
this.tasks = tasks;
|
|
426
|
+
this._write();
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
_write() {
|
|
431
|
+
const data = { version: 2, updatedAt: new Date(this.now()).toISOString(),
|
|
432
|
+
tasks: [...this.tasks.values()], schedules: [...this.schedules.values()] };
|
|
433
|
+
const temporary = `${this.storePath}.${randomUUID()}.tmp`;
|
|
434
|
+
try {
|
|
435
|
+
fs.writeFileSync(temporary, JSON.stringify(data, null, 2), { flag: 'wx', mode: 0o600 });
|
|
436
|
+
const fd = fs.openSync(temporary, 'r');
|
|
437
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
438
|
+
fs.renameSync(temporary, this.storePath);
|
|
439
|
+
const directory = fs.openSync(path.dirname(this.storePath), 'r');
|
|
440
|
+
try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
|
|
441
|
+
this.hasPersisted = true;
|
|
442
|
+
this.pendingOutputs.clear();
|
|
443
|
+
} catch (error) {
|
|
444
|
+
this.persistenceError = new Error(`TaskStore: Failed to persist; recovery required: ${error.message}`);
|
|
445
|
+
throw this.persistenceError;
|
|
446
|
+
} finally {
|
|
447
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|