@oyasmi/pipiclaw 0.9.2-beta.1 → 0.9.2-beta.2

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.
@@ -1,4 +1,4 @@
1
- import { existsSync, realpathSync, statSync } from "node:fs";
1
+ import { realpathSync, statSync } from "node:fs";
2
2
  import { mkdir } from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
@@ -16,7 +16,7 @@ import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.
16
16
  import { RecoverableToolError } from "../shared/recoverable-error.js";
17
17
  import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
18
18
  import { createEmptyUsageTotals } from "../shared/types.js";
19
- import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
19
+ import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
20
20
  import { readStoredTask } from "../tasks/store.js";
21
21
  import { writeVerificationAttestation } from "../tasks/verification.js";
22
22
  import { describeToolCall } from "../tools/presentation.js";
@@ -31,7 +31,7 @@ const workingDirectoryField = Type.Optional(Type.String({
31
31
  description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
32
32
  }));
33
33
  const purposeField = Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
34
- description: 'Use "verify" for an independent, read-only task acceptance check.',
34
+ description: 'Use "verify" for an independent task acceptance check. A write-capable verifier may run tests/builds; its attestation is advisory.',
35
35
  }));
36
36
  const taskIdField = Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." }));
37
37
  /**
@@ -170,16 +170,25 @@ export function assertWithinProjectBoundary(target, base, requested) {
170
170
  function resolveRunWorkingDirectory(requested, options) {
171
171
  const base = resolve(options.workingDirectory ?? process.cwd());
172
172
  const trimmed = requested?.trim();
173
+ // Resolve the project root once as well. Returning an alias here would leave the later lease,
174
+ // executor, subject hash, and external cwd exposed to a symlink swap after admission.
175
+ const canonicalBase = realpathOrSelf(base);
173
176
  if (!trimmed)
174
- return base;
175
- const target = resolve(base, trimmed);
176
- if (!existsSync(target) || !statSync(target).isDirectory()) {
177
+ return canonicalBase;
178
+ const target = resolve(canonicalBase, trimmed);
179
+ let canonicalTarget;
180
+ try {
181
+ canonicalTarget = realpathSync(target);
182
+ if (!statSync(canonicalTarget).isDirectory())
183
+ throw new Error("not a directory");
184
+ }
185
+ catch {
177
186
  throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
178
187
  }
179
188
  if (options.projectBoundary === "project") {
180
- assertWithinProjectBoundary(target, base, requested ?? trimmed);
189
+ assertWithinProjectBoundary(canonicalTarget, canonicalBase, requested ?? trimmed);
181
190
  }
182
- return target;
191
+ return canonicalTarget;
183
192
  }
184
193
  async function prepareRunContext(runId, params, options) {
185
194
  const purpose = params.purpose ?? "work";
@@ -311,25 +320,23 @@ export function buildVerificationProtocol(taskPath) {
311
320
  return [
312
321
  "Verification protocol:",
313
322
  `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
314
- "- You are the checker, not the maker. Do not edit files or fix failures; report them.",
323
+ "- You are the checker, not the maker. Do not modify the implementation or fix failures to make a check pass; report them.",
324
+ "- You may run npm tests/builds and other deterministic checks. Newly created outputs under recognized transient artifact paths (for example .run/, coverage/, build/, dist/ or caches) are allowed, but do not change tracked files or pre-existing untracked product files.",
325
+ "- This verification is advisory when the verifier can write or use bash: runtime cannot structurally prove that every write was harmless. Review the diff and evidence before trusting PASS.",
315
326
  "- Run deterministic checks when available and distinguish observed evidence from assumptions.",
316
327
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
317
328
  ].join("\n");
318
329
  }
319
330
  /**
320
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
321
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
322
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
331
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
332
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
333
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
323
334
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
324
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
325
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
335
+ * dispatch does, including the remaining `exec` restriction.
326
336
  */
