dsh-taskbridge 1.8.0 → 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.
@@ -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
  }
@@ -522,6 +522,9 @@ export const KNOWN_AGENT_TEMPLATES = [
522
522
  // Published 1.7.1 companion before the 1.8.0 black-box simplification, in LF and CRLF.
523
523
  { version: '1.7.1', sha256: '5a55b978c3de4f7cec8922d1af5302ef46b0bcbda867bfe53faebac1980eb1b3' },
524
524
  { version: '1.7.1', sha256: '026157837e2a99c5a265badb2ca6dc77be1ddcac28871e5949b80e61c949bfa0' },
525
+ // Published 1.8.0 companion before the 1.8.1 dual-client symmetry and Q&A boundary refinement, in LF and CRLF.
526
+ { version: '1.8.0', sha256: 'ba3c964cad6b9ae395dbe0d74971a430795fd8927a4a5daeb6a45617823a9cab' },
527
+ { version: '1.8.0', sha256: '6f732230068f3230f9ad1c6a92d30d677f717dd0b0ebd92abb73ed7578f956dd' },
525
528
  ];
526
529
 
527
530
  /** The `version = "…"` line of an agent file, at column 0. */
@@ -102,27 +102,23 @@ export const LIMITS = Object.freeze({
102
102
  });
103
103
 
104
104
  /**
105
- * Default activity-monitoring thresholds, in seconds of *inactivity*.
105
+ * Default progress-and-monitoring thresholds, in seconds.
106
106
  *
107
- * There is exactly ONE time base: consecutive time without real progress. Real progress
108
- * — model output, a reasoning step, a tool call or a tool result — resets it; a
109
- * heartbeat, a result poll, the self-check itself and a plain state read do not.
107
+ * `selfCheckSeconds` measures elapsed time from run start for one read-only local
108
+ * inspection (default 10 minutes; does not require a host to be waiting).
110
109
  *
111
- * Two reminders are measured on that clock, and each can be switched off with `0`:
112
- *
113
- * * `selfCheckSeconds` — one read-only local inspection (default 10 minutes);
114
- * * `attentionSeconds` — one notification to the commander asking it to check the
115
- * run's progress (default 40 minutes).
116
- *
117
- * Neither depends on total runtime, so a task that keeps working for hours produces
118
- * neither. Nothing here ever ends, cancels or restarts a run: a reminder is a REPORT,
119
- * never a verdict.
110
+ * `attentionSeconds` measures how long nothing new has been RETURNED to the commander
111
+ * (default 40 minutes). Internal model/tool activity, heartbeats, permission/question
112
+ * waits, and local self-checks do NOT reset this delivery clock; only a real stage
113
+ * result or terminal delivery moves it. Neither threshold ever ends, cancels, or restarts
114
+ * a run: a reminder is a progress checkpoint, never a verdict.
120
115
  */
