dsh-taskbridge 1.8.0 → 1.9.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 (50) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +246 -231
  3. package/antigravity/agents/dsh-taskbridge.md +17 -14
  4. package/antigravity/skills/dsh-taskbridge/SKILL.md +40 -27
  5. package/bin/dsh-delegate-codex-agent.js +9 -4
  6. package/codex/skills/dsh-taskbridge/SKILL.md +131 -0
  7. package/codex/skills/dsh-taskbridge/rules-reference-96027c387cb9b7587efa4aa3836235d86db1108068e007dc08196e807ca25e5d.md +114 -0
  8. package/docs/INTRODUCTION.md +148 -119
  9. package/docs/INTRODUCTION.zh.md +151 -134
  10. package/docs/antigravity-integration.md +47 -42
  11. package/docs/assets/taskbridge-workflow.en.svg +72 -0
  12. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  13. package/docs/claude-code.md +18 -18
  14. package/docs/codex-integration.md +139 -113
  15. package/docs/conversation-placement.md +7 -6
  16. package/docs/releases/1.8.0.zh.md +16 -16
  17. package/docs/releases/1.8.1.zh.md +24 -0
  18. package/docs/releases/1.9.0.zh.md +31 -0
  19. package/docs/runtime-compatibility.md +7 -9
  20. package/docs/silent-wait.md +17 -26
  21. package/docs/taskbridge-upgrade.md +4 -4
  22. package/lib/client.d.ts +74 -3
  23. package/lib/client.js +7 -7
  24. package/locale/en.json +7 -7
  25. package/locale/zh.json +7 -7
  26. package/package.json +11 -4
  27. package/src/antigravity/installer.js +1099 -1046
  28. package/src/antigravity/seam.js +142 -142
  29. package/src/client/api.js +258 -16
  30. package/src/client/index.jsx +130 -26
  31. package/src/client/task-cleanup.js +130 -5
  32. package/src/codex/agent-ownership.js +72 -12
  33. package/src/codex/installer.js +691 -268
  34. package/src/config/defaults.js +11 -15
  35. package/src/http/execution-plane.js +17 -0
  36. package/src/http/user-plane.js +17 -1
  37. package/src/index.d.ts +9 -1
  38. package/src/index.js +86 -64
  39. package/src/jobs/engine.js +279 -5
  40. package/src/jobs/history.js +18 -2
  41. package/src/jobs/plan-store.js +83 -0
  42. package/src/jobs/record-cleanup.js +714 -195
  43. package/src/mcp/server.js +271 -38
  44. package/src/mcp/wait.js +34 -15
  45. package/src/runtime/agent-runner.js +1 -0
  46. package/src/runtime/permissions.js +18 -0
  47. package/src/runtime/session-placement.js +36 -1
  48. package/src/runtime/worker-prompt.js +14 -9
  49. package/src/workspace/worktrees.js +155 -1
  50. package/codex/dsh-taskbridge.toml +0 -170
