percolation-inversion-compiler-ts 0.4.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +77 -22
  3. package/agent-manifest.json +50 -0
  4. package/dist/alt_lift/index.d.ts +7 -0
  5. package/dist/alt_lift/index.js +101 -0
  6. package/dist/bit_engine/index.d.ts +8 -0
  7. package/dist/bit_engine/index.js +213 -0
  8. package/dist/cli/main.js +2106 -162
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +1611 -16
  11. package/dist/phase_lab/index.d.ts +26 -0
  12. package/dist/phase_lab/index.js +1124 -0
  13. package/dist/sqot_controller/index.d.ts +8 -0
  14. package/dist/sqot_controller/index.js +141 -0
  15. package/dist/trc_adapter/index.d.ts +6 -0
  16. package/dist/trc_adapter/index.js +86 -0
  17. package/docs/alt-ecpt-lift.md +32 -0
  18. package/docs/bit-inversion-engine.md +32 -0
  19. package/docs/cli-reference.md +68 -0
  20. package/docs/effective-packet-graph.md +35 -0
  21. package/docs/for-agents.md +44 -0
  22. package/docs/phase-ecology-lab.md +46 -0
  23. package/docs/sqot-queue-sovereignty.md +31 -0
  24. package/docs/threshold-certificates.md +30 -0
  25. package/docs/trc-trace-adapter.md +30 -0
  26. package/docs/v050-audit.md +126 -0
  27. package/examples/alt_lift/alt_ecpt_lift.example.json +27 -0
  28. package/examples/bit_engine/bottlenecks.example.json +38 -0
  29. package/examples/bit_engine/inversion_candidates.example.json +55 -0
  30. package/examples/packet_exchange/packet_envelope.example.json +51 -0
  31. package/examples/packet_exchange/packet_merge_report.example.json +60 -0
  32. package/examples/phase_lab/certificate_abstain.example.json +39 -0
  33. package/examples/phase_lab/closure_report.example.json +41 -0
  34. package/examples/phase_lab/effective_graph.example.json +112 -0
  35. package/examples/phase_lab/executable_paths.example.json +20 -0
  36. package/examples/phase_lab/phase_window_observation.example.json +61 -0
  37. package/examples/phase_lab/runtime_report_1.json +19 -0
  38. package/examples/phase_lab/runtime_report_2.json +16 -0
  39. package/examples/phase_lab/threshold_status.example.json +31 -0
  40. package/examples/sqot_controller/queue_report.example.json +30 -0
  41. package/examples/sqot_controller/rebalance_plan.example.json +14 -0
  42. package/examples/thresholds/asi_proxy_development.json +15 -0
  43. package/examples/trc_adapter/tool_trace_input.example.json +17 -0
  44. package/examples/trc_adapter/typed_trace.example.json +64 -0
  45. package/fixtures/portability_conformance_v050/certificate_abstain.example.json +39 -0
  46. package/fixtures/portability_conformance_v050/closure_report.example.json +39 -0
  47. package/fixtures/portability_conformance_v050/effective_graph.example.json +112 -0
  48. package/fixtures/portability_conformance_v050/executable_paths.example.json +20 -0
  49. package/fixtures/portability_conformance_v050/manifest.json +55 -0
  50. package/fixtures/portability_conformance_v050/phase_lab_event_1.json +51 -0
  51. package/fixtures/portability_conformance_v050/phase_lab_event_2.json +55 -0
  52. package/fixtures/portability_conformance_v050/phase_window_observation.example.json +61 -0
  53. package/fixtures/portability_conformance_v050/runtime_report_1.json +19 -0
  54. package/fixtures/portability_conformance_v050/runtime_report_2.json +14 -0
  55. package/fixtures/portability_conformance_v050/threshold_status.example.json +29 -0
  56. package/fixtures/python_v044_cli/agent_autonomy_audit.json +4 -3
  57. package/fixtures/python_v044_cli/agent_manifest.json +2 -1
  58. package/fixtures/python_v044_cli/agent_runbook.json +2 -1
  59. package/fixtures/python_v044_cli/demo_installed_smoke.json +86 -86
  60. package/fixtures/python_v044_demo/manifest.json +2 -1
  61. package/fixtures/python_v050_cli/alt_capital_impact.json +30 -0
  62. package/fixtures/python_v050_cli/alt_ecpt_lift.json +85 -0
  63. package/fixtures/python_v050_cli/alt_liquidity_to_paths.json +85 -0
  64. package/fixtures/python_v050_cli/alt_receiver_lift.json +15 -0
  65. package/fixtures/python_v050_cli/bit_certificate.json +15 -0
  66. package/fixtures/python_v050_cli/bit_compare_baseline.json +24 -0
  67. package/fixtures/python_v050_cli/bit_diagnose.json +95 -0
  68. package/fixtures/python_v050_cli/bit_invert.json +235 -0
  69. package/fixtures/python_v050_cli/bit_mec.json +18 -0
  70. package/fixtures/python_v050_cli/ecology_effective_graph.json +178 -0
  71. package/fixtures/python_v050_cli/ecology_execution_available_paths.json +88 -0
  72. package/fixtures/python_v050_cli/manifest.json +48 -0
  73. package/fixtures/python_v050_cli/phase_lab_certify.json +443 -0
  74. package/fixtures/python_v050_cli/phase_lab_closure.json +85 -0
  75. package/fixtures/python_v050_cli/phase_lab_compare_window.json +24 -0
  76. package/fixtures/python_v050_cli/phase_lab_executable_paths.json +88 -0
  77. package/fixtures/python_v050_cli/phase_lab_graph.json +178 -0
  78. package/fixtures/python_v050_cli/phase_lab_ingest_1.json +105 -0
  79. package/fixtures/python_v050_cli/phase_lab_ingest_2.json +109 -0
  80. package/fixtures/python_v050_cli/phase_lab_init.json +20 -0
  81. package/fixtures/python_v050_cli/phase_lab_list_windows.json +63 -0
  82. package/fixtures/python_v050_cli/phase_lab_observe.json +108 -0
  83. package/fixtures/python_v050_cli/phase_lab_threshold_status.json +164 -0
  84. package/fixtures/python_v050_cli/sqot_diagnose_queue.json +38 -0
  85. package/fixtures/python_v050_cli/sqot_quarantine.json +7 -0
  86. package/fixtures/python_v050_cli/sqot_rebalance.json +19 -0
  87. package/fixtures/python_v050_cli/sqot_reserve_check.json +20 -0
  88. package/fixtures/python_v050_cli/sqot_salience_obstruction.json +19 -0
  89. package/fixtures/python_v050_cli/trc_action_boundary.json +451 -0
  90. package/fixtures/python_v050_cli/trc_tool_trace.json +221 -0
  91. package/fixtures/python_v050_cli/trc_trace_adapter.json +221 -0
  92. package/fixtures/python_v050_demo/asi_proxy_development.json +15 -0
  93. package/fixtures/python_v050_demo/certificate_abstain.example.json +39 -0
  94. package/fixtures/python_v050_demo/closure_report.example.json +39 -0
  95. package/fixtures/python_v050_demo/effective_graph.example.json +112 -0
  96. package/fixtures/python_v050_demo/executable_paths.example.json +20 -0
  97. package/fixtures/python_v050_demo/phase_window_observation.example.json +61 -0
  98. package/fixtures/python_v050_demo/runtime_report_1.json +19 -0
  99. package/fixtures/python_v050_demo/runtime_report_2.json +14 -0
  100. package/fixtures/python_v050_demo/threshold_status.example.json +29 -0
  101. package/fixtures/python_v050_snapshots/manifest.json +39 -0
  102. package/fixtures/python_v050_snapshots/snapshot_list.json +112 -0
  103. package/fixtures/python_v050_snapshots/snapshot_routes.json +926 -0
  104. package/fixtures/python_v050_snapshots/snapshot_show_alt.json +6830 -0
  105. package/fixtures/python_v050_snapshots/snapshot_show_bit.json +594 -0
  106. package/fixtures/python_v050_snapshots/snapshot_show_ecpt.json +2894 -0
  107. package/fixtures/python_v050_snapshots/snapshot_show_sqot.json +2392 -0
  108. package/fixtures/python_v050_snapshots/snapshot_show_trc.json +3037 -0
  109. package/fixtures/python_v050_snapshots/snapshot_verify_alt.json +10 -0
  110. package/fixtures/python_v050_snapshots/snapshot_verify_bit.json +10 -0
  111. package/fixtures/python_v050_snapshots/snapshot_verify_ecpt.json +10 -0
  112. package/fixtures/python_v050_snapshots/snapshot_verify_sqot.json +10 -0
  113. package/fixtures/python_v050_snapshots/snapshot_verify_trc.json +10 -0
  114. package/package.json +45 -3
  115. package/schemas/ASIProxyThresholdSpec.schema.json +72 -0
  116. package/schemas/ASIProxyThresholdStatus.schema.json +512 -0
  117. package/schemas/ActionBoundaryRequirement.schema.json +28 -0
  118. package/schemas/ActivationGainEstimate.schema.json +41 -0
  119. package/schemas/AltEcptLiftReport.schema.json +400 -0
  120. package/schemas/AltLiftBlocker.schema.json +34 -0
  121. package/schemas/AttentionBudgetLedger.schema.json +41 -0
  122. package/schemas/AutocatalyticClosureReport.schema.json +408 -0
  123. package/schemas/AutocatalyticClosureWitness.schema.json +22 -139
  124. package/schemas/BasinReachabilityProxy.schema.json +21 -0
  125. package/schemas/BottleneckClassDiagnosis.schema.json +115 -0
  126. package/schemas/BottleneckInversionCandidate.schema.json +249 -0
  127. package/schemas/BottleneckInversionReport.schema.json +499 -0
  128. package/schemas/CapabilityExpressionPath.schema.json +45 -0
  129. package/schemas/CapitalToPathContribution.schema.json +53 -0
  130. package/schemas/ClosureAbstentionReason.schema.json +25 -0
  131. package/schemas/ClosureCertificateCandidate.schema.json +109 -0
  132. package/schemas/ClosureDefect.schema.json +28 -0
  133. package/schemas/ClosureSupportHyperpath.schema.json +44 -0
  134. package/schemas/CollectivePhaseAbstentionReport.schema.json +591 -0
  135. package/schemas/CollectivePhaseCertificateCandidate.schema.json +688 -0
  136. package/schemas/CrossContextTransferWitness.schema.json +46 -0
  137. package/schemas/DiagnosticReserveReport.schema.json +87 -0
  138. package/schemas/DownstreamSearchCostDelta.schema.json +46 -0
  139. package/schemas/EcologyAutocatalyticClosureWitness.schema.json +187 -0
  140. package/schemas/EffectiveGraphResidualSummary.schema.json +38 -0
  141. package/schemas/EffectivePacketEdge.schema.json +135 -0
  142. package/schemas/EffectivePacketEligibility.schema.json +84 -0
  143. package/schemas/EffectivePacketGraph.schema.json +461 -0
  144. package/schemas/EffectivePacketGraphBuildReport.schema.json +521 -0
  145. package/schemas/EffectivePacketNode.schema.json +199 -0
  146. package/schemas/ExecutableClosureWitness.schema.json +47 -0
  147. package/schemas/ExecutablePathDensityReport.schema.json +314 -0
  148. package/schemas/ExecutionAuthorityStatus.schema.json +28 -0
  149. package/schemas/ExecutionAvailableHyperpath.schema.json +201 -0
  150. package/schemas/ExecutionPathDefect.schema.json +28 -0
  151. package/schemas/ExecutionPathWitness.schema.json +44 -0
  152. package/schemas/FalseLiquidityLoad.schema.json +21 -0
  153. package/schemas/GeneralIntakePolicy.schema.json +1 -1
  154. package/schemas/InversionCertificate.schema.json +56 -0
  155. package/schemas/LiquidityToClosureContribution.schema.json +53 -0
  156. package/schemas/MinimalEnablingCondition.schema.json +48 -0
  157. package/schemas/PacketContributionStatus.schema.json +32 -0
  158. package/schemas/PacketQuarantineDecision.schema.json +50 -0
  159. package/schemas/PhaseCertificateDefect.schema.json +33 -0
  160. package/schemas/PhaseComponentObservation.schema.json +39 -0
  161. package/schemas/PhaseLabEvent.schema.json +123 -0
  162. package/schemas/PhaseLabExportManifest.schema.json +127 -0
  163. package/schemas/PhaseLabIngestReport.schema.json +344 -0
  164. package/schemas/PhaseLabStoreManifest.schema.json +73 -0
  165. package/schemas/PhaseLabWindowIndex.schema.json +78 -0
  166. package/schemas/PhaseThresholdStatus.schema.json +51 -0
  167. package/schemas/PhaseWindow.schema.json +31 -0
  168. package/schemas/PhaseWindowComparison.schema.json +67 -0
  169. package/schemas/PhaseWindowObservation.schema.json +353 -0
  170. package/schemas/PostInversionAuditPlan.schema.json +38 -0
  171. package/schemas/ProductiveClosureWitness.schema.json +49 -0
  172. package/schemas/ProvenanceManifest.schema.json +1 -1
  173. package/schemas/QueueOccupationReport.schema.json +156 -0
  174. package/schemas/QueueRebalancePlan.schema.json +114 -0
  175. package/schemas/ReceiverContextSupport.schema.json +23 -0
  176. package/schemas/ReceiverLiquidityLift.schema.json +58 -0
  177. package/schemas/ReleaseArtifactManifest.schema.json +1 -1
  178. package/schemas/ReversibleSalienceSovereigntyCertificate.schema.json +53 -0
  179. package/schemas/RollbackOrDeactivationPlan.schema.json +38 -0
  180. package/schemas/SBOMManifest.schema.json +1 -1
  181. package/schemas/SalienceObstructionDiagnosis.schema.json +55 -0
  182. package/schemas/SalienceObstructionLoad.schema.json +21 -0
  183. package/schemas/SemanticEdgeEvidence.schema.json +40 -0
  184. package/schemas/TraceAdapterReport.schema.json +405 -0
  185. package/schemas/TraceFrontierDebt.schema.json +43 -0
  186. package/schemas/TraceNormalForm.schema.json +181 -0
  187. package/schemas/TraceToleranceLedger.schema.json +29 -0
  188. package/schemas/TypedActionBoundary.schema.json +58 -0
  189. package/schemas/TypedAgentTrace.schema.json +328 -0
  190. package/schemas/TypedToolCallTrace.schema.json +76 -0
  191. package/schemas/VerificationQueuePressure.schema.json +41 -0
  192. package/schemas/VerificationThroughputWindow.schema.json +21 -0
  193. package/schemas/WasteLoad.schema.json +21 -0
  194. package/schemas/WebFetchPolicy.schema.json +1 -1
  195. package/schemas/bundle.schema.json +11854 -2075
  196. package/schemas/index.json +445 -0
  197. package/schemas/schema-digest.json +733 -289
