@narumitw/pi-subagents 0.51.0 → 0.52.0
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.
- package/README.md +50 -1
- package/package.json +1 -1
- package/src/adaptive-scheduler.ts +29 -1
- package/src/execution.ts +291 -41
- package/src/inspect.ts +25 -0
- package/src/orchestration-metrics.ts +31 -0
- package/src/panel-execution.ts +0 -2
- package/src/params.ts +8 -1
- package/src/verification-policy.ts +50 -0
- package/src/work-item-ledger.ts +267 -18
- package/src/work-item-persistence.ts +5 -0
- package/src/workflow-planning.ts +13 -1
- package/src/workflow-tree-identity.ts +289 -0
- package/src/workflow-verification.ts +296 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash, type Hash } from "node:crypto";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
|
|
6
|
+
export const WORKFLOW_TREE_IDENTITY_VERSION = "pi-subagents:workflow-tree:v1" as const;
|
|
7
|
+
export const DEFAULT_WORKFLOW_TREE_MAX_BYTES = 1024 * 1024;
|
|
8
|
+
const MAX_UNTRACKED_FILES = 256;
|
|
9
|
+
|
|
10
|
+
export interface WorkflowTreeIdentity {
|
|
11
|
+
version: typeof WORKFLOW_TREE_IDENTITY_VERSION;
|
|
12
|
+
kind: "git-commit" | "git-dirty";
|
|
13
|
+
digest: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface CaptureWorkflowTreeIdentityOptions {
|
|
17
|
+
maxBytes?: number;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function captureWorkflowTreeIdentity(
|
|
22
|
+
cwd: string,
|
|
23
|
+
options: CaptureWorkflowTreeIdentityOptions = {},
|
|
24
|
+
): Promise<WorkflowTreeIdentity> {
|
|
25
|
+
const maxBytes = options.maxBytes ?? DEFAULT_WORKFLOW_TREE_MAX_BYTES;
|
|
26
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
|
|
27
|
+
throw new Error("Workflow tree identity maxBytes must be a positive safe integer");
|
|
28
|
+
}
|
|
29
|
+
throwIfAborted(options.signal);
|
|
30
|
+
let canonicalCwd: string;
|
|
31
|
+
try {
|
|
32
|
+
canonicalCwd = await fs.promises.realpath(path.resolve(cwd));
|
|
33
|
+
} catch {
|
|
34
|
+
throw new Error("Workflow verification requires a readable Git repository directory");
|
|
35
|
+
}
|
|
36
|
+
const rootOutput = await git(
|
|
37
|
+
canonicalCwd,
|
|
38
|
+
["rev-parse", "--show-toplevel"],
|
|
39
|
+
64 * 1024,
|
|
40
|
+
options.signal,
|
|
41
|
+
).catch((error) => {
|
|
42
|
+
throw normalizedGitError(error, "Workflow verification requires a Git repository");
|
|
43
|
+
});
|
|
44
|
+
let repositoryRoot: string;
|
|
45
|
+
try {
|
|
46
|
+
repositoryRoot = await fs.promises.realpath(rootOutput.toString("utf8").trim());
|
|
47
|
+
} catch {
|
|
48
|
+
throw new Error("Workflow verification requires a readable Git repository root");
|
|
49
|
+
}
|
|
50
|
+
const relativeCwd = path.relative(repositoryRoot, canonicalCwd);
|
|
51
|
+
if (relativeCwd.startsWith("..") || path.isAbsolute(relativeCwd)) {
|
|
52
|
+
throw new Error("Workflow verification cwd is outside its Git repository");
|
|
53
|
+
}
|
|
54
|
+
const submodules = await git(
|
|
55
|
+
repositoryRoot,
|
|
56
|
+
["submodule", "status", "--recursive"],
|
|
57
|
+
64 * 1024,
|
|
58
|
+
options.signal,
|
|
59
|
+
).catch((error) => {
|
|
60
|
+
throw normalizedGitError(error, "Workflow tree identity could not inspect submodules");
|
|
61
|
+
});
|
|
62
|
+
if (submodules.toString("utf8").trim()) {
|
|
63
|
+
throw new Error("Workflow tree identity does not support repositories with submodules");
|
|
64
|
+
}
|
|
65
|
+
const head = (
|
|
66
|
+
await git(repositoryRoot, ["rev-parse", "HEAD"], 64 * 1024, options.signal).catch((error) => {
|
|
67
|
+
throw normalizedGitError(error, "Workflow verification requires a stable Git HEAD");
|
|
68
|
+
})
|
|
69
|
+
)
|
|
70
|
+
.toString("utf8")
|
|
71
|
+
.trim();
|
|
72
|
+
if (!/^[a-f0-9]{40,64}$/u.test(head)) {
|
|
73
|
+
throw new Error("Workflow verification requires a stable Git HEAD");
|
|
74
|
+
}
|
|
75
|
+
const commandLimit = maxBytes + 1;
|
|
76
|
+
const indexDiff = await git(
|
|
77
|
+
repositoryRoot,
|
|
78
|
+
["diff", "--binary", "--no-ext-diff", "--cached", "HEAD", "--"],
|
|
79
|
+
commandLimit,
|
|
80
|
+
options.signal,
|
|
81
|
+
).catch((error) => {
|
|
82
|
+
throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
|
|
83
|
+
});
|
|
84
|
+
const worktreeDiff = await git(
|
|
85
|
+
repositoryRoot,
|
|
86
|
+
["diff", "--binary", "--no-ext-diff", "--"],
|
|
87
|
+
commandLimit,
|
|
88
|
+
options.signal,
|
|
89
|
+
).catch((error) => {
|
|
90
|
+
throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
|
|
91
|
+
});
|
|
92
|
+
if (indexDiff.length > maxBytes || worktreeDiff.length > maxBytes) {
|
|
93
|
+
throw new Error("Workflow tree identity exceeded its size limit");
|
|
94
|
+
}
|
|
95
|
+
const untrackedOutput = await git(
|
|
96
|
+
repositoryRoot,
|
|
97
|
+
["ls-files", "--others", "--exclude-standard", "-z"],
|
|
98
|
+
commandLimit,
|
|
99
|
+
options.signal,
|
|
100
|
+
).catch((error) => {
|
|
101
|
+
throw normalizedGitError(error, "Workflow tree identity exceeded its size limit");
|
|
102
|
+
});
|
|
103
|
+
const untrackedEntries = splitNul(untrackedOutput).sort(Buffer.compare);
|
|
104
|
+
if (untrackedEntries.length > MAX_UNTRACKED_FILES) {
|
|
105
|
+
throw new Error("Workflow tree identity exceeded its untracked-file limit");
|
|
106
|
+
}
|
|
107
|
+
if (indexDiff.length === 0 && worktreeDiff.length === 0 && untrackedEntries.length === 0) {
|
|
108
|
+
return identity("git-commit", hashParts([Buffer.from("commit\0"), Buffer.from(head)]));
|
|
109
|
+
}
|
|
110
|
+
let consumed = indexDiff.length + worktreeDiff.length + untrackedOutput.length;
|
|
111
|
+
if (consumed > maxBytes) throw new Error("Workflow tree identity exceeded its size limit");
|
|
112
|
+
const hasher = createHash("sha256");
|
|
113
|
+
hasher.update("pi-subagents:workflow-tree:v1\0");
|
|
114
|
+
updateHashFrame(hasher, "head", head);
|
|
115
|
+
updateHashFrame(hasher, "index-diff", indexDiff);
|
|
116
|
+
updateHashFrame(hasher, "worktree-diff", worktreeDiff);
|
|
117
|
+
for (const rawRelativePath of untrackedEntries) {
|
|
118
|
+
throwIfAborted(options.signal);
|
|
119
|
+
const relativePath = decodeGitPath(rawRelativePath);
|
|
120
|
+
const candidate = path.resolve(repositoryRoot, relativePath);
|
|
121
|
+
const relative = path.relative(repositoryRoot, candidate);
|
|
122
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
123
|
+
throw new Error("Workflow tree identity encountered an unsafe untracked path");
|
|
124
|
+
}
|
|
125
|
+
let bytes: Buffer;
|
|
126
|
+
let kind: string;
|
|
127
|
+
try {
|
|
128
|
+
const stat = await fs.promises.lstat(candidate);
|
|
129
|
+
if (stat.isSymbolicLink()) {
|
|
130
|
+
kind = "symlink";
|
|
131
|
+
bytes = Buffer.from(await fs.promises.readlink(candidate), "utf8");
|
|
132
|
+
} else if (stat.isFile()) {
|
|
133
|
+
kind = "file";
|
|
134
|
+
if (stat.size > maxBytes - consumed) {
|
|
135
|
+
throw new Error("Workflow tree identity exceeded its size limit");
|
|
136
|
+
}
|
|
137
|
+
bytes = await readRegularFileNoFollow(candidate, stat, options.signal);
|
|
138
|
+
} else {
|
|
139
|
+
throw new Error("Workflow tree identity encountered an unsupported untracked file type");
|
|
140
|
+
}
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
143
|
+
if (error instanceof Error && error.message.startsWith("Workflow tree identity")) {
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
throw new Error("Workflow tree identity could not read an untracked entry");
|
|
147
|
+
}
|
|
148
|
+
consumed += rawRelativePath.length + bytes.length;
|
|
149
|
+
if (consumed > maxBytes) throw new Error("Workflow tree identity exceeded its size limit");
|
|
150
|
+
updateHashFrame(hasher, "untracked-kind", kind);
|
|
151
|
+
updateHashFrame(hasher, "untracked-path", rawRelativePath);
|
|
152
|
+
updateHashFrame(hasher, "untracked-content", bytes);
|
|
153
|
+
}
|
|
154
|
+
return identity("git-dirty", hasher.digest("hex"));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function sameWorkflowTreeIdentity(
|
|
158
|
+
left: WorkflowTreeIdentity,
|
|
159
|
+
right: WorkflowTreeIdentity,
|
|
160
|
+
): boolean {
|
|
161
|
+
return (
|
|
162
|
+
isWorkflowTreeIdentity(left) &&
|
|
163
|
+
isWorkflowTreeIdentity(right) &&
|
|
164
|
+
left.kind === right.kind &&
|
|
165
|
+
left.digest === right.digest
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function isWorkflowTreeIdentity(value: unknown): value is WorkflowTreeIdentity {
|
|
170
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
171
|
+
const candidate = value as Partial<WorkflowTreeIdentity>;
|
|
172
|
+
if (
|
|
173
|
+
Object.keys(value as Record<string, unknown>).some(
|
|
174
|
+
(key) => !["version", "kind", "digest"].includes(key),
|
|
175
|
+
)
|
|
176
|
+
) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
return (
|
|
180
|
+
candidate.version === WORKFLOW_TREE_IDENTITY_VERSION &&
|
|
181
|
+
(candidate.kind === "git-commit" || candidate.kind === "git-dirty") &&
|
|
182
|
+
typeof candidate.digest === "string" &&
|
|
183
|
+
/^[a-f0-9]{64}$/u.test(candidate.digest)
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function identity(kind: WorkflowTreeIdentity["kind"], digest: string): WorkflowTreeIdentity {
|
|
188
|
+
return { version: WORKFLOW_TREE_IDENTITY_VERSION, kind, digest };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function hashParts(parts: Buffer[]): string {
|
|
192
|
+
const hash = createHash("sha256");
|
|
193
|
+
for (const part of parts) hash.update(part);
|
|
194
|
+
return hash.digest("hex");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function updateHashFrame(hash: Hash, label: string, value: string | Buffer): void {
|
|
198
|
+
const labelBytes = Buffer.from(label, "utf8");
|
|
199
|
+
const valueBytes = typeof value === "string" ? Buffer.from(value, "utf8") : value;
|
|
200
|
+
const header = Buffer.allocUnsafe(8);
|
|
201
|
+
header.writeUInt32BE(labelBytes.length, 0);
|
|
202
|
+
header.writeUInt32BE(valueBytes.length, 4);
|
|
203
|
+
hash.update(header);
|
|
204
|
+
hash.update(labelBytes);
|
|
205
|
+
hash.update(valueBytes);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function splitNul(value: Buffer): Buffer[] {
|
|
209
|
+
const entries: Buffer[] = [];
|
|
210
|
+
let start = 0;
|
|
211
|
+
for (let index = 0; index < value.length; index++) {
|
|
212
|
+
if (value[index] !== 0) continue;
|
|
213
|
+
if (index > start) entries.push(value.subarray(start, index));
|
|
214
|
+
start = index + 1;
|
|
215
|
+
}
|
|
216
|
+
if (start < value.length) entries.push(value.subarray(start));
|
|
217
|
+
return entries;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function decodeGitPath(value: Buffer): string {
|
|
221
|
+
const decoded = value.toString("utf8");
|
|
222
|
+
if (!decoded || decoded.includes("\0") || !Buffer.from(decoded, "utf8").equals(value)) {
|
|
223
|
+
throw new Error("Workflow tree identity encountered an unsupported Git path encoding");
|
|
224
|
+
}
|
|
225
|
+
return decoded;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function readRegularFileNoFollow(
|
|
229
|
+
filePath: string,
|
|
230
|
+
expected: fs.Stats,
|
|
231
|
+
signal: AbortSignal | undefined,
|
|
232
|
+
): Promise<Buffer> {
|
|
233
|
+
throwIfAborted(signal);
|
|
234
|
+
const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
235
|
+
try {
|
|
236
|
+
const before = await handle.stat();
|
|
237
|
+
if (!before.isFile() || before.dev !== expected.dev || before.ino !== expected.ino) {
|
|
238
|
+
throw new Error("Workflow tree identity file changed during capture");
|
|
239
|
+
}
|
|
240
|
+
const content = await handle.readFile({ signal });
|
|
241
|
+
const after = await handle.stat();
|
|
242
|
+
if (
|
|
243
|
+
after.dev !== before.dev ||
|
|
244
|
+
after.ino !== before.ino ||
|
|
245
|
+
after.size !== before.size ||
|
|
246
|
+
after.mtimeMs !== before.mtimeMs
|
|
247
|
+
) {
|
|
248
|
+
throw new Error("Workflow tree identity file changed during capture");
|
|
249
|
+
}
|
|
250
|
+
return content;
|
|
251
|
+
} finally {
|
|
252
|
+
await handle.close();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function git(
|
|
257
|
+
cwd: string,
|
|
258
|
+
args: string[],
|
|
259
|
+
maxBuffer: number,
|
|
260
|
+
signal?: AbortSignal,
|
|
261
|
+
): Promise<Buffer> {
|
|
262
|
+
throwIfAborted(signal);
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
execFile(
|
|
265
|
+
"git",
|
|
266
|
+
["-C", cwd, ...args],
|
|
267
|
+
{ encoding: "buffer", maxBuffer, signal },
|
|
268
|
+
(error, stdout) => {
|
|
269
|
+
if (error) reject(error);
|
|
270
|
+
else resolve(stdout);
|
|
271
|
+
},
|
|
272
|
+
);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
277
|
+
if (!signal?.aborted) return;
|
|
278
|
+
const error = new Error("Workflow tree identity capture was cancelled");
|
|
279
|
+
error.name = "AbortError";
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function normalizedGitError(error: unknown, fallback: string): Error {
|
|
284
|
+
if (error instanceof Error && error.name === "AbortError") return error;
|
|
285
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
286
|
+
return new Error(
|
|
287
|
+
/maxBuffer|stdout.*large|SIGTERM/iu.test(message) ? `${fallback}: size limit` : fallback,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { redactPrivateText } from "./context.js";
|
|
2
|
+
import { truncateUtf8 } from "./limits.js";
|
|
3
|
+
import type { StructuredSubagentResultV2 } from "./result-contract.js";
|
|
4
|
+
import { isWorkflowTreeIdentity, type WorkflowTreeIdentity } from "./workflow-tree-identity.js";
|
|
5
|
+
|
|
6
|
+
export const WORKFLOW_VERIFICATION_VERSION = "pi-subagents:workflow-verification:v1" as const;
|
|
7
|
+
export type WorkflowVerificationDecision = "accept" | "rework" | "reject";
|
|
8
|
+
const MAX_FIELD_BYTES = 2 * 1024;
|
|
9
|
+
const MAX_ITEMS = 32;
|
|
10
|
+
const MAX_EVIDENCE_BYTES = 6 * 1024;
|
|
11
|
+
const MAX_LIMITATION_BYTES = 4 * 1024;
|
|
12
|
+
const MAX_INSTRUCTION_LIST_BYTES = 8 * 1024;
|
|
13
|
+
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
|
|
14
|
+
const PLAN_PATTERN = /^[a-f0-9]{64}$/u;
|
|
15
|
+
|
|
16
|
+
export interface WorkflowVerificationReceipt {
|
|
17
|
+
version: typeof WORKFLOW_VERIFICATION_VERSION;
|
|
18
|
+
decision: WorkflowVerificationDecision;
|
|
19
|
+
targetTaskId: string;
|
|
20
|
+
targetTaskGeneration: number;
|
|
21
|
+
targetExecutionPlanId: string;
|
|
22
|
+
verifierTaskId: string;
|
|
23
|
+
verifierTaskGeneration: number;
|
|
24
|
+
verifierExecutionPlanId: string;
|
|
25
|
+
treeIdentity: WorkflowTreeIdentity;
|
|
26
|
+
summary: string;
|
|
27
|
+
evidence: string[];
|
|
28
|
+
limitations: string[];
|
|
29
|
+
createdAt: number;
|
|
30
|
+
truncated: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface WorkflowVerificationContext {
|
|
34
|
+
targetTaskId: string;
|
|
35
|
+
targetTaskGeneration: number;
|
|
36
|
+
targetExecutionPlanId: string;
|
|
37
|
+
verifierTaskId: string;
|
|
38
|
+
verifierTaskGeneration: number;
|
|
39
|
+
verifierExecutionPlanId: string;
|
|
40
|
+
treeIdentity: WorkflowTreeIdentity;
|
|
41
|
+
createdAt?: number;
|
|
42
|
+
sourceTruncated?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createWorkflowVerificationReceipt(
|
|
46
|
+
result: StructuredSubagentResultV2,
|
|
47
|
+
context: WorkflowVerificationContext,
|
|
48
|
+
): WorkflowVerificationReceipt {
|
|
49
|
+
validateContext(context);
|
|
50
|
+
const decision = verdict(result);
|
|
51
|
+
const boundedSummary = bound(result.summary);
|
|
52
|
+
if (!boundedSummary.value) throw new Error("Workflow verification verdict requires a summary");
|
|
53
|
+
const evidenceSource = [
|
|
54
|
+
...result.claims.flatMap((claim) => claim.evidence),
|
|
55
|
+
...result.verification.flatMap((item) => [item.summary, ...(item.evidence ?? [])]),
|
|
56
|
+
];
|
|
57
|
+
const evidence = boundList(evidenceSource, MAX_EVIDENCE_BYTES);
|
|
58
|
+
const limitations = boundList(
|
|
59
|
+
[...result.limitations, ...result.unresolvedDependencies],
|
|
60
|
+
MAX_LIMITATION_BYTES,
|
|
61
|
+
);
|
|
62
|
+
if (decision === "rework" && limitations.values.length === 0) {
|
|
63
|
+
throw new Error("Workflow verification rework requires a limitation or unresolved dependency");
|
|
64
|
+
}
|
|
65
|
+
if (decision === "reject" && evidence.values.length === 0) {
|
|
66
|
+
throw new Error("Workflow verification reject requires evidence");
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
version: WORKFLOW_VERIFICATION_VERSION,
|
|
70
|
+
decision,
|
|
71
|
+
targetTaskId: context.targetTaskId,
|
|
72
|
+
targetTaskGeneration: context.targetTaskGeneration,
|
|
73
|
+
targetExecutionPlanId: context.targetExecutionPlanId,
|
|
74
|
+
verifierTaskId: context.verifierTaskId,
|
|
75
|
+
verifierTaskGeneration: context.verifierTaskGeneration,
|
|
76
|
+
verifierExecutionPlanId: context.verifierExecutionPlanId,
|
|
77
|
+
treeIdentity: structuredClone(context.treeIdentity),
|
|
78
|
+
summary: boundedSummary.value,
|
|
79
|
+
evidence: evidence.values,
|
|
80
|
+
limitations: limitations.values,
|
|
81
|
+
createdAt: context.createdAt ?? Date.now(),
|
|
82
|
+
truncated:
|
|
83
|
+
context.sourceTruncated === true ||
|
|
84
|
+
boundedSummary.truncated ||
|
|
85
|
+
evidence.truncated ||
|
|
86
|
+
limitations.truncated,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function workflowVerificationInstruction(
|
|
91
|
+
targetTaskId: string,
|
|
92
|
+
treeIdentity: WorkflowTreeIdentity,
|
|
93
|
+
requirements: {
|
|
94
|
+
acceptanceCriteria?: readonly string[];
|
|
95
|
+
requiredEvidence?: readonly string[];
|
|
96
|
+
} = {},
|
|
97
|
+
): string {
|
|
98
|
+
if (!ID_PATTERN.test(targetTaskId) || !isWorkflowTreeIdentity(treeIdentity)) {
|
|
99
|
+
throw new Error("Workflow verification instruction received invalid executor metadata");
|
|
100
|
+
}
|
|
101
|
+
const acceptanceCriteria = boundList(
|
|
102
|
+
requirements.acceptanceCriteria ?? [],
|
|
103
|
+
MAX_INSTRUCTION_LIST_BYTES,
|
|
104
|
+
).values;
|
|
105
|
+
const requiredEvidence = boundList(
|
|
106
|
+
requirements.requiredEvidence ?? [],
|
|
107
|
+
MAX_INSTRUCTION_LIST_BYTES,
|
|
108
|
+
).values;
|
|
109
|
+
return [
|
|
110
|
+
"You are the independent verifier for one staged workflow result.",
|
|
111
|
+
`Target task: ${JSON.stringify(targetTaskId)}.`,
|
|
112
|
+
`Acceptance criteria: ${JSON.stringify(acceptanceCriteria)}.`,
|
|
113
|
+
`Required evidence: ${JSON.stringify(requiredEvidence)}.`,
|
|
114
|
+
`Exact Git-visible tree identity: ${treeIdentity.version}:${treeIdentity.kind}:${treeIdentity.digest}.`,
|
|
115
|
+
"Do not modify the repository; the executor will reject acceptance if the tree identity changes.",
|
|
116
|
+
"Return the requested pi-subagents:result:v2 object with exactly one verdict encoding.",
|
|
117
|
+
'Accept only with status "completed", reasonCode "verification-accepted", at least one passed verification item, no failed verification item, and no unresolved dependency.',
|
|
118
|
+
'Request rework only with status "partial" or "needs-input", reasonCode "verification-rework", and a concrete limitation or unresolved dependency.',
|
|
119
|
+
'Reject only with status "failed" or "abstained", reasonCode "verification-rejected", and concrete evidence.',
|
|
120
|
+
"Agreement, confidence, and the implementation worker's own verification claims are not proof.",
|
|
121
|
+
].join("\n");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function isWorkflowVerificationReceipt(
|
|
125
|
+
value: unknown,
|
|
126
|
+
): value is WorkflowVerificationReceipt {
|
|
127
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
128
|
+
const receipt = value as Partial<WorkflowVerificationReceipt>;
|
|
129
|
+
if (
|
|
130
|
+
Object.keys(value as Record<string, unknown>).some(
|
|
131
|
+
(key) =>
|
|
132
|
+
![
|
|
133
|
+
"version",
|
|
134
|
+
"decision",
|
|
135
|
+
"targetTaskId",
|
|
136
|
+
"targetTaskGeneration",
|
|
137
|
+
"targetExecutionPlanId",
|
|
138
|
+
"verifierTaskId",
|
|
139
|
+
"verifierTaskGeneration",
|
|
140
|
+
"verifierExecutionPlanId",
|
|
141
|
+
"treeIdentity",
|
|
142
|
+
"summary",
|
|
143
|
+
"evidence",
|
|
144
|
+
"limitations",
|
|
145
|
+
"createdAt",
|
|
146
|
+
"truncated",
|
|
147
|
+
].includes(key),
|
|
148
|
+
)
|
|
149
|
+
) {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
return (
|
|
153
|
+
receipt.version === WORKFLOW_VERIFICATION_VERSION &&
|
|
154
|
+
(receipt.decision !== "rework" ||
|
|
155
|
+
(Array.isArray(receipt.limitations) && receipt.limitations.length > 0)) &&
|
|
156
|
+
(receipt.decision !== "reject" ||
|
|
157
|
+
(Array.isArray(receipt.evidence) && receipt.evidence.length > 0)) &&
|
|
158
|
+
["accept", "rework", "reject"].includes(String(receipt.decision)) &&
|
|
159
|
+
typeof receipt.targetTaskId === "string" &&
|
|
160
|
+
ID_PATTERN.test(receipt.targetTaskId) &&
|
|
161
|
+
Number.isSafeInteger(receipt.targetTaskGeneration) &&
|
|
162
|
+
Number(receipt.targetTaskGeneration) >= 1 &&
|
|
163
|
+
typeof receipt.targetExecutionPlanId === "string" &&
|
|
164
|
+
PLAN_PATTERN.test(receipt.targetExecutionPlanId) &&
|
|
165
|
+
typeof receipt.verifierTaskId === "string" &&
|
|
166
|
+
ID_PATTERN.test(receipt.verifierTaskId) &&
|
|
167
|
+
Number.isSafeInteger(receipt.verifierTaskGeneration) &&
|
|
168
|
+
Number(receipt.verifierTaskGeneration) >= 1 &&
|
|
169
|
+
typeof receipt.verifierExecutionPlanId === "string" &&
|
|
170
|
+
PLAN_PATTERN.test(receipt.verifierExecutionPlanId) &&
|
|
171
|
+
isWorkflowTreeIdentity(receipt.treeIdentity) &&
|
|
172
|
+
typeof receipt.summary === "string" &&
|
|
173
|
+
receipt.summary.length > 0 &&
|
|
174
|
+
Buffer.byteLength(receipt.summary, "utf8") <= MAX_FIELD_BYTES &&
|
|
175
|
+
validStrings(receipt.evidence, MAX_EVIDENCE_BYTES) &&
|
|
176
|
+
validStrings(receipt.limitations, MAX_LIMITATION_BYTES) &&
|
|
177
|
+
typeof receipt.createdAt === "number" &&
|
|
178
|
+
Number.isFinite(receipt.createdAt) &&
|
|
179
|
+
receipt.createdAt >= 0 &&
|
|
180
|
+
typeof receipt.truncated === "boolean"
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function verdict(result: StructuredSubagentResultV2): WorkflowVerificationDecision {
|
|
185
|
+
if (result.version !== "pi-subagents:result:v2") {
|
|
186
|
+
throw new Error("Workflow verification requires structured-v2");
|
|
187
|
+
}
|
|
188
|
+
if (result.reasonCode === "verification-accepted" && result.status === "completed") {
|
|
189
|
+
if (result.verification.some((item) => item.status === "failed")) {
|
|
190
|
+
throw new Error("Workflow verification accept cannot contain failed evidence");
|
|
191
|
+
}
|
|
192
|
+
if (!result.verification.some((item) => item.status === "passed")) {
|
|
193
|
+
throw new Error("Workflow verification accept requires passed evidence");
|
|
194
|
+
}
|
|
195
|
+
if (result.unresolvedDependencies.length > 0) {
|
|
196
|
+
throw new Error("Workflow verification accept cannot contain unresolved dependencies");
|
|
197
|
+
}
|
|
198
|
+
return "accept";
|
|
199
|
+
}
|
|
200
|
+
if (
|
|
201
|
+
result.reasonCode === "verification-rework" &&
|
|
202
|
+
(result.status === "partial" || result.status === "needs-input")
|
|
203
|
+
) {
|
|
204
|
+
return "rework";
|
|
205
|
+
}
|
|
206
|
+
if (
|
|
207
|
+
result.reasonCode === "verification-rejected" &&
|
|
208
|
+
(result.status === "failed" || result.status === "abstained")
|
|
209
|
+
) {
|
|
210
|
+
return "reject";
|
|
211
|
+
}
|
|
212
|
+
throw new Error("Workflow verification result does not contain a valid verdict");
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function validateContext(context: WorkflowVerificationContext): void {
|
|
216
|
+
for (const [label, value] of [
|
|
217
|
+
["target task", context.targetTaskId],
|
|
218
|
+
["verifier task", context.verifierTaskId],
|
|
219
|
+
] as const) {
|
|
220
|
+
if (!ID_PATTERN.test(value))
|
|
221
|
+
throw new Error(`Workflow verification has an invalid ${label} id`);
|
|
222
|
+
}
|
|
223
|
+
for (const [label, value] of [
|
|
224
|
+
["target", context.targetTaskGeneration],
|
|
225
|
+
["verifier", context.verifierTaskGeneration],
|
|
226
|
+
] as const) {
|
|
227
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
228
|
+
throw new Error(`Workflow verification has an invalid ${label} task generation`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const value of [context.targetExecutionPlanId, context.verifierExecutionPlanId]) {
|
|
232
|
+
if (!PLAN_PATTERN.test(value)) {
|
|
233
|
+
throw new Error("Workflow verification has an invalid execution plan identity");
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (!isWorkflowTreeIdentity(context.treeIdentity)) {
|
|
237
|
+
throw new Error("Workflow verification has an invalid tree identity");
|
|
238
|
+
}
|
|
239
|
+
if (context.sourceTruncated !== undefined && typeof context.sourceTruncated !== "boolean") {
|
|
240
|
+
throw new Error("Workflow verification has an invalid truncation state");
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
context.createdAt !== undefined &&
|
|
244
|
+
(!Number.isFinite(context.createdAt) || context.createdAt < 0)
|
|
245
|
+
) {
|
|
246
|
+
throw new Error("Workflow verification has an invalid creation time");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function bound(value: string): { value: string; truncated: boolean } {
|
|
251
|
+
const redacted = redactPrivateText(value).trim();
|
|
252
|
+
const truncated = truncateUtf8(redacted, MAX_FIELD_BYTES);
|
|
253
|
+
return { value: truncated.text, truncated: truncated.truncated };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function boundList(
|
|
257
|
+
values: readonly string[],
|
|
258
|
+
maxTotalBytes: number,
|
|
259
|
+
): { values: string[]; truncated: boolean } {
|
|
260
|
+
let truncated = values.length > MAX_ITEMS;
|
|
261
|
+
let remaining = maxTotalBytes;
|
|
262
|
+
const result: string[] = [];
|
|
263
|
+
const seen = new Set<string>();
|
|
264
|
+
for (const raw of values.slice(0, MAX_ITEMS)) {
|
|
265
|
+
if (remaining < 1) {
|
|
266
|
+
truncated = true;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
const redacted = redactPrivateText(raw).trim();
|
|
270
|
+
const item = truncateUtf8(redacted, Math.min(MAX_FIELD_BYTES, remaining));
|
|
271
|
+
truncated ||= item.truncated;
|
|
272
|
+
if (!item.text || seen.has(item.text)) continue;
|
|
273
|
+
seen.add(item.text);
|
|
274
|
+
result.push(item.text);
|
|
275
|
+
remaining -= Buffer.byteLength(item.text, "utf8");
|
|
276
|
+
}
|
|
277
|
+
return { values: result, truncated };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function validStrings(value: unknown, maxTotalBytes: number): value is string[] {
|
|
281
|
+
return (
|
|
282
|
+
Array.isArray(value) &&
|
|
283
|
+
value.length <= MAX_ITEMS &&
|
|
284
|
+
value.reduce(
|
|
285
|
+
(total, item) =>
|
|
286
|
+
total + (typeof item === "string" ? Buffer.byteLength(item, "utf8") : maxTotalBytes + 1),
|
|
287
|
+
0,
|
|
288
|
+
) <= maxTotalBytes &&
|
|
289
|
+
value.every(
|
|
290
|
+
(item) =>
|
|
291
|
+
typeof item === "string" &&
|
|
292
|
+
item.length > 0 &&
|
|
293
|
+
Buffer.byteLength(item, "utf8") <= MAX_FIELD_BYTES,
|
|
294
|
+
)
|
|
295
|
+
);
|
|
296
|
+
}
|