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
@@ -37,6 +37,11 @@ import { checkProviderConnectivity } from '../model/connectivity.js';
37
37
  import { MAX_CREDENTIAL_VALUE_CHARS } from '../credentials/seam.js';
38
38
  import { CODEX_ACTIONS, publicCodexStatus, runCodexAction } from '../codex/installer.js';
39
39
  import { classifyError, HttpError, jsonResponse, readJsonRequest } from '../http/respond.js';
40
+ import { sameRecordedDirectory } from '../jobs/continuation-identity.js';
41
+ import { buildTaskTree } from '../jobs/task-tree.js';
42
+ import { findDisplayNode } from '../jobs/task-display.js';
43
+ import { MAX_PLAN_BATCH, PLAN_CODES } from '../jobs/plan-store.js';
44
+ import { cleanupOverview, runCleanup } from '../jobs/record-cleanup.js';
40
45
 
41
46
  /**
42
47
  * Route prefix, already below `/api` because the native exact-route registry
@@ -44,6 +49,18 @@ import { classifyError, HttpError, jsonResponse, readJsonRequest } from '../http
44
49
  */
45
50
  export const USER_PLANE_PREFIX = '/api/dsh-delegate';
46
51
 
52
+ /**
53
+ * The ONE connection identity a switch-mode dispatch is recorded under.
54
+ *
55
+ * `src/jobs/engine.js` stamps exactly this string on every task admitted in
56
+ * switch mode (`task.connectionId = 'local-mcp'`), so a planning node created
57
+ * from the operator page must carry the same owner or it could never be the
58
+ * parent of — or appear beside — a dispatched task. It is a FIXED value, never
59
+ * read from a request: the page cannot choose whose plan it writes, and a body
60
+ * field that tries to name another connection is refused rather than ignored.
61
+ */
62
+ export const USER_PLANE_PLAN_CONNECTION_ID = 'local-mcp';
63
+
47
64
  /** Body mode every user-plane route declares. Only `buffered`/`streaming` exist. */
48
65
  const BODY_MODE = 'buffered';
49
66
 
@@ -141,6 +158,45 @@ export function userPlaneRoutes(deps) {
141
158
  });
142
159
  },
143
160
  },
161
+ // One narrow route for the operator's execution choices — today, the Agent Teams
162
+ // default a NEW task gets when its dispatcher states no per-task choice.
163
+ //
164
+ // Like the monitoring route it is on the AUTHENTICATED operator plane, and the MCP
165
+ // surface never gains a settings write. It is deliberately narrow: it can set ONE
166
+ // task default and nothing else. It cannot turn on DSH's global agent-teams switch,
167
+ // cannot change a provider, a model, an effort, an isolation mode, a grant or the
168
+ // delegation switch, and it cannot change a task that already ran — those froze their
169
+ // own decision at admission. `setExecution` validates its own block.
170
+ {
171
+ path: `${USER_PLANE_PREFIX}/execution`,
172
+ methods: ['POST'],
173
+ requestBody: BODY_MODE,
174
+ fetch: async (request) => {
175
+ const body = await readJsonRequest(request);
176
+ if (body.execution === undefined) {
177
+ throw new HttpError(400, 'EXECUTION_SETTINGS_MISSING', 'an execution block is required');
178
+ }
179
+ // A refused block is the caller's mistake, not a server fault: the shared
180
+ // translator would render the validator's unlisted code as a 500, so it is
181
+ // re-thrown here as a 400 that keeps the original code and its field details.
182
+ // Nothing is written when this throws.
183
+ let committed;
184
+ try {
185
+ committed = await deps.settings.setExecution(body.execution);
186
+ } catch (error) {
187
+ const code = typeof error?.code === 'string' ? error.code : '';
188
+ if (!code.startsWith('EXECUTION_')) throw error;
189
+ throw new HttpError(400, code, String(error?.message ?? 'the execution block is invalid'), error?.details ?? {});
190
+ }
191
+ return jsonResponse(200, {
192
+ ok: true,
193
+ execution: { ...committed.execution },
194
+ // The whole document is returned too, because the page adopts it after a
195
+ // narrow save and must not have to issue a second read to stay truthful.
196
+ settings: publicSettings(committed),
197
+ });
198
+ },
199
+ },
144
200
  // One path, two methods. `GET` reads the stored document, `POST` replaces it.
145
201
  // There is deliberately no `PUT`: the native registry cannot express it.
