dsh-taskbridge 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +41 -41
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/codex/dsh-taskbridge.toml +140 -71
  5. package/docs/INTRODUCTION.md +44 -22
  6. package/docs/INTRODUCTION.zh.md +32 -26
  7. package/docs/codex-integration.md +90 -10
  8. package/docs/contracts-stage-b.md +4 -4
  9. package/docs/conversation-placement.md +25 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/releases/1.7.0.zh.md +11 -0
  12. package/docs/runtime-compatibility.md +4 -11
  13. package/docs/silent-wait.md +69 -31
  14. package/docs/taskbridge-upgrade.md +1 -1
  15. package/docs/worker-permissions.md +4 -14
  16. package/docs/workspace-grouping.md +126 -0
  17. package/lib/client.d.ts +365 -3
  18. package/lib/client.js +260 -5
  19. package/locale/en.json +1 -1
  20. package/locale/zh.json +1 -1
  21. package/package.json +7 -19
  22. package/src/client/api.js +550 -90
  23. package/src/client/index.jsx +699 -307
  24. package/src/client/sidebar.jsx +6 -5
  25. package/src/client/styles.js +251 -0
  26. package/src/client/task-cleanup.js +304 -0
  27. package/src/client/task-records-table.jsx +217 -0
  28. package/src/client/task-view.js +226 -10
  29. package/src/client/workspace-groups.js +482 -0
  30. package/src/client/workspaces-browser.jsx +770 -0
  31. package/src/codex/agent-ownership.js +270 -0
  32. package/src/codex/installer.js +525 -35
  33. package/src/codex/seam.js +5 -0
  34. package/src/config/defaults.js +63 -17
  35. package/src/config/settings.js +60 -62
  36. package/src/config/validate.js +126 -71
  37. package/src/http/respond.js +8 -0
  38. package/src/http/user-plane.js +197 -2
  39. package/src/index.js +50 -42
  40. package/src/jobs/activity.js +968 -78
  41. package/src/jobs/engine.js +784 -230
  42. package/src/jobs/history.js +188 -12
  43. package/src/jobs/plan-store.js +5 -0
  44. package/src/jobs/record-cleanup.js +196 -0
  45. package/src/jobs/task-tree.js +5 -3
  46. package/src/jobs/title.js +129 -12
  47. package/src/mcp/server.js +16 -8
  48. package/src/mcp/wait.js +64 -5
  49. package/src/runtime/agent-runner.js +53 -15
  50. package/src/runtime/worker-prompt.js +53 -0
  51. package/src/workspace/locks.js +288 -167
  52. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  53. package/docs/releases/1.4.0.zh.md +0 -54
  54. package/docs/releases/1.4.1.zh.md +0 -59
  55. package/docs/releases/1.4.2.zh.md +0 -23
  56. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  57. package/docs/releases/1.5.0.zh.md +0 -51
  58. package/docs/releases/1.5.1.zh.md +0 -70
  59. package/docs/releases/1.5.2.zh.md +0 -30
  60. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  61. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  62. package/docs/releases/1.5.3.zh.md +0 -33
  63. package/docs/releases/1.5.4.zh.md +0 -25
  64. package/src/review/preset.js +0 -868
  65. package/src/review/prompts.js +0 -145
  66. package/src/review/reviewer.js +0 -933
@@ -20,6 +20,10 @@
20
20
  // `hostAcceptance.completionSummary` enforce <= 2000 code points on writes (never cut by fitting)
21
21
  // and truncate with markers on loads of older/external documents.
22
22
  //
23
+ // Removal is `deleteMany` only: one atomic, bounded, all-or-nothing write that the
24
+ // execution record view drives. A live record is never removed, a refused batch
25
+ // writes nothing, and a failed write leaves the stored copy visible.
26
+ //
23
27
  // On load, `pending`/`running` records become `interrupted` with
24
28
  // `error.code = JOB_INTERRUPTED_RESTART`. They are never resubmitted, and the
25
29
  // authorization that once covered them is not restored.
@@ -91,8 +95,19 @@ export const HISTORY_CODES = Object.freeze({
91
95
  limitExceeded: 'HISTORY_LIMIT_EXCEEDED',
92
96
  writeFailed: 'HISTORY_WRITE_FAILED',
93
97
  disposed: 'HISTORY_DISPOSED',
98
+ // A batch delete that cannot be honoured as one unit. Nothing is written.
99
+ deleteInvalid: 'HISTORY_DELETE_INVALID',
94
100
  });
95
101
 
102
+ /**
103
+ * Upper bound on how many records one batch delete may remove.
104
+ *
105
+ * It matches the per-entry list bound of the projection, so a batch can never be
106
+ * larger than a document's own record list; the API also caps the number of CHAINS
107
+ * per request, so the composition cannot grow with a caller's list.
108
+ */
109
+ export const HISTORY_DELETE_MAX_TASKS = 500;
110
+
96
111
  /** Windows rename races are transient: retry them briefly before refusing. */