package/dist/index.js CHANGED
@@ -658,19 +658,1583 @@ function agentRunbookSteps(profile = "development") {
658
658
  ];
659
659
  }
660
660
 
661
+ // src/phase_lab/index.ts
662
+ import { createHash as createHash2 } from "crypto";
663
+ import {
664
+ existsSync as existsSync4,
665
+ mkdirSync as mkdirSync2,
666
+ readFileSync as readFileSync5,
667
+ readdirSync as readdirSync2,
668
+ writeFileSync as writeFileSync2
669
+ } from "fs";
670
+ import { basename as basename2, join as join4 } from "path";
671
+ var PHASE_LAB_SAFETY = [
672
+ "phase lab stores local report data only",
673
+ "phase lab never executes report or packet content",
674
+ "phase lab diagnostics do not settle claims",
675
+ "raw packet volume is diagnostic only"
676
+ ];
677
+ var GRAPH_SAFETY = [
678
+ "raw packet volume is diagnostic only",
679
+ "candidate-only nodes do not improve positive phase components",
680
+ "graph construction does not execute packet content",
681
+ "graph construction does not settle claims"
682
+ ];
683
+ function sha256Json(data) {
684
+ return createHash2("sha256").update(JSON.stringify(sortJson(data)), "utf8").digest("hex");
685
+ }
686
+ function asRecord(value) {
687
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
688
+ }
689
+ function asRecords(value) {
690
+ return Array.isArray(value) ? value.filter((item) => Boolean(asRecord(item))) : [];
691
+ }
692
+ function stringList(value) {
693
+ if (value === void 0 || value === null) return [];
694
+ if (Array.isArray(value)) return value.map(String).sort();
695
+ if (value instanceof Set) return [...value].map(String).sort();
696
+ return [String(value)];
697
+ }
698
+ function numeric(value) {
699
+ if (typeof value === "number" && Number.isFinite(value)) return value;
700
+ const parsed = Number(value);
701
+ return Number.isFinite(parsed) ? parsed : 0;
702
+ }
703
+ function numericDict(value) {
704
+ const record5 = asRecord(value);
705
+ if (!record5) return {};
706
+ return Object.fromEntries(
707
+ Object.entries(record5).map(([key, item]) => [key, numeric(item)]).sort(([a], [b]) => a.localeCompare(b))
708
+ );
709
+ }
710
+ function residualSummary(payload) {
711
+ const direct = asRecord(payload.residual_summary) ?? asRecord(payload.residual_ledger_summary);
712
+ if (direct) return numericDict(direct);
713
+ const coordinates = asRecord(asRecord(payload.residual_ledger)?.coordinates);
714
+ if (!coordinates) return {};
715
+ const summary = {};
716
+ for (const coordinate of Object.values(coordinates)) {
717
+ const item = asRecord(coordinate);
718
+ if (!item) continue;
719
+ const kind = String(item.kind ?? "residual");
720
+ summary[kind] = (summary[kind] ?? 0) + numeric(item.value);
721
+ }
722
+ return Object.fromEntries(
723
+ Object.entries(summary).sort(([a], [b]) => a.localeCompare(b))
724
+ );
725
+ }
726
+ function residualDebt(summary) {
727
+ return Object.values(summary).reduce((total, value) => total + value, 0);
728
+ }
729
+ function inferSchemaHint(payload) {
730
+ if ("packet_id" in payload && "content_digest" in payload && "content" in payload) {
731
+ return "PacketExchangeEnvelope";
732
+ }
733
+ if ("report_id" in payload && "registry" in payload)
734
+ return "RuntimeStepReport";
735
+ if ("graph_id" in payload && "nodes" in payload && "edges" in payload) {
736
+ return "EffectivePacketGraph";
737
+ }
738
+ if ("message_id" in payload) return "AgentMessageEnvelope";
739
+ if ("decision_id" in payload && "packet_id" in payload)
740
+ return "ALTAdmissionDecision";
741
+ if ("accepted" in payload && "workflow_usable" in payload)
742
+ return "AgentCheckReport";
743
+ return String(payload.schema_hint ?? payload.schema ?? "UnknownPICReport");
744
+ }
745
+ function inferSourceKind(payload, schemaHint) {
746
+ if (typeof payload.source_kind === "string") return payload.source_kind;
747
+ const mapping = {
748
+ AgentCheckReport: "agent-check",
749
+ AgentMessageEnvelope: "agent-message",
750
+ ALTAdmissionDecision: "alt-admission",
751
+ EffectivePacketGraph: "effective-graph",
752
+ PacketExchangeEnvelope: "packet-exchange",
753
+ RuntimeStepReport: "runtime-step-report"
754
+ };
755
+ return mapping[schemaHint] ?? "unknown-report";
756
+ }
757
+ function unsafeReasons(payload, missing, candidateOnlyReasons, settledBlockers) {
758
+ const text = JSON.stringify(payload).toLowerCase();
759
+ const reasons = [];
760
+ if ([
761
+ "npm install",
762
+ "npx",
763
+ "node ",
764
+ "docker run",
765
+ "kubectl",
766
+ "curl ",
767
+ "bash ",
768
+ "powershell",
769
+ "safe_commands"
770
+ ].some((marker) => text.includes(marker))) {
771
+ reasons.push("embedded command-like text remains inert");
772
+ }
773
+ if (missing.length > 0) reasons.push("missing obligations remain visible");
774
+ if (candidateOnlyReasons.length > 0)
775
+ reasons.push("candidate-only reasons remain visible");
776
+ if (settledBlockers.length > 0)
777
+ reasons.push("settlement blockers remain visible");
778
+ return dedupeSorted(reasons);
779
+ }
780
+ function eventFromPayload(payload, windowId, sequence, sourcePath, sourceKindOverride) {
781
+ const digest = sha256Json(payload);
782
+ const schemaHint = inferSchemaHint(payload);
783
+ const sourceKind = sourceKindOverride ?? inferSourceKind(payload, schemaHint);
784
+ const missing = dedupeSorted([
785
+ ...stringList(payload.missing_obligations),
786
+ ...stringList(payload.unresolved_obligations)
787
+ ]);
788
+ const candidateOnlyReasons = dedupeSorted(
789
+ stringList(payload.candidate_only_reasons)
790
+ );
791
+ const settledBlockers = dedupeSorted([
792
+ ...stringList(payload.settled_blockers),
793
+ ...payload.settled === true ? ["source-settled-ignored-by-phase-lab"] : []
794
+ ]);
795
+ const accepted = payload.accepted === true;
796
+ const candidateOnly = payload.candidate_only === true || candidateOnlyReasons.length > 0 || !accepted || [
797
+ "packet-exchange",
798
+ "general-intake",
799
+ "raw-external",
800
+ "phase-dashboard"
801
+ ].includes(sourceKind);
802
+ const reasons = unsafeReasons(
803
+ payload,
804
+ missing,
805
+ candidateOnlyReasons,
806
+ settledBlockers
807
+ );
808
+ const positiveContributionAllowed = accepted && !candidateOnly && reasons.length === 0 && missing.length === 0;
809
+ return {
810
+ accepted,
811
+ candidate_only: candidateOnly,
812
+ candidate_only_reasons: candidateOnlyReasons,
813
+ content_digest: digest,
814
+ event_id: `phase-lab-event:${sequence}:${digest.slice(0, 12)}`,
815
+ missing_obligations: missing,
816
+ operationally_usable: payload.operationally_usable === true,
817
+ payload,
818
+ positive_contribution_allowed: positiveContributionAllowed,
819
+ reasons: dedupeSorted([
820
+ "event content is stored as inert data",
821
+ ...reasons,
822
+ ...candidateOnly ? ["candidate-only event cannot improve phase metrics"] : []
823
+ ]),
824
+ residual_summary: residualSummary(payload),
825
+ safety_boundary: PHASE_LAB_SAFETY,
826
+ schema_hint: schemaHint,
827
+ settled: false,
828
+ settled_blockers: settledBlockers,
829
+ source_kind: sourceKind,
830
+ source_path: sourcePath ? basename2(sourcePath) : null,
831
+ window_id: windowId,
832
+ workflow_usable: payload.workflow_usable === true
833
+ };
834
+ }
835
+ function readJsonFile(path, label = "JSON") {
836
+ if (!path.toLowerCase().endsWith(".json")) {
837
+ throw new Error(
838
+ `${label} must be a JSON file; YAML input is not enabled in PIC-TS v0.5.0`
839
+ );
840
+ }
841
+ return parseJsonObject(readFileSync5(path, "utf8"), label);
842
+ }
843
+ function storePaths(storeDir) {
844
+ return {
845
+ events: join4(storeDir, "events.jsonl"),
846
+ manifest: join4(storeDir, "manifest.json"),
847
+ windows: join4(storeDir, "windows")
848
+ };
849
+ }
850
+ function windowFileName(windowId) {
851
+ return `${windowId.replace(/[^A-Za-z0-9_.-]/g, "_")}.json`;
852
+ }
853
+ function readEvents(storeDir) {
854
+ const eventsPath = storePaths(storeDir).events;
855
+ if (!existsSync4(eventsPath)) return [];
856
+ return readFileSync5(eventsPath, "utf8").split(/\r?\n/).filter(Boolean).map((line) => parseJsonObject(line, "phase lab event"));
857
+ }
858
+ function writeJson(path, data) {
859
+ writeFileSync2(path, stableStringify(data), "utf8");
860
+ }
861
+ function windowIndex(windowId, sequence, events) {
862
+ const residual = events.reduce(
863
+ (total, event) => total + residualDebt(numericDict(event.residual_summary)),
864
+ 0
865
+ );
866
+ return {
867
+ accepted: true,
868
+ accepted_event_count: events.filter((event) => event.accepted === true).length,
869
+ candidate_only_event_count: events.filter(
870
+ (event) => event.candidate_only === true
871
+ ).length,
872
+ event_count: events.length,
873
+ event_ids: events.map((event) => String(event.event_id)),
874
+ missing_obligation_count: events.reduce(
875
+ (total, event) => total + stringList(event.missing_obligations).length,
876
+ 0
877
+ ),
878
+ positive_contribution_event_count: events.filter(
879
+ (event) => event.positive_contribution_allowed === true
880
+ ).length,
881
+ reasons: ["window index preserves event residuals without settling claims"],
882
+ residual_debt: residual,
883
+ sequence,
884
+ settled: false,
885
+ settled_event_count: 0,
886
+ window_id: windowId
887
+ };
888
+ }
889
+ function readWindowIndexes(storeDir) {
890
+ const windowsDir = storePaths(storeDir).windows;
891
+ if (!existsSync4(windowsDir)) return [];
892
+ return readdirSync2(windowsDir).filter((name) => name !== "latest.json" && name.endsWith(".json")).sort().map(
893
+ (name) => parseJsonObject(readFileSync5(join4(windowsDir, name), "utf8"), "window")
894
+ );
895
+ }
896
+ function selectWindow(storeDir, selector = "latest") {
897
+ const windows = readWindowIndexes(storeDir);
898
+ if (windows.length === 0) throw new Error("phase lab store has no windows");
899
+ let selected;
900
+ if (selector === "latest" || selector === "all") {
901
+ selected = windows[windows.length - 1];
902
+ } else if (selector === "previous") {
903
+ selected = windows.length > 1 ? windows[windows.length - 2] : windows[windows.length - 1];
904
+ } else {
905
+ selected = windows.find((window) => window.window_id === selector);
906
+ }
907
+ if (!selected)
908
+ throw new Error(`unknown phase lab window ${JSON.stringify(selector)}`);
909
+ const selectedId = String(selected.window_id);
910
+ const events = selector === "all" ? readEvents(storeDir) : readEvents(storeDir).filter((event) => event.window_id === selectedId);
911
+ return { index: selected, events };
912
+ }
913
+ function writeManifest(storeDir) {
914
+ const paths = storePaths(storeDir);
915
+ mkdirSync2(paths.windows, { recursive: true });
916
+ const windows = readWindowIndexes(storeDir);
917
+ const events = readEvents(storeDir);
918
+ const manifest = {
919
+ accepted: true,
920
+ database_path: "events.jsonl",
921
+ event_count: events.length,
922
+ latest_window_id: windows.length > 0 ? String(windows[windows.length - 1]?.window_id ?? "") : null,
923
+ reasons: ["phase lab store is local and non-executing"],
924
+ safety_invariants: PHASE_LAB_SAFETY,
925
+ schema_version: "phase-lab-store-v1",
926
+ settled: false,
927
+ store_id: "phase-lab-store",
928
+ store_path: basename2(storeDir),
929
+ window_count: windows.length
930
+ };
931
+ writeJson(paths.manifest, manifest);
932
+ return manifest;
933
+ }
934
+ function initPhaseLabStore(outputDir) {
935
+ const paths = storePaths(outputDir);
936
+ mkdirSync2(paths.windows, { recursive: true });
937
+ if (!existsSync4(paths.events)) writeFileSync2(paths.events, "", "utf8");
938
+ return writeManifest(outputDir);
939
+ }
940
+ function ingestPayloads(storeDir, payloads) {
941
+ initPhaseLabStore(storeDir);
942
+ const sequence = readWindowIndexes(storeDir).length;
943
+ const offset = readEvents(storeDir).length;
944
+ const windowId = `phase-window:${String(sequence).padStart(4, "0")}`;
945
+ const events = payloads.map(
946
+ (item, index2) => eventFromPayload(
947
+ item.payload,
948
+ windowId,
949
+ offset + index2,
950
+ item.path,
951
+ item.sourceKind
952
+ )
953
+ );
954
+ const index = windowIndex(windowId, sequence, events);
955
+ const paths = storePaths(storeDir);
956
+ const append = events.map((event) => JSON.stringify(sortJson(event))).join("\n");
957
+ if (append) {
958
+ writeFileSync2(paths.events, `${append}
959
+ `, { encoding: "utf8", flag: "a" });
960
+ }
961
+ writeJson(join4(paths.windows, windowFileName(windowId)), index);
962
+ writeJson(join4(paths.windows, "latest.json"), index);
963
+ const manifest = writeManifest(storeDir);
964
+ return {
965
+ accepted: events.length > 0,
966
+ content_treated_as_data: true,
967
+ executed_command_count: 0,
968
+ ingested_events: events,
969
+ reasons: [
970
+ "ingested files were stored as inert local data",
971
+ "no embedded command, safe_command, network, repository, or model action was executed"
972
+ ],
973
+ rejected_paths: [],
974
+ report_id: `phase-lab-ingest:${windowId}`,
975
+ settled: false,
976
+ store_manifest: manifest,
977
+ window: index,
978
+ workflow_usable: true
979
+ };
980
+ }
981
+ function ingestPhaseLabReport(storeDir, reportPath) {
982
+ return ingestPayloads(storeDir, [
983
+ { payload: readJsonFile(reportPath, "phase lab report"), path: reportPath }
984
+ ]);
985
+ }
986
+ function ingestPhaseLabPacket(storeDir, packetPath) {
987
+ return ingestPayloads(storeDir, [
988
+ {
989
+ payload: readJsonFile(packetPath, "phase lab packet"),
990
+ path: packetPath,
991
+ sourceKind: "packet-exchange"
992
+ }
993
+ ]);
994
+ }
995
+ function listPhaseLabWindows(storeDir) {
996
+ return {
997
+ settled: false,
998
+ store_manifest: writeManifest(storeDir),
999
+ windows: readWindowIndexes(storeDir)
1000
+ };
1001
+ }
1002
+ function eligibilityBlockers(event) {
1003
+ const joined = [
1004
+ event.source_kind,
1005
+ ...stringList(event.missing_obligations),
1006
+ ...stringList(event.candidate_only_reasons),
1007
+ ...stringList(event.settled_blockers),
1008
+ ...stringList(event.reasons)
1009
+ ].join(" ").toLowerCase();
1010
+ const blockers = [];
1011
+ const markers = {
1012
+ "authority-invalid": [
1013
+ "authority-invalid",
1014
+ "missing authority",
1015
+ "authority"
1016
+ ],
1017
+ "candidate-only": ["candidate-only"],
1018
+ "hash-invalid": ["hash-invalid", "digest mismatch"],
1019
+ "raw-external-volume": ["general-intake", "raw-external"],
1020
+ "rollback-missing": ["rollback", "safe abort"],
1021
+ "salience-obstruction": ["salience", "queue occupation"],
1022
+ stale: ["stale", "expired"],
1023
+ "verification-blocked": [
1024
+ "missing evidence",
1025
+ "missing verifier",
1026
+ "verification"
1027
+ ]
1028
+ };
1029
+ for (const [blocker, needles] of Object.entries(markers)) {
1030
+ if (needles.some((needle) => joined.includes(needle)))
1031
+ blockers.push(blocker);
1032
+ }
1033
+ if (event.candidate_only === true) blockers.push("candidate-only");
1034
+ return dedupeSorted(blockers);
1035
+ }
1036
+ function nodeFromEvent(event) {
1037
+ const blockers = eligibilityBlockers(event);
1038
+ const eligible = event.positive_contribution_allowed === true && blockers.length === 0;
1039
+ const status = eligible ? "accepted" : event.candidate_only === true ? "candidate-only" : "diagnostic";
1040
+ return {
1041
+ accepted: event.accepted === true,
1042
+ content_digest: String(event.content_digest ?? ""),
1043
+ contribution: {
1044
+ candidate_only: !eligible,
1045
+ non_contributing_reason: eligible ? "" : "eligibility blockers prevent positive contribution",
1046
+ positive_contribution: eligible,
1047
+ settled: false,
1048
+ status
1049
+ },
1050
+ eligibility: {
1051
+ accepted_or_certificate_admissible: event.accepted === true,
1052
+ agent_text_not_treated_as_evidence: event.source_kind !== "agent-text-only",
1053
+ authority_valid: !blockers.includes("authority-invalid"),
1054
+ blockers,
1055
+ eligible,
1056
+ hash_valid: !blockers.includes("hash-invalid"),
1057
+ not_raw_external_volume: !blockers.includes("raw-external-volume"),
1058
+ not_registry_metadata_only: event.source_kind !== "registry-metadata",
1059
+ not_salience_blocked: !blockers.includes("salience-obstruction"),
1060
+ not_stale: !blockers.includes("stale"),
1061
+ not_verification_blocked: !blockers.includes("verification-blocked"),
1062
+ residuals_preserved: true,
1063
+ retrievable: Boolean(event.content_digest),
1064
+ rollback_available_or_not_required: !blockers.includes("rollback-missing"),
1065
+ within_validity_domain: true
1066
+ },
1067
+ missing_obligations: stringList(event.missing_obligations),
1068
+ node_id: `node:${String(event.content_digest ?? "").slice(0, 12)}`,
1069
+ operationally_usable: event.operationally_usable === true,
1070
+ reasons: stringList(event.reasons),
1071
+ residual_summary: numericDict(event.residual_summary),
1072
+ schema_hint: String(event.schema_hint ?? "UnknownPICReport"),
1073
+ settled: false,
1074
+ source_event_id: String(event.event_id ?? ""),
1075
+ source_kind: String(event.source_kind ?? "unknown-report"),
1076
+ workflow_usable: event.workflow_usable === true
1077
+ };
1078
+ }
1079
+ function extractEdges(payload) {
1080
+ const edges = [];
1081
+ for (const key of ["edges", "edge_witnesses", "edge_certificates"]) {
1082
+ edges.push(...asRecords(payload[key]));
1083
+ }
1084
+ const registry = asRecord(payload.registry);
1085
+ if (registry) edges.push(...extractEdges(registry));
1086
+ const content = asRecord(payload.content);
1087
+ if (content) edges.push(...extractEdges(content));
1088
+ return edges;
1089
+ }
1090
+ function nodeIdForRef(ref, nodes) {
1091
+ if (!ref) return void 0;
1092
+ return nodes.map((node) => String(node.node_id)).find((nodeId) => {
1093
+ const node = nodes.find((item) => item.node_id === nodeId);
1094
+ return node && [
1095
+ node.node_id,
1096
+ node.content_digest,
1097
+ String(node.content_digest).slice(0, 12),
1098
+ node.source_event_id
1099
+ ].map(String).includes(ref);
1100
+ });
1101
+ }
1102
+ function nodePositive(nodeId, nodes) {
1103
+ const node = nodes.find((item) => item.node_id === nodeId);
1104
+ return asRecord(node?.contribution)?.positive_contribution === true;
1105
+ }
1106
+ function edgesFromEvents(nodes, events) {
1107
+ const edges = [];
1108
+ events.forEach((event, eventIndex) => {
1109
+ const node = nodes[eventIndex];
1110
+ if (!node) return;
1111
+ extractEdges(asRecord(event.payload) ?? {}).forEach((edge, index) => {
1112
+ const sourceIds = stringList(edge.source_packet_ids).map((ref) => nodeIdForRef(ref, nodes)).filter((item) => Boolean(item));
1113
+ const target = nodeIdForRef(String(edge.target_packet_id ?? ""), nodes) ?? String(node.node_id);
1114
+ const evidenceRefs = stringList(edge.evidence_refs);
1115
+ const accepted = edge.accepted === true || event.accepted === true;
1116
+ const evidenceSupported = accepted && evidenceRefs.length > 0;
1117
+ const positive = evidenceSupported && sourceIds.every((source) => nodePositive(source, nodes)) && nodePositive(target, nodes);
1118
+ const edgeId = String(
1119
+ edge.edge_id ?? `edge:${String(node.node_id)}:${index}`
1120
+ );
1121
+ edges.push({
1122
+ accepted,
1123
+ contribution: {
1124
+ candidate_only: !positive,
1125
+ non_contributing_reason: positive ? "" : "edge lacks accepted evidence support",
1126
+ positive_contribution: positive,
1127
+ settled: false,
1128
+ status: positive ? "accepted" : "diagnostic"
1129
+ },
1130
+ edge_id: edgeId,
1131
+ evidence: {
1132
+ edge_certificate_refs: stringList(edge.edge_certificate_refs),
1133
+ evidence_refs: evidenceRefs,
1134
+ evidence_supported: evidenceSupported,
1135
+ missing_evidence: evidenceSupported ? [] : ["edge evidence refs required"],
1136
+ verifier_resolution_refs: stringList(edge.verifier_resolution_refs)
1137
+ },
1138
+ reasons: ["edge extracted from inert report data"],
1139
+ relation_type: String(
1140
+ edge.edge_type ?? edge.relation_type ?? "semantic-dependency"
1141
+ ),
1142
+ residual_summary: numericDict(event.residual_summary),
1143
+ settled: false,
1144
+ source_node_ids: sourceIds.length > 0 ? sourceIds : [String(node.node_id)],
1145
+ target_node_id: target
1146
+ });
1147
+ });
1148
+ });
1149
+ return edges;
1150
+ }
1151
+ function buildEffectivePacketGraph(input) {
1152
+ const events = Array.isArray(input) ? input : Array.isArray(input.events) ? input.events : [];
1153
+ const graphId = Array.isArray(input) ? "effective-packet-graph" : String(input.graph_id ?? "effective-packet-graph");
1154
+ const sourceWindowId = Array.isArray(input) ? "adhoc" : String(input.source_window_id ?? "adhoc");
1155
+ const normalized = events.map(
1156
+ (event, index) => event.event_id ? event : eventFromPayload(event, sourceWindowId, index, void 0, void 0)
1157
+ );
1158
+ const nodes = normalized.map(nodeFromEvent);
1159
+ const edges = edgesFromEvents(nodes, normalized);
1160
+ const nodeCountByStatus = {};
1161
+ for (const node of nodes) {
1162
+ const status = String(asRecord(node.contribution)?.status ?? "diagnostic");
1163
+ nodeCountByStatus[status] = (nodeCountByStatus[status] ?? 0) + 1;
1164
+ }
1165
+ const edgeCountByRelation = {};
1166
+ for (const edge of edges) {
1167
+ const relation = String(edge.relation_type ?? "semantic-dependency");
1168
+ edgeCountByRelation[relation] = (edgeCountByRelation[relation] ?? 0) + 1;
1169
+ }
1170
+ const mergedResidual = {};
1171
+ for (const node of nodes) {
1172
+ for (const [key, value] of Object.entries(
1173
+ numericDict(node.residual_summary)
1174
+ )) {
1175
+ mergedResidual[key] = (mergedResidual[key] ?? 0) + value;
1176
+ }
1177
+ }
1178
+ const acceptedPacketCapital = nodes.filter(
1179
+ (node) => asRecord(node.contribution)?.positive_contribution === true
1180
+ ).length;
1181
+ return {
1182
+ accepted: nodes.length > 0,
1183
+ accepted_packet_capital: acceptedPacketCapital,
1184
+ candidate_only_packets: nodes.filter(
1185
+ (node) => asRecord(node.contribution)?.candidate_only === true
1186
+ ).length,
1187
+ edge_count_by_relation: Object.fromEntries(
1188
+ Object.entries(edgeCountByRelation).sort()
1189
+ ),
1190
+ edges,
1191
+ graph_id: graphId,
1192
+ graph_safety_boundary: GRAPH_SAFETY,
1193
+ missing_edge_evidence: edges.filter(
1194
+ (edge) => edge.accepted === true && asRecord(edge.evidence)?.evidence_supported !== true
1195
+ ).map((edge) => String(edge.edge_id)),
1196
+ node_count_by_status: Object.fromEntries(
1197
+ Object.entries(nodeCountByStatus).sort()
1198
+ ),
1199
+ nodes,
1200
+ non_contributing_volume: nodes.filter(
1201
+ (node) => asRecord(node.contribution)?.positive_contribution !== true
1202
+ ).length,
1203
+ operationally_usable: acceptedPacketCapital > 0,
1204
+ reasons: [
1205
+ "effective graph separates positive contribution from diagnostic volume",
1206
+ "raw packet count does not increase positive phase metrics"
1207
+ ],
1208
+ rejected_or_quarantined_packets: nodes.filter(
1209
+ (node) => ["rejected", "quarantined"].includes(
1210
+ String(asRecord(node.contribution)?.status ?? "")
1211
+ )
1212
+ ).length,
1213
+ residual_summary: {
1214
+ candidate_only_reasons: dedupeSorted(
1215
+ normalized.flatMap((event) => stringList(event.candidate_only_reasons))
1216
+ ),
1217
+ missing_obligation_count: nodes.reduce(
1218
+ (total, node) => total + stringList(node.missing_obligations).length,
1219
+ 0
1220
+ ),
1221
+ residual_debt: residualDebt(mergedResidual),
1222
+ residual_summary: Object.fromEntries(
1223
+ Object.entries(mergedResidual).sort()
1224
+ ),
1225
+ settled_blockers: dedupeSorted(
1226
+ normalized.flatMap((event) => [
1227
+ ...stringList(event.settled_blockers),
1228
+ ...stringList(event.missing_obligations)
1229
+ ])
1230
+ )
1231
+ },
1232
+ semantic_edge_witnesses: edges.map((edge) => asRecord(edge.evidence)).filter(
1233
+ (evidence) => Boolean(evidence?.evidence_supported)
1234
+ ),
1235
+ settled: false,
1236
+ source_window_id: sourceWindowId,
1237
+ stale_or_unsafe_packets: nodes.filter(
1238
+ (node) => stringList(asRecord(node.eligibility)?.blockers).length > 0
1239
+ ).map((node) => String(node.node_id)),
1240
+ workflow_usable: true
1241
+ };
1242
+ }
1243
+ function positiveEdges(graph) {
1244
+ return asRecords(graph.edges).filter(
1245
+ (edge) => asRecord(edge.contribution)?.positive_contribution === true && asRecord(edge.evidence)?.evidence_supported === true
1246
+ );
1247
+ }
1248
+ function observePhaseWindow(window, events, graph) {
1249
+ const effectiveNodeCount = numeric(graph.accepted_packet_capital);
1250
+ const effectiveEdgeCount = positiveEdges(graph).length;
1251
+ const executionAvailablePathCount = detectExecutionAvailablePaths(graph).accepted_path_count;
1252
+ const closureWitnessCount = asRecords(
1253
+ detectAutocatalyticClosure(graph).closure_witnesses
1254
+ ).length;
1255
+ const total = Math.max(1, events.length);
1256
+ const acceptedPacketCount = events.filter(
1257
+ (event) => event.accepted === true
1258
+ ).length;
1259
+ const missingObligationCount = events.reduce(
1260
+ (sum, event) => sum + stringList(event.missing_obligations).length,
1261
+ 0
1262
+ );
1263
+ const residual = numeric(asRecord(graph.residual_summary)?.residual_debt);
1264
+ const candidateOnlyCount = events.filter(
1265
+ (event) => event.candidate_only === true
1266
+ ).length;
1267
+ const observation = {
1268
+ accepted: events.length > 0,
1269
+ accepted_packet_count: acceptedPacketCount,
1270
+ alt_certified_capital_count: events.filter(
1271
+ (event) => String(event.source_kind).includes("alt") && event.positive_contribution_allowed === true
1272
+ ).length,
1273
+ alt_liquidity_candidate_count: events.filter(
1274
+ (event) => String(event.source_kind).includes("alt")
1275
+ ).length,
1276
+ autocatalytic_closure_score: effectiveNodeCount > 0 ? closureWitnessCount / effectiveNodeCount : 0,
1277
+ basin_reachability_proxy: {
1278
+ effective_node_count: effectiveNodeCount,
1279
+ execution_available_path_count: executionAvailablePathCount,
1280
+ reachability_proxy: executionAvailablePathCount / Math.max(1, effectiveNodeCount)
1281
+ },
1282
+ bottleneck_count_by_type: Object.fromEntries(
1283
+ asRecords(graph.nodes).flatMap((node) => stringList(asRecord(node.eligibility)?.blockers)).reduce((map, blocker) => {
1284
+ map.set(blocker, (map.get(blocker) ?? 0) + 1);
1285
+ return map;
1286
+ }, /* @__PURE__ */ new Map()).entries()
1287
+ ),
1288
+ candidate_only_packet_count: candidateOnlyCount,
1289
+ closure_witness_count: closureWitnessCount,
1290
+ components: [
1291
+ {
1292
+ component: "accepted_packet_count",
1293
+ diagnostic_only: false,
1294
+ distance: 0,
1295
+ positive_contribution_source: "effective-graph-only",
1296
+ threshold: 0,
1297
+ value: acceptedPacketCount
1298
+ },
1299
+ {
1300
+ component: "raw_volume",
1301
+ diagnostic_only: true,
1302
+ distance: 0,
1303
+ positive_contribution_source: "diagnostic-only",
1304
+ threshold: 0,
1305
+ value: events.length
1306
+ }
1307
+ ],
1308
+ effective_edge_count: effectiveEdgeCount,
1309
+ effective_node_count: effectiveNodeCount,
1310
+ execution_available_path_count: executionAvailablePathCount,
1311
+ false_liquidity_load: {
1312
+ candidate_count: candidateOnlyCount,
1313
+ certified_count: 0,
1314
+ load: candidateOnlyCount / total
1315
+ },
1316
+ missing_obligation_count: missingObligationCount,
1317
+ observation_id: "phase-window-observation",
1318
+ operationally_usable: effectiveNodeCount > 0,
1319
+ oracle_truth_proven: false,
1320
+ packet_candidate_count: events.length,
1321
+ phase_gap_vector: {
1322
+ closure: Math.max(0, 1 - closureWitnessCount),
1323
+ effective_edges: Math.max(0, 1 - effectiveEdgeCount),
1324
+ effective_nodes: Math.max(0, 1 - effectiveNodeCount),
1325
+ execution_paths: Math.max(0, 1 - executionAvailablePathCount)
1326
+ },
1327
+ physical_truth_proven: false,
1328
+ proves_physical_or_oracle_truth: false,
1329
+ proves_real_asi: false,
1330
+ protocol_relative: true,
1331
+ protocol_relative_only: true,
1332
+ raw_external_volume_diagnostic_only: true,
1333
+ real_asi_proof: false,
1334
+ reasons: [
1335
+ "window observation is protocol-relative only",
1336
+ "raw external volume is diagnostic only"
1337
+ ],
1338
+ residual_debt: residual,
1339
+ salience_obstruction_load: {
1340
+ blocked_count: candidateOnlyCount,
1341
+ load: candidateOnlyCount / total,
1342
+ total_count: events.length
1343
+ },
1344
+ settled: false,
1345
+ settled_packet_count: 0,
1346
+ threshold_distance: Math.max(0, 1 - effectiveNodeCount) + Math.max(0, 1 - effectiveEdgeCount) + Math.max(0, 1 - closureWitnessCount) + Math.max(0, 1 - executionAvailablePathCount),
1347
+ verification_backlog: missingObligationCount,
1348
+ verification_throughput: {
1349
+ accepted_count: acceptedPacketCount,
1350
+ backlog_count: missingObligationCount,
1351
+ throughput_ratio: acceptedPacketCount / total
1352
+ },
1353
+ waste_load: {
1354
+ load: numeric(graph.non_contributing_volume) / total,
1355
+ non_contributing_volume: numeric(graph.non_contributing_volume),
1356
+ total_volume: events.length
1357
+ },
1358
+ window: {
1359
+ event_count: numeric(window.event_count),
1360
+ event_ids: stringList(window.event_ids),
1361
+ sequence: numeric(window.sequence),
1362
+ window_id: String(window.window_id ?? "phase-window")
1363
+ },
1364
+ workflow_usable: true,
1365
+ workflow_usable_packet_count: events.filter(
1366
+ (event) => event.workflow_usable === true
1367
+ ).length
1368
+ };
1369
+ return observation;
1370
+ }
1371
+ function comparePhaseWindows(baseline, candidate) {
1372
+ const metricDelta = {
1373
+ closure_witness_count: numeric(candidate.closure_witness_count) - numeric(baseline.closure_witness_count),
1374
+ effective_edge_count: numeric(candidate.effective_edge_count) - numeric(baseline.effective_edge_count),
1375
+ effective_node_count: numeric(candidate.effective_node_count) - numeric(baseline.effective_node_count),
1376
+ execution_available_path_count: numeric(candidate.execution_available_path_count) - numeric(baseline.execution_available_path_count),
1377
+ residual_debt: numeric(candidate.residual_debt) - numeric(baseline.residual_debt)
1378
+ };
1379
+ return {
1380
+ accepted: true,
1381
+ baseline_window_id: String(asRecord(baseline.window)?.window_id ?? ""),
1382
+ candidate_window_id: String(asRecord(candidate.window)?.window_id ?? ""),
1383
+ comparison_id: "phase-window-comparison",
1384
+ diagnostic_only_components: ["packet_candidate_count", "raw_volume"],
1385
+ metric_delta: metricDelta,
1386
+ positive_progress_components: Object.entries(metricDelta).filter(([key, value]) => key !== "residual_debt" && value > 0).map(([key]) => key),
1387
+ reasons: ["comparison preserves protocol-relative diagnostic status"],
1388
+ settled: false,
1389
+ workflow_usable: true
1390
+ };
1391
+ }
1392
+ function detectAutocatalyticClosure(graph) {
1393
+ const closureWitnesses = [];
1394
+ const defects = [];
1395
+ for (const edge of positiveEdges(graph)) {
1396
+ const sources = stringList(edge.source_node_ids);
1397
+ const target = String(edge.target_node_id ?? "");
1398
+ if (sources.includes(target)) {
1399
+ const witnessId = `closure-witness:${String(edge.edge_id)}`;
1400
+ closureWitnesses.push({
1401
+ accepted: true,
1402
+ edge_ids: [String(edge.edge_id)],
1403
+ evidence_supported: true,
1404
+ execution_available: false,
1405
+ packet_ids: dedupeSorted([...sources, target]),
1406
+ productive: true,
1407
+ protocol_relative_only: true,
1408
+ reasons: [
1409
+ "witness is evidence-supported within the effective graph",
1410
+ "witness remains diagnostic until finite threshold checks pass"
1411
+ ],
1412
+ settled: false,
1413
+ witness_id: witnessId,
1414
+ witness_kind: "autocatalytic-closure"
1415
+ });
1416
+ }
1417
+ }
1418
+ for (const edge of asRecords(graph.edges)) {
1419
+ if (edge.accepted === true && asRecord(edge.evidence)?.evidence_supported !== true) {
1420
+ defects.push({
1421
+ defect_id: `closure-defect:${String(edge.edge_id)}`,
1422
+ defect_type: "missing-edge-evidence",
1423
+ packet_or_edge_id: String(edge.edge_id),
1424
+ residual_preserved: true
1425
+ });
1426
+ }
1427
+ }
1428
+ const status = closureWitnesses.length > 0 && defects.length === 0 ? "candidate" : "abstain";
1429
+ return {
1430
+ accepted: status === "candidate",
1431
+ certificate_candidate: {
1432
+ abstention_reasons: closureWitnesses.length > 0 ? [] : [
1433
+ {
1434
+ missing_evidence_refs: [],
1435
+ reason: "closure requires evidence-supported accepted edges",
1436
+ reason_id: "closure-abstain:no-evidence-supported-cycle"
1437
+ }
1438
+ ],
1439
+ accepted: status === "candidate",
1440
+ certificate_id: "closure-certificate-candidate",
1441
+ certificate_status: status,
1442
+ defects,
1443
+ reasons: [
1444
+ "closure candidate is not automatically settled",
1445
+ "candidate-only cycles do not count"
1446
+ ],
1447
+ settled: false,
1448
+ witness_ids: closureWitnesses.map(
1449
+ (witness) => String(witness.witness_id)
1450
+ )
1451
+ },
1452
+ closure_score: closureWitnesses.length / Math.max(1, asRecords(graph.nodes).length),
1453
+ closure_witnesses: closureWitnesses,
1454
+ defects,
1455
+ executable_witnesses: [],
1456
+ graph_id: String(graph.graph_id ?? "effective-packet-graph"),
1457
+ operationally_usable: status === "candidate",
1458
+ productive_witnesses: closureWitnesses.map((witness) => ({
1459
+ accepted: true,
1460
+ packet_ids: witness.packet_ids,
1461
+ productive_edge_ids: witness.edge_ids,
1462
+ productivity_lower_bound: 0.1,
1463
+ reasons: [
1464
+ "self-supporting evidence edge is productive in declared scope"
1465
+ ],
1466
+ settled: false,
1467
+ witness_id: `productive:${String(witness.witness_id)}`
1468
+ })),
1469
+ reasons: ["closure detection does not execute or settle paths"],
1470
+ report_id: "autocatalytic-closure-report",
1471
+ settled: false,
1472
+ support_hyperpaths: [],
1473
+ workflow_usable: true
1474
+ };
1475
+ }
1476
+ function detectExecutionAvailablePaths(graph) {
1477
+ const paths = positiveEdges(graph).map((edge) => {
1478
+ const pathId = `execution-path:${String(edge.edge_id)}`;
1479
+ const reasons = [
1480
+ "execution authority is not granted by PIC-TS",
1481
+ "receiver context and action boundary remain diagnostic"
1482
+ ];
1483
+ return {
1484
+ accepted: false,
1485
+ action_boundary_requirements: [
1486
+ {
1487
+ requirement_id: `${pathId}:authority`,
1488
+ requirement_type: "explicit-scope-bounded-authority",
1489
+ residual: "host runtime authority required",
1490
+ satisfied: false
1491
+ }
1492
+ ],
1493
+ authority_status: {
1494
+ authority_status: "not-granted",
1495
+ explicit_scope_bounded: false,
1496
+ grants_execution: false,
1497
+ reasons
1498
+ },
1499
+ blocked: true,
1500
+ candidate_only: true,
1501
+ edge_ids: [String(edge.edge_id)],
1502
+ not_executed: true,
1503
+ packet_ids: dedupeSorted([
1504
+ ...stringList(edge.source_node_ids),
1505
+ String(edge.target_node_id ?? "")
1506
+ ]),
1507
+ path_id: pathId,
1508
+ reasons,
1509
+ receiver_context: {
1510
+ evidence_refs: [],
1511
+ present: false,
1512
+ receiver_context_id: "receiver-context:missing"
1513
+ },
1514
+ settled: false,
1515
+ witness: {
1516
+ accepted: false,
1517
+ edge_ids: [String(edge.edge_id)],
1518
+ packet_ids: dedupeSorted([
1519
+ ...stringList(edge.source_node_ids),
1520
+ String(edge.target_node_id ?? "")
1521
+ ]),
1522
+ reasons,
1523
+ settled: false,
1524
+ witness_id: `execution-witness:${String(edge.edge_id)}`
1525
+ }
1526
+ };
1527
+ });
1528
+ return {
1529
+ accepted: paths.length > 0,
1530
+ accepted_path_count: 0,
1531
+ authority_requirements: ["explicit-scope-bounded-authority"],
1532
+ blocked_path_count: paths.length,
1533
+ blocker_reason_by_path: Object.fromEntries(
1534
+ paths.map((path) => [String(path.path_id), stringList(path.reasons)])
1535
+ ),
1536
+ candidate_only_path_count: paths.length,
1537
+ executed_path_count: 0,
1538
+ execution_authority_granted: false,
1539
+ graph_id: String(graph.graph_id ?? "effective-packet-graph"),
1540
+ operationally_usable: false,
1541
+ path_count: paths.length,
1542
+ path_density: 0,
1543
+ paths,
1544
+ reasons: ["execution-available path detection never executes paths"],
1545
+ report_id: "execution-available-path-density",
1546
+ residual_carry_forward: stringList(
1547
+ asRecord(graph.residual_summary)?.settled_blockers
1548
+ ),
1549
+ rollback_requirements: ["rollback-or-safe-abort"],
1550
+ settled: false,
1551
+ workflow_usable: true
1552
+ };
1553
+ }
1554
+ function buildPhaseThresholdStatus(observation, threshold) {
1555
+ const pathDensity = numeric(
1556
+ asRecord(observation.basin_reachability_proxy)?.reachability_proxy
1557
+ );
1558
+ const checks = {
1559
+ maximum_false_liquidity_load: numeric(asRecord(observation.false_liquidity_load)?.load) <= numeric(threshold.maximum_false_liquidity_load ?? 0.5),
1560
+ maximum_residual_debt: numeric(observation.residual_debt) <= numeric(threshold.maximum_residual_debt ?? 0),
1561
+ maximum_salience_obstruction: numeric(asRecord(observation.salience_obstruction_load)?.load) <= numeric(threshold.maximum_salience_obstruction ?? 0.5),
1562
+ minimum_accepted_packet_count: numeric(observation.accepted_packet_count) >= numeric(threshold.minimum_accepted_packet_count ?? 1),
1563
+ minimum_alt_to_ecpt_lift_count: numeric(observation.alt_certified_capital_count) >= numeric(threshold.minimum_alt_to_ecpt_lift_count ?? 0),
1564
+ minimum_closure_witness_count: numeric(observation.closure_witness_count) >= numeric(threshold.minimum_closure_witness_count ?? 1),
1565
+ minimum_effective_edge_count: numeric(observation.effective_edge_count) >= numeric(threshold.minimum_effective_edge_count ?? 1),
1566
+ minimum_execution_available_path_density: pathDensity >= numeric(threshold.minimum_execution_available_path_density ?? 0.1),
1567
+ minimum_verification_throughput: numeric(
1568
+ asRecord(observation.verification_throughput)?.throughput_ratio
1569
+ ) >= numeric(threshold.minimum_verification_throughput ?? 0.1)
1570
+ };
1571
+ const failed = Object.entries(checks).filter(([, passed]) => !passed).map(([key]) => key).sort();
1572
+ const status = failed.length === 0 ? "candidate" : "abstain";
1573
+ return {
1574
+ accepted: status === "candidate",
1575
+ abstention_reasons: failed.map(
1576
+ (component) => `missing finite threshold component: ${component}`
1577
+ ),
1578
+ certificate_status: status,
1579
+ component_status: Object.fromEntries(Object.entries(checks).sort()),
1580
+ failed_components: failed,
1581
+ oracle_truth_proven: false,
1582
+ physical_truth_proven: false,
1583
+ protocol_relative: true,
1584
+ protocol_relative_only: true,
1585
+ real_asi_proof: false,
1586
+ reasons: [
1587
+ "threshold status is protocol-relative only",
1588
+ "threshold status does not prove real ASI"
1589
+ ],
1590
+ rejection_reasons: [],
1591
+ settled: false,
1592
+ status_id: "asi-proxy-threshold-status",
1593
+ threshold,
1594
+ threshold_distance: failed.length,
1595
+ observation
1596
+ };
1597
+ }
1598
+ function buildCollectivePhaseCertificateCandidate(thresholdStatus, graph) {
1599
+ const status = String(thresholdStatus.certificate_status ?? "abstain");
1600
+ const defects = stringList(thresholdStatus.failed_components).map(
1601
+ (component) => ({
1602
+ component,
1603
+ defect_id: `phase-defect:${component}`,
1604
+ defect_type: "threshold-component-missing",
1605
+ required_remediation: `provide finite evidence for ${component}`,
1606
+ residual_preserved: true
1607
+ })
1608
+ );
1609
+ return {
1610
+ accepted: status === "candidate",
1611
+ abstention_report: status === "candidate" ? null : {
1612
+ defects,
1613
+ protocol_relative_only: true,
1614
+ reasons: ["certificate abstains when finite evidence is missing"],
1615
+ report_id: "collective-phase-abstention",
1616
+ settled: false,
1617
+ threshold_status: thresholdStatus
1618
+ },
1619
+ certificate_id: "collective-phase-certificate-candidate",
1620
+ certificate_status: status,
1621
+ defects,
1622
+ execution_authority_granted: false,
1623
+ finite_requirements_passed: status === "candidate",
1624
+ graph_id: String(graph.graph_id ?? ""),
1625
+ observation_id: String(
1626
+ asRecord(thresholdStatus.observation)?.observation_id ?? ""
1627
+ ),
1628
+ operationally_usable: status === "candidate",
1629
+ oracle_truth_proven: false,
1630
+ physical_truth_proven: false,
1631
+ protocol_relative_only: true,
1632
+ proves_physical_or_oracle_truth: false,
1633
+ proves_real_asi: false,
1634
+ reasons: [
1635
+ "certificate candidate is protocol-relative only",
1636
+ "certificate candidate does not prove real ASI",
1637
+ "certificate candidate does not settle diagnostic reports"
1638
+ ],
1639
+ settled: false,
1640
+ threshold_status: thresholdStatus,
1641
+ workflow_usable: true
1642
+ };
1643
+ }
1644
+ function loadPhaseLabObservation(storeDir, window = "latest") {
1645
+ const selected = selectWindow(storeDir, window);
1646
+ const graph = buildEffectivePacketGraph({
1647
+ events: selected.events,
1648
+ graph_id: `effective-graph:${String(selected.index.window_id ?? "window")}`,
1649
+ source_window_id: String(selected.index.window_id ?? "window")
1650
+ });
1651
+ return {
1652
+ observation: observePhaseWindow(selected.index, selected.events, graph),
1653
+ graph
1654
+ };
1655
+ }
1656
+ function loadPhaseLabGraph(storeDir, window = "all") {
1657
+ const selected = selectWindow(storeDir, window);
1658
+ return buildEffectivePacketGraph({
1659
+ events: selected.events,
1660
+ graph_id: `effective-graph:${String(selected.index.window_id ?? "window")}`,
1661
+ source_window_id: String(selected.index.window_id ?? "window")
1662
+ });
1663
+ }
1664
+ function exportPhaseLabStore(storeDir, outputDir) {
1665
+ mkdirSync2(outputDir, { recursive: true });
1666
+ const manifest = writeManifest(storeDir);
1667
+ const events = readEvents(storeDir);
1668
+ const graph = buildEffectivePacketGraph({
1669
+ events,
1670
+ graph_id: "phase-lab-export-effective-graph",
1671
+ source_window_id: String(manifest.latest_window_id ?? "adhoc")
1672
+ });
1673
+ const files = [];
1674
+ const write = (name, data) => {
1675
+ writeJson(join4(outputDir, name), data);
1676
+ files.push(name);
1677
+ };
1678
+ write("manifest.json", manifest);
1679
+ write("events.json", {
1680
+ absolute_paths_sanitized: true,
1681
+ events,
1682
+ settled: false
1683
+ });
1684
+ write("effective_graph.json", graph);
1685
+ write("windows.json", {
1686
+ settled: false,
1687
+ windows: readWindowIndexes(storeDir)
1688
+ });
1689
+ if (events.length > 0) {
1690
+ const { observation } = loadPhaseLabObservation(storeDir, "latest");
1691
+ write("phase_window_observation.json", observation);
1692
+ }
1693
+ return {
1694
+ accepted: true,
1695
+ absolute_paths_sanitized: true,
1696
+ export_id: "phase-lab-export",
1697
+ files: files.sort(),
1698
+ output_dir: basename2(outputDir),
1699
+ reasons: ["phase lab export sanitizes local paths and preserves residuals"],
1700
+ settled: false,
1701
+ store_manifest: manifest
1702
+ };
1703
+ }
1704
+
1705
+ // src/bit_engine/index.ts
1706
+ var BOTTLENECK_CLASSES = [
1707
+ "missing_evidence",
1708
+ "missing_verifier_route",
1709
+ "missing_semantic_edge",
1710
+ "missing_rollback_support",
1711
+ "missing_authority",
1712
+ "missing_receiver_context",
1713
+ "identity_sybil_blocker",
1714
+ "stale_packet",
1715
+ "false_liquidity_blocker",
1716
+ "salience_obstruction",
1717
+ "queue_occupation",
1718
+ "missing_alt_lift",
1719
+ "trace_boundary_mismatch",
1720
+ "external_domain_obligation"
1721
+ ];
1722
+ function record(value) {
1723
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1724
+ }
1725
+ function records(value) {
1726
+ return Array.isArray(value) ? value.filter((item) => Boolean(record(item))) : [];
1727
+ }
1728
+ function strings(value) {
1729
+ if (Array.isArray(value)) return value.map(String).sort();
1730
+ if (value === void 0 || value === null) return [];
1731
+ return [String(value)];
1732
+ }
1733
+ function classForBlocker(blocker) {
1734
+ const normalized = blocker.replaceAll("-", "_");
1735
+ if (BOTTLENECK_CLASSES.includes(normalized)) return normalized;
1736
+ if (normalized.includes("evidence")) return "missing_evidence";
1737
+ if (normalized.includes("verification")) return "missing_verifier_route";
1738
+ if (normalized.includes("edge")) return "missing_semantic_edge";
1739
+ if (normalized.includes("rollback")) return "missing_rollback_support";
1740
+ if (normalized.includes("authority")) return "missing_authority";
1741
+ if (normalized.includes("receiver")) return "missing_receiver_context";
1742
+ if (normalized.includes("stale")) return "stale_packet";
1743
+ if (normalized.includes("salience")) return "salience_obstruction";
1744
+ if (normalized.includes("external")) return "external_domain_obligation";
1745
+ return "external_domain_obligation";
1746
+ }
1747
+ function minimalConditions(bottleneckId, bottleneckClass) {
1748
+ return [
1749
+ {
1750
+ condition_id: `mec:${bottleneckId}:evidence`,
1751
+ condition_kind: "finite-evidence",
1752
+ description: `provide finite evidence for ${bottleneckClass}`,
1753
+ execution_authority_granted: false,
1754
+ settled: false
1755
+ },
1756
+ {
1757
+ condition_id: `mec:${bottleneckId}:audit`,
1758
+ condition_kind: "post-check-audit",
1759
+ description: "preserve residuals and rerun the relevant checker",
1760
+ execution_authority_granted: false,
1761
+ settled: false
1762
+ }
1763
+ ];
1764
+ }
1765
+ function diagnoseBottlenecks(graph) {
1766
+ const diagnoses = [];
1767
+ for (const node of records(graph.nodes)) {
1768
+ for (const blocker of strings(record(node.eligibility)?.blockers)) {
1769
+ const bottleneckClass = classForBlocker(blocker);
1770
+ const bottleneckId = `bottleneck:${String(node.node_id)}:${bottleneckClass}`;
1771
+ diagnoses.push({
1772
+ accepted: true,
1773
+ bottleneck_class: bottleneckClass,
1774
+ bottleneck_id: bottleneckId,
1775
+ capability_expression_paths: [
1776
+ {
1777
+ accepted: false,
1778
+ path_id: `capability-path:${String(node.node_id)}`,
1779
+ reasons: [`blocked by ${blocker}`],
1780
+ settled: false
1781
+ }
1782
+ ],
1783
+ minimal_enabling_conditions: minimalConditions(
1784
+ bottleneckId,
1785
+ bottleneckClass
1786
+ ),
1787
+ node_id: String(node.node_id ?? ""),
1788
+ reasons: [`effective graph node is blocked by ${blocker}`],
1789
+ settled: false
1790
+ });
1791
+ }
1792
+ }
1793
+ for (const edgeId of strings(graph.missing_edge_evidence)) {
1794
+ const bottleneckId = `bottleneck:${edgeId}:missing_semantic_edge`;
1795
+ diagnoses.push({
1796
+ accepted: true,
1797
+ bottleneck_class: "missing_semantic_edge",
1798
+ bottleneck_id: bottleneckId,
1799
+ edge_id: edgeId,
1800
+ minimal_enabling_conditions: minimalConditions(
1801
+ bottleneckId,
1802
+ "missing_semantic_edge"
1803
+ ),
1804
+ reasons: ["edge lacks semantic evidence"],
1805
+ settled: false
1806
+ });
1807
+ }
1808
+ return {
1809
+ accepted: true,
1810
+ bottleneck_count: diagnoses.length,
1811
+ bottlenecks: diagnoses.sort(
1812
+ (a, b) => String(a.bottleneck_id).localeCompare(String(b.bottleneck_id))
1813
+ ),
1814
+ execution_authority_granted: false,
1815
+ graph_id: String(graph.graph_id ?? ""),
1816
+ report_id: "bottleneck-inversion-report",
1817
+ settled: false,
1818
+ workflow_usable: true
1819
+ };
1820
+ }
1821
+ function buildMinimalEnablingConditions(bottleneckId, report) {
1822
+ const found = records(report?.bottlenecks).find(
1823
+ (item) => item.bottleneck_id === bottleneckId
1824
+ );
1825
+ if (found) return records(found.minimal_enabling_conditions);
1826
+ return minimalConditions(bottleneckId, "external_domain_obligation");
1827
+ }
1828
+ function invertBottlenecks(report) {
1829
+ const candidates = records(report.bottlenecks).map((bottleneck, index) => {
1830
+ const bottleneckId = String(
1831
+ bottleneck.bottleneck_id ?? `bottleneck:${index}`
1832
+ );
1833
+ const bottleneckClass = String(
1834
+ bottleneck.bottleneck_class ?? "external_domain_obligation"
1835
+ );
1836
+ return {
1837
+ accepted: true,
1838
+ bottleneck_class: bottleneckClass,
1839
+ bottleneck_id: bottleneckId,
1840
+ candidate_id: `inversion-candidate:${bottleneckId}`,
1841
+ expected_activation_gain: {
1842
+ gain_lower_bound: bottleneckClass === "missing_semantic_edge" ? 0.2 : 0.1,
1843
+ protocol_relative_only: true
1844
+ },
1845
+ execution_authority_granted: false,
1846
+ minimal_enabling_conditions: buildMinimalEnablingConditions(
1847
+ bottleneckId,
1848
+ report
1849
+ ),
1850
+ post_inversion_audit_plan: {
1851
+ audit_steps: ["rerun graph", "rerun observation", "preserve residuals"],
1852
+ settled: false
1853
+ },
1854
+ reasons: ["inversion candidate is recommendation-only"],
1855
+ risk_hazard_authority_notes: [
1856
+ "host runtime authority required before external effects"
1857
+ ],
1858
+ rollback_or_deactivation_plan: {
1859
+ plan_id: `rollback:${bottleneckId}`,
1860
+ required: true,
1861
+ settled: false
1862
+ },
1863
+ settled: false,
1864
+ verification_cost: 1,
1865
+ why_not_settled: "minimal enabling conditions are not discharged"
1866
+ };
1867
+ });
1868
+ return {
1869
+ accepted: true,
1870
+ candidate_count: candidates.length,
1871
+ candidates,
1872
+ execution_authority_granted: false,
1873
+ report_id: "bottleneck-inversion-candidates",
1874
+ settled: false,
1875
+ workflow_usable: true
1876
+ };
1877
+ }
1878
+ function buildInversionCertificate(candidate) {
1879
+ const selected = records(candidate.inversion_candidates)[0] ?? records(candidate.candidates)[0] ?? candidate;
1880
+ return {
1881
+ accepted: selected.accepted === true,
1882
+ candidate: selected,
1883
+ certificate_id: `inversion-certificate:${String(selected.candidate_id ?? "candidate")}`,
1884
+ certificate_status: "candidate",
1885
+ execution_authority_granted: false,
1886
+ finite_requirements_passed: false,
1887
+ reasons: [
1888
+ "inversion certificate is a candidate only",
1889
+ "post-inversion audit remains required"
1890
+ ],
1891
+ settled: false,
1892
+ workflow_usable: true
1893
+ };
1894
+ }
1895
+ function compareBottleneckBaseline(baseline, candidate) {
1896
+ const delta = {
1897
+ closure_witness_count: Number(candidate.closure_witness_count ?? 0) - Number(baseline.closure_witness_count ?? 0),
1898
+ effective_edge_count: Number(candidate.effective_edge_count ?? 0) - Number(baseline.effective_edge_count ?? 0),
1899
+ effective_node_count: Number(candidate.effective_node_count ?? 0) - Number(baseline.effective_node_count ?? 0),
1900
+ residual_debt: Number(candidate.residual_debt ?? 0) - Number(baseline.residual_debt ?? 0)
1901
+ };
1902
+ return {
1903
+ accepted: true,
1904
+ activation_gain_estimate: delta,
1905
+ execution_authority_granted: false,
1906
+ report_id: "bottleneck-baseline-comparison",
1907
+ settled: false,
1908
+ workflow_usable: true
1909
+ };
1910
+ }
1911
+
1912
+ // src/sqot_controller/index.ts
1913
+ function record2(value) {
1914
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1915
+ }
1916
+ function records2(value) {
1917
+ return Array.isArray(value) ? value.filter((item) => Boolean(record2(item))) : [];
1918
+ }
1919
+ function strings2(value) {
1920
+ if (Array.isArray(value)) return value.map(String).sort();
1921
+ if (value === void 0 || value === null) return [];
1922
+ return [String(value)];
1923
+ }
1924
+ function graphNodes(graph) {
1925
+ return records2(graph.nodes);
1926
+ }
1927
+ function candidateNodes(graph) {
1928
+ return graphNodes(graph).filter(
1929
+ (node) => record2(node.contribution)?.positive_contribution !== true
1930
+ );
1931
+ }
1932
+ function diagnoseQueueOccupation(graph, attentionBudget = 1) {
1933
+ const nodes = graphNodes(graph);
1934
+ const candidates = candidateNodes(graph);
1935
+ const occupied = nodes.length === 0 ? 0 : candidates.length / nodes.length;
1936
+ return {
1937
+ accepted: true,
1938
+ attention_budget_ledger: {
1939
+ attention_budget: attentionBudget,
1940
+ occupied,
1941
+ occupied_by_candidate_only: candidates.length,
1942
+ settled: false
1943
+ },
1944
+ candidate_only_count: candidates.length,
1945
+ execution_authority_granted: false,
1946
+ graph_id: String(graph.graph_id ?? ""),
1947
+ queue_occupation: occupied,
1948
+ report_id: "queue-occupation-report",
1949
+ settled: false,
1950
+ verification_queue_pressure: {
1951
+ missing_obligation_count: Number(
1952
+ record2(graph.residual_summary)?.missing_obligation_count ?? 0
1953
+ ),
1954
+ pressure: occupied,
1955
+ settled: false
1956
+ },
1957
+ workflow_usable: true
1958
+ };
1959
+ }
1960
+ function diagnoseSalienceObstruction(graph) {
1961
+ const blocked = graphNodes(graph).filter(
1962
+ (node) => strings2(record2(node.eligibility)?.blockers).some(
1963
+ (blocker) => [
1964
+ "candidate-only",
1965
+ "salience-obstruction",
1966
+ "stale",
1967
+ "raw-external-volume"
1968
+ ].includes(blocker)
1969
+ )
1970
+ );
1971
+ return {
1972
+ accepted: true,
1973
+ blocked_packet_ids: blocked.map((node) => String(node.node_id)),
1974
+ execution_authority_granted: false,
1975
+ graph_id: String(graph.graph_id ?? ""),
1976
+ obstruction_count: blocked.length,
1977
+ reasons: [
1978
+ "salience obstruction is diagnostic and does not mutate queue state"
1979
+ ],
1980
+ report_id: "salience-obstruction-diagnosis",
1981
+ settled: false,
1982
+ workflow_usable: true
1983
+ };
1984
+ }
1985
+ function buildQueueRebalancePlan(graph) {
1986
+ const actions = graphNodes(graph).map((node) => {
1987
+ const blockers = strings2(record2(node.eligibility)?.blockers);
1988
+ const action = blockers.length > 0 ? "preserve_residual" : "inspect";
1989
+ return {
1990
+ action,
1991
+ applied: false,
1992
+ deletes_packet: false,
1993
+ node_id: String(node.node_id ?? ""),
1994
+ reasons: blockers,
1995
+ settled: false
1996
+ };
1997
+ });
1998
+ return {
1999
+ accepted: true,
2000
+ actions,
2001
+ applied_action_count: 0,
2002
+ execution_authority_granted: false,
2003
+ graph_id: String(graph.graph_id ?? ""),
2004
+ plan_id: "queue-rebalance-plan",
2005
+ recommended_action_count: actions.length,
2006
+ settled: false,
2007
+ workflow_usable: true
2008
+ };
2009
+ }
2010
+ function buildPacketQuarantineDecisions(graph) {
2011
+ const decisions = candidateNodes(graph).map((node) => ({
2012
+ applied: false,
2013
+ decision: "quarantine",
2014
+ deletes_packet: false,
2015
+ node_id: String(node.node_id ?? ""),
2016
+ reasons: strings2(record2(node.eligibility)?.blockers),
2017
+ reversible: true,
2018
+ settled: false
2019
+ }));
2020
+ return {
2021
+ accepted: true,
2022
+ applied: false,
2023
+ deletes_packets: false,
2024
+ execution_authority_granted: false,
2025
+ quarantine_decisions: decisions,
2026
+ settled: false,
2027
+ workflow_usable: true
2028
+ };
2029
+ }
2030
+ function checkDiagnosticReserve(graph, attentionBudget = 1) {
2031
+ const queue = diagnoseQueueOccupation(graph, attentionBudget);
2032
+ const occupied = Number(queue.queue_occupation ?? 0);
2033
+ const reserveFraction = Math.max(0, 1 - occupied);
2034
+ return {
2035
+ accepted: true,
2036
+ diagnostic_reserve_available: reserveFraction > 0.1,
2037
+ execution_authority_granted: false,
2038
+ minimum_reserve_fraction: 0.1,
2039
+ reasons: reserveFraction > 0.1 ? ["diagnostic reserve remains available"] : ["diagnostic reserve is below threshold"],
2040
+ report_id: "diagnostic-reserve-report",
2041
+ reserve_fraction: reserveFraction,
2042
+ settled: false,
2043
+ workflow_usable: true
2044
+ };
2045
+ }
2046
+
2047
+ // src/alt_lift/index.ts
2048
+ function record3(value) {
2049
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2050
+ }
2051
+ function records3(value) {
2052
+ return Array.isArray(value) ? value.filter((item) => Boolean(record3(item))) : [];
2053
+ }
2054
+ function packetId(packet) {
2055
+ return String(
2056
+ packet.packet_id ?? packet.report_id ?? packet.decision_id ?? "alt-packet"
2057
+ );
2058
+ }
2059
+ function graphHasCapital(graph) {
2060
+ return Number(graph.accepted_packet_capital ?? 0) > 0;
2061
+ }
2062
+ function verifyAltEcptLift(packets, graph) {
2063
+ const positive = packets.filter(
2064
+ (packet) => packet.accepted === true && packet.positive_ecpt_component_lift === true && graphHasCapital(graph)
2065
+ );
2066
+ return {
2067
+ accepted: true,
2068
+ blockers: positive.length > 0 ? [] : [
2069
+ {
2070
+ blocker_id: "alt-lift:no-positive-ecpt-component",
2071
+ blocker_type: "missing_alt_lift",
2072
+ residual_preserved: true
2073
+ }
2074
+ ],
2075
+ candidate_packet_count: packets.length,
2076
+ capital_to_path_contributions: positive.map((packet) => ({
2077
+ contribution_id: `capital-to-path:${packetId(packet)}`,
2078
+ packet_id: packetId(packet),
2079
+ positive_path_contribution: false,
2080
+ settled: false
2081
+ })),
2082
+ execution_authority_granted: false,
2083
+ graph_id: String(graph.graph_id ?? ""),
2084
+ lift_status: positive.length > 0 ? "candidate" : "diagnostic_only",
2085
+ positive_ecpt_component_lift: positive.length > 0,
2086
+ promotes_to_ecpt_capital: false,
2087
+ reasons: [
2088
+ "ALT liquidity does not automatically become ECPT packet capital",
2089
+ "lift report is protocol-relative and diagnostic"
2090
+ ],
2091
+ report_id: "alt-ecpt-lift-report",
2092
+ settled: false,
2093
+ workflow_usable: true
2094
+ };
2095
+ }
2096
+ function verifyReceiverLift(packet, receiverContext) {
2097
+ const present = receiverContext.accepted === true || receiverContext.present === true;
2098
+ return {
2099
+ accepted: true,
2100
+ execution_authority_granted: false,
2101
+ packet_id: packetId(packet),
2102
+ receiver_context_present: present,
2103
+ receiver_lift_status: present ? "candidate" : "diagnostic_only",
2104
+ reasons: present ? ["receiver context is present but does not settle lift"] : ["receiver context is missing or not accepted"],
2105
+ settled: false,
2106
+ workflow_usable: true
2107
+ };
2108
+ }
2109
+ function mapLiquidityToPaths(packet, graph) {
2110
+ const pathCount = records3(graph.edges).filter(
2111
+ (edge) => edge.accepted === true
2112
+ ).length;
2113
+ return {
2114
+ accepted: true,
2115
+ execution_authority_granted: false,
2116
+ mapped_path_count: 0,
2117
+ packet_id: packetId(packet),
2118
+ positive_path_contribution: false,
2119
+ reasons: [
2120
+ `observed ${pathCount} graph edges`,
2121
+ "liquidity-to-path mapping is diagnostic-only until execution path rules pass"
2122
+ ],
2123
+ settled: false,
2124
+ workflow_usable: true
2125
+ };
2126
+ }
2127
+ function estimateCapitalImpact(reports) {
2128
+ const positive = reports.filter(
2129
+ (report) => report.positive_ecpt_component_lift === true
2130
+ ).length;
2131
+ return {
2132
+ accepted: true,
2133
+ estimated_positive_lift_count: positive,
2134
+ execution_authority_granted: false,
2135
+ false_liquidity_risk: reports.length - positive,
2136
+ report_count: reports.length,
2137
+ report_id: "alt-capital-impact",
2138
+ settled: false,
2139
+ workflow_usable: true
2140
+ };
2141
+ }
2142
+
2143
+ // src/trc_adapter/index.ts
2144
+ function record4(value) {
2145
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2146
+ }
2147
+ function records4(value) {
2148
+ return Array.isArray(value) ? value.filter((item) => Boolean(record4(item))) : [];
2149
+ }
2150
+ function eventsFromTrace(input) {
2151
+ return records4(input.events).length > 0 ? records4(input.events) : records4(input.tool_calls).length > 0 ? records4(input.tool_calls) : [input];
2152
+ }
2153
+ function adaptTrcTrace(input) {
2154
+ const events = eventsFromTrace(input);
2155
+ const typedEvents = events.map((event, index) => ({
2156
+ action_kind: String(
2157
+ event.action_kind ?? event.type ?? event.name ?? "agent-event"
2158
+ ),
2159
+ authority_status: String(event.authority_status ?? "not-granted"),
2160
+ event_id: String(event.event_id ?? `trace-event:${index}`),
2161
+ evidence_refs: Array.isArray(event.evidence_refs) ? event.evidence_refs.map(String) : [],
2162
+ receiver: String(
2163
+ event.receiver ?? event.receiver_agent_id ?? "unknown-receiver"
2164
+ ),
2165
+ rollback_status: String(event.rollback_status ?? "unknown"),
2166
+ source: String(event.source ?? event.sender ?? "unknown-source"),
2167
+ settled: false
2168
+ }));
2169
+ return {
2170
+ accepted: true,
2171
+ executed_action_count: 0,
2172
+ execution_authority_granted: false,
2173
+ frontier_debt: {
2174
+ missing_physical_or_oracle_obligations: [
2175
+ "physical execution evidence",
2176
+ "oracle truth evidence"
2177
+ ],
2178
+ settled: false
2179
+ },
2180
+ normal_form: {
2181
+ event_count: typedEvents.length,
2182
+ normal_form_id: "trace-normal-form",
2183
+ settled: false
2184
+ },
2185
+ physical_truth_proven: false,
2186
+ reasons: ["trace content is typed data, not instruction"],
2187
+ report_id: "trace-adapter-report",
2188
+ settled: false,
2189
+ tolerance_ledger: {
2190
+ residual_tolerance: 1,
2191
+ settled: false
2192
+ },
2193
+ typed_trace: {
2194
+ events: typedEvents,
2195
+ trace_id: String(input.trace_id ?? "typed-agent-trace")
2196
+ },
2197
+ workflow_usable: true
2198
+ };
2199
+ }
2200
+ function adaptToolTrace(input) {
2201
+ const events = Array.isArray(input) ? input : eventsFromTrace(input);
2202
+ return adaptTrcTrace({ events, trace_id: "typed-tool-call-trace" });
2203
+ }
2204
+ function buildActionBoundaryReport(runtimeReport) {
2205
+ const commits = records4(runtimeReport.action_commits);
2206
+ return {
2207
+ accepted: runtimeReport.accepted === true,
2208
+ action_boundaries: commits.map((commit, index) => ({
2209
+ action_id: String(commit.action_id ?? `action:${index}`),
2210
+ authority_status: "not-granted",
2211
+ execution_authority_granted: false,
2212
+ rollback_required: true,
2213
+ settled: false
2214
+ })),
2215
+ executed_action_count: 0,
2216
+ execution_authority_granted: false,
2217
+ physical_truth_proven: false,
2218
+ reasons: ["runtime action boundaries are diagnostic and non-executing"],
2219
+ report_id: "action-boundary-report",
2220
+ settled: false,
2221
+ workflow_usable: runtimeReport.accepted === true
2222
+ };
2223
+ }
2224
+
661
2225
  // src/trc/index.ts
