zob-harness 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/.pi/capabilities/zob-public-runtime-capabilities.json +16 -17
  2. package/.pi/extensions/zob-harness/index.ts +1 -1
  3. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime/dry-run.ts +1107 -0
  4. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime/report-writers.ts +325 -0
  5. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime/smoke-run.ts +1286 -0
  6. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime/types.ts +30 -0
  7. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime/validation.ts +184 -0
  8. package/.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime.ts +4 -2912
  9. package/.pi/extensions/zob-harness/src/domains/compute/compute-profile.ts +2 -1
  10. package/.pi/extensions/zob-harness/src/domains/coms/coms-v2/registry.ts +24 -3
  11. package/.pi/extensions/zob-harness/src/domains/coms/coms-v2/types.ts +1 -0
  12. package/.pi/extensions/zob-harness/src/domains/coms/coms-v2/zpeer.ts +5 -3
  13. package/.pi/extensions/zob-harness/src/domains/delegation/child-runner.ts +28 -3
  14. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/constants.ts +19 -0
  15. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/formatting.ts +148 -0
  16. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/normalize.ts +476 -0
  17. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/operations.ts +393 -0
  18. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/parsing.ts +277 -0
  19. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos/reducer.ts +110 -0
  20. package/.pi/extensions/zob-harness/src/domains/goal/goal-todos.ts +6 -1429
  21. package/.pi/extensions/zob-harness/src/domains/governance/governed-requests.ts +3 -1
  22. package/.pi/extensions/zob-harness/src/domains/governance/merge-queue.ts +3 -1
  23. package/.pi/extensions/zob-harness/src/domains/governance/sandbox/helpers.ts +124 -0
  24. package/.pi/extensions/zob-harness/src/domains/governance/sandbox/runners.ts +444 -0
  25. package/.pi/extensions/zob-harness/src/domains/governance/sandbox/simulation.ts +569 -0
  26. package/.pi/extensions/zob-harness/src/domains/governance/sandbox/types.ts +127 -0
  27. package/.pi/extensions/zob-harness/src/domains/governance/sandbox/validation.ts +273 -0
  28. package/.pi/extensions/zob-harness/src/domains/governance/sandbox.ts +4 -1508
  29. package/.pi/extensions/zob-harness/src/domains/governance/worker-pool.ts +3 -1
  30. package/.pi/extensions/zob-harness/src/domains/governance/workspace-claims.ts +3 -1
  31. package/.pi/extensions/zob-harness/src/domains/orchestration/room.ts +8 -2
  32. package/.pi/extensions/zob-harness/src/domains/promotion/coms.ts +8 -1
  33. package/.pi/extensions/zob-harness/src/runtime/commands/autonomy.ts +188 -0
  34. package/.pi/extensions/zob-harness/src/runtime/commands/compute.ts +165 -0
  35. package/.pi/extensions/zob-harness/src/runtime/commands/daemon.ts +191 -0
  36. package/.pi/extensions/zob-harness/src/runtime/commands/delegates.ts +47 -0
  37. package/.pi/extensions/zob-harness/src/runtime/commands/goal.ts +70 -0
  38. package/.pi/extensions/zob-harness/src/runtime/commands/intent.ts +383 -0
  39. package/.pi/extensions/zob-harness/src/runtime/commands/misc.ts +229 -0
  40. package/.pi/extensions/zob-harness/src/runtime/commands/project-dna.ts +130 -0
  41. package/.pi/extensions/zob-harness/src/runtime/commands/types.ts +3 -0
  42. package/.pi/extensions/zob-harness/src/runtime/commands/zcommit.ts +145 -0
  43. package/.pi/extensions/zob-harness/src/runtime/commands/zlive.ts +1606 -0
  44. package/.pi/extensions/zob-harness/src/runtime/commands/zmode.ts +42 -0
  45. package/.pi/extensions/zob-harness/src/runtime/commands.ts +26 -3109
  46. package/.pi/extensions/zob-harness/src/runtime/events.ts +67 -33
  47. package/.pi/extensions/zob-harness/src/runtime/goal-runtime/commands.ts +194 -0
  48. package/.pi/extensions/zob-harness/src/runtime/goal-runtime/events.ts +81 -0
  49. package/.pi/extensions/zob-harness/src/runtime/goal-runtime/state.ts +662 -0
  50. package/.pi/extensions/zob-harness/src/runtime/goal-runtime/tools.ts +1005 -0
  51. package/.pi/extensions/zob-harness/src/runtime/goal-runtime.ts +5 -1949
  52. package/.pi/extensions/zob-harness/src/runtime/tools-delegation/helpers.ts +786 -0
  53. package/.pi/extensions/zob-harness/src/runtime/tools-delegation/register.ts +1120 -0
  54. package/.pi/extensions/zob-harness/src/runtime/tools-delegation/types.ts +77 -0
  55. package/.pi/extensions/zob-harness/src/runtime/tools-delegation.ts +1 -1904
  56. package/.pi/extensions/zob-harness/src/runtime/zob-intro.ts +46 -15
  57. package/.pi/factories/project-dna/batch-manifest.json +1 -1
  58. package/.pi/factories/project-dna/pilot-manifest.json +1 -1
  59. package/.pi/factories/project-dna/smoke-manifest.json +1 -1
  60. package/README.md +29 -8
  61. package/package.json +14 -5
  62. package/scripts/git-ops/commit-policy-smoke.mjs +33 -6
  63. package/scripts/goal-todo/child-goal-ref-smoke.mjs +30 -3
  64. package/scripts/goal-todo/handoff-static-smoke.mjs +31 -3
  65. package/scripts/harness-intake/lib/cli-io.mjs +89 -0
  66. package/scripts/harness-intake/lib/constants.mjs +59 -0
  67. package/scripts/harness-intake/lib/infer-spec.mjs +127 -0
  68. package/scripts/harness-intake/lib/profiles.mjs +458 -0
  69. package/scripts/harness-intake/lib/run-init.mjs +307 -0
  70. package/scripts/harness-intake/lib/scan.mjs +266 -0
  71. package/scripts/harness-intake/lib/tmux.mjs +92 -0
  72. package/scripts/harness-intake/lib/validate.mjs +152 -0
  73. package/scripts/harness-intake/lib.mjs +8 -1521
  74. package/scripts/harness-switch/static-smoke.mjs +1 -1
  75. package/scripts/model-catalog/validate-economy.mjs +3 -1
  76. package/scripts/model-catalog/validate.mjs +3 -1
  77. package/scripts/project-dna/scan/scan.mjs +5 -2
  78. package/scripts/project-dna/scan/validate-scan-artifacts.mjs +3 -1
  79. package/scripts/project-dna/validation/validate-ontology.mjs +3 -1
  80. package/scripts/project-dna/validation/validate-scaffold.mjs +2 -2
  81. package/scripts/zagent-static-smoke.mjs +30 -2
  82. package/scripts/zpeer-local-e2e-smoke.mjs +18 -0
  83. package/scripts/zpeer-static-smoke.mjs +40 -5
  84. package/scripts/zteam-hot-add/smoke.mjs +30 -2
