dsh-taskbridge 1.7.1 → 1.8.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -21
  3. package/README.md +733 -877
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +32 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +181 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +122 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/conversation-placement.md +7 -6
  17. package/docs/plugin-market.md +30 -30
  18. package/docs/redaction-contract.md +170 -170
  19. package/docs/releases/1.7.0.zh.md +11 -11
  20. package/docs/releases/1.8.0.zh.md +16 -0
  21. package/docs/releases/1.8.1.zh.md +24 -0
  22. package/docs/runtime-compatibility.md +1 -1
  23. package/docs/taskbridge-upgrade.md +28 -28
  24. package/docs/taskdispatch-upgrade.md +25 -25
  25. package/docs/workspace-contract.md +538 -538
  26. package/docs/workspace-grouping.md +126 -126
  27. package/icon.svg +1 -1
  28. package/lib/client.d.ts +804 -699
  29. package/lib/client.js +7 -7
  30. package/locale/en.json +1 -1
  31. package/locale/zh.json +1 -1
  32. package/package.json +150 -144
  33. package/src/antigravity/installer.js +1068 -0
  34. package/src/antigravity/seam.js +142 -0
  35. package/src/auth/fence.js +361 -361
  36. package/src/auth/grants.js +789 -789
  37. package/src/client/api.js +266 -3
  38. package/src/client/index.jsx +224 -11
  39. package/src/client/sidebar.jsx +862 -862
  40. package/src/client/styles.js +624 -624
  41. package/src/client/task-cleanup.js +429 -304
  42. package/src/client/task-records-table.jsx +217 -217
  43. package/src/client/task-view.js +307 -307
  44. package/src/client/workspace-groups.js +482 -482
  45. package/src/client/workspaces-browser.jsx +770 -770
  46. package/src/codex/agent-ownership.js +270 -270
  47. package/src/codex/installer.js +6 -0
  48. package/src/codex/toml.js +784 -784
  49. package/src/config/defaults.js +11 -15
  50. package/src/config/redact.js +245 -245
  51. package/src/config/store.js +186 -186
  52. package/src/credentials/seam.js +202 -202
  53. package/src/http/respond.js +6 -5
  54. package/src/http/user-plane.js +83 -1
  55. package/src/index.js +25 -0
  56. package/src/jobs/diagnostics.js +15 -15
  57. package/src/jobs/engine.js +1 -0
  58. package/src/jobs/history.js +1 -1
  59. package/src/jobs/plan-store.js +1103 -1020
  60. package/src/jobs/record-cleanup.js +452 -7
  61. package/src/jobs/review-note.js +63 -63
  62. package/src/jobs/task-descriptions.js +82 -82
  63. package/src/jobs/task-display.js +73 -73
  64. package/src/jobs/task-tree.js +786 -786
  65. package/src/jobs/title.js +134 -134
  66. package/src/mcp/continuation.js +317 -317
  67. package/src/mcp/server.js +34 -27
  68. package/src/mcp/wait.js +34 -15
  69. package/src/model/connectivity.js +371 -371
  70. package/src/model/discovery.js +582 -582
  71. package/src/model/native-catalog.js +68 -68
  72. package/src/model/openai-adapter.js +671 -671
  73. package/src/model/probe.js +264 -264
  74. package/src/model/providers.js +756 -756
  75. package/src/model/routing.js +321 -321
  76. package/src/runtime/agent-runner.js +1 -0
  77. package/src/runtime/permissions.js +1619 -1619
  78. package/src/runtime/question-call.js +162 -162
  79. package/src/runtime/questions.js +909 -909
  80. package/src/runtime/session-placement.js +36 -1
  81. package/src/runtime/worker-prompt.js +61 -55
  82. package/src/workspace/audit.js +775 -775
  83. package/src/workspace/preflight.js +424 -424
  84. package/src/workspace/worktrees.js +833 -679
@@ -1,8 +1,11 @@
1
1
  import { buildTaskTree } from './task-tree.js';
2
2
  import { HISTORY_CODES, HISTORY_DELETE_MAX_TASKS } from './history.js';
