dsh-taskbridge 1.3.1 → 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
@@ -71,6 +77,7 @@ import { RUN_OUTCOMES, RunError, SessionPlacementRefusal, diagnostic, runAgent }
71
77
  import { PermissionBridge, PermissionError, PERMISSION_CODES } from '../runtime/permissions.js';
72
78
  import { DELEGATE_SANDBOX_MODE } from '../runtime/sandbox.js';
73
79
  import { rememberSession, SESSION_CODES } from '../runtime/session-placement.js';
80
+ import { taskTitle } from './title.js';
74
81
  import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
75
82
  import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
76
83
  import { captureBaseline, captureDiff } from '../workspace/audit.js';
@@ -133,6 +140,16 @@ export const JOB_CODES = Object.freeze({
133
140
  // still `running`; the PHASE says it is waiting for the commander's decision.
134
141
  // `waitingForPermission` is not a terminal state and is not a failure.
135
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',
136
153
  });
137
154
 
138
155
  /** Default interval of the internal authorization sweep. */
@@ -180,6 +197,25 @@ const HISTORY_WRITE_TIMEOUT_MS = 5000;
180
197
  /** Upper bound on retained task records; oldest terminal records go first. */
181
198
  const MAX_RETAINED_TASKS = 256;
182
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
+
183
219
  /**
184
220
  * The phase a running task reports while a permission request is outstanding.
185
221
  *
@@ -192,6 +228,25 @@ const MAX_RETAINED_TASKS = 256;
192
228
  const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
193
229
  const PHASE_EXECUTE = 'execute';
194
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
+
195
250
  /**
196
251
  * The closed vocabulary of reasons one observation may report to a caller.
197
252
  *
@@ -292,6 +347,9 @@ export class JobEngine {
292
347
  // Observers currently waiting, so disposal can release them without touching
293
348
  // the workers they were only watching.
294
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();
295
353
  this.listen();
296
354
  }
297
355
 
@@ -425,6 +483,7 @@ export class JobEngine {
425
483
  ? 'switch'
426
484
  : (request?.authorization === 'session' ? 'session' : 'task');
427
485
  const task = this.createTask(prompt, authorization);
486
+ task.title = taskTitle(request?.title, prompt);
428
487
  // Frozen before the first await so the task record states, from the moment it
429
488
  // exists, whether it starts a conversation or continues one.
430
489
  task.continueFromTaskId = continueFromTaskId === '' ? null : continueFromTaskId;
@@ -2166,6 +2225,182 @@ export class JobEngine {
2166
2225
  return { task: this.view(task), permission: settled, hostAcceptance: null };
2167
2226
  }
2168
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
+
2169
2404
  /**
2170
2405
  * Stop every outstanding request of one task and disarm its bridge.
2171
2406
  *
@@ -2447,7 +2682,7 @@ export class JobEngine {
2447
2682
 
2448
2683
  // The last gate before a native agent exists. Everything above awaited at
2449
2684
  // least once; this re-check runs in the same step as the creation call.
2450
- task.phase = 'before-create';
2685
+ task.phase = PHASE_BEFORE_CREATE;
2451
2686
  this.assertLive(task, 'before-create');
2452
2687
 
2453
2688
  // The native executor comes into existence here. `started` is recorded
@@ -2464,9 +2699,14 @@ export class JobEngine {
2464
2699
  // the run keeps the fail-closed `never` stance and nothing about it changes.
2465
2700
  const bridge = this.createPermissionBridge(task);
2466
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`.
2467
2706
  task.native.started = true;
2468
2707
  const pending = runAgent(this.deps, {
2469
2708
  prompt,
2709
+ title: task.title,
2470
2710
  cwd: task.executionPath,
2471
2711
  selection: workerSelection,
2472
2712
  timeoutMs: task.effective.worker.timeoutSeconds * 1000,
@@ -2508,7 +2748,8 @@ export class JobEngine {
2508
2748
  // the event was progress, and (for a tool event) its name and call id.
2509
2749
  // Reasoning text, assistant text and tool arguments are never retained or
2510
2750
  // forwarded — there is no field in the summary they could travel in.
2511
- 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); },
2512
2753
  });
2513
2754
  task.native.promise = pending;
2514
2755
  let run;
@@ -2571,12 +2812,16 @@ export class JobEngine {
2571
2812
  }
2572
2813
  if (run.outcome === RUN_OUTCOMES.timedOut) {
2573
2814
  task.state = TASK_STATES.failed;
2815
+ task.phase = 'failed';
2574
2816
  task.error = { code: JOB_CODES.timeout, message: 'the task exceeded its time budget' };
2575
2817
  task.endedAt = Date.now();
2576
2818
  return;
2577
2819
  }
2578
2820
  if (run.outcome !== RUN_OUTCOMES.completed) {
2579
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';
2580
2825
  // Three endings that are not completion, kept apart because they need
2581
2826
  // different fixes:
2582
2827
  // * the model was stopped by its own output budget (`max-tokens`) — raise
@@ -2691,6 +2936,7 @@ export class JobEngine {
2691
2936
  waitSliceMs: this.observeSliceMs,
2692
2937
  selfCheckSeconds: monitoring?.selfCheckSeconds ?? MONITORING_DEFAULTS.selfCheckSeconds,
2693
2938
  attentionSeconds: monitoring?.attentionSeconds ?? MONITORING_DEFAULTS.attentionSeconds,
2939
+ repeatFailureThreshold: monitoring?.repeatFailureThreshold ?? MONITORING_DEFAULTS.repeatFailureThreshold,
2694
2940
  log: (message, detail) => this.deps?.logger?.warn?.(message, detail),
2695
2941
  });
2696
2942
  }
@@ -2752,6 +2998,26 @@ export class JobEngine {
2752
2998
  return LIVE.has(task.state) && monitor.activity.tool !== null;
2753
2999
  }
2754
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
+
2755
3021
  /**
2756
3022
  * The bounded, publishable activity block of one task view.
2757
3023
  *
@@ -2811,8 +3077,11 @@ export class JobEngine {
2811
3077
  * observer of the same task.
2812
3078
  * @param {string} taskId - task to observe.
2813
3079
  * @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000), `signal`.
2814
- * @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,
2815
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.
2816
3085
  * @throws {JobError} `JOB_TASK_NOT_FOUND` for an unknown or foreign task.
2817
3086
  */