327
337
  export function assertVerifyAdmissible(config, purpose, workingDirectory) {
328
338
  if (purpose !== "verify")
329
339
  return;
330
- if (config.mutates === "write") {
331
- throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
332
- }
333
340
  if (config.runtime === "external" && config.harness === "exec") {
334
341
  throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
335
342
  }
@@ -506,11 +513,11 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
506
513
  // with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
507
514
  // cannot drift between the two dispatch paths.
508
515
  assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
509
- // Admission: a write-mutating run takes an exclusive workspace lease before it is even
510
- // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
511
- // Read runs and purpose=verify never take one. Shared by both runtimes.
516
+ // Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
517
+ // workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
518
+ // never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
512
519
  let leaseKey;
513
- if (config.mutates === "write" && runContext.purpose !== "verify") {
520
+ if (config.mutates === "write") {
514
521
  const lease = acquireWorkspaceLease({
515
522
  runId: runContext.runId,
516
523
  channelId: options.runtimeContext.channelId,
@@ -615,11 +622,12 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
615
622
  let failureReason;
616
623
  /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
617
624
  let budgetExceeded = false;
618
- /** Set only by the `subagent_run op=cancel` handle registered below — a real stop, unlike a budget abort. */
625
+ /** Set only by the `subagent_run op=cancel` handle registered as soon as the run is durable. */
619
626
  let externallyCancelled = false;
620
627
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
621
628
  let detached = false;
622
629
  let lastUpdateText = "";
630
+ let worker;
623
631
  try {
624
632
  await runManager.register({
625
633
  runId: runContext.runId,
@@ -635,6 +643,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
635
643
  workingDirectory: runContext.workingDirectory,
636
644
  artifactDir: runContext.artifactDir,
637
645
  leaseKey,
646
+ mutates: config.mutates,
638
647
  });
639
648
  }
640
649
  catch (error) {
@@ -643,6 +652,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
643
652
  releaseWorkspaceLease(leaseKey, runContext.runId);
644
653
  throw error;
645
654
  }
655
+ // Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
656
+ // creation) can yield. Without this provisional handle, a cancel in that window was treated as
657
+ // an unreachable run: the manager released the lease and settled it while the worker could still
658
+ // start writing after the supposed cancellation (especially dangerous for a write verifier).
659
+ runManager.registerCancelHandle(runContext.runId, () => {
660
+ externallyCancelled = true;
661
+ worker?.abort();
662
+ });
646
663
  const emitUpdate = (text) => {
647
664
  // Once detached, execute() has already returned to the SDK; nothing is listening
648
665
  // for further progress on this (from its view, finished) tool call.
@@ -658,16 +675,21 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
658
675
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
659
676
  });
660
677
  };
661
- let worker;
662
678
  let wallClockTimer;
663
679
  let unsubscribe;
664
680
  let verifierGitStateBefore;
665
681
  let verifierSubjectBefore;
682
+ let verifierSubjectBaseCommit;
683
+ let verifierSubjectBaselineUntrackedPaths;
666
684
  try {
667
685
  const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
668
686
  verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
669
- verifierSubjectBefore =
670
- runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
687
+ if (runContext.purpose === "verify") {
688
+ const subjectSnapshot = await workspaceSubjectSnapshot(runContext.workingDirectory);
689
+ verifierSubjectBefore = subjectSnapshot?.hash;
690
+ verifierSubjectBaseCommit = subjectSnapshot?.baseCommit;
691
+ verifierSubjectBaselineUntrackedPaths = subjectSnapshot?.baselineUntrackedPaths;
692
+ }
671
693
  worker =
672
694
  options.createWorker?.({
673
695
  subAgent: config,
@@ -690,10 +712,6 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
690
712
  getApiKey: async () => apiKey,
691
713
  streamFn: streamSimple,
692
714
  });
693
- runManager.registerCancelHandle(runContext.runId, () => {
694
- externallyCancelled = true;
695
- worker?.abort();
696
- });
697
715
  wallClockTimer = setTimeout(() => {
698
716
  failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
699
717
  budgetExceeded = true;
@@ -779,8 +797,13 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
779
797
  log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
780
798
  return [];
781
799
  });
782
- await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
783
- await activeWorker.waitForIdle();
800
+ if (externallyCancelled) {
801
+ failureReason = failureReason || "Cancelled by request.";
802
+ }
803
+ else {
804
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
805
+ await activeWorker.waitForIdle();
806
+ }
784
807
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
785
808
  // conclusion instead of discarding the work outright. An explicit cancel skips
786
809
  // this — the model asked this run to stop now, not to wrap up.
@@ -828,7 +851,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
828
851
  ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
829
852
  : undefined);
830
853
  const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
831
- const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
854
+ const verifierSubjectAfter = runContext.purpose === "verify"
855
+ ? await workspaceSubjectHash(runContext.workingDirectory, verifierSubjectBaseCommit
856
+ ? {
857
+ baseCommit: verifierSubjectBaseCommit,
858
+ baselineUntrackedPaths: verifierSubjectBaselineUntrackedPaths,
859
+ }
860
+ : {})
861
+ : undefined;
832
862
  // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
833
863
  // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
834
864
  // run's own output does and does not prove. Only the attestation write and the
@@ -847,14 +877,14 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
847
877
  const verificationVerdict = verification?.verdict;
848
878
  // Internal verify always keeps write/edit structurally removed from the verifier's
849
879
  // tool set (buildSubagentTools above), but `bash` stays available by default and can
850
- // write files just as well — labeling that "enforced" would be dishonest (review
851
- // 2026-08-23 §2.2). Only a role that dropped `bash` from its declared tool list earns
852
- // the stronger label. Computed once so the attestation and the run record — the
880
+ // write files just as well. A role that declares mutates: write is advisory even when
881
+ // its effective tool list happens not to contain bash: the declaration says this run is
882
+ // not structurally read-only. Computed once so the attestation and run record — the
853
883
  // latter is what the completion wake and `subagent_list` display — cannot disagree.
854
- const internalVerificationStrength = config.tools.includes("bash")
855
- ? "advisory"
856
- : "enforced";
884
+ const internalVerificationStrength = config.mutates === "write" || config.tools.includes("bash") ? "advisory" : "enforced";
857
885
  if (runContext.purpose === "verify" && runContext.taskId && verification) {
886
+ const baseSubjectAvailable = verifierSubjectBaseCommit !== undefined && verifierSubjectBaselineUntrackedPaths !== undefined;
887
+ const subjectAvailable = !verification.workspaceChanged && verifierSubjectAfter !== undefined && baseSubjectAvailable;
858
888
  await writeVerificationAttestation(options.channelDir, {
859
889
  runId: runContext.runId,
860
890
  taskId: runContext.taskId,
@@ -862,8 +892,11 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
862
892
  checkedAt: formatLocalTime(),
863
893
  evidence: verification.evidence,
864
894
  workspaceChanged: verification.workspaceChanged,
865
- subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
866
- subjectDir: runContext.workingDirectory,
895
+ subjectHash: subjectAvailable ? verifierSubjectAfter : undefined,
896
+ subjectDir: subjectAvailable ? runContext.workingDirectory : undefined,
897
+ subjectMode: subjectAvailable ? "base-relative" : undefined,
898
+ subjectBaseCommit: subjectAvailable ? verifierSubjectBaseCommit : undefined,
899
+ subjectBaselineUntrackedPaths: subjectAvailable ? verifierSubjectBaselineUntrackedPaths : undefined,
867
900
  verificationStrength: internalVerificationStrength,
868
901
  });
869
902
  }
@@ -15,7 +15,7 @@ export function resolveVerificationOutcome(input) {
15
15
  const evidence = !comparable
16
16
  ? "Could not determine whether the workspace changed (not a Git checkout, or `git status` failed); refusing to record a PASS without that evidence."
17
17
  : workspaceChanged
18
- ? "Verifier changed tracked workspace files; the attestation is invalid."
18
+ ? "Verifier changed protected workspace content; the attestation is invalid."
19
19
  : !declaredVerdict
20
20
  ? "Verifier did not emit the required final VERDICT marker."
21
21
  : input.finalText.trim().slice(0, 8_000);
@@ -1,6 +1,32 @@
1
1
  /**
2
- * A compact, deterministic description of the code/artifact subject a verifier
3
- * observed. It intentionally uses only Git's own view, keeping verification
4
- * cheap and understandable for a local coding runtime.
2
+ * The legacy subject has HEAD plus separate staged/unstaged diffs in its input. It remains the
3
+ * default so attestations written before the base-relative subject was introduced can still be
4
+ * read and compared without silently changing their meaning.
5
5
  */
6
- export declare function workspaceSubjectHash(workingDirectory: string): Promise<string | undefined>;
6
+ export interface WorkspaceSubjectHashOptions {
7
+ /** Compare the checkout's current content to this commit, not to its current HEAD. */
8
+ baseCommit?: string;
9
+ /** Untracked paths, plus ignored non-transient paths, that existed when the subject was captured. */
10
+ baselineUntrackedPaths?: readonly string[];
11
+ }
12
+ /** The metadata a new purpose=verify run persists for a base-relative subject. */
13
+ export interface WorkspaceSubjectSnapshot {
14
+ hash: string;
15
+ baseCommit: string;
16
+ baselineUntrackedPaths: string[];
17
+ }
18
+ /** Exposed for focused tests and documentation that needs to describe the artifact scope. */
19
+ export declare function isTransientUntrackedPath(relativePath: string): boolean;
20
+ /**
21
+ * Capture the base-relative subject and the untracked manifest needed to compare it after a test
22
+ * or build. The snapshot is deliberately a single new mode; callers that need legacy semantics
23
+ * should continue using `workspaceSubjectHash()` without options.
24
+ */
25
+ export declare function workspaceSubjectSnapshot(workingDirectory: string): Promise<WorkspaceSubjectSnapshot | undefined>;
26
+ /**
27
+ * A compact, deterministic description of the code/artifact subject a verifier observed. Without
28
+ * options this retains the original HEAD + staged/unstaged + all-untracked behavior for old
29
+ * attestations. With `baseCommit`, it compares the current checkout's content relative to that
30
+ * fixed commit so committing the already-verified content does not invalidate the attestation.
31
+ */
32
+ export declare function workspaceSubjectHash(workingDirectory: string, options?: WorkspaceSubjectHashOptions): Promise<string | undefined>;
@@ -1,14 +1,74 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { readFile } from "node:fs/promises";
4
- import { join } from "node:path";
3
+ import { lstat, readFile, readlink } from "node:fs/promises";
4
+ import { isAbsolute, join, win32 } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  const execFileAsync = promisify(execFile);
7
+ /**
8
+ * New files in these named locations are conventional test/build/runtime outputs. They are an
9
+ * explicit, deliberately small artifact scope: a new untracked file anywhere else remains part of
10
+ * the subject and makes a verifier PASS fail. The directory names apply at the checkout root;
11
+ * `src/coverage/...` is not silently treated as generated output. Existing untracked paths are
12
+ * always retained in the subject through `baselineUntrackedPaths`, even when they live below one of
13
+ * these directories. Ignored paths are read separately with `git ls-files`; ignored paths in the
14
+ * same explicit transient scope are treated as generated at every snapshot, while ignored paths
15
+ * elsewhere are protected just like ordinary untracked product files. This avoids treating Git's
16
+ * default omission of ignored paths as permission to change arbitrary product files, without
17
+ * recording the entire `node_modules` tree in every attestation.
18
+ */
19
+ const TRANSIENT_UNTRACKED_DIRECTORY_NAMES = new Set([
20
+ ".cache",
21
+ ".next",
22
+ ".nuxt",
23
+ ".nyc_output",
24
+ ".parcel-cache",
25
+ ".pnpm-store",
26
+ ".pytest_cache",
27
+ ".temp",
28
+ ".tmp",
29
+ ".run",
30
+ ".turbo",
31
+ ".vite",
32
+ "build",
33
+ "coverage",
34
+ "dist",
35
+ "dist-evals",
36
+ "node_modules",
37
+ ".npm",
38
+ "playwright-report",
39
+ "subagent-artifacts",
40
+ "target",
41
+ "temp",
42
+ "test-results",
43
+ "tmp",
44
+ ]);
45
+ /** Cypress's source/test tree is not an output directory. Keep only its conventional generated
46
+ * screenshot/video roots transient; `cypress/e2e`, fixtures, support, and downloads remain subject
47
+ * to verification. */
48
+ const TRANSIENT_UNTRACKED_DIRECTORY_PREFIXES = ["cypress/screenshots", "cypress/videos"];
49
+ const TRANSIENT_UNTRACKED_FILE_NAMES = new Set([".eslintcache", ".stylelintcache"]);
50
+ /** Exposed for focused tests and documentation that needs to describe the artifact scope. */
51
+ export function isTransientUntrackedPath(relativePath) {
52
+ if (isAbsolute(relativePath) || win32.isAbsolute(relativePath))
53
+ return false;
54
+ const normalized = relativePath.replace(/^\.\//, "").replaceAll("\\", "/");
55
+ const segments = normalized.split("/").filter(Boolean);
56
+ if (segments.includes(".."))
57
+ return false;
58
+ if (TRANSIENT_UNTRACKED_DIRECTORY_PREFIXES.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`)))
59
+ return true;
60
+ if (segments.length > 0 &&
61
+ TRANSIENT_UNTRACKED_DIRECTORY_NAMES.has(segments[0]) &&
62
+ (segments.length > 1 || normalized.endsWith("/")))
63
+ return true;
64
+ const basename = segments.at(-1) ?? normalized;
65
+ return segments.length === 1 && (TRANSIENT_UNTRACKED_FILE_NAMES.has(basename) || basename.endsWith(".tsbuildinfo"));
66
+ }
7
67
  /**
8
68
  * git quotes a path containing special characters in double quotes with C-style escapes (spec
9
69
  * 040, D9). `JSON.parse` accepts the same escape set for the characters git actually emits
10
70
  * (`\"`, `\\`, `\t`, `\n`) and is close enough for a hash input; a path so exotic it defeats this
11
- * still contributes *a* value to the hash; it just won't be the literal decoded path.
71
+ * still contributes a value to the hash; it just won't be the literal decoded path.
12
72
  */
13
73
  function unquoteGitPath(raw) {
14
74
  if (raw.startsWith('"') && raw.endsWith('"')) {
@@ -21,22 +81,41 @@ function unquoteGitPath(raw) {
21
81
  }
22
82
  return raw;
23
83
  }
84
+ function parseStatusPaths(statusOutput, prefix) {
85
+ const nulSeparated = statusOutput.includes("\0");
86
+ const entries = nulSeparated ? statusOutput.split("\0") : statusOutput.split("\n");
87
+ return Array.from(new Set(entries
88
+ .filter((entry) => entry.startsWith(prefix))
89
+ .map((entry) => {
90
+ // `git status -z` emits raw paths. Only remove the three-byte status prefix: a
91
+ // leading/trailing space is part of the filename and must remain in the subject.
92
+ const rawPath = entry.slice(prefix.length);
93
+ return nulSeparated ? rawPath : unquoteGitPath(rawPath.trim());
94
+ })
95
+ .filter(Boolean))).sort();
96
+ }
97
+ function parseUntrackedPaths(statusOutput) {
98
+ return parseStatusPaths(statusOutput, "?? ");
99
+ }
100
+ function parseNulPathList(output) {
101
+ return Array.from(new Set(output.split("\0").filter(Boolean))).sort();
102
+ }
103
+ /** New base-relative subjects include ignored paths outside the explicit transient scope. */
104
+ function protectedWorkspacePaths(statusOutput, ignoredPaths = []) {
105
+ const paths = new Set(parseUntrackedPaths(statusOutput));
106
+ for (const path of ignoredPaths) {
107
+ if (!isTransientUntrackedPath(path))
108
+ paths.add(path);
109
+ }
110
+ return [...paths].sort();
111
+ }
24
112
  /**
25
- * Fold untracked-file *content* into the subject, not just their path/status (D9). `git status
26
- * --porcelain` reports an untracked file as present, but two different untracked files with the
27
- * same name are indistinguishable to it — a verifier that edits an untracked file's content
28
- * (or reverts it after inspection) previously left no trace in `workspaceSubjectHash` at all.
29
- * Best-effort per file: an unreadable entry (deleted mid-scan, a directory, a permission error)
30
- * still contributes its path to the hash, just not content — this function must never throw, since
31
- * its caller already treats the whole subject computation as best-effort.
113
+ * Preserve the exact untracked digest used by the pre-base-relative subject. This is intentionally
114
+ * separate from the new digest: changing the default would make an old attestation stale merely
115
+ * because the checkout already contained an untracked file.
32
116
  */
33
- async function untrackedFileDigest(workingDirectory, statusOutput) {
34
- const paths = statusOutput
35
- .split("\n")
36
- .filter((line) => line.startsWith("?? "))
37
- .map((line) => unquoteGitPath(line.slice(3).trim()))
38
- .filter(Boolean)
39
- .sort();
117
+ async function legacyUntrackedFileDigest(workingDirectory, statusOutput) {
118
+ const paths = parseUntrackedPaths(statusOutput);
40
119
  const hash = createHash("sha256");
41
120
  for (const relativePath of paths) {
42
121
  hash.update(relativePath);
@@ -50,25 +129,178 @@ async function untrackedFileDigest(workingDirectory, statusOutput) {
50
129
  return hash.digest("hex");
51
130
  }
52
131
  /**
53
- * A compact, deterministic description of the code/artifact subject a verifier
54
- * observed. It intentionally uses only Git's own view, keeping verification
55
- * cheap and understandable for a local coding runtime.
132
+ * Select the untracked paths for a base-relative subject. Paths present at the initial snapshot
133
+ * stay protected forever for that attestation. Only newly appearing paths under the explicit
134
+ * transient artifact scope are omitted; new source/config/product files remain visible.
135
+ */
136
+ function baseRelativeUntrackedPaths(currentPaths, baselineUntrackedPaths) {
137
+ if (baselineUntrackedPaths === undefined)
138
+ return [...currentPaths].sort();
139
+ const baseline = new Set(baselineUntrackedPaths);
140
+ const selected = new Set(baseline);
141
+ for (const path of currentPaths) {
142
+ if (baseline.has(path) || !isTransientUntrackedPath(path))
143
+ selected.add(path);
144
+ }
145
+ return [...selected].sort();
146
+ }
147
+ /** Read the current content for a canonical path set. This is deliberately content-based rather
148
+ * than diff-text-based: a normal commit changes Git's representation, but not the checked content.
149
+ * Baseline paths that disappear still contribute a missing marker.
56
150
  */
57
- export async function workspaceSubjectHash(workingDirectory) {
151
+ async function baseRelativeFileDigest(workingDirectory, paths) {
152
+ const hash = createHash("sha256");
153
+ for (const relativePath of paths) {
154
+ hash.update(`path:${relativePath}\0`);
155
+ try {
156
+ // Never follow a checkout entry while constructing an attestation. A symlink can point
157
+ // outside the checkout, and hashing its target content would both read an unrelated path
158
+ // and make regular-file -> symlink(same content) invisible.
159
+ const { filePath, fileStat } = await lstatWorkspaceEntry(workingDirectory, relativePath);
160
+ const type = fileType(fileStat);
161
+ hash.update(`type:${type}\0`);
162
+ hash.update(`mode:${fileStat.mode & 0o7777}\0`);
163
+ if (fileStat.isSymbolicLink()) {
164
+ hash.update(`target:${await readlink(filePath, "utf8")}\0`);
165
+ }
166
+ else if (fileStat.isFile()) {
167
+ hash.update(await readFile(filePath));
168
+ }
169
+ else {
170
+ // Git status normally expands untracked files, but an ignored/special entry may
171
+ // still be a directory or device. Its type/mode are evidence; never recurse or
172
+ // open an arbitrary special file while hashing a verifier subject.
173
+ hash.update("<non-regular>\0");
174
+ }
175
+ }
176
+ catch {
177
+ hash.update("<missing>\0");
178
+ }
179
+ hash.update("\0");
180
+ }
181
+ return hash.digest("hex");
182
+ }
183
+ /** lstat the final entry and reject symlinked parent components, so a path cannot redirect a
184
+ * content read outside the checkout through an intermediate directory symlink. The working
185
+ * directory itself may be a symlink (it is the explicitly selected checkout root). */
186
+ async function lstatWorkspaceEntry(workingDirectory, relativePath) {
187
+ if (isAbsolute(relativePath) || win32.isAbsolute(relativePath))
188
+ throw new Error("unsafe absolute subject path");
189
+ const segments = relativePath.replaceAll("\\", "/").split("/").filter(Boolean);
190
+ if (segments.length === 0 || segments.includes(".."))
191
+ throw new Error("unsafe subject path");
192
+ let filePath = workingDirectory;
193
+ let fileStat;
194
+ for (const [index, segment] of segments.entries()) {
195
+ filePath = join(filePath, segment);
196
+ fileStat = await lstat(filePath);
197
+ if (index < segments.length - 1 && fileStat.isSymbolicLink()) {
198
+ throw new Error("symlinked subject path component");
199
+ }
200
+ }
201
+ return { filePath, fileStat: fileStat };
202
+ }
203
+ function fileType(fileStat) {
204
+ if (fileStat.isSymbolicLink())
205
+ return "symlink";
206
+ if (fileStat.isFile())
207
+ return "file";
208
+ if (fileStat.isDirectory())
209
+ return "directory";
210
+ if (fileStat.isBlockDevice())
211
+ return "block-device";
212
+ if (fileStat.isCharacterDevice())
213
+ return "character-device";
214
+ if (fileStat.isFIFO())
215
+ return "fifo";
216
+ if (fileStat.isSocket())
217
+ return "socket";
218
+ return "other";
219
+ }
220
+ async function baseRelativeTrackedPaths(workingDirectory, baseCommit) {
221
+ const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "diff", "--no-ext-diff", "--no-renames", "--name-only", "-z", baseCommit, "--"], { maxBuffer: 8 * 1024 * 1024 });
222
+ return Array.from(new Set(stdout.split("\0").filter(Boolean))).sort();
223
+ }
224
+ async function readGitStatus(workingDirectory, nulSeparated = false) {
225
+ const args = ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"];
226
+ if (nulSeparated)
227
+ args.push("-z");
228
+ const { stdout } = await execFileAsync("git", args, { maxBuffer: 4 * 1024 * 1024 });
229
+ return stdout;
230
+ }
231
+ /** Git status deliberately omits ignored paths. Enumerate them separately so an ignored product
232
+ * file cannot disappear from the subject merely because it matches `.gitignore`. */
233
+ async function readGitIgnoredPaths(workingDirectory) {
234
+ const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "ls-files", "--others", "--ignored", "--exclude-standard", "-z"], { maxBuffer: 64 * 1024 * 1024 });
235
+ return parseNulPathList(stdout);
236
+ }
237
+ async function readGitHead(workingDirectory) {
238
+ const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "rev-parse", "HEAD"], {
239
+ maxBuffer: 1024 * 1024,
240
+ });
241
+ return stdout.trim();
242
+ }
243
+ /** Compute the subject used by a new verifier run, with a fixed base commit. */
244
+ async function baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, baseCommit, baselineUntrackedPaths) {
245
+ const trackedPaths = await baseRelativeTrackedPaths(workingDirectory, baseCommit);
246
+ const untrackedPaths = baseRelativeUntrackedPaths(protectedWorkspacePaths(statusOutput, ignoredPaths), baselineUntrackedPaths);
247
+ const paths = Array.from(new Set([...trackedPaths, ...untrackedPaths])).sort();
248
+ const contentDigest = await baseRelativeFileDigest(workingDirectory, paths);
249
+ return createHash("sha256").update(["base-relative-v3", baseCommit, contentDigest].join("\0")).digest("hex");
250
+ }
251
+ /**
252
+ * Capture the base-relative subject and the untracked manifest needed to compare it after a test
253
+ * or build. The snapshot is deliberately a single new mode; callers that need legacy semantics
254
+ * should continue using `workspaceSubjectHash()` without options.
255
+ */
256
+ export async function workspaceSubjectSnapshot(workingDirectory) {
257
+ try {
258
+ const [statusOutput, ignoredPaths, baseCommit] = await Promise.all([
259
+ readGitStatus(workingDirectory, true),
260
+ readGitIgnoredPaths(workingDirectory),
261
+ readGitHead(workingDirectory),
262
+ ]);
263
+ const baselineUntrackedPaths = protectedWorkspacePaths(statusOutput, ignoredPaths);
264
+ const hash = await baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, baseCommit, baselineUntrackedPaths);
265
+ return { hash, baseCommit, baselineUntrackedPaths };
266
+ }
267
+ catch {
268
+ return undefined;
269
+ }
270
+ }
271
+ /**
272
+ * A compact, deterministic description of the code/artifact subject a verifier observed. Without
273
+ * options this retains the original HEAD + staged/unstaged + all-untracked behavior for old
274
+ * attestations. With `baseCommit`, it compares the current checkout's content relative to that
275
+ * fixed commit so committing the already-verified content does not invalidate the attestation.
276
+ */
277
+ export async function workspaceSubjectHash(workingDirectory, options = {}) {
278
+ if (options.baseCommit !== undefined) {
279
+ try {
280
+ const [statusOutput, ignoredPaths] = await Promise.all([
281
+ readGitStatus(workingDirectory, true),
282
+ readGitIgnoredPaths(workingDirectory),
283
+ ]);
284
+ return await baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, options.baseCommit.trim(), options.baselineUntrackedPaths);
285
+ }
286
+ catch {
287
+ return undefined;
288
+ }
289
+ }
58
290
  try {
59
- const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"], { maxBuffer: 4 * 1024 * 1024 });
291
+ const statusOutput = await readGitStatus(workingDirectory);
60
292
  const [head, unstaged, staged, untrackedDigest] = await Promise.all([
61
- execFileAsync("git", ["-C", workingDirectory, "rev-parse", "HEAD"], { maxBuffer: 1024 * 1024 }),
293
+ readGitHead(workingDirectory),
62
294
  execFileAsync("git", ["-C", workingDirectory, "diff", "--no-ext-diff", "--binary"], {
63
295
  maxBuffer: 4 * 1024 * 1024,
64
296
  }),
65
297
  execFileAsync("git", ["-C", workingDirectory, "diff", "--cached", "--no-ext-diff", "--binary"], {
66
298
  maxBuffer: 4 * 1024 * 1024,
67
299
  }),
68
- untrackedFileDigest(workingDirectory, stdout),
300
+ legacyUntrackedFileDigest(workingDirectory, statusOutput),
69
301
  ]);
70
302
  return createHash("sha256")
71
- .update([head.stdout.trim(), stdout, unstaged.stdout, staged.stdout, untrackedDigest].join("\0"))
303
+ .update([head, statusOutput, unstaged.stdout, staged.stdout, untrackedDigest].join("\0"))
72
304
  .digest("hex");
73
305
  }
74
306
  catch {