3
+ import { sessionPathKey } from '../runtime/session-placement.js';
3
4
 
4
5
  export const MAX_CLEANUP_CHAINS = 100;
5
- const FINISHED = new Set(['awaiting-host-review', 'failed', 'cancelled']);
6
+ const FINISHED = new Set(['awaiting-host-review', 'failed', 'cancelled', 'interrupted']);
7
+ const ALLOWED_CLEANUP_KEYS = new Set(['chains', 'confirm', 'archiveSessions', 'removeWorktrees', 'cleanPlans']);
8
+ const ALLOWED_ORPHAN_KEYS = new Set(['confirm', 'archiveSessions', 'removeWorktrees']);
6
9
 
7
10
  export const CLEANUP_CODES = Object.freeze({
8
11
  invalid: 'CLEANUP_INVALID',
@@ -40,10 +43,15 @@ function isId(value) {
40
43
  }
41
44
 
42
45
  export function validateCleanupRequest(body) {
43
- if (!isObject(body) || Object.keys(body).some((key) => key !== 'chains' && key !== 'confirm')) {
46
+ if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_CLEANUP_KEYS.has(key))) {
44
47
  invalid('expected only chains and explicit confirmation');
45
48
  }
46
49
  if (body.confirm !== true) invalid('cleanup requires explicit confirmation', { field: 'confirm' });
50
+ for (const flag of ['archiveSessions', 'removeWorktrees', 'cleanPlans']) {
51
+ if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
52
+ invalid(`${flag} must be a boolean`, { field: flag });
53
+ }
54
+ }
47
55
  if (!Array.isArray(body.chains) || body.chains.length === 0 || body.chains.length > MAX_CLEANUP_CHAINS) {
48
56
  invalid('select a bounded list of execution chains', { field: 'chains', limit: MAX_CLEANUP_CHAINS });
49
57
  }
@@ -63,7 +71,14 @@ export function validateCleanupRequest(body) {
63
71
  }
64
72
  return { chainId: chain.chainId, taskIds: [...chain.taskIds] };
65
73
  });
66
- return { chains };
74
+ return {
75
+ chains,
76
+ options: {
77
+ archiveSessions: body.archiveSessions === true,
78
+ removeWorktrees: body.removeWorktrees === true,
79
+ cleanPlans: body.cleanPlans === true,
80
+ },
81
+ };
67
82
  }
68
83
 