146
202
  {
@@ -315,6 +371,10 @@ export function userPlaneRoutes(deps) {
315
371
  // projection is read-only in both directions: it neither dispatches work
316
372
  // nor rewrites the document.
317
373
  //
374
+ // Removal of those records is its own route (`POST /tasks/cleanup`, below). The
375
+ // list only PUBLISHES, per execution chain, whether that chain may be removed;
376
+ // it never deletes anything, so refreshing the page cannot destroy a record.
377
+ //
318
378
  // A history document that cannot be read is a *visible refusal*, never an
319
379
  // empty success: answering `tasks: []` for an unreadable archive would tell
320
380
  // an operator that nothing ever ran.
@@ -330,16 +390,82 @@ export function userPlaneRoutes(deps) {
330
390
  fetch: async (request) => {
331
391
  const url = new URL(request.url, 'http://localhost');
332
392
  const connectionId = url.searchParams.get('connectionId') ?? undefined;
333
- const { tasks, history } = await readTaskRecords(deps, { connectionId });
393
+ const { tasks, history, plans, tree } = await readTaskRecords(deps, { connectionId });
334
394
  return jsonResponse(200, {
335
395
  ok: true,
336
- tasks,
396
+ tasks: await restoreSidebarSessionIds(tasks, deps.sessionStore),
337
397
  // Stated, not implied: a client must be able to tell a complete list
338
398
  // from one whose archive section could not be read.
339
399
  history,
400
+ plans,
401
+ tree,
340
402
  });
341
403
  },
342
404
  },
405
+ // The session-placement map, narrowed to the fields the sidebar's grouped
406
+ // workspaces view needs to PROVE which real DSH sessions this plugin created.
407
+ //
408
+ // It exists because the grouped view runs in the browser, where a task record may
409
+ // already have been cleaned or hidden, while the durable map is the one document
410
+ // that still says "TaskBridge drove session X in workspace Y for source path S".
411
+ // Without it, a session whose records are gone has to be guessed at — and that is
412
+ // exactly the guess the sidebar must never make.
413
+ //
414
+ // What crosses the boundary is identity only, and it is the map's own field list
415
+ // (`RECORD_FIELDS`): task/source/execution paths, their digests, the Workspace,
416
+ // the Session, the isolation and the managed-tree facts. Never a prompt, a
417
+ // transcript, a model output, a token or a credential — none of them is in the
418
+ // document. This route is a read: it writes nothing and drives nothing.
419
+ {
420
+ path: `${USER_PLANE_PREFIX}/session-map`,
421
+ methods: ['GET'],
422
+ requestBody: BODY_MODE,
423
+ fetch: async () => {
424
+ const store = deps.sessionStore ?? null;
425
+ if (store === null || store === undefined || typeof store.list !== 'function') {
426
+ throw new HttpError(
427
+ 503,
428
+ 'SESSION_MAP_UNAVAILABLE',
429
+ 'this deployment keeps no task-to-conversation identity, so the sidebar cannot be grouped by it',
430
+ );
431
+ }
432
+ let rows;
433
+ try {
434
+ rows = await store.list();
435
+ } catch (error) {
436
+ throw new HttpError(
437
+ 503,
438
+ 'SESSION_MAP_UNREADABLE',
439
+ 'the stored task-to-conversation identity could not be read',
440
+ { cause: typeof error?.code === 'string' ? error.code : 'SESSION_MAP_UNREADABLE' },
441
+ );
442
+ }
443
+ return jsonResponse(200, { ok: true, sessions: projectSessionMap(rows) });
444
+ },
445
+ },
446
+ {
447
+ path: `${USER_PLANE_PREFIX}/tasks/display-archive`,
448
+ methods: ['POST'],
449
+ requestBody: BODY_MODE,
450
+ fetch: async (request) => {
451
+ const body = await readJsonRequest(request);
452
+ if (typeof body.nodeId !== 'string' || !body.nodeId.trim() || body.nodeId.length > 256 || typeof body.archived !== 'boolean') {
453
+ throw new HttpError(400, 'TASK_DISPLAY_INVALID', 'a task node id and an archive flag are required');
454
+ }
455
+ if (!deps.taskDisplay) throw new HttpError(503, 'TASK_DISPLAY_UNAVAILABLE', 'display archives are unavailable');
456
+ const { tree } = await readTaskRecords(deps);
457
+ const node = findDisplayNode(tree.roots, body.nodeId.trim());
458
+ if (node === null) throw new HttpError(404, 'TASK_DISPLAY_NOT_FOUND', 'this node is no longer in the task history');
459
+ let outcome;
460
+ try {
461
+ outcome = await deps.taskDisplay.setArchived(node, body.archived, new Set(tree.flatNodes.map((item) => item.nodeId)));
462
+ } catch {
463
+ throw new HttpError(503, 'TASK_DISPLAY_UNAVAILABLE', 'display archives could not be saved');
464
+ }
465
+ if (outcome.conflict) throw new HttpError(409, outcome.conflict, 'this task could not be archived');
466
+ return jsonResponse(200, { ok: true, archived: outcome.archived });
467
+ },
468
+ },
343
469
  {
344
470
  path: `${USER_PLANE_PREFIX}/tasks/get`,
345
471
  methods: ['POST'],
@@ -376,6 +502,97 @@ export function userPlaneRoutes(deps) {
376
502
  });
377
503
  },
378
504
  },
