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.
package/src/mcp/wait.js CHANGED
@@ -166,6 +166,15 @@ const SETTLED_STATE_REASONS = Object.freeze({
166
166
  interrupted: 'interrupted',
167
167
  });
168
168
 
169
+ /**
170
+ * Fields dropped from `compactTask` during an interactive pause (`permission` / `question`).
171
+ * The host only needs the task identity and live pending request/question to decide and continue;
172
+ * repeating static routing, monitoring history, and empty review persistence on every approval
173
+ * turn wastes commander context tokens. All of them remain present on `attention`, terminal
174
+ * returns, and `delegate_result`.
175
+ */
176
+ const INTERACTIVE_PAUSE_DROP = new Set(['route', 'hostAcceptance']);
177
+
169
178
  /**
170
179
  * Compact one observation's task view into what a wait answer carries.
171
180
  *
@@ -173,12 +182,16 @@ const SETTLED_STATE_REASONS = Object.freeze({
173
182
  * answer small and keeps a diff from reaching a host through the one tool that is
174
183
  * supposed to be cheap.
175
184
  * @param {object | null | undefined} task - observation `task`.
185
+ * @param {{ interactivePause?: boolean }} [options] - `interactivePause`: omit bulky monitoring
186
+ * and static routing fields on live `permission` / `question` turns.
176
187
  * @returns {object} the compact task.
177
188
  */
178
- export function compactTask(task) {
189
+ export function compactTask(task, options = {}) {
179
190
  if (task === null || typeof task !== 'object' || Array.isArray(task)) return {};
191
+ const interactivePause = options?.interactivePause === true;
180
192
  const out = {};
181
193
  for (const key of TASK_FIELDS) {
194
+ if (interactivePause && INTERACTIVE_PAUSE_DROP.has(key)) continue;
182
195
  if (task[key] !== undefined) out[key] = task[key];
183
196
  }
184
197
  // A wait NEVER carries the review note body: the conclusion's state, time and length are
@@ -203,15 +216,17 @@ export function compactTask(task) {
203
216
  : {}),
204
217
  };
205
218
  }
206
- if (task.reviewPersistence !== undefined) out.reviewPersistence = task.reviewPersistence;
207
- // Activity and self-check are small, bounded summaries the engine produced for
208
- // exactly this purpose; they are carried whole rather than re-projected here — EXCEPT
209
- // the fields a wait must never carry whatever depth they arrive at. An engine (or a
210
- // fixture) that nested a diff or execution prose inside `activity` would otherwise put
211
- // evidence on the one answer that is supposed to be cheap, so evidence keys are
212
- // dropped at any depth.
213
- if (task.activity !== undefined) out.activity = stripEvidenceFields(task.activity);
214
- if (task.selfCheck !== undefined) out.selfCheck = stripEvidenceFields(task.selfCheck);
219
+ if (!interactivePause) {
220
+ if (task.reviewPersistence !== undefined) out.reviewPersistence = task.reviewPersistence;
221
+ // Activity and self-check are small, bounded summaries the engine produced for
222
+ // exactly this purpose; they are carried whole rather than re-projected here — EXCEPT
223
+ // the fields a wait must never carry whatever depth they arrive at. An engine (or a
224
+ // fixture) that nested a diff or execution prose inside `activity` would otherwise put
225
+ // evidence on the one answer that is supposed to be cheap, so evidence keys are
226
+ // dropped at any depth.
227
+ if (task.activity !== undefined) out.activity = stripEvidenceFields(task.activity);
228
+ if (task.selfCheck !== undefined) out.selfCheck = stripEvidenceFields(task.selfCheck);
229
+ }
215
230
  return out;
216
231
  }
217
232
 
@@ -310,9 +325,11 @@ function instructionFor(reason, facts = {}) {
310
325
  + 'a real drift from the goal. Nothing was cancelled, restarted, resubmitted or re-queued, and this '
311
326
  + 'interval will not be reported again.';
312
327
  }
313
- return 'Nothing has been reported back for the configured no-progress threshold (ten minutes by default) '
314
- + 'while the task is still running. The run may be stuck. Check the current tool and idle time; cancel '
315
- + 'or follow up deliberately rather than assuming completion.';
328
+ return 'Nothing new has been returned to the host for the operator-configured delivery interval in DSH '
329
+ + 'settings (40 minutes by default; internal worker activity does not reset this clock) while the task '
330
+ + 'is still running. This is a progress check, not a verdict that the run is stuck: inspect the current '
331
+ + 'activity and elapsed state, and keep waiting on the same taskId unless you find a concrete error or '
332
+ + 'drift from the goal.';
316
333
  case 'ready':
317
334
  return 'The run ended and is awaiting host review. Read delegate_result for the diff and evidence; '
318
335
  + 'completion is not host acceptance.';
