dsh-taskbridge 1.4.0 → 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.
@@ -82,6 +82,12 @@ import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
82
82
  import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
83
83
  import { captureBaseline, captureDiff } from '../workspace/audit.js';
84
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';
85
91
 
86
92
  /** Task lifecycle states. `awaiting-host-review` is terminal for this plugin. */
87
93
  export const TASK_STATES = Object.freeze({
@@ -211,7 +217,36 @@ export const HOST_REVIEW_STATES = Object.freeze({
211
217
  });
212
218
 
213
219
  /** Bounds on a review note: non-empty for a decision, and never unbounded. */
214
- const REVIEW_NOTE_MAX_CHARS = 1_000;
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');
215
250
 
216
251
  /** The fixed marker recorded as the reviewer, so a stored decision is not a free name. */
217
252
  const HOST_REVIEW_BY = 'host-commander';
@@ -274,6 +309,17 @@ export const OBSERVE_TASK_REASONS = Object.freeze({
274
309
  const OBSERVE_WAIT_MS = 25_000;
275
310
  const OBSERVE_SLICE_MS = 1000;
276
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
+
277
323
  /** Raised for job-level refusals. */
278
324
  export class JobError extends Error {
279
325
  /**
@@ -347,9 +393,15 @@ export class JobEngine {
347
393
  // Observers currently waiting, so disposal can release them without touching
348
394
  // the workers they were only watching.
349
395
  this.observers = new Set();
350
- // One in-flight host-review write per task, so two concurrent identical requests
351
- // cannot both claim success before the durable write has actually landed.
352
- this.reviewWrites = new Map();
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;
353
405
  this.listen();
354
406
  }
355
407
 
@@ -613,7 +665,8 @@ export class JobEngine {
613
665
  cleanupError: null,
614
666
  historyError: null,
615
667
  historySavedAt: null,
616
- // 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`).
617
670
  hostAcceptance: null,
618
671
  settled,
619
672
  settle: () => { settle(); },
@@ -2248,12 +2301,24 @@ export class JobEngine {
2248
2301
  * 5. an existing decision is final: the SAME conclusion with the SAME note is an
2249
2302
  * idempotent no-op, and a DIFFERENT one is refused (a correction is a follow-up
2250
2303
  * task, not a rewrite of the record);
2251
- * 6. only then is it stored, and only reported as stored when the durable write
2252
- * succeeded.
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.
2253
2315
  * @param {object} request - `taskId`, `decision`, `note`, and the authenticated
2254
- * `connectionId` (from the plane, never from the caller's body).
2255
- * @returns {Promise<object>} `{ task, hostAcceptance }` where `task` is the public view.
2256
- * @throws {JobError} on any refusal.
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).
2257
2322
  */
2258
2323
  async recordHostReview(request) {
2259
2324
  const connectionId = typeof request?.connectionId === 'string' ? request.connectionId : null;
@@ -2265,23 +2330,7 @@ export class JobEngine {
2265
2330
  if (taskId === '') {
2266
2331
  throw new JobError(JOB_CODES.reviewInvalid, 'taskId is required', { field: 'taskId' });
2267
2332
  }
2268
- const decision = request?.decision;
2269
- if (decision !== HOST_REVIEW_STATES.accepted && decision !== HOST_REVIEW_STATES.changesRequested) {
2270
- throw new JobError(JOB_CODES.reviewInvalid,
2271
- `decision must be ${HOST_REVIEW_STATES.accepted} or ${HOST_REVIEW_STATES.changesRequested}`,
2272
- { field: 'decision' });
2273
- }
2274
- const rawNote = typeof request?.note === 'string' ? request.note.trim() : '';
2275
- if (rawNote === '') {
2276
- throw new JobError(JOB_CODES.reviewInvalid, 'note must be a non-empty string', { field: 'note' });
2277
- }
2278
- if (rawNote.length > REVIEW_NOTE_MAX_CHARS) {
2279
- throw new JobError(JOB_CODES.reviewInvalid, `note must be at most ${REVIEW_NOTE_MAX_CHARS} characters`, {
2280
- field: 'note',
2281
- limit: REVIEW_NOTE_MAX_CHARS,
2282
- length: rawNote.length,
2283
- });
2284
- }
2333
+ const { decision, note: rawNote } = reviewInput(request);
2285
2334
 
2286
2335
  const task = this.tasks.get(taskId);
2287
2336
  if (task === undefined || task.connectionId !== connectionId) {
@@ -2305,100 +2354,282 @@ export class JobEngine {
2305
2354
  }
2306
2355
 
2307
2356
  // The note is redacted through the same bounded redaction the rest of the projection
2308
- // uses, so a stored conclusion cannot smuggle a credential into history or a view.
2309
- const note = redactText(rawNote).slice(0, REVIEW_NOTE_MAX_CHARS);
2310
-
2311
- // One review write per task at a time. Without this, a second identical request
2312
- // arriving while the first is still awaiting `history.save` would see the in-memory
2313
- // record and answer "idempotent success" before that write had actually landed — and
2314
- // if the write then failed, BOTH callers would have been told something that was not
2315
- // true. The latch is a promise chained on the previous attempt, so a failed write
2316
- // releases it and the next caller re-attempts rather than hanging.
2317
- const previous = this.reviewWrites.get(taskId) ?? Promise.resolve();
2318
- // A rejected predecessor must not poison the chain: every caller retries the write
2319
- // itself, it does not inherit the failure.
2320
- const attempt = previous.then(
2321
- () => this.applyHostReview(task, decision, note),
2322
- () => this.applyHostReview(task, decision, note),
2323
- );
2324
- // Store a latched (never-rejecting) form, so the next caller can chain on it without
2325
- // an unhandled rejection, and so a failure genuinely frees the duty to re-attempt.
2326
- const latched = attempt.then(() => undefined, () => undefined);
2327
- this.reviewWrites.set(taskId, latched);
2328
- try {
2329
- return await attempt;
2330
- } finally {
2331
- // Only the LAST attempt clears the latch. An earlier attempt finishing late must not
2332
- // expose a window in which a newer writer is not serialised behind it.
2333
- if (this.reviewWrites.get(taskId) === latched) this.reviewWrites.delete(taskId);
2334
- }
2335
- }
2336
-
2337
- /**
2338
- * Apply one already-validated review decision and make it durable.
2339
- *
2340
- * Split out of {@link recordHostReview} so the caller can SERIALISE it per task: the
2341
- * read of the existing record, the decision and the durable write must happen as one
2342
- * step, or two concurrent identical requests could both observe "no decision yet" and
2343
- * both claim success before either had written anything.
2344
- * @param {object} task - the task record, already proven reviewable and owned.
2345
- * @param {string} decision - `accepted` or `changes-requested`.
2346
- * @param {string} note - already redacted and bounded.
2347
- * @returns {Promise<object>} `{ task, hostAcceptance }` public views.
2348
- * @throws {JobError} on a conflicting decision or a failed durable write.
2349
- */
2350
- async applyHostReview(task, decision, note) {
2351
- const existing = task.hostAcceptance;
2352
- if (existing !== null && existing !== undefined) {
2353
- if (existing.state === decision && existing.note === note) {
2354
- // The same conclusion replayed: an idempotent success, not a second record. It is
2355
- // only reached AFTER the first attempt settled, so a first write that failed was
2356
- // already rolled back and this caller really does record it.
2357
- const replayed = this.view(task);
2358
- return { task: replayed, hostAcceptance: replayed.hostAcceptance };
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);
2359
2389
  }
2360
- throw new JobError(JOB_CODES.reviewNotReviewable,
2361
- 'this task already has a recorded review; send a follow-up task to record a correction', {
2362
- taskId: task.taskId,
2363
- state: task.state,
2364
- recorded: existing.state,
2365
- requested: decision,
2366
- });
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.
2367
2403
  }
2368
2404
 
2369
- task.hostAcceptance = {
2370
- accepted: decision === HOST_REVIEW_STATES.accepted,
2371
- state: decision,
2372
- acceptedAt: this.clock(),
2373
- by: HOST_REVIEW_BY,
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,
2374
2412
  note,
2413
+ token: (this.reviewSeq ?? 0) + 1,
2414
+ startedAt: this.clock(),
2415
+ confirmedAt: null,
2416
+ error: null,
2375
2417
  };
2376
- // The record must be durable before the caller is told it exists: a review that is
2377
- // lost on restart would silently put the task back to "not reviewed". With no history
2378
- // store at all — or one with no `save` to call — there is nothing to write to, and
2379
- // `persistHistory` answers success for that case (it is the ordinary "no durable
2380
- // history" posture), which would let a review be claimed as saved when it is not.
2381
- if (this.history === null || this.history === undefined || typeof this.history.save !== 'function') {
2382
- task.hostAcceptance = null;
2383
- throw new JobError(JOB_CODES.reviewNotPersisted,
2384
- 'no durable history store is configured, so the review decision was not recorded', {
2385
- taskId: task.taskId,
2386
- historyError: null,
2387
- });
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) };
2388
2441
  }
2389
- const saved = await this.persistHistory(task);
2390
- if (saved !== true) {
2391
- // The in-memory record is rolled back so the two cannot disagree, and the caller is
2392
- // told the decision was NOT saved rather than being told it succeeded.
2393
- task.hostAcceptance = null;
2394
- throw new JobError(JOB_CODES.reviewNotPersisted,
2395
- 'the review decision could not be written to history, so it was not recorded', {
2396
- taskId: task.taskId,
2397
- historyError: task.historyError ?? null,
2398
- });
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;
2399
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) {
2400
2574
  const view = this.view(task);
2401
- return { task: view, hostAcceptance: view.hostAcceptance };
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
+ };
2402
2633
  }
2403
2634
 
2404
2635
  /**
@@ -3103,6 +3334,13 @@ export class JobEngine {
3103
3334
  // outstanding permission request, which is decidable right now.
3104
3335
  const immediate = this.settleReason(task);
3105
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;
3106
3344
  return this.observationOf(task, immediate, monitor, waitMs, 0, false);
3107
3345
  }
3108
3346
 
@@ -3127,6 +3365,36 @@ export class JobEngine {
3127
3365
  return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure);
3128
3366
  }
3129
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);
3396
+ }
3397
+
3130
3398
  /**
3131
3399
  * Run one bounded internal wait against a task's monitor.
3132
3400
  *
@@ -3286,9 +3554,15 @@ export class JobEngine {
3286
3554
  // Stated so no consumer reads `awaiting-host-review` as acceptance by itself; the
3287
3555
  // recorded review, when one exists, is reported separately below.
3288
3556
  selfApproved: false,
3289
- // The commander's own decision, or null when none has been recorded yet. Never
3290
- // derived from the task state: a completed run is not an accepted one.
3291
- hostAcceptance: task.hostAcceptance ?? null,
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),
3292
3566
  };
3293
3567
  }
3294
3568
 
@@ -3336,10 +3610,68 @@ export class JobEngine {
3336
3610
  // task, so the stored view still says how much activity there was.
3337
3611
  this.releaseMonitor(task);
3338
3612
  await this.finalize(task);
3339
- await this.persistHistory(task);
3613
+ await this.persistTerminalRecord(task);
3340
3614
  task.settle();
3341
3615
  }
3342
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
+
3343
3675
  /**
3344
3676
  * Persist one terminal task's public view to the durable history store.
3345
3677
  *
@@ -3392,6 +3724,314 @@ export class JobEngine {
3392
3724
  }
3393
3725
  }
3394
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
+
3395
4035
  /**
3396
4036
  * Persist the minimal task-thread identity a later `continueFromTaskId` needs.
3397
4037
  *
@@ -3705,6 +4345,12 @@ export class JobEngine {
3705
4345
  // becoming a second transcript.
3706
4346
  activity: this.activityView(task),
3707
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),
3708
4354
  // Stated explicitly so no consumer can read `awaiting-host-review` as
3709
4355
  // "done and approved".
3710
4356
  selfApproved: false,
@@ -3897,3 +4543,89 @@ export function sanitizeOverrides(value) {
3897
4543
  }
3898
4544
 
3899
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
+ }