@fish-under-sea/dsh-agent-teams-fish 1.0.2 → 2.0.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 (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
@@ -0,0 +1,487 @@
1
+ /**
2
+ * Workspace byte identity: the only module in this plugin that reads artifact
3
+ * bytes off disk.
4
+ *
5
+ * Two plugin surfaces need it:
6
+ * · a quality verdict must record which revision it judged (issue #161), so
7
+ * delivery can refuse to advertise bytes no review ever saw;
8
+ * · an auto-generated work order must record the workspace it was derived
9
+ * from (issue #174), so it can be marked stale after a later round edits a
10
+ * cited file.
11
+ *
12
+ * Safety rules this module must never lose:
13
+ * · directory traversal never follows symlinks, and every explicitly named
14
+ * path is resolved with `realpath` and rejected when it leaves the
15
+ * workspace — a symlink must not become a read of arbitrary host files, and
16
+ * a symlink cycle must not become an infinite walk;
17
+ * · a scope that cannot be enumerated completely (file cap, unreadable
18
+ * directory, non-workspace-relative path) produces an explicit
19
+ * {@link ArtifactScopeGap} instead of a short list that reads as complete;
20
+ * · "could not be read" is recorded separately from "does not exist";
21
+ * · plugins and secrets never enter a broad scope by accident.
22
+ *
23
+ * The gate rules themselves stay pure: they receive {@link ArtifactDigest}
24
+ * values from here and never touch the filesystem.
25
+ * @module dsh-agent-teams/artifacts
26
+ */
27
+
28
+ import { createHash } from 'node:crypto'
29
+ import { closeSync, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync, type BigIntStats } from 'node:fs'
30
+ import { isAbsolute, join, relative, sep } from 'node:path'
31
+ import { isDefaultExcludedPath, normalizeWorkspacePath } from './quality-gates.ts'
32
+ import type { ArtifactDigest, ArtifactScopeGap, ArtifactSnapshot } from './types.ts'
33
+
34
+ /**
35
+ * Directory segments never walked when a scope pattern names a directory:
36
+ * version control, the harness state root, plugin-private team state, and
37
+ * installed packages. They are either huge, plugin-private, or not project
38
+ * artifacts.
39
+ */
40
+ const SKIPPED_SEGMENTS = new Set(['.git', '.dsh', '.agent-teams', 'node_modules'])
41
+
42
+ /**
43
+ * Upper bound on files expanded from one scope. Verdicts are about a revision
44
+ * and an unbounded walk of a large tree would make every gate close slow, so
45
+ * the walk stops here — and says so with a gap, because a silently truncated
46
+ * list would let a change outside the list pass as "unchanged".
47
+ */
48
+ export const MAX_EXPANDED_ARTIFACTS = 200
49
+
50
+ /** Result of reading a declared scope: what was read, and what could not be. */
51
+ export interface ArtifactScopeRead {
52
+ artifacts: ArtifactDigest[]
53
+ gaps: ArtifactScopeGap[]
54
+ }
55
+
56
+ type PathOutcome =
57
+ | { kind: 'file'; digest: ArtifactDigest; stamp: string }
58
+ | { kind: 'directory' }
59
+ | { kind: 'absent' }
60
+ | { kind: 'unreadable'; reason: string }
61
+
62
+ function errorCode(error: unknown): string {
63
+ const code = (error as NodeJS.ErrnoException | undefined)?.code
64
+ return typeof code === 'string' ? code : 'EIO'
65
+ }
66
+
67
+ function workspaceRootOf(workspace: string): string | undefined {
68
+ try {
69
+ return realpathSync(workspace)
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ /** Is `absolute` (already resolved) inside the workspace root? */
76
+ function insideRoot(root: string, absolute: string): boolean {
77
+ const rel = relative(root, absolute)
78
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
79
+ }
80
+
81
+ /** `true` inside, `false` escapes the workspace, `undefined` unresolvable. */
82
+ function resolvesInside(root: string, absolute: string): boolean | undefined {
83
+ try {
84
+ return insideRoot(root, realpathSync(absolute))
85
+ } catch {
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Chunk size for the streaming digest. The activity panel polls the audit
92
+ * about once a second, so hashing must never read a whole artifact into
93
+ * memory: a multi-gigabyte file would otherwise stall the host process.
94
+ */
95
+ const HASH_CHUNK_BYTES = 64 * 1024
96
+
97
+ // These stamps only invalidate a read made in this audit. Matching timestamps
98
+ // never replace hashing, and no stamp/digest is reused by a later audit.
99
+ function fileVersion(stats: BigIntStats): string {
100
+ return [stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeNs, stats.ctimeNs].join(':')
101
+ }
102
+
103
+ function changedDuringRead(): Error {
104
+ return Object.assign(new Error('artifact changed while its bytes were being read'), { code: 'ESTALE' })
105
+ }
106
+
107
+ function pathStamp(workspaceRoot: string, absolute: string): string {
108
+ const resolved = realpathSync(absolute)
109
+ if (!insideRoot(workspaceRoot, resolved)) throw changedDuringRead()
110
+ return `${resolved}\0${fileVersion(statSync(absolute, { bigint: true }))}`
111
+ }
112
+
113
+ /**
114
+ * sha256 one file in constant memory (one reusable chunk buffer), never
115
+ * loading the whole artifact. Throws the underlying filesystem error so the
116
+ * caller can distinguish "cannot read" from "absent".
117
+ */
118
+ function hashFileConstantMemory(workspaceRoot: string, absolute: string): { sha256: string; size: number; stamp: string; mtimeMs: number } {
119
+ const resolved = realpathSync(absolute)
120
+ if (!insideRoot(workspaceRoot, resolved)) throw changedDuringRead()
121
+ const expected = statSync(resolved, { bigint: true })
122
+ const handle = openSync(resolved, 'r')
123
+ try {
124
+ const before = fstatSync(handle, { bigint: true })
125
+ const stamp = `${resolved}\0${fileVersion(before)}`
126
+ if (!before.isFile() || fileVersion(expected) !== fileVersion(before) || pathStamp(workspaceRoot, absolute) !== stamp) throw changedDuringRead()
127
+ const hash = createHash('sha256')
128
+ const buffer = Buffer.allocUnsafe(HASH_CHUNK_BYTES)
129
+ let size = 0
130
+ for (;;) {
131
+ const read = readSync(handle, buffer, 0, buffer.byteLength, null)
132
+ if (read <= 0) break
133
+ size += read
134
+ // `update` consumes the bytes synchronously, so the buffer is reused.
135
+ hash.update(read === buffer.byteLength ? buffer : buffer.subarray(0, read))
136
+ }
137
+ if (fileVersion(before) !== fileVersion(fstatSync(handle, { bigint: true })) || pathStamp(workspaceRoot, absolute) !== stamp) throw changedDuringRead()
138
+ return { sha256: hash.digest('hex'), size, stamp, mtimeMs: Number(before.mtimeNs) / 1_000_000 }
139
+ } finally {
140
+ closeSync(handle)
141
+ }
142
+ }
143
+ function inspectPath(workspaceRoot: string | undefined, workspace: string, normalized: string): PathOutcome {
144
+ const absolute = join(workspace, normalized)
145
+ let stats
146
+ try {
147
+ stats = lstatSync(absolute)
148
+ } catch (error) {
149
+ const code = errorCode(error)
150
+ return code === 'ENOENT' || code === 'ENOTDIR'
151
+ ? { kind: 'absent' }
152
+ : { kind: 'unreadable', reason: `${normalized} cannot be inspected (${code})` }
153
+ }
154
+ if (workspaceRoot === undefined) {
155
+ return { kind: 'unreadable', reason: `${normalized} cannot be verified against the workspace root` }
156
+ }
157
+ // Containment is checked on the fully resolved path, not only when the last
158
+ // segment is a symlink: an intermediate symlinked directory would otherwise
159
+ // let any inner path read (or walk) host files outside the workspace.
160
+ const inside = resolvesInside(workspaceRoot, absolute)
161
+ if (inside === undefined) return { kind: 'unreadable', reason: `${normalized} cannot be resolved (broken or cyclic link)` }
162
+ if (!inside) return { kind: 'unreadable', reason: `${normalized} resolves outside the workspace; refusing to read it` }
163
+ if (stats.isSymbolicLink()) {
164
+ try {
165
+ stats = statSync(absolute)
166
+ } catch (error) {
167
+ return { kind: 'unreadable', reason: `${normalized} symlink target cannot be inspected (${errorCode(error)})` }
168
+ }
169
+ }
170
+ if (stats.isDirectory()) return { kind: 'directory' }
171
+ if (!stats.isFile()) return { kind: 'unreadable', reason: `${normalized} is not a regular file` }
172
+ try {
173
+ const { sha256, size, stamp, mtimeMs } = hashFileConstantMemory(workspaceRoot, absolute)
174
+ return {
175
+ kind: 'file',
176
+ stamp,
177
+ digest: {
178
+ path: normalized,
179
+ present: true,
180
+ sha256,
181
+ size,
182
+ mtimeMs,
183
+ },
184
+ }
185
+ } catch (error) {
186
+ return { kind: 'unreadable', reason: `${normalized} cannot be read (${errorCode(error)})` }
187
+ }
188
+ }
189
+
190
+ function isSkipped(relativePath: string): boolean {
191
+ return relativePath.split('/').some((segment) => SKIPPED_SEGMENTS.has(segment)) || isDefaultExcludedPath(relativePath)
192
+ }
193
+
194
+ interface ScopeEntry {
195
+ path: string
196
+ directory: boolean
197
+ }
198
+
199
+ /** Enumeration and revalidation must apply the same scope boundaries. */
200
+ function listScopeEntries(absolute: string, prefix: string): ScopeEntry[] {
201
+ const entries: ScopeEntry[] = []
202
+ for (const entry of readdirSync(absolute, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
203
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`
204
+ // Traversal never follows symlinks: a symlinked directory can point
205
+ // outside the workspace or form a cycle.
206
+ if (entry.isSymbolicLink() || isSkipped(path)) continue
207
+ if (entry.isDirectory()) entries.push({ path, directory: true })
208
+ else if (entry.isFile()) entries.push({ path, directory: false })
209
+ }
210
+ return entries
211
+ }
212
+
213
+ function directorySignature(absolute: string, entries: readonly ScopeEntry[]): string {
214
+ return `${realpathSync(absolute)}\0${JSON.stringify(entries)}`
215
+ }
216
+
217
+ function walkDirectory(input: {
218
+ workspace: string
219
+ workspaceRoot: string | undefined
220
+ pattern: string
221
+ prefix: string
222
+ push: (path: string) => void
223
+ gap: (reason: string) => void
224
+ full: () => boolean
225
+ observe: (prefix: string, signature: string) => void
226
+ }): void {
227
+ // The prefix itself must be inside the workspace before it is enumerated:
228
+ // `escape/` may be a symlink to an outside directory, and readdir would
229
+ // happily list host names through it. Nested prefixes come from
230
+ // non-symlink directory entries of an already-verified parent.
231
+ if (input.prefix !== '') {
232
+ if (input.workspaceRoot === undefined) {
233
+ input.gap(`${input.pattern}: the workspace root cannot be resolved, so it is not enumerated`)
234
+ return
235
+ }
236
+ let inside: boolean | undefined
237
+ try {
238
+ inside = insideRoot(input.workspaceRoot, realpathSync(join(input.workspace, input.prefix)))
239
+ } catch (error) {
240
+ if (errorCode(error) === 'ENOENT' || errorCode(error) === 'ENOTDIR') {
241
+ input.gap(`${input.pattern}: ${input.prefix} does not exist, so the scope could not be enumerated`)
242
+ return
243
+ }
244
+ inside = undefined
245
+ }
246
+ if (inside === undefined) {
247
+ input.gap(`${input.pattern}: ${input.prefix} cannot be resolved (broken or cyclic link); refusing to enumerate it`)
248
+ return
249
+ }
250
+ if (!inside) {
251
+ input.gap(`${input.pattern}: ${input.prefix} resolves outside the workspace; refusing to enumerate it`)
252
+ return
253
+ }
254
+ }
255
+ const queue = input.prefix === '' ? [''] : [input.prefix]
256
+ while (queue.length > 0) {
257
+ const current = queue.shift() as string
258
+ let entries: ScopeEntry[]
259
+ try {
260
+ const absolute = join(input.workspace, current)
261
+ // A queued child may have been replaced after its parent was listed.
262
+ // Recheck containment before enumeration and never follow a new nested
263
+ // symlink (an explicitly declared, in-workspace prefix remains allowed).
264
+ if (input.workspaceRoot === undefined || resolvesInside(input.workspaceRoot, absolute) !== true
265
+ || (current !== input.prefix && lstatSync(absolute).isSymbolicLink())) {
266
+ input.gap(`${input.pattern}: ${current || '.'} changed or cannot be resolved inside the workspace; refusing to enumerate it`)
267
+ continue
268
+ }
269
+ entries = listScopeEntries(absolute, current)
270
+ if (resolvesInside(input.workspaceRoot, absolute) !== true) {
271
+ input.gap(`${input.pattern}: ${current || '.'} changed during enumeration; refusing to use its entries`)
272
+ continue
273
+ }
274
+ input.observe(current, directorySignature(absolute, entries))
275
+ } catch (error) {
276
+ input.gap(`${input.pattern}: cannot list ${current === '' ? '.' : current} (${errorCode(error)})`)
277
+ continue
278
+ }
279
+ for (const entry of entries) {
280
+ if (entry.directory) {
281
+ queue.push(entry.path)
282
+ continue
283
+ }
284
+ if (input.full()) {
285
+ input.gap(`${input.pattern}: stopped at the ${MAX_EXPANDED_ARTIFACTS}-file cap, so its contents are only partially recorded`)
286
+ return
287
+ }
288
+ input.push(entry.path)
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Read a declared scope: expand directory patterns to their current files,
295
+ * keep explicitly named paths even when they do not exist (a later creation is
296
+ * drift too), and report every part that could not be fully resolved.
297
+ */
298
+ function readScope(
299
+ workspace: string,
300
+ patterns: readonly string[],
301
+ inspect: (normalized: string) => PathOutcome,
302
+ observe: (prefix: string, signature: string) => void,
303
+ ): ArtifactScopeRead {
304
+ const workspaceRoot = workspaceRootOf(workspace)
305
+ const gaps: ArtifactScopeGap[] = []
306
+ const concrete: string[] = []
307
+ const seen = new Set<string>()
308
+ const full = (): boolean => concrete.length >= MAX_EXPANDED_ARTIFACTS
309
+ const push = (path: string): void => {
310
+ if (seen.has(path)) return
311
+ seen.add(path)
312
+ concrete.push(path)
313
+ }
314
+ const gap = (pattern: string, reason: string): void => {
315
+ if (gaps.some((item) => item.pattern === pattern && item.reason === reason)) return
316
+ gaps.push({ pattern, reason })
317
+ }
318
+ for (const raw of patterns) {
319
+ if (typeof raw !== 'string') continue
320
+ const trimmed = raw.trim()
321
+ const posix = trimmed.replaceAll('\\', '/')
322
+ const directory = posix.endsWith('/') || posix === '.'
323
+ const normalized = normalizeWorkspacePath(raw)
324
+ if (normalized === undefined) {
325
+ // Absolute paths, `..`, `~`, drive letters: illegal, and never a reason
326
+ // to fall back to the workspace root.
327
+ gap(trimmed, 'not a workspace-relative path (absolute paths and ".." can never match scope)')
328
+ continue
329
+ }
330
+ if (!directory) {
331
+ if (normalized === '') {
332
+ gap(trimmed, 'empty path is not a file; use "." for the whole workspace')
333
+ continue
334
+ }
335
+ if (full()) {
336
+ gap(trimmed, `stopped at the ${MAX_EXPANDED_ARTIFACTS}-path cap, so the scope is only partially recorded`)
337
+ continue
338
+ }
339
+ push(normalized)
340
+ continue
341
+ }
342
+ // Only an explicitly root-anchored pattern means the workspace root.
343
+ const rootAnchored = posix === '.' || posix === './' || posix.startsWith('./')
344
+ if (normalized === '' && !rootAnchored) {
345
+ gap(trimmed, 'unresolved directory pattern; use "./" explicitly for the workspace root')
346
+ continue
347
+ }
348
+ if (full()) {
349
+ gap(trimmed, `stopped at the ${MAX_EXPANDED_ARTIFACTS}-path cap, so its contents are only partially recorded`)
350
+ continue
351
+ }
352
+ walkDirectory({ workspace, workspaceRoot, pattern: trimmed, prefix: normalized, push, gap: (reason) => gap(trimmed, reason), full, observe })
353
+ }
354
+ const artifacts: ArtifactDigest[] = []
355
+ // Index-based: expanding an explicitly named directory appends its files to
356
+ // `concrete`, and those must be digested in the same pass.
357
+ for (let index = 0; index < concrete.length; index += 1) {
358
+ const normalized = concrete[index] as string
359
+ const outcome = inspect(normalized)
360
+ if (outcome.kind === 'file') {
361
+ artifacts.push(outcome.digest)
362
+ continue
363
+ }
364
+ if (outcome.kind === 'directory') {
365
+ // An explicitly named directory is expanded instead of being reported as
366
+ // unreadable: `src/lib` and `src/lib/` must behave the same.
367
+ walkDirectory({ workspace, workspaceRoot, pattern: normalized, prefix: normalized, push, gap: (reason) => gap(normalized, reason), full, observe })
368
+ continue
369
+ }
370
+ if (outcome.kind === 'absent') {
371
+ artifacts.push({ path: normalized, present: false })
372
+ continue
373
+ }
374
+ artifacts.push({ path: normalized, present: false, unreadable: true, reason: outcome.reason })
375
+ }
376
+ return { artifacts: artifacts.sort((a, b) => a.path.localeCompare(b.path)), gaps }
377
+ }
378
+
379
+ /**
380
+ * Read related scopes in one audit. Each scope retains its own expansion cap
381
+ * and gaps, but overlapping paths hash only once. A final revalidation rejects
382
+ * changed file identities and changed directory membership instead of handing
383
+ * out a mixture of revisions as complete evidence.
384
+ */
385
+ export function readArtifactScopes(workspace: string, scopes: readonly (readonly string[])[]): ArtifactScopeRead[] {
386
+ const root = workspaceRootOf(workspace)
387
+ const paths = new Map<string, PathOutcome>()
388
+ const directories = new Map<string, string>()
389
+ const changedDirectories = new Set<string>()
390
+ const inspect = (normalized: string): PathOutcome => {
391
+ let outcome = paths.get(normalized)
392
+ if (outcome === undefined) {
393
+ outcome = inspectPath(root, workspace, normalized)
394
+ paths.set(normalized, outcome)
395
+ }
396
+ return outcome
397
+ }
398
+ const observe = (prefix: string, signature: string): void => {
399
+ const prior = directories.get(prefix)
400
+ if (prior !== undefined && prior !== signature) changedDirectories.add(prefix)
401
+ directories.set(prefix, signature)
402
+ }
403
+ const reads = scopes.map(patterns => readScope(workspace, patterns, inspect, observe))
404
+ const changed = new Map<string, string>()
405
+ for (const [path, outcome] of paths) {
406
+ try {
407
+ if (outcome.kind === 'file' && (root === undefined || pathStamp(root, join(workspace, path)) !== outcome.stamp)) {
408
+ changed.set(path, `${path} changed during the workspace audit; retry a stable revision`)
409
+ } else if (outcome.kind === 'absent') {
410
+ try {
411
+ lstatSync(join(workspace, path))
412
+ changed.set(path, `${path} appeared during the workspace audit; retry a stable revision`)
413
+ } catch (error) {
414
+ if (errorCode(error) !== 'ENOENT' && errorCode(error) !== 'ENOTDIR') throw error
415
+ }
416
+ }
417
+ } catch {
418
+ changed.set(path, `${path} could not be revalidated after reading; the workspace audit is incomplete`)
419
+ }
420
+ }
421
+ const gaps: ArtifactScopeGap[] = []
422
+ for (const [prefix, signature] of directories) {
423
+ try {
424
+ const absolute = join(workspace, prefix)
425
+ if (root === undefined || resolvesInside(root, absolute) !== true
426
+ || directorySignature(absolute, listScopeEntries(absolute, prefix)) !== signature) changedDirectories.add(prefix)
427
+ } catch {
428
+ changedDirectories.add(prefix)
429
+ }
430
+ }
431
+ for (const prefix of changedDirectories) gaps.push({ pattern: prefix || '.', reason: 'directory membership changed or could not be revalidated during the workspace audit; retry a stable revision' })
432
+ for (const [path, reason] of changed) gaps.push({ pattern: path, reason })
433
+ for (const read of reads) {
434
+ read.artifacts = read.artifacts.map(artifact => changed.has(artifact.path)
435
+ ? { path: artifact.path, present: false, unreadable: true, reason: changed.get(artifact.path) as string }
436
+ : artifact)
437
+ read.gaps.push(...gaps)
438
+ }
439
+ return reads
440
+ }
441
+
442
+ /** Read one scope without retaining byte identities for the next request. */
443
+ export function readArtifactScope(workspace: string, patterns: readonly string[]): ArtifactScopeRead {
444
+ return readArtifactScopes(workspace, [patterns])[0] as ArtifactScopeRead
445
+ }
446
+
447
+ /**
448
+ * Read the current bytes of workspace-relative paths (directories expand).
449
+ * Illegal and unreadable paths are reported, never silently dropped.
450
+ */
451
+ export function digestWorkspacePaths(workspace: string, paths: readonly string[]): ArtifactDigest[] {
452
+ return readArtifactScope(workspace, paths).artifacts
453
+ }
454
+
455
+ /**
456
+ * Does this workspace-relative path currently exist as a file or directory?
457
+ * Uses the same containment rules as the digest reader: a symlink that leaves
458
+ * the workspace is not "an existing workspace path".
459
+ */
460
+ export function workspacePathExists(workspace: string, path: string): boolean {
461
+ const normalized = normalizeWorkspacePath(path)
462
+ if (normalized === undefined) return false
463
+ const outcome = inspectPath(workspaceRootOf(workspace), workspace, normalized)
464
+ return outcome.kind === 'file' || outcome.kind === 'directory'
465
+ }
466
+
467
+ /** Expand scope patterns to the concrete files they currently cover. */
468
+ export function expandScopePaths(workspace: string, patterns: readonly string[]): string[] {
469
+ return readArtifactScope(workspace, patterns)
470
+ .artifacts
471
+ .filter((artifact) => artifact.present)
472
+ .map((artifact) => artifact.path)
473
+ .sort()
474
+ }
475
+
476
+ /**
477
+ * Read one coherent snapshot of the given scope patterns. Directory patterns
478
+ * expand to the files they currently contain; a pattern naming a path that
479
+ * does not exist is recorded as `present: false` so a later creation or
480
+ * deletion is visible as drift, and any incomplete coverage is carried in
481
+ * `gaps`.
482
+ */
483
+ export function snapshotWorkspacePaths(workspace: string, patterns: readonly string[]): ArtifactSnapshot {
484
+ const at = Date.now()
485
+ const { artifacts, gaps } = readArtifactScope(workspace, patterns)
486
+ return { at, artifacts, ...gaps.length === 0 ? {} : { gaps } }
487
+ }