dsh-taskbridge 1.3.2 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -423,7 +423,7 @@ export function validateReviewSettings(value, providers) {
423
423
  /**
424
424
  * Validate the activity-monitoring block.
425
425
  *
426
- * Two silence thresholds, both in whole seconds, both bounded:
426
+ * Two silence thresholds and one failure-count threshold:
427
427
  *
428
428
  * * `selfCheckSeconds` is when the engine performs ONE read-only local
429
429
  * inspection of the executor it already holds (alive, phase, pending request,
@@ -431,33 +431,39 @@ export function validateReviewSettings(value, providers) {
431
431
  * call and never touches the task's state, budget or deadline.
432
432
  * * `attentionSeconds` is when a wait stops keeping quiet and reports
433
433
  * `attention` to the commander instead of `heartbeat`.
434
+ * * `repeatFailureThreshold` is how many CONSECUTIVE identical tool failures are
435
+ * reported once, or `0` to switch that reminder off. It is a count, so it is
436
+ * independent of the two silence thresholds: a busy run that keeps failing the
437
+ * same way never reaches either of them.
434
438
  *
435
439
  * A missing block is the documented default (backwards compatible: documents
436
- * written before this field existed keep loading). Everything else is refused
437
- * rather than repaired — an unknown key (a typo such as `atentionSeconds` would
438
- * otherwise silently keep the default), a wrong type, a non-integer, an
440
+ * written before this field existed keep loading, and a document that has the other
441
+ * two but not this one gets the default rather than an error). Everything else is
442
+ * refused rather than repaired — an unknown key (a typo such as `atentionSeconds`
443
+ * would otherwise silently keep the default), a wrong type, a non-integer, an
439
444
  * out-of-range value, and any pair where the attention threshold is not strictly
440
- * greater than the self-check one. A repaired value would make the two timers
441
- * disagree with what the operator stored, which is exactly the class of silent
442
- * mismatch this plugin refuses everywhere else.
445
+ * greater than the self-check one. A repaired value would make the timers disagree
446
+ * with what the operator stored, which is exactly the class of silent mismatch this
447
+ * plugin refuses everywhere else.
443
448
  * @param {unknown} value - candidate monitoring block.
444
- * @returns {{ selfCheckSeconds: number, attentionSeconds: number }} normalized block.
449
+ * @returns {{ selfCheckSeconds: number, attentionSeconds: number, repeatFailureThreshold: number }} normalized block.
445
450
  */
446
451
  export function validateMonitoringSettings(value) {
447
452
  if (value === undefined || value === null) {
448
453
  return {
449
454
  selfCheckSeconds: MONITORING_DEFAULTS.selfCheckSeconds,
450
455
  attentionSeconds: MONITORING_DEFAULTS.attentionSeconds,
456
+ repeatFailureThreshold: MONITORING_DEFAULTS.repeatFailureThreshold,
451
457
  };
452
458
  }
453
459
  if (typeof value !== 'object' || Array.isArray(value)) {
454
460
  throw new ConfigError('MONITORING_INVALID', 'monitoring settings must be an object', { field: 'monitoring' });
455
461
  }
456
462
  for (const key of Object.keys(value)) {
457
- if (key !== 'selfCheckSeconds' && key !== 'attentionSeconds') {
463
+ if (key !== 'selfCheckSeconds' && key !== 'attentionSeconds' && key !== 'repeatFailureThreshold') {
458
464
  throw new ConfigError('MONITORING_INVALID', `monitoring setting ${key} is not supported`, {
459
465
  field: `monitoring.${key}`,
460
- supported: ['selfCheckSeconds', 'attentionSeconds'],
466
+ supported: ['selfCheckSeconds', 'attentionSeconds', 'repeatFailureThreshold'],
461
467
  });
462
468
  }
463
469
  }
@@ -482,7 +488,16 @@ export function validateMonitoringSettings(value) {
482
488
  { field: 'monitoring.attentionSeconds', selfCheckSeconds, attentionSeconds },
483
489
  );
484
490
  }
485
- return { selfCheckSeconds, attentionSeconds };
491
+ const repeatFailureThreshold = requireInt(
492
+ value.repeatFailureThreshold === undefined
493
+ ? MONITORING_DEFAULTS.repeatFailureThreshold
494
+ : value.repeatFailureThreshold,
495
+ 'MONITORING_INVALID',
496
+ 'monitoring.repeatFailureThreshold',
497
+ LIMITS.repeatFailureThresholdMin,
498
+ LIMITS.repeatFailureThresholdMax,
499
+ );
500
+ return { selfCheckSeconds, attentionSeconds, repeatFailureThreshold };
486
501
  }
487
502
 
488
503
  /** Validate legacy grant TTLs kept for backwards-compatible imports. */
@@ -20,6 +20,8 @@ import { fenceExternalConnection } from '../auth/fence.js';
20
20
  import { AUTH_CODES } from '../auth/grants.js';
21
21
  import { classifyError, HttpError, readJsonBody, sendJson } from '../http/respond.js';
22
22
  import { preflightWorkspace } from '../workspace/preflight.js';
23
+ import { redactText } from '../config/redact.js';
24
+ import { REVIEW_NOTE_MAX_CHARS, normalizeReviewNote, reviewNoteOverflow } from '../jobs/review-note.js';
23
25
 
24
26
  /** Route prefix owned by this plane. Deliberately not under `/api`. */
25
27
  export const EXECUTION_PREFIX = '/dsh-delegate/x';
@@ -64,6 +66,13 @@ export function createExecutionHandler(deps) {
64
66
  // The switch gate below applies to it exactly as it does to a submission,
65
67
  // because a decision is an authorization exercise like any other.
66
68
  ['POST /tasks/permission', decidePermission],
69
+ // The commander's DELIVERY REVIEW of one finished task. It is the only write that
70
+ // records `hostAcceptance`, and it is narrow on purpose: it decides no permission,
71
+ // changes no switch/provider/model/isolation/credential, merges no file and creates
72
+ // no task. Because it only records a conclusion about a result that already exists, it
73
+ // is NOT gated by the delegation switch — like `/tasks/get` and `/tasks/cancel`, it
74
+ // stays answerable with the switch off.
75
+ ['POST /tasks/review', recordHostReview],
67
76
  // Read-only workspace inspection for a dispatcher: the facts and the isolation
68
77
  // recommendation that used to be discovered only when a job admitted. It is a
69
78
  // separate route — not a field on `/tasks` — because it neither authorizes nor
@@ -109,10 +118,11 @@ export function createExecutionHandler(deps) {
109
118
 
110
119
  let connection;
111
120
  if (deps.engine.authorizationMode === 'switch') {
112
- // Both AUTHORIZING verbs need the switch: a submission creates work and a
113
- // decision releases a paused call. Reads, cancel and preflight stay
114
- // answerable while the switch is off, so an operator can always observe and
115
- // stop what already exists.
121
+ // Only the two AUTHORIZING verbs need the switch: a submission creates work and a
122
+ // decision releases a paused call. A delivery REVIEW is not one of them: it records
123
+ // a conclusion about an already-finished result, so it stays answerable with the
124
+ // switch off, exactly like reading or cancelling a task. Reads, cancel and
125
+ // preflight are equally unaffected.
116
126
  const gated = key === 'POST /tasks' || key === 'POST /tasks/permission';
117
127
  if (gated && deps.engine.posture().authorized !== true) {
118
128
  sendJson(res, 403, {
@@ -246,15 +256,31 @@ async function getTask({ req, res, connection, deps }) {
246
256
  if (typeof body.taskId !== 'string') {
247
257
  throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
248
258
  }
249
- const task = deps.engine.get(body.taskId);
250
- if (task.connectionId !== connection.connectionId) {
251
- // Cross-connection reads are reported as absent, not as forbidden: a
252
- // distinct code would confirm that a task id exists.
253
- throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task for this connection');
259
+ // The live map first (unchanged, synchronous), then the durable record of a finished
260
+ // task this connection owns. A restored row is evidence only: it is never re-executable.
261
+ let task;
262
+ try {
263
+ task = deps.engine.get(body.taskId);
264
+ if (task.connectionId !== connection.connectionId) {
265
+ // Cross-connection reads are reported as absent, not as forbidden: a
266
+ // distinct code would confirm that a task id exists.
267
+ throw new HttpError(404, 'JOB_TASK_NOT_FOUND', NOT_FOUND_MESSAGE);
268
+ }
269
+ } catch (error) {
270
+ if (error?.code !== 'JOB_TASK_NOT_FOUND' || typeof deps.engine.storedTaskRow !== 'function') throw error;
271
+ const row = await deps.engine.storedTaskRow(body.taskId, connection.connectionId);
272
+ // ONE answer for unknown, foreign and ownerless: the same status, code and message, so
273
+ // the reply cannot be used to learn that a task id exists on another connection.
274
+ if (row === null) throw new HttpError(404, 'JOB_TASK_NOT_FOUND', NOT_FOUND_MESSAGE);
275
+ sendJson(res, 200, { ok: true, task: deps.engine.historyViewOf(row) });
276
+ return;
254
277
  }
255
278
  sendJson(res, 200, { ok: true, task });
256
279
  }
257
280
 
281
+ /** The one refusal for a task this caller cannot prove: unknown, foreign or ownerless. */
282
+ const NOT_FOUND_MESSAGE = 'no such task for this connection';
283
+
258
284
  async function cancelTask({ req, res, connection, deps }) {
259
285
  const body = await readJsonBody(req);
260
286
  if (typeof body.taskId !== 'string') {
@@ -313,6 +339,79 @@ async function decidePermission({ req, res, connection, deps }) {
313
339
  sendJson(res, 200, { ok: true, ...result });
314
340
  }
315
341
 
342
+ /** Body fields `POST /tasks/review` accepts. Everything else is refused. */
343
+ const REVIEW_FIELDS = Object.freeze(['taskId', 'decision', 'note']);
344
+
345
+ /**
346
+ * Longest review note the route will even read, in Unicode code points.
347
+ *
348
+ * Re-exported from the one shared definition (`src/jobs/review-note.js`) so the MCP
349
+ * schema, this route, the engine and the durable history projection cannot drift: a note
350
+ * this route accepts but the engine cuts would be recorded as something the caller never
351
+ * wrote. Code points, not UTF-16 units, so a Chinese or emoji note gets the same room as
352
+ * an ASCII one and a surrogate pair is never split.
353
+ */
354
+ export const REVIEW_NOTE_LIMIT_CODE_POINTS = REVIEW_NOTE_MAX_CHARS;
355
+
356
+ /**
357
+ * Record the commander's delivery review of one finished task.
358
+ *
359
+ * The body is validated here as well as in the engine and in the MCP server, because this
360
+ * route is reachable by any local caller: a closed field set, a closed decision vocabulary
361
+ * and a bounded non-empty note are refused before anything is read or written. The
362
+ * connection identity is taken from the authenticated request, never from the body, so a
363
+ * caller can only review its OWN task.
364
+ * @param {object} context - `req`, `res`, `connection`, `deps`.
365
+ * @returns {Promise<void>} resolves after the answer is sent.
366
+ */
367
+ async function recordHostReview({ req, res, connection, deps }) {
368
+ const body = await readJsonBody(req);
369
+ for (const key of Object.keys(body)) {
370
+ if (!REVIEW_FIELDS.includes(key)) {
371
+ throw new HttpError(400, 'REVIEW_ARGUMENT_UNKNOWN', `tasks/review does not accept ${JSON.stringify(key)}`);
372
+ }
373
+ }
374
+ if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
375
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
376
+ }
377
+ if (body.decision !== 'accepted' && body.decision !== 'changes-requested') {
378
+ throw new HttpError(400, 'REVIEW_DECISION_INVALID', 'decision must be accepted or changes-requested');
379
+ }
380
+ const note = normalizeReviewNote(body.note);
381
+ if (note === '') {
382
+ throw new HttpError(400, 'REVIEW_NOTE_REQUIRED', 'note must be a non-empty string');
383
+ }
384
+ if (Array.from(note).length > REVIEW_NOTE_MAX_CHARS) {
385
+ // The same facts the engine reports: the actual length and the bound, in the same
386
+ // unit. Nothing is written and no existing record is touched.
387
+ const overflow = reviewNoteOverflow(note);
388
+ throw new HttpError(400, 'REVIEW_NOTE_TOO_LONG', overflow.message, {
389
+ limit: overflow.limit,
390
+ length: overflow.length,
391
+ unit: 'unicode-code-points',
392
+ });
393
+ }
394
+ let result;
395
+ try {
396
+ result = await deps.engine.recordHostReview({
397
+ // The verified connection, not `body.connectionId`: a caller cannot name an owner.
398
+ connectionId: connection.connectionId,
399
+ taskId: body.taskId,
400
+ decision: body.decision,
401
+ note,
402
+ });
403
+ } catch (error) {
404
+ // A finished task read back from durable history (after a restart) is reviewed through
405
+ // the same rules, against the stored record. Any OTHER refusal keeps its own code.
406
+ if (error?.code !== 'JOB_TASK_NOT_FOUND' || typeof deps.engine.recordHistoricalReview !== 'function') throw error;
407
+ result = await deps.engine.recordHistoricalReview({
408
+ taskId: body.taskId,
409
+ connectionId: connection.connectionId,
410
+ }, body.decision, redactText(note), null);
411
+ }
412
+ sendJson(res, 200, { ok: true, ...result });
413
+ }
414
+
316
415
  /**
317
416
  * Report a bounded observation of one task of this connection.
318
417
  *
@@ -369,11 +468,82 @@ async function observeTask({ req, res, connection, deps }) {
369
468
  // and writing to a closed response would only throw into the refusal path.
370
469
  if (abandonment.abandoned() || !isWritable(res)) return;
371
470
  sendJson(res, 200, { ok: true, ...observation });
471
+ } catch (error) {
472
+ if (error?.code !== 'JOB_TASK_NOT_FOUND' || typeof deps.engine.storedTaskRow !== 'function') throw error;
473
+ // A finished task that survived a restart is reported AT ONCE as its stored outcome.
474
+ // It is never waited on: there is no live executor, and an old stored permission
475
+ // request can never be decided, so this must not enter a wait loop.
476
+ const observation = await historyObservation(deps, body.taskId, connection);
477
+ if (abandonment.abandoned() || !isWritable(res)) return;
478
+ sendJson(res, 200, { ok: true, wait: { waitMs, waitedMs: 0, activitySinceWait: false }, ...observation });
372
479
  } finally {
373
480
  abandonment.dispose();
374
481
  }
375
482
  }
376
483
 
484
+ /**
485
+ * The immediate observation of one stored (restarted) task.
486
+ *
487
+ * The reason follows the stored terminal state exactly (`failed`, `cancelled`,
488
+ * `interrupted`, or `ready` for a run awaiting review), so a restored failure is never
489
+ * reported as a result to review. The summary is the COMPACT observation shape, not the
490
+ * full record: no execution text, no diff and no review note travel on a wait, and no
491
+ * permission request is ever offered — an old one can never be decided.
492
+ * @param {object} deps - handler deps.
493
+ * @param {string} taskId - requested task id.
494
+ * @param {object} connection - verified connection.
495
+ * @returns {Promise<object>} observation fields.
496
+ */
497
+ async function historyObservation(deps, taskId, connection) {
498
+ const row = await deps.engine.storedTaskRow(taskId, connection.connectionId);
499
+ if (row === null) throw new HttpError(404, 'JOB_TASK_NOT_FOUND', NOT_FOUND_MESSAGE);
500
+ const view = deps.engine.historyViewOf(row);
501
+ const reason = HISTORY_REASON[row.state] ?? 'ready';
502
+ const acceptance = view.hostAcceptance === null ? null : view.hostAcceptance;
503
+ return {
504
+ task: {
505
+ taskId: view.taskId,
506
+ state: view.state,
507
+ phase: view.phase,
508
+ title: view.title ?? null,
509
+ createdAt: view.createdAt ?? null,
510
+ startedAt: view.startedAt ?? null,
511
+ endedAt: view.endedAt ?? null,
512
+ route: view.route ?? null,
513
+ connectionId: view.connectionId ?? null,
514
+ selfApproved: false,
515
+ // The CONCLUSION's status and time, never its body: a wait stays short (R5) and the
516
+ // full note is read on demand through `delegate_result`.
517
+ hostAcceptance: acceptance === null
518
+ ? null
519
+ : {
520
+ accepted: acceptance.accepted === true,
521
+ state: acceptance.state ?? null,
522
+ acceptedAt: acceptance.acceptedAt ?? null,
523
+ by: acceptance.by ?? null,
524
+ noteChars: acceptance.noteChars ?? 0,
525
+ noteOmitted: true,
526
+ },
527
+ reviewPersistence: view.reviewPersistence,
528
+ source: 'history',
529
+ evidence: view.evidence,
530
+ },
531
+ reason,
532
+ permission: null,
533
+ failure: null,
534
+ activity: null,
535
+ selfCheck: null,
536
+ };
537
+ }
538
+
539
+ /** The observation reason of a stored terminal state. */
540
+ const HISTORY_REASON = Object.freeze({
541
+ 'awaiting-host-review': 'ready',
542
+ failed: 'failed',
543
+ cancelled: 'cancelled',
544
+ interrupted: 'interrupted',
545
+ });
546
+
377
547
  /**
378
548
  * Watch one request/response pair for a real, premature disconnect.
379
549
  *