@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.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 (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -1,334 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { lstat, readFile, readlink } from "node:fs/promises";
4
- import { isAbsolute, join, win32 } from "node:path";
5
- import { promisify } from "node:util";
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
- }
67
- /**
68
- * git quotes a path containing special characters in double quotes with C-style escapes (spec
69
- * 040, D9). `JSON.parse` accepts the same escape set for the characters git actually emits
70
- * (`\"`, `\\`, `\t`, `\n`) and is close enough for a hash input; a path so exotic it defeats this
71
- * still contributes a value to the hash; it just won't be the literal decoded path.
72
- */
73
- function unquoteGitPath(raw) {
74
- if (raw.startsWith('"') && raw.endsWith('"')) {
75
- try {
76
- return JSON.parse(raw);
77
- }
78
- catch {
79
- return raw;
80
- }
81
- }
82
- return raw;
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
- }
112
- /**
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.
116
- */
117
- async function legacyUntrackedFileDigest(workingDirectory, statusOutput) {
118
- const paths = parseUntrackedPaths(statusOutput);
119
- const hash = createHash("sha256");
120
- for (const relativePath of paths) {
121
- hash.update(relativePath);
122
- try {
123
- hash.update(await readFile(join(workingDirectory, relativePath)));
124
- }
125
- catch {
126
- // Unreadable — the path alone still went into the hash above.
127
- }
128
- }
129
- return hash.digest("hex");
130
- }
131
- /**
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.
280
- */
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
- }
315
- try {
316
- const statusOutput = await readGitStatus(workingDirectory);
317
- const [head, unstaged, staged, untrackedDigest] = await Promise.all([
318
- readGitHead(workingDirectory),
319
- execFileAsync("git", ["-C", workingDirectory, "diff", "--no-ext-diff", "--binary"], {
320
- maxBuffer: 4 * 1024 * 1024,
321
- }),
322
- execFileAsync("git", ["-C", workingDirectory, "diff", "--cached", "--no-ext-diff", "--binary"], {
323
- maxBuffer: 4 * 1024 * 1024,
324
- }),
325
- legacyUntrackedFileDigest(workingDirectory, statusOutput),
326
- ]);
327
- return createHash("sha256")
328
- .update([head, statusOutput, unstaged.stdout, staged.stdout, untrackedDigest].join("\0"))
329
- .digest("hex");
330
- }
331
- catch {
332
- return undefined;
333
- }
334
- }
@@ -1,48 +0,0 @@
1
- import type { TaskCycle } from "./frontmatter.js";
2
- /**
3
- * Cycle boundaries (spec 051, §3.2).
4
- *
5
- * A cycle is the unit of work a task session's context is scoped to: opened when a one-shot task
6
- * is created or a recurring task's schedule fires, closed when the loop reports `done`. v3 marked
7
- * boundaries by shuffling `## Current Cycle` into `## History` inside the task file; v4 keeps the
8
- * per-cycle record in `<id>.jsonl` and leaves exactly one paragraph — `## 上次结果` — in the
9
- * contract, overwritten each time.
10
- */
11
- export declare const LAST_RESULT_SECTION_NAMES: readonly ["上次结果", "Last Result"];
12
- /** Cap for the one historical paragraph the contract carries; the rest lives in the log (INV-6). */
13
- export declare const MAX_LAST_RESULT_CHARS = 1200;
14
- /**
15
- * A stable cycle id for a runtime-opened cycle: `c-YYYY-MM-DD`, disambiguated with `-N` when the
16
- * same task opens more than one cycle on the same local day.
17
- */
18
- export declare function nextCycleId(previousCycleId: string | undefined, occurrence?: Date): string;
19
- /** Fresh counters for a newly opened cycle. */
20
- export declare function createCycle(id: string, now?: Date): TaskCycle;
21
- /**
22
- * Body transformation for opening a cycle. Only recurring tasks reset their Plan: for a one-shot
23
- * task the Plan is the single run's agenda and unchecking it would erase real progress, while for
24
- * a recurring task the same steps genuinely start over each occurrence.
25
- */
26
- export declare function openCycleBody(body: string, recurring: boolean): string;
27
- /**
28
- * Upsert `## 上次结果` — the contract's single, overwritten historical paragraph. Over-long text
29
- * is clipped with a pointer to `task_log`, because the contract has a hard size budget and the
30
- * complete record is already durable in the loop log.
31
- */
32
- export declare function writeLastResult(body: string, text: string): string;
33
- /** Remove `## 上次结果` entirely. The full record is always still in the loop log. */
34
- export declare function stripLastResult(body: string): string;
35
- /** The rendered `## 上次结果` text, if any — used by `/tasks show` and the step brief. */
36
- export declare function readLastResult(body: string): string | undefined;
37
- /** Compose the `## 上次结果` paragraph from a cycle close. */
38
- export declare function renderCloseSummary(input: {
39
- cycleId: string;
40
- outcome: "done" | "cancelled";
41
- summary: string;
42
- evidence?: string;
43
- residualRisk?: string;
44
- steps: number;
45
- rounds: number;
46
- usd: number;
47
- usdEstimated: boolean;
48
- }): string;
@@ -1,94 +0,0 @@
1
- import { formatLocalTime } from "../shared/local-time.js";
2
- import { findTaskSectionBounds, resetTaskPlanForCycle } from "./ledger.js";
3
- /**
4
- * Cycle boundaries (spec 051, §3.2).
5
- *
6
- * A cycle is the unit of work a task session's context is scoped to: opened when a one-shot task
7
- * is created or a recurring task's schedule fires, closed when the loop reports `done`. v3 marked
8
- * boundaries by shuffling `## Current Cycle` into `## History` inside the task file; v4 keeps the
9
- * per-cycle record in `<id>.jsonl` and leaves exactly one paragraph — `## 上次结果` — in the
10
- * contract, overwritten each time.
11
- */
12
- export const LAST_RESULT_SECTION_NAMES = ["上次结果", "Last Result"];
13
- const LAST_RESULT_HEADING = "## 上次结果";
14
- /** Cap for the one historical paragraph the contract carries; the rest lives in the log (INV-6). */
15
- export const MAX_LAST_RESULT_CHARS = 1_200;
16
- /**
17
- * A stable cycle id for a runtime-opened cycle: `c-YYYY-MM-DD`, disambiguated with `-N` when the
18
- * same task opens more than one cycle on the same local day.
19
- */
20
- export function nextCycleId(previousCycleId, occurrence = new Date()) {
21
- const base = `c-${occurrence.getFullYear()}-${String(occurrence.getMonth() + 1).padStart(2, "0")}-${String(occurrence.getDate()).padStart(2, "0")}`;
22
- if (!previousCycleId || !previousCycleId.startsWith(base))
23
- return base;
24
- const suffix = previousCycleId.slice(base.length + 1);
25
- const previousCount = suffix ? Number.parseInt(suffix, 10) : 1;
26
- const nextCount = Number.isFinite(previousCount) && previousCount >= 1 ? previousCount + 1 : 2;
27
- return `${base}-${nextCount}`;
28
- }
29
- /** Fresh counters for a newly opened cycle. */
30
- export function createCycle(id, now = new Date()) {
31
- return { id, startedAt: formatLocalTime(now), steps: 0, rounds: 0, usd: 0, usdEstimated: false, expired: 0 };
32
- }
33
- /**
34
- * Body transformation for opening a cycle. Only recurring tasks reset their Plan: for a one-shot
35
- * task the Plan is the single run's agenda and unchecking it would erase real progress, while for
36
- * a recurring task the same steps genuinely start over each occurrence.
37
- */
38
- export function openCycleBody(body, recurring) {
39
- return recurring ? resetTaskPlanForCycle(body) : body;
40
- }
41
- /**
42
- * Upsert `## 上次结果` — the contract's single, overwritten historical paragraph. Over-long text
43
- * is clipped with a pointer to `task_log`, because the contract has a hard size budget and the
44
- * complete record is already durable in the loop log.
45
- */
46
- export function writeLastResult(body, text) {
47
- const clipped = text.length > MAX_LAST_RESULT_CHARS
48
- ? `${text.slice(0, MAX_LAST_RESULT_CHARS).trimEnd()}…(完整记录见 task_log)`
49
- : text;
50
- const lines = body.split("\n");
51
- const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
52
- const block = [LAST_RESULT_HEADING, "", clipped, ""];
53
- if (bounds) {
54
- lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex, ...block);
55
- return lines.join("\n");
56
- }
57
- return `${body.replace(/\n+$/, "")}\n\n${block.join("\n")}`;
58
- }
59
- /** Remove `## 上次结果` entirely. The full record is always still in the loop log. */
60
- export function stripLastResult(body) {
61
- const lines = body.split("\n");
62
- const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
63
- if (!bounds)
64
- return body;
65
- lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
66
- return lines
67
- .join("\n")
68
- .replace(/\n{3,}/g, "\n\n")
69
- .trimEnd();
70
- }
71
- /** The rendered `## 上次结果` text, if any — used by `/tasks show` and the step brief. */
72
- export function readLastResult(body) {
73
- const lines = body.split("\n");
74
- const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
75
- if (!bounds)
76
- return undefined;
77
- const text = lines
78
- .slice(bounds.headingIndex + 1, bounds.end)
79
- .join("\n")
80
- .trim();
81
- return text || undefined;
82
- }
83
- /** Compose the `## 上次结果` paragraph from a cycle close. */
84
- export function renderCloseSummary(input) {
85
- const cost = `$${input.usd.toFixed(2)}${input.usdEstimated ? "(含估算)" : ""}`;
86
- return [
87
- `- ${input.cycleId} ${input.outcome === "done" ? "完成" : "取消"}:${input.summary}`,
88
- input.evidence ? `- 证据:${input.evidence}` : undefined,
89
- input.residualRisk ? `- 剩余风险:${input.residualRisk}` : undefined,
90
- `- 用量:${input.steps} 步 / ${input.rounds} 轮 / ${cost}`,
91
- ]
92
- .filter(Boolean)
93
- .join("\n");
94
- }
@@ -1,41 +0,0 @@
1
- import { type TaskRoundRecord } from "./log.js";
2
- /**
3
- * Rework accounting (spec 051, D7).
4
- *
5
- * The trace this exists for: one real task ran seven builder→reviewer rounds, six advisory FAILs
6
- * before a PASS, over 2.4 hours of delegation wall time — and its stored state said
7
- * `{"verification":{"required":false,"status":"pending"}}`. The rounds were invisible, so nothing
8
- * could bound them and the user could not see them. Recording a round is bookkeeping the runtime
9
- * already has the facts for at settlement, so it happens there rather than costing a tool call
10
- * and a model decision (`task_verify`, retired).
11
- */
12
- export interface RoundInput {
13
- channelDir: string;
14
- taskId: string;
15
- verifyRunId: string;
16
- verdict: "pass" | "fail";
17
- strength: "enforced" | "advisory";
18
- /** The delegation this verdict judged, when the caller could identify it. */
19
- workRunId?: string;
20
- /** Attributable cost of this run; `estimated` marks a fallback rather than reported usage. */
21
- usd?: number;
22
- usdEstimated?: boolean;
23
- /** Set when the attestation did not hold; the round is then recorded as a fail with this reason. */
24
- reason?: string;
25
- }
26
- export interface RoundResult {
27
- cycleId: string;
28
- round: number;
29
- /** True once `cycle.rounds` has reached the task's rework ceiling. */
30
- overBudget: boolean;
31
- }
32
- /**
33
- * Record one verification round against the task's current cycle and return where that leaves the
34
- * rework budget. Callers must guard this with their own idempotency marker: a replayed settlement
35
- * must not write a second round.
36
- */
37
- export declare function recordVerificationRound(input: RoundInput, roundsBudget: number): Promise<RoundResult | undefined>;
38
- /** Add one run's cost to the task's current cycle. Used for `purpose=work` runs and background jobs. */
39
- export declare function recordTaskCost(channelDir: string, taskId: string, usd: number, estimated: boolean): Promise<void>;
40
- /** The rework rounds recorded in one cycle, oldest first — `/tasks show`'s verdict trail. */
41
- export declare function readCycleRounds(channelDir: string, taskId: string, cycle: string | undefined): Promise<TaskRoundRecord[]>;
@@ -1,53 +0,0 @@
1
- import { appendTaskLog, readTaskLog } from "./log.js";
2
- import { updateStoredTask } from "./store.js";
3
- /**
4
- * Record one verification round against the task's current cycle and return where that leaves the
5
- * rework budget. Callers must guard this with their own idempotency marker: a replayed settlement
6
- * must not write a second round.
7
- */
8
- export async function recordVerificationRound(input, roundsBudget) {
9
- let result;
10
- const document = await updateStoredTask(input.channelDir, input.taskId, (task) => {
11
- const cycle = task.fields.cycle;
12
- if (!cycle)
13
- return;
14
- const rounds = cycle.rounds + 1;
15
- task.fields.cycle = {
16
- ...cycle,
17
- rounds,
18
- usd: cycle.usd + (input.usd ?? 0),
19
- usdEstimated: cycle.usdEstimated || Boolean(input.usdEstimated),
20
- };
21
- const ceiling = task.fields.budget?.rounds ?? roundsBudget;
22
- result = { cycleId: cycle.id, round: rounds, overBudget: rounds >= ceiling };
23
- });
24
- if (!document || !result)
25
- return undefined;
26
- await appendTaskLog(input.channelDir, input.taskId, {
27
- cycle: result.cycleId,
28
- kind: "round",
29
- n: result.round,
30
- workRunId: input.workRunId,
31
- verifyRunId: input.verifyRunId,
32
- verdict: input.verdict,
33
- strength: input.strength,
34
- reason: input.reason,
35
- });
36
- return result;
37
- }
38
- /** Add one run's cost to the task's current cycle. Used for `purpose=work` runs and background jobs. */
39
- export async function recordTaskCost(channelDir, taskId, usd, estimated) {
40
- if (usd <= 0 && !estimated)
41
- return;
42
- await updateStoredTask(channelDir, taskId, (task) => {
43
- const cycle = task.fields.cycle;
44
- if (!cycle)
45
- return;
46
- task.fields.cycle = { ...cycle, usd: cycle.usd + usd, usdEstimated: cycle.usdEstimated || estimated };
47
- });
48
- }
49
- /** The rework rounds recorded in one cycle, oldest first — `/tasks show`'s verdict trail. */
50
- export async function readCycleRounds(channelDir, taskId, cycle) {
51
- const records = await readTaskLog(channelDir, taskId, { cycle, kinds: ["round"] });
52
- return records.filter((record) => record.kind === "round");
53
- }
@@ -1,6 +0,0 @@
1
- export interface ParsedTaskEventName {
2
- id: string;
3
- use: string;
4
- }
5
- export declare function taskEventPrefix(channelId: string, id?: string): string;
6
- export declare function parseTaskEventName(name: string, channelId: string): ParsedTaskEventName | undefined;
@@ -1,14 +0,0 @@
1
- export function taskEventPrefix(channelId, id) {
2
- return id ? `task.${channelId}.${id}.` : `task.${channelId}.`;
3
- }
4
- export function parseTaskEventName(name, channelId) {
5
- const normalized = name.endsWith(".json") ? name.slice(0, -".json".length) : name;
6
- const prefix = taskEventPrefix(channelId);
7
- if (!normalized.startsWith(prefix))
8
- return undefined;
9
- const rest = normalized.slice(prefix.length);
10
- const lastDot = rest.lastIndexOf(".");
11
- if (lastDot <= 0 || lastDot === rest.length - 1)
12
- return undefined;
13
- return { id: rest.slice(0, lastDot), use: rest.slice(lastDot + 1) };
14
- }
@@ -1,18 +0,0 @@
1
- /**
2
- * The cron cadence of a recurring task lives in its `schedule` frontmatter key.
3
- * Cron is always interpreted in the host timezone — tasks (and events) follow the
4
- * person on their machine, so no `timezone` field or config exists.
5
- */
6
- /** A task schedule may fire no more often than this (anti-self-nudge floor). */
7
- export declare const MIN_TASK_SCHEDULE_INTERVAL_MS: number;
8
- /**
9
- * Validate a task `schedule` cron: it must parse (host timezone) and fire no more
10
- * often than every 30 minutes. Throws with an agent-readable message otherwise.
11
- * Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
12
- */
13
- export declare function validateTaskSchedule(schedule: string): void;
14
- /**
15
- * Next occurrence of a task `schedule` strictly after `from`, or undefined when the
16
- * cron cannot be parsed (the caller decides how to surface that).
17
- */
18
- export declare function nextTaskWake(schedule: string, from?: Date): Date | undefined;
@@ -1,50 +0,0 @@
1
- import { Cron } from "croner";
2
- import { errorMessage } from "../shared/text-utils.js";
3
- /**
4
- * The cron cadence of a recurring task lives in its `schedule` frontmatter key.
5
- * Cron is always interpreted in the host timezone — tasks (and events) follow the
6
- * person on their machine, so no `timezone` field or config exists.
7
- */
8
- /** A task schedule may fire no more often than this (anti-self-nudge floor). */
9
- export const MIN_TASK_SCHEDULE_INTERVAL_MS = 30 * 60 * 1000;
10
- /**
11
- * Validate a task `schedule` cron: it must parse (host timezone) and fire no more
12
- * often than every 30 minutes. Throws with an agent-readable message otherwise.
13
- * Mirrors the `event_manage` periodic gate so both write paths reject the same cron.
14
- */
15
- export function validateTaskSchedule(schedule) {
16
- let runs;
17
- try {
18
- const cron = new Cron(schedule);
19
- runs = cron.nextRuns(3);
20
- cron.stop();
21
- }
22
- catch (error) {
23
- throw new Error(`schedule "${schedule}" is not a valid cron: ${errorMessage(error)}`);
24
- }
25
- if (runs.length === 0) {
26
- throw new Error(`schedule "${schedule}" never fires; use a valid five-field cron.`);
27
- }
28
- const floorMinutes = Math.round(MIN_TASK_SCHEDULE_INTERVAL_MS / 60_000);
29
- // Fewer than two upcoming runs means no cadence to rate-limit (e.g. a one-off cron); allow it.
30
- for (let i = 1; i < runs.length; i++) {
31
- if (runs[i].getTime() - runs[i - 1].getTime() < MIN_TASK_SCHEDULE_INTERVAL_MS) {
32
- throw new Error(`schedule "${schedule}" must fire no more often than every ${floorMinutes} minutes.`);
33
- }
34
- }
35
- }
36
- /**
37
- * Next occurrence of a task `schedule` strictly after `from`, or undefined when the
38
- * cron cannot be parsed (the caller decides how to surface that).
39
- */
40
- export function nextTaskWake(schedule, from = new Date()) {
41
- try {
42
- const cron = new Cron(schedule);
43
- const next = cron.nextRun(from);
44
- cron.stop();
45
- return next ?? undefined;
46
- }
47
- catch {
48
- return undefined;
49
- }
50
- }