percolation-inversion-compiler-ts 0.4.4

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 (366) hide show
  1. package/LICENSE +152 -0
  2. package/NOTICE +21 -0
  3. package/README.md +255 -0
  4. package/dist/agent/messages.d.ts +23 -0
  5. package/dist/agent/messages.js +457 -0
  6. package/dist/cli/main.d.ts +1 -0
  7. package/dist/cli/main.js +2646 -0
  8. package/dist/index.d.ts +91 -0
  9. package/dist/index.js +983 -0
  10. package/dist/io/schema.d.ts +16 -0
  11. package/dist/io/schema.js +153 -0
  12. package/dist/packet/index.d.ts +10 -0
  13. package/dist/packet/index.js +385 -0
  14. package/fixtures/portability_conformance/README.md +17 -0
  15. package/fixtures/portability_conformance/agent_check_report.json +1251 -0
  16. package/fixtures/portability_conformance/agent_intake_report.json +1169 -0
  17. package/fixtures/portability_conformance/agent_message_delivery_report.json +124 -0
  18. package/fixtures/portability_conformance/agent_relay_readiness_report.json +40 -0
  19. package/fixtures/portability_conformance/alt_admission_decision.json +16 -0
  20. package/fixtures/portability_conformance/bottleneck_witness_report.json +23 -0
  21. package/fixtures/portability_conformance/collective_phase_certificate.json +330 -0
  22. package/fixtures/portability_conformance/frontier_debt_report.json +24 -0
  23. package/fixtures/portability_conformance/manifest.json +113 -0
  24. package/fixtures/portability_conformance/negative/checksum_mismatch.json +4 -0
  25. package/fixtures/portability_conformance/negative/schema_invalid_agent_check.json +3 -0
  26. package/fixtures/portability_conformance/negative/unknown_schema.json +3 -0
  27. package/fixtures/portability_conformance/phase_acceleration_benchmark_report.json +21 -0
  28. package/fixtures/portability_conformance/phase_acceleration_plan.json +72 -0
  29. package/fixtures/portability_conformance/phase_control_audit_summary.json +16 -0
  30. package/fixtures/portability_conformance/relay_inbox.json +37 -0
  31. package/fixtures/portability_conformance/runtime_step_report.json +1384 -0
  32. package/fixtures/portability_conformance/salience_schedule_report.json +100 -0
  33. package/fixtures/portability_conformance/theory_fidelity_report.json +53 -0
  34. package/fixtures/portability_conformance/value_bridge_report.json +17 -0
  35. package/fixtures/python_v044_cli/adoption_packet.json +131 -0
  36. package/fixtures/python_v044_cli/adoption_request.json +60 -0
  37. package/fixtures/python_v044_cli/agent_autonomy_audit.json +254 -0
  38. package/fixtures/python_v044_cli/agent_check_compact.json +80 -0
  39. package/fixtures/python_v044_cli/agent_check_full.json +1265 -0
  40. package/fixtures/python_v044_cli/agent_communication_guide.json +426 -0
  41. package/fixtures/python_v044_cli/agent_intake.json +1175 -0
  42. package/fixtures/python_v044_cli/agent_manifest.json +373 -0
  43. package/fixtures/python_v044_cli/agent_runbook.json +115 -0
  44. package/fixtures/python_v044_cli/demo_installed_smoke.json +1367 -0
  45. package/fixtures/python_v044_cli/doctor_development.json +264 -0
  46. package/fixtures/python_v044_cli/identity_explain_profile_production.json +39 -0
  47. package/fixtures/python_v044_cli/phase_benchmark.json +42 -0
  48. package/fixtures/python_v044_cli/phase_benchmark_suite.json +428 -0
  49. package/fixtures/python_v044_cli/phase_dashboard.json +173 -0
  50. package/fixtures/python_v044_cli/phase_gap.json +119 -0
  51. package/fixtures/python_v044_cli/phase_observe.json +203 -0
  52. package/fixtures/python_v044_cli/phase_plan_compact.json +384 -0
  53. package/fixtures/python_v044_cli/phase_plan_full.json +2020 -0
  54. package/fixtures/python_v044_cli/phase_runbook.json +66 -0
  55. package/fixtures/python_v044_cli/routes_bindings.json +716 -0
  56. package/fixtures/python_v044_cli/routes_explain_replay_trc_physical_trace.json +57 -0
  57. package/fixtures/python_v044_cli/runtime_step_demo.json +1384 -0
  58. package/fixtures/python_v044_cli/snapshot_list.json +112 -0
  59. package/fixtures/python_v044_cli/snapshot_routes.json +926 -0
  60. package/fixtures/python_v044_cli/snapshot_show_alt.json +6830 -0
  61. package/fixtures/python_v044_cli/snapshot_show_bit.json +594 -0
  62. package/fixtures/python_v044_cli/snapshot_show_ecpt.json +2894 -0
  63. package/fixtures/python_v044_cli/snapshot_show_sqot.json +2392 -0
  64. package/fixtures/python_v044_cli/snapshot_show_trc.json +3037 -0
  65. package/fixtures/python_v044_cli/snapshot_verify_alt.json +10 -0
  66. package/fixtures/python_v044_cli/snapshot_verify_bit.json +10 -0
  67. package/fixtures/python_v044_cli/snapshot_verify_ecpt.json +10 -0
  68. package/fixtures/python_v044_cli/snapshot_verify_sqot.json +10 -0
  69. package/fixtures/python_v044_cli/snapshot_verify_trc.json +10 -0
  70. package/fixtures/python_v044_demo/agent_inbox.json +26 -0
  71. package/fixtures/python_v044_demo/agent_message.json +19 -0
  72. package/fixtures/python_v044_demo/agent_output.txt +1 -0
  73. package/fixtures/python_v044_demo/alt_admission_packet.json +208 -0
  74. package/fixtures/python_v044_demo/asi_proxy_phase_request.json +47 -0
  75. package/fixtures/python_v044_demo/general_intake_policy.json +58 -0
  76. package/fixtures/python_v044_demo/manifest.json +78 -0
  77. package/fixtures/python_v044_demo/packet_envelope.json +1463 -0
  78. package/fixtures/python_v044_demo/phase_dashboard.json +175 -0
  79. package/fixtures/python_v044_demo/runtime_state.json +143 -0
  80. package/fixtures/python_v044_demo/runtime_step_input.json +8 -0
  81. package/fixtures/python_v044_demo/runtime_step_report.json +1384 -0
  82. package/fixtures/python_v044_snapshots/alt.json +6830 -0
  83. package/fixtures/python_v044_snapshots/bit.json +543 -0
  84. package/fixtures/python_v044_snapshots/ecpt.json +2741 -0
  85. package/fixtures/python_v044_snapshots/sqot.json +2134 -0
  86. package/fixtures/python_v044_snapshots/trc.json +2880 -0
  87. package/package.json +129 -0
  88. package/schemas/ALTAccelerationCertificate.schema.json +169 -0
  89. package/schemas/ALTAdmissionDecision.schema.json +199 -0
  90. package/schemas/ALTCARACertificate.schema.json +285 -0
  91. package/schemas/ALTDeprecationRecord.schema.json +171 -0
  92. package/schemas/ALTKernelTransitionReport.schema.json +185 -0
  93. package/schemas/ALTResurrectionRecord.schema.json +171 -0
  94. package/schemas/ASIProxyTargetContract.schema.json +52 -0
  95. package/schemas/AbstractionToken.schema.json +281 -0
  96. package/schemas/AccelerationCertificate.schema.json +225 -0
  97. package/schemas/AccelerationExperimentSuite.schema.json +3731 -0
  98. package/schemas/AcceptedPacketPath.schema.json +148 -0
  99. package/schemas/ActionCommit.schema.json +67 -0
  100. package/schemas/ActionGrammar.schema.json +36 -0
  101. package/schemas/ActionabilityVector.schema.json +33 -0
  102. package/schemas/ActivationThresholdCertificate.schema.json +185 -0
  103. package/schemas/AdapterRouteSpec.schema.json +110 -0
  104. package/schemas/AdoptionFirstRunCommand.schema.json +44 -0
  105. package/schemas/AdoptionReviewChecklist.schema.json +36 -0
  106. package/schemas/AdoptionSafetyBoundary.schema.json +104 -0
  107. package/schemas/AgentAutonomyAuditReport.schema.json +213 -0
  108. package/schemas/AgentCheckReport.schema.json +3494 -0
  109. package/schemas/AgentCommandInvocation.schema.json +63 -0
  110. package/schemas/AgentCommunicationGuide.schema.json +213 -0
  111. package/schemas/AgentCommunicationPolicy.schema.json +73 -0
  112. package/schemas/AgentCommunicationStep.schema.json +85 -0
  113. package/schemas/AgentConnectorSpec.schema.json +89 -0
  114. package/schemas/AgentFeatureReadinessReport.schema.json +206 -0
  115. package/schemas/AgentIdentityAttestation.schema.json +99 -0
  116. package/schemas/AgentIdentityCheckReport.schema.json +225 -0
  117. package/schemas/AgentInboxRecord.schema.json +319 -0
  118. package/schemas/AgentIntakeReport.schema.json +3373 -0
  119. package/schemas/AgentIntakeRequest.schema.json +2250 -0
  120. package/schemas/AgentMessageContractReport.schema.json +195 -0
  121. package/schemas/AgentMessageDeliveryReport.schema.json +630 -0
  122. package/schemas/AgentMessageEnvelope.schema.json +201 -0
  123. package/schemas/AgentMessageNonceLedger.schema.json +45 -0
  124. package/schemas/AgentMessageVerificationContext.schema.json +60 -0
  125. package/schemas/AgentNetworkReadinessReport.schema.json +109 -0
  126. package/schemas/AgentNextActionReport.schema.json +83 -0
  127. package/schemas/AgentPacketExchangeReport.schema.json +519 -0
  128. package/schemas/AgentPeerRecord.schema.json +85 -0
  129. package/schemas/AgentPolicyIdentity.schema.json +79 -0
  130. package/schemas/AgentPopulationState.schema.json +2523 -0
  131. package/schemas/AgentRelayReadinessReport.schema.json +125 -0
  132. package/schemas/AgentRunbookReport.schema.json +100 -0
  133. package/schemas/AgentRuntimeConfig.schema.json +78 -0
  134. package/schemas/AgentTask.schema.json +101 -0
  135. package/schemas/AgentToOperatorRequest.schema.json +222 -0
  136. package/schemas/AgentWorkflowGuide.schema.json +128 -0
  137. package/schemas/AgentWorkflowStep.schema.json +59 -0
  138. package/schemas/AlgebraLawCertificate.schema.json +101 -0
  139. package/schemas/AttestationRecord.schema.json +63 -0
  140. package/schemas/AutocatalyticClosureWitness.schema.json +187 -0
  141. package/schemas/BaselineRefreshCertificate.schema.json +178 -0
  142. package/schemas/BasinReachabilityReport.schema.json +244 -0
  143. package/schemas/BottleneckCandidate.schema.json +105 -0
  144. package/schemas/BottleneckIntervention.schema.json +157 -0
  145. package/schemas/BottleneckInversionPlan.schema.json +212 -0
  146. package/schemas/BottleneckWitnessReport.schema.json +128 -0
  147. package/schemas/BoundaryGeneratorRecord.schema.json +57 -0
  148. package/schemas/BoundaryScriptRecord.schema.json +30 -0
  149. package/schemas/BudgetedToleranceScheduler.schema.json +59 -0
  150. package/schemas/CalibrationCertificate.schema.json +252 -0
  151. package/schemas/CanonicalImplementationReadinessReport.schema.json +298 -0
  152. package/schemas/CanonicalManifest.schema.json +80 -0
  153. package/schemas/CanonicalManifestRecord.schema.json +54 -0
  154. package/schemas/CanonicalTheorySnapshotSummary.schema.json +102 -0
  155. package/schemas/CapabilityBasinContract.schema.json +59 -0
  156. package/schemas/CapabilityPacketCandidate.schema.json +247 -0
  157. package/schemas/CapabilityPacketRegistry.schema.json +442 -0
  158. package/schemas/CapabilityStateVector.schema.json +169 -0
  159. package/schemas/CascadeResidualPotential.schema.json +32 -0
  160. package/schemas/CertificateCompilerRecord.schema.json +81 -0
  161. package/schemas/CertificateFamily.schema.json +376 -0
  162. package/schemas/CertificateRoute.schema.json +128 -0
  163. package/schemas/CertifiedAbstractionCapital.schema.json +161 -0
  164. package/schemas/CheckResult.schema.json +369 -0
  165. package/schemas/CheckerContext.schema.json +255 -0
  166. package/schemas/ClosedLoopAgentIteration.schema.json +1045 -0
  167. package/schemas/CollectivePhaseCertificate.schema.json +1377 -0
  168. package/schemas/CommercialReadinessSummary.schema.json +134 -0
  169. package/schemas/ConfidenceLedger.schema.json +26 -0
  170. package/schemas/ContentAddressedEvidenceRef.schema.json +48 -0
  171. package/schemas/ControlledTransition.schema.json +90 -0
  172. package/schemas/CryptographicAgentIdentity.schema.json +192 -0
  173. package/schemas/DKWCertificate.schema.json +31 -0
  174. package/schemas/DiagnosticReservePolicy.schema.json +22 -0
  175. package/schemas/DischargeRouteBinding.schema.json +93 -0
  176. package/schemas/DomainTypedSemiring.schema.json +55 -0
  177. package/schemas/DominanceWitness.schema.json +31 -0
  178. package/schemas/EProcessCertificate.schema.json +22 -0
  179. package/schemas/EdgeRelationVerificationReport.schema.json +161 -0
  180. package/schemas/EdgeRelationVerifierSpec.schema.json +62 -0
  181. package/schemas/EdgeWitness.schema.json +73 -0
  182. package/schemas/EdgeWitnessCertificate.schema.json +192 -0
  183. package/schemas/EvidenceArtifact.schema.json +112 -0
  184. package/schemas/EvidenceEnvelopeStoreRecord.schema.json +100 -0
  185. package/schemas/EvidencePolicy.schema.json +57 -0
  186. package/schemas/EvidenceResolutionBatch.schema.json +347 -0
  187. package/schemas/EvidenceVerificationProfile.schema.json +74 -0
  188. package/schemas/ExecutableALTCertificatePacket.schema.json +1512 -0
  189. package/schemas/ExecutableTraceNormalForm.schema.json +659 -0
  190. package/schemas/ExecutionAvailablePathCertificate.schema.json +204 -0
  191. package/schemas/ExternalCandidateClassification.schema.json +10 -0
  192. package/schemas/ExternalObligationCatalog.schema.json +238 -0
  193. package/schemas/ExternalVerifierHook.schema.json +174 -0
  194. package/schemas/FiniteOrder.schema.json +34 -0
  195. package/schemas/FinitePhaseControlCertificate.schema.json +100 -0
  196. package/schemas/FiniteTraceLaw.schema.json +30 -0
  197. package/schemas/FixedPopulationLedger.schema.json +255 -0
  198. package/schemas/FormationCostLedger.schema.json +91 -0
  199. package/schemas/FoundryControlDashboard.schema.json +198 -0
  200. package/schemas/FoundryState.schema.json +1819 -0
  201. package/schemas/FrontierDebtReport.schema.json +115 -0
  202. package/schemas/FunctorLawCertificate.schema.json +82 -0
  203. package/schemas/FusedGeometricComparisonCertificate.schema.json +79 -0
  204. package/schemas/FutureFreedomVector.schema.json +84 -0
  205. package/schemas/GeneralIntakePolicy.schema.json +255 -0
  206. package/schemas/GeneralIntakePolicyDecision.schema.json +85 -0
  207. package/schemas/GeneralIntakeProfile.schema.json +11 -0
  208. package/schemas/GeneralIntakeReport.schema.json +861 -0
  209. package/schemas/GeneralIntakeRuntimeBridgeReport.schema.json +761 -0
  210. package/schemas/GeneralIntakeSource.schema.json +57 -0
  211. package/schemas/GoodTuringCertificate.schema.json +27 -0
  212. package/schemas/HazardEnvelopeCertificate.schema.json +192 -0
  213. package/schemas/HiddenCapabilityInjectionReport.schema.json +212 -0
  214. package/schemas/IdentityContributionStatus.schema.json +11 -0
  215. package/schemas/IdentityTrustProfile.schema.json +12 -0
  216. package/schemas/ImplementationMaturity.schema.json +27 -0
  217. package/schemas/IndependenceCertificate.schema.json +42 -0
  218. package/schemas/InnerViabilityKernel.schema.json +45 -0
  219. package/schemas/IntakeProvenanceRecord.schema.json +192 -0
  220. package/schemas/InterventionCandidate.schema.json +266 -0
  221. package/schemas/Judgment.schema.json +351 -0
  222. package/schemas/LatticeWitness.schema.json +63 -0
  223. package/schemas/LedgerCoordinate.schema.json +79 -0
  224. package/schemas/LifecycleCostBounds.schema.json +65 -0
  225. package/schemas/LiquidityCertificate.schema.json +1094 -0
  226. package/schemas/MartingaleBlockResidual.schema.json +32 -0
  227. package/schemas/MartingaleDeficiencyCertificate.schema.json +76 -0
  228. package/schemas/MechanismCubeCertificate.schema.json +92 -0
  229. package/schemas/MissionValidityCertificate.schema.json +153 -0
  230. package/schemas/MonoidRecord.schema.json +30 -0
  231. package/schemas/MonotoneMap.schema.json +61 -0
  232. package/schemas/NegativeLiquidityCertificate.schema.json +176 -0
  233. package/schemas/NonPromotionPolicy.schema.json +39 -0
  234. package/schemas/ObligationRule.schema.json +54 -0
  235. package/schemas/ObligationSet.schema.json +230 -0
  236. package/schemas/ObligationTrace.schema.json +156 -0
  237. package/schemas/ObservationWindow.schema.json +48 -0
  238. package/schemas/ObservedTraceProjection.schema.json +57 -0
  239. package/schemas/OccupationLedger.schema.json +33 -0
  240. package/schemas/OperationalCheck.schema.json +29 -0
  241. package/schemas/OperationalReadinessReport.schema.json +216 -0
  242. package/schemas/OperatorAdoptionPacket.schema.json +303 -0
  243. package/schemas/OpportunityMeasureContract.schema.json +165 -0
  244. package/schemas/OrderedPotentialCone.schema.json +125 -0
  245. package/schemas/PacketCapitalLineage.schema.json +90 -0
  246. package/schemas/PacketExchangeEnvelope.schema.json +213 -0
  247. package/schemas/PacketImportInspectionReport.schema.json +68 -0
  248. package/schemas/PacketIngestionReport.schema.json +655 -0
  249. package/schemas/PacketLineageDigest.schema.json +70 -0
  250. package/schemas/PacketMergeReport.schema.json +286 -0
  251. package/schemas/PacketPromotionPolicy.schema.json +47 -0
  252. package/schemas/PacketPromotionReport.schema.json +354 -0
  253. package/schemas/PacketRejection.schema.json +158 -0
  254. package/schemas/PhaseAccelerationBenchmarkReport.schema.json +103 -0
  255. package/schemas/PhaseAccelerationPlan.schema.json +4449 -0
  256. package/schemas/PhaseAccelerationRequest.schema.json +5333 -0
  257. package/schemas/PhaseAccelerationScore.schema.json +66 -0
  258. package/schemas/PhaseBenchmarkCaseResult.schema.json +164 -0
  259. package/schemas/PhaseBenchmarkSuiteReport.schema.json +234 -0
  260. package/schemas/PhaseBenchmarkTask.schema.json +36 -0
  261. package/schemas/PhaseComponentGap.schema.json +46 -0
  262. package/schemas/PhaseControlAction.schema.json +80 -0
  263. package/schemas/PhaseControlAuditSummary.schema.json +143 -0
  264. package/schemas/PhaseControlEnvelope.schema.json +53 -0
  265. package/schemas/PhaseControlObjective.schema.json +98 -0
  266. package/schemas/PhaseControlPlan.schema.json +377 -0
  267. package/schemas/PhaseControlRunReport.schema.json +425 -0
  268. package/schemas/PhaseControlState.schema.json +383 -0
  269. package/schemas/PhaseDashboardReport.schema.json +249 -0
  270. package/schemas/PhaseGapVector.schema.json +101 -0
  271. package/schemas/PhaseObservationReport.schema.json +321 -0
  272. package/schemas/PhaseTrajectoryReport.schema.json +4522 -0
  273. package/schemas/PopulationRuntimeStepReport.schema.json +5125 -0
  274. package/schemas/PortabilityConformanceReport.schema.json +99 -0
  275. package/schemas/PortabilitySchemaBundle.schema.json +23 -0
  276. package/schemas/ProblemSolvingTrace.schema.json +162 -0
  277. package/schemas/ProcessGrammarRecord.schema.json +56 -0
  278. package/schemas/ProductOrder.schema.json +53 -0
  279. package/schemas/ProductionReadinessProfile.schema.json +37 -0
  280. package/schemas/ProjectionAudit.schema.json +70 -0
  281. package/schemas/ProofObligation.schema.json +200 -0
  282. package/schemas/ProtocolFrameDigest.schema.json +79 -0
  283. package/schemas/ProtocolFunctorCertificate.schema.json +89 -0
  284. package/schemas/ProtocolObject.schema.json +45 -0
  285. package/schemas/ProtocolRelativeBenchmarkMetric.schema.json +39 -0
  286. package/schemas/ProvenanceManifest.schema.json +221 -0
  287. package/schemas/ProvenanceManifestEntry.schema.json +29 -0
  288. package/schemas/PsiDashboard.schema.json +213 -0
  289. package/schemas/PullbackGluingWitness.schema.json +43 -0
  290. package/schemas/QuarantineLedger.schema.json +31 -0
  291. package/schemas/ReachableMassRecursionCertificate.schema.json +129 -0
  292. package/schemas/ReconstructionResidual.schema.json +24 -0
  293. package/schemas/RefreshRule.schema.json +31 -0
  294. package/schemas/Registry.schema.json +231 -0
  295. package/schemas/ReleaseArtifactManifest.schema.json +62 -0
  296. package/schemas/ReproductionMatrixCertificate.schema.json +190 -0
  297. package/schemas/ResidualCarryForwardReport.schema.json +57 -0
  298. package/schemas/ResourceCalendarRecord.schema.json +67 -0
  299. package/schemas/ResourceEnvelope.schema.json +42 -0
  300. package/schemas/ResourceMatchedBaselineConfig.schema.json +81 -0
  301. package/schemas/RiskBudgetLedger.schema.json +19 -0
  302. package/schemas/RobotsDecision.schema.json +44 -0
  303. package/schemas/RootFinalityCertificate.schema.json +190 -0
  304. package/schemas/RouteExecutionBatch.schema.json +930 -0
  305. package/schemas/RouteExecutionRequest.schema.json +87 -0
  306. package/schemas/RuntimeActionResult.schema.json +807 -0
  307. package/schemas/RuntimeComparisonReport.schema.json +3670 -0
  308. package/schemas/RuntimeEvent.schema.json +142 -0
  309. package/schemas/RuntimeEventLog.schema.json +161 -0
  310. package/schemas/RuntimeExecutionReport.schema.json +872 -0
  311. package/schemas/RuntimeExecutorPolicy.schema.json +68 -0
  312. package/schemas/RuntimeHealthReport.schema.json +161 -0
  313. package/schemas/RuntimeIdentityContext.schema.json +480 -0
  314. package/schemas/RuntimeRunReport.schema.json +3487 -0
  315. package/schemas/RuntimeServiceSettings.schema.json +55 -0
  316. package/schemas/RuntimeState.schema.json +1438 -0
  317. package/schemas/RuntimeStepInput.schema.json +685 -0
  318. package/schemas/RuntimeStepReport.schema.json +3314 -0
  319. package/schemas/RuntimeStoreRecord.schema.json +106 -0
  320. package/schemas/RuntimeStoreSnapshot.schema.json +4815 -0
  321. package/schemas/SBOMManifest.schema.json +67 -0
  322. package/schemas/SQOTTheorySnapshot.schema.json +49 -0
  323. package/schemas/SafePhaseAction.schema.json +96 -0
  324. package/schemas/SalienceQueueRecord.schema.json +313 -0
  325. package/schemas/SalienceScheduleReport.schema.json +434 -0
  326. package/schemas/SalienceSchedulingDecision.schema.json +167 -0
  327. package/schemas/SchemaBundleDigest.schema.json +57 -0
  328. package/schemas/ScriptGroundMetricCertificate.schema.json +47 -0
  329. package/schemas/SelectiveCUPCertificate.schema.json +414 -0
  330. package/schemas/SettlementReturnRAFCertificate.schema.json +122 -0
  331. package/schemas/SinkhornCertificate.schema.json +55 -0
  332. package/schemas/SnapshotAttribution.schema.json +63 -0
  333. package/schemas/SnapshotCatalog.schema.json +481 -0
  334. package/schemas/SplitCertificate.schema.json +39 -0
  335. package/schemas/StatusAlgebraRecord.schema.json +37 -0
  336. package/schemas/StoppedEvidenceSheafCertificate.schema.json +120 -0
  337. package/schemas/StrictTexParseReport.schema.json +67 -0
  338. package/schemas/SybilResistanceLedger.schema.json +427 -0
  339. package/schemas/SybilResistancePolicy.schema.json +176 -0
  340. package/schemas/TRCCompileResult.schema.json +239 -0
  341. package/schemas/TRCStateRecord.schema.json +149 -0
  342. package/schemas/TelemetryCostCertificate.schema.json +171 -0
  343. package/schemas/TexGrammarDiagnostic.schema.json +39 -0
  344. package/schemas/TheoryAuditReport.schema.json +654 -0
  345. package/schemas/TheoryAuditSuiteReport.schema.json +775 -0
  346. package/schemas/TheoryFidelityReport.schema.json +100 -0
  347. package/schemas/TheoryImplementationRecord.schema.json +203 -0
  348. package/schemas/TheorySnapshot.schema.json +459 -0
  349. package/schemas/TheorySnapshotItem.schema.json +60 -0
  350. package/schemas/TokenLineage.schema.json +76 -0
  351. package/schemas/ToleranceAllocationCertificate.schema.json +62 -0
  352. package/schemas/TraceNormalizationCertificate.schema.json +77 -0
  353. package/schemas/TraceSufficiencyCertificate.schema.json +166 -0
  354. package/schemas/TransportCertificate.schema.json +178 -0
  355. package/schemas/TypedTraceTransducerRecord.schema.json +64 -0
  356. package/schemas/ValueBridgeReport.schema.json +131 -0
  357. package/schemas/VectorCompatibleFamily.schema.json +354 -0
  358. package/schemas/VerificationThroughputReport.schema.json +62 -0
  359. package/schemas/VerifiedCapabilityPacket.schema.json +251 -0
  360. package/schemas/VerifierEvidenceEnvelope.schema.json +178 -0
  361. package/schemas/VerifierResolution.schema.json +275 -0
  362. package/schemas/WebDiscoveryReport.schema.json +675 -0
  363. package/schemas/WebFetchPolicy.schema.json +145 -0
  364. package/schemas/WebFetchReport.schema.json +133 -0
  365. package/schemas/bundle.schema.json +100808 -0
  366. package/schemas/schema-digest.json +1674 -0