2818
3087
  async observeTask(taskId, options = {}) {
@@ -2851,7 +3120,11 @@ export class JobEngine {
2851
3120
  // request beats a silence report. `heartbeat` is the only reason that yields.
2852
3121
  const settled = this.settleReason(task);
2853
3122
  if (settled !== null) reason = settled;
2854
- 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);
2855
3128
  }
2856
3129
 
2857
3130
  /**
@@ -2946,9 +3219,11 @@ export class JobEngine {
2946
3219
  * @param {number} waitMs - the bound that applied.
2947
3220
  * @param {number} waitedMs - how long the wait actually took.
2948
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.
2949
3224
  * @returns {object} observation result.
2950
3225
  */
2951
- observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait) {
3226
+ observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null) {
2952
3227
  const at = this.clock();
2953
3228
  const summary = this.observationSummary(task, at);
2954
3229
  const pending = task?.permission?.pending ?? null;
@@ -2959,6 +3234,10 @@ export class JobEngine {
2959
3234
  reason,
2960
3235
  // The full, unshortened redacted request on the ONE reason that needs it.
2961
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,
2962
3241
  activity: summary.activity,
2963
3242
  selfCheck,
2964
3243
  wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
@@ -2985,6 +3264,7 @@ export class JobEngine {
2985
3264
  return {
2986
3265
  taskId: task.taskId,
2987
3266
  state: task.state,
3267
+ title: task.title ?? taskTitle(null, task.prompt),
2988
3268
  phase: task.phase,
2989
3269
  createdAt: task.createdAt ?? null,
2990
3270
  startedAt: task.startedAt ?? null,
@@ -3003,9 +3283,12 @@ export class JobEngine {
3003
3283
  // finished run is described as having used.
3004
3284
  route: this.observationRoute(task),
3005
3285
  connectionId: task.connectionId ?? null,
3006
- // 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.
3007
3288
  selfApproved: false,
3008
- 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,
3009
3292
  };
3010
3293
  }
3011
3294
 
@@ -3025,6 +3308,7 @@ export class JobEngine {
3025
3308
  monitoring: {
3026
3309
  selfCheckSeconds: task.effective.monitoring?.selfCheckSeconds ?? null,
3027
3310
  attentionSeconds: task.effective.monitoring?.attentionSeconds ?? null,
3311
+ repeatFailureThreshold: task.effective.monitoring?.repeatFailureThreshold ?? null,
3028
3312
  },
3029
3313
  };
3030
3314
  }
@@ -3039,7 +3323,9 @@ export class JobEngine {
3039
3323
  * @returns {Promise<void>} resolves after bookkeeping.
3040
3324
  */
3041
3325
  async finishTask(task) {
3042
- 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.
3043
3329
  this.clearPreflightDeadline(task);
3044
3330
  // The run is over, so its answerer must go: an outstanding request is released
3045
3331
  // (the worker's paused tool call resumes `unavailable`) and the bridge can never
@@ -3069,11 +3355,12 @@ export class JobEngine {
3069
3355
  * supported posture (the engine never reads history back to decide
3070
3356
  * anything), so `history === null` is silent while a *failing* store is loud.
3071
3357
  * @param {object} task - terminal task record.
3072
- * @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.
3073
3360
  */
3074
3361
  async persistHistory(task) {
3075
3362
  const history = this.history;
3076
- if (history === null || history === undefined || typeof history.save !== 'function') return;
3363
+ if (history === null || history === undefined || typeof history.save !== 'function') return true;
3077
3364
  let timer = null;
3078
3365
  try {
3079
3366
  const view = this.view(task);
@@ -3090,6 +3377,7 @@ export class JobEngine {
3090
3377
  await bounded;
3091
3378
  task.historyError = null;
3092
3379
  task.historySavedAt = Date.now();
3380
+ return true;
3093
3381
  } catch (error) {
3094
3382
  // Recorded, not thrown: a history failure must not turn a completed task
3095
3383
  // into a failed one, and it must not escape into the release path.
@@ -3098,6 +3386,7 @@ export class JobEngine {
3098
3386
  message: diagnostic(error?.message ?? error, 300),
3099
3387
  };
3100
3388
  task.historySavedAt = null;
3389
+ return false;
3101
3390
  } finally {
3102
3391
  if (timer !== null) clearTimeout(timer);
3103
3392
  }
@@ -3340,6 +3629,7 @@ export class JobEngine {
3340
3629
  const view = {
3341
3630
  taskId: task.taskId,
3342
3631
  state: task.state,
3632
+ title: task.title ?? taskTitle(null, task.prompt),
3343
3633
  phase: task.phase,
3344
3634
  createdAt: task.createdAt,
3345
3635
  startedAt: task.startedAt,
@@ -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
 
@@ -0,0 +1,17 @@
1
+ import { redactText } from '../config/redact.js';
2
+
3
+ /** A display title is task content, never a directory name or routing instruction. */
4
+ export function taskTitle(title, prompt = '') {
5
+ const lines = String(prompt).split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
6
+ const goal = lines.findIndex(line => /^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)(?:\s*[::]|\s*$)/iu.test(line));
7
+ let text = typeof title === 'string' ? title.trim() : '';
8
+ if (!text && goal >= 0) {
9
+ text = lines[goal].replace(/^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)\s*[::]?\s*/iu, '') || lines[goal + 1] || '';
10
+ }
11
+ if (!text) {
12
+ text = lines.find(line => !/^(?:you are\b|act as\b|你是|你负责|```|#{1,6}\s*(?:instructions|角色|执行规则))/iu.test(line)) || '委派任务';
13
+ }
14
+ text = redactText(text).replace(/^[#*\-\d.\s]+/u, '').replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim();
15
+ const chars = Array.from(text || '委派任务');
16
+ return chars.length > 48 ? chars.slice(0, 47).join('') + '…' : chars.join('');
17
+ }