69
84
  function planStore(deps) {
@@ -152,7 +167,7 @@ function checkBatch(chains, context) {
152
167
  }
153
168
 
154
169
  export async function runCleanup(deps, body) {
155
- const { chains } = validateCleanupRequest(body);
170
+ const { chains, options } = validateCleanupRequest(body);
156
171
  const store = deps.history;
157
172
  const plans = planStore(deps);
158
173
  const engine = deps.engine;
@@ -160,6 +175,9 @@ export async function runCleanup(deps, body) {
160
175
  throw new CleanupError(CLEANUP_CODES.unavailable, 'task record cleanup is unavailable');
161
176
  }
162
177
  const ids = chains.flatMap((chain) => chain.taskIds);
178
+ const idsSet = new Set(ids);
179
+ let deletedRowsSnapshot = [];
180
+ let remainingRowsSnapshot = [];
163
181
  const deleteRecords = async (planNodes) => {
164
182
  let release;
165
183
  try {
@@ -167,7 +185,11 @@ export async function runCleanup(deps, body) {
167
185
  beforeWrite(archived) {
168
186
  // Read the latest engine state inside the history queue. No asynchronous
169
187
  // work may run between checking relationships and reserving these ids.
170
- checkBatch(chains, cleanupContext(engine, archived, planNodes));
188
+ const context = cleanupContext(engine, archived, planNodes);
189
+ checkBatch(chains, context);
190
+ const allTasks = new Map([...context.archivedById, ...context.liveById]);
191
+ deletedRowsSnapshot = ids.map((id) => allTasks.get(id)).filter(Boolean);
192
+ remainingRowsSnapshot = [...allTasks.values()].filter((row) => !idsSet.has(row.taskId));
171
193
  release = engine?.reserveCleanupIds(ids);
172
194
  },
173
195
  afterWrite(deletedIds) {
@@ -187,10 +209,433 @@ export async function runCleanup(deps, body) {
187
209
  : error?.code === HISTORY_CODES.writeFailed ? CLEANUP_CODES.failed : CLEANUP_CODES.unavailable;
188
210
  throw new CleanupError(code, 'the task records could not be removed', { deleted: 0 });
189
211
  }
212
+
213
+ const hasLinkedCleanup = options.archiveSessions || options.removeWorktrees || options.cleanPlans;
214
+ if (!hasLinkedCleanup) {
215
+ return {
216
+ chains: chains.length,
217
+ tasks: result.deletedTaskIds.length,
218
+ ...result,
219
+ retained: { sessions: true, workspaces: true, worktrees: true, sourceFiles: true, plans: true },
220
+ };
221
+ }
222
+
223
+ const linked = await performLinkedCleanup(deps, {
224
+ options,
225
+ deletedTaskIds: result.deletedTaskIds,
226
+ deletedRows: deletedRowsSnapshot,
227
+ remainingRows: remainingRowsSnapshot,
228
+ plans,
229
+ });
230
+
190
231
  return {
191
232
  chains: chains.length,
192
233
  tasks: result.deletedTaskIds.length,
193
234
  ...result,
194
- retained: { sessions: true, workspaces: true, worktrees: true, sourceFiles: true, plans: true },
235
+ retained: {
236
+ sessions: !options.archiveSessions,
237
+ workspaces: !options.removeWorktrees,
238
+ worktrees: !options.removeWorktrees,
239
+ sourceFiles: true,
240
+ plans: !options.cleanPlans,
241
+ },
242
+ cleaned: linked,
195
243
  };
196
- }
244
+ }
245
+
246
+ function firstNonEmpty(...values) {
247
+ for (const val of values) {
248
+ if (typeof val === 'string' && val.trim() !== '') return val.trim();
249
+ }
250
+ return null;
251
+ }
252
+
253
+ function extractTaskFacts(row, sessionRow = null) {
254
+ const isolation = firstNonEmpty(
255
+ row?.isolation,
256
+ row?.effective?.worker?.isolation,
257
+ sessionRow?.isolation,
258
+ );
259
+ const sourcePath = firstNonEmpty(
260
+ sessionRow?.sourcePath,
261
+ row?.sourcePath,
262
+ row?.execution?.sourcePath,
263
+ row?.conversation?.sourcePath,
264
+ );
265
+ const executionPath = firstNonEmpty(
266
+ sessionRow?.executionPath,
267
+ row?.executionWorkspacePath,
268
+ row?.worktree?.workspacePath,
269
+ row?.execution?.workspacePath,
270
+ row?.workspacePath,
271
+ );
272
+ const workspaceId = firstNonEmpty(
273
+ sessionRow?.workspaceId,
274
+ row?.workspaceId,
275
+ row?.execution?.workspaceId,
276
+ row?.execution?.conversation?.workspaceId,
277
+ row?.conversation?.workspaceId,
278
+ );
279
+ const sessionId = firstNonEmpty(
280
+ sessionRow?.sessionId,
281
+ row?.sessionId,
282
+ row?.execution?.sessionId,
283
+ row?.execution?.conversation?.sessionId,
284
+ row?.conversation?.sessionId,
285
+ );
286
+ return {
287
+ taskId: firstNonEmpty(row?.taskId, sessionRow?.taskId),
288
+ isolation,
289
+ sourcePath,
290
+ executionPath,
291
+ workspaceId,
292
+ sessionId,
293
+ planNodeId: firstNonEmpty(row?.planNodeId),
294
+ parentNodeId: firstNonEmpty(row?.parentNodeId),
295
+ };
296
+ }
297
+
298
+ function resolveController(serviceOrAccessor) {
299
+ if (serviceOrAccessor === null || serviceOrAccessor === undefined) return null;
300
+ if (typeof serviceOrAccessor === 'object' && 'current' in serviceOrAccessor) {
301
+ return serviceOrAccessor.current ?? null;
302
+ }
303
+ return serviceOrAccessor;
304
+ }
305
+
306
+ async function tryArchiveHostSession(deps, sessionId) {
307
+ const ws = resolveController(deps?.workspaces);
308
+ if (typeof ws?.archiveSession === 'function') {
309
+ try {
310
+ await ws.archiveSession(sessionId);
311
+ return true;
312
+ } catch {
313
+ try {
314
+ await ws.archiveSession({ sessionId });
315
+ return true;
316
+ } catch {
317
+ // Ignore host controller error; browser client also reconciles via client workspaces service.
318
+ }
319
+ }
320
+ }
321
+ const sc = resolveController(deps?.sessionController);
322
+ if (typeof sc?.archiveSession === 'function') {
323
+ try {
324
+ await sc.archiveSession(sessionId);
325
+ return true;
326
+ } catch {
327
+ // Ignore
328
+ }
329
+ }
330
+ return false;
331
+ }
332
+
333
+ async function tryDeleteHostWorkspace(deps, workspaceId) {
334
+ const ws = resolveController(deps?.workspaces);
335
+ if (typeof ws?.delete === 'function') {
336
+ try {
337
+ await ws.delete(workspaceId);
338
+ return true;
339
+ } catch {
340
+ try {
341
+ await ws.delete({ workspaceId });
342
+ return true;
343
+ } catch {
344
+ // Ignore
345
+ }
346
+ }
347
+ }
348
+ return false;
349
+ }
350
+
351
+ async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows, remainingRows, plans }) {
352
+ const deletedSet = new Set(deletedTaskIds);
353
+ let sessionRows = [];
354
+ if (typeof deps?.sessionStore?.list === 'function') {
355
+ try {
356
+ sessionRows = await deps.sessionStore.list();
357
+ } catch {
358
+ sessionRows = [];
359
+ }
360
+ }
361
+ const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
362
+
363
+ const activeSessionIds = new Set();
364
+ const activeWorkspaceIds = new Set();
365
+ const activeExecKeys = new Set();
366
+ for (const row of remainingRows) {
367
+ const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
368
+ if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
369
+ if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
370
+ const execKey = sessionPathKey(facts.executionPath);
371
+ if (execKey !== null) activeExecKeys.add(execKey);
372
+ }
373
+
374
+ const deletedFacts = deletedTaskIds.map((taskId) => {
375
+ const row = deletedRows.find((item) => item?.taskId === taskId) ?? { taskId };
376
+ return extractTaskFacts(row, sessionByTask.get(taskId));
377
+ });
378
+
379
+ const archivedSessionIds = [];
380
+ const archivedSet = new Set();
381
+ if (options.archiveSessions) {
382
+ for (const facts of deletedFacts) {
383
+ if (facts.sessionId !== null && !activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
384
+ archivedSet.add(facts.sessionId);
385
+ archivedSessionIds.push(facts.sessionId);
386
+ await tryArchiveHostSession(deps, facts.sessionId);
387
+ }
388
+ }
389
+ if (typeof deps?.sessionStore?.forgetMany === 'function') {
390
+ await deps.sessionStore.forgetMany(deletedSet).catch(() => []);
391
+ } else if (typeof deps?.sessionStore?.forget === 'function') {
392
+ for (const id of deletedSet) {
393
+ await deps.sessionStore.forget(id).catch(() => false);
394
+ }
395
+ }
396
+ }
397
+
398
+ const removedWorktreePaths = [];
399
+ const removedWorktreeSet = new Set();
400
+ const removedWorkspaceIds = [];
401
+ const removedWorkspaceSet = new Set();
402
+
403
+ if (options.removeWorktrees) {
404
+ for (const facts of deletedFacts) {
405
+ // Strictly operate ONLY on worktree-isolated tasks; never touch shared directories or shared workspaces.
406
+ if (facts.isolation !== 'worktree') continue;
407
+ const execKey = sessionPathKey(facts.executionPath);
408
+ const sourceKey = sessionPathKey(facts.sourcePath);
409
+ if (execKey === null || execKey === sourceKey || activeExecKeys.has(execKey)) continue;
410
+
411
+ let worktreeEligibleForWorkspaceRemoval = false;
412
+ if (typeof deps?.worktrees?.removeManagedTree === 'function') {
413
+ if (!removedWorktreeSet.has(execKey)) {
414
+ const outcome = await deps.worktrees.removeManagedTree({
415
+ taskId: facts.taskId,
416
+ sourcePath: facts.sourcePath,
417
+ workspacePath: facts.executionPath,
418
+ });
419
+ if (outcome.removed && outcome.workspacePath) {
420
+ removedWorktreeSet.add(execKey);
421
+ removedWorktreePaths.push(outcome.workspacePath);
422
+ worktreeEligibleForWorkspaceRemoval = true;
423
+ } else if (outcome.reason === 'already-absent') {
424
+ removedWorktreeSet.add(execKey);
425
+ worktreeEligibleForWorkspaceRemoval = true;
426
+ }
427
+ } else {
428
+ worktreeEligibleForWorkspaceRemoval = true;
429
+ }
430
+ }
431
+
432
+ if (
433
+ worktreeEligibleForWorkspaceRemoval
434
+ && facts.workspaceId !== null
435
+ && !activeWorkspaceIds.has(facts.workspaceId)
436
+ && !removedWorkspaceSet.has(facts.workspaceId)
437
+ ) {
438
+ removedWorkspaceSet.add(facts.workspaceId);
439
+ removedWorkspaceIds.push(facts.workspaceId);
440
+ await tryDeleteHostWorkspace(deps, facts.workspaceId);
441
+ }
442
+ }
443
+ }
444
+
445
+ let removedPlanNodeIds = [];
446
+ if (options.cleanPlans && typeof plans?.deleteEmptyAncestors === 'function') {
447
+ const seedPlanIds = new Set();
448
+ for (const facts of deletedFacts) {
449
+ if (facts.planNodeId !== null) seedPlanIds.add(facts.planNodeId);
450
+ if (facts.parentNodeId !== null && facts.parentNodeId.startsWith('plan-')) {
451
+ seedPlanIds.add(facts.parentNodeId);
452
+ }
453
+ }
454
+ if (seedPlanIds.size > 0) {
455
+ try {
456
+ removedPlanNodeIds = await plans.deleteEmptyAncestors(seedPlanIds, remainingRows);
457
+ } catch {
458
+ removedPlanNodeIds = [];
459
+ }
460
+ }
461
+ }
462
+
463
+ return {
464
+ archivedSessionIds,
465
+ removedWorktreePaths,
466
+ removedWorkspaceIds,
467
+ removedPlanNodeIds,
468
+ };
469
+ }
470
+
471
+ export function validateOrphanCleanupRequest(body) {
472
+ if (!isObject(body) || Object.keys(body).some((key) => !ALLOWED_ORPHAN_KEYS.has(key))) {
473
+ invalid('expected explicit confirmation for orphan cleanup');
474
+ }
475
+ if (body.confirm !== true) invalid('orphan cleanup requires explicit confirmation', { field: 'confirm' });
476
+ for (const flag of ['archiveSessions', 'removeWorktrees']) {
477
+ if (body[flag] !== undefined && typeof body[flag] !== 'boolean') {
478
+ invalid(`${flag} must be a boolean`, { field: flag });
479
+ }
480
+ }
481
+ return {
482
+ archiveSessions: body.archiveSessions !== false,
483
+ removeWorktrees: body.removeWorktrees !== false,
484
+ };
485
+ }
486
+
487
+ /**
488
+ * Sweep residual worktrees and dispatched session identities whose task records
489
+ * were already deleted or rotated out of `history.json`.
490
+ *
491
+ * Strictly preserves any session, workspace or directory still referenced by a live
492
+ * or retained historical task, and never touches a shared checkout or shared project
493
+ * Workspace.
494
+ * @param {object} deps - runtime dependencies.
495
+ * @param {object} body - `{ confirm: true, archiveSessions?: boolean, removeWorktrees?: boolean }`.
496
+ * @returns {Promise<object>} sweep outcome.
497
+ */
498
+ export async function runOrphanCleanup(deps, body) {
499
+ const options = validateOrphanCleanupRequest(body);
500
+ const store = deps?.history;
501
+ if (typeof store?.load !== 'function') {
502
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task history is unavailable');
503
+ }
504
+ let archived = [];
505
+ try {
506
+ archived = await store.load();
507
+ } catch {
508
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task history could not be read');
509
+ }
510
+ const live = deps?.engine?.list?.() ?? [];
511
+ const allExisting = [...archived, ...live];
512
+ const existingTaskIds = new Set(allExisting.map((row) => row?.taskId).filter(Boolean));
513
+
514
+ let sessionRows = [];
515
+ if (typeof deps?.sessionStore?.list === 'function') {
516
+ try {
517
+ sessionRows = await deps.sessionStore.list();
518
+ } catch {
519
+ sessionRows = [];
520
+ }
521
+ }
522
+ const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
523
+
524
+ const activeSessionIds = new Set();
525
+ const activeWorkspaceIds = new Set();
526
+ const activeExecKeys = new Set();
527
+ const activeExecPaths = [];
528
+ const knownSourcePaths = new Set();
529
+
530
+ for (const row of allExisting) {
531
+ const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
532
+ if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
533
+ if (facts.workspaceId !== null) activeWorkspaceIds.add(facts.workspaceId);
534
+ if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
535
+ if (facts.executionPath !== null) {
536
+ activeExecPaths.push(facts.executionPath);
537
+ const key = sessionPathKey(facts.executionPath);
538
+ if (key !== null) activeExecKeys.add(key);
539
+ }
540
+ }
541
+
542
+ const orphanRows = sessionRows.filter((row) => typeof row?.taskId === 'string' && !existingTaskIds.has(row.taskId));
543
+ const orphanTaskIds = orphanRows.map((row) => row.taskId);
544
+
545
+ const archivedSessionIds = [];
546
+ const archivedSet = new Set();
547
+ const removedWorktreePaths = [];
548
+ const removedWorktreeSet = new Set();
549
+ const removedWorkspaceIds = [];
550
+ const removedWorkspaceSet = new Set();
551
+
552
+ for (const row of orphanRows) {
553
+ const facts = extractTaskFacts(null, row);
554
+ if (facts.sourcePath !== null) knownSourcePaths.add(facts.sourcePath);
555
+
556
+ if (options.archiveSessions && facts.sessionId !== null) {
557
+ if (!activeSessionIds.has(facts.sessionId) && !archivedSet.has(facts.sessionId)) {
558
+ archivedSet.add(facts.sessionId);
559
+ archivedSessionIds.push(facts.sessionId);
560
+ await tryArchiveHostSession(deps, facts.sessionId);
561
+ }
562
+ }
563
+
564
+ if (options.removeWorktrees && facts.isolation === 'worktree') {
565
+ const execKey = sessionPathKey(facts.executionPath);
566
+ const sourceKey = sessionPathKey(facts.sourcePath);
567
+ if (execKey !== null && execKey !== sourceKey && !activeExecKeys.has(execKey)) {
568
+ let canRemoveWs = false;
569
+ if (typeof deps?.worktrees?.removeManagedTree === 'function') {
570
+ if (!removedWorktreeSet.has(execKey)) {
571
+ const wt = await deps.worktrees.removeManagedTree({
572
+ taskId: facts.taskId,
573
+ sourcePath: facts.sourcePath,
574
+ workspacePath: facts.executionPath,
575
+ });
576
+ if (wt.removed && wt.workspacePath) {
577
+ removedWorktreeSet.add(execKey);
578
+ removedWorktreePaths.push(wt.workspacePath);
579
+ canRemoveWs = true;
580
+ } else if (wt.reason === 'already-absent') {
581
+ removedWorktreeSet.add(execKey);
582
+ canRemoveWs = true;
583
+ }
584
+ } else {
585
+ canRemoveWs = true;
586
+ }
587
+ }
588
+ if (
589
+ canRemoveWs
590
+ && facts.workspaceId !== null
591
+ && !activeWorkspaceIds.has(facts.workspaceId)
592
+ && !removedWorkspaceSet.has(facts.workspaceId)
593
+ ) {
594
+ removedWorkspaceSet.add(facts.workspaceId);
595
+ removedWorkspaceIds.push(facts.workspaceId);
596
+ await tryDeleteHostWorkspace(deps, facts.workspaceId);
597
+ }
598
+ }
599
+ }
600
+ }
601
+
602
+ if (options.archiveSessions && orphanTaskIds.length > 0) {
603
+ if (typeof deps?.sessionStore?.forgetMany === 'function') {
604
+ await deps.sessionStore.forgetMany(orphanTaskIds).catch(() => []);
605
+ } else if (typeof deps?.sessionStore?.forget === 'function') {
606
+ for (const id of orphanTaskIds) {
607
+ await deps.sessionStore.forget(id).catch(() => false);
608
+ }
609
+ }
610
+ }
611
+
612
+ if (options.removeWorktrees && typeof deps?.worktrees?.sweepOrphanTrees === 'function') {
613
+ try {
614
+ const swept = await deps.worktrees.sweepOrphanTrees({
615
+ activePaths: activeExecPaths,
616
+ sourcePaths: [...knownSourcePaths],
617
+ });
618
+ for (const wtPath of Array.isArray(swept?.removedWorktreePaths) ? swept.removedWorktreePaths : []) {
619
+ const key = sessionPathKey(wtPath);
620
+ if (key !== null && !removedWorktreeSet.has(key)) {
621
+ removedWorktreeSet.add(key);
622
+ removedWorktreePaths.push(wtPath);
623
+ }
624
+ }
625
+ } catch {
626
+ // Best-effort disk sweep.
627
+ }
628
+ }
629
+
630
+ return {
631
+ orphanSessionsForgotten: options.archiveSessions ? orphanTaskIds.length : 0,
632
+ cleaned: {
633
+ archivedSessionIds,
634
+ removedWorktreePaths,
635
+ removedWorkspaceIds,
636
+ },
637
+ retained: {
638
+ sourceFiles: true,
639
+ },
640
+ };
641
+ }
@@ -1,63 +1,63 @@
1
- // The one bound and normalization for a host-review note.
2
- //
3
- // A review note is free prose: Chinese, line breaks and emoji are ordinary in it. That is
4
- // why the bound is counted in Unicode code points — `Array.from(text).length` — rather than
5
- // in UTF-16 units, where an emoji counts twice. The same rule applies at every entry point
6
- // (MCP schema, HTTP route, engine, durable history projection), because a note one layer
7
- // accepts and another cuts is worse than a refusal: the caller would be told "recorded"
8
- // about text that was never recorded.
9
- //
10
- // This module has no imports on purpose: `src/mcp/server.js` is loaded by the standalone
11
- // MCP binary, which must not pull the engine or any native DSH module in through a shared
12
- // constant.
13
-
14
- /** Longest review note, in Unicode code points. */
15
- export const REVIEW_NOTE_MAX_CHARS = 8_000;
16
-
17
- /**
18
- * The normalization applied wherever a note is accepted or stored: surrounding whitespace
19
- * only. The body of the note is preserved exactly.
20
- * @param {unknown} value - candidate note.
21
- * @returns {string} the trimmed note, or '' for a non-string.
22
- */
23
- export function normalizeReviewNote(value) {
24
- return typeof value === 'string' ? value.trim() : '';
25
- }
26
-
27
- /**
28
- * @param {string} value - text to measure.
29
- * @returns {number} length in Unicode code points (0 for a non-string).
30
- */
31
- export function reviewNoteLength(value) {
32
- return typeof value === 'string' ? Array.from(value).length : 0;
33
- }
34
-
35
- /**
36
- * Refusal facts for an over-long note, so every surface reports the same numbers.
37
- * @param {string} value - the rejected note.
38
- * @returns {{ limit: number, length: number, message: string }} bound, actual length, message.
39
- */
40
- export function reviewNoteOverflow(value) {
41
- const length = reviewNoteLength(value);
42
- return {
43
- limit: REVIEW_NOTE_MAX_CHARS,
44
- length,
45
- message: `note must be at most ${REVIEW_NOTE_MAX_CHARS} Unicode code points, but it is ${length}`,
46
- };
47
- }
48
-
49
- /**
50
- * Cut a string to a code-point bound.
51
- *
52
- * Only for a stored value that reached the document some other way (an older build, a
53
- * hand-edited file). An accepted request is REFUSED when it is too long, never shortened.
54
- * @param {unknown} value - candidate text.
55
- * @param {number} [limit] - code points to keep.
56
- * @returns {string | null} bounded text, or null when the value is not a non-empty string.
57
- */
58
- export function truncateCodePoints(value, limit = REVIEW_NOTE_MAX_CHARS) {
59
- if (typeof value !== 'string' || value === '') return null;
60
- const points = Array.from(value);
61
- if (points.length <= limit) return value;
62
- return points.slice(0, limit).join('');
63
- }
1
+ // The one bound and normalization for a host-review note.
2
+ //
3
+ // A review note is free prose: Chinese, line breaks and emoji are ordinary in it. That is
4
+ // why the bound is counted in Unicode code points — `Array.from(text).length` — rather than
5
+ // in UTF-16 units, where an emoji counts twice. The same rule applies at every entry point
6
+ // (MCP schema, HTTP route, engine, durable history projection), because a note one layer
7
+ // accepts and another cuts is worse than a refusal: the caller would be told "recorded"
8
+ // about text that was never recorded.
9
+ //
10
+ // This module has no imports on purpose: `src/mcp/server.js` is loaded by the standalone
11
+ // MCP binary, which must not pull the engine or any native DSH module in through a shared
12
+ // constant.
13
+
14
+ /** Longest review note, in Unicode code points. */
15
+ export const REVIEW_NOTE_MAX_CHARS = 8_000;
16
+
17
+ /**
18
+ * The normalization applied wherever a note is accepted or stored: surrounding whitespace
19
+ * only. The body of the note is preserved exactly.
20
+ * @param {unknown} value - candidate note.
21
+ * @returns {string} the trimmed note, or '' for a non-string.
22
+ */
23
+ export function normalizeReviewNote(value) {
24
+ return typeof value === 'string' ? value.trim() : '';
25
+ }
26
+
27
+ /**
28
+ * @param {string} value - text to measure.
29
+ * @returns {number} length in Unicode code points (0 for a non-string).
30
+ */
31
+ export function reviewNoteLength(value) {
32
+ return typeof value === 'string' ? Array.from(value).length : 0;
33
+ }
34
+
35
+ /**
36
+ * Refusal facts for an over-long note, so every surface reports the same numbers.
37
+ * @param {string} value - the rejected note.
38
+ * @returns {{ limit: number, length: number, message: string }} bound, actual length, message.
39
+ */
40
+ export function reviewNoteOverflow(value) {
41
+ const length = reviewNoteLength(value);
42
+ return {
43
+ limit: REVIEW_NOTE_MAX_CHARS,
44
+ length,
45
+ message: `note must be at most ${REVIEW_NOTE_MAX_CHARS} Unicode code points, but it is ${length}`,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Cut a string to a code-point bound.
51
+ *
52
+ * Only for a stored value that reached the document some other way (an older build, a
53
+ * hand-edited file). An accepted request is REFUSED when it is too long, never shortened.
54
+ * @param {unknown} value - candidate text.
55
+ * @param {number} [limit] - code points to keep.
56
+ * @returns {string | null} bounded text, or null when the value is not a non-empty string.
57
+ */
58
+ export function truncateCodePoints(value, limit = REVIEW_NOTE_MAX_CHARS) {
59
+ if (typeof value !== 'string' || value === '') return null;
60
+ const points = Array.from(value);
61
+ if (points.length <= limit) return value;
62
+ return points.slice(0, limit).join('');
63
+ }