121
116
  export const MONITORING_DEFAULTS = Object.freeze({
122
- /** No-progress span after which one read-only local self-check is performed (0 = off). */
117
+ /** Elapsed seconds from run start after which one read-only local self-check runs (0 = off). */
123
118
  selfCheckSeconds: 10 * 60,
124
119
  /**
125
- * No-progress span after which the wait reports the run progress check (0 = off).
120
+ * Seconds without returning a new result to the commander before the wait reports a
121
+ * run progress check (0 = off).
126
122
  *
127
123
  * This is the ONE notification interval: it doubles as the point at which a host is
128
124
  * asked to confirm the goal, so there is no second duration to configure.
@@ -42,7 +42,7 @@ import { sameRecordedDirectory } from '../jobs/continuation-identity.js';
42
42
  import { buildTaskTree } from '../jobs/task-tree.js';
43
43
  import { findDisplayNode } from '../jobs/task-display.js';
44
44
  import { MAX_PLAN_BATCH, PLAN_CODES } from '../jobs/plan-store.js';
45
- import { cleanupOverview, runCleanup } from '../jobs/record-cleanup.js';
45
+ import { cleanupOverview, runCleanup, runOrphanCleanup } from '../jobs/record-cleanup.js';
46
46
 
47
47
  /**
48
48
  * Route prefix, already below `/api` because the native exact-route registry
@@ -594,6 +594,16 @@ export function userPlaneRoutes(deps) {
594
594
  return jsonResponse(200, { ok: true, ...outcome });
595
595
  },
596
596
  },
597
+ {
598
+ path: `${USER_PLANE_PREFIX}/tasks/cleanup-orphans`,
599
+ methods: ['POST'],
600
+ requestBody: BODY_MODE,
601
+ fetch: async (request) => {
602
+ const body = await readJsonRequest(request);
603
+ const outcome = await runOrphanCleanup(deps, body);
604
+ return jsonResponse(200, { ok: true, ...outcome });
605
+ },
606
+ },
597
607
  {
598
608
  path: `${USER_PLANE_PREFIX}/tasks/cancel`,
599
609
  methods: ['POST'],
@@ -3904,6 +3904,7 @@ export class JobEngine {
3904
3904
  taskId: task.taskId,
3905
3905
  connectionId: task.connectionId,
3906
3906
  sourcePath: task.sourcePath,
3907
+ isolation: task.effective?.worker?.isolation ?? null,
3907
3908
  // Worker sessions are writable only inside their current DSH workspace.
3908
3909
  // Wider sandbox requests are refused when no bridge is armed, and decided
3909
3910
  // per call by the commander when one is. The services that own both facts
@@ -467,7 +467,7 @@ export class HistoryStore {
467
467
  for (const taskId of ids) {
468
468
  const row = byId.get(taskId);
469
469
  if (row === undefined) missing.push(taskId);
470
- else if (!isTerminal(row.state) || row.state === 'interrupted') live.push(taskId);
470
+ else if (!isTerminal(row.state)) live.push(taskId);
471
471
  }
472
472
  if (missing.length > 0 || live.length > 0) {
473
473
  // The ids are echoed back because the caller sent them; nothing else is.
@@ -130,6 +130,89 @@ export class PlanStore {
130
130
  return await this.enqueue(async () => action(await this.load()));
131
131
  }
132
132
 
133
+ /**
134
+ * Remove planning nodes in `seedNodeIds` (and their ancestors) that no longer have
135
+ * any remaining execution tasks or child plan nodes after a task cleanup.
136
+ *
137
+ * Never removes an unrelated empty planning node that was not in the cleaned tasks'
138
+ * own plan ancestry.
139
+ * @param {Iterable<string>} seedNodeIds - plan node ids referenced by the deleted tasks.
140
+ * @param {object[]} remainingTasks - all remaining live and archived task records.
141
+ * @returns {Promise<string[]>} removed plan node ids.
142
+ */
143
+ async deleteEmptyAncestors(seedNodeIds, remainingTasks = []) {
144
+ if (this.disposed) throw this.disposedError();
145
+ this.throwIfRefused();
146
+ const seeds = new Set();
147
+ for (const id of Array.isArray(seedNodeIds) || seedNodeIds instanceof Set ? seedNodeIds : []) {
148
+ if (typeof id === 'string' && id.trim() !== '') seeds.add(id.trim());
149
+ }
150
+ if (seeds.size === 0) return [];
151
+
152
+ return await this.enqueue(async () => {
153
+ this.throwIfRefused();
154
+ const state = await this.ensureLoaded();
155
+ const byId = new Map(state.nodes.map((node) => [node.nodeId, node]));
156
+
157
+ // Collect the candidate scope: seed nodes and their plan ancestors.
158
+ const candidateScope = new Set();
159
+ for (const seedId of seeds) {
160
+ let cur = seedId;
161
+ const seen = new Set();
162
+ while (typeof cur === 'string' && cur !== '' && !seen.has(cur)) {
163
+ seen.add(cur);
164
+ const node = byId.get(cur);
165
+ if (!node) break;
166
+ candidateScope.add(node.nodeId);
167
+ cur = node.parentNodeId ?? null;
168
+ }
169
+ }
170
+ if (candidateScope.size === 0) return [];
171
+
172
+ const referencedByTasks = new Set();
173
+ for (const task of Array.isArray(remainingTasks) ? remainingTasks : []) {
174
+ if (typeof task?.planNodeId === 'string' && task.planNodeId.trim() !== '') {
175
+ referencedByTasks.add(task.planNodeId.trim());
176
+ }
177
+ if (typeof task?.parentNodeId === 'string' && task.parentNodeId.trim() !== '') {
178
+ referencedByTasks.add(task.parentNodeId.trim());
179
+ }
180
+ }
181
+
182
+ let draft = state.nodes.map((node) => structuredClone(node));
183
+ const removedIds = [];
184
+ let changed = true;
185
+ while (changed) {
186
+ changed = false;
187
+ const parentIdsWithPlanChildren = new Set(
188
+ draft
189
+ .map((node) => node.parentNodeId)
190
+ .filter((id) => typeof id === 'string' && id !== ''),
191
+ );
192
+ const next = [];
193
+ for (const node of draft) {
194
+ if (
195
+ candidateScope.has(node.nodeId)
196
+ && !referencedByTasks.has(node.nodeId)
197
+ && !parentIdsWithPlanChildren.has(node.nodeId)
198
+ ) {
199
+ removedIds.push(node.nodeId);
200
+ changed = true;
201
+ } else {
202
+ next.push(node);
203
+ }
204
+ }
205
+ draft = next;
206
+ }
207
+
208
+ if (removedIds.length === 0) return [];
209
+ const now = Date.now();
210
+ await this.writeDocument(draft, state.lastSequence, now);
211
+ this.nodes = draft;
212
+ return removedIds;
213
+ });
214
+ }
215
+
133
216
  async get(nodeId, connectionId) {
134
217
  if (typeof nodeId !== 'string' || nodeId.trim() === '') return null;
135
218
  if (typeof connectionId !== 'string' || connectionId.trim() === '') return null;