505
+ // ---- planning nodes (create only) ---------------------------------------
506
+ // One narrow write: a batch of planning nodes, created through the SAME
507
+ // `PlanStore.create` the MCP `delegate_plan create` action uses. Nothing is
508
+ // re-implemented here, so every rule that makes a plan document trustworthy is
509
+ // the store's own — atomic all-or-nothing batch validation, `parentKey`
510
+ // resolution inside the batch, depth and document bounds, redaction — and a
511
+ // refused batch writes no bytes at all.
512
+ //
513
+ // Three boundaries this route deliberately keeps:
514
+ //
515
+ // * The owner is FIXED (`USER_PLANE_PLAN_CONNECTION_ID`). A body that names a
516
+ // `connectionId` is refused with `PLAN_CONNECTION_UNTRUSTED` rather than
517
+ // silently rewritten, so a caller can never believe it addressed another
518
+ // connection.
519
+ // * The body is a closed field set. Only `workspacePath`, `parentNodeId` and a
520
+ // `nodes` batch of `{ key, parentKey, parentNodeId, title, goalDescription,
521
+ // workspacePath }` entries are accepted; anything else — a `connectionId`, a
522
+ // pre-minted `nodeId`, a `hostAcceptance` — is a 400, never dropped.
523
+ // * Creating a plan NEVER dispatches, authorizes or approves execution. No
524
+ // engine, agent, workspace-lease or grant call is reachable from this block;
525
+ // the response is the stored nodes plus the switch posture it did not change.
526
+ //
527
+ // The parent of a child is the CALLER-NAMED id (`parentNodeId`) or a batch key
528
+ // (`parentKey`), both resolved by the store against records that already exist
529
+ // there. Nothing here infers ancestry from a title.
530
+ {
531
+ path: `${USER_PLANE_PREFIX}/plans`,
532
+ methods: ['POST'],
533
+ requestBody: BODY_MODE,
534
+ fetch: async (request) => {
535
+ const method = String(request.method ?? 'POST').toUpperCase();
536
+ if (method !== 'POST') return methodRefusal(request, ['POST']);
537
+ const body = await readJsonRequest(request);
538
+ const planRequest = projectPlanCreateRequest(body);
539
+ const store = requirePlanStore(deps);
540
+ let outcome;
541
+ try {
542
+ outcome = await store.create(
543
+ { ...planRequest, connectionId: USER_PLANE_PLAN_CONNECTION_ID },
544
+ { resolveExternalParent: externalPlanParentResolver(deps) },
545
+ );
546
+ } catch (error) {
547
+ throw planCreateRefusal(error);
548
+ }
549
+ const nodes = Array.isArray(outcome?.nodes) ? outcome.nodes : [];
550
+ deps.logger?.info?.('dsh-delegate: planning nodes created from the settings page', {
551
+ count: nodes.length,
552
+ rootCount: nodes.filter((node) => node.parentNodeId === null).length,
553
+ });
554
+ // The answer carries the STORED records. `plan.json` is the durable copy, so
555
+ // this is what a later `/tasks` read (and therefore the tree view) will show.
556
+ return jsonResponse(201, {
557
+ ok: true,
558
+ nodes,
559
+ // Stated, not implied: this route created data and nothing else.
560
+ executed: false,
561
+ switch: {
562
+ authorized: deps.engine?.posture?.()?.authorized === true,
563
+ changedByThisAction: false,
564
+ },
565
+ });
566
+ },
567
+ },
568
+ // ---- task record cleanup (one narrow, explicit write) --------------------
569
+ // The operator selected finished execution chains in the task tree and confirmed.
570
+ // The body names those chains and their exact rounds and nothing else:
571
+ //
572
+ // { confirm: true, chains: [{ chainId, taskIds: [...] }] }
573
+ //
574
+ // There is no time window, no path, no "delete all" flag and no per-node id: a
575
+ // caller cannot express "remove whatever finished last week", which is what makes
576
+ // the batch reviewable before it is sent. `runCleanup` re-reads the UNFILTERED
577
+ // current records and refuses the batch whole when any named chain is unknown,
578
+ // changed, live, undurable, still being reviewed, or still depended on by a
579
+ // continuation or a planning node — so a refusal writes nothing at all.
580
+ //
581
+ // What it removes is the durable record (and with it the review conclusion).
582
+ // It creates nothing else: no native Session, Workspace, worktree or source file
583
+ // is touched, no plan node is deleted or orphaned, and no other data file is
584
+ // written. It is a user-plane route only — the execution plane, the MCP surface
585
+ // and the native fence pick up no new capability from it.
586
+ {
587
+ path: `${USER_PLANE_PREFIX}/tasks/cleanup`,
588
+ methods: ['POST'],
589
+ requestBody: BODY_MODE,
590
+ fetch: async (request) => {
591
+ const body = await readJsonRequest(request);
592
+ const outcome = await runCleanup(deps, body);
593
+ return jsonResponse(200, { ok: true, ...outcome });
594
+ },
595
+ },
379
596
  {
380
597
  path: `${USER_PLANE_PREFIX}/tasks/cancel`,
381
598
  methods: ['POST'],
@@ -790,10 +1007,30 @@ function archivedRecord(deps, job) {
790
1007
  * @param {object} [options] - `connectionId` to filter on.
791
1008
  * @returns {Promise<{ tasks: object[], history: object }>} merged list and archive status.
792
1009
  */
1010
+ async function loadPlans(deps, options = {}) {
1011
+ const store = deps.plans ?? deps.engine?.plans ?? null;
1012
+ if (store === null || store === undefined || typeof store.load !== 'function') {
1013
+ return { available: false, nodes: [], code: 'PLAN_UNAVAILABLE' };
1014
+ }
1015
+ try {
1016
+ const nodes = await store.load(options.connectionId ? { connectionId: options.connectionId } : {});
1017
+ return { available: true, nodes: Array.isArray(nodes) ? nodes : [], code: null };
1018
+ } catch (error) {
1019
+ deps.logger?.warn?.('dsh-delegate: durable plan store could not be read', error?.code ?? 'PLAN_UNREADABLE');
1020
+ throw new HttpError(
1021
+ 503,
1022
+ 'PLAN_HISTORY_UNREADABLE',
1023
+ 'the durable plan document could not be read, so task plans are not shown',
1024
+ { cause: typeof error?.code === 'string' ? error.code : 'PLAN_UNREADABLE' },
1025
+ );
1026
+ }
1027
+ }
1028
+
793
1029
  async function readTaskRecords(deps, options = {}) {
794
1030
  const filtered = options.connectionId !== undefined && options.connectionId !== null;
795
1031
  const live = deps.engine.list(filtered ? { connectionId: options.connectionId } : {});
796
1032
  const archive = await loadArchive(deps);
1033
+ const planState = await loadPlans(deps, filtered ? { connectionId: options.connectionId } : {});
797
1034
  const liveIds = new Set(live.map((task) => task.taskId));
798
1035
 
799
1036
  const merged = [];
@@ -807,6 +1044,37 @@ async function readTaskRecords(deps, options = {}) {
807
1044
  merged.push(archivedRecord(deps, job));
808
1045
  }
809
1046
  merged.sort(compareNewestFirst);
1047
+ const tree = buildTaskTree({ planNodes: planState.nodes, tasks: merged });
1048
+ // Every chain of the projection carries its own cleanup facts, computed from the
1049
+ // SAME unfiltered records above. The page draws a checkbox from this block and the
1050
+ // delete route re-checks the very same rules before writing, so a row the operator
1051
+ // can tick is a row whose server-side check will pass. A chain the projection could
1052
+ // not describe (no facts) is left untouched and is therefore not selectable.
1053
+ if (deps.history !== null && deps.history !== undefined && typeof deps.history.deleteMany === 'function') {
1054
+ try {
1055
+ const overview = await cleanupOverview(deps);
1056
+ attachCleanupFacts(tree, overview.chains);
1057
+ } catch (error) {
1058
+ // A tree that cannot describe removal is still a readable tree; the page then
1059
+ // shows the chains without the cleanup action instead of a broken list.
1060
+ deps.logger?.warn?.('dsh-delegate: record cleanup facts could not be computed', error?.code ?? 'CLEANUP_UNAVAILABLE');
1061
+ tree.cleanupAvailable = false;
1062
+ tree.cleanupError = typeof error?.code === 'string' ? error.code : 'CLEANUP_UNAVAILABLE';
1063
+ }
1064
+ } else {
1065
+ tree.cleanupAvailable = false;
1066
+ tree.cleanupError = 'CLEANUP_UNAVAILABLE';
1067
+ }
1068
+ if (deps.taskDisplay) {
1069
+ try {
1070
+ await deps.taskDisplay.project(tree);
1071
+ tree.displayArchiveAvailable = true;
1072
+ } catch (error) {
1073
+ tree.displayArchiveAvailable = false;
1074
+ tree.displayArchiveError = 'TASK_DISPLAY_UNAVAILABLE';
1075
+ deps.logger?.warn?.('dsh-delegate: display archives could not be read', error?.code ?? 'STORE_UNREADABLE');
1076
+ }
1077
+ }
810
1078
 
811
1079
  return {
812
1080
  tasks: merged,
@@ -816,9 +1084,305 @@ async function readTaskRecords(deps, options = {}) {
816
1084
  unreadable: false,
817
1085
  ...(archive.available ? {} : { reason: archive.code }),
818
1086
  },
1087
+ plans: {
1088
+ available: planState.available,
1089
+ count: planState.available ? planState.nodes.length : 0,
1090
+ unreadable: false,
1091
+ ...(planState.available ? {} : { reason: planState.code }),
1092
+ },
1093
+ tree,
819
1094
  };
820
1095
  }
821
1096
 
1097
+ /**
1098
+ * Attach the cleanup facts of one chain to every chain object of a projected tree.
1099
+ *
1100
+ * The chains inside `roots` are the projection's own objects, so this writes the
1101
+ * block onto them in place instead of rebuilding the tree: `flatNodes` deliberately
1102
+ * carries no chain detail and must not be widened (it is the transport shape an
1103
+ * execution-plane reader sees).
1104
+ * @param {object} tree - `buildTaskTree` result.
1105
+ * @param {object[]} facts - `cleanupOverview(...).chains`.
1106
+ * @returns {void}
1107
+ */
1108
+ function attachCleanupFacts(tree, facts) {
1109
+ const byId = new Map((Array.isArray(facts) ? facts : []).map((entry) => [entry.chainId, entry]));
1110
+ const walk = (node) => {
1111
+ const chains = node?.kind === 'plan' ? (node.executions ?? []) : (node?.chain ? [node.chain] : []);
1112
+ for (const chain of chains) {
1113
+ const fact = byId.get(chain.chainId) ?? null;
1114
+ // No facts means "this host cannot say", which the page reads as not selectable.
1115
+ if (fact === null) continue;
1116
+ chain.cleanup = {
1117
+ eligible: fact.eligible === true,
1118
+ blockers: Array.isArray(fact.blockers) ? [...fact.blockers] : [],
1119
+ };
1120
+ }
1121
+ for (const child of Array.isArray(node?.children) ? node.children : []) walk(child);
1122
+ };
1123
+ for (const root of Array.isArray(tree?.roots) ? tree.roots : []) walk(root);
1124
+ tree.cleanupAvailable = true;
1125
+ tree.cleanupError = null;
1126
+ }
1127
+
1128
+ // The identity fields the grouped sidebar needs, and nothing else. This is the
1129
+ // session map's own field list narrowed to what a VIEW model consumes; an unknown
1130
+ // future field on a stored row is dropped here rather than published by accident.
1131
+ const SESSION_MAP_VIEW_FIELDS = Object.freeze([
1132
+ 'taskId', 'sourcePath', 'executionPath', 'sourcePathDigest', 'executionPathDigest',
1133
+ 'workspaceId', 'sessionId', 'isolation', 'worktreeId', 'worktreeState', 'updatedAt',
1134
+ ]);
1135
+
1136
+ /**
1137
+ * Project the session-placement map onto the grouped sidebar's view fields.
1138
+ *
1139
+ * A row that cannot name a session or a Workspace proves nothing about the sidebar, so
1140
+ * it is dropped instead of published half-formed: the browser would otherwise have to
1141
+ * decide what a partially usable row means, and the answer could only be a guess.
1142
+ * @param {unknown} rows - `SessionStore.list()` result.
1143
+ * @returns {object[]} bounded rows, newest first.
1144
+ */
1145
+ function projectSessionMap(rows) {
1146
+ const usable = (Array.isArray(rows) ? rows : []).filter((row) => row !== null && typeof row === 'object'
1147
+ && typeof row.sessionId === 'string' && row.sessionId !== ''
1148
+ && typeof row.workspaceId === 'string' && row.workspaceId !== '');
1149
+ const projected = usable.map((row) => {
1150
+ const view = {};
1151
+ for (const field of SESSION_MAP_VIEW_FIELDS) {
1152
+ if (row[field] !== undefined) view[field] = row[field];
1153
+ }
1154
+ return view;
1155
+ });
1156
+ projected.sort((left, right) => (Number(right.updatedAt) || 0) - (Number(left.updatedAt) || 0));
1157
+ return projected;
1158
+ }
1159
+
1160
+ // Older review writes could drop the top-level session id while retaining the// placement and paths. Only the operator's task list needs this navigation link.
1161
+ async function restoreSidebarSessionIds(tasks, sessionStore) {
1162
+ const needsLink = (task) => task.archived === true && task.sessionId == null
1163
+ && typeof task.execution?.conversation?.workspaceId === 'string';
1164
+ if (typeof sessionStore?.list !== 'function' || !tasks.some(needsLink)) return tasks;
1165
+
1166
+ let identities;
1167
+ try {
1168
+ identities = new Map((await sessionStore.list()).map((identity) => [identity.taskId, identity]));
1169
+ } catch {
1170
+ return tasks;
1171
+ }
1172
+
1173
+ return tasks.map((task) => {
1174
+ if (!needsLink(task)) return task;
1175
+ const identity = identities.get(task.taskId);
1176
+ const workspaceId = task.execution.conversation.workspaceId;
1177
+ if (!identity || workspaceId === '' || identity.workspaceId !== workspaceId
1178
+ || typeof identity.sessionId !== 'string' || identity.sessionId === '') return task;
1179
+ const sameSource = sameRecordedDirectory(
1180
+ { path: task.sourcePath, digest: task.sourcePathDigest },
1181
+ { path: identity.sourcePath, digest: identity.sourcePathDigest },
1182
+ );
1183
+ const sameExecution = sameRecordedDirectory(
1184
+ { path: task.executionWorkspacePath, digest: task.executionPathDigest },
1185
+ { path: identity.executionPath, digest: identity.executionPathDigest },
1186
+ );
1187
+ return sameSource && sameExecution ? { ...task, sessionId: identity.sessionId } : task;
1188
+ });
1189
+ }
1190
+
1191
+ // ---- planning-node creation (narrow operator write) ------------------------
1192
+
1193
+ /**
1194
+ * Fields a planning-node create request may carry.
1195
+ *
1196
+ * A closed list, not a preference: the store would accept several more shapes
1197
+ * (a pre-minted `nodeId`, an acceptance record) and an operator page must not be
1198
+ * able to write any of them. `connectionId` is *checked* separately so that a
1199
+ * request which tries to name one is refused with its own code instead of a
1200
+ * generic "unknown field", which would hide that the attempt was about identity.
1201
+ */
1202
+ const PLAN_CREATE_FIELDS = Object.freeze(['workspacePath', 'parentNodeId', 'nodes']);
1203
+ const PLAN_CREATE_ITEM_FIELDS = Object.freeze([
1204
+ 'key',
1205
+ 'parentKey',
1206
+ 'parentNodeId',
1207
+ 'title',
1208
+ 'goalDescription',
1209
+ 'workspacePath',
1210
+ ]);
1211
+
1212
+ /**
1213
+ * Validate one browser create request and project it onto the store's shape.
1214
+ *
1215
+ * Every check here is a *shape* check whose refusal names the field; the meaning
1216
+ * of the values (title length, batch cycles, depth, source-repository agreement)
1217
+ * stays with `PlanStore.create`, which is the single authority the MCP surface
1218
+ * uses too. Nothing is coerced: a numeric title is a 400, never `String(...)`.
1219
+ * @param {object} body - parsed request body.
1220
+ * @returns {{ workspacePath?: string, parentNodeId?: string, nodes: object[] }} store request.
1221
+ * @throws {HttpError} 400 with `PLAN_CONNECTION_UNTRUSTED` or `PLAN_INVALID`.
1222
+ */
1223
+ function projectPlanCreateRequest(body) {
1224
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
1225
+ throw new HttpError(400, PLAN_CODES.invalid, 'the plan create body must be a JSON object');
1226
+ }
1227
+ if (Object.prototype.hasOwnProperty.call(body, 'connectionId')) {
1228
+ throw new HttpError(
1229
+ 403,
1230
+ 'PLAN_CONNECTION_UNTRUSTED',
1231
+ 'the settings page always writes planning nodes for the local caller; a body cannot name a connection',
1232
+ { field: 'connectionId', connectionId: USER_PLANE_PLAN_CONNECTION_ID },
1233
+ );
1234
+ }
1235
+ for (const key of Object.keys(body)) {
1236
+ if (!PLAN_CREATE_FIELDS.includes(key)) {
1237
+ throw new HttpError(400, PLAN_CODES.invalid, `plan create does not accept field ${JSON.stringify(key)}`, { field: key });
1238
+ }
1239
+ }
1240
+ const request = {};
1241
+ if (body.workspacePath !== undefined && body.workspacePath !== null) {
1242
+ if (typeof body.workspacePath !== 'string' || body.workspacePath.trim() === '') {
1243
+ throw new HttpError(400, PLAN_CODES.invalid, 'workspacePath must be a non-empty string when provided', {
1244
+ field: 'workspacePath',
1245
+ });
1246
+ }
1247
+ request.workspacePath = body.workspacePath;
1248
+ }
1249
+ if (body.parentNodeId !== undefined && body.parentNodeId !== null) {
1250
+ if (typeof body.parentNodeId !== 'string' || body.parentNodeId.trim() === '') {
1251
+ throw new HttpError(400, PLAN_CODES.invalid, 'parentNodeId must be a non-empty string when provided', {
1252
+ field: 'parentNodeId',
1253
+ });
1254
+ }
1255
+ request.parentNodeId = body.parentNodeId;
1256
+ }
1257
+ if (!Array.isArray(body.nodes) || body.nodes.length === 0) {
1258
+ throw new HttpError(400, PLAN_CODES.invalid, 'nodes must be a non-empty batch of planning nodes', {
1259
+ field: 'nodes',
1260
+ limit: MAX_PLAN_BATCH,
1261
+ });
1262
+ }
1263
+ if (body.nodes.length > MAX_PLAN_BATCH) {
1264
+ throw new HttpError(400, PLAN_CODES.invalid, `nodes may contain at most ${MAX_PLAN_BATCH} entries`, {
1265
+ field: 'nodes',
1266
+ limit: MAX_PLAN_BATCH,
1267
+ count: body.nodes.length,
1268
+ });
1269
+ }
1270
+ request.nodes = body.nodes.map((item, index) => projectPlanCreateItem(item, index));
1271
+ return request;
1272
+ }
1273
+
1274
+ /**
1275
+ * Validate one batch entry, keeping only the fields the operator form can set.
1276
+ * @param {unknown} item - caller-supplied entry.
1277
+ * @param {number} index - position in the batch, for the refusal detail.
1278
+ * @returns {object} projected entry.
1279
+ * @throws {HttpError} 400 `PLAN_INVALID`.
1280
+ */
1281
+ function projectPlanCreateItem(item, index) {
1282
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) {
1283
+ throw new HttpError(400, PLAN_CODES.invalid, `nodes[${index}] must be an object`, { index });
1284
+ }
1285
+ for (const key of Object.keys(item)) {
1286
+ if (!PLAN_CREATE_ITEM_FIELDS.includes(key)) {
1287
+ throw new HttpError(400, PLAN_CODES.invalid, `nodes[${index}] does not accept field ${JSON.stringify(key)}`, {
1288
+ index,
1289
+ field: key,
1290
+ });
1291
+ }
1292
+ }
1293
+ // `title` is the one field the store refuses late (it mints ids while iterating);
1294
+ // refusing it here keeps "the form's mistake" a 400 that names the field, while
1295
+ // every other rule stays the store's own.
1296
+ if (typeof item.title !== 'string' || item.title.trim() === '') {
1297
+ throw new HttpError(400, PLAN_CODES.titleInvalid, `nodes[${index}].title must be a non-empty string`, {
1298
+ index,
1299
+ field: 'title',
1300
+ });
1301
+ }
1302
+ const projected = { title: item.title };
1303
+ for (const key of ['key', 'parentKey', 'parentNodeId', 'goalDescription', 'workspacePath']) {
1304
+ if (item[key] !== undefined) projected[key] = item[key];
1305
+ }
1306
+ return projected;
1307
+ }
1308
+
1309
+ /**
1310
+ * The plan store this route writes through, or a refusal.
1311
+ *
1312
+ * It is the same instance the MCP surface and the read projection use, so a node
1313
+ * created here is immediately visible to `/tasks` and to `delegate_plan list`.
1314
+ * @param {object} deps - dependency object with `plans` (or an engine exposing it).
1315
+ * @returns {object} the store.
1316
+ * @throws {HttpError} 503 `JOB_PLAN_STORE_UNAVAILABLE`.
1317
+ */
1318
+ function requirePlanStore(deps) {
1319
+ const store = deps.plans ?? deps.engine?.plans ?? null;
1320
+ if (store === null || store === undefined || typeof store.create !== 'function') {
1321
+ throw new HttpError(
1322
+ 503,
1323
+ 'JOB_PLAN_STORE_UNAVAILABLE',
1324
+ 'the plan store is unavailable in this deployment',
1325
+ );
1326
+ }
1327
+ return store;
1328
+ }
1329
+
1330
+ /**
1331
+ * Resolve a parent id that names an execution record (rather than a plan node).
1332
+ *
1333
+ * Without this the store could only parent a node under another planning node, so
1334
+ * "add a step under this running task" would be refused as unknown parent. It
1335
+ * forwards the engine's own resolver when the host has one and otherwise reports
1336
+ * "not found", which keeps every refusal the store already knows.
1337
+ * @param {object} deps - dependency object with an optional engine.
1338
+ * @returns {Function | undefined} resolver passed to `PlanStore.create`.
1339
+ */
1340
+ function externalPlanParentResolver(deps) {
1341
+ const engine = deps.engine;
1342
+ if (engine === null || engine === undefined || typeof engine.resolveHierarchyParentFacts !== 'function') {
1343
+ return undefined;
1344
+ }
1345
+ return (parentId, connectionId, existingPlanMap) => engine.resolveHierarchyParentFacts(
1346
+ parentId,
1347
+ connectionId,
1348
+ existingPlanMap,
1349
+ );
1350
+ }
1351
+
1352
+ /**
1353
+ * Translate a plan-store refusal into an HTTP refusal that keeps its identity.
1354
+ *
1355
+ * `classifyError` already knows every `PLAN_*` code, so the mapping is mostly a
1356
+ * pass-through; a depth overflow or a `parentKey` cycle is unambiguously the
1357
+ * caller's batch shape and would otherwise be reported as a conflict, so those two
1358
+ * are answered as 400 while keeping the store's own code and details.
1359
+ * @param {unknown} error - thrown by the store.
1360
+ * @returns {HttpError} refusal to throw.
1361
+ */
1362
+ function planCreateRefusal(error) {
1363
+ if (error instanceof HttpError) return error;
1364
+ const code = typeof error?.code === 'string' && error.code !== '' ? error.code : PLAN_CODES.invalid;
1365
+ const details = error?.details !== null && typeof error.details === 'object' && error.details !== undefined
1366
+ ? redactDeep(error.details)
1367
+ : {};
1368
+ const message = typeof error?.message === 'string' && error.message !== ''
1369
+ ? error.message
1370
+ : 'the planning nodes could not be created';
1371
+ const status = code === PLAN_CODES.depthExceeded || code === PLAN_CODES.cycleDetected ? 400 : statusForPlanCode(code);
1372
+ return new HttpError(status, code, message, details);
1373
+ }
1374
+
1375
+ /**
1376
+ * The status this plane answers for one plan-store code, computed by the shared
1377
+ * translator rather than copied, so the two can never drift apart.
1378
+ * @param {string} code - plan-store code.
1379
+ * @returns {number} HTTP status.
1380
+ */
1381
+ function statusForPlanCode(code) {
1382
+ const mapped = classifyError({ code, message: '', details: {} });
1383
+ return mapped.status;
1384
+ }
1385
+
822
1386
  /**
823
1387
  * Newest first by creation time, then by id.
824
1388
  * @param {object} a - first record.