@oyasmi/pipiclaw 0.9.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.
Files changed (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -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);
@@ -57,5 +57,5 @@ export function findWorkspaceLeaseHolder(workingDirectory) {
57
57
  export function formatWorkspaceLeaseConflict(heldBy) {
58
58
  return (`Workspace "${heldBy.workingDirectory}" is already held by a running write delegation ` +
59
59
  `(runId ${heldBy.runId}, channel ${heldBy.channelId}). Wait for it to finish, cancel it with ` +
60
- "subagent_manage, or use a separate `git worktree add` checkout via workingDirectory.");
60
+ "subagent_run op=cancel, or use a separate `git worktree add` checkout via workingDirectory.");
61
61
  }
@@ -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 {
@@ -1,10 +1,8 @@
1
1
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
+ import { isPlainObject } from "../shared/type-guards.js";
3
4
  const WAITING_FOR = ["time", "user", "job", "external-signal"];
4
5
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
5
- function isRecord(value) {
6
- return typeof value === "object" && value !== null && !Array.isArray(value);
7
- }
8
6
  function optionalString(value) {
9
7
  if (typeof value !== "string")
10
8
  return undefined;
@@ -22,7 +20,7 @@ function enumValue(value, values, fallback) {
22
20
  function parseStop(value) {
23
21
  if (value === undefined)
24
22
  return undefined;
25
- if (!isRecord(value))
23
+ if (!isPlainObject(value))
26
24
  throw new Error("control.stop must be an object");
27
25
  const by = enumValue(value.by, ["user", "governor"], "user");
28
26
  const reason = optionalString(value.reason);
@@ -47,10 +45,10 @@ export function parseTaskControl(raw) {
47
45
  catch (error) {
48
46
  throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
49
47
  }
50
- if (!isRecord(value) || value.version !== 3) {
51
- throw new Error("control must be a version 3 JSON object; repair it with task_manage set.");
48
+ if (!isPlainObject(value) || value.version !== 3) {
49
+ throw new Error("control must be a version 3 JSON object; repair it with task_update (no note).");
52
50
  }
53
- const verification = isRecord(value.verification) ? value.verification : {};
51
+ const verification = isPlainObject(value.verification) ? value.verification : {};
54
52
  const deadline = optionalString(value.deadline);
55
53
  if (deadline && parseLocalTime(deadline) === undefined) {
56
54
  throw new Error("control.deadline must be a valid local time");
@@ -83,10 +81,10 @@ export function parseLegacyTaskControl(raw) {
83
81
  catch (error) {
84
82
  throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
85
83
  }
86
- if (!isRecord(value) || (value.version !== 1 && value.version !== 2)) {
84
+ if (!isPlainObject(value) || (value.version !== 1 && value.version !== 2)) {
87
85
  throw new Error("legacy control must be a version 1 or version 2 JSON object");
88
86
  }
89
- const verification = isRecord(value.verification) ? value.verification : {};
87
+ const verification = isPlainObject(value.verification) ? value.verification : {};
90
88
  const deadline = optionalString(value.deadline);
91
89
  const waitingFor = value.waitingFor === undefined ? undefined : enumValue(value.waitingFor, WAITING_FOR, "external-signal");
92
90
  let stop = parseStop(value.stop);
@@ -10,7 +10,7 @@ export type TaskArchiveOutcome = "completed" | "cancelled";
10
10
  * has a single owner. The parsing stays deliberately literal (flat `key: value` fields,
11
11
  * live-vs-archived, wake gating, fail-open on unreadable frontmatter) because task files
12
12
  * are hand-editable and must degrade toward "wake me up so I can be fixed".
13
- * `/tasks`, the task digest, and `task_manage list` all read through here.
13
+ * `/tasks`, the task digest, and `task_list` all read through here.
14
14
  */
15
15
  export interface TaskFrontmatter {
16
16
  /** false => frontmatter could not be read (fail-open: the task is treated as actionable). */
@@ -183,7 +183,7 @@ export declare function missingStandardTaskSections(content: string): string[];
183
183
  * Without the "no checklist items" case, a DoD written as prose or a numbered
184
184
  * list (no `- [ ]` anywhere) makes this function return an empty array —
185
185
  * indistinguishable from "everything is checked" — which would silently let
186
- * `task_manage complete` through with nothing ever actually verified.
186
+ * `task_close outcome=complete` through with nothing ever actually verified.
187
187
  */
188
188
  export declare function uncheckedTaskAcceptanceItems(content: string): string[];
189
189
  /**
@@ -2,6 +2,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
4
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
5
+ import { normalizeSafeId } from "../shared/safe-id.js";
5
6
  import { parseTaskControl } from "./control.js";
6
7
  import { nextTaskWake } from "./task-schedule.js";
7
8
  import { normalizeStoredStatus } from "./transitions.js";
@@ -30,12 +31,7 @@ const HISTORY_OMISSION_NOTE = "- Older cycle details omitted from working contex
30
31
  const HISTORY_TRUNCATION_NOTE = "- Entry truncated in working context; use session_search with the task id or cycle id to inspect the complete cold history.";
31
32
  /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
32
33
  export function normalizeTaskId(id) {
33
- const trimmed = id.trim();
34
- const normalized = trimmed.endsWith(".md") ? trimmed.slice(0, -".md".length) : trimmed;
35
- if (!normalized || normalized === "." || normalized === ".." || !TASK_ID_PATTERN.test(normalized)) {
36
- throw new Error(`Invalid task id: ${id}`);
37
- }
38
- return normalized;
34
+ return normalizeSafeId(id, { suffix: ".md", pattern: TASK_ID_PATTERN, label: "task id" });
39
35
  }
40
36
  /** The document body after the leading frontmatter block, or the whole content when there is none. */
41
37
  export function taskBody(content) {
@@ -366,7 +362,7 @@ export function missingStandardTaskSections(content) {
366
362
  * Without the "no checklist items" case, a DoD written as prose or a numbered
367
363
  * list (no `- [ ]` anywhere) makes this function return an empty array —
368
364
  * indistinguishable from "everything is checked" — which would silently let
369
- * `task_manage complete` through with nothing ever actually verified.
365
+ * `task_close outcome=complete` through with nothing ever actually verified.
370
366
  */
371
367
  export function uncheckedTaskAcceptanceItems(content) {
372
368
  const unchecked = [];
@@ -4,7 +4,11 @@ export type TaskStatus = (typeof TASK_STATUSES)[number];
4
4
  /** Statuses a model/user may set directly; recurring sleeping is runtime-owned but repairable. */
5
5
  export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "sleeping"];
6
6
  export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
7
- export type TaskLifecycleAction = "create" | "progress" | "verify" | "complete" | "skip" | "cancel" | "set" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
7
+ export type TaskLifecycleAction = "create"
8
+ /** task_update with a `note` — a checkpoint on an open cycle. */
9
+ | "checkpoint" | "verify" | "complete" | "skip" | "cancel"
10
+ /** task_update with no `note` — a metadata-only edit (spec 046, D3.2). */
11
+ | "metadata" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
8
12
  /** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
9
13
  export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
10
14
  export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
@@ -7,7 +7,7 @@ const LIVE = ["active", "waiting", "sleeping"];
7
7
  const WORKABLE = ["active", "waiting"];
8
8
  const TRANSITIONS = {
9
9
  create: { from: [], to: "active" },
10
- progress: { from: WORKABLE, to: "caller" },
10
+ checkpoint: { from: WORKABLE, to: "caller" },
11
11
  // Not gated on a specific waitingFor value: the wake that reactivates a task parked for a
12
12
  // purpose=verify sub-agent already flips it to active before this runs (the same as any other
13
13
  // delegation wake), but `verify` also accepts waiting so it is not sensitive to exactly when
@@ -16,7 +16,7 @@ const TRANSITIONS = {
16
16
  complete: { from: ["active"], to: "caller" },
17
17
  skip: { from: WORKABLE, to: "sleeping" },
18
18
  cancel: { from: LIVE, to: "caller" },
19
- set: { from: LIVE, to: "caller" },
19
+ metadata: { from: LIVE, to: "caller" },
20
20
  pause: { from: LIVE, to: "caller" },
21
21
  resume: { from: LIVE, to: "caller" },
22
22
  run: { from: LIVE, to: "active" },
@@ -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>;