@chroxy/server 0.10.0 → 0.11.10
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/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import { createHash, randomUUID } from 'crypto'
|
|
3
|
+
import { dirname, resolve } from 'path'
|
|
4
|
+
import { writeFileRestricted } from './platform.js'
|
|
5
|
+
import { createLogger } from './logger.js'
|
|
6
|
+
import { computeNextRun, parseCron, MIN_INTERVAL_MS } from './schedule-parser.js'
|
|
7
|
+
import { ALLOWED_PERMISSION_MODE_IDS } from './handler-utils.js'
|
|
8
|
+
|
|
9
|
+
const log = createLogger('scheduled-task-store')
|
|
10
|
+
|
|
11
|
+
// Current on-disk schema version. Bumped only on a breaking shape change so a
|
|
12
|
+
// future loader can migrate (or discard) an older file rather than silently
|
|
13
|
+
// mis-reading it. Mirrors permission-rule-store.js's version gate.
|
|
14
|
+
const STORE_VERSION = 1
|
|
15
|
+
|
|
16
|
+
// Hard cap on persisted tasks. A normal daemon has a handful of standing
|
|
17
|
+
// schedules; this only bites a hand-edited or runaway file. Extra entries beyond
|
|
18
|
+
// the cap are dropped on load (oldest kept) and refused on add.
|
|
19
|
+
const MAX_TASKS = 500
|
|
20
|
+
|
|
21
|
+
/** Exported so the wire-cap parity test can pin the snapshot's `tasks` bound to it. */
|
|
22
|
+
export const MAX_STORED_TASKS = MAX_TASKS
|
|
23
|
+
|
|
24
|
+
const CADENCE_KINDS = new Set(['once', 'interval', 'cron'])
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* #7051 — the wire cap on `cadence.cron.expression`, mirroring
|
|
28
|
+
* `ScheduledTaskCadenceCronSchema` in @chroxy/protocol
|
|
29
|
+
* (schemas/server/scheduler.ts). Kept as a local constant rather than imported
|
|
30
|
+
* so this module stays dependency-light, and pinned by a test that safeParses
|
|
31
|
+
* the REAL schema at the boundary — a comment cannot stop the two drifting, a
|
|
32
|
+
* failing test can.
|
|
33
|
+
*
|
|
34
|
+
* Rejected, NOT clamped. `projectTask` truncates the other capped strings
|
|
35
|
+
* (name, provider, model, ...) because a truncated label is merely ugly.
|
|
36
|
+
* Truncating a cron expression silently CHANGES THE SCHEDULE — `0,30 * * * *`
|
|
37
|
+
* cut to `0,3` is a different, still-valid schedule that fires at the wrong
|
|
38
|
+
* time forever. Refusing at the store boundary is the only safe option, the
|
|
39
|
+
* same reasoning as the unrepresentable-epoch check below.
|
|
40
|
+
*
|
|
41
|
+
* The blast radius is why this matters at all: the dashboard safeParses the
|
|
42
|
+
* WHOLE `scheduled_tasks` snapshot, so ONE over-cap task makes the panel render
|
|
43
|
+
* zero tasks (plus "the list below may be out of date") while N tasks are armed
|
|
44
|
+
* and firing — the store-legal / wire-illegal asymmetry the clamping in
|
|
45
|
+
* `scheduler-handlers.js` was added to eliminate.
|
|
46
|
+
*/
|
|
47
|
+
const MAX_CRON_EXPRESSION_LENGTH = 256
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* #7074 — the wire cap on a task `id`, mirroring `ScheduledTaskSchema.id`
|
|
51
|
+
* (max 256) in @chroxy/protocol. Pinned by a test that safeParses the REAL
|
|
52
|
+
* schema at the boundary, so the two cannot drift silently.
|
|
53
|
+
*
|
|
54
|
+
* Rejected, NOT clamped — and unlike the other capped strings the reason is not
|
|
55
|
+
* cosmetic: `id` is the MUTATION KEY, so a truncated id would make
|
|
56
|
+
* pause/update/delete address the wrong record, or nothing. `projectTask` in
|
|
57
|
+
* scheduler-handlers.js deliberately leaves `id` unclamped for exactly this
|
|
58
|
+
* reason, which leaves refusing at the store boundary as the only safe option.
|
|
59
|
+
*
|
|
60
|
+
* Generated ids are uuids (36 chars), and no writer supplies one: the WS path
|
|
61
|
+
* cannot (`ScheduledTaskInputSchema` has no `id` field and `z.object` strips
|
|
62
|
+
* unknown keys, so `ws-server.js` dispatches a payload without it) and the CLI
|
|
63
|
+
* omits it. The reachable path is therefore a hand-edited registry file.
|
|
64
|
+
*
|
|
65
|
+
* Since #7050 a refused entry is PRESERVED on disk rather than erased, so
|
|
66
|
+
* refusing here does not destroy the operator's task. An over-cap id is
|
|
67
|
+
* unaddressable at the wire (`ScheduledTaskActionSchema.taskId` is capped too)
|
|
68
|
+
* and absent from `store.list()`, so since #7079 the operator reaches such an
|
|
69
|
+
* entry through an opaque server-derived HANDLE (`listUnreadable()` /
|
|
70
|
+
* `discardUnreadable()`), not through its id; hand-editing the file remains a
|
|
71
|
+
* supported recovery path (#7077) — see the class docblock.
|
|
72
|
+
*/
|
|
73
|
+
const MAX_WIRE_ID_LENGTH = 256
|
|
74
|
+
|
|
75
|
+
// Audited alongside #7074: every OTHER capped field on `ScheduledTaskSchema` is
|
|
76
|
+
// already clamped before send by `projectTask`/`projectTarget`/`projectLastRun`
|
|
77
|
+
// in handlers/scheduler-handlers.js (name, target.*, lastRun.*, providerRefusal,
|
|
78
|
+
// effectiveProvider, effectivePermissionMode), and `prompt` is `z.string()` with
|
|
79
|
+
// NO wire cap, so it is symmetric and has nothing to violate. If a cap is ever
|
|
80
|
+
// added to `prompt` on the wire, it needs a bound HERE too — otherwise it
|
|
81
|
+
// becomes the next #7051.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Throw unless `id` fits the wire cap. Shared by `add()` and
|
|
86
|
+
* `_normalizeStoredTask()` so the client path and the load path cannot diverge
|
|
87
|
+
* — the split that made #7051 reachable through the file after add() was fixed.
|
|
88
|
+
* @param {string} id - an already-trimmed, non-empty id
|
|
89
|
+
*/
|
|
90
|
+
function requireIdWithinWireCap(id) {
|
|
91
|
+
if (id.length > MAX_WIRE_ID_LENGTH) {
|
|
92
|
+
throw new ScheduledTaskValidationError(
|
|
93
|
+
`task id must be <= ${MAX_WIRE_ID_LENGTH} characters (got ${id.length}) — ` +
|
|
94
|
+
'a longer id cannot be carried on the wire and would make the whole scheduled-tasks snapshot unparseable',
|
|
95
|
+
'id',
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The largest absolute epoch-ms a JS `Date` can represent (±8.64e15, i.e. ±100M
|
|
102
|
+
* days around the epoch — year ±275760). Beyond it `new Date(ms)` is an Invalid
|
|
103
|
+
* Date and `.toISOString()` THROWS `RangeError`.
|
|
104
|
+
*
|
|
105
|
+
* Checking only `Number.isFinite` let such a value be stored and served: it then
|
|
106
|
+
* crashed the dashboard's scheduled-tasks panel during render (#6871 review C3).
|
|
107
|
+
* Reachable without hand-editing the registry — a µs/ns epoch typo (`1.795e18`,
|
|
108
|
+
* a plausible unit mix-up) is finite. Rejecting it at the store boundary keeps
|
|
109
|
+
* an unrenderable instant out of the registry in the first place; every real
|
|
110
|
+
* schedule is many orders of magnitude below this bound, so nothing legitimate
|
|
111
|
+
* is refused.
|
|
112
|
+
*/
|
|
113
|
+
const MAX_EPOCH_MS = 8.64e15
|
|
114
|
+
// `refused` (#6997 review) = the engine declined to start the run at all — an
|
|
115
|
+
// unsupported hook-routed provider, a cwd outside the allowlist, or a permission
|
|
116
|
+
// mode it could not verify. Distinct from `error` (the run happened and failed)
|
|
117
|
+
// and `skipped` (the slot passed) so a reader can tell an operator that NOTHING
|
|
118
|
+
// ran and that the task definition needs fixing.
|
|
119
|
+
// `interrupted` (#7038) = the run was deliberately STOPPED (an operator Stop, an
|
|
120
|
+
// orchestration cancel) rather than failing. Distinct from `error` for the same
|
|
121
|
+
// reason `refused` is: nothing is broken, so an operator must not have to read
|
|
122
|
+
// the free-text message to tell an intentional interrupt from a crash.
|
|
123
|
+
//
|
|
124
|
+
// This set is a HARD GATE, not documentation: normalizeLastRun() throws on
|
|
125
|
+
// anything outside it, and the engine turns that throw into a QUARANTINE
|
|
126
|
+
// (scheduler.js `_recordRun` — "its run outcome could not be recorded"). An
|
|
127
|
+
// engine status missing here therefore does not just fail to persist; it stops
|
|
128
|
+
// the task firing for the rest of the process.
|
|
129
|
+
const LAST_RUN_STATUSES = new Set(['success', 'error', 'skipped', 'timeout', 'refused', 'interrupted'])
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Error thrown when a task submitted to add()/update() is malformed. Carries the
|
|
133
|
+
* offending field name so a caller (CLI #6868 / dashboard #6871) can surface a
|
|
134
|
+
* precise validation message. Corrupt entries read off DISK are silently dropped
|
|
135
|
+
* instead (fail-open), never thrown — only programmatic input is strict.
|
|
136
|
+
*/
|
|
137
|
+
export class ScheduledTaskValidationError extends Error {
|
|
138
|
+
constructor(message, field) {
|
|
139
|
+
super(message)
|
|
140
|
+
this.name = 'ScheduledTaskValidationError'
|
|
141
|
+
this.field = field
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Trim and validate an optional string target field. Returns the trimmed string,
|
|
147
|
+
* or undefined when absent/empty. Throws on a non-string.
|
|
148
|
+
*/
|
|
149
|
+
function optionalString(value, field) {
|
|
150
|
+
if (value === undefined || value === null) return undefined
|
|
151
|
+
if (typeof value !== 'string') throw new ScheduledTaskValidationError(`${field} must be a string`, field)
|
|
152
|
+
const trimmed = value.trim()
|
|
153
|
+
return trimmed.length > 0 ? trimmed : undefined
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* True only for a plain `{}` object — rejects arrays, class instances, and
|
|
158
|
+
* primitives. `typeof [] === 'object'` alone would let an array masquerade as a
|
|
159
|
+
* valid target, so callers that want a `{ provider, ... }` bag must use this.
|
|
160
|
+
*/
|
|
161
|
+
function isPlainObject(value) {
|
|
162
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
163
|
+
const proto = Object.getPrototypeOf(value)
|
|
164
|
+
return proto === Object.prototype || proto === null
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Normalize + validate a target session config `{ provider, model, cwd,
|
|
169
|
+
* permissionMode }`. All fields optional; unknown keys are dropped. `target`
|
|
170
|
+
* must be a plain object (an array or other non-plain value is rejected, since
|
|
171
|
+
* `typeof [] === 'object'`), and `permissionMode`, when present, must be one of
|
|
172
|
+
* the server's supported mode IDs ({@link ALLOWED_PERMISSION_MODE_IDS}). Returns
|
|
173
|
+
* a plain object (possibly empty).
|
|
174
|
+
*/
|
|
175
|
+
function normalizeTarget(target) {
|
|
176
|
+
if (target === undefined || target === null) return {}
|
|
177
|
+
if (!isPlainObject(target)) throw new ScheduledTaskValidationError('target must be a plain object', 'target')
|
|
178
|
+
const out = {}
|
|
179
|
+
const provider = optionalString(target.provider, 'target.provider')
|
|
180
|
+
const model = optionalString(target.model, 'target.model')
|
|
181
|
+
const cwd = optionalString(target.cwd, 'target.cwd')
|
|
182
|
+
const permissionMode = optionalString(target.permissionMode, 'target.permissionMode')
|
|
183
|
+
if (permissionMode !== undefined && !ALLOWED_PERMISSION_MODE_IDS.has(permissionMode)) {
|
|
184
|
+
throw new ScheduledTaskValidationError(
|
|
185
|
+
`target.permissionMode must be one of ${[...ALLOWED_PERMISSION_MODE_IDS].join(', ')}`,
|
|
186
|
+
'target.permissionMode',
|
|
187
|
+
)
|
|
188
|
+
}
|
|
189
|
+
if (provider !== undefined) out.provider = provider
|
|
190
|
+
if (model !== undefined) out.model = model
|
|
191
|
+
if (cwd !== undefined) out.cwd = cwd
|
|
192
|
+
if (permissionMode !== undefined) out.permissionMode = permissionMode
|
|
193
|
+
return out
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Normalize + validate a cadence into its canonical stored form. Throws
|
|
198
|
+
* {@link ScheduledTaskValidationError} on anything malformed.
|
|
199
|
+
* @returns {{kind:'once',at:number} | {kind:'interval',everyMs:number,anchor?:number} | {kind:'cron',expression:string}}
|
|
200
|
+
*/
|
|
201
|
+
function normalizeCadence(cadence) {
|
|
202
|
+
if (!cadence || typeof cadence !== 'object') {
|
|
203
|
+
throw new ScheduledTaskValidationError('cadence is required', 'cadence')
|
|
204
|
+
}
|
|
205
|
+
if (!CADENCE_KINDS.has(cadence.kind)) {
|
|
206
|
+
throw new ScheduledTaskValidationError(`cadence.kind must be one of ${[...CADENCE_KINDS].join(', ')}`, 'cadence.kind')
|
|
207
|
+
}
|
|
208
|
+
switch (cadence.kind) {
|
|
209
|
+
case 'once': {
|
|
210
|
+
if (!Number.isFinite(cadence.at)) {
|
|
211
|
+
throw new ScheduledTaskValidationError('once cadence requires a numeric `at` (epoch ms)', 'cadence.at')
|
|
212
|
+
}
|
|
213
|
+
if (Math.abs(cadence.at) > MAX_EPOCH_MS) {
|
|
214
|
+
throw new ScheduledTaskValidationError(
|
|
215
|
+
`once cadence \`at\` must be a representable epoch-ms instant (|at| <= ${MAX_EPOCH_MS}); got ${cadence.at} — check for a microsecond/nanosecond timestamp`,
|
|
216
|
+
'cadence.at',
|
|
217
|
+
)
|
|
218
|
+
}
|
|
219
|
+
return { kind: 'once', at: cadence.at }
|
|
220
|
+
}
|
|
221
|
+
case 'interval': {
|
|
222
|
+
if (!Number.isFinite(cadence.everyMs) || cadence.everyMs < MIN_INTERVAL_MS) {
|
|
223
|
+
throw new ScheduledTaskValidationError(`interval cadence requires everyMs >= ${MIN_INTERVAL_MS}`, 'cadence.everyMs')
|
|
224
|
+
}
|
|
225
|
+
const out = { kind: 'interval', everyMs: Math.floor(cadence.everyMs) }
|
|
226
|
+
if (cadence.anchor !== undefined) {
|
|
227
|
+
if (!Number.isFinite(cadence.anchor)) {
|
|
228
|
+
throw new ScheduledTaskValidationError('interval cadence anchor must be numeric (epoch ms)', 'cadence.anchor')
|
|
229
|
+
}
|
|
230
|
+
// Same representable-instant bound as `once.at` — an anchor feeds
|
|
231
|
+
// nextRun, which the panel renders as a date.
|
|
232
|
+
if (Math.abs(cadence.anchor) > MAX_EPOCH_MS) {
|
|
233
|
+
throw new ScheduledTaskValidationError(
|
|
234
|
+
`interval cadence anchor must be a representable epoch-ms instant (|anchor| <= ${MAX_EPOCH_MS}); got ${cadence.anchor}`,
|
|
235
|
+
'cadence.anchor',
|
|
236
|
+
)
|
|
237
|
+
}
|
|
238
|
+
out.anchor = cadence.anchor
|
|
239
|
+
}
|
|
240
|
+
return out
|
|
241
|
+
}
|
|
242
|
+
case 'cron': {
|
|
243
|
+
if (typeof cadence.expression !== 'string') {
|
|
244
|
+
throw new ScheduledTaskValidationError('cron cadence requires a string `expression`', 'cadence.expression')
|
|
245
|
+
}
|
|
246
|
+
// Measure the TRIMMED form, because that is what gets stored and sent
|
|
247
|
+
// (see the return below) — padding must not count against the cap, and
|
|
248
|
+
// must not sneak past it either.
|
|
249
|
+
const expression = cadence.expression.trim()
|
|
250
|
+
// #7051: length BEFORE parse — a 300-char expression can be perfectly valid
|
|
251
|
+
// cron, so parseCron will happily accept a value the wire cannot carry.
|
|
252
|
+
if (expression.length > MAX_CRON_EXPRESSION_LENGTH) {
|
|
253
|
+
throw new ScheduledTaskValidationError(
|
|
254
|
+
`cron expression must be <= ${MAX_CRON_EXPRESSION_LENGTH} characters (got ${expression.length}) — ` +
|
|
255
|
+
'longer expressions cannot be carried on the wire and would make the whole scheduled-tasks snapshot unparseable',
|
|
256
|
+
'cadence.expression',
|
|
257
|
+
)
|
|
258
|
+
}
|
|
259
|
+
// parseCron throws CronParseError on a malformed field — re-surface it as a
|
|
260
|
+
// validation error so callers get one error type off add()/update().
|
|
261
|
+
try {
|
|
262
|
+
parseCron(expression)
|
|
263
|
+
} catch (err) {
|
|
264
|
+
throw new ScheduledTaskValidationError(`invalid cron expression: ${err.message}`, 'cadence.expression')
|
|
265
|
+
}
|
|
266
|
+
return { kind: 'cron', expression }
|
|
267
|
+
}
|
|
268
|
+
default:
|
|
269
|
+
// Unreachable — CADENCE_KINDS gates kind above.
|
|
270
|
+
throw new ScheduledTaskValidationError('unsupported cadence', 'cadence.kind')
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Normalize + validate a `lastRun` result stub. Optional; when present must be
|
|
276
|
+
* `{ at, status[, sessionId, error] }`. The engine (#6865) fills this after a
|
|
277
|
+
* run — the foundation just stores it. Throws on a malformed shape.
|
|
278
|
+
*/
|
|
279
|
+
function normalizeLastRun(lastRun) {
|
|
280
|
+
if (lastRun === undefined || lastRun === null) return null
|
|
281
|
+
if (typeof lastRun !== 'object') throw new ScheduledTaskValidationError('lastRun must be an object', 'lastRun')
|
|
282
|
+
if (!Number.isFinite(lastRun.at)) throw new ScheduledTaskValidationError('lastRun.at must be numeric (epoch ms)', 'lastRun.at')
|
|
283
|
+
if (!LAST_RUN_STATUSES.has(lastRun.status)) {
|
|
284
|
+
throw new ScheduledTaskValidationError(`lastRun.status must be one of ${[...LAST_RUN_STATUSES].join(', ')}`, 'lastRun.status')
|
|
285
|
+
}
|
|
286
|
+
const out = { at: lastRun.at, status: lastRun.status }
|
|
287
|
+
const sessionId = optionalString(lastRun.sessionId, 'lastRun.sessionId')
|
|
288
|
+
const error = optionalString(lastRun.error, 'lastRun.error')
|
|
289
|
+
if (sessionId !== undefined) out.sessionId = sessionId
|
|
290
|
+
if (error !== undefined) out.error = error
|
|
291
|
+
return out
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Canonical JSON: object keys sorted recursively, so two structurally-equal
|
|
296
|
+
* values serialise identically regardless of key order. Used for two things that
|
|
297
|
+
* must agree on "is this the same raw entry?": reconciling a preserved entry
|
|
298
|
+
* against the file (#7077) and deriving its wire handle (#7079). A raw entry may
|
|
299
|
+
* be any JSON value, not only an object — a hand-edited file can hold anything.
|
|
300
|
+
*/
|
|
301
|
+
function canonicalJson(value) {
|
|
302
|
+
// ITERATIVE on purpose. A hand-edited registry can hold an entry nested
|
|
303
|
+
// thousands of levels deep; a recursive walk threw RangeError out of load() and
|
|
304
|
+
// crashed the daemon at boot, where the pre-#7077 loader read the same file
|
|
305
|
+
// fine. Work items are `[isLiteral, payload]` so a value that happens to look
|
|
306
|
+
// like a literal can never be mistaken for one.
|
|
307
|
+
const out = []
|
|
308
|
+
const work = [[false, value]]
|
|
309
|
+
while (work.length > 0) {
|
|
310
|
+
const [isLiteral, item] = work.pop()
|
|
311
|
+
if (isLiteral) { out.push(item); continue }
|
|
312
|
+
if (item === null || typeof item !== 'object') { out.push(String(JSON.stringify(item))); continue }
|
|
313
|
+
if (Array.isArray(item)) {
|
|
314
|
+
out.push('[')
|
|
315
|
+
work.push([true, ']'])
|
|
316
|
+
for (let i = item.length - 1; i >= 0; i--) {
|
|
317
|
+
work.push([false, item[i]])
|
|
318
|
+
if (i > 0) work.push([true, ','])
|
|
319
|
+
}
|
|
320
|
+
continue
|
|
321
|
+
}
|
|
322
|
+
const keys = Object.keys(item).sort()
|
|
323
|
+
out.push('{')
|
|
324
|
+
work.push([true, '}'])
|
|
325
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
326
|
+
work.push([false, item[keys[i]]])
|
|
327
|
+
work.push([true, `${JSON.stringify(keys[i])}:`])
|
|
328
|
+
if (i > 0) work.push([true, ','])
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return out.join('')
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* A persist that did not reach disk, for the callers that must report it
|
|
336
|
+
* (`remove()`, `discardUnreadable()`). Deliberately generic: the cause (a path,
|
|
337
|
+
* an errno) is logged server-side, not sent to a client.
|
|
338
|
+
*/
|
|
339
|
+
function persistFailure() {
|
|
340
|
+
return new Error('Could not write the scheduled-task registry; nothing was changed')
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* A preserved entry that is a well-formed task whose id a live task already
|
|
345
|
+
* owns. `duplicateOf` marks it so deleting that live task drops it too: left
|
|
346
|
+
* behind, a restart would load it as the task the operator just deleted.
|
|
347
|
+
*/
|
|
348
|
+
function duplicateOfLive(entry, id) {
|
|
349
|
+
return {
|
|
350
|
+
raw: entry,
|
|
351
|
+
id: usableId(entry),
|
|
352
|
+
duplicateOf: id,
|
|
353
|
+
reason: `duplicates the id of a live task (${id}) — edit that task through the panel, or discard this entry`,
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Multiset (canonical JSON -> count) of a list of raw entries. */
|
|
358
|
+
function countCanonical(entries) {
|
|
359
|
+
const counts = new Map()
|
|
360
|
+
for (const entry of entries) {
|
|
361
|
+
const key = canonicalJson(entry)
|
|
362
|
+
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
363
|
+
}
|
|
364
|
+
return counts
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The trimmed string id of a raw entry, or null when it has no usable one. */
|
|
368
|
+
function usableId(raw) {
|
|
369
|
+
return typeof raw?.id === 'string' && raw.id.trim().length > 0 ? raw.id.trim() : null
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* #7079 — the opaque wire handle of an unreadable entry: the first 16 hex chars
|
|
374
|
+
* (64 bits) of the sha256 of its canonical JSON. It is the ONLY way a client
|
|
375
|
+
* names a preserved entry, because the entry's own id may be absent, a non-string,
|
|
376
|
+
* or longer than the wire's 256-char task-id cap (which is correct and must not
|
|
377
|
+
* be widened to carry a malformed record). Derived server-side from content, so a
|
|
378
|
+
* client can neither forge a handle for a live task nor address anything the
|
|
379
|
+
* server did not itself derive. Never contains raw contents.
|
|
380
|
+
*/
|
|
381
|
+
function handleOf(canonical) {
|
|
382
|
+
return createHash('sha256').update(canonical).digest('hex').slice(0, 16)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* The scheduled-task data model (#6862). A standing, persisted schedule for a
|
|
387
|
+
* future/recurring agent run — explicitly SEPARATE from live session state and
|
|
388
|
+
* from `ScheduleWakeup` (transcript-tasks.js), which is an intra-session,
|
|
389
|
+
* single-shot self-resume. No firing here; that is the engine slice (#6865).
|
|
390
|
+
*
|
|
391
|
+
* Stored shape:
|
|
392
|
+
* {
|
|
393
|
+
* id: string, // stable uuid
|
|
394
|
+
* name: string | null, // optional human label
|
|
395
|
+
* enabled: boolean, // paused === !enabled
|
|
396
|
+
* prompt: string, // instructions the run executes
|
|
397
|
+
* target: { // session config the run is created with
|
|
398
|
+
* provider?, model?, cwd?, permissionMode?
|
|
399
|
+
* },
|
|
400
|
+
* cadence: // one-time vs recurring
|
|
401
|
+
* | { kind: 'once', at }
|
|
402
|
+
* | { kind: 'interval', everyMs, anchor? }
|
|
403
|
+
* | { kind: 'cron', expression },
|
|
404
|
+
* nextRun: number | null, // COMPUTED (never fired here), for display
|
|
405
|
+
* lastRun: { at, status, sessionId?, error? } | null, // engine fills this
|
|
406
|
+
* createdAt: number,
|
|
407
|
+
* updatedAt: number,
|
|
408
|
+
* }
|
|
409
|
+
*
|
|
410
|
+
* Persistence mirrors permission-rule-store.js exactly: a single JSON file (a
|
|
411
|
+
* sibling of session-state.json, e.g. ~/.chroxy/scheduled-tasks.json) written
|
|
412
|
+
* atomically (temp + rename via writeFileRestricted, mode 0600), version-gated,
|
|
413
|
+
* and fail-open-empty on a corrupt/unknown-version file. Loaded once on daemon
|
|
414
|
+
* start; keyed by task id.
|
|
415
|
+
*
|
|
416
|
+
* ── Unreadable (load-refused) entries (#7050, #7077, #7079, #8523) ────────────
|
|
417
|
+
* An entry the loader cannot read is never served as a task and never erased: it
|
|
418
|
+
* is kept verbatim and written back by every persist. Two ways to resolve one:
|
|
419
|
+
*
|
|
420
|
+
* 1. DISCARD (preferred) — the dashboard shows each entry with the reason it
|
|
421
|
+
* was refused and a Discard control; `discardUnreadable(handle)` removes it
|
|
422
|
+
* through the store, atomically, with no file editing.
|
|
423
|
+
* 2. HAND-EDIT — supported WHILE THE DAEMON RUNS.
|
|
424
|
+
*
|
|
425
|
+
* ── The hand-editing contract: the daemon only ever rewrites entries it wrote ──
|
|
426
|
+
* The store remembers exactly what it last wrote to the file (`_lastWritten`, a
|
|
427
|
+
* multiset of the canonical JSON of every entry, seeded from the raw entries as
|
|
428
|
+
* read at `load()`, and replaced only after an atomic write SUCCEEDS). At every
|
|
429
|
+
* persist it re-reads the file, and anything on disk that is not in that multiset
|
|
430
|
+
* is the OPERATOR's — an edit or an addition — and is never overwritten:
|
|
431
|
+
*
|
|
432
|
+
* | an entry on disk that is… | result |
|
|
433
|
+
* |----------------------------------------------|-------------------------------------|
|
|
434
|
+
* | one the daemon wrote (live or preserved) | the daemon's in-memory copy wins |
|
|
435
|
+
* | one the daemon wrote, now neither live nor preserved | gone on purpose (a delete or discard): NOT resurrected |
|
|
436
|
+
* | new, and it normalises, its id is free, cap allows | ADOPTED as a task |
|
|
437
|
+
* | new, and its id is a live task's (or was just adopted) | preserved as unreadable, "duplicates the id of …"; never armed |
|
|
438
|
+
* | new, and it does not normalise / cap reached | preserved as unreadable (reason re-derived) |
|
|
439
|
+
* | a preserved entry the operator edited or removed | the old capture is dropped; an edit is picked up as a new entry |
|
|
440
|
+
* | file missing / unparsable / wrong version or shape | no reconciliation: the in-memory set is written as before (nothing dropped) |
|
|
441
|
+
*
|
|
442
|
+
* New entries are processed in DISK ORDER, so when two share an id the first
|
|
443
|
+
* wins — exactly what `load()` of the same file would do. There is no identity
|
|
444
|
+
* inference (matching an edited entry to "the one it was" by id or position):
|
|
445
|
+
* each such guess had a hole that could resurrect a deleted task, arm a duplicate
|
|
446
|
+
* a restart would reject, or overwrite a live task. Editing a LIVE task's entry
|
|
447
|
+
* by hand therefore does not change the task; the edit is kept as an unreadable
|
|
448
|
+
* duplicate to discard or copy from. Such a duplicate is kept across restarts
|
|
449
|
+
* (`load()` preserves a duplicate id rather than dropping it; the first in file
|
|
450
|
+
* order is the task) and is dropped together with its task when that task is
|
|
451
|
+
* deleted, so deleting a task cannot leave a copy that a restart would arm. Edits are noticed only at a persist (any
|
|
452
|
+
* add/update/remove/discard or an engine run result), and an edit saved between
|
|
453
|
+
* that persist's read and its atomic rename is lost — the window any two writers
|
|
454
|
+
* of one file have. A persist that FAILS commits nothing (neither the adoption
|
|
455
|
+
* nor the new `_lastWritten`), and `remove()`/`discardUnreadable()` restore their
|
|
456
|
+
* in-memory change and throw so the caller reports the failure.
|
|
457
|
+
*/
|
|
458
|
+
export class ScheduledTaskStore {
|
|
459
|
+
/**
|
|
460
|
+
* @param {object} options
|
|
461
|
+
* @param {string} options.filePath - Path to the scheduled-tasks JSON file.
|
|
462
|
+
* @param {object} [options.logger] - Optional logger (defaults to module logger).
|
|
463
|
+
* @param {() => number} [options.now] - Test seam for the clock.
|
|
464
|
+
*/
|
|
465
|
+
constructor({ filePath, logger, now } = {}) {
|
|
466
|
+
if (!filePath) throw new Error('ScheduledTaskStore requires a filePath')
|
|
467
|
+
this._filePath = filePath
|
|
468
|
+
this._log = logger || log
|
|
469
|
+
this._now = typeof now === 'function' ? now : Date.now
|
|
470
|
+
// id -> normalized task record
|
|
471
|
+
this._tasks = new Map()
|
|
472
|
+
// #7050 — raw entries the loader REFUSED, kept verbatim so `_persist()` cannot
|
|
473
|
+
// erase them. Shape: `{ raw, id, reason }`. These are never served as live
|
|
474
|
+
// tasks; they exist so an operator's unreadable task survives the next
|
|
475
|
+
// unrelated mutation instead of being silently deleted from disk.
|
|
476
|
+
this._unreadable = []
|
|
477
|
+
// #7077: canonical JSON -> count of every entry in the last SUCCESSFUL write
|
|
478
|
+
// (seeded at load()). What is on disk and NOT in here is the operator's.
|
|
479
|
+
this._lastWritten = new Map()
|
|
480
|
+
this._loaded = false
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Load tasks from disk, REPLACING any in-memory state — load() is a true
|
|
485
|
+
* snapshot of the file, so a second load() (or a load after the file was
|
|
486
|
+
* deleted or corrupted) can never keep stale in-memory tasks alive and
|
|
487
|
+
* re-persist them on the next write. A missing file is treated as an empty
|
|
488
|
+
* store; an unparseable / malformed / unknown-version file is logged and
|
|
489
|
+
* skipped whole (fail-open to "no scheduled tasks", never a partial read).
|
|
490
|
+
*
|
|
491
|
+
* Individual entries that fail normalization are dropped (logged) while valid
|
|
492
|
+
* siblings load — a single hand-edited bad task can't nuke the whole registry.
|
|
493
|
+
* `nextRun` is recomputed on load so a stored value can't drift from the
|
|
494
|
+
* cadence (and a disabled task always loads with nextRun null).
|
|
495
|
+
* @returns {this}
|
|
496
|
+
*/
|
|
497
|
+
load() {
|
|
498
|
+
this._loaded = true
|
|
499
|
+
// Reset FIRST — every early return below must leave the store EMPTY, not
|
|
500
|
+
// holding the previous load's (now unbacked) tasks.
|
|
501
|
+
this._tasks.clear()
|
|
502
|
+
// #7050: reset with `_tasks`, NOT after the early returns below. Every early
|
|
503
|
+
// return must leave the store EMPTY — a reload that hits ENOENT / bad JSON /
|
|
504
|
+
// the version gate would otherwise keep the PREVIOUS load's preserved entries
|
|
505
|
+
// and `_persist()` would write them back into a file that no longer has them,
|
|
506
|
+
// resurrecting records the operator deleted.
|
|
507
|
+
this._unreadable = []
|
|
508
|
+
this._lastWritten = new Map()
|
|
509
|
+
let raw
|
|
510
|
+
try {
|
|
511
|
+
raw = fs.readFileSync(this._filePath, 'utf-8')
|
|
512
|
+
} catch (err) {
|
|
513
|
+
if (err && err.code !== 'ENOENT') {
|
|
514
|
+
this._log.warn(`Failed to read scheduled tasks at ${this._filePath}: ${err.message}`)
|
|
515
|
+
}
|
|
516
|
+
return this
|
|
517
|
+
}
|
|
518
|
+
let parsed
|
|
519
|
+
try {
|
|
520
|
+
parsed = JSON.parse(raw)
|
|
521
|
+
} catch (err) {
|
|
522
|
+
this._log.warn(`Failed to parse scheduled tasks at ${this._filePath}: ${err.message} — ignoring`)
|
|
523
|
+
return this
|
|
524
|
+
}
|
|
525
|
+
if (!parsed || typeof parsed !== 'object') return this
|
|
526
|
+
// Version gate: an unknown (future / hand-mangled) version is skipped WHOLE
|
|
527
|
+
// rather than partially read against the wrong shape assumptions.
|
|
528
|
+
if (parsed.version !== STORE_VERSION) {
|
|
529
|
+
this._log.warn(`Unsupported scheduled-tasks version ${JSON.stringify(parsed.version)} at ${this._filePath} (expected ${STORE_VERSION}) — ignoring`)
|
|
530
|
+
return this
|
|
531
|
+
}
|
|
532
|
+
const tasks = parsed.tasks
|
|
533
|
+
if (!Array.isArray(tasks)) return this
|
|
534
|
+
// #7077: everything in the file as read is, by definition, already known — the
|
|
535
|
+
// daemon is about to own it. Seeded BEFORE the loop so a refused or dropped
|
|
536
|
+
// entry is known too.
|
|
537
|
+
this._lastWritten = countCanonical(tasks)
|
|
538
|
+
for (const [i, entry] of tasks.entries()) {
|
|
539
|
+
if (this._tasks.size >= MAX_TASKS) {
|
|
540
|
+
// #7050: the remainder is never even examined, so it would be erased on
|
|
541
|
+
// the next write. Preserve it verbatim — these are valid tasks losing a
|
|
542
|
+
// race with a cap, which is the least defensible thing to delete.
|
|
543
|
+
const rest = tasks.slice(i)
|
|
544
|
+
this._log.warn(`Scheduled-tasks file exceeds cap (${MAX_TASKS}) — ${rest.length} ${rest.length === 1 ? 'entry' : 'entries'} not loaded (preserved on disk)`)
|
|
545
|
+
for (const skipped of rest) this._preserveUnreadable(skipped, `store cap (${MAX_TASKS}) reached`)
|
|
546
|
+
break
|
|
547
|
+
}
|
|
548
|
+
let record
|
|
549
|
+
try {
|
|
550
|
+
record = this._normalizeStoredTask(entry)
|
|
551
|
+
} catch (err) {
|
|
552
|
+
this._log.warn(`Refusing malformed scheduled task on load (preserved on disk): ${err.message}`)
|
|
553
|
+
this._preserveUnreadable(entry, err.message)
|
|
554
|
+
continue
|
|
555
|
+
}
|
|
556
|
+
if (this._tasks.has(record.id)) {
|
|
557
|
+
// Kept, not dropped: a duplicate may be an operator's edit that a running
|
|
558
|
+
// daemon preserved (see `_reconcile`), and dropping it here would erase
|
|
559
|
+
// it at the next write after a restart. First in file order wins, as ever.
|
|
560
|
+
this._log.warn(`Scheduled-task id ${record.id} appears more than once — keeping the first, preserving the duplicate (not scheduled)`)
|
|
561
|
+
this._unreadable.push(duplicateOfLive(entry, record.id))
|
|
562
|
+
continue
|
|
563
|
+
}
|
|
564
|
+
this._tasks.set(record.id, record)
|
|
565
|
+
}
|
|
566
|
+
if (this._tasks.size > 0) this._log.info(`Loaded ${this._tasks.size} scheduled task(s)`)
|
|
567
|
+
return this
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Add a new task. Assigns a fresh id (or accepts a caller-supplied id that
|
|
572
|
+
* does not collide), timestamps it, and computes `nextRun`. Persists. Throws
|
|
573
|
+
* {@link ScheduledTaskValidationError} on invalid input.
|
|
574
|
+
* @param {object} input - `{ prompt, cadence, target?, enabled?, name?, id?, lastRun? }`
|
|
575
|
+
* @returns {object} the stored task (a copy)
|
|
576
|
+
*/
|
|
577
|
+
add(input) {
|
|
578
|
+
if (!input || typeof input !== 'object') {
|
|
579
|
+
throw new ScheduledTaskValidationError('task input is required', 'task')
|
|
580
|
+
}
|
|
581
|
+
if (this._tasks.size >= MAX_TASKS) {
|
|
582
|
+
throw new ScheduledTaskValidationError(`scheduled-task cap reached (${MAX_TASKS})`, 'task')
|
|
583
|
+
}
|
|
584
|
+
let id = input.id
|
|
585
|
+
if (id === undefined || id === null) {
|
|
586
|
+
id = randomUUID()
|
|
587
|
+
} else {
|
|
588
|
+
if (typeof id !== 'string' || id.trim().length === 0) {
|
|
589
|
+
throw new ScheduledTaskValidationError('id must be a non-empty string', 'id')
|
|
590
|
+
}
|
|
591
|
+
id = id.trim()
|
|
592
|
+
requireIdWithinWireCap(id)
|
|
593
|
+
// #7050: preserved (unreadable) ids count as taken. They are on disk, so
|
|
594
|
+
// reusing one would put two entries with the same id in the file.
|
|
595
|
+
if (this._tasks.has(id) || this._unreadable.some((u) => u.id === id)) {
|
|
596
|
+
throw new ScheduledTaskValidationError(`task id ${id} already exists`, 'id')
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const now = this._now()
|
|
601
|
+
const record = {
|
|
602
|
+
id,
|
|
603
|
+
name: optionalString(input.name, 'name') ?? null,
|
|
604
|
+
enabled: input.enabled === undefined ? true : Boolean(input.enabled),
|
|
605
|
+
prompt: this._requirePrompt(input.prompt),
|
|
606
|
+
target: normalizeTarget(input.target),
|
|
607
|
+
cadence: normalizeCadence(input.cadence),
|
|
608
|
+
nextRun: null,
|
|
609
|
+
lastRun: normalizeLastRun(input.lastRun),
|
|
610
|
+
createdAt: now,
|
|
611
|
+
updatedAt: now,
|
|
612
|
+
}
|
|
613
|
+
record.nextRun = computeNextRun(record, { from: now })
|
|
614
|
+
this._tasks.set(id, record)
|
|
615
|
+
this._persist()
|
|
616
|
+
return this._clone(record)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Return a task by id (a copy), or null when absent.
|
|
621
|
+
* @param {string} id
|
|
622
|
+
* @returns {object|null}
|
|
623
|
+
*/
|
|
624
|
+
get(id) {
|
|
625
|
+
const record = this._tasks.get(id)
|
|
626
|
+
return record ? this._clone(record) : null
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Snapshot of every task (copies), insertion order.
|
|
631
|
+
* @returns {object[]}
|
|
632
|
+
*/
|
|
633
|
+
list() {
|
|
634
|
+
return Array.from(this._tasks.values(), (r) => this._clone(r))
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Apply a partial patch to an existing task and persist. Recomputes `nextRun`
|
|
639
|
+
* (so a cadence/enabled change is reflected) and bumps `updatedAt`. The `id`
|
|
640
|
+
* and `createdAt` are immutable. Returns the updated task (a copy), or null
|
|
641
|
+
* when the id is unknown. Throws {@link ScheduledTaskValidationError} on an
|
|
642
|
+
* invalid patch value.
|
|
643
|
+
* @param {string} id
|
|
644
|
+
* @param {object} patch - any subset of `{ prompt, cadence, target, enabled, name, lastRun }`
|
|
645
|
+
* @returns {object|null}
|
|
646
|
+
*/
|
|
647
|
+
update(id, patch) {
|
|
648
|
+
const existing = this._tasks.get(id)
|
|
649
|
+
if (!existing) return null
|
|
650
|
+
if (!patch || typeof patch !== 'object') {
|
|
651
|
+
throw new ScheduledTaskValidationError('update patch is required', 'patch')
|
|
652
|
+
}
|
|
653
|
+
const next = { ...existing }
|
|
654
|
+
if ('prompt' in patch) next.prompt = this._requirePrompt(patch.prompt)
|
|
655
|
+
if ('cadence' in patch) next.cadence = normalizeCadence(patch.cadence)
|
|
656
|
+
if ('target' in patch) next.target = normalizeTarget(patch.target)
|
|
657
|
+
if ('enabled' in patch) next.enabled = Boolean(patch.enabled)
|
|
658
|
+
if ('name' in patch) next.name = optionalString(patch.name, 'name') ?? null
|
|
659
|
+
if ('lastRun' in patch) next.lastRun = normalizeLastRun(patch.lastRun)
|
|
660
|
+
next.updatedAt = this._now()
|
|
661
|
+
next.nextRun = computeNextRun(next, { from: next.updatedAt })
|
|
662
|
+
this._tasks.set(id, next)
|
|
663
|
+
this._persist()
|
|
664
|
+
return this._clone(next)
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* Remove a task by id and persist. Returns true when a task was removed.
|
|
669
|
+
* @param {string} id
|
|
670
|
+
* @returns {boolean}
|
|
671
|
+
*/
|
|
672
|
+
remove(id) {
|
|
673
|
+
if (this._tasks.has(id)) {
|
|
674
|
+
const before = new Map(this._tasks)
|
|
675
|
+
const beforeUnreadable = this._unreadable
|
|
676
|
+
this._tasks.delete(id)
|
|
677
|
+
// The duplicates kept for this id go with it: otherwise a restart loads one
|
|
678
|
+
// as the very task that was just deleted.
|
|
679
|
+
this._unreadable = beforeUnreadable.filter((u) => u.duplicateOf !== id)
|
|
680
|
+
if (!this._persist()) {
|
|
681
|
+
this._tasks = before
|
|
682
|
+
this._unreadable = beforeUnreadable
|
|
683
|
+
throw persistFailure()
|
|
684
|
+
}
|
|
685
|
+
return true
|
|
686
|
+
}
|
|
687
|
+
// #7050: a preserved (unreadable) entry must stay deletable — otherwise
|
|
688
|
+
// refusing to erase it would trade silent data loss for an undeletable
|
|
689
|
+
// record the operator has no way to clear.
|
|
690
|
+
//
|
|
691
|
+
// Guard the id: preserved entries with no usable id carry `id: null`, so a
|
|
692
|
+
// `remove(null)` (or any non-string) would match and delete ALL of them at
|
|
693
|
+
// once and report success. `listUnreadable()` publicly emits those null rows,
|
|
694
|
+
// so this is reachable the moment a caller forwards one back.
|
|
695
|
+
if (typeof id !== 'string' || id.length === 0) return false
|
|
696
|
+
const before = this._unreadable
|
|
697
|
+
this._unreadable = before.filter((u) => u.id !== id)
|
|
698
|
+
if (this._unreadable.length === before.length) return false
|
|
699
|
+
if (!this._persist()) {
|
|
700
|
+
this._unreadable = before
|
|
701
|
+
throw persistFailure()
|
|
702
|
+
}
|
|
703
|
+
return true
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* #7050 — how many stored entries the loader could not read. Non-zero means
|
|
708
|
+
* `list()` is SHORTER than what is on disk, which the panel should say out
|
|
709
|
+
* loud rather than rendering a silently short list.
|
|
710
|
+
* @returns {number}
|
|
711
|
+
*/
|
|
712
|
+
unreadableCount() {
|
|
713
|
+
return this._unreadable.length
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* #7050 / #7079 — the refused entries' handles, ids and reasons (never their
|
|
718
|
+
* raw contents, which may be any shape). `id` is null when the entry had no
|
|
719
|
+
* usable string id. `handle` is the opaque, wire-legal token a client uses to
|
|
720
|
+
* name the entry (see {@link handleOf}); byte-identical entries get a `-<n>`
|
|
721
|
+
* suffix so each stays individually addressable.
|
|
722
|
+
*
|
|
723
|
+
* This reflects the daemon's view as of the last load or persist; it does not
|
|
724
|
+
* re-read the file (a read must not change what is armed to fire).
|
|
725
|
+
* @returns {{ handle: string, id: string|null, reason: string }[]}
|
|
726
|
+
*/
|
|
727
|
+
listUnreadable() {
|
|
728
|
+
const seen = new Map()
|
|
729
|
+
return this._unreadable.map(({ raw, id, reason }) => {
|
|
730
|
+
const base = handleOf(canonicalJson(raw))
|
|
731
|
+
const n = (seen.get(base) ?? 0) + 1
|
|
732
|
+
seen.set(base, n)
|
|
733
|
+
return { handle: n === 1 ? base : `${base}-${n}`, id, reason }
|
|
734
|
+
})
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* #7079 — discard ONE unreadable entry by the handle `listUnreadable()` derived
|
|
739
|
+
* for it, and persist. Returns false (changing nothing) for an unknown, stale or
|
|
740
|
+
* non-string handle. Re-derives handles server-side after refreshing the
|
|
741
|
+
* preserved set from disk, so a handle the operator saw before hand-editing the
|
|
742
|
+
* file no longer matches: their newer edit is never discarded blind.
|
|
743
|
+
* @param {string} handle
|
|
744
|
+
* @returns {boolean}
|
|
745
|
+
*/
|
|
746
|
+
discardUnreadable(handle) {
|
|
747
|
+
if (typeof handle !== 'string' || handle.length === 0) return false
|
|
748
|
+
const index = this.listUnreadable().findIndex((u) => u.handle === handle)
|
|
749
|
+
if (index === -1) return false
|
|
750
|
+
// A handle derives from the daemon's in-memory capture. If the operator has
|
|
751
|
+
// since edited or removed that entry in the file, the capture is stale and
|
|
752
|
+
// the handle no longer names what is on disk: refuse, and refresh (a persist
|
|
753
|
+
// reconciles) so the next listing carries the entry as it is now.
|
|
754
|
+
const disk = this._readDiskEntries()
|
|
755
|
+
const key = canonicalJson(this._unreadable[index].raw)
|
|
756
|
+
if (disk !== null && !disk.some((entry) => canonicalJson(entry) === key)) {
|
|
757
|
+
this._persist()
|
|
758
|
+
return false
|
|
759
|
+
}
|
|
760
|
+
const before = this._unreadable
|
|
761
|
+
this._unreadable = before.filter((_, i) => i !== index)
|
|
762
|
+
if (!this._persist()) {
|
|
763
|
+
this._unreadable = before
|
|
764
|
+
throw persistFailure()
|
|
765
|
+
}
|
|
766
|
+
return true
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* @private — #7077: read the file's task entries for reconciliation, or null
|
|
771
|
+
* when they cannot be trusted (missing / unreadable / unparsable / wrong
|
|
772
|
+
* version / `tasks` not an array). Null means "fall back to the captured raw
|
|
773
|
+
* entries", never "there are none".
|
|
774
|
+
*/
|
|
775
|
+
_readDiskEntries() {
|
|
776
|
+
try {
|
|
777
|
+
const parsed = JSON.parse(fs.readFileSync(this._filePath, 'utf-8'))
|
|
778
|
+
if (!parsed || typeof parsed !== 'object' || parsed.version !== STORE_VERSION) return null
|
|
779
|
+
return Array.isArray(parsed.tasks) ? parsed.tasks : null
|
|
780
|
+
} catch {
|
|
781
|
+
return null
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* @private — #7077/#8523: classify what is on disk against what the daemon last
|
|
787
|
+
* wrote. PURE — returns the result; `_persist()` commits it only if the write
|
|
788
|
+
* succeeds. See the class docblock for the table. `disk` is trusted.
|
|
789
|
+
* @returns {{ adopted: object[], unreadable: object[] }}
|
|
790
|
+
*/
|
|
791
|
+
_reconcile(disk) {
|
|
792
|
+
const diskKeys = disk.map(canonicalJson)
|
|
793
|
+
// A preserved entry the file still holds verbatim stays; one it does not was
|
|
794
|
+
// edited or removed by the operator, so the capture is dropped (an edit
|
|
795
|
+
// reappears below as a new entry).
|
|
796
|
+
const onDisk = countCanonical(disk)
|
|
797
|
+
const unreadable = []
|
|
798
|
+
for (const p of this._unreadable) {
|
|
799
|
+
const key = canonicalJson(p.raw)
|
|
800
|
+
const n = onDisk.get(key) ?? 0
|
|
801
|
+
if (n > 0) {
|
|
802
|
+
onDisk.set(key, n - 1)
|
|
803
|
+
unreadable.push(p)
|
|
804
|
+
} else {
|
|
805
|
+
this._log.info('A preserved unreadable scheduled-task entry was edited or removed in the registry file — dropping the stale copy')
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
// Everything the daemon did not write is the operator's, in DISK ORDER.
|
|
809
|
+
const known = new Map(this._lastWritten)
|
|
810
|
+
const taken = new Set(this._tasks.keys())
|
|
811
|
+
const adopted = []
|
|
812
|
+
disk.forEach((entry, i) => {
|
|
813
|
+
const n = known.get(diskKeys[i]) ?? 0
|
|
814
|
+
if (n > 0) { known.set(diskKeys[i], n - 1); return }
|
|
815
|
+
try {
|
|
816
|
+
const record = this._normalizeStoredTask(entry)
|
|
817
|
+
if (taken.has(record.id)) {
|
|
818
|
+
unreadable.push(duplicateOfLive(entry, record.id))
|
|
819
|
+
} else if (taken.size >= MAX_TASKS) {
|
|
820
|
+
unreadable.push({ raw: entry, id: usableId(entry), reason: `store cap (${MAX_TASKS}) reached` })
|
|
821
|
+
} else {
|
|
822
|
+
taken.add(record.id)
|
|
823
|
+
adopted.push(record)
|
|
824
|
+
this._log.info(`Adopted scheduled task ${record.id}: it was added or repaired in the registry file`)
|
|
825
|
+
}
|
|
826
|
+
} catch (err) {
|
|
827
|
+
unreadable.push({ raw: entry, id: usableId(entry), reason: String(err.message) })
|
|
828
|
+
}
|
|
829
|
+
})
|
|
830
|
+
return { adopted, unreadable }
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** @private — keep a refused raw entry so `_persist()` cannot erase it (#7050). */
|
|
834
|
+
_preserveUnreadable(raw, reason) {
|
|
835
|
+
const id = usableId(raw)
|
|
836
|
+
this._unreadable.push({ raw, id, reason: String(reason) })
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** @private — require a non-empty string prompt. */
|
|
840
|
+
_requirePrompt(prompt) {
|
|
841
|
+
if (typeof prompt !== 'string' || prompt.trim().length === 0) {
|
|
842
|
+
throw new ScheduledTaskValidationError('prompt is required (non-empty string)', 'prompt')
|
|
843
|
+
}
|
|
844
|
+
return prompt
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* @private — normalize an entry read from disk into a stored record, filling
|
|
849
|
+
* missing timestamps and recomputing nextRun. Throws on anything that can't be
|
|
850
|
+
* coerced into a valid task (the caller drops it, logging).
|
|
851
|
+
*/
|
|
852
|
+
_normalizeStoredTask(entry) {
|
|
853
|
+
if (!entry || typeof entry !== 'object') {
|
|
854
|
+
throw new ScheduledTaskValidationError('task entry must be an object', 'task')
|
|
855
|
+
}
|
|
856
|
+
if (typeof entry.id !== 'string' || entry.id.trim().length === 0) {
|
|
857
|
+
throw new ScheduledTaskValidationError('task id must be a non-empty string', 'id')
|
|
858
|
+
}
|
|
859
|
+
requireIdWithinWireCap(entry.id.trim())
|
|
860
|
+
const createdAt = Number.isFinite(entry.createdAt) ? entry.createdAt : this._now()
|
|
861
|
+
const updatedAt = Number.isFinite(entry.updatedAt) ? entry.updatedAt : createdAt
|
|
862
|
+
const record = {
|
|
863
|
+
id: entry.id.trim(),
|
|
864
|
+
name: optionalString(entry.name, 'name') ?? null,
|
|
865
|
+
enabled: entry.enabled === undefined ? true : Boolean(entry.enabled),
|
|
866
|
+
prompt: this._requirePrompt(entry.prompt),
|
|
867
|
+
target: normalizeTarget(entry.target),
|
|
868
|
+
cadence: normalizeCadence(entry.cadence),
|
|
869
|
+
nextRun: null,
|
|
870
|
+
lastRun: normalizeLastRun(entry.lastRun),
|
|
871
|
+
createdAt,
|
|
872
|
+
updatedAt,
|
|
873
|
+
}
|
|
874
|
+
// Recompute nextRun from the cadence rather than trusting the stored value,
|
|
875
|
+
// so a stale/hand-edited nextRun can never diverge from the schedule.
|
|
876
|
+
record.nextRun = computeNextRun(record, { from: this._now() })
|
|
877
|
+
return record
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** @private — deep-ish copy so callers can't mutate the in-memory record. */
|
|
881
|
+
_clone(record) {
|
|
882
|
+
return {
|
|
883
|
+
...record,
|
|
884
|
+
target: { ...record.target },
|
|
885
|
+
cadence: { ...record.cadence },
|
|
886
|
+
lastRun: record.lastRun ? { ...record.lastRun } : null,
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* @private — atomic write of the whole store. Returns true when the file was
|
|
892
|
+
* written, false when it was not (the failure is logged; nothing is committed).
|
|
893
|
+
* add()/update() keep their long-standing best-effort contract and ignore it;
|
|
894
|
+
* remove()/discardUnreadable() report it.
|
|
895
|
+
*/
|
|
896
|
+
_persist() {
|
|
897
|
+
try {
|
|
898
|
+
const dir = dirname(this._filePath)
|
|
899
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
|
|
900
|
+
// #7077/#8523: pick up the operator's edits and additions BEFORE writing, so
|
|
901
|
+
// the daemon only ever rewrites entries it wrote itself. A store that never
|
|
902
|
+
// loaded has no baseline to compare against and writes as before; so does a
|
|
903
|
+
// file that is missing / unparsable / the wrong shape (nothing is dropped).
|
|
904
|
+
let adopted = []
|
|
905
|
+
let unreadable = this._unreadable
|
|
906
|
+
if (this._loaded) {
|
|
907
|
+
const disk = this._readDiskEntries()
|
|
908
|
+
if (disk !== null) ({ adopted, unreadable } = this._reconcile(disk))
|
|
909
|
+
}
|
|
910
|
+
// The preserved raw entries ride along so an unrelated mutation cannot erase
|
|
911
|
+
// a task the loader merely could not READ. They are appended (never
|
|
912
|
+
// re-serialized from a normalized record) so nothing is lost in a round trip
|
|
913
|
+
// through a shape this version does not understand.
|
|
914
|
+
const text = JSON.stringify({
|
|
915
|
+
version: STORE_VERSION,
|
|
916
|
+
tasks: [...this._tasks.values(), ...adopted, ...unreadable.map((u) => u.raw)],
|
|
917
|
+
}, null, 2)
|
|
918
|
+
writeFileRestricted(this._filePath, text, { tmpSuffix: `.tmp-${process.pid}` })
|
|
919
|
+
// Committed only now that the file really holds it. A failed write leaves the
|
|
920
|
+
// baseline and the preserved set as they were, so the next persist reconciles
|
|
921
|
+
// against the truth instead of against something that never reached disk.
|
|
922
|
+
for (const record of adopted) this._tasks.set(record.id, record)
|
|
923
|
+
this._unreadable = unreadable
|
|
924
|
+
this._lastWritten = countCanonical(JSON.parse(text).tasks)
|
|
925
|
+
return true
|
|
926
|
+
} catch (err) {
|
|
927
|
+
// Best-effort: a failed persist leaves the in-memory set intact for this
|
|
928
|
+
// process; the prior good file (if any) survives (atomic write). Surface
|
|
929
|
+
// it so an operator can see the schedule won't survive a restart.
|
|
930
|
+
this._log.error(`Failed to persist scheduled tasks to ${this._filePath}: ${err?.stack || err}`)
|
|
931
|
+
return false
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Default on-disk path for the registry given the session-state file's dir — a
|
|
938
|
+
* sibling of session-state.json. Kept here so both session-manager wiring and a
|
|
939
|
+
* future CLI/engine resolve the same path.
|
|
940
|
+
* @param {string} stateFilePath
|
|
941
|
+
* @returns {string}
|
|
942
|
+
*/
|
|
943
|
+
export function defaultScheduledTasksPath(stateFilePath) {
|
|
944
|
+
return resolve(dirname(stateFilePath), 'scheduled-tasks.json')
|
|
945
|
+
}
|