@@ -736,14 +753,16 @@ export async function waitForTask(options) {
736
753
  * @returns {object} compact answer.
737
754
  */
738
755
  function answer(reason, observation, facts = {}) {
739
- const task = compactTask(observation?.task);
756
+ const task = compactTask(observation?.task, {
757
+ interactivePause: reason === 'permission' || reason === 'question',
758
+ });
740
759
  // A resolved interruption carries the state and terminal flag its resolution decided;
741
760
  // every other answer derives them from the reason and the published task.
742
761
  const state = facts.resolved === true
743
762
  ? (facts.resolvedState ?? null)
744
763
  : resolvedTaskState(task, reason);
745
764
  // The repeated-failure diagnostic, when THAT is what the reminder was about. It is
746
- // what lets a host tell "silent for ten minutes" from "kept failing the same call",
765
+ // what lets a host tell the run progress check from "kept failing the same call",
747
766
  // which need different decisions. Only the bounded fields the engine produced travel.
748
767
  const failure = reason === 'attention' && observation?.failure !== null
749
768
  && typeof observation?.failure === 'object'
@@ -552,6 +552,7 @@ async function resolvePlacement(deps, request) {
552
552
  taskId: request?.taskId,
553
553
  connectionId: request?.connectionId,
554
554
  sourcePath: request?.sourcePath,
555
+ isolation: request?.isolation,
555
556
  presetId: request?.placementPresetId,
556
557
  });
557
558
  return placement;
@@ -417,7 +417,13 @@ export async function placeSession(deps, request) {
417
417
  const execPath = request.path;
418
418
  const continueFromTaskId = continuationOf(request?.continueFromTaskId);
419
419
 
420
- const workspace = await ensureWorkspace(workspaces, execPath, continueFromTaskId === null ? request?.title : null, request?.taskId ?? deps.taskId ?? '');
420
+ // Only a newly created dedicated worktree Workspace is named after a single task's title.
421
+ // A shared-mode run executes directly inside the project's native source Workspace, which is
422
+ // shared across runs and manual conversations and must keep the project's own Workspace name.
423
+ const workspaceTitleForCreate = continueFromTaskId === null && request?.isolation !== 'shared'
424
+ ? request?.title
425
+ : null;
426
+ const workspace = await ensureWorkspace(workspaces, execPath, workspaceTitleForCreate, request?.taskId ?? deps.taskId ?? '');
421
427
  if (workspace.namingError) deps.logger?.warn?.(`TaskBridge workspace title: ${workspace.namingError}`);
422
428
 
423
429
  if (continueFromTaskId !== null) {
@@ -935,6 +941,35 @@ export class SessionStore {
935
941
  return await run;
936
942
  }
937
943
 
944
+ /**
945
+ * Forget the threads recorded for a batch of tasks in one atomic write.
946
+ * @param {Iterable<string>} taskIds - task ids to remove.
947
+ * @returns {Promise<object[]>} the removed records.
948
+ */
949
+ async forgetMany(taskIds) {
950
+ if (this.disposed) throw new Error('the session map has been disposed');
951
+ const keys = new Set();
952
+ for (const id of Array.isArray(taskIds) || taskIds instanceof Set ? taskIds : []) {
953
+ const key = typeof id === 'string' ? id.trim() : '';
954
+ if (key !== '') keys.add(key);
955
+ }
956
+ if (keys.size === 0) return [];
957
+ const run = this.enqueue(async () => {
958
+ const base = await this.ensureLoaded();
959
+ const removed = [];
960
+ const next = [];
961
+ for (const item of base) {
962
+ if (keys.has(item.taskId)) removed.push({ ...item });
963
+ else next.push(item);
964
+ }
965
+ if (removed.length === 0) return [];
966
+ await this.writeDocument(next);
967
+ this.records = next;
968
+ return removed;
969
+ });
970
+ return await run;
971
+ }
972
+
938
973
  /**
939
974
  * Wait for queued writes and stop accepting new ones.
940
975
  * @returns {Promise<void>} resolves when settled.
@@ -25,10 +25,11 @@ export function buildWorkerPrompt(input) {
25
25
  }
26
26
  lines.push('- Do not commit, push, tag, or rewrite git history.');
27
27
  lines.push('- Do not read or print credentials, tokens, or .env contents.');
28
- lines.push('- Do not install packages from the network unless the task explicitly requires it.');
28
+ lines.push('- Do not install packages or make external network requests (`Invoke-WebRequest`, `curl`, `wget`, etc.) unless the task explicitly requires it.');
29
29
  lines.push('- Report what you changed and what you could not do. Do not claim checks you did not run.');
30
30
  lines.push('');
31
31
  lines.push('## Checks and extra permissions');
32
+ lines.push('- Always prefer native file/search/edit tools (read, grep, glob, edit, write) over shell commands (`pwsh`, `powershell`, `cmd`, `bash`, `Get-Content`, `Select-String`, `cat`, `ls`, `dir`) to inspect files, search code, or read logs. Reserve shell commands strictly for running tests, builds, typechecks, and git inspection.');
32
33
  lines.push('- Read ordinary files and logs with the normal file tools and the ordinary workspace permission. '
33
34
  + 'Do not ask for elevated access merely to read a log, and do not use a sandbox escape as a substitute for '
34
35
  + 'a file tool.');
@@ -20,7 +20,7 @@
20
20
  // rather than implied by the word "isolated".
21
21
 
22
22
  import { randomUUID } from 'node:crypto';
23
- import { lstat, mkdir, realpath } from 'node:fs/promises';
23
+ import { lstat, mkdir, readdir, realpath, rm } from 'node:fs/promises';
24
24
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
25
25
 
26
26
  import { AUDIT_CODES, AUDIT_LIMITS, AuditError, probeRepository, readRepositoryTopLevel, readStatus } from './audit.js';
@@ -632,6 +632,160 @@ export class WorktreeManager {
632
632
  return this.view(record);
633
633
  }
634
634
 
635
+ /**
636
+ * Check whether a candidate path is syntactically a direct managed child directory
637
+ * of {@link WorktreeManager#rootDir} and never the root directory or the source
638
+ * checkout itself.
639
+ * @param {unknown} workspacePath - candidate worktree path.
640
+ * @param {unknown} [sourcePath] - optional source checkout path.
641
+ * @returns {boolean} true when the path is a managed child worktree path.
642
+ */
643
+ isManagedChildPath(workspacePath, sourcePath = null) {
644
+ if (typeof workspacePath !== 'string' || workspacePath.trim() === '' || !isAbsolute(workspacePath.trim())) {
645
+ return false;
646
+ }
647
+ const resolvedRoot = resolve(this.rootDir);
648
+ const resolvedTarget = resolve(workspacePath.trim());
649
+ const rootKey = normalizeKey(resolvedRoot);
650
+ const targetKey = normalizeKey(resolvedTarget);
651
+ if (targetKey === rootKey) return false;
652
+ if (typeof sourcePath === 'string' && sourcePath.trim() !== '' && isAbsolute(sourcePath.trim())) {
653
+ if (targetKey === normalizeKey(resolve(sourcePath.trim()))) return false;
654
+ }
655
+ if (normalizeKey(dirname(resolvedTarget)) !== rootKey) return false;
656
+ const folderName = basename(resolvedTarget);
657
+ return /^[A-Za-z0-9._-]+-[A-Za-z0-9]{1,12}$/.test(folderName);
658
+ }
659
+
660
+ /**
661
+ * Safely remove one plugin-managed worktree directory for a cleaned isolated task,
662
+ * including after a host restart when the in-memory tree map no longer holds it.
663
+ *
664
+ * Strictly refuses any path that is not a direct child of {@link WorktreeManager#rootDir},
665
+ * any path equal to `sourcePath`, or any symbolic link at the target location.
666
+ * @param {{ taskId?: string, sourcePath?: string | null, workspacePath?: string | null }} request
667
+ * @returns {Promise<{ removed: boolean, workspacePath: string | null, reason?: string }>}
668
+ */
669
+ async removeManagedTree(request = {}) {
670
+ const rawTarget = typeof request?.workspacePath === 'string' ? request.workspacePath.trim() : '';
671
+ const rawSource = typeof request?.sourcePath === 'string' && request.sourcePath.trim() !== ''
672
+ ? request.sourcePath.trim()
673
+ : null;
674
+ if (!this.isManagedChildPath(rawTarget, rawSource)) {
675
+ return { removed: false, workspacePath: null, reason: 'not-managed-worktree' };
676
+ }
677
+ const resolvedTarget = resolve(rawTarget);
678
+ const targetKey = normalizeKey(resolvedTarget);
679
+ const tracked = this.trees.get(targetKey) ?? null;
680
+ if (tracked !== null && tracked.state === WORKTREE_STATES.active) {
681
+ return { removed: false, workspacePath: resolvedTarget, reason: 'tree-active' };
682
+ }
683
+
684
+ const existedOnDisk = await pathExists(resolvedTarget).catch(() => false);
685
+ if (existedOnDisk) {
686
+ const statInfo = await lstat(resolvedTarget).catch(() => null);
687
+ if (statInfo === null || statInfo.isSymbolicLink() || !statInfo.isDirectory()) {
688
+ return { removed: false, workspacePath: resolvedTarget, reason: 'not-regular-directory' };
689
+ }
690
+ const [realRoot, realParent] = await Promise.all([
691
+ realpath(this.rootDir).catch(() => resolve(this.rootDir)),
692
+ realpath(dirname(resolvedTarget)).catch(() => null),
693
+ ]);
694
+ if (realParent === null || normalizeKey(realParent) !== normalizeKey(realRoot)) {
695
+ return { removed: false, workspacePath: resolvedTarget, reason: 'parent-mismatch' };
696
+ }
697
+ }
698
+
699
+ const effectiveSource = tracked?.sourcePath ?? (rawSource !== null && isAbsolute(rawSource) && !rawSource.includes('***') ? resolve(rawSource) : null);
700
+ let disposedViaGit = false;
701
+ if (tracked !== null && tracked.state !== WORKTREE_STATES.disposed) {
702
+ try {
703
+ await this.dispose(resolvedTarget, { reviewed: true });
704
+ disposedViaGit = true;
705
+ } catch {
706
+ tracked.state = WORKTREE_STATES.disposed;
707
+ }
708
+ } else if (effectiveSource !== null) {
709
+ try {
710
+ await this.deps.runGit(effectiveSource, ['worktree', 'remove', '--force', resolvedTarget]);
711
+ disposedViaGit = true;
712
+ } catch {
713
+ // Fallback to direct directory removal inside rootDir below.
714
+ }
715
+ try {
716
+ await this.deps.runGit(effectiveSource, ['worktree', 'prune']);
717
+ } catch {
718
+ // Best-effort git worktree administrative prune.
719
+ }
720
+ }
721
+
722
+ if (await pathExists(resolvedTarget).catch(() => false)) {
723
+ await rm(resolvedTarget, { recursive: true, force: true }).catch(() => {});
724
+ if (effectiveSource !== null) {
725
+ await this.deps.runGit(effectiveSource, ['worktree', 'prune']).catch(() => {});
726
+ }
727
+ }
728
+
729
+ const stillExists = await pathExists(resolvedTarget).catch(() => false);
730
+ if (stillExists) {
731
+ return { removed: false, workspacePath: resolvedTarget, reason: 'remove-failed' };
732
+ }
733
+ if (tracked !== null) {
734
+ tracked.state = WORKTREE_STATES.disposed;
735
+ }
736
+ if (!existedOnDisk && !disposedViaGit) {
737
+ return { removed: false, workspacePath: resolvedTarget, reason: 'already-absent' };
738
+ }
739
+ return { removed: true, workspacePath: resolvedTarget };
740
+ }
741
+
742
+ /**
743
+ * Sweep orphan managed worktree directories under {@link WorktreeManager#rootDir}
744
+ * that are no longer referenced by any live or retained historical task.
745
+ * @param {{ activePaths?: string[], sourcePaths?: string[] }} [options]
746
+ * @returns {Promise<{ removedWorktreePaths: string[] }>}
747
+ */
748
+ async sweepOrphanTrees(options = {}) {
749
+ const activeKeys = new Set();
750
+ for (const candidate of Array.isArray(options?.activePaths) ? options.activePaths : []) {
751
+ if (typeof candidate === 'string' && candidate.trim() !== '' && isAbsolute(candidate.trim())) {
752
+ activeKeys.add(normalizeKey(resolve(candidate.trim())));
753
+ }
754
+ }
755
+ for (const [key, record] of this.trees.entries()) {
756
+ if (record.state === WORKTREE_STATES.active) activeKeys.add(key);
757
+ }
758
+
759
+ let entries = [];
760
+ try {
761
+ entries = await readdir(this.rootDir, { withFileTypes: true });
762
+ } catch (error) {
763
+ if (error?.code === 'ENOENT') return { removedWorktreePaths: [] };
764
+ throw error;
765
+ }
766
+
767
+ const removedWorktreePaths = [];
768
+ for (const entry of entries) {
769
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
770
+ if (!/^[A-Za-z0-9._-]+-[A-Za-z0-9]{1,12}$/.test(entry.name)) continue;
771
+ const fullPath = resolve(join(this.rootDir, entry.name));
772
+ if (activeKeys.has(normalizeKey(fullPath))) continue;
773
+ const outcome = await this.removeManagedTree({ workspacePath: fullPath });
774
+ if (outcome.removed) removedWorktreePaths.push(fullPath);
775
+ }
776
+
777
+ const uniqueSources = new Set(
778
+ (Array.isArray(options?.sourcePaths) ? options.sourcePaths : [])
779
+ .filter((p) => typeof p === 'string' && p.trim() !== '' && isAbsolute(p.trim()) && !p.includes('***'))
780
+ .map((p) => resolve(p.trim())),
781
+ );
782
+ for (const source of uniqueSources) {
783
+ await this.deps.runGit(source, ['worktree', 'prune']).catch(() => {});
784
+ }
785
+
786
+ return { removedWorktreePaths };
787
+ }
788
+
635
789
  /**
636
790
  * Resolve a managed record or refuse.
637
791
  * @param {string} workspacePath - tree path.