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

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 (51) hide show
  1. package/dist/agent/channel-runner.d.ts +13 -0
  2. package/dist/agent/channel-runner.js +67 -19
  3. package/dist/agent/job-manager.js +3 -0
  4. package/dist/playbooks/agent-delegation.md +1 -1
  5. package/dist/playbooks/task-driving.md +3 -3
  6. package/dist/runtime/bootstrap.js +29 -7
  7. package/dist/runtime/channel-event.d.ts +8 -0
  8. package/dist/runtime/subagent-commands.d.ts +8 -0
  9. package/dist/runtime/subagent-commands.js +28 -4
  10. package/dist/runtime/task-commands.js +7 -2
  11. package/dist/runtime/task-wake.d.ts +7 -2
  12. package/dist/runtime/task-wake.js +22 -3
  13. package/dist/settings.d.ts +12 -0
  14. package/dist/settings.js +9 -0
  15. package/dist/subagents/external/claude-code.js +20 -0
  16. package/dist/subagents/external/codex-cli.js +33 -0
  17. package/dist/subagents/external/harness.d.ts +8 -0
  18. package/dist/subagents/external/progress-tail.d.ts +14 -0
  19. package/dist/subagents/external/progress-tail.js +84 -0
  20. package/dist/subagents/external/run.d.ts +6 -0
  21. package/dist/subagents/external/run.js +123 -58
  22. package/dist/subagents/external/settlement.d.ts +7 -1
  23. package/dist/subagents/external/settlement.js +28 -7
  24. package/dist/subagents/runs.d.ts +80 -8
  25. package/dist/subagents/runs.js +260 -58
  26. package/dist/subagents/tool.d.ts +4 -5
  27. package/dist/subagents/tool.js +73 -40
  28. package/dist/subagents/verification-outcome.js +1 -1
  29. package/dist/tasks/artifact-subject.d.ts +38 -4
  30. package/dist/tasks/artifact-subject.js +282 -25
  31. package/dist/tasks/verification.d.ts +24 -2
  32. package/dist/tasks/verification.js +113 -21
  33. package/dist/tools/grep.js +4 -1
  34. package/dist/tools/subagent-manage.js +14 -14
  35. package/dist/tools/task-manage/lifecycle.js +7 -4
  36. package/dist/tools/task-manage/verification.d.ts +1 -1
  37. package/dist/tools/task-manage/verification.js +12 -7
  38. package/dist/tui/pitui-frontend.js +3 -3
  39. package/examples/sub-agents/README.md +14 -13
  40. package/examples/sub-agents/builder-hard.md +17 -16
  41. package/examples/sub-agents/builder.md +16 -12
  42. package/examples/sub-agents/documenter.md +17 -17
  43. package/examples/sub-agents/explorer.md +12 -13
  44. package/examples/sub-agents/git-committer.md +15 -26
  45. package/examples/sub-agents/log-sifter.md +13 -12
  46. package/examples/sub-agents/planner.md +11 -11
  47. package/examples/sub-agents/reviewer.md +21 -12
  48. package/examples/sub-agents/scout.md +16 -12
  49. package/examples/sub-agents/verifier.md +18 -13
  50. package/examples/sub-agents/worker.md +17 -10
  51. package/package.json +5 -5