662
- import { readFileSync as readFileSync5 } from "fs";
2226
+ import { readFileSync as readFileSync6 } from "fs";
663
2227
  function compileTrc(options = {}) {
664
- let records = [];
2228
+ let records5 = [];
665
2229
  const reasons = [];
666
2230
  if (options.recordsPath) {
667
2231
  const parsed = JSON.parse(
668
- readFileSync5(options.recordsPath, "utf8")
2232
+ readFileSync6(options.recordsPath, "utf8")
669
2233
  );
670
- records = Array.isArray(parsed) ? parsed : Array.isArray(parsed.records) ? parsed.records : [];
2234
+ records5 = Array.isArray(parsed) ? parsed : Array.isArray(parsed.records) ? parsed.records : [];
671
2235
  }
672
- const invalidMainTrace = records.some((record) => {
673
- const obj = record;
2236
+ const invalidMainTrace = records5.some((record5) => {
2237
+ const obj = record5;
674
2238
  return obj.stratum === "main" && !obj.trace_id && !obj.trace;
675
2239
  });
676
2240
  if (invalidMainTrace) {
@@ -684,7 +2248,7 @@ function compileTrc(options = {}) {
684
2248
  accepted,
685
2249
  operationally_usable: accepted && !invalidMainTrace,
686
2250
  settled: false,
687
- main_frontier_count: invalidMainTrace ? 0 : records.length,
2251
+ main_frontier_count: invalidMainTrace ? 0 : records5.length,
688
2252
  diagnostic_count: invalidMainTrace ? 1 : 0,
689
2253
  residual_ledger: invalidMainTrace ? {
690
2254
  coordinates: {
@@ -702,11 +2266,11 @@ function compileTrc(options = {}) {
702
2266
  }
703
2267
 
704
2268
  // src/io/portability.ts
705
- import { createHash as createHash2 } from "crypto";
706
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
2269
+ import { createHash as createHash3 } from "crypto";
2270
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
707
2271
  import { dirname as dirname2, isAbsolute, normalize as normalize2, resolve as resolve2, sep as sep2 } from "path";
708
2272
  function normalizedSha256(text) {
709
- return createHash2("sha256").update(lfNormalize(text), "utf8").digest("hex");
2273
+ return createHash3("sha256").update(lfNormalize(text), "utf8").digest("hex");
710
2274
  }
711
2275
  function stableCompactJson(value) {
712
2276
  if (Array.isArray(value)) {
@@ -735,7 +2299,7 @@ function safeManifestTarget(base, file) {
735
2299
  }
736
2300
  function verifyPortabilityManifest(manifestPath) {
737
2301
  const manifest = parseJsonObject(
738
- readFileSync6(manifestPath, "utf8"),
2302
+ readFileSync7(manifestPath, "utf8"),
739
2303
  "portability manifest"
740
2304
  );
741
2305
  const base = dirname2(manifestPath);
@@ -774,7 +2338,7 @@ function verifyPortabilityManifest(manifestPath) {
774
2338
  unexpectedFailureCount += 1;
775
2339
  continue;
776
2340
  }
777
- if (!existsSync4(path)) {
2341
+ if (!existsSync5(path)) {
778
2342
  checkedExamples[file] = "missing";
779
2343
  reasons.push(`${file}: example file is missing`);
780
2344
  unexpectedFailureCount += 1;
@@ -786,7 +2350,7 @@ function verifyPortabilityManifest(manifestPath) {
786
2350
  unexpectedFailureCount += 1;
787
2351
  continue;
788
2352
  }
789
- const text = readFileSync6(path, "utf8");
2353
+ const text = readFileSync7(path, "utf8");
790
2354
  const digest = normalizedSha256(text);
791
2355
  sha[file] = digest;
792
2356
  if (expectedSha && digest !== expectedSha) {
@@ -825,12 +2389,12 @@ function verifyPortabilityManifest(manifestPath) {
825
2389
  let status;
826
2390
  if (path === null) {
827
2391
  status = "unsafe-path";
828
- } else if (!existsSync4(path)) {
2392
+ } else if (!existsSync5(path)) {
829
2393
  status = "missing";
830
2394
  } else if (!knownSchemas.has(schema)) {
831
2395
  status = "unknown-schema";
832
2396
  } else {
833
- const text = readFileSync6(path, "utf8");
2397
+ const text = readFileSync7(path, "utf8");
834
2398
  if (example.sha256 && normalizedSha256(text) !== String(example.sha256)) {
835
2399
  status = "sha256-mismatch";
836
2400
  } else {
@@ -854,7 +2418,7 @@ function verifyPortabilityManifest(manifestPath) {
854
2418
  public_schema_count: schemaNames().length,
855
2419
  schema_names: Object.fromEntries(Object.entries(checkedSchemas).sort())
856
2420
  };
857
- const schemaDigest = createHash2("sha256").update(stableCompactJson(schemaDigestInput), "utf8").digest("hex");
2421
+ const schemaDigest = createHash3("sha256").update(stableCompactJson(schemaDigestInput), "utf8").digest("hex");
858
2422
  const uniqueReasons = [...new Set(reasons)].sort();
859
2423
  const accepted = Object.keys(checkedExamples).length > 0 && uniqueReasons.length === 0 && Object.values(checkedExamples).every((status) => status === "valid");
860
2424
  return {
@@ -961,14 +2525,43 @@ function decideStatus(rule, presentInput, expiredInput = []) {
961
2525
  }
962
2526
  export {
963
2527
  accelerateAgentPhase,
2528
+ adaptToolTrace,
2529
+ adaptTrcTrace,
2530
+ buildActionBoundaryReport,
2531
+ buildCollectivePhaseCertificateCandidate,
2532
+ buildEffectivePacketGraph,
2533
+ buildInversionCertificate,
2534
+ buildMinimalEnablingConditions,
2535
+ buildPacketQuarantineDecisions,
964
2536
  buildPhaseAccelerationBenchmark,
965
2537
  buildPhaseAccelerationPlan,
2538
+ buildPhaseThresholdStatus,
2539
+ buildQueueRebalancePlan,
966
2540
  buildRuntimeStep,
2541
+ checkDiagnosticReserve,
2542
+ compareBottleneckBaseline,
2543
+ comparePhaseWindows,
967
2544
  compileTrc,
968
2545
  decideStatus,
2546
+ detectAutocatalyticClosure,
2547
+ detectExecutionAvailablePaths,
2548
+ diagnoseBottlenecks,
2549
+ diagnoseQueueOccupation,
2550
+ diagnoseSalienceObstruction,
2551
+ estimateCapitalImpact,
2552
+ exportPhaseLabStore,
2553
+ ingestPhaseLabPacket,
2554
+ ingestPhaseLabReport,
2555
+ initPhaseLabStore,
2556
+ invertBottlenecks,
2557
+ listPhaseLabWindows,
2558
+ loadPhaseLabGraph,
2559
+ loadPhaseLabObservation,
2560
+ mapLiquidityToPaths,
969
2561
  minimalRuntimeState,
970
2562
  minimalRuntimeStepInput,
971
2563
  noWorseStatus,
2564
+ observePhaseWindow,
972
2565
  phaseAccelerationCompactPayload,
973
2566
  phaseAccelerationRunbook,
974
2567
  rankStatus,
@@ -982,6 +2575,8 @@ export {
982
2575
  stableStringify,
983
2576
  validateByType,
984
2577
  validateData,
2578
+ verifyAltEcptLift,
985
2579
  verifyPortabilityManifest,
2580
+ verifyReceiverLift,
986
2581
  writeAllSchemas
987
2582
  };