97
112
  const WINDOWS_TRANSIENT_RENAME = new Set(['EACCES', 'EBUSY', 'EPERM']);
98
113
 
@@ -411,6 +426,74 @@ export class HistoryStore {
411
426
  return await run;
412
427
  }
413
428
 
429
+ /**
430
+ * Atomically delete ONE batch of TERMINAL stored records.
431
+ *
432
+ * This is the only removal path a caller may use, and it is deliberately narrow:
433
+ *
434
+ * * **All or nothing.** Every id must name a stored record that is terminal in
435
+ * the document as read INSIDE the write queue. A missing id, an id whose stored
436
+ * state is still `pending`/`running`, and a duplicate id refuse the WHOLE batch
437
+ * with `HISTORY_DELETE_INVALID` and write nothing. There is no partial success
438
+ * to report as a success.
439
+ * The write is serialized with saves and updates. The optional check runs on
440
+ * the latest rows in the queue. The store only publishes the new list after
441
+ * the temporary file replaces the old document.
442
+ *
443
+ * Deleting a history record removes the stored evidence only. It does not touch a
444
+ * DSH Workspace, a Session, a worktree, a source file or any other document.
445
+ * @param {string[]} taskIds - exact stored ids to remove.
446
+ * @param {object} [options] - synchronous `beforeWrite(rows)` and `afterWrite(ids)` hooks.
447
+ * @returns {Promise<{ deletedTaskIds: string[], remaining: number }>} outcome.
448
+ * @throws {HistoryError} `HISTORY_DELETE_INVALID` for a refused batch (nothing written),
449
+ * `HISTORY_WRITE_FAILED` when the document could not be written (nothing removed),
450
+ * or the error `beforeWrite` threw.
451
+ */
452
+ async deleteMany(taskIds, options = {}) {
453
+ if (this.disposed) throw this.disposedError();
454
+ if (this.refusal !== null) this.throwIfRefused();
455
+ const ids = requireDeleteIds(taskIds);
456
+ const beforeWrite = typeof options.beforeWrite === 'function' ? options.beforeWrite : null;
457
+ const run = this.enqueue(async () => {
458
+ this.throwIfRefused();
459
+ const base = await this.ensureLoaded();
460
+ // The re-check sees the freshest rows and the caller's own in-flight facts, so a
461
+ // batch that became unsafe while it waited is refused before anything is written.
462
+ if (beforeWrite !== null) beforeWrite(base.slice());
463
+ const byId = new Map();
464
+ for (const job of base) byId.set(job.taskId, job);
465
+ const missing = [];
466
+ const live = [];
467
+ for (const taskId of ids) {
468
+ const row = byId.get(taskId);
469
+ if (row === undefined) missing.push(taskId);
470
+ else if (!isTerminal(row.state) || row.state === 'interrupted') live.push(taskId);
471
+ }
472
+ if (missing.length > 0 || live.length > 0) {
473
+ // The ids are echoed back because the caller sent them; nothing else is.
474
+ // A refusal never rewrites the document, so the caller can re-read and retry.
475
+ throw new HistoryError(
476
+ HISTORY_CODES.deleteInvalid,
477
+ 'a history batch can only remove stored finished records that still exist',
478
+ {
479
+ missing,
480
+ live,
481
+ requested: ids.length,
482
+ limit: HISTORY_DELETE_MAX_TASKS,
483
+ },
484
+ );
485
+ }
486
+ const wanted = new Set(ids);
487
+ const draft = base.filter((job) => !wanted.has(job.taskId)).map((job) => structuredClone(job));
488
+ const now = Date.now();
489
+ await this.writeDocument(draft, now);
490
+ this.jobs = draft;
491
+ options.afterWrite?.(ids);
492
+ return { deletedTaskIds: [...ids], remaining: draft.length };
493
+ });
494
+ return await run;
495
+ }
496
+
414
497
  /**
415
498
  * Wait for the in-flight read and every queued write to settle.
416
499
  * @returns {Promise<void>} resolves when the document is consistent.
@@ -732,6 +815,15 @@ function projectView(view, maxEntryBytes, options = {}) {
732
815
  // dispatcher made no choice, so a restored record can tell "not asked" from "asked",
733
816
  // and "applied" from "asked but unapplied".
734
817
  agentTeams: typeof view.agentTeams === 'boolean' ? view.agentTeams : null,
818
+ // WHERE that decision came from (`request` / `continuation` / `settings-default`), or
819
+ // ABSENT when there is nothing to say. Closed vocabulary, so a restored record can
820
+ // never present the operator's default as something the dispatcher asked for.
821
+ //
822
+ // Omitted rather than written as `null`, for the same reason `title` is: a stored
823
+ // record that predates the field (or never recorded a decision) must reload byte for
824
+ // byte. Writing `null` would make every such load look like a change and rewrite the
825
+ // document just to add a key that means "unknown" anyway.
826
+ ...(teamOriginView(view.agentTeamsOrigin) === null ? {} : { agentTeamsOrigin: teamOriginView(view.agentTeamsOrigin) }),
735
827
  team: teamView(view.team, ctx),
736
828
  // A completed job is not an accepted one. This is fixed, never copied.
737
829
  selfApproved: false,
@@ -796,33 +888,46 @@ function markInterrupted(entry, now) {
796
888
  function effectiveView(value) {
797
889
  if (!isPlainObject(value)) return null;
798
890
  const worker = isPlainObject(value.worker) ? value.worker : {};
799
- const review = isPlainObject(value.review) ? value.review : {};
891
+ const review = isPlainObject(value.review) ? value.review : null;
800
892
  const provenance = isPlainObject(value.provenance) ? value.provenance : {};
801
893
  return {
802
894
  worker: {
803
895
  providerId: label(worker.providerId),
804
896
  model: label(worker.model),
805
897
  reasoningEffort: label(worker.reasoningEffort),
898
+ // The legacy stored value, kept verbatim so a stored record still says what the
899
+ // document it ran under contained. It is NOT what bounded the run.
806
900
  timeoutSeconds: count(worker.timeoutSeconds),
901
+ // What the run's budget actually was: `null` means "no total execution
902
+ // deadline" (the default), a number means an explicit per-job cap. Stored as
903
+ // its own field, because reading the legacy value as the budget would state a
904
+ // limit the engine did not apply.
905
+ executionTimeoutSeconds: Number.isFinite(worker.executionTimeoutSeconds)
906
+ ? count(worker.executionTimeoutSeconds)
907
+ : null,
807
908
  maxParallelism: count(worker.maxParallelism),
808
909
  isolation: knownValue(worker.isolation, ['worktree', 'shared']),
809
910
  },
810
- review: {
811
- enabled: review.enabled === true,
812
- providerId: label(review.providerId),
813
- model: label(review.model),
814
- reasoningEffort: label(review.reasoningEffort),
815
- },
911
+ ...(review === null ? {} : {
912
+ review: {
913
+ enabled: review.enabled === true,
914
+ providerId: label(review.providerId),
915
+ model: label(review.model),
916
+ reasoningEffort: label(review.reasoningEffort),
917
+ },
918
+ }),
816
919
  // The conversation policy the task was frozen with (a rule, not a stored
817
920
  // setting) plus, in `value.conversation` below, what the run actually did. No
818
921
  // session id is stored here, so history is not a way back into a conversation.
819
922
  conversation: isPlainObject(value.conversation)
820
923
  ? { policy: label(value.conversation.policy) }
821
924
  : null,
822
- // The silence thresholds this task froze at admission. Stored because they are
823
- // the only way a stored activity block can be interpreted: "idle for 12 minutes"
824
- // means something different under a 10-minute attention threshold than under a
825
- // two-hour one, and the live settings may have changed since.
925
+ // The no-progress thresholds this task froze at admission. Stored because they are
926
+ // the only way a stored activity block can be interpreted: "no progress for 12
927
+ // minutes" means something different under a 10-minute self-check threshold than
928
+ // under a two-hour one, and the live settings may have changed since. `0` is a
929
+ // stored decision ("this reminder is off") and is preserved as such, never
930
+ // re-defaulted.
826
931
  monitoring: isPlainObject(value.monitoring)
827
932
  ? {
828
933
  selfCheckSeconds: count(value.monitoring.selfCheckSeconds),
@@ -992,7 +1097,7 @@ function usageView(value) {
992
1097
  return Object.keys(out).length === 0 ? null : out;
993
1098
  }
994
1099
 
995
- /** @returns {object | null} bounded additional-review outcome. */
1100
+ /** @returns {object | null} bounded result from a legacy model review. */
996
1101
  function reviewView(value, ctx) {
997
1102
  if (!isPlainObject(value)) return null;
998
1103
  return {
@@ -1216,6 +1321,21 @@ function teamView(value, ctx) {
1216
1321
  };
1217
1322
  }
1218
1323
 
1324
+ /**
1325
+ * Project the ORIGIN of a task's frozen Agent Teams decision for storage.
1326
+ *
1327
+ * A closed vocabulary of three words, or `null`. Anything else stored in a document
1328
+ * (a hand edit, a field written by a later build) reads back as `null` instead of
1329
+ * being echoed, so no reader can be shown a fourth "origin" this build does not
1330
+ * understand. `null` is also what a record written before this field existed
1331
+ * restores as, which is the honest answer.
1332
+ * @param {unknown} value - task `agentTeamsOrigin`.
1333
+ * @returns {'request' | 'continuation' | 'settings-default' | null} the stored origin.
1334
+ */
1335
+ function teamOriginView(value) {
1336
+ return value === 'request' || value === 'continuation' || value === 'settings-default' ? value : null;
1337
+ }
1338
+
1219
1339
  /** @param {object} value - activity summary view. @returns {object|null} bounded activity view. */
1220
1340
  function activityView(value) {
1221
1341
  if (!isPlainObject(value)) return null;
@@ -1843,6 +1963,62 @@ function isTerminal(state) {
1843
1963
  return KNOWN_STATES.has(state) && !LIVE_STATES.has(state);
1844
1964
  }
1845
1965
 
1966
+ /**
1967
+ * Validate the id list of one batch delete, without touching any document.
1968
+ *
1969
+ * The list is a SET of exact ids: a duplicate, a blank id, a non-string, an empty
1970
+ * list or one above the bound is the caller's mistake and is refused whole. Each id
1971
+ * is TRIMMED exactly like `projectView` trims a stored `taskId`, so the comparison in
1972
+ * `deleteMany` is against the same canonical form that was written — nothing else is
1973
+ * coerced, so an id this store could not have minted can never match by accident.
1974
+ * @param {unknown} taskIds - caller-supplied ids.
1975
+ * @returns {string[]} the trimmed ids, in the caller's order.
1976
+ * @throws {HistoryError} `HISTORY_DELETE_INVALID`.
1977
+ */
1978
+ function requireDeleteIds(taskIds) {
1979
+ if (!Array.isArray(taskIds)) {
1980
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'a history batch delete needs a list of task ids', {
1981
+ field: 'taskIds',
1982
+ limit: HISTORY_DELETE_MAX_TASKS,
1983
+ });
1984
+ }
1985
+ if (taskIds.length === 0) {
1986
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'a history batch delete needs at least one task id', {
1987
+ field: 'taskIds',
1988
+ count: 0,
1989
+ });
1990
+ }
1991
+ if (taskIds.length > HISTORY_DELETE_MAX_TASKS) {
1992
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'a history batch delete exceeds the accepted bound', {
1993
+ field: 'taskIds',
1994
+ count: taskIds.length,
1995
+ limit: HISTORY_DELETE_MAX_TASKS,
1996
+ });
1997
+ }
1998
+ const seen = new Set();
1999
+ for (const value of taskIds) {
2000
+ if (typeof value !== 'string') {
2001
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'every task id in a batch delete must be a bounded task id', {
2002
+ field: 'taskIds',
2003
+ });
2004
+ }
2005
+ const id = value.trim();
2006
+ if (id === '' || id.length > MAX_LABEL_CHARS) {
2007
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'every task id in a batch delete must be a bounded task id', {
2008
+ field: 'taskIds',
2009
+ });
2010
+ }
2011
+ if (seen.has(id)) {
2012
+ throw new HistoryError(HISTORY_CODES.deleteInvalid, 'a batch delete may not repeat a task id', {
2013
+ field: 'taskIds',
2014
+ taskId: id,
2015
+ });
2016
+ }
2017
+ seen.add(id);
2018
+ }
2019
+ return [...seen];
2020
+ }
2021
+
1846
2022
  /**
1847
2023
  * Total order used on disk: creation time, then id, so serialization is stable.
1848
2024
  * @param {object} a - first entry.
@@ -125,6 +125,11 @@ export class PlanStore {
125
125
  return filtered.map((node) => structuredClone(node));
126
126
  }
127
127
 
128
+ // Let cleanup validate relationships while queued plan mutations are held.
129
+ async withStableNodes(action) {
130
+ return await this.enqueue(async () => action(await this.load()));
131
+ }
132
+
128
133
  async get(nodeId, connectionId) {
129
134
  if (typeof nodeId !== 'string' || nodeId.trim() === '') return null;
130
135
  if (typeof connectionId !== 'string' || connectionId.trim() === '') return null;
@@ -0,0 +1,196 @@
1
+ import { buildTaskTree } from './task-tree.js';
2
+ import { HISTORY_CODES, HISTORY_DELETE_MAX_TASKS } from './history.js';
3
+
4
+ export const MAX_CLEANUP_CHAINS = 100;
5
+ const FINISHED = new Set(['awaiting-host-review', 'failed', 'cancelled']);
6
+
7
+ export const CLEANUP_CODES = Object.freeze({
8
+ invalid: 'CLEANUP_INVALID',
9
+ notFound: 'CLEANUP_CHAIN_NOT_FOUND',
10
+ stale: 'CLEANUP_STALE',
11
+ live: 'CLEANUP_CHAIN_LIVE',
12
+ notDurable: 'CLEANUP_NOT_DURABLE',
13
+ nextRound: 'CLEANUP_NEXT_ROUND',
14
+ planChildren: 'CLEANUP_PLAN_CHILDREN',
15
+ hierarchyChildren: 'CLEANUP_HIERARCHY_CHILDREN',
16
+ reviewWrite: 'CLEANUP_REVIEW_WRITE',
17
+ unavailable: 'CLEANUP_UNAVAILABLE',
18
+ failed: 'CLEANUP_FAILED',
19
+ });
20
+
21
+ class CleanupError extends Error {
22
+ constructor(code, message, details = {}) {
23
+ super(message);
24
+ this.name = 'CleanupError';
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ }
29
+
30
+ function invalid(message, details) {
31
+ throw new CleanupError(CLEANUP_CODES.invalid, message, details);
32
+ }
33
+
34
+ function isObject(value) {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
36
+ }
37
+
38
+ function isId(value) {
39
+ return typeof value === 'string' && value.length > 0 && value.length <= 256 && value.trim() === value;
40
+ }
41
+
42
+ export function validateCleanupRequest(body) {
43
+ if (!isObject(body) || Object.keys(body).some((key) => key !== 'chains' && key !== 'confirm')) {
44
+ invalid('expected only chains and explicit confirmation');
45
+ }
46
+ if (body.confirm !== true) invalid('cleanup requires explicit confirmation', { field: 'confirm' });
47
+ if (!Array.isArray(body.chains) || body.chains.length === 0 || body.chains.length > MAX_CLEANUP_CHAINS) {
48
+ invalid('select a bounded list of execution chains', { field: 'chains', limit: MAX_CLEANUP_CHAINS });
49
+ }
50
+ const chainIds = new Set();
51
+ const taskIds = new Set();
52
+ const chains = body.chains.map((chain, index) => {
53
+ if (!isObject(chain) || Object.keys(chain).some((key) => key !== 'chainId' && key !== 'taskIds') || !isId(chain.chainId)) {
54
+ invalid('expected a chain id and its exact rounds', { index });
55
+ }
56
+ if (chainIds.has(chain.chainId)) invalid('duplicate chain id', { index });
57
+ chainIds.add(chain.chainId);
58
+ if (!Array.isArray(chain.taskIds) || chain.taskIds.length === 0) invalid('select the complete chain', { index });
59
+ for (const id of chain.taskIds) {
60
+ if (!isId(id) || taskIds.has(id)) invalid('expected unique task ids', { index });
61
+ taskIds.add(id);
62
+ if (taskIds.size > HISTORY_DELETE_MAX_TASKS) invalid('too many rounds for one batch', { limit: HISTORY_DELETE_MAX_TASKS });
63
+ }
64
+ return { chainId: chain.chainId, taskIds: [...chain.taskIds] };
65
+ });
66
+ return { chains };
67
+ }
68
+
69
+ function planStore(deps) {
70
+ return deps.plans ?? deps.engine?.plans ?? null;
71
+ }
72
+
73
+ function collectChains(node, byChain) {
74
+ for (const chain of node.chain ? [node.chain] : node.executions ?? []) byChain.set(chain.chainId, chain);
75
+ for (const child of node.children) collectChains(child, byChain);
76
+ }
77
+
78
+ function cleanupContext(engine, archived, plans) {
79
+ const live = engine?.list?.() ?? [];
80
+ const liveById = new Map(live.map((row) => [row.taskId, row]));
81
+ const archivedById = new Map(archived.map((row) => [row.taskId, row]));
82
+ const tasks = new Map([...archivedById, ...liveById]);
83
+ const continuations = new Map();
84
+ const taskChildren = new Map();
85
+ const planParents = new Set(plans.map((node) => node.parentNodeId));
86
+ const remember = (map, parent, child) => {
87
+ if (typeof parent !== 'string' || parent === '' || parent === child) return;
88
+ if (!map.has(parent)) map.set(parent, new Set());
89
+ map.get(parent).add(child);
90
+ };
91
+ for (const row of [...archived, ...live]) {
92
+ remember(continuations, row.continueFromTaskId, row.taskId);
93
+ remember(taskChildren, row.parentNodeId, row.taskId);
94
+ remember(taskChildren, row.planNodeId, row.taskId);
95
+ }
96
+ const tree = buildTaskTree({ planNodes: plans, tasks: [...tasks.values()] });
97
+ const byChain = new Map();
98
+ for (const root of tree.roots) collectChains(root, byChain);
99
+ return { byChain, liveById, archivedById, continuations, taskChildren, planParents, engine };
100
+ }
101
+
102
+ function blockersFor(chain, context) {
103
+ const blockers = new Set();
104
+ const members = new Set(chain.taskIds);
105
+ for (const taskId of members) {
106
+ const live = context.liveById.get(taskId);
107
+ const archived = context.archivedById.get(taskId);
108
+ if ((live && !FINISHED.has(live.state)) || (archived && !FINISHED.has(archived.state))) {
109
+ blockers.add(CLEANUP_CODES.live);
110
+ } else if (!archived || (live && !context.engine.isTaskSettledForCleanup?.(taskId))) {
111
+ blockers.add(CLEANUP_CODES.notDurable);
112
+ }
113
+ if (context.engine?.reviewWriteDone?.(taskId)) blockers.add(CLEANUP_CODES.reviewWrite);
114
+ for (const child of context.continuations.get(taskId) ?? []) {
115
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.nextRound);
116
+ }
117
+ for (const child of context.taskChildren.get(taskId) ?? []) {
118
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
119
+ }
120
+ if (context.planParents.has(taskId)) blockers.add(CLEANUP_CODES.planChildren);
121
+ }
122
+ return [...blockers];
123
+ }
124
+
125
+ export async function cleanupOverview(deps) {
126
+ const archived = await deps.history.load();
127
+ const plans = await planStore(deps)?.load() ?? [];
128
+ const context = cleanupContext(deps.engine, archived, plans);
129
+ const chains = [...context.byChain.values()].map((chain) => {
130
+ const blockers = blockersFor(chain, context);
131
+ return { chainId: chain.chainId, taskIds: [...chain.taskIds], eligible: blockers.length === 0, blockers };
132
+ });
133
+ return { chains };
134
+ }
135
+
136
+ function checkBatch(chains, context) {
137
+ const refused = [];
138
+ for (const { chainId, taskIds } of chains) {
139
+ const chain = context.byChain.get(chainId);
140
+ let blockers;
141
+ if (!chain) blockers = [CLEANUP_CODES.notFound];
142
+ else if (chain.taskIds.length !== taskIds.length || chain.taskIds.some((id, i) => id !== taskIds[i])) {
143
+ blockers = [CLEANUP_CODES.stale];
144
+ } else blockers = blockersFor(chain, context);
145
+ if (blockers.length) refused.push({ chainId, code: blockers[0], blockers });
146
+ }
147
+ if (refused.length) {
148
+ throw new CleanupError(refused[0].code, 'the selected chains cannot be removed as one batch', {
149
+ chains: refused, reason: refused[0].code, deleted: 0,
150
+ });
151
+ }
152
+ }
153
+
154
+ export async function runCleanup(deps, body) {
155
+ const { chains } = validateCleanupRequest(body);
156
+ const store = deps.history;
157
+ const plans = planStore(deps);
158
+ const engine = deps.engine;
159
+ if (typeof store?.deleteMany !== 'function' || (plans && typeof plans.withStableNodes !== 'function')) {
160
+ throw new CleanupError(CLEANUP_CODES.unavailable, 'task record cleanup is unavailable');
161
+ }
162
+ const ids = chains.flatMap((chain) => chain.taskIds);
163
+ const deleteRecords = async (planNodes) => {
164
+ let release;
165
+ try {
166
+ return await store.deleteMany(ids, {
167
+ beforeWrite(archived) {
168
+ // Read the latest engine state inside the history queue. No asynchronous
169
+ // work may run between checking relationships and reserving these ids.
170
+ checkBatch(chains, cleanupContext(engine, archived, planNodes));
171
+ release = engine?.reserveCleanupIds(ids);
172
+ },
173
+ afterWrite(deletedIds) {
174
+ engine?.forgetCleanedRecords(deletedIds);
175
+ },
176
+ });
177
+ } finally {
178
+ release?.();
179
+ }
180
+ };
181
+ let result;
182
+ try {
183
+ result = plans ? await plans.withStableNodes(deleteRecords) : await deleteRecords([]);
184
+ } catch (error) {
185
+ if (error instanceof CleanupError) throw error;
186
+ const code = error?.code === HISTORY_CODES.deleteInvalid ? CLEANUP_CODES.stale
187
+ : error?.code === HISTORY_CODES.writeFailed ? CLEANUP_CODES.failed : CLEANUP_CODES.unavailable;
188
+ throw new CleanupError(code, 'the task records could not be removed', { deleted: 0 });
189
+ }
190
+ return {
191
+ chains: chains.length,
192
+ tasks: result.deletedTaskIds.length,
193
+ ...result,
194
+ retained: { sessions: true, workspaces: true, worktrees: true, sourceFiles: true, plans: true },
195
+ };
196
+ }
@@ -157,6 +157,7 @@ export function groupContinuationChains(tasks = []) {
157
157
  }
158
158
  }
159
159
 
160
+ // Keep the original task name when a continuation uses a different round title.
160
161
  const recordedTitle = firstNonEmptyTitle(rounds);
161
162
  const titleMissing = recordedTitle === null;
162
163
  const displayTitle = titleMissing
@@ -711,8 +712,8 @@ function trailingSegments(pathValue, count) {
711
712
  }
712
713
 
713
714
  function firstNonEmptyTitle(rounds) {
714
- for (let i = rounds.length - 1; i >= 0; i -= 1) {
715
- const t = rounds[i]?.title;
715
+ for (const round of rounds) {
716
+ const t = round.title;
716
717
  if (typeof t === 'string' && t.trim() !== '') return t.trim();
717
718
  }
718
719
  return null;
@@ -729,7 +730,8 @@ function firstNonEmptyDescription(rounds, field) {
729
730
  function maxTimestampOfRounds(rounds) {
730
731
  let max = 0;
731
732
  for (const r of rounds) {
732
- for (const candidate of [r.endedAt, r.startedAt, r.createdAt, r.hostAcceptance?.acceptedAt, r.hostAcceptance?.decidedAt]) {
733
+ for (const candidate of [r.activity?.lastActivityAt, r.endedAt, r.startedAt, r.createdAt,
734
+ r.hostAcceptance?.acceptedAt, r.hostAcceptance?.decidedAt]) {
733
735
  const num = finiteNumber(candidate);
734
736
  if (num !== null && num > max) max = num;
735
737
  }
package/src/jobs/title.js CHANGED
@@ -1,17 +1,134 @@
1
1
  import { redactText } from '../config/redact.js';
2
2
 
3
- /** A display title is task content, never a directory name or routing instruction. */
4
- export function taskTitle(title, prompt = '') {
5
- const lines = String(prompt).split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
6
- const goal = lines.findIndex(line => /^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)(?:\s*[::]|\s*$)/iu.test(line));
7
- let text = typeof title === 'string' ? title.trim() : '';
8
- if (!text && goal >= 0) {
9
- text = lines[goal].replace(/^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)\s*[::]?\s*/iu, '') || lines[goal + 1] || '';
3
+ const GOAL = /^(?:目标|任务目标|工作内容|任务|goal|objective|task)(?:\s*[::]\s*|$)(.*)$/iu;
4
+ const ROLE = /^(?:you are\b|you're\b|you will\b|you must\b|act as\b|your (?:role|task|job|objective)\b|as an?\b|你是|您是一名|你负责|你需要|你的(?:角色|任务|职责)|请作为|作为一)/iu;
5
+ const RULE = /^(?:instructions?|execution task rules?|task rules?|rules?|guidelines?|constraints?|requirements?|role|persona|system|context|background|overview|summary|steps?|procedure|执行任务规则|执行规则|任务规则|规则|约束|限制|要求|角色|身份|系统|背景|上下文|说明|验收|范围|步骤|流程|概述)(?:\s*[::].*|\s*)$/iu;
6
+ const RESTRICTION = /^(?:不要|不准|不得|禁止|必须|务必|请勿|别|do not\b|don't\b|never\b|must\b|always\b|avoid\b|use only\b)/iu;
7
+ const METADATA = /^(?:workspace|worktree|source|repo|repository|branch|commit|path|路径|工作区|仓库|分支|目录|提交)\s*[::]/iu;
8
+ const IDENTIFIER = /^(?:task-[0-9a-z][0-9a-z-]{5,}|[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}|sha256:[\da-f]{64})[::]?$/iu;
9
+ const ROOTED_PATH = /^(?:[a-z]:[\\/]|\\\\|\/|~\/)/iu;
10
+ const RELATIVE_PATH = /^(?:[^\s\\/]+[\\/])+[^\s\\/]+$/u;
11
+
12
+ /**
13
+ * Common work actions. A title is "path + work", not "path", only when one of these starts
14
+ * the description AND that description has an object. Deliberately short: a wording
15
+ * heuristic, not natural-language parsing.
16
+ */
17
+ const CJK_ACTION = /^(?:修复|修改|修正|整改|更新|升级|补充|补齐|完善|新增|添加|删除|移除|替换|重构|重写|实现|支持|接入|迁移|优化|调整|对齐|统一|清理|整理|检查|校验|验证|排查|复现|回归|覆盖|编写|生成|同步|合并|拆分|提取|封装|加固|收紧|收口|处理|解决)/u;
18
+ const LATIN_ACTION = /^(?:fix(?:es|ed|ing)?|add(?:s|ed|ing)?|update(?:s|d|ing)?|remove(?:s|d|ing)?|delete(?:s|d|ing)?|refactor(?:s|ed|ing)?|implement(?:s|ed|ing)?|support(?:s|ed|ing)?|migrate|improve[sd]?|optimi[sz]e[sd]?|rename[sd]?|clean(?:s|ed|ing)?|test(?:s|ed|ing)?|check(?:s|ed|ing)?|review(?:s|ed|ing)?|sync(?:s|ed|ing)?|extract(?:s|ed|ing)?|merge[sd]?|align(?:s|ed|ing)?|tighten(?:s|ed|ing)?)\b/iu;
19
+
20
+ /**
21
+ * The object that starts a description, after its action, or '' when there is none.
22
+ *
23
+ * A description needs something to act ON, so a bare verb (`Fix:`, an isolated `测试`) never
24
+ * qualifies. Chinese attaches its object directly (`修复API显示`), while a Latin verb must be
25
+ * separated from its object by whitespace or a colon — which is also why `Fix:` alone, with
26
+ * nothing after the colon, has no object.
27
+ * @param {string} text - the text right after the action.
28
+ * @returns {string} the object text, or '' when the action has no object.
29
+ */
30
+ function actionObject(text) {
31
+ const trimmed = text.trim();
32
+ // A separator that leads nowhere (`Fix:` / `修复:`) is not an object.
33
+ return trimmed.replace(/^[::]+/u, '').trim();
34
+ }
35
+
36
+ /**
37
+ * Whether one rooted (absolute) line carries a work description after its path.
38
+ *
39
+ * A rooted line is ambiguous: `E:/repo 修复API显示` is a work title, while `E:/资料/修复记录`
40
+ * is a path whose last segment merely STARTS with a verb. Splitting on the first space
41
+ * cannot decide that — a path may itself contain spaces (`E:/资料/My Project 修复登录错误`) —
42
+ * so the boundary is searched for inside the LAST path segment:
43
+ *
44
+ * * a description may only begin at whitespace that follows at least one non-space path
45
+ * character, so index 0 and leading whitespace are never a boundary (that is what made
46
+ * `修复记录` and `Update notes` read as work);
47
+ * * the description may not cross a path separator, so `测试/历史` stays a path segment;
48
+ * * the action must have an object (see {@link actionObject});
49
+ * * Chinese attaches its object directly; Latin must be separated by whitespace or colon.
50
+ *
51
+ * A directory literally named after an action plus its object stays genuinely ambiguous;
52
+ * that is documented in the delivery, and no filesystem access is attempted.
53
+ * @param {string} line - one trimmed candidate line.
54
+ * @returns {boolean} true when the line reads as "path + work", not "path".
55
+ */
56
+ function describesWorkAfterPath(line) {
57
+ // Everything after the last separator is the final segment, which may hold the description.
58
+ const slash = Math.max(line.lastIndexOf('/'), line.lastIndexOf('\\'));
59
+ const segment = slash >= 0 ? line.slice(slash + 1) : line;
60
+ for (let index = 1; index < segment.length; index += 1) {
61
+ // A boundary is whitespace preceded by a path character: never the segment start.
62
+ if (!/\s/u.test(segment[index]) || /\s/u.test(segment[index - 1])) continue;
63
+ const rest = segment.slice(index).trim();
64
+ if (rest === '') continue;
65
+ const cjk = CJK_ACTION.exec(rest);
66
+ if (cjk !== null && actionObject(rest.slice(cjk[0].length)) !== '') return true;
67
+ const latin = LATIN_ACTION.exec(rest);
68
+ // Latin needs an explicit separator, so `Fixings` or `Update` alone never matches.
69
+ if (latin !== null && /^[\s::]/u.test(rest.slice(latin[0].length)) && actionObject(rest.slice(latin[0].length)) !== '') {
70
+ return true;
71
+ }
10
72
  }
11
- if (!text) {
12
- text = lines.find(line => !/^(?:you are\b|act as\b|你是|你负责|```|#{1,6}\s*(?:instructions|角色|执行规则))/iu.test(line)) || '委派任务';
73
+ return false;
74
+ }
75
+
76
+ function textLines(value) {
77
+ return typeof value === 'string' ? value.split(/\r\n?|\n/u).map((line) => line.trim()) : [];
78
+ }
79
+
80
+ function plainLine(line) {
81
+ return line.replace(/^(?:#{1,6}\s*|(?:\d+[.)、]|[-*+])\s+)/u, '').trim();
82
+ }
83
+
84
+ function outsideFences(value) {
85
+ let open = null;
86
+ return textLines(value).map((line) => {
87
+ const fence = /^(\x60{3,}|~{3,})(.*)$/u.exec(line);
88
+ if (open !== null) {
89
+ if (fence?.[1][0] === open[0] && fence[1].length >= open.length && fence[2].trim() === '') open = null;
90
+ return null;
91
+ }
92
+ if (fence) {
93
+ open = fence[1];
94
+ return null;
95
+ }
96
+ return plainLine(line);
97
+ });
98
+ }
99
+
100
+ function candidate(line) {
101
+ if (!line || /^(?:[|>]|[-*_]{3,}|\x60[^\x60]*\x60$)/u.test(line)) return '';
102
+ if (ROLE.test(line) || RULE.test(line) || RESTRICTION.test(line) || METADATA.test(line) || IDENTIFIER.test(line)) return '';
103
+ if (ROOTED_PATH.test(line) && !describesWorkAfterPath(line)) return '';
104
+ if (RELATIVE_PATH.test(line) && !/\p{Script=Han}/u.test(line)) return '';
105
+ return redactText(line).replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();
106
+ }
107
+
108
+ /** Use a short title, a structured goal, or one readable line from older callers. */
109
+ export function taskTitle(title, prompt = '') {
110
+ const explicit = outsideFences(title).map(candidate).find((line) => line && GOAL.exec(line)?.[1] !== '');
111
+ if (explicit) return boundedTitle(explicit);
112
+
113
+ const lines = outsideFences(prompt);
114
+ for (const [index, line] of lines.entries()) {
115
+ if (!line) continue;
116
+ const goal = GOAL.exec(line);
117
+ if (!goal) continue;
118
+ let body = goal[1];
119
+ if (body === '') {
120
+ let next = index + 1;
121
+ while (lines[next] === '') next += 1;
122
+ body = lines[next];
123
+ }
124
+ const text = candidate(body);
125
+ if (text && !GOAL.test(text)) return boundedTitle(text);
13
126
  }
14
- text = redactText(text).replace(/^[#*\-\d.\s]+/u, '').replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim();
15
- const chars = Array.from(text || '委派任务');
16
- return chars.length > 48 ? chars.slice(0, 47).join('') + '…' : chars.join('');
127
+ const fallback = lines.map(candidate).find((line) => line && !GOAL.test(line));
128
+ return boundedTitle(fallback || '委派任务');
129
+ }
130
+
131
+ function boundedTitle(title) {
132
+ const chars = Array.from(title);
133
+ return chars.length > 48 ? chars.slice(0, 47).join('') + '…' : title;
17
134
  }