@hearsay-tools/squawk 0.19.0-dev.9239 → 0.19.0-dev.9246

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 (129) hide show
  1. package/dist/built-in-run-slots.d.ts +4 -4
  2. package/dist/built-in-run-slots.js +10 -6
  3. package/dist/built-in-run-slots.js.map +1 -1
  4. package/dist/ci-wait/controller.d.ts +7 -7
  5. package/dist/contract/index.js +16 -1
  6. package/dist/contract/task-result.d.ts +11 -0
  7. package/dist/delegation/removal-slot.d.ts +6 -4
  8. package/dist/delegation/removal-slot.js +11 -18
  9. package/dist/delegation/removal-slot.js.map +1 -1
  10. package/dist/delegation/results.d.ts +9 -12
  11. package/dist/delegation/results.js +40 -167
  12. package/dist/delegation/results.js.map +1 -1
  13. package/dist/delegation/routes.d.ts +21 -21
  14. package/dist/delegation/transport.d.ts +10 -10
  15. package/dist/features/automations/automations-routes.d.ts +150 -150
  16. package/dist/features/automations/tools.d.ts +8 -8
  17. package/dist/features/mcp/tools.js +37 -1
  18. package/dist/features/mcp/tools.js.map +1 -1
  19. package/dist/features/reports/routes.d.ts +2 -2
  20. package/dist/runs/removal-slots.d.ts +4 -1
  21. package/dist/runs/removal-slots.js.map +1 -1
  22. package/dist/runs/retention.js +6 -1
  23. package/dist/runs/retention.js.map +1 -1
  24. package/dist/runs/task-result-builder.d.ts +117 -0
  25. package/dist/runs/task-result-builder.js +636 -0
  26. package/dist/runs/task-result-builder.js.map +1 -0
  27. package/dist/runs/task-result-preparation.d.ts +21 -0
  28. package/dist/runs/task-result-preparation.js +115 -0
  29. package/dist/runs/task-result-preparation.js.map +1 -0
  30. package/dist/runs/worker-workspace-evidence-registry.d.ts +31 -0
  31. package/dist/runs/worker-workspace-evidence-registry.js +24 -0
  32. package/dist/runs/worker-workspace-evidence-registry.js.map +1 -0
  33. package/dist/server/activity-routes.d.ts +23 -23
  34. package/dist/server/live-routes.d.ts +6 -6
  35. package/dist/server/project-settings-routes.d.ts +107 -107
  36. package/dist/server/projects-routes.d.ts +41 -41
  37. package/dist/server/provider-sign-in-routes.d.ts +2 -2
  38. package/dist/server/runner-install-routes.d.ts +10 -10
  39. package/dist/server/runs-routes.d.ts +481 -303
  40. package/dist/server/runs-routes.js +48 -3
  41. package/dist/server/runs-routes.js.map +1 -1
  42. package/dist/server/server.d.ts +2962 -2606
  43. package/dist/server/workspace-identity-routes.d.ts +5 -5
  44. package/dist/task-cli/cli.js +39 -4
  45. package/dist/task-cli/cli.js.map +1 -1
  46. package/dist/task-cli/operations.d.ts +8 -0
  47. package/dist/task-cli/operations.js +21 -0
  48. package/dist/task-cli/operations.js.map +1 -1
  49. package/dist/workflows/continuation-admission.d.ts +72 -72
  50. package/dist/workflows/input-acknowledgement.d.ts +24 -24
  51. package/dist/workflows/run/continuation-acceptance.d.ts +1 -0
  52. package/dist/workflows/run/continuation-acceptance.js +9 -2
  53. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  54. package/package.json +4 -4
  55. package/web/dist/assets/{accounts-section-BOZ9JyE6.js → accounts-section-BROiR4ew.js} +1 -1
  56. package/web/dist/assets/{activity-motion-D48R7Vry.js → activity-motion-BWSUUfiT.js} +1 -1
  57. package/web/dist/assets/{activity-route-jcGRtnMT.js → activity-route-B2N8ZaZ_.js} +1 -1
  58. package/web/dist/assets/{agent-accounts-CUthX0Yh.js → agent-accounts-DjIbGucr.js} +1 -1
  59. package/web/dist/assets/{agent-config-section-BvwoyNZb.js → agent-config-section-Ck4CXMFm.js} +1 -1
  60. package/web/dist/assets/{agent-defaults-section-Hb-jy4TN.js → agent-defaults-section-CSonqNrH.js} +1 -1
  61. package/web/dist/assets/{appearance-EXKzoghV.js → appearance-CtRi80xH.js} +1 -1
  62. package/web/dist/assets/{archive-on-merge-field-Ni7bKGkG.js → archive-on-merge-field-DWIBlp84.js} +1 -1
  63. package/web/dist/assets/{ask-card-CkE44gm3.js → ask-card-Cr2AS4K4.js} +1 -1
  64. package/web/dist/assets/{automations-route-3bhtdTy3.js → automations-route-iHpqtQ2V.js} +1 -1
  65. package/web/dist/assets/{commit-list-DSw7qvVY.js → commit-list-BjI9yFlp.js} +1 -1
  66. package/web/dist/assets/{diff-BidPzsVK.js → diff-BKikntA1.js} +2 -2
  67. package/web/dist/assets/{diff-controls-DeMSGYln.js → diff-controls-DXLI7YrY.js} +1 -1
  68. package/web/dist/assets/{diff-view-BqU4sJld.js → diff-view-NHfT1G3r.js} +1 -1
  69. package/web/dist/assets/{discard-changes-dialog-B1AO0GSt.js → discard-changes-dialog-COQOWWB4.js} +1 -1
  70. package/web/dist/assets/{file-preview-BIZXTzkp.js → file-preview-CuynH2GY.js} +1 -1
  71. package/web/dist/assets/{folder-browser-C9Phl0rS.js → folder-browser-p1qA81Do.js} +1 -1
  72. package/web/dist/assets/{git-toolbar-BBon1yHh.js → git-toolbar-C27plnSQ.js} +1 -1
  73. package/web/dist/assets/{github-QOB5Qi4v.js → github-BVFqmL19.js} +1 -1
  74. package/web/dist/assets/{global-activity-route-lSnYAZE9.js → global-activity-route-DUa3ZKH5.js} +1 -1
  75. package/web/dist/assets/{hosts-DDwDUxT9.js → hosts-dk-7MbxQ.js} +1 -1
  76. package/web/dist/assets/{index-BuR9xHfb.js → index-BMO-SCLT.js} +5 -5
  77. package/web/dist/assets/{label-D6vgq5lF.js → label-B4KzRUWE.js} +1 -1
  78. package/web/dist/assets/{markdown-A6dvDky9.js → markdown-RyIndDEG.js} +1 -1
  79. package/web/dist/assets/{open-in-menu-Bb_jc7pm.js → open-in-menu-GSvSbohX.js} +1 -1
  80. package/web/dist/assets/{option-select-CCpypHbW.js → option-select-DRpdIulm.js} +1 -1
  81. package/web/dist/assets/{preferences-section-B75Zx0mY.js → preferences-section-PTJo2Ohl.js} +1 -1
  82. package/web/dist/assets/{preview-DiBpgf-5.js → preview-B13nIXDV.js} +1 -1
  83. package/web/dist/assets/{preview-pane-connected-BVu2oO0V.js → preview-pane-connected-B9GKjFwm.js} +1 -1
  84. package/web/dist/assets/{project-location-D1etWKHg.js → project-location-BE1vP9ox.js} +1 -1
  85. package/web/dist/assets/{project-router-yoWCTDaT.js → project-router-Bl7pejIP.js} +1 -1
  86. package/web/dist/assets/project-scope-context-BT4qzyOz.js +4 -0
  87. package/web/dist/assets/{projects-section-BRnIJ47e.js → projects-section-B3-nydjA.js} +1 -1
  88. package/web/dist/assets/{prompt-templates-section-D7JLM5BM.js → prompt-templates-section-JgrQfgx0.js} +1 -1
  89. package/web/dist/assets/{queries-ChH9ctc-.js → queries-CzUiyqt4.js} +1 -1
  90. package/web/dist/assets/{reference-chip-BPRZm7Kb.js → reference-chip-jxISA5ls.js} +1 -1
  91. package/web/dist/assets/{remote-settings-notice-Ip6H5hLU.js → remote-settings-notice-BihAOLqD.js} +1 -1
  92. package/web/dist/assets/{repo-git-Wf30akEt.js → repo-git-B1q5EsnP.js} +1 -1
  93. package/web/dist/assets/{report-reader-DhcZcNql.js → report-reader-DjeG4XbX.js} +1 -1
  94. package/web/dist/assets/{report-selection-CwPw7vbG.js → report-selection-DBxcKtc9.js} +1 -1
  95. package/web/dist/assets/{reports-DPKDwzxY.js → reports-DWiYYakL.js} +1 -1
  96. package/web/dist/assets/{resources-section-DaWcyqur.js → resources-section-DWjxu1Aj.js} +1 -1
  97. package/web/dist/assets/{review-notes-drafts-D7QuBuTL.js → review-notes-drafts-iAtTr6a6.js} +1 -1
  98. package/web/dist/assets/{review-panel-Bpxl4TvO.js → review-panel-DPRxBYq7.js} +1 -1
  99. package/web/dist/assets/{review-strip-Da5n1k8s.js → review-strip-S4KkkMIo.js} +1 -1
  100. package/web/dist/assets/{run-detail-refresh-CVSK_VKG.js → run-detail-refresh-e7rB9lt5.js} +1 -1
  101. package/web/dist/assets/{run-diff-CPuNFD3X.js → run-diff-QWOM0ICK.js} +1 -1
  102. package/web/dist/assets/{run-header-B8EAOHFc.js → run-header-BNh2z4aw.js} +1 -1
  103. package/web/dist/assets/{select-xjUzLrk9.js → select-DlJM2_n-.js} +1 -1
  104. package/web/dist/assets/{session-context-section-C7OTexKU.js → session-context-section-vdKhbdZx.js} +1 -1
  105. package/web/dist/assets/{settings-agent-picker-mESK-hj4.js → settings-agent-picker-tNi4Xm3k.js} +1 -1
  106. package/web/dist/assets/{settings-save-bar-BUaa1kHw.js → settings-save-bar-fQqyWU1c.js} +1 -1
  107. package/web/dist/assets/{settings-shell-BKSsBxqQ.js → settings-shell-B-pmSB5-.js} +1 -1
  108. package/web/dist/assets/{sidebar-section-BFBZlQ-x.js → sidebar-section-DBgf2u5s.js} +1 -1
  109. package/web/dist/assets/{skills-BSqszv5g.js → skills-BePs-LtJ.js} +1 -1
  110. package/web/dist/assets/{status-dot-Fp5SnPHI.js → status-dot-BlqTixB7.js} +1 -1
  111. package/web/dist/assets/{tab-link-j06AaWSU.js → tab-link-tv_Wy5eF.js} +1 -1
  112. package/web/dist/assets/{task-changes-B4KFHxVa.js → task-changes-D-ehUptL.js} +1 -1
  113. package/web/dist/assets/{task-commits-D-UAUoZ5.js → task-commits-BgDfumUM.js} +1 -1
  114. package/web/dist/assets/{task-file-scope-BhWG35a8.js → task-file-scope-Bqt2wkkO.js} +1 -1
  115. package/web/dist/assets/{task-files-BOCx_Lp0.js → task-files-BME7tXzx.js} +1 -1
  116. package/web/dist/assets/{task-github-item-CZqaaxNv.js → task-github-item-BQL_jlnH.js} +1 -1
  117. package/web/dist/assets/{task-thread-D3d419VX.js → task-thread-D-BHmr_Z.js} +1 -1
  118. package/web/dist/assets/{thread-state-B0pz2Y8K.js → thread-state-DWcNrVOV.js} +1 -1
  119. package/web/dist/assets/{use-finish-run-TX3pIPCS.js → use-finish-run-B4gkbFl_.js} +1 -1
  120. package/web/dist/assets/{use-hand-to-agent-state-D2oChRzw.js → use-hand-to-agent-state-7ItPHT6A.js} +1 -1
  121. package/web/dist/assets/use-path-bases-DfSirdvs.js +1 -0
  122. package/web/dist/assets/use-workspace-config-save-Dz8Cl7MP.js +1 -0
  123. package/web/dist/assets/{workflows-BwzNhxT0.js → workflows-CFKtz_8t.js} +1 -1
  124. package/web/dist/assets/{workspace-tools-Be_j9oke.js → workspace-tools-CBQyH8IV.js} +1 -1
  125. package/web/dist/assets/{worktrees-section-cnibWU5-.js → worktrees-section-CA7lv70p.js} +1 -1
  126. package/web/dist/index.html +14 -14
  127. package/web/dist/assets/project-scope-context-hfRzPMZ4.js +0 -4
  128. package/web/dist/assets/use-path-bases-DFxEHoyU.js +0 -1
  129. package/web/dist/assets/use-workspace-config-save-DR8brU5p.js +0 -1
