@narumitw/pi-subagents 0.51.0 → 0.53.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.
@@ -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
+ }