@@ -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,203 @@ 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.
150
+ */
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
+ /**
232
+ * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
233
+ * does not have to spend its own first tool call finding out. `git status --porcelain` only — not
234
+ * a full subject hash — since this is a convenience for the reader, not a verification input.
235
+ * Returns `undefined` on any failure (not a git repo, `git` unavailable) or when nothing changed;
236
+ * a caller with nothing to show should simply omit the line.
237
+ */
238
+ export async function changedPathsSummary(workingDirectory, limit = 20) {
239
+ let statusOutput;
240
+ try {
241
+ statusOutput = await readGitStatus(workingDirectory);
242
+ }
243
+ catch {
244
+ return undefined;
245
+ }
246
+ const lines = statusOutput
247
+ .split("\n")
248
+ .map((line) => line.trim())
249
+ .filter(Boolean);
250
+ if (lines.length === 0)
251
+ return undefined;
252
+ const shown = lines.slice(0, limit).join(", ");
253
+ const overflow = lines.length > limit ? ` (+${lines.length - limit} more)` : "";
254
+ return `${shown}${overflow}`;
255
+ }
256
+ /** Git status deliberately omits ignored paths. Enumerate them separately so an ignored product
257
+ * file cannot disappear from the subject merely because it matches `.gitignore`. */
258
+ async function readGitIgnoredPaths(workingDirectory) {
259
+ const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "ls-files", "--others", "--ignored", "--exclude-standard", "-z"], { maxBuffer: 64 * 1024 * 1024 });
260
+ return parseNulPathList(stdout);
261
+ }
262
+ async function readGitHead(workingDirectory) {
263
+ const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "rev-parse", "HEAD"], {
264
+ maxBuffer: 1024 * 1024,
265
+ });
266
+ return stdout.trim();
267
+ }
268
+ /** Compute the subject used by a new verifier run, with a fixed base commit. */
269
+ async function baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, baseCommit, baselineUntrackedPaths) {
270
+ const trackedPaths = await baseRelativeTrackedPaths(workingDirectory, baseCommit);
271
+ const untrackedPaths = baseRelativeUntrackedPaths(protectedWorkspacePaths(statusOutput, ignoredPaths), baselineUntrackedPaths);
272
+ const paths = Array.from(new Set([...trackedPaths, ...untrackedPaths])).sort();
273
+ const contentDigest = await baseRelativeFileDigest(workingDirectory, paths);
274
+ return createHash("sha256").update(["base-relative-v3", baseCommit, contentDigest].join("\0")).digest("hex");
275
+ }
276
+ /**
277
+ * Capture the base-relative subject and the untracked manifest needed to compare it after a test
278
+ * or build. The snapshot is deliberately a single new mode; callers that need legacy semantics
279
+ * should continue using `workspaceSubjectHash()` without options.
56
280
  */