@@ -129,9 +129,11 @@ import {
129
129
  import { registerSessionRowMarker } from './workspaces-browser.jsx';
130
130
  import {
131
131
  cleanupCandidates,
132
+ cleanupConfirmText,
132
133
  cleanupProjection,
133
134
  cleanupSelectionSummary,
134
135
  cleanupWarningText,
136
+ selectCleanupCandidatesByPreset,
135
137
  toggleCleanupSelection,
136
138
  withSelectionState,
137
139
  } from './task-cleanup.js';
@@ -1510,12 +1512,15 @@ function PresetsCard({ store, snapshot }) {
1510
1512
  }
1511
1513
 
1512
1514
  /**
1513
- * Monitoring controls: the two no-progress reminders and the repeated-failure reminder.
1515
+ * Monitoring controls: the start-elapsed local self-check, the commander delivery
1516
+ * progress check, and the repeated-failure reminder.
1514
1517
  *
1515
- * There is exactly ONE time base — consecutive time without real progress — and TWO
1516
- * duration controls on it: the local self-check (default 10 minutes) and the run progress
1517
- * check reported to the dispatcher (default 40 minutes). A task that keeps working never
1518
- * reaches either, whatever its total runtime; a run's length is never itself a reminder.
1518
+ * `selfCheckSeconds` runs one read-only local inspection after execution starts
1519
+ * (default 10 minutes; active work does not postpone it). `attentionSeconds` reports a
1520
+ * run progress check to the commander when nothing new has been returned for that span
1521
+ * (default 40 minutes; internal activity, heartbeats, and self-checks do not reset it).
1522
+ * Neither reminder is a total-runtime cap and neither can cancel, restart, or resubmit
1523
+ * a task.
1519
1524
  *
1520
1525
  * What this card deliberately does NOT do: it does not submit work, does not read a
1521
1526
  * task, does not call a model, and does not create a monitoring process of its own. It
@@ -1808,7 +1813,7 @@ function ExecutionPanel({ store, snapshot }) {
1808
1813
  store.editDraft((current) => { current.worker.maxParallelism = value; });
1809
1814
  }}
1810
1815
  />
1811
- <Field label="工作区隔离" htmlFor="dshdg-worker-isolation" hint="默认独立工作树;共享工作区需要你明确选择。">
1816
+ <Field label="工作区隔离" htmlFor="dshdg-worker-isolation" hint="默认独立工作树;共享工作区需要你明确选择。两种模式均要求目标目录为已初始化且至少有 1 次 commit 的 Git 仓库根目录。">
1812
1817
  <select
1813
1818
  id="dshdg-worker-isolation"
1814
1819
  value={worker.isolation ?? ISOLATION_MODES[0]}
@@ -2131,7 +2136,7 @@ function TaskDetail({ store, task }) {
2131
2136
  <dt>无进展诊断</dt>
2132
2137
  <dd>
2133
2138
  {activity === null || activity.selfCheck === null || activity.selfCheck.verdict === null
2134
- ? (activity === null ? '未采集到' : '尚未触发程序自检(安静时间还没到自检间隔)')
2139
+ ? (activity === null ? '未采集到' : '尚未触发程序自检(开始运行时间还没到自检间隔,或已关闭自检)')
2135
2140
  : `${SELF_CHECK_LABELS[activity.selfCheck.verdict] ?? activity.selfCheck.verdict}`
2136
2141
  + (activity.selfCheck.checkedAt === null ? '' : `(${formatTime(activity.selfCheck.checkedAt)})`)}
2137
2142
  </dd>
@@ -2224,8 +2229,8 @@ function TaskDetail({ store, task }) {
2224
2229
  </>
2225
2230
  )}
2226
2231
  <p className="dshdg-hint">
2227
- 逐次授权桥只决定“这一次调用”。它不能创建或扩大任何长期有效的授权(“长期有效”指跨调用、跨会话持久的授权),不能修改设置、凭据、本机调用开关、提供方、模型或隔离方式,
2228
- 也不能预先批准后续调用;工作进程的常规沙箱权限始终保持 workspace-write。此界面不提供手工批准按钮,决定由本机 MCP 指挥官通过
2232
+ 逐次授权只覆盖当前调用。后续调用如需扩大权限,须重新核对参数并审批。它不能创建或扩大任何跨任务或长期有效的授权(“长期有效”指跨会话持久的授权),不能修改设置、凭据、本机调用开关、提供方、模型或隔离方式;
2233
+ 工作进程的常规沙箱权限始终保持 workspace-write。此界面不提供手工批准按钮,决定由本机 MCP 指挥官通过
2229
2234
  delegate_permission_decide 作出。
2230
2235
  </p>
2231
2236
 
@@ -2642,6 +2647,7 @@ function TaskTreeItem({ node, store, snapshot, collapsed, setCollapsed, expanded
2642
2647
  }
2643
2648
 
2644
2649
  function TaskTreePanel({ store, snapshot, onOpen }) {
2650
+ const nav = useContext(SessionNavigation);
2645
2651
  const view = snapshot.tree ?? null;
2646
2652
  const [recordView, setRecordView] = useState('recent');
2647
2653
  const [collapsed, setCollapsed] = useState(() => new Set());
@@ -2658,6 +2664,11 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2658
2664
  const [cleanupMode, setCleanupMode] = useState(false);
2659
2665
  const [cleanupSelection, setCleanupSelection] = useState({});
2660
2666
  const [cleanupConfirm, setCleanupConfirm] = useState(false);
2667
+ const [cleanupOptions, setCleanupOptions] = useState({
2668
+ archiveSessions: false,
2669
+ removeWorktrees: false,
2670
+ cleanPlans: false,
2671
+ });
2661
2672
  if (view === null) {
2662
2673
  return <p className="dshdg-faint" data-dshdg-tree-unavailable="">
2663
2674
  {snapshot.tasksError ? '任务树读取失败,下面显示已有记录。' : '当前宿主按列表显示任务。'}
@@ -2680,14 +2691,28 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2680
2691
  : groups.flatMap((group) => group.roots);
2681
2692
  const candidates = cleanupCandidates({ roots });
2682
2693
  const canCleanup = view.cleanupAvailable === true && (view.counts?.taskChains ?? 0) > 0;
2694
+ const canSweepOrphans = view.cleanupAvailable === true && typeof store?.cleanupOrphans === 'function';
2683
2695
  const cleanupActive = cleanupMode && canCleanup;
2684
2696
  const cleanupBusy = snapshot.loading?.cleanup === true;
2697
+ const orphanSweepBusy = snapshot.loading?.cleanupOrphans === true;
2685
2698
  const summary = cleanupSelectionSummary(cleanupSelection, candidates);
2686
2699
  const mayDelete = dateError === null && !cleanupBusy && summary.executable;
2687
2700
  function clearSelection() {
2688
2701
  setCleanupSelection({});
2689
2702
  setCleanupConfirm(false);
2690
2703
  }
2704
+ function applyPresetSelection(preset) {
2705
+ setCleanupSelection(selectCleanupCandidatesByPreset(candidates, preset));
2706
+ setCleanupConfirm(false);
2707
+ }
2708
+ function toggleCleanupOption(key) {
2709
+ setCleanupOptions((prev) => ({ ...prev, [key]: !prev[key] }));
2710
+ setCleanupConfirm(false);
2711
+ }
2712
+ async function runOrphanSweep() {
2713
+ if (orphanSweepBusy || cleanupBusy) return;
2714
+ await store.cleanupOrphans({ hostWorkspaces: nav?.workspaces });
2715
+ }
2691
2716
  const updateFilter = (setter) => (event) => {
2692
2717
  setter(event.target.value);
2693
2718
  clearSelection();
@@ -2708,6 +2733,7 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2708
2733
  function leaveCleanup() {
2709
2734
  setCleanupMode(false);
2710
2735
  clearSelection();
2736
+ setCleanupOptions({ archiveSessions: false, removeWorktrees: false, cleanPlans: false });
2711
2737
  }
2712
2738
  function onToggleChain(candidate) {
2713
2739
  setCleanupSelection((old) => toggleCleanupSelection(old, withSelectionState(candidate, old[candidate.chainId])));
@@ -2715,7 +2741,10 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2715
2741
  }
2716
2742
  async function confirmCleanup() {
2717
2743
  if (!mayDelete) return;
2718
- const result = await store.cleanupTasks(cleanupSelection);
2744
+ const result = await store.cleanupTasks(cleanupSelection, {
2745
+ ...cleanupOptions,
2746
+ hostWorkspaces: nav?.workspaces,
2747
+ });
2719
2748
  if (result.ok) leaveCleanup();
2720
2749
  setCleanupConfirm(false);
2721
2750
  }
@@ -2772,6 +2801,17 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2772
2801
  项目树
2773
2802
  </button>
2774
2803
  </div>
2804
+ {canSweepOrphans ? (
2805
+ <button
2806
+ type="button"
2807
+ data-dshdg-cleanup-orphans=""
2808
+ disabled={orphanSweepBusy || cleanupBusy}
2809
+ title="扫描并清理任务记录已删除后残留的隔离工作树目录、DSH 临时工作区及已删记录对应的派工对话(绝不触碰共享工作区与源码)"
2810
+ onClick={() => { void runOrphanSweep(); }}
2811
+ >
2812
+ {orphanSweepBusy ? '正在清理残留…' : '清理残留工作区与对话'}
2813
+ </button>
2814
+ ) : null}
2775
2815
  {canCleanup ? (
2776
2816
  <button
2777
2817
  type="button"
@@ -2830,6 +2870,65 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2830
2870
  <p className="dshdg-hint" data-dshdg-cleanup-counts="">
2831
2871
  {`已选 ${summary.chains} 条执行链 / 共 ${summary.rounds} 轮`}
2832
2872
  </p>
2873
+ <div className="dshdg-row" data-dshdg-cleanup-presets="">
2874
+ <span className="dshdg-hint">快捷选择(当前筛选视图):</span>
2875
+ <button
2876
+ type="button"
2877
+ data-dshdg-cleanup-preset="all"
2878
+ disabled={cleanupBusy}
2879
+ onClick={() => applyPresetSelection('all')}
2880
+ >
2881
+ 全选可清理
2882
+ </button>
2883
+ <button
2884
+ type="button"
2885
+ data-dshdg-cleanup-preset="accepted"
2886
+ disabled={cleanupBusy}
2887
+ onClick={() => applyPresetSelection('accepted')}
2888
+ >
2889
+ 全选已审查通过
2890
+ </button>
2891
+ <button
2892
+ type="button"
2893
+ data-dshdg-cleanup-preset="failed-cancelled"
2894
+ disabled={cleanupBusy}
2895
+ onClick={() => applyPresetSelection('failed-cancelled')}
2896
+ >
2897
+ 全选已失败/已取消
2898
+ </button>
2899
+ </div>
2900
+ <div className="dshdg-cleanup-options" data-dshdg-cleanup-options="">
2901
+ <label className="dshdg-check">
2902
+ <input
2903
+ type="checkbox"
2904
+ data-dshdg-cleanup-opt="archiveSessions"
2905
+ checked={cleanupOptions.archiveSessions}
2906
+ disabled={cleanupBusy}
2907
+ onChange={() => toggleCleanupOption('archiveSessions')}
2908
+ />
2909
+ <span>同时归档对应的 DSH 派工对话(共享与隔离模式均适用,不影响你自己的普通对话)</span>
2910
+ </label>
2911
+ <label className="dshdg-check">
2912
+ <input
2913
+ type="checkbox"
2914
+ data-dshdg-cleanup-opt="removeWorktrees"
2915
+ checked={cleanupOptions.removeWorktrees}
2916
+ disabled={cleanupBusy}
2917
+ onChange={() => toggleCleanupOption('removeWorktrees')}
2918
+ />
2919
+ <span>同时删除隔离任务的工作树目录与 DSH 临时工作区(仅作用于独立工作树,绝不删除共享工作区与源文件)</span>
2920
+ </label>
2921
+ <label className="dshdg-check">
2922
+ <input
2923
+ type="checkbox"
2924
+ data-dshdg-cleanup-opt="cleanPlans"
2925
+ checked={cleanupOptions.cleanPlans}
2926
+ disabled={cleanupBusy}
2927
+ onChange={() => toggleCleanupOption('cleanPlans')}
2928
+ />
2929
+ <span>同时清理已无关联任务的空规划节点</span>
2930
+ </label>
2931
+ </div>
2833
2932
  {cleanupConfirm ? null : <p className="dshdg-warn">{cleanupWarningText()}</p>}
2834
2933
  {Object.keys(cleanupSelection).length === 0 ? null : summary.problems.map((problem) => (
2835
2934
  <p className="dshdg-warn" role="alert" key={problem} data-dshdg-cleanup-problem="">{problem}</p>
@@ -2837,7 +2936,7 @@ function TaskTreePanel({ store, snapshot, onOpen }) {
2837
2936
  {cleanupConfirm ? (
2838
2937
  <div className="dshdg-row" data-dshdg-cleanup-confirm-dialog="" role="alertdialog" aria-label="确认永久删除记录">
2839
2938
  <span>
2840
- {`确认永久删除 ${summary.chains} 条执行链、共 ${summary.rounds} 轮的任务记录及审查意见?删除后无法按任务编号查询或续接。DSH 会话、工作区与源文件不会被删除。`}
2939
+ {cleanupConfirmText(summary, cleanupOptions)}
2841
2940
  </span>
2842
2941
  <button
2843
2942
  type="button"
@@ -3217,7 +3316,7 @@ function TasksPanel({ store, snapshot }) {
3217
3316
  return (
3218
3317
  <div className="dshdg-panel">
3219
3318
  <div className="dshdg-row">
3220
- <p className="dshdg-muted">这里只记录执行事实。执行完成不等于被接受:“等待宿主审查”要由宿主(例如 Codex)单独给出结论。</p>
3319
+ <p className="dshdg-muted">这里只记录执行事实。执行完成不等于被接受:“等待宿主审查”要由宿主(例如 Codex 或 Antigravity)单独给出结论。</p>
3221
3320
  <span className="dshdg-spacer" />
3222
3321
  <span className="dshdg-hint" data-dshdg-refresh-hint="">
3223
3322
  {changing !== true
@@ -3379,19 +3478,21 @@ function CodexPanel({ store, snapshot }) {
3379
3478
  return (
3380
3479
  <section className="dshdg-card" aria-labelledby="dshdg-codex-title">
3381
3480
  <div className="dshdg-row">
3382
- <h3 id="dshdg-codex-title">Codex 集成(子智能体 + MCP)</h3>
3481
+ <h3 id="dshdg-codex-title">Codex 集成(技能 Skill + MCP)</h3>
3383
3482
  <span className="dshdg-spacer" />
3384
3483
  <Badge tone={ready ? 'on' : 'off'}>{ready ? '已就绪' : '未就绪'}</Badge>
3385
3484
  </div>
3386
3485
  <p className="dshdg-muted">
3387
- {'点下面的按钮,把 '}
3388
- <span className="dshdg-mono">agents/dsh-taskbridge.toml</span>
3486
+ {'点下面的按钮,把原生技能 '}
3487
+ <span className="dshdg-mono">skills/dsh-taskbridge/SKILL.md</span>
3389
3488
  {' 装进 Codex 目录,并在 Codex 的 '}
3390
3489
  <span className="dshdg-mono">config.toml</span>
3391
- {' 里登记本插件的 stdio MCP 服务(delegate_status / delegate_submit / delegate_result / delegate_wait / delegate_cancel)。'
3392
- + '首次安装只会由你点击触发:打开本页、安装或升级本插件都不会自动创建子智能体文件或 MCP 条目。'
3393
- + '已经安装过的情况下,插件下次启动会把本插件自己写入的过期托管条目就地更新(例如补上 tool_timeout_sec);'
3394
- + '它不会改写非托管、被你改过的条目,也不会触碰 Codex 的其他设置。下面会显示当前条目缺了什么。'}
3490
+ {' 里登记本插件的 stdio MCP 服务(全套 11 个 delegate_* 工具:delegate_status / delegate_preflight / delegate_plan / delegate_submit / delegate_wait / delegate_permission_decide / delegate_question_answer / delegate_result / delegate_review / delegate_cancel / delegate_metrics)。'
3491
+ + '首次安装只会由你点击触发:打开本页、安装或升级本插件都不会自动创建技能文件或 MCP 条目。'
3492
+ + '若目录里存在早期版本写入且未经你改动的旧子智能体文件(agents/dsh-taskbridge.toml / agents/dsh-delegate.toml),'
3493
+ + '插件会在升级或安装时自动迁移为原生技能并安全移除旧文件;你手动改过的旧文件会原样保留不删。'
3494
+ + '已经安装过的情况下,插件下次启动也会把本插件自己写入的过期托管 MCP 条目就地更新(例如补上 tool_timeout_sec),'
3495
+ + '不触碰非托管条目或 Codex 的其他设置。'}
3395
3496
  </p>
3396
3497
  {error === null ? null : <p className="dshdg-fail">{error}</p>}
3397
3498
  {codex === null ? (
@@ -3412,7 +3513,7 @@ function CodexPanel({ store, snapshot }) {
3412
3513
  <p className="dshdg-hint" data-dshdg-codex-drift="">
3413
3514
  {'这个托管 MCP 条目已经过期:'}
3414
3515
  {codexMcpDriftText(codex.mcp)}
3415
- {'。插件下次启动会自动在原地更新;也可以点上面的「安装 / 更新 TaskBridge 智能体」。'}
3516
+ {'。插件下次启动会自动在原地更新;也可以点上面的「安装 / 更新 TaskBridge 技能」。'}
3416
3517
  </p>
3417
3518
  ) : null}
3418
3519
  {notes.length === 0 ? null : (
@@ -3425,7 +3526,7 @@ function CodexPanel({ store, snapshot }) {
3425
3526
  {refreshing ? '读取中…' : '刷新状态'}
3426
3527
  </button>
3427
3528
  <button type="button" className="dshdg-primary" disabled={disabled} onClick={() => { void store.runCodexAction('install'); }}>
3428
- {busy ? '处理中…' : '安装 / 更新 TaskBridge 智能体'}
3529
+ {busy ? '处理中…' : '安装 / 更新 TaskBridge 技能'}
3429
3530
  </button>
3430
3531
  <button type="button" disabled={disabled} onClick={() => { void store.runCodexAction('repair'); }}>
3431
3532
  仅修复 MCP 配置
@@ -3440,11 +3541,10 @@ function CodexPanel({ store, snapshot }) {
3440
3541
  </>
3441
3542
  )}
3442
3543
  <p className="dshdg-hint">
3443
- {'安装后需要让 Codex 重新载入:新开会话或重启 Codex,才会读到新的子智能体和 MCP 条目。'
3444
- + '本插件不宣称当前 Codex 桌面版/CLI 能在输入框用 @dsh-taskbridge 直接选中该子智能体——这取决于 Codex 版本自身是否提供提及选择;'
3445
- + '这里只保证子智能体文件与 MCP 工具存在,并由你在 Codex 提供的选择方式中指派它。'
3446
- + '子智能体只在明确指派时派发任务,并在提交前先检查上面的本机调用开关;本页不会替你打开该开关。'
3447
- + '同名的自定义 agent 会被保留并报告为冲突;没有本插件托管标记注释的同名 MCP 条目也视为你自己写的,不会被覆盖或删除。'}
3544
+ {'安装后需要让 Codex 重新载入:新开会话或重启 Codex,才会读到新的原生技能和 MCP 条目。'
3545
+ + 'Codex 会话在明确指派时(例如 $dsh-taskbridge 或明确要求交给 DSH / TaskBridge)会按技能规则由当前会话直接调用 delegate_submit 与单链 delegate_wait(利用 tool_timeout_sec = 3660 静默长等,不再派生子智能体并做 wait_agent 短轮询)。'
3546
+ + '技能只在明确指派时派发任务,并在提交前先检查上面的本机调用开关;本页不会替你打开该开关。'
3547
+ + '同名的自定义技能文件或你手动改过的旧 agents/*.toml 都会被保留而不被覆盖或删除;没有本插件托管标记注释的同名 MCP 条目也视为你自己写的,不会被覆盖或删除。'}
3448
3548
  </p>
3449
3549
  </section>
3450
3550
  );
@@ -3678,9 +3778,11 @@ export {
3678
3778
  };
3679
3779
 
3680
3780
  export {
3781
+ CLEANUP_PRESETS,
3681
3782
  MAX_CLEANUP_CHAINS,
3682
3783
  cleanupBlockerLabel,
3683
3784
  cleanupCandidates,
3785
+ cleanupConfirmText,
3684
3786
  cleanupOutcome,
3685
3787
  cleanupProjection,
3686
3788
  cleanupRequest,
@@ -3688,7 +3790,9 @@ export {
3688
3790
  cleanupSelectionSummary,
3689
3791
  cleanupWarningText,
3690
3792
  describeCleanupOutcome,
3793
+ describeOrphanCleanupOutcome,
3691
3794
  pruneCleanupSelection,
3795
+ selectCleanupCandidatesByPreset,
3692
3796
  toggleCleanupSelection,
3693
3797
  withSelectionState,
3694
3798
  } from './task-cleanup.js';
@@ -95,6 +95,12 @@ export function cleanupCandidates(view) {
95
95
  parentNodeId: typeof chain.parentNodeId === 'string' ? chain.parentNodeId : null,
96
96
  nodeId: typeof node?.nodeId === 'string' ? node.nodeId : null,
97
97
  nodeKind: typeof node?.kind === 'string' ? node.kind : 'unknown',
98
+ nodeStatus: typeof chain.nodeStatus === 'string'
99
+ ? chain.nodeStatus
100
+ : (typeof node?.nodeStatus === 'string' ? node.nodeStatus : null),
101
+ isolation: typeof chain.isolation === 'string'
102
+ ? chain.isolation
103
+ : (Array.isArray(chain.rounds) && typeof chain.rounds[0]?.isolation === 'string' ? chain.rounds[0].isolation : null),
98
104
  selectable,
99
105
  blockers,
100
106
  reason: selectable
@@ -178,6 +184,49 @@ export function toggleCleanupSelection(selection, candidate) {
178
184
  return next;
179
185
  }
180
186
 
187
+ /**
188
+ * Which status group one preset shortcut selects.
189
+ *
190
+ * `all` takes every selectable chain of the current view, `accepted` only the chains
191
+ * the host marked `accepted`, and `failed-cancelled` the chains that ended badly:
192
+ * `failed`, `cancelled`, and `interrupted` (a chain a host restart left in a terminal
193
+ * state no round can resume).
194
+ */
195
+ export const CLEANUP_PRESETS = Object.freeze(['all', 'accepted', 'failed-cancelled']);
196
+
197
+ /**
198
+ * Batch-select up to {@link MAX_CLEANUP_CHAINS} selectable candidates matching a preset,
199
+ * optionally restricted to the chains currently visible under the active UI filters.
200
+ * @param {object[]} candidates - entries from {@link cleanupCandidates}.
201
+ * @param {'all'|'accepted'|'failed-cancelled'} [preset] - which status group to select.
202
+ * @param {Set<string>|string[]|null} [visibleChainIds] - optional visible chain id filter.
203
+ * @returns {object} `{ [chainId]: taskIds }` selection map.
204
+ */
205
+ export function selectCleanupCandidatesByPreset(candidates, preset = 'all', visibleChainIds = null) {
206
+ const visibleSet = visibleChainIds instanceof Set
207
+ ? visibleChainIds
208
+ : (Array.isArray(visibleChainIds) ? new Set(visibleChainIds) : null);
209
+ const next = {};
210
+ let count = 0;
211
+ for (const candidate of Array.isArray(candidates) ? candidates : []) {
212
+ if (count >= MAX_CLEANUP_CHAINS) break;
213
+ if (candidate === null || typeof candidate !== 'object' || candidate.selectable !== true) continue;
214
+ if (visibleSet !== null && !visibleSet.has(candidate.chainId)) continue;
215
+ if (preset === 'accepted' && candidate.nodeStatus !== 'accepted') continue;
216
+ if (
217
+ preset === 'failed-cancelled'
218
+ && candidate.nodeStatus !== 'failed'
219
+ && candidate.nodeStatus !== 'cancelled'
220
+ && candidate.nodeStatus !== 'interrupted'
221
+ ) {
222
+ continue;
223
+ }
224
+ next[candidate.chainId] = candidate.taskIds.slice();
225
+ count += 1;
226
+ }
227
+ return next;
228
+ }
229
+
181
230
  /**
182
231
  * What the confirmation says BEFORE anything is sent.
183
232
  *
@@ -222,16 +271,20 @@ export function cleanupSelectionSummary(selection, candidates) {
222
271
  * @param {object[]} candidates - current candidates.
223
272
  * @returns {{ body: { chains: Array<{ chainId: string, taskIds: string[] }> }, problems: string[] }} request.
224
273
  */
225
- export function cleanupRequest(selection, candidates) {
274
+ export function cleanupRequest(selection, candidates, options = {}) {
226
275
  const byId = new Map(candidates.map((candidate) => [candidate.chainId, candidate]));
227
276
  const summary = cleanupSelectionSummary(selection, candidates);
228
277
  if (!summary.executable) return { body: { chains: [] }, problems: summary.problems };
229
278
  const chains = [];
230
- for (const [chainId, ids] of Object.entries(selection)) {
279
+ for (const [chainId] of Object.entries(selection)) {
231
280
  const candidate = byId.get(chainId);
232
281
  chains.push({ chainId: candidate.chainId, taskIds: candidate.taskIds.slice() });
233
282
  }
234
- return { body: { chains }, problems: [] };
283
+ const body = { chains };
284
+ if (options?.archiveSessions === true) body.archiveSessions = true;
285
+ if (options?.removeWorktrees === true) body.removeWorktrees = true;
286
+ if (options?.cleanPlans === true) body.cleanPlans = true;
287
+ return { body, problems: [] };
235
288
  }
236
289
 
237
290
  /**
@@ -272,8 +325,76 @@ export function cleanupOutcome(outcome) {
272
325
  export function describeCleanupOutcome(outcome) {
273
326
  const summary = cleanupOutcome(outcome);
274
327
  if (summary.chains === 0 && summary.rounds === 0) return '';
328
+ const cleaned = outcome?.cleaned ?? null;
329
+ const retained = outcome?.retained ?? null;
330
+ const hasLinkedOption = cleaned !== null
331
+ || (retained !== null && (
332
+ retained.sessions === false
333
+ || retained.worktrees === false
334
+ || retained.workspaces === false
335
+ || retained.plans === false
336
+ ));
337
+ if (!hasLinkedOption) {
338
+ return `已永久删除 ${summary.chains} 条执行链、共 ${summary.rounds} 轮的任务记录与审查意见;`
339
+ + 'DSH 会话、工作区与源文件均未删除。';
340
+ }
341
+ const archivedCount = Array.isArray(cleaned?.archivedSessionIds) ? cleaned.archivedSessionIds.length : 0;
342
+ const worktreeCount = Array.isArray(cleaned?.removedWorktreePaths) ? cleaned.removedWorktreePaths.length : 0;
343
+ const workspaceCount = Array.isArray(cleaned?.removedWorkspaceIds) ? cleaned.removedWorkspaceIds.length : 0;
344
+ const planCount = Array.isArray(cleaned?.removedPlanNodeIds) ? cleaned.removedPlanNodeIds.length : 0;
345
+ const extras = [];
346
+ if (archivedCount > 0) extras.push(`归档 ${archivedCount} 个派工对话`);
347
+ if (worktreeCount > 0) extras.push(`清理 ${worktreeCount} 个隔离工作树`);
348
+ if (workspaceCount > 0) extras.push(`移除 ${workspaceCount} 个临时工作区`);
349
+ if (planCount > 0) extras.push(`清理 ${planCount} 个空规划节点`);
350
+ const linkedClause = extras.length > 0
351
+ ? `同步${extras.join('、')};`
352
+ : '无额外需归档的派工对话或隔离工作树;';
275
353
  return `已永久删除 ${summary.chains} 条执行链、共 ${summary.rounds} 轮的任务记录与审查意见;`
276
- + 'DSH 会话、工作区与源文件均未删除。';
354
+ + `${linkedClause}主项目源文件与共享工作区均未删除。`;
355
+ }
356
+
357
+ /**
358
+ * Plain-Chinese description of one completed orphan worktree/session sweep.
359
+ * @param {object | null} outcome - the host's orphan cleanup body.
360
+ * @returns {string} summary sentence.
361
+ */
362
+ export function describeOrphanCleanupOutcome(outcome) {
363
+ if (outcome === null || typeof outcome !== 'object') return '';
364
+ const cleaned = outcome.cleaned ?? {};
365
+ const archivedCount = Array.isArray(cleaned.archivedSessionIds) ? cleaned.archivedSessionIds.length : 0;
366
+ const worktreeCount = Array.isArray(cleaned.removedWorktreePaths) ? cleaned.removedWorktreePaths.length : 0;
367
+ const workspaceCount = Array.isArray(cleaned.removedWorkspaceIds) ? cleaned.removedWorkspaceIds.length : 0;
368
+ const forgottenCount = Number.isFinite(outcome.orphanSessionsForgotten) ? outcome.orphanSessionsForgotten : 0;
369
+ if (archivedCount === 0 && worktreeCount === 0 && workspaceCount === 0 && forgottenCount === 0) {
370
+ return '未发现残留的隔离工作树或已删记录的派工对话;主项目源文件与共享工作区均未改动。';
371
+ }
372
+ const parts = [];
373
+ if (archivedCount > 0) parts.push(`归档 ${archivedCount} 个已删记录的派工对话`);
374
+ else if (forgottenCount > 0) parts.push(`清理 ${forgottenCount} 条残留会话映射`);
375
+ if (worktreeCount > 0) parts.push(`清理 ${worktreeCount} 个残留隔离工作树`);
376
+ if (workspaceCount > 0) parts.push(`移除 ${workspaceCount} 个临时工作区`);
377
+ return `已完成残留清理:${parts.join('、')};主项目源文件与共享工作区均未删除。`;
378
+ }
379
+
380
+ /**
381
+ * Build the confirmation dialog text before deletion is executed.
382
+ * @param {{ chains: number, rounds: number }} summary - selection counts.
383
+ * @param {{ archiveSessions?: boolean, removeWorktrees?: boolean, cleanPlans?: boolean }} [options] - linked cleanup choices.
384
+ * @returns {string} confirmation sentence.
385
+ */
386
+ export function cleanupConfirmText(summary, options = {}) {
387
+ const archiveSessions = options?.archiveSessions === true;
388
+ const removeWorktrees = options?.removeWorktrees === true;
389
+ const cleanPlans = options?.cleanPlans === true;
390
+ if (!archiveSessions && !removeWorktrees && !cleanPlans) {
391
+ return `确认永久删除 ${summary.chains} 条执行链、共 ${summary.rounds} 轮的任务记录及审查意见?删除后无法按任务编号查询或续接。DSH 会话、工作区与源文件不会被删除。`;
392
+ }
393
+ const linked = [];
394
+ if (archiveSessions) linked.push('归档对应的 DSH 派工对话(不影响你自己的普通对话)');
395
+ if (removeWorktrees) linked.push('删除隔离任务的工作树目录与临时工作区(共享工作区绝不删除)');
396
+ if (cleanPlans) linked.push('清理已无关联任务的空规划节点');
397
+ return `确认永久删除 ${summary.chains} 条执行链、共 ${summary.rounds} 轮的任务记录及审查意见,并同时${linked.join('、')}?删除后无法按任务编号查询或续接;主项目源文件与共享工作区不会被删除。`;
277
398
  }
278
399
 
279
400
  /**
@@ -286,7 +407,7 @@ export function cleanupWarningText() {
286
407
 
287
408
  /**
288
409
  * A detached copy of the projection, for one caller that must not see bindings change.
289
- * @returns {object} the seven functions plus the bound.
410
+ * @returns {object} the projection functions plus the bound.
290
411
  */
291
412
  export function cleanupProjection() {
292
413
  return {
@@ -294,11 +415,15 @@ export function cleanupProjection() {
294
415
  request: cleanupRequest,
295
416
  outcome: cleanupOutcome,
296
417
  describe: describeCleanupOutcome,
418
+ describeOrphans: describeOrphanCleanupOutcome,
419
+ confirmText: cleanupConfirmText,
420
+ selectByPreset: selectCleanupCandidatesByPreset,
297
421
  selectionSummary: cleanupSelectionSummary,
298
422
  prune: pruneCleanupSelection,
299
423
  toggle: toggleCleanupSelection,
300
424
  blockerLabel: cleanupBlockerLabel,
301
425
  warning: cleanupWarningText,
302
426
  MAX_CHAINS: MAX_CLEANUP_CHAINS,
427
+ PRESETS: CLEANUP_PRESETS,
303
428
  };
304
429
  }
@@ -38,9 +38,12 @@ import { dirname, isAbsolute, join, resolve } from 'node:path';
38
38
  /** Schema version of the record this module writes. */
39
39
  export const OWNERSHIP_SCHEMA_VERSION = 1;
40
40
 
41
- /** Directory, inside the plugin data directory, that holds one file per Codex home. */
41
+ /** Directory, inside the plugin data directory, that holds one legacy agent record per Codex home. */
42
42
  export const OWNERSHIP_DIR_NAME = 'codex-agent-ownership';
43
43
 
44
+ /** Directory, inside the plugin data directory, that holds one skill record per Codex home. */
45
+ export const SKILL_OWNERSHIP_DIR_NAME = 'codex-skill-ownership';
46
+
44
47
  /** A digest: lowercase hex SHA-256. */
45
48
  const SHA256 = /^[0-9a-f]{64}$/u;
46
49
 
@@ -73,12 +76,17 @@ export function pluginDataDirectory(env = process.env) {
73
76
  * @param {Record<string, string | undefined>} [env] - environment (`DSH_HOME`).
74
77
  * @returns {string | null} absolute record path, or null when the data directory is unusable.
75
78
  */
76
- export function ownershipRecordPath(codexHome, env = process.env) {
79
+ export function ownershipRecordPath(codexHome, env = process.env, dirName = OWNERSHIP_DIR_NAME) {
77
80
  const dataDir = pluginDataDirectory(env);
78
81
  if (dataDir === null) return null;
79
82
  if (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome)) return null;
80
83
  const key = createHash('sha256').update(resolve(codexHome), 'utf8').digest('hex');
81
- return join(dataDir, OWNERSHIP_DIR_NAME, `${key}.json`);
84
+ return join(dataDir, dirName, `${key}.json`);
85
+ }
86
+
87
+ /** The skill ownership record path for one Codex home. */
88
+ export function skillOwnershipRecordPath(codexHome, env = process.env) {
89
+ return ownershipRecordPath(codexHome, env, SKILL_OWNERSHIP_DIR_NAME);
82
90
  }
83
91
 
84
92
  /**
@@ -94,14 +102,35 @@ export function ownershipRecordPath(codexHome, env = process.env) {
94
102
  * platform attribute read. Injected so this module never grows a second, weaker copy of it.
95
103
  * @returns {Promise<{ ok: boolean, missing: boolean, reason: string }>} verdict.
96
104
  */
97
- async function inspectRealChain(target, classify) {
105
+ export function chainPathsOf(target) {
98
106
  const absolute = resolve(target);
99
107
  const root = rootOf(absolute);
108
+ const paths = [root];
100
109
  let current = root;
101
- if ((await classify(root)) !== 'directory') return { ok: false, missing: false, reason: 'ancestor-not-a-directory' };
102
110
  for (const part of absolute.slice(root.length).split(/[\\/]+/u).filter((part) => part !== '')) {
103
111
  current = join(current, part);
104
- const kind = await classify(current);
112
+ paths.push(current);
113
+ }
114
+ return paths;
115
+ }
116
+
117
+ async function inspectRealChain(target, classify, classifyMany = null) {
118
+ const paths = chainPathsOf(target);
119
+ if (typeof classifyMany === 'function') {
120
+ const verdicts = await classifyMany(paths);
121
+ if (verdicts.get(paths[0]) !== 'directory') return { ok: false, missing: false, reason: 'ancestor-not-a-directory' };
122
+ for (let i = 1; i < paths.length; i += 1) {
123
+ const kind = verdicts.get(paths[i]);
124
+ if (kind === 'directory') continue;
125
+ if (kind === 'missing') return { ok: false, missing: true, reason: 'ancestor-missing' };
126
+ if (kind === 'link') return { ok: false, missing: false, reason: 'ancestor-is-a-link' };
127
+ return { ok: false, missing: false, reason: 'ancestor-not-a-directory' };
128
+ }
129
+ return { ok: true, missing: false, reason: 'ok' };
130
+ }
131
+ if ((await classify(paths[0])) !== 'directory') return { ok: false, missing: false, reason: 'ancestor-not-a-directory' };
132
+ for (let i = 1; i < paths.length; i += 1) {
133
+ const kind = await classify(paths[i]);
105
134
  if (kind === 'directory') continue;
106
135
  if (kind === 'missing') return { ok: false, missing: true, reason: 'ancestor-missing' };
107
136
  if (kind === 'link') return { ok: false, missing: false, reason: 'ancestor-is-a-link' };
@@ -135,11 +164,11 @@ function rootOf(absolute) {
135
164
  * @param {object} options - `codexHome` (real, pinned), `env`, `classify` (see {@link inspectRealChain}).
136
165
  * @returns {Promise<string | null>} LF-normalized template digest, or null.
137
166
  */
138
- export async function recallTemplateDigest({ codexHome, env = process.env, classify } = {}) {
139
- const path = ownershipRecordPath(codexHome, env);
167
+ export async function recallTemplateDigest({ codexHome, env = process.env, classify, classifyMany = null, dirName = OWNERSHIP_DIR_NAME } = {}) {
168
+ const path = ownershipRecordPath(codexHome, env, dirName);
140
169
  if (path === null) return null;
141
- if (typeof classify !== 'function') return null;
142
- const chain = await inspectRealChain(dirname(path), classify);
170
+ if (typeof classify !== 'function' && typeof classifyMany !== 'function') return null;
171
+ const chain = await inspectRealChain(dirname(path), classify, classifyMany);
143
172
  if (chain.ok !== true) return null;
144
173
  const info = await lstat(path).catch(() => null);
145
174
  // A junction is a directory to `lstat`, and a symlink is not a regular file: both are refused.
@@ -181,8 +210,10 @@ export async function rememberTemplateDigest({
181
210
  writeFileAtomic,
182
211
  mkdir: makeDirectory,
183
212
  classify,
213
+ classifyMany = null,
214
+ dirName = OWNERSHIP_DIR_NAME,
184
215
  } = {}) {
185
- const path = ownershipRecordPath(codexHome, env);
216
+ const path = ownershipRecordPath(codexHome, env, dirName);
186
217
  if (path === null) return { ok: false, reason: 'record-path-unusable' };
187
218
  if (typeof template !== 'string' || template === '') return { ok: false, reason: 'no-template' };
188
219
  if (typeof classify !== 'function') return { ok: false, reason: 'no-classifier' };
@@ -199,7 +230,7 @@ export async function rememberTemplateDigest({
199
230
  }
200
231
  if (current !== template) return { ok: false, reason: 'agent-not-this-template' };
201
232
 
202
- const chain = await inspectRealChain(dirname(path), classify);
233
+ const chain = await inspectRealChain(dirname(path), classify, classifyMany);
203
234
  if (chain.ok !== true) {
204
235
  if (chain.reason !== 'ancestor-missing') return { ok: false, reason: chain.reason };
205
236
  // The record directory does not exist yet: create it one level at a time and re-prove.
@@ -265,6 +296,35 @@ async function createArchiveDirectory(directory, classify, makeDirectory) {
265
296
  * @param {string} text - agent file or template text.
266
297
  * @returns {string} lowercase hex SHA-256.
267
298
  */
299
+ export async function recallSkillTemplateDigest({ codexHome, env = process.env, classify, classifyMany = null } = {}) {
300
+ return await recallTemplateDigest({ codexHome, env, classify, classifyMany, dirName: SKILL_OWNERSHIP_DIR_NAME });
301
+ }
302
+
303
+ export async function rememberSkillTemplateDigest({
304
+ codexHome,
305
+ env = process.env,
306
+ template,
307
+ skillPath,
308
+ readFile: read = readFile,
309
+ writeFileAtomic,
310
+ mkdir: makeDirectory,
311
+ classify,
312
+ classifyMany = null,
313
+ } = {}) {
314
+ return await rememberTemplateDigest({
315
+ codexHome,
316
+ env,
317
+ template,
318
+ agentPath: skillPath,
319
+ readFile: read,
320
+ writeFileAtomic,
321
+ mkdir: makeDirectory,
322
+ classify,
323
+ classifyMany,
324
+ dirName: SKILL_OWNERSHIP_DIR_NAME,
325
+ });
326
+ }
327
+
268
328
  export function digestLf(text) {
269
329
  return createHash('sha256').update(String(text).replace(/\r\n/gu, '\n'), 'utf8').digest('hex');
270
330
  }