| 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 | import { createHash } from 'node:crypto'; |
| 28 | import { closeSync, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs'; |
| 29 | import { isAbsolute, join, relative, sep } from 'node:path'; |
| 30 | import { isDefaultExcludedPath, normalizeWorkspacePath } from "./quality-gates.js"; |
| 31 | /** |
| 32 | * Directory segments never walked when a scope pattern names a directory: |
| 33 | * version control, the harness state root, plugin-private team state, and |
| 34 | * installed packages. They are either huge, plugin-private, or not project |
| 35 | * artifacts. |
| 36 | */ |
| 37 | const SKIPPED_SEGMENTS = new Set(['.git', '.dsh', '.agent-teams', 'node_modules']); |
| 38 | /** |
| 39 | * Upper bound on files expanded from one scope. Verdicts are about a revision |
| 40 | * and an unbounded walk of a large tree would make every gate close slow, so |
| 41 | * the walk stops here — and says so with a gap, because a silently truncated |
| 42 | * list would let a change outside the list pass as "unchanged". |
| 43 | */ |
| 44 | export const MAX_EXPANDED_ARTIFACTS = 200; |
| 45 | function errorCode(error) { |
| 46 | const code = error?.code; |
| 47 | return typeof code === 'string' ? code : 'EIO'; |
| 48 | } |
| 49 | function workspaceRootOf(workspace) { |
| 50 | try { |
| 51 | return realpathSync(workspace); |
| 52 | } |
| 53 | catch { |
| 54 | return undefined; |
| 55 | } |
| 56 | } |
| 57 | /** Is `absolute` (already resolved) inside the workspace root? */ |
| 58 | function insideRoot(root, absolute) { |
| 59 | const rel = relative(root, absolute); |
| 60 | return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); |
| 61 | } |
| 62 | /** `true` inside, `false` escapes the workspace, `undefined` unresolvable. */ |
| 63 | function resolvesInside(root, absolute) { |
| 64 | try { |
| 65 | return insideRoot(root, realpathSync(absolute)); |
| 66 | } |
| 67 | catch { |
| 68 | return undefined; |
| 69 | } |
| 70 | } |
| 71 | /** |
| 72 | * Chunk size for the streaming digest. The activity panel polls the audit |
| 73 | * about once a second, so hashing must never read a whole artifact into |
| 74 | * memory: a multi-gigabyte file would otherwise stall the host process. |
| 75 | */ |
| 76 | const HASH_CHUNK_BYTES = 64 * 1024; |
| 77 | // These stamps only invalidate a read made in this audit. Matching timestamps |
| 78 | // never replace hashing, and no stamp/digest is reused by a later audit. |
| 79 | function fileVersion(stats) { |
| 80 | return [stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeNs, stats.ctimeNs].join(':'); |
| 81 | } |
| 82 | function changedDuringRead() { |
| 83 | return Object.assign(new Error('artifact changed while its bytes were being read'), { code: 'ESTALE' }); |
| 84 | } |
| 85 | function pathStamp(workspaceRoot, absolute) { |
| 86 | const resolved = realpathSync(absolute); |
| 87 | if (!insideRoot(workspaceRoot, resolved)) |
| 88 | throw changedDuringRead(); |
| 89 | return `${resolved}\0${fileVersion(statSync(absolute, { bigint: true }))}`; |
| 90 | } |
| 91 | /** |
| 92 | * sha256 one file in constant memory (one reusable chunk buffer), never |
| 93 | * loading the whole artifact. Throws the underlying filesystem error so the |
| 94 | * caller can distinguish "cannot read" from "absent". |
| 95 | */ |
| 96 | function hashFileConstantMemory(workspaceRoot, absolute) { |
| 97 | const resolved = realpathSync(absolute); |
| 98 | if (!insideRoot(workspaceRoot, resolved)) |
| 99 | throw changedDuringRead(); |
| 100 | const expected = statSync(resolved, { bigint: true }); |
| 101 | const handle = openSync(resolved, 'r'); |
| 102 | try { |
| 103 | const before = fstatSync(handle, { bigint: true }); |
| 104 | const stamp = `${resolved}\0${fileVersion(before)}`; |
| 105 | if (!before.isFile() || fileVersion(expected) !== fileVersion(before) || pathStamp(workspaceRoot, absolute) !== stamp) |
| 106 | throw changedDuringRead(); |
| 107 | const hash = createHash('sha256'); |
| 108 | const buffer = Buffer.allocUnsafe(HASH_CHUNK_BYTES); |
| 109 | let size = 0; |
| 110 | for (;;) { |
| 111 | const read = readSync(handle, buffer, 0, buffer.byteLength, null); |
| 112 | if (read <= 0) |
| 113 | break; |
| 114 | size += read; |
| 115 | // `update` consumes the bytes synchronously, so the buffer is reused. |
| 116 | hash.update(read === buffer.byteLength ? buffer : buffer.subarray(0, read)); |
| 117 | } |
| 118 | if (fileVersion(before) !== fileVersion(fstatSync(handle, { bigint: true })) || pathStamp(workspaceRoot, absolute) !== stamp) |
| 119 | throw changedDuringRead(); |
| 120 | return { sha256: hash.digest('hex'), size, stamp, mtimeMs: Number(before.mtimeNs) / 1_000_000 }; |
| 121 | } |
| 122 | finally { |
| 123 | closeSync(handle); |
| 124 | } |
| 125 | } |
| 126 | function inspectPath(workspaceRoot, workspace, normalized) { |
| 127 | const absolute = join(workspace, normalized); |
| 128 | let stats; |
| 129 | try { |
| 130 | stats = lstatSync(absolute); |
| 131 | } |
| 132 | catch (error) { |
| 133 | const code = errorCode(error); |
| 134 | return code === 'ENOENT' || code === 'ENOTDIR' |
| 135 | ? { kind: 'absent' } |
| 136 | : { kind: 'unreadable', reason: `${normalized} cannot be inspected (${code})` }; |
| 137 | } |
| 138 | if (workspaceRoot === undefined) { |
| 139 | return { kind: 'unreadable', reason: `${normalized} cannot be verified against the workspace root` }; |
| 140 | } |
| 141 | // Containment is checked on the fully resolved path, not only when the last |
| 142 | // segment is a symlink: an intermediate symlinked directory would otherwise |
| 143 | // let any inner path read (or walk) host files outside the workspace. |
| 144 | const inside = resolvesInside(workspaceRoot, absolute); |
| 145 | if (inside === undefined) |
| 146 | return { kind: 'unreadable', reason: `${normalized} cannot be resolved (broken or cyclic link)` }; |
| 147 | if (!inside) |
| 148 | return { kind: 'unreadable', reason: `${normalized} resolves outside the workspace; refusing to read it` }; |
| 149 | if (stats.isSymbolicLink()) { |
| 150 | try { |
| 151 | stats = statSync(absolute); |
| 152 | } |
| 153 | catch (error) { |
| 154 | return { kind: 'unreadable', reason: `${normalized} symlink target cannot be inspected (${errorCode(error)})` }; |
| 155 | } |
| 156 | } |
| 157 | if (stats.isDirectory()) |
| 158 | return { kind: 'directory' }; |
| 159 | if (!stats.isFile()) |
| 160 | return { kind: 'unreadable', reason: `${normalized} is not a regular file` }; |
| 161 | try { |
| 162 | const { sha256, size, stamp, mtimeMs } = hashFileConstantMemory(workspaceRoot, absolute); |
| 163 | return { |
| 164 | kind: 'file', |
| 165 | stamp, |
| 166 | digest: { |
| 167 | path: normalized, |
| 168 | present: true, |
| 169 | sha256, |
| 170 | size, |
| 171 | mtimeMs, |
| 172 | }, |
| 173 | }; |
| 174 | } |
| 175 | catch (error) { |
| 176 | return { kind: 'unreadable', reason: `${normalized} cannot be read (${errorCode(error)})` }; |
| 177 | } |
| 178 | } |
| 179 | function isSkipped(relativePath) { |
| 180 | return relativePath.split('/').some((segment) => SKIPPED_SEGMENTS.has(segment)) || isDefaultExcludedPath(relativePath); |
| 181 | } |
| 182 | /** Enumeration and revalidation must apply the same scope boundaries. */ |
| 183 | function listScopeEntries(absolute, prefix) { |
| 184 | const entries = []; |
| 185 | for (const entry of readdirSync(absolute, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { |
| 186 | const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`; |
| 187 | // Traversal never follows symlinks: a symlinked directory can point |
| 188 | // outside the workspace or form a cycle. |
| 189 | if (entry.isSymbolicLink() || isSkipped(path)) |
| 190 | continue; |
| 191 | if (entry.isDirectory()) |
| 192 | entries.push({ path, directory: true }); |
| 193 | else if (entry.isFile()) |
| 194 | entries.push({ path, directory: false }); |
| 195 | } |
| 196 | return entries; |
| 197 | } |
| 198 | function directorySignature(absolute, entries) { |
| 199 | return `${realpathSync(absolute)}\0${JSON.stringify(entries)}`; |
| 200 | } |
| 201 | function walkDirectory(input) { |
| 202 | // The prefix itself must be inside the workspace before it is enumerated: |
| 203 | // `escape/` may be a symlink to an outside directory, and readdir would |
| 204 | // happily list host names through it. Nested prefixes come from |
| 205 | // non-symlink directory entries of an already-verified parent. |
| 206 | if (input.prefix !== '') { |
| 207 | if (input.workspaceRoot === undefined) { |
| 208 | input.gap(`${input.pattern}: the workspace root cannot be resolved, so it is not enumerated`); |
| 209 | return; |
| 210 | } |
| 211 | let inside; |
| 212 | try { |
| 213 | inside = insideRoot(input.workspaceRoot, realpathSync(join(input.workspace, input.prefix))); |
| 214 | } |
| 215 | catch (error) { |
| 216 | if (errorCode(error) === 'ENOENT' || errorCode(error) === 'ENOTDIR') { |
| 217 | input.gap(`${input.pattern}: ${input.prefix} does not exist, so the scope could not be enumerated`); |
| 218 | return; |
| 219 | } |
| 220 | inside = undefined; |
| 221 | } |
| 222 | if (inside === undefined) { |
| 223 | input.gap(`${input.pattern}: ${input.prefix} cannot be resolved (broken or cyclic link); refusing to enumerate it`); |
| 224 | return; |
| 225 | } |
| 226 | if (!inside) { |
| 227 | input.gap(`${input.pattern}: ${input.prefix} resolves outside the workspace; refusing to enumerate it`); |
| 228 | return; |
| 229 | } |
| 230 | } |
| 231 | const queue = input.prefix === '' ? [''] : [input.prefix]; |
| 232 | while (queue.length > 0) { |
| 233 | const current = queue.shift(); |
| 234 | let entries; |
| 235 | try { |
| 236 | const absolute = join(input.workspace, current); |
| 237 | // A queued child may have been replaced after its parent was listed. |
| 238 | // Recheck containment before enumeration and never follow a new nested |
| 239 | // symlink (an explicitly declared, in-workspace prefix remains allowed). |
| 240 | if (input.workspaceRoot === undefined || resolvesInside(input.workspaceRoot, absolute) !== true |
| 241 | || (current !== input.prefix && lstatSync(absolute).isSymbolicLink())) { |
| 242 | input.gap(`${input.pattern}: ${current || '.'} changed or cannot be resolved inside the workspace; refusing to enumerate it`); |
| 243 | continue; |
| 244 | } |
| 245 | entries = listScopeEntries(absolute, current); |
| 246 | if (resolvesInside(input.workspaceRoot, absolute) !== true) { |
| 247 | input.gap(`${input.pattern}: ${current || '.'} changed during enumeration; refusing to use its entries`); |
| 248 | continue; |
| 249 | } |
| 250 | input.observe(current, directorySignature(absolute, entries)); |
| 251 | } |
| 252 | catch (error) { |
| 253 | input.gap(`${input.pattern}: cannot list ${current === '' ? '.' : current} (${errorCode(error)})`); |
| 254 | continue; |
| 255 | } |
| 256 | for (const entry of entries) { |
| 257 | if (entry.directory) { |
| 258 | queue.push(entry.path); |
| 259 | continue; |
| 260 | } |
| 261 | if (input.full()) { |
| 262 | input.gap(`${input.pattern}: stopped at the ${MAX_EXPANDED_ARTIFACTS}-file cap, so its contents are only partially recorded`); |
| 263 | return; |
| 264 | } |
| 265 | input.push(entry.path); |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | /** |
| 270 | * Read a declared scope: expand directory patterns to their current files, |
| 271 | * keep explicitly named paths even when they do not exist (a later creation is |
| 272 | * drift too), and report every part that could not be fully resolved. |
| 273 | */ |
| 274 | function readScope(workspace, patterns, inspect, observe) { |
| 275 | const workspaceRoot = workspaceRootOf(workspace); |
| 276 | const gaps = []; |
| 277 | const concrete = []; |
| 278 | const seen = new Set(); |
| 279 | const full = () => concrete.length >= MAX_EXPANDED_ARTIFACTS; |
| 280 | const push = (path) => { |
| 281 | if (seen.has(path)) |
| 282 | return; |
| 283 | seen.add(path); |
| 284 | concrete.push(path); |
| 285 | }; |
| 286 | const gap = (pattern, reason) => { |
| 287 | if (gaps.some((item) => item.pattern === pattern && item.reason === reason)) |
| 288 | return; |
| 289 | gaps.push({ pattern, reason }); |
| 290 | }; |
| 291 | for (const raw of patterns) { |
| 292 | if (typeof raw !== 'string') |
| 293 | continue; |
| 294 | const trimmed = raw.trim(); |
| 295 | const posix = trimmed.replaceAll('\\', '/'); |
| 296 | const directory = posix.endsWith('/') || posix === '.'; |
| 297 | const normalized = normalizeWorkspacePath(raw); |
| 298 | if (normalized === undefined) { |
| 299 | // Absolute paths, `..`, `~`, drive letters: illegal, and never a reason |
| 300 | // to fall back to the workspace root. |
| 301 | gap(trimmed, 'not a workspace-relative path (absolute paths and ".." can never match scope)'); |
| 302 | continue; |
| 303 | } |
| 304 | if (!directory) { |
| 305 | if (normalized === '') { |
| 306 | gap(trimmed, 'empty path is not a file; use "." for the whole workspace'); |
| 307 | continue; |
| 308 | } |
| 309 | if (full()) { |
| 310 | gap(trimmed, `stopped at the ${MAX_EXPANDED_ARTIFACTS}-path cap, so the scope is only partially recorded`); |
| 311 | continue; |
| 312 | } |
| 313 | push(normalized); |
| 314 | continue; |
| 315 | } |
| 316 | // Only an explicitly root-anchored pattern means the workspace root. |
| 317 | const rootAnchored = posix === '.' || posix === './' || posix.startsWith('./'); |
| 318 | if (normalized === '' && !rootAnchored) { |
| 319 | gap(trimmed, 'unresolved directory pattern; use "./" explicitly for the workspace root'); |
| 320 | continue; |
| 321 | } |
| 322 | if (full()) { |
| 323 | gap(trimmed, `stopped at the ${MAX_EXPANDED_ARTIFACTS}-path cap, so its contents are only partially recorded`); |
| 324 | continue; |
| 325 | } |
| 326 | walkDirectory({ workspace, workspaceRoot, pattern: trimmed, prefix: normalized, push, gap: (reason) => gap(trimmed, reason), full, observe }); |
| 327 | } |
| 328 | const artifacts = []; |
| 329 | // Index-based: expanding an explicitly named directory appends its files to |
| 330 | // `concrete`, and those must be digested in the same pass. |
| 331 | for (let index = 0; index < concrete.length; index += 1) { |
| 332 | const normalized = concrete[index]; |
| 333 | const outcome = inspect(normalized); |
| 334 | if (outcome.kind === 'file') { |
| 335 | artifacts.push(outcome.digest); |
| 336 | continue; |
| 337 | } |
| 338 | if (outcome.kind === 'directory') { |
| 339 | // An explicitly named directory is expanded instead of being reported as |
| 340 | // unreadable: `src/lib` and `src/lib/` must behave the same. |
| 341 | walkDirectory({ workspace, workspaceRoot, pattern: normalized, prefix: normalized, push, gap: (reason) => gap(normalized, reason), full, observe }); |
| 342 | continue; |
| 343 | } |
| 344 | if (outcome.kind === 'absent') { |
| 345 | artifacts.push({ path: normalized, present: false }); |
| 346 | continue; |
| 347 | } |
| 348 | artifacts.push({ path: normalized, present: false, unreadable: true, reason: outcome.reason }); |
| 349 | } |
| 350 | return { artifacts: artifacts.sort((a, b) => a.path.localeCompare(b.path)), gaps }; |
| 351 | } |
| 352 | /** |
| 353 | * Read related scopes in one audit. Each scope retains its own expansion cap |
| 354 | * and gaps, but overlapping paths hash only once. A final revalidation rejects |
| 355 | * changed file identities and changed directory membership instead of handing |
| 356 | * out a mixture of revisions as complete evidence. |
| 357 | */ |
| 358 | export function readArtifactScopes(workspace, scopes) { |
| 359 | const root = workspaceRootOf(workspace); |
| 360 | const paths = new Map(); |
| 361 | const directories = new Map(); |
| 362 | const changedDirectories = new Set(); |
| 363 | const inspect = (normalized) => { |
| 364 | let outcome = paths.get(normalized); |
| 365 | if (outcome === undefined) { |
| 366 | outcome = inspectPath(root, workspace, normalized); |
| 367 | paths.set(normalized, outcome); |
| 368 | } |
| 369 | return outcome; |
| 370 | }; |
| 371 | const observe = (prefix, signature) => { |
| 372 | const prior = directories.get(prefix); |
| 373 | if (prior !== undefined && prior !== signature) |
| 374 | changedDirectories.add(prefix); |
| 375 | directories.set(prefix, signature); |
| 376 | }; |
| 377 | const reads = scopes.map(patterns => readScope(workspace, patterns, inspect, observe)); |
| 378 | const changed = new Map(); |
| 379 | for (const [path, outcome] of paths) { |
| 380 | try { |
| 381 | if (outcome.kind === 'file' && (root === undefined || pathStamp(root, join(workspace, path)) !== outcome.stamp)) { |
| 382 | changed.set(path, `${path} changed during the workspace audit; retry a stable revision`); |
| 383 | } |
| 384 | else if (outcome.kind === 'absent') { |
| 385 | try { |
| 386 | lstatSync(join(workspace, path)); |
| 387 | changed.set(path, `${path} appeared during the workspace audit; retry a stable revision`); |
| 388 | } |
| 389 | catch (error) { |
| 390 | if (errorCode(error) !== 'ENOENT' && errorCode(error) !== 'ENOTDIR') |
| 391 | throw error; |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | catch { |
| 396 | changed.set(path, `${path} could not be revalidated after reading; the workspace audit is incomplete`); |
| 397 | } |
| 398 | } |
| 399 | const gaps = []; |
| 400 | for (const [prefix, signature] of directories) { |
| 401 | try { |
| 402 | const absolute = join(workspace, prefix); |
| 403 | if (root === undefined || resolvesInside(root, absolute) !== true |
| 404 | || directorySignature(absolute, listScopeEntries(absolute, prefix)) !== signature) |
| 405 | changedDirectories.add(prefix); |
| 406 | } |
| 407 | catch { |
| 408 | changedDirectories.add(prefix); |
| 409 | } |
| 410 | } |
| 411 | for (const prefix of changedDirectories) |
| 412 | gaps.push({ pattern: prefix || '.', reason: 'directory membership changed or could not be revalidated during the workspace audit; retry a stable revision' }); |
| 413 | for (const [path, reason] of changed) |
| 414 | gaps.push({ pattern: path, reason }); |
| 415 | for (const read of reads) { |
| 416 | read.artifacts = read.artifacts.map(artifact => changed.has(artifact.path) |
| 417 | ? { path: artifact.path, present: false, unreadable: true, reason: changed.get(artifact.path) } |
| 418 | : artifact); |
| 419 | read.gaps.push(...gaps); |
| 420 | } |
| 421 | return reads; |
| 422 | } |
| 423 | /** Read one scope without retaining byte identities for the next request. */ |
| 424 | export function readArtifactScope(workspace, patterns) { |
| 425 | return readArtifactScopes(workspace, [patterns])[0]; |
| 426 | } |
| 427 | /** |
| 428 | * Read the current bytes of workspace-relative paths (directories expand). |
| 429 | * Illegal and unreadable paths are reported, never silently dropped. |
| 430 | */ |
| 431 | export function digestWorkspacePaths(workspace, paths) { |
| 432 | return readArtifactScope(workspace, paths).artifacts; |
| 433 | } |
| 434 | /** |
| 435 | * Does this workspace-relative path currently exist as a file or directory? |
| 436 | * Uses the same containment rules as the digest reader: a symlink that leaves |
| 437 | * the workspace is not "an existing workspace path". |
| 438 | */ |
| 439 | export function workspacePathExists(workspace, path) { |
| 440 | const normalized = normalizeWorkspacePath(path); |
| 441 | if (normalized === undefined) |
| 442 | return false; |
| 443 | const outcome = inspectPath(workspaceRootOf(workspace), workspace, normalized); |
| 444 | return outcome.kind === 'file' || outcome.kind === 'directory'; |
| 445 | } |
| 446 | /** Expand scope patterns to the concrete files they currently cover. */ |
| 447 | export function expandScopePaths(workspace, patterns) { |
| 448 | return readArtifactScope(workspace, patterns) |
| 449 | .artifacts |
| 450 | .filter((artifact) => artifact.present) |
| 451 | .map((artifact) => artifact.path) |
| 452 | .sort(); |
| 453 | } |
| 454 | /** |
| 455 | * Read one coherent snapshot of the given scope patterns. Directory patterns |
| 456 | * expand to the files they currently contain; a pattern naming a path that |
| 457 | * does not exist is recorded as `present: false` so a later creation or |
| 458 | * deletion is visible as drift, and any incomplete coverage is carried in |
| 459 | * `gaps`. |
| 460 | */ |
| 461 | export function snapshotWorkspacePaths(workspace, patterns) { |
| 462 | const at = Date.now(); |
| 463 | const { artifacts, gaps } = readArtifactScope(workspace, patterns); |
| 464 | return { at, artifacts, ...gaps.length === 0 ? {} : { gaps } }; |
| 465 | } |
| 466 |