dsh-taskbridge 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ // Closed vocabulary shared by the activity monitor and the MCP wait answer.
2
+ //
3
+ // This module exists only to hold string constants that BOTH sides compare, so the
4
+ // producer and the consumer cannot drift apart, and so neither has to import the other.
5
+ // It has no imports of its own: it is the leaf of the graph, which is what keeps the
6
+ // `server ⇄ wait` pair and the engine from forming a cycle over one literal.
7
+
8
+ /**
9
+ * `failure.kind` for a repeated-tool-failure reminder.
10
+ *
11
+ * The reminder rides the existing `attention` reason rather than adding a new one; this
12
+ * discriminator is what lets a host tell "silent for the configured interval" from "kept
13
+ * failing the same operation", which need different decisions.
14
+ */
15
+ export const REPEATED_FAILURE_KIND = 'repeated-tool-failure';
@@ -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
@@ -134,6 +140,16 @@ export const JOB_CODES = Object.freeze({
134
140
  // still `running`; the PHASE says it is waiting for the commander's decision.
135
141
  // `waitingForPermission` is not a terminal state and is not a failure.
136
142
  permissionPending: 'JOB_PERMISSION_PENDING',
143
+ // Host review (delivery acceptance). These are refusals of the REVIEW verb, not new
144
+ // task states: the task keeps `awaiting-host-review` and its underlying outcome.
145
+ // * notReviewable: the task is not waiting for review (still running, failed,
146
+ // cancelled, interrupted, or already has a DIFFERENT recorded decision);
147
+ // * invalid: the decision/note did not pass the closed vocabulary or the bound;
148
+ // * notPersisted: the decision was made but could not be written to history, so the
149
+ // caller is TOLD it was not saved instead of being told it succeeded.
150
+ reviewNotReviewable: 'JOB_REVIEW_NOT_REVIEWABLE',
151
+ reviewInvalid: 'JOB_REVIEW_INVALID',
152
+ reviewNotPersisted: 'JOB_REVIEW_NOT_PERSISTED',
137
153
  });
138
154
 
139
155
  /** Default interval of the internal authorization sweep. */
@@ -181,6 +197,25 @@ const HISTORY_WRITE_TIMEOUT_MS = 5000;
181
197
  /** Upper bound on retained task records; oldest terminal records go first. */
182
198
  const MAX_RETAINED_TASKS = 256;
183
199
 
