@xzzpig/pi-subagents 0.1.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/CHANGELOG.md +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,1365 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import type {
|
|
7
|
+
AcceptanceConfig,
|
|
8
|
+
AcceptanceEvidenceKind,
|
|
9
|
+
AcceptanceInput,
|
|
10
|
+
AgentContract,
|
|
11
|
+
AcceptanceLedger,
|
|
12
|
+
AcceptanceLevel,
|
|
13
|
+
AcceptanceReport,
|
|
14
|
+
AcceptanceRole,
|
|
15
|
+
AcceptanceRuntimeCheck,
|
|
16
|
+
AcceptanceRuntimeCheckStatus,
|
|
17
|
+
AcceptanceReviewResult,
|
|
18
|
+
AcceptanceVerifyCommand,
|
|
19
|
+
AcceptanceVerifyResult,
|
|
20
|
+
ResolvedAcceptanceConfig,
|
|
21
|
+
ResolvedAcceptanceGate,
|
|
22
|
+
SingleResult,
|
|
23
|
+
SubagentRunMode,
|
|
24
|
+
} from "../../shared/types.ts";
|
|
25
|
+
import { isAgentContractV1 } from "./agent-contract.ts";
|
|
26
|
+
import { classifyTaskMutationIntent, taskMayMutate } from "./task-intent.ts";
|
|
27
|
+
|
|
28
|
+
const LEVEL_RANK: Record<Exclude<AcceptanceLevel, "auto">, number> = {
|
|
29
|
+
none: 0,
|
|
30
|
+
attested: 1,
|
|
31
|
+
checked: 2,
|
|
32
|
+
verified: 3,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const VALID_LEVELS = new Set<AcceptanceLevel>(["auto", "none", "attested", "checked", "verified"]);
|
|
36
|
+
const VALID_EVIDENCE_KINDS: AcceptanceEvidenceKind[] = [
|
|
37
|
+
"changed-files",
|
|
38
|
+
"tests-added",
|
|
39
|
+
"commands-run",
|
|
40
|
+
"validation-output",
|
|
41
|
+
"residual-risks",
|
|
42
|
+
"no-staged-files",
|
|
43
|
+
"diff-summary",
|
|
44
|
+
"review-findings",
|
|
45
|
+
"manual-notes",
|
|
46
|
+
];
|
|
47
|
+
const VALID_EVIDENCE = new Set<AcceptanceEvidenceKind>(VALID_EVIDENCE_KINDS);
|
|
48
|
+
const ACCEPTANCE_EVIDENCE_HELP = `Supported evidence kinds: ${VALID_EVIDENCE_KINDS.join(", ")}. Example: { level: "checked", evidence: ["commands-run", "changed-files"] }.`;
|
|
49
|
+
const ACCEPTANCE_OBJECT_EXAMPLE = "Example: { level: \"checked\", evidence: [\"commands-run\", \"changed-files\"] }.";
|
|
50
|
+
const ACCEPTANCE_CONFIG_KEYS = new Set(["level", "criteria", "evidence", "verify", "review", "stopRules", "reason"]);
|
|
51
|
+
const ACCEPTANCE_GATE_KEYS = new Set(["id", "must", "evidence", "severity"]);
|
|
52
|
+
const ACCEPTANCE_VERIFY_KEYS = new Set(["id", "command", "timeoutMs", "cwd", "env", "allowFailure"]);
|
|
53
|
+
const ACCEPTANCE_REVIEW_KEYS = new Set(["agent", "focus", "required"]);
|
|
54
|
+
const EXPLICIT_REVIEWED_UNAVAILABLE = "is an achieved status, not a requestable acceptance level. For a read-only reviewer call, omit acceptance. To require independent review of a writer result, use acceptance.review.required and orchestrate the reviewer separately.";
|
|
55
|
+
|
|
56
|
+
function normalizeLevel(level: AcceptanceLevel | undefined): Exclude<AcceptanceLevel, "auto"> | "auto" {
|
|
57
|
+
return level ?? "auto";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function unique<T>(items: T[]): T[] {
|
|
61
|
+
return [...new Set(items)];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function requiredEvidenceForLevel(level: Exclude<AcceptanceLevel, "auto">): AcceptanceEvidenceKind[] {
|
|
65
|
+
switch (level) {
|
|
66
|
+
case "none":
|
|
67
|
+
return [];
|
|
68
|
+
case "attested":
|
|
69
|
+
return ["manual-notes", "residual-risks"];
|
|
70
|
+
case "checked":
|
|
71
|
+
return ["changed-files", "tests-added", "commands-run", "residual-risks", "no-staged-files"];
|
|
72
|
+
case "verified":
|
|
73
|
+
return ["changed-files", "tests-added", "commands-run", "validation-output", "residual-risks", "no-staged-files"];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function inferLevel(input: {
|
|
78
|
+
agentName: string;
|
|
79
|
+
acceptanceRole?: AcceptanceRole;
|
|
80
|
+
task?: string;
|
|
81
|
+
mode?: SubagentRunMode;
|
|
82
|
+
async?: boolean;
|
|
83
|
+
dynamic?: boolean;
|
|
84
|
+
dynamicGroup?: boolean;
|
|
85
|
+
}): { level: Exclude<AcceptanceLevel, "auto">; reasons: string[]; criteria: string[]; evidence: AcceptanceEvidenceKind[]; review?: { agent?: string; required?: boolean } } {
|
|
86
|
+
const agent = input.agentName.toLowerCase();
|
|
87
|
+
const task = input.task?.toLowerCase() ?? "";
|
|
88
|
+
const reasons: string[] = [];
|
|
89
|
+
// Declared roles replace name heuristics, so use the full writer grammar to detect explicit mutation independently of the actual agent name.
|
|
90
|
+
const intent = classifyTaskMutationIntent(input.acceptanceRole ? "worker" : input.agentName, input.task ?? "");
|
|
91
|
+
const readOnlyTask = intent.kind === "read-only"
|
|
92
|
+
|| (intent.kind === "unknown" && /\b(?:read[- ]only|review[- ]only|no edits|without edits|inspect|summari[sz]e)\b/.test(task));
|
|
93
|
+
const rolePatchTask = input.acceptanceRole !== undefined
|
|
94
|
+
&& intent.kind !== "read-only"
|
|
95
|
+
&& !/\b(?:do not|don't|must not)\s+patch\b/.test(task)
|
|
96
|
+
&& /\bpatch\s+(?:(?:\.{0,2}[\\/])?(?:[\w.-]+[\\/])+[\w.-]+|[\w.-]+\.[a-z0-9]+\b|(?:the\s+)?parser\b)/.test(task);
|
|
97
|
+
const taskMayWrite = readOnlyTask ? false : taskMayMutate(input.task ?? "") || intent.kind === "implementation" || rolePatchTask;
|
|
98
|
+
const readOnlyAgent = input.acceptanceRole === "read-only"
|
|
99
|
+
|| (input.acceptanceRole === undefined && /\b(?:reviewer|oracle|scout|researcher|analyst)\b/.test(agent));
|
|
100
|
+
const writeTask = taskMayWrite
|
|
101
|
+
|| (input.acceptanceRole === "writer" && !readOnlyTask)
|
|
102
|
+
|| (input.acceptanceRole === undefined && /\bworker\b/.test(agent) && !readOnlyTask);
|
|
103
|
+
const inferredReadOnly = readOnlyTask || (input.acceptanceRole === "read-only" && !taskMayWrite);
|
|
104
|
+
const roleResolvesReadOnly = input.acceptanceRole !== undefined && inferredReadOnly;
|
|
105
|
+
const keywordRiskReadOnly = input.acceptanceRole === undefined ? intent.kind === "read-only" : inferredReadOnly;
|
|
106
|
+
const risky = Boolean(input.async && writeTask)
|
|
107
|
+
|| (Boolean(input.dynamic) && !roleResolvesReadOnly)
|
|
108
|
+
|| (Boolean(input.dynamicGroup) && !roleResolvesReadOnly)
|
|
109
|
+
|| (!keywordRiskReadOnly && /\b(?:release|migration|migrate|security|data[- ]loss|destructive|post-review|fix pass)\b/.test(task));
|
|
110
|
+
|
|
111
|
+
if (risky) {
|
|
112
|
+
reasons.push(input.async ? "async write-capable or risky run" : "risky write-capable run");
|
|
113
|
+
if (input.dynamic || input.dynamicGroup) reasons.push("dynamic fanout context");
|
|
114
|
+
return {
|
|
115
|
+
level: "checked",
|
|
116
|
+
reasons,
|
|
117
|
+
criteria: ["Implement the requested change without widening scope", "Return evidence sufficient for an independent acceptance review"],
|
|
118
|
+
evidence: requiredEvidenceForLevel("checked"),
|
|
119
|
+
review: { agent: "reviewer", required: true },
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (writeTask && !readOnlyTask) {
|
|
123
|
+
reasons.push(input.acceptanceRole === "writer" && !taskMayWrite ? "declared writer acceptance role" : "write-capable worker/task");
|
|
124
|
+
return {
|
|
125
|
+
level: "checked",
|
|
126
|
+
reasons,
|
|
127
|
+
criteria: ["Implement the requested change without widening scope"],
|
|
128
|
+
evidence: requiredEvidenceForLevel("checked"),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (readOnlyAgent || readOnlyTask) {
|
|
132
|
+
reasons.push(input.acceptanceRole === "read-only" && !readOnlyTask ? "declared read-only acceptance role" : readOnlyAgent ? "read-only/reviewer-style agent" : "read-only task wording");
|
|
133
|
+
return {
|
|
134
|
+
level: "attested",
|
|
135
|
+
reasons,
|
|
136
|
+
criteria: ["Return concrete findings with file paths and severity when applicable"],
|
|
137
|
+
evidence: ["review-findings", "residual-risks"],
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
reasons.push("default lightweight attestation");
|
|
141
|
+
return {
|
|
142
|
+
level: "attested",
|
|
143
|
+
reasons,
|
|
144
|
+
criteria: ["Return a concise result and residual risks when applicable"],
|
|
145
|
+
evidence: ["manual-notes", "residual-risks"],
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function normalizeAcceptanceInput(input: AcceptanceInput | undefined): AcceptanceConfig {
|
|
150
|
+
if (input === undefined || input === "auto") return { level: "auto" };
|
|
151
|
+
if (input === false) return { level: "none", reason: "disabled by deprecated false shorthand" };
|
|
152
|
+
if (typeof input === "string") return { level: input };
|
|
153
|
+
return { ...input };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
type GateAcceptanceNormalizationResult =
|
|
157
|
+
| { ok: true; acceptance?: AcceptanceInput }
|
|
158
|
+
| { ok: false; error: string };
|
|
159
|
+
|
|
160
|
+
export function normalizeGateAcceptance(gate: unknown, acceptance: AcceptanceInput | undefined): GateAcceptanceNormalizationResult {
|
|
161
|
+
if (gate === undefined) return acceptance === undefined ? { ok: true } : { ok: true, acceptance };
|
|
162
|
+
if (typeof gate !== "string" || !gate.trim()) return { ok: false, error: "gate must be a non-empty command string." };
|
|
163
|
+
if (acceptance !== undefined) return { ok: false, error: "gate cannot be combined with acceptance; use one gate command or acceptance.verify." };
|
|
164
|
+
return { ok: true, acceptance: { level: "verified", verify: [{ id: "gate", command: gate.trim() }] } };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function explicitAcceptanceCanDisable(explicit: AcceptanceConfig): boolean {
|
|
168
|
+
return explicit.level === "none" && typeof explicit.reason === "string" && explicit.reason.trim().length > 0;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function unsupportedEvidenceKindMessage(pathLabel: string, item: unknown): string {
|
|
172
|
+
const value = typeof item === "string" ? ` "${item}"` : "";
|
|
173
|
+
return `${pathLabel}${value} is not a supported evidence kind. ${ACCEPTANCE_EVIDENCE_HELP}`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function validateAcceptanceInput(input: unknown, pathLabel = "acceptance"): string[] {
|
|
177
|
+
const errors: string[] = [];
|
|
178
|
+
if (input === undefined) return errors;
|
|
179
|
+
if (input === false) return errors;
|
|
180
|
+
if (typeof input === "string") {
|
|
181
|
+
if (input === "reviewed") errors.push(`${pathLabel} ${EXPLICIT_REVIEWED_UNAVAILABLE}`);
|
|
182
|
+
else if (!VALID_LEVELS.has(input as AcceptanceLevel)) errors.push(`${pathLabel} has invalid level '${input}'.`);
|
|
183
|
+
else if (input === "none") errors.push(`${pathLabel} level "none" requires a reason; use { level: "none", reason: "..." }.`);
|
|
184
|
+
else if (input === "verified") errors.push(`${pathLabel} level "verified" requires object form with at least one runtime verify command. Use level "checked" or provide a non-empty acceptance.verify array.`);
|
|
185
|
+
return errors;
|
|
186
|
+
}
|
|
187
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
188
|
+
errors.push(`${pathLabel} must be a string level, false, or an object. ${ACCEPTANCE_OBJECT_EXAMPLE}`);
|
|
189
|
+
return errors;
|
|
190
|
+
}
|
|
191
|
+
const value = input as Record<string, unknown>;
|
|
192
|
+
for (const key of Object.keys(value)) {
|
|
193
|
+
if (!ACCEPTANCE_CONFIG_KEYS.has(key)) errors.push(`${pathLabel}.${key} is not supported.`);
|
|
194
|
+
}
|
|
195
|
+
if (value.level === "reviewed") {
|
|
196
|
+
errors.push(`${pathLabel}.level ${EXPLICIT_REVIEWED_UNAVAILABLE}`);
|
|
197
|
+
} else if (value.level !== undefined && (typeof value.level !== "string" || !VALID_LEVELS.has(value.level as AcceptanceLevel))) {
|
|
198
|
+
errors.push(`${pathLabel}.level must be one of auto, none, attested, checked, verified.`);
|
|
199
|
+
}
|
|
200
|
+
if (value.level === "none" && (typeof value.reason !== "string" || !value.reason.trim())) {
|
|
201
|
+
errors.push(`${pathLabel}.reason is required when level is none.`);
|
|
202
|
+
}
|
|
203
|
+
if (value.reason !== undefined && typeof value.reason !== "string") errors.push(`${pathLabel}.reason must be a string.`);
|
|
204
|
+
if (value.criteria !== undefined && !Array.isArray(value.criteria)) errors.push(`${pathLabel}.criteria must be an array.`);
|
|
205
|
+
if (Array.isArray(value.criteria)) {
|
|
206
|
+
const criterionIds = new Set<string>();
|
|
207
|
+
for (const [index, criterion] of value.criteria.entries()) {
|
|
208
|
+
if (typeof criterion === "string") continue;
|
|
209
|
+
const criterionPath = `${pathLabel}.criteria[${index}]`;
|
|
210
|
+
if (!criterion || typeof criterion !== "object" || Array.isArray(criterion)) {
|
|
211
|
+
errors.push(`${criterionPath} must be a string or an object.`);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const gate = criterion as Record<string, unknown>;
|
|
215
|
+
for (const key of Object.keys(gate)) {
|
|
216
|
+
if (!ACCEPTANCE_GATE_KEYS.has(key)) errors.push(`${criterionPath}.${key} is not supported.`);
|
|
217
|
+
}
|
|
218
|
+
if (typeof gate.id !== "string" || !gate.id.trim()) {
|
|
219
|
+
errors.push(`${criterionPath}.id is required.`);
|
|
220
|
+
} else {
|
|
221
|
+
const normalizedId = normalizedToken(gate.id);
|
|
222
|
+
if (criterionIds.has(normalizedId)) errors.push(`${criterionPath}.id duplicates normalized criterion id '${normalizedId}'.`);
|
|
223
|
+
criterionIds.add(normalizedId);
|
|
224
|
+
}
|
|
225
|
+
if (typeof gate.must !== "string" || !gate.must.trim()) errors.push(`${criterionPath}.must is required.`);
|
|
226
|
+
if (gate.evidence !== undefined && !Array.isArray(gate.evidence)) errors.push(`${criterionPath}.evidence must be an array. ${ACCEPTANCE_EVIDENCE_HELP}`);
|
|
227
|
+
if (Array.isArray(gate.evidence)) {
|
|
228
|
+
for (const [evidenceIndex, item] of gate.evidence.entries()) {
|
|
229
|
+
if (typeof item !== "string" || !VALID_EVIDENCE.has(item as AcceptanceEvidenceKind)) {
|
|
230
|
+
errors.push(unsupportedEvidenceKindMessage(`${criterionPath}.evidence[${evidenceIndex}]`, item));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (gate.severity !== undefined && gate.severity !== "required" && gate.severity !== "recommended") {
|
|
235
|
+
errors.push(`${criterionPath}.severity must be required or recommended.`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (Array.isArray(value.evidence)) {
|
|
240
|
+
for (const [index, item] of value.evidence.entries()) {
|
|
241
|
+
if (typeof item !== "string" || !VALID_EVIDENCE.has(item as AcceptanceEvidenceKind)) {
|
|
242
|
+
errors.push(unsupportedEvidenceKindMessage(`${pathLabel}.evidence[${index}]`, item));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
} else if (value.evidence !== undefined) {
|
|
246
|
+
errors.push(`${pathLabel}.evidence must be an array. ${ACCEPTANCE_EVIDENCE_HELP}`);
|
|
247
|
+
}
|
|
248
|
+
if (value.level === "verified" && (!Array.isArray(value.verify) || value.verify.length === 0)) {
|
|
249
|
+
errors.push(`${pathLabel}.verify must contain at least one runtime command when level is verified. Use level "checked" or provide a non-empty acceptance.verify array.`);
|
|
250
|
+
} else if (value.verify !== undefined && !Array.isArray(value.verify)) {
|
|
251
|
+
errors.push(`${pathLabel}.verify must be an array.`);
|
|
252
|
+
}
|
|
253
|
+
if (Array.isArray(value.verify)) {
|
|
254
|
+
for (const [index, command] of value.verify.entries()) {
|
|
255
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) {
|
|
256
|
+
errors.push(`${pathLabel}.verify[${index}] must be an object.`);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const cmd = command as Record<string, unknown>;
|
|
260
|
+
for (const key of Object.keys(cmd)) {
|
|
261
|
+
if (!ACCEPTANCE_VERIFY_KEYS.has(key)) errors.push(`${pathLabel}.verify[${index}].${key} is not supported.`);
|
|
262
|
+
}
|
|
263
|
+
if (typeof cmd.id !== "string" || !cmd.id.trim()) errors.push(`${pathLabel}.verify[${index}].id is required.`);
|
|
264
|
+
if (typeof cmd.command !== "string" || !cmd.command.trim()) errors.push(`${pathLabel}.verify[${index}].command is required.`);
|
|
265
|
+
if (cmd.timeoutMs !== undefined && (typeof cmd.timeoutMs !== "number" || !Number.isInteger(cmd.timeoutMs) || cmd.timeoutMs < 1)) {
|
|
266
|
+
errors.push(`${pathLabel}.verify[${index}].timeoutMs must be an integer >= 1.`);
|
|
267
|
+
}
|
|
268
|
+
if (cmd.cwd !== undefined && typeof cmd.cwd !== "string") errors.push(`${pathLabel}.verify[${index}].cwd must be a string.`);
|
|
269
|
+
if (cmd.env !== undefined) {
|
|
270
|
+
if (!cmd.env || typeof cmd.env !== "object" || Array.isArray(cmd.env)) {
|
|
271
|
+
errors.push(`${pathLabel}.verify[${index}].env must be an object.`);
|
|
272
|
+
} else {
|
|
273
|
+
for (const [envKey, envValue] of Object.entries(cmd.env as Record<string, unknown>)) {
|
|
274
|
+
if (typeof envValue !== "string") errors.push(`${pathLabel}.verify[${index}].env.${envKey} must be a string.`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (cmd.allowFailure !== undefined && typeof cmd.allowFailure !== "boolean") {
|
|
279
|
+
errors.push(`${pathLabel}.verify[${index}].allowFailure must be a boolean.`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (value.review !== undefined && value.review !== false) {
|
|
284
|
+
if (!value.review || typeof value.review !== "object" || Array.isArray(value.review)) {
|
|
285
|
+
errors.push(`${pathLabel}.review must be false or an object.`);
|
|
286
|
+
} else {
|
|
287
|
+
const review = value.review as Record<string, unknown>;
|
|
288
|
+
for (const key of Object.keys(review)) {
|
|
289
|
+
if (!ACCEPTANCE_REVIEW_KEYS.has(key)) errors.push(`${pathLabel}.review.${key} is not supported.`);
|
|
290
|
+
}
|
|
291
|
+
if (review.agent !== undefined && typeof review.agent !== "string") errors.push(`${pathLabel}.review.agent must be a string.`);
|
|
292
|
+
if (review.focus !== undefined && typeof review.focus !== "string") errors.push(`${pathLabel}.review.focus must be a string.`);
|
|
293
|
+
if (review.required !== undefined && typeof review.required !== "boolean") errors.push(`${pathLabel}.review.required must be a boolean.`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (value.stopRules !== undefined && !Array.isArray(value.stopRules)) errors.push(`${pathLabel}.stopRules must be an array.`);
|
|
297
|
+
if (Array.isArray(value.stopRules)) {
|
|
298
|
+
for (const [index, item] of value.stopRules.entries()) {
|
|
299
|
+
if (typeof item !== "string") errors.push(`${pathLabel}.stopRules[${index}] must be a string.`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return errors;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export function validateExecutionAcceptance(input: {
|
|
306
|
+
acceptance?: unknown;
|
|
307
|
+
tasks?: Array<{ acceptance?: unknown }>;
|
|
308
|
+
chain?: Array<{
|
|
309
|
+
acceptance?: unknown;
|
|
310
|
+
parallel?: Array<{ acceptance?: unknown }> | { acceptance?: unknown };
|
|
311
|
+
}>;
|
|
312
|
+
}): string[] {
|
|
313
|
+
const errors = validateAcceptanceInput(input.acceptance, "acceptance");
|
|
314
|
+
for (const [index, task] of (input.tasks ?? []).entries()) {
|
|
315
|
+
errors.push(...validateAcceptanceInput(task.acceptance, `tasks[${index}].acceptance`));
|
|
316
|
+
}
|
|
317
|
+
for (const [stepIndex, step] of (input.chain ?? []).entries()) {
|
|
318
|
+
errors.push(...validateAcceptanceInput(step.acceptance, `chain[${stepIndex}].acceptance`));
|
|
319
|
+
if (Array.isArray(step.parallel)) {
|
|
320
|
+
for (const [taskIndex, task] of step.parallel.entries()) {
|
|
321
|
+
errors.push(...validateAcceptanceInput(task.acceptance, `chain[${stepIndex}].parallel[${taskIndex}].acceptance`));
|
|
322
|
+
}
|
|
323
|
+
} else if (step.parallel) {
|
|
324
|
+
errors.push(...validateAcceptanceInput(step.parallel.acceptance, `chain[${stepIndex}].parallel.acceptance`));
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return errors;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function normalizeCriteria(criteria: Array<string | { id?: string; must?: string; evidence?: AcceptanceEvidenceKind[]; severity?: "required" | "recommended" }> | undefined, evidence: AcceptanceEvidenceKind[]): ResolvedAcceptanceGate[] {
|
|
331
|
+
return (criteria ?? []).map((criterion, index): ResolvedAcceptanceGate => {
|
|
332
|
+
if (typeof criterion === "string") {
|
|
333
|
+
return { id: `criterion-${index + 1}`, must: criterion, evidence, severity: "required" };
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
id: criterion.id?.trim() || `criterion-${index + 1}`,
|
|
337
|
+
must: criterion.must ?? "",
|
|
338
|
+
evidence: criterion.evidence?.filter((item) => VALID_EVIDENCE.has(item)) ?? evidence,
|
|
339
|
+
severity: criterion.severity ?? "required",
|
|
340
|
+
};
|
|
341
|
+
}).filter((criterion) => criterion.must.trim());
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function resolveEffectiveAcceptance(input: {
|
|
345
|
+
explicit?: AcceptanceInput;
|
|
346
|
+
agentName: string;
|
|
347
|
+
acceptanceRole?: AcceptanceRole;
|
|
348
|
+
task?: string;
|
|
349
|
+
mode?: SubagentRunMode;
|
|
350
|
+
async?: boolean;
|
|
351
|
+
dynamic?: boolean;
|
|
352
|
+
dynamicGroup?: boolean;
|
|
353
|
+
agentContract?: AgentContract;
|
|
354
|
+
}): ResolvedAcceptanceConfig {
|
|
355
|
+
const explicit = normalizeAcceptanceInput(input.explicit);
|
|
356
|
+
const explicitLevel = normalizeLevel(explicit.level);
|
|
357
|
+
if (isAgentContractV1(input.agentContract)) {
|
|
358
|
+
const level = explicitAcceptanceCanDisable(explicit) || explicitLevel === "auto"
|
|
359
|
+
? "none"
|
|
360
|
+
: explicitLevel;
|
|
361
|
+
const evidence = unique(explicit.evidence ?? []);
|
|
362
|
+
const criteria = normalizeCriteria(
|
|
363
|
+
explicit.criteria as Array<string | { id?: string; must?: string; evidence?: AcceptanceEvidenceKind[]; severity?: "required" | "recommended" }> | undefined,
|
|
364
|
+
evidence,
|
|
365
|
+
);
|
|
366
|
+
return {
|
|
367
|
+
level,
|
|
368
|
+
explicit: input.explicit !== undefined,
|
|
369
|
+
inferredReason: [],
|
|
370
|
+
criteria,
|
|
371
|
+
evidence,
|
|
372
|
+
verify: explicit.verify ?? [],
|
|
373
|
+
review: explicit.review,
|
|
374
|
+
stopRules: explicit.stopRules ?? [],
|
|
375
|
+
reason: explicit.reason,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
const inferred = inferLevel(input);
|
|
379
|
+
const level = explicitAcceptanceCanDisable(explicit)
|
|
380
|
+
? "none"
|
|
381
|
+
: explicitLevel === "auto"
|
|
382
|
+
? inferred.level
|
|
383
|
+
: (LEVEL_RANK[explicitLevel] >= LEVEL_RANK[inferred.level] ? explicitLevel : inferred.level);
|
|
384
|
+
const evidence = unique([...(level === inferred.level ? inferred.evidence : requiredEvidenceForLevel(level)), ...(explicit.evidence ?? [])]);
|
|
385
|
+
const criteria = normalizeCriteria(
|
|
386
|
+
(explicit.criteria?.length ? explicit.criteria : inferred.criteria) as Array<string | { id?: string; must?: string; evidence?: AcceptanceEvidenceKind[]; severity?: "required" | "recommended" }>,
|
|
387
|
+
evidence,
|
|
388
|
+
);
|
|
389
|
+
const review = explicit.review !== undefined ? explicit.review : inferred.review;
|
|
390
|
+
return {
|
|
391
|
+
level,
|
|
392
|
+
explicit: input.explicit !== undefined,
|
|
393
|
+
inferredReason: inferred.reasons,
|
|
394
|
+
criteria,
|
|
395
|
+
evidence,
|
|
396
|
+
verify: explicit.verify ?? [],
|
|
397
|
+
review,
|
|
398
|
+
stopRules: explicit.stopRules ?? [],
|
|
399
|
+
reason: explicit.reason,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function acceptanceRequiresChildReport(acceptance: ResolvedAcceptanceConfig): boolean {
|
|
404
|
+
return acceptance.criteria.length > 0 || acceptance.evidence.length > 0;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, options: { reportOptional?: boolean } = {}): string {
|
|
408
|
+
if (acceptance.level === "none") return "";
|
|
409
|
+
if (options.reportOptional && !acceptanceRequiresChildReport(acceptance)) return "";
|
|
410
|
+
const lines = [
|
|
411
|
+
"",
|
|
412
|
+
"## Acceptance Contract",
|
|
413
|
+
`Acceptance level: ${acceptance.level}`,
|
|
414
|
+
"Completion is not accepted from prose alone. End with a structured acceptance report.",
|
|
415
|
+
"",
|
|
416
|
+
"Criteria:",
|
|
417
|
+
...(acceptance.criteria.length ? acceptance.criteria.map((criterion) => `- ${criterion.id}: ${criterion.must}`) : ["- Return the requested result."]),
|
|
418
|
+
"",
|
|
419
|
+
`Required evidence: ${acceptance.evidence.join(", ") || "none"}`,
|
|
420
|
+
];
|
|
421
|
+
if (acceptance.verify.length > 0) {
|
|
422
|
+
lines.push("", "Runtime verification commands configured by parent:");
|
|
423
|
+
for (const command of acceptance.verify) lines.push(`- ${command.id}: ${command.command}`);
|
|
424
|
+
}
|
|
425
|
+
if (acceptance.review) {
|
|
426
|
+
lines.push("", `Review gate: ${acceptance.review.required === false ? "optional" : "required"}${acceptance.review.agent ? ` by ${acceptance.review.agent}` : ""}.`);
|
|
427
|
+
if (acceptance.review.focus) lines.push(`Review focus: ${acceptance.review.focus}`);
|
|
428
|
+
}
|
|
429
|
+
if (acceptance.stopRules.length > 0) {
|
|
430
|
+
lines.push("", "Stop rules:", ...acceptance.stopRules.map((rule) => `- ${rule}`));
|
|
431
|
+
}
|
|
432
|
+
lines.push(
|
|
433
|
+
"",
|
|
434
|
+
"Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
|
|
435
|
+
"Use empty arrays when no items apply; array fields contain strings unless object entries are shown.",
|
|
436
|
+
"`criteriaSatisfied[].status` must be exactly one of: satisfied, not-satisfied, not-applicable.",
|
|
437
|
+
"`commandsRun[].result` must be exactly one of: passed, failed, not-run.",
|
|
438
|
+
"`manualNotes` and `notes` are optional strings; an empty string means no note and does not satisfy `manual-notes` evidence.",
|
|
439
|
+
"```acceptance-report",
|
|
440
|
+
JSON.stringify({
|
|
441
|
+
criteriaSatisfied: acceptance.criteria
|
|
442
|
+
.filter((criterion) => criterion.severity !== "recommended")
|
|
443
|
+
.map((criterion) => ({ id: criterion.id, status: "satisfied", evidence: "specific proof" })),
|
|
444
|
+
changedFiles: ["src/file.ts"],
|
|
445
|
+
testsAddedOrUpdated: ["test/file.test.ts"],
|
|
446
|
+
commandsRun: [{ command: "command", result: "passed", summary: "short result" }],
|
|
447
|
+
validationOutput: ["validation output or concise summary"],
|
|
448
|
+
residualRisks: ["none"],
|
|
449
|
+
noStagedFiles: true,
|
|
450
|
+
diffSummary: "short description of the diff",
|
|
451
|
+
reviewFindings: ["blocker: file.ts:12 - issue found, or no blockers"],
|
|
452
|
+
manualNotes: "anything else the parent should know",
|
|
453
|
+
}, null, 2),
|
|
454
|
+
"```",
|
|
455
|
+
);
|
|
456
|
+
return lines.join("\n");
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function extractBalancedJson(text: string, start: number): string | undefined {
|
|
460
|
+
let depth = 0;
|
|
461
|
+
let inString = false;
|
|
462
|
+
let escaped = false;
|
|
463
|
+
for (let i = start; i < text.length; i++) {
|
|
464
|
+
const char = text[i]!;
|
|
465
|
+
if (inString) {
|
|
466
|
+
if (escaped) escaped = false;
|
|
467
|
+
else if (char === "\\") escaped = true;
|
|
468
|
+
else if (char === "\"") inString = false;
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (char === "\"") {
|
|
472
|
+
inString = true;
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
if (char === "{") depth++;
|
|
476
|
+
if (char === "}") {
|
|
477
|
+
depth--;
|
|
478
|
+
if (depth === 0) return text.slice(start, i + 1);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return undefined;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const ACCEPTANCE_REPORT_WRAPPERS = new Set(["acceptance", "acceptance-report", "acceptance_report", "acceptanceReport"]);
|
|
485
|
+
|
|
486
|
+
const ACCEPTANCE_REPORT_FIELDS: Record<string, keyof AcceptanceReport> = {
|
|
487
|
+
criteriaSatisfied: "criteriaSatisfied",
|
|
488
|
+
criteria_satisfied: "criteriaSatisfied",
|
|
489
|
+
changedFiles: "changedFiles",
|
|
490
|
+
changed_files: "changedFiles",
|
|
491
|
+
testsAddedOrUpdated: "testsAddedOrUpdated",
|
|
492
|
+
tests_added_or_updated: "testsAddedOrUpdated",
|
|
493
|
+
commandsRun: "commandsRun",
|
|
494
|
+
commands_run: "commandsRun",
|
|
495
|
+
validationOutput: "validationOutput",
|
|
496
|
+
validation_output: "validationOutput",
|
|
497
|
+
residualRisks: "residualRisks",
|
|
498
|
+
residual_risks: "residualRisks",
|
|
499
|
+
noStagedFiles: "noStagedFiles",
|
|
500
|
+
no_staged_files: "noStagedFiles",
|
|
501
|
+
diffSummary: "diffSummary",
|
|
502
|
+
diff_summary: "diffSummary",
|
|
503
|
+
reviewFindings: "reviewFindings",
|
|
504
|
+
review_findings: "reviewFindings",
|
|
505
|
+
manualNotes: "manualNotes",
|
|
506
|
+
manual_notes: "manualNotes",
|
|
507
|
+
notes: "notes",
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
const CRITERION_REPORT_FIELDS = new Set(["id", "status", "evidence"]);
|
|
511
|
+
const COMMAND_REPORT_FIELDS = new Set(["command", "result", "summary"]);
|
|
512
|
+
|
|
513
|
+
function normalizedToken(value: string): string {
|
|
514
|
+
return value.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/-+/g, "-");
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function normalizeCriterionStatus(value: unknown): unknown {
|
|
518
|
+
if (typeof value !== "string") return value;
|
|
519
|
+
const token = normalizedToken(value);
|
|
520
|
+
if (["satisfied", "met", "complete", "completed", "done", "pass", "passed", "success", "succeeded"].includes(token)) return "satisfied";
|
|
521
|
+
if (["not-satisfied", "not-met", "unmet", "incomplete", "fail", "failed"].includes(token)) return "not-satisfied";
|
|
522
|
+
if (["not-applicable", "n-a", "na", "skip", "skipped"].includes(token)) return "not-applicable";
|
|
523
|
+
return value;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function normalizeCommandResult(value: unknown): unknown {
|
|
527
|
+
if (typeof value !== "string") return value;
|
|
528
|
+
const token = normalizedToken(value);
|
|
529
|
+
if (["passed", "pass", "success", "successful", "succeeded", "ok"].includes(token)) return "passed";
|
|
530
|
+
if (["failed", "fail", "failure", "error"].includes(token)) return "failed";
|
|
531
|
+
if (["not-run", "not-executed", "skip", "skipped"].includes(token)) return "not-run";
|
|
532
|
+
return value;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function normalizeCriterionReport(value: unknown, pathLabel: string, errors: string[]): unknown {
|
|
536
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
537
|
+
const normalized: Record<string, unknown> = {};
|
|
538
|
+
for (const [key, fieldValue] of Object.entries(value as Record<string, unknown>)) {
|
|
539
|
+
if (!CRITERION_REPORT_FIELDS.has(key)) {
|
|
540
|
+
errors.push(`${pathLabel}.${key}: unsupported acceptance criterion field`);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
normalized[key] = key === "id" && typeof fieldValue === "string"
|
|
544
|
+
? normalizedToken(fieldValue)
|
|
545
|
+
: key === "status"
|
|
546
|
+
? normalizeCriterionStatus(fieldValue)
|
|
547
|
+
: fieldValue;
|
|
548
|
+
}
|
|
549
|
+
return normalized;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function normalizeCommandReport(value: unknown, pathLabel: string, errors: string[]): unknown {
|
|
553
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
554
|
+
const normalized: Record<string, unknown> = {};
|
|
555
|
+
for (const [key, fieldValue] of Object.entries(value as Record<string, unknown>)) {
|
|
556
|
+
if (!COMMAND_REPORT_FIELDS.has(key)) {
|
|
557
|
+
errors.push(`${pathLabel}.${key}: unsupported acceptance command field`);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
normalized[key] = key === "result" ? normalizeCommandResult(fieldValue) : fieldValue;
|
|
561
|
+
}
|
|
562
|
+
return normalized;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function normalizeAcceptanceReportValue(value: unknown, pathLabel = ""): { value: unknown; pathLabel: string; errors: string[] } {
|
|
566
|
+
const errors: string[] = [];
|
|
567
|
+
let reportValue = value;
|
|
568
|
+
let reportPath = pathLabel;
|
|
569
|
+
if (reportValue && typeof reportValue === "object" && !Array.isArray(reportValue)) {
|
|
570
|
+
const record = reportValue as Record<string, unknown>;
|
|
571
|
+
const wrapperKeys = Object.keys(record).filter((key) => ACCEPTANCE_REPORT_WRAPPERS.has(key));
|
|
572
|
+
if (wrapperKeys.length > 0) {
|
|
573
|
+
const wrapperKey = wrapperKeys[0]!;
|
|
574
|
+
if (wrapperKeys.length > 1) errors.push(`${pathLabel || "acceptance-report"}: multiple acceptance report wrappers are ambiguous`);
|
|
575
|
+
for (const key of Object.keys(record)) {
|
|
576
|
+
if (key !== wrapperKey) errors.push(`${pathFor(pathLabel, key)}: unsupported alongside acceptance report wrapper '${wrapperKey}'`);
|
|
577
|
+
}
|
|
578
|
+
reportValue = record[wrapperKey];
|
|
579
|
+
reportPath = pathFor(pathLabel, wrapperKey);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (!reportValue || typeof reportValue !== "object" || Array.isArray(reportValue)) return { value: reportValue, pathLabel: reportPath, errors };
|
|
583
|
+
|
|
584
|
+
const normalized: Record<string, unknown> = {};
|
|
585
|
+
for (const [key, fieldValue] of Object.entries(reportValue as Record<string, unknown>)) {
|
|
586
|
+
const canonical = ACCEPTANCE_REPORT_FIELDS[key];
|
|
587
|
+
if (!canonical) {
|
|
588
|
+
errors.push(`${pathFor(reportPath, key)}: unsupported acceptance report field`);
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
if (Object.hasOwn(normalized, canonical)) {
|
|
592
|
+
errors.push(`${pathFor(reportPath, key)}: duplicates normalized field '${canonical}'`);
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
const fieldPath = pathFor(reportPath, canonical);
|
|
596
|
+
switch (canonical) {
|
|
597
|
+
case "criteriaSatisfied": {
|
|
598
|
+
const items = Array.isArray(fieldValue) ? fieldValue : fieldValue && typeof fieldValue === "object" ? [fieldValue] : fieldValue;
|
|
599
|
+
normalized[canonical] = Array.isArray(items)
|
|
600
|
+
? items.map((item, index) => normalizeCriterionReport(item, `${fieldPath}[${index}]`, errors))
|
|
601
|
+
: items;
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
case "commandsRun": {
|
|
605
|
+
const items = Array.isArray(fieldValue) ? fieldValue : fieldValue && typeof fieldValue === "object" ? [fieldValue] : fieldValue;
|
|
606
|
+
normalized[canonical] = Array.isArray(items)
|
|
607
|
+
? items.map((item, index) => normalizeCommandReport(item, `${fieldPath}[${index}]`, errors))
|
|
608
|
+
: items;
|
|
609
|
+
break;
|
|
610
|
+
}
|
|
611
|
+
case "changedFiles":
|
|
612
|
+
case "testsAddedOrUpdated":
|
|
613
|
+
case "validationOutput":
|
|
614
|
+
case "residualRisks":
|
|
615
|
+
case "reviewFindings":
|
|
616
|
+
normalized[canonical] = typeof fieldValue === "string" ? [fieldValue] : fieldValue;
|
|
617
|
+
break;
|
|
618
|
+
case "noStagedFiles": {
|
|
619
|
+
const token = typeof fieldValue === "string" ? fieldValue.trim().toLowerCase() : undefined;
|
|
620
|
+
normalized[canonical] = token === "true" ? true : token === "false" ? false : fieldValue;
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
default:
|
|
624
|
+
normalized[canonical] = fieldValue;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return { value: normalized, pathLabel: reportPath, errors };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function hasGenericAcceptanceReportSignal(value: unknown): boolean {
|
|
631
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
632
|
+
const record = value as Record<string, unknown>;
|
|
633
|
+
return "criteriaSatisfied" in record && [
|
|
634
|
+
"changedFiles",
|
|
635
|
+
"testsAddedOrUpdated",
|
|
636
|
+
"commandsRun",
|
|
637
|
+
"validationOutput",
|
|
638
|
+
"residualRisks",
|
|
639
|
+
"noStagedFiles",
|
|
640
|
+
"diffSummary",
|
|
641
|
+
"reviewFindings",
|
|
642
|
+
"manualNotes",
|
|
643
|
+
].some((key) => key in record);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function parseReportJson(body: string): unknown {
|
|
647
|
+
const trimmed = body.trim();
|
|
648
|
+
try {
|
|
649
|
+
return JSON.parse(trimmed) as unknown;
|
|
650
|
+
} catch (error) {
|
|
651
|
+
const jsonStart = trimmed.indexOf("{");
|
|
652
|
+
if (jsonStart > 0) {
|
|
653
|
+
const json = extractBalancedJson(trimmed, jsonStart);
|
|
654
|
+
if (json) return JSON.parse(json) as unknown;
|
|
655
|
+
}
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function fencedBlocks(output: string, tag: string): string[] {
|
|
661
|
+
return [...output.matchAll(new RegExp(`\`\`\`${tag}\\s*\\n([\\s\\S]*?)\`\`\``, "gi"))]
|
|
662
|
+
.map((match) => match[1]?.trim())
|
|
663
|
+
.filter((value): value is string => Boolean(value));
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function parseAcceptanceReportBody(body: string): { report?: AcceptanceReport; errors: string[] } {
|
|
667
|
+
return validateAcceptanceReport(parseReportJson(body));
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function parseUnterminatedAcceptanceReportFence(output: string): { report?: AcceptanceReport; error?: string } {
|
|
671
|
+
const opener = /```acceptance[-_]report\b[^\n]*\n/gi.exec(output);
|
|
672
|
+
if (!opener) return {};
|
|
673
|
+
const bodyStart = opener.index + opener[0].length;
|
|
674
|
+
if (output.indexOf("```", bodyStart) !== -1) return {};
|
|
675
|
+
try {
|
|
676
|
+
const validation = validateAcceptanceReport(JSON.parse(output.slice(bodyStart).trim()) as unknown);
|
|
677
|
+
return validation.report
|
|
678
|
+
? { report: validation.report }
|
|
679
|
+
: { error: `Failed to parse acceptance-report: Invalid acceptance-report: ${validation.errors.join("; ")}` };
|
|
680
|
+
} catch (error) {
|
|
681
|
+
return { error: `Failed to parse acceptance-report: ${error instanceof Error ? error.message : String(error)}` };
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function parseGenericJsonAcceptanceReportBody(body: string): { report?: AcceptanceReport; error?: string } {
|
|
686
|
+
const parsed = parseReportJson(body);
|
|
687
|
+
const normalized = normalizeAcceptanceReportValue(parsed);
|
|
688
|
+
const hasCriteriaMarker = normalized.value !== null
|
|
689
|
+
&& typeof normalized.value === "object"
|
|
690
|
+
&& !Array.isArray(normalized.value)
|
|
691
|
+
&& "criteriaSatisfied" in normalized.value;
|
|
692
|
+
if (!hasGenericAcceptanceReportSignal(normalized.value) && !(hasCriteriaMarker && normalized.errors.length > 0)) return {};
|
|
693
|
+
const validation = validateAcceptanceReport(parsed);
|
|
694
|
+
return validation.report
|
|
695
|
+
? { report: validation.report }
|
|
696
|
+
: { error: `Invalid acceptance-report: ${validation.errors.join("; ")}` };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
export const ACCEPTANCE_REPORT_NOT_FOUND = "Structured acceptance report not found.";
|
|
700
|
+
|
|
701
|
+
export function parseAcceptanceReport(output: string): { report?: AcceptanceReport; error?: string } {
|
|
702
|
+
const explicitFencePresent = /```acceptance[-_]report\b/i.test(output);
|
|
703
|
+
const fenced = fencedBlocks(output, "acceptance[-_]report");
|
|
704
|
+
const parseErrors: string[] = [];
|
|
705
|
+
for (const body of fenced) {
|
|
706
|
+
try {
|
|
707
|
+
const validation = parseAcceptanceReportBody(body);
|
|
708
|
+
if (validation.report) return { report: validation.report };
|
|
709
|
+
parseErrors.push(`Invalid acceptance-report: ${validation.errors.join("; ")}`);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
parseErrors.push(error instanceof Error ? error.message : String(error));
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
if (parseErrors.length > 0) return { error: `Failed to parse acceptance-report: ${parseErrors.join("; ")}` };
|
|
715
|
+
if (explicitFencePresent) {
|
|
716
|
+
const recovered = parseUnterminatedAcceptanceReportFence(output);
|
|
717
|
+
if (recovered.report || recovered.error) return recovered;
|
|
718
|
+
return { error: "Failed to parse acceptance-report: Empty or unterminated acceptance-report fence." };
|
|
719
|
+
}
|
|
720
|
+
for (const body of fencedBlocks(output, "(?:json|jsonc|json5)")) {
|
|
721
|
+
try {
|
|
722
|
+
const parsed = parseGenericJsonAcceptanceReportBody(body);
|
|
723
|
+
if (parsed.report) return { report: parsed.report };
|
|
724
|
+
if (parsed.error) return { error: `Failed to parse acceptance-report: ${parsed.error}` };
|
|
725
|
+
} catch {
|
|
726
|
+
// Ignore unrelated malformed generic JSON. A recognizable report shape
|
|
727
|
+
// returns exact validation errors above instead of being mistaken for prose.
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const markerIndex = output.search(/ACCEPTANCE_REPORT\s*:/i);
|
|
731
|
+
if (markerIndex !== -1) {
|
|
732
|
+
const jsonStart = output.indexOf("{", markerIndex);
|
|
733
|
+
if (jsonStart === -1) {
|
|
734
|
+
return { error: "Failed to parse acceptance-report: Expected a JSON object after ACCEPTANCE_REPORT:." };
|
|
735
|
+
}
|
|
736
|
+
const json = extractBalancedJson(output, jsonStart);
|
|
737
|
+
if (!json) {
|
|
738
|
+
return { error: "Failed to parse acceptance-report: Unterminated JSON object after ACCEPTANCE_REPORT:." };
|
|
739
|
+
}
|
|
740
|
+
try {
|
|
741
|
+
const parsed = JSON.parse(json) as unknown;
|
|
742
|
+
const validation = validateAcceptanceReport(parsed);
|
|
743
|
+
if (validation.report) return { report: validation.report };
|
|
744
|
+
return { error: `Failed to parse acceptance-report: Invalid acceptance-report: ${validation.errors.join("; ")}` };
|
|
745
|
+
} catch (error) {
|
|
746
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
747
|
+
return { error: `Failed to parse acceptance-report: ${message}` };
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
return { error: ACCEPTANCE_REPORT_NOT_FOUND };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function parseAcceptanceReportSources(
|
|
754
|
+
output: string,
|
|
755
|
+
fileOutput: { content: string; path: string; authoritative?: boolean } | undefined,
|
|
756
|
+
): { report?: AcceptanceReport; error?: string } {
|
|
757
|
+
const fromText = () => parseAcceptanceReport(output);
|
|
758
|
+
const fromFile = () => {
|
|
759
|
+
if (!fileOutput) return { error: ACCEPTANCE_REPORT_NOT_FOUND };
|
|
760
|
+
const parsed = parseAcceptanceReport(fileOutput.content);
|
|
761
|
+
return parsed.report || parsed.error === ACCEPTANCE_REPORT_NOT_FOUND
|
|
762
|
+
? parsed
|
|
763
|
+
: { error: `${parsed.error} (in configured output ${fileOutput.path})` };
|
|
764
|
+
};
|
|
765
|
+
const [primary, secondary] = fileOutput?.authoritative ? [fromFile, fromText] : [fromText, fromFile];
|
|
766
|
+
const first = primary();
|
|
767
|
+
// A malformed report in the primary source is a defect to surface, not a
|
|
768
|
+
// miss to paper over with the secondary source; only a genuinely absent
|
|
769
|
+
// report falls through.
|
|
770
|
+
if (first.report || first.error !== ACCEPTANCE_REPORT_NOT_FOUND) return first;
|
|
771
|
+
return secondary();
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
export function stripAcceptanceReport(output: string): string {
|
|
775
|
+
const trailingFencePattern = /\n?```(acceptance[-_]report|json|jsonc|json5)\s*\n([\s\S]*?)```\s*/gi;
|
|
776
|
+
let trailingFence: { index: number; tag: string; body: string } | undefined;
|
|
777
|
+
for (const match of output.matchAll(trailingFencePattern)) {
|
|
778
|
+
const end = (match.index ?? 0) + match[0].length;
|
|
779
|
+
if (output.slice(end).trim().length === 0 && match[1] && match[2]) {
|
|
780
|
+
trailingFence = { index: match.index ?? 0, tag: match[1].toLowerCase(), body: match[2] };
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
if (trailingFence) {
|
|
784
|
+
if (trailingFence.tag === "acceptance-report" || trailingFence.tag === "acceptance_report") return output.slice(0, trailingFence.index).trimEnd();
|
|
785
|
+
try {
|
|
786
|
+
if (parseGenericJsonAcceptanceReportBody(trailingFence.body).report) return output.slice(0, trailingFence.index).trimEnd();
|
|
787
|
+
} catch {
|
|
788
|
+
// Leave unrelated or malformed generic JSON fences visible.
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return output
|
|
792
|
+
.replace(/\n?```acceptance[-_]report\s*\n[\s\S]*?```\s*$/i, "")
|
|
793
|
+
.replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i, "")
|
|
794
|
+
.trimEnd();
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function isStringArray(value: unknown): value is string[] {
|
|
798
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function pathFor(base: string, segment: string): string {
|
|
802
|
+
return base ? `${base}.${segment}` : segment;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function describeValidationValue(value: unknown): string {
|
|
806
|
+
if (value === undefined) return "missing";
|
|
807
|
+
if (value === null) return "null";
|
|
808
|
+
if (Array.isArray(value)) return "array";
|
|
809
|
+
if (typeof value === "object") return "object";
|
|
810
|
+
if (typeof value === "string") {
|
|
811
|
+
const short = value.length > 80 ? `${value.slice(0, 77)}...` : value;
|
|
812
|
+
return JSON.stringify(short);
|
|
813
|
+
}
|
|
814
|
+
return `${typeof value} ${String(value)}`;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function pushTypeError(errors: string[], pathLabel: string, expected: string, value: unknown): void {
|
|
818
|
+
errors.push(`${pathLabel}: expected ${expected}; got ${describeValidationValue(value)}`);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function validateStringArrayField(errors: string[], value: unknown, pathLabel: string): void {
|
|
822
|
+
if (!Array.isArray(value)) {
|
|
823
|
+
pushTypeError(errors, pathLabel, "string[]", value);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
for (const [index, item] of value.entries()) {
|
|
827
|
+
if (typeof item !== "string" || !item.trim()) pushTypeError(errors, `${pathLabel}[${index}]`, "non-empty string", item);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function validateAcceptanceReport(value: unknown, pathLabel = ""): { report?: AcceptanceReport; errors: string[] } {
|
|
832
|
+
const normalized = normalizeAcceptanceReportValue(value, pathLabel);
|
|
833
|
+
value = normalized.value;
|
|
834
|
+
pathLabel = normalized.pathLabel;
|
|
835
|
+
const errors = normalized.errors;
|
|
836
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
837
|
+
pushTypeError(errors, pathLabel || "acceptance-report", "object", value);
|
|
838
|
+
return { errors };
|
|
839
|
+
}
|
|
840
|
+
const report = value as AcceptanceReport;
|
|
841
|
+
if (report.criteriaSatisfied !== undefined) {
|
|
842
|
+
if (!Array.isArray(report.criteriaSatisfied)) {
|
|
843
|
+
pushTypeError(errors, pathFor(pathLabel, "criteriaSatisfied"), "array", report.criteriaSatisfied);
|
|
844
|
+
} else {
|
|
845
|
+
const criterionIds = new Set<string>();
|
|
846
|
+
for (const [index, item] of report.criteriaSatisfied.entries()) {
|
|
847
|
+
const itemPath = `${pathFor(pathLabel, "criteriaSatisfied")}[${index}]`;
|
|
848
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
849
|
+
pushTypeError(errors, itemPath, "object", item);
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
const criterion = item as { id?: unknown; status?: unknown; evidence?: unknown };
|
|
853
|
+
if (criterion.id !== undefined && typeof criterion.id !== "string") {
|
|
854
|
+
pushTypeError(errors, `${itemPath}.id`, "string", criterion.id);
|
|
855
|
+
} else if (typeof criterion.id === "string" && criterion.id) {
|
|
856
|
+
if (criterionIds.has(criterion.id)) errors.push(`${itemPath}.id: duplicate normalized criterion id '${criterion.id}'`);
|
|
857
|
+
criterionIds.add(criterion.id);
|
|
858
|
+
}
|
|
859
|
+
if (criterion.status !== "satisfied" && criterion.status !== "not-satisfied" && criterion.status !== "not-applicable") {
|
|
860
|
+
pushTypeError(errors, `${itemPath}.status`, "one of \"satisfied\", \"not-satisfied\", \"not-applicable\"", criterion.status);
|
|
861
|
+
}
|
|
862
|
+
if (typeof criterion.evidence !== "string" || !criterion.evidence.trim()) pushTypeError(errors, `${itemPath}.evidence`, "non-empty string", criterion.evidence);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
if (report.changedFiles !== undefined) validateStringArrayField(errors, report.changedFiles, pathFor(pathLabel, "changedFiles"));
|
|
867
|
+
if (report.testsAddedOrUpdated !== undefined) validateStringArrayField(errors, report.testsAddedOrUpdated, pathFor(pathLabel, "testsAddedOrUpdated"));
|
|
868
|
+
if (report.commandsRun !== undefined) {
|
|
869
|
+
if (!Array.isArray(report.commandsRun)) {
|
|
870
|
+
pushTypeError(errors, pathFor(pathLabel, "commandsRun"), "array", report.commandsRun);
|
|
871
|
+
} else {
|
|
872
|
+
for (const [index, item] of report.commandsRun.entries()) {
|
|
873
|
+
const itemPath = `${pathFor(pathLabel, "commandsRun")}[${index}]`;
|
|
874
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
875
|
+
pushTypeError(errors, itemPath, "object", item);
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
const command = item as { command?: unknown; result?: unknown; summary?: unknown };
|
|
879
|
+
if (typeof command.command !== "string" || !command.command.trim()) pushTypeError(errors, `${itemPath}.command`, "non-empty string", command.command);
|
|
880
|
+
if (command.result !== "passed" && command.result !== "failed" && command.result !== "not-run") {
|
|
881
|
+
pushTypeError(errors, `${itemPath}.result`, "one of \"passed\", \"failed\", \"not-run\"", command.result);
|
|
882
|
+
}
|
|
883
|
+
if (typeof command.summary !== "string" || !command.summary.trim()) pushTypeError(errors, `${itemPath}.summary`, "non-empty string", command.summary);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
if (report.validationOutput !== undefined) validateStringArrayField(errors, report.validationOutput, pathFor(pathLabel, "validationOutput"));
|
|
888
|
+
if (report.residualRisks !== undefined) validateStringArrayField(errors, report.residualRisks, pathFor(pathLabel, "residualRisks"));
|
|
889
|
+
if (report.noStagedFiles !== undefined && typeof report.noStagedFiles !== "boolean") pushTypeError(errors, pathFor(pathLabel, "noStagedFiles"), "boolean", report.noStagedFiles);
|
|
890
|
+
if (report.diffSummary !== undefined && (typeof report.diffSummary !== "string" || !report.diffSummary.trim())) pushTypeError(errors, pathFor(pathLabel, "diffSummary"), "non-empty string", report.diffSummary);
|
|
891
|
+
if (report.reviewFindings !== undefined) validateStringArrayField(errors, report.reviewFindings, pathFor(pathLabel, "reviewFindings"));
|
|
892
|
+
if (report.manualNotes !== undefined && typeof report.manualNotes !== "string") pushTypeError(errors, pathFor(pathLabel, "manualNotes"), "string", report.manualNotes);
|
|
893
|
+
if (report.notes !== undefined && typeof report.notes !== "string") pushTypeError(errors, pathFor(pathLabel, "notes"), "string", report.notes);
|
|
894
|
+
if (errors.length > 0) return { errors };
|
|
895
|
+
const hasReportField = report.criteriaSatisfied !== undefined
|
|
896
|
+
|| report.changedFiles !== undefined
|
|
897
|
+
|| report.testsAddedOrUpdated !== undefined
|
|
898
|
+
|| report.commandsRun !== undefined
|
|
899
|
+
|| report.validationOutput !== undefined
|
|
900
|
+
|| report.residualRisks !== undefined
|
|
901
|
+
|| report.noStagedFiles !== undefined
|
|
902
|
+
|| report.diffSummary !== undefined
|
|
903
|
+
|| report.manualNotes !== undefined
|
|
904
|
+
|| report.notes !== undefined
|
|
905
|
+
|| report.reviewFindings !== undefined;
|
|
906
|
+
return hasReportField
|
|
907
|
+
? { report, errors }
|
|
908
|
+
: { errors: [`${pathLabel || "acceptance-report"}: expected at least one acceptance report field`] };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function checkCriteriaSatisfied(criteria: ResolvedAcceptanceGate[], report: AcceptanceReport): AcceptanceRuntimeCheck[] {
|
|
912
|
+
const reports = new Map((report.criteriaSatisfied ?? []).filter((item) => item.id).map((item) => [normalizedToken(item.id!), item]));
|
|
913
|
+
return criteria.filter((criterion) => criterion.severity !== "recommended").map((criterion) => {
|
|
914
|
+
const item = reports.get(normalizedToken(criterion.id));
|
|
915
|
+
if (!item) return { id: `criterion:${criterion.id}`, status: "failed", message: `Required criterion '${criterion.id}' was not reported.` };
|
|
916
|
+
if (item.status !== "satisfied") return { id: `criterion:${criterion.id}`, status: "failed", message: `Required criterion '${criterion.id}' was reported as ${item.status}.` };
|
|
917
|
+
return { id: `criterion:${criterion.id}`, status: "passed", message: `Required criterion '${criterion.id}' satisfied.` };
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function reportEvidenceStatus(report: AcceptanceReport, kind: AcceptanceEvidenceKind): AcceptanceRuntimeCheckStatus {
|
|
922
|
+
switch (kind) {
|
|
923
|
+
case "changed-files":
|
|
924
|
+
if (!isStringArray(report.changedFiles)) return "failed";
|
|
925
|
+
return report.changedFiles.length === 0 ? "not-applicable" : "passed";
|
|
926
|
+
case "tests-added":
|
|
927
|
+
if (!isStringArray(report.testsAddedOrUpdated)) return "failed";
|
|
928
|
+
return report.testsAddedOrUpdated.length === 0 ? "not-applicable" : "passed";
|
|
929
|
+
case "commands-run": return Array.isArray(report.commandsRun) && report.commandsRun.length > 0 ? "passed" : "failed";
|
|
930
|
+
case "validation-output": return isStringArray(report.validationOutput) && report.validationOutput.length > 0 ? "passed" : "failed";
|
|
931
|
+
case "residual-risks": return isStringArray(report.residualRisks) ? "passed" : "failed";
|
|
932
|
+
case "no-staged-files": return report.noStagedFiles === true ? "passed" : "failed";
|
|
933
|
+
case "diff-summary": return typeof report.diffSummary === "string" && report.diffSummary.trim().length > 0 ? "passed" : "failed";
|
|
934
|
+
case "review-findings": return isStringArray(report.reviewFindings) ? "passed" : "failed";
|
|
935
|
+
case "manual-notes": return Boolean((report.manualNotes ?? report.notes)?.trim()) ? "passed" : "failed";
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function checkNoStagedFiles(cwd: string): AcceptanceRuntimeCheck {
|
|
940
|
+
const result = spawnSync("git", ["status", "--short"], { cwd, encoding: "utf-8" });
|
|
941
|
+
if (result.status !== 0) {
|
|
942
|
+
return { id: "no-staged-files", status: "not-applicable", message: "git status unavailable; no staged-files check skipped" };
|
|
943
|
+
}
|
|
944
|
+
const staged = result.stdout.split(/\r?\n/).filter((line) => line.length >= 2 && line[0] !== " " && line[0] !== "?");
|
|
945
|
+
return staged.length === 0
|
|
946
|
+
? { id: "no-staged-files", status: "passed", message: "No staged files detected." }
|
|
947
|
+
: { id: "no-staged-files", status: "failed", message: `Staged files present: ${staged.join(", ")}` };
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: AcceptanceReport, cwd: string): AcceptanceRuntimeCheck[] {
|
|
951
|
+
const checks: AcceptanceRuntimeCheck[] = [];
|
|
952
|
+
for (const kind of acceptance.evidence) {
|
|
953
|
+
const status = reportEvidenceStatus(report, kind);
|
|
954
|
+
checks.push({
|
|
955
|
+
id: `evidence:${kind}`,
|
|
956
|
+
status,
|
|
957
|
+
message: status === "passed"
|
|
958
|
+
? `${kind} evidence present.`
|
|
959
|
+
: status === "not-applicable"
|
|
960
|
+
? `${kind} evidence explicitly reported as not applicable.`
|
|
961
|
+
: `${kind} evidence missing from child report.`,
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
if (acceptance.evidence.includes("no-staged-files")) checks.push(checkNoStagedFiles(cwd));
|
|
965
|
+
return checks;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
function trimOutput(value: string): string | undefined {
|
|
969
|
+
const trimmed = value.trim();
|
|
970
|
+
if (!trimmed) return undefined;
|
|
971
|
+
return trimmed.length > 12_000 ? `${trimmed.slice(0, 12_000)}\n...[truncated]` : trimmed;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
const SENSITIVE_ENV_KEY_PATTERN = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASS|AUTH|CREDENTIAL|COOKIE|SESSION|PRIVATE|API_KEY|ACCESS_KEY)(?:_|$)/i;
|
|
975
|
+
|
|
976
|
+
function effectiveVerifyEnv(env: Record<string, string> | undefined): Record<string, string> {
|
|
977
|
+
const inherited = Object.fromEntries(Object.entries(process.env).flatMap(([key, value]) => {
|
|
978
|
+
return typeof value === "string" ? [[key, value]] : [];
|
|
979
|
+
}));
|
|
980
|
+
return { ...inherited, ...(env ?? {}) };
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function verifyRedactionEnv(env: Record<string, string> | undefined): Record<string, string> {
|
|
984
|
+
return Object.fromEntries(Object.entries(effectiveVerifyEnv(env)).filter(([key, value]) => {
|
|
985
|
+
return value.length >= 4 && SENSITIVE_ENV_KEY_PATTERN.test(key);
|
|
986
|
+
}));
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
function redactVerifyEnv(value: string, env: Record<string, string> | undefined): string {
|
|
990
|
+
let redacted = value;
|
|
991
|
+
const secrets = [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
|
|
992
|
+
for (const secret of secrets) redacted = redacted.replaceAll(secret, "[REDACTED]");
|
|
993
|
+
return redacted;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
function uniqueStrings(items: Array<string | undefined>): string[] {
|
|
997
|
+
return unique(items.map((item) => item?.trim()).filter((item): item is string => Boolean(item)));
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
export function aggregateAcceptanceReport(input: {
|
|
1001
|
+
results: Array<Pick<SingleResult, "agent" | "acceptance" | "error"> & { exitCode: number | null }>;
|
|
1002
|
+
notes?: string;
|
|
1003
|
+
}): AcceptanceReport {
|
|
1004
|
+
const childReports = input.results.map((result) => result.acceptance?.childReport).filter((report): report is AcceptanceReport => Boolean(report));
|
|
1005
|
+
const blockers = input.results.filter((result) => result.exitCode !== 0 || result.acceptance?.status === "rejected");
|
|
1006
|
+
const successfulChildren = input.results.length > 0 && blockers.length === 0;
|
|
1007
|
+
return {
|
|
1008
|
+
criteriaSatisfied: [
|
|
1009
|
+
{ id: "criterion-1", status: successfulChildren ? "satisfied" : "not-satisfied", evidence: successfulChildren ? `All ${input.results.length} dynamic child run(s) completed without child or acceptance blockers.` : "Dynamic fanout produced no accepted child evidence." },
|
|
1010
|
+
{ id: "criterion-2", status: successfulChildren ? "satisfied" : "not-satisfied", evidence: successfulChildren ? "Collected child acceptance evidence for aggregate review." : "Dynamic fanout produced no aggregate review evidence." },
|
|
1011
|
+
...input.results.map((result, index): { id?: string; status: "satisfied" | "not-satisfied" | "not-applicable"; evidence: string } => ({
|
|
1012
|
+
id: `child-${index + 1}`,
|
|
1013
|
+
status: result.exitCode === 0 && result.acceptance?.status !== "rejected" ? "satisfied" : "not-satisfied",
|
|
1014
|
+
evidence: `${result.agent}: acceptance ${result.acceptance?.status ?? "unreported"}${result.error ? ` (${result.error})` : ""}`,
|
|
1015
|
+
})),
|
|
1016
|
+
],
|
|
1017
|
+
changedFiles: uniqueStrings(childReports.flatMap((report) => report.changedFiles ?? [])),
|
|
1018
|
+
testsAddedOrUpdated: uniqueStrings(childReports.flatMap((report) => report.testsAddedOrUpdated ?? [])),
|
|
1019
|
+
commandsRun: childReports.flatMap((report) => report.commandsRun ?? []),
|
|
1020
|
+
validationOutput: uniqueStrings(childReports.flatMap((report) => report.validationOutput ?? [])),
|
|
1021
|
+
residualRisks: uniqueStrings([
|
|
1022
|
+
...childReports.flatMap((report) => report.residualRisks ?? []),
|
|
1023
|
+
...blockers.map((result) => `${result.agent}: ${result.error ?? "child or acceptance gate failed"}`),
|
|
1024
|
+
]),
|
|
1025
|
+
noStagedFiles: childReports.length > 0 && childReports.every((report) => report.noStagedFiles === true),
|
|
1026
|
+
reviewFindings: uniqueStrings(childReports.flatMap((report) => report.reviewFindings ?? [])),
|
|
1027
|
+
manualNotes: input.notes ?? `Aggregated acceptance evidence from ${input.results.length} dynamic fanout child run(s).`,
|
|
1028
|
+
notes: input.notes,
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const DEFAULT_VERIFY_TIMEOUT_MS = 120_000;
|
|
1033
|
+
|
|
1034
|
+
function hash(value: string): string {
|
|
1035
|
+
return createHash("sha256").update(value).digest("hex");
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
interface VerifyWorkspaceState {
|
|
1039
|
+
kind: "git-tracked";
|
|
1040
|
+
repoRoot: string;
|
|
1041
|
+
cwdRelative: string;
|
|
1042
|
+
head: string;
|
|
1043
|
+
diffHash: string;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function readVerifyWorkspaceState(cwd: string): VerifyWorkspaceState | undefined {
|
|
1047
|
+
const repo = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf-8" });
|
|
1048
|
+
if (repo.status !== 0 || !repo.stdout.trim()) return undefined;
|
|
1049
|
+
const repoRoot = fs.realpathSync(repo.stdout.trim());
|
|
1050
|
+
const head = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf-8" });
|
|
1051
|
+
const diff = spawnSync("git", ["diff", "--binary", "--full-index", "HEAD", "--"], { cwd: repoRoot, encoding: "utf-8", maxBuffer: 50 * 1024 * 1024 });
|
|
1052
|
+
if (head.status !== 0 || diff.status !== 0 || !head.stdout.trim()) return undefined;
|
|
1053
|
+
return {
|
|
1054
|
+
kind: "git-tracked",
|
|
1055
|
+
repoRoot,
|
|
1056
|
+
cwdRelative: path.relative(repoRoot, fs.realpathSync(cwd)) || ".",
|
|
1057
|
+
head: head.stdout.trim(),
|
|
1058
|
+
diffHash: hash(diff.stdout),
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
function isCachedVerifyResult(value: unknown): value is AcceptanceVerifyResult {
|
|
1063
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1064
|
+
const result = value as Partial<AcceptanceVerifyResult>;
|
|
1065
|
+
return typeof result.id === "string"
|
|
1066
|
+
&& typeof result.command === "string"
|
|
1067
|
+
&& (typeof result.exitCode === "number" || result.exitCode === null)
|
|
1068
|
+
&& (result.status === "passed" || result.status === "failed" || result.status === "timed-out" || result.status === "allowed-failure")
|
|
1069
|
+
&& typeof result.durationMs === "number";
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
async function runMemoizedVerifyCommand(command: AcceptanceVerifyCommand, defaultCwd: string, options: {
|
|
1073
|
+
signal?: AbortSignal;
|
|
1074
|
+
abortMessage?: string;
|
|
1075
|
+
artifactsDir?: string;
|
|
1076
|
+
runId?: string;
|
|
1077
|
+
} = {}): Promise<AcceptanceVerifyResult> {
|
|
1078
|
+
const cwd = command.cwd ? path.resolve(defaultCwd, command.cwd) : defaultCwd;
|
|
1079
|
+
let workspaceState: VerifyWorkspaceState | undefined;
|
|
1080
|
+
try {
|
|
1081
|
+
workspaceState = readVerifyWorkspaceState(cwd);
|
|
1082
|
+
} catch {
|
|
1083
|
+
workspaceState = undefined;
|
|
1084
|
+
}
|
|
1085
|
+
if (!workspaceState || !options.artifactsDir || !options.runId) {
|
|
1086
|
+
return runVerifyCommand(command, defaultCwd, options);
|
|
1087
|
+
}
|
|
1088
|
+
const envKeys = Object.keys(command.env ?? {}).sort();
|
|
1089
|
+
const envHash = hash(JSON.stringify(Object.fromEntries(Object.entries(effectiveVerifyEnv(command.env)).sort(([left], [right]) => left.localeCompare(right)))));
|
|
1090
|
+
const timeoutMs = command.timeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS;
|
|
1091
|
+
const cacheKey = hash(JSON.stringify({
|
|
1092
|
+
version: 1,
|
|
1093
|
+
command: command.command,
|
|
1094
|
+
cwdRelative: workspaceState.cwdRelative,
|
|
1095
|
+
envKeys,
|
|
1096
|
+
envHash,
|
|
1097
|
+
timeoutMs,
|
|
1098
|
+
allowFailure: command.allowFailure === true,
|
|
1099
|
+
head: workspaceState.head,
|
|
1100
|
+
diffHash: workspaceState.diffHash,
|
|
1101
|
+
}));
|
|
1102
|
+
const artifactPath = path.join(options.artifactsDir, "acceptance", "verify", options.runId, `${cacheKey}.json`);
|
|
1103
|
+
try {
|
|
1104
|
+
const cached = JSON.parse(fs.readFileSync(artifactPath, "utf-8")) as { cacheKey?: unknown; result?: unknown };
|
|
1105
|
+
if (cached.cacheKey === cacheKey && isCachedVerifyResult(cached.result)) {
|
|
1106
|
+
return { ...cached.result, id: command.id, command: command.command, cwd, artifactPath, cacheKey, memoized: true, envKeys, envHash, workspaceState };
|
|
1107
|
+
}
|
|
1108
|
+
} catch {
|
|
1109
|
+
// A cache miss or unreadable artifact must not prevent host verification.
|
|
1110
|
+
}
|
|
1111
|
+
const result = await runVerifyCommand(command, defaultCwd, options);
|
|
1112
|
+
const evidenced: AcceptanceVerifyResult = { ...result, artifactPath, cacheKey, memoized: false, envKeys, envHash, workspaceState };
|
|
1113
|
+
try {
|
|
1114
|
+
fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
|
|
1115
|
+
fs.writeFileSync(artifactPath, JSON.stringify({
|
|
1116
|
+
version: 1,
|
|
1117
|
+
cacheKey,
|
|
1118
|
+
command: command.command,
|
|
1119
|
+
cwdRelative: workspaceState.cwdRelative,
|
|
1120
|
+
envKeys,
|
|
1121
|
+
envHash,
|
|
1122
|
+
timeoutMs,
|
|
1123
|
+
allowFailure: command.allowFailure === true,
|
|
1124
|
+
workspaceState,
|
|
1125
|
+
result: evidenced,
|
|
1126
|
+
}, null, 2), "utf-8");
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
evidenced.artifactError = error instanceof Error ? error.message : String(error);
|
|
1129
|
+
delete evidenced.artifactPath;
|
|
1130
|
+
}
|
|
1131
|
+
return evidenced;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
function runVerifyCommand(command: AcceptanceVerifyCommand, defaultCwd: string, options: { signal?: AbortSignal; abortMessage?: string } = {}): Promise<AcceptanceVerifyResult> {
|
|
1135
|
+
return new Promise((resolve) => {
|
|
1136
|
+
const startedAt = Date.now();
|
|
1137
|
+
const cwd = command.cwd ? path.resolve(defaultCwd, command.cwd) : defaultCwd;
|
|
1138
|
+
let stdout = "";
|
|
1139
|
+
let stderr = "";
|
|
1140
|
+
let timedOut = false;
|
|
1141
|
+
let settled = false;
|
|
1142
|
+
let hardKill: NodeJS.Timeout | undefined;
|
|
1143
|
+
const child = spawn(command.command, {
|
|
1144
|
+
cwd,
|
|
1145
|
+
env: effectiveVerifyEnv(command.env),
|
|
1146
|
+
shell: true,
|
|
1147
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1148
|
+
windowsHide: true,
|
|
1149
|
+
});
|
|
1150
|
+
const finish = (result: Omit<AcceptanceVerifyResult, "id" | "command" | "cwd" | "durationMs">) => {
|
|
1151
|
+
if (settled) return;
|
|
1152
|
+
settled = true;
|
|
1153
|
+
clearTimeout(timeout);
|
|
1154
|
+
if (hardKill) clearTimeout(hardKill);
|
|
1155
|
+
options.signal?.removeEventListener("abort", abortVerification);
|
|
1156
|
+
resolve({
|
|
1157
|
+
id: command.id,
|
|
1158
|
+
command: command.command,
|
|
1159
|
+
cwd,
|
|
1160
|
+
durationMs: Date.now() - startedAt,
|
|
1161
|
+
...result,
|
|
1162
|
+
});
|
|
1163
|
+
};
|
|
1164
|
+
const abortVerification = () => {
|
|
1165
|
+
if (settled || timedOut) return;
|
|
1166
|
+
timedOut = true;
|
|
1167
|
+
child.kill("SIGTERM");
|
|
1168
|
+
hardKill = setTimeout(() => {
|
|
1169
|
+
child.kill("SIGKILL");
|
|
1170
|
+
finish({
|
|
1171
|
+
exitCode: null,
|
|
1172
|
+
status: "timed-out",
|
|
1173
|
+
stdout: trimOutput(redactVerifyEnv(stdout, command.env)),
|
|
1174
|
+
stderr: trimOutput(redactVerifyEnv(stderr || options.abortMessage || "Acceptance verification timed out.", command.env)),
|
|
1175
|
+
});
|
|
1176
|
+
}, 1000);
|
|
1177
|
+
hardKill.unref?.();
|
|
1178
|
+
};
|
|
1179
|
+
const timeout = setTimeout(abortVerification, command.timeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS);
|
|
1180
|
+
timeout.unref?.();
|
|
1181
|
+
if (options.signal?.aborted) abortVerification();
|
|
1182
|
+
else options.signal?.addEventListener("abort", abortVerification, { once: true });
|
|
1183
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
1184
|
+
stdout += chunk.toString();
|
|
1185
|
+
});
|
|
1186
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
1187
|
+
stderr += chunk.toString();
|
|
1188
|
+
});
|
|
1189
|
+
child.on("close", (exitCode) => {
|
|
1190
|
+
const passed = exitCode === 0 && !timedOut;
|
|
1191
|
+
finish({
|
|
1192
|
+
exitCode,
|
|
1193
|
+
status: timedOut ? "timed-out" : passed ? "passed" : command.allowFailure ? "allowed-failure" : "failed",
|
|
1194
|
+
stdout: trimOutput(redactVerifyEnv(stdout, command.env)),
|
|
1195
|
+
stderr: trimOutput(redactVerifyEnv(stderr || (timedOut ? options.abortMessage ?? "" : ""), command.env)),
|
|
1196
|
+
});
|
|
1197
|
+
});
|
|
1198
|
+
child.on("error", (error) => {
|
|
1199
|
+
finish({
|
|
1200
|
+
exitCode: timedOut ? null : 1,
|
|
1201
|
+
status: timedOut ? "timed-out" : command.allowFailure ? "allowed-failure" : "failed",
|
|
1202
|
+
stderr: timedOut
|
|
1203
|
+
? trimOutput(redactVerifyEnv(stderr || options.abortMessage || "Acceptance verification timed out.", command.env))
|
|
1204
|
+
: redactVerifyEnv(error instanceof Error ? error.message : String(error), command.env),
|
|
1205
|
+
});
|
|
1206
|
+
});
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
export async function evaluateAcceptance(input: {
|
|
1211
|
+
acceptance: ResolvedAcceptanceConfig;
|
|
1212
|
+
output: string;
|
|
1213
|
+
cwd: string;
|
|
1214
|
+
/**
|
|
1215
|
+
* Content the child sent to its configured output file (from its own write
|
|
1216
|
+
* tool calls, not from disk, so a concurrent writer to the same path cannot
|
|
1217
|
+
* be misattributed). Searched for the acceptance report; searched before
|
|
1218
|
+
* the assistant output when `authoritative` (outputMode "file-only").
|
|
1219
|
+
*/
|
|
1220
|
+
fileOutput?: { content: string; path: string; authoritative?: boolean };
|
|
1221
|
+
report?: AcceptanceReport;
|
|
1222
|
+
reviewResult?: AcceptanceReviewResult;
|
|
1223
|
+
signal?: AbortSignal;
|
|
1224
|
+
abortMessage?: string;
|
|
1225
|
+
reportOptional?: boolean;
|
|
1226
|
+
artifactsDir?: string;
|
|
1227
|
+
runId?: string;
|
|
1228
|
+
}): Promise<AcceptanceLedger> {
|
|
1229
|
+
const acceptance = input.acceptance;
|
|
1230
|
+
const initialStatus = acceptance.level === "none" ? "not-required" : "claimed";
|
|
1231
|
+
const ledger: AcceptanceLedger = {
|
|
1232
|
+
status: initialStatus,
|
|
1233
|
+
evidenceStatus: initialStatus,
|
|
1234
|
+
explicit: acceptance.explicit,
|
|
1235
|
+
effectiveAcceptance: acceptance,
|
|
1236
|
+
inferredReason: acceptance.inferredReason,
|
|
1237
|
+
criteria: acceptance.criteria,
|
|
1238
|
+
runtimeChecks: [],
|
|
1239
|
+
verifyRuns: [],
|
|
1240
|
+
};
|
|
1241
|
+
if (acceptance.level === "none") return ledger;
|
|
1242
|
+
|
|
1243
|
+
const parsed = input.report
|
|
1244
|
+
? (() => {
|
|
1245
|
+
const validation = validateAcceptanceReport(input.report);
|
|
1246
|
+
return validation.report
|
|
1247
|
+
? { report: validation.report }
|
|
1248
|
+
: { error: `Failed to parse acceptance-report: Invalid acceptance-report: ${validation.errors.join("; ")}` };
|
|
1249
|
+
})()
|
|
1250
|
+
: parseAcceptanceReportSources(input.output, input.fileOutput);
|
|
1251
|
+
const needsReport = acceptanceRequiresChildReport(acceptance);
|
|
1252
|
+
if (parsed.report) {
|
|
1253
|
+
ledger.childReport = parsed.report;
|
|
1254
|
+
ledger.status = "attested";
|
|
1255
|
+
ledger.evidenceStatus = "attested";
|
|
1256
|
+
} else if (!input.reportOptional || needsReport || parsed.error !== ACCEPTANCE_REPORT_NOT_FOUND) {
|
|
1257
|
+
ledger.childReportParseError = parsed.error;
|
|
1258
|
+
ledger.runtimeChecks.push({ id: "attestation", status: "failed", message: parsed.error ?? "Structured acceptance report missing." });
|
|
1259
|
+
if (!input.reportOptional) {
|
|
1260
|
+
ledger.status = "rejected";
|
|
1261
|
+
ledger.evidenceStatus = "rejected";
|
|
1262
|
+
return ledger;
|
|
1263
|
+
}
|
|
1264
|
+
} else {
|
|
1265
|
+
ledger.childReportParseError = parsed.error;
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
if (parsed.report && LEVEL_RANK[acceptance.level] >= LEVEL_RANK.checked) {
|
|
1269
|
+
ledger.runtimeChecks = [
|
|
1270
|
+
...ledger.runtimeChecks,
|
|
1271
|
+
...checkCriteriaSatisfied(acceptance.criteria, parsed.report),
|
|
1272
|
+
...runStructuralChecks(acceptance, parsed.report, input.cwd),
|
|
1273
|
+
];
|
|
1274
|
+
if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
|
|
1275
|
+
ledger.status = "checked";
|
|
1276
|
+
ledger.evidenceStatus = "checked";
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
if (LEVEL_RANK[acceptance.level] >= LEVEL_RANK.verified && (acceptance.level === "verified" || acceptance.verify.length > 0)) {
|
|
1281
|
+
if (acceptance.level === "verified" && acceptance.verify.length === 0) {
|
|
1282
|
+
ledger.runtimeChecks.push({ id: "verification-config", status: "failed", message: "verified acceptance requires runtime verify commands." });
|
|
1283
|
+
ledger.status = "rejected";
|
|
1284
|
+
ledger.evidenceStatus = "rejected";
|
|
1285
|
+
return ledger;
|
|
1286
|
+
}
|
|
1287
|
+
ledger.verifyRuns = [];
|
|
1288
|
+
for (const command of acceptance.verify) {
|
|
1289
|
+
ledger.verifyRuns.push(await runMemoizedVerifyCommand(command, input.cwd, {
|
|
1290
|
+
signal: input.signal,
|
|
1291
|
+
abortMessage: input.abortMessage,
|
|
1292
|
+
artifactsDir: input.artifactsDir,
|
|
1293
|
+
runId: input.runId,
|
|
1294
|
+
}));
|
|
1295
|
+
if (input.signal?.aborted) break;
|
|
1296
|
+
}
|
|
1297
|
+
if (ledger.verifyRuns.some((run) => run.status === "failed" || run.status === "timed-out")) {
|
|
1298
|
+
ledger.status = "rejected";
|
|
1299
|
+
ledger.evidenceStatus = "rejected";
|
|
1300
|
+
return ledger;
|
|
1301
|
+
}
|
|
1302
|
+
if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
|
|
1303
|
+
ledger.status = "verified";
|
|
1304
|
+
ledger.evidenceStatus = "verified";
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
if (ledger.runtimeChecks.some((check) => check.status === "failed")) {
|
|
1309
|
+
ledger.status = "rejected";
|
|
1310
|
+
ledger.evidenceStatus = "rejected";
|
|
1311
|
+
return ledger;
|
|
1312
|
+
}
|
|
1313
|
+
if (ledger.status === "claimed") {
|
|
1314
|
+
ledger.status = acceptance.level === "verified" ? "verified" : acceptance.level;
|
|
1315
|
+
ledger.evidenceStatus = ledger.status;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
if (acceptance.review) {
|
|
1319
|
+
if (input.reviewResult?.status === "reviewed") {
|
|
1320
|
+
ledger.reviewResult = input.reviewResult;
|
|
1321
|
+
ledger.status = "reviewed";
|
|
1322
|
+
} else if (input.reviewResult?.status === "blockers") {
|
|
1323
|
+
ledger.reviewResult = input.reviewResult;
|
|
1324
|
+
ledger.status = "rejected";
|
|
1325
|
+
} else if (acceptance.review.required !== false) {
|
|
1326
|
+
ledger.reviewResult = input.reviewResult ?? {
|
|
1327
|
+
status: "review-required",
|
|
1328
|
+
findings: [{
|
|
1329
|
+
severity: "non-blocking",
|
|
1330
|
+
issue: "Independent review has not been supplied.",
|
|
1331
|
+
rationale: "The run cannot be marked reviewed from child evidence alone.",
|
|
1332
|
+
}],
|
|
1333
|
+
};
|
|
1334
|
+
ledger.status = "review-required";
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
return ledger;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
export function buildSkippedAcceptanceLedger(acceptance: ResolvedAcceptanceConfig, input: { id: string; message: string }): AcceptanceLedger {
|
|
1342
|
+
const status = acceptance.level === "none" ? "not-required" : "rejected";
|
|
1343
|
+
return {
|
|
1344
|
+
status,
|
|
1345
|
+
evidenceStatus: status,
|
|
1346
|
+
explicit: acceptance.explicit,
|
|
1347
|
+
effectiveAcceptance: acceptance,
|
|
1348
|
+
inferredReason: acceptance.inferredReason,
|
|
1349
|
+
criteria: acceptance.criteria,
|
|
1350
|
+
runtimeChecks: acceptance.level === "none"
|
|
1351
|
+
? []
|
|
1352
|
+
: [{ id: input.id, status: "failed", message: input.message }],
|
|
1353
|
+
verifyRuns: [],
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
export function acceptanceFailureMessage(ledger: AcceptanceLedger): string | undefined {
|
|
1358
|
+
if (ledger.status !== "rejected") return undefined;
|
|
1359
|
+
const failedCheck = ledger.runtimeChecks.find((check) => check.status === "failed");
|
|
1360
|
+
if (failedCheck) return `Acceptance rejected: ${failedCheck.message}`;
|
|
1361
|
+
const failedVerify = ledger.verifyRuns.find((run) => run.status === "failed" || run.status === "timed-out");
|
|
1362
|
+
if (failedVerify) return `Acceptance verification '${failedVerify.id}' ${failedVerify.status}.`;
|
|
1363
|
+
if (ledger.reviewResult?.status === "blockers") return "Acceptance review found blockers.";
|
|
1364
|
+
return "Acceptance rejected.";
|
|
1365
|
+
}
|