@@ -1,2912 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
-
4
- import { buildCapabilityIndex, buildReuseScoutReport } from "../delegation/capabilities.js";
5
- import { runFactoryRun } from "../factory/run.js";
6
- import { selectFactoryForDemands } from "../factory/factory-selector.js";
7
- import { evaluateStrictBudgetDispatchGate } from "../governance/budget-policy.js";
8
- import { evaluateBudgetPreflightDryRun } from "../telemetry/chronicle.js";
9
- import { buildBrainLookupResult, buildContextPack, buildDefaultContextScope, validateContextPack, validateContextScope } from "../context/context-gbrain.js";
10
- import { validateDaemonPolicyConfig } from "./daemon-policy.js";
11
- import { MISSION_CONTROL_COMMANDS, buildMissionControlCommandProposal, buildMissionControlSnapshot, buildZobComsTransportReadiness, buildZobCommunicationReadinessAudit } from "../coms/mission-control.js";
12
- import { evaluateModelRoutingDispatchGate, evaluateModelRoutingDryRun } from "../models/model-routing.js";
13
- import { loadTeamDefinition, validateTeamDefinition } from "../topology/teams.js";
14
- import { sha256 } from "../../core/utils/hashing.js";
15
- import { safeFileStem } from "../../core/utils/paths.js";
16
- import { isRecord } from "../../core/utils/records.js";
17
-
18
- export type AutonomousApplyPolicy = "no_apply" | "sandbox_simulation" | "manual_apply_only" | "auto_apply_in_scope";
19
- export type AutonomousBudgetProfile = "advisory" | "strict_requested";
20
- export type AutonomousRisk = "low" | "medium" | "high";
21
- export type AutonomousLevel = "L4" | "L5" | "L6";
22
-
23
- export interface AutonomousRuntimeDryRunInput {
24
- userNeed: string;
25
- refinedSpec?: string;
26
- runId?: string;
27
- constraints?: string[];
28
- acceptanceCriteria?: string[];
29
- expectedArtifacts?: string[];
30
- allowedPaths?: string[];
31
- forbiddenPaths?: string[];
32
- allowedSources?: string[];
33
- maxContextTokens?: number;
34
- applyPolicy?: AutonomousApplyPolicy;
35
- budgetProfile?: AutonomousBudgetProfile;
36
- risk?: AutonomousRisk;
37
- authorizedAutonomyLevel?: AutonomousLevel;
38
- userLaunchConfirmed?: boolean;
39
- launchConfirmedAt?: string;
40
- allowedActions?: string[];
41
- }
42
-
43
- export interface AutonomousReadOnlySmokeRunInput extends AutonomousRuntimeDryRunInput {
44
- factoryRunId?: string;
45
- }
46
-
47
- const FORBIDDEN_BODY_KEYS = new Set(["task", "prompt", "output", "body", "content", "patch", "diff", "raw", "messages", "conversationHistory"]);
48
- const AMBIGUOUS_PATTERNS = [/\bstuff\b/i, /\bsomething\b/i, /\bwhatever\b/i, /\bfix it\b/i, /\bmake it better\b/i, /\betc\.?\b/i];
49
- const SECRET_PATTERNS = [/\.env\b/i, /api[_-]?key/i, /secret/i, /password/i, /token/i, /private[_-]?key/i, /ssh[_-]?key/i];
50
- const DEFAULT_AUTONOMOUS_FORBIDDEN_PATHS = [".env", ".env.*", "secrets", "raw-conversation-history", "node_modules", "dist", "build"];
51
- const UNSAFE_AUTONOMOUS_ALLOWED_SEGMENTS = new Set(["node_modules", "dist", "build", "secrets", "raw-conversation-history"]);
52
- const AUTONOMOUS_CURRENT_SOURCE_FINGERPRINT_FILES = [
53
- "package.json",
54
- "tsconfig.json",
55
- "scripts/harness-smoke.mjs",
56
- "docs/AUTONOMY_FACTORY_AGENT_DETAILED_PLAN.md",
57
- ".pi/budget-policy.json",
58
- ".pi/model-routing.json",
59
- ".pi/daemon-policy.json",
60
- ".pi/teams/zob-core.json",
61
- ".pi/extensions/zob-harness/index.ts",
62
- ".pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime.ts",
63
- ".pi/extensions/zob-harness/src/domains/autonomy/autonomy-readiness.ts",
64
- ".pi/extensions/zob-harness/src/runtime/tools-autonomous.ts",
65
- ".pi/extensions/zob-harness/src/runtime/schemas.ts",
66
- ".pi/extensions/zob-harness/src/domains/factory/run.ts",
67
- ".pi/extensions/zob-harness/src/domains/models/model-routing.ts",
68
- ".pi/extensions/zob-harness/src/domains/governance/budget-policy.ts",
69
- ".pi/extensions/zob-harness/src/domains/autonomy/daemon-policy.ts",
70
- ".pi/extensions/zob-harness/src/domains/coms/mission-control.ts",
71
- ".pi/extensions/zob-harness/src/domains/governance/sandbox.ts",
72
- ];
73
-
74
- function hasForbiddenBodyKeys(value: unknown): boolean {
75
- if (!value || typeof value !== "object") return false;
76
- if (Array.isArray(value)) return value.some(hasForbiddenBodyKeys);
77
- return Object.entries(value as Record<string, unknown>).some(([key, child]) => FORBIDDEN_BODY_KEYS.has(key) || hasForbiddenBodyKeys(child));
78
- }
79
-
80
- function stableStrings(values: string[] | undefined): string[] {
81
- return [...new Set((values ?? []).filter((value) => typeof value === "string" && value.trim().length > 0).map((value) => value.trim()))].sort();
82
- }
83
-
84
- function normalizeAutonomousSpecPath(value: string): string {
85
- return value.trim().replace(/\\+/g, "/").replace(/\/+/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
86
- }
87
-
88
- function isBroadAutonomousAllowedPath(value: string): boolean {
89
- const normalized = normalizeAutonomousSpecPath(value);
90
- return normalized === "" || normalized === "." || normalized === "/" || normalized === "*" || normalized === "**" || normalized === "~" || normalized === "~/";
91
- }
92
-
93
- function forbiddenPatternBase(value: string): string {
94
- return normalizeAutonomousSpecPath(value)
95
- .replace(/\/\*\*$/, "")
96
- .replace(/\/\*$/, "")
97
- .replace(/\.\*$/, "");
98
- }
99
-
100
- function pathConflict(left: string, right: string): boolean {
101
- const a = forbiddenPatternBase(left).toLowerCase();
102
- const b = forbiddenPatternBase(right).toLowerCase();
103
- if (!a || !b) return false;
104
- return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
105
- }
106
-
107
- function unsafeAllowedPathReason(value: string, forbiddenPaths: string[]): string | undefined {
108
- const normalized = normalizeAutonomousSpecPath(value);
109
- const lower = normalized.toLowerCase();
110
- if (value.includes("\0")) return "allowed_path_contains_nul_byte";
111
- if (isBroadAutonomousAllowedPath(value)) return "allowed_path_too_broad";
112
- if (lower.startsWith("/") || lower.startsWith("~/") || /^[a-z]:\//i.test(lower)) return "allowed_path_must_be_repo_relative";
113
- if (lower.split("/").includes("..")) return "allowed_path_must_not_traverse_parent";
114
- const segments = lower.split("/").filter(Boolean);
115
- if (segments.some((segment) => segment === ".env" || segment.startsWith(".env."))) return "allowed_path_references_secret_path";
116
- if (segments.some((segment) => UNSAFE_AUTONOMOUS_ALLOWED_SEGMENTS.has(segment))) return "allowed_path_references_forbidden_segment";
117
- if (forbiddenPaths.some((forbidden) => pathConflict(normalized, forbidden))) return "allowed_path_conflicts_with_forbidden_path";
118
- return undefined;
119
- }
120
-
121
- function validateAutonomousSpecPathGate(allowedPaths: string[], forbiddenPaths: string[]): string[] {
122
- if (allowedPaths.length === 0) return ["allowed_paths_required_before_execution"];
123
- return allowedPaths.flatMap((allowedPath) => {
124
- const reason = unsafeAllowedPathReason(allowedPath, forbiddenPaths);
125
- return reason ? [reason] : [];
126
- });
127
- }
128
-
129
- function hashes(values: string[]): string[] {
130
- return values.map((value) => sha256(value)).sort();
131
- }
132
-
133
- function defaultAutonomousAllowedActions(applyPolicy: AutonomousApplyPolicy): string[] {
134
- const base = ["read_repo", "context_lookup", "select_factory", "run_factory_smoke", "run_factory_pilot", "run_factory_batch", "post_run_validation", "post_run_oracle"];
135
- return applyPolicy === "auto_apply_in_scope"
136
- ? [...base, "sandbox_edit", "apply_in_scope", "post_apply_validation", "post_apply_oracle"]
137
- : base;
138
- }
139
-
140
- function inferAutonomousLevel(applyPolicy: AutonomousApplyPolicy): AutonomousLevel {
141
- return applyPolicy === "auto_apply_in_scope" ? "L6" : "L4";
142
- }
143
-
144
- function capabilityFactories(capabilityIndex: Record<string, unknown>): Record<string, unknown>[] {
145
- const capabilities = Array.isArray(capabilityIndex.capabilities) ? capabilityIndex.capabilities.filter(isRecord) : [];
146
- return capabilities.filter((capability) => capability.kind === "factory");
147
- }
148
-
149
- function textSignals(...values: string[]): string[] {
150
- const text = values.join("\n").toLowerCase();
151
- const signals: string[] = [];
152
- const add = (condition: boolean, signal: string): void => {
153
- if (condition) signals.push(signal);
154
- };
155
- add(/\b(code review|review code|review changes|oracle matrix|security review|qa review|correctness|architecture)\b/.test(text), "code_review");
156
- add(/\b(budget|cost|costs|cap|caps|preflight|strict budget|max runs|max cost|parallel children)\b/.test(text), "budget_preflight");
157
- add(/\b(roadmap|lot|lots|milestone|unchecked item|execution queue)\b/.test(text), "roadmap_lots");
158
- add(/\b(opencode|pattern|patterns|canonizer|canonical|taxonomy|workflow rules|quality gates)\b/.test(text), "opencode_patterns");
159
- add(/\b(projectdna|project dna|project-dna|knowledge graph|code knowledge|context pack|repo scan|reference project)\b/.test(text), "project_dna");
160
- add(/\b(new factory|create factory|generate factory|factory scaffold|quarantine|factory-forge|forge)\b/.test(text), "factory_forge");
161
- return [...new Set(signals)].sort();
162
- }
163
-
164
- function scoreFactoryCandidate(factory: Record<string, unknown>, signals: string[]): Record<string, unknown> {
165
- const id = typeof factory.id === "string" ? factory.id : "unknown";
166
- const reasonCodes: string[] = [];
167
- let score = 0;
168
- const add = (condition: boolean, points: number, reason: string): void => {
169
- if (condition) {
170
- score += points;
171
- reasonCodes.push(reason);
172
- }
173
- };
174
- add(id === "code-review-matrix" && signals.includes("code_review"), 8, "signal:code_review");
175
- add(id === "budget-preflight-dry-run" && signals.includes("budget_preflight"), 8, "signal:budget_preflight");
176
- add(id === "roadmap-smoke-lots" && signals.includes("roadmap_lots"), 8, "signal:roadmap_lots");
177
- add(id === "opencode-pattern-canonizer" && signals.includes("opencode_patterns"), 8, "signal:opencode_patterns");
178
- add(id === "project-dna" && signals.includes("project_dna"), 8, "signal:project_dna");
179
- add(id === "factory-forge" && signals.includes("factory_forge"), 8, "signal:factory_forge");
180
- const metadata = isRecord(factory.metadata) ? factory.metadata : {};
181
- const manifests = Array.isArray(metadata.manifests) ? metadata.manifests.filter((item): item is string => typeof item === "string") : [];
182
- add(manifests.includes("smoke-manifest.json"), 1, "manifest:smoke");
183
- add(manifests.includes("pilot-manifest.json"), 1, "manifest:pilot");
184
- add(manifests.includes("batch-manifest.json"), 1, "manifest:batch");
185
- const confidence = Math.max(0, Math.min(0.99, score / 12));
186
- return {
187
- kind: "factory",
188
- id,
189
- sourcePath: factory.sourcePath,
190
- score,
191
- confidence,
192
- reasonCodes: reasonCodes.sort(),
193
- summaryHash: typeof factory.summary === "string" ? sha256(factory.summary) : undefined,
194
- };
195
- }
196
-
197
- function selectAutonomousFactory(input: { factories: Record<string, unknown>[]; refinedSpec: string; acceptanceCriteria: string[]; expectedArtifacts: string[] }): Record<string, unknown> {
198
- return selectFactoryForDemands({
199
- schema: "zob.autonomous-factory-selection-score.v1",
200
- factories: input.factories,
201
- refinedSpec: input.refinedSpec,
202
- acceptanceCriteria: input.acceptanceCriteria,
203
- expectedArtifacts: input.expectedArtifacts,
204
- }) as unknown as Record<string, unknown>;
205
- }
206
-
207
- function factoryManifestAvailability(repoRoot: string, factoryName: string | undefined): Record<string, unknown> {
208
- if (!factoryName) return { smoke: false, pilot: false, batch: false };
209
- return {
210
- smoke: existsSync(join(repoRoot, ".pi", "factories", factoryName, "smoke-manifest.json")),
211
- pilot: existsSync(join(repoRoot, ".pi", "factories", factoryName, "pilot-manifest.json")),
212
- batch: existsSync(join(repoRoot, ".pi", "factories", factoryName, "batch-manifest.json")),
213
- };
214
- }
215
-
216
- function readFactoryRegistryReadiness(repoRoot: string, factoryName: string | undefined): Record<string, unknown> {
217
- const reportPath = "reports/factory-registry-readiness-audit-smoke.json";
218
- const absolutePath = join(repoRoot, reportPath);
219
- const base = {
220
- schema: "zob.autonomous-factory-readiness-snapshot.v1",
221
- reportPath,
222
- reportPresent: false,
223
- reportHash: undefined,
224
- selectedFactory: factoryName,
225
- registeredBatchReady: false,
226
- arbitraryFactoryNoShip: true,
227
- currentSourceProofRequired: true,
228
- proofBeforeExecutionRequired: true,
229
- readinessFreshness: "missing_registry_snapshot",
230
- bodyStored: false,
231
- promptBodiesStored: false,
232
- outputBodiesStored: false,
233
- };
234
- if (!existsSync(absolutePath)) return base;
235
- try {
236
- const rawJson = readFileSync(absolutePath, "utf8");
237
- const parsed = JSON.parse(rawJson) as unknown;
238
- const registry = isRecord(parsed) ? parsed : {};
239
- const readyFactories = Array.isArray(registry.registeredAgenticBatchReadyFactories) ? registry.registeredAgenticBatchReadyFactories.filter((item): item is string => typeof item === "string") : [];
240
- const missingFactories = Array.isArray(registry.factoriesMissingRegisteredBatchProof) ? registry.factoriesMissingRegisteredBatchProof.filter((item): item is string => typeof item === "string") : [];
241
- const registeredBatchReady = typeof factoryName === "string" && readyFactories.includes(factoryName);
242
- return {
243
- ...base,
244
- reportPresent: true,
245
- reportHash: sha256(rawJson),
246
- registeredBatchReady,
247
- arbitraryFactoryNoShip: registry.arbitraryFactoryNoShip !== false,
248
- currentSourceProofRequired: true,
249
- proofBeforeExecutionRequired: !registeredBatchReady,
250
- readinessFreshness: "snapshot_requires_current_source_refresh_before_execution",
251
- registeredAgenticBatchReadyFactoryCount: readyFactories.length,
252
- factoriesMissingRegisteredBatchProofCount: missingFactories.length,
253
- selectedFactoryMissingRegisteredBatchProof: typeof factoryName === "string" ? missingFactories.includes(factoryName) : undefined,
254
- };
255
- } catch {
256
- return { ...base, reportPresent: true, readinessFreshness: "invalid_registry_snapshot", reportHash: undefined };
257
- }
258
- }
259
-
260
- function buildAutonomousContextArtifacts(repoRoot: string, scope: Record<string, unknown>, queryHash: string): Record<string, unknown> {
261
- const scopeErrors = validateContextScope(repoRoot, scope);
262
- if (scopeErrors.length > 0) return { lookupResults: [], contextPack: undefined, contextPackValid: false, contextPackErrors: scopeErrors };
263
- const allowedSources = Array.isArray(scope.allowedSources) ? scope.allowedSources.filter((source): source is string => typeof source === "string") : [];
264
- try {
265
- const lookupResults: Record<string, unknown>[] = [];
266
- if (allowedSources.includes("zob-harness-docs")) {
267
- const citation = "harness-system:zob-harness-docs:docs/AUTONOMOUS_SUPER_FACTORY_GOAL.md#phase-3";
268
- lookupResults.push(buildBrainLookupResult(repoRoot, {
269
- scope,
270
- brainId: "harness-system",
271
- sourceId: "zob-harness-docs",
272
- queryHash,
273
- facts: [{ factHash: sha256("autonomous loop requires spec context factory oracle final report"), citations: [citation], confidence: "HIGH" }],
274
- gaps: [{ gapHash: sha256("P0 dry-run does not execute live factories"), citations: [citation], noShipIfTreatedAsPass: true }],
275
- confidence: "HIGH",
276
- }));
277
- }
278
- if (allowedSources.includes("factory-run-reports")) {
279
- const citation = "factory-evidence:factory-run-reports:reports/factory-registry-readiness-audit-smoke.json";
280
- lookupResults.push(buildBrainLookupResult(repoRoot, {
281
- scope,
282
- brainId: "factory-evidence",
283
- sourceId: "factory-run-reports",
284
- queryHash,
285
- facts: [{ factHash: sha256("registered factory current-source proof is required before execution"), citations: [citation], confidence: "HIGH", sourcePresent: existsSync(join(repoRoot, "reports", "factory-registry-readiness-audit-smoke.json")) }],
286
- gaps: [{ gapHash: sha256("selected factory may still require current-source proof refresh"), citations: [citation], noShipIfTreatedAsPass: true }],
287
- confidence: "HIGH",
288
- }));
289
- }
290
- if (lookupResults.length === 0 && allowedSources.includes("zob-harness-src")) {
291
- const citation = "harness-system:zob-harness-src:.pi/extensions/zob-harness/src/domains/autonomy/autonomous-runtime.ts";
292
- lookupResults.push(buildBrainLookupResult(repoRoot, {
293
- scope,
294
- brainId: "harness-system",
295
- sourceId: "zob-harness-src",
296
- queryHash,
297
- facts: [{ factHash: sha256("autonomous dry-run implementation is repo-local metadata-only"), citations: [citation], confidence: "MEDIUM" }],
298
- confidence: "MEDIUM",
299
- }));
300
- }
301
- if (lookupResults.length === 0) return { lookupResults: [], contextPack: undefined, contextPackValid: false, contextPackErrors: ["no_allowed_context_source_for_autonomous_lookup"] };
302
- const contextPack = buildContextPack(repoRoot, scope, lookupResults);
303
- const contextPackErrors = validateContextPack(repoRoot, contextPack);
304
- return { lookupResults, contextPack, contextPackValid: contextPackErrors.length === 0, contextPackErrors };
305
- } catch (error) {
306
- const message = error instanceof Error ? error.message : String(error);
307
- return { lookupResults: [], contextPack: undefined, contextPackValid: false, contextPackErrors: [message] };
308
- }
309
- }
310
-
311
- function buildAutonomousRuntimeGates(input: { runId: string; risk: AutonomousRisk; budgetProfile: AutonomousBudgetProfile; applyPolicy: AutonomousApplyPolicy; maxContextTokens?: number }): Record<string, unknown> {
312
- const budgetGate = evaluateBudgetPreflightDryRun({
313
- runs: 0,
314
- durationMs: 0,
315
- parallelChildren: 0,
316
- caps: { maxRuns: 0, maxParallelChildren: 0 },
317
- strictRequested: input.budgetProfile === "strict_requested",
318
- });
319
- const modelRoutingGate = evaluateModelRoutingDryRun({
320
- mode: "factory",
321
- taskType: "autonomous-runtime-dry-run",
322
- risk: input.risk,
323
- contextTokens: input.maxContextTokens,
324
- estimatedRuns: 0,
325
- estimatedParallelChildren: 0,
326
- caps: { maxRuns: 0, maxParallelChildren: 0 },
327
- strictRequested: input.budgetProfile === "strict_requested",
328
- });
329
- const sandboxGate = {
330
- schema: "zob.autonomous-sandbox-gate.v1",
331
- applyPolicy: input.applyPolicy,
332
- sandboxSimulationPlanned: input.applyPolicy === "sandbox_simulation",
333
- manualApplyOnly: input.applyPolicy === "manual_apply_only",
334
- launchAuthorizedApplyPlanned: input.applyPolicy === "auto_apply_in_scope",
335
- launchAuthorizationRequiredForApply: input.applyPolicy === "auto_apply_in_scope",
336
- productionWritesPerformed: false,
337
- autoApply: false,
338
- rollbackRequiredBeforeRealApply: true,
339
- oracleDiffReviewRequiredBeforeRealApply: true,
340
- childDispatchAllowed: false,
341
- noExecution: true,
342
- bodyStored: false,
343
- promptBodiesStored: false,
344
- outputBodiesStored: false,
345
- };
346
- const daemonGate = {
347
- schema: "zob.autonomous-daemon-gate.v1",
348
- autoStartDaemon: false,
349
- continuousLoop: false,
350
- daemonStarted: false,
351
- manualOneShotOnly: true,
352
- killSwitchRequiredBeforeLiveAutonomy: true,
353
- childDispatchAllowed: false,
354
- noExecution: true,
355
- bodyStored: false,
356
- promptBodiesStored: false,
357
- outputBodiesStored: false,
358
- };
359
- const missionControlGate = {
360
- schema: "zob.autonomous-mission-control-gate.v1",
361
- proposalOnly: true,
362
- directWorkerWrites: false,
363
- transportDispatch: false,
364
- networkComsEnabled: false,
365
- topologyGuardRequired: true,
366
- hashOnlyLedgerRequired: true,
367
- childDispatchAllowed: false,
368
- noExecution: true,
369
- bodyStored: false,
370
- promptBodiesStored: false,
371
- outputBodiesStored: false,
372
- };
373
- const autonomousStrictBudgetGate = {
374
- schema: "zob.autonomous-strict-budget-gate.v1",
375
- strictBudgetRequiredForAutonomy: true,
376
- budgetProfile: input.budgetProfile,
377
- strictRequested: input.budgetProfile === "strict_requested",
378
- strictEnabled: false,
379
- globalDefaultEnabled: false,
380
- budgetEnforced: false,
381
- childDispatchAllowed: false,
382
- dispatchBlockedUntilLiveStrictGate: true,
383
- noExecution: true,
384
- bodyStored: false,
385
- promptBodiesStored: false,
386
- outputBodiesStored: false,
387
- };
388
- const checks = [
389
- { name: "autonomous_strict_budget_requested_no_dispatch", passed: autonomousStrictBudgetGate.strictRequested === true && autonomousStrictBudgetGate.noExecution === true && autonomousStrictBudgetGate.budgetEnforced === false && autonomousStrictBudgetGate.childDispatchAllowed === false },
390
- { name: "budget_preflight_advisory_no_dispatch", passed: budgetGate.noExecution === true && budgetGate.childDispatchAllowed === false && budgetGate.budgetEnforced === false && budgetGate.wouldBlockDispatch === false },
391
- { name: "model_routing_dry_run_no_dispatch", passed: modelRoutingGate.noExecution === true && modelRoutingGate.modelRouterUsed === false && modelRoutingGate.routingApplied === false && modelRoutingGate.childDispatchAllowed === false },
392
- { name: "sandbox_no_production_apply", passed: sandboxGate.productionWritesPerformed === false && sandboxGate.autoApply === false && sandboxGate.noExecution === true },
393
- { name: "daemon_not_started", passed: daemonGate.daemonStarted === false && daemonGate.autoStartDaemon === false && daemonGate.continuousLoop === false },
394
- { name: "mission_control_proposals_only", passed: missionControlGate.proposalOnly === true && missionControlGate.directWorkerWrites === false && missionControlGate.transportDispatch === false && missionControlGate.networkComsEnabled === false },
395
- ];
396
- const failedChecks = checks.filter((check) => !check.passed).map((check) => check.name);
397
- const gates = {
398
- schema: "zob.autonomous-runtime-gates.v1",
399
- runId: input.runId,
400
- passed: failedChecks.length === 0,
401
- failedChecks,
402
- checks,
403
- budgetGate,
404
- autonomousStrictBudgetGate,
405
- modelRoutingGate,
406
- sandboxGate,
407
- daemonGate,
408
- missionControlGate,
409
- dryRun: true,
410
- noExecution: true,
411
- childDispatchAllowed: false,
412
- globalBudgetEnforced: false,
413
- globalModelRoutingEnabled: false,
414
- daemonStarted: false,
415
- productionWritesPerformed: false,
416
- autoApply: false,
417
- networkAccessed: false,
418
- bodyStored: false,
419
- promptBodiesStored: false,
420
- outputBodiesStored: false,
421
- };
422
- if (hasForbiddenBodyKeys(gates)) throw new Error("autonomous runtime gates would store forbidden plaintext body keys");
423
- return gates;
424
- }
425
-
426
- function buildAutonomousStrictBudgetProofPlan(input: { runId: string; runtimeGates: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
427
- const scenarioSpecs = [
428
- { name: "strict_gate_allows_within_caps", gateInput: { runId: `${input.runId}-strict-budget-allow`, mode: "smoke", execution: "agentic", taskCount: 1, budget: { strictEnabled: true, maxRuns: 2, estimatedRuns: 1, maxParallelChildren: 1, estimatedParallelChildren: 1 } } },
429
- { name: "strict_gate_blocks_exceedance_pre_dispatch", gateInput: { runId: `${input.runId}-strict-budget-block`, mode: "smoke", execution: "agentic", taskCount: 3, budget: { strictEnabled: true, maxRuns: 2, estimatedRuns: 3, maxParallelChildren: 1, estimatedParallelChildren: 1 } } },
430
- { name: "strict_gate_default_disabled_advisory", gateInput: { runId: `${input.runId}-strict-budget-default`, mode: "smoke", execution: "agentic", taskCount: 3, budget: { strictRequested: true, maxRuns: 2, estimatedRuns: 3, maxParallelChildren: 1, estimatedParallelChildren: 1 } } },
431
- ].map((scenario) => {
432
- const gate = evaluateStrictBudgetDispatchGate(scenario.gateInput);
433
- return {
434
- name: scenario.name,
435
- inputHash: sha256(JSON.stringify(scenario.gateInput)),
436
- strictRequested: gate.strictRequested === true,
437
- strictEnabled: gate.strictEnabled === true,
438
- budgetEnforced: gate.budgetEnforced === true,
439
- wouldExceed: gate.wouldExceed === true,
440
- wouldBlockDispatch: gate.wouldBlockDispatch === true,
441
- gateChildDispatchAllowed: gate.childDispatchAllowed === true,
442
- dispatchDecision: gate.dispatchDecision,
443
- stopCondition: gate.stopCondition,
444
- noExecution: gate.noExecution === true,
445
- failures: Array.isArray(gate.failures) ? gate.failures.filter((failure): failure is string => typeof failure === "string") : [],
446
- bodyStored: false,
447
- promptBodiesStored: false,
448
- outputBodiesStored: false,
449
- };
450
- });
451
- const allow = scenarioSpecs.find((scenario) => scenario.name === "strict_gate_allows_within_caps");
452
- const block = scenarioSpecs.find((scenario) => scenario.name === "strict_gate_blocks_exceedance_pre_dispatch");
453
- const defaultDisabled = scenarioSpecs.find((scenario) => scenario.name === "strict_gate_default_disabled_advisory");
454
- const autonomousStrictBudgetGate = isRecord(input.runtimeGates.autonomousStrictBudgetGate) ? input.runtimeGates.autonomousStrictBudgetGate : {};
455
- const checks = [
456
- { name: "strict_gate_allows_within_caps", passed: allow?.strictEnabled === true && allow.budgetEnforced === true && allow.wouldBlockDispatch === false && allow.gateChildDispatchAllowed === true && allow.dispatchDecision === "allow_strict" },
457
- { name: "strict_gate_blocks_exceedance_pre_dispatch", passed: block?.strictEnabled === true && block.budgetEnforced === true && block.wouldBlockDispatch === true && block.gateChildDispatchAllowed === false && block.dispatchDecision === "block" && block.stopCondition === "blocked" },
458
- { name: "strict_gate_default_disabled_advisory", passed: defaultDisabled?.strictRequested === true && defaultDisabled.strictEnabled === false && defaultDisabled.budgetEnforced === false && defaultDisabled.wouldBlockDispatch === false && defaultDisabled.dispatchDecision === "allow_advisory" },
459
- { name: "autonomous_runtime_global_budget_still_disabled", passed: autonomousStrictBudgetGate.strictRequested === true && autonomousStrictBudgetGate.strictEnabled === false && autonomousStrictBudgetGate.budgetEnforced === false && autonomousStrictBudgetGate.childDispatchAllowed === false },
460
- { name: "run_scope_no_global_autonomy", passed: input.validation.globalAutonomyReady === false && input.validation.globalAutonomyNoShip === true && input.validation.childDispatchAllowed === false && input.validation.productionWritesPerformed === false && input.validation.autoApply === false },
461
- ];
462
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
463
- const proof = {
464
- schema: "zob.autonomous-strict-budget-proof-plan.v1",
465
- runId: input.runId,
466
- phase: "5B",
467
- status: failedChecks.length === 0 ? "strict_budget_dispatch_gate_proof_ready_global_default_blocked" : "strict_budget_dispatch_gate_proof_incomplete",
468
- strictBudgetProofReady: failedChecks.length === 0,
469
- strictBudgetDispatchGateAvailable: true,
470
- strictBudgetAllowProofPassed: allow?.dispatchDecision === "allow_strict" && allow.budgetEnforced === true,
471
- strictBudgetBlockProofPassed: block?.dispatchDecision === "block" && block.wouldBlockDispatch === true,
472
- strictBudgetDefaultDisabledProofPassed: defaultDisabled?.dispatchDecision === "allow_advisory" && defaultDisabled.strictEnabled === false,
473
- finalE2ERequirementCleared: false,
474
- no_ship: true,
475
- checks,
476
- failedChecks,
477
- scenarios: scenarioSpecs,
478
- evidenceRefs: [
479
- `reports/autonomous-runs/${safeFileStem(input.runId)}/runtime-gates.json`,
480
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
481
- ],
482
- blockers: [
483
- "live_autonomous_strict_budget_not_enforced",
484
- "global_default_strict_budget_disabled",
485
- "final_e2e_strict_budget_evidence_required",
486
- ],
487
- autonomousRuntimeStrictBudgetEnforced: false,
488
- globalStrictBudgetEnabled: false,
489
- globalBudgetEnforced: false,
490
- liveAutonomousBudgetEnforced: false,
491
- budgetEnforced: false,
492
- strictEnabled: false,
493
- childDispatchAllowed: false,
494
- daemonStarted: false,
495
- productionWritesPerformed: false,
496
- autoApply: false,
497
- noExecution: true,
498
- globalAutonomyReady: false,
499
- globalAutonomyNoShip: true,
500
- bodyStored: false,
501
- promptBodiesStored: false,
502
- outputBodiesStored: false,
503
- };
504
- if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous strict budget proof plan would store forbidden plaintext body keys");
505
- return proof;
506
- }
507
-
508
- function buildAutonomousModelRoutingPlan(input: { runId: string; risk: AutonomousRisk; budgetProfile: AutonomousBudgetProfile; maxContextTokens?: number; specText: string; selectedFactory?: string }): Record<string, unknown> {
509
- const strictRequested = input.budgetProfile === "strict_requested";
510
- const contextTokens = typeof input.maxContextTokens === "number" && Number.isFinite(input.maxContextTokens) ? Math.max(0, Math.floor(input.maxContextTokens)) : 0;
511
- const highContextRequired = contextTokens >= 120_000;
512
- const securitySensitive = input.risk === "high" || /\b(security|secure|vulnerability|vulnerabilities|auth|permission|permissions|sandbox|apply|write|privilege|injection)\b/i.test(input.specText);
513
- const routeSpecs: Array<{ stage: string; mode: "explore" | "plan" | "implement" | "oracle" | "factory"; taskType: string; outputContract?: string; risk: AutonomousRisk; contextTokens?: number; expectedModelClass: string; securityCritical?: boolean; oracleCritical?: boolean }> = [
514
- { stage: "context_reuse_scout", mode: "explore", taskType: "read-only-inspection", risk: "low", expectedModelClass: "cheap_scout" },
515
- { stage: "context_pack", mode: "explore", taskType: "context-pack-read-only", risk: "low", contextTokens: contextTokens || undefined, expectedModelClass: highContextRequired ? "high_context" : "cheap_scout" },
516
- { stage: "factory_selection", mode: "factory", taskType: securitySensitive ? "security-critical-plan" : "factory-selection", risk: securitySensitive ? "high" : input.risk, expectedModelClass: securitySensitive ? "strong_reasoning" : "balanced_worker", securityCritical: securitySensitive },
517
- { stage: "factory_smoke_plan", mode: "factory", taskType: `factory-smoke:${input.selectedFactory ?? "unselected"}`, risk: input.risk, expectedModelClass: input.risk === "high" ? "strong_reasoning" : "balanced_worker" },
518
- { stage: "smoke_oracle", mode: "oracle", taskType: "oracle-review", outputContract: "oracle.v1", risk: "high", expectedModelClass: "strong_oracle", oracleCritical: true },
519
- { stage: "pilot_oracle", mode: "oracle", taskType: "oracle-review", outputContract: "oracle.v1", risk: "high", expectedModelClass: "strong_oracle", oracleCritical: true },
520
- { stage: "final_report_synthesis", mode: "implement", taskType: "synthesis-final-report", risk: input.risk, expectedModelClass: input.risk === "high" ? "strong_reasoning" : "balanced_worker" },
521
- ];
522
- if (securitySensitive) {
523
- routeSpecs.push({ stage: "security_reasoning_gate", mode: "plan", taskType: "security-critical-plan", risk: "high", expectedModelClass: "strong_reasoning", securityCritical: true });
524
- }
525
- const routes = routeSpecs.map((spec) => {
526
- const route = evaluateModelRoutingDryRun({
527
- mode: spec.mode,
528
- taskType: spec.taskType,
529
- outputContract: spec.outputContract,
530
- risk: spec.risk,
531
- contextTokens: spec.contextTokens,
532
- estimatedRuns: 0,
533
- estimatedParallelChildren: 0,
534
- caps: { maxRuns: 0, maxParallelChildren: 0 },
535
- strictRequested,
536
- });
537
- return {
538
- stage: spec.stage,
539
- mode: spec.mode,
540
- taskType: spec.taskType,
541
- outputContract: spec.outputContract,
542
- risk: spec.risk,
543
- contextTokens: spec.contextTokens,
544
- expectedModelClass: spec.expectedModelClass,
545
- recommendedModelClass: route.recommendedModelClass,
546
- matchedExpectedClass: route.recommendedModelClass === spec.expectedModelClass,
547
- reasonCodes: Array.isArray(route.reasonCodes) ? route.reasonCodes : [],
548
- budgetWouldExceed: route.budgetWouldExceed === true,
549
- budgetEnforced: route.budgetEnforced === true,
550
- strictRequested: route.strictRequested === true,
551
- strictEnabled: route.strictEnabled === true,
552
- modelRouterUsed: route.modelRouterUsed === true,
553
- routingApplied: route.routingApplied === true,
554
- childDispatchAllowed: route.childDispatchAllowed === true,
555
- noExecution: route.noExecution === true,
556
- securityCritical: spec.securityCritical === true,
557
- oracleCritical: spec.oracleCritical === true,
558
- bodyStored: false,
559
- promptBodiesStored: false,
560
- outputBodiesStored: false,
561
- };
562
- });
563
- const oracleRoutes = routes.filter((route) => route.oracleCritical === true);
564
- const securityRoutes = routes.filter((route) => route.securityCritical === true);
565
- const checks = [
566
- { name: "model_routing_plan_present", passed: routes.length >= 7 },
567
- { name: "low_risk_readonly_uses_cheap_scout", passed: routes.some((route) => route.stage === "context_reuse_scout" && route.recommendedModelClass === "cheap_scout") },
568
- { name: "oracle_uses_strong_oracle", passed: oracleRoutes.length > 0 && oracleRoutes.every((route) => route.recommendedModelClass === "strong_oracle") },
569
- { name: "high_context_uses_high_context", passed: !highContextRequired || routes.some((route) => route.stage === "context_pack" && route.recommendedModelClass === "high_context") },
570
- { name: "security_not_downgraded", passed: !securitySensitive || (securityRoutes.length > 0 && securityRoutes.every((route) => route.recommendedModelClass === "strong_reasoning" || route.recommendedModelClass === "strong_oracle" || route.recommendedModelClass === "high_context")) },
571
- { name: "budget_aware_strict_requested", passed: strictRequested && routes.every((route) => route.strictRequested === true && route.budgetEnforced === false && route.strictEnabled === false) },
572
- { name: "routing_dry_run_no_dispatch", passed: routes.every((route) => route.noExecution === true && route.modelRouterUsed === false && route.routingApplied === false && route.childDispatchAllowed === false) },
573
- { name: "global_live_routing_disabled", passed: true },
574
- ];
575
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
576
- const plan = {
577
- schema: "zob.autonomous-model-routing-plan.v1",
578
- runId: input.runId,
579
- selectedFactory: input.selectedFactory,
580
- routingRequiredForAutonomy: true,
581
- routingPlanReady: failedChecks.length === 0,
582
- failedChecks,
583
- checks,
584
- routes,
585
- highContextRequired,
586
- securitySensitive,
587
- budgetAware: strictRequested,
588
- strictRequested,
589
- strictEnabled: false,
590
- budgetEnforced: false,
591
- liveRoutingEnabled: false,
592
- globalLiveRoutingEnabled: false,
593
- modelRouterUsed: false,
594
- routingApplied: false,
595
- childDispatchAllowed: false,
596
- noExecution: true,
597
- bodyStored: false,
598
- promptBodiesStored: false,
599
- outputBodiesStored: false,
600
- };
601
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous model routing plan would store forbidden plaintext body keys");
602
- return plan;
603
- }
604
-
605
- function buildAutonomousModelRoutingProofPlan(input: { runId: string; modelRoutingPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
606
- const proofModelByClass = { cheap_scout: "scout-model", balanced_worker: "worker-model", strong_reasoning: "reasoning-model", strong_oracle: "oracle-model", high_context: "long-context-model" };
607
- const scenarioSpecs = [
608
- { name: "routing_default_disabled", gateInput: { runId: `${input.runId}-routing-default`, mode: "factory" as const, stage: "map", agent: "explore", outputContract: "explore.v1", modelRouting: { enabled: false, modelByClass: proofModelByClass } } },
609
- { name: "routing_oracle_applies_when_enabled", gateInput: { runId: `${input.runId}-routing-oracle`, mode: "factory" as const, stage: "validate", agent: "oracle-merge", outputContract: "oracle-merge.v1", modelRouting: { enabled: true, modelByClass: proofModelByClass } } },
610
- { name: "routing_high_context_applies_when_enabled", gateInput: { runId: `${input.runId}-routing-high-context`, mode: "factory" as const, stage: "reduce", agent: "synthesis", outputContract: "synthesis.v1", modelRouting: { enabled: true, contextTokens: 150_000, modelByClass: proofModelByClass } } },
611
- { name: "routing_security_not_downgraded_when_enabled", gateInput: { runId: `${input.runId}-routing-security`, mode: "plan" as const, stage: "security_reasoning_gate", agent: "planner", outputContract: "plan.v1", risk: "high" as const, taskType: "security-critical-plan", modelRouting: { enabled: true, modelByClass: proofModelByClass } } },
612
- ].map((scenario) => {
613
- const gate = evaluateModelRoutingDispatchGate(scenario.gateInput);
614
- return {
615
- name: scenario.name,
616
- inputHash: sha256(JSON.stringify(scenario.gateInput)),
617
- liveRoutingRequested: gate.liveRoutingRequested === true,
618
- liveRoutingEnabled: gate.liveRoutingEnabled === true,
619
- modelRouterUsed: gate.modelRouterUsed === true,
620
- routingApplied: gate.routingApplied === true,
621
- selectedModelClass: gate.selectedModelClass,
622
- recommendedModelClass: gate.recommendedModelClass,
623
- selectedModelHash: typeof gate.selectedModelHash === "string" ? gate.selectedModelHash : undefined,
624
- selectedModelStored: gate.selectedModelStored === true,
625
- modelByClassProvided: gate.modelByClassProvided === true,
626
- gateChildDispatchAllowed: gate.childDispatchAllowed === true,
627
- defaultDispatchDecision: gate.defaultDispatchDecision,
628
- noExecution: gate.noExecution === true,
629
- budgetEnforced: gate.budgetEnforced === true,
630
- strictEnabled: gate.strictEnabled === true,
631
- reasonCodes: Array.isArray(gate.reasonCodes) ? gate.reasonCodes.filter((reason): reason is string => typeof reason === "string") : [],
632
- bodyStored: false,
633
- promptBodiesStored: false,
634
- outputBodiesStored: false,
635
- };
636
- });
637
- const defaultDisabled = scenarioSpecs.find((scenario) => scenario.name === "routing_default_disabled");
638
- const oracle = scenarioSpecs.find((scenario) => scenario.name === "routing_oracle_applies_when_enabled");
639
- const highContext = scenarioSpecs.find((scenario) => scenario.name === "routing_high_context_applies_when_enabled");
640
- const security = scenarioSpecs.find((scenario) => scenario.name === "routing_security_not_downgraded_when_enabled");
641
- const checks = [
642
- { name: "routing_default_disabled", passed: defaultDisabled?.liveRoutingEnabled === false && defaultDisabled.modelRouterUsed === false && defaultDisabled.routingApplied === false && defaultDisabled.gateChildDispatchAllowed === false && defaultDisabled.defaultDispatchDecision === "allow_default_model" },
643
- { name: "routing_oracle_uses_strong_oracle_when_enabled", passed: oracle?.liveRoutingEnabled === true && oracle.modelRouterUsed === true && oracle.routingApplied === true && oracle.selectedModelClass === "strong_oracle" && typeof oracle.selectedModelHash === "string" && oracle.selectedModelStored === false },
644
- { name: "routing_high_context_uses_high_context_when_enabled", passed: highContext?.liveRoutingEnabled === true && highContext.selectedModelClass === "high_context" && typeof highContext.selectedModelHash === "string" && highContext.selectedModelStored === false },
645
- { name: "routing_security_not_downgraded_when_enabled", passed: security?.liveRoutingEnabled === true && security.selectedModelClass === "strong_reasoning" && typeof security.selectedModelHash === "string" && security.selectedModelStored === false },
646
- { name: "autonomous_model_routing_plan_still_disabled", passed: input.modelRoutingPlan.liveRoutingEnabled === false && input.modelRoutingPlan.globalLiveRoutingEnabled === false && input.modelRoutingPlan.modelRouterUsed === false && input.modelRoutingPlan.routingApplied === false && input.modelRoutingPlan.childDispatchAllowed === false },
647
- { name: "run_scope_no_global_autonomy", passed: input.validation.globalAutonomyReady === false && input.validation.globalAutonomyNoShip === true && input.validation.childDispatchAllowed === false && input.validation.productionWritesPerformed === false && input.validation.autoApply === false },
648
- ];
649
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
650
- const proof = {
651
- schema: "zob.autonomous-model-routing-proof-plan.v1",
652
- runId: input.runId,
653
- phase: "6B",
654
- status: failedChecks.length === 0 ? "model_routing_dispatch_gate_proof_ready_global_default_blocked" : "model_routing_dispatch_gate_proof_incomplete",
655
- modelRoutingProofReady: failedChecks.length === 0,
656
- liveRoutingDispatchGateAvailable: true,
657
- routingDefaultDisabledProofPassed: defaultDisabled?.defaultDispatchDecision === "allow_default_model" && defaultDisabled.liveRoutingEnabled === false,
658
- routingOracleProofPassed: oracle?.selectedModelClass === "strong_oracle" && oracle.routingApplied === true,
659
- routingHighContextProofPassed: highContext?.selectedModelClass === "high_context" && highContext.routingApplied === true,
660
- routingSecurityNoDowngradeProofPassed: security?.selectedModelClass === "strong_reasoning" && security.routingApplied === true,
661
- selectedModelsStored: false,
662
- selectedModelHashesOnly: scenarioSpecs.every((scenario) => scenario.selectedModelStored === false && (scenario.liveRoutingEnabled === false || typeof scenario.selectedModelHash === "string")),
663
- finalE2ERequirementCleared: false,
664
- no_ship: true,
665
- checks,
666
- failedChecks,
667
- scenarios: scenarioSpecs,
668
- evidenceRefs: [
669
- `reports/autonomous-runs/${safeFileStem(input.runId)}/model-routing-plan.json`,
670
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
671
- ],
672
- blockers: [
673
- "live_autonomous_model_routing_not_enabled",
674
- "global_default_model_routing_disabled",
675
- "final_e2e_model_routing_evidence_required",
676
- ],
677
- globalLiveRoutingEnabled: false,
678
- liveAutonomousRoutingApplied: false,
679
- modelRouterUsed: false,
680
- routingApplied: false,
681
- budgetEnforced: false,
682
- strictEnabled: false,
683
- childDispatchAllowed: false,
684
- daemonStarted: false,
685
- productionWritesPerformed: false,
686
- autoApply: false,
687
- noExecution: true,
688
- globalAutonomyReady: false,
689
- globalAutonomyNoShip: true,
690
- bodyStored: false,
691
- promptBodiesStored: false,
692
- outputBodiesStored: false,
693
- };
694
- if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous model routing proof plan would store forbidden plaintext body keys");
695
- return proof;
696
- }
697
-
698
- function buildAutonomousRunGraph(input: {
699
- runId: string;
700
- specLocked: boolean;
701
- contextScopeValid: boolean;
702
- contextPackValid: boolean;
703
- runtimeGatesValid: boolean;
704
- modelRoutingPlanValid: boolean;
705
- factorySelected: boolean;
706
- registeredBatchReady: boolean;
707
- proofBeforeExecutionRequired: boolean;
708
- selectedFactory?: string;
709
- }): Record<string, unknown> {
710
- const nodes = [
711
- { id: "spec_gate", kind: "gate", artifactRef: "spec-gate.json", passed: input.specLocked, stopOnFail: true },
712
- { id: "context_scope", kind: "context", artifactRef: "context-scope.json", passed: input.contextScopeValid, stopOnFail: true },
713
- { id: "context_lookup", kind: "context", artifactRef: "context-lookup.json", passed: input.contextPackValid, stopOnFail: true },
714
- { id: "context_pack", kind: "context", artifactRef: "context-pack.json", passed: input.contextPackValid, stopOnFail: true },
715
- { id: "runtime_gates", kind: "gate", artifactRef: "runtime-gates.json", passed: input.runtimeGatesValid, stopOnFail: true },
716
- { id: "model_routing_plan", kind: "gate", artifactRef: "model-routing-plan.json", passed: input.modelRoutingPlanValid, stopOnFail: true },
717
- { id: "factory_selection", kind: "selection", artifactRef: "factory-selection.json", passed: input.factorySelected, selectedFactory: input.selectedFactory, stopOnFail: true },
718
- { id: "registered_factory_current_source_proof", kind: "proof", artifactRef: "proof-plan.json", passed: input.registeredBatchReady, proofBeforeExecutionRequired: input.proofBeforeExecutionRequired, stopOnFail: false },
719
- { id: "smoke", kind: "future_execution", artifactRef: "SMOKE_PASSED.sentinel", passed: false, dispatchAllowed: false },
720
- { id: "smoke_oracle", kind: "future_oracle", artifactRef: "oracle-review-pass.json", passed: false, dispatchAllowed: false },
721
- { id: "pilot", kind: "future_execution", artifactRef: "PILOT_PASSED.sentinel", passed: false, dispatchAllowed: false },
722
- { id: "pilot_oracle", kind: "future_oracle", artifactRef: "oracle-review-pass.json", passed: false, dispatchAllowed: false },
723
- { id: "batch", kind: "future_execution", artifactRef: "BATCH_PASSED.sentinel", passed: false, dispatchAllowed: false },
724
- { id: "final_report", kind: "report", artifactRef: "final-report.md", passed: false, dispatchAllowed: false },
725
- ];
726
- const edges = [
727
- ["spec_gate", "context_scope"],
728
- ["context_scope", "context_lookup"],
729
- ["context_lookup", "context_pack"],
730
- ["context_pack", "runtime_gates"],
731
- ["runtime_gates", "model_routing_plan"],
732
- ["model_routing_plan", "factory_selection"],
733
- ["factory_selection", "registered_factory_current_source_proof"],
734
- ["registered_factory_current_source_proof", "smoke"],
735
- ["smoke", "smoke_oracle"],
736
- ["smoke_oracle", "pilot"],
737
- ["pilot", "pilot_oracle"],
738
- ["pilot_oracle", "batch"],
739
- ["batch", "final_report"],
740
- ].map(([from, to]) => ({ from, to, parentOwned: true, dispatchAllowed: false }));
741
- const runGraph = {
742
- schema: "zob.autonomous-run-graph.v1",
743
- runId: input.runId,
744
- status: input.specLocked && input.contextScopeValid && input.contextPackValid && input.runtimeGatesValid && input.modelRoutingPlanValid && input.factorySelected ? "dry_run_graph_ready" : "dry_run_graph_blocked",
745
- parentOwned: true,
746
- nodes,
747
- edges,
748
- stopConditions: ["clarification_required", "context_scope_invalid", "context_pack_invalid", "runtime_gates_invalid", "model_routing_plan_invalid", "factory_selection_missing", "current_source_proof_missing", "oracle_fail", "budget_exceeded", "secret_reference", "production_apply_requested"],
749
- futureExecutionNodesDispatchAllowed: false,
750
- childDispatchAllowed: false,
751
- noExecution: true,
752
- daemonStarted: false,
753
- productionWritesPerformed: false,
754
- autoApply: false,
755
- globalAutonomyReady: false,
756
- globalAutonomyNoShip: true,
757
- bodyStored: false,
758
- promptBodiesStored: false,
759
- outputBodiesStored: false,
760
- };
761
- if (hasForbiddenBodyKeys(runGraph)) throw new Error("autonomous run graph would store forbidden plaintext body keys");
762
- return runGraph;
763
- }
764
-
765
- function detectContextNeedTags(specText: string): string[] {
766
- const lower = specText.toLowerCase();
767
- const tags = new Set<string>(["harness-system", "factory-evidence"]);
768
- if (/factory|batch|pilot|smoke|oracle/.test(lower)) tags.add("factory-evidence");
769
- if (/context|gbrain|brain|citation|source/.test(lower)) tags.add("context-gbrain");
770
- if (/budget|cost|cap/.test(lower)) tags.add("budget-policy");
771
- if (/model|routing|oracle/.test(lower)) tags.add("model-routing");
772
- if (/sandbox|apply|write|patch|edit/.test(lower)) tags.add("sandbox-policy");
773
- if (/daemon|queue|worker|mission|coms|heartbeat/.test(lower)) tags.add("mission-control");
774
- return [...tags].sort();
775
- }
776
-
777
- function buildClarificationQuestions(input: {
778
- shortSpec: boolean;
779
- missingAcceptance: boolean;
780
- missingArtifacts: boolean;
781
- missingAllowedPaths: boolean;
782
- unsafeAllowedPaths: boolean;
783
- missingApplyPolicy: boolean;
784
- missingBudgetProfile: boolean;
785
- riskyApply: boolean;
786
- sensitiveReference: boolean;
787
- }): string[] {
788
- const questions: string[] = [];
789
- if (input.shortSpec) questions.push("What exact deliverable should the autonomous dry-run plan target?");
790
- if (input.missingAcceptance) questions.push("What acceptance criteria must be true before the run can proceed past spec lock?");
791
- if (input.missingArtifacts) questions.push("Which final artifacts or reports should be produced?");
792
- if (input.missingAllowedPaths) questions.push("Which repo-relative allowed_paths should bound future autonomous work?");
793
- if (input.unsafeAllowedPaths) questions.push("Please remove unsafe or forbidden entries from allowed_paths and keep them in forbidden_paths only.");
794
- if (input.missingApplyPolicy) questions.push("Which apply_policy should govern this autonomous run: no_apply, sandbox_simulation, manual_apply_only, or auto_apply_in_scope?");
795
- if (input.missingBudgetProfile) questions.push("Which budget_profile should govern this autonomous run: advisory or strict_requested?");
796
- if (input.riskyApply) questions.push("Should this remain no-apply/manual-apply, or is a sandbox simulation explicitly required?");
797
- if (input.sensitiveReference) questions.push("Please remove or replace any secret-like values with safe placeholders before planning.");
798
- return questions;
799
- }
800
-
801
- export function buildAutonomousRuntimeDryRun(repoRoot: string, input: AutonomousRuntimeDryRunInput): Record<string, unknown> {
802
- const userNeed = typeof input.userNeed === "string" ? input.userNeed.trim() : "";
803
- const refinedSpec = typeof input.refinedSpec === "string" && input.refinedSpec.trim().length > 0 ? input.refinedSpec.trim() : userNeed;
804
- const constraints = stableStrings(input.constraints);
805
- const acceptanceCriteria = stableStrings(input.acceptanceCriteria);
806
- const expectedArtifacts = stableStrings(input.expectedArtifacts);
807
- const allowedPaths = stableStrings(input.allowedPaths);
808
- const forbiddenPaths = stableStrings(input.forbiddenPaths ?? DEFAULT_AUTONOMOUS_FORBIDDEN_PATHS);
809
- const applyPolicyProvided = typeof input.applyPolicy === "string";
810
- const budgetProfileProvided = typeof input.budgetProfile === "string";
811
- const applyPolicy = input.applyPolicy ?? "no_apply";
812
- const budgetProfile = input.budgetProfile ?? "advisory";
813
- const risk = input.risk ?? "medium";
814
- const authorizedAutonomyLevel = input.authorizedAutonomyLevel ?? inferAutonomousLevel(applyPolicy);
815
- const userLaunchConfirmed = input.userLaunchConfirmed === true;
816
- const allowedActions = stableStrings(input.allowedActions ?? defaultAutonomousAllowedActions(applyPolicy));
817
- const runId = safeFileStem(input.runId ?? `autonomous-dry-run-${sha256(refinedSpec || "missing-spec").slice(0, 12)}`);
818
- const specText = `${userNeed}\n${refinedSpec}\n${constraints.join("\n")}\n${acceptanceCriteria.join("\n")}\n${expectedArtifacts.join("\n")}`;
819
- const shortSpec = refinedSpec.length < 24;
820
- const ambiguous = AMBIGUOUS_PATTERNS.some((pattern) => pattern.test(refinedSpec));
821
- const sensitiveReference = SECRET_PATTERNS.some((pattern) => pattern.test(specText));
822
- const missingAcceptance = acceptanceCriteria.length === 0;
823
- const missingArtifacts = expectedArtifacts.length === 0;
824
- const pathGateErrors = validateAutonomousSpecPathGate(allowedPaths, forbiddenPaths);
825
- const missingAllowedPaths = allowedPaths.length === 0;
826
- const unsafeAllowedPaths = pathGateErrors.some((error) => error !== "allowed_paths_required_before_execution");
827
- const missingApplyPolicy = !applyPolicyProvided;
828
- const missingBudgetProfile = !budgetProfileProvided;
829
- const riskyApply = applyPolicy !== "no_apply" && allowedPaths.length === 0;
830
- const clarificationRequired = !userNeed || shortSpec || ambiguous || sensitiveReference || missingAcceptance || missingArtifacts || missingAllowedPaths || unsafeAllowedPaths || missingApplyPolicy || missingBudgetProfile || riskyApply;
831
- const clarificationQuestions = buildClarificationQuestions({ shortSpec: !userNeed || shortSpec || ambiguous, missingAcceptance, missingArtifacts, missingAllowedPaths, unsafeAllowedPaths, missingApplyPolicy, missingBudgetProfile, riskyApply, sensitiveReference });
832
-
833
- const contextScope = buildDefaultContextScope(repoRoot, {
834
- runId,
835
- allowedSources: input.allowedSources,
836
- forbiddenSources: forbiddenPaths,
837
- agentProfile: "autonomous-runtime-dry-run-p0",
838
- maxContextTokens: input.maxContextTokens,
839
- });
840
- const contextScopeErrors = validateContextScope(repoRoot, contextScope);
841
- const contextArtifacts = buildAutonomousContextArtifacts(repoRoot, contextScope, sha256(refinedSpec));
842
- const contextPackValid = contextArtifacts.contextPackValid === true;
843
- const contextPackErrors = Array.isArray(contextArtifacts.contextPackErrors) ? contextArtifacts.contextPackErrors : [];
844
- const runtimeGates = buildAutonomousRuntimeGates({ runId, risk, budgetProfile, applyPolicy, maxContextTokens: input.maxContextTokens });
845
- const runtimeGatesValid = runtimeGates.passed === true;
846
- const capabilityIndex = buildCapabilityIndex(repoRoot);
847
- const reuseScout = buildReuseScoutReport(repoRoot, { query: refinedSpec, run_id: runId, limit: 8 });
848
- const candidates = Array.isArray(reuseScout.candidates) ? reuseScout.candidates : [];
849
- const factories = capabilityFactories(capabilityIndex);
850
- const factoryForgeAvailable = factories.some((factory) => factory.id === "factory-forge");
851
- const factoryScore = selectAutonomousFactory({ factories, refinedSpec, acceptanceCriteria, expectedArtifacts });
852
- const selectedFactory = typeof factoryScore.selectedFactory === "string" ? factoryScore.selectedFactory : (factoryForgeAvailable ? "factory-forge" : undefined);
853
- const selectionStatus = typeof factoryScore.selectionStatus === "string" && factoryScore.selectionStatus !== "no_factory_available"
854
- ? factoryScore.selectionStatus
855
- : (factoryForgeAvailable ? "factory_forge_quarantine_recommended" : "no_factory_available");
856
- const manifestAvailability = factoryManifestAvailability(repoRoot, selectedFactory);
857
- const factoryReadiness = readFactoryRegistryReadiness(repoRoot, selectedFactory);
858
- const proofBeforeExecutionRequired = factoryReadiness.proofBeforeExecutionRequired === true;
859
- const modelRoutingPlan = buildAutonomousModelRoutingPlan({ runId, risk, budgetProfile, maxContextTokens: input.maxContextTokens, specText, selectedFactory });
860
- const modelRoutingPlanValid = modelRoutingPlan.routingPlanReady === true;
861
- const selectionBlockers = selectedFactory ? [] : ["no_factory_available_for_spec"];
862
-
863
- const strictBudgetMissing = budgetProfile !== "strict_requested";
864
- const blockers = [
865
- ...(!userNeed ? ["user_need_required"] : []),
866
- ...(clarificationRequired ? ["clarification_required_before_execution"] : []),
867
- ...pathGateErrors,
868
- ...(missingApplyPolicy ? ["apply_policy_required_before_execution"] : []),
869
- ...(missingBudgetProfile ? ["budget_profile_required_before_execution"] : []),
870
- ...(!missingBudgetProfile && strictBudgetMissing ? ["autonomous_strict_budget_required_before_execution"] : []),
871
- ...(contextScopeErrors.length > 0 ? ["context_scope_invalid"] : []),
872
- ...(!contextPackValid ? ["context_pack_invalid"] : []),
873
- ...(!runtimeGatesValid ? ["runtime_gates_invalid"] : []),
874
- ...(!modelRoutingPlanValid ? ["model_routing_plan_invalid"] : []),
875
- ...selectionBlockers,
876
- ];
877
- const specLocked = blockers.length === 0;
878
- const launchAuthorization = {
879
- schema: "zob.launch-authorization.v1",
880
- runId,
881
- originalUserAskHash: sha256(userNeed),
882
- refinedSpecHash: sha256(refinedSpec),
883
- specLocked,
884
- userLaunchConfirmed,
885
- launchConfirmedAt: userLaunchConfirmed && typeof input.launchConfirmedAt === "string" && input.launchConfirmedAt.trim().length > 0 ? input.launchConfirmedAt.trim() : undefined,
886
- authorizedAutonomyLevel,
887
- allowedActions,
888
- allowedPaths,
889
- forbiddenPaths,
890
- applyPolicy: {
891
- mode: applyPolicy,
892
- rollbackRequired: applyPolicy !== "no_apply",
893
- exactDiffHashRequired: applyPolicy !== "no_apply",
894
- postApplyValidationRequired: applyPolicy !== "no_apply",
895
- postApplyOracleRequired: applyPolicy !== "no_apply",
896
- },
897
- budgetPolicy: {
898
- mode: budgetProfile,
899
- strict: budgetProfile === "strict_requested",
900
- strictBudgetRequired: true,
901
- strictBudgetSatisfied: budgetProfile === "strict_requested",
902
- },
903
- stopConditions: ["scope_drift", "secret_required", "validation_fail_exhausted", "oracle_no_ship", "budget_exceeded", "stale_worker_unrecoverable"],
904
- launchAuthorizesInScopeActions: specLocked && userLaunchConfirmed,
905
- actionExecutionBlockedUntilLaunch: !userLaunchConfirmed,
906
- exceptionApprovalRequiredOnlyForOutOfScope: true,
907
- bodyStored: false,
908
- promptBodiesStored: false,
909
- outputBodiesStored: false,
910
- };
911
- const status = specLocked ? "dry_run_plan_ready" : "clarification_or_gate_required";
912
- const runGraph = buildAutonomousRunGraph({
913
- runId,
914
- specLocked,
915
- contextScopeValid: contextScopeErrors.length === 0,
916
- contextPackValid,
917
- runtimeGatesValid,
918
- modelRoutingPlanValid,
919
- factorySelected: Boolean(selectedFactory),
920
- registeredBatchReady: factoryReadiness.registeredBatchReady === true,
921
- proofBeforeExecutionRequired,
922
- selectedFactory,
923
- });
924
-
925
- const report = {
926
- schema: "zob.autonomous-runtime-dry-run.v1",
927
- runId,
928
- status,
929
- no_ship: true,
930
- noShipReason: "P0 dry-run only; global autonomy remains disabled until current-source proof and policy gates pass.",
931
- globalAutonomyReady: false,
932
- globalAutonomyNoShip: true,
933
- dryRun: true,
934
- noExecution: true,
935
- childDispatchAllowed: false,
936
- daemonStarted: false,
937
- productionWritesPerformed: false,
938
- autoApply: false,
939
- networkAccessed: false,
940
- bodyStored: false,
941
- promptBodiesStored: false,
942
- outputBodiesStored: false,
943
- specGate: {
944
- schema: "zob.autonomous-spec-gate.v1",
945
- userNeedHash: sha256(userNeed),
946
- refinedSpecHash: sha256(refinedSpec),
947
- constraintHashes: hashes(constraints),
948
- acceptanceCriteriaHashes: hashes(acceptanceCriteria),
949
- expectedArtifactHashes: hashes(expectedArtifacts),
950
- allowedPaths,
951
- forbiddenPaths,
952
- allowedPathsRequired: true,
953
- pathGatePassed: pathGateErrors.length === 0,
954
- pathGateErrors,
955
- applyPolicyRequired: true,
956
- applyPolicyProvided,
957
- applyPolicy,
958
- budgetProfileRequired: true,
959
- budgetProfileProvided,
960
- budgetProfile,
961
- autonomousStrictBudgetRequired: true,
962
- autonomousStrictBudgetSatisfied: budgetProfile === "strict_requested",
963
- risk,
964
- specTextStored: false,
965
- specLocked,
966
- launchAuthorizationRequired: true,
967
- userLaunchConfirmed,
968
- launchAuthorizesInScopeActions: launchAuthorization.launchAuthorizesInScopeActions,
969
- actionExecutionBlockedUntilLaunch: launchAuthorization.actionExecutionBlockedUntilLaunch,
970
- clarificationRequired,
971
- clarificationQuestions,
972
- blockers,
973
- },
974
- launchAuthorization,
975
- contextPlan: {
976
- schema: "zob.autonomous-context-plan.v1",
977
- contextNeedTags: detectContextNeedTags(specText),
978
- contextScope,
979
- contextScopeValid: contextScopeErrors.length === 0,
980
- contextScopeErrors,
981
- lookupResults: contextArtifacts.lookupResults,
982
- contextPack: contextArtifacts.contextPack,
983
- contextPackValid,
984
- contextPackErrors,
985
- lookupPlan: {
986
- queryHash: sha256(refinedSpec),
987
- allowedSources: contextScope.allowedSources,
988
- citationRequired: true,
989
- boundedContextOnly: true,
990
- gbrainImportEnabled: false,
991
- gbrainEmbedEnabled: false,
992
- gbrainSyncEnabled: false,
993
- gbrainWriteEnabled: false,
994
- },
995
- },
996
- runtimeGates,
997
- modelRoutingPlan,
998
- runGraph,
999
- factorySelection: {
1000
- schema: "zob.autonomous-factory-selection.v1",
1001
- queryHash: reuseScout.queryHash,
1002
- selectionStatus,
1003
- selectedFactory,
1004
- selectedFactorySourcePath: selectedFactory ? `.pi/factories/${selectedFactory}/factory.json` : undefined,
1005
- manifestAvailability,
1006
- candidateCount: candidates.length,
1007
- reuseScoutCandidates: candidates.filter(isRecord).map((candidate) => ({
1008
- kind: candidate.kind,
1009
- id: candidate.id,
1010
- sourcePath: candidate.sourcePath,
1011
- score: candidate.score,
1012
- reasonCodes: candidate.reasonCodes,
1013
- summaryHash: candidate.summaryHash,
1014
- })),
1015
- deterministicScoring: factoryScore,
1016
- factoryForgeAvailable,
1017
- factoryReadiness,
1018
- currentSourceProofRequired: true,
1019
- proofBeforeExecutionRequired,
1020
- noAutoActivation: true,
1021
- quarantineRequiredForNewFactory: selectionStatus === "factory_forge_quarantine_recommended",
1022
- },
1023
- proofPlan: {
1024
- schema: "zob.autonomous-proof-plan.v1",
1025
- parentOwned: true,
1026
- stages: [
1027
- { name: "spec_lock", required: true, passed: specLocked },
1028
- { name: "launch_authorization", required: true, passed: launchAuthorization.launchAuthorizesInScopeActions, executionBlockedUntilLaunch: launchAuthorization.actionExecutionBlockedUntilLaunch, dispatchAllowed: false, noExecution: true },
1029
- { name: "context_scope", required: true, passed: contextScopeErrors.length === 0, citationRequired: true },
1030
- { name: "context_lookup_and_pack", required: true, passed: contextPackValid, citationRequired: true, boundedContextOnly: true, dispatchAllowed: false },
1031
- { name: "runtime_gates_preflight", required: true, passed: runtimeGatesValid, dispatchAllowed: false, noExecution: true },
1032
- { name: "model_routing_plan", required: true, passed: modelRoutingPlanValid, dispatchAllowed: false, liveRoutingEnabled: false },
1033
- { name: "factory_selection", required: true, passed: Boolean(selectedFactory) },
1034
- { name: "registered_factory_current_source_proof", required: true, passed: factoryReadiness.registeredBatchReady === true, dispatchAllowed: false, proofBeforeExecutionRequired },
1035
- { name: "smoke", required: true, dispatchAllowed: false, sentinelRequired: "SMOKE_PASSED.sentinel" },
1036
- { name: "smoke_oracle", required: true, dispatchAllowed: false, verdictRequired: "PASS", noShipRequired: false },
1037
- { name: "pilot", required: true, dispatchAllowed: false, requiresSmokeOracle: true, sentinelRequired: "PILOT_PASSED.sentinel" },
1038
- { name: "pilot_oracle", required: true, dispatchAllowed: false, verdictRequired: "PASS", noShipRequired: false },
1039
- { name: "batch", required: true, dispatchAllowed: false, requiresPilotOracle: true, sentinelRequired: "BATCH_PASSED.sentinel", batchConcurrencyCapRequired: true },
1040
- { name: "final_report", required: true, dispatchAllowed: false, validationJsonRequired: true, doneSentinelRequired: true },
1041
- ],
1042
- gates: ["strict_goal_spec", "context_scope", "context_lookup_and_pack", "runtime_gates_preflight", "model_routing_plan", "run_graph_ready", "registered_factory_current_source_proof", "budget_preflight", "model_routing_policy", "sandbox_apply_policy", "daemon_policy", "oracle_review", "mission_control_proposals_only"],
1043
- noShipConditions: ["clarification_required", "context_scope_invalid", "context_pack_invalid", "runtime_gates_invalid", "model_routing_plan_invalid", "factory_selection_missing", "oracle_fail", "budget_exceeded", "secret_reference", "production_apply_requested", "current_source_proof_missing"],
1044
- },
1045
- finalReportPlan: {
1046
- schema: "zob.autonomous-final-report-plan.v1",
1047
- artifactPath: `reports/autonomous-runs/${runId}/dry-run-report.json`,
1048
- includesEvidenceRefs: true,
1049
- includesBlockers: true,
1050
- includesNoShipDecision: true,
1051
- rawSpecStored: false,
1052
- },
1053
- validation: {
1054
- passed: blockers.length === 0,
1055
- blockers,
1056
- warnings: ["dry_run_only", "global_autonomy_no_ship", "no_child_dispatch", ...(proofBeforeExecutionRequired ? ["selected_factory_current_source_proof_required_before_execution"] : [])],
1057
- },
1058
- generatedAt: new Date().toISOString(),
1059
- };
1060
- if (hasForbiddenBodyKeys(report)) throw new Error("autonomous dry-run report would store forbidden plaintext body keys");
1061
- return report;
1062
- }
1063
-
1064
- export function buildAutonomousRuntimeDryRunValidation(report: Record<string, unknown>): Record<string, unknown> {
1065
- const validation = {
1066
- schema: "zob.autonomous-runtime-dry-run-validation.v1",
1067
- runId: report.runId,
1068
- status: report.status,
1069
- passed: report.status === "dry_run_plan_ready",
1070
- no_ship: report.no_ship,
1071
- dryRun: report.dryRun,
1072
- noExecution: report.noExecution,
1073
- childDispatchAllowed: report.childDispatchAllowed,
1074
- daemonStarted: report.daemonStarted,
1075
- productionWritesPerformed: report.productionWritesPerformed,
1076
- autoApply: report.autoApply,
1077
- networkAccessed: report.networkAccessed,
1078
- globalAutonomyReady: report.globalAutonomyReady,
1079
- globalAutonomyNoShip: report.globalAutonomyNoShip,
1080
- blockers: isRecord(report.validation) && Array.isArray(report.validation.blockers) ? report.validation.blockers : [],
1081
- requiredArtifacts: ["spec-gate.json", "context-scope.json", "context-lookup.json", "context-pack.json", "runtime-gates.json", "model-routing-plan.json", "run-graph.json", "factory-selection.json", "proof-plan.json", "dry-run-report.json", "validation.json", "final-report.md", "DRY_RUN_READY.sentinel"],
1082
- sentinel: report.status === "dry_run_plan_ready" ? "DRY_RUN_READY.sentinel" : undefined,
1083
- bodyStored: false,
1084
- promptBodiesStored: false,
1085
- outputBodiesStored: false,
1086
- generatedAt: new Date().toISOString(),
1087
- };
1088
- if (hasForbiddenBodyKeys(validation)) throw new Error("autonomous dry-run validation would store forbidden plaintext body keys");
1089
- return validation;
1090
- }
1091
-
1092
- export function buildAutonomousRuntimeDryRunFinalReport(report: Record<string, unknown>): string {
1093
- const factorySelection = isRecord(report.factorySelection) ? report.factorySelection : {};
1094
- const validation = isRecord(report.validation) ? report.validation : {};
1095
- const blockers = Array.isArray(validation.blockers) ? validation.blockers.map((blocker) => `- ${String(blocker)}`).join("\n") : "";
1096
- return [
1097
- "# Autonomous Runtime Dry-Run Report",
1098
- "",
1099
- `Run ID: ${String(report.runId ?? "unknown")}`,
1100
- `Status: ${String(report.status ?? "unknown")}`,
1101
- `No-ship: ${String(report.no_ship ?? true)}`,
1102
- "",
1103
- "## Safety posture",
1104
- "",
1105
- `- Dry-run only: ${String(report.dryRun === true)}`,
1106
- `- No execution: ${String(report.noExecution === true)}`,
1107
- `- Child dispatch allowed: ${String(report.childDispatchAllowed === true)}`,
1108
- `- Daemon started: ${String(report.daemonStarted === true)}`,
1109
- `- Production writes performed: ${String(report.productionWritesPerformed === true)}`,
1110
- `- Auto-apply: ${String(report.autoApply === true)}`,
1111
- `- Global autonomy no-ship: ${String(report.globalAutonomyNoShip === true)}`,
1112
- "",
1113
- "## Factory selection",
1114
- "",
1115
- `- Status: ${String(factorySelection.selectionStatus ?? "unknown")}`,
1116
- `- Selected factory: ${String(factorySelection.selectedFactory ?? "none")}`,
1117
- "",
1118
- "## Blockers",
1119
- "",
1120
- blockers || "- None for dry-run plan readiness.",
1121
- "",
1122
- "## Evidence refs",
1123
- "",
1124
- "- spec-gate.json",
1125
- "- context-scope.json",
1126
- "- context-lookup.json",
1127
- "- context-pack.json",
1128
- "- runtime-gates.json",
1129
- "- model-routing-plan.json",
1130
- "- run-graph.json",
1131
- "- factory-selection.json",
1132
- "- proof-plan.json",
1133
- "- dry-run-report.json",
1134
- "- validation.json",
1135
- "- DRY_RUN_READY.sentinel when status=dry_run_plan_ready",
1136
- "",
1137
- "Compliance: P0 dry-run artifact only; no global autonomy claim.",
1138
- "",
1139
- ].join("\n");
1140
- }
1141
-
1142
- function readJsonArtifact(path: string): { parsed?: Record<string, unknown> | unknown[]; hash?: string; error?: string } {
1143
- try {
1144
- const raw = readFileSync(path, "utf8");
1145
- const parsed = JSON.parse(raw) as unknown;
1146
- return { parsed: isRecord(parsed) || Array.isArray(parsed) ? parsed : undefined, hash: sha256(raw), error: isRecord(parsed) || Array.isArray(parsed) ? undefined : "artifact JSON root must be object or array" };
1147
- } catch (error) {
1148
- return { error: error instanceof Error ? error.message : String(error) };
1149
- }
1150
- }
1151
-
1152
- function artifactHashIfPresent(path: string): string | undefined {
1153
- if (!existsSync(path)) return undefined;
1154
- return sha256(readFileSync(path, "utf8"));
1155
- }
1156
-
1157
- function relativeFactoryRunPath(runId: string, artifact?: string): string {
1158
- return artifact ? `reports/factory-runs/${runId}/${artifact}` : `reports/factory-runs/${runId}`;
1159
- }
1160
-
1161
- function buildAutonomousPromotionPlan(input: { runId: string; selectedFactory?: string; factoryRunRef: Record<string, unknown>; oracleReview: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1162
- const smokeGatePassed = input.validation.status === "smoke_autonomy_passed"
1163
- && input.validation.no_ship === false
1164
- && input.factoryRunRef.status === "done"
1165
- && input.factoryRunRef.phaseSentinelPresent === true
1166
- && input.factoryRunRef.doneSentinelPresent === true
1167
- && input.oracleReview.verdict === "PASS"
1168
- && input.oracleReview.no_ship === false;
1169
- const factoryRunId = typeof input.factoryRunRef.factoryRunId === "string" ? input.factoryRunRef.factoryRunId : "unknown";
1170
- const plan = {
1171
- schema: "zob.autonomous-promotion-plan.v1",
1172
- runId: input.runId,
1173
- selectedFactory: input.selectedFactory,
1174
- sourceSmoke: {
1175
- autonomousRunId: input.runId,
1176
- factoryRunId,
1177
- smokeSentinelRef: relativeFactoryRunPath(factoryRunId, "SMOKE_PASSED.sentinel"),
1178
- doneSentinelRef: relativeFactoryRunPath(factoryRunId, "DONE.sentinel"),
1179
- oracleReviewRef: `reports/autonomous-runs/${input.runId}/oracle-review.json`,
1180
- },
1181
- smokeGate: {
1182
- passed: smokeGatePassed,
1183
- sentinelPresent: input.factoryRunRef.phaseSentinelPresent === true,
1184
- doneSentinelPresent: input.factoryRunRef.doneSentinelPresent === true,
1185
- oraclePass: input.oracleReview.verdict === "PASS" && input.oracleReview.no_ship === false,
1186
- structuralOracleOnly: input.oracleReview.oracleType === "deterministic_structural",
1187
- },
1188
- pilotGate: {
1189
- preconditionsMet: smokeGatePassed,
1190
- executionAllowed: false,
1191
- dispatchAllowed: false,
1192
- reason: "phase_7a_promotion_metadata_only_no_pilot_execution",
1193
- requiredBeforeExecution: ["strict_budget_gate", "live_or_structural_oracle_pass", "current_source_factory_proof", "operator_or_parent_gate", "PILOT_PASSED.sentinel_on_success"],
1194
- maxItems: 10,
1195
- prerequisiteSmokeRunId: factoryRunId,
1196
- oracleReviewPath: `reports/autonomous-runs/${input.runId}/oracle-review.json`,
1197
- },
1198
- batchGate: {
1199
- preconditionsMet: false,
1200
- executionAllowed: false,
1201
- dispatchAllowed: false,
1202
- reason: "pilot_not_executed_in_phase_7a",
1203
- requiredBeforeExecution: ["PILOT_PASSED.sentinel", "pilot_oracle_PASS_no_ship_false", "batch_concurrency_cap", "strict_budget_gate", "final_oracle_gate"],
1204
- batchConcurrencyCapRequired: true,
1205
- },
1206
- resumePolicy: {
1207
- resumeOnlyIncompleteItems: true,
1208
- doNotRerunPassedItems: true,
1209
- stopOnRepeatedFail: true,
1210
- maxRetryPolicyRequiredBeforeLiveScale: true,
1211
- },
1212
- oraclePolicy: {
1213
- smokeOracleRequired: true,
1214
- pilotOracleRequired: true,
1215
- batchOracleRequired: true,
1216
- warnOrFailTreatedAsNoShip: true,
1217
- },
1218
- strictBudgetRequired: true,
1219
- liveRoutingEnabled: false,
1220
- childDispatchAllowed: false,
1221
- pilotExecuted: false,
1222
- batchExecuted: false,
1223
- noExecutionBeyondSmoke: true,
1224
- globalAutonomyReady: false,
1225
- globalAutonomyNoShip: true,
1226
- bodyStored: false,
1227
- promptBodiesStored: false,
1228
- outputBodiesStored: false,
1229
- };
1230
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous promotion plan would store forbidden plaintext body keys");
1231
- return plan;
1232
- }
1233
-
1234
- function buildAutonomousPromotionProofPlan(input: { runId: string; promotionPlan: Record<string, unknown>; factoryRunRef: Record<string, unknown>; oracleReview: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1235
- const smokeGate = isRecord(input.promotionPlan.smokeGate) ? input.promotionPlan.smokeGate : {};
1236
- const pilotGate = isRecord(input.promotionPlan.pilotGate) ? input.promotionPlan.pilotGate : {};
1237
- const batchGate = isRecord(input.promotionPlan.batchGate) ? input.promotionPlan.batchGate : {};
1238
- const resumePolicy = isRecord(input.promotionPlan.resumePolicy) ? input.promotionPlan.resumePolicy : {};
1239
- const oraclePolicy = isRecord(input.promotionPlan.oraclePolicy) ? input.promotionPlan.oraclePolicy : {};
1240
- const scenarios = [
1241
- {
1242
- name: "smoke_to_pilot_preconditions_met",
1243
- passed: smokeGate.passed === true && smokeGate.sentinelPresent === true && smokeGate.doneSentinelPresent === true && smokeGate.oraclePass === true,
1244
- evidenceRefs: [`reports/autonomous-runs/${safeFileStem(input.runId)}/promotion-plan.json`, `reports/autonomous-runs/${safeFileStem(input.runId)}/oracle-review.json`],
1245
- dispatchAllowed: false,
1246
- },
1247
- {
1248
- name: "pilot_execution_blocked_until_live_gates",
1249
- passed: pilotGate.preconditionsMet === true && pilotGate.executionAllowed === false && pilotGate.dispatchAllowed === false && input.promotionPlan.pilotExecuted === false,
1250
- blockers: ["pilot_execution_disabled_until_live_budget_routing_daemon_oracle_gates"],
1251
- dispatchAllowed: false,
1252
- },
1253
- {
1254
- name: "batch_execution_blocked_without_pilot_oracle_and_concurrency",
1255
- passed: batchGate.preconditionsMet === false && batchGate.executionAllowed === false && batchGate.dispatchAllowed === false && batchGate.batchConcurrencyCapRequired === true && input.promotionPlan.batchExecuted === false,
1256
- blockers: ["pilot_not_executed", "pilot_oracle_missing", "batch_concurrency_cap_missing"],
1257
- dispatchAllowed: false,
1258
- },
1259
- {
1260
- name: "resume_retry_policy_safe_before_scale",
1261
- passed: resumePolicy.resumeOnlyIncompleteItems === true && resumePolicy.doNotRerunPassedItems === true && resumePolicy.stopOnRepeatedFail === true && resumePolicy.maxRetryPolicyRequiredBeforeLiveScale === true,
1262
- dispatchAllowed: false,
1263
- },
1264
- {
1265
- name: "oracle_policy_no_warn_fail_promotion",
1266
- passed: oraclePolicy.smokeOracleRequired === true && oraclePolicy.pilotOracleRequired === true && oraclePolicy.batchOracleRequired === true && oraclePolicy.warnOrFailTreatedAsNoShip === true,
1267
- dispatchAllowed: false,
1268
- },
1269
- ];
1270
- const checks = [
1271
- { name: "smoke_gate_passed", passed: scenarios[0].passed === true },
1272
- { name: "pilot_blocked_no_execution", passed: scenarios[1].passed === true },
1273
- { name: "batch_blocked_no_execution", passed: scenarios[2].passed === true },
1274
- { name: "resume_retry_policy_safe", passed: scenarios[3].passed === true },
1275
- { name: "oracle_policy_safe", passed: scenarios[4].passed === true },
1276
- { name: "run_scope_no_global_autonomy", passed: input.validation.globalAutonomyReady === false && input.validation.globalAutonomyNoShip === true && input.validation.childDispatchAllowed === false && input.validation.productionWritesPerformed === false && input.validation.autoApply === false },
1277
- ];
1278
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1279
- const proof = {
1280
- schema: "zob.autonomous-promotion-proof-plan.v1",
1281
- runId: input.runId,
1282
- phase: "7B",
1283
- status: failedChecks.length === 0 ? "pilot_batch_promotion_proof_ready_execution_blocked" : "pilot_batch_promotion_proof_incomplete",
1284
- promotionProofReady: failedChecks.length === 0,
1285
- smokeToPilotPreconditionsProved: scenarios[0].passed === true,
1286
- pilotExecutionBlockedProofPassed: scenarios[1].passed === true,
1287
- batchExecutionBlockedProofPassed: scenarios[2].passed === true,
1288
- resumeRetryPolicyProofPassed: scenarios[3].passed === true,
1289
- oraclePolicyProofPassed: scenarios[4].passed === true,
1290
- finalE2ERequirementCleared: false,
1291
- no_ship: true,
1292
- checks,
1293
- failedChecks,
1294
- scenarios,
1295
- evidenceRefs: [
1296
- `reports/autonomous-runs/${safeFileStem(input.runId)}/promotion-plan.json`,
1297
- `reports/autonomous-runs/${safeFileStem(input.runId)}/factory-run-ref.json`,
1298
- `reports/autonomous-runs/${safeFileStem(input.runId)}/oracle-review.json`,
1299
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
1300
- ],
1301
- blockers: [
1302
- "pilot_execution_disabled",
1303
- "batch_execution_disabled",
1304
- "pilot_oracle_missing",
1305
- "batch_concurrency_cap_missing",
1306
- "final_e2e_pilot_batch_evidence_required",
1307
- ],
1308
- pilotExecutionAllowed: false,
1309
- batchExecutionAllowed: false,
1310
- pilotExecuted: false,
1311
- batchExecuted: false,
1312
- pilotOraclePass: false,
1313
- batchConcurrencyCapPresent: false,
1314
- childDispatchAllowed: false,
1315
- daemonStarted: false,
1316
- productionWritesPerformed: false,
1317
- autoApply: false,
1318
- noExecutionBeyondSmoke: true,
1319
- globalAutonomyReady: false,
1320
- globalAutonomyNoShip: true,
1321
- bodyStored: false,
1322
- promptBodiesStored: false,
1323
- outputBodiesStored: false,
1324
- };
1325
- if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous promotion proof plan would store forbidden plaintext body keys");
1326
- return proof;
1327
- }
1328
-
1329
- function buildAutonomousSchedulerPlan(repoRoot: string, input: { runId: string; promotionPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1330
- const daemonPolicy = validateDaemonPolicyConfig(repoRoot);
1331
- const allowedJobTypes = Array.isArray(daemonPolicy.allowedJobTypes) ? daemonPolicy.allowedJobTypes.filter((item): item is string => typeof item === "string") : [];
1332
- const requiredStopConditions = Array.isArray(daemonPolicy.requiredStopConditions) ? daemonPolicy.requiredStopConditions.filter((item): item is string => typeof item === "string") : [];
1333
- const promotionReady = isRecord(input.promotionPlan.smokeGate) && input.promotionPlan.smokeGate.passed === true;
1334
- const checks = [
1335
- { name: "daemon_policy_valid", passed: daemonPolicy.present === true && daemonPolicy.valid === true },
1336
- { name: "daemon_disabled_by_default", passed: daemonPolicy.daemonEnabled === false && daemonPolicy.alwaysOnDaemonEnabled === false && daemonPolicy.autoStartDaemon === false && daemonPolicy.continuousLoop === false },
1337
- { name: "one_worker_bounded", passed: daemonPolicy.maxWorkersDefault === 1 && daemonPolicy.maxWorkersMax === 1 },
1338
- { name: "read_only_work_kinds_only", passed: allowedJobTypes.length > 0 && daemonPolicy.writeAdaptersEnabled === false && daemonPolicy.productionWritesPerformed === false && daemonPolicy.autoApply === false },
1339
- { name: "terminal_stop_conditions_available", passed: requiredStopConditions.includes("timeout") && requiredStopConditions.includes("blocked") && requiredStopConditions.includes("fail_loop") && requiredStopConditions.includes("no_ship") },
1340
- { name: "kill_switch_required", passed: true },
1341
- { name: "leases_and_heartbeat_required", passed: true },
1342
- { name: "budget_required_before_dispatch", passed: true },
1343
- { name: "scheduler_execution_disabled", passed: true },
1344
- ];
1345
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1346
- const plan = {
1347
- schema: "zob.autonomous-scheduler-plan.v1",
1348
- runId: input.runId,
1349
- schedulerPlanReady: failedChecks.length === 0,
1350
- failedChecks,
1351
- checks,
1352
- promotionReady,
1353
- daemonPolicy,
1354
- queuePolicy: {
1355
- allowedWorkKinds: allowedJobTypes,
1356
- initialWorkKinds: ["docs_watch", "repo_audit_readonly", "todo_risk_report", "session_analysis"].filter((kind) => allowedJobTypes.includes(kind)),
1357
- writeWorkAccepted: false,
1358
- claimAtMostOnePerTick: daemonPolicy.claimAtMostOneJobPerTick === true,
1359
- boundedQueueOnly: true,
1360
- },
1361
- leasePolicy: {
1362
- leaseRequired: true,
1363
- leaseTtlMs: 300_000,
1364
- maxLeaseRenewals: 0,
1365
- staleLeaseFailsCleanly: true,
1366
- leaseOwnerHashOnly: true,
1367
- },
1368
- heartbeatPolicy: {
1369
- heartbeatRequired: true,
1370
- heartbeatIntervalMs: 30_000,
1371
- staleHeartbeatTimeoutMs: 90_000,
1372
- staleHeartbeatStopCondition: "timeout",
1373
- },
1374
- timeoutPolicy: {
1375
- perWorkItemTimeoutMs: 300_000,
1376
- globalTickTimeoutMs: 600_000,
1377
- timeoutStopCondition: "timeout",
1378
- },
1379
- retryPolicy: {
1380
- retriesCapped: true,
1381
- maxRetriesPerWorkItem: 1,
1382
- failLoopThreshold: 3,
1383
- repeatedFailureStopCondition: "fail_loop",
1384
- doNotRetryNoShip: true,
1385
- },
1386
- killSwitch: {
1387
- required: true,
1388
- defaultState: "stopped_until_manual_start",
1389
- stopFileRef: ".pi/queue/STOP_DAEMON.sentinel",
1390
- checkedBeforeEachTick: true,
1391
- stopsQueueCleanly: true,
1392
- },
1393
- workerPool: {
1394
- defaultWorkers: 1,
1395
- maxWorkers: 1,
1396
- workerPoolBounded: true,
1397
- },
1398
- budgetPolicy: {
1399
- strictBudgetRequired: true,
1400
- perRunCapsRequired: true,
1401
- perDayCapsRequired: true,
1402
- budgetEnforced: false,
1403
- dispatchBlockedUntilStrictBudgetEnforced: true,
1404
- },
1405
- stopConditions: requiredStopConditions,
1406
- approvalPolicy: {
1407
- manualStartRequiresApproval: true,
1408
- alwaysOnRequiresApproval: true,
1409
- schedulerAutostartAllowed: false,
1410
- },
1411
- schedulerExecutionAllowed: false,
1412
- daemonEnabled: false,
1413
- alwaysOnDaemonEnabled: false,
1414
- autoStartDaemon: false,
1415
- continuousLoop: false,
1416
- daemonStarted: false,
1417
- cronEnabled: false,
1418
- childDispatchAllowed: false,
1419
- liveChildExecution: false,
1420
- networkAccessed: false,
1421
- writeAdaptersEnabled: false,
1422
- productionWritesPerformed: false,
1423
- autoApply: false,
1424
- pilotExecuted: false,
1425
- batchExecuted: false,
1426
- globalAutonomyReady: false,
1427
- globalAutonomyNoShip: true,
1428
- bodyStored: false,
1429
- promptBodiesStored: false,
1430
- outputBodiesStored: false,
1431
- };
1432
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous scheduler plan would store forbidden plaintext body keys");
1433
- return plan;
1434
- }
1435
-
1436
- function buildAutonomousSchedulerProofPlan(input: { runId: string; schedulerPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1437
- const queuePolicy = isRecord(input.schedulerPlan.queuePolicy) ? input.schedulerPlan.queuePolicy : {};
1438
- const leasePolicy = isRecord(input.schedulerPlan.leasePolicy) ? input.schedulerPlan.leasePolicy : {};
1439
- const heartbeatPolicy = isRecord(input.schedulerPlan.heartbeatPolicy) ? input.schedulerPlan.heartbeatPolicy : {};
1440
- const timeoutPolicy = isRecord(input.schedulerPlan.timeoutPolicy) ? input.schedulerPlan.timeoutPolicy : {};
1441
- const retryPolicy = isRecord(input.schedulerPlan.retryPolicy) ? input.schedulerPlan.retryPolicy : {};
1442
- const killSwitch = isRecord(input.schedulerPlan.killSwitch) ? input.schedulerPlan.killSwitch : {};
1443
- const workerPool = isRecord(input.schedulerPlan.workerPool) ? input.schedulerPlan.workerPool : {};
1444
- const budgetPolicy = isRecord(input.schedulerPlan.budgetPolicy) ? input.schedulerPlan.budgetPolicy : {};
1445
- const approvalPolicy = isRecord(input.schedulerPlan.approvalPolicy) ? input.schedulerPlan.approvalPolicy : {};
1446
- const daemonPolicy = isRecord(input.schedulerPlan.daemonPolicy) ? input.schedulerPlan.daemonPolicy : {};
1447
- const stopConditions = Array.isArray(input.schedulerPlan.stopConditions) ? input.schedulerPlan.stopConditions.filter((condition): condition is string => typeof condition === "string") : [];
1448
- const scenarios = [
1449
- {
1450
- name: "daemon_default_disabled",
1451
- passed: input.schedulerPlan.schedulerExecutionAllowed === false && input.schedulerPlan.daemonStarted === false && input.schedulerPlan.autoStartDaemon === false && input.schedulerPlan.continuousLoop === false && input.schedulerPlan.cronEnabled === false,
1452
- dispatchAllowed: false,
1453
- },
1454
- {
1455
- name: "one_worker_bounded_readonly_queue",
1456
- passed: workerPool.defaultWorkers === 1 && workerPool.maxWorkers === 1 && workerPool.workerPoolBounded === true && queuePolicy.writeWorkAccepted === false && queuePolicy.claimAtMostOnePerTick === true,
1457
- dispatchAllowed: false,
1458
- },
1459
- {
1460
- name: "lease_heartbeat_timeout_stop_conditions_required",
1461
- passed: leasePolicy.leaseRequired === true && heartbeatPolicy.heartbeatRequired === true && heartbeatPolicy.staleHeartbeatStopCondition === "timeout" && timeoutPolicy.timeoutStopCondition === "timeout" && stopConditions.includes("timeout") && stopConditions.includes("blocked") && stopConditions.includes("fail_loop") && stopConditions.includes("no_ship"),
1462
- dispatchAllowed: false,
1463
- },
1464
- {
1465
- name: "kill_switch_and_retry_stop_clean",
1466
- passed: killSwitch.required === true && killSwitch.checkedBeforeEachTick === true && killSwitch.stopsQueueCleanly === true && retryPolicy.retriesCapped === true && retryPolicy.doNotRetryNoShip === true && retryPolicy.repeatedFailureStopCondition === "fail_loop",
1467
- dispatchAllowed: false,
1468
- },
1469
- {
1470
- name: "strict_budget_required_before_daemon_dispatch",
1471
- passed: budgetPolicy.strictBudgetRequired === true && budgetPolicy.perRunCapsRequired === true && budgetPolicy.perDayCapsRequired === true && budgetPolicy.budgetEnforced === false && budgetPolicy.dispatchBlockedUntilStrictBudgetEnforced === true,
1472
- dispatchAllowed: false,
1473
- },
1474
- {
1475
- name: "always_on_requires_future_approval",
1476
- passed: approvalPolicy.manualStartRequiresApproval === true && approvalPolicy.alwaysOnRequiresApproval === true && approvalPolicy.schedulerAutostartAllowed === false && daemonPolicy.alwaysOnDaemonEnabled === false,
1477
- dispatchAllowed: false,
1478
- },
1479
- ];
1480
- const checks = [
1481
- { name: "scheduler_plan_ready", passed: input.schedulerPlan.schedulerPlanReady === true },
1482
- { name: "daemon_default_disabled", passed: scenarios[0].passed === true },
1483
- { name: "one_worker_bounded_readonly_queue", passed: scenarios[1].passed === true },
1484
- { name: "lease_heartbeat_timeout_stop_conditions_required", passed: scenarios[2].passed === true },
1485
- { name: "kill_switch_and_retry_stop_clean", passed: scenarios[3].passed === true },
1486
- { name: "strict_budget_required_before_daemon_dispatch", passed: scenarios[4].passed === true },
1487
- { name: "always_on_requires_future_approval", passed: scenarios[5].passed === true },
1488
- { name: "run_scope_no_global_autonomy", passed: input.validation.globalAutonomyReady === false && input.validation.globalAutonomyNoShip === true && input.validation.childDispatchAllowed === false && input.validation.productionWritesPerformed === false && input.validation.autoApply === false },
1489
- ];
1490
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1491
- const proof = {
1492
- schema: "zob.autonomous-scheduler-proof-plan.v1",
1493
- runId: input.runId,
1494
- phase: "8B",
1495
- status: failedChecks.length === 0 ? "scheduler_daemon_proof_ready_execution_blocked" : "scheduler_daemon_proof_incomplete",
1496
- schedulerProofReady: failedChecks.length === 0,
1497
- daemonDefaultDisabledProofPassed: scenarios[0].passed === true,
1498
- oneWorkerBoundedProofPassed: scenarios[1].passed === true,
1499
- stopConditionsProofPassed: scenarios[2].passed === true,
1500
- killSwitchRetryProofPassed: scenarios[3].passed === true,
1501
- strictBudgetBeforeDispatchProofPassed: scenarios[4].passed === true,
1502
- alwaysOnApprovalProofPassed: scenarios[5].passed === true,
1503
- finalE2ERequirementCleared: false,
1504
- no_ship: true,
1505
- checks,
1506
- failedChecks,
1507
- scenarios,
1508
- evidenceRefs: [
1509
- `reports/autonomous-runs/${safeFileStem(input.runId)}/scheduler-plan.json`,
1510
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
1511
- ".pi/daemon-policy.json",
1512
- ],
1513
- blockers: [
1514
- "daemon_scheduler_not_started",
1515
- "always_on_daemon_not_enabled",
1516
- "daemon_autostart_disabled",
1517
- "final_e2e_daemon_scheduler_evidence_required",
1518
- ],
1519
- schedulerExecutionAllowed: false,
1520
- daemonStarted: false,
1521
- autoStartDaemon: false,
1522
- continuousLoop: false,
1523
- cronEnabled: false,
1524
- childDispatchAllowed: false,
1525
- liveChildExecution: false,
1526
- writeAdaptersEnabled: false,
1527
- productionWritesPerformed: false,
1528
- autoApply: false,
1529
- noExecutionBeyondSmoke: true,
1530
- globalAutonomyReady: false,
1531
- globalAutonomyNoShip: true,
1532
- bodyStored: false,
1533
- promptBodiesStored: false,
1534
- outputBodiesStored: false,
1535
- };
1536
- if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous scheduler proof plan would store forbidden plaintext body keys");
1537
- return proof;
1538
- }
1539
-
1540
- function buildAutonomousMissionControlPlan(repoRoot: string, input: { runId: string; schedulerPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1541
- const team = loadTeamDefinition(repoRoot, "zob-core");
1542
- const teamErrors = [...team.errors, ...validateTeamDefinition(repoRoot, team.definition)];
1543
- const definition = team.definition;
1544
- const snapshot = definition ? buildMissionControlSnapshot(repoRoot, definition, { runId: input.runId, limit: 5 }) : undefined;
1545
- const communicationAudit = definition ? buildZobCommunicationReadinessAudit(repoRoot, definition) : undefined;
1546
- const transport = buildZobComsTransportReadiness(repoRoot);
1547
- const orchestratorId = definition?.orchestrator.id ?? "orchestrator";
1548
- const commandProposals = definition ? MISSION_CONTROL_COMMANDS.map((command) => buildMissionControlCommandProposal(definition, {
1549
- proposalId: `auto-${sha256(`${input.runId}-${command}`).slice(0, 16)}-${command}`,
1550
- runId: input.runId,
1551
- command,
1552
- targetRole: orchestratorId,
1553
- rationaleHash: sha256(`autonomous mission control ${command}`),
1554
- artifactRefs: [`reports/autonomous-runs/${input.runId}/validation.json`],
1555
- })) : [];
1556
- const directWorkerErrors = definition && definition.workers[0] ? (() => {
1557
- try {
1558
- buildMissionControlCommandProposal(definition, {
1559
- proposalId: `auto-${sha256(`${input.runId}-blocked-worker`).slice(0, 16)}-blocked-worker`,
1560
- runId: input.runId,
1561
- command: "stop",
1562
- targetRole: definition.workers[0].id,
1563
- rationaleHash: sha256("direct worker blocked"),
1564
- });
1565
- return [] as string[];
1566
- } catch (error) {
1567
- return [error instanceof Error ? error.message : String(error)];
1568
- }
1569
- })() : ["no worker role available for direct worker guard"];
1570
- const transportFailedChecks = Array.isArray(transport.failedChecks) ? transport.failedChecks.filter((check): check is string => typeof check === "string") : [];
1571
- const communicationFailedChecks = Array.isArray(communicationAudit?.failedChecks) ? communicationAudit.failedChecks.filter((check): check is string => typeof check === "string") : [];
1572
- const communicationChecks = Array.isArray(communicationAudit?.checks) ? communicationAudit.checks.filter(isRecord) : [];
1573
- const communicationCheckPassed = (name: string): boolean => communicationChecks.some((check) => check.name === name && check.passed === true);
1574
- const livePeerAbsenceBlocksDelivery = transport.mode === "required_local"
1575
- && transport.networkEnabled === false
1576
- && transport.dispatchAllowed === true
1577
- && transportFailedChecks.length > 0
1578
- && transportFailedChecks.every((check) => check === "required_local_live_ready_when_enabled");
1579
- const proposalOnlyCommunicationSafety = communicationAudit?.verdict === "PASS" && communicationAudit.no_ship === false
1580
- || (livePeerAbsenceBlocksDelivery
1581
- && communicationFailedChecks.length > 0
1582
- && communicationFailedChecks.every((check) => check === "transport_policy_safe" || check === "registry_observe_only_available")
1583
- && communicationCheckPassed("topology_guard_active")
1584
- && communicationCheckPassed("worker_to_worker_blocked")
1585
- && communicationCheckPassed("message_body_storage_blocked")
1586
- && communicationCheckPassed("existing_ledgers_body_free")
1587
- && communicationCheckPassed("stale_transport_not_completion")
1588
- && communicationCheckPassed("dashboard_commands_are_proposals")
1589
- && communicationCheckPassed("dashboard_direct_worker_commands_blocked"));
1590
- const requiredLocalTransportSafeForNoDispatchPlan = transport.mode === "required_local"
1591
- && transport.verdict === "PASS"
1592
- && transport.noExecution === true
1593
- && transport.networkEnabled === false
1594
- && transport.dispatchAllowed === true;
1595
- const transportSafeForAutonomySmoke = transport.networkEnabled === false
1596
- && (
1597
- (transport.verdict === "PASS" && transport.enabled === false && transport.dispatchAllowed === false)
1598
- || requiredLocalTransportSafeForNoDispatchPlan
1599
- || livePeerAbsenceBlocksDelivery
1600
- || (transport.mode === "required_local" && transport.verdict === "PASS")
1601
- );
1602
- const checks = [
1603
- { name: "team_topology_valid", passed: teamErrors.length === 0 },
1604
- { name: "dashboard_snapshot_available", passed: snapshot?.schema === "zob.mission-control-snapshot.v1" },
1605
- { name: "communication_readiness_pass", passed: proposalOnlyCommunicationSafety, detail: { readinessVerdict: communicationAudit?.verdict ?? "FAIL", livePeerAbsenceBlocksDelivery, livePeerReadyRequiredForDispatch: true, proposalOnlyNoDispatchPlan: true } },
1606
- { name: "transport_disabled", passed: transportSafeForAutonomySmoke, detail: { transportVerdict: transport.verdict, requiredLocalTransportSafeForNoDispatchPlan, livePeerAbsenceBlocksDelivery, dispatchAllowedInPlan: false, networkComsEnabledInPlan: false } },
1607
- { name: "commands_proposal_only", passed: commandProposals.length === MISSION_CONTROL_COMMANDS.length && commandProposals.every((proposal) => proposal.proposalOnly === true && proposal.parentOwned === true && proposal.directWorkerWrite === false && proposal.transportDispatch === false && proposal.networkTransport === false) },
1608
- { name: "direct_worker_commands_blocked", passed: directWorkerErrors.some((error) => error.includes("direct worker")) },
1609
- { name: "no_body_storage", passed: commandProposals.every((proposal) => proposal.bodyStored === false && proposal.promptBodiesStored === false && proposal.outputBodiesStored === false) },
1610
- { name: "scheduler_still_disabled", passed: input.schedulerPlan.schedulerExecutionAllowed === false && input.schedulerPlan.daemonStarted === false },
1611
- ];
1612
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1613
- const plan = {
1614
- schema: "zob.autonomous-mission-control-plan.v1",
1615
- runId: input.runId,
1616
- missionControlPlanReady: failedChecks.length === 0,
1617
- failedChecks,
1618
- checks,
1619
- dashboard: {
1620
- snapshotAvailable: snapshot?.schema === "zob.mission-control-snapshot.v1",
1621
- dashboardReads: ["runs", "factories", "queue", "budget", "model_routing", "coms", "blockers", "autonomy_status"],
1622
- latestRunLimit: 5,
1623
- directWorkerWrites: false,
1624
- bypassesParentGates: false,
1625
- networkComsEnabled: false,
1626
- snapshotSchema: snapshot?.schema,
1627
- },
1628
- commandPolicy: {
1629
- proposalOnly: true,
1630
- parentOwned: true,
1631
- directWorkerWrites: false,
1632
- transportDispatch: false,
1633
- networkTransport: false,
1634
- allowedCommands: [...MISSION_CONTROL_COMMANDS],
1635
- proposalCount: commandProposals.length,
1636
- proposalHashes: commandProposals.map((proposal) => proposal.commandHash).filter((hash): hash is string => typeof hash === "string"),
1637
- directWorkerCommandBlocked: directWorkerErrors.some((error) => error.includes("direct worker")),
1638
- },
1639
- comsPolicy: {
1640
- readinessVerdict: communicationAudit?.verdict ?? "FAIL",
1641
- proposalOnlyReadinessAccepted: proposalOnlyCommunicationSafety,
1642
- livePeerAbsenceBlocksDelivery,
1643
- livePeerReadyRequiredForDispatch: true,
1644
- topologyGuardActive: Array.isArray(communicationAudit?.checks) && communicationAudit.checks.some((check) => isRecord(check) && check.name === "topology_guard_active" && check.passed === true),
1645
- hashOnlyLedgers: true,
1646
- workerToWorkerFreeChatAllowed: false,
1647
- rawPromptOutputStored: false,
1648
- bodyStored: false,
1649
- promptBodiesStored: false,
1650
- outputBodiesStored: false,
1651
- },
1652
- transportPolicy: {
1653
- enabled: false,
1654
- localDispatchEnabled: false,
1655
- dispatchAllowed: false,
1656
- networkEnabled: false,
1657
- stalePeerCountsAsCompletion: false,
1658
- responseBodiesStored: false,
1659
- livePeerAbsenceBlocksDelivery,
1660
- livePeerReadyRequiredForDispatch: true,
1661
- futureHeartbeatRequired: true,
1662
- futureStaleDetectionRequired: true,
1663
- futureActiveWorkerRegistryRequired: true,
1664
- futureResponseCaptureRequired: true,
1665
- },
1666
- autonomyStatus: {
1667
- globalAutonomyReady: false,
1668
- globalAutonomyNoShip: true,
1669
- noGlobalAutonomyClaim: true,
1670
- },
1671
- schedulerExecutionAllowed: false,
1672
- daemonStarted: false,
1673
- childDispatchAllowed: false,
1674
- directWorkerWrites: false,
1675
- transportDispatch: false,
1676
- networkComsEnabled: false,
1677
- productionWritesPerformed: false,
1678
- autoApply: false,
1679
- globalAutonomyReady: false,
1680
- globalAutonomyNoShip: true,
1681
- bodyStored: false,
1682
- promptBodiesStored: false,
1683
- outputBodiesStored: false,
1684
- };
1685
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous mission control plan would store forbidden plaintext body keys");
1686
- return plan;
1687
- }
1688
-
1689
- function buildAutonomousMissionControlProofPlan(input: { runId: string; missionControlPlan: Record<string, unknown>; schedulerProofPlan: Record<string, unknown>; modelRoutingProofPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1690
- const commandPolicy = isRecord(input.missionControlPlan.commandPolicy) ? input.missionControlPlan.commandPolicy : {};
1691
- const comsPolicy = isRecord(input.missionControlPlan.comsPolicy) ? input.missionControlPlan.comsPolicy : {};
1692
- const transportPolicy = isRecord(input.missionControlPlan.transportPolicy) ? input.missionControlPlan.transportPolicy : {};
1693
- const allowedCommands = Array.isArray(commandPolicy.allowedCommands) ? commandPolicy.allowedCommands.filter((command): command is string => typeof command === "string") : [];
1694
- const proposalHashes = Array.isArray(commandPolicy.proposalHashes) ? commandPolicy.proposalHashes.filter((hash): hash is string => typeof hash === "string") : [];
1695
- const proposalHashesValid = proposalHashes.length === MISSION_CONTROL_COMMANDS.length && proposalHashes.every((hash) => /^[a-f0-9]{64}$/.test(hash));
1696
- const allMissionCommandsCovered = MISSION_CONTROL_COMMANDS.every((command) => allowedCommands.includes(command));
1697
- const approvalCommandAvailable = allowedCommands.includes("approve");
1698
- const scenarios = [
1699
- {
1700
- name: "proposal_only_commands_parent_owned",
1701
- passed: commandPolicy.proposalOnly === true && commandPolicy.parentOwned === true && commandPolicy.transportDispatch === false && commandPolicy.networkTransport === false && commandPolicy.proposalCount === MISSION_CONTROL_COMMANDS.length && allMissionCommandsCovered && proposalHashesValid,
1702
- dispatchAllowed: false,
1703
- },
1704
- {
1705
- name: "topology_hash_only_comms",
1706
- passed: comsPolicy.topologyGuardActive === true && comsPolicy.hashOnlyLedgers === true && comsPolicy.workerToWorkerFreeChatAllowed === false && comsPolicy.rawPromptOutputStored === false && comsPolicy.bodyStored === false && comsPolicy.promptBodiesStored === false && comsPolicy.outputBodiesStored === false,
1707
- dispatchAllowed: false,
1708
- },
1709
- {
1710
- name: "direct_worker_commands_blocked",
1711
- passed: commandPolicy.directWorkerWrites === false && commandPolicy.directWorkerCommandBlocked === true && input.missionControlPlan.directWorkerWrites === false,
1712
- dispatchAllowed: false,
1713
- },
1714
- {
1715
- name: "live_transport_and_network_disabled",
1716
- passed: transportPolicy.enabled === false && transportPolicy.localDispatchEnabled === false && transportPolicy.dispatchAllowed === false && transportPolicy.networkEnabled === false && input.missionControlPlan.transportDispatch === false && input.missionControlPlan.networkComsEnabled === false,
1717
- dispatchAllowed: false,
1718
- },
1719
- {
1720
- name: "approval_required_before_live_global_routing",
1721
- passed: approvalCommandAvailable && commandPolicy.proposalOnly === true && commandPolicy.parentOwned === true && input.modelRoutingProofPlan.globalLiveRoutingEnabled === false && input.modelRoutingProofPlan.liveAutonomousRoutingApplied === false && input.modelRoutingProofPlan.finalE2ERequirementCleared === false && input.modelRoutingProofPlan.no_ship === true,
1722
- dispatchAllowed: false,
1723
- },
1724
- {
1725
- name: "post_8b_scheduler_still_blocked",
1726
- passed: input.schedulerProofPlan.schedulerProofReady === true && input.schedulerProofPlan.schedulerExecutionAllowed === false && input.schedulerProofPlan.daemonStarted === false && input.schedulerProofPlan.childDispatchAllowed === false,
1727
- dispatchAllowed: false,
1728
- },
1729
- ];
1730
- const checks = [
1731
- { name: "mission_control_plan_ready", passed: input.missionControlPlan.missionControlPlanReady === true },
1732
- { name: "proposal_only_commands_parent_owned", passed: scenarios[0].passed === true },
1733
- { name: "topology_hash_only_comms", passed: scenarios[1].passed === true },
1734
- { name: "direct_worker_commands_blocked", passed: scenarios[2].passed === true },
1735
- { name: "live_transport_and_network_disabled", passed: scenarios[3].passed === true },
1736
- { name: "approval_required_before_live_global_routing", passed: scenarios[4].passed === true },
1737
- { name: "post_8b_scheduler_still_blocked", passed: scenarios[5].passed === true },
1738
- { name: "run_scope_no_global_autonomy", passed: input.validation.globalAutonomyReady === false && input.validation.globalAutonomyNoShip === true && input.validation.childDispatchAllowed === false && input.validation.productionWritesPerformed === false && input.validation.autoApply === false && input.missionControlPlan.globalAutonomyReady === false && input.missionControlPlan.globalAutonomyNoShip === true },
1739
- ];
1740
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1741
- const proof = {
1742
- schema: "zob.autonomous-mission-control-proof-plan.v1",
1743
- runId: input.runId,
1744
- phase: "9B",
1745
- status: failedChecks.length === 0 ? "mission_control_comms_proof_ready_execution_blocked" : "mission_control_comms_proof_incomplete",
1746
- missionControlProofReady: failedChecks.length === 0,
1747
- proposalOnlyCommandsProofPassed: scenarios[0].passed === true,
1748
- topologyHashOnlyCommsProofPassed: scenarios[1].passed === true,
1749
- directWorkerCommandsBlockedProofPassed: scenarios[2].passed === true,
1750
- liveTransportNetworkDisabledProofPassed: scenarios[3].passed === true,
1751
- liveGlobalRoutingApprovalProofPassed: scenarios[4].passed === true,
1752
- post8bSchedulerBlockedProofPassed: scenarios[5].passed === true,
1753
- finalE2ERequirementCleared: false,
1754
- no_ship: true,
1755
- checks,
1756
- failedChecks,
1757
- scenarios,
1758
- commandProposalProof: {
1759
- proposalOnly: true,
1760
- parentOwned: true,
1761
- allowedCommands,
1762
- proposalCount: commandPolicy.proposalCount,
1763
- proposalHashesValid,
1764
- directWorkerCommandBlocked: commandPolicy.directWorkerCommandBlocked === true,
1765
- transportDispatch: false,
1766
- networkTransport: false,
1767
- },
1768
- comsTopologyProof: {
1769
- topologyGuardActive: comsPolicy.topologyGuardActive === true,
1770
- hashOnlyLedgers: comsPolicy.hashOnlyLedgers === true,
1771
- workerToWorkerFreeChatAllowed: false,
1772
- rawPromptOutputStored: false,
1773
- bodyStored: false,
1774
- promptBodiesStored: false,
1775
- outputBodiesStored: false,
1776
- },
1777
- transportProof: {
1778
- enabled: false,
1779
- localDispatchEnabled: false,
1780
- dispatchAllowed: false,
1781
- networkEnabled: false,
1782
- stalePeerCountsAsCompletion: false,
1783
- responseBodiesStored: false,
1784
- futureHeartbeatRequired: transportPolicy.futureHeartbeatRequired === true,
1785
- futureStaleDetectionRequired: transportPolicy.futureStaleDetectionRequired === true,
1786
- futureActiveWorkerRegistryRequired: transportPolicy.futureActiveWorkerRegistryRequired === true,
1787
- futureResponseCaptureRequired: transportPolicy.futureResponseCaptureRequired === true,
1788
- },
1789
- routingApprovalPolicy: {
1790
- approvalCommandAvailable,
1791
- approvalCommandProposalOnly: true,
1792
- liveRoutingRequiresApproval: true,
1793
- globalRoutingRequiresApproval: true,
1794
- approvalDoesNotEnableRoutingInThisRun: true,
1795
- liveRoutingAllowedAfterThisProof: false,
1796
- globalLiveRoutingAllowedAfterThisProof: false,
1797
- },
1798
- evidenceRefs: [
1799
- `reports/autonomous-runs/${safeFileStem(input.runId)}/mission-control-plan.json`,
1800
- `reports/autonomous-runs/${safeFileStem(input.runId)}/scheduler-proof-plan.json`,
1801
- `reports/autonomous-runs/${safeFileStem(input.runId)}/model-routing-proof-plan.json`,
1802
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
1803
- ".pi/teams/zob-core.json",
1804
- ".pi/mission-control/zob_coms_transport.json",
1805
- ".pi/coms/messages.jsonl",
1806
- ".pi/coms/status.jsonl",
1807
- ],
1808
- blockers: [
1809
- "live_transport_not_enabled",
1810
- "network_coms_disabled",
1811
- "global_live_routing_approval_not_granted",
1812
- "final_e2e_mission_control_live_comms_evidence_required",
1813
- ],
1814
- schedulerExecutionAllowed: false,
1815
- daemonStarted: false,
1816
- childDispatchAllowed: false,
1817
- liveChildExecution: false,
1818
- directWorkerWrites: false,
1819
- transportDispatch: false,
1820
- networkComsEnabled: false,
1821
- liveRoutingEnabled: false,
1822
- globalLiveRoutingEnabled: false,
1823
- productionWritesPerformed: false,
1824
- autoApply: false,
1825
- noExecutionBeyondSmoke: true,
1826
- globalAutonomyReady: false,
1827
- globalAutonomyNoShip: true,
1828
- bodyStored: false,
1829
- promptBodiesStored: false,
1830
- outputBodiesStored: false,
1831
- };
1832
- if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous mission control proof plan would store forbidden plaintext body keys");
1833
- return proof;
1834
- }
1835
-
1836
- function buildAutonomousSandboxApplyPlan(repoRoot: string, input: { runId: string; missionControlPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
1837
- const isolatedPath = "reports/sandbox-isolated-execution-smoke.json";
1838
- const reviewPath = "reports/sandbox-diff-review-gate-smoke.json";
1839
- const simulationPath = "reports/sandbox-apply-simulation-smoke.json";
1840
- const preflightPath = "reports/sandbox-manual-apply-preflight-smoke.json";
1841
- const isolatedRead = readJsonArtifact(join(repoRoot, isolatedPath));
1842
- const reviewRead = readJsonArtifact(join(repoRoot, reviewPath));
1843
- const simulationRead = readJsonArtifact(join(repoRoot, simulationPath));
1844
- const preflightRead = readJsonArtifact(join(repoRoot, preflightPath));
1845
- const isolated = isRecord(isolatedRead.parsed) ? isolatedRead.parsed : {};
1846
- const review = isRecord(reviewRead.parsed) ? reviewRead.parsed : {};
1847
- const simulation = isRecord(simulationRead.parsed) ? simulationRead.parsed : {};
1848
- const preflight = isRecord(preflightRead.parsed) ? preflightRead.parsed : {};
1849
- const isolatedDiffHash = typeof isolated.diffHash === "string" ? isolated.diffHash : undefined;
1850
- const reviewDiffHash = typeof review.diffHash === "string" ? review.diffHash : undefined;
1851
- const simulationDiffHash = typeof simulation.diffHash === "string" ? simulation.diffHash : undefined;
1852
- const diffHashesMatch = Boolean(isolatedDiffHash && isolatedDiffHash === reviewDiffHash && reviewDiffHash === simulationDiffHash);
1853
- const checks = [
1854
- { name: "isolated_temp_workspace_executed", passed: isolated.status === "executed_in_sandbox" && isolated.isolatedExecutionPerformed === true && isolated.productionWritesPerformed === false },
1855
- { name: "diff_hash_consistent", passed: diffHashesMatch },
1856
- { name: "oracle_diff_review_passed", passed: review.status === "diff_review_passed" && review.reviewPassed === true && review.applyReadyUnlocked === true && review.applyPerformed === false },
1857
- { name: "rollback_metadata_required", passed: isolated.rollbackPrepared === true && simulation.rollbackPrepared === true && isolated.rollbackApplied === false && simulation.rollbackApplied === false },
1858
- { name: "apply_simulation_temp_workspace_only", passed: simulation.status === "simulated_apply_in_temp_workspace" && simulation.simulatedApplyPerformed === true && simulation.tempTargetWorkspaceScoped === true && simulation.productionWritesPerformed === false },
1859
- { name: "manual_apply_preflight_packet_ready", passed: preflight.status === "manual_apply_preflight_passed" && preflight.manualApplyPreflightPassed === true && preflight.executionAllowedByThisTool === false && preflight.realApplyExecuted === false && preflight.productionWritesPerformed === false },
1860
- { name: "manual_approval_required", passed: isolated.manualApplyRequired === true && review.manualApplyRequired === true && simulation.manualApplyRequired === true && preflight.manualApplyRequired === true && isolated.humanApprovalRequired === true && review.humanApprovalRequired === true && simulation.humanApprovalRequired === true && preflight.humanApprovalRequired === true },
1861
- { name: "auto_apply_disabled", passed: isolated.autoApply === false && review.autoApply === false && simulation.autoApply === false && preflight.autoApply === false },
1862
- { name: "mission_control_still_proposal_only", passed: input.missionControlPlan.directWorkerWrites === false && input.missionControlPlan.transportDispatch === false },
1863
- ];
1864
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1865
- const plan = {
1866
- schema: "zob.autonomous-sandbox-apply-plan.v1",
1867
- runId: input.runId,
1868
- sandboxApplyPlanReady: failedChecks.length === 0,
1869
- failedChecks,
1870
- checks,
1871
- evidenceRefs: [isolatedPath, reviewPath, simulationPath, preflightPath],
1872
- evidenceHashes: {
1873
- isolatedExecution: isolatedRead.hash,
1874
- diffReviewGate: reviewRead.hash,
1875
- applySimulation: simulationRead.hash,
1876
- manualApplyPreflight: preflightRead.hash,
1877
- },
1878
- sandboxRunIdHash: typeof isolated.runId === "string" ? sha256(isolated.runId) : undefined,
1879
- isolatedTempWorkspace: {
1880
- required: true,
1881
- executed: isolated.isolatedExecutionPerformed === true,
1882
- workspacePathStored: false,
1883
- productionWritesPerformed: false,
1884
- },
1885
- applyPlan: {
1886
- required: true,
1887
- plaintextContentStored: false,
1888
- allowedPathsRequired: true,
1889
- forbiddenPathsRequired: true,
1890
- writeTargetsMustExcludeSecretsVendorGenerated: true,
1891
- },
1892
- diffGate: {
1893
- diffHashRequired: true,
1894
- diffHash: isolatedDiffHash,
1895
- diffHashesMatch,
1896
- changedPathCount: Array.isArray(isolated.changedPaths) ? isolated.changedPaths.length : undefined,
1897
- rawDiffStored: false,
1898
- },
1899
- oracleDiffReview: {
1900
- required: true,
1901
- reviewPassed: review.reviewPassed === true,
1902
- applyReadyUnlocked: review.applyReadyUnlocked === true,
1903
- liveOracleDispatchRequiredBeforeRealApply: true,
1904
- },
1905
- rollbackPolicy: {
1906
- rollbackMetadataRequired: true,
1907
- rollbackPrepared: isolated.rollbackPrepared === true && simulation.rollbackPrepared === true,
1908
- rollbackApplied: false,
1909
- rollbackSnapshotRequiredBeforeMainApply: true,
1910
- },
1911
- approvalPolicy: {
1912
- manualApprovalRequired: true,
1913
- humanApprovalRequired: true,
1914
- approvalMetadataHashOnly: true,
1915
- approvedForMainWorkspaceApply: false,
1916
- },
1917
- applySimulation: {
1918
- required: true,
1919
- simulatedApplyPerformed: simulation.simulatedApplyPerformed === true,
1920
- tempTargetWorkspaceScoped: simulation.tempTargetWorkspaceScoped === true,
1921
- productionWritesPerformed: false,
1922
- autoApply: false,
1923
- },
1924
- manualApplyPreflight: {
1925
- required: true,
1926
- preflightPassed: preflight.manualApplyPreflightPassed === true,
1927
- executionAllowedByThisTool: false,
1928
- confirmationPhraseMatched: isRecord(preflight.gates) && preflight.gates.confirmationPhraseMatched === true,
1929
- approvalHashOnly: isRecord(preflight.gates) && preflight.gates.approvalHashOnly === true,
1930
- realApplyExecuted: false,
1931
- productionWritesPerformed: false,
1932
- autoApply: false,
1933
- },
1934
- mainWorkspaceApply: {
1935
- realApplyAllowed: false,
1936
- realApplyExecuted: false,
1937
- productionWritesPerformed: false,
1938
- autoApply: false,
1939
- reason: "phase_10b_manual_apply_preflight_only_no_main_workspace_apply",
1940
- requiredBeforeRealApply: ["fresh_oracle_diff_review_PASS", "rollback_snapshot", "manual_human_approval", "strict_budget_gate", "allowed_paths_write_policy", "separate_manual_apply_executor", "post_apply_validation_oracle"],
1941
- },
1942
- writeSafety: {
1943
- noDirectAutonomousWritesToMainWorkspace: true,
1944
- noAutoApplyByDefault: true,
1945
- noSecretsVendorGeneratedPaths: true,
1946
- rollbackMetadataRequiredBeforeScalingWrites: true,
1947
- },
1948
- childDispatchAllowed: false,
1949
- daemonStarted: false,
1950
- directWorkerWrites: false,
1951
- transportDispatch: false,
1952
- networkComsEnabled: false,
1953
- productionWritesPerformed: false,
1954
- autoApply: false,
1955
- realApplyExecuted: false,
1956
- globalAutonomyReady: false,
1957
- globalAutonomyNoShip: true,
1958
- bodyStored: false,
1959
- promptBodiesStored: false,
1960
- outputBodiesStored: false,
1961
- };
1962
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous sandbox apply plan would store forbidden plaintext body keys");
1963
- return plan;
1964
- }
1965
-
1966
- function expectedAutonomousCurrentSourceFingerprintFiles(factorySelection: Record<string, unknown>): string[] {
1967
- const selectedFactory = typeof factorySelection.selectedFactory === "string" ? factorySelection.selectedFactory : undefined;
1968
- const factoryFiles = selectedFactory ? [`.pi/factories/${selectedFactory}/factory.json`, `.pi/factories/${selectedFactory}/smoke-manifest.json`] : [];
1969
- return [...AUTONOMOUS_CURRENT_SOURCE_FINGERPRINT_FILES, ...factoryFiles].filter((file, index, items) => items.indexOf(file) === index).sort();
1970
- }
1971
-
1972
- function stringRecord(value: unknown): Record<string, string> {
1973
- if (!isRecord(value)) return {};
1974
- return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
1975
- }
1976
-
1977
- function sameStringArray(left: unknown, right: string[]): boolean {
1978
- return Array.isArray(left) && left.every((item) => typeof item === "string") && JSON.stringify([...left].sort()) === JSON.stringify([...right].sort());
1979
- }
1980
-
1981
- function buildAutonomousCurrentSourceFingerprint(repoRoot: string, input: { runId: string; factorySelection: Record<string, unknown> }): Record<string, unknown> {
1982
- const selectedFactory = typeof input.factorySelection.selectedFactory === "string" ? input.factorySelection.selectedFactory : undefined;
1983
- const sourceFiles = expectedAutonomousCurrentSourceFingerprintFiles(input.factorySelection);
1984
- const missingFiles = sourceFiles.filter((file) => !existsSync(join(repoRoot, file)));
1985
- const fileHashes = Object.fromEntries(sourceFiles.filter((file) => existsSync(join(repoRoot, file))).map((file) => [file, sha256(readFileSync(join(repoRoot, file), "utf8"))]));
1986
- const fingerprintHash = sha256(JSON.stringify(fileHashes));
1987
- const fingerprint = {
1988
- schema: "zob.autonomous-current-source-fingerprint.v1",
1989
- runId: input.runId,
1990
- phase: "11C",
1991
- status: missingFiles.length === 0 ? "current_source_fingerprint_captured" : "blocked_missing_source_files",
1992
- currentSourceFingerprintReady: missingFiles.length === 0,
1993
- currentSourceFingerprintCaptured: missingFiles.length === 0,
1994
- noMockCurrentSourceE2EProved: false,
1995
- finalE2EProofReady: false,
1996
- sourceFiles,
1997
- sourceFileCount: sourceFiles.length,
1998
- hashedFileCount: Object.keys(fileHashes).length,
1999
- missingFiles,
2000
- fileHashes,
2001
- fingerprintHash,
2002
- selectedFactory,
2003
- evidencePolicy: {
2004
- hashOnly: true,
2005
- sourceBodiesStored: false,
2006
- currentSourceOnly: true,
2007
- rehashRequiredBeforeFinalE2E: true,
2008
- noMockProofRequiredSeparately: true,
2009
- },
2010
- safety: {
2011
- noExecution: true,
2012
- childDispatchAllowed: false,
2013
- daemonStarted: false,
2014
- productionWritesPerformed: false,
2015
- autoApply: false,
2016
- networkAccessed: false,
2017
- globalAutonomyReady: false,
2018
- globalAutonomyNoShip: true,
2019
- },
2020
- bodyStored: false,
2021
- promptBodiesStored: false,
2022
- outputBodiesStored: false,
2023
- };
2024
- if (hasForbiddenBodyKeys(fingerprint)) throw new Error("autonomous current-source fingerprint would store forbidden plaintext body keys");
2025
- return fingerprint;
2026
- }
2027
-
2028
- function validateAutonomousCurrentSourceFingerprintFreshness(repoRoot: string, fingerprint: Record<string, unknown>, factorySelection: Record<string, unknown>): Record<string, unknown> {
2029
- const expectedSourceFiles = expectedAutonomousCurrentSourceFingerprintFiles(factorySelection);
2030
- const currentMissingFiles = expectedSourceFiles.filter((file) => !existsSync(join(repoRoot, file)));
2031
- const currentFileHashes = Object.fromEntries(expectedSourceFiles.filter((file) => existsSync(join(repoRoot, file))).map((file) => [file, sha256(readFileSync(join(repoRoot, file), "utf8"))]));
2032
- const storedFileHashes = stringRecord(fingerprint.fileHashes);
2033
- const currentFingerprintHash = sha256(JSON.stringify(currentFileHashes));
2034
- const storedFingerprintHash = typeof fingerprint.fingerprintHash === "string" ? fingerprint.fingerprintHash : undefined;
2035
- const hashValuesValid = Object.values(storedFileHashes).every((hash) => /^[a-f0-9]{64}$/.test(hash));
2036
- const expectedHashKeys = Object.keys(currentFileHashes).sort();
2037
- const storedHashKeys = Object.keys(storedFileHashes).sort();
2038
- const fileHashesMatch = JSON.stringify(expectedHashKeys) === JSON.stringify(storedHashKeys) && expectedHashKeys.every((file) => storedFileHashes[file] === currentFileHashes[file]);
2039
- const sourceFilesMatch = sameStringArray(fingerprint.sourceFiles, expectedSourceFiles);
2040
- const missingFilesMatch = sameStringArray(fingerprint.missingFiles, currentMissingFiles);
2041
- const fingerprintHashMatches = storedFingerprintHash === currentFingerprintHash;
2042
- const fresh = fingerprint.schema === "zob.autonomous-current-source-fingerprint.v1"
2043
- && fingerprint.currentSourceFingerprintReady === true
2044
- && fingerprint.currentSourceFingerprintCaptured === true
2045
- && sourceFilesMatch
2046
- && missingFilesMatch
2047
- && currentMissingFiles.length === 0
2048
- && hashValuesValid
2049
- && fileHashesMatch
2050
- && fingerprintHashMatches
2051
- && fingerprint.noMockCurrentSourceE2EProved === false;
2052
- const result = {
2053
- schema: "zob.autonomous-current-source-fingerprint-freshness.v1",
2054
- fresh,
2055
- sourceFilesMatch,
2056
- missingFilesMatch,
2057
- hashValuesValid,
2058
- fileHashesMatch,
2059
- fingerprintHashMatches,
2060
- currentFingerprintHash,
2061
- storedFingerprintHash,
2062
- expectedSourceFileCount: expectedSourceFiles.length,
2063
- storedSourceFileCount: Array.isArray(fingerprint.sourceFiles) ? fingerprint.sourceFiles.length : 0,
2064
- expectedHashedFileCount: expectedHashKeys.length,
2065
- storedHashedFileCount: storedHashKeys.length,
2066
- currentMissingFiles,
2067
- noMockCurrentSourceE2EProved: false,
2068
- noExecution: true,
2069
- childDispatchAllowed: false,
2070
- globalAutonomyReady: false,
2071
- globalAutonomyNoShip: true,
2072
- bodyStored: false,
2073
- promptBodiesStored: false,
2074
- outputBodiesStored: false,
2075
- };
2076
- if (hasForbiddenBodyKeys(result)) throw new Error("autonomous current-source freshness validation would store forbidden plaintext body keys");
2077
- return result;
2078
- }
2079
-
2080
- function buildAutonomousFinalNoShipOracle(input: { runId: string; finalE2EProofPlan: Record<string, unknown>; currentSourceFingerprint: Record<string, unknown> }): Record<string, unknown> {
2081
- const blockers = Array.isArray(input.finalE2EProofPlan.blockers) ? input.finalE2EProofPlan.blockers.filter((blocker): blocker is string => typeof blocker === "string") : ["final_e2e_proof_plan_missing_blockers"];
2082
- const checks = [
2083
- { name: "final_e2e_proof_ready", passed: input.finalE2EProofPlan.finalE2EProofReady === true },
2084
- { name: "final_e2e_no_ship_cleared", passed: input.finalE2EProofPlan.no_ship === false },
2085
- { name: "no_mock_current_source_e2e_proved", passed: isRecord(input.finalE2EProofPlan.currentSourceProof) && input.finalE2EProofPlan.currentSourceProof.noMockCurrentSourceE2EProved === true },
2086
- { name: "current_source_fingerprint_captured", passed: input.currentSourceFingerprint.currentSourceFingerprintCaptured === true && typeof input.currentSourceFingerprint.fingerprintHash === "string" },
2087
- { name: "pilot_executed", passed: isRecord(input.finalE2EProofPlan.promotionStatus) && input.finalE2EProofPlan.promotionStatus.pilotExecuted === true },
2088
- { name: "batch_executed", passed: isRecord(input.finalE2EProofPlan.promotionStatus) && input.finalE2EProofPlan.promotionStatus.batchExecuted === true },
2089
- { name: "live_strict_budget_enforced", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.strictBudgetEnforced === true },
2090
- { name: "live_model_routing_enabled", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.liveModelRoutingEnabled === true },
2091
- { name: "daemon_started", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.daemonStarted === true },
2092
- { name: "real_apply_executed", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.sandboxRealApplyExecuted === true },
2093
- { name: "global_ready_sentinel_allowed", passed: isRecord(input.finalE2EProofPlan.sentinelPolicy) && input.finalE2EProofPlan.sentinelPolicy.globalReadySentinelAllowed === true },
2094
- ];
2095
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
2096
- const oracle = {
2097
- schema: "zob.autonomous-final-no-ship-oracle.v1",
2098
- runId: input.runId,
2099
- phase: "11E",
2100
- oracleType: "deterministic_structural_no_ship",
2101
- verdict: "FAIL",
2102
- no_ship: true,
2103
- finalOracleReady: false,
2104
- finalOraclePass: false,
2105
- finalE2EProofReady: false,
2106
- evidenceChecked: true,
2107
- checks,
2108
- failedChecks,
2109
- blockers,
2110
- evidenceRefs: [
2111
- `reports/autonomous-runs/${safeFileStem(input.runId)}/final-e2e-proof-plan.json`,
2112
- `reports/autonomous-runs/${safeFileStem(input.runId)}/current-source-fingerprint.json`,
2113
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
2114
- ],
2115
- decision: {
2116
- globalAutonomyReady: false,
2117
- globalAutonomyNoShip: true,
2118
- claim100PercentAutonomyAllowed: false,
2119
- writeGlobalReadySentinelAllowed: false,
2120
- writeFinalDoneSentinelAllowed: false,
2121
- },
2122
- childDispatchAllowed: false,
2123
- daemonStarted: false,
2124
- directWorkerWrites: false,
2125
- transportDispatch: false,
2126
- networkComsEnabled: false,
2127
- productionWritesPerformed: false,
2128
- autoApply: false,
2129
- realApplyExecuted: false,
2130
- liveRoutingEnabled: false,
2131
- budgetEnforced: false,
2132
- globalAutonomyReady: false,
2133
- globalAutonomyNoShip: true,
2134
- bodyStored: false,
2135
- promptBodiesStored: false,
2136
- outputBodiesStored: false,
2137
- };
2138
- if (hasForbiddenBodyKeys(oracle)) throw new Error("autonomous final no-ship oracle would store forbidden plaintext body keys");
2139
- return oracle;
2140
- }
2141
-
2142
- function buildAutonomousFinalE2EProofPlan(repoRoot: string, input: { runId: string; runtimeGates: Record<string, unknown>; strictBudgetProofPlan: Record<string, unknown>; modelRoutingProofPlan: Record<string, unknown>; modelRoutingPlan: Record<string, unknown>; factorySelection: Record<string, unknown>; factoryRunRef: Record<string, unknown>; oracleReview: Record<string, unknown>; promotionPlan: Record<string, unknown>; promotionProofPlan: Record<string, unknown>; schedulerPlan: Record<string, unknown>; schedulerProofPlan: Record<string, unknown>; missionControlPlan: Record<string, unknown>; missionControlProofPlan: Record<string, unknown>; sandboxApplyPlan: Record<string, unknown>; currentSourceFingerprint: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
2143
- const safeRunId = safeFileStem(input.runId);
2144
- const runRoot = `reports/autonomous-runs/${safeRunId}`;
2145
- const globalReadySentinelPath = join(repoRoot, runRoot, "GLOBAL_AUTONOMY_READY.sentinel");
2146
- const smokeGate = isRecord(input.promotionPlan.smokeGate) ? input.promotionPlan.smokeGate : {};
2147
- const pilotGate = isRecord(input.promotionPlan.pilotGate) ? input.promotionPlan.pilotGate : {};
2148
- const batchGate = isRecord(input.promotionPlan.batchGate) ? input.promotionPlan.batchGate : {};
2149
- const strictBudgetGate = isRecord(input.runtimeGates.autonomousStrictBudgetGate) ? input.runtimeGates.autonomousStrictBudgetGate : {};
2150
- const mainWorkspaceApply = isRecord(input.sandboxApplyPlan.mainWorkspaceApply) ? input.sandboxApplyPlan.mainWorkspaceApply : {};
2151
- const globalReadySentinelPresent = existsSync(globalReadySentinelPath);
2152
- const proofSteps = [
2153
- { name: "user_need", state: "captured", evidenceRef: `${runRoot}/spec-gate.json`, dispatchAllowed: false },
2154
- { name: "spec_lock", state: "proved", evidenceRef: `${runRoot}/spec-gate.json`, dispatchAllowed: false },
2155
- { name: "context_scope", state: "proved", evidenceRef: `${runRoot}/context-scope.json`, dispatchAllowed: false },
2156
- { name: "context_pack", state: "proved", evidenceRef: `${runRoot}/context-pack.json`, dispatchAllowed: false },
2157
- { name: "strict_budget", state: input.strictBudgetProofPlan.strictBudgetProofReady === true ? "proved_run_scope_gate_only" : "blocked", evidenceRef: `${runRoot}/strict-budget-proof-plan.json`, blocker: "live_autonomous_strict_budget_not_enforced", dispatchAllowed: false },
2158
- { name: "model_routing", state: input.modelRoutingProofPlan.modelRoutingProofReady === true ? "proved_run_scope_gate_only" : "blocked", evidenceRef: `${runRoot}/model-routing-proof-plan.json`, blocker: "live_autonomous_model_routing_not_enabled", dispatchAllowed: false },
2159
- { name: "factory_selection", state: "proved", evidenceRef: `${runRoot}/factory-selection.json`, dispatchAllowed: false },
2160
- { name: "smoke", state: input.factoryRunRef.status === "done" ? "proved" : "blocked", evidenceRef: `${runRoot}/factory-run-ref.json`, dispatchAllowed: false },
2161
- { name: "smoke_oracle", state: input.oracleReview.verdict === "PASS" && input.oracleReview.no_ship === false ? "proved" : "blocked", evidenceRef: `${runRoot}/oracle-review.json`, dispatchAllowed: false },
2162
- { name: "promotion_proof", state: input.promotionProofPlan.promotionProofReady === true ? "proved_run_scope_gate_only" : "blocked", evidenceRef: `${runRoot}/promotion-proof-plan.json`, blocker: "pilot_batch_execution_not_enabled", dispatchAllowed: false },
2163
- { name: "pilot", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "pilot_execution_disabled_until_live_gates", dispatchAllowed: false },
2164
- { name: "pilot_oracle", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "pilot_oracle_missing_until_pilot_executes", dispatchAllowed: false },
2165
- { name: "batch", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "batch_execution_disabled_until_pilot_oracle_and_concurrency_gate", dispatchAllowed: false },
2166
- { name: "final_oracle", state: "blocked", evidenceRef: `${runRoot}/final-e2e-proof-plan.json`, blocker: "final_oracle_missing_until_full_current_source_e2e", dispatchAllowed: false },
2167
- { name: "scheduler_proof", state: input.schedulerProofPlan.schedulerProofReady === true ? "proved_run_scope_gate_only" : "blocked", evidenceRef: `${runRoot}/scheduler-proof-plan.json`, blocker: "daemon_scheduler_not_started", dispatchAllowed: false },
2168
- { name: "mission_control_proof", state: input.missionControlProofPlan.missionControlProofReady === true ? "proved_run_scope_gate_only" : "blocked", evidenceRef: `${runRoot}/mission-control-proof-plan.json`, blocker: "live_mission_control_transport_not_enabled", dispatchAllowed: false },
2169
- { name: "stop_clean", state: "planned", evidenceRef: `${runRoot}/scheduler-plan.json`, dispatchAllowed: false },
2170
- ];
2171
- const requiredArtifacts = [
2172
- { name: "spec-gate.json", present: true, evidenceRef: `${runRoot}/spec-gate.json` },
2173
- { name: "context-scope.json", present: true, evidenceRef: `${runRoot}/context-scope.json` },
2174
- { name: "context-pack.json", present: true, evidenceRef: `${runRoot}/context-pack.json` },
2175
- { name: "factory-selection.json", present: true, evidenceRef: `${runRoot}/factory-selection.json` },
2176
- { name: "runtime-gates.json", present: true, evidenceRef: `${runRoot}/runtime-gates.json` },
2177
- { name: "strict-budget-proof-plan.json", present: input.strictBudgetProofPlan.strictBudgetProofReady === true, evidenceRef: `${runRoot}/strict-budget-proof-plan.json` },
2178
- { name: "model-routing-proof-plan.json", present: input.modelRoutingProofPlan.modelRoutingProofReady === true, evidenceRef: `${runRoot}/model-routing-proof-plan.json` },
2179
- { name: "run-graph.json", present: true, evidenceRef: `${runRoot}/run-graph.json` },
2180
- { name: "current-source-fingerprint.json", present: input.currentSourceFingerprint.currentSourceFingerprintReady === true, evidenceRef: `${runRoot}/current-source-fingerprint.json` },
2181
- { name: "factory-run-smoke", present: input.factoryRunRef.status === "done", evidenceRef: `${runRoot}/factory-run-ref.json` },
2182
- { name: "factory-run-pilot", present: false, missingReason: "pilot_not_executed" },
2183
- { name: "factory-run-batch", present: false, missingReason: "batch_not_executed" },
2184
- { name: "oracle-review-smoke.json", present: input.oracleReview.verdict === "PASS", evidenceRef: `${runRoot}/oracle-review.json` },
2185
- { name: "promotion-proof-plan.json", present: input.promotionProofPlan.promotionProofReady === true, evidenceRef: `${runRoot}/promotion-proof-plan.json` },
2186
- { name: "scheduler-proof-plan.json", present: input.schedulerProofPlan.schedulerProofReady === true, evidenceRef: `${runRoot}/scheduler-proof-plan.json` },
2187
- { name: "mission-control-proof-plan.json", present: input.missionControlProofPlan.missionControlProofReady === true, evidenceRef: `${runRoot}/mission-control-proof-plan.json` },
2188
- { name: "oracle-review-pilot.json", present: false, missingReason: "pilot_oracle_missing" },
2189
- { name: "final-oracle.json", present: false, missingReason: "final_oracle_missing" },
2190
- { name: "validation.json", present: input.validation.status === "smoke_autonomy_passed", evidenceRef: `${runRoot}/validation.json` },
2191
- { name: "DONE.sentinel", present: false, missingReason: "final_e2e_not_run" },
2192
- { name: "GLOBAL_AUTONOMY_READY.sentinel", present: globalReadySentinelPresent, missingReason: globalReadySentinelPresent ? undefined : "global_autonomy_not_ready" },
2193
- ];
2194
- const blockers = [
2195
- "final_e2e_no_mock_current_source_not_proven",
2196
- ...(strictBudgetGate.strictEnabled === true && strictBudgetGate.budgetEnforced === true ? [] : ["live_strict_budget_not_enforced"]),
2197
- ...(input.modelRoutingPlan.liveRoutingEnabled === true ? [] : ["live_model_routing_not_enabled"]),
2198
- ...(input.schedulerPlan.schedulerExecutionAllowed === true && input.schedulerPlan.daemonStarted === true ? [] : ["daemon_scheduler_not_started"]),
2199
- ...(input.missionControlProofPlan.finalE2ERequirementCleared === true ? [] : ["live_mission_control_transport_not_enabled"]),
2200
- ...(smokeGate.passed === true ? [] : ["smoke_gate_not_passed"]),
2201
- ...(pilotGate.executionAllowed === true ? [] : ["pilot_execution_disabled"]),
2202
- ...(batchGate.executionAllowed === true ? [] : ["batch_execution_disabled"]),
2203
- ...(mainWorkspaceApply.realApplyExecuted === true ? [] : ["real_apply_not_executed"]),
2204
- "final_oracle_missing",
2205
- ...(globalReadySentinelPresent ? [] : ["global_autonomy_ready_sentinel_absent"]),
2206
- ];
2207
- const plan = {
2208
- schema: "zob.autonomous-final-e2e-proof-plan.v1",
2209
- runId: input.runId,
2210
- phase: "11A",
2211
- status: "blocked_for_final_e2e_proof",
2212
- finalE2EProofReady: false,
2213
- no_ship: true,
2214
- blockers,
2215
- proofSteps,
2216
- requiredArtifacts,
2217
- currentSourceProof: {
2218
- required: true,
2219
- noMockRequired: true,
2220
- currentSourceFingerprintCaptured: input.currentSourceFingerprint.currentSourceFingerprintCaptured === true,
2221
- currentSourceFingerprintHash: typeof input.currentSourceFingerprint.fingerprintHash === "string" ? input.currentSourceFingerprint.fingerprintHash : undefined,
2222
- sourceFileCount: typeof input.currentSourceFingerprint.sourceFileCount === "number" ? input.currentSourceFingerprint.sourceFileCount : undefined,
2223
- missingFiles: Array.isArray(input.currentSourceFingerprint.missingFiles) ? input.currentSourceFingerprint.missingFiles : [],
2224
- noMockCurrentSourceE2EProved: false,
2225
- registeredFactoryPathChecked: input.factorySelection.currentSourceProofRequired === true,
2226
- arbitraryFactoryAutonomyReady: false,
2227
- },
2228
- liveGateStatus: {
2229
- strictBudgetEnforced: strictBudgetGate.budgetEnforced === true,
2230
- strictBudgetEnabled: strictBudgetGate.strictEnabled === true,
2231
- strictBudgetProofReady: input.strictBudgetProofPlan.strictBudgetProofReady === true,
2232
- strictBudgetBlockProofPassed: input.strictBudgetProofPlan.strictBudgetBlockProofPassed === true,
2233
- strictBudgetFinalE2ERequirementCleared: input.strictBudgetProofPlan.finalE2ERequirementCleared === true,
2234
- modelRoutingProofReady: input.modelRoutingProofPlan.modelRoutingProofReady === true,
2235
- modelRoutingOracleProofPassed: input.modelRoutingProofPlan.routingOracleProofPassed === true,
2236
- modelRoutingFinalE2ERequirementCleared: input.modelRoutingProofPlan.finalE2ERequirementCleared === true,
2237
- liveModelRoutingEnabled: input.modelRoutingPlan.liveRoutingEnabled === true,
2238
- schedulerExecutionAllowed: input.schedulerPlan.schedulerExecutionAllowed === true,
2239
- schedulerProofReady: input.schedulerProofPlan.schedulerProofReady === true,
2240
- schedulerFinalE2ERequirementCleared: input.schedulerProofPlan.finalE2ERequirementCleared === true,
2241
- daemonStarted: input.schedulerPlan.daemonStarted === true,
2242
- missionControlProposalOnly: isRecord(input.missionControlPlan.commandPolicy) && input.missionControlPlan.commandPolicy.proposalOnly === true,
2243
- missionControlProofReady: input.missionControlProofPlan.missionControlProofReady === true,
2244
- missionControlFinalE2ERequirementCleared: input.missionControlProofPlan.finalE2ERequirementCleared === true,
2245
- directWorkerCommandsBlocked: input.missionControlProofPlan.directWorkerCommandsBlockedProofPassed === true,
2246
- liveTransportNetworkDisabled: input.missionControlProofPlan.liveTransportNetworkDisabledProofPassed === true,
2247
- liveGlobalRoutingApprovalRequired: input.missionControlProofPlan.liveGlobalRoutingApprovalProofPassed === true,
2248
- sandboxRealApplyExecuted: mainWorkspaceApply.realApplyExecuted === true,
2249
- },
2250
- promotionStatus: {
2251
- smokeGatePassed: smokeGate.passed === true,
2252
- pilotPreconditionsMet: pilotGate.preconditionsMet === true,
2253
- promotionProofReady: input.promotionProofPlan.promotionProofReady === true,
2254
- promotionFinalE2ERequirementCleared: input.promotionProofPlan.finalE2ERequirementCleared === true,
2255
- pilotExecutionAllowed: pilotGate.executionAllowed === true,
2256
- batchPreconditionsMet: batchGate.preconditionsMet === true,
2257
- batchExecutionAllowed: batchGate.executionAllowed === true,
2258
- pilotExecuted: input.promotionPlan.pilotExecuted === true,
2259
- batchExecuted: input.promotionPlan.batchExecuted === true,
2260
- },
2261
- sentinelPolicy: {
2262
- doneSentinelAllowed: false,
2263
- globalReadySentinelAllowed: false,
2264
- globalReadySentinelPresent,
2265
- globalReadySentinelPath: `${runRoot}/GLOBAL_AUTONOMY_READY.sentinel`,
2266
- },
2267
- finalReportPolicy: {
2268
- finalGlobalReportAllowed: false,
2269
- currentReportIsRunScopedSmokeOnly: true,
2270
- claim100PercentAutonomyAllowed: false,
2271
- },
2272
- childDispatchAllowed: false,
2273
- daemonStarted: false,
2274
- directWorkerWrites: false,
2275
- transportDispatch: false,
2276
- networkComsEnabled: false,
2277
- productionWritesPerformed: false,
2278
- autoApply: false,
2279
- realApplyExecuted: false,
2280
- globalAutonomyReady: false,
2281
- globalAutonomyNoShip: true,
2282
- bodyStored: false,
2283
- promptBodiesStored: false,
2284
- outputBodiesStored: false,
2285
- };
2286
- if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous final e2e proof plan would store forbidden plaintext body keys");
2287
- return plan;
2288
- }
2289
-
2290
- function buildAutonomousCompletionGate(input: { runId: string; finalE2EProofPlan: Record<string, unknown>; finalNoShipOracle: Record<string, unknown>; currentSourceFingerprintFreshness: Record<string, unknown> }): Record<string, unknown> {
2291
- const finalBlockers = Array.isArray(input.finalE2EProofPlan.blockers) ? input.finalE2EProofPlan.blockers.filter((blocker): blocker is string => typeof blocker === "string") : [];
2292
- const oracleFailedChecks = Array.isArray(input.finalNoShipOracle.failedChecks) ? input.finalNoShipOracle.failedChecks.filter((check): check is string => typeof check === "string") : [];
2293
- const checks = [
2294
- { name: "final_e2e_proof_ready", passed: input.finalE2EProofPlan.finalE2EProofReady === true },
2295
- { name: "final_no_ship_oracle_pass", passed: input.finalNoShipOracle.finalOraclePass === true && input.finalNoShipOracle.no_ship === false },
2296
- { name: "current_source_fingerprint_fresh", passed: input.currentSourceFingerprintFreshness.fresh === true },
2297
- { name: "global_ready_sentinel_allowed", passed: isRecord(input.finalE2EProofPlan.sentinelPolicy) && input.finalE2EProofPlan.sentinelPolicy.globalReadySentinelAllowed === true },
2298
- { name: "final_done_sentinel_allowed", passed: isRecord(input.finalNoShipOracle.decision) && input.finalNoShipOracle.decision.writeFinalDoneSentinelAllowed === true },
2299
- { name: "claim_100_percent_allowed", passed: isRecord(input.finalNoShipOracle.decision) && input.finalNoShipOracle.decision.claim100PercentAutonomyAllowed === true },
2300
- ];
2301
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
2302
- const gate = {
2303
- schema: "zob.autonomous-completion-gate.v1",
2304
- runId: input.runId,
2305
- phase: "11F",
2306
- status: "blocked_for_goal_completion",
2307
- completionReady: false,
2308
- allRequirementsVerified: false,
2309
- no_ship: true,
2310
- updateGoalAllowed: false,
2311
- requiredGoalStatus: "in_progress",
2312
- completionToolAvailableInThisRun: false,
2313
- checks,
2314
- failedChecks,
2315
- blockers: [...new Set([...finalBlockers, ...oracleFailedChecks, ...failedChecks])].sort(),
2316
- evidenceRefs: [
2317
- `reports/autonomous-runs/${safeFileStem(input.runId)}/final-e2e-proof-plan.json`,
2318
- `reports/autonomous-runs/${safeFileStem(input.runId)}/final-no-ship-oracle.json`,
2319
- `reports/autonomous-runs/${safeFileStem(input.runId)}/current-source-fingerprint.json`,
2320
- `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
2321
- ],
2322
- requiredBeforeCompletion: [
2323
- "final_e2e_no_mock_current_source_proof",
2324
- "final_oracle_PASS_no_ship_false",
2325
- "smoke_pilot_batch_artifacts_current_source",
2326
- "live_strict_budget_enforced",
2327
- "live_model_routing_enabled",
2328
- "daemon_scheduler_proven_with_kill_switch",
2329
- "sandbox_real_apply_or_explicit_no_apply_final_policy",
2330
- "GLOBAL_AUTONOMY_READY_sentinel_allowed_by_final_oracle",
2331
- "update_goal_tool_available_and_called_only_after_all_gates_pass",
2332
- ],
2333
- decision: {
2334
- updateGoalStatusCompleteAllowed: false,
2335
- globalAutonomyReady: false,
2336
- globalAutonomyNoShip: true,
2337
- writeGlobalReadySentinelAllowed: false,
2338
- writeFinalDoneSentinelAllowed: false,
2339
- claim100PercentAutonomyAllowed: false,
2340
- },
2341
- childDispatchAllowed: false,
2342
- daemonStarted: false,
2343
- directWorkerWrites: false,
2344
- transportDispatch: false,
2345
- networkComsEnabled: false,
2346
- productionWritesPerformed: false,
2347
- autoApply: false,
2348
- realApplyExecuted: false,
2349
- liveRoutingEnabled: false,
2350
- budgetEnforced: false,
2351
- globalAutonomyReady: false,
2352
- globalAutonomyNoShip: true,
2353
- bodyStored: false,
2354
- promptBodiesStored: false,
2355
- outputBodiesStored: false,
2356
- };
2357
- if (hasForbiddenBodyKeys(gate)) throw new Error("autonomous completion gate would store forbidden plaintext body keys");
2358
- return gate;
2359
- }
2360
-
2361
- function buildAutonomousReadOnlySmokeFinalReport(validation: Record<string, unknown>, factoryRunRef: Record<string, unknown>, oracleReview: Record<string, unknown>): string {
2362
- const blockers = Array.isArray(validation.blockers) ? validation.blockers.map((blocker) => `- ${String(blocker)}`).join("\n") : "";
2363
- return [
2364
- "# Autonomous Read-Only Smoke Report",
2365
- "",
2366
- `Run ID: ${String(validation.runId ?? "unknown")}`,
2367
- `Status: ${String(validation.status ?? "unknown")}`,
2368
- `Smoke no-ship: ${String(validation.no_ship === true)}`,
2369
- `Global autonomy no-ship: ${String(validation.globalAutonomyNoShip === true)}`,
2370
- "",
2371
- "## Factory smoke",
2372
- "",
2373
- `- Selected factory: ${String(factoryRunRef.selectedFactory ?? "none")}`,
2374
- `- Factory run id: ${String(factoryRunRef.factoryRunId ?? "none")}`,
2375
- `- Factory status: ${String(factoryRunRef.status ?? "unknown")}`,
2376
- `- Deterministic execution: ${String(factoryRunRef.execution === "deterministic")}`,
2377
- "",
2378
- "## Structural oracle",
2379
- "",
2380
- `- Verdict: ${String(oracleReview.verdict ?? "unknown")}`,
2381
- `- No-ship for this smoke: ${String(oracleReview.no_ship === true)}`,
2382
- `- Live oracle dispatched: ${String(oracleReview.liveOracleDispatched === true)}`,
2383
- "",
2384
- "## Blockers",
2385
- "",
2386
- blockers || "- None for this read-only smoke slice.",
2387
- "",
2388
- "## Evidence refs",
2389
- "",
2390
- "- spec-gate.json",
2391
- "- context-scope.json",
2392
- "- context-pack.json",
2393
- "- runtime-gates.json",
2394
- "- model-routing-plan.json",
2395
- "- model-routing-proof-plan.json",
2396
- "- factory-selection.json",
2397
- "- factory-run-ref.json",
2398
- "- oracle-review.json",
2399
- "- promotion-plan.json",
2400
- "- promotion-proof-plan.json",
2401
- "- scheduler-plan.json",
2402
- "- scheduler-proof-plan.json",
2403
- "- mission-control-plan.json",
2404
- "- mission-control-proof-plan.json",
2405
- "- sandbox-apply-plan.json",
2406
- "- strict-budget-proof-plan.json",
2407
- "- current-source-fingerprint.json",
2408
- "- final-e2e-proof-plan.json",
2409
- "- final-no-ship-oracle.json",
2410
- "- completion-gate.json",
2411
- "- validation.json",
2412
- "- SMOKE_AUTONOMY_PASSED.sentinel when status=smoke_autonomy_passed",
2413
- "",
2414
- "Compliance: Phase 4A read-only deterministic smoke evidence only; global autonomy remains no-ship.",
2415
- "",
2416
- ].join("\n");
2417
- }
2418
-
2419
- export function validateAutonomousRuntimeDryRunArtifacts(repoRoot: string, runId: string): Record<string, unknown> {
2420
- const safeRunId = safeFileStem(runId);
2421
- const runDir = join(repoRoot, "reports", "autonomous-runs", safeRunId);
2422
- const requiredArtifacts = ["spec-gate.json", "context-scope.json", "context-lookup.json", "context-pack.json", "runtime-gates.json", "model-routing-plan.json", "run-graph.json", "factory-selection.json", "proof-plan.json", "dry-run-report.json", "validation.json", "final-report.md", "DRY_RUN_READY.sentinel"];
2423
- const jsonArtifacts = requiredArtifacts.filter((name) => name.endsWith(".json"));
2424
- const parsedArtifacts: Record<string, Record<string, unknown> | unknown[]> = {};
2425
- const artifactMetadata = requiredArtifacts.map((name) => {
2426
- const artifactPath = join(runDir, name);
2427
- const present = existsSync(artifactPath);
2428
- if (!present) return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, bodyStored: false };
2429
- if (!name.endsWith(".json")) {
2430
- const raw = readFileSync(artifactPath, "utf8");
2431
- return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, hash: sha256(raw), bodyStored: false };
2432
- }
2433
- const read = readJsonArtifact(artifactPath);
2434
- if (read.parsed) parsedArtifacts[name] = read.parsed;
2435
- return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, hash: read.hash, schema: isRecord(read.parsed) ? read.parsed.schema : undefined, error: read.error, bodyStored: false };
2436
- });
2437
- const artifact = (name: string): Record<string, unknown> => isRecord(parsedArtifacts[name]) ? parsedArtifacts[name] as Record<string, unknown> : {};
2438
- const arrayArtifact = (name: string): unknown[] => Array.isArray(parsedArtifacts[name]) ? parsedArtifacts[name] as unknown[] : [];
2439
- const report = artifact("dry-run-report.json");
2440
- const validation = artifact("validation.json");
2441
- const specGate = artifact("spec-gate.json");
2442
- const contextScope = artifact("context-scope.json");
2443
- const contextLookups = arrayArtifact("context-lookup.json");
2444
- const contextPack = artifact("context-pack.json");
2445
- const runtimeGates = artifact("runtime-gates.json");
2446
- const modelRoutingPlan = artifact("model-routing-plan.json");
2447
- const runGraph = artifact("run-graph.json");
2448
- const factorySelection = artifact("factory-selection.json");
2449
- const proofPlan = artifact("proof-plan.json");
2450
- const proofStages = Array.isArray(proofPlan.stages) ? proofPlan.stages.filter(isRecord) : [];
2451
- const graphEdges = Array.isArray(runGraph.edges) ? runGraph.edges.filter(isRecord) : [];
2452
- const graphNodes = Array.isArray(runGraph.nodes) ? runGraph.nodes.filter(isRecord) : [];
2453
- const modelRoutes = Array.isArray(modelRoutingPlan.routes) ? modelRoutingPlan.routes.filter(isRecord) : [];
2454
- const lookupPlan = isRecord(report.contextPlan) && isRecord(report.contextPlan.lookupPlan) ? report.contextPlan.lookupPlan : {};
2455
- const factoryReadiness = isRecord(factorySelection.factoryReadiness) ? factorySelection.factoryReadiness : {};
2456
- const jsonBodyFree = jsonArtifacts.every((name) => {
2457
- const parsed = parsedArtifacts[name];
2458
- return parsed !== undefined && !hasForbiddenBodyKeys(parsed);
2459
- });
2460
- const checks = [
2461
- { name: "required_artifacts_present", passed: artifactMetadata.every((item) => item.present === true), detail: { requiredArtifacts } },
2462
- { name: "json_artifacts_parse", passed: artifactMetadata.filter((item) => item.name.endsWith(".json")).every((item) => !item.error), detail: { jsonArtifacts } },
2463
- { name: "artifact_schemas", passed: specGate.schema === "zob.autonomous-spec-gate.v1" && contextScope.schema === "zob.context-scope.v1" && contextPack.schema === "zob.context-pack.v1" && runtimeGates.schema === "zob.autonomous-runtime-gates.v1" && modelRoutingPlan.schema === "zob.autonomous-model-routing-plan.v1" && runGraph.schema === "zob.autonomous-run-graph.v1" && factorySelection.schema === "zob.autonomous-factory-selection.v1" && proofPlan.schema === "zob.autonomous-proof-plan.v1" && report.schema === "zob.autonomous-runtime-dry-run.v1" && validation.schema === "zob.autonomous-runtime-dry-run-validation.v1", detail: "expected autonomous dry-run artifact schemas" },
2464
- { name: "spec_gate_scope_locked", passed: specGate.specLocked === true && specGate.allowedPathsRequired === true && specGate.pathGatePassed === true && specGate.applyPolicyRequired === true && specGate.applyPolicyProvided === true && specGate.budgetProfileRequired === true && specGate.budgetProfileProvided === true && specGate.autonomousStrictBudgetRequired === true && specGate.autonomousStrictBudgetSatisfied === true && Array.isArray(specGate.allowedPaths) && specGate.allowedPaths.length > 0 && Array.isArray(specGate.forbiddenPaths) && specGate.forbiddenPaths.length > 0, detail: "autonomous spec lock requires safe bounded allowed_paths, forbidden_paths, explicit apply_policy, and explicit strict_requested budget_profile" },
2465
- { name: "dry_run_safety_flags", passed: report.noExecution === true && report.childDispatchAllowed === false && report.daemonStarted === false && report.productionWritesPerformed === false && report.autoApply === false && report.networkAccessed === false && report.globalAutonomyReady === false && report.globalAutonomyNoShip === true, detail: "report safety posture" },
2466
- { name: "validation_safety_flags", passed: validation.passed === true && validation.noExecution === true && validation.childDispatchAllowed === false && validation.networkAccessed === false && validation.globalAutonomyNoShip === true && validation.sentinel === "DRY_RUN_READY.sentinel", detail: "validation safety posture" },
2467
- { name: "context_lookup_pack_cited_bounded", passed: contextLookups.length > 0 && contextLookups.every((lookup) => isRecord(lookup) && lookup.schema === "zob.brain-lookup-result.v1" && lookup.queryStored === false && lookup.citationRequired === true) && Array.isArray(contextPack.citations) && contextPack.citations.length > 0 && isRecord(contextPack.loadingRules) && contextPack.loadingRules.boundedContextOnly === true && contextPack.loadingRules.agentLoadsEntireCorpus === false, detail: { lookupCount: contextLookups.length, citationCount: Array.isArray(contextPack.citations) ? contextPack.citations.length : 0 } },
2468
- { name: "gbrain_disabled", passed: lookupPlan.gbrainImportEnabled === false && lookupPlan.gbrainEmbedEnabled === false && lookupPlan.gbrainSyncEnabled === false && lookupPlan.gbrainWriteEnabled === false, detail: "P0 dry-run does not import/embed/sync/write GBrain" },
2469
- { name: "runtime_gates_no_execution", passed: runtimeGates.passed === true && isRecord(runtimeGates.autonomousStrictBudgetGate) && runtimeGates.autonomousStrictBudgetGate.strictRequested === true && runtimeGates.autonomousStrictBudgetGate.strictEnabled === false && runtimeGates.autonomousStrictBudgetGate.budgetEnforced === false && runtimeGates.noExecution === true && runtimeGates.childDispatchAllowed === false && runtimeGates.globalBudgetEnforced === false && runtimeGates.globalModelRoutingEnabled === false && runtimeGates.daemonStarted === false && runtimeGates.productionWritesPerformed === false && runtimeGates.autoApply === false && runtimeGates.networkAccessed === false, detail: "runtime gates require strict budget intent while remaining disabled/proposal-only" },
2470
- { name: "model_routing_plan_safe", passed: modelRoutingPlan.routingPlanReady === true && modelRoutingPlan.liveRoutingEnabled === false && modelRoutingPlan.globalLiveRoutingEnabled === false && modelRoutingPlan.modelRouterUsed === false && modelRoutingPlan.routingApplied === false && modelRoutingPlan.childDispatchAllowed === false && modelRoutingPlan.noExecution === true && modelRoutes.some((route) => route.stage === "context_reuse_scout" && route.recommendedModelClass === "cheap_scout") && modelRoutes.some((route) => route.oracleCritical === true && route.recommendedModelClass === "strong_oracle") && modelRoutes.every((route) => route.noExecution === true && route.modelRouterUsed === false && route.routingApplied === false && route.childDispatchAllowed === false), detail: { routeCount: modelRoutes.length, failedChecks: modelRoutingPlan.failedChecks } },
2471
- { name: "run_graph_parent_owned_no_dispatch", passed: runGraph.status === "dry_run_graph_ready" && runGraph.parentOwned === true && runGraph.noExecution === true && runGraph.childDispatchAllowed === false && graphNodes.some((node) => node.id === "model_routing_plan") && graphNodes.some((node) => node.id === "registered_factory_current_source_proof") && graphEdges.length > 0 && graphEdges.every((edge) => edge.parentOwned === true && edge.dispatchAllowed === false), detail: { nodes: graphNodes.length, edges: graphEdges.length } },
2472
- { name: "factory_selection_requires_current_source_proof", passed: factorySelection.currentSourceProofRequired === true && typeof factoryReadiness.registeredBatchReady === "boolean" && factorySelection.proofBeforeExecutionRequired === (factoryReadiness.registeredBatchReady !== true), detail: { selectedFactory: factorySelection.selectedFactory, registeredBatchReady: factoryReadiness.registeredBatchReady } },
2473
- { name: "proof_plan_has_required_gates", passed: ["context_lookup_and_pack", "runtime_gates_preflight", "model_routing_plan", "registered_factory_current_source_proof", "smoke_oracle", "pilot_oracle", "batch"].every((name) => proofStages.some((stage) => stage.name === name)) && proofStages.every((stage) => stage.name === "spec_lock" || stage.dispatchAllowed === false || stage.dispatchAllowed === undefined), detail: { stages: proofStages.map((stage) => stage.name) } },
2474
- { name: "json_artifacts_body_free", passed: jsonBodyFree, detail: "no forbidden plaintext body keys in JSON artifacts" },
2475
- ];
2476
- const failedChecks = checks.filter((check) => !check.passed).map((check) => check.name);
2477
- const result = {
2478
- schema: "zob.autonomous-runtime-dry-run-artifact-validation.v1",
2479
- runId: safeRunId,
2480
- valid: failedChecks.length === 0,
2481
- failedChecks,
2482
- checks,
2483
- artifacts: artifactMetadata,
2484
- noExecution: true,
2485
- childDispatchAllowed: false,
2486
- networkAccessed: false,
2487
- globalAutonomyReady: false,
2488
- globalAutonomyNoShip: true,
2489
- bodyStored: false,
2490
- promptBodiesStored: false,
2491
- outputBodiesStored: false,
2492
- generatedAt: new Date().toISOString(),
2493
- };
2494
- if (hasForbiddenBodyKeys(result)) throw new Error("autonomous dry-run artifact validation would store forbidden plaintext body keys");
2495
- return result;
2496
- }
2497
-
2498
- export function writeAutonomousRuntimeDryRunReport(repoRoot: string, input: AutonomousRuntimeDryRunInput): Record<string, unknown> {
2499
- const report = buildAutonomousRuntimeDryRun(repoRoot, input);
2500
- const runId = String(report.runId);
2501
- const safeRunId = safeFileStem(runId);
2502
- const runDir = join(repoRoot, "reports", "autonomous-runs", safeRunId);
2503
- mkdirSync(runDir, { recursive: true });
2504
- const specGatePath = join(runDir, "spec-gate.json");
2505
- const contextScopePath = join(runDir, "context-scope.json");
2506
- const contextLookupPath = join(runDir, "context-lookup.json");
2507
- const contextPackPath = join(runDir, "context-pack.json");
2508
- const runtimeGatesPath = join(runDir, "runtime-gates.json");
2509
- const modelRoutingPlanPath = join(runDir, "model-routing-plan.json");
2510
- const runGraphPath = join(runDir, "run-graph.json");
2511
- const factorySelectionPath = join(runDir, "factory-selection.json");
2512
- const proofPlanPath = join(runDir, "proof-plan.json");
2513
- const reportPath = join(runDir, "dry-run-report.json");
2514
- const validationPath = join(runDir, "validation.json");
2515
- const finalReportPath = join(runDir, "final-report.md");
2516
- writeFileSync(specGatePath, `${JSON.stringify(report.specGate, null, 2)}\n`);
2517
- const contextPlan = isRecord(report.contextPlan) ? report.contextPlan : {};
2518
- const contextScope = isRecord(contextPlan.contextScope) ? contextPlan.contextScope : {};
2519
- writeFileSync(contextScopePath, `${JSON.stringify(contextScope, null, 2)}\n`);
2520
- writeFileSync(contextLookupPath, `${JSON.stringify(contextPlan.lookupResults ?? [], null, 2)}\n`);
2521
- writeFileSync(contextPackPath, `${JSON.stringify(contextPlan.contextPack ?? {}, null, 2)}\n`);
2522
- writeFileSync(runtimeGatesPath, `${JSON.stringify(report.runtimeGates, null, 2)}\n`);
2523
- writeFileSync(modelRoutingPlanPath, `${JSON.stringify(report.modelRoutingPlan, null, 2)}\n`);
2524
- writeFileSync(runGraphPath, `${JSON.stringify(report.runGraph, null, 2)}\n`);
2525
- writeFileSync(factorySelectionPath, `${JSON.stringify(report.factorySelection, null, 2)}\n`);
2526
- writeFileSync(proofPlanPath, `${JSON.stringify(report.proofPlan, null, 2)}\n`);
2527
- writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
2528
- const validation = buildAutonomousRuntimeDryRunValidation(report);
2529
- writeFileSync(validationPath, `${JSON.stringify(validation, null, 2)}\n`);
2530
- writeFileSync(finalReportPath, buildAutonomousRuntimeDryRunFinalReport(report));
2531
- if (report.status === "dry_run_plan_ready") writeFileSync(join(runDir, "DRY_RUN_READY.sentinel"), "dry-run-ready\n");
2532
- return {
2533
- ...report,
2534
- specGatePath: `reports/autonomous-runs/${safeRunId}/spec-gate.json`,
2535
- contextScopePath: `reports/autonomous-runs/${safeRunId}/context-scope.json`,
2536
- contextLookupPath: `reports/autonomous-runs/${safeRunId}/context-lookup.json`,
2537
- contextPackPath: `reports/autonomous-runs/${safeRunId}/context-pack.json`,
2538
- runtimeGatesPath: `reports/autonomous-runs/${safeRunId}/runtime-gates.json`,
2539
- modelRoutingPlanPath: `reports/autonomous-runs/${safeRunId}/model-routing-plan.json`,
2540
- runGraphPath: `reports/autonomous-runs/${safeRunId}/run-graph.json`,
2541
- factorySelectionPath: `reports/autonomous-runs/${safeRunId}/factory-selection.json`,
2542
- proofPlanPath: `reports/autonomous-runs/${safeRunId}/proof-plan.json`,
2543
- reportPath: `reports/autonomous-runs/${safeRunId}/dry-run-report.json`,
2544
- validationPath: `reports/autonomous-runs/${safeRunId}/validation.json`,
2545
- finalReportPath: `reports/autonomous-runs/${safeRunId}/final-report.md`,
2546
- sentinelPath: report.status === "dry_run_plan_ready" ? `reports/autonomous-runs/${safeRunId}/DRY_RUN_READY.sentinel` : undefined,
2547
- };
2548
- }
2549
-
2550
- export function writeAutonomousReadOnlySmokeRunReport(repoRoot: string, input: AutonomousReadOnlySmokeRunInput): Record<string, unknown> {
2551
- const runId = safeFileStem(input.runId ?? `autonomous-readonly-smoke-${sha256(input.userNeed || "missing-spec").slice(0, 12)}`);
2552
- const safeRunId = safeFileStem(runId);
2553
- const runDir = join(repoRoot, "reports", "autonomous-runs", safeRunId);
2554
- const smokeAutonomySentinelPath = join(runDir, "SMOKE_AUTONOMY_PASSED.sentinel");
2555
- if (existsSync(smokeAutonomySentinelPath)) throw new Error(`Autonomous smoke run already passed; choose a fresh run_id to avoid stale sentinel reuse: ${runId}`);
2556
- const dryRun = writeAutonomousRuntimeDryRunReport(repoRoot, {
2557
- ...input,
2558
- runId,
2559
- applyPolicy: input.applyPolicy ?? "no_apply",
2560
- budgetProfile: input.budgetProfile ?? "strict_requested",
2561
- });
2562
- const factorySelection = isRecord(dryRun.factorySelection) ? dryRun.factorySelection : {};
2563
- const selectedFactory = typeof factorySelection.selectedFactory === "string" ? factorySelection.selectedFactory : undefined;
2564
- const manifestPath = selectedFactory ? `.pi/factories/${selectedFactory}/smoke-manifest.json` : undefined;
2565
- const factoryRunId = safeFileStem(input.factoryRunId ?? `autonomous-smoke-${safeRunId}`);
2566
- const factoryRunAlreadyExists = existsSync(join(repoRoot, "reports", "factory-runs", factoryRunId));
2567
- const blockers = [
2568
- ...(dryRun.status === "dry_run_plan_ready" ? [] : ["dry_run_not_ready"]),
2569
- ...(isRecord(dryRun.validation) && Array.isArray(dryRun.validation.blockers) ? dryRun.validation.blockers.filter((blocker): blocker is string => typeof blocker === "string") : []),
2570
- ...(isRecord(dryRun.specGate) && dryRun.specGate.applyPolicy === "no_apply" ? [] : ["apply_policy_must_be_no_apply_for_readonly_smoke"]),
2571
- ...(isRecord(dryRun.specGate) && dryRun.specGate.budgetProfile === "strict_requested" ? [] : ["strict_requested_budget_required_for_readonly_smoke"]),
2572
- ...(isRecord(dryRun.runtimeGates) && dryRun.runtimeGates.childDispatchAllowed === false && dryRun.runtimeGates.daemonStarted === false && dryRun.runtimeGates.productionWritesPerformed === false && dryRun.runtimeGates.autoApply === false ? [] : ["runtime_gates_not_readonly_safe"]),
2573
- ...(isRecord(dryRun.modelRoutingPlan) && dryRun.modelRoutingPlan.routingPlanReady === true && dryRun.modelRoutingPlan.liveRoutingEnabled === false && dryRun.modelRoutingPlan.childDispatchAllowed === false ? [] : ["model_routing_plan_not_readonly_safe"]),
2574
- ...(selectedFactory ? [] : ["factory_selection_missing"]),
2575
- ...(factorySelection.selectionStatus === "existing_factory_selected" ? [] : ["selected_factory_must_be_existing_for_readonly_smoke"]),
2576
- ...(manifestPath && existsSync(join(repoRoot, manifestPath)) ? [] : ["selected_factory_smoke_manifest_missing"]),
2577
- ...(factoryRunAlreadyExists ? ["factory_run_id_already_exists"] : []),
2578
- ];
2579
- const shouldRunFactory = blockers.length === 0 && selectedFactory !== undefined && manifestPath !== undefined;
2580
- const factoryRunResult = shouldRunFactory ? runFactoryRun(repoRoot, {
2581
- factory: selectedFactory,
2582
- input_manifest: manifestPath,
2583
- run_id: factoryRunId,
2584
- mode: "smoke",
2585
- max_items: 1,
2586
- execution: "deterministic",
2587
- budget: { strictRequested: true, strictEnabled: false, maxRuns: 1, estimatedRuns: 1, maxParallelChildren: 1, estimatedParallelChildren: 1 },
2588
- model_routing: { enabled: false, risk: input.risk ?? "medium", contextTokens: input.maxContextTokens },
2589
- }) : undefined;
2590
- const factoryRunDir = join(repoRoot, "reports", "factory-runs", factoryRunId);
2591
- const factoryValidationPath = join(factoryRunDir, "validation.json");
2592
- const factoryValidationRead = readJsonArtifact(factoryValidationPath);
2593
- const factoryValidation = isRecord(factoryValidationRead.parsed) ? factoryValidationRead.parsed : {};
2594
- const phaseSentinelPresent = existsSync(join(factoryRunDir, "SMOKE_PASSED.sentinel"));
2595
- const doneSentinelPresent = existsSync(join(factoryRunDir, "DONE.sentinel"));
2596
- const factoryRunRef = {
2597
- schema: "zob.autonomous-readonly-smoke-factory-run-ref.v1",
2598
- runId,
2599
- selectedFactory,
2600
- manifestPath,
2601
- factoryRunId,
2602
- factoryRunPath: relativeFactoryRunPath(factoryRunId),
2603
- status: factoryRunResult?.status ?? "not_started",
2604
- processed: factoryRunResult?.processed ?? 0,
2605
- failed: factoryRunResult?.failed ?? 0,
2606
- execution: "deterministic",
2607
- mode: "smoke",
2608
- reportsOnlyWrites: true,
2609
- productionWritesPerformed: false,
2610
- autoApply: false,
2611
- childDispatchAllowed: false,
2612
- liveChildDispatches: 0,
2613
- daemonStarted: false,
2614
- phaseSentinel: "SMOKE_PASSED.sentinel",
2615
- phaseSentinelPresent,
2616
- doneSentinelPresent,
2617
- validationPath: relativeFactoryRunPath(factoryRunId, "validation.json"),
2618
- validationHash: factoryValidationRead.hash,
2619
- artifactHashes: {
2620
- validation: factoryValidationRead.hash,
2621
- smokeSentinel: artifactHashIfPresent(join(factoryRunDir, "SMOKE_PASSED.sentinel")),
2622
- doneSentinel: artifactHashIfPresent(join(factoryRunDir, "DONE.sentinel")),
2623
- telemetry: artifactHashIfPresent(join(factoryRunDir, "telemetry.json")),
2624
- agenticPlan: artifactHashIfPresent(join(factoryRunDir, "agentic-plan.json")),
2625
- },
2626
- artifacts: factoryRunResult?.artifacts ?? [],
2627
- errors: factoryRunResult?.errors ?? [],
2628
- bodyStored: false,
2629
- promptBodiesStored: false,
2630
- outputBodiesStored: false,
2631
- };
2632
- const oracleChecks = [
2633
- { name: "dry_run_ready", passed: dryRun.status === "dry_run_plan_ready" },
2634
- { name: "context_pack_cited", passed: isRecord(dryRun.contextPlan) && dryRun.contextPlan.contextPackValid === true },
2635
- { name: "runtime_gates_readonly", passed: isRecord(dryRun.runtimeGates) && dryRun.runtimeGates.childDispatchAllowed === false && dryRun.runtimeGates.daemonStarted === false && dryRun.runtimeGates.productionWritesPerformed === false && dryRun.runtimeGates.autoApply === false },
2636
- { name: "model_routing_plan_readonly", passed: isRecord(dryRun.modelRoutingPlan) && dryRun.modelRoutingPlan.routingPlanReady === true && dryRun.modelRoutingPlan.liveRoutingEnabled === false && dryRun.modelRoutingPlan.childDispatchAllowed === false },
2637
- { name: "factory_selection_existing", passed: factorySelection.selectionStatus === "existing_factory_selected" && Boolean(selectedFactory) },
2638
- { name: "factory_smoke_done", passed: factoryRunResult?.status === "done" && factoryRunResult.processed === 1 && factoryRunResult.failed === 0 },
2639
- { name: "factory_validation_passed", passed: factoryValidation.status === "passed" },
2640
- { name: "smoke_sentinel_present", passed: phaseSentinelPresent },
2641
- { name: "done_sentinel_present", passed: doneSentinelPresent },
2642
- ];
2643
- const structuralOraclePassed = blockers.length === 0 && oracleChecks.every((check) => check.passed === true);
2644
- const oracleReview = {
2645
- schema: "zob.autonomous-readonly-smoke-oracle-review.v1",
2646
- runId,
2647
- oracleType: "deterministic_structural",
2648
- verdict: structuralOraclePassed ? "PASS" : "FAIL",
2649
- no_ship: !structuralOraclePassed,
2650
- liveOracleDispatched: false,
2651
- evidenceChecked: true,
2652
- checks: oracleChecks,
2653
- failedChecks: oracleChecks.filter((check) => check.passed !== true).map((check) => check.name),
2654
- evidenceRefs: [
2655
- `reports/autonomous-runs/${safeRunId}/spec-gate.json`,
2656
- `reports/autonomous-runs/${safeRunId}/context-pack.json`,
2657
- `reports/autonomous-runs/${safeRunId}/runtime-gates.json`,
2658
- `reports/autonomous-runs/${safeRunId}/model-routing-plan.json`,
2659
- `reports/autonomous-runs/${safeRunId}/factory-selection.json`,
2660
- `reports/autonomous-runs/${safeRunId}/factory-run-ref.json`,
2661
- relativeFactoryRunPath(factoryRunId, "validation.json"),
2662
- relativeFactoryRunPath(factoryRunId, "SMOKE_PASSED.sentinel"),
2663
- relativeFactoryRunPath(factoryRunId, "DONE.sentinel"),
2664
- ],
2665
- globalAutonomyReady: false,
2666
- globalAutonomyNoShip: true,
2667
- bodyStored: false,
2668
- promptBodiesStored: false,
2669
- outputBodiesStored: false,
2670
- };
2671
- const validation = {
2672
- schema: "zob.autonomous-readonly-smoke-validation.v1",
2673
- runId,
2674
- status: structuralOraclePassed ? "smoke_autonomy_passed" : "blocked",
2675
- passed: structuralOraclePassed,
2676
- no_ship: !structuralOraclePassed,
2677
- smokeRunNoShip: !structuralOraclePassed,
2678
- globalAutonomyReady: false,
2679
- globalAutonomyNoShip: true,
2680
- blockers: [...blockers, ...oracleChecks.filter((check) => check.passed !== true).map((check) => check.name)],
2681
- warnings: ["phase_4a_deterministic_structural_oracle_only", "global_autonomy_no_ship", "reports_only_writes"],
2682
- dryRunReady: dryRun.status === "dry_run_plan_ready",
2683
- selectedFactory,
2684
- factoryRunId,
2685
- factoryRunStatus: factoryRunResult?.status ?? "not_started",
2686
- oracleVerdict: oracleReview.verdict,
2687
- oracleNoShip: oracleReview.no_ship,
2688
- reportsOnlyWrites: true,
2689
- deterministicExecution: true,
2690
- childDispatchAllowed: false,
2691
- liveChildDispatches: 0,
2692
- daemonStarted: false,
2693
- productionWritesPerformed: false,
2694
- autoApply: false,
2695
- liveRoutingEnabled: false,
2696
- globalLiveRoutingEnabled: false,
2697
- sentinel: structuralOraclePassed ? "SMOKE_AUTONOMY_PASSED.sentinel" : undefined,
2698
- bodyStored: false,
2699
- promptBodiesStored: false,
2700
- outputBodiesStored: false,
2701
- generatedAt: new Date().toISOString(),
2702
- };
2703
- const promotionPlan = buildAutonomousPromotionPlan({ runId, selectedFactory, factoryRunRef, oracleReview, validation });
2704
- const promotionProofPlan = buildAutonomousPromotionProofPlan({ runId, promotionPlan, factoryRunRef, oracleReview, validation });
2705
- const schedulerPlan = buildAutonomousSchedulerPlan(repoRoot, { runId, promotionPlan, validation });
2706
- const schedulerProofPlan = buildAutonomousSchedulerProofPlan({ runId, schedulerPlan, validation });
2707
- const missionControlPlan = buildAutonomousMissionControlPlan(repoRoot, { runId, schedulerPlan, validation });
2708
- const strictBudgetProofPlan = buildAutonomousStrictBudgetProofPlan({ runId, runtimeGates: isRecord(dryRun.runtimeGates) ? dryRun.runtimeGates : {}, validation });
2709
- const modelRoutingProofPlan = buildAutonomousModelRoutingProofPlan({ runId, modelRoutingPlan: isRecord(dryRun.modelRoutingPlan) ? dryRun.modelRoutingPlan : {}, validation });
2710
- const missionControlProofPlan = buildAutonomousMissionControlProofPlan({ runId, missionControlPlan, schedulerProofPlan, modelRoutingProofPlan, validation });
2711
- const sandboxApplyPlan = buildAutonomousSandboxApplyPlan(repoRoot, { runId, missionControlPlan, validation });
2712
- const currentSourceFingerprint = buildAutonomousCurrentSourceFingerprint(repoRoot, { runId, factorySelection });
2713
- const finalE2EProofPlan = buildAutonomousFinalE2EProofPlan(repoRoot, {
2714
- runId,
2715
- runtimeGates: isRecord(dryRun.runtimeGates) ? dryRun.runtimeGates : {},
2716
- strictBudgetProofPlan,
2717
- modelRoutingProofPlan,
2718
- modelRoutingPlan: isRecord(dryRun.modelRoutingPlan) ? dryRun.modelRoutingPlan : {},
2719
- factorySelection,
2720
- factoryRunRef,
2721
- oracleReview,
2722
- promotionPlan,
2723
- promotionProofPlan,
2724
- schedulerPlan,
2725
- schedulerProofPlan,
2726
- missionControlPlan,
2727
- missionControlProofPlan,
2728
- sandboxApplyPlan,
2729
- currentSourceFingerprint,
2730
- validation,
2731
- });
2732
- const finalNoShipOracle = buildAutonomousFinalNoShipOracle({ runId, finalE2EProofPlan, currentSourceFingerprint });
2733
- const currentSourceFingerprintFreshness = validateAutonomousCurrentSourceFingerprintFreshness(repoRoot, currentSourceFingerprint, factorySelection);
2734
- const completionGate = buildAutonomousCompletionGate({ runId, finalE2EProofPlan, finalNoShipOracle, currentSourceFingerprintFreshness });
2735
- if (hasForbiddenBodyKeys(factoryRunRef) || hasForbiddenBodyKeys(oracleReview) || hasForbiddenBodyKeys(promotionPlan) || hasForbiddenBodyKeys(promotionProofPlan) || hasForbiddenBodyKeys(schedulerPlan) || hasForbiddenBodyKeys(schedulerProofPlan) || hasForbiddenBodyKeys(missionControlPlan) || hasForbiddenBodyKeys(missionControlProofPlan) || hasForbiddenBodyKeys(sandboxApplyPlan) || hasForbiddenBodyKeys(strictBudgetProofPlan) || hasForbiddenBodyKeys(modelRoutingProofPlan) || hasForbiddenBodyKeys(currentSourceFingerprint) || hasForbiddenBodyKeys(finalE2EProofPlan) || hasForbiddenBodyKeys(finalNoShipOracle) || hasForbiddenBodyKeys(completionGate) || hasForbiddenBodyKeys(validation)) throw new Error("autonomous readonly smoke artifacts would store forbidden plaintext body keys");
2736
- const factoryRunRefPath = join(runDir, "factory-run-ref.json");
2737
- const oracleReviewPath = join(runDir, "oracle-review.json");
2738
- const promotionPlanPath = join(runDir, "promotion-plan.json");
2739
- const promotionProofPlanPath = join(runDir, "promotion-proof-plan.json");
2740
- const schedulerPlanPath = join(runDir, "scheduler-plan.json");
2741
- const schedulerProofPlanPath = join(runDir, "scheduler-proof-plan.json");
2742
- const missionControlPlanPath = join(runDir, "mission-control-plan.json");
2743
- const missionControlProofPlanPath = join(runDir, "mission-control-proof-plan.json");
2744
- const sandboxApplyPlanPath = join(runDir, "sandbox-apply-plan.json");
2745
- const strictBudgetProofPlanPath = join(runDir, "strict-budget-proof-plan.json");
2746
- const modelRoutingProofPlanPath = join(runDir, "model-routing-proof-plan.json");
2747
- const currentSourceFingerprintPath = join(runDir, "current-source-fingerprint.json");
2748
- const finalE2EProofPlanPath = join(runDir, "final-e2e-proof-plan.json");
2749
- const finalNoShipOraclePath = join(runDir, "final-no-ship-oracle.json");
2750
- const completionGatePath = join(runDir, "completion-gate.json");
2751
- const validationPath = join(runDir, "validation.json");
2752
- const finalReportPath = join(runDir, "final-report.md");
2753
- writeFileSync(factoryRunRefPath, `${JSON.stringify(factoryRunRef, null, 2)}\n`);
2754
- writeFileSync(oracleReviewPath, `${JSON.stringify(oracleReview, null, 2)}\n`);
2755
- writeFileSync(promotionPlanPath, `${JSON.stringify(promotionPlan, null, 2)}\n`);
2756
- writeFileSync(promotionProofPlanPath, `${JSON.stringify(promotionProofPlan, null, 2)}\n`);
2757
- writeFileSync(schedulerPlanPath, `${JSON.stringify(schedulerPlan, null, 2)}\n`);
2758
- writeFileSync(schedulerProofPlanPath, `${JSON.stringify(schedulerProofPlan, null, 2)}\n`);
2759
- writeFileSync(missionControlPlanPath, `${JSON.stringify(missionControlPlan, null, 2)}\n`);
2760
- writeFileSync(missionControlProofPlanPath, `${JSON.stringify(missionControlProofPlan, null, 2)}\n`);
2761
- writeFileSync(sandboxApplyPlanPath, `${JSON.stringify(sandboxApplyPlan, null, 2)}\n`);
2762
- writeFileSync(strictBudgetProofPlanPath, `${JSON.stringify(strictBudgetProofPlan, null, 2)}\n`);
2763
- writeFileSync(modelRoutingProofPlanPath, `${JSON.stringify(modelRoutingProofPlan, null, 2)}\n`);
2764
- writeFileSync(currentSourceFingerprintPath, `${JSON.stringify(currentSourceFingerprint, null, 2)}\n`);
2765
- writeFileSync(finalE2EProofPlanPath, `${JSON.stringify(finalE2EProofPlan, null, 2)}\n`);
2766
- writeFileSync(finalNoShipOraclePath, `${JSON.stringify(finalNoShipOracle, null, 2)}\n`);
2767
- writeFileSync(completionGatePath, `${JSON.stringify(completionGate, null, 2)}\n`);
2768
- writeFileSync(validationPath, `${JSON.stringify(validation, null, 2)}\n`);
2769
- writeFileSync(finalReportPath, buildAutonomousReadOnlySmokeFinalReport(validation, factoryRunRef, oracleReview));
2770
- if (structuralOraclePassed) writeFileSync(smokeAutonomySentinelPath, "smoke-autonomy-passed\n");
2771
- return {
2772
- ...dryRun,
2773
- status: validation.status,
2774
- no_ship: validation.no_ship,
2775
- smokeRunNoShip: validation.smokeRunNoShip,
2776
- globalAutonomyReady: false,
2777
- globalAutonomyNoShip: true,
2778
- factoryRunRef,
2779
- oracleReview,
2780
- promotionPlan,
2781
- promotionProofPlan,
2782
- schedulerPlan,
2783
- schedulerProofPlan,
2784
- missionControlPlan,
2785
- missionControlProofPlan,
2786
- sandboxApplyPlan,
2787
- strictBudgetProofPlan,
2788
- modelRoutingProofPlan,
2789
- currentSourceFingerprint,
2790
- finalE2EProofPlan,
2791
- finalNoShipOracle,
2792
- completionGate,
2793
- validation,
2794
- factoryRunRefPath: `reports/autonomous-runs/${safeRunId}/factory-run-ref.json`,
2795
- oracleReviewPath: `reports/autonomous-runs/${safeRunId}/oracle-review.json`,
2796
- promotionPlanPath: `reports/autonomous-runs/${safeRunId}/promotion-plan.json`,
2797
- promotionProofPlanPath: `reports/autonomous-runs/${safeRunId}/promotion-proof-plan.json`,
2798
- schedulerPlanPath: `reports/autonomous-runs/${safeRunId}/scheduler-plan.json`,
2799
- schedulerProofPlanPath: `reports/autonomous-runs/${safeRunId}/scheduler-proof-plan.json`,
2800
- missionControlPlanPath: `reports/autonomous-runs/${safeRunId}/mission-control-plan.json`,
2801
- missionControlProofPlanPath: `reports/autonomous-runs/${safeRunId}/mission-control-proof-plan.json`,
2802
- sandboxApplyPlanPath: `reports/autonomous-runs/${safeRunId}/sandbox-apply-plan.json`,
2803
- strictBudgetProofPlanPath: `reports/autonomous-runs/${safeRunId}/strict-budget-proof-plan.json`,
2804
- modelRoutingProofPlanPath: `reports/autonomous-runs/${safeRunId}/model-routing-proof-plan.json`,
2805
- currentSourceFingerprintPath: `reports/autonomous-runs/${safeRunId}/current-source-fingerprint.json`,
2806
- finalE2EProofPlanPath: `reports/autonomous-runs/${safeRunId}/final-e2e-proof-plan.json`,
2807
- finalNoShipOraclePath: `reports/autonomous-runs/${safeRunId}/final-no-ship-oracle.json`,
2808
- completionGatePath: `reports/autonomous-runs/${safeRunId}/completion-gate.json`,
2809
- validationPath: `reports/autonomous-runs/${safeRunId}/validation.json`,
2810
- finalReportPath: `reports/autonomous-runs/${safeRunId}/final-report.md`,
2811
- smokeSentinelPath: structuralOraclePassed ? `reports/autonomous-runs/${safeRunId}/SMOKE_AUTONOMY_PASSED.sentinel` : undefined,
2812
- };
2813
- }
2814
-
2815
- export function validateAutonomousReadOnlySmokeRunArtifacts(repoRoot: string, runId: string): Record<string, unknown> {
2816
- const safeRunId = safeFileStem(runId);
2817
- const runDir = join(repoRoot, "reports", "autonomous-runs", safeRunId);
2818
- const requiredArtifacts = ["spec-gate.json", "context-scope.json", "context-pack.json", "runtime-gates.json", "model-routing-plan.json", "model-routing-proof-plan.json", "factory-selection.json", "factory-run-ref.json", "oracle-review.json", "promotion-plan.json", "promotion-proof-plan.json", "scheduler-plan.json", "scheduler-proof-plan.json", "mission-control-plan.json", "mission-control-proof-plan.json", "sandbox-apply-plan.json", "strict-budget-proof-plan.json", "current-source-fingerprint.json", "final-e2e-proof-plan.json", "final-no-ship-oracle.json", "completion-gate.json", "validation.json", "final-report.md", "SMOKE_AUTONOMY_PASSED.sentinel"];
2819
- const jsonArtifacts = requiredArtifacts.filter((name) => name.endsWith(".json"));
2820
- const parsedArtifacts: Record<string, Record<string, unknown>> = {};
2821
- const artifacts = requiredArtifacts.map((name) => {
2822
- const artifactPath = join(runDir, name);
2823
- const present = existsSync(artifactPath);
2824
- if (!present) return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, bodyStored: false };
2825
- if (!name.endsWith(".json")) return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, hash: artifactHashIfPresent(artifactPath), bodyStored: false };
2826
- const read = readJsonArtifact(artifactPath);
2827
- if (isRecord(read.parsed)) parsedArtifacts[name] = read.parsed;
2828
- return { name, path: `reports/autonomous-runs/${safeRunId}/${name}`, present, hash: read.hash, schema: isRecord(read.parsed) ? read.parsed.schema : undefined, error: read.error, bodyStored: false };
2829
- });
2830
- const artifact = (name: string): Record<string, unknown> => parsedArtifacts[name] ?? {};
2831
- const runtimeGates = artifact("runtime-gates.json");
2832
- const modelRoutingPlan = artifact("model-routing-plan.json");
2833
- const modelRoutingProofPlan = artifact("model-routing-proof-plan.json");
2834
- const factorySelection = artifact("factory-selection.json");
2835
- const factoryRunRef = artifact("factory-run-ref.json");
2836
- const oracleReview = artifact("oracle-review.json");
2837
- const promotionPlan = artifact("promotion-plan.json");
2838
- const promotionProofPlan = artifact("promotion-proof-plan.json");
2839
- const schedulerPlan = artifact("scheduler-plan.json");
2840
- const schedulerProofPlan = artifact("scheduler-proof-plan.json");
2841
- const missionControlPlan = artifact("mission-control-plan.json");
2842
- const missionControlProofPlan = artifact("mission-control-proof-plan.json");
2843
- const sandboxApplyPlan = artifact("sandbox-apply-plan.json");
2844
- const strictBudgetProofPlan = artifact("strict-budget-proof-plan.json");
2845
- const currentSourceFingerprint = artifact("current-source-fingerprint.json");
2846
- const finalE2EProofPlan = artifact("final-e2e-proof-plan.json");
2847
- const finalNoShipOracle = artifact("final-no-ship-oracle.json");
2848
- const completionGate = artifact("completion-gate.json");
2849
- const validation = artifact("validation.json");
2850
- const currentSourceFingerprintFreshness = validateAutonomousCurrentSourceFingerprintFreshness(repoRoot, currentSourceFingerprint, factorySelection);
2851
- const factoryRunId = typeof factoryRunRef.factoryRunId === "string" ? factoryRunRef.factoryRunId : "unknown";
2852
- const factoryRunDir = join(repoRoot, "reports", "factory-runs", factoryRunId);
2853
- const finalDoneSentinelPath = join(runDir, "DONE.sentinel");
2854
- const globalReadySentinelPath = join(runDir, "GLOBAL_AUTONOMY_READY.sentinel");
2855
- const finalDoneSentinelPresent = existsSync(finalDoneSentinelPath);
2856
- const globalReadySentinelPresent = existsSync(globalReadySentinelPath);
2857
- const checks = [
2858
- { name: "required_artifacts_present", passed: artifacts.every((item) => item.present === true), detail: { requiredArtifacts } },
2859
- { name: "json_artifacts_parse", passed: artifacts.filter((item) => item.name.endsWith(".json")).every((item) => !item.error), detail: { jsonArtifacts } },
2860
- { name: "artifact_schemas", passed: factoryRunRef.schema === "zob.autonomous-readonly-smoke-factory-run-ref.v1" && oracleReview.schema === "zob.autonomous-readonly-smoke-oracle-review.v1" && promotionPlan.schema === "zob.autonomous-promotion-plan.v1" && promotionProofPlan.schema === "zob.autonomous-promotion-proof-plan.v1" && schedulerPlan.schema === "zob.autonomous-scheduler-plan.v1" && schedulerProofPlan.schema === "zob.autonomous-scheduler-proof-plan.v1" && missionControlPlan.schema === "zob.autonomous-mission-control-plan.v1" && missionControlProofPlan.schema === "zob.autonomous-mission-control-proof-plan.v1" && sandboxApplyPlan.schema === "zob.autonomous-sandbox-apply-plan.v1" && strictBudgetProofPlan.schema === "zob.autonomous-strict-budget-proof-plan.v1" && modelRoutingProofPlan.schema === "zob.autonomous-model-routing-proof-plan.v1" && currentSourceFingerprint.schema === "zob.autonomous-current-source-fingerprint.v1" && finalE2EProofPlan.schema === "zob.autonomous-final-e2e-proof-plan.v1" && finalNoShipOracle.schema === "zob.autonomous-final-no-ship-oracle.v1" && completionGate.schema === "zob.autonomous-completion-gate.v1" && validation.schema === "zob.autonomous-readonly-smoke-validation.v1", detail: "expected Phase 4A/5B/6B/7B/8B/9A/9B/10B/11F smoke artifact schemas" },
2861
- { name: "runtime_and_model_gates_safe", passed: runtimeGates.childDispatchAllowed === false && runtimeGates.daemonStarted === false && runtimeGates.productionWritesPerformed === false && runtimeGates.autoApply === false && modelRoutingPlan.liveRoutingEnabled === false && modelRoutingPlan.globalLiveRoutingEnabled === false && modelRoutingPlan.childDispatchAllowed === false, detail: "runtime/model routing gates remain disabled" },
2862
- { name: "model_routing_proof_plan_gate_only", passed: modelRoutingProofPlan.status === "model_routing_dispatch_gate_proof_ready_global_default_blocked" && modelRoutingProofPlan.modelRoutingProofReady === true && modelRoutingProofPlan.routingDefaultDisabledProofPassed === true && modelRoutingProofPlan.routingOracleProofPassed === true && modelRoutingProofPlan.routingHighContextProofPassed === true && modelRoutingProofPlan.routingSecurityNoDowngradeProofPassed === true && modelRoutingProofPlan.selectedModelsStored === false && modelRoutingProofPlan.selectedModelHashesOnly === true && modelRoutingProofPlan.finalE2ERequirementCleared === false && modelRoutingProofPlan.no_ship === true && Array.isArray(modelRoutingProofPlan.scenarios) && modelRoutingProofPlan.scenarios.some((scenario) => isRecord(scenario) && scenario.name === "routing_oracle_applies_when_enabled" && scenario.selectedModelClass === "strong_oracle" && typeof scenario.selectedModelHash === "string" && scenario.selectedModelStored === false) && modelRoutingProofPlan.globalLiveRoutingEnabled === false && modelRoutingProofPlan.liveAutonomousRoutingApplied === false && modelRoutingProofPlan.modelRouterUsed === false && modelRoutingProofPlan.routingApplied === false && modelRoutingProofPlan.childDispatchAllowed === false && modelRoutingProofPlan.noExecution === true && modelRoutingProofPlan.globalAutonomyReady === false && modelRoutingProofPlan.globalAutonomyNoShip === true, detail: "Phase 6B proves model routing dispatch gate class selection without enabling global/live routing" },
2863
- { name: "factory_selection_existing", passed: factorySelection.selectionStatus === "existing_factory_selected" && typeof factorySelection.selectedFactory === "string", detail: { selectedFactory: factorySelection.selectedFactory } },
2864
- { name: "factory_smoke_completed", passed: factoryRunRef.status === "done" && factoryRunRef.execution === "deterministic" && factoryRunRef.phaseSentinelPresent === true && factoryRunRef.doneSentinelPresent === true && existsSync(join(factoryRunDir, "SMOKE_PASSED.sentinel")) && existsSync(join(factoryRunDir, "DONE.sentinel")), detail: { factoryRunId } },
2865
- { name: "structural_oracle_passed", passed: oracleReview.verdict === "PASS" && oracleReview.no_ship === false && oracleReview.liveOracleDispatched === false, detail: { oracleType: oracleReview.oracleType } },
2866
- { name: "promotion_plan_smoke_to_pilot_gate", passed: isRecord(promotionPlan.smokeGate) && promotionPlan.smokeGate.passed === true && isRecord(promotionPlan.pilotGate) && promotionPlan.pilotGate.preconditionsMet === true && promotionPlan.pilotGate.executionAllowed === false && promotionPlan.pilotGate.dispatchAllowed === false && isRecord(promotionPlan.batchGate) && promotionPlan.batchGate.preconditionsMet === false && promotionPlan.batchGate.batchConcurrencyCapRequired === true && promotionPlan.globalAutonomyNoShip === true, detail: "Phase 7A promotion gates are metadata-only and do not execute pilot/batch" },
2867
- { name: "promotion_proof_plan_execution_blocked", passed: promotionProofPlan.status === "pilot_batch_promotion_proof_ready_execution_blocked" && promotionProofPlan.promotionProofReady === true && promotionProofPlan.smokeToPilotPreconditionsProved === true && promotionProofPlan.pilotExecutionBlockedProofPassed === true && promotionProofPlan.batchExecutionBlockedProofPassed === true && promotionProofPlan.resumeRetryPolicyProofPassed === true && promotionProofPlan.oraclePolicyProofPassed === true && promotionProofPlan.finalE2ERequirementCleared === false && promotionProofPlan.no_ship === true && promotionProofPlan.pilotExecutionAllowed === false && promotionProofPlan.batchExecutionAllowed === false && promotionProofPlan.pilotExecuted === false && promotionProofPlan.batchExecuted === false && promotionProofPlan.childDispatchAllowed === false && promotionProofPlan.noExecutionBeyondSmoke === true && promotionProofPlan.globalAutonomyReady === false && promotionProofPlan.globalAutonomyNoShip === true, detail: "Phase 7B proves pilot/batch promotion prerequisites and blocked execution without running pilot/batch" },
2868
- { name: "scheduler_plan_disabled_bounded", passed: schedulerPlan.schedulerPlanReady === true && schedulerPlan.schedulerExecutionAllowed === false && schedulerPlan.daemonStarted === false && schedulerPlan.autoStartDaemon === false && schedulerPlan.continuousLoop === false && schedulerPlan.childDispatchAllowed === false && isRecord(schedulerPlan.killSwitch) && schedulerPlan.killSwitch.required === true && isRecord(schedulerPlan.workerPool) && schedulerPlan.workerPool.maxWorkers === 1 && isRecord(schedulerPlan.retryPolicy) && schedulerPlan.retryPolicy.retriesCapped === true && isRecord(schedulerPlan.budgetPolicy) && schedulerPlan.budgetPolicy.strictBudgetRequired === true && schedulerPlan.globalAutonomyNoShip === true, detail: "Phase 8A scheduler plan is bounded and disabled by default" },
2869
- { name: "scheduler_proof_plan_execution_blocked", passed: schedulerProofPlan.status === "scheduler_daemon_proof_ready_execution_blocked" && schedulerProofPlan.schedulerProofReady === true && schedulerProofPlan.daemonDefaultDisabledProofPassed === true && schedulerProofPlan.oneWorkerBoundedProofPassed === true && schedulerProofPlan.stopConditionsProofPassed === true && schedulerProofPlan.killSwitchRetryProofPassed === true && schedulerProofPlan.strictBudgetBeforeDispatchProofPassed === true && schedulerProofPlan.alwaysOnApprovalProofPassed === true && schedulerProofPlan.finalE2ERequirementCleared === false && schedulerProofPlan.no_ship === true && schedulerProofPlan.schedulerExecutionAllowed === false && schedulerProofPlan.daemonStarted === false && schedulerProofPlan.autoStartDaemon === false && schedulerProofPlan.continuousLoop === false && schedulerProofPlan.childDispatchAllowed === false && schedulerProofPlan.productionWritesPerformed === false && schedulerProofPlan.autoApply === false && schedulerProofPlan.noExecutionBeyondSmoke === true && schedulerProofPlan.globalAutonomyReady === false && schedulerProofPlan.globalAutonomyNoShip === true, detail: "Phase 8B proves daemon/scheduler policy and blocked execution without starting daemon" },
2870
- { name: "mission_control_plan_proposal_only", passed: missionControlPlan.missionControlPlanReady === true && missionControlPlan.transportDispatch === false && missionControlPlan.networkComsEnabled === false && missionControlPlan.directWorkerWrites === false && missionControlPlan.childDispatchAllowed === false && isRecord(missionControlPlan.commandPolicy) && missionControlPlan.commandPolicy.proposalOnly === true && missionControlPlan.commandPolicy.directWorkerWrites === false && missionControlPlan.commandPolicy.directWorkerCommandBlocked === true && isRecord(missionControlPlan.comsPolicy) && missionControlPlan.comsPolicy.topologyGuardActive === true && missionControlPlan.comsPolicy.hashOnlyLedgers === true && missionControlPlan.globalAutonomyNoShip === true, detail: "Phase 9A Mission Control/coms plan is proposal-only and transport-disabled" },
2871
- { name: "mission_control_proof_plan_execution_blocked", passed: missionControlProofPlan.status === "mission_control_comms_proof_ready_execution_blocked" && missionControlProofPlan.missionControlProofReady === true && missionControlProofPlan.proposalOnlyCommandsProofPassed === true && missionControlProofPlan.topologyHashOnlyCommsProofPassed === true && missionControlProofPlan.directWorkerCommandsBlockedProofPassed === true && missionControlProofPlan.liveTransportNetworkDisabledProofPassed === true && missionControlProofPlan.liveGlobalRoutingApprovalProofPassed === true && missionControlProofPlan.post8bSchedulerBlockedProofPassed === true && missionControlProofPlan.finalE2ERequirementCleared === false && missionControlProofPlan.no_ship === true && missionControlProofPlan.childDispatchAllowed === false && missionControlProofPlan.daemonStarted === false && missionControlProofPlan.directWorkerWrites === false && missionControlProofPlan.transportDispatch === false && missionControlProofPlan.networkComsEnabled === false && missionControlProofPlan.liveRoutingEnabled === false && missionControlProofPlan.globalLiveRoutingEnabled === false && missionControlProofPlan.productionWritesPerformed === false && missionControlProofPlan.autoApply === false && missionControlProofPlan.globalAutonomyReady === false && missionControlProofPlan.globalAutonomyNoShip === true, detail: "Phase 9B proves proposal-only commands, topology/hash-only comms, blocked direct-worker commands, disabled transport/network, and approval-required live/global routing" },
2872
- { name: "sandbox_apply_plan_metadata_only", passed: sandboxApplyPlan.sandboxApplyPlanReady === true && sandboxApplyPlan.productionWritesPerformed === false && sandboxApplyPlan.autoApply === false && sandboxApplyPlan.realApplyExecuted === false && sandboxApplyPlan.childDispatchAllowed === false && sandboxApplyPlan.globalAutonomyNoShip === true && isRecord(sandboxApplyPlan.isolatedTempWorkspace) && sandboxApplyPlan.isolatedTempWorkspace.required === true && sandboxApplyPlan.isolatedTempWorkspace.executed === true && isRecord(sandboxApplyPlan.diffGate) && sandboxApplyPlan.diffGate.diffHashRequired === true && sandboxApplyPlan.diffGate.diffHashesMatch === true && isRecord(sandboxApplyPlan.oracleDiffReview) && sandboxApplyPlan.oracleDiffReview.required === true && sandboxApplyPlan.oracleDiffReview.reviewPassed === true && isRecord(sandboxApplyPlan.rollbackPolicy) && sandboxApplyPlan.rollbackPolicy.rollbackMetadataRequired === true && sandboxApplyPlan.rollbackPolicy.rollbackPrepared === true && isRecord(sandboxApplyPlan.approvalPolicy) && sandboxApplyPlan.approvalPolicy.manualApprovalRequired === true && sandboxApplyPlan.approvalPolicy.approvedForMainWorkspaceApply === false && isRecord(sandboxApplyPlan.manualApplyPreflight) && sandboxApplyPlan.manualApplyPreflight.required === true && sandboxApplyPlan.manualApplyPreflight.preflightPassed === true && sandboxApplyPlan.manualApplyPreflight.executionAllowedByThisTool === false && sandboxApplyPlan.manualApplyPreflight.realApplyExecuted === false && isRecord(sandboxApplyPlan.mainWorkspaceApply) && sandboxApplyPlan.mainWorkspaceApply.realApplyAllowed === false && sandboxApplyPlan.mainWorkspaceApply.realApplyExecuted === false && sandboxApplyPlan.mainWorkspaceApply.productionWritesPerformed === false, detail: "Phase 10B sandbox/apply plan requires temp workspace, diff hash, oracle review, rollback, manual approval, and manual apply preflight while blocking real apply" },
2873
- { name: "strict_budget_proof_plan_gate_only", passed: strictBudgetProofPlan.status === "strict_budget_dispatch_gate_proof_ready_global_default_blocked" && strictBudgetProofPlan.strictBudgetProofReady === true && strictBudgetProofPlan.strictBudgetAllowProofPassed === true && strictBudgetProofPlan.strictBudgetBlockProofPassed === true && strictBudgetProofPlan.strictBudgetDefaultDisabledProofPassed === true && strictBudgetProofPlan.finalE2ERequirementCleared === false && strictBudgetProofPlan.no_ship === true && Array.isArray(strictBudgetProofPlan.scenarios) && strictBudgetProofPlan.scenarios.some((scenario) => isRecord(scenario) && scenario.name === "strict_gate_blocks_exceedance_pre_dispatch" && scenario.wouldBlockDispatch === true && scenario.gateChildDispatchAllowed === false && scenario.dispatchDecision === "block") && strictBudgetProofPlan.globalStrictBudgetEnabled === false && strictBudgetProofPlan.globalBudgetEnforced === false && strictBudgetProofPlan.liveAutonomousBudgetEnforced === false && strictBudgetProofPlan.budgetEnforced === false && strictBudgetProofPlan.strictEnabled === false && strictBudgetProofPlan.childDispatchAllowed === false && strictBudgetProofPlan.noExecution === true && strictBudgetProofPlan.globalAutonomyReady === false && strictBudgetProofPlan.globalAutonomyNoShip === true, detail: "Phase 5B proves strict dispatch gate allow/block/default-disabled behavior without clearing final live strict-budget requirement" },
2874
- { name: "current_source_fingerprint_hash_only", passed: currentSourceFingerprint.status === "current_source_fingerprint_captured" && currentSourceFingerprint.currentSourceFingerprintReady === true && currentSourceFingerprint.currentSourceFingerprintCaptured === true && currentSourceFingerprint.noMockCurrentSourceE2EProved === false && typeof currentSourceFingerprint.fingerprintHash === "string" && /^[a-f0-9]{64}$/.test(currentSourceFingerprint.fingerprintHash) && Array.isArray(currentSourceFingerprint.sourceFiles) && currentSourceFingerprint.sourceFiles.length > 0 && isRecord(currentSourceFingerprint.fileHashes) && Object.values(currentSourceFingerprint.fileHashes).every((hash) => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash)) && Array.isArray(currentSourceFingerprint.missingFiles) && currentSourceFingerprint.missingFiles.length === 0 && isRecord(currentSourceFingerprint.evidencePolicy) && currentSourceFingerprint.evidencePolicy.hashOnly === true && currentSourceFingerprint.evidencePolicy.sourceBodiesStored === false && isRecord(currentSourceFingerprint.safety) && currentSourceFingerprint.safety.noExecution === true && currentSourceFingerprint.safety.globalAutonomyNoShip === true, detail: "Phase 11C current-source fingerprint captures hash-only source evidence without proving final no-mock E2E" },
2875
- { name: "current_source_fingerprint_fresh", passed: currentSourceFingerprintFreshness.fresh === true && currentSourceFingerprintFreshness.fileHashesMatch === true && currentSourceFingerprintFreshness.fingerprintHashMatches === true && currentSourceFingerprintFreshness.sourceFilesMatch === true && currentSourceFingerprintFreshness.missingFilesMatch === true && currentSourceFingerprintFreshness.currentMissingFiles && Array.isArray(currentSourceFingerprintFreshness.currentMissingFiles) && currentSourceFingerprintFreshness.currentMissingFiles.length === 0, detail: "Phase 11D validator recomputes current source hashes and fails stale/tampered fingerprints" },
2876
- { name: "final_e2e_proof_plan_no_ship", passed: finalE2EProofPlan.status === "blocked_for_final_e2e_proof" && finalE2EProofPlan.finalE2EProofReady === false && finalE2EProofPlan.no_ship === true && Array.isArray(finalE2EProofPlan.blockers) && finalE2EProofPlan.blockers.includes("live_strict_budget_not_enforced") && finalE2EProofPlan.blockers.includes("live_model_routing_not_enabled") && finalE2EProofPlan.blockers.includes("pilot_execution_disabled") && finalE2EProofPlan.blockers.includes("batch_execution_disabled") && finalE2EProofPlan.blockers.includes("final_oracle_missing") && isRecord(finalE2EProofPlan.sentinelPolicy) && finalE2EProofPlan.sentinelPolicy.globalReadySentinelAllowed === false && finalE2EProofPlan.sentinelPolicy.globalReadySentinelPresent === false && isRecord(finalE2EProofPlan.currentSourceProof) && finalE2EProofPlan.currentSourceProof.currentSourceFingerprintCaptured === true && typeof finalE2EProofPlan.currentSourceProof.currentSourceFingerprintHash === "string" && finalE2EProofPlan.currentSourceProof.noMockCurrentSourceE2EProved === false && finalE2EProofPlan.globalAutonomyReady === false && finalE2EProofPlan.globalAutonomyNoShip === true && finalE2EProofPlan.childDispatchAllowed === false && finalE2EProofPlan.productionWritesPerformed === false && finalE2EProofPlan.autoApply === false, detail: "Phase 11C final E2E proof plan references current-source fingerprint while preserving no-ship" },
2877
- { name: "final_no_ship_oracle_blocks_global_autonomy", passed: finalNoShipOracle.verdict === "FAIL" && finalNoShipOracle.no_ship === true && finalNoShipOracle.finalOracleReady === false && finalNoShipOracle.finalOraclePass === false && Array.isArray(finalNoShipOracle.failedChecks) && finalNoShipOracle.failedChecks.includes("final_e2e_proof_ready") && finalNoShipOracle.failedChecks.includes("no_mock_current_source_e2e_proved") && isRecord(finalNoShipOracle.decision) && finalNoShipOracle.decision.globalAutonomyReady === false && finalNoShipOracle.decision.globalAutonomyNoShip === true && finalNoShipOracle.decision.writeGlobalReadySentinelAllowed === false && finalNoShipOracle.globalAutonomyReady === false && finalNoShipOracle.globalAutonomyNoShip === true && finalNoShipOracle.childDispatchAllowed === false && finalNoShipOracle.productionWritesPerformed === false && finalNoShipOracle.autoApply === false, detail: "Phase 11E deterministic final no-ship oracle blocks global autonomy until final E2E proof" },
2878
- { name: "completion_gate_blocks_goal_completion", passed: completionGate.status === "blocked_for_goal_completion" && completionGate.completionReady === false && completionGate.allRequirementsVerified === false && completionGate.no_ship === true && completionGate.updateGoalAllowed === false && completionGate.requiredGoalStatus === "in_progress" && Array.isArray(completionGate.failedChecks) && completionGate.failedChecks.includes("final_e2e_proof_ready") && isRecord(completionGate.decision) && completionGate.decision.updateGoalStatusCompleteAllowed === false && completionGate.decision.globalAutonomyReady === false && completionGate.decision.globalAutonomyNoShip === true && completionGate.decision.writeGlobalReadySentinelAllowed === false && completionGate.globalAutonomyReady === false && completionGate.globalAutonomyNoShip === true && completionGate.childDispatchAllowed === false && completionGate.productionWritesPerformed === false && completionGate.autoApply === false, detail: "Phase 11F completion gate blocks update_goal complete until every final requirement is verified" },
2879
- { name: "final_global_sentinels_absent", passed: finalDoneSentinelPresent === false && globalReadySentinelPresent === false, detail: { doneSentinelPresent: finalDoneSentinelPresent, globalReadySentinelPresent } },
2880
- { name: "validation_passed_scope_limited", passed: validation.passed === true && validation.status === "smoke_autonomy_passed" && validation.no_ship === false && validation.globalAutonomyReady === false && validation.globalAutonomyNoShip === true && validation.childDispatchAllowed === false && validation.productionWritesPerformed === false && validation.autoApply === false, detail: "run-scoped smoke pass without global autonomy" },
2881
- { name: "json_artifacts_body_free", passed: jsonArtifacts.every((name) => isRecord(parsedArtifacts[name]) && !hasForbiddenBodyKeys(parsedArtifacts[name])), detail: "no forbidden plaintext body keys" },
2882
- ];
2883
- const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
2884
- const result = {
2885
- schema: "zob.autonomous-readonly-smoke-artifact-validation.v1",
2886
- runId: safeRunId,
2887
- valid: failedChecks.length === 0,
2888
- failedChecks,
2889
- checks,
2890
- artifacts,
2891
- finalGlobalSentinels: {
2892
- doneSentinelPresent: finalDoneSentinelPresent,
2893
- globalReadySentinelPresent,
2894
- doneSentinelAllowed: false,
2895
- globalReadySentinelAllowed: false,
2896
- },
2897
- currentSourceFingerprintFreshness,
2898
- globalAutonomyReady: false,
2899
- globalAutonomyNoShip: true,
2900
- childDispatchAllowed: false,
2901
- daemonStarted: false,
2902
- productionWritesPerformed: false,
2903
- autoApply: false,
2904
- liveRoutingEnabled: false,
2905
- bodyStored: false,
2906
- promptBodiesStored: false,
2907
- outputBodiesStored: false,
2908
- generatedAt: new Date().toISOString(),
2909
- };
2910
- if (hasForbiddenBodyKeys(result)) throw new Error("autonomous readonly smoke validation would store forbidden plaintext body keys");
2911
- return result;
2912
- }
1
+ export type { AutonomousApplyPolicy, AutonomousBudgetProfile, AutonomousRisk, AutonomousLevel, AutonomousRuntimeDryRunInput, AutonomousReadOnlySmokeRunInput } from "./autonomous-runtime/types.js";
2
+ export { buildAutonomousRuntimeDryRun, buildAutonomousRuntimeDryRunValidation, buildAutonomousRuntimeDryRunFinalReport } from "./autonomous-runtime/dry-run.js";
3
+ export { writeAutonomousRuntimeDryRunReport, writeAutonomousReadOnlySmokeRunReport } from "./autonomous-runtime/report-writers.js";
4
+ export { validateAutonomousRuntimeDryRunArtifacts, validateAutonomousReadOnlySmokeRunArtifacts } from "./autonomous-runtime/validation.js";