200
+ /**
201
+ * The closed vocabulary of host-review decisions.
202
+ *
203
+ * `accepted` is the host saying "I reviewed the delivered evidence and it is right".
204
+ * `changes-requested` is the same review with a different conclusion. Neither is a task
205
+ * state: the run stays `awaiting-host-review`, which is what keeps older clients and a
206
+ * later `continueFromTaskId` follow-up compatible.
207
+ */
208
+ export const HOST_REVIEW_STATES = Object.freeze({
209
+ accepted: 'accepted',
210
+ changesRequested: 'changes-requested',
211
+ });
212
+
213
+ /** Bounds on a review note: non-empty for a decision, and never unbounded. */
214
+ const REVIEW_NOTE_MAX_CHARS = 1_000;
215
+
216
+ /** The fixed marker recorded as the reviewer, so a stored decision is not a free name. */
217
+ const HOST_REVIEW_BY = 'host-commander';
218
+
184
219
  /**
185
220
  * The phase a running task reports while a permission request is outstanding.
186
221
  *
@@ -193,6 +228,25 @@ const MAX_RETAINED_TASKS = 256;
193
228
  const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
194
229
  const PHASE_EXECUTE = 'execute';
195
230
 
231
+ /**
232
+ * The phase a running task reports until its executor demonstrably does work.
233
+ *
234
+ * Every admission step has finished and the runner has been called, but a native
235
+ * create may still be pending (a placement is resolved through the controllers
236
+ * first), so this phase claims only "submitted", never "executing".
237
+ */
238
+ const PHASE_BEFORE_CREATE = 'before-create';
239
+
240
+ /**
241
+ * Session event types that prove the executor itself is working.
242
+ *
243
+ * The durable lifecycle types only: an opened turn, an opened model step and a
244
+ * native tool call/result cannot be produced by a pending create, whereas a
245
+ * streaming delta can arrive empty while a provider is still connecting.
246
+ * @type {ReadonlySet<string>}
247
+ */
248
+ const EXECUTION_EVIDENCE_EVENTS = Object.freeze(new Set(['turn/start', 'step/start', 'tool/call', 'tool/result']));
249
+
196
250
  /**
197
251
  * The closed vocabulary of reasons one observation may report to a caller.
198
252
  *
@@ -293,6 +347,9 @@ export class JobEngine {
293
347
  // Observers currently waiting, so disposal can release them without touching
294
348
  // the workers they were only watching.
295
349
  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();
296
353
  this.listen();
297
354
  }
298
355
 
@@ -2168,6 +2225,182 @@ export class JobEngine {
2168
2225
  return { task: this.view(task), permission: settled, hostAcceptance: null };
2169
2226
  }
2170
2227
 
2228
+ /**
2229
+ * Record the commander's delivery review for one finished task.
2230
+ *
2231
+ * This is the ONLY writer of a task's `hostAcceptance`, and it is deliberately the
2232
+ * narrowest write in the plugin. It does not decide a permission, change the switch,
2233
+ * a provider, a model, the isolation or a credential, merge a file, or create work:
2234
+ * it records "the host looked at what was delivered and concluded X" on a task whose
2235
+ * execution has already ended.
2236
+ *
2237
+ * The run's STATE is left `awaiting-host-review`. That is the compatibility anchor: an
2238
+ * older client keeps reading the same state, and `continueFromTaskId` keeps working.
2239
+ * The review conclusion lives in its own field.
2240
+ *
2241
+ * The chain of checks, all refusals:
2242
+ * 1. the task exists and belongs to the deciding connection (a foreign task answers
2243
+ * exactly like an unknown one);
2244
+ * 2. the decision and note pass the closed vocabulary and the bound;
2245
+ * 3. closing the delegation switch does not prevent reviewing an existing result;
2246
+ * 4. the task is actually waiting for review AND its native executor has settled, so
2247
+ * "still running" can never be recorded as reviewed;
2248
+ * 5. an existing decision is final: the SAME conclusion with the SAME note is an
2249
+ * idempotent no-op, and a DIFFERENT one is refused (a correction is a follow-up
2250
+ * 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.
2253
+ * @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.
2257
+ */
2258
+ async recordHostReview(request) {
2259
+ const connectionId = typeof request?.connectionId === 'string' ? request.connectionId : null;
2260
+ if (connectionId === null) {
2261
+ // No verified identity means no ownership proof: the same answer an unknown task gets.
2262
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', {});
2263
+ }
2264
+ const taskId = typeof request?.taskId === 'string' ? request.taskId.trim() : '';
2265
+ if (taskId === '') {
2266
+ throw new JobError(JOB_CODES.reviewInvalid, 'taskId is required', { field: 'taskId' });
2267
+ }
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
+ }
2285
+
2286
+ const task = this.tasks.get(taskId);
2287
+ if (task === undefined || task.connectionId !== connectionId) {
2288
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
2289
+ }
2290
+ // NO posture gate here, deliberately. A review records a conclusion about a result
2291
+ // that already exists: it creates no work, releases no permission, issues no grant and
2292
+ // changes no setting. Like reading a task or cancelling it, it therefore stays
2293
+ // available after the operator closes the switch — you must still be able to review
2294
+ // what you already paid for. Starting a NEW task and answering a permission request
2295
+ // remain gated by the switch at their own entry points.
2296
+ // Only a finished execution can be reviewed. `awaiting-host-review` is the state the
2297
+ // engine records after a completed run, and `native.settled` is the second,
2298
+ // independent proof that the executor is gone: neither can be inferred by the caller.
2299
+ if (task.state !== TASK_STATES.awaitingHostReview || task.native?.settled !== true) {
2300
+ throw new JobError(JOB_CODES.reviewNotReviewable, 'this task is not awaiting host review', {
2301
+ taskId,
2302
+ state: task.state,
2303
+ phase: task.phase,
2304
+ });
2305
+ }
2306
+
2307
+ // 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 };
2359
+ }
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
+ });
2367
+ }
2368
+
2369
+ task.hostAcceptance = {
2370
+ accepted: decision === HOST_REVIEW_STATES.accepted,
2371
+ state: decision,
2372
+ acceptedAt: this.clock(),
2373
+ by: HOST_REVIEW_BY,
2374
+ note,
2375
+ };
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
+ });
2388
+ }
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
+ });
2399
+ }
2400
+ const view = this.view(task);
2401
+ return { task: view, hostAcceptance: view.hostAcceptance };
2402
+ }
2403
+
2171
2404
  /**
2172
2405
  * Stop every outstanding request of one task and disarm its bridge.
2173
2406
  *
@@ -2449,7 +2682,7 @@ export class JobEngine {
2449
2682
 
2450
2683
  // The last gate before a native agent exists. Everything above awaited at
2451
2684
  // least once; this re-check runs in the same step as the creation call.
2452
- task.phase = 'before-create';
2685
+ task.phase = PHASE_BEFORE_CREATE;
2453
2686
  this.assertLive(task, 'before-create');
2454
2687
 
2455
2688
  // The native executor comes into existence here. `started` is recorded
@@ -2466,6 +2699,10 @@ export class JobEngine {
2466
2699
  // the run keeps the fail-closed `never` stance and nothing about it changes.
2467
2700
  const bridge = this.createPermissionBridge(task);
2468
2701
  task.permission.bridge = bridge;
2702
+ // `started` means "this task called the runner", not "the executor is
2703
+ // running": placement resolves before the runner sees an Agent, so the task
2704
+ // is handed over in `before-create` and only the executor's own events
2705
+ // ({@link onExecutionEvent}) publish `execute`.
2469
2706
  task.native.started = true;
2470
2707
  const pending = runAgent(this.deps, {
2471
2708
  prompt,
@@ -2511,7 +2748,8 @@ export class JobEngine {
2511
2748
  // the event was progress, and (for a tool event) its name and call id.
2512
2749
  // Reasoning text, assistant text and tool arguments are never retained or
2513
2750
  // forwarded — there is no field in the summary they could travel in.
2514
- onEvent: (event) => { task.monitor?.onEvent(event, this.clock()); },
2751
+ // This hook is also the only execution evidence the phase trusts.
2752
+ onEvent: (event) => { this.onExecutionEvent(task, event); },
2515
2753
  });
2516
2754
  task.native.promise = pending;
2517
2755
  let run;
@@ -2574,12 +2812,16 @@ export class JobEngine {
2574
2812
  }
2575
2813
  if (run.outcome === RUN_OUTCOMES.timedOut) {
2576
2814
  task.state = TASK_STATES.failed;
2815
+ task.phase = 'failed';
2577
2816
  task.error = { code: JOB_CODES.timeout, message: 'the task exceeded its time budget' };
2578
2817
  task.endedAt = Date.now();
2579
2818
  return;
2580
2819
  }
2581
2820
  if (run.outcome !== RUN_OUTCOMES.completed) {
2582
2821
  task.state = TASK_STATES.failed;
2822
+ // The phase states the same ending as the state, so a failed run never keeps
2823
+ // describing a creation or an execution.
2824
+ task.phase = 'failed';
2583
2825
  // Three endings that are not completion, kept apart because they need
2584
2826
  // different fixes:
2585
2827
  // * the model was stopped by its own output budget (`max-tokens`) — raise
@@ -2694,6 +2936,7 @@ export class JobEngine {
2694
2936
  waitSliceMs: this.observeSliceMs,
2695
2937
  selfCheckSeconds: monitoring?.selfCheckSeconds ?? MONITORING_DEFAULTS.selfCheckSeconds,
2696
2938
  attentionSeconds: monitoring?.attentionSeconds ?? MONITORING_DEFAULTS.attentionSeconds,
2939
+ repeatFailureThreshold: monitoring?.repeatFailureThreshold ?? MONITORING_DEFAULTS.repeatFailureThreshold,
2697
2940
  log: (message, detail) => this.deps?.logger?.warn?.(message, detail),
2698
2941
  });
2699
2942
  }
@@ -2755,6 +2998,26 @@ export class JobEngine {
2755
2998
  return LIVE.has(task.state) && monitor.activity.tool !== null;
2756
2999
  }
2757
3000
 
3001
+ /**
3002
+ * Feed one native executor event to the run's monitor and, on real evidence that
3003
+ * the executor is working, publish `execute`.
3004
+ *
3005
+ * Only a live task still at {@link PHASE_BEFORE_CREATE} advances, so a late event
3006
+ * can never overwrite `awaiting-permission`, `review`, a terminal phase or a
3007
+ * `pending` task.
3008
+ * @param {object} task - running task record.
3009
+ * @param {unknown} event - native event dispatched by the runner.
3010
+ * @returns {void}
3011
+ */
3012
+ onExecutionEvent(task, event) {
3013
+ task.monitor?.onEvent(event, this.clock());
3014
+ if (task.state === TASK_STATES.running
3015
+ && task.phase === PHASE_BEFORE_CREATE
3016
+ && EXECUTION_EVIDENCE_EVENTS.has(event?.type)) {
3017
+ task.phase = PHASE_EXECUTE;
3018
+ }
3019
+ }
3020
+
2758
3021
  /**
2759
3022
  * The bounded, publishable activity block of one task view.
2760
3023
  *
@@ -2814,8 +3077,11 @@ export class JobEngine {
2814
3077
  * observer of the same task.
2815
3078
  * @param {string} taskId - task to observe.
2816
3079
  * @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000), `signal`.
2817
- * @returns {Promise<{ task: object, reason: string, permission: object | null, activity: object | null,
3080
+ * @returns {Promise<{ task: object, reason: string, permission: object | null,
3081
+ * failure: object | null, activity: object | null,
2818
3082
  * selfCheck: object | null, wait: { waitMs: number, waitedMs: number, activitySinceWait: boolean } }>} observation.
3083
+ * `failure` is present only when `attention` reports a repeated-tool-failure
3084
+ * reminder; it carries a tool name, a failure code, an operation digest and counts.
2819
3085
  * @throws {JobError} `JOB_TASK_NOT_FOUND` for an unknown or foreign task.
2820
3086
  */