57
- export async function workspaceSubjectHash(workingDirectory) {
281
+ export async function workspaceSubjectSnapshot(workingDirectory) {
282
+ try {
283
+ const [statusOutput, ignoredPaths, baseCommit] = await Promise.all([
284
+ readGitStatus(workingDirectory, true),
285
+ readGitIgnoredPaths(workingDirectory),
286
+ readGitHead(workingDirectory),
287
+ ]);
288
+ const baselineUntrackedPaths = protectedWorkspacePaths(statusOutput, ignoredPaths);
289
+ const hash = await baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, baseCommit, baselineUntrackedPaths);
290
+ return { hash, baseCommit, baselineUntrackedPaths };
291
+ }
292
+ catch {
293
+ return undefined;
294
+ }
295
+ }
296
+ /**
297
+ * A compact, deterministic description of the code/artifact subject a verifier observed. Without
298
+ * options this retains the original HEAD + staged/unstaged + all-untracked behavior for old
299
+ * attestations. With `baseCommit`, it compares the current checkout's content relative to that
300
+ * fixed commit so committing the already-verified content does not invalidate the attestation.
301
+ */
302
+ export async function workspaceSubjectHash(workingDirectory, options = {}) {
303
+ if (options.baseCommit !== undefined) {
304
+ try {
305
+ const [statusOutput, ignoredPaths] = await Promise.all([
306
+ readGitStatus(workingDirectory, true),
307
+ readGitIgnoredPaths(workingDirectory),
308
+ ]);
309
+ return await baseRelativeSubjectHash(workingDirectory, statusOutput, ignoredPaths, options.baseCommit.trim(), options.baselineUntrackedPaths);
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ }
58
315
  try {
59
- const { stdout } = await execFileAsync("git", ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"], { maxBuffer: 4 * 1024 * 1024 });
316
+ const statusOutput = await readGitStatus(workingDirectory);
60
317
  const [head, unstaged, staged, untrackedDigest] = await Promise.all([
61
- execFileAsync("git", ["-C", workingDirectory, "rev-parse", "HEAD"], { maxBuffer: 1024 * 1024 }),
318
+ readGitHead(workingDirectory),
62
319
  execFileAsync("git", ["-C", workingDirectory, "diff", "--no-ext-diff", "--binary"], {
63
320
  maxBuffer: 4 * 1024 * 1024,
64
321
  }),
65
322
  execFileAsync("git", ["-C", workingDirectory, "diff", "--cached", "--no-ext-diff", "--binary"], {
66
323
  maxBuffer: 4 * 1024 * 1024,
67
324
  }),
68
- untrackedFileDigest(workingDirectory, stdout),
325
+ legacyUntrackedFileDigest(workingDirectory, statusOutput),
69
326
  ]);
70
327
  return createHash("sha256")
71
- .update([head.stdout.trim(), stdout, unstaged.stdout, staged.stdout, untrackedDigest].join("\0"))
328
+ .update([head, statusOutput, unstaged.stdout, staged.stdout, untrackedDigest].join("\0"))
72
329
  .digest("hex");
73
330
  }
74
331
  catch {
@@ -1,4 +1,6 @@
1
+ import type { WorkspaceSubjectHashOptions } from "./artifact-subject.js";
1
2
  export type VerificationVerdict = "pass" | "fail";
3
+ export type VerificationSubjectMode = "legacy-head" | "base-relative";
2
4
  /**
3
5
  * A verifier's verdict, recorded on disk beside the task (spec 036, D6).
4
6
  *
@@ -17,7 +19,7 @@ export interface VerificationAttestation {
17
19
  bodyHash: string;
18
20
  evidence: string;
19
21
  workspaceChanged: boolean;
20
- /** Git HEAD + working-tree subject that the verifier actually inspected. */
22
+ /** Git subject that the verifier actually inspected. */
21
23
  subjectHash?: string;
22
24
  /**
23
25
  * The checkout `subjectHash` was computed in. Recorded so `verify` and `complete` recompute the
@@ -27,6 +29,17 @@ export interface VerificationAttestation {
27
29
  * a PASS against an unrelated repository. Absent on attestations written before this field.
28
30
  */
29
31
  subjectDir?: string;
32
+ /**
33
+ * New attestations use a fixed base commit and compare the current content relative to it. The
34
+ * old field-less form is the legacy HEAD-sensitive subject and is retained for compatibility.
35
+ */
36
+ subjectMode?: VerificationSubjectMode;
37
+ /** Commit recorded before the verifier started, for `subjectMode: "base-relative"`. */
38
+ subjectBaseCommit?: string;
39
+ /** Untracked paths, plus ignored non-transient paths, present at verification start; existing
40
+ * paths remain protected even when new files under the explicit transient-artifact scope are
41
+ * allowed. Ignored paths inside that explicit scope are treated as generated at every snapshot. */
42
+ subjectBaselineUntrackedPaths?: string[];
30
43
  /**
31
44
  * `enforced` — a built-in verifier that could not write at all: write/edit are structurally
32
45
  * removed before it runs, and its role declared no `bash` either (a real gate). `advisory` —
@@ -38,8 +51,17 @@ export interface VerificationAttestation {
38
51
  */
39
52
  verificationStrength: "enforced" | "advisory";
40
53
  }
54
+ /**
55
+ * Trusted context supplied by a task consumer from the persisted sub-agent run record. The
56
+ * attestation file is evidence, not the authority for which checkout was verified.
57
+ */
58
+ export interface VerificationAttestationReadOptions {
59
+ trustedWorkingDirectory?: string;
60
+ }
41
61
  export declare function verificationDir(channelDir: string): string;
42
62
  export declare function verificationAttestationPath(channelDir: string, runId: string): string;
43
63
  export declare function parseVerificationVerdict(output: string): VerificationVerdict | undefined;
64
+ /** Translate an attestation's subject metadata into the hash options used by verify/close. */
65
+ export declare function getVerificationSubjectHashOptions(attestation: Pick<VerificationAttestation, "subjectMode" | "subjectBaseCommit" | "subjectBaselineUntrackedPaths">): WorkspaceSubjectHashOptions | undefined;
44
66
  export declare function writeVerificationAttestation(channelDir: string, input: Omit<VerificationAttestation, "version" | "bodyHash">): Promise<VerificationAttestation>;
45
- export declare function readVerificationAttestation(channelDir: string, runId: string): Promise<VerificationAttestation>;
67
+ export declare function readVerificationAttestation(channelDir: string, runId: string, options?: VerificationAttestationReadOptions): Promise<VerificationAttestation>;
@@ -1,10 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { realpathSync, statSync } from "node:fs";
2
3
  import { mkdir, readFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
+ import { isAbsolute, join, win32 } from "node:path";
4
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
6
  import { parseLocalTime } from "../shared/local-time.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  import { readStoredTask, taskBodyHash } from "./store.js";
9
+ const FULL_COMMIT_PATTERN = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i;
8
10
  function attestationFilename(runId) {
9
11
  return `${createHash("sha256").update(runId).digest("hex")}.json`;
10
12
  }
@@ -18,10 +20,43 @@ export function parseVerificationVerdict(output) {
18
20
  const value = /(?:^|\n)VERDICT:\s*(PASS|FAIL)\s*$/i.exec(output.trim())?.[1]?.toLowerCase();
19
21
  return value === "pass" || value === "fail" ? value : undefined;
20
22
  }
23
+ /** Translate an attestation's subject metadata into the hash options used by verify/close. */
24
+ export function getVerificationSubjectHashOptions(attestation) {
25
+ if (attestation.subjectMode !== "base-relative" && attestation.subjectBaseCommit === undefined)
26
+ return undefined;
27
+ if (attestation.subjectBaseCommit === undefined)
28
+ return undefined;
29
+ if (attestation.subjectMode === "base-relative" && attestation.subjectBaselineUntrackedPaths === undefined)
30
+ return undefined;
31
+ return {
32
+ baseCommit: attestation.subjectBaseCommit,
33
+ baselineUntrackedPaths: attestation.subjectBaselineUntrackedPaths ?? [],
34
+ };
35
+ }
21
36
  export async function writeVerificationAttestation(channelDir, input) {
22
37
  const task = await readStoredTask(channelDir, input.taskId);
23
38
  if (!task)
24
39
  throw new Error(`Cannot attest verification: task "${input.taskId}" does not exist.`);
40
+ const hasSubjectHash = input.subjectHash !== undefined;
41
+ const subjectMode = hasSubjectHash
42
+ ? (input.subjectMode ?? (input.subjectBaseCommit !== undefined ? "base-relative" : "legacy-head"))
43
+ : input.subjectMode;
44
+ if (subjectMode === "base-relative" &&
45
+ (input.subjectBaseCommit === undefined ||
46
+ !FULL_COMMIT_PATTERN.test(input.subjectBaseCommit.trim()) ||
47
+ !input.subjectBaselineUntrackedPaths)) {
48
+ throw new Error("Cannot attest verification: base-relative subject metadata is incomplete.");
49
+ }
50
+ if (subjectMode === "legacy-head" &&
51
+ (input.subjectBaseCommit !== undefined || input.subjectBaselineUntrackedPaths !== undefined)) {
52
+ throw new Error("Cannot attest verification: legacy-head subject cannot carry base-relative metadata.");
53
+ }
54
+ if (!hasSubjectHash &&
55
+ (subjectMode !== undefined ||
56
+ input.subjectBaseCommit !== undefined ||
57
+ input.subjectBaselineUntrackedPaths !== undefined)) {
58
+ throw new Error("Cannot attest verification: subject metadata requires a subject hash.");
59
+ }
25
60
  const attestation = {
26
61
  version: 1,
27
62
  runId: input.runId,
@@ -32,14 +67,39 @@ export async function writeVerificationAttestation(channelDir, input) {
32
67
  evidence: input.evidence,
33
68
  workspaceChanged: input.workspaceChanged,
34
69
  subjectHash: input.subjectHash,
35
- subjectDir: input.subjectHash ? input.subjectDir : undefined,
70
+ subjectDir: hasSubjectHash ? input.subjectDir : undefined,
71
+ subjectMode,
72
+ subjectBaseCommit: subjectMode === "base-relative" ? input.subjectBaseCommit : undefined,
73
+ subjectBaselineUntrackedPaths: subjectMode === "base-relative" ? [...(input.subjectBaselineUntrackedPaths ?? [])] : undefined,
36
74
  verificationStrength: input.verificationStrength,
37
75
  };
38
76
  await mkdir(verificationDir(channelDir), { recursive: true });
39
77
  await writeFileAtomically(verificationAttestationPath(channelDir, input.runId), `${JSON.stringify(attestation, null, 2)}\n`);
40
78
  return attestation;
41
79
  }
42
- export async function readVerificationAttestation(channelDir, runId) {
80
+ function canonicalDirectory(path) {
81
+ try {
82
+ const canonical = realpathSync(path);
83
+ return statSync(canonical).isDirectory() ? canonical : undefined;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ function bindSubjectDirectory(runId, subjectDir, options) {
90
+ if (!options || subjectDir === undefined)
91
+ return subjectDir;
92
+ if (!options.trustedWorkingDirectory) {
93
+ throw new Error(`Verification run "${runId}" has a subjectDir but no persisted workingDirectory is available; refusing to trust this attestation. Rerun the verifier.`);
94
+ }
95
+ const canonicalSubjectDir = canonicalDirectory(subjectDir);
96
+ const canonicalWorkingDirectory = canonicalDirectory(options.trustedWorkingDirectory);
97
+ if (!canonicalSubjectDir || !canonicalWorkingDirectory || canonicalSubjectDir !== canonicalWorkingDirectory) {
98
+ throw new Error(`Verification run "${runId}" subjectDir does not match its persisted workingDirectory; refusing to trust this attestation. Rerun the verifier.`);
99
+ }
100
+ return canonicalSubjectDir;
101
+ }
102
+ export async function readVerificationAttestation(channelDir, runId, options) {
43
103
  let value;
44
104
  try {
45
105
  value = JSON.parse(await readFile(verificationAttestationPath(channelDir, runId), "utf-8"));
@@ -47,29 +107,61 @@ export async function readVerificationAttestation(channelDir, runId) {
47
107
  catch (error) {
48
108
  throw new Error(`Verification run "${runId}" was not found or is unreadable. Run a subagent with purpose=verify and taskId first. ${errorMessage(error)}`);
49
109
  }
110
+ const raw = (typeof value === "object" && value !== null ? value : {});
111
+ const subjectMode = raw.subjectMode !== undefined
112
+ ? raw.subjectMode
113
+ : raw.subjectBaseCommit !== undefined
114
+ ? "base-relative"
115
+ : "legacy-head";
116
+ const safeSubjectPath = (path) => {
117
+ const normalized = path.replaceAll("\\", "/");
118
+ return (path.length > 0 &&
119
+ !isAbsolute(path) &&
120
+ !win32.isAbsolute(path) &&
121
+ !path.includes("\0") &&
122
+ !normalized.split("/").includes(".."));
123
+ };
50
124
  if (typeof value !== "object" ||
51
125
  value === null ||
52
- value.version !== 1 ||
53
- value.runId !== runId ||
54
- typeof value.taskId !== "string" ||
55
- (value.verdict !== "pass" && value.verdict !== "fail") ||
56
- typeof value.checkedAt !== "string" ||
57
- parseLocalTime(value.checkedAt) === undefined ||
58
- !/^[a-f0-9]{64}$/i.test(String(value.bodyHash)) ||
59
- typeof value.evidence !== "string" ||
60
- typeof value.workspaceChanged !== "boolean" ||
61
- (value.subjectHash !== undefined &&
62
- !/^[a-f0-9]{64}$/i.test(String(value.subjectHash))) ||
63
- (value.subjectDir !== undefined &&
64
- typeof value.subjectDir !== "string") ||
65
- (value.verificationStrength !== undefined &&
66
- value.verificationStrength !== "enforced" &&
67
- value.verificationStrength !== "advisory")) {
126
+ raw.version !== 1 ||
127
+ raw.runId !== runId ||
128
+ typeof raw.taskId !== "string" ||
129
+ (raw.verdict !== "pass" && raw.verdict !== "fail") ||
130
+ typeof raw.checkedAt !== "string" ||
131
+ parseLocalTime(raw.checkedAt) === undefined ||
132
+ !/^[a-f0-9]{64}$/i.test(String(raw.bodyHash)) ||
133
+ typeof raw.evidence !== "string" ||
134
+ typeof raw.workspaceChanged !== "boolean" ||
135
+ (raw.subjectHash !== undefined && !/^[a-f0-9]{64}$/i.test(String(raw.subjectHash))) ||
136
+ (raw.subjectDir !== undefined && typeof raw.subjectDir !== "string") ||
137
+ (raw.subjectMode !== undefined && subjectMode !== "legacy-head" && subjectMode !== "base-relative") ||
138
+ (raw.subjectBaseCommit !== undefined &&
139
+ (typeof raw.subjectBaseCommit !== "string" || !FULL_COMMIT_PATTERN.test(raw.subjectBaseCommit.trim()))) ||
140
+ (raw.subjectBaselineUntrackedPaths !== undefined &&
141
+ (!Array.isArray(raw.subjectBaselineUntrackedPaths) ||
142
+ raw.subjectBaselineUntrackedPaths.some((path) => typeof path !== "string" || !safeSubjectPath(path)))) ||
143
+ (raw.subjectHash === undefined &&
144
+ (raw.subjectMode !== undefined ||
145
+ raw.subjectBaseCommit !== undefined ||
146
+ raw.subjectBaselineUntrackedPaths !== undefined)) ||
147
+ (raw.subjectHash !== undefined &&
148
+ (subjectMode === "base-relative"
149
+ ? typeof raw.subjectBaseCommit !== "string" || !Array.isArray(raw.subjectBaselineUntrackedPaths)
150
+ : raw.subjectBaseCommit !== undefined || raw.subjectBaselineUntrackedPaths !== undefined)) ||
151
+ (raw.verificationStrength !== undefined &&
152
+ raw.verificationStrength !== "enforced" &&
153
+ raw.verificationStrength !== "advisory")) {
68
154
  throw new Error(`Verification run "${runId}" has an invalid attestation. Run the verifier again.`);
69
155
  }
70
- // Pre-spec-040 attestations predate this field; every verifier back then was built-in.
71
- return {
156
+ // Pre-spec-040 attestations predate this field; every verifier back then was built-in. When an
157
+ // old attestation also lacks subjectDir, consumers may keep its legacy subject semantics. A
158
+ // subjectDir-bearing attestation is newer and, when read by task lifecycle code, must be bound to
159
+ // a still-available persisted run record instead of choosing an arbitrary checkout.
160
+ const attestation = {
72
161
  ...value,
162
+ subjectMode: subjectMode,
73
163
  verificationStrength: value.verificationStrength ?? "enforced",
74
164
  };
165
+ const boundSubjectDir = bindSubjectDirectory(runId, attestation.subjectDir, options);
166
+ return boundSubjectDir === attestation.subjectDir ? attestation : { ...attestation, subjectDir: boundSubjectDir };
75
167
  }
@@ -166,7 +166,10 @@ export function createGrepTool(executor, options = {}) {
166
166
  flags.push(`--exclude-dir=${segment}`);
167
167
  }
168
168
  if (glob) {
169
- flags.push(`--include=${glob}`);
169
+ // Model-controlled, so it must be shell-escaped like the pattern and path below -- the
170
+ // executor runs the command via `sh -c`, and an unescaped glob such as `*.ts; rm -rf x`
171
+ // would otherwise run as an extra command instead of matching nothing.
172
+ flags.push(`--include=${shellEscape(glob)}`);
170
173
  }
171
174
  // `--` terminates flags so a pattern beginning with `-` is not read as one. Bounded via
172
175
  // `maxCaptureBytes` (D5.2) rather than a `| head -n` pipe: piping through `head` would
@@ -198,9 +198,9 @@ export function createSubAgentRunTool(options) {
198
198
  if (role.shell) {
199
199
  throw new RecoverableToolError(`Role "${record.agent}" runs its command through a shell, which has no way to carry a resume session id. Delegate a new run instead, carrying forward whatever context it needs.`);
200
200
  }
201
- // Spec 042 D7: verify admission is re-checked against the *current* role config, shared
202
- // with the initial dispatch — a role hot-edited to mutates: write since the original run
203
- // must not silently take the write lease and dispatch just because it once was read-only.
201
+ // Verify admission is re-checked against the *current* role config, shared with the initial
202
+ // dispatch. A write-capable verify follow-up takes the same exclusive lease as any writer;
203
+ // `exec` remains barred because it has no verification protocol terminal.
204
204
  assertVerifyAdmissible(role, record.purpose, record.workingDirectory);
205
205
  // Spec 042 D7: a role hot-edited since the original dispatch (different command, model,
206
206
  // or shell mode) would resume the old session under a harness invocation it never wrote.
@@ -245,19 +245,19 @@ export function createSubAgentRunTool(options) {
245
245
  // inside `buildContextualBlocks` — optional here so a caller that only ever exercises
246
246
  // list/cancel is not forced to wire an LLM-backed dependency it will never use. Absent
247
247
  // either, context blocks degrade to none rather than guessing at a model or key.
248
- const contextualBlocks = options.getCurrentModel && options.resolveApiKey
249
- ? await buildContextualBlocks(task, role, {
250
- channelDir: options.channelDir,
251
- workspaceDir: options.workspaceDir,
252
- runtimeContext: { workspaceDir: options.workspaceDir, channelId: options.channelId },
253
- getMemoryRecallSettings: options.getMemoryRecallSettings,
254
- resolveApiKey: options.resolveApiKey,
255
- memoryCandidateStore: options.memoryCandidateStore,
256
- }, options.getCurrentModel())
257
- : [];
258
- const envelopedTask = buildSubAgentTask(task, role, { workspaceDir: options.workspaceDir, channelId: options.channelId }, contextualBlocks, runContext);
259
248
  let launchResult;
260
249
  try {
250
+ const contextualBlocks = options.getCurrentModel && options.resolveApiKey
251
+ ? await buildContextualBlocks(task, role, {
252
+ channelDir: options.channelDir,
253
+ workspaceDir: options.workspaceDir,
254
+ runtimeContext: { workspaceDir: options.workspaceDir, channelId: options.channelId },
255
+ getMemoryRecallSettings: options.getMemoryRecallSettings,
256
+ resolveApiKey: options.resolveApiKey,
257
+ memoryCandidateStore: options.memoryCandidateStore,
258
+ }, options.getCurrentModel())
259
+ : [];
260
+ const envelopedTask = buildSubAgentTask(task, role, { workspaceDir: options.workspaceDir, channelId: options.channelId }, contextualBlocks, runContext);
261
261
  launchResult = await launchExternalRun({
262
262
  runId: newRunId,
263
263
  channelId: options.channelId,