dsh-taskbridge 1.5.4 → 1.7.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +80 -59
  2. package/README.md +51 -50
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/bin/dsh-delegate-mcp.d.ts +1 -0
  5. package/bin/dsh-delegate-mcp.js +1 -0
  6. package/codex/dsh-taskbridge.toml +148 -71
  7. package/docs/INTRODUCTION.md +44 -22
  8. package/docs/INTRODUCTION.zh.md +32 -26
  9. package/docs/codex-integration.md +99 -19
  10. package/docs/contracts-stage-b.md +4 -4
  11. package/docs/conversation-placement.md +25 -7
  12. package/docs/plugin-market.md +1 -1
  13. package/docs/releases/1.6.0.zh.md +11 -0
  14. package/docs/releases/1.7.0.zh.md +11 -0
  15. package/docs/runtime-compatibility.md +10 -11
  16. package/docs/silent-wait.md +69 -31
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +11 -21
  19. package/docs/workspace-grouping.md +126 -0
  20. package/lib/client.d.ts +581 -0
  21. package/lib/client.js +332 -3461
  22. package/locale/en.json +1 -1
  23. package/locale/zh.json +1 -1
  24. package/package.json +7 -19
  25. package/src/client/api.js +895 -90
  26. package/src/client/index.jsx +1363 -296
  27. package/src/client/sidebar.jsx +862 -0
  28. package/src/client/styles.js +340 -0
  29. package/src/client/task-cleanup.js +304 -0
  30. package/src/client/task-records-table.jsx +217 -0
  31. package/src/client/task-view.js +307 -0
  32. package/src/client/workspace-groups.js +482 -0
  33. package/src/client/workspaces-browser.jsx +770 -0
  34. package/src/codex/agent-ownership.js +270 -0
  35. package/src/codex/installer.js +528 -35
  36. package/src/codex/seam.js +5 -0
  37. package/src/config/defaults.js +63 -17
  38. package/src/config/settings.js +60 -62
  39. package/src/config/validate.js +126 -71
  40. package/src/http/execution-plane.js +200 -1
  41. package/src/http/respond.js +26 -2
  42. package/src/http/user-plane.js +566 -2
  43. package/src/index.d.ts +55 -0
  44. package/src/index.js +58 -42
  45. package/src/jobs/activity.js +968 -78
  46. package/src/jobs/engine.js +1010 -230
  47. package/src/jobs/history.js +224 -12
  48. package/src/jobs/plan-store.js +1020 -0
  49. package/src/jobs/record-cleanup.js +196 -0
  50. package/src/jobs/task-display.js +73 -0
  51. package/src/jobs/task-tree.js +786 -0
  52. package/src/jobs/title.js +129 -12
  53. package/src/mcp/server.js +206 -10
  54. package/src/mcp/wait.js +64 -5
  55. package/src/runtime/agent-runner.js +101 -15
  56. package/src/runtime/worker-prompt.js +53 -0
  57. package/src/workspace/locks.js +288 -167
  58. package/docs/assets/taskbridge-workflow.en.png +0 -0
  59. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  60. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  61. package/docs/releases/1.4.0.zh.md +0 -54
  62. package/docs/releases/1.4.1.zh.md +0 -59
  63. package/docs/releases/1.4.2.zh.md +0 -23
  64. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  65. package/docs/releases/1.5.0.zh.md +0 -51
  66. package/docs/releases/1.5.1.zh.md +0 -70
  67. package/docs/releases/1.5.2.zh.md +0 -30
  68. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  69. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  70. package/docs/releases/1.5.3.zh.md +0 -33
  71. package/docs/releases/1.5.4.zh.md +0 -25
  72. package/src/review/preset.js +0 -868
  73. package/src/review/prompts.js +0 -145
  74. package/src/review/reviewer.js +0 -933
@@ -9,6 +9,7 @@
9
9
  import { posix, win32 } from 'node:path';
10
10
 
