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
@@ -0,0 +1,1286 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { validateDaemonPolicyConfig } from "../daemon-policy.js";
4
+ import { MISSION_CONTROL_COMMANDS, buildMissionControlCommandProposal, buildMissionControlSnapshot, buildZobComsTransportReadiness, buildZobCommunicationReadinessAudit } from "../../coms/mission-control.js";
5
+ import { loadTeamDefinition, validateTeamDefinition } from "../../topology/teams.js";
6
+ import { sha256 } from "../../../core/utils/hashing.js";
7
+ import { safeFileStem } from "../../../core/utils/paths.js";
8
+ import { isRecord } from "../../../core/utils/records.js";
9
+ import { AUTONOMOUS_CURRENT_SOURCE_FINGERPRINT_FILES, hasForbiddenBodyKeys } from "./dry-run.js";
10
+
11
+ export function readJsonArtifact(path: string): { parsed?: Record<string, unknown> | unknown[]; hash?: string; error?: string } {
12
+ try {
13
+ const raw = readFileSync(path, "utf8");
14
+ const parsed = JSON.parse(raw) as unknown;
15
+ 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" };
16
+ } catch (error) {
17
+ return { error: error instanceof Error ? error.message : String(error) };
18
+ }
19
+ }
20
+
21
+ export function artifactHashIfPresent(path: string): string | undefined {
22
+ if (!existsSync(path)) return undefined;
23
+ return sha256(readFileSync(path, "utf8"));
24
+ }
25
+
26
+ export function relativeFactoryRunPath(runId: string, artifact?: string): string {
27
+ return artifact ? `reports/factory-runs/${runId}/${artifact}` : `reports/factory-runs/${runId}`;
28
+ }
29
+
30
+ export function buildAutonomousPromotionPlan(input: { runId: string; selectedFactory?: string; factoryRunRef: Record<string, unknown>; oracleReview: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
31
+ const smokeGatePassed = input.validation.status === "smoke_autonomy_passed"
32
+ && input.validation.no_ship === false
33
+ && input.factoryRunRef.status === "done"
34
+ && input.factoryRunRef.phaseSentinelPresent === true
35
+ && input.factoryRunRef.doneSentinelPresent === true
36
+ && input.oracleReview.verdict === "PASS"
37
+ && input.oracleReview.no_ship === false;
38
+ const factoryRunId = typeof input.factoryRunRef.factoryRunId === "string" ? input.factoryRunRef.factoryRunId : "unknown";
39
+ const plan = {
40
+ schema: "zob.autonomous-promotion-plan.v1",
41
+ runId: input.runId,
42
+ selectedFactory: input.selectedFactory,
43
+ sourceSmoke: {
44
+ autonomousRunId: input.runId,
45
+ factoryRunId,
46
+ smokeSentinelRef: relativeFactoryRunPath(factoryRunId, "SMOKE_PASSED.sentinel"),
47
+ doneSentinelRef: relativeFactoryRunPath(factoryRunId, "DONE.sentinel"),
48
+ oracleReviewRef: `reports/autonomous-runs/${input.runId}/oracle-review.json`,
49
+ },
50
+ smokeGate: {
51
+ passed: smokeGatePassed,
52
+ sentinelPresent: input.factoryRunRef.phaseSentinelPresent === true,
53
+ doneSentinelPresent: input.factoryRunRef.doneSentinelPresent === true,
54
+ oraclePass: input.oracleReview.verdict === "PASS" && input.oracleReview.no_ship === false,
55
+ structuralOracleOnly: input.oracleReview.oracleType === "deterministic_structural",
56
+ },
57
+ pilotGate: {
58
+ preconditionsMet: smokeGatePassed,
59
+ executionAllowed: false,
60
+ dispatchAllowed: false,
61
+ reason: "phase_7a_promotion_metadata_only_no_pilot_execution",
62
+ requiredBeforeExecution: ["strict_budget_gate", "live_or_structural_oracle_pass", "current_source_factory_proof", "operator_or_parent_gate", "PILOT_PASSED.sentinel_on_success"],
63
+ maxItems: 10,
64
+ prerequisiteSmokeRunId: factoryRunId,
65
+ oracleReviewPath: `reports/autonomous-runs/${input.runId}/oracle-review.json`,
66
+ },
67
+ batchGate: {
68
+ preconditionsMet: false,
69
+ executionAllowed: false,
70
+ dispatchAllowed: false,
71
+ reason: "pilot_not_executed_in_phase_7a",
72
+ requiredBeforeExecution: ["PILOT_PASSED.sentinel", "pilot_oracle_PASS_no_ship_false", "batch_concurrency_cap", "strict_budget_gate", "final_oracle_gate"],
73
+ batchConcurrencyCapRequired: true,
74
+ },
75
+ resumePolicy: {
76
+ resumeOnlyIncompleteItems: true,
77
+ doNotRerunPassedItems: true,
78
+ stopOnRepeatedFail: true,
79
+ maxRetryPolicyRequiredBeforeLiveScale: true,
80
+ },
81
+ oraclePolicy: {
82
+ smokeOracleRequired: true,
83
+ pilotOracleRequired: true,
84
+ batchOracleRequired: true,
85
+ warnOrFailTreatedAsNoShip: true,
86
+ },
87
+ strictBudgetRequired: true,
88
+ liveRoutingEnabled: false,
89
+ childDispatchAllowed: false,
90
+ pilotExecuted: false,
91
+ batchExecuted: false,
92
+ noExecutionBeyondSmoke: true,
93
+ globalAutonomyReady: false,
94
+ globalAutonomyNoShip: true,
95
+ bodyStored: false,
96
+ promptBodiesStored: false,
97
+ outputBodiesStored: false,
98
+ };
99
+ if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous promotion plan would store forbidden plaintext body keys");
100
+ return plan;
101
+ }
102
+
103
+ export function buildAutonomousPromotionProofPlan(input: { runId: string; promotionPlan: Record<string, unknown>; factoryRunRef: Record<string, unknown>; oracleReview: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
104
+ const smokeGate = isRecord(input.promotionPlan.smokeGate) ? input.promotionPlan.smokeGate : {};
105
+ const pilotGate = isRecord(input.promotionPlan.pilotGate) ? input.promotionPlan.pilotGate : {};
106
+ const batchGate = isRecord(input.promotionPlan.batchGate) ? input.promotionPlan.batchGate : {};
107
+ const resumePolicy = isRecord(input.promotionPlan.resumePolicy) ? input.promotionPlan.resumePolicy : {};
108
+ const oraclePolicy = isRecord(input.promotionPlan.oraclePolicy) ? input.promotionPlan.oraclePolicy : {};
109
+ const scenarios = [
110
+ {
111
+ name: "smoke_to_pilot_preconditions_met",
112
+ passed: smokeGate.passed === true && smokeGate.sentinelPresent === true && smokeGate.doneSentinelPresent === true && smokeGate.oraclePass === true,
113
+ evidenceRefs: [`reports/autonomous-runs/${safeFileStem(input.runId)}/promotion-plan.json`, `reports/autonomous-runs/${safeFileStem(input.runId)}/oracle-review.json`],
114
+ dispatchAllowed: false,
115
+ },
116
+ {
117
+ name: "pilot_execution_blocked_until_live_gates",
118
+ passed: pilotGate.preconditionsMet === true && pilotGate.executionAllowed === false && pilotGate.dispatchAllowed === false && input.promotionPlan.pilotExecuted === false,
119
+ blockers: ["pilot_execution_disabled_until_live_budget_routing_daemon_oracle_gates"],
120
+ dispatchAllowed: false,
121
+ },
122
+ {
123
+ name: "batch_execution_blocked_without_pilot_oracle_and_concurrency",
124
+ passed: batchGate.preconditionsMet === false && batchGate.executionAllowed === false && batchGate.dispatchAllowed === false && batchGate.batchConcurrencyCapRequired === true && input.promotionPlan.batchExecuted === false,
125
+ blockers: ["pilot_not_executed", "pilot_oracle_missing", "batch_concurrency_cap_missing"],
126
+ dispatchAllowed: false,
127
+ },
128
+ {
129
+ name: "resume_retry_policy_safe_before_scale",
130
+ passed: resumePolicy.resumeOnlyIncompleteItems === true && resumePolicy.doNotRerunPassedItems === true && resumePolicy.stopOnRepeatedFail === true && resumePolicy.maxRetryPolicyRequiredBeforeLiveScale === true,
131
+ dispatchAllowed: false,
132
+ },
133
+ {
134
+ name: "oracle_policy_no_warn_fail_promotion",
135
+ passed: oraclePolicy.smokeOracleRequired === true && oraclePolicy.pilotOracleRequired === true && oraclePolicy.batchOracleRequired === true && oraclePolicy.warnOrFailTreatedAsNoShip === true,
136
+ dispatchAllowed: false,
137
+ },
138
+ ];
139
+ const checks = [
140
+ { name: "smoke_gate_passed", passed: scenarios[0].passed === true },
141
+ { name: "pilot_blocked_no_execution", passed: scenarios[1].passed === true },
142
+ { name: "batch_blocked_no_execution", passed: scenarios[2].passed === true },
143
+ { name: "resume_retry_policy_safe", passed: scenarios[3].passed === true },
144
+ { name: "oracle_policy_safe", passed: scenarios[4].passed === true },
145
+ { 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 },
146
+ ];
147
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
148
+ const proof = {
149
+ schema: "zob.autonomous-promotion-proof-plan.v1",
150
+ runId: input.runId,
151
+ phase: "7B",
152
+ status: failedChecks.length === 0 ? "pilot_batch_promotion_proof_ready_execution_blocked" : "pilot_batch_promotion_proof_incomplete",
153
+ promotionProofReady: failedChecks.length === 0,
154
+ smokeToPilotPreconditionsProved: scenarios[0].passed === true,
155
+ pilotExecutionBlockedProofPassed: scenarios[1].passed === true,
156
+ batchExecutionBlockedProofPassed: scenarios[2].passed === true,
157
+ resumeRetryPolicyProofPassed: scenarios[3].passed === true,
158
+ oraclePolicyProofPassed: scenarios[4].passed === true,
159
+ finalE2ERequirementCleared: false,
160
+ no_ship: true,
161
+ checks,
162
+ failedChecks,
163
+ scenarios,
164
+ evidenceRefs: [
165
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/promotion-plan.json`,
166
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/factory-run-ref.json`,
167
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/oracle-review.json`,
168
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
169
+ ],
170
+ blockers: [
171
+ "pilot_execution_disabled",
172
+ "batch_execution_disabled",
173
+ "pilot_oracle_missing",
174
+ "batch_concurrency_cap_missing",
175
+ "final_e2e_pilot_batch_evidence_required",
176
+ ],
177
+ pilotExecutionAllowed: false,
178
+ batchExecutionAllowed: false,
179
+ pilotExecuted: false,
180
+ batchExecuted: false,
181
+ pilotOraclePass: false,
182
+ batchConcurrencyCapPresent: false,
183
+ childDispatchAllowed: false,
184
+ daemonStarted: false,
185
+ productionWritesPerformed: false,
186
+ autoApply: false,
187
+ noExecutionBeyondSmoke: true,
188
+ globalAutonomyReady: false,
189
+ globalAutonomyNoShip: true,
190
+ bodyStored: false,
191
+ promptBodiesStored: false,
192
+ outputBodiesStored: false,
193
+ };
194
+ if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous promotion proof plan would store forbidden plaintext body keys");
195
+ return proof;
196
+ }
197
+
198
+ export function buildAutonomousSchedulerPlan(repoRoot: string, input: { runId: string; promotionPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
199
+ const daemonPolicy = validateDaemonPolicyConfig(repoRoot);
200
+ const allowedJobTypes = Array.isArray(daemonPolicy.allowedJobTypes) ? daemonPolicy.allowedJobTypes.filter((item): item is string => typeof item === "string") : [];
201
+ const requiredStopConditions = Array.isArray(daemonPolicy.requiredStopConditions) ? daemonPolicy.requiredStopConditions.filter((item): item is string => typeof item === "string") : [];
202
+ const promotionReady = isRecord(input.promotionPlan.smokeGate) && input.promotionPlan.smokeGate.passed === true;
203
+ const checks = [
204
+ { name: "daemon_policy_valid", passed: daemonPolicy.present === true && daemonPolicy.valid === true },
205
+ { name: "daemon_disabled_by_default", passed: daemonPolicy.daemonEnabled === false && daemonPolicy.alwaysOnDaemonEnabled === false && daemonPolicy.autoStartDaemon === false && daemonPolicy.continuousLoop === false },
206
+ { name: "one_worker_bounded", passed: daemonPolicy.maxWorkersDefault === 1 && daemonPolicy.maxWorkersMax === 1 },
207
+ { name: "read_only_work_kinds_only", passed: allowedJobTypes.length > 0 && daemonPolicy.writeAdaptersEnabled === false && daemonPolicy.productionWritesPerformed === false && daemonPolicy.autoApply === false },
208
+ { name: "terminal_stop_conditions_available", passed: requiredStopConditions.includes("timeout") && requiredStopConditions.includes("blocked") && requiredStopConditions.includes("fail_loop") && requiredStopConditions.includes("no_ship") },
209
+ { name: "kill_switch_required", passed: true },
210
+ { name: "leases_and_heartbeat_required", passed: true },
211
+ { name: "budget_required_before_dispatch", passed: true },
212
+ { name: "scheduler_execution_disabled", passed: true },
213
+ ];
214
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
215
+ const plan = {
216
+ schema: "zob.autonomous-scheduler-plan.v1",
217
+ runId: input.runId,
218
+ schedulerPlanReady: failedChecks.length === 0,
219
+ failedChecks,
220
+ checks,
221
+ promotionReady,
222
+ daemonPolicy,
223
+ queuePolicy: {
224
+ allowedWorkKinds: allowedJobTypes,
225
+ initialWorkKinds: ["docs_watch", "repo_audit_readonly", "todo_risk_report", "session_analysis"].filter((kind) => allowedJobTypes.includes(kind)),
226
+ writeWorkAccepted: false,
227
+ claimAtMostOnePerTick: daemonPolicy.claimAtMostOneJobPerTick === true,
228
+ boundedQueueOnly: true,
229
+ },
230
+ leasePolicy: {
231
+ leaseRequired: true,
232
+ leaseTtlMs: 300_000,
233
+ maxLeaseRenewals: 0,
234
+ staleLeaseFailsCleanly: true,
235
+ leaseOwnerHashOnly: true,
236
+ },
237
+ heartbeatPolicy: {
238
+ heartbeatRequired: true,
239
+ heartbeatIntervalMs: 30_000,
240
+ staleHeartbeatTimeoutMs: 90_000,
241
+ staleHeartbeatStopCondition: "timeout",
242
+ },
243
+ timeoutPolicy: {
244
+ perWorkItemTimeoutMs: 300_000,
245
+ globalTickTimeoutMs: 600_000,
246
+ timeoutStopCondition: "timeout",
247
+ },
248
+ retryPolicy: {
249
+ retriesCapped: true,
250
+ maxRetriesPerWorkItem: 1,
251
+ failLoopThreshold: 3,
252
+ repeatedFailureStopCondition: "fail_loop",
253
+ doNotRetryNoShip: true,
254
+ },
255
+ killSwitch: {
256
+ required: true,
257
+ defaultState: "stopped_until_manual_start",
258
+ stopFileRef: ".pi/queue/STOP_DAEMON.sentinel",
259
+ checkedBeforeEachTick: true,
260
+ stopsQueueCleanly: true,
261
+ },
262
+ workerPool: {
263
+ defaultWorkers: 1,
264
+ maxWorkers: 1,
265
+ workerPoolBounded: true,
266
+ },
267
+ budgetPolicy: {
268
+ strictBudgetRequired: true,
269
+ perRunCapsRequired: true,
270
+ perDayCapsRequired: true,
271
+ budgetEnforced: false,
272
+ dispatchBlockedUntilStrictBudgetEnforced: true,
273
+ },
274
+ stopConditions: requiredStopConditions,
275
+ approvalPolicy: {
276
+ manualStartRequiresApproval: true,
277
+ alwaysOnRequiresApproval: true,
278
+ schedulerAutostartAllowed: false,
279
+ },
280
+ schedulerExecutionAllowed: false,
281
+ daemonEnabled: false,
282
+ alwaysOnDaemonEnabled: false,
283
+ autoStartDaemon: false,
284
+ continuousLoop: false,
285
+ daemonStarted: false,
286
+ cronEnabled: false,
287
+ childDispatchAllowed: false,
288
+ liveChildExecution: false,
289
+ networkAccessed: false,
290
+ writeAdaptersEnabled: false,
291
+ productionWritesPerformed: false,
292
+ autoApply: false,
293
+ pilotExecuted: false,
294
+ batchExecuted: false,
295
+ globalAutonomyReady: false,
296
+ globalAutonomyNoShip: true,
297
+ bodyStored: false,
298
+ promptBodiesStored: false,
299
+ outputBodiesStored: false,
300
+ };
301
+ if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous scheduler plan would store forbidden plaintext body keys");
302
+ return plan;
303
+ }
304
+
305
+ export function buildAutonomousSchedulerProofPlan(input: { runId: string; schedulerPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
306
+ const queuePolicy = isRecord(input.schedulerPlan.queuePolicy) ? input.schedulerPlan.queuePolicy : {};
307
+ const leasePolicy = isRecord(input.schedulerPlan.leasePolicy) ? input.schedulerPlan.leasePolicy : {};
308
+ const heartbeatPolicy = isRecord(input.schedulerPlan.heartbeatPolicy) ? input.schedulerPlan.heartbeatPolicy : {};
309
+ const timeoutPolicy = isRecord(input.schedulerPlan.timeoutPolicy) ? input.schedulerPlan.timeoutPolicy : {};
310
+ const retryPolicy = isRecord(input.schedulerPlan.retryPolicy) ? input.schedulerPlan.retryPolicy : {};
311
+ const killSwitch = isRecord(input.schedulerPlan.killSwitch) ? input.schedulerPlan.killSwitch : {};
312
+ const workerPool = isRecord(input.schedulerPlan.workerPool) ? input.schedulerPlan.workerPool : {};
313
+ const budgetPolicy = isRecord(input.schedulerPlan.budgetPolicy) ? input.schedulerPlan.budgetPolicy : {};
314
+ const approvalPolicy = isRecord(input.schedulerPlan.approvalPolicy) ? input.schedulerPlan.approvalPolicy : {};
315
+ const daemonPolicy = isRecord(input.schedulerPlan.daemonPolicy) ? input.schedulerPlan.daemonPolicy : {};
316
+ const stopConditions = Array.isArray(input.schedulerPlan.stopConditions) ? input.schedulerPlan.stopConditions.filter((condition): condition is string => typeof condition === "string") : [];
317
+ const scenarios = [
318
+ {
319
+ name: "daemon_default_disabled",
320
+ passed: input.schedulerPlan.schedulerExecutionAllowed === false && input.schedulerPlan.daemonStarted === false && input.schedulerPlan.autoStartDaemon === false && input.schedulerPlan.continuousLoop === false && input.schedulerPlan.cronEnabled === false,
321
+ dispatchAllowed: false,
322
+ },
323
+ {
324
+ name: "one_worker_bounded_readonly_queue",
325
+ passed: workerPool.defaultWorkers === 1 && workerPool.maxWorkers === 1 && workerPool.workerPoolBounded === true && queuePolicy.writeWorkAccepted === false && queuePolicy.claimAtMostOnePerTick === true,
326
+ dispatchAllowed: false,
327
+ },
328
+ {
329
+ name: "lease_heartbeat_timeout_stop_conditions_required",
330
+ 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"),
331
+ dispatchAllowed: false,
332
+ },
333
+ {
334
+ name: "kill_switch_and_retry_stop_clean",
335
+ passed: killSwitch.required === true && killSwitch.checkedBeforeEachTick === true && killSwitch.stopsQueueCleanly === true && retryPolicy.retriesCapped === true && retryPolicy.doNotRetryNoShip === true && retryPolicy.repeatedFailureStopCondition === "fail_loop",
336
+ dispatchAllowed: false,
337
+ },
338
+ {
339
+ name: "strict_budget_required_before_daemon_dispatch",
340
+ passed: budgetPolicy.strictBudgetRequired === true && budgetPolicy.perRunCapsRequired === true && budgetPolicy.perDayCapsRequired === true && budgetPolicy.budgetEnforced === false && budgetPolicy.dispatchBlockedUntilStrictBudgetEnforced === true,
341
+ dispatchAllowed: false,
342
+ },
343
+ {
344
+ name: "always_on_requires_future_approval",
345
+ passed: approvalPolicy.manualStartRequiresApproval === true && approvalPolicy.alwaysOnRequiresApproval === true && approvalPolicy.schedulerAutostartAllowed === false && daemonPolicy.alwaysOnDaemonEnabled === false,
346
+ dispatchAllowed: false,
347
+ },
348
+ ];
349
+ const checks = [
350
+ { name: "scheduler_plan_ready", passed: input.schedulerPlan.schedulerPlanReady === true },
351
+ { name: "daemon_default_disabled", passed: scenarios[0].passed === true },
352
+ { name: "one_worker_bounded_readonly_queue", passed: scenarios[1].passed === true },
353
+ { name: "lease_heartbeat_timeout_stop_conditions_required", passed: scenarios[2].passed === true },
354
+ { name: "kill_switch_and_retry_stop_clean", passed: scenarios[3].passed === true },
355
+ { name: "strict_budget_required_before_daemon_dispatch", passed: scenarios[4].passed === true },
356
+ { name: "always_on_requires_future_approval", passed: scenarios[5].passed === true },
357
+ { 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 },
358
+ ];
359
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
360
+ const proof = {
361
+ schema: "zob.autonomous-scheduler-proof-plan.v1",
362
+ runId: input.runId,
363
+ phase: "8B",
364
+ status: failedChecks.length === 0 ? "scheduler_daemon_proof_ready_execution_blocked" : "scheduler_daemon_proof_incomplete",
365
+ schedulerProofReady: failedChecks.length === 0,
366
+ daemonDefaultDisabledProofPassed: scenarios[0].passed === true,
367
+ oneWorkerBoundedProofPassed: scenarios[1].passed === true,
368
+ stopConditionsProofPassed: scenarios[2].passed === true,
369
+ killSwitchRetryProofPassed: scenarios[3].passed === true,
370
+ strictBudgetBeforeDispatchProofPassed: scenarios[4].passed === true,
371
+ alwaysOnApprovalProofPassed: scenarios[5].passed === true,
372
+ finalE2ERequirementCleared: false,
373
+ no_ship: true,
374
+ checks,
375
+ failedChecks,
376
+ scenarios,
377
+ evidenceRefs: [
378
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/scheduler-plan.json`,
379
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
380
+ ".pi/daemon-policy.json",
381
+ ],
382
+ blockers: [
383
+ "daemon_scheduler_not_started",
384
+ "always_on_daemon_not_enabled",
385
+ "daemon_autostart_disabled",
386
+ "final_e2e_daemon_scheduler_evidence_required",
387
+ ],
388
+ schedulerExecutionAllowed: false,
389
+ daemonStarted: false,
390
+ autoStartDaemon: false,
391
+ continuousLoop: false,
392
+ cronEnabled: false,
393
+ childDispatchAllowed: false,
394
+ liveChildExecution: false,
395
+ writeAdaptersEnabled: false,
396
+ productionWritesPerformed: false,
397
+ autoApply: false,
398
+ noExecutionBeyondSmoke: true,
399
+ globalAutonomyReady: false,
400
+ globalAutonomyNoShip: true,
401
+ bodyStored: false,
402
+ promptBodiesStored: false,
403
+ outputBodiesStored: false,
404
+ };
405
+ if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous scheduler proof plan would store forbidden plaintext body keys");
406
+ return proof;
407
+ }
408
+
409
+ export function buildAutonomousMissionControlPlan(repoRoot: string, input: { runId: string; schedulerPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
410
+ const team = loadTeamDefinition(repoRoot, "zob-core");
411
+ const teamErrors = [...team.errors, ...validateTeamDefinition(repoRoot, team.definition)];
412
+ const definition = team.definition;
413
+ const snapshot = definition ? buildMissionControlSnapshot(repoRoot, definition, { runId: input.runId, limit: 5 }) : undefined;
414
+ const communicationAudit = definition ? buildZobCommunicationReadinessAudit(repoRoot, definition) : undefined;
415
+ const transport = buildZobComsTransportReadiness(repoRoot);
416
+ const orchestratorId = definition?.orchestrator.id ?? "orchestrator";
417
+ const commandProposals = definition ? MISSION_CONTROL_COMMANDS.map((command) => buildMissionControlCommandProposal(definition, {
418
+ proposalId: `auto-${sha256(`${input.runId}-${command}`).slice(0, 16)}-${command}`,
419
+ runId: input.runId,
420
+ command,
421
+ targetRole: orchestratorId,
422
+ rationaleHash: sha256(`autonomous mission control ${command}`),
423
+ artifactRefs: [`reports/autonomous-runs/${input.runId}/validation.json`],
424
+ })) : [];
425
+ const directWorkerErrors = definition && definition.workers[0] ? (() => {
426
+ try {
427
+ buildMissionControlCommandProposal(definition, {
428
+ proposalId: `auto-${sha256(`${input.runId}-blocked-worker`).slice(0, 16)}-blocked-worker`,
429
+ runId: input.runId,
430
+ command: "stop",
431
+ targetRole: definition.workers[0].id,
432
+ rationaleHash: sha256("direct worker blocked"),
433
+ });
434
+ return [] as string[];
435
+ } catch (error) {
436
+ return [error instanceof Error ? error.message : String(error)];
437
+ }
438
+ })() : ["no worker role available for direct worker guard"];
439
+ const transportFailedChecks = Array.isArray(transport.failedChecks) ? transport.failedChecks.filter((check): check is string => typeof check === "string") : [];
440
+ const communicationFailedChecks = Array.isArray(communicationAudit?.failedChecks) ? communicationAudit.failedChecks.filter((check): check is string => typeof check === "string") : [];
441
+ const communicationChecks = Array.isArray(communicationAudit?.checks) ? communicationAudit.checks.filter(isRecord) : [];
442
+ const communicationCheckPassed = (name: string): boolean => communicationChecks.some((check) => check.name === name && check.passed === true);
443
+ const livePeerAbsenceBlocksDelivery = transport.mode === "required_local"
444
+ && transport.networkEnabled === false
445
+ && transport.dispatchAllowed === true
446
+ && transportFailedChecks.length > 0
447
+ && transportFailedChecks.every((check) => check === "required_local_live_ready_when_enabled");
448
+ const proposalOnlyCommunicationSafety = communicationAudit?.verdict === "PASS" && communicationAudit.no_ship === false
449
+ || (livePeerAbsenceBlocksDelivery
450
+ && communicationFailedChecks.length > 0
451
+ && communicationFailedChecks.every((check) => check === "transport_policy_safe" || check === "registry_observe_only_available")
452
+ && communicationCheckPassed("topology_guard_active")
453
+ && communicationCheckPassed("worker_to_worker_blocked")
454
+ && communicationCheckPassed("message_body_storage_blocked")
455
+ && communicationCheckPassed("existing_ledgers_body_free")
456
+ && communicationCheckPassed("stale_transport_not_completion")
457
+ && communicationCheckPassed("dashboard_commands_are_proposals")
458
+ && communicationCheckPassed("dashboard_direct_worker_commands_blocked"));
459
+ const requiredLocalTransportSafeForNoDispatchPlan = transport.mode === "required_local"
460
+ && transport.verdict === "PASS"
461
+ && transport.noExecution === true
462
+ && transport.networkEnabled === false
463
+ && transport.dispatchAllowed === true;
464
+ const transportSafeForAutonomySmoke = transport.networkEnabled === false
465
+ && (
466
+ (transport.verdict === "PASS" && transport.enabled === false && transport.dispatchAllowed === false)
467
+ || requiredLocalTransportSafeForNoDispatchPlan
468
+ || livePeerAbsenceBlocksDelivery
469
+ || (transport.mode === "required_local" && transport.verdict === "PASS")
470
+ );
471
+ const checks = [
472
+ { name: "team_topology_valid", passed: teamErrors.length === 0 },
473
+ { name: "dashboard_snapshot_available", passed: snapshot?.schema === "zob.mission-control-snapshot.v1" },
474
+ { name: "communication_readiness_pass", passed: proposalOnlyCommunicationSafety, detail: { readinessVerdict: communicationAudit?.verdict ?? "FAIL", livePeerAbsenceBlocksDelivery, livePeerReadyRequiredForDispatch: true, proposalOnlyNoDispatchPlan: true } },
475
+ { name: "transport_disabled", passed: transportSafeForAutonomySmoke, detail: { transportVerdict: transport.verdict, requiredLocalTransportSafeForNoDispatchPlan, livePeerAbsenceBlocksDelivery, dispatchAllowedInPlan: false, networkComsEnabledInPlan: false } },
476
+ { 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) },
477
+ { name: "direct_worker_commands_blocked", passed: directWorkerErrors.some((error) => error.includes("direct worker")) },
478
+ { name: "no_body_storage", passed: commandProposals.every((proposal) => proposal.bodyStored === false && proposal.promptBodiesStored === false && proposal.outputBodiesStored === false) },
479
+ { name: "scheduler_still_disabled", passed: input.schedulerPlan.schedulerExecutionAllowed === false && input.schedulerPlan.daemonStarted === false },
480
+ ];
481
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
482
+ const plan = {
483
+ schema: "zob.autonomous-mission-control-plan.v1",
484
+ runId: input.runId,
485
+ missionControlPlanReady: failedChecks.length === 0,
486
+ failedChecks,
487
+ checks,
488
+ dashboard: {
489
+ snapshotAvailable: snapshot?.schema === "zob.mission-control-snapshot.v1",
490
+ dashboardReads: ["runs", "factories", "queue", "budget", "model_routing", "coms", "blockers", "autonomy_status"],
491
+ latestRunLimit: 5,
492
+ directWorkerWrites: false,
493
+ bypassesParentGates: false,
494
+ networkComsEnabled: false,
495
+ snapshotSchema: snapshot?.schema,
496
+ },
497
+ commandPolicy: {
498
+ proposalOnly: true,
499
+ parentOwned: true,
500
+ directWorkerWrites: false,
501
+ transportDispatch: false,
502
+ networkTransport: false,
503
+ allowedCommands: [...MISSION_CONTROL_COMMANDS],
504
+ proposalCount: commandProposals.length,
505
+ proposalHashes: commandProposals.map((proposal) => proposal.commandHash).filter((hash): hash is string => typeof hash === "string"),
506
+ directWorkerCommandBlocked: directWorkerErrors.some((error) => error.includes("direct worker")),
507
+ },
508
+ comsPolicy: {
509
+ readinessVerdict: communicationAudit?.verdict ?? "FAIL",
510
+ proposalOnlyReadinessAccepted: proposalOnlyCommunicationSafety,
511
+ livePeerAbsenceBlocksDelivery,
512
+ livePeerReadyRequiredForDispatch: true,
513
+ topologyGuardActive: Array.isArray(communicationAudit?.checks) && communicationAudit.checks.some((check) => isRecord(check) && check.name === "topology_guard_active" && check.passed === true),
514
+ hashOnlyLedgers: true,
515
+ workerToWorkerFreeChatAllowed: false,
516
+ rawPromptOutputStored: false,
517
+ bodyStored: false,
518
+ promptBodiesStored: false,
519
+ outputBodiesStored: false,
520
+ },
521
+ transportPolicy: {
522
+ enabled: false,
523
+ localDispatchEnabled: false,
524
+ dispatchAllowed: false,
525
+ networkEnabled: false,
526
+ stalePeerCountsAsCompletion: false,
527
+ responseBodiesStored: false,
528
+ livePeerAbsenceBlocksDelivery,
529
+ livePeerReadyRequiredForDispatch: true,
530
+ futureHeartbeatRequired: true,
531
+ futureStaleDetectionRequired: true,
532
+ futureActiveWorkerRegistryRequired: true,
533
+ futureResponseCaptureRequired: true,
534
+ },
535
+ autonomyStatus: {
536
+ globalAutonomyReady: false,
537
+ globalAutonomyNoShip: true,
538
+ noGlobalAutonomyClaim: true,
539
+ },
540
+ schedulerExecutionAllowed: false,
541
+ daemonStarted: false,
542
+ childDispatchAllowed: false,
543
+ directWorkerWrites: false,
544
+ transportDispatch: false,
545
+ networkComsEnabled: false,
546
+ productionWritesPerformed: false,
547
+ autoApply: false,
548
+ globalAutonomyReady: false,
549
+ globalAutonomyNoShip: true,
550
+ bodyStored: false,
551
+ promptBodiesStored: false,
552
+ outputBodiesStored: false,
553
+ };
554
+ if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous mission control plan would store forbidden plaintext body keys");
555
+ return plan;
556
+ }
557
+
558
+ export function buildAutonomousMissionControlProofPlan(input: { runId: string; missionControlPlan: Record<string, unknown>; schedulerProofPlan: Record<string, unknown>; modelRoutingProofPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
559
+ const commandPolicy = isRecord(input.missionControlPlan.commandPolicy) ? input.missionControlPlan.commandPolicy : {};
560
+ const comsPolicy = isRecord(input.missionControlPlan.comsPolicy) ? input.missionControlPlan.comsPolicy : {};
561
+ const transportPolicy = isRecord(input.missionControlPlan.transportPolicy) ? input.missionControlPlan.transportPolicy : {};
562
+ const allowedCommands = Array.isArray(commandPolicy.allowedCommands) ? commandPolicy.allowedCommands.filter((command): command is string => typeof command === "string") : [];
563
+ const proposalHashes = Array.isArray(commandPolicy.proposalHashes) ? commandPolicy.proposalHashes.filter((hash): hash is string => typeof hash === "string") : [];
564
+ const proposalHashesValid = proposalHashes.length === MISSION_CONTROL_COMMANDS.length && proposalHashes.every((hash) => /^[a-f0-9]{64}$/.test(hash));
565
+ const allMissionCommandsCovered = MISSION_CONTROL_COMMANDS.every((command) => allowedCommands.includes(command));
566
+ const approvalCommandAvailable = allowedCommands.includes("approve");
567
+ const scenarios = [
568
+ {
569
+ name: "proposal_only_commands_parent_owned",
570
+ passed: commandPolicy.proposalOnly === true && commandPolicy.parentOwned === true && commandPolicy.transportDispatch === false && commandPolicy.networkTransport === false && commandPolicy.proposalCount === MISSION_CONTROL_COMMANDS.length && allMissionCommandsCovered && proposalHashesValid,
571
+ dispatchAllowed: false,
572
+ },
573
+ {
574
+ name: "topology_hash_only_comms",
575
+ passed: comsPolicy.topologyGuardActive === true && comsPolicy.hashOnlyLedgers === true && comsPolicy.workerToWorkerFreeChatAllowed === false && comsPolicy.rawPromptOutputStored === false && comsPolicy.bodyStored === false && comsPolicy.promptBodiesStored === false && comsPolicy.outputBodiesStored === false,
576
+ dispatchAllowed: false,
577
+ },
578
+ {
579
+ name: "direct_worker_commands_blocked",
580
+ passed: commandPolicy.directWorkerWrites === false && commandPolicy.directWorkerCommandBlocked === true && input.missionControlPlan.directWorkerWrites === false,
581
+ dispatchAllowed: false,
582
+ },
583
+ {
584
+ name: "live_transport_and_network_disabled",
585
+ passed: transportPolicy.enabled === false && transportPolicy.localDispatchEnabled === false && transportPolicy.dispatchAllowed === false && transportPolicy.networkEnabled === false && input.missionControlPlan.transportDispatch === false && input.missionControlPlan.networkComsEnabled === false,
586
+ dispatchAllowed: false,
587
+ },
588
+ {
589
+ name: "approval_required_before_live_global_routing",
590
+ 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,
591
+ dispatchAllowed: false,
592
+ },
593
+ {
594
+ name: "post_8b_scheduler_still_blocked",
595
+ passed: input.schedulerProofPlan.schedulerProofReady === true && input.schedulerProofPlan.schedulerExecutionAllowed === false && input.schedulerProofPlan.daemonStarted === false && input.schedulerProofPlan.childDispatchAllowed === false,
596
+ dispatchAllowed: false,
597
+ },
598
+ ];
599
+ const checks = [
600
+ { name: "mission_control_plan_ready", passed: input.missionControlPlan.missionControlPlanReady === true },
601
+ { name: "proposal_only_commands_parent_owned", passed: scenarios[0].passed === true },
602
+ { name: "topology_hash_only_comms", passed: scenarios[1].passed === true },
603
+ { name: "direct_worker_commands_blocked", passed: scenarios[2].passed === true },
604
+ { name: "live_transport_and_network_disabled", passed: scenarios[3].passed === true },
605
+ { name: "approval_required_before_live_global_routing", passed: scenarios[4].passed === true },
606
+ { name: "post_8b_scheduler_still_blocked", passed: scenarios[5].passed === true },
607
+ { 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 },
608
+ ];
609
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
610
+ const proof = {
611
+ schema: "zob.autonomous-mission-control-proof-plan.v1",
612
+ runId: input.runId,
613
+ phase: "9B",
614
+ status: failedChecks.length === 0 ? "mission_control_comms_proof_ready_execution_blocked" : "mission_control_comms_proof_incomplete",
615
+ missionControlProofReady: failedChecks.length === 0,
616
+ proposalOnlyCommandsProofPassed: scenarios[0].passed === true,
617
+ topologyHashOnlyCommsProofPassed: scenarios[1].passed === true,
618
+ directWorkerCommandsBlockedProofPassed: scenarios[2].passed === true,
619
+ liveTransportNetworkDisabledProofPassed: scenarios[3].passed === true,
620
+ liveGlobalRoutingApprovalProofPassed: scenarios[4].passed === true,
621
+ post8bSchedulerBlockedProofPassed: scenarios[5].passed === true,
622
+ finalE2ERequirementCleared: false,
623
+ no_ship: true,
624
+ checks,
625
+ failedChecks,
626
+ scenarios,
627
+ commandProposalProof: {
628
+ proposalOnly: true,
629
+ parentOwned: true,
630
+ allowedCommands,
631
+ proposalCount: commandPolicy.proposalCount,
632
+ proposalHashesValid,
633
+ directWorkerCommandBlocked: commandPolicy.directWorkerCommandBlocked === true,
634
+ transportDispatch: false,
635
+ networkTransport: false,
636
+ },
637
+ comsTopologyProof: {
638
+ topologyGuardActive: comsPolicy.topologyGuardActive === true,
639
+ hashOnlyLedgers: comsPolicy.hashOnlyLedgers === true,
640
+ workerToWorkerFreeChatAllowed: false,
641
+ rawPromptOutputStored: false,
642
+ bodyStored: false,
643
+ promptBodiesStored: false,
644
+ outputBodiesStored: false,
645
+ },
646
+ transportProof: {
647
+ enabled: false,
648
+ localDispatchEnabled: false,
649
+ dispatchAllowed: false,
650
+ networkEnabled: false,
651
+ stalePeerCountsAsCompletion: false,
652
+ responseBodiesStored: false,
653
+ futureHeartbeatRequired: transportPolicy.futureHeartbeatRequired === true,
654
+ futureStaleDetectionRequired: transportPolicy.futureStaleDetectionRequired === true,
655
+ futureActiveWorkerRegistryRequired: transportPolicy.futureActiveWorkerRegistryRequired === true,
656
+ futureResponseCaptureRequired: transportPolicy.futureResponseCaptureRequired === true,
657
+ },
658
+ routingApprovalPolicy: {
659
+ approvalCommandAvailable,
660
+ approvalCommandProposalOnly: true,
661
+ liveRoutingRequiresApproval: true,
662
+ globalRoutingRequiresApproval: true,
663
+ approvalDoesNotEnableRoutingInThisRun: true,
664
+ liveRoutingAllowedAfterThisProof: false,
665
+ globalLiveRoutingAllowedAfterThisProof: false,
666
+ },
667
+ evidenceRefs: [
668
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/mission-control-plan.json`,
669
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/scheduler-proof-plan.json`,
670
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/model-routing-proof-plan.json`,
671
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
672
+ ".pi/teams/zob-core.json",
673
+ ".pi/mission-control/zob_coms_transport.json",
674
+ ".pi/coms/messages.jsonl",
675
+ ".pi/coms/status.jsonl",
676
+ ],
677
+ blockers: [
678
+ "live_transport_not_enabled",
679
+ "network_coms_disabled",
680
+ "global_live_routing_approval_not_granted",
681
+ "final_e2e_mission_control_live_comms_evidence_required",
682
+ ],
683
+ schedulerExecutionAllowed: false,
684
+ daemonStarted: false,
685
+ childDispatchAllowed: false,
686
+ liveChildExecution: false,
687
+ directWorkerWrites: false,
688
+ transportDispatch: false,
689
+ networkComsEnabled: false,
690
+ liveRoutingEnabled: false,
691
+ globalLiveRoutingEnabled: false,
692
+ productionWritesPerformed: false,
693
+ autoApply: false,
694
+ noExecutionBeyondSmoke: true,
695
+ globalAutonomyReady: false,
696
+ globalAutonomyNoShip: true,
697
+ bodyStored: false,
698
+ promptBodiesStored: false,
699
+ outputBodiesStored: false,
700
+ };
701
+ if (hasForbiddenBodyKeys(proof)) throw new Error("autonomous mission control proof plan would store forbidden plaintext body keys");
702
+ return proof;
703
+ }
704
+
705
+ export function buildAutonomousSandboxApplyPlan(repoRoot: string, input: { runId: string; missionControlPlan: Record<string, unknown>; validation: Record<string, unknown> }): Record<string, unknown> {
706
+ const isolatedPath = "reports/sandbox-isolated-execution-smoke.json";
707
+ const reviewPath = "reports/sandbox-diff-review-gate-smoke.json";
708
+ const simulationPath = "reports/sandbox-apply-simulation-smoke.json";
709
+ const preflightPath = "reports/sandbox-manual-apply-preflight-smoke.json";
710
+ const isolatedRead = readJsonArtifact(join(repoRoot, isolatedPath));
711
+ const reviewRead = readJsonArtifact(join(repoRoot, reviewPath));
712
+ const simulationRead = readJsonArtifact(join(repoRoot, simulationPath));
713
+ const preflightRead = readJsonArtifact(join(repoRoot, preflightPath));
714
+ const isolated = isRecord(isolatedRead.parsed) ? isolatedRead.parsed : {};
715
+ const review = isRecord(reviewRead.parsed) ? reviewRead.parsed : {};
716
+ const simulation = isRecord(simulationRead.parsed) ? simulationRead.parsed : {};
717
+ const preflight = isRecord(preflightRead.parsed) ? preflightRead.parsed : {};
718
+ const isolatedDiffHash = typeof isolated.diffHash === "string" ? isolated.diffHash : undefined;
719
+ const reviewDiffHash = typeof review.diffHash === "string" ? review.diffHash : undefined;
720
+ const simulationDiffHash = typeof simulation.diffHash === "string" ? simulation.diffHash : undefined;
721
+ const diffHashesMatch = Boolean(isolatedDiffHash && isolatedDiffHash === reviewDiffHash && reviewDiffHash === simulationDiffHash);
722
+ const checks = [
723
+ { name: "isolated_temp_workspace_executed", passed: isolated.status === "executed_in_sandbox" && isolated.isolatedExecutionPerformed === true && isolated.productionWritesPerformed === false },
724
+ { name: "diff_hash_consistent", passed: diffHashesMatch },
725
+ { name: "oracle_diff_review_passed", passed: review.status === "diff_review_passed" && review.reviewPassed === true && review.applyReadyUnlocked === true && review.applyPerformed === false },
726
+ { name: "rollback_metadata_required", passed: isolated.rollbackPrepared === true && simulation.rollbackPrepared === true && isolated.rollbackApplied === false && simulation.rollbackApplied === false },
727
+ { name: "apply_simulation_temp_workspace_only", passed: simulation.status === "simulated_apply_in_temp_workspace" && simulation.simulatedApplyPerformed === true && simulation.tempTargetWorkspaceScoped === true && simulation.productionWritesPerformed === false },
728
+ { 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 },
729
+ { 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 },
730
+ { name: "auto_apply_disabled", passed: isolated.autoApply === false && review.autoApply === false && simulation.autoApply === false && preflight.autoApply === false },
731
+ { name: "mission_control_still_proposal_only", passed: input.missionControlPlan.directWorkerWrites === false && input.missionControlPlan.transportDispatch === false },
732
+ ];
733
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
734
+ const plan = {
735
+ schema: "zob.autonomous-sandbox-apply-plan.v1",
736
+ runId: input.runId,
737
+ sandboxApplyPlanReady: failedChecks.length === 0,
738
+ failedChecks,
739
+ checks,
740
+ evidenceRefs: [isolatedPath, reviewPath, simulationPath, preflightPath],
741
+ evidenceHashes: {
742
+ isolatedExecution: isolatedRead.hash,
743
+ diffReviewGate: reviewRead.hash,
744
+ applySimulation: simulationRead.hash,
745
+ manualApplyPreflight: preflightRead.hash,
746
+ },
747
+ sandboxRunIdHash: typeof isolated.runId === "string" ? sha256(isolated.runId) : undefined,
748
+ isolatedTempWorkspace: {
749
+ required: true,
750
+ executed: isolated.isolatedExecutionPerformed === true,
751
+ workspacePathStored: false,
752
+ productionWritesPerformed: false,
753
+ },
754
+ applyPlan: {
755
+ required: true,
756
+ plaintextContentStored: false,
757
+ allowedPathsRequired: true,
758
+ forbiddenPathsRequired: true,
759
+ writeTargetsMustExcludeSecretsVendorGenerated: true,
760
+ },
761
+ diffGate: {
762
+ diffHashRequired: true,
763
+ diffHash: isolatedDiffHash,
764
+ diffHashesMatch,
765
+ changedPathCount: Array.isArray(isolated.changedPaths) ? isolated.changedPaths.length : undefined,
766
+ rawDiffStored: false,
767
+ },
768
+ oracleDiffReview: {
769
+ required: true,
770
+ reviewPassed: review.reviewPassed === true,
771
+ applyReadyUnlocked: review.applyReadyUnlocked === true,
772
+ liveOracleDispatchRequiredBeforeRealApply: true,
773
+ },
774
+ rollbackPolicy: {
775
+ rollbackMetadataRequired: true,
776
+ rollbackPrepared: isolated.rollbackPrepared === true && simulation.rollbackPrepared === true,
777
+ rollbackApplied: false,
778
+ rollbackSnapshotRequiredBeforeMainApply: true,
779
+ },
780
+ approvalPolicy: {
781
+ manualApprovalRequired: true,
782
+ humanApprovalRequired: true,
783
+ approvalMetadataHashOnly: true,
784
+ approvedForMainWorkspaceApply: false,
785
+ },
786
+ applySimulation: {
787
+ required: true,
788
+ simulatedApplyPerformed: simulation.simulatedApplyPerformed === true,
789
+ tempTargetWorkspaceScoped: simulation.tempTargetWorkspaceScoped === true,
790
+ productionWritesPerformed: false,
791
+ autoApply: false,
792
+ },
793
+ manualApplyPreflight: {
794
+ required: true,
795
+ preflightPassed: preflight.manualApplyPreflightPassed === true,
796
+ executionAllowedByThisTool: false,
797
+ confirmationPhraseMatched: isRecord(preflight.gates) && preflight.gates.confirmationPhraseMatched === true,
798
+ approvalHashOnly: isRecord(preflight.gates) && preflight.gates.approvalHashOnly === true,
799
+ realApplyExecuted: false,
800
+ productionWritesPerformed: false,
801
+ autoApply: false,
802
+ },
803
+ mainWorkspaceApply: {
804
+ realApplyAllowed: false,
805
+ realApplyExecuted: false,
806
+ productionWritesPerformed: false,
807
+ autoApply: false,
808
+ reason: "phase_10b_manual_apply_preflight_only_no_main_workspace_apply",
809
+ 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"],
810
+ },
811
+ writeSafety: {
812
+ noDirectAutonomousWritesToMainWorkspace: true,
813
+ noAutoApplyByDefault: true,
814
+ noSecretsVendorGeneratedPaths: true,
815
+ rollbackMetadataRequiredBeforeScalingWrites: true,
816
+ },
817
+ childDispatchAllowed: false,
818
+ daemonStarted: false,
819
+ directWorkerWrites: false,
820
+ transportDispatch: false,
821
+ networkComsEnabled: false,
822
+ productionWritesPerformed: false,
823
+ autoApply: false,
824
+ realApplyExecuted: false,
825
+ globalAutonomyReady: false,
826
+ globalAutonomyNoShip: true,
827
+ bodyStored: false,
828
+ promptBodiesStored: false,
829
+ outputBodiesStored: false,
830
+ };
831
+ if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous sandbox apply plan would store forbidden plaintext body keys");
832
+ return plan;
833
+ }
834
+
835
+ export function expectedAutonomousCurrentSourceFingerprintFiles(factorySelection: Record<string, unknown>): string[] {
836
+ const selectedFactory = typeof factorySelection.selectedFactory === "string" ? factorySelection.selectedFactory : undefined;
837
+ const factoryFiles = selectedFactory ? [`.pi/factories/${selectedFactory}/factory.json`, `.pi/factories/${selectedFactory}/smoke-manifest.json`] : [];
838
+ return [...AUTONOMOUS_CURRENT_SOURCE_FINGERPRINT_FILES, ...factoryFiles].filter((file, index, items) => items.indexOf(file) === index).sort();
839
+ }
840
+
841
+ export function stringRecord(value: unknown): Record<string, string> {
842
+ if (!isRecord(value)) return {};
843
+ return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
844
+ }
845
+
846
+ export function sameStringArray(left: unknown, right: string[]): boolean {
847
+ return Array.isArray(left) && left.every((item) => typeof item === "string") && JSON.stringify([...left].sort()) === JSON.stringify([...right].sort());
848
+ }
849
+
850
+ export function buildAutonomousCurrentSourceFingerprint(repoRoot: string, input: { runId: string; factorySelection: Record<string, unknown> }): Record<string, unknown> {
851
+ const selectedFactory = typeof input.factorySelection.selectedFactory === "string" ? input.factorySelection.selectedFactory : undefined;
852
+ const sourceFiles = expectedAutonomousCurrentSourceFingerprintFiles(input.factorySelection);
853
+ const missingFiles = sourceFiles.filter((file) => !existsSync(join(repoRoot, file)));
854
+ const fileHashes = Object.fromEntries(sourceFiles.filter((file) => existsSync(join(repoRoot, file))).map((file) => [file, sha256(readFileSync(join(repoRoot, file), "utf8"))]));
855
+ const fingerprintHash = sha256(JSON.stringify(fileHashes));
856
+ const fingerprint = {
857
+ schema: "zob.autonomous-current-source-fingerprint.v1",
858
+ runId: input.runId,
859
+ phase: "11C",
860
+ status: missingFiles.length === 0 ? "current_source_fingerprint_captured" : "blocked_missing_source_files",
861
+ currentSourceFingerprintReady: missingFiles.length === 0,
862
+ currentSourceFingerprintCaptured: missingFiles.length === 0,
863
+ noMockCurrentSourceE2EProved: false,
864
+ finalE2EProofReady: false,
865
+ sourceFiles,
866
+ sourceFileCount: sourceFiles.length,
867
+ hashedFileCount: Object.keys(fileHashes).length,
868
+ missingFiles,
869
+ fileHashes,
870
+ fingerprintHash,
871
+ selectedFactory,
872
+ evidencePolicy: {
873
+ hashOnly: true,
874
+ sourceBodiesStored: false,
875
+ currentSourceOnly: true,
876
+ rehashRequiredBeforeFinalE2E: true,
877
+ noMockProofRequiredSeparately: true,
878
+ },
879
+ safety: {
880
+ noExecution: true,
881
+ childDispatchAllowed: false,
882
+ daemonStarted: false,
883
+ productionWritesPerformed: false,
884
+ autoApply: false,
885
+ networkAccessed: false,
886
+ globalAutonomyReady: false,
887
+ globalAutonomyNoShip: true,
888
+ },
889
+ bodyStored: false,
890
+ promptBodiesStored: false,
891
+ outputBodiesStored: false,
892
+ };
893
+ if (hasForbiddenBodyKeys(fingerprint)) throw new Error("autonomous current-source fingerprint would store forbidden plaintext body keys");
894
+ return fingerprint;
895
+ }
896
+
897
+ export function validateAutonomousCurrentSourceFingerprintFreshness(repoRoot: string, fingerprint: Record<string, unknown>, factorySelection: Record<string, unknown>): Record<string, unknown> {
898
+ const expectedSourceFiles = expectedAutonomousCurrentSourceFingerprintFiles(factorySelection);
899
+ const currentMissingFiles = expectedSourceFiles.filter((file) => !existsSync(join(repoRoot, file)));
900
+ const currentFileHashes = Object.fromEntries(expectedSourceFiles.filter((file) => existsSync(join(repoRoot, file))).map((file) => [file, sha256(readFileSync(join(repoRoot, file), "utf8"))]));
901
+ const storedFileHashes = stringRecord(fingerprint.fileHashes);
902
+ const currentFingerprintHash = sha256(JSON.stringify(currentFileHashes));
903
+ const storedFingerprintHash = typeof fingerprint.fingerprintHash === "string" ? fingerprint.fingerprintHash : undefined;
904
+ const hashValuesValid = Object.values(storedFileHashes).every((hash) => /^[a-f0-9]{64}$/.test(hash));
905
+ const expectedHashKeys = Object.keys(currentFileHashes).sort();
906
+ const storedHashKeys = Object.keys(storedFileHashes).sort();
907
+ const fileHashesMatch = JSON.stringify(expectedHashKeys) === JSON.stringify(storedHashKeys) && expectedHashKeys.every((file) => storedFileHashes[file] === currentFileHashes[file]);
908
+ const sourceFilesMatch = sameStringArray(fingerprint.sourceFiles, expectedSourceFiles);
909
+ const missingFilesMatch = sameStringArray(fingerprint.missingFiles, currentMissingFiles);
910
+ const fingerprintHashMatches = storedFingerprintHash === currentFingerprintHash;
911
+ const fresh = fingerprint.schema === "zob.autonomous-current-source-fingerprint.v1"
912
+ && fingerprint.currentSourceFingerprintReady === true
913
+ && fingerprint.currentSourceFingerprintCaptured === true
914
+ && sourceFilesMatch
915
+ && missingFilesMatch
916
+ && currentMissingFiles.length === 0
917
+ && hashValuesValid
918
+ && fileHashesMatch
919
+ && fingerprintHashMatches
920
+ && fingerprint.noMockCurrentSourceE2EProved === false;
921
+ const result = {
922
+ schema: "zob.autonomous-current-source-fingerprint-freshness.v1",
923
+ fresh,
924
+ sourceFilesMatch,
925
+ missingFilesMatch,
926
+ hashValuesValid,
927
+ fileHashesMatch,
928
+ fingerprintHashMatches,
929
+ currentFingerprintHash,
930
+ storedFingerprintHash,
931
+ expectedSourceFileCount: expectedSourceFiles.length,
932
+ storedSourceFileCount: Array.isArray(fingerprint.sourceFiles) ? fingerprint.sourceFiles.length : 0,
933
+ expectedHashedFileCount: expectedHashKeys.length,
934
+ storedHashedFileCount: storedHashKeys.length,
935
+ currentMissingFiles,
936
+ noMockCurrentSourceE2EProved: false,
937
+ noExecution: true,
938
+ childDispatchAllowed: false,
939
+ globalAutonomyReady: false,
940
+ globalAutonomyNoShip: true,
941
+ bodyStored: false,
942
+ promptBodiesStored: false,
943
+ outputBodiesStored: false,
944
+ };
945
+ if (hasForbiddenBodyKeys(result)) throw new Error("autonomous current-source freshness validation would store forbidden plaintext body keys");
946
+ return result;
947
+ }
948
+
949
+ export function buildAutonomousFinalNoShipOracle(input: { runId: string; finalE2EProofPlan: Record<string, unknown>; currentSourceFingerprint: Record<string, unknown> }): Record<string, unknown> {
950
+ const blockers = Array.isArray(input.finalE2EProofPlan.blockers) ? input.finalE2EProofPlan.blockers.filter((blocker): blocker is string => typeof blocker === "string") : ["final_e2e_proof_plan_missing_blockers"];
951
+ const checks = [
952
+ { name: "final_e2e_proof_ready", passed: input.finalE2EProofPlan.finalE2EProofReady === true },
953
+ { name: "final_e2e_no_ship_cleared", passed: input.finalE2EProofPlan.no_ship === false },
954
+ { name: "no_mock_current_source_e2e_proved", passed: isRecord(input.finalE2EProofPlan.currentSourceProof) && input.finalE2EProofPlan.currentSourceProof.noMockCurrentSourceE2EProved === true },
955
+ { name: "current_source_fingerprint_captured", passed: input.currentSourceFingerprint.currentSourceFingerprintCaptured === true && typeof input.currentSourceFingerprint.fingerprintHash === "string" },
956
+ { name: "pilot_executed", passed: isRecord(input.finalE2EProofPlan.promotionStatus) && input.finalE2EProofPlan.promotionStatus.pilotExecuted === true },
957
+ { name: "batch_executed", passed: isRecord(input.finalE2EProofPlan.promotionStatus) && input.finalE2EProofPlan.promotionStatus.batchExecuted === true },
958
+ { name: "live_strict_budget_enforced", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.strictBudgetEnforced === true },
959
+ { name: "live_model_routing_enabled", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.liveModelRoutingEnabled === true },
960
+ { name: "daemon_started", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.daemonStarted === true },
961
+ { name: "real_apply_executed", passed: isRecord(input.finalE2EProofPlan.liveGateStatus) && input.finalE2EProofPlan.liveGateStatus.sandboxRealApplyExecuted === true },
962
+ { name: "global_ready_sentinel_allowed", passed: isRecord(input.finalE2EProofPlan.sentinelPolicy) && input.finalE2EProofPlan.sentinelPolicy.globalReadySentinelAllowed === true },
963
+ ];
964
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
965
+ const oracle = {
966
+ schema: "zob.autonomous-final-no-ship-oracle.v1",
967
+ runId: input.runId,
968
+ phase: "11E",
969
+ oracleType: "deterministic_structural_no_ship",
970
+ verdict: "FAIL",
971
+ no_ship: true,
972
+ finalOracleReady: false,
973
+ finalOraclePass: false,
974
+ finalE2EProofReady: false,
975
+ evidenceChecked: true,
976
+ checks,
977
+ failedChecks,
978
+ blockers,
979
+ evidenceRefs: [
980
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/final-e2e-proof-plan.json`,
981
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/current-source-fingerprint.json`,
982
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
983
+ ],
984
+ decision: {
985
+ globalAutonomyReady: false,
986
+ globalAutonomyNoShip: true,
987
+ claim100PercentAutonomyAllowed: false,
988
+ writeGlobalReadySentinelAllowed: false,
989
+ writeFinalDoneSentinelAllowed: false,
990
+ },
991
+ childDispatchAllowed: false,
992
+ daemonStarted: false,
993
+ directWorkerWrites: false,
994
+ transportDispatch: false,
995
+ networkComsEnabled: false,
996
+ productionWritesPerformed: false,
997
+ autoApply: false,
998
+ realApplyExecuted: false,
999
+ liveRoutingEnabled: false,
1000
+ budgetEnforced: false,
1001
+ globalAutonomyReady: false,
1002
+ globalAutonomyNoShip: true,
1003
+ bodyStored: false,
1004
+ promptBodiesStored: false,
1005
+ outputBodiesStored: false,
1006
+ };
1007
+ if (hasForbiddenBodyKeys(oracle)) throw new Error("autonomous final no-ship oracle would store forbidden plaintext body keys");
1008
+ return oracle;
1009
+ }
1010
+
1011
+ export 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> {
1012
+ const safeRunId = safeFileStem(input.runId);
1013
+ const runRoot = `reports/autonomous-runs/${safeRunId}`;
1014
+ const globalReadySentinelPath = join(repoRoot, runRoot, "GLOBAL_AUTONOMY_READY.sentinel");
1015
+ const smokeGate = isRecord(input.promotionPlan.smokeGate) ? input.promotionPlan.smokeGate : {};
1016
+ const pilotGate = isRecord(input.promotionPlan.pilotGate) ? input.promotionPlan.pilotGate : {};
1017
+ const batchGate = isRecord(input.promotionPlan.batchGate) ? input.promotionPlan.batchGate : {};
1018
+ const strictBudgetGate = isRecord(input.runtimeGates.autonomousStrictBudgetGate) ? input.runtimeGates.autonomousStrictBudgetGate : {};
1019
+ const mainWorkspaceApply = isRecord(input.sandboxApplyPlan.mainWorkspaceApply) ? input.sandboxApplyPlan.mainWorkspaceApply : {};
1020
+ const globalReadySentinelPresent = existsSync(globalReadySentinelPath);
1021
+ const proofSteps = [
1022
+ { name: "user_need", state: "captured", evidenceRef: `${runRoot}/spec-gate.json`, dispatchAllowed: false },
1023
+ { name: "spec_lock", state: "proved", evidenceRef: `${runRoot}/spec-gate.json`, dispatchAllowed: false },
1024
+ { name: "context_scope", state: "proved", evidenceRef: `${runRoot}/context-scope.json`, dispatchAllowed: false },
1025
+ { name: "context_pack", state: "proved", evidenceRef: `${runRoot}/context-pack.json`, dispatchAllowed: false },
1026
+ { 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 },
1027
+ { 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 },
1028
+ { name: "factory_selection", state: "proved", evidenceRef: `${runRoot}/factory-selection.json`, dispatchAllowed: false },
1029
+ { name: "smoke", state: input.factoryRunRef.status === "done" ? "proved" : "blocked", evidenceRef: `${runRoot}/factory-run-ref.json`, dispatchAllowed: false },
1030
+ { name: "smoke_oracle", state: input.oracleReview.verdict === "PASS" && input.oracleReview.no_ship === false ? "proved" : "blocked", evidenceRef: `${runRoot}/oracle-review.json`, dispatchAllowed: false },
1031
+ { 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 },
1032
+ { name: "pilot", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "pilot_execution_disabled_until_live_gates", dispatchAllowed: false },
1033
+ { name: "pilot_oracle", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "pilot_oracle_missing_until_pilot_executes", dispatchAllowed: false },
1034
+ { name: "batch", state: "blocked", evidenceRef: `${runRoot}/promotion-plan.json`, blocker: "batch_execution_disabled_until_pilot_oracle_and_concurrency_gate", dispatchAllowed: false },
1035
+ { name: "final_oracle", state: "blocked", evidenceRef: `${runRoot}/final-e2e-proof-plan.json`, blocker: "final_oracle_missing_until_full_current_source_e2e", dispatchAllowed: false },
1036
+ { 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 },
1037
+ { 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 },
1038
+ { name: "stop_clean", state: "planned", evidenceRef: `${runRoot}/scheduler-plan.json`, dispatchAllowed: false },
1039
+ ];
1040
+ const requiredArtifacts = [
1041
+ { name: "spec-gate.json", present: true, evidenceRef: `${runRoot}/spec-gate.json` },
1042
+ { name: "context-scope.json", present: true, evidenceRef: `${runRoot}/context-scope.json` },
1043
+ { name: "context-pack.json", present: true, evidenceRef: `${runRoot}/context-pack.json` },
1044
+ { name: "factory-selection.json", present: true, evidenceRef: `${runRoot}/factory-selection.json` },
1045
+ { name: "runtime-gates.json", present: true, evidenceRef: `${runRoot}/runtime-gates.json` },
1046
+ { name: "strict-budget-proof-plan.json", present: input.strictBudgetProofPlan.strictBudgetProofReady === true, evidenceRef: `${runRoot}/strict-budget-proof-plan.json` },
1047
+ { name: "model-routing-proof-plan.json", present: input.modelRoutingProofPlan.modelRoutingProofReady === true, evidenceRef: `${runRoot}/model-routing-proof-plan.json` },
1048
+ { name: "run-graph.json", present: true, evidenceRef: `${runRoot}/run-graph.json` },
1049
+ { name: "current-source-fingerprint.json", present: input.currentSourceFingerprint.currentSourceFingerprintReady === true, evidenceRef: `${runRoot}/current-source-fingerprint.json` },
1050
+ { name: "factory-run-smoke", present: input.factoryRunRef.status === "done", evidenceRef: `${runRoot}/factory-run-ref.json` },
1051
+ { name: "factory-run-pilot", present: false, missingReason: "pilot_not_executed" },
1052
+ { name: "factory-run-batch", present: false, missingReason: "batch_not_executed" },
1053
+ { name: "oracle-review-smoke.json", present: input.oracleReview.verdict === "PASS", evidenceRef: `${runRoot}/oracle-review.json` },
1054
+ { name: "promotion-proof-plan.json", present: input.promotionProofPlan.promotionProofReady === true, evidenceRef: `${runRoot}/promotion-proof-plan.json` },
1055
+ { name: "scheduler-proof-plan.json", present: input.schedulerProofPlan.schedulerProofReady === true, evidenceRef: `${runRoot}/scheduler-proof-plan.json` },
1056
+ { name: "mission-control-proof-plan.json", present: input.missionControlProofPlan.missionControlProofReady === true, evidenceRef: `${runRoot}/mission-control-proof-plan.json` },
1057
+ { name: "oracle-review-pilot.json", present: false, missingReason: "pilot_oracle_missing" },
1058
+ { name: "final-oracle.json", present: false, missingReason: "final_oracle_missing" },
1059
+ { name: "validation.json", present: input.validation.status === "smoke_autonomy_passed", evidenceRef: `${runRoot}/validation.json` },
1060
+ { name: "DONE.sentinel", present: false, missingReason: "final_e2e_not_run" },
1061
+ { name: "GLOBAL_AUTONOMY_READY.sentinel", present: globalReadySentinelPresent, missingReason: globalReadySentinelPresent ? undefined : "global_autonomy_not_ready" },
1062
+ ];
1063
+ const blockers = [
1064
+ "final_e2e_no_mock_current_source_not_proven",
1065
+ ...(strictBudgetGate.strictEnabled === true && strictBudgetGate.budgetEnforced === true ? [] : ["live_strict_budget_not_enforced"]),
1066
+ ...(input.modelRoutingPlan.liveRoutingEnabled === true ? [] : ["live_model_routing_not_enabled"]),
1067
+ ...(input.schedulerPlan.schedulerExecutionAllowed === true && input.schedulerPlan.daemonStarted === true ? [] : ["daemon_scheduler_not_started"]),
1068
+ ...(input.missionControlProofPlan.finalE2ERequirementCleared === true ? [] : ["live_mission_control_transport_not_enabled"]),
1069
+ ...(smokeGate.passed === true ? [] : ["smoke_gate_not_passed"]),
1070
+ ...(pilotGate.executionAllowed === true ? [] : ["pilot_execution_disabled"]),
1071
+ ...(batchGate.executionAllowed === true ? [] : ["batch_execution_disabled"]),
1072
+ ...(mainWorkspaceApply.realApplyExecuted === true ? [] : ["real_apply_not_executed"]),
1073
+ "final_oracle_missing",
1074
+ ...(globalReadySentinelPresent ? [] : ["global_autonomy_ready_sentinel_absent"]),
1075
+ ];
1076
+ const plan = {
1077
+ schema: "zob.autonomous-final-e2e-proof-plan.v1",
1078
+ runId: input.runId,
1079
+ phase: "11A",
1080
+ status: "blocked_for_final_e2e_proof",
1081
+ finalE2EProofReady: false,
1082
+ no_ship: true,
1083
+ blockers,
1084
+ proofSteps,
1085
+ requiredArtifacts,
1086
+ currentSourceProof: {
1087
+ required: true,
1088
+ noMockRequired: true,
1089
+ currentSourceFingerprintCaptured: input.currentSourceFingerprint.currentSourceFingerprintCaptured === true,
1090
+ currentSourceFingerprintHash: typeof input.currentSourceFingerprint.fingerprintHash === "string" ? input.currentSourceFingerprint.fingerprintHash : undefined,
1091
+ sourceFileCount: typeof input.currentSourceFingerprint.sourceFileCount === "number" ? input.currentSourceFingerprint.sourceFileCount : undefined,
1092
+ missingFiles: Array.isArray(input.currentSourceFingerprint.missingFiles) ? input.currentSourceFingerprint.missingFiles : [],
1093
+ noMockCurrentSourceE2EProved: false,
1094
+ registeredFactoryPathChecked: input.factorySelection.currentSourceProofRequired === true,
1095
+ arbitraryFactoryAutonomyReady: false,
1096
+ },
1097
+ liveGateStatus: {
1098
+ strictBudgetEnforced: strictBudgetGate.budgetEnforced === true,
1099
+ strictBudgetEnabled: strictBudgetGate.strictEnabled === true,
1100
+ strictBudgetProofReady: input.strictBudgetProofPlan.strictBudgetProofReady === true,
1101
+ strictBudgetBlockProofPassed: input.strictBudgetProofPlan.strictBudgetBlockProofPassed === true,
1102
+ strictBudgetFinalE2ERequirementCleared: input.strictBudgetProofPlan.finalE2ERequirementCleared === true,
1103
+ modelRoutingProofReady: input.modelRoutingProofPlan.modelRoutingProofReady === true,
1104
+ modelRoutingOracleProofPassed: input.modelRoutingProofPlan.routingOracleProofPassed === true,
1105
+ modelRoutingFinalE2ERequirementCleared: input.modelRoutingProofPlan.finalE2ERequirementCleared === true,
1106
+ liveModelRoutingEnabled: input.modelRoutingPlan.liveRoutingEnabled === true,
1107
+ schedulerExecutionAllowed: input.schedulerPlan.schedulerExecutionAllowed === true,
1108
+ schedulerProofReady: input.schedulerProofPlan.schedulerProofReady === true,
1109
+ schedulerFinalE2ERequirementCleared: input.schedulerProofPlan.finalE2ERequirementCleared === true,
1110
+ daemonStarted: input.schedulerPlan.daemonStarted === true,
1111
+ missionControlProposalOnly: isRecord(input.missionControlPlan.commandPolicy) && input.missionControlPlan.commandPolicy.proposalOnly === true,
1112
+ missionControlProofReady: input.missionControlProofPlan.missionControlProofReady === true,
1113
+ missionControlFinalE2ERequirementCleared: input.missionControlProofPlan.finalE2ERequirementCleared === true,
1114
+ directWorkerCommandsBlocked: input.missionControlProofPlan.directWorkerCommandsBlockedProofPassed === true,
1115
+ liveTransportNetworkDisabled: input.missionControlProofPlan.liveTransportNetworkDisabledProofPassed === true,
1116
+ liveGlobalRoutingApprovalRequired: input.missionControlProofPlan.liveGlobalRoutingApprovalProofPassed === true,
1117
+ sandboxRealApplyExecuted: mainWorkspaceApply.realApplyExecuted === true,
1118
+ },
1119
+ promotionStatus: {
1120
+ smokeGatePassed: smokeGate.passed === true,
1121
+ pilotPreconditionsMet: pilotGate.preconditionsMet === true,
1122
+ promotionProofReady: input.promotionProofPlan.promotionProofReady === true,
1123
+ promotionFinalE2ERequirementCleared: input.promotionProofPlan.finalE2ERequirementCleared === true,
1124
+ pilotExecutionAllowed: pilotGate.executionAllowed === true,
1125
+ batchPreconditionsMet: batchGate.preconditionsMet === true,
1126
+ batchExecutionAllowed: batchGate.executionAllowed === true,
1127
+ pilotExecuted: input.promotionPlan.pilotExecuted === true,
1128
+ batchExecuted: input.promotionPlan.batchExecuted === true,
1129
+ },
1130
+ sentinelPolicy: {
1131
+ doneSentinelAllowed: false,
1132
+ globalReadySentinelAllowed: false,
1133
+ globalReadySentinelPresent,
1134
+ globalReadySentinelPath: `${runRoot}/GLOBAL_AUTONOMY_READY.sentinel`,
1135
+ },
1136
+ finalReportPolicy: {
1137
+ finalGlobalReportAllowed: false,
1138
+ currentReportIsRunScopedSmokeOnly: true,
1139
+ claim100PercentAutonomyAllowed: false,
1140
+ },
1141
+ childDispatchAllowed: false,
1142
+ daemonStarted: false,
1143
+ directWorkerWrites: false,
1144
+ transportDispatch: false,
1145
+ networkComsEnabled: false,
1146
+ productionWritesPerformed: false,
1147
+ autoApply: false,
1148
+ realApplyExecuted: false,
1149
+ globalAutonomyReady: false,
1150
+ globalAutonomyNoShip: true,
1151
+ bodyStored: false,
1152
+ promptBodiesStored: false,
1153
+ outputBodiesStored: false,
1154
+ };
1155
+ if (hasForbiddenBodyKeys(plan)) throw new Error("autonomous final e2e proof plan would store forbidden plaintext body keys");
1156
+ return plan;
1157
+ }
1158
+
1159
+ export function buildAutonomousCompletionGate(input: { runId: string; finalE2EProofPlan: Record<string, unknown>; finalNoShipOracle: Record<string, unknown>; currentSourceFingerprintFreshness: Record<string, unknown> }): Record<string, unknown> {
1160
+ const finalBlockers = Array.isArray(input.finalE2EProofPlan.blockers) ? input.finalE2EProofPlan.blockers.filter((blocker): blocker is string => typeof blocker === "string") : [];
1161
+ const oracleFailedChecks = Array.isArray(input.finalNoShipOracle.failedChecks) ? input.finalNoShipOracle.failedChecks.filter((check): check is string => typeof check === "string") : [];
1162
+ const checks = [
1163
+ { name: "final_e2e_proof_ready", passed: input.finalE2EProofPlan.finalE2EProofReady === true },
1164
+ { name: "final_no_ship_oracle_pass", passed: input.finalNoShipOracle.finalOraclePass === true && input.finalNoShipOracle.no_ship === false },
1165
+ { name: "current_source_fingerprint_fresh", passed: input.currentSourceFingerprintFreshness.fresh === true },
1166
+ { name: "global_ready_sentinel_allowed", passed: isRecord(input.finalE2EProofPlan.sentinelPolicy) && input.finalE2EProofPlan.sentinelPolicy.globalReadySentinelAllowed === true },
1167
+ { name: "final_done_sentinel_allowed", passed: isRecord(input.finalNoShipOracle.decision) && input.finalNoShipOracle.decision.writeFinalDoneSentinelAllowed === true },
1168
+ { name: "claim_100_percent_allowed", passed: isRecord(input.finalNoShipOracle.decision) && input.finalNoShipOracle.decision.claim100PercentAutonomyAllowed === true },
1169
+ ];
1170
+ const failedChecks = checks.filter((check) => check.passed !== true).map((check) => check.name);
1171
+ const gate = {
1172
+ schema: "zob.autonomous-completion-gate.v1",
1173
+ runId: input.runId,
1174
+ phase: "11F",
1175
+ status: "blocked_for_goal_completion",
1176
+ completionReady: false,
1177
+ allRequirementsVerified: false,
1178
+ no_ship: true,
1179
+ updateGoalAllowed: false,
1180
+ requiredGoalStatus: "in_progress",
1181
+ completionToolAvailableInThisRun: false,
1182
+ checks,
1183
+ failedChecks,
1184
+ blockers: [...new Set([...finalBlockers, ...oracleFailedChecks, ...failedChecks])].sort(),
1185
+ evidenceRefs: [
1186
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/final-e2e-proof-plan.json`,
1187
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/final-no-ship-oracle.json`,
1188
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/current-source-fingerprint.json`,
1189
+ `reports/autonomous-runs/${safeFileStem(input.runId)}/validation.json`,
1190
+ ],
1191
+ requiredBeforeCompletion: [
1192
+ "final_e2e_no_mock_current_source_proof",
1193
+ "final_oracle_PASS_no_ship_false",
1194
+ "smoke_pilot_batch_artifacts_current_source",
1195
+ "live_strict_budget_enforced",
1196
+ "live_model_routing_enabled",
1197
+ "daemon_scheduler_proven_with_kill_switch",
1198
+ "sandbox_real_apply_or_explicit_no_apply_final_policy",
1199
+ "GLOBAL_AUTONOMY_READY_sentinel_allowed_by_final_oracle",
1200
+ "update_goal_tool_available_and_called_only_after_all_gates_pass",
1201
+ ],
1202
+ decision: {
1203
+ updateGoalStatusCompleteAllowed: false,
1204
+ globalAutonomyReady: false,
1205
+ globalAutonomyNoShip: true,
1206
+ writeGlobalReadySentinelAllowed: false,
1207
+ writeFinalDoneSentinelAllowed: false,
1208
+ claim100PercentAutonomyAllowed: false,
1209
+ },
1210
+ childDispatchAllowed: false,
1211
+ daemonStarted: false,
1212
+ directWorkerWrites: false,
1213
+ transportDispatch: false,
1214
+ networkComsEnabled: false,
1215
+ productionWritesPerformed: false,
1216
+ autoApply: false,
1217
+ realApplyExecuted: false,
1218
+ liveRoutingEnabled: false,
1219
+ budgetEnforced: false,
1220
+ globalAutonomyReady: false,
1221
+ globalAutonomyNoShip: true,
1222
+ bodyStored: false,
1223
+ promptBodiesStored: false,
1224
+ outputBodiesStored: false,
1225
+ };
1226
+ if (hasForbiddenBodyKeys(gate)) throw new Error("autonomous completion gate would store forbidden plaintext body keys");
1227
+ return gate;
1228
+ }
1229
+
1230
+ export function buildAutonomousReadOnlySmokeFinalReport(validation: Record<string, unknown>, factoryRunRef: Record<string, unknown>, oracleReview: Record<string, unknown>): string {
1231
+ const blockers = Array.isArray(validation.blockers) ? validation.blockers.map((blocker) => `- ${String(blocker)}`).join("\n") : "";
1232
+ return [
1233
+ "# Autonomous Read-Only Smoke Report",
1234
+ "",
1235
+ `Run ID: ${String(validation.runId ?? "unknown")}`,
1236
+ `Status: ${String(validation.status ?? "unknown")}`,
1237
+ `Smoke no-ship: ${String(validation.no_ship === true)}`,
1238
+ `Global autonomy no-ship: ${String(validation.globalAutonomyNoShip === true)}`,
1239
+ "",
1240
+ "## Factory smoke",
1241
+ "",
1242
+ `- Selected factory: ${String(factoryRunRef.selectedFactory ?? "none")}`,
1243
+ `- Factory run id: ${String(factoryRunRef.factoryRunId ?? "none")}`,
1244
+ `- Factory status: ${String(factoryRunRef.status ?? "unknown")}`,
1245
+ `- Deterministic execution: ${String(factoryRunRef.execution === "deterministic")}`,
1246
+ "",
1247
+ "## Structural oracle",
1248
+ "",
1249
+ `- Verdict: ${String(oracleReview.verdict ?? "unknown")}`,
1250
+ `- No-ship for this smoke: ${String(oracleReview.no_ship === true)}`,
1251
+ `- Live oracle dispatched: ${String(oracleReview.liveOracleDispatched === true)}`,
1252
+ "",
1253
+ "## Blockers",
1254
+ "",
1255
+ blockers || "- None for this read-only smoke slice.",
1256
+ "",
1257
+ "## Evidence refs",
1258
+ "",
1259
+ "- spec-gate.json",
1260
+ "- context-scope.json",
1261
+ "- context-pack.json",
1262
+ "- runtime-gates.json",
1263
+ "- model-routing-plan.json",
1264
+ "- model-routing-proof-plan.json",
1265
+ "- factory-selection.json",
1266
+ "- factory-run-ref.json",
1267
+ "- oracle-review.json",
1268
+ "- promotion-plan.json",
1269
+ "- promotion-proof-plan.json",
1270
+ "- scheduler-plan.json",
1271
+ "- scheduler-proof-plan.json",
1272
+ "- mission-control-plan.json",
1273
+ "- mission-control-proof-plan.json",
1274
+ "- sandbox-apply-plan.json",
1275
+ "- strict-budget-proof-plan.json",
1276
+ "- current-source-fingerprint.json",
1277
+ "- final-e2e-proof-plan.json",
1278
+ "- final-no-ship-oracle.json",
1279
+ "- completion-gate.json",
1280
+ "- validation.json",
1281
+ "- SMOKE_AUTONOMY_PASSED.sentinel when status=smoke_autonomy_passed",
1282
+ "",
1283
+ "Compliance: Phase 4A read-only deterministic smoke evidence only; global autonomy remains no-ship.",
1284
+ "",
1285
+ ].join("\n");
1286
+ }