dsh-taskbridge 1.3.2 → 1.4.1
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/CHANGELOG.md +23 -2
- package/README.md +19 -13
- package/bin/dsh-delegate-mcp.js +4 -0
- package/codex/dsh-taskbridge.toml +129 -24
- package/docs/INTRODUCTION.md +19 -15
- package/docs/INTRODUCTION.zh.md +38 -34
- package/docs/codex-integration.md +63 -20
- package/docs/plugin-market.md +1 -1
- package/docs/releases/1.4.0-token-benchmark.zh.md +40 -0
- package/docs/releases/1.4.0.zh.md +54 -0
- package/docs/releases/1.4.1.zh.md +59 -0
- package/docs/runtime-compatibility.md +17 -9
- package/docs/silent-wait.md +87 -10
- package/docs/taskbridge-upgrade.md +1 -1
- package/lib/client.js +305 -65
- package/package.json +7 -3
- package/src/client/api.js +326 -46
- package/src/client/index.jsx +226 -52
- package/src/codex/installer.js +39 -6
- package/src/config/defaults.js +12 -0
- package/src/config/settings.js +12 -10
- package/src/config/validate.js +26 -11
- package/src/http/execution-plane.js +179 -9
- package/src/http/respond.js +179 -175
- package/src/http/user-plane.js +5 -4
- package/src/index.d.ts +157 -3
- package/src/index.js +1 -1
- package/src/jobs/activity.js +1369 -1008
- package/src/jobs/diagnostics.js +15 -0
- package/src/jobs/engine.js +1029 -12
- package/src/jobs/history.js +152 -6
- package/src/jobs/review-note.js +63 -0
- package/src/mcp/server.js +345 -21
- package/src/mcp/wait.js +67 -10
package/src/jobs/engine.js
CHANGED
|
@@ -46,6 +46,12 @@
|
|
|
46
46
|
// an operator who cancelled did ask to stop, and reporting a timeout instead
|
|
47
47
|
// would misattribute the outcome.
|
|
48
48
|
//
|
|
49
|
+
// Phases. A phase is what the task is doing now, and every terminal branch publishes
|
|
50
|
+
// the phase matching the state it recorded (`failed`, `cancelled`,
|
|
51
|
+
// `awaiting-host-review`). `execute` is published only from the executor's own
|
|
52
|
+
// recognised event ({@link onExecutionEvent}): a pending native create is not
|
|
53
|
+
// execution, and no late event overwrites `awaiting-permission` or a terminal phase.
|
|
54
|
+
//
|
|
49
55
|
// Cleanup. Release of a lease, release of the concurrency slot and completion of a
|
|
50
56
|
// prepared tree all happen in {@link finalize}, which is idempotent and runs on
|
|
51
57
|
// every exit path — successful completion, cancellation, timeout, failure and an
|
|
@@ -76,6 +82,12 @@ import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
|
|
|
76
82
|
import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
|
|
77
83
|
import { captureBaseline, captureDiff } from '../workspace/audit.js';
|
|
78
84
|
import { LOCK_CODES, WorkspaceError, resolveWorkspacePath } from '../workspace/locks.js';
|
|
85
|
+
import {
|
|
86
|
+
REVIEW_NOTE_MAX_CHARS,
|
|
87
|
+
normalizeReviewNote,
|
|
88
|
+
reviewNoteLength,
|
|
89
|
+
reviewNoteOverflow,
|
|
90
|
+
} from './review-note.js';
|
|
79
91
|
|
|
80
92
|
/** Task lifecycle states. `awaiting-host-review` is terminal for this plugin. */
|
|
81
93
|
export const TASK_STATES = Object.freeze({
|
|
@@ -134,6 +146,16 @@ export const JOB_CODES = Object.freeze({
|
|
|
134
146
|
// still `running`; the PHASE says it is waiting for the commander's decision.
|
|
135
147
|
// `waitingForPermission` is not a terminal state and is not a failure.
|
|
136
148
|
permissionPending: 'JOB_PERMISSION_PENDING',
|
|
149
|
+
// Host review (delivery acceptance). These are refusals of the REVIEW verb, not new
|
|
150
|
+
// task states: the task keeps `awaiting-host-review` and its underlying outcome.
|
|
151
|
+
// * notReviewable: the task is not waiting for review (still running, failed,
|
|
152
|
+
// cancelled, interrupted, or already has a DIFFERENT recorded decision);
|
|
153
|
+
// * invalid: the decision/note did not pass the closed vocabulary or the bound;
|
|
154
|
+
// * notPersisted: the decision was made but could not be written to history, so the
|
|
155
|
+
// caller is TOLD it was not saved instead of being told it succeeded.
|
|
156
|
+
reviewNotReviewable: 'JOB_REVIEW_NOT_REVIEWABLE',
|
|
157
|
+
reviewInvalid: 'JOB_REVIEW_INVALID',
|
|
158
|
+
reviewNotPersisted: 'JOB_REVIEW_NOT_PERSISTED',
|
|
137
159
|
});
|
|
138
160
|
|
|
139
161
|
/** Default interval of the internal authorization sweep. */
|
|
@@ -181,6 +203,54 @@ const HISTORY_WRITE_TIMEOUT_MS = 5000;
|
|
|
181
203
|
/** Upper bound on retained task records; oldest terminal records go first. */
|
|
182
204
|
const MAX_RETAINED_TASKS = 256;
|
|
183
205
|
|
|
206
|
+
/**
|
|
207
|
+
* The closed vocabulary of host-review decisions.
|
|
208
|
+
*
|
|
209
|
+
* `accepted` is the host saying "I reviewed the delivered evidence and it is right".
|
|
210
|
+
* `changes-requested` is the same review with a different conclusion. Neither is a task
|
|
211
|
+
* state: the run stays `awaiting-host-review`, which is what keeps older clients and a
|
|
212
|
+
* later `continueFromTaskId` follow-up compatible.
|
|
213
|
+
*/
|
|
214
|
+
export const HOST_REVIEW_STATES = Object.freeze({
|
|
215
|
+
accepted: 'accepted',
|
|
216
|
+
changesRequested: 'changes-requested',
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
/** Bounds on a review note: non-empty for a decision, and never unbounded. */
|
|
220
|
+
const REVIEW_NOTE_MAX = REVIEW_NOTE_MAX_CHARS;
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Where a review decision is in its journey to durable storage.
|
|
224
|
+
*
|
|
225
|
+
* `saving` means "accepted for writing, durability not yet confirmed" — deliberately NOT
|
|
226
|
+
* acceptance: `hostAcceptance` stays null until the store has answered. `failed` is a
|
|
227
|
+
* settled failure a retry may leave. `timed-out` is UNCONFIRMED: the write is still in
|
|
228
|
+
* flight and may yet land, so it is neither failure nor success. A process restart holds
|
|
229
|
+
* no saving state; the disk is the only fact that outlives the process.
|
|
230
|
+
*/
|
|
231
|
+
export const REVIEW_PERSISTENCE_STATES = Object.freeze({
|
|
232
|
+
none: 'none',
|
|
233
|
+
saving: 'saving',
|
|
234
|
+
saved: 'saved',
|
|
235
|
+
failed: 'failed',
|
|
236
|
+
timedOut: 'timed-out',
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* How long ONE review request waits for its durable write.
|
|
241
|
+
*
|
|
242
|
+
* A bound on the REQUEST, never on the write: exceeding it answers "still saving" and
|
|
243
|
+
* leaves the write running, so a slow disk costs a deferred answer instead of a fabricated
|
|
244
|
+
* failure — and the late outcome is what the engine publishes afterwards.
|
|
245
|
+
*/
|
|
246
|
+
const REVIEW_WRITE_TIMEOUT_MS = HISTORY_WRITE_TIMEOUT_MS;
|
|
247
|
+
|
|
248
|
+
/** Returned by `raceOutcome` when its bound expired first. */
|
|
249
|
+
const REVIEW_OUTCOME_TIMEOUT = Symbol('review-write-timeout');
|
|
250
|
+
|
|
251
|
+
/** The fixed marker recorded as the reviewer, so a stored decision is not a free name. */
|
|
252
|
+
const HOST_REVIEW_BY = 'host-commander';
|
|
253
|
+
|
|
184
254
|
/**
|
|
185
255
|
* The phase a running task reports while a permission request is outstanding.
|
|
186
256
|
*
|
|
@@ -193,6 +263,25 @@ const MAX_RETAINED_TASKS = 256;
|
|
|
193
263
|
const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
|
|
194
264
|
const PHASE_EXECUTE = 'execute';
|
|
195
265
|
|
|
266
|
+
/**
|
|
267
|
+
* The phase a running task reports until its executor demonstrably does work.
|
|
268
|
+
*
|
|
269
|
+
* Every admission step has finished and the runner has been called, but a native
|
|
270
|
+
* create may still be pending (a placement is resolved through the controllers
|
|
271
|
+
* first), so this phase claims only "submitted", never "executing".
|
|
272
|
+
*/
|
|
273
|
+
const PHASE_BEFORE_CREATE = 'before-create';
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Session event types that prove the executor itself is working.
|
|
277
|
+
*
|
|
278
|
+
* The durable lifecycle types only: an opened turn, an opened model step and a
|
|
279
|
+
* native tool call/result cannot be produced by a pending create, whereas a
|
|
280
|
+
* streaming delta can arrive empty while a provider is still connecting.
|
|
281
|
+
* @type {ReadonlySet<string>}
|
|
282
|
+
*/
|
|
283
|
+
const EXECUTION_EVIDENCE_EVENTS = Object.freeze(new Set(['turn/start', 'step/start', 'tool/call', 'tool/result']));
|
|
284
|
+
|
|
196
285
|
/**
|
|
197
286
|
* The closed vocabulary of reasons one observation may report to a caller.
|
|
198
287
|
*
|
|
@@ -220,6 +309,17 @@ export const OBSERVE_TASK_REASONS = Object.freeze({
|
|
|
220
309
|
const OBSERVE_WAIT_MS = 25_000;
|
|
221
310
|
const OBSERVE_SLICE_MS = 1000;
|
|
222
311
|
|
|
312
|
+
/**
|
|
313
|
+
* How much of an observation's own bound is kept back when it waits for a review write.
|
|
314
|
+
*
|
|
315
|
+
* An observation must be answerable WITHIN the bound the caller asked for, so the wait for
|
|
316
|
+
* a still-running review write stops this much short of it and leaves room to build and
|
|
317
|
+
* return the answer. Without the margin a wait that used the whole budget would answer
|
|
318
|
+
* after its own deadline, which is exactly the kind of overrun the bounded observation was
|
|
319
|
+
* introduced to remove.
|
|
320
|
+
*/
|
|
321
|
+
const OBSERVE_REVIEW_SETTLE_MARGIN_MS = 250;
|
|
322
|
+
|
|
223
323
|
/** Raised for job-level refusals. */
|
|
224
324
|
export class JobError extends Error {
|
|
225
325
|
/**
|
|
@@ -293,6 +393,15 @@ export class JobEngine {
|
|
|
293
393
|
// Observers currently waiting, so disposal can release them without touching
|
|
294
394
|
// the workers they were only watching.
|
|
295
395
|
this.observers = new Set();
|
|
396
|
+
// One in-flight host-review write per task, plus the state of the last one, so two
|
|
397
|
+
// concurrent identical requests cannot both claim success before the durable write has
|
|
398
|
+
// landed — and so a write that outlived its request can still publish its outcome.
|
|
399
|
+
// Keyed by task id; see {@link beginReviewWrite} for the acceptance rule.
|
|
400
|
+
this.reviewState = new Map();
|
|
401
|
+
// Monotonic token for review writes. Not per task: a token is compared against the
|
|
402
|
+
// entry it belongs to, so a global counter is enough and cannot wrap into confusion
|
|
403
|
+
// with a task's own numbering.
|
|
404
|
+
this.reviewSeq = 0;
|
|
296
405
|
this.listen();
|
|
297
406
|
}
|
|
298
407
|
|
|
@@ -556,7 +665,8 @@ export class JobEngine {
|
|
|
556
665
|
cleanupError: null,
|
|
557
666
|
historyError: null,
|
|
558
667
|
historySavedAt: null,
|
|
559
|
-
// Host acceptance is never granted here; it is the host's own record
|
|
668
|
+
// Host acceptance is never granted here; it is the host's own record, and it is
|
|
669
|
+
// published only once the durable write has CONFIRMED it (see `recordHostReview`).
|
|
560
670
|
hostAcceptance: null,
|
|
561
671
|
settled,
|
|
562
672
|
settle: () => { settle(); },
|
|
@@ -2168,6 +2278,360 @@ export class JobEngine {
|
|
|
2168
2278
|
return { task: this.view(task), permission: settled, hostAcceptance: null };
|
|
2169
2279
|
}
|
|
2170
2280
|
|
|
2281
|
+
/**
|
|
2282
|
+
* Record the commander's delivery review for one finished task.
|
|
2283
|
+
*
|
|
2284
|
+
* This is the ONLY writer of a task's `hostAcceptance`, and it is deliberately the
|
|
2285
|
+
* narrowest write in the plugin. It does not decide a permission, change the switch,
|
|
2286
|
+
* a provider, a model, the isolation or a credential, merge a file, or create work:
|
|
2287
|
+
* it records "the host looked at what was delivered and concluded X" on a task whose
|
|
2288
|
+
* execution has already ended.
|
|
2289
|
+
*
|
|
2290
|
+
* The run's STATE is left `awaiting-host-review`. That is the compatibility anchor: an
|
|
2291
|
+
* older client keeps reading the same state, and `continueFromTaskId` keeps working.
|
|
2292
|
+
* The review conclusion lives in its own field.
|
|
2293
|
+
*
|
|
2294
|
+
* The chain of checks, all refusals:
|
|
2295
|
+
* 1. the task exists and belongs to the deciding connection (a foreign task answers
|
|
2296
|
+
* exactly like an unknown one);
|
|
2297
|
+
* 2. the decision and note pass the closed vocabulary and the bound;
|
|
2298
|
+
* 3. closing the delegation switch does not prevent reviewing an existing result;
|
|
2299
|
+
* 4. the task is actually waiting for review AND its native executor has settled, so
|
|
2300
|
+
* "still running" can never be recorded as reviewed;
|
|
2301
|
+
* 5. an existing decision is final: the SAME conclusion with the SAME note is an
|
|
2302
|
+
* idempotent no-op, and a DIFFERENT one is refused (a correction is a follow-up
|
|
2303
|
+
* task, not a rewrite of the record);
|
|
2304
|
+
* 6. only then is it stored — and the conclusion becomes visible ONLY once the durable
|
|
2305
|
+
* write has confirmed it.
|
|
2306
|
+
*
|
|
2307
|
+
* Step 6 is the persistence contract: the decision is NOT put in
|
|
2308
|
+
* `task.hostAcceptance` before the store answers, so an ordinary read never shows a
|
|
2309
|
+
* conclusion the disk does not have. The request waits at most
|
|
2310
|
+
* {@link REVIEW_WRITE_TIMEOUT_MS}; exceeding it is UNCONFIRMED, not failed — the write
|
|
2311
|
+
* keeps running, the answer reports `reviewPersistence.state === 'timed-out'` with no
|
|
2312
|
+
* decision, and the late outcome updates memory either way. Writes are serialized per
|
|
2313
|
+
* task, and every attempt carries a token so a stale write cannot land on a newer
|
|
2314
|
+
* conclusion.
|
|
2315
|
+
* @param {object} request - `taskId`, `decision`, `note`, and the authenticated
|
|
2316
|
+
* `connectionId` (from the plane, never from the caller's body). An optional integer
|
|
2317
|
+
* `waitMs` bounds how long THIS CALL waits for durability (0 = the engine default).
|
|
2318
|
+
* @returns {Promise<object>} `{ task, hostAcceptance, reviewPersistence }` where `task`
|
|
2319
|
+
* is the public view. `hostAcceptance` is non-null only for a confirmed decision.
|
|
2320
|
+
* @throws {JobError} on any refusal, and with `JOB_REVIEW_NOT_PERSISTED` once the write
|
|
2321
|
+
* has genuinely FAILED (a timeout throws nothing).
|
|
2322
|
+
*/
|
|
2323
|
+
async recordHostReview(request) {
|
|
2324
|
+
const connectionId = typeof request?.connectionId === 'string' ? request.connectionId : null;
|
|
2325
|
+
if (connectionId === null) {
|
|
2326
|
+
// No verified identity means no ownership proof: the same answer an unknown task gets.
|
|
2327
|
+
throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', {});
|
|
2328
|
+
}
|
|
2329
|
+
const taskId = typeof request?.taskId === 'string' ? request.taskId.trim() : '';
|
|
2330
|
+
if (taskId === '') {
|
|
2331
|
+
throw new JobError(JOB_CODES.reviewInvalid, 'taskId is required', { field: 'taskId' });
|
|
2332
|
+
}
|
|
2333
|
+
const { decision, note: rawNote } = reviewInput(request);
|
|
2334
|
+
|
|
2335
|
+
const task = this.tasks.get(taskId);
|
|
2336
|
+
if (task === undefined || task.connectionId !== connectionId) {
|
|
2337
|
+
throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
|
|
2338
|
+
}
|
|
2339
|
+
// NO posture gate here, deliberately. A review records a conclusion about a result
|
|
2340
|
+
// that already exists: it creates no work, releases no permission, issues no grant and
|
|
2341
|
+
// changes no setting. Like reading a task or cancelling it, it therefore stays
|
|
2342
|
+
// available after the operator closes the switch — you must still be able to review
|
|
2343
|
+
// what you already paid for. Starting a NEW task and answering a permission request
|
|
2344
|
+
// remain gated by the switch at their own entry points.
|
|
2345
|
+
// Only a finished execution can be reviewed. `awaiting-host-review` is the state the
|
|
2346
|
+
// engine records after a completed run, and `native.settled` is the second,
|
|
2347
|
+
// independent proof that the executor is gone: neither can be inferred by the caller.
|
|
2348
|
+
if (task.state !== TASK_STATES.awaitingHostReview || task.native?.settled !== true) {
|
|
2349
|
+
throw new JobError(JOB_CODES.reviewNotReviewable, 'this task is not awaiting host review', {
|
|
2350
|
+
taskId,
|
|
2351
|
+
state: task.state,
|
|
2352
|
+
phase: task.phase,
|
|
2353
|
+
});
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// The note is redacted through the same bounded redaction the rest of the projection
|
|
2357
|
+
// uses, so a stored conclusion cannot smuggle a credential into history or a view. It
|
|
2358
|
+
// is NOT cut here: the bound was already enforced above.
|
|
2359
|
+
const note = redactText(rawNote);
|
|
2360
|
+
const entry = this.beginReviewWrite(task, decision, note);
|
|
2361
|
+
return await this.awaitReviewWrite(task, entry, reviewWaitMs(request));
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
/**
|
|
2365
|
+
* Begin (or join) the durable write of one review decision. Only a write that is
|
|
2366
|
+
* genuinely IN FLIGHT locks the conclusion: `saving`/`timed-out` join the same
|
|
2367
|
+
* conclusion and refuse a different one; `failed` with no confirmed record frees the
|
|
2368
|
+
* conclusion for a new attempt; `saved` replays idempotently or refuses a conflict.
|
|
2369
|
+
* @param {object} task - task record (already proven reviewable and owned).
|
|
2370
|
+
* @param {string} decision - validated decision.
|
|
2371
|
+
* @param {string} note - normalized, redacted note.
|
|
2372
|
+
* @returns {object} the persistence entry this request must wait on.
|
|
2373
|
+
* @throws {JobError} when a different conclusion is recorded or already in flight.
|
|
2374
|
+
*/
|
|
2375
|
+
beginReviewWrite(task, decision, note) {
|
|
2376
|
+
if (this.history === null || this.history === undefined || typeof this.history.save !== 'function') {
|
|
2377
|
+
// `persistHistory` answers success for the missing-store posture, which would let a
|
|
2378
|
+
// review be claimed as saved when nothing was written, so this is refused up front.
|
|
2379
|
+
throw this.reviewNotPersisted(
|
|
2380
|
+
'no durable history store is configured, so the review decision was not recorded', task, null,
|
|
2381
|
+
);
|
|
2382
|
+
}
|
|
2383
|
+
const current = this.reviewState.get(task.taskId) ?? null;
|
|
2384
|
+
const recorded = task.hostAcceptance ?? null;
|
|
2385
|
+
|
|
2386
|
+
if (current !== null) {
|
|
2387
|
+
if (current.state === REVIEW_PERSISTENCE_STATES.saved) {
|
|
2388
|
+
return this.replayOrRefuse(task, recorded, decision, note);
|
|
2389
|
+
}
|
|
2390
|
+
if (current.state === REVIEW_PERSISTENCE_STATES.saving
|
|
2391
|
+
|| current.state === REVIEW_PERSISTENCE_STATES.timedOut) {
|
|
2392
|
+
if (current.decision === decision && current.note === note) return current;
|
|
2393
|
+
throw new JobError(JOB_CODES.reviewNotReviewable,
|
|
2394
|
+
'a different review decision is being recorded for this task; wait for it or send a follow-up task', {
|
|
2395
|
+
taskId: task.taskId,
|
|
2396
|
+
state: task.state,
|
|
2397
|
+
recorded: current.decision,
|
|
2398
|
+
requested: decision,
|
|
2399
|
+
persistence: current.state,
|
|
2400
|
+
});
|
|
2401
|
+
}
|
|
2402
|
+
// `failed`: nothing was recorded, so this is a genuine new attempt.
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
if (recorded !== null && recorded !== undefined) {
|
|
2406
|
+
return this.replayOrRefuse(task, recorded, decision, note);
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
const entry = {
|
|
2410
|
+
state: REVIEW_PERSISTENCE_STATES.saving,
|
|
2411
|
+
decision,
|
|
2412
|
+
note,
|
|
2413
|
+
token: (this.reviewSeq ?? 0) + 1,
|
|
2414
|
+
startedAt: this.clock(),
|
|
2415
|
+
confirmedAt: null,
|
|
2416
|
+
error: null,
|
|
2417
|
+
};
|
|
2418
|
+
this.reviewSeq = entry.token;
|
|
2419
|
+
this.reviewState.set(task.taskId, entry);
|
|
2420
|
+
// Started, deliberately not awaited: the request bounds how long IT waits, not how
|
|
2421
|
+
// long the write may take. A write still running when the request stops waiting must
|
|
2422
|
+
// be allowed to finish and publish its outcome.
|
|
2423
|
+
entry.done = this.writeReview(task, entry);
|
|
2424
|
+
entry.done.catch(() => undefined);
|
|
2425
|
+
return entry;
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
/**
|
|
2429
|
+
* Answer a request whose conclusion is already the recorded one, or refuse a conflict.
|
|
2430
|
+
* @param {object} task - task record.
|
|
2431
|
+
* @param {object} recorded - the recorded `hostAcceptance`.
|
|
2432
|
+
* @param {string} decision - requested decision.
|
|
2433
|
+
* @param {string} note - requested note.
|
|
2434
|
+
* @returns {object} the saved persistence entry.
|
|
2435
|
+
* @throws {JobError} on a different conclusion.
|
|
2436
|
+
*/
|
|
2437
|
+
replayOrRefuse(task, recorded, decision, note) {
|
|
2438
|
+
if (recorded !== null && recorded !== undefined
|
|
2439
|
+
&& recorded.state === decision && recorded.note === note) {
|
|
2440
|
+
return { state: REVIEW_PERSISTENCE_STATES.saved, decision, note, token: -1, done: Promise.resolve(true) };
|
|
2441
|
+
}
|
|
2442
|
+
throw new JobError(JOB_CODES.reviewNotReviewable,
|
|
2443
|
+
'this task already has a recorded review; send a follow-up task to record a correction', {
|
|
2444
|
+
taskId: task.taskId,
|
|
2445
|
+
state: task.state,
|
|
2446
|
+
recorded: recorded?.state ?? null,
|
|
2447
|
+
requested: decision,
|
|
2448
|
+
});
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
/**
|
|
2452
|
+
* Write one review decision to the durable store and publish its real outcome.
|
|
2453
|
+
*
|
|
2454
|
+
* Success publishes `task.hostAcceptance` and marks `saved` — this is the only place a
|
|
2455
|
+
* review becomes visible. Failure marks `failed`, records `historyError` and leaves
|
|
2456
|
+
* `hostAcceptance` null so a retry is legal. An outcome whose token is no longer current
|
|
2457
|
+
* is discarded: a stale write must never overwrite a newer conclusion.
|
|
2458
|
+
*
|
|
2459
|
+
* The view is snapshotted here WITH the decision, because the decision is not in memory
|
|
2460
|
+
* until the write lands: the durable record says exactly what the request said.
|
|
2461
|
+
* @param {object} task - task record.
|
|
2462
|
+
* @param {object} entry - the persistence entry being written.
|
|
2463
|
+
* @returns {Promise<boolean>} true when the decision is durable.
|
|
2464
|
+
*/
|
|
2465
|
+
async writeReview(task, entry) {
|
|
2466
|
+
let view;
|
|
2467
|
+
try {
|
|
2468
|
+
view = this.viewForReviewWrite(task, entry);
|
|
2469
|
+
await this.history.save(view);
|
|
2470
|
+
} catch (error) {
|
|
2471
|
+
this.settleReviewWrite(task, entry, false, {
|
|
2472
|
+
code: typeof error?.code === 'string' ? error.code : JOB_CODES.historyFailed,
|
|
2473
|
+
message: diagnostic(error?.message ?? error, 300),
|
|
2474
|
+
});
|
|
2475
|
+
return false;
|
|
2476
|
+
}
|
|
2477
|
+
this.settleReviewWrite(task, entry, true, null);
|
|
2478
|
+
return true;
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
/**
|
|
2482
|
+
* Publish (or discard) the outcome of one review write.
|
|
2483
|
+
* @param {object} task - task record.
|
|
2484
|
+
* @param {object} entry - persistence entry.
|
|
2485
|
+
* @param {boolean} ok - whether the decision is durable.
|
|
2486
|
+
* @param {object | null} error - bounded history error when not.
|
|
2487
|
+
* @returns {void}
|
|
2488
|
+
*/
|
|
2489
|
+
settleReviewWrite(task, entry, ok, error) {
|
|
2490
|
+
if (this.reviewState.get(task.taskId) !== entry) return;
|
|
2491
|
+
if (entry.state === REVIEW_PERSISTENCE_STATES.saved) return;
|
|
2492
|
+
if (ok) {
|
|
2493
|
+
task.hostAcceptance = {
|
|
2494
|
+
accepted: entry.decision === HOST_REVIEW_STATES.accepted,
|
|
2495
|
+
state: entry.decision,
|
|
2496
|
+
acceptedAt: entry.startedAt,
|
|
2497
|
+
by: HOST_REVIEW_BY,
|
|
2498
|
+
note: entry.note,
|
|
2499
|
+
};
|
|
2500
|
+
task.historyError = null;
|
|
2501
|
+
task.historySavedAt = this.clock();
|
|
2502
|
+
entry.state = REVIEW_PERSISTENCE_STATES.saved;
|
|
2503
|
+
entry.confirmedAt = this.clock();
|
|
2504
|
+
entry.error = null;
|
|
2505
|
+
return;
|
|
2506
|
+
}
|
|
2507
|
+
task.hostAcceptance = null;
|
|
2508
|
+
task.historyError = error;
|
|
2509
|
+
task.historySavedAt = null;
|
|
2510
|
+
entry.state = REVIEW_PERSISTENCE_STATES.failed;
|
|
2511
|
+
entry.error = error;
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
/**
|
|
2515
|
+
* Wait for one review write, boundedly, and answer honestly about where it got to.
|
|
2516
|
+
*
|
|
2517
|
+
* Exceeding the bound is NOT a failure: the write is still running and may yet land, so
|
|
2518
|
+
* the caller is answered `timed-out` with `pending: true` and no decision. Reporting a
|
|
2519
|
+
* timeout as `JOB_REVIEW_NOT_PERSISTED` is the defect this replaces.
|
|
2520
|
+
* @param {object} task - task record.
|
|
2521
|
+
* @param {object} entry - persistence entry being awaited.
|
|
2522
|
+
* @param {number} timeoutMs - wait bound in milliseconds (0 = engine default).
|
|
2523
|
+
* @returns {Promise<object>} `{ task, hostAcceptance, reviewPersistence }`, JSON-safe.
|
|
2524
|
+
* @throws {JobError} when the write has actually failed.
|
|
2525
|
+
*/
|
|
2526
|
+
async awaitReviewWrite(task, entry, timeoutMs) {
|
|
2527
|
+
if (entry.state !== REVIEW_PERSISTENCE_STATES.saved) {
|
|
2528
|
+
const bound = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : REVIEW_WRITE_TIMEOUT_MS;
|
|
2529
|
+
const outcome = await raceOutcome(entry.done, bound);
|
|
2530
|
+
if (outcome === REVIEW_OUTCOME_TIMEOUT
|
|
2531
|
+
&& this.reviewState.get(task.taskId) === entry
|
|
2532
|
+
&& entry.state === REVIEW_PERSISTENCE_STATES.saving) {
|
|
2533
|
+
entry.state = REVIEW_PERSISTENCE_STATES.timedOut;
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
if (entry.state === REVIEW_PERSISTENCE_STATES.saved) {
|
|
2537
|
+
const view = this.view(task);
|
|
2538
|
+
return { task: view, hostAcceptance: view.hostAcceptance, reviewPersistence: view.reviewPersistence };
|
|
2539
|
+
}
|
|
2540
|
+
if (entry.state === REVIEW_PERSISTENCE_STATES.timedOut) {
|
|
2541
|
+
const view = this.view(task);
|
|
2542
|
+
return { task: view, hostAcceptance: view.hostAcceptance, reviewPersistence: view.reviewPersistence };
|
|
2543
|
+
}
|
|
2544
|
+
throw this.reviewNotPersisted(
|
|
2545
|
+
'the review decision could not be written to history, so it was not recorded',
|
|
2546
|
+
task,
|
|
2547
|
+
entry.error ?? task.historyError ?? null,
|
|
2548
|
+
);
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2551
|
+
/**
|
|
2552
|
+
* The in-flight review write of one task, if any.
|
|
2553
|
+
*
|
|
2554
|
+
* In-process only: the public projection carries no promise (JSON cannot), so a wire
|
|
2555
|
+
* consumer reads `reviewPersistence` and re-reads the task.
|
|
2556
|
+
* @param {string} taskId - task id.
|
|
2557
|
+
* @returns {Promise<boolean> | null} the write's own promise, or null when none is running.
|
|
2558
|
+
*/
|
|
2559
|
+
reviewWriteDone(taskId) {
|
|
2560
|
+
const entry = this.reviewState.get(taskId) ?? null;
|
|
2561
|
+
if (entry === null || typeof entry.done?.then !== 'function') return null;
|
|
2562
|
+
if (entry.state !== REVIEW_PERSISTENCE_STATES.saving && entry.state !== REVIEW_PERSISTENCE_STATES.timedOut) return null;
|
|
2563
|
+
return entry.done;
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
/**
|
|
2567
|
+
* The refusal for a review that was not (and will not be) durable.
|
|
2568
|
+
* @param {string} message - explanation.
|
|
2569
|
+
* @param {object} task - task record.
|
|
2570
|
+
* @param {object | null} historyError - bounded history error.
|
|
2571
|
+
* @returns {JobError} the refusal, with the task's persistence state attached.
|
|
2572
|
+
*/
|
|
2573
|
+
reviewNotPersisted(message, task, historyError) {
|
|
2574
|
+
const view = this.view(task);
|
|
2575
|
+
return new JobError(JOB_CODES.reviewNotPersisted, message, {
|
|
2576
|
+
taskId: task.taskId,
|
|
2577
|
+
historyError,
|
|
2578
|
+
reviewPersistence: view.reviewPersistence,
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
|
|
2582
|
+
/**
|
|
2583
|
+
* The public record of where a task's review decision is in its write.
|
|
2584
|
+
*
|
|
2585
|
+
* `hostAcceptance` answers "what conclusion is recorded?"; this answers "is it durable
|
|
2586
|
+
* yet?". Both are JSON data only — no promise, no handle — so they survive a wire hop.
|
|
2587
|
+
* @param {object} task - task record.
|
|
2588
|
+
* @returns {object} bounded persistence block.
|
|
2589
|
+
*/
|
|
2590
|
+
reviewPersistenceView(task) {
|
|
2591
|
+
const entry = this.reviewState?.get(task.taskId) ?? null;
|
|
2592
|
+
const recorded = task.hostAcceptance ?? null;
|
|
2593
|
+
if (entry !== null) {
|
|
2594
|
+
const durable = entry.state === REVIEW_PERSISTENCE_STATES.saved;
|
|
2595
|
+
return {
|
|
2596
|
+
state: entry.state,
|
|
2597
|
+
decision: entry.decision,
|
|
2598
|
+
// Only a DURABLE decision can be acceptance, and only the document can say it is
|
|
2599
|
+
// durable: an in-flight entry never does.
|
|
2600
|
+
accepted: durable && recorded?.accepted === true && recorded?.state === entry.decision,
|
|
2601
|
+
durable,
|
|
2602
|
+
pending: entry.state === REVIEW_PERSISTENCE_STATES.saving || entry.state === REVIEW_PERSISTENCE_STATES.timedOut,
|
|
2603
|
+
startedAt: entry.startedAt ?? null,
|
|
2604
|
+
confirmedAt: entry.confirmedAt ?? null,
|
|
2605
|
+
retryable: entry.state === REVIEW_PERSISTENCE_STATES.failed,
|
|
2606
|
+
error: entry.error ?? null,
|
|
2607
|
+
};
|
|
2608
|
+
}
|
|
2609
|
+
if (recorded !== null && recorded !== undefined) {
|
|
2610
|
+
return {
|
|
2611
|
+
state: REVIEW_PERSISTENCE_STATES.saved,
|
|
2612
|
+
decision: recorded.state ?? null,
|
|
2613
|
+
accepted: recorded.accepted === true,
|
|
2614
|
+
durable: true,
|
|
2615
|
+
pending: false,
|
|
2616
|
+
startedAt: null,
|
|
2617
|
+
confirmedAt: recorded.acceptedAt ?? null,
|
|
2618
|
+
retryable: false,
|
|
2619
|
+
error: null,
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
return {
|
|
2623
|
+
state: REVIEW_PERSISTENCE_STATES.none,
|
|
2624
|
+
decision: null,
|
|
2625
|
+
accepted: false,
|
|
2626
|
+
durable: false,
|
|
2627
|
+
pending: false,
|
|
2628
|
+
startedAt: null,
|
|
2629
|
+
confirmedAt: null,
|
|
2630
|
+
retryable: false,
|
|
2631
|
+
error: null,
|
|
2632
|
+
};
|
|
2633
|
+
}
|
|
2634
|
+
|
|
2171
2635
|
/**
|
|
2172
2636
|
* Stop every outstanding request of one task and disarm its bridge.
|
|
2173
2637
|
*
|
|
@@ -2449,7 +2913,7 @@ export class JobEngine {
|
|
|
2449
2913
|
|
|
2450
2914
|
// The last gate before a native agent exists. Everything above awaited at
|
|
2451
2915
|
// least once; this re-check runs in the same step as the creation call.
|
|
2452
|
-
task.phase =
|
|
2916
|
+
task.phase = PHASE_BEFORE_CREATE;
|
|
2453
2917
|
this.assertLive(task, 'before-create');
|
|
2454
2918
|
|
|
2455
2919
|
// The native executor comes into existence here. `started` is recorded
|
|
@@ -2466,6 +2930,10 @@ export class JobEngine {
|
|
|
2466
2930
|
// the run keeps the fail-closed `never` stance and nothing about it changes.
|
|
2467
2931
|
const bridge = this.createPermissionBridge(task);
|
|
2468
2932
|
task.permission.bridge = bridge;
|
|
2933
|
+
// `started` means "this task called the runner", not "the executor is
|
|
2934
|
+
// running": placement resolves before the runner sees an Agent, so the task
|
|
2935
|
+
// is handed over in `before-create` and only the executor's own events
|
|
2936
|
+
// ({@link onExecutionEvent}) publish `execute`.
|
|
2469
2937
|
task.native.started = true;
|
|
2470
2938
|
const pending = runAgent(this.deps, {
|
|
2471
2939
|
prompt,
|
|
@@ -2511,7 +2979,8 @@ export class JobEngine {
|
|
|
2511
2979
|
// the event was progress, and (for a tool event) its name and call id.
|
|
2512
2980
|
// Reasoning text, assistant text and tool arguments are never retained or
|
|
2513
2981
|
// forwarded — there is no field in the summary they could travel in.
|
|
2514
|
-
|
|
2982
|
+
// This hook is also the only execution evidence the phase trusts.
|
|
2983
|
+
onEvent: (event) => { this.onExecutionEvent(task, event); },
|
|
2515
2984
|
});
|
|
2516
2985
|
task.native.promise = pending;
|
|
2517
2986
|
let run;
|
|
@@ -2574,12 +3043,16 @@ export class JobEngine {
|
|
|
2574
3043
|
}
|
|
2575
3044
|
if (run.outcome === RUN_OUTCOMES.timedOut) {
|
|
2576
3045
|
task.state = TASK_STATES.failed;
|
|
3046
|
+
task.phase = 'failed';
|
|
2577
3047
|
task.error = { code: JOB_CODES.timeout, message: 'the task exceeded its time budget' };
|
|
2578
3048
|
task.endedAt = Date.now();
|
|
2579
3049
|
return;
|
|
2580
3050
|
}
|
|
2581
3051
|
if (run.outcome !== RUN_OUTCOMES.completed) {
|
|
2582
3052
|
task.state = TASK_STATES.failed;
|
|
3053
|
+
// The phase states the same ending as the state, so a failed run never keeps
|
|
3054
|
+
// describing a creation or an execution.
|
|
3055
|
+
task.phase = 'failed';
|
|
2583
3056
|
// Three endings that are not completion, kept apart because they need
|
|
2584
3057
|
// different fixes:
|
|
2585
3058
|
// * the model was stopped by its own output budget (`max-tokens`) — raise
|
|
@@ -2694,6 +3167,7 @@ export class JobEngine {
|
|
|
2694
3167
|
waitSliceMs: this.observeSliceMs,
|
|
2695
3168
|
selfCheckSeconds: monitoring?.selfCheckSeconds ?? MONITORING_DEFAULTS.selfCheckSeconds,
|
|
2696
3169
|
attentionSeconds: monitoring?.attentionSeconds ?? MONITORING_DEFAULTS.attentionSeconds,
|
|
3170
|
+
repeatFailureThreshold: monitoring?.repeatFailureThreshold ?? MONITORING_DEFAULTS.repeatFailureThreshold,
|
|
2697
3171
|
log: (message, detail) => this.deps?.logger?.warn?.(message, detail),
|
|
2698
3172
|
});
|
|
2699
3173
|
}
|
|
@@ -2755,6 +3229,26 @@ export class JobEngine {
|
|
|
2755
3229
|
return LIVE.has(task.state) && monitor.activity.tool !== null;
|
|
2756
3230
|
}
|
|
2757
3231
|
|
|
3232
|
+
/**
|
|
3233
|
+
* Feed one native executor event to the run's monitor and, on real evidence that
|
|
3234
|
+
* the executor is working, publish `execute`.
|
|
3235
|
+
*
|
|
3236
|
+
* Only a live task still at {@link PHASE_BEFORE_CREATE} advances, so a late event
|
|
3237
|
+
* can never overwrite `awaiting-permission`, `review`, a terminal phase or a
|
|
3238
|
+
* `pending` task.
|
|
3239
|
+
* @param {object} task - running task record.
|
|
3240
|
+
* @param {unknown} event - native event dispatched by the runner.
|
|
3241
|
+
* @returns {void}
|
|
3242
|
+
*/
|
|
3243
|
+
onExecutionEvent(task, event) {
|
|
3244
|
+
task.monitor?.onEvent(event, this.clock());
|
|
3245
|
+
if (task.state === TASK_STATES.running
|
|
3246
|
+
&& task.phase === PHASE_BEFORE_CREATE
|
|
3247
|
+
&& EXECUTION_EVIDENCE_EVENTS.has(event?.type)) {
|
|
3248
|
+
task.phase = PHASE_EXECUTE;
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
|
|
2758
3252
|
/**
|
|
2759
3253
|
* The bounded, publishable activity block of one task view.
|
|
2760
3254
|
*
|
|
@@ -2814,8 +3308,11 @@ export class JobEngine {
|
|
|
2814
3308
|
* observer of the same task.
|
|
2815
3309
|
* @param {string} taskId - task to observe.
|
|
2816
3310
|
* @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000), `signal`.
|
|
2817
|
-
* @returns {Promise<{ task: object, reason: string, permission: object | null,
|
|
3311
|
+
* @returns {Promise<{ task: object, reason: string, permission: object | null,
|
|
3312
|
+
* failure: object | null, activity: object | null,
|
|
2818
3313
|
* selfCheck: object | null, wait: { waitMs: number, waitedMs: number, activitySinceWait: boolean } }>} observation.
|
|
3314
|
+
* `failure` is present only when `attention` reports a repeated-tool-failure
|
|
3315
|
+
* reminder; it carries a tool name, a failure code, an operation digest and counts.
|
|
2819
3316
|
* @throws {JobError} `JOB_TASK_NOT_FOUND` for an unknown or foreign task.
|
|
2820
3317
|
*/
|
|
2821
3318
|
async observeTask(taskId, options = {}) {
|
|
@@ -2837,6 +3334,13 @@ export class JobEngine {
|
|
|
2837
3334
|
// outstanding permission request, which is decidable right now.
|
|
2838
3335
|
const immediate = this.settleReason(task);
|
|
2839
3336
|
if (immediate !== null) {
|
|
3337
|
+
// Except for one thing a settled run can still change: its review decision may be
|
|
3338
|
+
// mid-write. Waiting for that write is what lets a caller who lost the answer to a
|
|
3339
|
+
// timed-out review learn the outcome here, instead of re-sending a decision (or
|
|
3340
|
+
// believing the review vanished). The wait is bounded and the report is honest
|
|
3341
|
+
// either way; nothing about the task's state is touched.
|
|
3342
|
+
const settledObservation = await this.awaitReviewSettlement(task, waitMs, signal);
|
|
3343
|
+
if (settledObservation !== null) return settledObservation;
|
|
2840
3344
|
return this.observationOf(task, immediate, monitor, waitMs, 0, false);
|
|
2841
3345
|
}
|
|
2842
3346
|
|
|
@@ -2854,7 +3358,41 @@ export class JobEngine {
|
|
|
2854
3358
|
// request beats a silence report. `heartbeat` is the only reason that yields.
|
|
2855
3359
|
const settled = this.settleReason(task);
|
|
2856
3360
|
if (settled !== null) reason = settled;
|
|
2857
|
-
|
|
3361
|
+
// A reminder superseded by a terminal state or a pending request above is dropped:
|
|
3362
|
+
// those outrank it, and a failure report must not describe a task that now needs a
|
|
3363
|
+
// different decision.
|
|
3364
|
+
const failure = reason === OBSERVE_TASK_REASONS.attention ? (outcome.failure ?? null) : null;
|
|
3365
|
+
return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure);
|
|
3366
|
+
}
|
|
3367
|
+
|
|
3368
|
+
/**
|
|
3369
|
+
* Wait — boundedly — for a task's in-flight review write to settle.
|
|
3370
|
+
*
|
|
3371
|
+
* Only an UNCONFIRMED write is waited for: a saved decision is already visible in the
|
|
3372
|
+
* ordinary observation, and no write at all is the ordinary case. This never changes the
|
|
3373
|
+
* task's state and never decides anything; it only delays the answer so that a caller
|
|
3374
|
+
* who lost the reply to a slow review can still find out what happened.
|
|
3375
|
+
* @param {object} task - task record.
|
|
3376
|
+
* @param {number} waitMs - the caller's own wait bound.
|
|
3377
|
+
* @param {AbortSignal | null} signal - the caller's cancellation.
|
|
3378
|
+
* @returns {Promise<object | null>} an observation when the wait changed the answer, else null.
|
|
3379
|
+
*/
|
|
3380
|
+
async awaitReviewSettlement(task, waitMs, signal) {
|
|
3381
|
+
const entry = this.reviewState.get(task.taskId) ?? null;
|
|
3382
|
+
if (entry === null) return null;
|
|
3383
|
+
if (entry.state !== REVIEW_PERSISTENCE_STATES.saving && entry.state !== REVIEW_PERSISTENCE_STATES.timedOut) return null;
|
|
3384
|
+
if (entry.done === undefined) return null;
|
|
3385
|
+
const bound = Math.max(0, waitMs - OBSERVE_REVIEW_SETTLE_MARGIN_MS);
|
|
3386
|
+
if (bound === 0) return null;
|
|
3387
|
+
const started = this.clock();
|
|
3388
|
+
const outcome = await raceOutcome(entry.done, bound, signal);
|
|
3389
|
+
if (outcome === REVIEW_OUTCOME_TIMEOUT) return null;
|
|
3390
|
+
if (signal !== null && signal.aborted === true) return null;
|
|
3391
|
+
// The write settled inside the wait: report the resulting fact (confirmed or failed)
|
|
3392
|
+
// together with how long it took, without re-deriving the task's state.
|
|
3393
|
+
const reason = this.settleReason(task) ?? OBSERVE_TASK_REASONS.attention;
|
|
3394
|
+
const waitedMs = Math.max(0, this.clock() - started);
|
|
3395
|
+
return this.observationOf(task, reason, this.ensureMonitor(task), waitMs, waitedMs, true, null);
|
|
2858
3396
|
}
|
|
2859
3397
|
|
|
2860
3398
|
/**
|
|
@@ -2949,9 +3487,11 @@ export class JobEngine {
|
|
|
2949
3487
|
* @param {number} waitMs - the bound that applied.
|
|
2950
3488
|
* @param {number} waitedMs - how long the wait actually took.
|
|
2951
3489
|
* @param {boolean} activitySinceWait - whether activity arrived during the wait.
|
|
3490
|
+
* @param {object | null} [failure] - the repeated-failure diagnostic, when that is
|
|
3491
|
+
* what ended the wait.
|
|
2952
3492
|
* @returns {object} observation result.
|
|
2953
3493
|
*/
|
|
2954
|
-
observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait) {
|
|
3494
|
+
observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null) {
|
|
2955
3495
|
const at = this.clock();
|
|
2956
3496
|
const summary = this.observationSummary(task, at);
|
|
2957
3497
|
const pending = task?.permission?.pending ?? null;
|
|
@@ -2962,6 +3502,10 @@ export class JobEngine {
|
|
|
2962
3502
|
reason,
|
|
2963
3503
|
// The full, unshortened redacted request on the ONE reason that needs it.
|
|
2964
3504
|
permission: reason === OBSERVE_TASK_REASONS.permission ? pending : null,
|
|
3505
|
+
// The typed, bounded diagnostic for a repeated-failure reminder. It is the only
|
|
3506
|
+
// thing that distinguishes that reminder from an ordinary silence report, whose
|
|
3507
|
+
// own diagnostic is `selfCheck`.
|
|
3508
|
+
failure: reason === OBSERVE_TASK_REASONS.attention && failure !== null ? failure : null,
|
|
2965
3509
|
activity: summary.activity,
|
|
2966
3510
|
selfCheck,
|
|
2967
3511
|
wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
|
|
@@ -3007,9 +3551,18 @@ export class JobEngine {
|
|
|
3007
3551
|
// finished run is described as having used.
|
|
3008
3552
|
route: this.observationRoute(task),
|
|
3009
3553
|
connectionId: task.connectionId ?? null,
|
|
3010
|
-
// Stated so no consumer reads `awaiting-host-review` as acceptance
|
|
3554
|
+
// Stated so no consumer reads `awaiting-host-review` as acceptance by itself; the
|
|
3555
|
+
// recorded review, when one exists, is reported separately below.
|
|
3011
3556
|
selfApproved: false,
|
|
3012
|
-
|
|
3557
|
+
// The commander's own decision, or null when none has been RECORDED YET. Never
|
|
3558
|
+
// derived from the task state: a completed run is not an accepted one, and a
|
|
3559
|
+
// decision that is still being written is not accepted either. The note BODY is not
|
|
3560
|
+
// carried on a wait (R5): its state, time and length are, plus `noteOmitted`, so the
|
|
3561
|
+
// summary stays short without letting an old client read a missing body as "none".
|
|
3562
|
+
hostAcceptance: summarizedAcceptance(task.hostAcceptance ?? null),
|
|
3563
|
+
// Where that decision is in its durable write, so a waiting host can tell "not
|
|
3564
|
+
// reviewed" from "the review is being written right now" and does not resubmit one.
|
|
3565
|
+
reviewPersistence: this.reviewPersistenceView(task),
|
|
3013
3566
|
};
|
|
3014
3567
|
}
|
|
3015
3568
|
|
|
@@ -3029,6 +3582,7 @@ export class JobEngine {
|
|
|
3029
3582
|
monitoring: {
|
|
3030
3583
|
selfCheckSeconds: task.effective.monitoring?.selfCheckSeconds ?? null,
|
|
3031
3584
|
attentionSeconds: task.effective.monitoring?.attentionSeconds ?? null,
|
|
3585
|
+
repeatFailureThreshold: task.effective.monitoring?.repeatFailureThreshold ?? null,
|
|
3032
3586
|
},
|
|
3033
3587
|
};
|
|
3034
3588
|
}
|
|
@@ -3043,7 +3597,9 @@ export class JobEngine {
|
|
|
3043
3597
|
* @returns {Promise<void>} resolves after bookkeeping.
|
|
3044
3598
|
*/
|
|
3045
3599
|
async finishTask(task) {
|
|
3046
|
-
|
|
3600
|
+
// `hostAcceptance` is NOT reset here. This path runs when a run ends, and a review
|
|
3601
|
+
// can only be recorded after that — but a terminal task that somehow reaches this
|
|
3602
|
+
// method again must not lose a decision the host already recorded.
|
|
3047
3603
|
this.clearPreflightDeadline(task);
|
|
3048
3604
|
// The run is over, so its answerer must go: an outstanding request is released
|
|
3049
3605
|
// (the worker's paused tool call resumes `unavailable`) and the bridge can never
|
|
@@ -3054,10 +3610,68 @@ export class JobEngine {
|
|
|
3054
3610
|
// task, so the stored view still says how much activity there was.
|
|
3055
3611
|
this.releaseMonitor(task);
|
|
3056
3612
|
await this.finalize(task);
|
|
3057
|
-
await this.
|
|
3613
|
+
await this.persistTerminalRecord(task);
|
|
3058
3614
|
task.settle();
|
|
3059
3615
|
}
|
|
3060
3616
|
|
|
3617
|
+
/**
|
|
3618
|
+
* Store a terminal task's record without ever erasing a review.
|
|
3619
|
+
*
|
|
3620
|
+
* A review can be recorded while `finalize` is still waiting for the executor to confirm
|
|
3621
|
+
* it stopped, so the two writes can overlap. The rule is order, not a race:
|
|
3622
|
+
*
|
|
3623
|
+
* * a write already IN FLIGHT (`saving`/`timed-out`) is awaited first, so the terminal
|
|
3624
|
+
* snapshot can never be queued behind it and then overwrite its result;
|
|
3625
|
+
* * a `saved` decision is the newest fact, so the older terminal snapshot is skipped —
|
|
3626
|
+
* writing it would erase the conclusion with a view that predates it;
|
|
3627
|
+
* * a confirmed decision already on disk is carried into the new snapshot through
|
|
3628
|
+
* `history.update`, which patches the CURRENT row instead of trusting a stale copy;
|
|
3629
|
+
* * anything else (a settled failure, or no review at all) is a normal snapshot.
|
|
3630
|
+
* @param {object} task - terminal task record.
|
|
3631
|
+
* @returns {Promise<void>} resolves after the attempt, never rejects.
|
|
3632
|
+
*/
|
|
3633
|
+
async persistTerminalRecord(task) {
|
|
3634
|
+
const entry = this.reviewState.get(task.taskId) ?? null;
|
|
3635
|
+
if (entry !== null && (entry.state === REVIEW_PERSISTENCE_STATES.saving || entry.state === REVIEW_PERSISTENCE_STATES.timedOut)) {
|
|
3636
|
+
await raceOutcome(entry.done, HISTORY_WRITE_TIMEOUT_MS);
|
|
3637
|
+
}
|
|
3638
|
+
const current = this.reviewState.get(task.taskId) ?? null;
|
|
3639
|
+
// A conclusion confirmed in this process — or one already on disk from an earlier
|
|
3640
|
+
// process — is the newest fact; the terminal snapshot must not replace it.
|
|
3641
|
+
if (current !== null && current.state === REVIEW_PERSISTENCE_STATES.saved) return;
|
|
3642
|
+
const stored = await this.confirmedAcceptanceOnDisk(task.taskId).catch(() => null);
|
|
3643
|
+
if (stored !== null) {
|
|
3644
|
+
const view = this.view(task);
|
|
3645
|
+
view.hostAcceptance = stored;
|
|
3646
|
+
if (this.history !== null && typeof this.history.update === 'function') {
|
|
3647
|
+
try {
|
|
3648
|
+
await this.history.update(task.taskId, (row) => {
|
|
3649
|
+
const next = { ...view };
|
|
3650
|
+
next.hostAcceptance = row?.hostAcceptance ?? stored;
|
|
3651
|
+
return next;
|
|
3652
|
+
});
|
|
3653
|
+
return;
|
|
3654
|
+
} catch {
|
|
3655
|
+
// fall through to the ordinary bounded write below
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
await this.persistHistory(task);
|
|
3660
|
+
}
|
|
3661
|
+
|
|
3662
|
+
/**
|
|
3663
|
+
* The confirmed review already stored for a task, if any.
|
|
3664
|
+
* @param {string} taskId - task id.
|
|
3665
|
+
* @returns {Promise<object | null>} the stored acceptance, or null.
|
|
3666
|
+
*/
|
|
3667
|
+
async confirmedAcceptanceOnDisk(taskId) {
|
|
3668
|
+
const history = this.history;
|
|
3669
|
+
if (history === null || typeof history.load !== 'function') return null;
|
|
3670
|
+
const rows = await history.load();
|
|
3671
|
+
const row = Array.isArray(rows) ? rows.find((entry) => entry?.taskId === taskId) : undefined;
|
|
3672
|
+
return row?.hostAcceptance ?? null;
|
|
3673
|
+
}
|
|
3674
|
+
|
|
3061
3675
|
/**
|
|
3062
3676
|
* Persist one terminal task's public view to the durable history store.
|
|
3063
3677
|
*
|
|
@@ -3073,11 +3687,12 @@ export class JobEngine {
|
|
|
3073
3687
|
* supported posture (the engine never reads history back to decide
|
|
3074
3688
|
* anything), so `history === null` is silent while a *failing* store is loud.
|
|
3075
3689
|
* @param {object} task - terminal task record.
|
|
3076
|
-
* @returns {Promise<
|
|
3690
|
+
* @returns {Promise<boolean>} true when the record is durable (or history is absent),
|
|
3691
|
+
* false when the write failed; never rejects.
|
|
3077
3692
|
*/
|
|
3078
3693
|
async persistHistory(task) {
|
|
3079
3694
|
const history = this.history;
|
|
3080
|
-
if (history === null || history === undefined || typeof history.save !== 'function') return;
|
|
3695
|
+
if (history === null || history === undefined || typeof history.save !== 'function') return true;
|
|
3081
3696
|
let timer = null;
|
|
3082
3697
|
try {
|
|
3083
3698
|
const view = this.view(task);
|
|
@@ -3094,6 +3709,7 @@ export class JobEngine {
|
|
|
3094
3709
|
await bounded;
|
|
3095
3710
|
task.historyError = null;
|
|
3096
3711
|
task.historySavedAt = Date.now();
|
|
3712
|
+
return true;
|
|
3097
3713
|
} catch (error) {
|
|
3098
3714
|
// Recorded, not thrown: a history failure must not turn a completed task
|
|
3099
3715
|
// into a failed one, and it must not escape into the release path.
|
|
@@ -3102,11 +3718,320 @@ export class JobEngine {
|
|
|
3102
3718
|
message: diagnostic(error?.message ?? error, 300),
|
|
3103
3719
|
};
|
|
3104
3720
|
task.historySavedAt = null;
|
|
3721
|
+
return false;
|
|
3105
3722
|
} finally {
|
|
3106
3723
|
if (timer !== null) clearTimeout(timer);
|
|
3107
3724
|
}
|
|
3108
3725
|
}
|
|
3109
3726
|
|
|
3727
|
+
/**
|
|
3728
|
+
* Build the public view one review write should store.
|
|
3729
|
+
*
|
|
3730
|
+
* The decision is not in memory yet — that is the whole point of the contract — so the
|
|
3731
|
+
* stored view is the task's own projection with THIS decision filled in. It therefore
|
|
3732
|
+
* inherits every redaction and every bound the projection applies, and the durable
|
|
3733
|
+
* record says exactly what the request said rather than what memory happens to hold.
|
|
3734
|
+
* @param {object} task - task record.
|
|
3735
|
+
* @param {object} entry - the persistence entry being written.
|
|
3736
|
+
* @returns {object} public view carrying the decision under review.
|
|
3737
|
+
*/
|
|
3738
|
+
viewForReviewWrite(task, entry) {
|
|
3739
|
+
const view = this.view(task);
|
|
3740
|
+
view.hostAcceptance = {
|
|
3741
|
+
accepted: entry.decision === HOST_REVIEW_STATES.accepted,
|
|
3742
|
+
state: entry.decision,
|
|
3743
|
+
acceptedAt: entry.startedAt,
|
|
3744
|
+
by: HOST_REVIEW_BY,
|
|
3745
|
+
note: entry.note,
|
|
3746
|
+
};
|
|
3747
|
+
return view;
|
|
3748
|
+
}
|
|
3749
|
+
|
|
3750
|
+
/**
|
|
3751
|
+
* Read one task's stored row for a caller that proved ownership.
|
|
3752
|
+
*
|
|
3753
|
+
* This is the R1 seam: after a restart the in-memory map is empty, but a finished task's
|
|
3754
|
+
* result is still on disk. The row is a durable RECORD, never a runnable task — no
|
|
3755
|
+
* native handle, grant or permission is reconstructed from it, and nothing is put back
|
|
3756
|
+
* into `this.tasks`.
|
|
3757
|
+
* @param {string} taskId - caller-supplied id.
|
|
3758
|
+
* @param {string} connectionId - the caller's verified connection identity.
|
|
3759
|
+
* @returns {Promise<object | null>} the stored row, or null when this caller cannot prove it.
|
|
3760
|
+
*/
|
|
3761
|
+
async storedTaskRow(taskId, connectionId) {
|
|
3762
|
+
const history = this.history;
|
|
3763
|
+
if (history === null || history === undefined || typeof history.load !== 'function') return null;
|
|
3764
|
+
const requested = typeof taskId === 'string' ? taskId.trim() : '';
|
|
3765
|
+
const caller = typeof connectionId === 'string' && connectionId !== '' ? connectionId : null;
|
|
3766
|
+
if (requested === '' || caller === null) return null;
|
|
3767
|
+
let rows;
|
|
3768
|
+
try {
|
|
3769
|
+
rows = await history.load();
|
|
3770
|
+
} catch (error) {
|
|
3771
|
+
// An unreadable document is not evidence about any one task, so it is reported as an
|
|
3772
|
+
// upstream failure rather than "no such task" (which would claim the task never existed).
|
|
3773
|
+
throw new JobError(JOB_CODES.historyFailed, 'the stored task history could not be read', {
|
|
3774
|
+
code: typeof error?.code === 'string' ? error.code : 'HISTORY_UNREADABLE',
|
|
3775
|
+
});
|
|
3776
|
+
}
|
|
3777
|
+
const row = Array.isArray(rows) ? rows.find((entry) => entry?.taskId === requested) : undefined;
|
|
3778
|
+
// A row with no owner recorded is NOT readable by anyone: there is no identity that can
|
|
3779
|
+
// prove it, and answering it differently from an unknown id would confirm that it exists.
|
|
3780
|
+
if (row === undefined || typeof row.connectionId !== 'string' || row.connectionId === ''
|
|
3781
|
+
|| row.connectionId !== caller) return null;
|
|
3782
|
+
return row;
|
|
3783
|
+
}
|
|
3784
|
+
|
|
3785
|
+
/**
|
|
3786
|
+
* The public view of a stored row, with the evidence it no longer has stated.
|
|
3787
|
+
*
|
|
3788
|
+
* `truncation` from the document is kept (it says what was cut on the way to disk) and
|
|
3789
|
+
* `evidence` states that this is history: which blocks are absent, whether the stored
|
|
3790
|
+
* diff was already truncated, and — crucially — that a stored row is NOT an acceptance.
|
|
3791
|
+
* `reviewPersistence` is the SAME projection a live task uses, so an in-flight, timed-out
|
|
3792
|
+
* or failed review started in this process is visible through a restored task too; a
|
|
3793
|
+
* confirmed conclusion comes from the document, never from memory.
|
|
3794
|
+
* @param {object} row - stored history row.
|
|
3795
|
+
* @returns {object} redacted public view.
|
|
3796
|
+
*/
|
|
3797
|
+
historyViewOf(row) {
|
|
3798
|
+
const view = structuredClone(row);
|
|
3799
|
+
// A stored row carries no prompt and no resumable handle; nothing here may look like a
|
|
3800
|
+
// task that could be started, continued or approved again.
|
|
3801
|
+
delete view.prompt;
|
|
3802
|
+
// Only a DURABLE record is acceptance: this is what the document says.
|
|
3803
|
+
view.hostAcceptance = row.hostAcceptance ?? null;
|
|
3804
|
+
view.reviewPersistence = this.reviewPersistenceView(row);
|
|
3805
|
+
view.source = 'history';
|
|
3806
|
+
view.selfApproved = false;
|
|
3807
|
+
view.evidence = this.historyEvidenceOf(view);
|
|
3808
|
+
return redactDeep(view);
|
|
3809
|
+
}
|
|
3810
|
+
|
|
3811
|
+
/**
|
|
3812
|
+
* State what a stored row does and does not carry.
|
|
3813
|
+
*
|
|
3814
|
+
* A restored record must never read as "the whole result, accepted": the operator
|
|
3815
|
+
* decides whether the remaining evidence is enough, and a field that was cut or was
|
|
3816
|
+
* never stored is named rather than silently missing.
|
|
3817
|
+
* @param {object} view - history view.
|
|
3818
|
+
* @returns {object} bounded evidence statement.
|
|
3819
|
+
*/
|
|
3820
|
+
historyEvidenceOf(view) {
|
|
3821
|
+
const absent = [];
|
|
3822
|
+
if (view.diff === null || view.diff === undefined || (view.diff.files ?? []).length === 0) absent.push('diff');
|
|
3823
|
+
if (view.execution === null || view.execution === undefined || (view.execution.text ?? '') === '') absent.push('execution.text');
|
|
3824
|
+
const stored = view.truncation ?? null;
|
|
3825
|
+
return {
|
|
3826
|
+
source: 'history',
|
|
3827
|
+
// Stated explicitly: the run ended before this process started.
|
|
3828
|
+
restored: true,
|
|
3829
|
+
// A stored row is evidence, never an acceptance.
|
|
3830
|
+
accepted: view.hostAcceptance?.accepted === true,
|
|
3831
|
+
absent,
|
|
3832
|
+
// What the document itself recorded as cut on the way to disk (diff.patchText etc).
|
|
3833
|
+
truncatedFields: Array.isArray(stored?.fields) ? stored.fields : [],
|
|
3834
|
+
droppedBlocks: Array.isArray(stored?.dropped) ? stored.dropped : [],
|
|
3835
|
+
note: 'this result was read from durable history: evidence the document no longer carries is listed here, and only the recorded review counts as acceptance',
|
|
3836
|
+
};
|
|
3837
|
+
}
|
|
3838
|
+
|
|
3839
|
+
/**
|
|
3840
|
+
* Record a review of a task that exists only as a durable record (after a restart).
|
|
3841
|
+
*
|
|
3842
|
+
* The SAME rules as a live review apply — closed vocabulary, the shared note bound, one
|
|
3843
|
+
* conclusion per task, idempotent replay, conflicting refusal — and the write goes
|
|
3844
|
+
* through the same serialized store write. What is different is the candidate record:
|
|
3845
|
+
* it is the stored row, re-read under the write so the stored evidence is never
|
|
3846
|
+
* discarded or partially overwritten.
|
|
3847
|
+
* @param {object} taskIdAndOwner - `taskId` and the verified `connectionId`.
|
|
3848
|
+
* @param {string} decision - validated decision.
|
|
3849
|
+
* @param {string} note - normalized, redacted note.
|
|
3850
|
+
* @param {number} waitMs - per-request wait bound.
|
|
3851
|
+
* @returns {Promise<object>} `{ task, hostAcceptance, reviewPersistence }`.
|
|
3852
|
+
* @throws {JobError} on any refusal.
|
|
3853
|
+
*/
|
|
3854
|
+
async recordHistoricalReview({ taskId, connectionId }, decision, note, waitMs) {
|
|
3855
|
+
const input = reviewInput({ decision, note });
|
|
3856
|
+
decision = input.decision;
|
|
3857
|
+
note = redactText(input.note);
|
|
3858
|
+
const row = await this.storedTaskRow(taskId, connectionId);
|
|
3859
|
+
// The SAME answer an unknown task gets: the live path refuses an unknown id with this
|
|
3860
|
+
// wording, so a restored task must not be distinguishable from a missing one.
|
|
3861
|
+
if (row === null) throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
|
|
3862
|
+
// Only a run that really ENDED in `awaiting-host-review` may be reviewed. A failed,
|
|
3863
|
+
// cancelled or interrupted record keeps its real outcome and cannot be turned into a
|
|
3864
|
+
// reviewable one, and a live state stored by an older build is equally not reviewable.
|
|
3865
|
+
if (row.state !== TASK_STATES.awaitingHostReview) {
|
|
3866
|
+
throw new JobError(JOB_CODES.reviewNotReviewable, 'this stored task is not awaiting host review', {
|
|
3867
|
+
taskId: row.taskId,
|
|
3868
|
+
state: row.state,
|
|
3869
|
+
});
|
|
3870
|
+
}
|
|
3871
|
+
const entry = this.beginHistoryReviewWrite(row, decision, note);
|
|
3872
|
+
return await this.awaitHistoryReviewWrite(row, entry, waitMs);
|
|
3873
|
+
}
|
|
3874
|
+
|
|
3875
|
+
/**
|
|
3876
|
+
* Serialize a historical review write on the store.
|
|
3877
|
+
*
|
|
3878
|
+
* The row is re-read INSIDE the queued write (see {@link writeHistoryReview}), so the
|
|
3879
|
+
* stored evidence is the base and a concurrent terminal write for the same task can only
|
|
3880
|
+
* be followed, never overwritten with a stale copy.
|
|
3881
|
+
* @param {object} row - the stored row as first read.
|
|
3882
|
+
* @param {string} decision - validated decision.
|
|
3883
|
+
* @param {string} note - normalized note to record.
|
|
3884
|
+
* @returns {object} persistence entry to await.
|
|
3885
|
+
* @throws {JobError} on a recorded or in-flight conflict.
|
|
3886
|
+
*/
|
|
3887
|
+
beginHistoryReviewWrite(row, decision, note) {
|
|
3888
|
+
const history = this.history;
|
|
3889
|
+
if (history === null || history === undefined || typeof history.update !== 'function') {
|
|
3890
|
+
throw new JobError(JOB_CODES.reviewNotPersisted,
|
|
3891
|
+
'no durable history store is configured, so the review decision was not recorded', {
|
|
3892
|
+
taskId: row.taskId,
|
|
3893
|
+
historyError: null,
|
|
3894
|
+
});
|
|
3895
|
+
}
|
|
3896
|
+
const recorded = row.hostAcceptance ?? null;
|
|
3897
|
+
const key = row.taskId;
|
|
3898
|
+
const current = this.reviewState.get(key) ?? null;
|
|
3899
|
+
if (current !== null
|
|
3900
|
+
&& (current.state === REVIEW_PERSISTENCE_STATES.saving || current.state === REVIEW_PERSISTENCE_STATES.timedOut)) {
|
|
3901
|
+
if (current.decision === decision && current.note === note) return current;
|
|
3902
|
+
throw new JobError(JOB_CODES.reviewNotReviewable,
|
|
3903
|
+
'a different review decision is being recorded for this task; wait for it or send a follow-up task', {
|
|
3904
|
+
taskId: key,
|
|
3905
|
+
recorded: current.decision,
|
|
3906
|
+
requested: decision,
|
|
3907
|
+
});
|
|
3908
|
+
}
|
|
3909
|
+
if (recorded !== null && recorded !== undefined) {
|
|
3910
|
+
if (recorded.state === decision && recorded.note === note) {
|
|
3911
|
+
return { state: REVIEW_PERSISTENCE_STATES.saved, decision, note, token: -1, done: Promise.resolve(true) };
|
|
3912
|
+
}
|
|
3913
|
+
throw new JobError(JOB_CODES.reviewNotReviewable,
|
|
3914
|
+
'this task already has a recorded review; send a follow-up task to record a correction', {
|
|
3915
|
+
taskId: key,
|
|
3916
|
+
recorded: recorded.state ?? null,
|
|
3917
|
+
requested: decision,
|
|
3918
|
+
});
|
|
3919
|
+
}
|
|
3920
|
+
const entry = {
|
|
3921
|
+
state: REVIEW_PERSISTENCE_STATES.saving,
|
|
3922
|
+
decision,
|
|
3923
|
+
note,
|
|
3924
|
+
token: (this.reviewSeq ?? 0) + 1,
|
|
3925
|
+
startedAt: this.clock(),
|
|
3926
|
+
confirmedAt: null,
|
|
3927
|
+
error: null,
|
|
3928
|
+
historical: true,
|
|
3929
|
+
connectionId: row.connectionId,
|
|
3930
|
+
};
|
|
3931
|
+
this.reviewSeq = entry.token;
|
|
3932
|
+
this.reviewState.set(key, entry);
|
|
3933
|
+
entry.done = this.writeHistoryReview(key, entry);
|
|
3934
|
+
entry.done.catch(() => undefined);
|
|
3935
|
+
return entry;
|
|
3936
|
+
}
|
|
3937
|
+
|
|
3938
|
+
/**
|
|
3939
|
+
* Write one historical review decision, re-reading the stored row under the write.
|
|
3940
|
+
* @param {string} taskId - task id.
|
|
3941
|
+
* @param {object} entry - persistence entry.
|
|
3942
|
+
* @returns {Promise<boolean>} true when the decision is durable.
|
|
3943
|
+
*/
|
|
3944
|
+
async writeHistoryReview(taskId, entry) {
|
|
3945
|
+
const acceptance = {
|
|
3946
|
+
accepted: entry.decision === HOST_REVIEW_STATES.accepted,
|
|
3947
|
+
state: entry.decision,
|
|
3948
|
+
acceptedAt: entry.startedAt,
|
|
3949
|
+
by: HOST_REVIEW_BY,
|
|
3950
|
+
note: entry.note,
|
|
3951
|
+
};
|
|
3952
|
+
try {
|
|
3953
|
+
await this.history.update(taskId, (row) => {
|
|
3954
|
+
if (row?.connectionId !== entry.connectionId) {
|
|
3955
|
+
throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
|
|
3956
|
+
}
|
|
3957
|
+
if (row?.state !== TASK_STATES.awaitingHostReview) {
|
|
3958
|
+
throw new JobError(JOB_CODES.reviewNotReviewable, 'this stored task is not awaiting host review', {
|
|
3959
|
+
taskId,
|
|
3960
|
+
state: row?.state ?? null,
|
|
3961
|
+
});
|
|
3962
|
+
}
|
|
3963
|
+
if (row.hostAcceptance !== null && row.hostAcceptance !== undefined) {
|
|
3964
|
+
if (row.hostAcceptance.state === entry.decision && row.hostAcceptance.note === entry.note) return row;
|
|
3965
|
+
throw new JobError(JOB_CODES.reviewNotReviewable,
|
|
3966
|
+
'this task already has a recorded review; send a follow-up task to record a correction', { taskId });
|
|
3967
|
+
}
|
|
3968
|
+
row.hostAcceptance = acceptance;
|
|
3969
|
+
return row;
|
|
3970
|
+
});
|
|
3971
|
+
} catch (error) {
|
|
3972
|
+
if (this.reviewState.get(taskId) === entry) {
|
|
3973
|
+
entry.state = REVIEW_PERSISTENCE_STATES.failed;
|
|
3974
|
+
entry.error = {
|
|
3975
|
+
code: typeof error?.code === 'string' ? error.code : JOB_CODES.historyFailed,
|
|
3976
|
+
message: diagnostic(error?.message ?? error, 300),
|
|
3977
|
+
};
|
|
3978
|
+
}
|
|
3979
|
+
return false;
|
|
3980
|
+
}
|
|
3981
|
+
if (this.reviewState.get(taskId) === entry) {
|
|
3982
|
+
entry.state = REVIEW_PERSISTENCE_STATES.saved;
|
|
3983
|
+
entry.confirmedAt = this.clock();
|
|
3984
|
+
entry.error = null;
|
|
3985
|
+
}
|
|
3986
|
+
return true;
|
|
3987
|
+
}
|
|
3988
|
+
|
|
3989
|
+
/**
|
|
3990
|
+
* Answer a historical review request from the real persistence state.
|
|
3991
|
+
*
|
|
3992
|
+
* The answer is always read back from the DOCUMENT: a conclusion is reported only when
|
|
3993
|
+
* the stored row carries it. An unresolved write is reported as `timed-out`/`failed`
|
|
3994
|
+
* through the same projection a live task uses, never as a saved conclusion assembled
|
|
3995
|
+
* from memory, and never with a fabricated review if the row can no longer be read.
|
|
3996
|
+
* @param {object} row - the stored row.
|
|
3997
|
+
* @param {object} entry - persistence entry.
|
|
3998
|
+
* @param {number} timeoutMs - per-request bound (0 = default).
|
|
3999
|
+
* @returns {Promise<object>} `{ task, hostAcceptance, reviewPersistence }`.
|
|
4000
|
+
* @throws {JobError} when the write failed.
|
|
4001
|
+
*/
|
|
4002
|
+
async awaitHistoryReviewWrite(row, entry, timeoutMs) {
|
|
4003
|
+
const answer = async () => {
|
|
4004
|
+
const stored = await this.storedTaskRow(row.taskId, row.connectionId);
|
|
4005
|
+
if (stored === null) {
|
|
4006
|
+
throw new JobError(JOB_CODES.historyFailed,
|
|
4007
|
+
'the stored record is no longer available, so the review outcome cannot be confirmed from history',
|
|
4008
|
+
{ taskId: row.taskId, missingRecord: true });
|
|
4009
|
+
}
|
|
4010
|
+
const view = this.historyViewOf(stored);
|
|
4011
|
+
return { task: view, hostAcceptance: view.hostAcceptance, reviewPersistence: view.reviewPersistence };
|
|
4012
|
+
};
|
|
4013
|
+
if (entry.state === REVIEW_PERSISTENCE_STATES.saved) {
|
|
4014
|
+
return await answer();
|
|
4015
|
+
}
|
|
4016
|
+
const bound = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : REVIEW_WRITE_TIMEOUT_MS;
|
|
4017
|
+
const outcome = await raceOutcome(entry.done, bound);
|
|
4018
|
+
if (outcome === REVIEW_OUTCOME_TIMEOUT
|
|
4019
|
+
&& this.reviewState.get(row.taskId) === entry
|
|
4020
|
+
&& entry.state === REVIEW_PERSISTENCE_STATES.saving) {
|
|
4021
|
+
// Unconfirmed, not failed: the write keeps running and a later GET reports the
|
|
4022
|
+
// outcome once the document carries it.
|
|
4023
|
+
entry.state = REVIEW_PERSISTENCE_STATES.timedOut;
|
|
4024
|
+
}
|
|
4025
|
+
if (entry.state === REVIEW_PERSISTENCE_STATES.failed) {
|
|
4026
|
+
throw new JobError(JOB_CODES.reviewNotPersisted,
|
|
4027
|
+
'the review decision could not be written to history, so it was not recorded', {
|
|
4028
|
+
taskId: row.taskId,
|
|
4029
|
+
historyError: entry.error ?? null,
|
|
4030
|
+
});
|
|
4031
|
+
}
|
|
4032
|
+
return await answer();
|
|
4033
|
+
}
|
|
4034
|
+
|
|
3110
4035
|
/**
|
|
3111
4036
|
* Persist the minimal task-thread identity a later `continueFromTaskId` needs.
|
|
3112
4037
|
*
|
|
@@ -3420,6 +4345,12 @@ export class JobEngine {
|
|
|
3420
4345
|
// becoming a second transcript.
|
|
3421
4346
|
activity: this.activityView(task),
|
|
3422
4347
|
hostAcceptance: task.hostAcceptance,
|
|
4348
|
+
// Where the review decision is in its durable write: `none`, `saving`, `saved`,
|
|
4349
|
+
// `failed` or `timed-out`. Stated as its own field so a reader can tell "no decision"
|
|
4350
|
+
// from "the decision is being written right now" WITHOUT having to read a
|
|
4351
|
+
// provisional `hostAcceptance`. It never makes an unconfirmed decision look accepted:
|
|
4352
|
+
// `accepted` here is true only for a `saved` entry.
|
|
4353
|
+
reviewPersistence: this.reviewPersistenceView(task),
|
|
3423
4354
|
// Stated explicitly so no consumer can read `awaiting-host-review` as
|
|
3424
4355
|
// "done and approved".
|
|
3425
4356
|
selfApproved: false,
|
|
@@ -3612,3 +4543,89 @@ export function sanitizeOverrides(value) {
|
|
|
3612
4543
|
}
|
|
3613
4544
|
|
|
3614
4545
|
export { AuthError, AUTH_CODES, defaultSettings };
|
|
4546
|
+
|
|
4547
|
+
/**
|
|
4548
|
+
* Validate the same review vocabulary and note bound for live and restored tasks.
|
|
4549
|
+
* @param {object} request - decision and note.
|
|
4550
|
+
* @returns {{ decision: string, note: string }} normalized review input.
|
|
4551
|
+
*/
|
|
4552
|
+
function reviewInput(request) {
|
|
4553
|
+
const decision = request?.decision;
|
|
4554
|
+
if (decision !== HOST_REVIEW_STATES.accepted && decision !== HOST_REVIEW_STATES.changesRequested) {
|
|
4555
|
+
throw new JobError(JOB_CODES.reviewInvalid,
|
|
4556
|
+
`decision must be ${HOST_REVIEW_STATES.accepted} or ${HOST_REVIEW_STATES.changesRequested}`,
|
|
4557
|
+
{ field: 'decision' });
|
|
4558
|
+
}
|
|
4559
|
+
const note = normalizeReviewNote(request?.note);
|
|
4560
|
+
if (note === '') {
|
|
4561
|
+
throw new JobError(JOB_CODES.reviewInvalid, 'note must be a non-empty string', { field: 'note' });
|
|
4562
|
+
}
|
|
4563
|
+
if (reviewNoteLength(note) > REVIEW_NOTE_MAX) {
|
|
4564
|
+
const overflow = reviewNoteOverflow(note);
|
|
4565
|
+
throw new JobError(JOB_CODES.reviewInvalid, overflow.message, {
|
|
4566
|
+
field: 'note', limit: overflow.limit, length: overflow.length, unit: 'unicode-code-points',
|
|
4567
|
+
});
|
|
4568
|
+
}
|
|
4569
|
+
return { decision, note };
|
|
4570
|
+
}
|
|
4571
|
+
|
|
4572
|
+
/** Read an optional shorter per-call durability wait, in milliseconds. */
|
|
4573
|
+
function reviewWaitMs(request) {
|
|
4574
|
+
const value = request?.waitMs;
|
|
4575
|
+
if (!Number.isSafeInteger(value) || value < 0) return 0;
|
|
4576
|
+
return Math.min(value, REVIEW_WRITE_TIMEOUT_MS);
|
|
4577
|
+
}
|
|
4578
|
+
|
|
4579
|
+
/**
|
|
4580
|
+
* Await a promise for at most `ms`, answering a sentinel instead of rejecting.
|
|
4581
|
+
*
|
|
4582
|
+
* The write keeps its own rejection handler: a failure that lands AFTER the bound expired
|
|
4583
|
+
* must not become an unhandled rejection, and the engine reads the outcome from the
|
|
4584
|
+
* persistence entry rather than from this race.
|
|
4585
|
+
* @param {Promise<unknown>} promise - work to await.
|
|
4586
|
+
* @param {number} ms - bound in milliseconds.
|
|
4587
|
+
* @param {AbortSignal | null} [signal] - optional caller cancellation.
|
|
4588
|
+
* @returns {Promise<unknown | symbol>} the value, or {@link REVIEW_OUTCOME_TIMEOUT}.
|
|
4589
|
+
*/
|
|
4590
|
+
async function raceOutcome(promise, ms, signal = null) {
|
|
4591
|
+
if (signal?.aborted === true) return REVIEW_OUTCOME_TIMEOUT;
|
|
4592
|
+
let onAbort = null;
|
|
4593
|
+
let timer = null;
|
|
4594
|
+
try {
|
|
4595
|
+
return await new Promise((resolvePromise) => {
|
|
4596
|
+
timer = setTimeout(() => { resolvePromise(REVIEW_OUTCOME_TIMEOUT); }, ms);
|
|
4597
|
+
timer.unref?.();
|
|
4598
|
+
if (signal !== null) {
|
|
4599
|
+
onAbort = () => { resolvePromise(REVIEW_OUTCOME_TIMEOUT); };
|
|
4600
|
+
signal.addEventListener?.('abort', onAbort, { once: true });
|
|
4601
|
+
}
|
|
4602
|
+
Promise.resolve(promise).then(
|
|
4603
|
+
(value) => { resolvePromise(value); },
|
|
4604
|
+
() => { resolvePromise(REVIEW_OUTCOME_TIMEOUT); },
|
|
4605
|
+
);
|
|
4606
|
+
});
|
|
4607
|
+
} finally {
|
|
4608
|
+
if (timer !== null) clearTimeout(timer);
|
|
4609
|
+
if (onAbort !== null) signal.removeEventListener?.('abort', onAbort);
|
|
4610
|
+
}
|
|
4611
|
+
}
|
|
4612
|
+
|
|
4613
|
+
/**
|
|
4614
|
+
* A review conclusion as a WAIT reports it: status, time and length, never the body.
|
|
4615
|
+
*
|
|
4616
|
+
* The object is kept so an old client cannot read "no note" as "not reviewed"; the body is
|
|
4617
|
+
* read on demand (R5). `noteOmitted: true` states the omission explicitly.
|
|
4618
|
+
* @param {object | null} acceptance - recorded acceptance.
|
|
4619
|
+
* @returns {object | null} summarized acceptance.
|
|
4620
|
+
*/
|
|
4621
|
+
function summarizedAcceptance(acceptance) {
|
|
4622
|
+
if (acceptance === null || typeof acceptance !== 'object') return null;
|
|
4623
|
+
return {
|
|
4624
|
+
accepted: acceptance.accepted === true,
|
|
4625
|
+
state: acceptance.state ?? null,
|
|
4626
|
+
acceptedAt: acceptance.acceptedAt ?? null,
|
|
4627
|
+
by: acceptance.by ?? null,
|
|
4628
|
+
noteChars: typeof acceptance.note === 'string' ? Array.from(acceptance.note).length : (acceptance.noteChars ?? 0),
|
|
4629
|
+
noteOmitted: true,
|
|
4630
|
+
};
|
|
4631
|
+
}
|