11
11
  import {
12
+ DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS,
12
13
  DEFAULT_ISOLATION,
13
14
  EFFORT_ORDER,
14
15
  ISOLATION_MODES,
@@ -356,6 +357,26 @@ function validateIsolation(value, code, field) {
356
357
  return isolation;
357
358
  }
358
359
 
360
+ /**
361
+ * Normalize the LEGACY `worker.timeoutSeconds` value.
362
+ *
363
+ * The field is retired as a knob — the settings page no longer offers it and an
364
+ * ordinary run is not bounded by it — but a stored document that carries one must
365
+ * still open. The rule is therefore "read it, never refuse it": a whole number
366
+ * inside the documented bounds is preserved (so a reader can still see what the
367
+ * old document said), and anything else — out of range, fractional, textual, a
368
+ * negative number — falls back to the documented default. Nothing is clamped into
369
+ * a different number nobody chose, and nothing here can make a task fail to start.
370
+ * @param {unknown} value - stored legacy value.
371
+ * @returns {number} a whole number of seconds inside the documented bounds.
372
+ */
373
+ export function legacyTimeoutSeconds(value) {
374
+ const candidate = typeof value === 'number' ? value : (typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN);
375
+ if (!Number.isSafeInteger(candidate)) return 1800;
376
+ if (candidate < LIMITS.timeoutSecondsMin || candidate > LIMITS.timeoutSecondsMax) return 1800;
377
+ return candidate;
378
+ }
379
+
359
380
  /**
360
381
  * Validate the worker execution settings block.
361
382
  * @param {unknown} value - candidate worker block.
@@ -368,13 +389,13 @@ export function validateWorkerSettings(value, providers) {
368
389
  throw new ConfigError('WORKER_INVALID', 'worker settings must be an object', {});
369
390
  }
370
391
  const selection = validateSelection(source, providers, 'worker');
371
- const timeoutSeconds = requireInt(
372
- source.timeoutSeconds ?? 1800,
373
- 'WORKER_TIMEOUT_INVALID',
374
- 'worker.timeoutSeconds',
375
- LIMITS.timeoutSecondsMin,
376
- LIMITS.timeoutSecondsMax,
377
- );
392
+ // `timeoutSeconds` is a LEGACY field: it is no longer offered in the settings
393
+ // page and no longer bounds an ordinary run, but a document written by an older
394
+ // build (or an older client that still sends it) must keep loading. So the value
395
+ // is READ AND NORMALIZED, never refused: an out-of-range, fractional or
396
+ // non-numeric legacy value falls back to the documented default instead of
397
+ // failing the whole document, and the run is not limited by it either way.
398
+ const timeoutSeconds = legacyTimeoutSeconds(source.timeoutSeconds);
378
399
  const maxParallelism = requireInt(
379
400
  source.maxParallelism ?? 1,
380
401
  'WORKER_PARALLELISM_INVALID',
@@ -395,56 +416,40 @@ export function validateWorkerSettings(value, providers) {
395
416
  };
396
417
  }
397
418
 
398
- /**
399
- * Validate the additional-review block. Review is off unless explicitly enabled
400
- * and it owns a fully separate provider/model/effort triple.
401
- * @param {unknown} value - candidate review block.
402
- * @param {object[]} providers - validated providers.
403
- * @returns {object} normalized review block.
404
- */
405
- export function validateReviewSettings(value, providers) {
406
- const source = value ?? {};
407
- if (typeof source !== 'object' || Array.isArray(source)) {
408
- throw new ConfigError('REVIEW_INVALID', 'review settings must be an object', {});
409
- }
410
- const enabled = requireBool(source.enabled ?? false, 'REVIEW_INVALID', 'review.enabled');
411
- if (!enabled) {
412
- return { enabled: false, providerId: null, model: null, reasoningEffort: null };
413
- }
414
- const selection = validateSelection(source, providers, 'review');
415
- return {
416
- enabled: true,
417
- providerId: selection.providerId,
418
- model: selection.model,
419
- reasoningEffort: selection.reasoningEffort,
420
- };
421
- }
422
-
423
419
  /**
424
420
  * Validate the activity-monitoring block.
425
421
  *
426
- * Two silence thresholds and one failure-count threshold:
422
+ * Two no-progress thresholds and one failure-count threshold. Each is INDEPENDENT and
423
+ * each can be switched off with `0`. There is exactly ONE time base — consecutive time
424
+ * without real progress — and nothing here depends on total runtime:
427
425
  *
428
426
  * * `selfCheckSeconds` is when the engine performs ONE read-only local
429
427
  * inspection of the executor it already holds (alive, phase, pending request,
430
428
  * current tool) and reports it on an internal re-wait. It never starts an LLM
431
- * call and never touches the task's state, budget or deadline.
432
- * * `attentionSeconds` is when a wait stops keeping quiet and reports
433
- * `attention` to the commander instead of `heartbeat`.
429
+ * call and never touches the task's state, budget or deadline. Default 10 min.
430
+ * * `attentionSeconds` is when a wait stops keeping quiet and reports ONE run
431
+ * progress check to the commander — `reason: "attention"` with
432
+ * `checkpoint: "progress"` — instead of `heartbeat`. It is a report, never an
433
+ * action: the run is not cancelled, restarted or resubmitted. Default 40 min.
434
434
  * * `repeatFailureThreshold` is how many CONSECUTIVE identical tool failures are
435
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
436
+ * independent of the two duration thresholds: a busy run that keeps failing the
437
437
  * same way never reaches either of them.
438
438
  *
439
439
  * A missing block is the documented default (backwards compatible: documents
440
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
444
- * out-of-range value, and any pair where the attention threshold is not strictly
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.
441
+ * keys but not one of them gets that key's default rather than an error). Everything
442
+ * else is refused rather than repaired — an unknown key (a typo such as
443
+ * `atentionSeconds` would otherwise silently keep the default), a wrong type, a
444
+ * non-integer, an out-of-range value, and any pair where BOTH thresholds are enabled
445
+ * and the progress check is not strictly after the self-check. A repaired value would make
446
+ * the timers disagree with what the operator stored, which is exactly the class of
447
+ * silent mismatch this plugin refuses everywhere else.
448
+ *
449
+ * A stored document that still carries a value the earlier build offered as its own
450
+ * progress cadence is READ AND DROPPED rather than refused: that value was never
451
+ * published, it is not a second clock, and refusing the document would make an
452
+ * operator's settings unreadable over a field no longer shown anywhere.
448
453
  * @param {unknown} value - candidate monitoring block.
449
454
  * @returns {{ selfCheckSeconds: number, attentionSeconds: number, repeatFailureThreshold: number }} normalized block.
450
455
  */
@@ -460,6 +465,7 @@ export function validateMonitoringSettings(value) {
460
465
  throw new ConfigError('MONITORING_INVALID', 'monitoring settings must be an object', { field: 'monitoring' });
461
466
  }
462
467
  for (const key of Object.keys(value)) {
468
+ if (key === 'progressCheckSeconds') continue;
463
469
  if (key !== 'selfCheckSeconds' && key !== 'attentionSeconds' && key !== 'repeatFailureThreshold') {
464
470
  throw new ConfigError('MONITORING_INVALID', `monitoring setting ${key} is not supported`, {
465
471
  field: `monitoring.${key}`,
@@ -481,10 +487,12 @@ export function validateMonitoringSettings(value) {
481
487
  LIMITS.attentionSecondsMin,
482
488
  LIMITS.attentionSecondsMax,
483
489
  );
484
- if (attentionSeconds <= selfCheckSeconds) {
490
+ // Ordering matters only when BOTH reminders are on. A disabled threshold has no
491
+ // instant of its own, so `0` can never be "too early" for the other one.
492
+ if (selfCheckSeconds > 0 && attentionSeconds > 0 && attentionSeconds <= selfCheckSeconds) {
485
493
  throw new ConfigError(
486
494
  'MONITORING_TIMING_INVALID',
487
- 'monitoring.attentionSeconds must be greater than monitoring.selfCheckSeconds',
495
+ 'monitoring.attentionSeconds must be greater than monitoring.selfCheckSeconds when both are enabled',
488
496
  { field: 'monitoring.attentionSeconds', selfCheckSeconds, attentionSeconds },
489
497
  );
490
498
  }
@@ -500,8 +508,53 @@ export function validateMonitoringSettings(value) {
500
508
  return { selfCheckSeconds, attentionSeconds, repeatFailureThreshold };
501
509
  }
502
510
 
503
- /** Validate legacy grant TTLs kept for backwards-compatible imports. */
504
- export function validateAuthorizationSettings(value) {
511
+ /**
512
+ * Validate the operator's execution-choice block.
513
+ *
514
+ * Today it holds exactly one decision: whether a new delegated task should have
515
+ * DSH Agent Teams on when its dispatcher states no per-task choice. The rules:
516
+ *
517
+ * * the block is optional — a document written before it existed, and a host
518
+ * that never served one, both load at the documented OFF default, so an
519
+ * upgrade can never turn collaboration on by itself;
520
+ * * the value must be a real boolean. `"false"`, `0` and `null` are REFUSED
521
+ * rather than coerced: a value that reads as "off" to a reader but is not a
522
+ * boolean would be stored as an intention nobody can honour;
523
+ * * an unknown key is refused, not ignored (a typo such as
524
+ * `agentTeamDefault` would otherwise silently keep the default).
525
+ *
526
+ * The block is a TASK default only. It is not DSH's global switch and nothing
527
+ * here writes a global setting.
528
+ * @param {unknown} value - candidate `execution` block.
529
+ * @returns {{ agentTeamsDefault: boolean }} normalized block.
530
+ */
531
+ export function validateExecutionSettings(value) {
532
+ if (value === undefined || value === null) {
533
+ return { agentTeamsDefault: DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS };
534
+ }
535
+ if (typeof value !== 'object' || Array.isArray(value)) {
536
+ throw new ConfigError('EXECUTION_SETTINGS_INVALID', 'execution settings must be an object', {
537
+ field: 'execution',
538
+ });
539
+ }
540
+ for (const key of Object.keys(value)) {
541
+ if (key !== 'agentTeamsDefault') {
542
+ throw new ConfigError('EXECUTION_SETTINGS_INVALID', `execution setting ${key} is not supported`, {
543
+ field: `execution.${key}`,
544
+ supported: ['agentTeamsDefault'],
545
+ });
546
+ }
547
+ }
548
+ return {
549
+ agentTeamsDefault: requireBool(
550
+ value.agentTeamsDefault === undefined ? DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS : value.agentTeamsDefault,
551
+ 'EXECUTION_SETTINGS_INVALID',
552
+ 'execution.agentTeamsDefault',
553
+ ),
554
+ };
555
+ }
556
+
557
+ /** Validate legacy grant TTLs kept for backwards-compatible imports. */export function validateAuthorizationSettings(value) {
505
558
  const source = value ?? {};
506
559
  if (typeof source !== 'object' || Array.isArray(source)) {
507
560
  throw new ConfigError('AUTHORIZATION_INVALID', 'authorization settings must be an object', {});
@@ -563,6 +616,11 @@ export function validateJobOverrides(value, providers) {
563
616
  out.reasoningEffort = null;
564
617
  }
565
618
  if (value.timeoutSeconds !== undefined) {
619
+ // The ONE compatibility path that still bounds a run: a caller that explicitly
620
+ // asks for a per-job cap gets exactly that cap. It is deliberately not offered
621
+ // in the settings page (a stored global value never bounds a task), so an
622
+ // operator can never inherit an unintended deadline — only a dispatch that
623
+ // names one states it.
566
624
  out.timeoutSeconds = requireInt(
567
625
  value.timeoutSeconds,
568
626
  'WORKER_TIMEOUT_INVALID',
@@ -589,7 +647,6 @@ export function validateProjectOverride(value, providers) {
589
647
  }
590
648
  const out = {};
591
649
  if (value.worker !== undefined) out.worker = validateWorkerSettings(value.worker, providers);
592
- if (value.review !== undefined) out.review = validateReviewSettings(value.review, providers);
593
650
  return out;
594
651
  }
595
652
 
@@ -655,6 +712,8 @@ export function validateProjectOverrides(value, providers) {
655
712
  const seen = new Map();
656
713
  for (const [projectPath, block] of Object.entries(raw)) {
657
714
  const { key, display } = canonicalProjectKey(projectPath, 'projectOverrides key');
715
+ const override = validateProjectOverride(block, providers);
716
+ if (block.review !== undefined && override.worker === undefined) continue;
658
717
  const existing = seen.get(key);
659
718
  if (existing !== undefined) {
660
719
  throw new ConfigError('PROJECT_OVERRIDE_DUPLICATE', 'two project overrides name the same project', {
@@ -663,18 +722,17 @@ export function validateProjectOverrides(value, providers) {
663
722
  });
664
723
  }
665
724
  seen.set(key, display);
666
- out[display] = validateProjectOverride(block, providers);
725
+ out[display] = override;
667
726
  }
668
727
  return out;
669
728
  }
670
729
 
671
730
  /**
672
- * Validate one named preset: a reusable, entirely non-secret worker/review
673
- * combination. Both blocks are validated against the same provider list as live
674
- * settings, so a preset can never store a combination that settings would refuse.
731
+ * Validate one named worker preset. Older presets that configured only the
732
+ * retired model review are omitted without validating their unused selection.
675
733
  * @param {unknown} value - candidate preset.
676
734
  * @param {object[]} providers - validated providers.
677
- * @returns {{ id: string, name: string, worker: object | null, review: object | null }} normalized preset.
735
+ * @returns {{ id: string, name: string, worker: object } | null} normalized preset.
678
736
  */
679
737
  export function validatePreset(value, providers) {
680
738
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
@@ -682,15 +740,11 @@ export function validatePreset(value, providers) {
682
740
  }
683
741
  const id = requireString(value.id, 'PRESET_INVALID', 'preset.id', { max: 40, pattern: ID_PATTERN });
684
742
  const name = requireString(value.name ?? id, 'PRESET_INVALID', 'preset.name', { max: 80 });
685
- if (value.worker === undefined && value.review === undefined) {
686
- throw new ConfigError('PRESET_INVALID', 'preset must contain worker or review settings', { id });
743
+ if (value.worker === undefined || value.worker === null) {
744
+ if (value.review !== undefined && value.review !== null) return null;
745
+ throw new ConfigError('PRESET_INVALID', 'preset must contain worker settings', { id });
687
746
  }
688
- return {
689
- id,
690
- name,
691
- worker: value.worker === undefined ? null : validateWorkerSettings(value.worker, providers),
692
- review: value.review === undefined ? null : validateReviewSettings(value.review, providers),
693
- };
747
+ return { id, name, worker: validateWorkerSettings(value.worker, providers) };
694
748
  }
695
749
 
696
750
  /**
@@ -707,7 +761,7 @@ export function validatePresets(value, providers) {
707
761
  if (raw.length > LIMITS.presets) {
708
762
  throw new ConfigError('PRESET_INVALID', `presets exceeds ${LIMITS.presets} entries`, {});
709
763
  }
710
- const presets = raw.map((entry) => validatePreset(entry, providers));
764
+ const presets = raw.map((entry) => validatePreset(entry, providers)).filter((preset) => preset !== null);
711
765
  const seen = new Set();
712
766
  for (const preset of presets) {
713
767
  if (seen.has(preset.id)) throw new ConfigError('PRESET_DUPLICATE', `duplicate preset id ${preset.id}`, { id: preset.id });
@@ -724,8 +778,6 @@ export function validatePresets(value, providers) {
724
778
  function isUnconfiguredSelection(value) {
725
779
  if (value === null || value === undefined) return true;
726
780
  if (typeof value !== 'object' || Array.isArray(value)) return false;
727
- const enabled = value.enabled;
728
- if (enabled === true) return false;
729
781
  return (value.providerId ?? null) === null;
730
782
  }
731
783
 
@@ -752,13 +804,14 @@ export function validateSettings(value, options = {}) {
752
804
  // fresh install can add its first provider before choosing a worker. It is
753
805
  // never legal to RUN: resolveEffectiveConfig refuses it, which keeps the
754
806
  // refusal at the job boundary instead of at every settings edit.
807
+ //
808
+ // The default block is used as the BASE, not as a replacement: a legacy document
809
+ // that still carries `worker.timeoutSeconds` must keep that value verbatim even
810
+ // before a provider is chosen, or a settings save would silently rewrite a field
811
+ // nobody touched.
755
812
  const worker = isUnconfiguredSelection(value.worker)
756
- ? defaultSettings().worker
813
+ ? { ...defaultSettings().worker, timeoutSeconds: legacyTimeoutSeconds(value.worker?.timeoutSeconds) }
757
814
  : validateWorkerSettings(value.worker ?? {}, providers);
758
- const review = isUnconfiguredSelection(value.review)
759
- ? defaultSettings().review
760
- : validateReviewSettings(value.review ?? {}, providers);
761
-
762
815
  if (options.requireProviders === true && providers.length === 0) {
763
816
  throw new ConfigError('SETTINGS_NO_PROVIDERS', 'no provider profile is configured', {});
764
817
  }
@@ -768,8 +821,10 @@ export function validateSettings(value, options = {}) {
768
821
  delegationEnabled: requireBool(value.delegationEnabled ?? false, 'SETTINGS_INVALID', 'delegationEnabled'),
769
822
  providers,
770
823
  worker,
771
- review,
772
824
  authorization: validateAuthorizationSettings(value.authorization),
825
+ // The operator's default for NEW tasks. An absent block is the documented
826
+ // OFF default, which is also what an upgraded document loads as.
827
+ execution: validateExecutionSettings(value.execution),
773
828
  monitoring: validateMonitoringSettings(value.monitoring),
774
829
  projectOverrides: validateProjectOverrides(value.projectOverrides, providers),
775
830
  presets: validatePresets(value.presets, providers),
@@ -26,6 +26,9 @@ import {
26
26
  TASK_DESCRIPTION_FIELDS,
27
27
  canonicalTaskDescription,
28
28
  } from '../jobs/task-descriptions.js';
29
+ import { PLAN_CODES } from '../jobs/plan-store.js';
30
+ import { buildTaskTree } from '../jobs/task-tree.js';
31
+ import { recordedDirectoryIs } from '../jobs/continuation-identity.js';
29
32
 
30
33
  /** Route prefix owned by this plane. Deliberately not under `/api`. */
31
34
  export const EXECUTION_PREFIX = '/dsh-delegate/x';
@@ -88,6 +91,7 @@ export function createExecutionHandler(deps) {
88
91
  // is NOT gated by the delegation switch — like `/tasks/get` and `/tasks/cancel`, it
89
92
  // stays answerable with the switch off.
90
93
  ['POST /tasks/review', recordHostReview],
94
+ ['POST /plans', managePlans],
91
95
  // Read-only workspace inspection for a dispatcher: the facts and the isolation
92
96
  // recommendation that used to be discovered only when a job admitted. It is a
93
97
  // separate route — not a field on `/tasks` — because it neither authorizes nor
@@ -242,7 +246,7 @@ async function submitTask({ req, res, connection, deps }) {
242
246
  const overrides = body.agentTeams === undefined
243
247
  ? body.overrides
244
248
  : { ...(body.overrides ?? {}), agentTeams: body.agentTeams };
245
- // Checked here as well as in the engine: a bad or redaction-lengthened goal is refused
249
+ // Checked here as well as in the engine: a bad or redaction-lengthened goal is refused
246
250
  // before a task, slot or consumed grant exists.
247
251
  const goal = canonicalTaskDescription(body.goalDescription, TASK_DESCRIPTION_FIELDS.goal, redactText);
248
252
  if (goal.ok === false) {
@@ -255,6 +259,16 @@ async function submitTask({ req, res, connection, deps }) {
255
259
  }
256
260
  // The canonical value travels on; the engine re-derives the same form (a no-op).
257
261
  const goalField = goal.value === null ? {} : { goalDescription: goal.value };
262
+ if (body.planNodeId !== undefined && typeof body.planNodeId !== 'string') {
263
+ throw new HttpError(400, 'JOB_PLAN_REF_INVALID', 'planNodeId must be a string', { field: 'planNodeId' });
264
+ }
265
+ if (body.parentNodeId !== undefined && typeof body.parentNodeId !== 'string') {
266
+ throw new HttpError(400, 'JOB_PLAN_REF_INVALID', 'parentNodeId must be a string', { field: 'parentNodeId' });
267
+ }
268
+ const hierarchyFields = {
269
+ ...(body.planNodeId === undefined ? {} : { planNodeId: body.planNodeId }),
270
+ ...(body.parentNodeId === undefined ? {} : { parentNodeId: body.parentNodeId }),
271
+ };
258
272
  if (deps.engine.authorizationMode === 'switch') {
259
273
  const task = await deps.engine.start({
260
274
  connectionId: connection.connectionId,
@@ -263,6 +277,7 @@ async function submitTask({ req, res, connection, deps }) {
263
277
  ...(body.title === undefined ? {} : { title: body.title }),
264
278
  overrides,
265
279
  ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
280
+ ...hierarchyFields,
266
281
  ...goalField,
267
282
  });
268
283
  sendJson(res, 202, { ok: true, task });
@@ -282,6 +297,7 @@ async function submitTask({ req, res, connection, deps }) {
282
297
  ...(body.title === undefined ? {} : { title: body.title }),
283
298
  overrides,
284
299
  ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
300
+ ...hierarchyFields,
285
301
  ...goalField,
286
302
  });
287
303
  sendJson(res, 202, { ok: true, task });
@@ -770,3 +786,186 @@ async function preflight({ req, res, deps }) {
770
786
  });
771
787
  sendJson(res, 200, result);
772
788
  }
789
+
790
+ const PLAN_ALLOWED_FIELDS = Object.freeze({
791
+ create: Object.freeze(['action', 'title', 'goalDescription', 'parentNodeId', 'workspacePath', 'nodes']),
792
+ update: Object.freeze(['action', 'nodeId', 'title', 'goalDescription', 'workspacePath', 'parentNodeId']),
793
+ review: Object.freeze(['action', 'nodeId', 'decision', 'note', 'completionSummary']),
794
+ get: Object.freeze(['action', 'nodeId']),
795
+ list: Object.freeze(['action', 'workspacePath']),
796
+ });
797
+
798
+ async function managePlans({ req, res, connection, deps }) {
799
+ const body = await readJsonBody(req);
800
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
801
+ const allowedFields = PLAN_ALLOWED_FIELDS[action];
802
+ if (allowedFields === undefined) {
803
+ throw new HttpError(400, PLAN_CODES.invalid, 'action must be one of create, update, review, get, list');
804
+ }
805
+ for (const key of Object.keys(body)) {
806
+ if (!allowedFields.includes(key)) {
807
+ throw new HttpError(400, PLAN_CODES.invalid, `plan ${action} does not accept field ${JSON.stringify(key)}`, {
808
+ action,
809
+ field: key,
810
+ });
811
+ }
812
+ }
813
+
814
+ if (action === 'create' || action === 'update') {
815
+ if (deps.engine.posture().authorized !== true) {
816
+ const code = deps.engine.authorizationMode === 'switch' ? 'DELEGATION_DISABLED' : 'JOB_NOT_AUTHORIZED';
817
+ const msg = deps.engine.authorizationMode === 'switch'
818
+ ? 'delegation is disabled in DSH settings'
819
+ : 'no live delegation authorization exists';
820
+ throw new HttpError(403, code, msg);
821
+ }
822
+ }
823
+
824
+ const plans = deps.plans ?? deps.engine?.plans ?? null;
825
+ if (plans === null || typeof plans.load !== 'function') {
826
+ throw new HttpError(503, 'JOB_PLAN_STORE_UNAVAILABLE', 'the plan store is unavailable in this deployment');
827
+ }
828
+
829
+ const connectionId = connection.connectionId;
830
+
831
+ if (action === 'create') {
832
+ const resolveExternalParent = typeof deps.engine?.resolveHierarchyParentFacts === 'function'
833
+ ? (parentId, connId, existingPlanMap) => deps.engine.resolveHierarchyParentFacts(parentId, connId, existingPlanMap)
834
+ : undefined;
835
+ const outcome = await plans.create({ ...body, connectionId }, { resolveExternalParent });
836
+ sendJson(res, 201, {
837
+ ok: true,
838
+ ...(outcome.node !== undefined ? { node: outcome.node } : {}),
839
+ nodes: outcome.nodes,
840
+ });
841
+ return;
842
+ }
843
+
844
+ if (action === 'update') {
845
+ const node = await plans.update({ ...body, connectionId });
846
+ sendJson(res, 200, { ok: true, node });
847
+ return;
848
+ }
849
+
850
+ if (action === 'review') {
851
+ const outcome = await plans.review({ ...body, connectionId });
852
+ sendJson(res, 200, { ok: true, node: outcome.node, replayed: outcome.replayed });
853
+ return;
854
+ }
855
+
856
+ if (action === 'get') {
857
+ const nodeId = typeof body.nodeId === 'string' ? body.nodeId.trim() : '';
858
+ if (nodeId === '') {
859
+ throw new HttpError(400, PLAN_CODES.invalid, 'nodeId is required for plan get', { field: 'nodeId' });
860
+ }
861
+ const node = await plans.get(nodeId, connectionId);
862
+ if (node === null) {
863
+ throw new HttpError(404, PLAN_CODES.nodeNotFound, 'no such plan node for this connection', { nodeId });
864
+ }
865
+ const { planNodes, tasks } = await connectionTreeInputs(deps, connectionId);
866
+ const tree = buildTaskTree({ planNodes, tasks });
867
+ const treeNode = findTreeNode(tree.roots, node.nodeId);
868
+ sendJson(res, 200, {
869
+ ok: true,
870
+ node,
871
+ treeNode: treeNode === null ? null : compactTreeNodeSummary(treeNode),
872
+ });
873
+ return;
874
+ }
875
+
876
+ let { planNodes, tasks } = await connectionTreeInputs(deps, connectionId);
877
+ if (body.workspacePath !== undefined) {
878
+ if (typeof body.workspacePath !== 'string' || body.workspacePath.trim() === '') {
879
+ throw new HttpError(400, PLAN_CODES.invalid, 'workspacePath must be a non-empty string when provided', {
880
+ field: 'workspacePath',
881
+ });
882
+ }
883
+ const targetWs = body.workspacePath.trim();
884
+ planNodes = planNodes.filter((n) => (
885
+ (n.sourcePath !== null || n.sourcePathDigest !== null)
886
+ && recordedDirectoryIs({ path: n.sourcePath, digest: n.sourcePathDigest }, targetWs)
887
+ ));
888
+ tasks = tasks.filter((t) => (
889
+ (t.sourcePath !== null || t.sourcePathDigest !== null)
890
+ && recordedDirectoryIs({ path: t.sourcePath, digest: t.sourcePathDigest }, targetWs)
891
+ ));
892
+ }
893
+ const tree = buildTaskTree({ planNodes, tasks });
894
+ sendJson(res, 200, {
895
+ ok: true,
896
+ nodes: planNodes,
897
+ tree: {
898
+ flatNodes: tree.flatNodes,
899
+ orphans: tree.orphans,
900
+ projects: tree.projects,
901
+ counts: tree.counts,
902
+ },
903
+ });
904
+ }
905
+
906
+ async function connectionTreeInputs(deps, connectionId) {
907
+ const plans = deps.plans ?? deps.engine?.plans ?? null;
908
+ const planNodes = plans && typeof plans.load === 'function'
909
+ ? await plans.load({ connectionId })
910
+ : [];
911
+ const live = typeof deps.engine?.list === 'function'
912
+ ? deps.engine.list({ connectionId })
913
+ : [];
914
+ const liveIds = new Set(live.map((t) => t.taskId));
915
+ const historyStore = deps.history ?? deps.engine?.history ?? null;
916
+ const tasks = [...live];
917
+ if (historyStore && typeof historyStore.load === 'function') {
918
+ const stored = await historyStore.load();
919
+ for (const row of Array.isArray(stored) ? stored : []) {
920
+ if (!row || row.connectionId !== connectionId || liveIds.has(row.taskId)) continue;
921
+ tasks.push(typeof deps.engine?.historyViewOf === 'function' ? deps.engine.historyViewOf(row) : row);
922
+ }
923
+ }
924
+ return { planNodes, tasks };
925
+ }
926
+
927
+ function findTreeNode(nodes, nodeId) {
928
+ for (const node of nodes) {
929
+ if (node.nodeId === nodeId) return node;
930
+ const found = findTreeNode(node.children ?? [], nodeId);
931
+ if (found !== null) return found;
932
+ }
933
+ return null;
934
+ }
935
+
936
+ function compactTreeNodeSummary(treeNode) {
937
+ return {
938
+ nodeId: treeNode.nodeId,
939
+ kind: treeNode.kind,
940
+ parentNodeId: treeNode.parentNodeId,
941
+ depth: treeNode.depth,
942
+ title: treeNode.title,
943
+ displayTitle: treeNode.displayTitle,
944
+ goalDescription: treeNode.goalDescription,
945
+ completionSummary: treeNode.completionSummary,
946
+ executed: treeNode.executed,
947
+ nodeStatus: treeNode.nodeStatus,
948
+ orphan: treeNode.orphan,
949
+ projectKey: treeNode.projectKey,
950
+ executions: (treeNode.executions ?? []).map((ch) => ({
951
+ chainId: ch.chainId,
952
+ rootTaskId: ch.rootTaskId,
953
+ latestTaskId: ch.latestTaskId,
954
+ roundCount: ch.roundCount,
955
+ taskIds: ch.taskIds,
956
+ nodeStatus: ch.nodeStatus,
957
+ brokenContinuation: ch.brokenContinuation,
958
+ })),
959
+ children: (treeNode.children ?? []).map((child) => ({
960
+ nodeId: child.nodeId,
961
+ kind: child.kind,
962
+ title: child.displayTitle,
963
+ executed: child.executed,
964
+ nodeStatus: child.nodeStatus,
965
+ roundCount: child.kind === 'plan'
966
+ ? child.executions.reduce((s, e) => s + e.roundCount, 0)
967
+ : child.chain.roundCount,
968
+ childCount: child.children.length,
969
+ })),
970
+ };
971
+ }
@@ -156,8 +156,32 @@ function statusForCode(code) {
156
156
  if (code === 'JOB_ARCHIVED_TASK') return 409;
157
157
  // A malformed review request is the caller's mistake; an unpersisted one is an
158
158
  // upstream failure; "this task cannot be reviewed (now)" conflicts with its state.
159
- if (code === 'JOB_REVIEW_INVALID') return 400;
160
- if (code === 'JOB_REVIEW_NOT_PERSISTED') return 502;
159
+ if (code === 'JOB_REVIEW_INVALID' || code === 'JOB_DESCRIPTION_INVALID'
160
+ || code === 'JOB_PLAN_REF_INVALID' || code === 'JOB_PLAN_REF_CONFLICT') {
161
+ return 400;
162
+ }
163
+ if (code === 'JOB_REVIEW_NOT_PERSISTED' || code === 'PLAN_WRITE_FAILED') return 502;
164
+ if (code === 'JOB_PLAN_STORE_UNAVAILABLE' || code === 'PLAN_UNREADABLE' || code === 'PLAN_FILE_TOO_LARGE'
165
+ || code === 'PLAN_MALFORMED' || code === 'PLAN_SCHEMA_UNSUPPORTED' || code === 'PLAN_DISPOSED') {
166
+ return 503;
167
+ }
168
+ // The settings page writes planning nodes for the fixed local caller; a body that
169
+ // tries to name a connection is refused outright, like every other identity write
170
+ // on this plane.
171
+ if (code === 'PLAN_CONNECTION_UNTRUSTED') return 403;
172
+ if (code === 'PLAN_INVALID' || code === 'PLAN_TITLE_INVALID'
173
+ || code === 'PLAN_DESCRIPTION_INVALID' || code === 'PLAN_REVIEW_INVALID') {
174
+ return 400;
175
+ }
176
+ if (code.startsWith('PLAN_')) return 409;
177
+ // Task-record cleanup. A batch that cannot be honoured is a state conflict (the
178
+ // operator re-reads and retries), an unusable request is the caller's mistake, a
179
+ // capability the host does not have is 503 and a failed document write is 502.
180
+ if (code === 'CLEANUP_CHAIN_NOT_FOUND') return 404;
181
+ if (code === 'CLEANUP_INVALID') return 400;
182
+ if (code === 'CLEANUP_UNAVAILABLE') return 503;
183
+ if (code === 'CLEANUP_FAILED') return 502;
184
+ if (code.startsWith('CLEANUP_')) return 409;
161
185
  if (code.startsWith('JOB_')) return 409;
162
186
  // The credential seam is a separate service. "It is not installed here" is a
163
187
  // capability gap (503), "the backend refused the write" is an upstream failure