@chroxy/server 0.10.0 → 0.11.0
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 +411 -14
- package/hooks/permission-hook.sh +253 -3
- package/package.json +8 -15
- package/sidecar/node_modules/.package-lock.json +29 -0
- package/sidecar/node_modules/ws/LICENSE +20 -0
- package/sidecar/node_modules/ws/README.md +548 -0
- package/sidecar/node_modules/ws/browser.js +8 -0
- package/sidecar/node_modules/ws/index.js +22 -0
- package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
- package/sidecar/node_modules/ws/lib/constants.js +19 -0
- package/sidecar/node_modules/ws/lib/event-target.js +292 -0
- package/sidecar/node_modules/ws/lib/extension.js +203 -0
- package/sidecar/node_modules/ws/lib/limiter.js +55 -0
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/sidecar/node_modules/ws/lib/receiver.js +706 -0
- package/sidecar/node_modules/ws/lib/sender.js +602 -0
- package/sidecar/node_modules/ws/lib/stream.js +161 -0
- package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
- package/sidecar/node_modules/ws/lib/validation.js +152 -0
- package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
- package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
- package/sidecar/node_modules/ws/package.json +70 -0
- package/sidecar/node_modules/ws/wrapper.mjs +21 -0
- package/src/base-session.js +151 -6
- package/src/billing-budget.js +5 -1
- package/src/binary-provenance-trust.js +95 -0
- package/src/built-in-tools/file-ops.js +5 -4
- package/src/byok-mcp-client.js +1061 -13
- package/src/byok-mcp-config.js +1201 -4
- package/src/byok-mcp-fleet.js +374 -29
- package/src/byok-mcp-oauth-store.js +327 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +254 -37
- package/src/byok-session.js +789 -13
- package/src/byok-tool-executor.js +20 -13
- package/src/checkpoint-manager.js +33 -6
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-stream-parser.js +56 -0
- package/src/claude-tui/pty-driver.js +54 -14
- package/src/claude-tui-session.js +106 -7
- package/src/cli/config-cmd.js +2 -2
- package/src/cli/deploy-cmd.js +1 -1
- package/src/cli/init-cmd.js +1 -1
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +775 -0
- package/src/cli/server-cmd.js +16 -1
- package/src/cli/service-cmd.js +39 -19
- package/src/cli/shared.js +7 -4
- package/src/cli/tokens-cmd.js +213 -0
- package/src/cli/tunnel-cmd.js +1 -1
- package/src/cli-session.js +66 -10
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +671 -39
- package/src/codex-session.js +121 -18
- package/src/config.js +453 -27
- package/src/control-room/integrations.js +16 -10
- package/src/control-room/skills-inventory.js +6 -1
- package/src/control-room/survey.js +32 -0
- package/src/credential-store.js +256 -10
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/diagnostics.js +3 -0
- package/src/docker-sdk-session.js +16 -1
- package/src/docker-session.js +9 -0
- package/src/doctor.js +19 -8
- package/src/environments/backends/docker.js +8 -0
- package/src/environments/backends/k8s.js +9 -0
- package/src/event-ingest.js +19 -1
- package/src/event-normalizer.js +354 -19
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +19 -2
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +42 -8
- package/src/handlers/checkpoint-handlers.js +126 -19
- package/src/handlers/control-room-handlers.js +48 -18
- package/src/handlers/conversation-handlers.js +127 -2
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/file-handlers.js +47 -3
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +4 -0
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +510 -0
- package/src/handlers/session-handlers.js +10 -2
- package/src/handlers/settings-handlers.js +510 -11
- package/src/handlers/token-handlers.js +11 -2
- package/src/http-routes.js +159 -0
- package/src/jsonl-reader.js +60 -6
- package/src/jsonl-subprocess-session.js +35 -6
- package/src/keychain.js +159 -12
- package/src/logger.js +182 -19
- package/src/notification-prefs.js +88 -6
- package/src/notifications/discord-webhook-sink.js +30 -1
- package/src/orchestration/build-manager.js +56 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +347 -0
- package/src/orchestration/orchestration-manager.js +1295 -0
- package/src/orchestration/permission-gate.js +109 -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 +205 -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 +398 -0
- package/src/pairing.js +146 -1
- package/src/permission-audit.js +79 -3
- package/src/permission-floor.js +455 -0
- package/src/permission-manager.js +492 -40
- package/src/permission-resolver.js +55 -7
- package/src/permission-rule-store.js +411 -0
- package/src/platform.js +367 -23
- package/src/providers.js +21 -2
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +653 -0
- package/src/scheduler.js +1029 -0
- package/src/sdk-session.js +338 -5
- package/src/server-cli/server-orchestrator.js +23 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli.js +238 -26
- package/src/server-identity.js +28 -4
- package/src/service.js +291 -33
- package/src/session-manager.js +417 -25
- package/src/session-message-history.js +27 -21
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +60 -35
- package/src/skills-usage.js +20 -2
- package/src/statusline.js +584 -0
- package/src/subagent-counter.js +9 -1
- package/src/supervisor.js +77 -27
- package/src/token-manager.js +39 -9
- package/src/transcript-tasks.js +41 -6
- package/src/tunnel/cloudflare.js +115 -8
- package/src/tunnel/index.js +4 -1
- package/src/tunnel-check.js +1 -1
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +118 -0
- package/src/user-shell-session.js +98 -32
- package/src/utils/componentwise-resolver.js +205 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/preflight.js +140 -28
- package/src/utils/spawn-env.js +8 -2
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +241 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/worktree-gc.js +4 -1
- package/src/ws-file-ops/browser.js +42 -11
- package/src/ws-file-ops/common.js +68 -1
- package/src/ws-file-ops/git.js +221 -3
- package/src/ws-file-ops/index.js +5 -0
- package/src/ws-file-ops/memory.js +358 -0
- package/src/ws-file-ops/reader.js +124 -0
- package/src/ws-forwarding.js +44 -16
- package/src/ws-handler-context.js +19 -0
- package/src/ws-history.js +84 -11
- package/src/ws-message-handlers.js +6 -0
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +285 -4
- package/src/ws-schemas.js +1 -0
- package/src/ws-server.js +301 -17
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import { 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
|
+
const CADENCE_KINDS = new Set(['once', 'interval', 'cron'])
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* #7051 — the wire cap on `cadence.cron.expression`, mirroring
|
|
25
|
+
* `ScheduledTaskCadenceCronSchema` in @chroxy/protocol
|
|
26
|
+
* (schemas/server/scheduler.ts). Kept as a local constant rather than imported
|
|
27
|
+
* so this module stays dependency-light, and pinned by a test that safeParses
|
|
28
|
+
* the REAL schema at the boundary — a comment cannot stop the two drifting, a
|
|
29
|
+
* failing test can.
|
|
30
|
+
*
|
|
31
|
+
* Rejected, NOT clamped. `projectTask` truncates the other capped strings
|
|
32
|
+
* (name, provider, model, ...) because a truncated label is merely ugly.
|
|
33
|
+
* Truncating a cron expression silently CHANGES THE SCHEDULE — `0,30 * * * *`
|
|
34
|
+
* cut to `0,3` is a different, still-valid schedule that fires at the wrong
|
|
35
|
+
* time forever. Refusing at the store boundary is the only safe option, the
|
|
36
|
+
* same reasoning as the unrepresentable-epoch check below.
|
|
37
|
+
*
|
|
38
|
+
* The blast radius is why this matters at all: the dashboard safeParses the
|
|
39
|
+
* WHOLE `scheduled_tasks` snapshot, so ONE over-cap task makes the panel render
|
|
40
|
+
* zero tasks (plus "the list below may be out of date") while N tasks are armed
|
|
41
|
+
* and firing — the store-legal / wire-illegal asymmetry the clamping in
|
|
42
|
+
* `scheduler-handlers.js` was added to eliminate.
|
|
43
|
+
*/
|
|
44
|
+
const MAX_CRON_EXPRESSION_LENGTH = 256
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* #7074 — the wire cap on a task `id`, mirroring `ScheduledTaskSchema.id`
|
|
48
|
+
* (max 256) in @chroxy/protocol. Pinned by a test that safeParses the REAL
|
|
49
|
+
* schema at the boundary, so the two cannot drift silently.
|
|
50
|
+
*
|
|
51
|
+
* Rejected, NOT clamped — and unlike the other capped strings the reason is not
|
|
52
|
+
* cosmetic: `id` is the MUTATION KEY, so a truncated id would make
|
|
53
|
+
* pause/update/delete address the wrong record, or nothing. `projectTask` in
|
|
54
|
+
* scheduler-handlers.js deliberately leaves `id` unclamped for exactly this
|
|
55
|
+
* reason, which leaves refusing at the store boundary as the only safe option.
|
|
56
|
+
*
|
|
57
|
+
* Generated ids are uuids (36 chars), and no writer supplies one: the WS path
|
|
58
|
+
* cannot (`ScheduledTaskInputSchema` has no `id` field and `z.object` strips
|
|
59
|
+
* unknown keys, so `ws-server.js` dispatches a payload without it) and the CLI
|
|
60
|
+
* omits it. The reachable path is therefore a hand-edited registry file.
|
|
61
|
+
*
|
|
62
|
+
* Since #7050 a refused entry is PRESERVED on disk rather than erased, so
|
|
63
|
+
* refusing here does not destroy the operator's task. It does NOT yet mean they
|
|
64
|
+
* can repair it in-product: an over-cap id is unaddressable at the wire
|
|
65
|
+
* (`ScheduledTaskActionSchema.taskId` is capped too) and absent from
|
|
66
|
+
* `store.list()`, so today the only remediation is hand-editing the same file.
|
|
67
|
+
* Closing that loop is #7079.
|
|
68
|
+
*/
|
|
69
|
+
const MAX_WIRE_ID_LENGTH = 256
|
|
70
|
+
|
|
71
|
+
// Audited alongside #7074: every OTHER capped field on `ScheduledTaskSchema` is
|
|
72
|
+
// already clamped before send by `projectTask`/`projectTarget`/`projectLastRun`
|
|
73
|
+
// in handlers/scheduler-handlers.js (name, target.*, lastRun.*, providerRefusal,
|
|
74
|
+
// effectiveProvider, effectivePermissionMode), and `prompt` is `z.string()` with
|
|
75
|
+
// NO wire cap, so it is symmetric and has nothing to violate. If a cap is ever
|
|
76
|
+
// added to `prompt` on the wire, it needs a bound HERE too — otherwise it
|
|
77
|
+
// becomes the next #7051.
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Throw unless `id` fits the wire cap. Shared by `add()` and
|
|
82
|
+
* `_normalizeStoredTask()` so the client path and the load path cannot diverge
|
|
83
|
+
* — the split that made #7051 reachable through the file after add() was fixed.
|
|
84
|
+
* @param {string} id - an already-trimmed, non-empty id
|
|
85
|
+
*/
|
|
86
|
+
function requireIdWithinWireCap(id) {
|
|
87
|
+
if (id.length > MAX_WIRE_ID_LENGTH) {
|
|
88
|
+
throw new ScheduledTaskValidationError(
|
|
89
|
+
`task id must be <= ${MAX_WIRE_ID_LENGTH} characters (got ${id.length}) — ` +
|
|
90
|
+
'a longer id cannot be carried on the wire and would make the whole scheduled-tasks snapshot unparseable',
|
|
91
|
+
'id',
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The largest absolute epoch-ms a JS `Date` can represent (±8.64e15, i.e. ±100M
|
|
98
|
+
* days around the epoch — year ±275760). Beyond it `new Date(ms)` is an Invalid
|
|
99
|
+
* Date and `.toISOString()` THROWS `RangeError`.
|
|
100
|
+
*
|
|
101
|
+
* Checking only `Number.isFinite` let such a value be stored and served: it then
|
|
102
|
+
* crashed the dashboard's scheduled-tasks panel during render (#6871 review C3).
|
|
103
|
+
* Reachable without hand-editing the registry — a µs/ns epoch typo (`1.795e18`,
|
|
104
|
+
* a plausible unit mix-up) is finite. Rejecting it at the store boundary keeps
|
|
105
|
+
* an unrenderable instant out of the registry in the first place; every real
|
|
106
|
+
* schedule is many orders of magnitude below this bound, so nothing legitimate
|
|
107
|
+
* is refused.
|
|
108
|
+
*/
|
|
109
|
+
const MAX_EPOCH_MS = 8.64e15
|
|
110
|
+
// `refused` (#6997 review) = the engine declined to start the run at all — an
|
|
111
|
+
// unsupported hook-routed provider, a cwd outside the allowlist, or a permission
|
|
112
|
+
// mode it could not verify. Distinct from `error` (the run happened and failed)
|
|
113
|
+
// and `skipped` (the slot passed) so a reader can tell an operator that NOTHING
|
|
114
|
+
// ran and that the task definition needs fixing.
|
|
115
|
+
// `interrupted` (#7038) = the run was deliberately STOPPED (an operator Stop, an
|
|
116
|
+
// orchestration cancel) rather than failing. Distinct from `error` for the same
|
|
117
|
+
// reason `refused` is: nothing is broken, so an operator must not have to read
|
|
118
|
+
// the free-text message to tell an intentional interrupt from a crash.
|
|
119
|
+
//
|
|
120
|
+
// This set is a HARD GATE, not documentation: normalizeLastRun() throws on
|
|
121
|
+
// anything outside it, and the engine turns that throw into a QUARANTINE
|
|
122
|
+
// (scheduler.js `_recordRun` — "its run outcome could not be recorded"). An
|
|
123
|
+
// engine status missing here therefore does not just fail to persist; it stops
|
|
124
|
+
// the task firing for the rest of the process.
|
|
125
|
+
const LAST_RUN_STATUSES = new Set(['success', 'error', 'skipped', 'timeout', 'refused', 'interrupted'])
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Error thrown when a task submitted to add()/update() is malformed. Carries the
|
|
129
|
+
* offending field name so a caller (CLI #6868 / dashboard #6871) can surface a
|
|
130
|
+
* precise validation message. Corrupt entries read off DISK are silently dropped
|
|
131
|
+
* instead (fail-open), never thrown — only programmatic input is strict.
|
|
132
|
+
*/
|
|
133
|
+
export class ScheduledTaskValidationError extends Error {
|
|
134
|
+
constructor(message, field) {
|
|
135
|
+
super(message)
|
|
136
|
+
this.name = 'ScheduledTaskValidationError'
|
|
137
|
+
this.field = field
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Trim and validate an optional string target field. Returns the trimmed string,
|
|
143
|
+
* or undefined when absent/empty. Throws on a non-string.
|
|
144
|
+
*/
|
|
145
|
+
function optionalString(value, field) {
|
|
146
|
+
if (value === undefined || value === null) return undefined
|
|
147
|
+
if (typeof value !== 'string') throw new ScheduledTaskValidationError(`${field} must be a string`, field)
|
|
148
|
+
const trimmed = value.trim()
|
|
149
|
+
return trimmed.length > 0 ? trimmed : undefined
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* True only for a plain `{}` object — rejects arrays, class instances, and
|
|
154
|
+
* primitives. `typeof [] === 'object'` alone would let an array masquerade as a
|
|
155
|
+
* valid target, so callers that want a `{ provider, ... }` bag must use this.
|
|
156
|
+
*/
|
|
157
|
+
function isPlainObject(value) {
|
|
158
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
159
|
+
const proto = Object.getPrototypeOf(value)
|
|
160
|
+
return proto === Object.prototype || proto === null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Normalize + validate a target session config `{ provider, model, cwd,
|
|
165
|
+
* permissionMode }`. All fields optional; unknown keys are dropped. `target`
|
|
166
|
+
* must be a plain object (an array or other non-plain value is rejected, since
|
|
167
|
+
* `typeof [] === 'object'`), and `permissionMode`, when present, must be one of
|
|
168
|
+
* the server's supported mode IDs ({@link ALLOWED_PERMISSION_MODE_IDS}). Returns
|
|
169
|
+
* a plain object (possibly empty).
|
|
170
|
+
*/
|
|
171
|
+
function normalizeTarget(target) {
|
|
172
|
+
if (target === undefined || target === null) return {}
|
|
173
|
+
if (!isPlainObject(target)) throw new ScheduledTaskValidationError('target must be a plain object', 'target')
|
|
174
|
+
const out = {}
|
|
175
|
+
const provider = optionalString(target.provider, 'target.provider')
|
|
176
|
+
const model = optionalString(target.model, 'target.model')
|
|
177
|
+
const cwd = optionalString(target.cwd, 'target.cwd')
|
|
178
|
+
const permissionMode = optionalString(target.permissionMode, 'target.permissionMode')
|
|
179
|
+
if (permissionMode !== undefined && !ALLOWED_PERMISSION_MODE_IDS.has(permissionMode)) {
|
|
180
|
+
throw new ScheduledTaskValidationError(
|
|
181
|
+
`target.permissionMode must be one of ${[...ALLOWED_PERMISSION_MODE_IDS].join(', ')}`,
|
|
182
|
+
'target.permissionMode',
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
if (provider !== undefined) out.provider = provider
|
|
186
|
+
if (model !== undefined) out.model = model
|
|
187
|
+
if (cwd !== undefined) out.cwd = cwd
|
|
188
|
+
if (permissionMode !== undefined) out.permissionMode = permissionMode
|
|
189
|
+
return out
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Normalize + validate a cadence into its canonical stored form. Throws
|
|
194
|
+
* {@link ScheduledTaskValidationError} on anything malformed.
|
|
195
|
+
* @returns {{kind:'once',at:number} | {kind:'interval',everyMs:number,anchor?:number} | {kind:'cron',expression:string}}
|
|
196
|
+
*/
|
|
197
|
+
function normalizeCadence(cadence) {
|
|
198
|
+
if (!cadence || typeof cadence !== 'object') {
|
|
199
|
+
throw new ScheduledTaskValidationError('cadence is required', 'cadence')
|
|
200
|
+
}
|
|
201
|
+
if (!CADENCE_KINDS.has(cadence.kind)) {
|
|
202
|
+
throw new ScheduledTaskValidationError(`cadence.kind must be one of ${[...CADENCE_KINDS].join(', ')}`, 'cadence.kind')
|
|
203
|
+
}
|
|
204
|
+
switch (cadence.kind) {
|
|
205
|
+
case 'once': {
|
|
206
|
+
if (!Number.isFinite(cadence.at)) {
|
|
207
|
+
throw new ScheduledTaskValidationError('once cadence requires a numeric `at` (epoch ms)', 'cadence.at')
|
|
208
|
+
}
|
|
209
|
+
if (Math.abs(cadence.at) > MAX_EPOCH_MS) {
|
|
210
|
+
throw new ScheduledTaskValidationError(
|
|
211
|
+
`once cadence \`at\` must be a representable epoch-ms instant (|at| <= ${MAX_EPOCH_MS}); got ${cadence.at} — check for a microsecond/nanosecond timestamp`,
|
|
212
|
+
'cadence.at',
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
return { kind: 'once', at: cadence.at }
|
|
216
|
+
}
|
|
217
|
+
case 'interval': {
|
|
218
|
+
if (!Number.isFinite(cadence.everyMs) || cadence.everyMs < MIN_INTERVAL_MS) {
|
|
219
|
+
throw new ScheduledTaskValidationError(`interval cadence requires everyMs >= ${MIN_INTERVAL_MS}`, 'cadence.everyMs')
|
|
220
|
+
}
|
|
221
|
+
const out = { kind: 'interval', everyMs: Math.floor(cadence.everyMs) }
|
|
222
|
+
if (cadence.anchor !== undefined) {
|
|
223
|
+
if (!Number.isFinite(cadence.anchor)) {
|
|
224
|
+
throw new ScheduledTaskValidationError('interval cadence anchor must be numeric (epoch ms)', 'cadence.anchor')
|
|
225
|
+
}
|
|
226
|
+
// Same representable-instant bound as `once.at` — an anchor feeds
|
|
227
|
+
// nextRun, which the panel renders as a date.
|
|
228
|
+
if (Math.abs(cadence.anchor) > MAX_EPOCH_MS) {
|
|
229
|
+
throw new ScheduledTaskValidationError(
|
|
230
|
+
`interval cadence anchor must be a representable epoch-ms instant (|anchor| <= ${MAX_EPOCH_MS}); got ${cadence.anchor}`,
|
|
231
|
+
'cadence.anchor',
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
out.anchor = cadence.anchor
|
|
235
|
+
}
|
|
236
|
+
return out
|
|
237
|
+
}
|
|
238
|
+
case 'cron': {
|
|
239
|
+
if (typeof cadence.expression !== 'string') {
|
|
240
|
+
throw new ScheduledTaskValidationError('cron cadence requires a string `expression`', 'cadence.expression')
|
|
241
|
+
}
|
|
242
|
+
// Measure the TRIMMED form, because that is what gets stored and sent
|
|
243
|
+
// (see the return below) — padding must not count against the cap, and
|
|
244
|
+
// must not sneak past it either.
|
|
245
|
+
const expression = cadence.expression.trim()
|
|
246
|
+
// #7051: length BEFORE parse — a 300-char expression can be perfectly valid
|
|
247
|
+
// cron, so parseCron will happily accept a value the wire cannot carry.
|
|
248
|
+
if (expression.length > MAX_CRON_EXPRESSION_LENGTH) {
|
|
249
|
+
throw new ScheduledTaskValidationError(
|
|
250
|
+
`cron expression must be <= ${MAX_CRON_EXPRESSION_LENGTH} characters (got ${expression.length}) — ` +
|
|
251
|
+
'longer expressions cannot be carried on the wire and would make the whole scheduled-tasks snapshot unparseable',
|
|
252
|
+
'cadence.expression',
|
|
253
|
+
)
|
|
254
|
+
}
|
|
255
|
+
// parseCron throws CronParseError on a malformed field — re-surface it as a
|
|
256
|
+
// validation error so callers get one error type off add()/update().
|
|
257
|
+
try {
|
|
258
|
+
parseCron(expression)
|
|
259
|
+
} catch (err) {
|
|
260
|
+
throw new ScheduledTaskValidationError(`invalid cron expression: ${err.message}`, 'cadence.expression')
|
|
261
|
+
}
|
|
262
|
+
return { kind: 'cron', expression }
|
|
263
|
+
}
|
|
264
|
+
default:
|
|
265
|
+
// Unreachable — CADENCE_KINDS gates kind above.
|
|
266
|
+
throw new ScheduledTaskValidationError('unsupported cadence', 'cadence.kind')
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Normalize + validate a `lastRun` result stub. Optional; when present must be
|
|
272
|
+
* `{ at, status[, sessionId, error] }`. The engine (#6865) fills this after a
|
|
273
|
+
* run — the foundation just stores it. Throws on a malformed shape.
|
|
274
|
+
*/
|
|
275
|
+
function normalizeLastRun(lastRun) {
|
|
276
|
+
if (lastRun === undefined || lastRun === null) return null
|
|
277
|
+
if (typeof lastRun !== 'object') throw new ScheduledTaskValidationError('lastRun must be an object', 'lastRun')
|
|
278
|
+
if (!Number.isFinite(lastRun.at)) throw new ScheduledTaskValidationError('lastRun.at must be numeric (epoch ms)', 'lastRun.at')
|
|
279
|
+
if (!LAST_RUN_STATUSES.has(lastRun.status)) {
|
|
280
|
+
throw new ScheduledTaskValidationError(`lastRun.status must be one of ${[...LAST_RUN_STATUSES].join(', ')}`, 'lastRun.status')
|
|
281
|
+
}
|
|
282
|
+
const out = { at: lastRun.at, status: lastRun.status }
|
|
283
|
+
const sessionId = optionalString(lastRun.sessionId, 'lastRun.sessionId')
|
|
284
|
+
const error = optionalString(lastRun.error, 'lastRun.error')
|
|
285
|
+
if (sessionId !== undefined) out.sessionId = sessionId
|
|
286
|
+
if (error !== undefined) out.error = error
|
|
287
|
+
return out
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The scheduled-task data model (#6862). A standing, persisted schedule for a
|
|
292
|
+
* future/recurring agent run — explicitly SEPARATE from live session state and
|
|
293
|
+
* from `ScheduleWakeup` (transcript-tasks.js), which is an intra-session,
|
|
294
|
+
* single-shot self-resume. No firing here; that is the engine slice (#6865).
|
|
295
|
+
*
|
|
296
|
+
* Stored shape:
|
|
297
|
+
* {
|
|
298
|
+
* id: string, // stable uuid
|
|
299
|
+
* name: string | null, // optional human label
|
|
300
|
+
* enabled: boolean, // paused === !enabled
|
|
301
|
+
* prompt: string, // instructions the run executes
|
|
302
|
+
* target: { // session config the run is created with
|
|
303
|
+
* provider?, model?, cwd?, permissionMode?
|
|
304
|
+
* },
|
|
305
|
+
* cadence: // one-time vs recurring
|
|
306
|
+
* | { kind: 'once', at }
|
|
307
|
+
* | { kind: 'interval', everyMs, anchor? }
|
|
308
|
+
* | { kind: 'cron', expression },
|
|
309
|
+
* nextRun: number | null, // COMPUTED (never fired here), for display
|
|
310
|
+
* lastRun: { at, status, sessionId?, error? } | null, // engine fills this
|
|
311
|
+
* createdAt: number,
|
|
312
|
+
* updatedAt: number,
|
|
313
|
+
* }
|
|
314
|
+
*
|
|
315
|
+
* Persistence mirrors permission-rule-store.js exactly: a single JSON file (a
|
|
316
|
+
* sibling of session-state.json, e.g. ~/.chroxy/scheduled-tasks.json) written
|
|
317
|
+
* atomically (temp + rename via writeFileRestricted, mode 0600), version-gated,
|
|
318
|
+
* and fail-open-empty on a corrupt/unknown-version file. Loaded once on daemon
|
|
319
|
+
* start; keyed by task id.
|
|
320
|
+
*/
|
|
321
|
+
export class ScheduledTaskStore {
|
|
322
|
+
/**
|
|
323
|
+
* @param {object} options
|
|
324
|
+
* @param {string} options.filePath - Path to the scheduled-tasks JSON file.
|
|
325
|
+
* @param {object} [options.logger] - Optional logger (defaults to module logger).
|
|
326
|
+
* @param {() => number} [options.now] - Test seam for the clock.
|
|
327
|
+
*/
|
|
328
|
+
constructor({ filePath, logger, now } = {}) {
|
|
329
|
+
if (!filePath) throw new Error('ScheduledTaskStore requires a filePath')
|
|
330
|
+
this._filePath = filePath
|
|
331
|
+
this._log = logger || log
|
|
332
|
+
this._now = typeof now === 'function' ? now : Date.now
|
|
333
|
+
// id -> normalized task record
|
|
334
|
+
this._tasks = new Map()
|
|
335
|
+
// #7050 — raw entries the loader REFUSED, kept verbatim so `_persist()` cannot
|
|
336
|
+
// erase them. Shape: `{ raw, id, reason }`. These are never served as live
|
|
337
|
+
// tasks; they exist so an operator's unreadable task survives the next
|
|
338
|
+
// unrelated mutation instead of being silently deleted from disk.
|
|
339
|
+
this._unreadable = []
|
|
340
|
+
this._loaded = false
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Load tasks from disk, REPLACING any in-memory state — load() is a true
|
|
345
|
+
* snapshot of the file, so a second load() (or a load after the file was
|
|
346
|
+
* deleted or corrupted) can never keep stale in-memory tasks alive and
|
|
347
|
+
* re-persist them on the next write. A missing file is treated as an empty
|
|
348
|
+
* store; an unparseable / malformed / unknown-version file is logged and
|
|
349
|
+
* skipped whole (fail-open to "no scheduled tasks", never a partial read).
|
|
350
|
+
*
|
|
351
|
+
* Individual entries that fail normalization are dropped (logged) while valid
|
|
352
|
+
* siblings load — a single hand-edited bad task can't nuke the whole registry.
|
|
353
|
+
* `nextRun` is recomputed on load so a stored value can't drift from the
|
|
354
|
+
* cadence (and a disabled task always loads with nextRun null).
|
|
355
|
+
* @returns {this}
|
|
356
|
+
*/
|
|
357
|
+
load() {
|
|
358
|
+
this._loaded = true
|
|
359
|
+
// Reset FIRST — every early return below must leave the store EMPTY, not
|
|
360
|
+
// holding the previous load's (now unbacked) tasks.
|
|
361
|
+
this._tasks.clear()
|
|
362
|
+
// #7050: reset with `_tasks`, NOT after the early returns below. Every early
|
|
363
|
+
// return must leave the store EMPTY — a reload that hits ENOENT / bad JSON /
|
|
364
|
+
// the version gate would otherwise keep the PREVIOUS load's preserved entries
|
|
365
|
+
// and `_persist()` would write them back into a file that no longer has them,
|
|
366
|
+
// resurrecting records the operator deleted.
|
|
367
|
+
this._unreadable = []
|
|
368
|
+
let raw
|
|
369
|
+
try {
|
|
370
|
+
raw = fs.readFileSync(this._filePath, 'utf-8')
|
|
371
|
+
} catch (err) {
|
|
372
|
+
if (err && err.code !== 'ENOENT') {
|
|
373
|
+
this._log.warn(`Failed to read scheduled tasks at ${this._filePath}: ${err.message}`)
|
|
374
|
+
}
|
|
375
|
+
return this
|
|
376
|
+
}
|
|
377
|
+
let parsed
|
|
378
|
+
try {
|
|
379
|
+
parsed = JSON.parse(raw)
|
|
380
|
+
} catch (err) {
|
|
381
|
+
this._log.warn(`Failed to parse scheduled tasks at ${this._filePath}: ${err.message} — ignoring`)
|
|
382
|
+
return this
|
|
383
|
+
}
|
|
384
|
+
if (!parsed || typeof parsed !== 'object') return this
|
|
385
|
+
// Version gate: an unknown (future / hand-mangled) version is skipped WHOLE
|
|
386
|
+
// rather than partially read against the wrong shape assumptions.
|
|
387
|
+
if (parsed.version !== STORE_VERSION) {
|
|
388
|
+
this._log.warn(`Unsupported scheduled-tasks version ${JSON.stringify(parsed.version)} at ${this._filePath} (expected ${STORE_VERSION}) — ignoring`)
|
|
389
|
+
return this
|
|
390
|
+
}
|
|
391
|
+
const tasks = parsed.tasks
|
|
392
|
+
if (!Array.isArray(tasks)) return this
|
|
393
|
+
for (const [i, entry] of tasks.entries()) {
|
|
394
|
+
if (this._tasks.size >= MAX_TASKS) {
|
|
395
|
+
// #7050: the remainder is never even examined, so it would be erased on
|
|
396
|
+
// the next write. Preserve it verbatim — these are valid tasks losing a
|
|
397
|
+
// race with a cap, which is the least defensible thing to delete.
|
|
398
|
+
const rest = tasks.slice(i)
|
|
399
|
+
this._log.warn(`Scheduled-tasks file exceeds cap (${MAX_TASKS}) — ${rest.length} ${rest.length === 1 ? 'entry' : 'entries'} not loaded (preserved on disk)`)
|
|
400
|
+
for (const skipped of rest) this._preserveUnreadable(skipped, `store cap (${MAX_TASKS}) reached`)
|
|
401
|
+
break
|
|
402
|
+
}
|
|
403
|
+
let record
|
|
404
|
+
try {
|
|
405
|
+
record = this._normalizeStoredTask(entry)
|
|
406
|
+
} catch (err) {
|
|
407
|
+
this._log.warn(`Refusing malformed scheduled task on load (preserved on disk): ${err.message}`)
|
|
408
|
+
this._preserveUnreadable(entry, err.message)
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
411
|
+
if (this._tasks.has(record.id)) {
|
|
412
|
+
this._log.warn(`Dropping duplicate scheduled-task id ${record.id} on load`)
|
|
413
|
+
continue
|
|
414
|
+
}
|
|
415
|
+
this._tasks.set(record.id, record)
|
|
416
|
+
}
|
|
417
|
+
if (this._tasks.size > 0) this._log.info(`Loaded ${this._tasks.size} scheduled task(s)`)
|
|
418
|
+
return this
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Add a new task. Assigns a fresh id (or accepts a caller-supplied id that
|
|
423
|
+
* does not collide), timestamps it, and computes `nextRun`. Persists. Throws
|
|
424
|
+
* {@link ScheduledTaskValidationError} on invalid input.
|
|
425
|
+
* @param {object} input - `{ prompt, cadence, target?, enabled?, name?, id?, lastRun? }`
|
|
426
|
+
* @returns {object} the stored task (a copy)
|
|
427
|
+
*/
|
|
428
|
+
add(input) {
|
|
429
|
+
if (!input || typeof input !== 'object') {
|
|
430
|
+
throw new ScheduledTaskValidationError('task input is required', 'task')
|
|
431
|
+
}
|
|
432
|
+
if (this._tasks.size >= MAX_TASKS) {
|
|
433
|
+
throw new ScheduledTaskValidationError(`scheduled-task cap reached (${MAX_TASKS})`, 'task')
|
|
434
|
+
}
|
|
435
|
+
let id = input.id
|
|
436
|
+
if (id === undefined || id === null) {
|
|
437
|
+
id = randomUUID()
|
|
438
|
+
} else {
|
|
439
|
+
if (typeof id !== 'string' || id.trim().length === 0) {
|
|
440
|
+
throw new ScheduledTaskValidationError('id must be a non-empty string', 'id')
|
|
441
|
+
}
|
|
442
|
+
id = id.trim()
|
|
443
|
+
requireIdWithinWireCap(id)
|
|
444
|
+
// #7050: preserved (unreadable) ids count as taken. They are on disk, so
|
|
445
|
+
// reusing one would put two entries with the same id in the file.
|
|
446
|
+
if (this._tasks.has(id) || this._unreadable.some((u) => u.id === id)) {
|
|
447
|
+
throw new ScheduledTaskValidationError(`task id ${id} already exists`, 'id')
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const now = this._now()
|
|
452
|
+
const record = {
|
|
453
|
+
id,
|
|
454
|
+
name: optionalString(input.name, 'name') ?? null,
|
|
455
|
+
enabled: input.enabled === undefined ? true : Boolean(input.enabled),
|
|
456
|
+
prompt: this._requirePrompt(input.prompt),
|
|
457
|
+
target: normalizeTarget(input.target),
|
|
458
|
+
cadence: normalizeCadence(input.cadence),
|
|
459
|
+
nextRun: null,
|
|
460
|
+
lastRun: normalizeLastRun(input.lastRun),
|
|
461
|
+
createdAt: now,
|
|
462
|
+
updatedAt: now,
|
|
463
|
+
}
|
|
464
|
+
record.nextRun = computeNextRun(record, { from: now })
|
|
465
|
+
this._tasks.set(id, record)
|
|
466
|
+
this._persist()
|
|
467
|
+
return this._clone(record)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Return a task by id (a copy), or null when absent.
|
|
472
|
+
* @param {string} id
|
|
473
|
+
* @returns {object|null}
|
|
474
|
+
*/
|
|
475
|
+
get(id) {
|
|
476
|
+
const record = this._tasks.get(id)
|
|
477
|
+
return record ? this._clone(record) : null
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Snapshot of every task (copies), insertion order.
|
|
482
|
+
* @returns {object[]}
|
|
483
|
+
*/
|
|
484
|
+
list() {
|
|
485
|
+
return Array.from(this._tasks.values(), (r) => this._clone(r))
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Apply a partial patch to an existing task and persist. Recomputes `nextRun`
|
|
490
|
+
* (so a cadence/enabled change is reflected) and bumps `updatedAt`. The `id`
|
|
491
|
+
* and `createdAt` are immutable. Returns the updated task (a copy), or null
|
|
492
|
+
* when the id is unknown. Throws {@link ScheduledTaskValidationError} on an
|
|
493
|
+
* invalid patch value.
|
|
494
|
+
* @param {string} id
|
|
495
|
+
* @param {object} patch - any subset of `{ prompt, cadence, target, enabled, name, lastRun }`
|
|
496
|
+
* @returns {object|null}
|
|
497
|
+
*/
|
|
498
|
+
update(id, patch) {
|
|
499
|
+
const existing = this._tasks.get(id)
|
|
500
|
+
if (!existing) return null
|
|
501
|
+
if (!patch || typeof patch !== 'object') {
|
|
502
|
+
throw new ScheduledTaskValidationError('update patch is required', 'patch')
|
|
503
|
+
}
|
|
504
|
+
const next = { ...existing }
|
|
505
|
+
if ('prompt' in patch) next.prompt = this._requirePrompt(patch.prompt)
|
|
506
|
+
if ('cadence' in patch) next.cadence = normalizeCadence(patch.cadence)
|
|
507
|
+
if ('target' in patch) next.target = normalizeTarget(patch.target)
|
|
508
|
+
if ('enabled' in patch) next.enabled = Boolean(patch.enabled)
|
|
509
|
+
if ('name' in patch) next.name = optionalString(patch.name, 'name') ?? null
|
|
510
|
+
if ('lastRun' in patch) next.lastRun = normalizeLastRun(patch.lastRun)
|
|
511
|
+
next.updatedAt = this._now()
|
|
512
|
+
next.nextRun = computeNextRun(next, { from: next.updatedAt })
|
|
513
|
+
this._tasks.set(id, next)
|
|
514
|
+
this._persist()
|
|
515
|
+
return this._clone(next)
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Remove a task by id and persist. Returns true when a task was removed.
|
|
520
|
+
* @param {string} id
|
|
521
|
+
* @returns {boolean}
|
|
522
|
+
*/
|
|
523
|
+
remove(id) {
|
|
524
|
+
if (this._tasks.has(id)) {
|
|
525
|
+
this._tasks.delete(id)
|
|
526
|
+
this._persist()
|
|
527
|
+
return true
|
|
528
|
+
}
|
|
529
|
+
// #7050: a preserved (unreadable) entry must stay deletable — otherwise
|
|
530
|
+
// refusing to erase it would trade silent data loss for an undeletable
|
|
531
|
+
// record the operator has no way to clear.
|
|
532
|
+
//
|
|
533
|
+
// Guard the id: preserved entries with no usable id carry `id: null`, so a
|
|
534
|
+
// `remove(null)` (or any non-string) would match and delete ALL of them at
|
|
535
|
+
// once and report success. `listUnreadable()` publicly emits those null rows,
|
|
536
|
+
// so this is reachable the moment a caller forwards one back.
|
|
537
|
+
if (typeof id !== 'string' || id.length === 0) return false
|
|
538
|
+
const before = this._unreadable.length
|
|
539
|
+
this._unreadable = this._unreadable.filter((u) => u.id !== id)
|
|
540
|
+
if (this._unreadable.length === before) return false
|
|
541
|
+
this._persist()
|
|
542
|
+
return true
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* #7050 — how many stored entries the loader could not read. Non-zero means
|
|
547
|
+
* `list()` is SHORTER than what is on disk, which the panel should say out
|
|
548
|
+
* loud rather than rendering a silently short list.
|
|
549
|
+
* @returns {number}
|
|
550
|
+
*/
|
|
551
|
+
unreadableCount() {
|
|
552
|
+
return this._unreadable.length
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* #7050 — the refused entries' ids and reasons (never their raw contents, which
|
|
557
|
+
* may be any shape). `id` is null when the entry had no usable string id.
|
|
558
|
+
* @returns {{ id: string|null, reason: string }[]}
|
|
559
|
+
*/
|
|
560
|
+
listUnreadable() {
|
|
561
|
+
return this._unreadable.map(({ id, reason }) => ({ id, reason }))
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** @private — keep a refused raw entry so `_persist()` cannot erase it (#7050). */
|
|
565
|
+
_preserveUnreadable(raw, reason) {
|
|
566
|
+
const id = typeof raw?.id === 'string' && raw.id.trim().length > 0 ? raw.id.trim() : null
|
|
567
|
+
this._unreadable.push({ raw, id, reason: String(reason) })
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** @private — require a non-empty string prompt. */
|
|
571
|
+
_requirePrompt(prompt) {
|
|
572
|
+
if (typeof prompt !== 'string' || prompt.trim().length === 0) {
|
|
573
|
+
throw new ScheduledTaskValidationError('prompt is required (non-empty string)', 'prompt')
|
|
574
|
+
}
|
|
575
|
+
return prompt
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* @private — normalize an entry read from disk into a stored record, filling
|
|
580
|
+
* missing timestamps and recomputing nextRun. Throws on anything that can't be
|
|
581
|
+
* coerced into a valid task (the caller drops it, logging).
|
|
582
|
+
*/
|
|
583
|
+
_normalizeStoredTask(entry) {
|
|
584
|
+
if (!entry || typeof entry !== 'object') {
|
|
585
|
+
throw new ScheduledTaskValidationError('task entry must be an object', 'task')
|
|
586
|
+
}
|
|
587
|
+
if (typeof entry.id !== 'string' || entry.id.trim().length === 0) {
|
|
588
|
+
throw new ScheduledTaskValidationError('task id must be a non-empty string', 'id')
|
|
589
|
+
}
|
|
590
|
+
requireIdWithinWireCap(entry.id.trim())
|
|
591
|
+
const createdAt = Number.isFinite(entry.createdAt) ? entry.createdAt : this._now()
|
|
592
|
+
const updatedAt = Number.isFinite(entry.updatedAt) ? entry.updatedAt : createdAt
|
|
593
|
+
const record = {
|
|
594
|
+
id: entry.id.trim(),
|
|
595
|
+
name: optionalString(entry.name, 'name') ?? null,
|
|
596
|
+
enabled: entry.enabled === undefined ? true : Boolean(entry.enabled),
|
|
597
|
+
prompt: this._requirePrompt(entry.prompt),
|
|
598
|
+
target: normalizeTarget(entry.target),
|
|
599
|
+
cadence: normalizeCadence(entry.cadence),
|
|
600
|
+
nextRun: null,
|
|
601
|
+
lastRun: normalizeLastRun(entry.lastRun),
|
|
602
|
+
createdAt,
|
|
603
|
+
updatedAt,
|
|
604
|
+
}
|
|
605
|
+
// Recompute nextRun from the cadence rather than trusting the stored value,
|
|
606
|
+
// so a stale/hand-edited nextRun can never diverge from the schedule.
|
|
607
|
+
record.nextRun = computeNextRun(record, { from: this._now() })
|
|
608
|
+
return record
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** @private — deep-ish copy so callers can't mutate the in-memory record. */
|
|
612
|
+
_clone(record) {
|
|
613
|
+
return {
|
|
614
|
+
...record,
|
|
615
|
+
target: { ...record.target },
|
|
616
|
+
cadence: { ...record.cadence },
|
|
617
|
+
lastRun: record.lastRun ? { ...record.lastRun } : null,
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** @private — atomic write of the whole store. */
|
|
622
|
+
_persist() {
|
|
623
|
+
try {
|
|
624
|
+
const dir = dirname(this._filePath)
|
|
625
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
|
|
626
|
+
// #7050: the preserved raw entries ride along so an unrelated mutation
|
|
627
|
+
// cannot erase a task the loader merely could not READ. They are appended
|
|
628
|
+
// (never re-serialized from a normalized record) so nothing is lost in a
|
|
629
|
+
// round trip through a shape this version does not understand.
|
|
630
|
+
const state = {
|
|
631
|
+
version: STORE_VERSION,
|
|
632
|
+
tasks: [...this._tasks.values(), ...this._unreadable.map((u) => u.raw)],
|
|
633
|
+
}
|
|
634
|
+
writeFileRestricted(this._filePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
|
|
635
|
+
} catch (err) {
|
|
636
|
+
// Best-effort: a failed persist leaves the in-memory set intact for this
|
|
637
|
+
// process; the prior good file (if any) survives (atomic write). Surface
|
|
638
|
+
// it so an operator can see the schedule won't survive a restart.
|
|
639
|
+
this._log.error(`Failed to persist scheduled tasks to ${this._filePath}: ${err?.stack || err}`)
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Default on-disk path for the registry given the session-state file's dir — a
|
|
646
|
+
* sibling of session-state.json. Kept here so both session-manager wiring and a
|
|
647
|
+
* future CLI/engine resolve the same path.
|
|
648
|
+
* @param {string} stateFilePath
|
|
649
|
+
* @returns {string}
|
|
650
|
+
*/
|
|
651
|
+
export function defaultScheduledTasksPath(stateFilePath) {
|
|
652
|
+
return resolve(dirname(stateFilePath), 'scheduled-tasks.json')
|
|
653
|
+
}
|