2821
3087
  async observeTask(taskId, options = {}) {
@@ -2854,7 +3120,11 @@ export class JobEngine {
2854
3120
  // request beats a silence report. `heartbeat` is the only reason that yields.
2855
3121
  const settled = this.settleReason(task);
2856
3122
  if (settled !== null) reason = settled;
2857
- return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait);
3123
+ // A reminder superseded by a terminal state or a pending request above is dropped:
3124
+ // those outrank it, and a failure report must not describe a task that now needs a
3125
+ // different decision.
3126
+ const failure = reason === OBSERVE_TASK_REASONS.attention ? (outcome.failure ?? null) : null;
3127
+ return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure);
2858
3128
  }
2859
3129
 
2860
3130
  /**
@@ -2949,9 +3219,11 @@ export class JobEngine {
2949
3219
  * @param {number} waitMs - the bound that applied.
2950
3220
  * @param {number} waitedMs - how long the wait actually took.
2951
3221
  * @param {boolean} activitySinceWait - whether activity arrived during the wait.
3222
+ * @param {object | null} [failure] - the repeated-failure diagnostic, when that is
3223
+ * what ended the wait.
2952
3224
  * @returns {object} observation result.
2953
3225
  */
2954
- observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait) {
3226
+ observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null) {
2955
3227
  const at = this.clock();
2956
3228
  const summary = this.observationSummary(task, at);
2957
3229
  const pending = task?.permission?.pending ?? null;
@@ -2962,6 +3234,10 @@ export class JobEngine {
2962
3234
  reason,
2963
3235
  // The full, unshortened redacted request on the ONE reason that needs it.
2964
3236
  permission: reason === OBSERVE_TASK_REASONS.permission ? pending : null,
3237
+ // The typed, bounded diagnostic for a repeated-failure reminder. It is the only
3238
+ // thing that distinguishes that reminder from an ordinary silence report, whose
3239
+ // own diagnostic is `selfCheck`.
3240
+ failure: reason === OBSERVE_TASK_REASONS.attention && failure !== null ? failure : null,
2965
3241
  activity: summary.activity,
2966
3242
  selfCheck,
2967
3243
  wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
@@ -3007,9 +3283,12 @@ export class JobEngine {
3007
3283
  // finished run is described as having used.
3008
3284
  route: this.observationRoute(task),
3009
3285
  connectionId: task.connectionId ?? null,
3010
- // Stated so no consumer reads `awaiting-host-review` as acceptance.
3286
+ // Stated so no consumer reads `awaiting-host-review` as acceptance by itself; the
3287
+ // recorded review, when one exists, is reported separately below.
3011
3288
  selfApproved: false,
3012
- hostAcceptance: null,
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,
3013
3292
  };
3014
3293
  }
3015
3294
 
@@ -3029,6 +3308,7 @@ export class JobEngine {
3029
3308
  monitoring: {
3030
3309
  selfCheckSeconds: task.effective.monitoring?.selfCheckSeconds ?? null,
3031
3310
  attentionSeconds: task.effective.monitoring?.attentionSeconds ?? null,
3311
+ repeatFailureThreshold: task.effective.monitoring?.repeatFailureThreshold ?? null,
3032
3312
  },
3033
3313
  };
3034
3314
  }