@@ -0,0 +1,636 @@
1
+ /**
2
+ * Core task result builder (E2 hearsay-tools/squawk#4629): builds a `StoredTaskResult` (and
3
+ * optional `diffSnapshot`) for any task — standalone worktree, `--no-worktree` project task, or
4
+ * worker (delegating worker workspace checks through the registered/injected adapter so `runs/`
5
+ * imports nothing from `delegation/`).
6
+ *
7
+ * Strictly read-only: never writes to disk or `runs.db`, takes no claims, and never touches the
8
+ * task worktree's real Git index.
9
+ */
10
+ import { randomUUID } from 'node:crypto';
11
+ import { existsSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { z } from 'zod';
14
+ import { ownsDirectory, WORKER_SUMMARY_PAGE_CHARS } from '../contract/index.js';
15
+ import { isLiveStatus } from '../contract/index.js';
16
+ import { toPublicTaskResult, workerResultToStoredTaskResult } from '../contract/index.js';
17
+ import { git } from '../git-command.js';
18
+ import { diffFromMergeBase, resolveTaskDiffAnchor } from '../git-diff-base.js';
19
+ import { withPrivateIndex } from '../git-private-index.js';
20
+ import { isSafeGitRef } from '../git-refs.js';
21
+ import { DIFF_CAP } from '../git-worktree.js';
22
+ import { commandText } from '../home/command.js';
23
+ import { runDataDir } from '../legacy-runs.js';
24
+ import { artifactContentPath, artifactDirectory, listArtifacts, readArtifact } from '../task-files/artifact-kind.js';
25
+ import { isAttachmentFileName, resolveAttachmentPath } from '../workflows/attachment-path.js';
26
+ import { workerObservation } from './delegation-state.js';
27
+ import { workerWorkspaceEvidenceAdapter, } from './worker-workspace-evidence-registry.js';
28
+ export const TASK_SUMMARY_CHARS = 4000;
29
+ const COMMIT_SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
30
+ const SETTLED_STATUSES = new Set(['review', 'done', 'failed', 'cancelled']);
31
+ const NO_PRIVATE_INDEX = { ok: false, reason: 'unreadable', detail: 'no private index' };
32
+ /** Current execution revision of any task (0 before the first Continue). */
33
+ export function taskExecutionRevision(run) {
34
+ return run.delegation?.role === 'worker' ? run.delegation.executionRevision ?? 0 : run.executionRevision ?? 0;
35
+ }
36
+ /** Current execution start sequence of any task (-1 when never continued). */
37
+ function taskExecutionStartSeq(run) {
38
+ return run.delegation?.role === 'worker' ? run.delegation.executionStartSeq ?? -1 : run.executionStartSeq ?? -1;
39
+ }
40
+ /** The public status mapped to an execution outcome. */
41
+ export function taskExecutionOutcome(status) {
42
+ if (status === 'review')
43
+ return 'review-ready';
44
+ if (status === 'done')
45
+ return 'completed';
46
+ if (status === 'failed')
47
+ return 'failed';
48
+ if (status === 'cancelled')
49
+ return 'cancelled';
50
+ return 'running';
51
+ }
52
+ /** Pre-E3 settlement rule for non-worker tasks (spec Decision 2). */
53
+ export function nonWorkerObservation(run, isActive) {
54
+ const settled = SETTLED_STATUSES.has(run.status) && !isActive;
55
+ return { settled, partial: !settled || run.status === 'failed' || run.status === 'cancelled' };
56
+ }
57
+ /**
58
+ * The text of a top-level assistant message event, v1 `text` or v2 `item.completed`; the newest
59
+ * one is what result collection reports and what a park notice quotes (hearsay-tools/cezarion#1327).
60
+ */
61
+ export function topLevelAssistantText(event) {
62
+ const item = event.item;
63
+ const text = event.type === 'text' && !event.parentItemId
64
+ ? event.text
65
+ : event.type === 'item.completed' && item?.kind === 'message' && item.role === 'assistant' && item.parentItemId === undefined
66
+ ? item.text
67
+ : undefined;
68
+ return typeof text === 'string' ? text : undefined;
69
+ }
70
+ /** Count logical wrapped lines identically to `delegation/worker-summary.ts`. */
71
+ export function summaryLineCount(text) {
72
+ const lines = text.split('\n');
73
+ if (lines.length > 1 && lines.at(-1) === '')
74
+ lines.pop();
75
+ let total = 0;
76
+ for (const line of lines) {
77
+ total += line.length <= WORKER_SUMMARY_PAGE_CHARS ? 1 : Math.ceil(line.length / WORKER_SUMMARY_PAGE_CHARS);
78
+ }
79
+ return Math.max(1, total);
80
+ }
81
+ function newestAssistantMessage(events) {
82
+ let message;
83
+ for (const event of events) {
84
+ const text = topLevelAssistantText(event);
85
+ if (text?.trim())
86
+ message = { text, source: 'assistant', seq: event.seq };
87
+ }
88
+ return message;
89
+ }
90
+ /**
91
+ * Resolve the task's final message (owner D6):
92
+ * - A failed run with an error reports `Runner failure: <error>`.
93
+ * - Otherwise scope to `seq > executionStartSeq`.
94
+ * - Non-workers fall back to the newest non-blank assistant message of the whole run when the
95
+ * current continuation produced none; workers keep strict current-execution scoping.
96
+ */
97
+ export function finalTaskMessage(run, allEvents, opts = {}) {
98
+ const strict = opts.strictScope ?? (run.delegation?.role === 'worker');
99
+ const startSeq = taskExecutionStartSeq(run);
100
+ const scoped = allEvents.filter((event) => event.seq > startSeq);
101
+ if (run.status === 'failed' && run.error?.trim()) {
102
+ const seq = strict ? (scoped.at(-1)?.seq ?? 0) : (scoped.at(-1)?.seq ?? allEvents.at(-1)?.seq ?? 0);
103
+ return { text: `Runner failure: ${run.error.trim()}`, source: 'failure', seq };
104
+ }
105
+ const current = newestAssistantMessage(scoped);
106
+ if (current || strict || startSeq < 0)
107
+ return current;
108
+ return newestAssistantMessage(allEvents);
109
+ }
110
+ function boundedTaskSummary(message) {
111
+ if (!message)
112
+ return { state: 'unavailable', reason: 'no-assistant-output' };
113
+ return {
114
+ state: 'available',
115
+ text: message.text.slice(0, TASK_SUMMARY_CHARS),
116
+ source: message.source,
117
+ seq: message.seq,
118
+ truncated: message.text.length > TASK_SUMMARY_CHARS,
119
+ totalLines: summaryLineCount(message.text),
120
+ };
121
+ }
122
+ /** Read a verified commit SHA for `HEAD` in `dir`, or undefined if unreadable. */
123
+ export async function readTaskHead(dir) {
124
+ const res = await git(dir, ['rev-parse', '--verify', 'HEAD^{commit}'], { timeout: 30_000, maxBuffer: 1024 });
125
+ if (!res.ok)
126
+ return undefined;
127
+ const sha = res.stdout.trim();
128
+ return COMMIT_SHA_RE.test(sha) ? sha : undefined;
129
+ }
130
+ /**
131
+ * Structured task worktree diff over `withPrivateIndex` (docs/areas/git-worktree.md):
132
+ * - Anchors with `resolveTaskDiffAnchor` (passing run `branch` and `startedAt`) then
133
+ * `diffFromMergeBase`, never `diffFromMergeBase` alone against the base branch.
134
+ * - Refuses the real-index fallback through `beforeLiveIndex` so the worktree's real `.git/index`
135
+ * stays byte-identical when no scratch directory can be created.
136
+ * - Bounds output to `cap` (`DIFF_CAP = 400_000`) and reports `{ diff, truncated }`.
137
+ */
138
+ export async function readTaskWorktreeDiff(worktreePath, baseBranch, opts = {}) {
139
+ if (!isSafeGitRef(baseBranch)) {
140
+ return { ok: false, reason: 'unverified', detail: 'refusing option-like base ref' };
141
+ }
142
+ const cap = opts.cap ?? DIFF_CAP;
143
+ return withPrivateIndex(worktreePath, async (indexedGit) => {
144
+ const added = await indexedGit(['add', '-N', '.']);
145
+ if (!added.ok) {
146
+ return { ok: false, reason: 'unverified', detail: added.stderr.trim() || 'git add -N failed' };
147
+ }
148
+ const { base, viaMergeBase } = await resolveTaskDiffAnchor(indexedGit, baseBranch, {
149
+ taskBranch: opts.taskBranch,
150
+ runStartedAt: opts.runStartedAt,
151
+ });
152
+ const diffArgs = ['--no-ext-diff', '--no-textconv'];
153
+ const res = viaMergeBase
154
+ ? await diffFromMergeBase(indexedGit, base, diffArgs)
155
+ : await indexedGit(['diff', ...diffArgs, base, '--']);
156
+ if (!res.ok && !(res.overflow && res.stdout.length > cap)) {
157
+ return { ok: false, reason: 'unverified', detail: res.stderr.trim() || 'git diff failed' };
158
+ }
159
+ const truncated = res.overflow || res.stdout.length > cap;
160
+ return { ok: true, diff: truncated ? res.stdout.slice(0, cap) : res.stdout, truncated };
161
+ }, () => NO_PRIVATE_INDEX);
162
+ }
163
+ function escapeRegExp(value) {
164
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
165
+ }
166
+ function collectAttachmentIds(run, allEvents) {
167
+ const ids = new Set();
168
+ const imageRe = new RegExp(`^/api/(?:v1/)?runs/${escapeRegExp(run.id)}/images/([^/]+)$`);
169
+ for (const event of allEvents) {
170
+ if (event.type !== 'image' || typeof event.url !== 'string')
171
+ continue;
172
+ const match = event.url.match(imageRe);
173
+ if (match && isAttachmentFileName(match[1]) && match[1].length <= 255)
174
+ ids.add(match[1]);
175
+ }
176
+ if (run.delegation?.role === 'worker') {
177
+ for (const input of run.delegation.context?.inputs ?? []) {
178
+ if (input.source.kind !== 'parent-attachment')
179
+ continue;
180
+ const name = input.path.split('/').at(-1);
181
+ if (isAttachmentFileName(name))
182
+ ids.add(name);
183
+ }
184
+ }
185
+ return [...ids];
186
+ }
187
+ function attachmentItem(dataDir, runId, id) {
188
+ const path = join(runDataDir(dataDir, runId), 'runs', `${runId}-images`, id);
189
+ if (resolveAttachmentPath(dataDir, runId, id))
190
+ return { state: 'available', id, kind: 'attachment', path };
191
+ if (existsSync(path))
192
+ return { state: 'unavailable', reason: 'unreadable', id, kind: 'attachment', path };
193
+ return { state: 'deleted', reason: 'missing', id, kind: 'attachment', path };
194
+ }
195
+ async function listPublishedItems(dataDir, runId) {
196
+ if (!z.uuid().safeParse(runId).success)
197
+ return [];
198
+ const dir = artifactDirectory(dataDir, runId);
199
+ const published = await listArtifacts(dir, runId);
200
+ return published.slice().reverse().map((item) => ({
201
+ state: 'available',
202
+ id: `published:${item.id}`,
203
+ kind: 'published',
204
+ name: item.name,
205
+ size: item.size,
206
+ path: artifactContentPath(dir, item.id),
207
+ }));
208
+ }
209
+ async function listTaskArtifacts(dataDir, run, allEvents) {
210
+ const publishedItems = await listPublishedItems(dataDir, run.id);
211
+ const attachmentIds = collectAttachmentIds(run, allEvents);
212
+ const attachmentItems = attachmentIds.map((id) => attachmentItem(dataDir, run.id, id));
213
+ const total = publishedItems.length + attachmentItems.length;
214
+ return { state: 'available', items: [...publishedItems, ...attachmentItems].slice(0, 32), truncated: total > 32 };
215
+ }
216
+ async function revalidateStoredItem(dataDir, runId, item) {
217
+ const meta = {
218
+ ...(item.name === undefined ? {} : { name: item.name }),
219
+ ...(item.size === undefined ? {} : { size: item.size }),
220
+ ...(item.path === undefined ? {} : { path: item.path }),
221
+ };
222
+ if (item.kind === 'published' && item.id.startsWith('published:') && z.uuid().safeParse(runId).success) {
223
+ const found = await readArtifact(artifactDirectory(dataDir, runId), runId, item.id.slice('published:'.length));
224
+ return found
225
+ ? { state: 'available', id: item.id, kind: 'published', ...meta }
226
+ : { state: 'deleted', reason: 'missing', id: item.id, kind: 'published', ...meta };
227
+ }
228
+ return attachmentItem(dataDir, runId, item.id);
229
+ }
230
+ async function revalidateTaskArtifacts(dataDir, run, allEvents, previous) {
231
+ const live = await listTaskArtifacts(dataDir, run, allEvents);
232
+ if (live.state !== 'available' || previous.state !== 'available')
233
+ return live;
234
+ const seen = new Set(live.items.map((item) => item.id));
235
+ const missingFromLive = [];
236
+ for (const oldItem of previous.items) {
237
+ if (!seen.has(oldItem.id)) {
238
+ seen.add(oldItem.id);
239
+ missingFromLive.push(await revalidateStoredItem(dataDir, run.id, oldItem));
240
+ }
241
+ }
242
+ const combined = [...live.items, ...missingFromLive];
243
+ return {
244
+ state: 'available',
245
+ items: combined.slice(0, 32),
246
+ truncated: live.truncated || previous.truncated || combined.length > 32,
247
+ };
248
+ }
249
+ function historicalHeadSha(head) {
250
+ return head && 'sha' in head ? head.sha : undefined;
251
+ }
252
+ function knownBaselineSha(run, previous) {
253
+ if (run.baseBranch && COMMIT_SHA_RE.test(run.baseBranch))
254
+ return run.baseBranch;
255
+ return previous?.baselineSha;
256
+ }
257
+ function toWorkerArtifacts(artifacts) {
258
+ if (artifacts.state !== 'available')
259
+ return artifacts;
260
+ return {
261
+ state: 'available',
262
+ truncated: artifacts.truncated,
263
+ items: artifacts.items.map((item) => {
264
+ const path = item.path ?? '';
265
+ if (item.state === 'available')
266
+ return { state: 'available', id: item.id, path };
267
+ if (item.state === 'deleted')
268
+ return { state: 'deleted', reason: item.reason, id: item.id, path };
269
+ return {
270
+ state: 'unavailable',
271
+ reason: item.reason,
272
+ ...(item.detail === undefined ? {} : { detail: item.detail }),
273
+ id: item.id,
274
+ path,
275
+ };
276
+ }),
277
+ };
278
+ }
279
+ function toWorkerSummary(runId, summary) {
280
+ if (summary.state !== 'available')
281
+ return summary;
282
+ return {
283
+ ...summary,
284
+ ...(summary.truncated ? { fullCommand: commandText(`cez worker summary ${runId}`) } : {}),
285
+ };
286
+ }
287
+ async function readWorkerHeadEvidence(repoRoot, run, previous, workspaceRemoved, adapter) {
288
+ const sha = historicalHeadSha(previous?.head);
289
+ const base = {
290
+ state: workspaceRemoved ? 'deleted' : 'unavailable',
291
+ reason: 'missing',
292
+ ...(sha ? { sha } : {}),
293
+ };
294
+ try {
295
+ const live = await adapter.readHead(repoRoot, run);
296
+ if (!COMMIT_SHA_RE.test(live))
297
+ throw new Error('invalid HEAD');
298
+ return { state: 'available', sha: live };
299
+ }
300
+ catch {
301
+ if (workspaceRemoved)
302
+ return base;
303
+ return { state: 'unavailable', reason: 'unverified', ...(sha ? { sha } : {}) };
304
+ }
305
+ }
306
+ async function readWorkerDiffEvidence(repoRoot, store, run, delegation, cleanup, adapter) {
307
+ const noDiff = adapter.noDiff(run);
308
+ if (noDiff)
309
+ return { diff: { state: 'unavailable', reason: 'unsupported', detail: noDiff }, diffSnapshot: undefined, fromStored: false };
310
+ let diff = { state: cleanup.workspaceRemoved ? 'deleted' : 'unavailable', reason: 'missing' };
311
+ let diffSnapshot;
312
+ try {
313
+ const observation = await adapter.readDiff(repoRoot, run);
314
+ diffSnapshot = observation.diff;
315
+ const snapshotId = randomUUID();
316
+ diff = {
317
+ state: 'available',
318
+ snapshotId,
319
+ path: store.workerResults.workerResultSnapshotPath(delegation.parentRunId, run.id, snapshotId),
320
+ truncated: observation.truncated,
321
+ };
322
+ }
323
+ catch {
324
+ if (!cleanup.destroyed)
325
+ diff = { state: 'unavailable', reason: 'unverified' };
326
+ }
327
+ // Re-read after the live workspace checks: a concurrent reclaim can commit a snapshot while this read ran.
328
+ if (diffSnapshot === undefined && !cleanup.requireLiveDiff) {
329
+ const stored = store.workerResults.readWorkerResult(delegation.parentRunId, run.id);
330
+ if (stored?.revision === taskExecutionRevision(run) && stored.diff.state === 'available') {
331
+ const retained = store.workerResults.readWorkerResultDiff(delegation.parentRunId, run.id);
332
+ if (retained !== undefined) {
333
+ return { diff: { ...stored.diff, snapshotId: randomUUID() }, diffSnapshot: retained, fromStored: true };
334
+ }
335
+ }
336
+ }
337
+ return { diff, diffSnapshot, fromStored: false };
338
+ }
339
+ function isWorkerWorkspaceRemoved(run, delegation, adapter) {
340
+ if (delegation.destroy && adapter.workspaceDirectoryRemoved(delegation.workspace, delegation.destroy.remaining)) {
341
+ return true;
342
+ }
343
+ return Boolean(run.worktreeReclaimedAt && ownsDirectory(delegation.workspace));
344
+ }
345
+ function workerOptionalFields(run) {
346
+ return {
347
+ ...(run.error ? { error: run.error.slice(0, 2000) } : {}),
348
+ ...(run.runner ? { backend: run.runner } : {}),
349
+ ...(run.model ? { model: run.model } : {}),
350
+ };
351
+ }
352
+ function taskOptionalFields(run) {
353
+ return {
354
+ ...(run.error ? { error: run.error.slice(0, 2000) } : {}),
355
+ ...(run.runner ? { runner: run.runner } : {}),
356
+ ...(run.model ? { model: run.model } : {}),
357
+ };
358
+ }
359
+ function workspaceStateFor(removed, head) {
360
+ if (removed)
361
+ return 'deleted';
362
+ return head.state === 'available' ? 'available' : 'unavailable';
363
+ }
364
+ /**
365
+ * Build a worker task's lossless `WorkerCollectedResult` and projected `StoredTaskResult`.
366
+ * Strictly read-only: writes nothing to disk or `runs.db`.
367
+ */
368
+ export async function buildWorkerTaskResult(repoRoot, store, run, options = {}) {
369
+ if (run.delegation?.role !== 'worker')
370
+ throw new Error('missing worker ownership');
371
+ const delegation = run.delegation;
372
+ const adapter = options.workerWorkspace ?? workerWorkspaceEvidenceAdapter();
373
+ const previous = store.workerResults.readWorkerResult(delegation.parentRunId, run.id);
374
+ const allEvents = await store.eventLog.readEventsAsync(run.id);
375
+ const summary = toWorkerSummary(run.id, boundedTaskSummary(finalTaskMessage(run, allEvents, { strictScope: true })));
376
+ const destroyed = delegation.destroy?.phase === 'complete';
377
+ const workspaceRemoved = isWorkerWorkspaceRemoved(run, delegation, adapter);
378
+ const lastExecutionOutcome = taskExecutionOutcome(run.status);
379
+ const execution = store.workerExecutions.readWorkerExecution(run.id);
380
+ const observation = workerObservation(run, execution);
381
+ const head = await readWorkerHeadEvidence(repoRoot, run, previous, workspaceRemoved, adapter);
382
+ const { diff, diffSnapshot, fromStored } = await readWorkerDiffEvidence(repoRoot, store, run, delegation, { destroyed, workspaceRemoved, requireLiveDiff: Boolean(options.requireLiveDiff) }, adapter);
383
+ const dataDir = store.claims.sourceDataDir(run.id);
384
+ const changes = await adapter.changeReport(dataDir, run, { generation: execution?.generation, settled: !isLiveStatus(run.status) });
385
+ const artifacts = toWorkerArtifacts(await listTaskArtifacts(dataDir, run, allEvents));
386
+ const result = {
387
+ workerId: run.id,
388
+ parentRunId: delegation.parentRunId,
389
+ revision: taskExecutionRevision(run),
390
+ observedAt: (options.now ?? (() => new Date().toISOString()))(),
391
+ status: run.status,
392
+ outcome: destroyed ? 'destroyed' : lastExecutionOutcome,
393
+ lastExecutionOutcome,
394
+ ...observation,
395
+ ...workerOptionalFields(run),
396
+ baselineSha: delegation.workspace.baselineSha,
397
+ workspace: { ...delegation.workspace, state: workspaceStateFor(workspaceRemoved, head) },
398
+ cleanup: delegation.destroy?.phase ?? 'retained',
399
+ summary,
400
+ head,
401
+ diff,
402
+ ...(changes ? { changes } : {}),
403
+ artifacts,
404
+ };
405
+ const storedResult = workerResultToStoredTaskResult(result, diffSnapshot);
406
+ const source = (workspaceRemoved || destroyed) && fromStored ? 'stored' : 'live';
407
+ return { result, storedResult, ...(diffSnapshot === undefined ? {} : { diffSnapshot }), source };
408
+ }
409
+ async function buildProjectWorkspaceEvidence(repoRoot, run, previous) {
410
+ const baselineSha = knownBaselineSha(run, previous);
411
+ const historicalSha = historicalHeadSha(previous?.head);
412
+ const liveSha = await readTaskHead(repoRoot);
413
+ const head = liveSha
414
+ ? { state: 'available', sha: liveSha }
415
+ : { state: 'unavailable', reason: 'unverified', ...(historicalSha ? { sha: historicalSha } : {}) };
416
+ return {
417
+ workspace: {
418
+ kind: 'project',
419
+ state: workspaceStateFor(false, head),
420
+ path: repoRoot,
421
+ ...(baselineSha ? { baselineSha } : {}),
422
+ },
423
+ head,
424
+ diff: { state: 'unavailable', reason: 'unsupported' },
425
+ };
426
+ }
427
+ async function buildLiveOwnedWorktreeEvidence(store, run, worktreePath, previous, requireLiveDiff) {
428
+ const baselineSha = knownBaselineSha(run, previous);
429
+ const historicalSha = historicalHeadSha(previous?.head);
430
+ const hasGit = existsSync(join(worktreePath, '.git'));
431
+ const liveSha = hasGit ? await readTaskHead(worktreePath) : undefined;
432
+ const head = liveSha
433
+ ? { state: 'available', sha: liveSha }
434
+ : { state: 'unavailable', reason: 'unverified', ...(historicalSha ? { sha: historicalSha } : {}) };
435
+ const { diff, diffSnapshot } = await readLiveOwnedWorktreeDiff(store, run, worktreePath, hasGit, requireLiveDiff);
436
+ return {
437
+ workspace: {
438
+ kind: 'owned',
439
+ state: workspaceStateFor(false, head),
440
+ path: worktreePath,
441
+ ...(run.branch ? { branch: run.branch } : {}),
442
+ ...(baselineSha ? { baselineSha } : {}),
443
+ },
444
+ head,
445
+ diff,
446
+ ...(diffSnapshot === undefined ? {} : { diffSnapshot }),
447
+ };
448
+ }
449
+ function readConcurrentRemovalDiff(store, run, worktreePath, requireLiveDiff) {
450
+ if (requireLiveDiff || existsSync(worktreePath))
451
+ return undefined;
452
+ const stored = store.taskResults.readTaskResult(run.id);
453
+ if (!stored || stored.result.revision !== taskExecutionRevision(run) || stored.result.diff.state !== 'available' || stored.diffSnapshot === undefined) {
454
+ return undefined;
455
+ }
456
+ return { diffSnapshot: stored.diffSnapshot, diff: { ...stored.result.diff, snapshotId: randomUUID() } };
457
+ }
458
+ async function readLiveOwnedWorktreeDiff(store, run, worktreePath, hasGit, requireLiveDiff) {
459
+ if (!hasGit) {
460
+ const recovered = readConcurrentRemovalDiff(store, run, worktreePath, requireLiveDiff);
461
+ if (recovered)
462
+ return recovered;
463
+ return { diff: { state: 'unavailable', reason: 'unverified', detail: 'worktree has no .git entry' } };
464
+ }
465
+ const read = await readTaskWorktreeDiff(worktreePath, run.baseBranch ?? 'HEAD', {
466
+ taskBranch: run.branch,
467
+ runStartedAt: run.startedAt,
468
+ });
469
+ if (read.ok) {
470
+ const snapshotId = randomUUID();
471
+ return {
472
+ diffSnapshot: read.diff,
473
+ diff: {
474
+ state: 'available',
475
+ snapshotId,
476
+ path: store.taskResults.taskResultSnapshotPath(run.id, snapshotId),
477
+ truncated: read.truncated,
478
+ bytes: Buffer.byteLength(read.diff, 'utf8'),
479
+ },
480
+ };
481
+ }
482
+ // Re-read after live Git checks only if a concurrent removal deleted the worktree while Git ran.
483
+ // Never reuse an earlier snapshot when live Git failed on an existing directory or during pre-removal capture.
484
+ if (read.detail !== NO_PRIVATE_INDEX.detail) {
485
+ const recovered = readConcurrentRemovalDiff(store, run, worktreePath, requireLiveDiff);
486
+ if (recovered)
487
+ return recovered;
488
+ }
489
+ return { diff: { state: 'unavailable', reason: read.reason, ...(read.detail ? { detail: read.detail } : {}) } };
490
+ }
491
+ function buildMissingWorktreeEvidence(run, previous) {
492
+ const baselineSha = knownBaselineSha(run, previous);
493
+ const historicalSha = historicalHeadSha(previous?.head);
494
+ const baseWorkspace = {
495
+ kind: 'owned',
496
+ ...(run.worktreePath ? { path: run.worktreePath } : {}),
497
+ ...(run.branch ? { branch: run.branch } : {}),
498
+ ...(baselineSha ? { baselineSha } : {}),
499
+ };
500
+ if (run.worktreeReclaimedAt) {
501
+ return {
502
+ workspace: { ...baseWorkspace, state: 'deleted' },
503
+ head: { state: 'deleted', reason: 'missing', ...(historicalSha ? { sha: historicalSha } : {}) },
504
+ diff: { state: 'deleted', reason: 'missing' },
505
+ };
506
+ }
507
+ if (run.worktreePath) {
508
+ return {
509
+ workspace: { ...baseWorkspace, state: 'unavailable' },
510
+ head: { state: 'unavailable', reason: 'unverified', ...(historicalSha ? { sha: historicalSha } : {}) },
511
+ diff: { state: 'unavailable', reason: 'unverified' },
512
+ };
513
+ }
514
+ return {
515
+ workspace: { ...baseWorkspace, state: 'unavailable' },
516
+ head: { state: 'unavailable', reason: 'missing', ...(historicalSha ? { sha: historicalSha } : {}) },
517
+ diff: { state: 'unavailable', reason: 'missing' },
518
+ };
519
+ }
520
+ function isManuallyRemovedOwnedSnapshot(run, previous) {
521
+ return !run.worktreePath && previous.workspace.kind === 'owned';
522
+ }
523
+ function canUseStoredNonWorkerSnapshot(run, hasLiveWorktree, previous, revision) {
524
+ if (run.worktree === false || hasLiveWorktree || previous.result.revision !== revision)
525
+ return false;
526
+ return Boolean(run.worktreeReclaimedAt)
527
+ || previous.result.workspace.state === 'deleted'
528
+ || Boolean(run.worktreePath)
529
+ || isManuallyRemovedOwnedSnapshot(run, previous.result);
530
+ }
531
+ function selectNonWorkerEvidence(repoRoot, store, run, hasLiveWorktree, previous, requireLiveDiff) {
532
+ if (run.worktree === false)
533
+ return buildProjectWorkspaceEvidence(repoRoot, run, previous);
534
+ if (hasLiveWorktree)
535
+ return buildLiveOwnedWorktreeEvidence(store, run, run.worktreePath, previous, requireLiveDiff);
536
+ return buildMissingWorktreeEvidence(run, previous);
537
+ }
538
+ async function buildStoredNonWorkerResult(dataDir, run, allEvents, previous, isActive) {
539
+ const observation = nonWorkerObservation(run, isActive);
540
+ const outcome = taskExecutionOutcome(run.status);
541
+ const deleted = Boolean(run.worktreeReclaimedAt)
542
+ || previous.result.workspace.state === 'deleted'
543
+ || isManuallyRemovedOwnedSnapshot(run, previous.result);
544
+ const historicalSha = historicalHeadSha(previous.result.head);
545
+ const artifacts = await revalidateTaskArtifacts(dataDir, run, allEvents, previous.result.artifacts);
546
+ const result = {
547
+ ...previous.result,
548
+ status: run.status,
549
+ outcome,
550
+ lastExecutionOutcome: outcome,
551
+ ...observation,
552
+ ...(run.error ? { error: run.error.slice(0, 2000) } : {}),
553
+ workspace: { ...previous.result.workspace, state: deleted ? 'deleted' : 'unavailable' },
554
+ head: deleted
555
+ ? { state: 'deleted', reason: 'missing', ...(historicalSha ? { sha: historicalSha } : {}) }
556
+ : { state: 'unavailable', reason: 'unverified', ...(historicalSha ? { sha: historicalSha } : {}) },
557
+ artifacts,
558
+ };
559
+ return {
560
+ result,
561
+ ...(previous.diffSnapshot === undefined ? {} : { diffSnapshot: previous.diffSnapshot }),
562
+ source: 'stored',
563
+ };
564
+ }
565
+ async function buildNonWorkerTaskResult(repoRoot, store, run, options) {
566
+ const revision = taskExecutionRevision(run);
567
+ const isActive = options.isActive ?? false;
568
+ const requireLiveDiff = Boolean(options.requireLiveDiff);
569
+ const allEvents = await store.eventLog.readEventsAsync(run.id);
570
+ const dataDir = store.claims.sourceDataDir(run.id);
571
+ const hasLiveWorktree = run.worktree !== false && Boolean(run.worktreePath && existsSync(run.worktreePath));
572
+ const previous = store.taskResults.readTaskResult(run.id);
573
+ if (!requireLiveDiff && previous && canUseStoredNonWorkerSnapshot(run, hasLiveWorktree, previous, revision)) {
574
+ return buildStoredNonWorkerResult(dataDir, run, allEvents, previous, isActive);
575
+ }
576
+ const observation = nonWorkerObservation(run, isActive);
577
+ const outcome = taskExecutionOutcome(run.status);
578
+ const summary = boundedTaskSummary(finalTaskMessage(run, allEvents, { strictScope: false }));
579
+ const artifacts = await listTaskArtifacts(dataDir, run, allEvents);
580
+ const evidence = await selectNonWorkerEvidence(repoRoot, store, run, hasLiveWorktree, previous?.result, requireLiveDiff);
581
+ const baselineSha = evidence.workspace.baselineSha;
582
+ const result = {
583
+ taskId: run.id,
584
+ revision,
585
+ observedAt: (options.now ?? (() => new Date().toISOString()))(),
586
+ status: run.status,
587
+ outcome,
588
+ lastExecutionOutcome: outcome,
589
+ ...observation,
590
+ ...taskOptionalFields(run),
591
+ ...(baselineSha ? { baselineSha } : {}),
592
+ workspace: evidence.workspace,
593
+ summary,
594
+ head: evidence.head,
595
+ diff: evidence.diff,
596
+ artifacts,
597
+ };
598
+ return {
599
+ result,
600
+ ...(evidence.diffSnapshot === undefined ? {} : { diffSnapshot: evidence.diffSnapshot }),
601
+ source: 'live',
602
+ };
603
+ }
604
+ /**
605
+ * Build a result for any task (standalone worktree, `--no-worktree`, or worker).
606
+ * Strictly read-only: takes no claims and writes nothing to disk or `runs.db`.
607
+ */
608
+ export async function buildTaskResult(repoRoot, store, run, options = {}) {
609
+ if (run.delegation?.role === 'worker') {
610
+ if (!store.workerResults || !store.workerExecutions) {
611
+ throw new Error('worker task result requires workerResults and workerExecutions store ports');
612
+ }
613
+ const built = await buildWorkerTaskResult(repoRoot, store, run, options);
614
+ return {
615
+ result: built.storedResult,
616
+ ...(built.diffSnapshot === undefined ? {} : { diffSnapshot: built.diffSnapshot }),
617
+ source: built.source,
618
+ workerResult: built.result,
619
+ };
620
+ }
621
+ return buildNonWorkerTaskResult(repoRoot, store, run, options);
622
+ }
623
+ /**
624
+ * Read-only entry point for operator, CLI, MCP, and cockpit surfaces (S3).
625
+ * Never writes to disk or `runs.db`, takes no claims, and never falls back to the real Git index.
626
+ */
627
+ export async function readPublicTaskResult(repoRoot, store, run, options = {}) {
628
+ const built = await buildTaskResult(repoRoot, store, run, options);
629
+ return toPublicTaskResult(built.result, {
630
+ source: built.source,
631
+ ...(built.diffSnapshot === undefined ? {} : { diffSnapshot: built.diffSnapshot }),
632
+ ...(options.includeDiff === undefined ? {} : { includeDiff: options.includeDiff }),
633
+ ...(options.maxChars === undefined ? {} : { maxChars: options.maxChars }),
634
+ });
635
+ }
636
+ //# sourceMappingURL=task-result-builder.js.map