@@ -0,0 +1,2646 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/main.ts
4
+ import {
5
+ cpSync as cpSync2,
6
+ existsSync as existsSync6,
7
+ mkdirSync as mkdirSync3,
8
+ readFileSync as readFileSync9,
9
+ readdirSync as readdirSync2,
10
+ writeFileSync as writeFileSync3
11
+ } from "fs";
12
+ import { dirname as dirname4, join as join4 } from "path";
13
+ import { Command } from "commander";
14
+
15
+ // src/io/fixtures.ts
16
+ import { readFileSync } from "fs";
17
+ import { join as join2, normalize, sep } from "path";
18
+
19
+ // src/core/json.ts
20
+ function sortJson(value) {
21
+ if (Array.isArray(value)) {
22
+ return value.map((item) => sortJson(item));
23
+ }
24
+ if (value && typeof value === "object") {
25
+ const input = value;
26
+ const output = {};
27
+ for (const key of Object.keys(input).sort()) {
28
+ const child = input[key];
29
+ if (child !== void 0) {
30
+ output[key] = sortJson(child);
31
+ }
32
+ }
33
+ return output;
34
+ }
35
+ return value;
36
+ }
37
+ function stableStringify(value) {
38
+ return `${JSON.stringify(sortJson(value), null, 2)}
39
+ `;
40
+ }
41
+ function lfNormalize(text) {
42
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
43
+ }
44
+ function parseJsonObject(text, label = "JSON") {
45
+ const parsed = JSON.parse(text);
46
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
47
+ throw new Error(`${label} must be a JSON object`);
48
+ }
49
+ return parsed;
50
+ }
51
+ function dedupeSorted(values) {
52
+ return [
53
+ ...new Set([...values].filter((item) => Boolean(item)))
54
+ ].sort();
55
+ }
56
+
57
+ // src/io/paths.ts
58
+ import { existsSync } from "fs";
59
+ import { dirname, join, resolve } from "path";
60
+ import { fileURLToPath } from "url";
61
+ function packageRoot() {
62
+ let current = dirname(fileURLToPath(import.meta.url));
63
+ for (let i = 0; i < 8; i += 1) {
64
+ if (existsSync(join(current, "package.json")) && existsSync(join(current, "schemas"))) {
65
+ return current;
66
+ }
67
+ const next = dirname(current);
68
+ if (next === current) {
69
+ break;
70
+ }
71
+ current = next;
72
+ }
73
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../..");
74
+ }
75
+ function schemaDir() {
76
+ return join(packageRoot(), "schemas");
77
+ }
78
+ function fixtureDir() {
79
+ return join(packageRoot(), "fixtures", "portability_conformance");
80
+ }
81
+ function fixtureRoot() {
82
+ return join(packageRoot(), "fixtures");
83
+ }
84
+
85
+ // src/io/fixtures.ts
86
+ function safeFixturePath(...parts) {
87
+ const root = normalize(fixtureRoot());
88
+ const normalized = normalize(join2(root, ...parts));
89
+ if (normalized !== root && !normalized.startsWith(`${root}${sep}`)) {
90
+ throw new Error("fixture path escapes package fixtures");
91
+ }
92
+ return normalized;
93
+ }
94
+ function fixtureJson(file) {
95
+ return parseJsonObject(readFileSync(join2(fixtureDir(), file), "utf8"), file);
96
+ }
97
+ function fixtureText(namespace, file) {
98
+ if (namespace.includes("..") || file.includes("..")) {
99
+ throw new Error("fixture path must not contain parent traversal");
100
+ }
101
+ return readFileSync(safeFixturePath(namespace, file), "utf8");
102
+ }
103
+ function fixtureJsonFrom(namespace, file) {
104
+ return parseJsonObject(fixtureText(namespace, file), `${namespace}/${file}`);
105
+ }
106
+ function pythonCliFixture(name) {
107
+ if (!/^[a-z0-9_]+$/.test(name)) {
108
+ throw new Error(
109
+ `invalid Python v0.4.4 CLI fixture ${JSON.stringify(name)}`
110
+ );
111
+ }
112
+ return fixtureJsonFrom("python_v044_cli", `${name}.json`);
113
+ }
114
+ function portabilityManifest() {
115
+ return fixtureJson("manifest.json");
116
+ }
117
+
118
+ // src/alt/index.ts
119
+ function altAdmit(packetId = "alt-packet:demo") {
120
+ const decision = structuredClone(fixtureJson("alt_admission_decision.json"));
121
+ decision.packet_id = packetId;
122
+ decision.accepted = Boolean(decision.accepted ?? false);
123
+ decision.settled = false;
124
+ decision.reasons = [
125
+ ...Array.isArray(decision.reasons) ? decision.reasons.map(String) : [],
126
+ "ALT admission remains candidate-only until value, transport, hazard, and baseline obligations are discharged"
127
+ ].sort();
128
+ return decision;
129
+ }
130
+
131
+ // src/core/ledger.ts
132
+ function emptyLedger() {
133
+ return { coordinates: {} };
134
+ }
135
+ function residualLedger(name, value = 1, description) {
136
+ return {
137
+ coordinates: {
138
+ [name]: {
139
+ name,
140
+ value,
141
+ unit: "dimensionless",
142
+ kind: "residual",
143
+ description: description ?? null,
144
+ evidence_status: "declared",
145
+ evidence_refs: [],
146
+ known: true
147
+ }
148
+ }
149
+ };
150
+ }
151
+ function summarizeLedger(ledger) {
152
+ const summary = {};
153
+ if (!ledger) {
154
+ return summary;
155
+ }
156
+ for (const coordinate of Object.values(ledger.coordinates ?? {})) {
157
+ const kind = coordinate.kind ?? "residual";
158
+ summary[kind] = (summary[kind] ?? 0) + Number(coordinate.value ?? 0);
159
+ }
160
+ return Object.fromEntries(
161
+ Object.entries(summary).sort(([a], [b]) => a.localeCompare(b))
162
+ );
163
+ }
164
+
165
+ // src/phase/index.ts
166
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
167
+
168
+ // src/io/schema.ts
169
+ import {
170
+ cpSync,
171
+ existsSync as existsSync2,
172
+ mkdirSync,
173
+ readdirSync,
174
+ readFileSync as readFileSync2,
175
+ writeFileSync
176
+ } from "fs";
177
+ import { basename, join as join3 } from "path";
178
+ import Ajv2020Module from "ajv/dist/2020.js";
179
+ var PUBLIC_SCHEMA_NAME = /^[A-Za-z][A-Za-z0-9]*$/;
180
+ function assertSchemaTypeName(typeName) {
181
+ if (!PUBLIC_SCHEMA_NAME.test(typeName)) {
182
+ throw new Error(`unknown schema type ${JSON.stringify(typeName)}`);
183
+ }
184
+ }
185
+ function schemaPath(typeName) {
186
+ assertSchemaTypeName(typeName);
187
+ return join3(schemaDir(), `${typeName}.schema.json`);
188
+ }
189
+ function schemaNames() {
190
+ return readdirSync(schemaDir()).filter(
191
+ (name) => name.endsWith(".schema.json") && name !== "bundle.schema.json"
192
+ ).map((name) => name.slice(0, -".schema.json".length)).sort();
193
+ }
194
+ function schemaByType(typeName = "Registry") {
195
+ const path = schemaPath(typeName);
196
+ if (!existsSync2(path)) {
197
+ throw new Error(`unknown schema type ${JSON.stringify(typeName)}`);
198
+ }
199
+ return parseJsonObject(readFileSync2(path, "utf8"), `${typeName} schema`);
200
+ }
201
+ function schemaBundle() {
202
+ const bundlePath = join3(schemaDir(), "bundle.schema.json");
203
+ if (existsSync2(bundlePath)) {
204
+ const bundle = parseJsonObject(
205
+ readFileSync2(bundlePath, "utf8"),
206
+ "schema bundle"
207
+ );
208
+ if (bundle.bundle_id && bundle.schemas && typeof bundle.schemas === "object" && !Array.isArray(bundle.schemas)) {
209
+ return bundle;
210
+ }
211
+ }
212
+ const schemas = {};
213
+ for (const name of schemaNames()) {
214
+ schemas[name] = schemaByType(name);
215
+ }
216
+ return {
217
+ bundle_id: "percolation-inversion-compiler-portability",
218
+ schemas
219
+ };
220
+ }
221
+ function validateData(data, schema) {
222
+ const Ajv2020 = Ajv2020Module;
223
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
224
+ const validate = ajv.compile(schema);
225
+ const valid = Boolean(validate(data));
226
+ return {
227
+ valid,
228
+ errors: valid ? [] : (validate.errors ?? []).map(
229
+ (error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`
230
+ )
231
+ };
232
+ }
233
+ function validateByType(data, typeName) {
234
+ return validateData(data, schemaByType(typeName));
235
+ }
236
+ function writeAllSchemas(outputDir) {
237
+ mkdirSync(outputDir, { recursive: true });
238
+ const written = [];
239
+ const files = [
240
+ ...schemaNames().map((name) => `${name}.schema.json`),
241
+ "bundle.schema.json",
242
+ "schema-digest.json"
243
+ ];
244
+ for (const file of files) {
245
+ const source = join3(schemaDir(), file);
246
+ if (!existsSync2(source)) {
247
+ continue;
248
+ }
249
+ const target = join3(outputDir, file);
250
+ cpSync(source, target);
251
+ written.push(basename(target));
252
+ }
253
+ return written.sort();
254
+ }
255
+
256
+ // src/io/identity.ts
257
+ function nonEmptyStringArray(value) {
258
+ return Array.isArray(value) && value.some((item) => typeof item === "string" && item.length > 0);
259
+ }
260
+ function runtimeIdentityContextAccepted(data) {
261
+ return validateByType(data, "RuntimeIdentityContext").valid && data.accepted === true && nonEmptyStringArray(data.accepted_agent_ids) && nonEmptyStringArray(data.accepted_public_key_ids);
262
+ }
263
+
264
+ // src/runtime/index.ts
265
+ import { readFileSync as readFileSync3 } from "fs";
266
+ function clone(value) {
267
+ return structuredClone(value);
268
+ }
269
+ function buildRuntimeStep(options = {}) {
270
+ const report = clone(pythonCliFixture("runtime_step_demo"));
271
+ const profile = options.profile ?? "development";
272
+ const reasons = new Set(
273
+ Array.isArray(report.reasons) ? report.reasons.map(String) : []
274
+ );
275
+ if (options.agentOutput) {
276
+ report.agent_output_digest = `sha256:${Buffer.from(options.agentOutput, "utf8").toString("hex").slice(0, 16)}`;
277
+ }
278
+ if (options.statePath) {
279
+ const state = parseJsonObject(
280
+ readFileSync3(options.statePath, "utf8"),
281
+ "runtime state"
282
+ );
283
+ const validation = validateByType(state, "RuntimeState");
284
+ if (!validation.valid) {
285
+ throw new Error(
286
+ `runtime state schema-invalid: ${validation.errors.join("; ")}`
287
+ );
288
+ }
289
+ }
290
+ if (options.inputPath) {
291
+ const input = parseJsonObject(
292
+ readFileSync3(options.inputPath, "utf8"),
293
+ "runtime input"
294
+ );
295
+ const validation = validateByType(input, "RuntimeStepInput");
296
+ if (!validation.valid) {
297
+ throw new Error(
298
+ `runtime input schema-invalid: ${validation.errors.join("; ")}`
299
+ );
300
+ }
301
+ if (typeof input.allow_live_connectors === "boolean") {
302
+ report.allow_live_connectors = input.allow_live_connectors;
303
+ }
304
+ }
305
+ if (typeof options.allowLiveConnectors === "boolean") {
306
+ report.allow_live_connectors = options.allowLiveConnectors;
307
+ }
308
+ if (options.identityContextPath) {
309
+ const identity2 = parseJsonObject(
310
+ readFileSync3(options.identityContextPath, "utf8"),
311
+ "identity context"
312
+ );
313
+ const validation = validateByType(identity2, "RuntimeIdentityContext");
314
+ const accepted = runtimeIdentityContextAccepted(identity2);
315
+ report.identity_context_accepted = accepted;
316
+ report.identity_verified = accepted;
317
+ if (!accepted) {
318
+ reasons.add("identity context is missing or not accepted");
319
+ report.operationally_usable = false;
320
+ }
321
+ }
322
+ if (profile === "production" || profile === "adversarial") {
323
+ if (!options.identityContextPath) {
324
+ reasons.add(
325
+ "production/adversarial identity context is missing or not accepted"
326
+ );
327
+ report.operationally_usable = false;
328
+ report.identity_verified = false;
329
+ }
330
+ }
331
+ report.accepted = true;
332
+ report.finite_checks_passed = true;
333
+ report.settled = false;
334
+ report.reasons = [...reasons].sort();
335
+ return report;
336
+ }
337
+ function runtimeHealth(profile = "development") {
338
+ return {
339
+ report_id: "runtime-health",
340
+ profile,
341
+ accepted: true,
342
+ operationally_usable: profile === "development",
343
+ settled: false,
344
+ checks: {
345
+ command_execution_allowed: false,
346
+ background_crawling_allowed: false,
347
+ hidden_promotion_allowed: false,
348
+ residual_ledgers_preserved: true
349
+ },
350
+ reasons: profile === "development" ? [] : [
351
+ "production profile requires explicit identity and provenance context"
352
+ ]
353
+ };
354
+ }
355
+
356
+ // src/phase/index.ts
357
+ function clone2(value) {
358
+ return structuredClone(value);
359
+ }
360
+ var phaseSchemaRefs = pythonCliFixture("phase_plan_compact").schema_refs ?? [
361
+ "PhaseAccelerationRequest",
362
+ "PhaseAccelerationPlan",
363
+ "PhaseGapVector",
364
+ "PhaseComponentGap",
365
+ "BottleneckCandidate",
366
+ "SafePhaseAction"
367
+ ];
368
+ function phaseAccelerationSafetyInvariants() {
369
+ const fixture = pythonCliFixture("phase_plan_compact");
370
+ if (Array.isArray(fixture.safety_invariants)) {
371
+ return fixture.safety_invariants.map(String);
372
+ }
373
+ return [
374
+ "phase acceleration planning is recommendation-only and does not execute actions",
375
+ "raw external candidate volume cannot improve Psi, BR, AC, or settled status",
376
+ "candidate packets, agent messages, and proxy-only ALT reports remain candidates",
377
+ "settled remains false unless scoped finite verifier rules discharge all obligations",
378
+ "residual ledgers and missing obligations must be preserved into downstream loops",
379
+ "ASI-proxy phase is protocol-relative workflow coordination, not real ASI proof",
380
+ "no physical, simulator, oracle, legal, or policy outcome is proven by this report",
381
+ "no hidden promotion from accepted or workflow_usable to settled"
382
+ ];
383
+ }
384
+ function identityContextAccepted(path) {
385
+ if (!path || !existsSync3(path)) {
386
+ return false;
387
+ }
388
+ try {
389
+ const data = parseJsonObject(
390
+ readFileSync4(path, "utf8"),
391
+ "identity context"
392
+ );
393
+ return runtimeIdentityContextAccepted(data);
394
+ } catch {
395
+ return false;
396
+ }
397
+ }
398
+ function runtimeReportIdentityAccepted(report) {
399
+ if (!report) {
400
+ return false;
401
+ }
402
+ const identity2 = report.identity_context;
403
+ if (!identity2 || typeof identity2 !== "object" || Array.isArray(identity2)) {
404
+ return false;
405
+ }
406
+ const data = identity2;
407
+ return runtimeIdentityContextAccepted(data);
408
+ }
409
+ function objectList(value) {
410
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
411
+ }
412
+ function ensureActionBoundary(plan) {
413
+ for (const action of objectList(plan.recommended_actions)) {
414
+ action.execution_authority_granted = false;
415
+ action.settled = false;
416
+ }
417
+ }
418
+ function buildPhaseAccelerationPlan(request = {}) {
419
+ const plan = clone2(pythonCliFixture("phase_plan_full"));
420
+ const profile = request.profile ?? "development";
421
+ const hasDynamicRuntimeInput = Boolean(
422
+ request.agent_output || request.profile && request.profile !== "development" || request.allow_live_connectors === false || request.identity_context_path
423
+ );
424
+ const runtimeReport = request.runtime_report ?? (hasDynamicRuntimeInput ? buildRuntimeStep({
425
+ profile,
426
+ agentOutput: request.agent_output,
427
+ allowLiveConnectors: request.allow_live_connectors,
428
+ identityContextPath: request.identity_context_path
429
+ }) : plan.runtime_report);
430
+ const cannotPromote = new Set(
431
+ Array.isArray(plan.cannot_promote_because) ? plan.cannot_promote_because.map(String) : []
432
+ );
433
+ const candidateOnly = new Set(
434
+ Array.isArray(plan.candidate_only_reasons) ? plan.candidate_only_reasons.map(String) : []
435
+ );
436
+ const settledBlockers = new Set(
437
+ Array.isArray(plan.settled_blockers) ? plan.settled_blockers.map(String) : []
438
+ );
439
+ const reasons = new Set(
440
+ Array.isArray(plan.reasons) ? plan.reasons.map(String) : []
441
+ );
442
+ cannotPromote.add("missing obligations remain");
443
+ settledBlockers.add(
444
+ "phase planner is recommendation-only and cannot settle claims"
445
+ );
446
+ if ((request.general_intake_bridge_reports ?? []).some(
447
+ (report) => report.candidate_only !== false
448
+ )) {
449
+ candidateOnly.add(
450
+ "candidate-only external volume cannot reduce phase gaps"
451
+ );
452
+ }
453
+ if ((request.alt_admission_decisions ?? []).some(
454
+ (decision) => Array.isArray(decision.missing_obligations) && decision.missing_obligations.length > 0
455
+ )) {
456
+ candidateOnly.add(
457
+ "ALT admission is candidate-only until missing obligations are discharged"
458
+ );
459
+ }
460
+ const identityRequired = profile === "production" || profile === "adversarial";
461
+ const identityAccepted = identityContextAccepted(request.identity_context_path) || runtimeReportIdentityAccepted(runtimeReport);
462
+ if (identityRequired && !identityAccepted) {
463
+ cannotPromote.add(
464
+ "production/adversarial identity context is missing or not accepted"
465
+ );
466
+ settledBlockers.add(
467
+ "production identity context is required before operational promotion"
468
+ );
469
+ }
470
+ plan.plan_id = `phase-acceleration-plan:${request.request_id ?? "phase-acceleration"}`;
471
+ plan.request_id = request.request_id ?? "phase-acceleration";
472
+ plan.profile = profile;
473
+ plan.report_mode = request.compact ? "compact" : "full";
474
+ plan.accepted = true;
475
+ plan.workflow_usable = true;
476
+ plan.finite_checks_passed = plan.finite_checks_passed ?? true;
477
+ plan.operationally_usable = !(identityRequired && !identityAccepted);
478
+ plan.settled = false;
479
+ plan.status = cannotPromote.size > 0 || candidateOnly.size > 0 ? "diagnostic" : "provisional";
480
+ plan.runtime_report = request.compact ? void 0 : runtimeReport;
481
+ plan.cannot_promote_because = [...cannotPromote].sort();
482
+ plan.candidate_only_reasons = [...candidateOnly].sort();
483
+ plan.settled_blockers = [...settledBlockers].sort();
484
+ plan.reasons = dedupeSorted([...reasons, ...cannotPromote, ...candidateOnly]);
485
+ plan.safety_invariants = phaseAccelerationSafetyInvariants();
486
+ plan.schema_refs = phaseSchemaRefs;
487
+ plan.safe_commands = dedupeSorted([
488
+ ...Array.isArray(plan.safe_commands) ? plan.safe_commands.map(String) : []
489
+ ]);
490
+ plan.sdk_calls = dedupeSorted([
491
+ ...Array.isArray(plan.sdk_calls) ? plan.sdk_calls.map(String) : []
492
+ ]);
493
+ ensureActionBoundary(plan);
494
+ return plan;
495
+ }
496
+ function phaseAccelerationCompactPayload(plan) {
497
+ return {
498
+ plan_id: plan.plan_id,
499
+ request_id: plan.request_id,
500
+ profile: plan.profile,
501
+ report_mode: "compact",
502
+ accepted: plan.accepted,
503
+ workflow_usable: plan.workflow_usable,
504
+ finite_checks_passed: plan.finite_checks_passed ?? true,
505
+ operationally_usable: plan.operationally_usable,
506
+ settled: false,
507
+ status: plan.status ?? "diagnostic",
508
+ phase_gap_vector: plan.phase_gap_vector,
509
+ top_bottlenecks: plan.top_bottlenecks ?? (Array.isArray(plan.bottlenecks) ? plan.bottlenecks.slice(0, 5) : []),
510
+ safe_commands: plan.safe_commands ?? [],
511
+ sdk_calls: plan.sdk_calls ?? [],
512
+ schema_refs: plan.schema_refs ?? phaseSchemaRefs,
513
+ cannot_promote_because: plan.cannot_promote_because ?? [],
514
+ candidate_only_reasons: plan.candidate_only_reasons ?? [],
515
+ settled_blockers: plan.settled_blockers ?? [],
516
+ residual_summary: plan.residual_summary ?? {},
517
+ missing_obligations: plan.missing_obligations ?? [],
518
+ safety_invariants: plan.safety_invariants ?? phaseAccelerationSafetyInvariants(),
519
+ reasons: plan.reasons ?? []
520
+ };
521
+ }
522
+ function phaseAccelerationRunbook(profile = "development") {
523
+ const runbook = clone2(pythonCliFixture("phase_runbook"));
524
+ runbook.profile = profile;
525
+ return runbook;
526
+ }
527
+ function buildPhaseAccelerationBenchmark(profile = "development") {
528
+ const report = clone2(pythonCliFixture("phase_benchmark"));
529
+ report.profile = profile;
530
+ report.accepted = true;
531
+ report.workflow_usable = true;
532
+ report.operationally_usable = true;
533
+ report.settled = false;
534
+ report.invariant_checks = {
535
+ candidate_only_volume_does_not_reduce_gap: true,
536
+ planner_does_not_execute_commands: true,
537
+ residuals_visible: true,
538
+ settled_not_promoted: true
539
+ };
540
+ report.safety_invariants = phaseAccelerationSafetyInvariants();
541
+ return report;
542
+ }
543
+
544
+ // src/agent/index.ts
545
+ function clone3(value) {
546
+ return structuredClone(value);
547
+ }
548
+ function agentSafetyInvariants() {
549
+ const fixture = pythonCliFixture("agent_check_compact");
550
+ if (Array.isArray(fixture.safety_invariants)) {
551
+ return fixture.safety_invariants.map(String);
552
+ }
553
+ return [
554
+ "accepted is not settled",
555
+ "workflow_usable is not settled",
556
+ "safe_commands are inspection guidance and are not executed by PIC",
557
+ "residual ledgers and missing obligations are preserved",
558
+ "no hidden promotion from accepted or workflow_usable to settled",
559
+ "default-live explicit sources remain candidate-only until verified"
560
+ ];
561
+ }
562
+ function runAgentIntake(request = {}) {
563
+ const report = clone3(pythonCliFixture("agent_intake"));
564
+ const hasDynamicInput = Boolean(
565
+ request.agent_output || request.profile && request.profile !== "development" || request.allow_live_connectors === false || request.identity_context_path
566
+ );
567
+ const runtime2 = hasDynamicInput ? buildRuntimeStep({
568
+ profile: request.profile,
569
+ agentOutput: request.agent_output,
570
+ allowLiveConnectors: request.allow_live_connectors,
571
+ identityContextPath: request.identity_context_path
572
+ }) : report.runtime_report;
573
+ report.report_id = `agent-intake:${request.request_id ?? "agent-intake"}:agent-intake-step`;
574
+ report.profile = request.profile ?? "development";
575
+ report.runtime_report = runtime2;
576
+ report.accepted = runtime2.accepted;
577
+ report.operationally_usable = runtime2.operationally_usable;
578
+ report.settled = false;
579
+ report.residual_summary = summarizeLedger(runtime2.residual_ledger);
580
+ report.recommended_next_commands = [
581
+ "Inspect runtime_report.residual_ledger and runtime_report.missing_obligations.",
582
+ "Inspect runtime_report.route_execution_requests before route execution.",
583
+ "Review runtime_report.agent_tasks; do not execute arbitrary commands.",
584
+ "Run another runtime step after new evidence or action results are available."
585
+ ];
586
+ report.reasons = Array.isArray(runtime2.reasons) ? runtime2.reasons : [];
587
+ return report;
588
+ }
589
+ function runAgentCheck(request = {}, compact = false) {
590
+ const report = clone3(
591
+ compact ? pythonCliFixture("agent_check_compact") : pythonCliFixture("agent_check_full")
592
+ );
593
+ const intake = runAgentIntake(request);
594
+ const runtime2 = intake.runtime_report;
595
+ const unresolved = dedupeSorted([
596
+ ...runtime2.missing_obligations ?? []
597
+ ]);
598
+ const reasons = dedupeSorted([
599
+ ...intake.reasons ?? [],
600
+ "unresolved obligations remain; use workflow_usable for routing only"
601
+ ]);
602
+ report.report_id = `agent-check:${request.request_id ?? "agent-intake"}`;
603
+ report.profile = request.profile ?? "development";
604
+ report.report_mode = compact ? "compact" : "full";
605
+ report.compact = compact;
606
+ report.practical_entrypoint = compact ? "pic agent check --compact" : "pic agent check";
607
+ report.intake_report = intake;
608
+ report.unresolved_obligations = unresolved;
609
+ report.residual_summary = intake.residual_summary;
610
+ report.workflow_usable = true;
611
+ report.accepted = true;
612
+ report.operationally_usable = Boolean(intake.operationally_usable);
613
+ report.settled = false;
614
+ report.reasons = reasons;
615
+ report.safety_invariants = agentSafetyInvariants();
616
+ return compact ? agentCheckCompactPayload(report) : report;
617
+ }
618
+ function agentCheckCompactPayload(report) {
619
+ return {
620
+ report_id: report.report_id,
621
+ profile: report.profile,
622
+ report_mode: "compact",
623
+ accepted: report.accepted,
624
+ workflow_usable: report.workflow_usable,
625
+ operationally_usable: report.operationally_usable,
626
+ settled: false,
627
+ checked_outputs: report.checked_outputs ?? {
628
+ agent_tasks: "present",
629
+ input: "accepted",
630
+ promotion: "diagnostic",
631
+ residual_ledger: "preserved",
632
+ route_requests: "present",
633
+ salience_schedule: "accepted"
634
+ },
635
+ unresolved_obligations: report.unresolved_obligations ?? [],
636
+ residual_summary: report.residual_summary ?? {},
637
+ next_safe_actions: report.next_safe_actions ?? [
638
+ "Inspect unresolved_obligations before reusing the output.",
639
+ "Preserve residual_summary in downstream logs.",
640
+ "Route verifier requests before promoting candidates to reusable work."
641
+ ],
642
+ schema_refs: report.schema_refs ?? [
643
+ "AgentCheckReport",
644
+ "AgentIntakeReport",
645
+ "RuntimeStepReport"
646
+ ],
647
+ runbook_steps: report.runbook_steps ?? agentRunbookSteps(String(report.profile ?? "development")),
648
+ safety_invariants: report.safety_invariants ?? agentSafetyInvariants(),
649
+ reasons: report.reasons ?? []
650
+ };
651
+ }
652
+ function accelerateAgentPhase(request = {}, compact = false) {
653
+ const plan = buildPhaseAccelerationPlan({
654
+ request_id: `agent-accelerate:${request.request_id ?? "agent-intake"}`,
655
+ profile: request.profile ?? "development",
656
+ compact,
657
+ agent_output: request.agent_output,
658
+ allow_live_connectors: request.allow_live_connectors,
659
+ identity_context_path: request.identity_context_path
660
+ });
661
+ return compact ? phaseAccelerationCompactPayload(plan) : plan;
662
+ }
663
+ function agentRunbookSteps(profile = "development") {
664
+ return [
665
+ `pic agent check --compact --profile ${profile}`,
666
+ "Inspect accepted, workflow_usable, operationally_usable, settled.",
667
+ "Inspect residual_summary and unresolved_obligations.",
668
+ "Run verifier routes before packet promotion.",
669
+ "Keep settled=false unless scoped finite obligations are discharged."
670
+ ];
671
+ }
672
+ function buildAgentRunbook(profile = "development") {
673
+ const runbook = clone3(pythonCliFixture("agent_runbook"));
674
+ runbook.profile = profile;
675
+ return runbook;
676
+ }
677
+ function buildAgentAutonomyAudit(profile = "development") {
678
+ const report = clone3(pythonCliFixture("agent_autonomy_audit"));
679
+ report.profile = profile;
680
+ return report;
681
+ }
682
+ function requestFromCli(options) {
683
+ return {
684
+ request_id: typeof options.requestId === "string" ? options.requestId : void 0,
685
+ agent_output: typeof options.text === "string" ? options.text : void 0,
686
+ profile: typeof options.profile === "string" ? options.profile : "development",
687
+ allow_live_connectors: typeof options.allowLiveConnectors === "boolean" ? options.allowLiveConnectors : true,
688
+ identity_context_path: typeof options.identityContext === "string" ? options.identityContext : void 0
689
+ };
690
+ }
691
+ function runtimeOptionsFromCli(options) {
692
+ return {
693
+ profile: typeof options.profile === "string" ? options.profile : "development",
694
+ agentOutput: typeof options.text === "string" ? options.text : void 0,
695
+ allowLiveConnectors: typeof options.allowLiveConnectors === "boolean" ? options.allowLiveConnectors : true,
696
+ statePath: typeof options.state === "string" ? options.state : void 0,
697
+ inputPath: typeof options.input === "string" ? options.input : void 0,
698
+ identityContextPath: typeof options.identityContext === "string" ? options.identityContext : void 0
699
+ };
700
+ }
701
+
702
+ // src/agent/messages.ts
703
+ import { createHash } from "crypto";
704
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
705
+ import { dirname as dirname2 } from "path";
706
+ function sha256(text) {
707
+ return createHash("sha256").update(text, "utf8").digest("hex");
708
+ }
709
+ function sortedUnique(values) {
710
+ return [
711
+ ...new Set(values.filter((value) => Boolean(value)))
712
+ ].sort();
713
+ }
714
+ function acceptedIdentityContext(path) {
715
+ if (!path || !existsSync4(path)) {
716
+ return false;
717
+ }
718
+ try {
719
+ const data = parseJsonObject(
720
+ readFileSync5(path, "utf8"),
721
+ "identity context"
722
+ );
723
+ return runtimeIdentityContextAccepted(data);
724
+ } catch {
725
+ return false;
726
+ }
727
+ }
728
+ function createAgentMessage(options) {
729
+ const digest = sha256(options.text);
730
+ return {
731
+ audience: [],
732
+ content: options.text,
733
+ content_sha256: digest,
734
+ declared_packet_kind: "capability-packet-candidate",
735
+ declared_receiver_family: ["agent", "verifier"],
736
+ declared_routes: [],
737
+ declared_validity_domain: "protocol-relative-finite",
738
+ evidence_refs: [],
739
+ expires_at: null,
740
+ issued_at: null,
741
+ issuer_attestation_id: null,
742
+ issuer_public_key_id: null,
743
+ message_id: `agent-message:${digest.slice(0, 12)}`,
744
+ metadata: {},
745
+ nonce: options.nonce ?? null,
746
+ protocol_version: "pic-agent-message-v1",
747
+ receiver_agent_id: options.receiver ?? null,
748
+ reply_to: null,
749
+ route_request_refs: [],
750
+ sender_agent_id: options.sender,
751
+ signature_ref: null,
752
+ tags: ["agent-message"],
753
+ thread_id: null
754
+ };
755
+ }
756
+ function readAgentMessage(path) {
757
+ const message2 = parseJsonObject(readFileSync5(path, "utf8"), "agent message");
758
+ const validation = validateByType(message2, "AgentMessageEnvelope");
759
+ if (!validation.valid) {
760
+ throw new Error(
761
+ `agent message schema-invalid: ${validation.errors.join("; ")}`
762
+ );
763
+ }
764
+ return message2;
765
+ }
766
+ function agentMessageContract(message2) {
767
+ const content = String(message2.content ?? "");
768
+ const digestValid = sha256(content) === message2.content_sha256;
769
+ const declaredReceiverFamily = Array.isArray(message2.declared_receiver_family) ? message2.declared_receiver_family.map(String) : [];
770
+ const evidenceRefs = Array.isArray(message2.evidence_refs) ? message2.evidence_refs.map(String) : [];
771
+ const routeRefs = Array.isArray(message2.route_request_refs) ? message2.route_request_refs.map(String) : [];
772
+ const reasons = digestValid ? [] : ["message content digest mismatch"];
773
+ return {
774
+ accepted: digestValid,
775
+ candidate_only: true,
776
+ declared_packet_kind: message2.declared_packet_kind ?? "capability-packet-candidate",
777
+ declared_receiver_family: declaredReceiverFamily,
778
+ declared_validity_domain: message2.declared_validity_domain ?? "protocol-relative-finite",
779
+ evidence_refs: evidenceRefs,
780
+ message_contract_valid: digestValid,
781
+ message_id: message2.message_id ?? null,
782
+ protocol_version: message2.protocol_version ?? "pic-agent-message-v1",
783
+ reasons,
784
+ receiver_agent_id: message2.receiver_agent_id ?? null,
785
+ report_id: `agent-message-contract:${sha256(stableStringify(message2)).slice(0, 12)}`,
786
+ residual_ledger: digestValid ? emptyLedger() : residualLedger(
787
+ `agent-message:${String(message2.message_id ?? "unknown")}:digest-mismatch`,
788
+ 1,
789
+ "message content digest mismatch"
790
+ ),
791
+ route_request_refs: routeRefs,
792
+ sender_agent_id: message2.sender_agent_id ?? null,
793
+ settled: false
794
+ };
795
+ }
796
+ function verifyAgentMessage(message2, options = {}) {
797
+ const profile = options.profile ?? "development";
798
+ const contract = agentMessageContract(message2);
799
+ const content = String(message2.content ?? "");
800
+ const digest = String(message2.content_sha256 ?? sha256(content));
801
+ const nonce = typeof message2.nonce === "string" ? message2.nonce : null;
802
+ const replayDetected = Boolean(nonce && options.seenNonces?.includes(nonce));
803
+ const signaturePresent = Boolean(
804
+ message2.signature_ref && message2.issuer_public_key_id && message2.issuer_attestation_id
805
+ );
806
+ const signatureRequired = ["production", "adversarial"].includes(
807
+ profile.toLowerCase()
808
+ );
809
+ const identityRequired = signatureRequired;
810
+ const identityAccepted = acceptedIdentityContext(options.identityContextPath);
811
+ const reasons = [
812
+ ...contract.reasons ?? []
813
+ ];
814
+ const identityReasons = [];
815
+ if (replayDetected) {
816
+ reasons.push("message replay nonce was already seen");
817
+ }
818
+ if (signatureRequired && !signaturePresent) {
819
+ reasons.push("signed agent message required by profile");
820
+ }
821
+ if (identityRequired && !identityAccepted) {
822
+ identityReasons.push("accepted identity context required by profile");
823
+ }
824
+ reasons.push(...identityReasons);
825
+ const accepted = contract.accepted === true && reasons.length === 0;
826
+ const packetId = `packet:agent-message:${String(message2.message_id ?? "unknown")}`;
827
+ const packets = contract.accepted === true ? [
828
+ {
829
+ authority_granted: false,
830
+ authority_requested: false,
831
+ authority_required: false,
832
+ claim: content,
833
+ content_sha256: digest,
834
+ dependencies: [],
835
+ evidence_hash_valid: true,
836
+ evidence_refs: sortedUnique([
837
+ ...Array.isArray(message2.evidence_refs) ? message2.evidence_refs.map(String) : [],
838
+ `sha256:${digest}`,
839
+ `agent-message:${String(message2.message_id ?? "unknown")}`
840
+ ]),
841
+ expected_downstream_gain: 125e-5,
842
+ expires_at: null,
843
+ freshness: 1,
844
+ hazard_charge: 0,
845
+ identity_contribution_status: "provisional",
846
+ issuer_agent_id: message2.sender_agent_id ?? null,
847
+ issuer_attestation_id: message2.issuer_attestation_id ?? null,
848
+ issuer_public_key_id: message2.issuer_public_key_id ?? null,
849
+ issuer_signature_ref: message2.signature_ref ?? null,
850
+ packet_id: packetId,
851
+ receiver_family: Array.isArray(message2.declared_receiver_family) ? message2.declared_receiver_family.map(String) : ["agent", "verifier"],
852
+ residual_charge: 0,
853
+ reuse_context: "general",
854
+ rollback_available: true,
855
+ route_safe: true,
856
+ salience_class: "packet",
857
+ source_kind: "agent-message",
858
+ source_ref: String(message2.message_id ?? "unknown"),
859
+ status: "provisional",
860
+ tags: sortedUnique([
861
+ ...Array.isArray(message2.tags) ? message2.tags.map(String) : [],
862
+ "agent-message",
863
+ "external-candidate",
864
+ "general"
865
+ ]),
866
+ verification_cost: 5e-3,
867
+ verifier_routes: Array.isArray(message2.declared_routes) ? message2.declared_routes.map(String) : []
868
+ }
869
+ ] : [];
870
+ return {
871
+ accepted,
872
+ candidate_packet_ids: packets.map((packet2) => packet2.packet_id),
873
+ consumed_nonces: accepted && nonce ? [nonce] : [],
874
+ identity_reasons: sortedUnique(identityReasons),
875
+ identity_status: identityAccepted ? "verified" : identityRequired ? "required" : "not-required",
876
+ identity_verified: identityAccepted,
877
+ message_contract_valid: contract.accepted === true,
878
+ message_id: message2.message_id ?? null,
879
+ next_safe_commands: [
880
+ "uv run pic agent message contract --message <message.json>",
881
+ "uv run pic ecology bridge-runtime --report <general-intake-report.json>"
882
+ ],
883
+ nonce_ledger: {
884
+ accepted,
885
+ consumed_nonces: accepted && nonce ? [nonce] : [],
886
+ ledger_id: "agent-message-nonce-ledger",
887
+ reasons: sortedUnique(reasons),
888
+ rejected_message_ids: accepted ? [] : [String(message2.message_id ?? "unknown")],
889
+ replayed_nonces: replayDetected && nonce ? [nonce] : []
890
+ },
891
+ nonce_status: replayDetected ? "replayed" : nonce && accepted ? "consumed" : "not-provided",
892
+ packets,
893
+ quarantine_recommended: reasons.length > 0,
894
+ reasons: sortedUnique(reasons),
895
+ replay_detected: replayDetected,
896
+ report_id: `agent-message-check:${String(message2.message_id ?? "unknown")}`,
897
+ residual_ledger: reasons.length === 0 ? emptyLedger() : residualLedger(
898
+ `agent-message:${String(message2.message_id ?? "unknown")}:verification-residual`,
899
+ reasons.length,
900
+ "agent message verification residual"
901
+ ),
902
+ sender_agent_id: message2.sender_agent_id ?? null,
903
+ settled: false,
904
+ signature_present: signaturePresent,
905
+ signature_required: signatureRequired
906
+ };
907
+ }
908
+ function initAgentInbox(path, inboxId = "agent-inbox") {
909
+ const record = {
910
+ inbox_id: inboxId,
911
+ messages: [],
912
+ peers: [],
913
+ seen_nonces: []
914
+ };
915
+ mkdirSync2(dirname2(path), { recursive: true });
916
+ writeFileSync2(path, stableStringify(record), "utf8");
917
+ return record;
918
+ }
919
+ function readAgentInbox(path) {
920
+ const text = readFileSync5(path, "utf8").trim();
921
+ if (text.includes("\n") && !text.startsWith("{")) {
922
+ return {
923
+ inbox_id: "agent-inbox",
924
+ messages: text.split(/\r?\n/).filter(Boolean).map((line) => parseJsonObject(line, "agent inbox line")),
925
+ peers: [],
926
+ seen_nonces: []
927
+ };
928
+ }
929
+ const inbox2 = parseJsonObject(text, "agent inbox");
930
+ const validation = validateByType(inbox2, "AgentInboxRecord");
931
+ if (!validation.valid) {
932
+ throw new Error(
933
+ `agent inbox schema-invalid: ${validation.errors.join("; ")}`
934
+ );
935
+ }
936
+ return inbox2;
937
+ }
938
+ function writeAgentInbox(path, inbox2) {
939
+ mkdirSync2(dirname2(path), { recursive: true });
940
+ writeFileSync2(path, stableStringify(inbox2), "utf8");
941
+ }
942
+ function appendAgentMessage(inboxPath, message2) {
943
+ const inbox2 = existsSync4(inboxPath) ? readAgentInbox(inboxPath) : { inbox_id: "agent-inbox", messages: [], peers: [], seen_nonces: [] };
944
+ const messages = Array.isArray(inbox2.messages) ? inbox2.messages : [];
945
+ const updated = {
946
+ ...inbox2,
947
+ messages: [...messages, message2]
948
+ };
949
+ writeAgentInbox(inboxPath, updated);
950
+ return updated;
951
+ }
952
+ function deliveryReport(action, inboxRef, inbox2, reports, profile = "development") {
953
+ const accepted = reports.every((report) => report.accepted === true);
954
+ const delivered = accepted ? reports.map((report) => String(report.message_id ?? "unknown")) : [];
955
+ const rejected = accepted ? [] : reports.map((report) => String(report.message_id ?? "unknown"));
956
+ const consumed = sortedUnique(
957
+ reports.flatMap(
958
+ (report) => Array.isArray(report.consumed_nonces) ? report.consumed_nonces.map(String) : []
959
+ )
960
+ );
961
+ const reasons = sortedUnique(
962
+ reports.flatMap(
963
+ (report) => Array.isArray(report.reasons) ? report.reasons.map(String) : []
964
+ )
965
+ );
966
+ return {
967
+ accepted,
968
+ action,
969
+ candidate_only: true,
970
+ candidate_packet_ids: sortedUnique(
971
+ reports.flatMap(
972
+ (report) => Array.isArray(report.candidate_packet_ids) ? report.candidate_packet_ids.map(String) : []
973
+ )
974
+ ),
975
+ delivered_message_ids: delivered,
976
+ exchange_reports: reports,
977
+ identity_context_accepted: false,
978
+ inbox_id: inbox2.inbox_id ?? "agent-inbox",
979
+ inbox_ref: inboxRef,
980
+ message_ids: reports.map(
981
+ (report) => String(report.message_id ?? "unknown")
982
+ ),
983
+ next_safe_commands: [
984
+ "uv run pic agent inbox verify --inbox <inbox.json>",
985
+ "uv run pic ecology bridge-runtime --report <general-intake-report.json>"
986
+ ],
987
+ nonce_ledger: {
988
+ accepted,
989
+ consumed_nonces: consumed,
990
+ ledger_id: "agent-message-nonce-ledger",
991
+ reasons,
992
+ rejected_message_ids: rejected,
993
+ replayed_nonces: []
994
+ },
995
+ operationally_usable: accepted,
996
+ profile,
997
+ reasons,
998
+ rejected_message_ids: rejected,
999
+ report_id: `agent-message-delivery:${action}:${String(inbox2.inbox_id ?? "agent-inbox")}`,
1000
+ settled: false
1001
+ };
1002
+ }
1003
+ function receiveAgentInbox(inboxPath, options = {}) {
1004
+ const inbox2 = readAgentInbox(inboxPath);
1005
+ const seen = Array.isArray(inbox2.seen_nonces) ? inbox2.seen_nonces.map(String) : [];
1006
+ const messages = Array.isArray(inbox2.messages) ? inbox2.messages : [];
1007
+ const reports = messages.map(
1008
+ (message2) => verifyAgentMessage(message2, { ...options, seenNonces: seen })
1009
+ );
1010
+ return deliveryReport(
1011
+ "receive",
1012
+ inboxPath,
1013
+ inbox2,
1014
+ reports,
1015
+ options.profile ?? "development"
1016
+ );
1017
+ }
1018
+
1019
+ // src/ecology/index.ts
1020
+ import { createHash as createHash2 } from "crypto";
1021
+ function packetFromText(text, outputId = "agent-output") {
1022
+ const sha2563 = createHash2("sha256").update(text, "utf8").digest("hex");
1023
+ return {
1024
+ packet_id: `candidate:${outputId}`,
1025
+ source_kind: "agent-output",
1026
+ content_sha256: sha2563,
1027
+ candidate_only: true,
1028
+ accepted: true,
1029
+ workflow_usable: true,
1030
+ settled: false,
1031
+ reasons: ["candidate packet requires verifier routes before promotion"]
1032
+ };
1033
+ }
1034
+ function ecologyPolicy(profile = "controlled_web") {
1035
+ return {
1036
+ profile,
1037
+ explicit_source_required: true,
1038
+ candidate_only_by_default: true,
1039
+ background_crawling_allowed: false,
1040
+ arbitrary_execution_allowed: false,
1041
+ accepted: true,
1042
+ operationally_usable: profile !== "production_network",
1043
+ settled: false
1044
+ };
1045
+ }
1046
+
1047
+ // src/io/portability.ts
1048
+ import { createHash as createHash3 } from "crypto";
1049
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1050
+ import { dirname as dirname3, isAbsolute, normalize as normalize2, resolve as resolve2, sep as sep2 } from "path";
1051
+ function normalizedSha256(text) {
1052
+ return createHash3("sha256").update(lfNormalize(text), "utf8").digest("hex");
1053
+ }
1054
+ function stableCompactJson(value) {
1055
+ if (Array.isArray(value)) {
1056
+ return `[${value.map((item) => stableCompactJson(item)).join(",")}]`;
1057
+ }
1058
+ if (value && typeof value === "object") {
1059
+ const input = value;
1060
+ return `{${Object.keys(input).sort().map((key) => `${JSON.stringify(key)}:${stableCompactJson(input[key])}`).join(",")}}`;
1061
+ }
1062
+ return JSON.stringify(value);
1063
+ }
1064
+ function safeManifestTarget(base, file) {
1065
+ if (!file || isAbsolute(file)) {
1066
+ return null;
1067
+ }
1068
+ const normalized = normalize2(file);
1069
+ if (normalized.split(/[\\/]+/).includes("..")) {
1070
+ return null;
1071
+ }
1072
+ const baseResolved = resolve2(base);
1073
+ const target = resolve2(baseResolved, normalized);
1074
+ if (target !== baseResolved && !target.startsWith(`${baseResolved}${sep2}`)) {
1075
+ return null;
1076
+ }
1077
+ return target;
1078
+ }
1079
+ function verifyPortabilityManifest(manifestPath) {
1080
+ const manifest = parseJsonObject(
1081
+ readFileSync6(manifestPath, "utf8"),
1082
+ "portability manifest"
1083
+ );
1084
+ const base = dirname3(manifestPath);
1085
+ const knownSchemas = new Set(schemaNames());
1086
+ const checkedExamples = {};
1087
+ const checkedNegativeExamples = {};
1088
+ const checkedSchemas = {};
1089
+ const sha = {};
1090
+ const reasons = [];
1091
+ let unexpectedFailureCount = 0;
1092
+ let expectedFailureCount = 0;
1093
+ if (!Array.isArray(manifest.examples)) {
1094
+ reasons.push("manifest examples must be a list");
1095
+ }
1096
+ if (!Array.isArray(manifest.negative_examples)) {
1097
+ reasons.push("manifest negative_examples must be a list");
1098
+ }
1099
+ for (const entry of Array.isArray(manifest.examples) ? manifest.examples : []) {
1100
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1101
+ reasons.push("manifest example entry must be an object");
1102
+ continue;
1103
+ }
1104
+ const example = entry;
1105
+ const file = String(example.file ?? "");
1106
+ const schema = String(example.schema ?? "");
1107
+ const expectedSha = example.sha256 ? String(example.sha256) : "";
1108
+ if (typeof example.file !== "string" || typeof example.schema !== "string") {
1109
+ reasons.push("manifest example entries require string file and schema");
1110
+ continue;
1111
+ }
1112
+ checkedSchemas[file] = schema;
1113
+ const path = safeManifestTarget(base, file);
1114
+ if (path === null) {
1115
+ checkedExamples[file] = "unsafe-path";
1116
+ reasons.push(`${file}: example path is outside manifest directory`);
1117
+ unexpectedFailureCount += 1;
1118
+ continue;
1119
+ }
1120
+ if (!existsSync5(path)) {
1121
+ checkedExamples[file] = "missing";
1122
+ reasons.push(`${file}: example file is missing`);
1123
+ unexpectedFailureCount += 1;
1124
+ continue;
1125
+ }
1126
+ if (!knownSchemas.has(schema)) {
1127
+ checkedExamples[file] = "unknown-schema";
1128
+ reasons.push(`${schema} is not a known schema`);
1129
+ unexpectedFailureCount += 1;
1130
+ continue;
1131
+ }
1132
+ const text = readFileSync6(path, "utf8");
1133
+ const digest = normalizedSha256(text);
1134
+ sha[file] = digest;
1135
+ if (expectedSha && digest !== expectedSha) {
1136
+ checkedExamples[file] = "sha256-mismatch";
1137
+ reasons.push(`${file}: sha256 does not match manifest`);
1138
+ unexpectedFailureCount += 1;
1139
+ continue;
1140
+ }
1141
+ const data = parseJsonObject(text, file);
1142
+ const validation = validateByType(data, schema);
1143
+ checkedExamples[file] = validation.valid ? "valid" : "schema-invalid";
1144
+ if (!validation.valid) {
1145
+ unexpectedFailureCount += 1;
1146
+ reasons.push(...validation.errors.map((error) => `${file}: ${error}`));
1147
+ }
1148
+ }
1149
+ for (const entry of Array.isArray(manifest.negative_examples) ? manifest.negative_examples : []) {
1150
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1151
+ reasons.push("manifest negative example entry must be an object");
1152
+ unexpectedFailureCount += 1;
1153
+ continue;
1154
+ }
1155
+ const example = entry;
1156
+ const file = String(example.file ?? "");
1157
+ const schema = String(example.schema ?? "");
1158
+ const expectedStatus = String(example.expected_status ?? "schema-invalid");
1159
+ if (typeof example.file !== "string" || typeof example.schema !== "string" || typeof example.expected_status !== "string") {
1160
+ reasons.push(
1161
+ "manifest negative example entries require string file, schema, and expected_status"
1162
+ );
1163
+ unexpectedFailureCount += 1;
1164
+ continue;
1165
+ }
1166
+ checkedSchemas[file] = schema;
1167
+ const path = safeManifestTarget(base, file);
1168
+ let status;
1169
+ if (path === null) {
1170
+ status = "unsafe-path";
1171
+ } else if (!existsSync5(path)) {
1172
+ status = "missing";
1173
+ } else if (!knownSchemas.has(schema)) {
1174
+ status = "unknown-schema";
1175
+ } else {
1176
+ const text = readFileSync6(path, "utf8");
1177
+ if (example.sha256 && normalizedSha256(text) !== String(example.sha256)) {
1178
+ status = "sha256-mismatch";
1179
+ } else {
1180
+ try {
1181
+ const data = parseJsonObject(text, file);
1182
+ status = validateByType(data, schema).valid ? "valid" : "schema-invalid";
1183
+ } catch {
1184
+ status = "schema-invalid";
1185
+ }
1186
+ }
1187
+ }
1188
+ checkedNegativeExamples[file] = status;
1189
+ if (status === expectedStatus && status !== "valid") {
1190
+ expectedFailureCount += 1;
1191
+ } else {
1192
+ unexpectedFailureCount += 1;
1193
+ reasons.push(`${file} expected ${expectedStatus} but got ${status}`);
1194
+ }
1195
+ }
1196
+ const schemaDigestInput = {
1197
+ public_schema_count: schemaNames().length,
1198
+ schema_names: Object.fromEntries(Object.entries(checkedSchemas).sort())
1199
+ };
1200
+ const schemaDigest = createHash3("sha256").update(stableCompactJson(schemaDigestInput), "utf8").digest("hex");
1201
+ const uniqueReasons = [...new Set(reasons)].sort();
1202
+ const accepted = Object.keys(checkedExamples).length > 0 && uniqueReasons.length === 0 && Object.values(checkedExamples).every((status) => status === "valid");
1203
+ return {
1204
+ report_id: "pic-portability-conformance",
1205
+ manifest_path: manifestPath,
1206
+ checked_examples: checkedExamples,
1207
+ checked_negative_examples: checkedNegativeExamples,
1208
+ schema_names: checkedSchemas,
1209
+ sha256: sha,
1210
+ schema_digest: schemaDigest,
1211
+ positive_example_count: Object.keys(checkedExamples).length,
1212
+ negative_example_count: Object.keys(checkedNegativeExamples).length,
1213
+ expected_failure_count: expectedFailureCount,
1214
+ unexpected_failure_count: unexpectedFailureCount,
1215
+ semantic_invariants: Array.isArray(manifest.invariants) ? manifest.invariants.map(String) : [],
1216
+ accepted,
1217
+ operationally_usable: accepted,
1218
+ settled: false,
1219
+ reasons: uniqueReasons
1220
+ };
1221
+ }
1222
+
1223
+ // src/packet/index.ts
1224
+ import { createHash as createHash4 } from "crypto";
1225
+ import { readFileSync as readFileSync7 } from "fs";
1226
+ var COMMAND_MARKERS = [
1227
+ "cmd.exe",
1228
+ "powershell",
1229
+ "bash ",
1230
+ "sh ",
1231
+ "wsl ",
1232
+ "git ",
1233
+ "pip install",
1234
+ "python -m pip",
1235
+ "uv run",
1236
+ "rm -rf",
1237
+ "curl ",
1238
+ "wget "
1239
+ ];
1240
+ function sha2562(text) {
1241
+ return createHash4("sha256").update(text, "utf8").digest("hex");
1242
+ }
1243
+ function stableDigest(data) {
1244
+ return sha2562(JSON.stringify(sortJson(data)));
1245
+ }
1246
+ function sortedUnique2(values) {
1247
+ return [
1248
+ ...new Set(values.filter((value) => Boolean(value)))
1249
+ ].sort();
1250
+ }
1251
+ function commandLikeStrings(data) {
1252
+ if (typeof data === "string") {
1253
+ const lower = data.toLowerCase();
1254
+ return COMMAND_MARKERS.some((marker) => lower.includes(marker)) ? [data] : [];
1255
+ }
1256
+ if (Array.isArray(data)) {
1257
+ return data.flatMap((item) => commandLikeStrings(item));
1258
+ }
1259
+ if (data && typeof data === "object") {
1260
+ return Object.values(data).flatMap((value) => commandLikeStrings(value));
1261
+ }
1262
+ return [];
1263
+ }
1264
+ function readTypedJson(path, schema) {
1265
+ const data = parseJsonObject(readFileSync7(path, "utf8"), schema);
1266
+ const validation = validateByType(data, schema);
1267
+ if (!validation.valid) {
1268
+ throw new Error(
1269
+ `${schema} schema-invalid: ${validation.errors.join("; ")}`
1270
+ );
1271
+ }
1272
+ return data;
1273
+ }
1274
+ function residualCarryForward(reportId, residualSummary, missingObligations, candidateOnlyReasons, settledBlockers, accepted) {
1275
+ return {
1276
+ accepted,
1277
+ candidate_only_reasons: candidateOnlyReasons,
1278
+ missing_obligations: missingObligations,
1279
+ reasons: ["residuals and blockers are preserved during packet export"],
1280
+ report_id: reportId,
1281
+ residual_summary: residualSummary,
1282
+ settled: false,
1283
+ settled_blockers: settledBlockers
1284
+ };
1285
+ }
1286
+ function packetEnvelopeFromRuntimeReport(report) {
1287
+ const digest = stableDigest(report);
1288
+ const missing = Array.isArray(report.missing_obligations) ? report.missing_obligations.map(String) : [];
1289
+ const residualSummary = summarizeLedger(report.residual_ledger);
1290
+ const candidateOnlyReasons = [
1291
+ "runtime report is exported as diagnostic packet-exchange data",
1292
+ "packet exchange does not route promotion checks"
1293
+ ];
1294
+ const settledBlockers = sortedUnique2([
1295
+ "packet exchange is sidecar-only and cannot settle claims",
1296
+ report.settled === true ? null : "source runtime report settled=false",
1297
+ ...missing
1298
+ ]);
1299
+ const reportId = String(report.report_id ?? "runtime-report");
1300
+ return {
1301
+ accepted: report.accepted === true,
1302
+ candidate_only_reasons: candidateOnlyReasons,
1303
+ content: report,
1304
+ content_digest: digest,
1305
+ created_timestamp: "not-recorded",
1306
+ identity_context_summary: {
1307
+ accepted_agent_context_present: false,
1308
+ accepted_public_key_context_present: false
1309
+ },
1310
+ issuer_agent_id: null,
1311
+ issuer_public_key_id: null,
1312
+ lineage_parents: [reportId],
1313
+ missing_obligations: missing,
1314
+ packet_id: `packet-exchange:${reportId}:${digest.slice(0, 12)}`,
1315
+ provenance_summary: {
1316
+ source_report_id: reportId,
1317
+ state_id: String(report.state_id ?? ""),
1318
+ input_id: String(report.input_id ?? "")
1319
+ },
1320
+ reasons: ["exported packet is diagnostic data and is not promoted"],
1321
+ residual_carry_forward: residualCarryForward(
1322
+ `residual-carry-forward:${reportId}`,
1323
+ residualSummary,
1324
+ missing,
1325
+ candidateOnlyReasons,
1326
+ settledBlockers,
1327
+ report.accepted === true
1328
+ ),
1329
+ residual_ledger_summary: residualSummary,
1330
+ safety_invariants: [
1331
+ "packet exchange treats content as inert data",
1332
+ "packet exchange does not execute embedded commands",
1333
+ "packet exchange does not promote packets to settled"
1334
+ ],
1335
+ schema_version: "pic-packet-exchange-v1",
1336
+ settled: false,
1337
+ settled_blockers: settledBlockers,
1338
+ source_kind: "runtime-report",
1339
+ workflow_usable: report.accepted === true
1340
+ };
1341
+ }
1342
+ function packetEnvelopeFromPath(path) {
1343
+ return packetEnvelopeFromRuntimeReport(
1344
+ readTypedJson(path, "RuntimeStepReport")
1345
+ );
1346
+ }
1347
+ function readPacketEnvelope(path) {
1348
+ return readTypedJson(path, "PacketExchangeEnvelope");
1349
+ }
1350
+ function readPacketOrMerge(path) {
1351
+ const data = parseJsonObject(
1352
+ readFileSync7(path, "utf8"),
1353
+ "packet or merge report"
1354
+ );
1355
+ if (Array.isArray(data.packets)) {
1356
+ const validation2 = validateByType(data, "PacketMergeReport");
1357
+ if (!validation2.valid) {
1358
+ throw new Error(
1359
+ `PacketMergeReport schema-invalid: ${validation2.errors.join("; ")}`
1360
+ );
1361
+ }
1362
+ return data;
1363
+ }
1364
+ const validation = validateByType(data, "PacketExchangeEnvelope");
1365
+ if (!validation.valid) {
1366
+ throw new Error(
1367
+ `PacketExchangeEnvelope schema-invalid: ${validation.errors.join("; ")}`
1368
+ );
1369
+ }
1370
+ return data;
1371
+ }
1372
+ function inspectPacketEnvelope(envelope) {
1373
+ return {
1374
+ accepted: envelope.accepted === true,
1375
+ candidate_only: true,
1376
+ content_digest: String(envelope.content_digest ?? ""),
1377
+ content_treated_as_data: true,
1378
+ embedded_command_like_values: sortedUnique2(commandLikeStrings(envelope)),
1379
+ executed_command_count: 0,
1380
+ packet_id: String(envelope.packet_id ?? ""),
1381
+ reasons: [
1382
+ "packet content was inspected as inert data",
1383
+ "embedded command-like strings are not execution authority"
1384
+ ],
1385
+ report_id: `packet-inspection:${String(envelope.packet_id ?? "")}`,
1386
+ settled: false,
1387
+ workflow_usable: envelope.workflow_usable === true
1388
+ };
1389
+ }
1390
+ function mergePacketEnvelopes(envelopes) {
1391
+ const byDigest = /* @__PURE__ */ new Map();
1392
+ const duplicateIds = [];
1393
+ const duplicateDigests = [];
1394
+ const residualSummary = {};
1395
+ const missing = [];
1396
+ const candidateOnly = [];
1397
+ const blockers = [];
1398
+ for (const envelope of envelopes) {
1399
+ const digest = String(envelope.content_digest ?? "");
1400
+ if (byDigest.has(digest)) {
1401
+ duplicateIds.push(String(envelope.packet_id ?? ""));
1402
+ duplicateDigests.push(digest);
1403
+ } else {
1404
+ byDigest.set(digest, envelope);
1405
+ }
1406
+ for (const [key, value] of Object.entries(
1407
+ envelope.residual_ledger_summary ?? {}
1408
+ )) {
1409
+ residualSummary[key] = (residualSummary[key] ?? 0) + Number(value);
1410
+ }
1411
+ if (Array.isArray(envelope.missing_obligations)) {
1412
+ missing.push(...envelope.missing_obligations.map(String));
1413
+ }
1414
+ if (Array.isArray(envelope.candidate_only_reasons)) {
1415
+ candidateOnly.push(...envelope.candidate_only_reasons.map(String));
1416
+ }
1417
+ if (Array.isArray(envelope.settled_blockers)) {
1418
+ blockers.push(...envelope.settled_blockers.map(String));
1419
+ }
1420
+ }
1421
+ const packets = [...byDigest.values()];
1422
+ return {
1423
+ accepted: packets.length > 0 && packets.every((packet2) => packet2.accepted === true),
1424
+ candidate_only_preserved: packets.every(
1425
+ (packet2) => packet2.settled !== true
1426
+ ),
1427
+ duplicate_content_digests: sortedUnique2(duplicateDigests),
1428
+ duplicate_packet_ids: sortedUnique2(duplicateIds),
1429
+ input_packet_count: envelopes.length,
1430
+ merged_packet_count: packets.length,
1431
+ packets,
1432
+ reasons: ["packet merge is diagnostic-only and does not promote packets"],
1433
+ report_id: "packet-merge-report",
1434
+ residual_carry_forward: residualCarryForward(
1435
+ "residual-carry-forward:packet-merge",
1436
+ Object.fromEntries(Object.entries(residualSummary).sort()),
1437
+ sortedUnique2(missing),
1438
+ sortedUnique2(candidateOnly),
1439
+ sortedUnique2(blockers),
1440
+ packets.length > 0 && packets.every((packet2) => packet2.accepted === true)
1441
+ ),
1442
+ settled: false,
1443
+ workflow_usable: packets.some((packet2) => packet2.workflow_usable === true)
1444
+ };
1445
+ }
1446
+ function packetLineageDigest(packetOrMerge) {
1447
+ const packets = Array.isArray(packetOrMerge.packets) ? packetOrMerge.packets : [packetOrMerge];
1448
+ const residualSummary = {};
1449
+ for (const packet2 of packets) {
1450
+ for (const [key, value] of Object.entries(
1451
+ packet2.residual_ledger_summary ?? {}
1452
+ )) {
1453
+ residualSummary[key] = (residualSummary[key] ?? 0) + Number(value);
1454
+ }
1455
+ }
1456
+ return {
1457
+ accepted: packets.length > 0 && packets.every((packet2) => packet2.accepted === true),
1458
+ candidate_only: true,
1459
+ content_digests: packets.map(
1460
+ (packet2) => String(packet2.content_digest ?? "")
1461
+ ),
1462
+ lineage_id: "packet-lineage-digest",
1463
+ packet_ids: packets.map((packet2) => String(packet2.packet_id ?? "")),
1464
+ parent_edges: Object.fromEntries(
1465
+ packets.map((packet2) => [
1466
+ String(packet2.packet_id ?? ""),
1467
+ Array.isArray(packet2.lineage_parents) ? packet2.lineage_parents.map(String) : []
1468
+ ])
1469
+ ),
1470
+ reasons: [
1471
+ "lineage digest is diagnostic-only and preserves candidate status"
1472
+ ],
1473
+ residual_summary: Object.fromEntries(
1474
+ Object.entries(residualSummary).sort()
1475
+ ),
1476
+ settled: false,
1477
+ workflow_usable: packets.some((packet2) => packet2.workflow_usable === true)
1478
+ };
1479
+ }
1480
+
1481
+ // src/sqot/index.ts
1482
+ function buildSalienceSchedule(profile = "production") {
1483
+ const report = structuredClone(fixtureJson("salience_schedule_report.json"));
1484
+ report.profile = profile;
1485
+ report.accepted = true;
1486
+ report.operationally_usable = true;
1487
+ report.settled = false;
1488
+ return report;
1489
+ }
1490
+
1491
+ // src/trc/index.ts
1492
+ import { readFileSync as readFileSync8 } from "fs";
1493
+ function compileTrc(options = {}) {
1494
+ let records = [];
1495
+ const reasons = [];
1496
+ if (options.recordsPath) {
1497
+ const parsed = JSON.parse(
1498
+ readFileSync8(options.recordsPath, "utf8")
1499
+ );
1500
+ records = Array.isArray(parsed) ? parsed : Array.isArray(parsed.records) ? parsed.records : [];
1501
+ }
1502
+ const invalidMainTrace = records.some((record) => {
1503
+ const obj = record;
1504
+ return obj.stratum === "main" && !obj.trace_id && !obj.trace;
1505
+ });
1506
+ if (invalidMainTrace) {
1507
+ reasons.push(
1508
+ "main frontier record lacks accepted executable trace normal form"
1509
+ );
1510
+ }
1511
+ const accepted = !invalidMainTrace;
1512
+ return {
1513
+ result_id: "trc-compile-result",
1514
+ accepted,
1515
+ operationally_usable: accepted && !invalidMainTrace,
1516
+ settled: false,
1517
+ main_frontier_count: invalidMainTrace ? 0 : records.length,
1518
+ diagnostic_count: invalidMainTrace ? 1 : 0,
1519
+ residual_ledger: invalidMainTrace ? {
1520
+ coordinates: {
1521
+ "trc:trace-normal-form": {
1522
+ name: "trc:trace-normal-form",
1523
+ value: 1,
1524
+ unit: "dimensionless",
1525
+ kind: "residual",
1526
+ description: "main-frontier records require executable trace normal forms"
1527
+ }
1528
+ }
1529
+ } : { coordinates: {} },
1530
+ reasons
1531
+ };
1532
+ }
1533
+
1534
+ // src/cli/main.ts
1535
+ var VERSION = "0.4.4";
1536
+ function outputJson(data, output) {
1537
+ const text = stableStringify(data);
1538
+ if (output) {
1539
+ mkdirSync3(dirname4(output), { recursive: true });
1540
+ writeFileSync3(output, text, "utf8");
1541
+ } else {
1542
+ process.stdout.write(text);
1543
+ }
1544
+ }
1545
+ function readText(options, fallback = "Candidate packet: preserve residuals.") {
1546
+ if (typeof options.text === "string" && typeof options.textFile === "string") {
1547
+ throw new Error("Use either --text or --text-file, not both");
1548
+ }
1549
+ if (typeof options.text === "string") {
1550
+ return options.text;
1551
+ }
1552
+ if (typeof options.textFile === "string") {
1553
+ return readFileSync9(options.textFile, "utf8");
1554
+ }
1555
+ return fallback;
1556
+ }
1557
+ function readRequiredText(options) {
1558
+ if (typeof options.text !== "string" && typeof options.textFile !== "string") {
1559
+ throw new Error("message content requires --text or --text-file");
1560
+ }
1561
+ return readText(options, "");
1562
+ }
1563
+ function optionalText(options) {
1564
+ if (typeof options.text === "string" || typeof options.textFile === "string") {
1565
+ return readText(options, "");
1566
+ }
1567
+ return void 0;
1568
+ }
1569
+ function diagnostic(command, extra = {}) {
1570
+ return {
1571
+ command,
1572
+ accepted: true,
1573
+ workflow_usable: true,
1574
+ operationally_usable: false,
1575
+ execution_authority_granted: false,
1576
+ settled: false,
1577
+ residual_ledger: {
1578
+ coordinates: {
1579
+ [`${command}:external-obligation`]: {
1580
+ name: `${command}:external-obligation`,
1581
+ value: 1,
1582
+ unit: "dimensionless",
1583
+ kind: "residual",
1584
+ description: "TypeScript port preserves the public boundary and returns diagnostic residuals for unsupported heavy routes"
1585
+ }
1586
+ }
1587
+ },
1588
+ missing_obligations: [`${command}:finite-verifier-route`],
1589
+ reasons: [
1590
+ "diagnostic-only route; no execution authority granted",
1591
+ "settled remains false"
1592
+ ],
1593
+ ...extra
1594
+ };
1595
+ }
1596
+ function recordList(value) {
1597
+ if (!Array.isArray(value)) {
1598
+ return [];
1599
+ }
1600
+ return value.filter(
1601
+ (item) => Boolean(item) && typeof item === "object" && !Array.isArray(item)
1602
+ );
1603
+ }
1604
+ function optionalRecord(value) {
1605
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1606
+ return value;
1607
+ }
1608
+ return void 0;
1609
+ }
1610
+ function optionalString(value) {
1611
+ return typeof value === "string" ? value : void 0;
1612
+ }
1613
+ function boolOptionOrRequest(optionValue, requestValue) {
1614
+ if (optionValue === false) {
1615
+ return false;
1616
+ }
1617
+ if (typeof requestValue === "boolean") {
1618
+ return requestValue;
1619
+ }
1620
+ return typeof optionValue === "boolean" ? optionValue : void 0;
1621
+ }
1622
+ function readPhaseRequest(path) {
1623
+ return parseJsonObject(readFileSync9(path, "utf8"), "phase request");
1624
+ }
1625
+ function phaseRequestFromCli(options) {
1626
+ if (typeof options.request === "string") {
1627
+ const request = readPhaseRequest(options.request);
1628
+ return {
1629
+ request_id: String(request.request_id ?? "phase-cli"),
1630
+ profile: String(request.profile ?? options.profile ?? "development"),
1631
+ compact: Boolean(options.compact) && !options.full,
1632
+ agent_output: optionalString(request.agent_output),
1633
+ allow_live_connectors: boolOptionOrRequest(
1634
+ options.allowLiveConnectors,
1635
+ request.allow_live_connectors
1636
+ ),
1637
+ identity_context_path: optionalString(request.identity_context_path),
1638
+ general_intake_bridge_reports: recordList(
1639
+ request.general_intake_bridge_reports
1640
+ ),
1641
+ alt_admission_decisions: recordList(request.alt_admission_decisions),
1642
+ runtime_report: optionalRecord(request.runtime_report)
1643
+ };
1644
+ }
1645
+ const runtimeReport = typeof options.runtimeReport === "string" ? parseJsonObject(
1646
+ readFileSync9(options.runtimeReport, "utf8"),
1647
+ "runtime report"
1648
+ ) : void 0;
1649
+ return {
1650
+ request_id: "phase-cli",
1651
+ profile: String(options.profile ?? "development"),
1652
+ compact: Boolean(options.compact) && !options.full,
1653
+ agent_output: optionalText(options),
1654
+ allow_live_connectors: options.allowLiveConnectors,
1655
+ identity_context_path: optionalString(options.identityContext),
1656
+ runtime_report: runtimeReport
1657
+ };
1658
+ }
1659
+ function assertPhaseRequestExclusive(options) {
1660
+ const otherInputs = [
1661
+ options.runtimeReport,
1662
+ options.state,
1663
+ options.input,
1664
+ options.text,
1665
+ options.textFile,
1666
+ options.identityContext
1667
+ ].filter(Boolean);
1668
+ if (options.request && otherInputs.length > 0) {
1669
+ throw new Error(
1670
+ "--request cannot be combined with runtime/text/state inputs"
1671
+ );
1672
+ }
1673
+ }
1674
+ function addOutputOptions(command) {
1675
+ return command.option(
1676
+ "--output <path>",
1677
+ "write JSON to path instead of stdout"
1678
+ );
1679
+ }
1680
+ function addProfile(command) {
1681
+ return command.option(
1682
+ "--profile <profile>",
1683
+ "runtime profile",
1684
+ "development"
1685
+ );
1686
+ }
1687
+ function addTextOptions(command) {
1688
+ return command.option("--text <text>", "literal agent output").option("--text-file <path>", "read agent output from file");
1689
+ }
1690
+ var program = new Command();
1691
+ program.name("pic").description(
1692
+ "TypeScript port of percolation-inversion-compiler v0.4.4 public CLI contracts."
1693
+ ).version(VERSION);
1694
+ program.exitOverride();
1695
+ addOutputOptions(
1696
+ addProfile(
1697
+ program.command("doctor").description("Run operational readiness checks.")
1698
+ )
1699
+ ).option("--fail-on <mode>", "fail mode", "never").action(
1700
+ (options) => outputJson(
1701
+ options.profile === "development" || options.profile === void 0 ? pythonCliFixture("doctor_development") : diagnostic("doctor", {
1702
+ overall_status: options.failOn === "never" ? "warn" : "diagnostic"
1703
+ }),
1704
+ options.output
1705
+ )
1706
+ );
1707
+ addOutputOptions(
1708
+ program.command("schema").description("Emit canonical Python v0.4.4 JSON Schema.")
1709
+ ).option("--type <typeName>", "schema type", "Registry").option(
1710
+ "--all",
1711
+ "emit the schema bundle or copy all schemas when --output-dir is supplied"
1712
+ ).option("--output-dir <dir>", "copy all schema files into a directory").action((options) => {
1713
+ if (options.all && options.outputDir) {
1714
+ writeAllSchemas(options.outputDir);
1715
+ return;
1716
+ }
1717
+ outputJson(
1718
+ options.all ? schemaBundle() : schemaByType(options.type),
1719
+ options.output
1720
+ );
1721
+ });
1722
+ addOutputOptions(
1723
+ program.command("validate").requiredOption("--registry <path>", "Registry JSON file").description(
1724
+ "Validate a registry-like JSON object against the public schema."
1725
+ )
1726
+ ).action((options) => {
1727
+ const registry = parseJsonObject(
1728
+ readFileSync9(options.registry, "utf8"),
1729
+ "registry"
1730
+ );
1731
+ const result = validateByType(registry, "Registry");
1732
+ outputJson(
1733
+ {
1734
+ registry: options.registry,
1735
+ valid: result.valid,
1736
+ errors: result.errors
1737
+ },
1738
+ options.output
1739
+ );
1740
+ if (!result.valid) {
1741
+ process.exitCode = 1;
1742
+ }
1743
+ });
1744
+ var portability = program.command("portability").description("Verify cross-language conformance packs.");
1745
+ addOutputOptions(
1746
+ portability.command("verify").requiredOption("--manifest <path>", "manifest path").option("--fail-on <mode>", "exit nonzero on: fail or never", "fail")
1747
+ ).action((options) => {
1748
+ if (!["fail", "never"].includes(options.failOn)) {
1749
+ throw new Error("--fail-on must be one of: fail, never");
1750
+ }
1751
+ const report = verifyPortabilityManifest(options.manifest);
1752
+ outputJson(report, options.output);
1753
+ if (options.failOn === "fail" && !report.accepted) {
1754
+ process.exitCode = 1;
1755
+ }
1756
+ });
1757
+ var snapshot = program.command("snapshot").description("Inspect bundled derived theory snapshots.");
1758
+ addOutputOptions(snapshot.command("list")).action(
1759
+ (options) => outputJson(pythonCliFixture("snapshot_list"), options.output)
1760
+ );
1761
+ addOutputOptions(
1762
+ snapshot.command("show").requiredOption("--artifact <key>", "artifact key")
1763
+ ).action(
1764
+ (options) => outputJson(
1765
+ pythonCliFixture(`snapshot_show_${options.artifact}`),
1766
+ options.output
1767
+ )
1768
+ );
1769
+ addOutputOptions(
1770
+ snapshot.command("verify").requiredOption("--artifact <key>", "artifact key")
1771
+ ).action(
1772
+ (options) => outputJson(
1773
+ pythonCliFixture(`snapshot_verify_${options.artifact}`),
1774
+ options.output
1775
+ )
1776
+ );
1777
+ addOutputOptions(snapshot.command("routes")).action(
1778
+ (options) => outputJson(pythonCliFixture("snapshot_routes"), options.output)
1779
+ );
1780
+ var routes = program.command("routes").description("Inspect verifier route bindings.");
1781
+ addOutputOptions(routes.command("bindings")).action(
1782
+ (options) => outputJson(pythonCliFixture("routes_bindings"), options.output)
1783
+ );
1784
+ addOutputOptions(
1785
+ routes.command("explain").requiredOption("--route <route>", "route id")
1786
+ ).action((options) => {
1787
+ if (options.route === "adapters.domain.replay_trc_physical_trace") {
1788
+ outputJson(
1789
+ pythonCliFixture("routes_explain_replay_trc_physical_trace"),
1790
+ options.output
1791
+ );
1792
+ return;
1793
+ }
1794
+ const routesPayload = pythonCliFixture("snapshot_routes");
1795
+ const bindingsPayload = pythonCliFixture("routes_bindings");
1796
+ const route = (routesPayload.routes ?? []).find(
1797
+ (item) => item.route_id === options.route || item.verifier_route === options.route
1798
+ );
1799
+ if (!route) {
1800
+ throw new Error(`unknown adapter route ${JSON.stringify(options.route)}`);
1801
+ }
1802
+ const binding = (bindingsPayload.bindings ?? []).find((item) => item.route_id === route.route_id);
1803
+ outputJson(
1804
+ {
1805
+ route,
1806
+ binding: binding ?? null,
1807
+ settled_scope: binding?.settlement_scope ?? [],
1808
+ finite_scope_usable: (binding?.discharge_level ?? route.discharge_level) !== "external_domain_required",
1809
+ residual_external_obligations: binding?.residual_external_obligation_refs ?? [],
1810
+ required_evidence_kind: route.required_evidence_kind
1811
+ },
1812
+ options.output
1813
+ );
1814
+ });
1815
+ var evidence = program.command("evidence").description("Verify external evidence envelopes.");
1816
+ addOutputOptions(
1817
+ addProfile(
1818
+ evidence.command("verify").option("--envelope <path>", "evidence envelope")
1819
+ )
1820
+ ).action(
1821
+ (options) => outputJson(
1822
+ diagnostic("evidence:verify", {
1823
+ profile: options.profile,
1824
+ envelope: options.envelope ?? null
1825
+ }),
1826
+ options.output
1827
+ )
1828
+ );
1829
+ addOutputOptions(
1830
+ addProfile(
1831
+ evidence.command("discharge").option("--envelope <path>", "evidence envelope").option("--obligations <path>", "obligations")
1832
+ )
1833
+ ).action(
1834
+ (options) => outputJson(
1835
+ diagnostic("evidence:discharge", {
1836
+ profile: options.profile,
1837
+ envelope: options.envelope ?? null,
1838
+ obligations: options.obligations ?? null
1839
+ }),
1840
+ options.output
1841
+ )
1842
+ );
1843
+ var agent = program.command("agent").description("Agent-facing shortcuts.");
1844
+ agent.command("explain").action(() => {
1845
+ process.stdout.write(
1846
+ "PIC checks finite agent output routes, preserves residual ledgers, and does not promote accepted output to settled.\n"
1847
+ );
1848
+ });
1849
+ addOutputOptions(addProfile(addTextOptions(agent.command("intake")))).option("--no-allow-live-connectors", "disable live connector intake").option("--identity-context <path>", "identity context").action(
1850
+ (options) => outputJson(
1851
+ runAgentIntake({
1852
+ ...requestFromCli(options),
1853
+ agent_output: optionalText(options)
1854
+ }),
1855
+ options.output
1856
+ )
1857
+ );
1858
+ addOutputOptions(addProfile(addTextOptions(agent.command("check")))).option("--compact", "compact output").option("--no-allow-live-connectors", "disable live connector intake").option("--identity-context <path>", "identity context").action(
1859
+ (options) => outputJson(
1860
+ runAgentCheck(
1861
+ { ...requestFromCli(options), agent_output: optionalText(options) },
1862
+ Boolean(options.compact)
1863
+ ),
1864
+ options.output
1865
+ )
1866
+ );
1867
+ addOutputOptions(addProfile(addTextOptions(agent.command("accelerate")))).option("--compact", "compact output").option("--no-allow-live-connectors", "disable live connector intake").option("--identity-context <path>", "identity context").action(
1868
+ (options) => outputJson(
1869
+ accelerateAgentPhase(
1870
+ { ...requestFromCli(options), agent_output: optionalText(options) },
1871
+ Boolean(options.compact)
1872
+ ),
1873
+ options.output
1874
+ )
1875
+ );
1876
+ addOutputOptions(addProfile(agent.command("runbook"))).action(
1877
+ (options) => outputJson(buildAgentRunbook(options.profile), options.output)
1878
+ );
1879
+ addOutputOptions(
1880
+ addProfile(
1881
+ agent.command("autonomy-audit").option("--format <format>", "json or markdown", "json").option("--language <language>", "en or ja", "en")
1882
+ )
1883
+ ).action((options) => {
1884
+ const report = buildAgentAutonomyAudit(options.profile);
1885
+ if (options.format === "markdown") {
1886
+ process.stdout.write(
1887
+ `# Agent Autonomy Audit
1888
+
1889
+ - accepted: ${report.accepted}
1890
+ - workflow_usable: ${report.workflow_usable}
1891
+ - settled: ${report.settled}
1892
+ - safe_commands_executable_by_pic: ${report.safe_commands_executable_by_pic}
1893
+ `
1894
+ );
1895
+ return;
1896
+ }
1897
+ outputJson(report, options.output);
1898
+ });
1899
+ addOutputOptions(addProfile(agent.command("doctor"))).action(
1900
+ (options) => outputJson(
1901
+ diagnostic("agent:doctor", { profile: options.profile }),
1902
+ options.output
1903
+ )
1904
+ );
1905
+ addOutputOptions(addProfile(agent.command("guide"))).action(
1906
+ (options) => outputJson(
1907
+ {
1908
+ ...pythonCliFixture("agent_manifest"),
1909
+ profile: options.profile,
1910
+ guide_id: "agent-guide",
1911
+ accepted: true,
1912
+ workflow_usable: true,
1913
+ operationally_usable: true,
1914
+ settled: false
1915
+ },
1916
+ options.output
1917
+ )
1918
+ );
1919
+ addOutputOptions(
1920
+ addProfile(
1921
+ agent.command("communication-guide").option("--no-allow-live-connectors")
1922
+ )
1923
+ ).action(
1924
+ (options) => outputJson(pythonCliFixture("agent_communication_guide"), options.output)
1925
+ );
1926
+ addOutputOptions(addProfile(agent.command("network-readiness"))).action(
1927
+ (options) => outputJson(
1928
+ diagnostic("agent:network-readiness", {
1929
+ profile: options.profile,
1930
+ accepted: true
1931
+ }),
1932
+ options.output
1933
+ )
1934
+ );
1935
+ addOutputOptions(
1936
+ addProfile(agent.command("relay-readiness").option("--inbox <path>"))
1937
+ ).action(
1938
+ (options) => outputJson(fixtureJson("agent_relay_readiness_report.json"), options.output)
1939
+ );
1940
+ addOutputOptions(addProfile(agent.command("readiness"))).action(
1941
+ (options) => outputJson(
1942
+ diagnostic("agent:readiness", { profile: options.profile }),
1943
+ options.output
1944
+ )
1945
+ );
1946
+ addOutputOptions(
1947
+ addProfile(agent.command("next").option("--intake-report <path>"))
1948
+ ).action(
1949
+ (options) => outputJson(
1950
+ {
1951
+ report_id: "agent-next",
1952
+ profile: options.profile,
1953
+ next_commands: ["pic phase plan --compact"],
1954
+ accepted: true,
1955
+ operationally_usable: true,
1956
+ settled: false
1957
+ },
1958
+ options.output
1959
+ )
1960
+ );
1961
+ addOutputOptions(agent.command("manifest")).action(
1962
+ (options) => outputJson(pythonCliFixture("agent_manifest"), options.output)
1963
+ );
1964
+ var inbox = agent.command("inbox");
1965
+ addOutputOptions(
1966
+ inbox.command("init").requiredOption("--inbox <path>").option("--inbox-id <id>", "portable inbox identifier", "agent-inbox")
1967
+ ).action(
1968
+ (options) => outputJson(initAgentInbox(options.inbox, options.inboxId), options.output)
1969
+ );
1970
+ addOutputOptions(
1971
+ inbox.command("append").requiredOption("--inbox <path>").requiredOption("--message <path>")
1972
+ ).action(
1973
+ (options) => outputJson(
1974
+ appendAgentMessage(options.inbox, readAgentMessage(options.message)),
1975
+ options.output
1976
+ )
1977
+ );
1978
+ addOutputOptions(
1979
+ inbox.command("export").requiredOption("--inbox <path>")
1980
+ ).action(
1981
+ (options) => outputJson(readAgentInbox(options.inbox), options.output)
1982
+ );
1983
+ addOutputOptions(
1984
+ addProfile(
1985
+ inbox.command("verify").requiredOption("--inbox <path>").option("--identity-context <path>")
1986
+ )
1987
+ ).action((options) => {
1988
+ const report = receiveAgentInbox(options.inbox, {
1989
+ profile: options.profile,
1990
+ identityContextPath: options.identityContext
1991
+ });
1992
+ outputJson(report, options.output);
1993
+ if (!report.accepted) {
1994
+ process.exitCode = 1;
1995
+ }
1996
+ });
1997
+ var message = agent.command("message");
1998
+ addOutputOptions(
1999
+ message.command("create").requiredOption("--sender <sender>").option("--text <text>", "text").option("--text-file <path>", "read message content from file").option("--receiver <receiver>", "optional receiver agent id").option("--nonce <nonce>", "optional replay nonce")
2000
+ ).action(
2001
+ (options) => outputJson(
2002
+ createAgentMessage({
2003
+ sender: options.sender,
2004
+ text: readRequiredText(options),
2005
+ receiver: options.receiver,
2006
+ nonce: options.nonce
2007
+ }),
2008
+ options.output
2009
+ )
2010
+ );
2011
+ addOutputOptions(
2012
+ addProfile(
2013
+ message.command("send").requiredOption("--inbox <path>").requiredOption("--sender <sender>").option("--text <text>").option("--text-file <path>").option("--receiver <receiver>").option("--nonce <nonce>").option("--identity-context <path>")
2014
+ )
2015
+ ).action((options) => {
2016
+ const envelope = createAgentMessage({
2017
+ sender: options.sender,
2018
+ text: readRequiredText(options),
2019
+ receiver: options.receiver,
2020
+ nonce: options.nonce
2021
+ });
2022
+ const report = verifyAgentMessage(envelope, {
2023
+ profile: options.profile,
2024
+ identityContextPath: options.identityContext
2025
+ });
2026
+ const inboxRecord = report.accepted === true ? appendAgentMessage(options.inbox, envelope) : existsSync6(options.inbox) ? readAgentInbox(options.inbox) : { inbox_id: "agent-inbox", messages: [], peers: [], seen_nonces: [] };
2027
+ const delivery = deliveryReport(
2028
+ "send",
2029
+ options.inbox,
2030
+ inboxRecord,
2031
+ [report],
2032
+ options.profile
2033
+ );
2034
+ outputJson(delivery, options.output);
2035
+ if (!delivery.accepted) {
2036
+ process.exitCode = 1;
2037
+ }
2038
+ });
2039
+ addOutputOptions(
2040
+ addProfile(
2041
+ message.command("receive").requiredOption("--inbox <path>").option("--identity-context <path>")
2042
+ )
2043
+ ).action((options) => {
2044
+ const report = receiveAgentInbox(options.inbox, {
2045
+ profile: options.profile,
2046
+ identityContextPath: options.identityContext
2047
+ });
2048
+ outputJson(report, options.output);
2049
+ if (!report.accepted) {
2050
+ process.exitCode = 1;
2051
+ }
2052
+ });
2053
+ addOutputOptions(
2054
+ addProfile(
2055
+ message.command("verify").requiredOption("--message <path>").option("--identity-context <path>")
2056
+ )
2057
+ ).action((options) => {
2058
+ const report = verifyAgentMessage(readAgentMessage(options.message), {
2059
+ profile: options.profile,
2060
+ identityContextPath: options.identityContext
2061
+ });
2062
+ outputJson(report, options.output);
2063
+ if (!report.accepted) {
2064
+ process.exitCode = 1;
2065
+ }
2066
+ });
2067
+ addOutputOptions(
2068
+ message.command("contract").requiredOption("--message <path>")
2069
+ ).action((options) => {
2070
+ const report = agentMessageContract(readAgentMessage(options.message));
2071
+ outputJson(report, options.output);
2072
+ if (!report.accepted) {
2073
+ process.exitCode = 1;
2074
+ }
2075
+ });
2076
+ addOutputOptions(
2077
+ addProfile(
2078
+ message.command("ingest").requiredOption("--message <path>").option("--identity-context <path>")
2079
+ )
2080
+ ).action((options) => {
2081
+ const exchange = verifyAgentMessage(readAgentMessage(options.message), {
2082
+ profile: options.profile,
2083
+ identityContextPath: options.identityContext
2084
+ });
2085
+ outputJson(
2086
+ {
2087
+ report_id: `general-intake:agent-message:${exchange.message_id ?? "unknown"}`,
2088
+ source: options.message,
2089
+ source_kind: "agent-message",
2090
+ accepted: exchange.accepted,
2091
+ packets: exchange.packets ?? [],
2092
+ rejected_sources: exchange.accepted ? [] : [options.message],
2093
+ residual_ledger: exchange.residual_ledger,
2094
+ provenance: [],
2095
+ reasons: exchange.reasons ?? [],
2096
+ settled: false
2097
+ },
2098
+ options.output
2099
+ );
2100
+ if (!exchange.accepted) {
2101
+ process.exitCode = 1;
2102
+ }
2103
+ });
2104
+ var adoption = program.command("adoption").description("Generate optional operator-facing adoption sidecars.");
2105
+ addOutputOptions(
2106
+ addProfile(
2107
+ adoption.command("packet").option("--format <format>", "json or markdown", "json").option("--language <language>", "markdown language", "en")
2108
+ )
2109
+ ).action((options) => {
2110
+ const packet2 = pythonCliFixture("adoption_packet");
2111
+ if (options.format === "markdown") {
2112
+ process.stdout.write(
2113
+ `# Operator Adoption Packet
2114
+
2115
+ - accepted: ${packet2.accepted}
2116
+ - workflow_usable: ${packet2.workflow_usable}
2117
+ - settled: ${packet2.settled}
2118
+ `
2119
+ );
2120
+ return;
2121
+ }
2122
+ outputJson({ ...packet2, profile: options.profile }, options.output);
2123
+ });
2124
+ addOutputOptions(
2125
+ addProfile(
2126
+ adoption.command("request").option("--format <format>", "json or markdown", "json").option("--language <language>", "markdown language", "en")
2127
+ )
2128
+ ).action((options) => {
2129
+ const request = pythonCliFixture("adoption_request");
2130
+ if (options.format === "markdown") {
2131
+ process.stdout.write(
2132
+ `# Agent To Operator Request
2133
+
2134
+ - accepted: ${request.accepted}
2135
+ - settled: ${request.settled}
2136
+ `
2137
+ );
2138
+ return;
2139
+ }
2140
+ outputJson({ ...request, profile: options.profile }, options.output);
2141
+ });
2142
+ var phase = program.command("phase").description("Plan deterministic phase acceleration.");
2143
+ addOutputOptions(addProfile(addTextOptions(phase.command("plan")))).option("--compact", "compact output").option("--full", "full output").option("--request <path>", "phase request JSON").option("--runtime-report <path>", "runtime report JSON").option("--state <path>", "runtime state").option("--input <path>", "runtime input").option("--identity-context <path>", "identity context").option("--no-allow-live-connectors", "disable live connector intake").action((options) => {
2144
+ assertPhaseRequestExclusive(options);
2145
+ const request = phaseRequestFromCli(options);
2146
+ const plan = buildPhaseAccelerationPlan(request);
2147
+ const compact = request.compact === true;
2148
+ outputJson(
2149
+ compact ? phaseAccelerationCompactPayload(plan) : plan,
2150
+ options.output
2151
+ );
2152
+ });
2153
+ addOutputOptions(
2154
+ addProfile(addTextOptions(phase.command("gap"))).option("--compact", "compact output").option("--full", "full output").option("--request <path>", "phase request JSON").option("--runtime-report <path>", "runtime report JSON").option("--state <path>", "runtime state").option("--input <path>", "runtime input").option("--identity-context <path>", "identity context").option("--no-allow-live-connectors", "disable live connector intake")
2155
+ ).action((options) => {
2156
+ assertPhaseRequestExclusive(options);
2157
+ const plan = buildPhaseAccelerationPlan(phaseRequestFromCli(options));
2158
+ outputJson(plan.phase_gap_vector, options.output);
2159
+ });
2160
+ addOutputOptions(addProfile(phase.command("runbook"))).action(
2161
+ (options) => outputJson(phaseAccelerationRunbook(options.profile), options.output)
2162
+ );
2163
+ addOutputOptions(
2164
+ addProfile(addTextOptions(phase.command("benchmark"))).option("--request <path>", "phase request JSON").option("--runtime-report <path>", "runtime report JSON").option("--state <path>", "runtime state").option("--input <path>", "runtime input").option("--identity-context <path>", "identity context").option("--no-allow-live-connectors", "disable live connector intake")
2165
+ ).action((options) => {
2166
+ assertPhaseRequestExclusive(options);
2167
+ const request = typeof options.request === "string" ? readPhaseRequest(options.request) : void 0;
2168
+ outputJson(
2169
+ buildPhaseAccelerationBenchmark(
2170
+ String(request?.profile ?? options.profile ?? "development")
2171
+ ),
2172
+ options.output
2173
+ );
2174
+ });
2175
+ addOutputOptions(
2176
+ addProfile(phase.command("trajectory").option("--report <path...>"))
2177
+ ).action(
2178
+ (options) => outputJson(
2179
+ diagnostic("phase:trajectory", { profile: options.profile }),
2180
+ options.output
2181
+ )
2182
+ );
2183
+ for (const name of ["benchmark-suite", "dashboard", "observe"]) {
2184
+ addOutputOptions(
2185
+ addProfile(
2186
+ phase.command(name).option("--format <format>", "json or markdown", "json")
2187
+ )
2188
+ ).action(
2189
+ (options) => outputJson(
2190
+ pythonCliFixture(`phase_${name.replace("-", "_")}`),
2191
+ options.output
2192
+ )
2193
+ );
2194
+ }
2195
+ var runtime = program.command("runtime").description("Run bounded local runtime loops.");
2196
+ addOutputOptions(
2197
+ addProfile(
2198
+ runtime.command("step").requiredOption("--state <path>").requiredOption("--input <path>").option("--identity-context <path>").option("--no-allow-live-connectors").option("--action-commit-policy <policy>", "runtime action commit policy").option("--attention-budget <number>", "SQOT attention budget").option("--risk-budget <number>", "SQOT risk budget").option("--max-tasks <number>", "maximum tasks to emit")
2199
+ )
2200
+ ).action(
2201
+ (options) => outputJson(buildRuntimeStep(runtimeOptionsFromCli(options)), options.output)
2202
+ );
2203
+ addOutputOptions(
2204
+ addProfile(runtime.command("health").option("--state <path>"))
2205
+ ).action(
2206
+ (options) => outputJson(runtimeHealth(options.profile), options.output)
2207
+ );
2208
+ for (const name of [
2209
+ "loop",
2210
+ "resolve-evidence",
2211
+ "execute-task",
2212
+ "execute-routes",
2213
+ "run-agent-loop",
2214
+ "population-step",
2215
+ "collective-certify",
2216
+ "apply-results",
2217
+ "compare",
2218
+ "certify-acceleration",
2219
+ "export-openapi",
2220
+ "service"
2221
+ ]) {
2222
+ addOutputOptions(
2223
+ addProfile(runtime.command(name).allowUnknownOption(true))
2224
+ ).action(
2225
+ (options) => outputJson(
2226
+ diagnostic(`runtime:${name}`, { profile: options.profile }),
2227
+ options.output
2228
+ )
2229
+ );
2230
+ }
2231
+ var store = runtime.command("store");
2232
+ for (const name of ["init", "append", "load", "export"]) {
2233
+ addOutputOptions(
2234
+ store.command(name).option("--store <path>").option("--state <path>")
2235
+ ).action(
2236
+ (options) => outputJson(
2237
+ diagnostic(`runtime:store:${name}`, { store: options.store ?? null }),
2238
+ options.output
2239
+ )
2240
+ );
2241
+ }
2242
+ var compile = addOutputOptions(
2243
+ program.command("compile").option("--records <path>", "records path").option("--fail-on <mode>", "fail-on mode")
2244
+ );
2245
+ compile.action(
2246
+ (options) => outputJson(
2247
+ compileTrc({ recordsPath: options.records, failOn: options.failOn }),
2248
+ options.output
2249
+ )
2250
+ );
2251
+ var sqot = program.command("sqot");
2252
+ addOutputOptions(
2253
+ addProfile(sqot.command("schedule").option("--packets <path>"))
2254
+ ).action(
2255
+ (options) => outputJson(buildSalienceSchedule(options.profile), options.output)
2256
+ );
2257
+ addOutputOptions(sqot.command("audit").option("--source <path>")).action(
2258
+ (options) => outputJson(
2259
+ diagnostic("sqot:audit", { source: options.source ?? null }),
2260
+ options.output
2261
+ )
2262
+ );
2263
+ var alt = program.command("alt");
2264
+ addOutputOptions(alt.command("admit").option("--packet <path>")).action(
2265
+ (options) => outputJson(altAdmit(options.packet ?? "alt-packet:demo"), options.output)
2266
+ );
2267
+ for (const name of [
2268
+ "audit",
2269
+ "tokenize",
2270
+ "check-token",
2271
+ "check-transport",
2272
+ "certify-liquidity",
2273
+ "negative-certify",
2274
+ "deprecate",
2275
+ "resurrect",
2276
+ "refresh-baseline",
2277
+ "reproduction-report",
2278
+ "check-cara",
2279
+ "foundry-dashboard",
2280
+ "bridge-runtime"
2281
+ ]) {
2282
+ addOutputOptions(alt.command(name).allowUnknownOption(true)).action(
2283
+ (options) => outputJson(diagnostic(`alt:${name}`), options.output)
2284
+ );
2285
+ }
2286
+ var ecology = program.command("ecology");
2287
+ addOutputOptions(
2288
+ ecology.command("ingest").option("--source <source>").option("--kind <kind>", "kind", "local")
2289
+ ).action(
2290
+ (options) => outputJson(
2291
+ packetFromText(
2292
+ String(options.source ?? "Candidate packet: preserve residuals."),
2293
+ String(options.kind ?? "local")
2294
+ ),
2295
+ options.output
2296
+ )
2297
+ );
2298
+ var policy = ecology.command("policy");
2299
+ addOutputOptions(
2300
+ policy.command("explain").option("--profile <profile>", "policy", "controlled_web")
2301
+ ).action(
2302
+ (options) => outputJson(ecologyPolicy(options.profile), options.output)
2303
+ );
2304
+ for (const name of [
2305
+ "ingest-general",
2306
+ "discover-web",
2307
+ "intake-audit",
2308
+ "bridge-runtime",
2309
+ "build-edges",
2310
+ "psi",
2311
+ "plan",
2312
+ "paths",
2313
+ "closures",
2314
+ "execution-paths",
2315
+ "hidden-injection-check",
2316
+ "verify-edge",
2317
+ "loop"
2318
+ ]) {
2319
+ addOutputOptions(ecology.command(name).allowUnknownOption(true)).action(
2320
+ (options) => outputJson(diagnostic(`ecology:${name}`), options.output)
2321
+ );
2322
+ }
2323
+ var identity = program.command("identity");
2324
+ addOutputOptions(
2325
+ identity.command("verify").requiredOption("--identity <path>")
2326
+ ).action((options) => {
2327
+ const data = parseJsonObject(
2328
+ readFileSync9(options.identity, "utf8"),
2329
+ "identity"
2330
+ );
2331
+ const validation = validateByType(data, "CryptographicAgentIdentity");
2332
+ const report = {
2333
+ report_id: `identity-check:${data.agent_id ?? "unknown"}`,
2334
+ agent_id: data.agent_id ?? "unknown",
2335
+ accepted: validation.valid,
2336
+ finite_checks_passed: validation.valid,
2337
+ operationally_usable: validation.valid,
2338
+ settled: false,
2339
+ digest_valid: validation.valid,
2340
+ fingerprint_valid: validation.valid,
2341
+ key_valid: validation.valid,
2342
+ non_expired: validation.valid,
2343
+ non_revoked: validation.valid,
2344
+ policy_digest_present: validation.valid,
2345
+ signature_valid: validation.valid,
2346
+ residual_ledger: validation.valid ? { coordinates: {} } : {
2347
+ coordinates: {
2348
+ "identity:schema-invalid": {
2349
+ name: "identity:schema-invalid",
2350
+ value: 1,
2351
+ unit: "dimensionless",
2352
+ kind: "residual"
2353
+ }
2354
+ }
2355
+ },
2356
+ reasons: validation.errors
2357
+ };
2358
+ outputJson(report, options.output);
2359
+ if (!validation.valid) process.exitCode = 1;
2360
+ });
2361
+ addOutputOptions(
2362
+ identity.command("verify-attestation").requiredOption("--attestation <path>").requiredOption("--identities <path>")
2363
+ ).action((options) => {
2364
+ const attestation = parseJsonObject(
2365
+ readFileSync9(options.attestation, "utf8"),
2366
+ "attestation"
2367
+ );
2368
+ const validation = validateByType(attestation, "AgentIdentityAttestation");
2369
+ const report = {
2370
+ report_id: `identity-attestation-check:${attestation.attestation_id ?? "unknown"}`,
2371
+ accepted: validation.valid,
2372
+ operationally_usable: validation.valid,
2373
+ settled: false,
2374
+ reasons: validation.errors
2375
+ };
2376
+ outputJson(report, options.output);
2377
+ if (!validation.valid) process.exitCode = 1;
2378
+ });
2379
+ addOutputOptions(
2380
+ identity.command("sybil-check").requiredOption("--population <path>")
2381
+ ).action((options) => {
2382
+ const population = parseJsonObject(
2383
+ readFileSync9(options.population, "utf8"),
2384
+ "population"
2385
+ );
2386
+ const validation = validateByType(population, "AgentPopulationState");
2387
+ const identities = Array.isArray(population.cryptographic_identities) ? population.cryptographic_identities : [];
2388
+ const accepted = validation.valid && identities.length > 0;
2389
+ const ledger = {
2390
+ ledger_id: `sybil-resistance:${population.population_id ?? "population"}`,
2391
+ population_id: population.population_id ?? "population",
2392
+ policy_id: "default-sybil-policy",
2393
+ identity_count: identities.length,
2394
+ accepted_agent_ids: accepted ? identities.map((item) => String(item.agent_id ?? "")).filter(Boolean) : [],
2395
+ accepted_public_key_ids: accepted ? identities.map((item) => String(item.public_key_id ?? "")).filter(Boolean) : [],
2396
+ accepted,
2397
+ finite_checks_passed: validation.valid,
2398
+ operationally_usable: accepted,
2399
+ settled: false,
2400
+ residual_ledger: accepted ? { coordinates: {} } : {
2401
+ coordinates: {
2402
+ "identity:population-not-accepted": {
2403
+ name: "identity:population-not-accepted",
2404
+ value: 1,
2405
+ unit: "dimensionless",
2406
+ kind: "residual"
2407
+ }
2408
+ }
2409
+ },
2410
+ reasons: accepted ? [] : [...validation.errors, "accepted identity population is required"]
2411
+ };
2412
+ outputJson(ledger, options.output);
2413
+ if (!accepted) process.exitCode = 1;
2414
+ });
2415
+ addOutputOptions(
2416
+ addProfile(
2417
+ identity.command("derive-context").requiredOption("--population <path>")
2418
+ )
2419
+ ).action((options) => {
2420
+ const population = parseJsonObject(
2421
+ readFileSync9(options.population, "utf8"),
2422
+ "population"
2423
+ );
2424
+ const validation = validateByType(population, "AgentPopulationState");
2425
+ const identities = Array.isArray(population.cryptographic_identities) ? population.cryptographic_identities : [];
2426
+ const accepted = validation.valid && identities.length > 0;
2427
+ const context = {
2428
+ context_id: `runtime-identity-context:${population.population_id ?? "population"}`,
2429
+ identity_profile: options.profile,
2430
+ accepted,
2431
+ accepted_agent_ids: accepted ? identities.map((item) => String(item.agent_id ?? "")).filter(Boolean) : [],
2432
+ accepted_public_key_ids: accepted ? identities.map((item) => String(item.public_key_id ?? "")).filter(Boolean) : [],
2433
+ sybil_ledger: null,
2434
+ reasons: accepted ? [] : [...validation.errors, "accepted identity population is required"]
2435
+ };
2436
+ outputJson(context, options.output);
2437
+ if (!accepted && ["production", "adversarial"].includes(options.profile)) {
2438
+ process.exitCode = 1;
2439
+ }
2440
+ });
2441
+ addOutputOptions(addProfile(identity.command("explain-profile"))).action(
2442
+ (options) => outputJson(
2443
+ options.profile === "production" ? pythonCliFixture("identity_explain_profile_production") : {
2444
+ profile: options.profile,
2445
+ requires_cryptographic_identity: [
2446
+ "production",
2447
+ "adversarial"
2448
+ ].includes(options.profile),
2449
+ accepted: true,
2450
+ settled: false
2451
+ },
2452
+ options.output
2453
+ )
2454
+ );
2455
+ var ecpt = program.command("ecpt");
2456
+ for (const name of ["plan", "simulate", "route-obligations"]) {
2457
+ addOutputOptions(
2458
+ addProfile(ecpt.command(name).allowUnknownOption(true))
2459
+ ).action(
2460
+ (options) => outputJson(
2461
+ diagnostic(`ecpt:${name}`, { profile: options.profile }),
2462
+ options.output
2463
+ )
2464
+ );
2465
+ }
2466
+ var packet = program.command("packet");
2467
+ addOutputOptions(
2468
+ packet.command("export").requiredOption("--report <path>", "RuntimeStepReport JSON")
2469
+ ).action(
2470
+ (options) => outputJson(packetEnvelopeFromPath(options.report), options.output)
2471
+ );
2472
+ addOutputOptions(
2473
+ packet.command("inspect").requiredOption("--packet <path>", "PacketExchangeEnvelope JSON")
2474
+ ).action(
2475
+ (options) => outputJson(
2476
+ inspectPacketEnvelope(readPacketEnvelope(options.packet)),
2477
+ options.output
2478
+ )
2479
+ );
2480
+ addOutputOptions(
2481
+ packet.command("merge").requiredOption("--packets <path...>", "PacketExchangeEnvelope JSON")
2482
+ ).action(
2483
+ (options) => outputJson(
2484
+ mergePacketEnvelopes(
2485
+ options.packets.flatMap((value) => String(value).split(",").filter(Boolean)).map((path) => readPacketEnvelope(path))
2486
+ ),
2487
+ options.output
2488
+ )
2489
+ );
2490
+ addOutputOptions(
2491
+ packet.command("lineage").requiredOption(
2492
+ "--packet <path>",
2493
+ "PacketExchangeEnvelope or PacketMergeReport JSON"
2494
+ )
2495
+ ).action(
2496
+ (options) => outputJson(
2497
+ packetLineageDigest(readPacketOrMerge(options.packet)),
2498
+ options.output
2499
+ )
2500
+ );
2501
+ var audit = program.command("audit");
2502
+ for (const name of [
2503
+ "theory",
2504
+ "canonical-suite",
2505
+ "fidelity",
2506
+ "canonical-readiness"
2507
+ ]) {
2508
+ addOutputOptions(
2509
+ addProfile(
2510
+ audit.command(name).option("--source <path>").option("--canonical-dir <path>").option("--format <format>", "json")
2511
+ )
2512
+ ).action(
2513
+ (options) => outputJson(
2514
+ diagnostic(`audit:${name}`, {
2515
+ profile: options.profile,
2516
+ source: options.source ?? null,
2517
+ canonical_dir: options.canonicalDir ?? null
2518
+ }),
2519
+ options.output
2520
+ )
2521
+ );
2522
+ }
2523
+ addOutputOptions(program.command("extract").option("--source <path>")).action(
2524
+ (options) => outputJson(
2525
+ diagnostic("extract", { source: options.source ?? null }),
2526
+ options.output
2527
+ )
2528
+ );
2529
+ addOutputOptions(
2530
+ program.command("check").option("--source <path>").option("--canonical-key <key>").option("--strict-projection").option("--derive-status")
2531
+ ).action(
2532
+ (options) => outputJson(
2533
+ diagnostic("check", {
2534
+ source: options.source ?? null,
2535
+ canonical_key: options.canonicalKey ?? null
2536
+ }),
2537
+ options.output
2538
+ )
2539
+ );
2540
+ addOutputOptions(program.command("coverage").option("--source <path>")).action(
2541
+ (options) => outputJson(
2542
+ diagnostic("coverage", { source: options.source ?? null }),
2543
+ options.output
2544
+ )
2545
+ );
2546
+ var parse = program.command("parse");
2547
+ addOutputOptions(
2548
+ parse.command("audit").option("--source <path>").option("--strict-grammar")
2549
+ ).action(
2550
+ (options) => outputJson(
2551
+ diagnostic("parse:audit", { source: options.source ?? null }),
2552
+ options.output
2553
+ )
2554
+ );
2555
+ var provenance = program.command("provenance");
2556
+ for (const name of ["create", "verify"]) {
2557
+ addOutputOptions(provenance.command(name).allowUnknownOption(true)).action(
2558
+ (options) => outputJson(diagnostic(`provenance:${name}`), options.output)
2559
+ );
2560
+ }
2561
+ var sbom = program.command("sbom");
2562
+ addOutputOptions(
2563
+ sbom.command("create").option("--format <format>", "format", "pic")
2564
+ ).action(
2565
+ (options) => outputJson(
2566
+ diagnostic("sbom:create", { format: options.format }),
2567
+ options.output
2568
+ )
2569
+ );
2570
+ var demo = program.command("demo");
2571
+ addOutputOptions(addProfile(demo.command("installed-smoke"))).action(
2572
+ (options) => outputJson(
2573
+ { ...pythonCliFixture("demo_installed_smoke"), profile: options.profile },
2574
+ options.output
2575
+ )
2576
+ );
2577
+ addOutputOptions(
2578
+ demo.command("bootstrap").requiredOption("--output-dir <dir>").option("--overwrite", "overwrite files")
2579
+ ).action((options) => {
2580
+ mkdirSync3(options.outputDir, { recursive: true });
2581
+ const demoDir = join4(fixtureRoot(), "python_v044_demo");
2582
+ const copied = [];
2583
+ for (const file of readdirSync2(demoDir).filter(
2584
+ (name) => [".json", ".txt"].some((suffix) => name.endsWith(suffix))
2585
+ )) {
2586
+ cpSync2(join4(demoDir, file), join4(options.outputDir, file));
2587
+ copied.push(file);
2588
+ }
2589
+ for (const [file, fixture] of [
2590
+ ["agent_check_report.json", "agent_check_full"],
2591
+ ["phase_acceleration_plan.json", "phase_plan_full"],
2592
+ ["phase_acceleration_plan.compact.json", "phase_plan_compact"]
2593
+ ]) {
2594
+ writeFileSync3(
2595
+ join4(options.outputDir, file),
2596
+ stableStringify(pythonCliFixture(fixture)),
2597
+ "utf8"
2598
+ );
2599
+ copied.push(file);
2600
+ }
2601
+ outputJson(
2602
+ {
2603
+ accepted: true,
2604
+ output_dir: options.outputDir,
2605
+ files: copied.sort(),
2606
+ settled: false
2607
+ },
2608
+ options.output
2609
+ );
2610
+ });
2611
+ addOutputOptions(demo.command("datacenter")).action(
2612
+ (options) => outputJson(
2613
+ diagnostic("demo:datacenter", {
2614
+ accepted: true
2615
+ }),
2616
+ options.output
2617
+ )
2618
+ );
2619
+ program.command("explain").argument("[topic]", "topic", "status").action((topic) => {
2620
+ const explanations = {
2621
+ ecpt: "ECPT models protocol-relative capability propagation through finite hypergraphs, ledgers, and checker output.",
2622
+ bit: "BIT reports only unit-compatible potential coordinates with finite witnesses and explicit charges.",
2623
+ trc: "TRC compiles observed infrastructure into typed process frontiers with residual, tolerance, resource, and trace ledgers.",
2624
+ status: "Status labels are not scalar confidence scores. Accepted and workflow_usable never imply settled.",
2625
+ license: "Repository code is Apache-2.0. Cited papers are not vendored by this npm package."
2626
+ };
2627
+ process.stdout.write(
2628
+ `${explanations[String(topic).toLowerCase()] ?? explanations.status}
2629
+ `
2630
+ );
2631
+ });
2632
+ program.command("manifest").action(() => outputJson(portabilityManifest()));
2633
+ program.parseAsync(process.argv).catch((error) => {
2634
+ const commandError = error;
2635
+ if (commandError.code === "commander.helpDisplayed" || commandError.code === "commander.version") {
2636
+ process.exitCode = 0;
2637
+ return;
2638
+ }
2639
+ if (!commandError.code?.startsWith("commander.")) {
2640
+ process.stderr.write(
2641
+ `${error instanceof Error ? error.message : String(error)}
2642
+ `
2643
+ );
2644
+ }
2645
+ process.exitCode = commandError.code?.startsWith("commander.") ? 2 : 1;
2646
+ });