@@ -3043,7 +3323,9 @@ export class JobEngine {
3043
3323
  * @returns {Promise<void>} resolves after bookkeeping.
3044
3324
  */
3045
3325
  async finishTask(task) {
3046
- task.hostAcceptance = null;
3326
+ // `hostAcceptance` is NOT reset here. This path runs when a run ends, and a review
3327
+ // can only be recorded after that — but a terminal task that somehow reaches this
3328
+ // method again must not lose a decision the host already recorded.
3047
3329
  this.clearPreflightDeadline(task);
3048
3330
  // The run is over, so its answerer must go: an outstanding request is released
3049
3331
  // (the worker's paused tool call resumes `unavailable`) and the bridge can never
@@ -3073,11 +3355,12 @@ export class JobEngine {
3073
3355
  * supported posture (the engine never reads history back to decide
3074
3356
  * anything), so `history === null` is silent while a *failing* store is loud.
3075
3357
  * @param {object} task - terminal task record.
3076
- * @returns {Promise<void>} resolves after the attempt, never rejects.
3358
+ * @returns {Promise<boolean>} true when the record is durable (or history is absent),
3359
+ * false when the write failed; never rejects.
3077
3360
  */
3078
3361
  async persistHistory(task) {
3079
3362
  const history = this.history;
3080
- if (history === null || history === undefined || typeof history.save !== 'function') return;
3363
+ if (history === null || history === undefined || typeof history.save !== 'function') return true;
3081
3364
  let timer = null;
3082
3365
  try {
3083
3366
  const view = this.view(task);
@@ -3094,6 +3377,7 @@ export class JobEngine {
3094
3377
  await bounded;
3095
3378
  task.historyError = null;
3096
3379
  task.historySavedAt = Date.now();
3380
+ return true;
3097
3381
  } catch (error) {
3098
3382
  // Recorded, not thrown: a history failure must not turn a completed task
3099
3383
  // into a failed one, and it must not escape into the release path.
@@ -3102,6 +3386,7 @@ export class JobEngine {
3102
3386
  message: diagnostic(error?.message ?? error, 300),
3103
3387
  };
3104
3388
  task.historySavedAt = null;
3389
+ return false;
3105
3390
  } finally {
3106
3391
  if (timer !== null) clearTimeout(timer);
3107
3392
  }
@@ -632,6 +632,7 @@ function effectiveView(value) {
632
632
  ? {
633
633
  selfCheckSeconds: count(value.monitoring.selfCheckSeconds),
634
634
  attentionSeconds: count(value.monitoring.attentionSeconds),
635
+ repeatFailureThreshold: count(value.monitoring.repeatFailureThreshold),
635
636
  }
636
637
  : null,
637
638
  provenance: {
@@ -1029,6 +1030,33 @@ function activityView(value) {
1029
1030
  }
1030
1031
  : {}),
1031
1032
  kinds,
1033
+ // The repeated-failure reminder as bounded evidence: a tool NAME, a failure CODE,
1034
+ // an operation digest and counts. No arguments, no output, no error prose — the
1035
+ // live monitor already reduced it to that, and this keeps the same shape.
1036
+ repeatFailure: repeatFailureOf(value.repeatFailure),
1037
+ };
1038
+ }
1039
+
1040
+ /**
1041
+ * Project a stored `repeatFailure` block, dropping anything but the bounded facts.
1042
+ * @param {unknown} value - candidate block.
1043
+ * @returns {object | null} projection.
1044
+ */
1045
+ function repeatFailureOf(value) {
1046
+ if (!isPlainObject(value)) return null;
1047
+ const reported = Array.isArray(value.reported) ? value.reported : [];
1048
+ return {
1049
+ threshold: count(value.threshold),
1050
+ reported: reported.filter(isPlainObject).slice(0, 32).map((entry) => ({
1051
+ kind: label(entry.kind),
1052
+ toolName: label(entry.toolName),
1053
+ failureCode: label(entry.failureCode),
1054
+ operationDigest: label(entry.operationDigest),
1055
+ consecutive: count(entry.consecutive),
1056
+ threshold: count(entry.threshold),
1057
+ firstSeenAt: time(entry.firstSeenAt),
1058
+ lastSeenAt: time(entry.lastSeenAt),
1059
+ })),
1032
1060
  };
1033
1061
  }
1034
1062