chainlesschain 0.165.10 → 0.166.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/completions/_cc +2 -1
- package/completions/cc.bash +2 -2
- package/completions/cc.fish +2 -2
- package/completions/cc.ps1 +2 -1
- package/package.json +1 -1
- package/src/assets/web-panel/assets/{AIOps-DoxapYEM.js → AIOps-DwdhBUBc.js} +1 -1
- package/src/assets/web-panel/assets/{ActionButton-DyiHvT2O.js → ActionButton-Dd1lBEeo.js} +1 -1
- package/src/assets/web-panel/assets/{Analytics-CAX06POB.js → Analytics-DuGuuI36.js} +3 -3
- package/src/assets/web-panel/assets/{AppLayout-JXxcyn0R.js → AppLayout-CvHpSs3M.js} +5 -5
- package/src/assets/web-panel/assets/{Artifacts-40nZDb9N.js → Artifacts-BU9F3wJh.js} +1 -1
- package/src/assets/web-panel/assets/{Audit-B_wc8Kcq.js → Audit-DK_n_WFm.js} +1 -1
- package/src/assets/web-panel/assets/{BackgroundAgents-CReWOiQY.js → BackgroundAgents-qKsxF5tv.js} +1 -1
- package/src/assets/web-panel/assets/{Backup-sXrv9fE6.js → Backup-JS58pSyV.js} +1 -1
- package/src/assets/web-panel/assets/{BaseInput-CHWmIERI.js → BaseInput-gGl6Ray1.js} +1 -1
- package/src/assets/web-panel/assets/{Chat-DgQrMZCb.js → Chat-B2FZNq3U.js} +6 -6
- package/src/assets/web-panel/assets/{ChatBubbleRenderer-Clpgj0fi.js → ChatBubbleRenderer-CZS_bLAr.js} +1 -1
- package/src/assets/web-panel/assets/{Checkbox-DmRwzt3e.js → Checkbox-tsI0TE22.js} +1 -1
- package/src/assets/web-panel/assets/{Codegen-tllAfrrc.js → Codegen-D5kqhfAr.js} +1 -1
- package/src/assets/web-panel/assets/{Col-CA_wqwEp.js → Col-DdN1TrqS.js} +1 -1
- package/src/assets/web-panel/assets/{Community-DQ_szKAv.js → Community-DgbEeh6V.js} +1 -1
- package/src/assets/web-panel/assets/{Compact-CjkqX60k.js → Compact-FIm-fRB_.js} +1 -1
- package/src/assets/web-panel/assets/{Compliance-CfDNkDex.js → Compliance-B-N0pudf.js} +1 -1
- package/src/assets/web-panel/assets/{Cowork-PINc6CPv.js → Cowork-CuMafBpi.js} +3 -3
- package/src/assets/web-panel/assets/{Cron-snYq4WCj.js → Cron-BTwzNFHR.js} +2 -2
- package/src/assets/web-panel/assets/{Crosschain-CKR7he4B.js → Crosschain-DRoYbLOd.js} +1 -1
- package/src/assets/web-panel/assets/{DID-Bp5xJSbE.js → DID-CPhnNkz_.js} +2 -2
- package/src/assets/web-panel/assets/{Dashboard-Dn-y6txl.js → Dashboard-DJQftix2.js} +2 -2
- package/src/assets/web-panel/assets/{Dropdown-D0uEeunr.js → Dropdown-PSAH1Kfy.js} +1 -1
- package/src/assets/web-panel/assets/{EmailListRenderer-DIhjyeNw.js → EmailListRenderer-PVRqeMiZ.js} +1 -1
- package/src/assets/web-panel/assets/{FamilyGuardDashboard-D2Pv1Hnb.js → FamilyGuardDashboard-CYtnjqjl.js} +1 -1
- package/src/assets/web-panel/assets/{Federation-D6oSp4P4.js → Federation-_-53kTDz.js} +1 -1
- package/src/assets/web-panel/assets/{FormItemContext-s6bzlfQs.js → FormItemContext-DTQ4qGuE.js} +1 -1
- package/src/assets/web-panel/assets/{GenericCardRenderer-B_NTgGP9.js → GenericCardRenderer-ON_NfX8k.js} +1 -1
- package/src/assets/web-panel/assets/{Git-Dk1lCoBr.js → Git-DUc3w_Bf.js} +2 -2
- package/src/assets/web-panel/assets/{Governance-xOnLBQzd.js → Governance-CktsJ2ku.js} +1 -1
- package/src/assets/web-panel/assets/{Inference-BFVHy-0I.js → Inference-4wUHQvju.js} +1 -1
- package/src/assets/web-panel/assets/{KnowledgeGraph-BXzITB9_.js → KnowledgeGraph-Dq4saPnZ.js} +1 -1
- package/src/assets/web-panel/assets/{Logs-BD2M4NPu.js → Logs-Btb50m5s.js} +2 -2
- package/src/assets/web-panel/assets/MarkdownRenderer-Cre8P8HG.js +1 -0
- package/src/assets/web-panel/assets/{Marketplace-awpllI_9.js → Marketplace-D3rSncxx.js} +1 -1
- package/src/assets/web-panel/assets/{McpTools-tL0IgbIX.js → McpTools-Bc6Mori_.js} +3 -3
- package/src/assets/web-panel/assets/{Memory-CrptLGSN.js → Memory-C-ottUdN.js} +2 -2
- package/src/assets/web-panel/assets/{MobileBridge-DZX-l_BS.js → MobileBridge-C0DITBmP.js} +1 -1
- package/src/assets/web-panel/assets/MobileProjects-O6cr0Nal.js +1 -0
- package/src/assets/web-panel/assets/{Mtc-dQ5-FjpQ.js → Mtc-B_MXKXvY.js} +6 -6
- package/src/assets/web-panel/assets/{MtcAudit-U0nDxDlG.js → MtcAudit-BDkUqWIT.js} +5 -5
- package/src/assets/web-panel/assets/{Multisig-D1PpAtiq.js → Multisig-BaxNWm8c.js} +3 -3
- package/src/assets/web-panel/assets/{NLProgramming-phZr6nyZ.js → NLProgramming-UD2GndZc.js} +1 -1
- package/src/assets/web-panel/assets/{Notes-BPzSSUrX.js → Notes-pU7wtMwB.js} +3 -3
- package/src/assets/web-panel/assets/{NotificationSettings-AypFEc7p.js → NotificationSettings-BIs6ULr3.js} +1 -1
- package/src/assets/web-panel/assets/{OrderTableRenderer-S3k1qjT-.js → OrderTableRenderer-0NuumnfG.js} +1 -1
- package/src/assets/web-panel/assets/{Organization-BvdQXFPR.js → Organization-C9o-n2lq.js} +4 -4
- package/src/assets/web-panel/assets/{Overflow-CUz_jbQC.js → Overflow-CEvMXxCS.js} +1 -1
- package/src/assets/web-panel/assets/{P2P-C0xQ7H_2.js → P2P-C3gQMTK3.js} +2 -2
- package/src/assets/web-panel/assets/{PdhVaultBrowser-DJKMjfB8.js → PdhVaultBrowser-D1LVpBOr.js} +3 -3
- package/src/assets/web-panel/assets/{Permissions-dkMtmDwK.js → Permissions-Dj5nIi0Y.js} +4 -4
- package/src/assets/web-panel/assets/{PersonalDataHub-CyHE7fnn.js → PersonalDataHub-uiLYuFcu.js} +6 -6
- package/src/assets/web-panel/assets/{Pipeline-_dU0Nwy3.js → Pipeline-CIrmF89x.js} +1 -1
- package/src/assets/web-panel/assets/{Privacy-fqLyg57f.js → Privacy-B3K1CUBa.js} +1 -1
- package/src/assets/web-panel/assets/{ProjectInit-COybCr5d.js → ProjectInit-C_wCZ0zW.js} +2 -2
- package/src/assets/web-panel/assets/{ProjectSettings-B4DngMZW.js → ProjectSettings-iCitfuNJ.js} +2 -2
- package/src/assets/web-panel/assets/{Projects-D0bMwUBm.js → Projects-BwimeXkW.js} +1 -1
- package/src/assets/web-panel/assets/{Providers-Ba-7WNA8.js → Providers-BLpepgr6.js} +1 -1
- package/src/assets/web-panel/assets/{QrScannerModal-X-I8dDMT.js → QrScannerModal-DPy8tjXV.js} +1 -1
- package/src/assets/web-panel/assets/{QuickAsk-BCUP0a90.js → QuickAsk-CRq8VhID.js} +1 -1
- package/src/assets/web-panel/assets/{Recommend-DtFNmiQZ.js → Recommend-CirlWIiK.js} +1 -1
- package/src/assets/web-panel/assets/{RemoteSession-INR5CIAI.js → RemoteSession-nlnJlKXO.js} +3 -3
- package/src/assets/web-panel/assets/{Reputation-B6NfaCc6.js → Reputation-B5aaxee5.js} +1 -1
- package/src/assets/web-panel/assets/{Row-Dmz76txh.js → Row-lzsTQZlq.js} +1 -1
- package/src/assets/web-panel/assets/{RssFeed-B7qyFCea.js → RssFeed-C41AzjgC.js} +3 -3
- package/src/assets/web-panel/assets/{Search-Bi6eS0oY.js → Search-1Hxx3TZ3.js} +1 -1
- package/src/assets/web-panel/assets/{Security-D9_xim1L.js → Security-8VqwRxAp.js} +4 -4
- package/src/assets/web-panel/assets/{Services-PI1O-uYU.js → Services-DCm0HHAD.js} +2 -2
- package/src/assets/web-panel/assets/{Skeleton-B8BrJnk8.js → Skeleton-D6w5gpmW.js} +1 -1
- package/src/assets/web-panel/assets/{Skills-DvSm92dJ.js → Skills-Bw_pUTJB.js} +1 -1
- package/src/assets/web-panel/assets/{Sla-BWyhCoRo.js → Sla-BkMj8Dxu.js} +1 -1
- package/src/assets/web-panel/assets/{SpeechSettings-BL9H27jl.js → SpeechSettings-BOmLqW44.js} +1 -1
- package/src/assets/web-panel/assets/{SyncSettings-B7r--6yN.js → SyncSettings-2xKSqFDO.js} +2 -2
- package/src/assets/web-panel/assets/{Tasks-sc64p2Jt.js → Tasks-BPAnzVau.js} +1 -1
- package/src/assets/web-panel/assets/{Templates-DEK55RVb.js → Templates-CcOGWgZz.js} +1 -1
- package/src/assets/web-panel/assets/{Tenant-DElr8R1l.js → Tenant-CAyzzQWN.js} +1 -1
- package/src/assets/web-panel/assets/{Terminal-BywaLBgz.js → Terminal-Daagerkm.js} +2 -2
- package/src/assets/web-panel/assets/{TimelineRenderer-B5NcgLyS.js → TimelineRenderer-1jGbMj7I.js} +1 -1
- package/src/assets/web-panel/assets/{Tokens-COFYqr6A.js → Tokens-CYQ-FQju.js} +1 -1
- package/src/assets/web-panel/assets/{Trigger-CfnVS3ij.js → Trigger-C70zRwuR.js} +1 -1
- package/src/assets/web-panel/assets/{Trust-Bz94Gu5k.js → Trust-CeqXfiX_.js} +1 -1
- package/src/assets/web-panel/assets/{UkeySign-Be10drSk.js → UkeySign-D0j6m1bU.js} +1 -1
- package/src/assets/web-panel/assets/{VideoEditing-CUB_cMem.js → VideoEditing-DFHpM7Yd.js} +1 -1
- package/src/assets/web-panel/assets/{Wallet-DxBJJuvG.js → Wallet-BVC2J0Yx.js} +4 -4
- package/src/assets/web-panel/assets/{WebAuthn-BZx5lwT8.js → WebAuthn-BceIN2Gn.js} +4 -4
- package/src/assets/web-panel/assets/{WorkflowEditor-B4sJikPT.js → WorkflowEditor-Bgeb-i-S.js} +1 -1
- package/src/assets/web-panel/assets/{chat-Wl-95AgM.js → chat-BmMBqgvz.js} +1 -1
- package/src/assets/web-panel/assets/{colors-DUSwYVCg.js → colors-sjRzwnyw.js} +1 -1
- package/src/assets/web-panel/assets/{compact-item-DkKRDHcU.js → compact-item-DNt6m2bM.js} +1 -1
- package/src/assets/web-panel/assets/{createContext-B5nAVC_Y.js → createContext-DELaLit3.js} +1 -1
- package/src/assets/web-panel/assets/devWarning-Ct8o3bu_.js +1 -0
- package/src/assets/web-panel/assets/{hasIn-rtotsRlA.js → hasIn-dfwk9O8x.js} +1 -1
- package/src/assets/web-panel/assets/{index-B_KDhTdt.js → index-1w7dha_a.js} +1 -1
- package/src/assets/web-panel/assets/{index-C7kGJlSA.js → index-6bjBUhoH.js} +1 -1
- package/src/assets/web-panel/assets/{index-CN2LNCWW.js → index-B0wkOqE9.js} +1 -1
- package/src/assets/web-panel/assets/{index-CAtnIdx_.js → index-B4Z4HZcf.js} +1 -1
- package/src/assets/web-panel/assets/{index-D7zQADRc.js → index-B7qiZc2Z.js} +1 -1
- package/src/assets/web-panel/assets/{index-DoBh4Ezg.js → index-BLbvXsxf.js} +1 -1
- package/src/assets/web-panel/assets/{index-mwPG3TJQ.js → index-BMnvNNEd.js} +1 -1
- package/src/assets/web-panel/assets/{index-Ba8raWtd.js → index-BSB9Gin8.js} +1 -1
- package/src/assets/web-panel/assets/{index-CJWpTdCW.js → index-BXJ68ObJ.js} +1 -1
- package/src/assets/web-panel/assets/{index-DCCTgytM.js → index-Bs-mWOWt.js} +1 -1
- package/src/assets/web-panel/assets/{index-D7Nx-jzS.js → index-BvIQ9sZa.js} +1 -1
- package/src/assets/web-panel/assets/{index-DUS7KK-i.js → index-BzddvOOb.js} +1 -1
- package/src/assets/web-panel/assets/{index-X36Wyd1S.js → index-C2Sxf7yC.js} +1 -1
- package/src/assets/web-panel/assets/{index-btxpIsXs.js → index-CAIn5cS9.js} +1 -1
- package/src/assets/web-panel/assets/{index-CskW4gDB.js → index-CLSqyAcE.js} +1 -1
- package/src/assets/web-panel/assets/{index-CUDraKtq.js → index-Cbu3-zFd.js} +1 -1
- package/src/assets/web-panel/assets/{index-Cv38Cwx0.js → index-Clrqtycd.js} +1 -1
- package/src/assets/web-panel/assets/{index-DupOVIEb.js → index-CpVt6M_8.js} +1 -1
- package/src/assets/web-panel/assets/{index-yt994jkW.js → index-CtfYPnsY.js} +1 -1
- package/src/assets/web-panel/assets/{index-JWQxvZ4x.js → index-CujMHspH.js} +1 -1
- package/src/assets/web-panel/assets/index-D685kO6L.js +1 -0
- package/src/assets/web-panel/assets/{index-Bj6mJ7tw.js → index-DC6FlHlP.js} +1 -1
- package/src/assets/web-panel/assets/{index-DQhlLyT6.js → index-DFOYbzg-.js} +1 -1
- package/src/assets/web-panel/assets/index-DTlIRMqX.js +1 -0
- package/src/assets/web-panel/assets/{index-BMHNKa11.js → index-DV8q_Hki.js} +1 -1
- package/src/assets/web-panel/assets/{index-C3lcOYkZ.js → index-DX3wwu3G.js} +3 -3
- package/src/assets/web-panel/assets/{index-CUqLWyY0.js → index-DY2G1Th2.js} +1 -1
- package/src/assets/web-panel/assets/{index-cKc70R9h.js → index-DlYL8VP8.js} +1 -1
- package/src/assets/web-panel/assets/{index-1J_Q-Ovw.js → index-DnQOc5wo.js} +1 -1
- package/src/assets/web-panel/assets/{index-CDWNrtvg.js → index-Du62m6pG.js} +1 -1
- package/src/assets/web-panel/assets/{index-03w73yRM.js → index-LMfsEdLk.js} +1 -1
- package/src/assets/web-panel/assets/{index-YANfaEyE.js → index-OC3qYV4-.js} +1 -1
- package/src/assets/web-panel/assets/{index-Dnbdqjxz.js → index-Rt-fym5b.js} +1 -1
- package/src/assets/web-panel/assets/{index-DfNeBiyO.js → index-WpEDoyTv.js} +1 -1
- package/src/assets/web-panel/assets/{index-INU8TpRu.js → index-aj9ObF2R.js} +1 -1
- package/src/assets/web-panel/assets/{index-CAdTY3kv.js → index-dAF9qRVa.js} +1 -1
- package/src/assets/web-panel/assets/{index-BxAMRZR0.js → index-dpDeFZNt.js} +1 -1
- package/src/assets/web-panel/assets/{index-CbqotoPt.js → index-fNwu9CU_.js} +1 -1
- package/src/assets/web-panel/assets/{index-Ch5SqZaK.js → index-vCQ3l6DX.js} +1 -1
- package/src/assets/web-panel/assets/{initDefaultProps-Ck8wTHsR.js → initDefaultProps-DUt9Xj8y.js} +1 -1
- package/src/assets/web-panel/assets/{motion-teBWI8ni.js → motion-DdiFPnv7.js} +1 -1
- package/src/assets/web-panel/assets/{move-BdxzRStQ.js → move-BJ2VH7Y2.js} +1 -1
- package/src/assets/web-panel/assets/{mtc-parser-DMpcDDsk.js → mtc-parser-BCnX6oOJ.js} +1 -1
- package/src/assets/web-panel/assets/{omit-BwkyHyWr.js → omit-CyHxlDLV.js} +1 -1
- package/src/assets/web-panel/assets/{pickAttrs-SlaxZUQd.js → pickAttrs-BJiGW3bY.js} +1 -1
- package/src/assets/web-panel/assets/{placementArrow-BlEZZ3cs.js → placementArrow-DhJ9Rhx8.js} +1 -1
- package/src/assets/web-panel/assets/{responsiveObserve-Cl5uK6S5.js → responsiveObserve-C6zpL9bC.js} +1 -1
- package/src/assets/web-panel/assets/{slide-LlOJWbeE.js → slide-DCbMFRF-.js} +1 -1
- package/src/assets/web-panel/assets/{statusUtils-DxbwIpQR.js → statusUtils-CNtVLsIq.js} +1 -1
- package/src/assets/web-panel/assets/{styleChecker-G_P9gils.js → styleChecker-Z078OtUc.js} +1 -1
- package/src/assets/web-panel/assets/{useFlexGapSupport-BDS7KDuK.js → useFlexGapSupport-w4RVmcGs.js} +1 -1
- package/src/assets/web-panel/assets/{useFs-Xx3R_4Qk.js → useFs-D4Xw1XRt.js} +1 -1
- package/src/assets/web-panel/assets/{usePersonalDataHub-ChOtRWax.js → usePersonalDataHub-Bnbd1PgY.js} +1 -1
- package/src/assets/web-panel/assets/{vnode-CAUrMwRC.js → vnode-DSOQxMFN.js} +1 -1
- package/src/assets/web-panel/assets/{zoom-Choqv7b5.js → zoom-DNPE1Wca.js} +1 -1
- package/src/assets/web-panel/index.html +1 -1
- package/src/command-help-index.json +3 -3
- package/src/command-manifest.json +1 -1
- package/src/commands/agent.js +1 -1
- package/src/commands/graph.js +100 -0
- package/src/commands/orchestrate.js +85 -18
- package/src/commands/serve.js +39 -0
- package/src/commands/team.js +2 -0
- package/src/data/changelog.json +27 -1
- package/src/generated/cc-agent-protocol.schema.json +2013 -0
- package/src/lib/app-server/bounded-queue.js +87 -0
- package/src/lib/app-server/cli-agent-kernel-adapter.js +309 -0
- package/src/lib/app-server/protocol.js +125 -0
- package/src/lib/app-server/rollout-store.js +603 -0
- package/src/lib/app-server/server.js +922 -0
- package/src/lib/app-server/sqlite-rollout-store.js +315 -0
- package/src/lib/app-server/stdio-transport.js +118 -0
- package/src/lib/codex-app-server-adapter.js +249 -0
- package/src/lib/graph-kernel/adapters.js +238 -0
- package/src/lib/graph-kernel/compiler.js +1443 -0
- package/src/lib/graph-kernel/eval.js +207 -0
- package/src/lib/graph-kernel/event-store.js +101 -0
- package/src/lib/graph-kernel/index.js +7 -0
- package/src/lib/graph-kernel/runtime.js +3788 -0
- package/src/lib/graph-kernel/trace-reducer.js +409 -0
- package/src/lib/graph-kernel/trigger-adapter.js +183 -0
- package/src/lib/orchestrator.js +2 -1
- package/src/lib/record-replay/index.js +1 -0
- package/src/lib/record-replay/skill-recorder.js +386 -0
- package/src/lib/webhook-security.js +159 -0
- package/src/repl/agent-repl.js +5 -4
- package/src/repl/prompt-interactions.js +11 -1
- package/src/assets/web-panel/assets/MarkdownRenderer-CDSwkj7Y.js +0 -1
- package/src/assets/web-panel/assets/MobileProjects-krNyADYi.js +0 -1
- package/src/assets/web-panel/assets/devWarning-DFO12EfA.js +0 -1
- package/src/assets/web-panel/assets/index-DaDlUWea.js +0 -1
- package/src/assets/web-panel/assets/index-xn89TjWJ.js +0 -1
|
@@ -0,0 +1,3788 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
assertCompiledGraph,
|
|
4
|
+
compileGraphDefinition,
|
|
5
|
+
executionAttemptId,
|
|
6
|
+
graphDigest,
|
|
7
|
+
writeScopesOverlap,
|
|
8
|
+
} from "./compiler.js";
|
|
9
|
+
import { GraphEventStore } from "./event-store.js";
|
|
10
|
+
|
|
11
|
+
export const GRAPH_RUN_PHASES = Object.freeze(["open", "sealed"]);
|
|
12
|
+
export const GRAPH_RUN_STATUSES = Object.freeze([
|
|
13
|
+
"running",
|
|
14
|
+
"waiting_input",
|
|
15
|
+
"waiting_external",
|
|
16
|
+
"waiting_human",
|
|
17
|
+
"reconciliation_required",
|
|
18
|
+
"succeeded",
|
|
19
|
+
"failed",
|
|
20
|
+
"partial",
|
|
21
|
+
"cancelled",
|
|
22
|
+
"blocked",
|
|
23
|
+
"deadlocked",
|
|
24
|
+
"budget_exhausted",
|
|
25
|
+
]);
|
|
26
|
+
export const GRAPH_NODE_STATUSES = Object.freeze([
|
|
27
|
+
"pending",
|
|
28
|
+
"running",
|
|
29
|
+
"waiting_human",
|
|
30
|
+
"reconciliation_required",
|
|
31
|
+
"succeeded",
|
|
32
|
+
"failed",
|
|
33
|
+
"skipped",
|
|
34
|
+
"upstream_failed",
|
|
35
|
+
"cancelled",
|
|
36
|
+
"blocked",
|
|
37
|
+
"timed_out",
|
|
38
|
+
"budget_exhausted",
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
const TERMINAL_RUN = new Set([
|
|
42
|
+
"succeeded",
|
|
43
|
+
"failed",
|
|
44
|
+
"partial",
|
|
45
|
+
"cancelled",
|
|
46
|
+
"blocked",
|
|
47
|
+
"deadlocked",
|
|
48
|
+
"budget_exhausted",
|
|
49
|
+
]);
|
|
50
|
+
const TERMINAL_NODE = new Set([
|
|
51
|
+
"succeeded",
|
|
52
|
+
"failed",
|
|
53
|
+
"skipped",
|
|
54
|
+
"upstream_failed",
|
|
55
|
+
"cancelled",
|
|
56
|
+
"blocked",
|
|
57
|
+
"timed_out",
|
|
58
|
+
"budget_exhausted",
|
|
59
|
+
]);
|
|
60
|
+
const SUCCESS_NODE = new Set(["succeeded"]);
|
|
61
|
+
const FAILURE_NODE = new Set([
|
|
62
|
+
"failed",
|
|
63
|
+
"upstream_failed",
|
|
64
|
+
"blocked",
|
|
65
|
+
"timed_out",
|
|
66
|
+
"budget_exhausted",
|
|
67
|
+
]);
|
|
68
|
+
const ACTIVE_ATTEMPT = new Set(["active", "waiting_human", "cancelling"]);
|
|
69
|
+
const SENSITIVITY_RANK = Object.freeze({
|
|
70
|
+
public: 0,
|
|
71
|
+
internal: 1,
|
|
72
|
+
confidential: 2,
|
|
73
|
+
secret: 3,
|
|
74
|
+
});
|
|
75
|
+
const TRUST_RANK = Object.freeze({
|
|
76
|
+
unknown: 0,
|
|
77
|
+
untrusted_content: 1,
|
|
78
|
+
authenticated_user: 2,
|
|
79
|
+
trusted_host: 3,
|
|
80
|
+
});
|
|
81
|
+
const BUDGET_FIELDS = Object.freeze([
|
|
82
|
+
"turns",
|
|
83
|
+
"tokens",
|
|
84
|
+
"costUsd",
|
|
85
|
+
"wallMs",
|
|
86
|
+
"spawnCount",
|
|
87
|
+
]);
|
|
88
|
+
|
|
89
|
+
function kernelError(code, message, details = {}) {
|
|
90
|
+
const error = new Error(message);
|
|
91
|
+
error.name = "GraphKernelError";
|
|
92
|
+
error.code = code;
|
|
93
|
+
Object.assign(error, details);
|
|
94
|
+
return error;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function clone(value) {
|
|
98
|
+
return value == null ? value : JSON.parse(JSON.stringify(value));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function mapSnapshot(map) {
|
|
102
|
+
return [...map.entries()].map(([key, value]) => [key, clone(value)]);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function mapRestore(entries) {
|
|
106
|
+
return new Map((entries || []).map(([key, value]) => [key, clone(value)]));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function emptyBudgetUsage() {
|
|
110
|
+
return Object.fromEntries(BUDGET_FIELDS.map((field) => [field, 0]));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function budgetValue(budget, field) {
|
|
114
|
+
return Number(budget?.[field] || 0);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function persistedSubgraphRegistry(definitions = {}) {
|
|
118
|
+
return new Map(
|
|
119
|
+
Object.entries(definitions).map(([id, definition]) => [
|
|
120
|
+
id,
|
|
121
|
+
{
|
|
122
|
+
definition,
|
|
123
|
+
revisionDigest: graphDigest(
|
|
124
|
+
definition,
|
|
125
|
+
`cc.graph.definition/${definition.schemaVersion}`,
|
|
126
|
+
),
|
|
127
|
+
},
|
|
128
|
+
]),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function idleCompensationState() {
|
|
133
|
+
return {
|
|
134
|
+
status: "idle",
|
|
135
|
+
triggerNodeId: null,
|
|
136
|
+
reason: null,
|
|
137
|
+
terminalStatus: null,
|
|
138
|
+
plan: [],
|
|
139
|
+
currentIndex: 0,
|
|
140
|
+
completedNodeIds: [],
|
|
141
|
+
completedEntries: [],
|
|
142
|
+
failure: null,
|
|
143
|
+
startedAt: null,
|
|
144
|
+
completedAt: null,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function iterationFrameId(runId, regionId, iterationPath) {
|
|
149
|
+
const digest = graphDigest(
|
|
150
|
+
{ runId, regionId, iterationPath },
|
|
151
|
+
"cc.graph.iteration-frame/v1",
|
|
152
|
+
);
|
|
153
|
+
return `iteration-${digest.slice(7, 39)}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function deterministicSubgraphRunId(parentRunId, nodeId, revisionDigest) {
|
|
157
|
+
const digest = graphDigest(
|
|
158
|
+
{ parentRunId, nodeId, revisionDigest },
|
|
159
|
+
"cc.graph.subgraph-run/v1",
|
|
160
|
+
);
|
|
161
|
+
return `subgraph-${digest.slice(7, 39)}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function iterationEffectIdempotencyKey(
|
|
165
|
+
baseIdempotencyKey,
|
|
166
|
+
iterationPath = [],
|
|
167
|
+
) {
|
|
168
|
+
const base = String(baseIdempotencyKey || "").trim();
|
|
169
|
+
if (!base) {
|
|
170
|
+
throw kernelError(
|
|
171
|
+
"CC_GRAPH_EFFECT_IDEMPOTENCY_REQUIRED",
|
|
172
|
+
"effect idempotency key is required",
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (!Array.isArray(iterationPath)) {
|
|
176
|
+
throw kernelError(
|
|
177
|
+
"CC_GRAPH_INVALID_ARGUMENT",
|
|
178
|
+
"iterationPath must be an array",
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const path = iterationPath.map((value) => {
|
|
182
|
+
const number = Number(value);
|
|
183
|
+
if (!Number.isInteger(number) || number < 0) {
|
|
184
|
+
throw kernelError(
|
|
185
|
+
"CC_GRAPH_INVALID_ARGUMENT",
|
|
186
|
+
"iterationPath must contain non-negative integers",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
return number;
|
|
190
|
+
});
|
|
191
|
+
if (path.length === 0) return base;
|
|
192
|
+
return graphDigest(
|
|
193
|
+
{ baseIdempotencyKey: base, iterationPath: path },
|
|
194
|
+
"cc.graph.iteration-effect-idempotency/v1",
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function finitePositive(value, fallback) {
|
|
199
|
+
const number = Number(value);
|
|
200
|
+
return Number.isFinite(number) && number > 0 ? number : fallback;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function safeIdentifier(value, label = "identifier") {
|
|
204
|
+
const id = String(value || "").trim();
|
|
205
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/u.test(id)) {
|
|
206
|
+
throw kernelError("CC_GRAPH_INVALID_ARGUMENT", `${label} is invalid`);
|
|
207
|
+
}
|
|
208
|
+
return id;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function nowIso(now) {
|
|
212
|
+
return new Date(now()).toISOString();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function attemptIsLive(attempt, now) {
|
|
216
|
+
return (
|
|
217
|
+
ACTIVE_ATTEMPT.has(attempt.status) && Number(attempt.expiresAtMs) > now
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function producerIsLive(lease, now) {
|
|
222
|
+
return lease.status === "active" && Number(lease.expiresAtMs) > now;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function hasTerminalEvidence(evidence) {
|
|
226
|
+
return Boolean(
|
|
227
|
+
evidence &&
|
|
228
|
+
(evidence.outputDigest ||
|
|
229
|
+
evidence.commit ||
|
|
230
|
+
(Array.isArray(evidence.artifactIds) && evidence.artifactIds.length) ||
|
|
231
|
+
(Array.isArray(evidence.testReceiptIds) &&
|
|
232
|
+
evidence.testReceiptIds.length)),
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function dependencySatisfied(policy, status) {
|
|
237
|
+
if (policy === "always") return TERMINAL_NODE.has(status);
|
|
238
|
+
if (policy === "failure") return FAILURE_NODE.has(status);
|
|
239
|
+
if (policy === "timeout") return status === "timed_out";
|
|
240
|
+
if (policy === "cancel") return status === "cancelled";
|
|
241
|
+
return SUCCESS_NODE.has(status);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function dependencyMismatchStatus(policy, status) {
|
|
245
|
+
if (policy === "success" && FAILURE_NODE.has(status)) {
|
|
246
|
+
return "upstream_failed";
|
|
247
|
+
}
|
|
248
|
+
if (policy === "success" && status === "cancelled") return "cancelled";
|
|
249
|
+
return "skipped";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function validateDataPolicy(policy) {
|
|
253
|
+
if (
|
|
254
|
+
!policy ||
|
|
255
|
+
typeof policy.origin !== "string" ||
|
|
256
|
+
!Object.hasOwn(TRUST_RANK, policy.trust) ||
|
|
257
|
+
!Object.hasOwn(SENSITIVITY_RANK, policy.sensitivity) ||
|
|
258
|
+
!Array.isArray(policy.allowedSinks)
|
|
259
|
+
) {
|
|
260
|
+
throw kernelError(
|
|
261
|
+
"CC_GRAPH_DATA_POLICY_REQUIRED",
|
|
262
|
+
"origin/trust/sensitivity/allowedSinks must be assigned at a trusted boundary",
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
return clone(policy);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function sinkAllowed(policy, sink) {
|
|
269
|
+
return policy.allowedSinks.some(
|
|
270
|
+
(allowed) =>
|
|
271
|
+
allowed === "*" ||
|
|
272
|
+
allowed === sink ||
|
|
273
|
+
(allowed.endsWith("*") && sink.startsWith(allowed.slice(0, -1))),
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function containsAuthorityPayload(value, state = { nodes: 0 }) {
|
|
278
|
+
state.nodes += 1;
|
|
279
|
+
if (state.nodes > 10_000) return true;
|
|
280
|
+
if (Array.isArray(value)) {
|
|
281
|
+
return value.some((item) => containsAuthorityPayload(item, state));
|
|
282
|
+
}
|
|
283
|
+
if (!value || typeof value !== "object") return false;
|
|
284
|
+
for (const [key, child] of Object.entries(value)) {
|
|
285
|
+
if (
|
|
286
|
+
[
|
|
287
|
+
"approval",
|
|
288
|
+
"capability",
|
|
289
|
+
"permission",
|
|
290
|
+
"controlEdge",
|
|
291
|
+
"authority",
|
|
292
|
+
].includes(key)
|
|
293
|
+
) {
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
if (containsAuthorityPayload(child, state)) return true;
|
|
297
|
+
}
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function deriveDataPolicy(policies, { declassification = null } = {}) {
|
|
302
|
+
const values = policies.map(validateDataPolicy);
|
|
303
|
+
if (!values.length) {
|
|
304
|
+
throw kernelError(
|
|
305
|
+
"CC_GRAPH_DATA_POLICY_REQUIRED",
|
|
306
|
+
"at least one source data policy is required",
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
const trust = values.reduce(
|
|
310
|
+
(lowest, policy) =>
|
|
311
|
+
TRUST_RANK[policy.trust] < TRUST_RANK[lowest] ? policy.trust : lowest,
|
|
312
|
+
values[0].trust,
|
|
313
|
+
);
|
|
314
|
+
const sensitivity = values.reduce(
|
|
315
|
+
(highest, policy) =>
|
|
316
|
+
SENSITIVITY_RANK[policy.sensitivity] > SENSITIVITY_RANK[highest]
|
|
317
|
+
? policy.sensitivity
|
|
318
|
+
: highest,
|
|
319
|
+
values[0].sensitivity,
|
|
320
|
+
);
|
|
321
|
+
const allowedSinks = values
|
|
322
|
+
.map((policy) => new Set(policy.allowedSinks))
|
|
323
|
+
.reduce(
|
|
324
|
+
(intersection, current) =>
|
|
325
|
+
new Set([...intersection].filter((sink) => current.has(sink))),
|
|
326
|
+
);
|
|
327
|
+
const output = {
|
|
328
|
+
origin: `derived:${graphDigest(values, "cc.graph.data-origin/v1")}`,
|
|
329
|
+
trust,
|
|
330
|
+
sensitivity,
|
|
331
|
+
allowedSinks: [...allowedSinks].sort(),
|
|
332
|
+
};
|
|
333
|
+
if (declassification) {
|
|
334
|
+
if (
|
|
335
|
+
typeof declassification.decisionId !== "string" ||
|
|
336
|
+
!Array.isArray(declassification.allowedSinks)
|
|
337
|
+
) {
|
|
338
|
+
throw kernelError(
|
|
339
|
+
"CC_GRAPH_DECLASSIFICATION_INVALID",
|
|
340
|
+
"declassification requires an audited decision and explicit sinks",
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
output.allowedSinks = [...new Set(declassification.allowedSinks)].sort();
|
|
344
|
+
output.declassificationDecisionId = declassification.decisionId;
|
|
345
|
+
}
|
|
346
|
+
return Object.freeze(output);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function stateSnapshot(run) {
|
|
350
|
+
return {
|
|
351
|
+
version: 1,
|
|
352
|
+
id: run.id,
|
|
353
|
+
definition: run.compiled.definition,
|
|
354
|
+
subgraphDefinitions: run.compiled.subgraphDefinitions,
|
|
355
|
+
phase: run.phase,
|
|
356
|
+
status: run.status,
|
|
357
|
+
graphRevision: run.graphRevision,
|
|
358
|
+
revisionDigest: run.revisionDigest,
|
|
359
|
+
occurrenceRef: run.occurrenceRef,
|
|
360
|
+
authorityDigest: run.authorityDigest,
|
|
361
|
+
budget: run.budget,
|
|
362
|
+
budgetUsed: run.budgetUsed,
|
|
363
|
+
budgetReserved: run.budgetReserved,
|
|
364
|
+
createdAt: run.createdAt,
|
|
365
|
+
completedAt: run.completedAt,
|
|
366
|
+
cancellationRequested: run.cancellationRequested,
|
|
367
|
+
progressEpoch: run.progressEpoch,
|
|
368
|
+
compensation: clone(run.compensation),
|
|
369
|
+
parentRunRef: clone(run.parentRunRef),
|
|
370
|
+
subgraphDepth: run.subgraphDepth,
|
|
371
|
+
definitionPath: clone(run.definitionPath),
|
|
372
|
+
loopStates: mapSnapshot(run.loopStates),
|
|
373
|
+
iterationFrames: mapSnapshot(run.iterationFrames),
|
|
374
|
+
loopDecisionCache: mapSnapshot(run.loopDecisionCache),
|
|
375
|
+
subgraphRuns: mapSnapshot(run.subgraphRuns),
|
|
376
|
+
nodeStates: mapSnapshot(run.nodeStates),
|
|
377
|
+
attempts: mapSnapshot(run.attempts),
|
|
378
|
+
agents: mapSnapshot(run.agents),
|
|
379
|
+
producerLeases: mapSnapshot(run.producerLeases),
|
|
380
|
+
artifacts: mapSnapshot(run.artifacts),
|
|
381
|
+
effects: mapSnapshot(run.effects),
|
|
382
|
+
messages: mapSnapshot(run.messages),
|
|
383
|
+
messageConsumers: mapSnapshot(run.messageConsumers),
|
|
384
|
+
handoffs: mapSnapshot(run.handoffs),
|
|
385
|
+
humanTasks: mapSnapshot(run.humanTasks),
|
|
386
|
+
waitReasons: mapSnapshot(run.waitReasons),
|
|
387
|
+
timers: mapSnapshot(run.timers),
|
|
388
|
+
requestCache: mapSnapshot(run.requestCache),
|
|
389
|
+
progressDigests: mapSnapshot(run.progressDigests),
|
|
390
|
+
fenceCounters: mapSnapshot(run.fenceCounters),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function restoreState(run, snapshot, compiled = null) {
|
|
395
|
+
run.compiled =
|
|
396
|
+
compiled ||
|
|
397
|
+
compileGraphDefinition(snapshot.definition, {
|
|
398
|
+
subgraphs: persistedSubgraphRegistry(snapshot.subgraphDefinitions),
|
|
399
|
+
allowUnresolvedSubgraphs: snapshot.subgraphDefinitions == null,
|
|
400
|
+
});
|
|
401
|
+
run.phase = snapshot.phase;
|
|
402
|
+
run.status = snapshot.status;
|
|
403
|
+
run.graphRevision = snapshot.graphRevision;
|
|
404
|
+
run.revisionDigest = snapshot.revisionDigest;
|
|
405
|
+
run.occurrenceRef = clone(snapshot.occurrenceRef);
|
|
406
|
+
run.authorityDigest = snapshot.authorityDigest;
|
|
407
|
+
run.budget = clone(snapshot.budget);
|
|
408
|
+
run.budgetUsed = clone(snapshot.budgetUsed);
|
|
409
|
+
run.budgetReserved = clone(snapshot.budgetReserved || emptyBudgetUsage());
|
|
410
|
+
run.createdAt = snapshot.createdAt;
|
|
411
|
+
run.completedAt = snapshot.completedAt;
|
|
412
|
+
run.cancellationRequested = snapshot.cancellationRequested === true;
|
|
413
|
+
run.progressEpoch = snapshot.progressEpoch;
|
|
414
|
+
run.compensation = clone(snapshot.compensation || idleCompensationState());
|
|
415
|
+
run.compensation.completedEntries ||= [];
|
|
416
|
+
run.parentRunRef = clone(snapshot.parentRunRef || null);
|
|
417
|
+
run.subgraphDepth = Number(snapshot.subgraphDepth || 0);
|
|
418
|
+
run.definitionPath = clone(
|
|
419
|
+
snapshot.definitionPath || [run.compiled.definitionId],
|
|
420
|
+
);
|
|
421
|
+
for (const field of [
|
|
422
|
+
"loopStates",
|
|
423
|
+
"iterationFrames",
|
|
424
|
+
"loopDecisionCache",
|
|
425
|
+
"subgraphRuns",
|
|
426
|
+
"nodeStates",
|
|
427
|
+
"attempts",
|
|
428
|
+
"agents",
|
|
429
|
+
"producerLeases",
|
|
430
|
+
"artifacts",
|
|
431
|
+
"effects",
|
|
432
|
+
"messages",
|
|
433
|
+
"messageConsumers",
|
|
434
|
+
"handoffs",
|
|
435
|
+
"humanTasks",
|
|
436
|
+
"waitReasons",
|
|
437
|
+
"timers",
|
|
438
|
+
"requestCache",
|
|
439
|
+
"progressDigests",
|
|
440
|
+
"fenceCounters",
|
|
441
|
+
]) {
|
|
442
|
+
run[field] = mapRestore(snapshot[field]);
|
|
443
|
+
}
|
|
444
|
+
return run;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function nodeProjection(run, nodeId) {
|
|
448
|
+
const state = run.nodeStates.get(nodeId);
|
|
449
|
+
return Object.freeze({
|
|
450
|
+
nodeId,
|
|
451
|
+
status: state.status,
|
|
452
|
+
attemptIds: Object.freeze([...state.attemptIds]),
|
|
453
|
+
acceptedAttemptId: state.acceptedAttemptId,
|
|
454
|
+
blockedRoot: state.blockedRoot,
|
|
455
|
+
iterationPath: Object.freeze([...(state.iterationPath || [])]),
|
|
456
|
+
createdAt: state.createdAt,
|
|
457
|
+
updatedAt: state.updatedAt,
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function attemptProjection(attempt) {
|
|
462
|
+
return Object.freeze(clone(attempt));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function runProjection(run) {
|
|
466
|
+
return Object.freeze({
|
|
467
|
+
id: run.id,
|
|
468
|
+
definitionId: run.compiled.definitionId,
|
|
469
|
+
revision: run.compiled.revision,
|
|
470
|
+
revisionDigest: run.revisionDigest,
|
|
471
|
+
occurrenceRef: clone(run.occurrenceRef),
|
|
472
|
+
phase: run.phase,
|
|
473
|
+
status: run.status,
|
|
474
|
+
graphRevision: run.graphRevision,
|
|
475
|
+
authorityDigest: run.authorityDigest,
|
|
476
|
+
budget: clone(run.budget),
|
|
477
|
+
budgetUsed: clone(run.budgetUsed),
|
|
478
|
+
budgetReserved: clone(run.budgetReserved),
|
|
479
|
+
createdAt: run.createdAt,
|
|
480
|
+
completedAt: run.completedAt,
|
|
481
|
+
progressEpoch: run.progressEpoch,
|
|
482
|
+
compensation: Object.freeze(clone(run.compensation)),
|
|
483
|
+
parentRunRef: Object.freeze(clone(run.parentRunRef)),
|
|
484
|
+
subgraphDepth: run.subgraphDepth,
|
|
485
|
+
definitionPath: Object.freeze([...run.definitionPath]),
|
|
486
|
+
loops: Object.freeze(
|
|
487
|
+
[...run.loopStates.values()]
|
|
488
|
+
.sort((left, right) => left.regionId.localeCompare(right.regionId))
|
|
489
|
+
.map((state) => Object.freeze(clone(state))),
|
|
490
|
+
),
|
|
491
|
+
iterationFrames: Object.freeze(
|
|
492
|
+
[...run.iterationFrames.values()]
|
|
493
|
+
.sort((left, right) =>
|
|
494
|
+
left.iterationPath
|
|
495
|
+
.join(".")
|
|
496
|
+
.localeCompare(right.iterationPath.join(".")),
|
|
497
|
+
)
|
|
498
|
+
.map((frame) => Object.freeze(clone(frame))),
|
|
499
|
+
),
|
|
500
|
+
subgraphRuns: Object.freeze(
|
|
501
|
+
[...run.subgraphRuns.values()]
|
|
502
|
+
.sort((left, right) => left.nodeId.localeCompare(right.nodeId))
|
|
503
|
+
.map((relation) => Object.freeze(clone(relation))),
|
|
504
|
+
),
|
|
505
|
+
nodes: Object.freeze(
|
|
506
|
+
run.compiled.topologicalOrder.map((id) => nodeProjection(run, id)),
|
|
507
|
+
),
|
|
508
|
+
attempts: Object.freeze(
|
|
509
|
+
[...run.attempts.values()]
|
|
510
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt))
|
|
511
|
+
.map(attemptProjection),
|
|
512
|
+
),
|
|
513
|
+
artifactIds: Object.freeze([...run.artifacts.keys()].sort()),
|
|
514
|
+
effectIds: Object.freeze([...run.effects.keys()].sort()),
|
|
515
|
+
reconciliationEffectIds: Object.freeze(
|
|
516
|
+
[...run.effects.values()]
|
|
517
|
+
.filter((effect) => effect.status === "unknown")
|
|
518
|
+
.map((effect) => effect.id)
|
|
519
|
+
.sort(),
|
|
520
|
+
),
|
|
521
|
+
pendingHumanTaskIds: Object.freeze(
|
|
522
|
+
[...run.humanTasks.values()]
|
|
523
|
+
.filter((task) => ["open", "claimed"].includes(task.status))
|
|
524
|
+
.map((task) => task.id)
|
|
525
|
+
.sort(),
|
|
526
|
+
),
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function buildRun(compiled, options, now) {
|
|
531
|
+
const createdAt = nowIso(now);
|
|
532
|
+
const run = {
|
|
533
|
+
id: safeIdentifier(options.runId || randomUUID(), "runId"),
|
|
534
|
+
compiled,
|
|
535
|
+
phase: "open",
|
|
536
|
+
status: "running",
|
|
537
|
+
graphRevision: compiled.revision,
|
|
538
|
+
revisionDigest: compiled.revisionDigest,
|
|
539
|
+
occurrenceRef: clone(options.occurrenceRef || null),
|
|
540
|
+
authorityDigest:
|
|
541
|
+
options.authorityDigest ||
|
|
542
|
+
graphDigest(
|
|
543
|
+
{
|
|
544
|
+
definition: compiled.revisionDigest,
|
|
545
|
+
capabilities: compiled.definition.allowedCapabilities,
|
|
546
|
+
workspace: options.workspaceDigest || null,
|
|
547
|
+
},
|
|
548
|
+
"cc.graph.authority/v1",
|
|
549
|
+
),
|
|
550
|
+
budget: clone(options.budget || compiled.definition.budget || {}),
|
|
551
|
+
budgetUsed: emptyBudgetUsage(),
|
|
552
|
+
budgetReserved: emptyBudgetUsage(),
|
|
553
|
+
createdAt,
|
|
554
|
+
completedAt: null,
|
|
555
|
+
cancellationRequested: false,
|
|
556
|
+
progressEpoch: 0,
|
|
557
|
+
compensation: idleCompensationState(),
|
|
558
|
+
parentRunRef: clone(options.parentRunRef || null),
|
|
559
|
+
subgraphDepth: Number(options.subgraphDepth || 0),
|
|
560
|
+
definitionPath: clone(options.definitionPath || [compiled.definitionId]),
|
|
561
|
+
loopStates: new Map(),
|
|
562
|
+
iterationFrames: new Map(),
|
|
563
|
+
loopDecisionCache: new Map(),
|
|
564
|
+
subgraphRuns: new Map(),
|
|
565
|
+
nodeStates: new Map(),
|
|
566
|
+
attempts: new Map(),
|
|
567
|
+
agents: new Map(),
|
|
568
|
+
producerLeases: new Map(),
|
|
569
|
+
artifacts: new Map(),
|
|
570
|
+
effects: new Map(),
|
|
571
|
+
messages: new Map(),
|
|
572
|
+
messageConsumers: new Map(),
|
|
573
|
+
handoffs: new Map(),
|
|
574
|
+
humanTasks: new Map(),
|
|
575
|
+
waitReasons: new Map(),
|
|
576
|
+
timers: new Map(),
|
|
577
|
+
requestCache: new Map(),
|
|
578
|
+
progressDigests: new Map(),
|
|
579
|
+
fenceCounters: new Map(),
|
|
580
|
+
lastEvent: null,
|
|
581
|
+
};
|
|
582
|
+
for (const loop of compiled.definition.loops || []) {
|
|
583
|
+
const iterationPath = [0];
|
|
584
|
+
const frameId = iterationFrameId(run.id, loop.id, iterationPath);
|
|
585
|
+
run.loopStates.set(loop.id, {
|
|
586
|
+
regionId: loop.id,
|
|
587
|
+
status: "active",
|
|
588
|
+
iteration: 0,
|
|
589
|
+
iterationPath,
|
|
590
|
+
frameId,
|
|
591
|
+
maxIterations: loop.maxIterations,
|
|
592
|
+
condition: loop.condition || null,
|
|
593
|
+
conditionEvidenceDigest: null,
|
|
594
|
+
});
|
|
595
|
+
run.iterationFrames.set(frameId, {
|
|
596
|
+
id: frameId,
|
|
597
|
+
runId: run.id,
|
|
598
|
+
regionId: loop.id,
|
|
599
|
+
parentFrameId: null,
|
|
600
|
+
iterationPath,
|
|
601
|
+
status: "active",
|
|
602
|
+
startedAt: createdAt,
|
|
603
|
+
completedAt: null,
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
const compensationNodeIds = new Set(compiled.compensationNodeIds || []);
|
|
607
|
+
for (const nodeId of compiled.topologicalOrder) {
|
|
608
|
+
const loopId = compiled.loopByNode?.[nodeId];
|
|
609
|
+
run.nodeStates.set(nodeId, {
|
|
610
|
+
status: compensationNodeIds.has(nodeId) ? "skipped" : "pending",
|
|
611
|
+
attemptIds: [],
|
|
612
|
+
acceptedAttemptId: null,
|
|
613
|
+
blockedRoot: null,
|
|
614
|
+
iterationPath: loopId
|
|
615
|
+
? [...run.loopStates.get(loopId).iterationPath]
|
|
616
|
+
: [],
|
|
617
|
+
createdAt,
|
|
618
|
+
updatedAt: createdAt,
|
|
619
|
+
});
|
|
620
|
+
run.fenceCounters.set(nodeId, 0);
|
|
621
|
+
}
|
|
622
|
+
return run;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function eventDetails(value) {
|
|
626
|
+
if (value === undefined) return null;
|
|
627
|
+
return clone(value);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function checkBudget(run, usage) {
|
|
631
|
+
for (const field of BUDGET_FIELDS) {
|
|
632
|
+
const delta = Number(usage?.[field] || 0);
|
|
633
|
+
if (!Number.isFinite(delta) || delta < 0) {
|
|
634
|
+
throw kernelError(
|
|
635
|
+
"CC_GRAPH_USAGE_INVALID",
|
|
636
|
+
`usage.${field} must be a non-negative finite number`,
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
const cap = run.budget?.[field];
|
|
640
|
+
const reserved = budgetValue(run.budgetReserved, field);
|
|
641
|
+
if (cap != null && run.budgetUsed[field] + reserved + delta > cap) {
|
|
642
|
+
throw kernelError(
|
|
643
|
+
"CC_GRAPH_BUDGET_EXHAUSTED",
|
|
644
|
+
`GraphRun ${field} budget would be exceeded`,
|
|
645
|
+
{
|
|
646
|
+
field,
|
|
647
|
+
cap,
|
|
648
|
+
used: run.budgetUsed[field],
|
|
649
|
+
reserved,
|
|
650
|
+
requested: delta,
|
|
651
|
+
},
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function addUsage(run, usage) {
|
|
658
|
+
checkBudget(run, usage);
|
|
659
|
+
for (const field of BUDGET_FIELDS) {
|
|
660
|
+
run.budgetUsed[field] += Number(usage?.[field] || 0);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function reserveBudget(run, budget) {
|
|
665
|
+
checkBudget(run, budget);
|
|
666
|
+
for (const field of BUDGET_FIELDS) {
|
|
667
|
+
run.budgetReserved[field] += budgetValue(budget, field);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function settleSubgraphBudget(run, relation, usage) {
|
|
672
|
+
if (relation.budgetSettled === true) return;
|
|
673
|
+
for (const field of BUDGET_FIELDS) {
|
|
674
|
+
const reserved = budgetValue(relation.budgetSlice, field);
|
|
675
|
+
const actual = budgetValue(usage, field);
|
|
676
|
+
if (actual > reserved) {
|
|
677
|
+
throw kernelError(
|
|
678
|
+
"CC_GRAPH_SUBGRAPH_BUDGET_INVARIANT",
|
|
679
|
+
`child ${field} usage exceeds its reserved budget slice`,
|
|
680
|
+
{ field, reserved, actual, childRunId: relation.childRunId },
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
run.budgetReserved[field] = Math.max(
|
|
684
|
+
0,
|
|
685
|
+
budgetValue(run.budgetReserved, field) - reserved,
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
addUsage(run, usage);
|
|
689
|
+
relation.budgetUsed = Object.fromEntries(
|
|
690
|
+
BUDGET_FIELDS.map((field) => [field, budgetValue(usage, field)]),
|
|
691
|
+
);
|
|
692
|
+
relation.budgetSettled = true;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function effectiveDependencyStatus(run, dependency) {
|
|
696
|
+
const status = run.nodeStates.get(dependency).status;
|
|
697
|
+
const loopId = run.compiled.loopByExitNode?.[dependency];
|
|
698
|
+
const loopState = loopId ? run.loopStates.get(loopId) : null;
|
|
699
|
+
if (loopState && ["active", "waiting_condition"].includes(loopState.status)) {
|
|
700
|
+
return "running";
|
|
701
|
+
}
|
|
702
|
+
if (loopState?.status === "failed") return "failed";
|
|
703
|
+
if (loopState?.status === "cancelled") return "cancelled";
|
|
704
|
+
if (loopState?.status === "exhausted") return "budget_exhausted";
|
|
705
|
+
return status;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function refreshLoopStates(run, now) {
|
|
709
|
+
let changed = false;
|
|
710
|
+
for (const loop of run.compiled.definition.loops || []) {
|
|
711
|
+
const loopState = run.loopStates.get(loop.id);
|
|
712
|
+
if (!loopState || loopState.status !== "active") continue;
|
|
713
|
+
const statuses = loop.nodeIds.map(
|
|
714
|
+
(nodeId) => run.nodeStates.get(nodeId).status,
|
|
715
|
+
);
|
|
716
|
+
const failure = statuses.find((status) => FAILURE_NODE.has(status));
|
|
717
|
+
const cancelled = statuses.find((status) => status === "cancelled");
|
|
718
|
+
const frame = run.iterationFrames.get(loopState.frameId);
|
|
719
|
+
if (failure || cancelled) {
|
|
720
|
+
loopState.status = failure ? "failed" : "cancelled";
|
|
721
|
+
if (frame) {
|
|
722
|
+
frame.status = failure ? "failed" : "cancelled";
|
|
723
|
+
frame.completedAt = nowIso(now);
|
|
724
|
+
}
|
|
725
|
+
changed = true;
|
|
726
|
+
} else if (statuses.every((status) => status === "succeeded")) {
|
|
727
|
+
loopState.status = "waiting_condition";
|
|
728
|
+
if (frame) {
|
|
729
|
+
frame.status = "succeeded";
|
|
730
|
+
frame.completedAt = nowIso(now);
|
|
731
|
+
}
|
|
732
|
+
changed = true;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return changed;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function nodeReadiness(run, nodeId) {
|
|
739
|
+
const node = run.compiled.nodes[nodeId];
|
|
740
|
+
const dependencies = run.compiled.dependencies[nodeId] || [];
|
|
741
|
+
if (!dependencies.length) return { ready: true };
|
|
742
|
+
const policies = run.compiled.dependencyPolicies[nodeId] || {};
|
|
743
|
+
const observations = dependencies.map((dependency) => {
|
|
744
|
+
const status = effectiveDependencyStatus(run, dependency);
|
|
745
|
+
const policy = policies[dependency] || "success";
|
|
746
|
+
return {
|
|
747
|
+
dependency,
|
|
748
|
+
status,
|
|
749
|
+
policy,
|
|
750
|
+
terminal: TERMINAL_NODE.has(status),
|
|
751
|
+
satisfied: dependencySatisfied(policy, status),
|
|
752
|
+
};
|
|
753
|
+
});
|
|
754
|
+
const satisfied = observations.filter((entry) => entry.satisfied).length;
|
|
755
|
+
const possible = observations.filter(
|
|
756
|
+
(entry) => entry.satisfied || !entry.terminal,
|
|
757
|
+
).length;
|
|
758
|
+
const join = node.join || "all";
|
|
759
|
+
const threshold =
|
|
760
|
+
join === "any" || join === "race"
|
|
761
|
+
? 1
|
|
762
|
+
: join === "quorum"
|
|
763
|
+
? Math.min(node.quorum || dependencies.length, dependencies.length)
|
|
764
|
+
: dependencies.length;
|
|
765
|
+
if (satisfied >= threshold) return { ready: true, observations };
|
|
766
|
+
if (possible >= threshold)
|
|
767
|
+
return { ready: false, waiting: true, observations };
|
|
768
|
+
const mismatch = observations.find(
|
|
769
|
+
(entry) => entry.terminal && !entry.satisfied,
|
|
770
|
+
);
|
|
771
|
+
return {
|
|
772
|
+
ready: false,
|
|
773
|
+
waiting: false,
|
|
774
|
+
terminalStatus: dependencyMismatchStatus(
|
|
775
|
+
mismatch?.policy || "success",
|
|
776
|
+
mismatch?.status || "blocked",
|
|
777
|
+
),
|
|
778
|
+
blockedRoot: mismatch?.dependency || null,
|
|
779
|
+
observations,
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function propagate(run, now) {
|
|
784
|
+
let changed = false;
|
|
785
|
+
for (;;) {
|
|
786
|
+
let passChanged = false;
|
|
787
|
+
for (const nodeId of run.compiled.topologicalOrder) {
|
|
788
|
+
const state = run.nodeStates.get(nodeId);
|
|
789
|
+
if (state.status !== "pending") continue;
|
|
790
|
+
const readiness = nodeReadiness(run, nodeId);
|
|
791
|
+
if (!readiness.terminalStatus) continue;
|
|
792
|
+
state.status = readiness.terminalStatus;
|
|
793
|
+
state.blockedRoot = readiness.blockedRoot;
|
|
794
|
+
state.updatedAt = nowIso(now);
|
|
795
|
+
passChanged = true;
|
|
796
|
+
changed = true;
|
|
797
|
+
}
|
|
798
|
+
if (!passChanged) break;
|
|
799
|
+
}
|
|
800
|
+
return changed;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function effectivePriority(run, nodeId, now, agingWindowMs) {
|
|
804
|
+
const node = run.compiled.nodes[nodeId];
|
|
805
|
+
const state = run.nodeStates.get(nodeId);
|
|
806
|
+
const base = Number(node.priority || 0);
|
|
807
|
+
const ageMs = Math.max(0, now - Date.parse(state.createdAt));
|
|
808
|
+
const aging = Math.min(1000, Math.floor(ageMs / agingWindowMs));
|
|
809
|
+
let donation = base;
|
|
810
|
+
for (const descendantId of run.compiled.descendants[nodeId] || []) {
|
|
811
|
+
const descendantState = run.nodeStates.get(descendantId);
|
|
812
|
+
if (!TERMINAL_NODE.has(descendantState.status)) {
|
|
813
|
+
donation = Math.max(
|
|
814
|
+
donation,
|
|
815
|
+
Number(run.compiled.nodes[descendantId].priority || 0),
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
const criticalPathBoost = (run.compiled.descendants[nodeId] || []).filter(
|
|
820
|
+
(id) => !TERMINAL_NODE.has(run.nodeStates.get(id).status),
|
|
821
|
+
).length;
|
|
822
|
+
return {
|
|
823
|
+
base,
|
|
824
|
+
donation: Math.max(0, donation - base),
|
|
825
|
+
aging,
|
|
826
|
+
criticalPathBoost,
|
|
827
|
+
total: Math.max(base, donation) + aging + criticalPathBoost,
|
|
828
|
+
queueWaitMs: ageMs,
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function activeAttemptsForAgent(run, agentId, now) {
|
|
833
|
+
return [...run.attempts.values()].filter(
|
|
834
|
+
(attempt) => attempt.agentId === agentId && attemptIsLive(attempt, now),
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function activeWriteConflict(run, node, now) {
|
|
839
|
+
if (node.effectClass !== "workspace_write") return null;
|
|
840
|
+
if (node.workspaceIsolation === "worktree") return null;
|
|
841
|
+
for (const attempt of run.attempts.values()) {
|
|
842
|
+
if (!attemptIsLive(attempt, now) || attempt.role !== "executor") continue;
|
|
843
|
+
const activeNode = run.compiled.nodes[attempt.nodeId];
|
|
844
|
+
if (!activeNode || activeNode.effectClass !== "workspace_write") continue;
|
|
845
|
+
if (
|
|
846
|
+
(node.writeSet || []).some((left) =>
|
|
847
|
+
(activeNode.writeSet || []).some((right) =>
|
|
848
|
+
writeScopesOverlap(left, right),
|
|
849
|
+
),
|
|
850
|
+
)
|
|
851
|
+
) {
|
|
852
|
+
return attempt;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function sweepExpirations(run, now) {
|
|
859
|
+
let changed = false;
|
|
860
|
+
for (const lease of run.producerLeases.values()) {
|
|
861
|
+
if (lease.status === "active" && lease.expiresAtMs <= now) {
|
|
862
|
+
lease.status = "expired";
|
|
863
|
+
lease.updatedAt = nowIso(() => now);
|
|
864
|
+
changed = true;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
for (const attempt of run.attempts.values()) {
|
|
868
|
+
if (ACTIVE_ATTEMPT.has(attempt.status) && attempt.expiresAtMs <= now) {
|
|
869
|
+
attempt.status = "expired";
|
|
870
|
+
attempt.updatedAt = nowIso(() => now);
|
|
871
|
+
const nodeState = run.nodeStates.get(attempt.nodeId);
|
|
872
|
+
if (
|
|
873
|
+
nodeState.status === "running" &&
|
|
874
|
+
nodeState.acceptedAttemptId == null
|
|
875
|
+
) {
|
|
876
|
+
nodeState.status = "pending";
|
|
877
|
+
nodeState.updatedAt = nowIso(() => now);
|
|
878
|
+
}
|
|
879
|
+
changed = true;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
for (const handoff of run.handoffs.values()) {
|
|
883
|
+
if (
|
|
884
|
+
["offered", "accepted"].includes(handoff.status) &&
|
|
885
|
+
handoff.expiresAtMs <= now
|
|
886
|
+
) {
|
|
887
|
+
handoff.status = "expired";
|
|
888
|
+
handoff.updatedAt = nowIso(() => now);
|
|
889
|
+
changed = true;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
for (const task of run.humanTasks.values()) {
|
|
893
|
+
if (["open", "claimed"].includes(task.status) && task.expiresAtMs <= now) {
|
|
894
|
+
task.status = "expired";
|
|
895
|
+
task.updatedAt = nowIso(() => now);
|
|
896
|
+
const state = run.nodeStates.get(task.nodeId);
|
|
897
|
+
state.status = "failed";
|
|
898
|
+
state.blockedRoot = task.id;
|
|
899
|
+
state.updatedAt = nowIso(() => now);
|
|
900
|
+
changed = true;
|
|
901
|
+
} else if (task.status === "claimed" && task.claimExpiresAtMs <= now) {
|
|
902
|
+
task.status = "open";
|
|
903
|
+
task.claimActorId = null;
|
|
904
|
+
task.claimLeaseId = null;
|
|
905
|
+
task.claimExpiresAtMs = null;
|
|
906
|
+
task.updatedAt = nowIso(() => now);
|
|
907
|
+
changed = true;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
for (const timer of run.timers.values()) {
|
|
911
|
+
if (timer.status === "pending" && timer.dueAtMs <= now) {
|
|
912
|
+
timer.status = "ready";
|
|
913
|
+
timer.updatedAt = nowIso(() => now);
|
|
914
|
+
changed = true;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return changed;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function waitGraphCycles(run) {
|
|
921
|
+
const adjacency = new Map();
|
|
922
|
+
for (const [nodeId, reason] of run.waitReasons) {
|
|
923
|
+
if (reason.ownerNodeId) {
|
|
924
|
+
const values = adjacency.get(nodeId) || [];
|
|
925
|
+
values.push(reason.ownerNodeId);
|
|
926
|
+
adjacency.set(nodeId, values);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
let index = 0;
|
|
930
|
+
const stack = [];
|
|
931
|
+
const state = new Map();
|
|
932
|
+
const components = [];
|
|
933
|
+
const visit = (node) => {
|
|
934
|
+
const entry = { index, low: index, onStack: true };
|
|
935
|
+
index += 1;
|
|
936
|
+
state.set(node, entry);
|
|
937
|
+
stack.push(node);
|
|
938
|
+
for (const target of adjacency.get(node) || []) {
|
|
939
|
+
if (!state.has(target)) {
|
|
940
|
+
visit(target);
|
|
941
|
+
entry.low = Math.min(entry.low, state.get(target).low);
|
|
942
|
+
} else if (state.get(target).onStack) {
|
|
943
|
+
entry.low = Math.min(entry.low, state.get(target).index);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (entry.low === entry.index) {
|
|
947
|
+
const component = [];
|
|
948
|
+
for (;;) {
|
|
949
|
+
const value = stack.pop();
|
|
950
|
+
state.get(value).onStack = false;
|
|
951
|
+
component.push(value);
|
|
952
|
+
if (value === node) break;
|
|
953
|
+
}
|
|
954
|
+
if (
|
|
955
|
+
component.length > 1 ||
|
|
956
|
+
(component.length === 1 &&
|
|
957
|
+
(adjacency.get(component[0]) || []).includes(component[0]))
|
|
958
|
+
) {
|
|
959
|
+
components.push(component.sort());
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
for (const node of adjacency.keys()) if (!state.has(node)) visit(node);
|
|
964
|
+
return components.sort((left, right) => left[0].localeCompare(right[0]));
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function currentCompensationEntry(run) {
|
|
968
|
+
if (run.compensation?.status !== "running") return null;
|
|
969
|
+
return run.compensation.plan[run.compensation.currentIndex] || null;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function compensationAssignment(run, nodeId) {
|
|
973
|
+
const entry = currentCompensationEntry(run);
|
|
974
|
+
return entry?.compensationNodeId === nodeId ? entry : null;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
function sameIterationPath(left, right) {
|
|
978
|
+
return JSON.stringify(left || []) === JSON.stringify(right || []);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
function compareIterationPath(left, right) {
|
|
982
|
+
const a = left || [];
|
|
983
|
+
const b = right || [];
|
|
984
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
985
|
+
if (a[index] == null) return -1;
|
|
986
|
+
if (b[index] == null) return 1;
|
|
987
|
+
if (a[index] !== b[index]) return a[index] - b[index];
|
|
988
|
+
}
|
|
989
|
+
return 0;
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function committedEffectsForNode(run, nodeId, iterationPath = null) {
|
|
993
|
+
return [...run.effects.values()]
|
|
994
|
+
.filter(
|
|
995
|
+
(effect) =>
|
|
996
|
+
effect.nodeId === nodeId &&
|
|
997
|
+
effect.status === "committed" &&
|
|
998
|
+
(iterationPath == null ||
|
|
999
|
+
sameIterationPath(effect.iterationPath, iterationPath)),
|
|
1000
|
+
)
|
|
1001
|
+
.sort(
|
|
1002
|
+
(left, right) =>
|
|
1003
|
+
compareIterationPath(left.iterationPath, right.iterationPath) ||
|
|
1004
|
+
left.createdAt.localeCompare(right.createdAt) ||
|
|
1005
|
+
left.id.localeCompare(right.id),
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
function completeCompensationStep(run, entry, now) {
|
|
1010
|
+
const compensationEffects = committedEffectsForNode(
|
|
1011
|
+
run,
|
|
1012
|
+
entry.compensationNodeId,
|
|
1013
|
+
entry.iterationPath,
|
|
1014
|
+
);
|
|
1015
|
+
if (compensationEffects.length === 0) {
|
|
1016
|
+
throw kernelError(
|
|
1017
|
+
"CC_GRAPH_COMPENSATION_RECEIPT_REQUIRED",
|
|
1018
|
+
`compensation node requires a committed effect receipt: ${entry.compensationNodeId}`,
|
|
1019
|
+
);
|
|
1020
|
+
}
|
|
1021
|
+
const compensationEffect = compensationEffects.at(-1);
|
|
1022
|
+
const sourceEffects = entry.effectIds.map((effectId) =>
|
|
1023
|
+
run.effects.get(effectId),
|
|
1024
|
+
);
|
|
1025
|
+
if (
|
|
1026
|
+
sourceEffects.some(
|
|
1027
|
+
(effect) =>
|
|
1028
|
+
!effect ||
|
|
1029
|
+
effect.status !== "committed" ||
|
|
1030
|
+
!sameIterationPath(effect.iterationPath, entry.iterationPath),
|
|
1031
|
+
)
|
|
1032
|
+
) {
|
|
1033
|
+
throw kernelError(
|
|
1034
|
+
"CC_GRAPH_COMPENSATION_SOURCE_RECEIPT_INVALID",
|
|
1035
|
+
`compensation source receipts changed for ${entry.nodeId}`,
|
|
1036
|
+
);
|
|
1037
|
+
}
|
|
1038
|
+
for (const effect of sourceEffects) {
|
|
1039
|
+
effect.status = "compensated";
|
|
1040
|
+
effect.compensationEffectId = compensationEffect.id;
|
|
1041
|
+
effect.updatedAt = nowIso(() => now);
|
|
1042
|
+
}
|
|
1043
|
+
run.compensation.completedNodeIds.push(entry.nodeId);
|
|
1044
|
+
run.compensation.completedEntries.push({
|
|
1045
|
+
nodeId: entry.nodeId,
|
|
1046
|
+
iterationPath: [...entry.iterationPath],
|
|
1047
|
+
effectIds: [...entry.effectIds],
|
|
1048
|
+
compensationEffectId: compensationEffect.id,
|
|
1049
|
+
});
|
|
1050
|
+
run.compensation.currentIndex += 1;
|
|
1051
|
+
if (run.compensation.currentIndex >= run.compensation.plan.length) {
|
|
1052
|
+
run.compensation.status = "completed";
|
|
1053
|
+
run.compensation.completedAt = nowIso(() => now);
|
|
1054
|
+
run.status = run.compensation.terminalStatus;
|
|
1055
|
+
run.completedAt = nowIso(() => now);
|
|
1056
|
+
} else {
|
|
1057
|
+
const next = run.compensation.plan[run.compensation.currentIndex];
|
|
1058
|
+
const state = run.nodeStates.get(next.compensationNodeId);
|
|
1059
|
+
state.status = "pending";
|
|
1060
|
+
state.acceptedAttemptId = null;
|
|
1061
|
+
state.blockedRoot = null;
|
|
1062
|
+
state.iterationPath = [...next.iterationPath];
|
|
1063
|
+
state.updatedAt = nowIso(() => now);
|
|
1064
|
+
run.status = "running";
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function failCompensation(run, entry, error, now) {
|
|
1069
|
+
run.compensation.status = "failed";
|
|
1070
|
+
run.compensation.failure = {
|
|
1071
|
+
nodeId: entry.nodeId,
|
|
1072
|
+
compensationNodeId: entry.compensationNodeId,
|
|
1073
|
+
iterationPath: [...entry.iterationPath],
|
|
1074
|
+
effectIds: [...entry.effectIds],
|
|
1075
|
+
error: String(error || "compensation_failed").slice(0, 4096),
|
|
1076
|
+
};
|
|
1077
|
+
run.compensation.completedAt = nowIso(() => now);
|
|
1078
|
+
run.status = "reconciliation_required";
|
|
1079
|
+
run.completedAt = null;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
function terminalAlgebra(run) {
|
|
1083
|
+
const statuses = [...run.nodeStates.values()].map((state) => state.status);
|
|
1084
|
+
const successes = statuses.filter((status) => status === "succeeded").length;
|
|
1085
|
+
const failures = statuses.filter((status) => FAILURE_NODE.has(status)).length;
|
|
1086
|
+
const cancelled = statuses.filter((status) => status === "cancelled").length;
|
|
1087
|
+
const skipped = statuses.filter((status) => status === "skipped").length;
|
|
1088
|
+
if (statuses.every((status) => status === "cancelled")) return "cancelled";
|
|
1089
|
+
if (statuses.every((status) => status === "skipped")) return "blocked";
|
|
1090
|
+
if (failures > 0 && successes > 0) return "partial";
|
|
1091
|
+
if (failures > 0) return "failed";
|
|
1092
|
+
if (cancelled > 0 && successes > 0) return "partial";
|
|
1093
|
+
if (cancelled > 0) return "cancelled";
|
|
1094
|
+
if (successes > 0 || skipped > 0) return "succeeded";
|
|
1095
|
+
return "blocked";
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
function classifyQuiescence(run, now) {
|
|
1099
|
+
if (run.compensation?.status === "failed") {
|
|
1100
|
+
return "reconciliation_required";
|
|
1101
|
+
}
|
|
1102
|
+
if (run.compensation?.status === "completed") {
|
|
1103
|
+
return run.compensation.terminalStatus || "failed";
|
|
1104
|
+
}
|
|
1105
|
+
if (TERMINAL_RUN.has(run.status)) return run.status;
|
|
1106
|
+
if (run.phase === "open") return "running";
|
|
1107
|
+
if (
|
|
1108
|
+
[...run.producerLeases.values()].some((lease) => producerIsLive(lease, now))
|
|
1109
|
+
) {
|
|
1110
|
+
return "running";
|
|
1111
|
+
}
|
|
1112
|
+
if (
|
|
1113
|
+
[...run.attempts.values()].some((attempt) =>
|
|
1114
|
+
ACTIVE_ATTEMPT.has(attempt.status),
|
|
1115
|
+
)
|
|
1116
|
+
) {
|
|
1117
|
+
return "running";
|
|
1118
|
+
}
|
|
1119
|
+
if ([...run.effects.values()].some((effect) => effect.status === "started")) {
|
|
1120
|
+
return "running";
|
|
1121
|
+
}
|
|
1122
|
+
if (
|
|
1123
|
+
[...run.attempts.values()].some(
|
|
1124
|
+
(attempt) => attempt.status === "unknown",
|
|
1125
|
+
) ||
|
|
1126
|
+
[...run.effects.values()].some((effect) => effect.status === "unknown") ||
|
|
1127
|
+
[...run.nodeStates.values()].some(
|
|
1128
|
+
(state) => state.status === "reconciliation_required",
|
|
1129
|
+
)
|
|
1130
|
+
) {
|
|
1131
|
+
return "reconciliation_required";
|
|
1132
|
+
}
|
|
1133
|
+
if (
|
|
1134
|
+
[...run.humanTasks.values()].some((task) =>
|
|
1135
|
+
["open", "claimed"].includes(task.status),
|
|
1136
|
+
)
|
|
1137
|
+
) {
|
|
1138
|
+
return "waiting_human";
|
|
1139
|
+
}
|
|
1140
|
+
if (
|
|
1141
|
+
[...run.messages.values()].some((message) =>
|
|
1142
|
+
["admitted", "delivered", "read"].includes(message.status),
|
|
1143
|
+
) ||
|
|
1144
|
+
[...run.timers.values()].some((timer) => timer.status === "pending")
|
|
1145
|
+
) {
|
|
1146
|
+
return "waiting_external";
|
|
1147
|
+
}
|
|
1148
|
+
if (
|
|
1149
|
+
[...run.loopStates.values()].some(
|
|
1150
|
+
(loopState) => loopState.status === "waiting_condition",
|
|
1151
|
+
) ||
|
|
1152
|
+
[...run.subgraphRuns.values()].some((relation) =>
|
|
1153
|
+
["starting", "running"].includes(relation.status),
|
|
1154
|
+
)
|
|
1155
|
+
) {
|
|
1156
|
+
return "waiting_external";
|
|
1157
|
+
}
|
|
1158
|
+
const cycles = waitGraphCycles(run);
|
|
1159
|
+
if (cycles.length) return "deadlocked";
|
|
1160
|
+
const pending = [...run.nodeStates.entries()].filter(
|
|
1161
|
+
([, state]) => state.status === "pending",
|
|
1162
|
+
);
|
|
1163
|
+
const ready = pending.filter(([nodeId]) => nodeReadiness(run, nodeId).ready);
|
|
1164
|
+
if (ready.length) return "running";
|
|
1165
|
+
if (pending.length) {
|
|
1166
|
+
const reasons = pending.map(([nodeId]) => run.waitReasons.get(nodeId));
|
|
1167
|
+
if (reasons.some((reason) => reason?.kind === "input"))
|
|
1168
|
+
return "waiting_input";
|
|
1169
|
+
if (reasons.some(Boolean)) return "waiting_external";
|
|
1170
|
+
return "blocked";
|
|
1171
|
+
}
|
|
1172
|
+
if (
|
|
1173
|
+
[...run.nodeStates.values()].every((state) =>
|
|
1174
|
+
TERMINAL_NODE.has(state.status),
|
|
1175
|
+
)
|
|
1176
|
+
) {
|
|
1177
|
+
return terminalAlgebra(run);
|
|
1178
|
+
}
|
|
1179
|
+
return "running";
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
export class GraphKernel {
|
|
1183
|
+
constructor({
|
|
1184
|
+
eventStore = new GraphEventStore(),
|
|
1185
|
+
now = Date.now,
|
|
1186
|
+
createId = randomUUID,
|
|
1187
|
+
agingWindowMs = 1000,
|
|
1188
|
+
maxPendingMessagesPerAgent = 100,
|
|
1189
|
+
maxLivelockRepeats = 8,
|
|
1190
|
+
} = {}) {
|
|
1191
|
+
this.eventStore = eventStore;
|
|
1192
|
+
this.now = now;
|
|
1193
|
+
this.createId = createId;
|
|
1194
|
+
this.agingWindowMs = Math.max(1, Number(agingWindowMs) || 1000);
|
|
1195
|
+
this.maxPendingMessagesPerAgent = Math.max(
|
|
1196
|
+
1,
|
|
1197
|
+
Number(maxPendingMessagesPerAgent) || 100,
|
|
1198
|
+
);
|
|
1199
|
+
this.maxLivelockRepeats = Math.max(2, Number(maxLivelockRepeats) || 8);
|
|
1200
|
+
this.runs = new Map();
|
|
1201
|
+
this.occurrences = new Map();
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
_run(runId) {
|
|
1205
|
+
const run = this.runs.get(safeIdentifier(runId, "runId"));
|
|
1206
|
+
if (!run) {
|
|
1207
|
+
throw kernelError(
|
|
1208
|
+
"CC_GRAPH_RUN_NOT_FOUND",
|
|
1209
|
+
`GraphRun not found: ${runId}`,
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
return run;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
_loadRun(runId) {
|
|
1216
|
+
const id = safeIdentifier(runId, "runId");
|
|
1217
|
+
if (this.runs.has(id)) return this.runs.get(id);
|
|
1218
|
+
try {
|
|
1219
|
+
if (this.eventStore.read(id).length > 0) {
|
|
1220
|
+
this.recoverRun(id);
|
|
1221
|
+
return this.runs.get(id);
|
|
1222
|
+
}
|
|
1223
|
+
} catch (error) {
|
|
1224
|
+
if (error?.code !== "CC_ROLLOUT_THREAD_NOT_FOUND") throw error;
|
|
1225
|
+
}
|
|
1226
|
+
return null;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
_transaction(run, type, details, mutator, options = {}) {
|
|
1230
|
+
if (TERMINAL_RUN.has(run.status) && options.allowTerminal !== true) {
|
|
1231
|
+
throw kernelError(
|
|
1232
|
+
"CC_GRAPH_RUN_TERMINAL",
|
|
1233
|
+
`GraphRun is terminal: ${run.status}`,
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
const before = stateSnapshot(run);
|
|
1237
|
+
try {
|
|
1238
|
+
const result = mutator();
|
|
1239
|
+
run.progressEpoch += 1;
|
|
1240
|
+
const snapshot = stateSnapshot(run);
|
|
1241
|
+
const event = this.eventStore.append(
|
|
1242
|
+
run.id,
|
|
1243
|
+
type,
|
|
1244
|
+
{ details: eventDetails(details), state: snapshot },
|
|
1245
|
+
{
|
|
1246
|
+
idempotencyKey: options.idempotencyKey || null,
|
|
1247
|
+
traceId: options.traceId || null,
|
|
1248
|
+
},
|
|
1249
|
+
);
|
|
1250
|
+
run.lastEvent = event;
|
|
1251
|
+
return result;
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
restoreState(run, before);
|
|
1254
|
+
throw error;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
startRun(compiledGraph, options = {}) {
|
|
1259
|
+
const compiled = assertCompiledGraph(compiledGraph);
|
|
1260
|
+
const occurrence = options.occurrenceRef || null;
|
|
1261
|
+
const occurrenceKey = occurrence
|
|
1262
|
+
? `${occurrence.jobRevision || ""}\0${occurrence.occurrenceId || occurrence.idempotencyKey || ""}`
|
|
1263
|
+
: null;
|
|
1264
|
+
if (occurrenceKey && this.occurrences.has(occurrenceKey)) {
|
|
1265
|
+
const existing = this._run(this.occurrences.get(occurrenceKey));
|
|
1266
|
+
if (existing.revisionDigest !== compiled.revisionDigest) {
|
|
1267
|
+
throw kernelError(
|
|
1268
|
+
"CC_GRAPH_OCCURRENCE_CONFLICT",
|
|
1269
|
+
"occurrence was already bound to a different GraphRevision",
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
return runProjection(existing);
|
|
1273
|
+
}
|
|
1274
|
+
const run = buildRun(compiled, options, this.now);
|
|
1275
|
+
if (this.runs.has(run.id)) {
|
|
1276
|
+
throw kernelError(
|
|
1277
|
+
"CC_GRAPH_RUN_CONFLICT",
|
|
1278
|
+
`GraphRun id already exists: ${run.id}`,
|
|
1279
|
+
);
|
|
1280
|
+
}
|
|
1281
|
+
this.eventStore.start(run.id, {
|
|
1282
|
+
definitionId: compiled.definitionId,
|
|
1283
|
+
revisionDigest: compiled.revisionDigest,
|
|
1284
|
+
});
|
|
1285
|
+
this.runs.set(run.id, run);
|
|
1286
|
+
try {
|
|
1287
|
+
this._transaction(
|
|
1288
|
+
run,
|
|
1289
|
+
"run.started",
|
|
1290
|
+
{
|
|
1291
|
+
definitionId: compiled.definitionId,
|
|
1292
|
+
revisionDigest: compiled.revisionDigest,
|
|
1293
|
+
occurrenceRef: occurrence,
|
|
1294
|
+
parentRunRef: run.parentRunRef,
|
|
1295
|
+
subgraphDepth: run.subgraphDepth,
|
|
1296
|
+
definitionPath: run.definitionPath,
|
|
1297
|
+
},
|
|
1298
|
+
() => {},
|
|
1299
|
+
{ idempotencyKey: `run-start:${run.id}` },
|
|
1300
|
+
);
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
this.runs.delete(run.id);
|
|
1303
|
+
throw error;
|
|
1304
|
+
}
|
|
1305
|
+
if (occurrenceKey) this.occurrences.set(occurrenceKey, run.id);
|
|
1306
|
+
return runProjection(run);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
recoverRun(runId) {
|
|
1310
|
+
const id = safeIdentifier(runId, "runId");
|
|
1311
|
+
const events = this.eventStore.read(id);
|
|
1312
|
+
const latest = [...events]
|
|
1313
|
+
.reverse()
|
|
1314
|
+
.find((event) => event.payload?.state?.version === 1);
|
|
1315
|
+
if (!latest) {
|
|
1316
|
+
throw kernelError(
|
|
1317
|
+
"CC_GRAPH_RECOVERY_UNAVAILABLE",
|
|
1318
|
+
`GraphRun has no recoverable state: ${id}`,
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
const snapshot = latest.payload.state;
|
|
1322
|
+
const run = { id, lastEvent: latest };
|
|
1323
|
+
restoreState(run, snapshot);
|
|
1324
|
+
run.lastEvent = latest;
|
|
1325
|
+
this.runs.set(id, run);
|
|
1326
|
+
if (run.occurrenceRef) {
|
|
1327
|
+
const key = `${run.occurrenceRef.jobRevision || ""}\0${run.occurrenceRef.occurrenceId || run.occurrenceRef.idempotencyKey || ""}`;
|
|
1328
|
+
this.occurrences.set(key, id);
|
|
1329
|
+
}
|
|
1330
|
+
const uncertainEffects = [...run.effects.values()].filter(
|
|
1331
|
+
(effect) => effect.status === "started",
|
|
1332
|
+
);
|
|
1333
|
+
if (uncertainEffects.length) {
|
|
1334
|
+
this._transaction(
|
|
1335
|
+
run,
|
|
1336
|
+
"effect.recovery_unknown",
|
|
1337
|
+
{ effectIds: uncertainEffects.map((effect) => effect.id).sort() },
|
|
1338
|
+
() => {
|
|
1339
|
+
for (const effect of uncertainEffects) {
|
|
1340
|
+
effect.status = "unknown";
|
|
1341
|
+
effect.updatedAt = nowIso(this.now);
|
|
1342
|
+
const attempt = run.attempts.get(effect.attemptId);
|
|
1343
|
+
if (attempt && ACTIVE_ATTEMPT.has(attempt.status)) {
|
|
1344
|
+
attempt.status = "unknown";
|
|
1345
|
+
attempt.participationStatus = "reconciliation_required";
|
|
1346
|
+
attempt.updatedAt = nowIso(this.now);
|
|
1347
|
+
}
|
|
1348
|
+
const state = run.nodeStates.get(effect.nodeId);
|
|
1349
|
+
if (state) {
|
|
1350
|
+
state.status = "reconciliation_required";
|
|
1351
|
+
state.updatedAt = nowIso(this.now);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
run.status = "reconciliation_required";
|
|
1355
|
+
},
|
|
1356
|
+
{ idempotencyKey: `effect-recovery:${latest.hash}` },
|
|
1357
|
+
);
|
|
1358
|
+
}
|
|
1359
|
+
return runProjection(run);
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
getRun(runId) {
|
|
1363
|
+
return runProjection(this._run(runId));
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
events(runId, options = {}) {
|
|
1367
|
+
return this.eventStore.read(safeIdentifier(runId, "runId"), options);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
registerAgent(runId, { agentId, capacity = 1, resident = true } = {}) {
|
|
1371
|
+
const run = this._run(runId);
|
|
1372
|
+
const id = safeIdentifier(agentId, "agentId");
|
|
1373
|
+
return this._transaction(
|
|
1374
|
+
run,
|
|
1375
|
+
"agent.registered",
|
|
1376
|
+
{ agentId: id, capacity, resident },
|
|
1377
|
+
() => {
|
|
1378
|
+
const existing = run.agents.get(id);
|
|
1379
|
+
const agent = {
|
|
1380
|
+
id,
|
|
1381
|
+
capacity: Math.max(1, Number(capacity) || 1),
|
|
1382
|
+
resident: resident !== false,
|
|
1383
|
+
status: "idle",
|
|
1384
|
+
registeredAt: existing?.registeredAt || nowIso(this.now),
|
|
1385
|
+
updatedAt: nowIso(this.now),
|
|
1386
|
+
};
|
|
1387
|
+
run.agents.set(id, agent);
|
|
1388
|
+
return Object.freeze(clone(agent));
|
|
1389
|
+
},
|
|
1390
|
+
{},
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
acquireProducerLease(
|
|
1395
|
+
runId,
|
|
1396
|
+
{ producerId, ttlMs = 60_000, leaseId = this.createId() } = {},
|
|
1397
|
+
) {
|
|
1398
|
+
const run = this._run(runId);
|
|
1399
|
+
const id = safeIdentifier(leaseId, "leaseId");
|
|
1400
|
+
const owner = safeIdentifier(producerId, "producerId");
|
|
1401
|
+
return this._transaction(
|
|
1402
|
+
run,
|
|
1403
|
+
"producer.acquired",
|
|
1404
|
+
{ producerId: owner, leaseId: id },
|
|
1405
|
+
() => {
|
|
1406
|
+
if (run.phase !== "open") {
|
|
1407
|
+
throw kernelError(
|
|
1408
|
+
"CC_GRAPH_SEALED",
|
|
1409
|
+
"producer leases cannot be acquired after the graph is sealed",
|
|
1410
|
+
);
|
|
1411
|
+
}
|
|
1412
|
+
const now = this.now();
|
|
1413
|
+
sweepExpirations(run, now);
|
|
1414
|
+
const existing = [...run.producerLeases.values()].find(
|
|
1415
|
+
(lease) => lease.producerId === owner && producerIsLive(lease, now),
|
|
1416
|
+
);
|
|
1417
|
+
if (existing) return Object.freeze(clone(existing));
|
|
1418
|
+
const fence =
|
|
1419
|
+
Math.max(
|
|
1420
|
+
0,
|
|
1421
|
+
...[...run.producerLeases.values()]
|
|
1422
|
+
.filter((lease) => lease.producerId === owner)
|
|
1423
|
+
.map((lease) => lease.fence),
|
|
1424
|
+
) + 1;
|
|
1425
|
+
const lease = {
|
|
1426
|
+
id,
|
|
1427
|
+
producerId: owner,
|
|
1428
|
+
fence,
|
|
1429
|
+
status: "active",
|
|
1430
|
+
createdAt: nowIso(() => now),
|
|
1431
|
+
updatedAt: nowIso(() => now),
|
|
1432
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 60_000)),
|
|
1433
|
+
expiresAtMs: now + finitePositive(ttlMs, 60_000),
|
|
1434
|
+
};
|
|
1435
|
+
run.producerLeases.set(id, lease);
|
|
1436
|
+
return Object.freeze(clone(lease));
|
|
1437
|
+
},
|
|
1438
|
+
{ idempotencyKey: `producer-acquire:${id}` },
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
releaseProducerLease(runId, leaseId, fence) {
|
|
1443
|
+
const run = this._run(runId);
|
|
1444
|
+
const id = safeIdentifier(leaseId, "leaseId");
|
|
1445
|
+
return this._transaction(run, "producer.released", { leaseId: id }, () => {
|
|
1446
|
+
const lease = run.producerLeases.get(id);
|
|
1447
|
+
if (
|
|
1448
|
+
!lease ||
|
|
1449
|
+
lease.fence !== Number(fence) ||
|
|
1450
|
+
lease.status !== "active"
|
|
1451
|
+
) {
|
|
1452
|
+
throw kernelError(
|
|
1453
|
+
"CC_GRAPH_STALE_PRODUCER_LEASE",
|
|
1454
|
+
"producer lease is missing, stale, or inactive",
|
|
1455
|
+
);
|
|
1456
|
+
}
|
|
1457
|
+
lease.status = "released";
|
|
1458
|
+
lease.updatedAt = nowIso(this.now);
|
|
1459
|
+
return Object.freeze(clone(lease));
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
appendGraph(
|
|
1464
|
+
runId,
|
|
1465
|
+
{
|
|
1466
|
+
expectedGraphRevision,
|
|
1467
|
+
requestId,
|
|
1468
|
+
producerLeaseId,
|
|
1469
|
+
producerFence,
|
|
1470
|
+
nodes = [],
|
|
1471
|
+
edges = [],
|
|
1472
|
+
loops = [],
|
|
1473
|
+
subgraphCalls = [],
|
|
1474
|
+
} = {},
|
|
1475
|
+
) {
|
|
1476
|
+
const run = this._run(runId);
|
|
1477
|
+
const key = safeIdentifier(requestId, "requestId");
|
|
1478
|
+
const request = {
|
|
1479
|
+
expectedGraphRevision,
|
|
1480
|
+
producerLeaseId,
|
|
1481
|
+
producerFence,
|
|
1482
|
+
nodes,
|
|
1483
|
+
edges,
|
|
1484
|
+
loops,
|
|
1485
|
+
subgraphCalls,
|
|
1486
|
+
};
|
|
1487
|
+
const requestDigest = graphDigest(request, "cc.graph.append-request/v1");
|
|
1488
|
+
const replay = run.requestCache.get(key);
|
|
1489
|
+
if (replay) {
|
|
1490
|
+
if (replay.digest !== requestDigest) {
|
|
1491
|
+
throw kernelError(
|
|
1492
|
+
"CC_GRAPH_REQUEST_ID_CONFLICT",
|
|
1493
|
+
"dynamic graph requestId was reused with different content",
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
return Object.freeze(clone(replay.result));
|
|
1497
|
+
}
|
|
1498
|
+
return this._transaction(
|
|
1499
|
+
run,
|
|
1500
|
+
"graph.revised",
|
|
1501
|
+
{ requestId: key, requestDigest },
|
|
1502
|
+
() => {
|
|
1503
|
+
if (run.phase !== "open") {
|
|
1504
|
+
throw kernelError(
|
|
1505
|
+
"CC_GRAPH_SEALED",
|
|
1506
|
+
"a sealed GraphRun cannot be extended",
|
|
1507
|
+
);
|
|
1508
|
+
}
|
|
1509
|
+
if (Number(expectedGraphRevision) !== run.graphRevision) {
|
|
1510
|
+
throw kernelError(
|
|
1511
|
+
"CC_GRAPH_REVISION_CONFLICT",
|
|
1512
|
+
"expectedGraphRevision does not match the current revision",
|
|
1513
|
+
{ expectedGraphRevision, currentGraphRevision: run.graphRevision },
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
const now = this.now();
|
|
1517
|
+
sweepExpirations(run, now);
|
|
1518
|
+
const lease = run.producerLeases.get(
|
|
1519
|
+
safeIdentifier(producerLeaseId, "producerLeaseId"),
|
|
1520
|
+
);
|
|
1521
|
+
if (
|
|
1522
|
+
!lease ||
|
|
1523
|
+
lease.fence !== Number(producerFence) ||
|
|
1524
|
+
!producerIsLive(lease, now)
|
|
1525
|
+
) {
|
|
1526
|
+
throw kernelError(
|
|
1527
|
+
"CC_GRAPH_STALE_PRODUCER_LEASE",
|
|
1528
|
+
"dynamic graph mutation requires the current producer lease",
|
|
1529
|
+
);
|
|
1530
|
+
}
|
|
1531
|
+
const definition = {
|
|
1532
|
+
...clone(run.compiled.definition),
|
|
1533
|
+
revision: run.compiled.definition.revision + 1,
|
|
1534
|
+
nodes: [...clone(run.compiled.definition.nodes), ...clone(nodes)],
|
|
1535
|
+
edges: [...clone(run.compiled.definition.edges), ...clone(edges)],
|
|
1536
|
+
loops: [...clone(run.compiled.definition.loops), ...clone(loops)],
|
|
1537
|
+
subgraphCalls: [
|
|
1538
|
+
...clone(run.compiled.definition.subgraphCalls),
|
|
1539
|
+
...clone(subgraphCalls),
|
|
1540
|
+
],
|
|
1541
|
+
};
|
|
1542
|
+
const compiled = compileGraphDefinition(definition, {
|
|
1543
|
+
subgraphs: persistedSubgraphRegistry(
|
|
1544
|
+
run.compiled.subgraphDefinitions,
|
|
1545
|
+
),
|
|
1546
|
+
});
|
|
1547
|
+
const createdAt = nowIso(() => now);
|
|
1548
|
+
const compensationNodeIds = new Set(compiled.compensationNodeIds || []);
|
|
1549
|
+
const addedNodeIds = new Set(nodes.map((node) => node.id));
|
|
1550
|
+
for (const loop of loops) {
|
|
1551
|
+
if (loop.nodeIds.some((nodeId) => !addedNodeIds.has(nodeId))) {
|
|
1552
|
+
throw kernelError(
|
|
1553
|
+
"CC_GRAPH_DYNAMIC_LOOP_BOUNDARY",
|
|
1554
|
+
"a dynamic loop must be added atomically with all of its nodes",
|
|
1555
|
+
{ loopId: loop.id },
|
|
1556
|
+
);
|
|
1557
|
+
}
|
|
1558
|
+
const iterationPath = [0];
|
|
1559
|
+
const frameId = iterationFrameId(run.id, loop.id, iterationPath);
|
|
1560
|
+
run.loopStates.set(loop.id, {
|
|
1561
|
+
regionId: loop.id,
|
|
1562
|
+
status: "active",
|
|
1563
|
+
iteration: 0,
|
|
1564
|
+
iterationPath,
|
|
1565
|
+
frameId,
|
|
1566
|
+
maxIterations: loop.maxIterations,
|
|
1567
|
+
condition: loop.condition || null,
|
|
1568
|
+
conditionEvidenceDigest: null,
|
|
1569
|
+
});
|
|
1570
|
+
run.iterationFrames.set(frameId, {
|
|
1571
|
+
id: frameId,
|
|
1572
|
+
runId: run.id,
|
|
1573
|
+
regionId: loop.id,
|
|
1574
|
+
parentFrameId: null,
|
|
1575
|
+
iterationPath,
|
|
1576
|
+
status: "active",
|
|
1577
|
+
startedAt: createdAt,
|
|
1578
|
+
completedAt: null,
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
for (const node of nodes) {
|
|
1582
|
+
const loopId = compiled.loopByNode?.[node.id];
|
|
1583
|
+
run.nodeStates.set(node.id, {
|
|
1584
|
+
status: compensationNodeIds.has(node.id) ? "skipped" : "pending",
|
|
1585
|
+
attemptIds: [],
|
|
1586
|
+
acceptedAttemptId: null,
|
|
1587
|
+
blockedRoot: null,
|
|
1588
|
+
iterationPath: loopId
|
|
1589
|
+
? [...run.loopStates.get(loopId).iterationPath]
|
|
1590
|
+
: [],
|
|
1591
|
+
createdAt,
|
|
1592
|
+
updatedAt: createdAt,
|
|
1593
|
+
});
|
|
1594
|
+
run.fenceCounters.set(node.id, 0);
|
|
1595
|
+
}
|
|
1596
|
+
for (const compensationNodeId of compensationNodeIds) {
|
|
1597
|
+
const state = run.nodeStates.get(compensationNodeId);
|
|
1598
|
+
if (!state || state.status === "skipped") continue;
|
|
1599
|
+
if (state.status !== "pending" || state.attemptIds.length > 0) {
|
|
1600
|
+
throw kernelError(
|
|
1601
|
+
"CC_GRAPH_COMPENSATION_TARGET_ACTIVE",
|
|
1602
|
+
`dynamic revision cannot convert an active node into a compensation target: ${compensationNodeId}`,
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
state.status = "skipped";
|
|
1606
|
+
state.updatedAt = createdAt;
|
|
1607
|
+
}
|
|
1608
|
+
run.compiled = compiled;
|
|
1609
|
+
run.graphRevision += 1;
|
|
1610
|
+
run.revisionDigest = compiled.revisionDigest;
|
|
1611
|
+
const result = {
|
|
1612
|
+
runId: run.id,
|
|
1613
|
+
graphRevision: run.graphRevision,
|
|
1614
|
+
revisionDigest: run.revisionDigest,
|
|
1615
|
+
addedNodeIds: nodes.map((node) => node.id).sort(),
|
|
1616
|
+
};
|
|
1617
|
+
run.requestCache.set(key, { digest: requestDigest, result });
|
|
1618
|
+
return Object.freeze(clone(result));
|
|
1619
|
+
},
|
|
1620
|
+
{ idempotencyKey: `graph-append:${key}` },
|
|
1621
|
+
);
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
sealRun(runId) {
|
|
1625
|
+
const run = this._run(runId);
|
|
1626
|
+
return this._transaction(
|
|
1627
|
+
run,
|
|
1628
|
+
"graph.sealed",
|
|
1629
|
+
{ graphRevision: run.graphRevision },
|
|
1630
|
+
() => {
|
|
1631
|
+
const now = this.now();
|
|
1632
|
+
sweepExpirations(run, now);
|
|
1633
|
+
const active = [...run.producerLeases.values()].filter((lease) =>
|
|
1634
|
+
producerIsLive(lease, now),
|
|
1635
|
+
);
|
|
1636
|
+
if (active.length) {
|
|
1637
|
+
throw kernelError(
|
|
1638
|
+
"CC_GRAPH_PRODUCERS_ACTIVE",
|
|
1639
|
+
"GraphRun cannot be sealed while producer leases are active",
|
|
1640
|
+
{ producerLeaseIds: active.map((lease) => lease.id) },
|
|
1641
|
+
);
|
|
1642
|
+
}
|
|
1643
|
+
run.phase = "sealed";
|
|
1644
|
+
propagate(run, () => now);
|
|
1645
|
+
if (refreshLoopStates(run, () => now)) propagate(run, () => now);
|
|
1646
|
+
run.status = classifyQuiescence(run, now);
|
|
1647
|
+
if (TERMINAL_RUN.has(run.status)) run.completedAt = nowIso(() => now);
|
|
1648
|
+
return runProjection(run);
|
|
1649
|
+
},
|
|
1650
|
+
{ idempotencyKey: `graph-seal:${run.id}:${run.graphRevision}` },
|
|
1651
|
+
);
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
tick(runId) {
|
|
1655
|
+
const run = this._run(runId);
|
|
1656
|
+
return this._transaction(run, "run.ticked", {}, () => {
|
|
1657
|
+
const now = this.now();
|
|
1658
|
+
sweepExpirations(run, now);
|
|
1659
|
+
propagate(run, () => now);
|
|
1660
|
+
if (refreshLoopStates(run, () => now)) propagate(run, () => now);
|
|
1661
|
+
run.status = classifyQuiescence(run, now);
|
|
1662
|
+
if (TERMINAL_RUN.has(run.status)) run.completedAt ||= nowIso(() => now);
|
|
1663
|
+
return runProjection(run);
|
|
1664
|
+
});
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
advanceLoop(
|
|
1668
|
+
runId,
|
|
1669
|
+
{ regionId, continueLoop, conditionEvidenceDigest, requestId = null } = {},
|
|
1670
|
+
) {
|
|
1671
|
+
const run = this._run(runId);
|
|
1672
|
+
const safeRegionId = safeIdentifier(regionId, "regionId");
|
|
1673
|
+
const evidenceDigest = String(conditionEvidenceDigest || "");
|
|
1674
|
+
if (!/^sha256:[a-f0-9]{64}$/u.test(evidenceDigest)) {
|
|
1675
|
+
throw kernelError(
|
|
1676
|
+
"CC_GRAPH_LOOP_EVIDENCE_REQUIRED",
|
|
1677
|
+
"loop advancement requires a sha256 condition evidence digest",
|
|
1678
|
+
);
|
|
1679
|
+
}
|
|
1680
|
+
if (typeof continueLoop !== "boolean") {
|
|
1681
|
+
throw kernelError(
|
|
1682
|
+
"CC_GRAPH_LOOP_DECISION_INVALID",
|
|
1683
|
+
"continueLoop must be a boolean",
|
|
1684
|
+
);
|
|
1685
|
+
}
|
|
1686
|
+
const loop = run.compiled.loops?.[safeRegionId];
|
|
1687
|
+
const loopState = run.loopStates.get(safeRegionId);
|
|
1688
|
+
if (!loop || !loopState) {
|
|
1689
|
+
throw kernelError(
|
|
1690
|
+
"CC_GRAPH_LOOP_NOT_FOUND",
|
|
1691
|
+
`loop region not found: ${safeRegionId}`,
|
|
1692
|
+
);
|
|
1693
|
+
}
|
|
1694
|
+
if (requestId == null) {
|
|
1695
|
+
throw kernelError(
|
|
1696
|
+
"CC_GRAPH_LOOP_REQUEST_ID_REQUIRED",
|
|
1697
|
+
"loop advancement requires a stable requestId for crash-safe replay",
|
|
1698
|
+
);
|
|
1699
|
+
}
|
|
1700
|
+
const decisionKey = safeIdentifier(requestId, "requestId");
|
|
1701
|
+
const decisionDigest = graphDigest(
|
|
1702
|
+
{
|
|
1703
|
+
regionId: safeRegionId,
|
|
1704
|
+
continueLoop,
|
|
1705
|
+
conditionEvidenceDigest: evidenceDigest,
|
|
1706
|
+
},
|
|
1707
|
+
"cc.graph.loop-decision/v1",
|
|
1708
|
+
);
|
|
1709
|
+
const replay = run.loopDecisionCache.get(decisionKey);
|
|
1710
|
+
if (replay) {
|
|
1711
|
+
if (replay.digest !== decisionDigest) {
|
|
1712
|
+
throw kernelError(
|
|
1713
|
+
"CC_GRAPH_REQUEST_ID_CONFLICT",
|
|
1714
|
+
"loop requestId was reused with a different decision",
|
|
1715
|
+
);
|
|
1716
|
+
}
|
|
1717
|
+
return runProjection(run);
|
|
1718
|
+
}
|
|
1719
|
+
this._transaction(
|
|
1720
|
+
run,
|
|
1721
|
+
continueLoop ? "loop.continued" : "loop.exited",
|
|
1722
|
+
{
|
|
1723
|
+
regionId: safeRegionId,
|
|
1724
|
+
iteration: loopState.iteration,
|
|
1725
|
+
continueLoop,
|
|
1726
|
+
conditionEvidenceDigest: evidenceDigest,
|
|
1727
|
+
requestId: decisionKey,
|
|
1728
|
+
},
|
|
1729
|
+
() => {
|
|
1730
|
+
if (loopState.status !== "waiting_condition") {
|
|
1731
|
+
throw kernelError(
|
|
1732
|
+
"CC_GRAPH_LOOP_NOT_WAITING",
|
|
1733
|
+
`loop body is not awaiting a condition decision: ${safeRegionId}`,
|
|
1734
|
+
);
|
|
1735
|
+
}
|
|
1736
|
+
const now = this.now();
|
|
1737
|
+
loopState.conditionEvidenceDigest = evidenceDigest;
|
|
1738
|
+
if (!continueLoop) {
|
|
1739
|
+
loopState.status = "succeeded";
|
|
1740
|
+
run.loopDecisionCache.set(decisionKey, {
|
|
1741
|
+
digest: decisionDigest,
|
|
1742
|
+
result: "exited",
|
|
1743
|
+
});
|
|
1744
|
+
propagate(run, () => now);
|
|
1745
|
+
refreshLoopStates(run, () => now);
|
|
1746
|
+
run.status = classifyQuiescence(run, now);
|
|
1747
|
+
if (TERMINAL_RUN.has(run.status)) {
|
|
1748
|
+
run.completedAt = nowIso(() => now);
|
|
1749
|
+
}
|
|
1750
|
+
return runProjection(run);
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
const nextIteration = loopState.iteration + 1;
|
|
1754
|
+
if (nextIteration >= loop.maxIterations) {
|
|
1755
|
+
loopState.status = "exhausted";
|
|
1756
|
+
const frame = run.iterationFrames.get(loopState.frameId);
|
|
1757
|
+
if (frame) frame.status = "exhausted";
|
|
1758
|
+
const exitState = run.nodeStates.get(loop.exitNodeId);
|
|
1759
|
+
exitState.status = "budget_exhausted";
|
|
1760
|
+
exitState.blockedRoot = loop.id;
|
|
1761
|
+
exitState.updatedAt = nowIso(() => now);
|
|
1762
|
+
run.loopDecisionCache.set(decisionKey, {
|
|
1763
|
+
digest: decisionDigest,
|
|
1764
|
+
result: "exhausted",
|
|
1765
|
+
});
|
|
1766
|
+
propagate(run, () => now);
|
|
1767
|
+
run.status = "budget_exhausted";
|
|
1768
|
+
run.completedAt = nowIso(() => now);
|
|
1769
|
+
return runProjection(run);
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
const iterationPath = [nextIteration];
|
|
1773
|
+
const frameId = iterationFrameId(run.id, safeRegionId, iterationPath);
|
|
1774
|
+
loopState.status = "active";
|
|
1775
|
+
loopState.iteration = nextIteration;
|
|
1776
|
+
loopState.iterationPath = iterationPath;
|
|
1777
|
+
loopState.frameId = frameId;
|
|
1778
|
+
loopState.conditionEvidenceDigest = null;
|
|
1779
|
+
run.iterationFrames.set(frameId, {
|
|
1780
|
+
id: frameId,
|
|
1781
|
+
runId: run.id,
|
|
1782
|
+
regionId: safeRegionId,
|
|
1783
|
+
parentFrameId: null,
|
|
1784
|
+
iterationPath,
|
|
1785
|
+
status: "active",
|
|
1786
|
+
startedAt: nowIso(() => now),
|
|
1787
|
+
completedAt: null,
|
|
1788
|
+
});
|
|
1789
|
+
for (const nodeId of loop.nodeIds) {
|
|
1790
|
+
const state = run.nodeStates.get(nodeId);
|
|
1791
|
+
state.status = "pending";
|
|
1792
|
+
state.acceptedAttemptId = null;
|
|
1793
|
+
state.blockedRoot = null;
|
|
1794
|
+
state.iterationPath = [...iterationPath];
|
|
1795
|
+
state.updatedAt = nowIso(() => now);
|
|
1796
|
+
}
|
|
1797
|
+
run.loopDecisionCache.set(decisionKey, {
|
|
1798
|
+
digest: decisionDigest,
|
|
1799
|
+
result: "continued",
|
|
1800
|
+
});
|
|
1801
|
+
run.status = "running";
|
|
1802
|
+
run.completedAt = null;
|
|
1803
|
+
return runProjection(run);
|
|
1804
|
+
},
|
|
1805
|
+
{ idempotencyKey: `loop-decision:${decisionKey}` },
|
|
1806
|
+
);
|
|
1807
|
+
return runProjection(run);
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
startSubgraph(
|
|
1811
|
+
parentRunId,
|
|
1812
|
+
nodeId,
|
|
1813
|
+
compiledGraph,
|
|
1814
|
+
{ childRunId = null, seal = true } = {},
|
|
1815
|
+
) {
|
|
1816
|
+
const childCompiled = assertCompiledGraph(compiledGraph);
|
|
1817
|
+
const parent = this._run(parentRunId);
|
|
1818
|
+
const safeNodeId = safeIdentifier(nodeId, "nodeId");
|
|
1819
|
+
const call = parent.compiled.subgraphCalls?.[safeNodeId];
|
|
1820
|
+
const state = parent.nodeStates.get(safeNodeId);
|
|
1821
|
+
if (!call || !state) {
|
|
1822
|
+
throw kernelError(
|
|
1823
|
+
"CC_GRAPH_SUBGRAPH_CALL_NOT_FOUND",
|
|
1824
|
+
`subgraph call not found: ${safeNodeId}`,
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
if (
|
|
1828
|
+
call.definitionId !== childCompiled.definitionId ||
|
|
1829
|
+
call.revisionDigest !== childCompiled.revisionDigest
|
|
1830
|
+
) {
|
|
1831
|
+
throw kernelError(
|
|
1832
|
+
"CC_GRAPH_SUBGRAPH_DIGEST_MISMATCH",
|
|
1833
|
+
`subgraph definition does not match the pinned call: ${safeNodeId}`,
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
const childDepth = parent.subgraphDepth + 1;
|
|
1837
|
+
if (childDepth > call.maxDepth) {
|
|
1838
|
+
throw kernelError(
|
|
1839
|
+
"CC_GRAPH_SUBGRAPH_DEPTH_EXCEEDED",
|
|
1840
|
+
`subgraph depth ${childDepth} exceeds maxDepth ${call.maxDepth}`,
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
if (parent.definitionPath.includes(childCompiled.definitionId)) {
|
|
1844
|
+
throw kernelError(
|
|
1845
|
+
"CC_GRAPH_SUBGRAPH_RECURSION",
|
|
1846
|
+
`recursive subgraph call rejected: ${[
|
|
1847
|
+
...parent.definitionPath,
|
|
1848
|
+
childCompiled.definitionId,
|
|
1849
|
+
].join(" -> ")}`,
|
|
1850
|
+
);
|
|
1851
|
+
}
|
|
1852
|
+
const id = safeIdentifier(
|
|
1853
|
+
childRunId ||
|
|
1854
|
+
deterministicSubgraphRunId(
|
|
1855
|
+
parent.id,
|
|
1856
|
+
safeNodeId,
|
|
1857
|
+
childCompiled.revisionDigest,
|
|
1858
|
+
),
|
|
1859
|
+
"childRunId",
|
|
1860
|
+
);
|
|
1861
|
+
let relation = parent.subgraphRuns.get(safeNodeId);
|
|
1862
|
+
if (relation) {
|
|
1863
|
+
if (
|
|
1864
|
+
relation.childRunId !== id ||
|
|
1865
|
+
relation.revisionDigest !== childCompiled.revisionDigest
|
|
1866
|
+
) {
|
|
1867
|
+
throw kernelError(
|
|
1868
|
+
"CC_GRAPH_SUBGRAPH_CALL_CONFLICT",
|
|
1869
|
+
"subgraph call was already bound to a different child run",
|
|
1870
|
+
);
|
|
1871
|
+
}
|
|
1872
|
+
} else {
|
|
1873
|
+
if (parent.phase !== "sealed") {
|
|
1874
|
+
throw kernelError(
|
|
1875
|
+
"CC_GRAPH_SUBGRAPH_REQUIRES_SEALED_PARENT",
|
|
1876
|
+
"subgraph calls require a sealed parent GraphRun",
|
|
1877
|
+
);
|
|
1878
|
+
}
|
|
1879
|
+
if (
|
|
1880
|
+
state.status !== "pending" ||
|
|
1881
|
+
!nodeReadiness(parent, safeNodeId).ready
|
|
1882
|
+
) {
|
|
1883
|
+
throw kernelError(
|
|
1884
|
+
"CC_GRAPH_NODE_NOT_READY",
|
|
1885
|
+
`Graph node is not ready: ${safeNodeId}`,
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
relation = this._transaction(
|
|
1889
|
+
parent,
|
|
1890
|
+
"subgraph.starting",
|
|
1891
|
+
{
|
|
1892
|
+
nodeId: safeNodeId,
|
|
1893
|
+
childRunId: id,
|
|
1894
|
+
definitionId: childCompiled.definitionId,
|
|
1895
|
+
revisionDigest: childCompiled.revisionDigest,
|
|
1896
|
+
depth: childDepth,
|
|
1897
|
+
budgetSlice: call.budget,
|
|
1898
|
+
inputBindings: call.inputBindings || [],
|
|
1899
|
+
outputBindings: call.outputBindings || [],
|
|
1900
|
+
},
|
|
1901
|
+
() => {
|
|
1902
|
+
const createdAt = nowIso(this.now);
|
|
1903
|
+
reserveBudget(parent, call.budget || {});
|
|
1904
|
+
const value = {
|
|
1905
|
+
nodeId: safeNodeId,
|
|
1906
|
+
childRunId: id,
|
|
1907
|
+
definitionId: childCompiled.definitionId,
|
|
1908
|
+
revisionDigest: childCompiled.revisionDigest,
|
|
1909
|
+
depth: childDepth,
|
|
1910
|
+
inputBindings: clone(call.inputBindings || []),
|
|
1911
|
+
outputBindings: clone(call.outputBindings || []),
|
|
1912
|
+
budgetSlice: clone(call.budget || {}),
|
|
1913
|
+
budgetUsed: null,
|
|
1914
|
+
budgetSettled: false,
|
|
1915
|
+
status: "starting",
|
|
1916
|
+
createdAt,
|
|
1917
|
+
updatedAt: createdAt,
|
|
1918
|
+
completedAt: null,
|
|
1919
|
+
};
|
|
1920
|
+
parent.subgraphRuns.set(safeNodeId, value);
|
|
1921
|
+
state.status = "running";
|
|
1922
|
+
state.updatedAt = createdAt;
|
|
1923
|
+
parent.status = "waiting_external";
|
|
1924
|
+
return clone(value);
|
|
1925
|
+
},
|
|
1926
|
+
{ idempotencyKey: `subgraph-starting:${safeNodeId}:${id}` },
|
|
1927
|
+
);
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
let child = this._loadRun(id);
|
|
1931
|
+
if (child) {
|
|
1932
|
+
if (
|
|
1933
|
+
child.revisionDigest !== childCompiled.revisionDigest ||
|
|
1934
|
+
child.parentRunRef?.runId !== parent.id ||
|
|
1935
|
+
child.parentRunRef?.nodeId !== safeNodeId
|
|
1936
|
+
) {
|
|
1937
|
+
throw kernelError(
|
|
1938
|
+
"CC_GRAPH_SUBGRAPH_RUN_CONFLICT",
|
|
1939
|
+
`child run id is already bound to another call: ${id}`,
|
|
1940
|
+
);
|
|
1941
|
+
}
|
|
1942
|
+
} else {
|
|
1943
|
+
this.startRun(childCompiled, {
|
|
1944
|
+
runId: id,
|
|
1945
|
+
parentRunRef: {
|
|
1946
|
+
runId: parent.id,
|
|
1947
|
+
nodeId: safeNodeId,
|
|
1948
|
+
revisionDigest: parent.revisionDigest,
|
|
1949
|
+
},
|
|
1950
|
+
subgraphDepth: childDepth,
|
|
1951
|
+
definitionPath: [...parent.definitionPath, childCompiled.definitionId],
|
|
1952
|
+
budget: call.budget || {},
|
|
1953
|
+
});
|
|
1954
|
+
child = this._run(id);
|
|
1955
|
+
}
|
|
1956
|
+
if (seal !== false && child.phase === "open") this.sealRun(id);
|
|
1957
|
+
|
|
1958
|
+
relation = parent.subgraphRuns.get(safeNodeId);
|
|
1959
|
+
if (relation.status === "starting") {
|
|
1960
|
+
this._transaction(
|
|
1961
|
+
parent,
|
|
1962
|
+
"subgraph.started",
|
|
1963
|
+
{ nodeId: safeNodeId, childRunId: id },
|
|
1964
|
+
() => {
|
|
1965
|
+
relation.status = "running";
|
|
1966
|
+
relation.updatedAt = nowIso(this.now);
|
|
1967
|
+
parent.status = "waiting_external";
|
|
1968
|
+
},
|
|
1969
|
+
{ idempotencyKey: `subgraph-started:${safeNodeId}:${id}` },
|
|
1970
|
+
);
|
|
1971
|
+
}
|
|
1972
|
+
return Object.freeze({
|
|
1973
|
+
relation: Object.freeze(clone(parent.subgraphRuns.get(safeNodeId))),
|
|
1974
|
+
parentRun: runProjection(parent),
|
|
1975
|
+
childRun: runProjection(child),
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
settleSubgraph(parentRunId, nodeId) {
|
|
1980
|
+
const parent = this._run(parentRunId);
|
|
1981
|
+
const safeNodeId = safeIdentifier(nodeId, "nodeId");
|
|
1982
|
+
const relation = parent.subgraphRuns.get(safeNodeId);
|
|
1983
|
+
if (!relation) {
|
|
1984
|
+
throw kernelError(
|
|
1985
|
+
"CC_GRAPH_SUBGRAPH_NOT_STARTED",
|
|
1986
|
+
`subgraph has not been started: ${safeNodeId}`,
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
if (["succeeded", "failed", "cancelled"].includes(relation.status)) {
|
|
1990
|
+
return runProjection(parent);
|
|
1991
|
+
}
|
|
1992
|
+
const child = this._loadRun(relation.childRunId);
|
|
1993
|
+
if (!child) {
|
|
1994
|
+
throw kernelError(
|
|
1995
|
+
"CC_GRAPH_SUBGRAPH_RUN_NOT_FOUND",
|
|
1996
|
+
`subgraph child run not found: ${relation.childRunId}`,
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
if (!TERMINAL_RUN.has(child.status)) {
|
|
2000
|
+
throw kernelError(
|
|
2001
|
+
"CC_GRAPH_SUBGRAPH_ACTIVE",
|
|
2002
|
+
`subgraph child run is not terminal: ${child.status}`,
|
|
2003
|
+
);
|
|
2004
|
+
}
|
|
2005
|
+
return this._transaction(
|
|
2006
|
+
parent,
|
|
2007
|
+
"subgraph.settled",
|
|
2008
|
+
{
|
|
2009
|
+
nodeId: safeNodeId,
|
|
2010
|
+
childRunId: child.id,
|
|
2011
|
+
childStatus: child.status,
|
|
2012
|
+
},
|
|
2013
|
+
() => {
|
|
2014
|
+
const now = this.now();
|
|
2015
|
+
const state = parent.nodeStates.get(safeNodeId);
|
|
2016
|
+
const succeeded = child.status === "succeeded";
|
|
2017
|
+
relation.status = succeeded
|
|
2018
|
+
? "succeeded"
|
|
2019
|
+
: child.status === "cancelled"
|
|
2020
|
+
? "cancelled"
|
|
2021
|
+
: "failed";
|
|
2022
|
+
relation.updatedAt = nowIso(() => now);
|
|
2023
|
+
relation.completedAt = nowIso(() => now);
|
|
2024
|
+
relation.childStatus = child.status;
|
|
2025
|
+
settleSubgraphBudget(parent, relation, child.budgetUsed);
|
|
2026
|
+
state.status = succeeded
|
|
2027
|
+
? "succeeded"
|
|
2028
|
+
: child.status === "cancelled"
|
|
2029
|
+
? "cancelled"
|
|
2030
|
+
: child.status === "budget_exhausted"
|
|
2031
|
+
? "budget_exhausted"
|
|
2032
|
+
: "failed";
|
|
2033
|
+
state.blockedRoot = succeeded ? null : child.id;
|
|
2034
|
+
state.updatedAt = nowIso(() => now);
|
|
2035
|
+
propagate(parent, () => now);
|
|
2036
|
+
refreshLoopStates(parent, () => now);
|
|
2037
|
+
parent.status = classifyQuiescence(parent, now);
|
|
2038
|
+
if (TERMINAL_RUN.has(parent.status)) {
|
|
2039
|
+
parent.completedAt = nowIso(() => now);
|
|
2040
|
+
}
|
|
2041
|
+
return runProjection(parent);
|
|
2042
|
+
},
|
|
2043
|
+
{
|
|
2044
|
+
idempotencyKey: `subgraph-settle:${safeNodeId}:${child.id}:${child.status}`,
|
|
2045
|
+
},
|
|
2046
|
+
);
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
readyNodes(runId) {
|
|
2050
|
+
const run = this._run(runId);
|
|
2051
|
+
const now = this.now();
|
|
2052
|
+
const compensationEntry = currentCompensationEntry(run);
|
|
2053
|
+
if (compensationEntry) {
|
|
2054
|
+
const state = run.nodeStates.get(compensationEntry.compensationNodeId);
|
|
2055
|
+
if (state?.status !== "pending") return [];
|
|
2056
|
+
return [
|
|
2057
|
+
Object.freeze({
|
|
2058
|
+
nodeId: compensationEntry.compensationNodeId,
|
|
2059
|
+
compensationForNodeId: compensationEntry.nodeId,
|
|
2060
|
+
iterationPath: Object.freeze([...compensationEntry.iterationPath]),
|
|
2061
|
+
effectIdempotencyKey: iterationEffectIdempotencyKey(
|
|
2062
|
+
run.compiled.nodes[compensationEntry.compensationNodeId]
|
|
2063
|
+
.idempotencyKey,
|
|
2064
|
+
compensationEntry.iterationPath,
|
|
2065
|
+
),
|
|
2066
|
+
priority: Object.freeze({
|
|
2067
|
+
base: 1000,
|
|
2068
|
+
donation: 0,
|
|
2069
|
+
aging: 0,
|
|
2070
|
+
criticalPathBoost: 0,
|
|
2071
|
+
total: 1000,
|
|
2072
|
+
queueWaitMs: 0,
|
|
2073
|
+
}),
|
|
2074
|
+
}),
|
|
2075
|
+
];
|
|
2076
|
+
}
|
|
2077
|
+
return run.compiled.topologicalOrder
|
|
2078
|
+
.filter((nodeId) => {
|
|
2079
|
+
const state = run.nodeStates.get(nodeId);
|
|
2080
|
+
return state.status === "pending" && nodeReadiness(run, nodeId).ready;
|
|
2081
|
+
})
|
|
2082
|
+
.map((nodeId) => ({
|
|
2083
|
+
nodeId,
|
|
2084
|
+
iterationPath: Object.freeze([
|
|
2085
|
+
...(run.nodeStates.get(nodeId)?.iterationPath || []),
|
|
2086
|
+
]),
|
|
2087
|
+
...(["workspace_write", "external"].includes(
|
|
2088
|
+
run.compiled.nodes[nodeId].effectClass,
|
|
2089
|
+
)
|
|
2090
|
+
? {
|
|
2091
|
+
effectIdempotencyKey: iterationEffectIdempotencyKey(
|
|
2092
|
+
run.compiled.nodes[nodeId].idempotencyKey,
|
|
2093
|
+
run.nodeStates.get(nodeId)?.iterationPath || [],
|
|
2094
|
+
),
|
|
2095
|
+
}
|
|
2096
|
+
: {}),
|
|
2097
|
+
...(run.compiled.subgraphCalls?.[nodeId]
|
|
2098
|
+
? {
|
|
2099
|
+
dispatch: "subgraph",
|
|
2100
|
+
definitionId: run.compiled.subgraphCalls[nodeId].definitionId,
|
|
2101
|
+
revisionDigest: run.compiled.subgraphCalls[nodeId].revisionDigest,
|
|
2102
|
+
maxDepth: run.compiled.subgraphCalls[nodeId].maxDepth,
|
|
2103
|
+
inputBindings:
|
|
2104
|
+
run.compiled.subgraphCalls[nodeId].inputBindings || [],
|
|
2105
|
+
outputBindings:
|
|
2106
|
+
run.compiled.subgraphCalls[nodeId].outputBindings || [],
|
|
2107
|
+
budget: run.compiled.subgraphCalls[nodeId].budget || {},
|
|
2108
|
+
}
|
|
2109
|
+
: {}),
|
|
2110
|
+
priority: effectivePriority(run, nodeId, now, this.agingWindowMs),
|
|
2111
|
+
}))
|
|
2112
|
+
.sort(
|
|
2113
|
+
(left, right) =>
|
|
2114
|
+
right.priority.total - left.priority.total ||
|
|
2115
|
+
left.nodeId.localeCompare(right.nodeId),
|
|
2116
|
+
)
|
|
2117
|
+
.map((entry) => Object.freeze(entry));
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
assignNext(runId, agentId, options = {}) {
|
|
2121
|
+
const ready = this.readyNodes(runId);
|
|
2122
|
+
if (!ready.length) return null;
|
|
2123
|
+
let lastConflict = null;
|
|
2124
|
+
for (const candidate of ready) {
|
|
2125
|
+
if (candidate.dispatch === "subgraph") continue;
|
|
2126
|
+
try {
|
|
2127
|
+
return this.assignNode(runId, candidate.nodeId, agentId, options);
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
if (
|
|
2130
|
+
["CC_GRAPH_WRITE_SCOPE_BUSY", "CC_GRAPH_AGENT_CAPACITY"].includes(
|
|
2131
|
+
error?.code,
|
|
2132
|
+
)
|
|
2133
|
+
) {
|
|
2134
|
+
lastConflict = error;
|
|
2135
|
+
continue;
|
|
2136
|
+
}
|
|
2137
|
+
throw error;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
if (lastConflict) throw lastConflict;
|
|
2141
|
+
return null;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
assignNode(
|
|
2145
|
+
runId,
|
|
2146
|
+
nodeId,
|
|
2147
|
+
agentId,
|
|
2148
|
+
{
|
|
2149
|
+
role = "executor",
|
|
2150
|
+
ttlMs = 60_000,
|
|
2151
|
+
leaseId = this.createId(),
|
|
2152
|
+
attemptId = null,
|
|
2153
|
+
grant = {},
|
|
2154
|
+
} = {},
|
|
2155
|
+
) {
|
|
2156
|
+
const run = this._run(runId);
|
|
2157
|
+
const safeNodeId = safeIdentifier(nodeId, "nodeId");
|
|
2158
|
+
const safeAgentId = safeIdentifier(agentId, "agentId");
|
|
2159
|
+
const plannedCompensation = compensationAssignment(run, safeNodeId);
|
|
2160
|
+
const iterationPath = [
|
|
2161
|
+
...(plannedCompensation?.iterationPath ||
|
|
2162
|
+
run.nodeStates.get(safeNodeId)?.iterationPath ||
|
|
2163
|
+
[]),
|
|
2164
|
+
];
|
|
2165
|
+
const attemptNumber =
|
|
2166
|
+
[...run.attempts.values()].filter(
|
|
2167
|
+
(candidate) =>
|
|
2168
|
+
candidate.nodeId === safeNodeId &&
|
|
2169
|
+
JSON.stringify(candidate.iterationPath || []) ===
|
|
2170
|
+
JSON.stringify(iterationPath),
|
|
2171
|
+
).length + 1;
|
|
2172
|
+
const requestedAttemptId = safeIdentifier(
|
|
2173
|
+
attemptId || executionAttemptId(safeNodeId, iterationPath, attemptNumber),
|
|
2174
|
+
"attemptId",
|
|
2175
|
+
);
|
|
2176
|
+
return this._transaction(
|
|
2177
|
+
run,
|
|
2178
|
+
"assignment.started",
|
|
2179
|
+
{ nodeId: safeNodeId, agentId: safeAgentId, role },
|
|
2180
|
+
() => {
|
|
2181
|
+
const now = this.now();
|
|
2182
|
+
sweepExpirations(run, now);
|
|
2183
|
+
propagate(run, () => now);
|
|
2184
|
+
refreshLoopStates(run, () => now);
|
|
2185
|
+
const node = run.compiled.nodes[safeNodeId];
|
|
2186
|
+
const state = run.nodeStates.get(safeNodeId);
|
|
2187
|
+
if (!node || !state) {
|
|
2188
|
+
throw kernelError(
|
|
2189
|
+
"CC_GRAPH_NODE_NOT_FOUND",
|
|
2190
|
+
`Graph node not found: ${safeNodeId}`,
|
|
2191
|
+
);
|
|
2192
|
+
}
|
|
2193
|
+
if (run.compiled.subgraphCalls?.[safeNodeId]) {
|
|
2194
|
+
throw kernelError(
|
|
2195
|
+
"CC_GRAPH_SUBGRAPH_DISPATCH_REQUIRED",
|
|
2196
|
+
`subgraph nodes must be started through startSubgraph(): ${safeNodeId}`,
|
|
2197
|
+
);
|
|
2198
|
+
}
|
|
2199
|
+
const compensationEntry = compensationAssignment(run, safeNodeId);
|
|
2200
|
+
const ready = compensationEntry
|
|
2201
|
+
? state.status === "pending"
|
|
2202
|
+
: run.compensation.status !== "running" &&
|
|
2203
|
+
state.status === "pending" &&
|
|
2204
|
+
nodeReadiness(run, safeNodeId).ready;
|
|
2205
|
+
if (!ready) {
|
|
2206
|
+
throw kernelError(
|
|
2207
|
+
"CC_GRAPH_NODE_NOT_READY",
|
|
2208
|
+
`Graph node is not ready: ${safeNodeId}`,
|
|
2209
|
+
);
|
|
2210
|
+
}
|
|
2211
|
+
let agent = run.agents.get(safeAgentId);
|
|
2212
|
+
if (!agent) {
|
|
2213
|
+
agent = {
|
|
2214
|
+
id: safeAgentId,
|
|
2215
|
+
capacity: 1,
|
|
2216
|
+
resident: true,
|
|
2217
|
+
status: "idle",
|
|
2218
|
+
registeredAt: nowIso(() => now),
|
|
2219
|
+
updatedAt: nowIso(() => now),
|
|
2220
|
+
};
|
|
2221
|
+
run.agents.set(safeAgentId, agent);
|
|
2222
|
+
}
|
|
2223
|
+
if (
|
|
2224
|
+
activeAttemptsForAgent(run, safeAgentId, now).length >= agent.capacity
|
|
2225
|
+
) {
|
|
2226
|
+
throw kernelError(
|
|
2227
|
+
"CC_GRAPH_AGENT_CAPACITY",
|
|
2228
|
+
`agent capacity is exhausted: ${safeAgentId}`,
|
|
2229
|
+
);
|
|
2230
|
+
}
|
|
2231
|
+
if (role === "executor") {
|
|
2232
|
+
const conflict = activeWriteConflict(run, node, now);
|
|
2233
|
+
if (conflict) {
|
|
2234
|
+
throw kernelError(
|
|
2235
|
+
"CC_GRAPH_WRITE_SCOPE_BUSY",
|
|
2236
|
+
`write scope is held by attempt ${conflict.id}`,
|
|
2237
|
+
{ holderAttemptId: conflict.id },
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const fence = (run.fenceCounters.get(safeNodeId) || 0) + 1;
|
|
2242
|
+
run.fenceCounters.set(safeNodeId, fence);
|
|
2243
|
+
const id = requestedAttemptId;
|
|
2244
|
+
const attempt = {
|
|
2245
|
+
id,
|
|
2246
|
+
runId: run.id,
|
|
2247
|
+
nodeId: safeNodeId,
|
|
2248
|
+
iterationPath,
|
|
2249
|
+
attempt: attemptNumber,
|
|
2250
|
+
agentId: safeAgentId,
|
|
2251
|
+
role: compensationEntry ? "executor" : role,
|
|
2252
|
+
compensationForNodeId: compensationEntry?.nodeId || null,
|
|
2253
|
+
effectIdempotencyKey: ["workspace_write", "external"].includes(
|
|
2254
|
+
node.effectClass,
|
|
2255
|
+
)
|
|
2256
|
+
? iterationEffectIdempotencyKey(node.idempotencyKey, iterationPath)
|
|
2257
|
+
: null,
|
|
2258
|
+
leaseId: safeIdentifier(leaseId, "leaseId"),
|
|
2259
|
+
fence,
|
|
2260
|
+
status: "active",
|
|
2261
|
+
participationStatus: "active",
|
|
2262
|
+
grant: clone(grant),
|
|
2263
|
+
createdAt: nowIso(() => now),
|
|
2264
|
+
updatedAt: nowIso(() => now),
|
|
2265
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 60_000)),
|
|
2266
|
+
expiresAtMs: now + finitePositive(ttlMs, 60_000),
|
|
2267
|
+
terminalEvidence: null,
|
|
2268
|
+
usage: null,
|
|
2269
|
+
};
|
|
2270
|
+
run.attempts.set(id, attempt);
|
|
2271
|
+
state.attemptIds.push(id);
|
|
2272
|
+
state.status = "running";
|
|
2273
|
+
state.updatedAt = nowIso(() => now);
|
|
2274
|
+
agent.status = "busy";
|
|
2275
|
+
agent.updatedAt = nowIso(() => now);
|
|
2276
|
+
return attemptProjection(attempt);
|
|
2277
|
+
},
|
|
2278
|
+
{ idempotencyKey: `assignment:${requestedAttemptId}` },
|
|
2279
|
+
);
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
renewAttempt(runId, attemptId, leaseId, fence, ttlMs = 60_000) {
|
|
2283
|
+
const run = this._run(runId);
|
|
2284
|
+
return this._transaction(run, "assignment.renewed", { attemptId }, () => {
|
|
2285
|
+
const attempt = this._requireAttemptLease(run, attemptId, leaseId, fence);
|
|
2286
|
+
const now = this.now();
|
|
2287
|
+
attempt.expiresAtMs = now + finitePositive(ttlMs, 60_000);
|
|
2288
|
+
attempt.expiresAt = nowIso(() => attempt.expiresAtMs);
|
|
2289
|
+
attempt.updatedAt = nowIso(() => now);
|
|
2290
|
+
return attemptProjection(attempt);
|
|
2291
|
+
});
|
|
2292
|
+
}
|
|
2293
|
+
|
|
2294
|
+
_requireAttemptLease(run, attemptId, leaseId, fence, statuses = ["active"]) {
|
|
2295
|
+
const attempt = run.attempts.get(safeIdentifier(attemptId, "attemptId"));
|
|
2296
|
+
const now = this.now();
|
|
2297
|
+
if (
|
|
2298
|
+
!attempt ||
|
|
2299
|
+
attempt.leaseId !== safeIdentifier(leaseId, "leaseId") ||
|
|
2300
|
+
attempt.fence !== Number(fence) ||
|
|
2301
|
+
!statuses.includes(attempt.status) ||
|
|
2302
|
+
attempt.expiresAtMs <= now
|
|
2303
|
+
) {
|
|
2304
|
+
throw kernelError(
|
|
2305
|
+
"CC_GRAPH_STALE_ATTEMPT_LEASE",
|
|
2306
|
+
"attempt lease is missing, expired, fenced, or inactive",
|
|
2307
|
+
);
|
|
2308
|
+
}
|
|
2309
|
+
return attempt;
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
beginEffect(
|
|
2313
|
+
runId,
|
|
2314
|
+
{
|
|
2315
|
+
effectId = this.createId(),
|
|
2316
|
+
attemptId,
|
|
2317
|
+
leaseId,
|
|
2318
|
+
fence,
|
|
2319
|
+
idempotencyKey,
|
|
2320
|
+
operationDigest,
|
|
2321
|
+
compensationEffectId = null,
|
|
2322
|
+
} = {},
|
|
2323
|
+
) {
|
|
2324
|
+
const run = this._run(runId);
|
|
2325
|
+
const key = String(idempotencyKey || "").trim();
|
|
2326
|
+
const existing = [...run.effects.values()].find(
|
|
2327
|
+
(effect) => effect.idempotencyKey === key,
|
|
2328
|
+
);
|
|
2329
|
+
if (existing) {
|
|
2330
|
+
if (existing.operationDigest !== operationDigest) {
|
|
2331
|
+
throw kernelError(
|
|
2332
|
+
"CC_GRAPH_EFFECT_IDEMPOTENCY_CONFLICT",
|
|
2333
|
+
"effect idempotency key was reused for a different operation",
|
|
2334
|
+
);
|
|
2335
|
+
}
|
|
2336
|
+
return Object.freeze(clone(existing));
|
|
2337
|
+
}
|
|
2338
|
+
const id = safeIdentifier(effectId, "effectId");
|
|
2339
|
+
return this._transaction(
|
|
2340
|
+
run,
|
|
2341
|
+
"effect.started",
|
|
2342
|
+
{ effectId: id, attemptId },
|
|
2343
|
+
() => {
|
|
2344
|
+
const attempt = this._requireAttemptLease(
|
|
2345
|
+
run,
|
|
2346
|
+
attemptId,
|
|
2347
|
+
leaseId,
|
|
2348
|
+
fence,
|
|
2349
|
+
);
|
|
2350
|
+
const node = run.compiled.nodes[attempt.nodeId];
|
|
2351
|
+
if (
|
|
2352
|
+
!node ||
|
|
2353
|
+
!["workspace_write", "external"].includes(node.effectClass)
|
|
2354
|
+
) {
|
|
2355
|
+
throw kernelError(
|
|
2356
|
+
"CC_GRAPH_EFFECT_NOT_DECLARED",
|
|
2357
|
+
"node did not declare an effectful execution class",
|
|
2358
|
+
);
|
|
2359
|
+
}
|
|
2360
|
+
const authenticatedKey = iterationEffectIdempotencyKey(
|
|
2361
|
+
node.idempotencyKey,
|
|
2362
|
+
attempt.iterationPath,
|
|
2363
|
+
);
|
|
2364
|
+
if (!key || key !== authenticatedKey) {
|
|
2365
|
+
throw kernelError(
|
|
2366
|
+
"CC_GRAPH_EFFECT_IDEMPOTENCY_REQUIRED",
|
|
2367
|
+
"effect must use the idempotency key authenticated by Graph Compiler",
|
|
2368
|
+
);
|
|
2369
|
+
}
|
|
2370
|
+
if (!/^sha256:[a-f0-9]{64}$/u.test(String(operationDigest || ""))) {
|
|
2371
|
+
throw kernelError(
|
|
2372
|
+
"CC_GRAPH_EFFECT_OPERATION_DIGEST_INVALID",
|
|
2373
|
+
"effect operationDigest must be sha256",
|
|
2374
|
+
);
|
|
2375
|
+
}
|
|
2376
|
+
const effect = {
|
|
2377
|
+
id,
|
|
2378
|
+
runId: run.id,
|
|
2379
|
+
nodeId: attempt.nodeId,
|
|
2380
|
+
attemptId: attempt.id,
|
|
2381
|
+
iterationPath: [...attempt.iterationPath],
|
|
2382
|
+
leaseId: attempt.leaseId,
|
|
2383
|
+
fence: attempt.fence,
|
|
2384
|
+
idempotencyKey: key,
|
|
2385
|
+
baseIdempotencyKey: node.idempotencyKey,
|
|
2386
|
+
operationDigest,
|
|
2387
|
+
status: "started",
|
|
2388
|
+
receipt: null,
|
|
2389
|
+
compensationEffectId:
|
|
2390
|
+
compensationEffectId == null
|
|
2391
|
+
? null
|
|
2392
|
+
: safeIdentifier(compensationEffectId, "compensationEffectId"),
|
|
2393
|
+
createdAt: nowIso(this.now),
|
|
2394
|
+
updatedAt: nowIso(this.now),
|
|
2395
|
+
};
|
|
2396
|
+
run.effects.set(id, effect);
|
|
2397
|
+
return Object.freeze(clone(effect));
|
|
2398
|
+
},
|
|
2399
|
+
{ idempotencyKey: `effect-start:${id}` },
|
|
2400
|
+
);
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
settleEffect(
|
|
2404
|
+
runId,
|
|
2405
|
+
{ effectId, attemptId, leaseId, fence, outcome, receipt = null } = {},
|
|
2406
|
+
) {
|
|
2407
|
+
const run = this._run(runId);
|
|
2408
|
+
const id = safeIdentifier(effectId, "effectId");
|
|
2409
|
+
const current = run.effects.get(id);
|
|
2410
|
+
if (current && current.status !== "started") {
|
|
2411
|
+
if (current.status === outcome) return Object.freeze(clone(current));
|
|
2412
|
+
throw kernelError(
|
|
2413
|
+
"CC_GRAPH_EFFECT_TERMINAL_CONFLICT",
|
|
2414
|
+
"effect already has a different terminal outcome",
|
|
2415
|
+
);
|
|
2416
|
+
}
|
|
2417
|
+
return this._transaction(
|
|
2418
|
+
run,
|
|
2419
|
+
"effect.settled",
|
|
2420
|
+
{ effectId: id, outcome },
|
|
2421
|
+
() => {
|
|
2422
|
+
const effect = run.effects.get(id);
|
|
2423
|
+
if (!effect || effect.attemptId !== attemptId) {
|
|
2424
|
+
throw kernelError(
|
|
2425
|
+
"CC_GRAPH_EFFECT_NOT_FOUND",
|
|
2426
|
+
`effect was not started by this attempt: ${id}`,
|
|
2427
|
+
);
|
|
2428
|
+
}
|
|
2429
|
+
this._requireAttemptLease(run, attemptId, leaseId, fence);
|
|
2430
|
+
if (!["committed", "failed", "unknown"].includes(outcome)) {
|
|
2431
|
+
throw kernelError(
|
|
2432
|
+
"CC_GRAPH_EFFECT_OUTCOME_INVALID",
|
|
2433
|
+
`unsupported effect outcome: ${outcome}`,
|
|
2434
|
+
);
|
|
2435
|
+
}
|
|
2436
|
+
if (
|
|
2437
|
+
outcome === "committed" &&
|
|
2438
|
+
!/^sha256:[a-f0-9]{64}$/u.test(String(receipt?.receiptDigest || ""))
|
|
2439
|
+
) {
|
|
2440
|
+
throw kernelError(
|
|
2441
|
+
"CC_GRAPH_EFFECT_RECEIPT_REQUIRED",
|
|
2442
|
+
"committed effect requires an immutable receipt digest",
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
effect.status = outcome;
|
|
2446
|
+
effect.receipt = receipt
|
|
2447
|
+
? {
|
|
2448
|
+
...clone(receipt),
|
|
2449
|
+
recordedAt: receipt.recordedAt || nowIso(this.now),
|
|
2450
|
+
}
|
|
2451
|
+
: null;
|
|
2452
|
+
effect.updatedAt = nowIso(this.now);
|
|
2453
|
+
if (outcome === "unknown") {
|
|
2454
|
+
const attempt = run.attempts.get(effect.attemptId);
|
|
2455
|
+
attempt.status = "unknown";
|
|
2456
|
+
attempt.participationStatus = "reconciliation_required";
|
|
2457
|
+
const state = run.nodeStates.get(effect.nodeId);
|
|
2458
|
+
state.status = "reconciliation_required";
|
|
2459
|
+
state.updatedAt = nowIso(this.now);
|
|
2460
|
+
run.status = "reconciliation_required";
|
|
2461
|
+
}
|
|
2462
|
+
return Object.freeze(clone(effect));
|
|
2463
|
+
},
|
|
2464
|
+
{ idempotencyKey: `effect-settle:${id}:${outcome}` },
|
|
2465
|
+
);
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
reconcileEffect(
|
|
2469
|
+
runId,
|
|
2470
|
+
{ effectId, decision, receipt = null, auditDecisionId } = {},
|
|
2471
|
+
) {
|
|
2472
|
+
const run = this._run(runId);
|
|
2473
|
+
const id = safeIdentifier(effectId, "effectId");
|
|
2474
|
+
if (!auditDecisionId) {
|
|
2475
|
+
throw kernelError(
|
|
2476
|
+
"CC_GRAPH_RECONCILIATION_AUDIT_REQUIRED",
|
|
2477
|
+
"effect reconciliation requires an audited decision",
|
|
2478
|
+
);
|
|
2479
|
+
}
|
|
2480
|
+
return this._transaction(
|
|
2481
|
+
run,
|
|
2482
|
+
"effect.reconciled",
|
|
2483
|
+
{ effectId: id, decision, auditDecisionId },
|
|
2484
|
+
() => {
|
|
2485
|
+
const effect = run.effects.get(id);
|
|
2486
|
+
if (!effect || effect.status !== "unknown") {
|
|
2487
|
+
throw kernelError(
|
|
2488
|
+
"CC_GRAPH_EFFECT_NOT_RECONCILABLE",
|
|
2489
|
+
"only an unknown effect can be reconciled",
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
if (!["committed", "failed"].includes(decision)) {
|
|
2493
|
+
throw kernelError(
|
|
2494
|
+
"CC_GRAPH_EFFECT_OUTCOME_INVALID",
|
|
2495
|
+
"reconciliation decision must be committed or failed",
|
|
2496
|
+
);
|
|
2497
|
+
}
|
|
2498
|
+
if (
|
|
2499
|
+
decision === "committed" &&
|
|
2500
|
+
!/^sha256:[a-f0-9]{64}$/u.test(String(receipt?.receiptDigest || ""))
|
|
2501
|
+
) {
|
|
2502
|
+
throw kernelError(
|
|
2503
|
+
"CC_GRAPH_EFFECT_RECEIPT_REQUIRED",
|
|
2504
|
+
"committed reconciliation requires an immutable receipt digest",
|
|
2505
|
+
);
|
|
2506
|
+
}
|
|
2507
|
+
effect.status = decision;
|
|
2508
|
+
effect.receipt = receipt
|
|
2509
|
+
? {
|
|
2510
|
+
...clone(receipt),
|
|
2511
|
+
recordedAt: receipt.recordedAt || nowIso(this.now),
|
|
2512
|
+
}
|
|
2513
|
+
: null;
|
|
2514
|
+
effect.auditDecisionId = String(auditDecisionId);
|
|
2515
|
+
effect.updatedAt = nowIso(this.now);
|
|
2516
|
+
const attempt = run.attempts.get(effect.attemptId);
|
|
2517
|
+
if (attempt?.status === "unknown") {
|
|
2518
|
+
attempt.status = "expired";
|
|
2519
|
+
attempt.participationStatus = "reconciled";
|
|
2520
|
+
attempt.updatedAt = nowIso(this.now);
|
|
2521
|
+
const agent = run.agents.get(attempt.agentId);
|
|
2522
|
+
if (agent) agent.status = "idle";
|
|
2523
|
+
}
|
|
2524
|
+
const state = run.nodeStates.get(effect.nodeId);
|
|
2525
|
+
state.status = "pending";
|
|
2526
|
+
state.updatedAt = nowIso(this.now);
|
|
2527
|
+
run.status = classifyQuiescence(run, this.now());
|
|
2528
|
+
return Object.freeze(clone(effect));
|
|
2529
|
+
},
|
|
2530
|
+
{ idempotencyKey: `effect-reconcile:${id}:${auditDecisionId}` },
|
|
2531
|
+
);
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
registerArtifact(
|
|
2535
|
+
runId,
|
|
2536
|
+
{
|
|
2537
|
+
artifactId = this.createId(),
|
|
2538
|
+
attemptId,
|
|
2539
|
+
leaseId,
|
|
2540
|
+
fence,
|
|
2541
|
+
digest: artifactDigest,
|
|
2542
|
+
schema = {},
|
|
2543
|
+
commit = null,
|
|
2544
|
+
validationEvidence = [],
|
|
2545
|
+
consumerNodeIds = [],
|
|
2546
|
+
dataPolicy,
|
|
2547
|
+
} = {},
|
|
2548
|
+
) {
|
|
2549
|
+
const run = this._run(runId);
|
|
2550
|
+
const id = safeIdentifier(artifactId, "artifactId");
|
|
2551
|
+
return this._transaction(
|
|
2552
|
+
run,
|
|
2553
|
+
"artifact.recorded",
|
|
2554
|
+
{ artifactId: id, attemptId },
|
|
2555
|
+
() => {
|
|
2556
|
+
const existing = run.artifacts.get(id);
|
|
2557
|
+
if (existing) {
|
|
2558
|
+
if (existing.digest !== artifactDigest) {
|
|
2559
|
+
throw kernelError(
|
|
2560
|
+
"CC_GRAPH_ARTIFACT_IMMUTABLE",
|
|
2561
|
+
"artifact id was reused with a different digest",
|
|
2562
|
+
);
|
|
2563
|
+
}
|
|
2564
|
+
return Object.freeze(clone(existing));
|
|
2565
|
+
}
|
|
2566
|
+
const attempt = this._requireAttemptLease(
|
|
2567
|
+
run,
|
|
2568
|
+
attemptId,
|
|
2569
|
+
leaseId,
|
|
2570
|
+
fence,
|
|
2571
|
+
);
|
|
2572
|
+
if (!/^sha256:[a-f0-9]{64}$/u.test(String(artifactDigest))) {
|
|
2573
|
+
throw kernelError(
|
|
2574
|
+
"CC_GRAPH_ARTIFACT_DIGEST_INVALID",
|
|
2575
|
+
"artifact digest must be sha256",
|
|
2576
|
+
);
|
|
2577
|
+
}
|
|
2578
|
+
const policy = validateDataPolicy(dataPolicy);
|
|
2579
|
+
const artifact = {
|
|
2580
|
+
id,
|
|
2581
|
+
digest: artifactDigest,
|
|
2582
|
+
producerNodeId: attempt.nodeId,
|
|
2583
|
+
producerAttemptId: attempt.id,
|
|
2584
|
+
producerLeaseId: attempt.leaseId,
|
|
2585
|
+
producerFence: attempt.fence,
|
|
2586
|
+
schema: clone(schema),
|
|
2587
|
+
commit,
|
|
2588
|
+
validationEvidence: [...validationEvidence],
|
|
2589
|
+
consumerNodeIds: [...consumerNodeIds],
|
|
2590
|
+
dataPolicy: policy,
|
|
2591
|
+
createdAt: nowIso(this.now),
|
|
2592
|
+
};
|
|
2593
|
+
run.artifacts.set(id, artifact);
|
|
2594
|
+
return Object.freeze(clone(artifact));
|
|
2595
|
+
},
|
|
2596
|
+
{ idempotencyKey: `artifact:${id}` },
|
|
2597
|
+
);
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
settleAttempt(
|
|
2601
|
+
runId,
|
|
2602
|
+
{
|
|
2603
|
+
attemptId,
|
|
2604
|
+
leaseId,
|
|
2605
|
+
fence,
|
|
2606
|
+
outcome,
|
|
2607
|
+
evidence = null,
|
|
2608
|
+
usage = {},
|
|
2609
|
+
error = null,
|
|
2610
|
+
} = {},
|
|
2611
|
+
) {
|
|
2612
|
+
const run = this._run(runId);
|
|
2613
|
+
return this._transaction(
|
|
2614
|
+
run,
|
|
2615
|
+
"assignment.settled",
|
|
2616
|
+
{ attemptId, outcome },
|
|
2617
|
+
() => {
|
|
2618
|
+
const attempt = this._requireAttemptLease(
|
|
2619
|
+
run,
|
|
2620
|
+
attemptId,
|
|
2621
|
+
leaseId,
|
|
2622
|
+
fence,
|
|
2623
|
+
);
|
|
2624
|
+
const state = run.nodeStates.get(attempt.nodeId);
|
|
2625
|
+
const node = run.compiled.nodes[attempt.nodeId];
|
|
2626
|
+
const compensationEntry = compensationAssignment(run, attempt.nodeId);
|
|
2627
|
+
if (state.acceptedAttemptId && state.acceptedAttemptId !== attempt.id) {
|
|
2628
|
+
attempt.status = "rejected";
|
|
2629
|
+
attempt.participationStatus = "loser";
|
|
2630
|
+
throw kernelError(
|
|
2631
|
+
"CC_GRAPH_ATTEMPT_LOST_RACE",
|
|
2632
|
+
"another attempt already finalized this task",
|
|
2633
|
+
{ acceptedAttemptId: state.acceptedAttemptId },
|
|
2634
|
+
);
|
|
2635
|
+
}
|
|
2636
|
+
addUsage(run, usage);
|
|
2637
|
+
attempt.usage = clone(usage);
|
|
2638
|
+
attempt.updatedAt = nowIso(this.now);
|
|
2639
|
+
if (outcome === "unknown") {
|
|
2640
|
+
attempt.status = "unknown";
|
|
2641
|
+
attempt.participationStatus = "reconciliation_required";
|
|
2642
|
+
attempt.terminalEvidence = clone(evidence);
|
|
2643
|
+
state.status = "reconciliation_required";
|
|
2644
|
+
state.updatedAt = nowIso(this.now);
|
|
2645
|
+
if (compensationEntry) {
|
|
2646
|
+
failCompensation(
|
|
2647
|
+
run,
|
|
2648
|
+
compensationEntry,
|
|
2649
|
+
error || "compensation outcome is unknown",
|
|
2650
|
+
this.now(),
|
|
2651
|
+
);
|
|
2652
|
+
} else {
|
|
2653
|
+
run.status = "reconciliation_required";
|
|
2654
|
+
}
|
|
2655
|
+
return attemptProjection(attempt);
|
|
2656
|
+
}
|
|
2657
|
+
if (outcome === "succeeded") {
|
|
2658
|
+
const unresolvedEffect = [...run.effects.values()].find(
|
|
2659
|
+
(effect) =>
|
|
2660
|
+
effect.attemptId === attempt.id && effect.status !== "committed",
|
|
2661
|
+
);
|
|
2662
|
+
if (unresolvedEffect) {
|
|
2663
|
+
throw kernelError(
|
|
2664
|
+
"CC_GRAPH_EFFECT_RECEIPT_REQUIRED",
|
|
2665
|
+
`attempt cannot succeed before effect receipt is committed: ${unresolvedEffect.id}`,
|
|
2666
|
+
);
|
|
2667
|
+
}
|
|
2668
|
+
if (!hasTerminalEvidence(evidence)) {
|
|
2669
|
+
throw kernelError(
|
|
2670
|
+
"CC_GRAPH_TERMINAL_EVIDENCE_REQUIRED",
|
|
2671
|
+
"successful attempts require output/artifact/commit/test evidence",
|
|
2672
|
+
);
|
|
2673
|
+
}
|
|
2674
|
+
for (const artifactId of evidence.artifactIds || []) {
|
|
2675
|
+
const artifact = run.artifacts.get(artifactId);
|
|
2676
|
+
if (
|
|
2677
|
+
!artifact ||
|
|
2678
|
+
artifact.producerAttemptId !== attempt.id ||
|
|
2679
|
+
artifact.producerLeaseId !== attempt.leaseId ||
|
|
2680
|
+
artifact.producerFence !== attempt.fence
|
|
2681
|
+
) {
|
|
2682
|
+
throw kernelError(
|
|
2683
|
+
"CC_GRAPH_ARTIFACT_PROVENANCE_INVALID",
|
|
2684
|
+
`terminal artifact is not owned by the settling attempt: ${artifactId}`,
|
|
2685
|
+
);
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
attempt.status = "accepted";
|
|
2689
|
+
attempt.participationStatus = "accepted_winner";
|
|
2690
|
+
attempt.terminalEvidence = clone(evidence);
|
|
2691
|
+
state.status = "succeeded";
|
|
2692
|
+
state.acceptedAttemptId = attempt.id;
|
|
2693
|
+
state.updatedAt = nowIso(this.now);
|
|
2694
|
+
for (const other of run.attempts.values()) {
|
|
2695
|
+
if (
|
|
2696
|
+
other.nodeId === attempt.nodeId &&
|
|
2697
|
+
other.id !== attempt.id &&
|
|
2698
|
+
ACTIVE_ATTEMPT.has(other.status)
|
|
2699
|
+
) {
|
|
2700
|
+
other.status = "cancelled";
|
|
2701
|
+
other.participationStatus = "loser";
|
|
2702
|
+
other.updatedAt = nowIso(this.now);
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
} else if (outcome === "failed" || outcome === "timed_out") {
|
|
2706
|
+
attempt.status = "rejected";
|
|
2707
|
+
attempt.participationStatus = "failed";
|
|
2708
|
+
attempt.error = error == null ? null : String(error).slice(0, 4096);
|
|
2709
|
+
attempt.terminalEvidence = clone(evidence);
|
|
2710
|
+
if (attempt.attempt <= Number(node.retryLimit || 0)) {
|
|
2711
|
+
state.status = "pending";
|
|
2712
|
+
} else {
|
|
2713
|
+
state.status = outcome === "timed_out" ? "timed_out" : "failed";
|
|
2714
|
+
state.blockedRoot = attempt.nodeId;
|
|
2715
|
+
}
|
|
2716
|
+
state.updatedAt = nowIso(this.now);
|
|
2717
|
+
} else if (outcome === "cancelled") {
|
|
2718
|
+
attempt.status = "cancelled";
|
|
2719
|
+
attempt.participationStatus = "cancelled";
|
|
2720
|
+
state.status = run.cancellationRequested ? "cancelled" : "pending";
|
|
2721
|
+
state.updatedAt = nowIso(this.now);
|
|
2722
|
+
} else {
|
|
2723
|
+
throw kernelError(
|
|
2724
|
+
"CC_GRAPH_OUTCOME_INVALID",
|
|
2725
|
+
`unsupported attempt outcome: ${outcome}`,
|
|
2726
|
+
);
|
|
2727
|
+
}
|
|
2728
|
+
const agent = run.agents.get(attempt.agentId);
|
|
2729
|
+
if (agent) {
|
|
2730
|
+
agent.status = "idle";
|
|
2731
|
+
agent.updatedAt = nowIso(this.now);
|
|
2732
|
+
}
|
|
2733
|
+
if (compensationEntry) {
|
|
2734
|
+
if (outcome === "succeeded") {
|
|
2735
|
+
completeCompensationStep(run, compensationEntry, this.now());
|
|
2736
|
+
} else if (state.status !== "pending") {
|
|
2737
|
+
failCompensation(
|
|
2738
|
+
run,
|
|
2739
|
+
compensationEntry,
|
|
2740
|
+
error || outcome,
|
|
2741
|
+
this.now(),
|
|
2742
|
+
);
|
|
2743
|
+
}
|
|
2744
|
+
} else {
|
|
2745
|
+
propagate(run, this.now);
|
|
2746
|
+
if (refreshLoopStates(run, this.now)) propagate(run, this.now);
|
|
2747
|
+
run.status = classifyQuiescence(run, this.now());
|
|
2748
|
+
}
|
|
2749
|
+
if (TERMINAL_RUN.has(run.status)) run.completedAt = nowIso(this.now);
|
|
2750
|
+
return attemptProjection(attempt);
|
|
2751
|
+
},
|
|
2752
|
+
{ idempotencyKey: `attempt-settle:${attemptId}:${outcome}` },
|
|
2753
|
+
);
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
async cancelRun(runId, { reason = "cancelled", interrupt = null } = {}) {
|
|
2757
|
+
const run = this._run(runId);
|
|
2758
|
+
const active = this._transaction(
|
|
2759
|
+
run,
|
|
2760
|
+
"run.cancel_requested",
|
|
2761
|
+
{ reason },
|
|
2762
|
+
() => {
|
|
2763
|
+
run.cancellationRequested = true;
|
|
2764
|
+
run.phase = "sealed";
|
|
2765
|
+
for (const lease of run.producerLeases.values()) {
|
|
2766
|
+
if (lease.status === "active") lease.status = "revoked";
|
|
2767
|
+
}
|
|
2768
|
+
const attempts = [];
|
|
2769
|
+
for (const attempt of run.attempts.values()) {
|
|
2770
|
+
if (attempt.status === "active") {
|
|
2771
|
+
attempt.status = "cancelling";
|
|
2772
|
+
attempt.updatedAt = nowIso(this.now);
|
|
2773
|
+
attempts.push(clone(attempt));
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
for (const state of run.nodeStates.values()) {
|
|
2777
|
+
if (state.status === "pending") {
|
|
2778
|
+
state.status = "cancelled";
|
|
2779
|
+
state.updatedAt = nowIso(this.now);
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
return attempts;
|
|
2783
|
+
},
|
|
2784
|
+
);
|
|
2785
|
+
const failures = [];
|
|
2786
|
+
await Promise.all(
|
|
2787
|
+
active.map(async (attempt) => {
|
|
2788
|
+
try {
|
|
2789
|
+
if (typeof interrupt === "function") await interrupt(attempt);
|
|
2790
|
+
} catch (error) {
|
|
2791
|
+
failures.push({
|
|
2792
|
+
attemptId: attempt.id,
|
|
2793
|
+
error: String(error?.message || error).slice(0, 4096),
|
|
2794
|
+
});
|
|
2795
|
+
}
|
|
2796
|
+
}),
|
|
2797
|
+
);
|
|
2798
|
+
for (const relation of run.subgraphRuns.values()) {
|
|
2799
|
+
if (!["starting", "running"].includes(relation.status)) continue;
|
|
2800
|
+
try {
|
|
2801
|
+
const child = this._loadRun(relation.childRunId);
|
|
2802
|
+
if (child && !TERMINAL_RUN.has(child.status)) {
|
|
2803
|
+
await this.cancelRun(child.id, { reason, interrupt });
|
|
2804
|
+
}
|
|
2805
|
+
} catch (error) {
|
|
2806
|
+
failures.push({
|
|
2807
|
+
subgraphRunId: relation.childRunId,
|
|
2808
|
+
error: String(error?.message || error).slice(0, 4096),
|
|
2809
|
+
});
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
return this._transaction(
|
|
2813
|
+
run,
|
|
2814
|
+
failures.length ? "run.cancel_reconciliation" : "run.cancelled",
|
|
2815
|
+
{ reason, failures },
|
|
2816
|
+
() => {
|
|
2817
|
+
for (const attempt of run.attempts.values()) {
|
|
2818
|
+
if (attempt.status !== "cancelling") continue;
|
|
2819
|
+
const failure = failures.find(
|
|
2820
|
+
(entry) => entry.attemptId === attempt.id,
|
|
2821
|
+
);
|
|
2822
|
+
attempt.status = failure ? "unknown" : "cancelled";
|
|
2823
|
+
attempt.participationStatus = failure
|
|
2824
|
+
? "reconciliation_required"
|
|
2825
|
+
: "cancelled";
|
|
2826
|
+
attempt.updatedAt = nowIso(this.now);
|
|
2827
|
+
const state = run.nodeStates.get(attempt.nodeId);
|
|
2828
|
+
state.status = failure ? "reconciliation_required" : "cancelled";
|
|
2829
|
+
state.updatedAt = nowIso(this.now);
|
|
2830
|
+
}
|
|
2831
|
+
for (const relation of run.subgraphRuns.values()) {
|
|
2832
|
+
if (!["starting", "running"].includes(relation.status)) continue;
|
|
2833
|
+
const failure = failures.find(
|
|
2834
|
+
(entry) => entry.subgraphRunId === relation.childRunId,
|
|
2835
|
+
);
|
|
2836
|
+
const child = this._loadRun(relation.childRunId);
|
|
2837
|
+
if (!failure) {
|
|
2838
|
+
settleSubgraphBudget(
|
|
2839
|
+
run,
|
|
2840
|
+
relation,
|
|
2841
|
+
child?.budgetUsed || emptyBudgetUsage(),
|
|
2842
|
+
);
|
|
2843
|
+
}
|
|
2844
|
+
relation.status = failure ? "failed" : "cancelled";
|
|
2845
|
+
relation.updatedAt = nowIso(this.now);
|
|
2846
|
+
relation.completedAt = failure ? null : nowIso(this.now);
|
|
2847
|
+
const state = run.nodeStates.get(relation.nodeId);
|
|
2848
|
+
state.status = failure ? "reconciliation_required" : "cancelled";
|
|
2849
|
+
state.blockedRoot = relation.childRunId;
|
|
2850
|
+
state.updatedAt = nowIso(this.now);
|
|
2851
|
+
}
|
|
2852
|
+
const unsettledEffects = [...run.effects.values()].filter(
|
|
2853
|
+
(effect) => effect.status === "started",
|
|
2854
|
+
);
|
|
2855
|
+
for (const effect of unsettledEffects) {
|
|
2856
|
+
effect.status = "unknown";
|
|
2857
|
+
effect.updatedAt = nowIso(this.now);
|
|
2858
|
+
const state = run.nodeStates.get(effect.nodeId);
|
|
2859
|
+
state.status = "reconciliation_required";
|
|
2860
|
+
state.updatedAt = nowIso(this.now);
|
|
2861
|
+
}
|
|
2862
|
+
refreshLoopStates(run, this.now);
|
|
2863
|
+
const requiresReconciliation =
|
|
2864
|
+
failures.length > 0 || unsettledEffects.length > 0;
|
|
2865
|
+
run.status = requiresReconciliation
|
|
2866
|
+
? "reconciliation_required"
|
|
2867
|
+
: "cancelled";
|
|
2868
|
+
run.completedAt = requiresReconciliation ? null : nowIso(this.now);
|
|
2869
|
+
return runProjection(run);
|
|
2870
|
+
},
|
|
2871
|
+
);
|
|
2872
|
+
}
|
|
2873
|
+
|
|
2874
|
+
beginCompensation(
|
|
2875
|
+
runId,
|
|
2876
|
+
{ triggerNodeId = null, reason = "forward_failure" } = {},
|
|
2877
|
+
) {
|
|
2878
|
+
const run = this._run(runId);
|
|
2879
|
+
const trigger =
|
|
2880
|
+
triggerNodeId == null
|
|
2881
|
+
? null
|
|
2882
|
+
: safeIdentifier(triggerNodeId, "triggerNodeId");
|
|
2883
|
+
if (run.compensation.status !== "idle") {
|
|
2884
|
+
if (
|
|
2885
|
+
run.compensation.triggerNodeId === trigger &&
|
|
2886
|
+
run.compensation.reason === String(reason)
|
|
2887
|
+
) {
|
|
2888
|
+
return runProjection(run);
|
|
2889
|
+
}
|
|
2890
|
+
throw kernelError(
|
|
2891
|
+
"CC_GRAPH_COMPENSATION_ALREADY_STARTED",
|
|
2892
|
+
"compensation has already been started for this run",
|
|
2893
|
+
);
|
|
2894
|
+
}
|
|
2895
|
+
return this._transaction(
|
|
2896
|
+
run,
|
|
2897
|
+
"compensation.started",
|
|
2898
|
+
{ triggerNodeId: trigger, reason },
|
|
2899
|
+
() => {
|
|
2900
|
+
if (
|
|
2901
|
+
!["failed", "partial", "cancelled", "budget_exhausted"].includes(
|
|
2902
|
+
run.status,
|
|
2903
|
+
)
|
|
2904
|
+
) {
|
|
2905
|
+
throw kernelError(
|
|
2906
|
+
"CC_GRAPH_COMPENSATION_NOT_AVAILABLE",
|
|
2907
|
+
"compensation requires a failed, partial, cancelled, or budget-exhausted terminal run",
|
|
2908
|
+
);
|
|
2909
|
+
}
|
|
2910
|
+
if (trigger && !run.compiled.nodes[trigger]) {
|
|
2911
|
+
throw kernelError(
|
|
2912
|
+
"CC_GRAPH_NODE_NOT_FOUND",
|
|
2913
|
+
`Graph node not found: ${trigger}`,
|
|
2914
|
+
);
|
|
2915
|
+
}
|
|
2916
|
+
const activeAttempts = [...run.attempts.values()].filter((attempt) =>
|
|
2917
|
+
ACTIVE_ATTEMPT.has(attempt.status),
|
|
2918
|
+
);
|
|
2919
|
+
const unsettledEffects = [...run.effects.values()].filter((effect) =>
|
|
2920
|
+
["started", "unknown"].includes(effect.status),
|
|
2921
|
+
);
|
|
2922
|
+
if (activeAttempts.length || unsettledEffects.length) {
|
|
2923
|
+
throw kernelError(
|
|
2924
|
+
"CC_GRAPH_COMPENSATION_UNSETTLED",
|
|
2925
|
+
"compensation cannot start before attempts and effects are settled",
|
|
2926
|
+
{
|
|
2927
|
+
attemptIds: activeAttempts.map((attempt) => attempt.id).sort(),
|
|
2928
|
+
effectIds: unsettledEffects.map((effect) => effect.id).sort(),
|
|
2929
|
+
},
|
|
2930
|
+
);
|
|
2931
|
+
}
|
|
2932
|
+
const plan = (run.compiled.forwardTopologicalOrder || [])
|
|
2933
|
+
.filter((nodeId) => run.compiled.compensationByNode?.[nodeId])
|
|
2934
|
+
.reverse()
|
|
2935
|
+
.flatMap((nodeId) =>
|
|
2936
|
+
committedEffectsForNode(run, nodeId)
|
|
2937
|
+
.reverse()
|
|
2938
|
+
.map((effect) => ({
|
|
2939
|
+
nodeId,
|
|
2940
|
+
compensationNodeId: run.compiled.compensationByNode[nodeId],
|
|
2941
|
+
iterationPath: [...(effect.iterationPath || [])],
|
|
2942
|
+
effectIds: [effect.id],
|
|
2943
|
+
})),
|
|
2944
|
+
);
|
|
2945
|
+
if (plan.length === 0) {
|
|
2946
|
+
throw kernelError(
|
|
2947
|
+
"CC_GRAPH_COMPENSATION_NOT_REQUIRED",
|
|
2948
|
+
"run has no committed compensatable effects",
|
|
2949
|
+
);
|
|
2950
|
+
}
|
|
2951
|
+
const now = this.now();
|
|
2952
|
+
const preparedTargets = new Set();
|
|
2953
|
+
for (const entry of plan) {
|
|
2954
|
+
if (preparedTargets.has(entry.compensationNodeId)) continue;
|
|
2955
|
+
const state = run.nodeStates.get(entry.compensationNodeId);
|
|
2956
|
+
if (!state || state.status !== "skipped") {
|
|
2957
|
+
throw kernelError(
|
|
2958
|
+
"CC_GRAPH_COMPENSATION_TARGET_INVALID",
|
|
2959
|
+
`compensation target is not isolated and idle: ${entry.compensationNodeId}`,
|
|
2960
|
+
);
|
|
2961
|
+
}
|
|
2962
|
+
state.status = "pending";
|
|
2963
|
+
state.blockedRoot = null;
|
|
2964
|
+
state.iterationPath = [...entry.iterationPath];
|
|
2965
|
+
state.updatedAt = nowIso(() => now);
|
|
2966
|
+
preparedTargets.add(entry.compensationNodeId);
|
|
2967
|
+
}
|
|
2968
|
+
run.compensation = {
|
|
2969
|
+
status: "running",
|
|
2970
|
+
triggerNodeId: trigger,
|
|
2971
|
+
reason: String(reason),
|
|
2972
|
+
terminalStatus: run.status,
|
|
2973
|
+
plan,
|
|
2974
|
+
currentIndex: 0,
|
|
2975
|
+
completedNodeIds: [],
|
|
2976
|
+
completedEntries: [],
|
|
2977
|
+
failure: null,
|
|
2978
|
+
startedAt: nowIso(() => now),
|
|
2979
|
+
completedAt: null,
|
|
2980
|
+
};
|
|
2981
|
+
run.status = "running";
|
|
2982
|
+
run.completedAt = null;
|
|
2983
|
+
run.phase = "sealed";
|
|
2984
|
+
return runProjection(run);
|
|
2985
|
+
},
|
|
2986
|
+
{
|
|
2987
|
+
allowTerminal: true,
|
|
2988
|
+
idempotencyKey: `compensation-start:${run.id}:${trigger || "terminal"}`,
|
|
2989
|
+
},
|
|
2990
|
+
);
|
|
2991
|
+
}
|
|
2992
|
+
|
|
2993
|
+
sendMessage(
|
|
2994
|
+
runId,
|
|
2995
|
+
{
|
|
2996
|
+
messageId = this.createId(),
|
|
2997
|
+
fromAttemptId,
|
|
2998
|
+
leaseId,
|
|
2999
|
+
fence,
|
|
3000
|
+
toAgentId,
|
|
3001
|
+
mode = "send",
|
|
3002
|
+
payload,
|
|
3003
|
+
dataPolicy,
|
|
3004
|
+
causationId = null,
|
|
3005
|
+
correlationId = null,
|
|
3006
|
+
ttlMs = 24 * 60 * 60 * 1000,
|
|
3007
|
+
} = {},
|
|
3008
|
+
) {
|
|
3009
|
+
const run = this._run(runId);
|
|
3010
|
+
const id = safeIdentifier(messageId, "messageId");
|
|
3011
|
+
const recipient = safeIdentifier(toAgentId, "toAgentId");
|
|
3012
|
+
const contentDigest = graphDigest(
|
|
3013
|
+
{ recipient, mode, payload, causationId, correlationId },
|
|
3014
|
+
"cc.graph.message/v1",
|
|
3015
|
+
);
|
|
3016
|
+
const existing = run.messages.get(id);
|
|
3017
|
+
if (existing) {
|
|
3018
|
+
if (existing.payloadDigest !== contentDigest) {
|
|
3019
|
+
throw kernelError(
|
|
3020
|
+
"CC_GRAPH_MESSAGE_ID_CONFLICT",
|
|
3021
|
+
"messageId was reused with different content",
|
|
3022
|
+
);
|
|
3023
|
+
}
|
|
3024
|
+
return Object.freeze(clone(existing));
|
|
3025
|
+
}
|
|
3026
|
+
return this._transaction(
|
|
3027
|
+
run,
|
|
3028
|
+
"message.admitted",
|
|
3029
|
+
{ messageId: id, toAgentId: recipient, mode },
|
|
3030
|
+
() => {
|
|
3031
|
+
const attempt = this._requireAttemptLease(
|
|
3032
|
+
run,
|
|
3033
|
+
fromAttemptId,
|
|
3034
|
+
leaseId,
|
|
3035
|
+
fence,
|
|
3036
|
+
);
|
|
3037
|
+
const policy = validateDataPolicy(dataPolicy);
|
|
3038
|
+
const sink = `agent:${recipient}`;
|
|
3039
|
+
if (!sinkAllowed(policy, sink)) {
|
|
3040
|
+
throw kernelError(
|
|
3041
|
+
"CC_GRAPH_MESSAGE_SINK_DENIED",
|
|
3042
|
+
`message data policy does not allow ${sink}`,
|
|
3043
|
+
);
|
|
3044
|
+
}
|
|
3045
|
+
if (
|
|
3046
|
+
policy.trust === "untrusted_content" &&
|
|
3047
|
+
containsAuthorityPayload(payload)
|
|
3048
|
+
) {
|
|
3049
|
+
throw kernelError(
|
|
3050
|
+
"CC_GRAPH_UNTRUSTED_AUTHORITY_PAYLOAD",
|
|
3051
|
+
"untrusted content cannot create approval, capability, or control authority",
|
|
3052
|
+
);
|
|
3053
|
+
}
|
|
3054
|
+
const pending = [...run.messages.values()].filter(
|
|
3055
|
+
(message) =>
|
|
3056
|
+
message.toAgentId === recipient &&
|
|
3057
|
+
["admitted", "delivered", "read"].includes(message.status),
|
|
3058
|
+
);
|
|
3059
|
+
if (pending.length >= this.maxPendingMessagesPerAgent) {
|
|
3060
|
+
throw kernelError(
|
|
3061
|
+
"CC_GRAPH_MESSAGE_BACKPRESSURE",
|
|
3062
|
+
`message queue is full for ${recipient}`,
|
|
3063
|
+
{ retryAfterMs: 100 },
|
|
3064
|
+
);
|
|
3065
|
+
}
|
|
3066
|
+
const now = this.now();
|
|
3067
|
+
const message = {
|
|
3068
|
+
id,
|
|
3069
|
+
runId: run.id,
|
|
3070
|
+
fromAttemptId: attempt.id,
|
|
3071
|
+
fromLeaseId: attempt.leaseId,
|
|
3072
|
+
fromFence: attempt.fence,
|
|
3073
|
+
toAgentId: recipient,
|
|
3074
|
+
causationId,
|
|
3075
|
+
correlationId,
|
|
3076
|
+
mode: mode === "followup" ? "followup" : "send",
|
|
3077
|
+
status: "admitted",
|
|
3078
|
+
payload: clone(payload),
|
|
3079
|
+
payloadDigest: contentDigest,
|
|
3080
|
+
dataPolicy: policy,
|
|
3081
|
+
createdAt: nowIso(() => now),
|
|
3082
|
+
updatedAt: nowIso(() => now),
|
|
3083
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 86_400_000)),
|
|
3084
|
+
expiresAtMs: now + finitePositive(ttlMs, 86_400_000),
|
|
3085
|
+
deliveryCount: 0,
|
|
3086
|
+
readAt: null,
|
|
3087
|
+
processedAt: null,
|
|
3088
|
+
};
|
|
3089
|
+
run.messages.set(id, message);
|
|
3090
|
+
return Object.freeze(clone(message));
|
|
3091
|
+
},
|
|
3092
|
+
{ idempotencyKey: `message:${id}` },
|
|
3093
|
+
);
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
deliverMessage(runId, messageId) {
|
|
3097
|
+
const run = this._run(runId);
|
|
3098
|
+
const id = safeIdentifier(messageId, "messageId");
|
|
3099
|
+
return this._transaction(
|
|
3100
|
+
run,
|
|
3101
|
+
"message.delivered",
|
|
3102
|
+
{ messageId: id },
|
|
3103
|
+
() => {
|
|
3104
|
+
const message = run.messages.get(id);
|
|
3105
|
+
if (!message) {
|
|
3106
|
+
throw kernelError(
|
|
3107
|
+
"CC_GRAPH_MESSAGE_NOT_FOUND",
|
|
3108
|
+
`message not found: ${id}`,
|
|
3109
|
+
);
|
|
3110
|
+
}
|
|
3111
|
+
if (message.status === "processed")
|
|
3112
|
+
return Object.freeze(clone(message));
|
|
3113
|
+
if (message.expiresAtMs <= this.now()) {
|
|
3114
|
+
message.status = "dead_letter";
|
|
3115
|
+
message.reason = "expired";
|
|
3116
|
+
} else {
|
|
3117
|
+
message.status = "delivered";
|
|
3118
|
+
message.deliveryCount += 1;
|
|
3119
|
+
}
|
|
3120
|
+
message.updatedAt = nowIso(this.now);
|
|
3121
|
+
return Object.freeze(clone(message));
|
|
3122
|
+
},
|
|
3123
|
+
);
|
|
3124
|
+
}
|
|
3125
|
+
|
|
3126
|
+
receiveMessages(runId, agentId, { markRead = true } = {}) {
|
|
3127
|
+
const run = this._run(runId);
|
|
3128
|
+
const recipient = safeIdentifier(agentId, "agentId");
|
|
3129
|
+
return this._transaction(
|
|
3130
|
+
run,
|
|
3131
|
+
markRead ? "message.read" : "message.received",
|
|
3132
|
+
{ agentId: recipient },
|
|
3133
|
+
() => {
|
|
3134
|
+
const messages = [...run.messages.values()]
|
|
3135
|
+
.filter(
|
|
3136
|
+
(message) =>
|
|
3137
|
+
message.toAgentId === recipient &&
|
|
3138
|
+
["delivered", "read"].includes(message.status),
|
|
3139
|
+
)
|
|
3140
|
+
.sort(
|
|
3141
|
+
(left, right) =>
|
|
3142
|
+
left.createdAt.localeCompare(right.createdAt) ||
|
|
3143
|
+
left.id.localeCompare(right.id),
|
|
3144
|
+
);
|
|
3145
|
+
if (markRead) {
|
|
3146
|
+
for (const message of messages) {
|
|
3147
|
+
message.status = "read";
|
|
3148
|
+
message.readAt ||= nowIso(this.now);
|
|
3149
|
+
message.updatedAt = nowIso(this.now);
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
return Object.freeze(
|
|
3153
|
+
messages.map((message) => Object.freeze(clone(message))),
|
|
3154
|
+
);
|
|
3155
|
+
},
|
|
3156
|
+
);
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
processMessage(runId, messageId, agentId, consumerKey) {
|
|
3160
|
+
const run = this._run(runId);
|
|
3161
|
+
const id = safeIdentifier(messageId, "messageId");
|
|
3162
|
+
const recipient = safeIdentifier(agentId, "agentId");
|
|
3163
|
+
const key = safeIdentifier(consumerKey, "consumerKey");
|
|
3164
|
+
const dedupKey = `${recipient}\0${id}\0${key}`;
|
|
3165
|
+
if (run.messageConsumers.has(dedupKey)) {
|
|
3166
|
+
return Object.freeze(clone(run.messageConsumers.get(dedupKey)));
|
|
3167
|
+
}
|
|
3168
|
+
return this._transaction(
|
|
3169
|
+
run,
|
|
3170
|
+
"message.processed",
|
|
3171
|
+
{ messageId: id, agentId: recipient, consumerKey: key },
|
|
3172
|
+
() => {
|
|
3173
|
+
const message = run.messages.get(id);
|
|
3174
|
+
if (!message || message.toAgentId !== recipient) {
|
|
3175
|
+
throw kernelError(
|
|
3176
|
+
"CC_GRAPH_MESSAGE_NOT_FOUND",
|
|
3177
|
+
`message is not addressed to ${recipient}`,
|
|
3178
|
+
);
|
|
3179
|
+
}
|
|
3180
|
+
if (!["delivered", "read", "processed"].includes(message.status)) {
|
|
3181
|
+
throw kernelError(
|
|
3182
|
+
"CC_GRAPH_MESSAGE_NOT_DELIVERED",
|
|
3183
|
+
"message must be delivered before processing",
|
|
3184
|
+
);
|
|
3185
|
+
}
|
|
3186
|
+
message.status = "processed";
|
|
3187
|
+
message.readAt ||= nowIso(this.now);
|
|
3188
|
+
message.processedAt ||= nowIso(this.now);
|
|
3189
|
+
message.updatedAt = nowIso(this.now);
|
|
3190
|
+
const receipt = {
|
|
3191
|
+
messageId: id,
|
|
3192
|
+
agentId: recipient,
|
|
3193
|
+
consumerKey: key,
|
|
3194
|
+
payloadDigest: message.payloadDigest,
|
|
3195
|
+
processedAt: message.processedAt,
|
|
3196
|
+
};
|
|
3197
|
+
run.messageConsumers.set(dedupKey, receipt);
|
|
3198
|
+
return Object.freeze(clone(receipt));
|
|
3199
|
+
},
|
|
3200
|
+
{
|
|
3201
|
+
idempotencyKey: `message-processed:${graphDigest(
|
|
3202
|
+
dedupKey,
|
|
3203
|
+
"cc.graph.message-consumer/v1",
|
|
3204
|
+
)}`,
|
|
3205
|
+
},
|
|
3206
|
+
);
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
deadLetterMessage(runId, messageId, reason = "poison_message") {
|
|
3210
|
+
const run = this._run(runId);
|
|
3211
|
+
const id = safeIdentifier(messageId, "messageId");
|
|
3212
|
+
return this._transaction(
|
|
3213
|
+
run,
|
|
3214
|
+
"message.dead_lettered",
|
|
3215
|
+
{ messageId: id, reason },
|
|
3216
|
+
() => {
|
|
3217
|
+
const message = run.messages.get(id);
|
|
3218
|
+
if (!message) {
|
|
3219
|
+
throw kernelError(
|
|
3220
|
+
"CC_GRAPH_MESSAGE_NOT_FOUND",
|
|
3221
|
+
`message not found: ${id}`,
|
|
3222
|
+
);
|
|
3223
|
+
}
|
|
3224
|
+
message.status = "dead_letter";
|
|
3225
|
+
message.reason = String(reason).slice(0, 1024);
|
|
3226
|
+
message.updatedAt = nowIso(this.now);
|
|
3227
|
+
return Object.freeze(clone(message));
|
|
3228
|
+
},
|
|
3229
|
+
);
|
|
3230
|
+
}
|
|
3231
|
+
|
|
3232
|
+
offerHandoff(
|
|
3233
|
+
runId,
|
|
3234
|
+
{
|
|
3235
|
+
handoffId = this.createId(),
|
|
3236
|
+
fromAttemptId,
|
|
3237
|
+
leaseId,
|
|
3238
|
+
fence,
|
|
3239
|
+
toAgentId,
|
|
3240
|
+
artifactIds = [],
|
|
3241
|
+
preconditions = {},
|
|
3242
|
+
ttlMs = 60_000,
|
|
3243
|
+
} = {},
|
|
3244
|
+
) {
|
|
3245
|
+
const run = this._run(runId);
|
|
3246
|
+
const id = safeIdentifier(handoffId, "handoffId");
|
|
3247
|
+
return this._transaction(
|
|
3248
|
+
run,
|
|
3249
|
+
"handoff.offered",
|
|
3250
|
+
{ handoffId: id, fromAttemptId, toAgentId },
|
|
3251
|
+
() => {
|
|
3252
|
+
const existing = run.handoffs.get(id);
|
|
3253
|
+
if (existing) return Object.freeze(clone(existing));
|
|
3254
|
+
const attempt = this._requireAttemptLease(
|
|
3255
|
+
run,
|
|
3256
|
+
fromAttemptId,
|
|
3257
|
+
leaseId,
|
|
3258
|
+
fence,
|
|
3259
|
+
);
|
|
3260
|
+
for (const artifactId of artifactIds) {
|
|
3261
|
+
if (!run.artifacts.has(artifactId)) {
|
|
3262
|
+
throw kernelError(
|
|
3263
|
+
"CC_GRAPH_ARTIFACT_NOT_FOUND",
|
|
3264
|
+
`handoff artifact not found: ${artifactId}`,
|
|
3265
|
+
);
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
const now = this.now();
|
|
3269
|
+
const handoff = {
|
|
3270
|
+
id,
|
|
3271
|
+
runId: run.id,
|
|
3272
|
+
nodeId: attempt.nodeId,
|
|
3273
|
+
fromAttemptId: attempt.id,
|
|
3274
|
+
fromLeaseId: attempt.leaseId,
|
|
3275
|
+
fromFence: attempt.fence,
|
|
3276
|
+
toAgentId: safeIdentifier(toAgentId, "toAgentId"),
|
|
3277
|
+
revisionDigest: run.revisionDigest,
|
|
3278
|
+
authorityDigest: run.authorityDigest,
|
|
3279
|
+
artifactIds: [...artifactIds],
|
|
3280
|
+
preconditions: clone(preconditions),
|
|
3281
|
+
status: "offered",
|
|
3282
|
+
createdAt: nowIso(() => now),
|
|
3283
|
+
updatedAt: nowIso(() => now),
|
|
3284
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 60_000)),
|
|
3285
|
+
expiresAtMs: now + finitePositive(ttlMs, 60_000),
|
|
3286
|
+
};
|
|
3287
|
+
run.handoffs.set(id, handoff);
|
|
3288
|
+
return Object.freeze(clone(handoff));
|
|
3289
|
+
},
|
|
3290
|
+
{ idempotencyKey: `handoff:${id}` },
|
|
3291
|
+
);
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
acceptHandoff(runId, handoffId, agentId) {
|
|
3295
|
+
const run = this._run(runId);
|
|
3296
|
+
const id = safeIdentifier(handoffId, "handoffId");
|
|
3297
|
+
const recipient = safeIdentifier(agentId, "agentId");
|
|
3298
|
+
return this._transaction(
|
|
3299
|
+
run,
|
|
3300
|
+
"handoff.accepted",
|
|
3301
|
+
{ handoffId: id, agentId: recipient },
|
|
3302
|
+
() => {
|
|
3303
|
+
const handoff = run.handoffs.get(id);
|
|
3304
|
+
if (
|
|
3305
|
+
!handoff ||
|
|
3306
|
+
handoff.status !== "offered" ||
|
|
3307
|
+
handoff.toAgentId !== recipient ||
|
|
3308
|
+
handoff.expiresAtMs <= this.now()
|
|
3309
|
+
) {
|
|
3310
|
+
throw kernelError(
|
|
3311
|
+
"CC_GRAPH_HANDOFF_NOT_ACCEPTABLE",
|
|
3312
|
+
"handoff is missing, expired, or addressed to another agent",
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
handoff.status = "accepted";
|
|
3316
|
+
handoff.updatedAt = nowIso(this.now);
|
|
3317
|
+
return Object.freeze(clone(handoff));
|
|
3318
|
+
},
|
|
3319
|
+
);
|
|
3320
|
+
}
|
|
3321
|
+
|
|
3322
|
+
rejectHandoff(runId, handoffId, agentId, reason = "rejected") {
|
|
3323
|
+
const run = this._run(runId);
|
|
3324
|
+
const id = safeIdentifier(handoffId, "handoffId");
|
|
3325
|
+
const recipient = safeIdentifier(agentId, "agentId");
|
|
3326
|
+
return this._transaction(
|
|
3327
|
+
run,
|
|
3328
|
+
"handoff.rejected",
|
|
3329
|
+
{ handoffId: id, reason },
|
|
3330
|
+
() => {
|
|
3331
|
+
const handoff = run.handoffs.get(id);
|
|
3332
|
+
if (
|
|
3333
|
+
!handoff ||
|
|
3334
|
+
handoff.status !== "offered" ||
|
|
3335
|
+
handoff.toAgentId !== recipient
|
|
3336
|
+
) {
|
|
3337
|
+
throw kernelError(
|
|
3338
|
+
"CC_GRAPH_HANDOFF_NOT_REJECTABLE",
|
|
3339
|
+
"handoff cannot be rejected in its current state",
|
|
3340
|
+
);
|
|
3341
|
+
}
|
|
3342
|
+
handoff.status = "rejected";
|
|
3343
|
+
handoff.reason = String(reason).slice(0, 1024);
|
|
3344
|
+
handoff.updatedAt = nowIso(this.now);
|
|
3345
|
+
return Object.freeze(clone(handoff));
|
|
3346
|
+
},
|
|
3347
|
+
);
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
commitHandoff(
|
|
3351
|
+
runId,
|
|
3352
|
+
handoffId,
|
|
3353
|
+
{
|
|
3354
|
+
leaseId = this.createId(),
|
|
3355
|
+
attemptId = this.createId(),
|
|
3356
|
+
ttlMs = 60_000,
|
|
3357
|
+
} = {},
|
|
3358
|
+
) {
|
|
3359
|
+
const run = this._run(runId);
|
|
3360
|
+
const id = safeIdentifier(handoffId, "handoffId");
|
|
3361
|
+
return this._transaction(
|
|
3362
|
+
run,
|
|
3363
|
+
"handoff.committed",
|
|
3364
|
+
{ handoffId: id },
|
|
3365
|
+
() => {
|
|
3366
|
+
const handoff = run.handoffs.get(id);
|
|
3367
|
+
if (!handoff || handoff.status !== "accepted") {
|
|
3368
|
+
throw kernelError(
|
|
3369
|
+
"CC_GRAPH_HANDOFF_NOT_COMMITTABLE",
|
|
3370
|
+
"handoff must be accepted before custody can transfer",
|
|
3371
|
+
);
|
|
3372
|
+
}
|
|
3373
|
+
if (
|
|
3374
|
+
handoff.revisionDigest !== run.revisionDigest ||
|
|
3375
|
+
handoff.authorityDigest !== run.authorityDigest
|
|
3376
|
+
) {
|
|
3377
|
+
throw kernelError(
|
|
3378
|
+
"CC_GRAPH_HANDOFF_BINDING_STALE",
|
|
3379
|
+
"handoff binding no longer matches the GraphRun",
|
|
3380
|
+
);
|
|
3381
|
+
}
|
|
3382
|
+
const sender = this._requireAttemptLease(
|
|
3383
|
+
run,
|
|
3384
|
+
handoff.fromAttemptId,
|
|
3385
|
+
handoff.fromLeaseId,
|
|
3386
|
+
handoff.fromFence,
|
|
3387
|
+
);
|
|
3388
|
+
const now = this.now();
|
|
3389
|
+
sender.status = "expired";
|
|
3390
|
+
sender.participationStatus = "handed_off";
|
|
3391
|
+
sender.updatedAt = nowIso(() => now);
|
|
3392
|
+
const fence = (run.fenceCounters.get(sender.nodeId) || 0) + 1;
|
|
3393
|
+
run.fenceCounters.set(sender.nodeId, fence);
|
|
3394
|
+
const iterationPath = [...(sender.iterationPath || [])];
|
|
3395
|
+
const attemptNumber =
|
|
3396
|
+
[...run.attempts.values()].filter(
|
|
3397
|
+
(candidate) =>
|
|
3398
|
+
candidate.nodeId === sender.nodeId &&
|
|
3399
|
+
JSON.stringify(candidate.iterationPath || []) ===
|
|
3400
|
+
JSON.stringify(iterationPath),
|
|
3401
|
+
).length + 1;
|
|
3402
|
+
const newAttempt = {
|
|
3403
|
+
id: safeIdentifier(attemptId, "attemptId"),
|
|
3404
|
+
runId: run.id,
|
|
3405
|
+
nodeId: sender.nodeId,
|
|
3406
|
+
iterationPath,
|
|
3407
|
+
attempt: attemptNumber,
|
|
3408
|
+
agentId: handoff.toAgentId,
|
|
3409
|
+
role: "executor",
|
|
3410
|
+
leaseId: safeIdentifier(leaseId, "leaseId"),
|
|
3411
|
+
fence,
|
|
3412
|
+
status: "active",
|
|
3413
|
+
participationStatus: "active",
|
|
3414
|
+
grant: clone(sender.grant),
|
|
3415
|
+
createdAt: nowIso(() => now),
|
|
3416
|
+
updatedAt: nowIso(() => now),
|
|
3417
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 60_000)),
|
|
3418
|
+
expiresAtMs: now + finitePositive(ttlMs, 60_000),
|
|
3419
|
+
terminalEvidence: null,
|
|
3420
|
+
usage: null,
|
|
3421
|
+
};
|
|
3422
|
+
run.attempts.set(newAttempt.id, newAttempt);
|
|
3423
|
+
run.nodeStates.get(sender.nodeId).attemptIds.push(newAttempt.id);
|
|
3424
|
+
handoff.status = "committed";
|
|
3425
|
+
handoff.committedAttemptId = newAttempt.id;
|
|
3426
|
+
handoff.updatedAt = nowIso(() => now);
|
|
3427
|
+
return Object.freeze({
|
|
3428
|
+
handoff: Object.freeze(clone(handoff)),
|
|
3429
|
+
assignmentAttempt: attemptProjection(newAttempt),
|
|
3430
|
+
});
|
|
3431
|
+
},
|
|
3432
|
+
);
|
|
3433
|
+
}
|
|
3434
|
+
|
|
3435
|
+
revokeHandoff(runId, handoffId, fromAttemptId, leaseId, fence) {
|
|
3436
|
+
const run = this._run(runId);
|
|
3437
|
+
const id = safeIdentifier(handoffId, "handoffId");
|
|
3438
|
+
return this._transaction(run, "handoff.revoked", { handoffId: id }, () => {
|
|
3439
|
+
const handoff = run.handoffs.get(id);
|
|
3440
|
+
if (!handoff || !["offered", "accepted"].includes(handoff.status)) {
|
|
3441
|
+
throw kernelError(
|
|
3442
|
+
"CC_GRAPH_HANDOFF_NOT_REVOKABLE",
|
|
3443
|
+
"committed or terminal handoffs cannot be revoked",
|
|
3444
|
+
);
|
|
3445
|
+
}
|
|
3446
|
+
this._requireAttemptLease(run, fromAttemptId, leaseId, fence);
|
|
3447
|
+
if (handoff.fromAttemptId !== fromAttemptId) {
|
|
3448
|
+
throw kernelError(
|
|
3449
|
+
"CC_GRAPH_HANDOFF_SENDER_MISMATCH",
|
|
3450
|
+
"only the current custody holder can revoke the handoff",
|
|
3451
|
+
);
|
|
3452
|
+
}
|
|
3453
|
+
handoff.status = "revoked";
|
|
3454
|
+
handoff.updatedAt = nowIso(this.now);
|
|
3455
|
+
return Object.freeze(clone(handoff));
|
|
3456
|
+
});
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
createHumanTask(
|
|
3460
|
+
runId,
|
|
3461
|
+
{
|
|
3462
|
+
humanTaskId = this.createId(),
|
|
3463
|
+
attemptId,
|
|
3464
|
+
leaseId,
|
|
3465
|
+
fence,
|
|
3466
|
+
operation,
|
|
3467
|
+
nonce = this.createId(),
|
|
3468
|
+
ttlMs = 24 * 60 * 60 * 1000,
|
|
3469
|
+
quorum = 1,
|
|
3470
|
+
separationOfDuties = false,
|
|
3471
|
+
} = {},
|
|
3472
|
+
) {
|
|
3473
|
+
const run = this._run(runId);
|
|
3474
|
+
const id = safeIdentifier(humanTaskId, "humanTaskId");
|
|
3475
|
+
return this._transaction(
|
|
3476
|
+
run,
|
|
3477
|
+
"human_task.created",
|
|
3478
|
+
{ humanTaskId: id, attemptId },
|
|
3479
|
+
() => {
|
|
3480
|
+
const attempt = this._requireAttemptLease(
|
|
3481
|
+
run,
|
|
3482
|
+
attemptId,
|
|
3483
|
+
leaseId,
|
|
3484
|
+
fence,
|
|
3485
|
+
);
|
|
3486
|
+
const now = this.now();
|
|
3487
|
+
attempt.status = "waiting_human";
|
|
3488
|
+
attempt.participationStatus = "waiting_human";
|
|
3489
|
+
attempt.updatedAt = nowIso(() => now);
|
|
3490
|
+
const state = run.nodeStates.get(attempt.nodeId);
|
|
3491
|
+
state.status = "waiting_human";
|
|
3492
|
+
state.updatedAt = nowIso(() => now);
|
|
3493
|
+
const agent = run.agents.get(attempt.agentId);
|
|
3494
|
+
if (agent) {
|
|
3495
|
+
agent.status = "idle";
|
|
3496
|
+
agent.updatedAt = nowIso(() => now);
|
|
3497
|
+
}
|
|
3498
|
+
const task = {
|
|
3499
|
+
id,
|
|
3500
|
+
runId: run.id,
|
|
3501
|
+
revisionDigest: run.revisionDigest,
|
|
3502
|
+
nodeId: attempt.nodeId,
|
|
3503
|
+
attemptId: attempt.id,
|
|
3504
|
+
operation: clone(operation),
|
|
3505
|
+
operationDigest: graphDigest(
|
|
3506
|
+
operation,
|
|
3507
|
+
"cc.graph.human-operation/v1",
|
|
3508
|
+
),
|
|
3509
|
+
authorityDigest: run.authorityDigest,
|
|
3510
|
+
status: "open",
|
|
3511
|
+
nonce: safeIdentifier(nonce, "nonce"),
|
|
3512
|
+
quorum: Math.max(1, Number(quorum) || 1),
|
|
3513
|
+
separationOfDuties: separationOfDuties === true,
|
|
3514
|
+
decisions: [],
|
|
3515
|
+
claimActorId: null,
|
|
3516
|
+
claimLeaseId: null,
|
|
3517
|
+
claimExpiresAtMs: null,
|
|
3518
|
+
createdAt: nowIso(() => now),
|
|
3519
|
+
updatedAt: nowIso(() => now),
|
|
3520
|
+
expiresAt: nowIso(() => now + finitePositive(ttlMs, 86_400_000)),
|
|
3521
|
+
expiresAtMs: now + finitePositive(ttlMs, 86_400_000),
|
|
3522
|
+
decision: null,
|
|
3523
|
+
};
|
|
3524
|
+
run.humanTasks.set(id, task);
|
|
3525
|
+
run.status = "waiting_human";
|
|
3526
|
+
return Object.freeze(clone(task));
|
|
3527
|
+
},
|
|
3528
|
+
{ idempotencyKey: `human-task:${id}` },
|
|
3529
|
+
);
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
claimHumanTask(
|
|
3533
|
+
runId,
|
|
3534
|
+
humanTaskId,
|
|
3535
|
+
actorId,
|
|
3536
|
+
{ claimLeaseId = this.createId(), ttlMs = 5 * 60 * 1000 } = {},
|
|
3537
|
+
) {
|
|
3538
|
+
const run = this._run(runId);
|
|
3539
|
+
const id = safeIdentifier(humanTaskId, "humanTaskId");
|
|
3540
|
+
const actor = safeIdentifier(actorId, "actorId");
|
|
3541
|
+
return this._transaction(
|
|
3542
|
+
run,
|
|
3543
|
+
"human_task.claimed",
|
|
3544
|
+
{ humanTaskId: id, actorId: actor },
|
|
3545
|
+
() => {
|
|
3546
|
+
const task = run.humanTasks.get(id);
|
|
3547
|
+
const now = this.now();
|
|
3548
|
+
if (
|
|
3549
|
+
!task ||
|
|
3550
|
+
!["open", "claimed"].includes(task.status) ||
|
|
3551
|
+
task.expiresAtMs <= now
|
|
3552
|
+
) {
|
|
3553
|
+
throw kernelError(
|
|
3554
|
+
"CC_GRAPH_HUMAN_TASK_NOT_CLAIMABLE",
|
|
3555
|
+
"human task is missing, expired, or terminal",
|
|
3556
|
+
);
|
|
3557
|
+
}
|
|
3558
|
+
if (
|
|
3559
|
+
task.status === "claimed" &&
|
|
3560
|
+
task.claimExpiresAtMs > now &&
|
|
3561
|
+
task.claimActorId !== actor
|
|
3562
|
+
) {
|
|
3563
|
+
throw kernelError(
|
|
3564
|
+
"CC_GRAPH_HUMAN_TASK_CLAIMED",
|
|
3565
|
+
"human task is already claimed",
|
|
3566
|
+
);
|
|
3567
|
+
}
|
|
3568
|
+
task.status = "claimed";
|
|
3569
|
+
task.claimActorId = actor;
|
|
3570
|
+
task.claimLeaseId = safeIdentifier(claimLeaseId, "claimLeaseId");
|
|
3571
|
+
task.claimExpiresAtMs = now + finitePositive(ttlMs, 300_000);
|
|
3572
|
+
task.updatedAt = nowIso(() => now);
|
|
3573
|
+
return Object.freeze(clone(task));
|
|
3574
|
+
},
|
|
3575
|
+
);
|
|
3576
|
+
}
|
|
3577
|
+
|
|
3578
|
+
decideHumanTask(
|
|
3579
|
+
runId,
|
|
3580
|
+
humanTaskId,
|
|
3581
|
+
{
|
|
3582
|
+
actorId,
|
|
3583
|
+
claimLeaseId,
|
|
3584
|
+
revisionDigest,
|
|
3585
|
+
operationDigest,
|
|
3586
|
+
nonce,
|
|
3587
|
+
decision,
|
|
3588
|
+
} = {},
|
|
3589
|
+
) {
|
|
3590
|
+
const run = this._run(runId);
|
|
3591
|
+
const id = safeIdentifier(humanTaskId, "humanTaskId");
|
|
3592
|
+
return this._transaction(
|
|
3593
|
+
run,
|
|
3594
|
+
"human_task.decided",
|
|
3595
|
+
{ humanTaskId: id, actorId },
|
|
3596
|
+
() => {
|
|
3597
|
+
const task = run.humanTasks.get(id);
|
|
3598
|
+
const now = this.now();
|
|
3599
|
+
if (
|
|
3600
|
+
!task ||
|
|
3601
|
+
task.status !== "claimed" ||
|
|
3602
|
+
task.claimActorId !== safeIdentifier(actorId, "actorId") ||
|
|
3603
|
+
task.claimLeaseId !== safeIdentifier(claimLeaseId, "claimLeaseId") ||
|
|
3604
|
+
task.claimExpiresAtMs <= now
|
|
3605
|
+
) {
|
|
3606
|
+
throw kernelError(
|
|
3607
|
+
"CC_GRAPH_HUMAN_TASK_STALE_CLAIM",
|
|
3608
|
+
"human task claim is stale or owned by another actor",
|
|
3609
|
+
);
|
|
3610
|
+
}
|
|
3611
|
+
if (
|
|
3612
|
+
task.revisionDigest !== revisionDigest ||
|
|
3613
|
+
task.operationDigest !== operationDigest ||
|
|
3614
|
+
task.nonce !== nonce ||
|
|
3615
|
+
task.authorityDigest !== run.authorityDigest
|
|
3616
|
+
) {
|
|
3617
|
+
throw kernelError(
|
|
3618
|
+
"CC_GRAPH_HUMAN_TASK_BINDING_MISMATCH",
|
|
3619
|
+
"human decision does not match the bound revision, operation, nonce, or authority",
|
|
3620
|
+
);
|
|
3621
|
+
}
|
|
3622
|
+
if (
|
|
3623
|
+
!decision ||
|
|
3624
|
+
![
|
|
3625
|
+
"acceptOnce",
|
|
3626
|
+
"acceptForTurn",
|
|
3627
|
+
"acceptForSession",
|
|
3628
|
+
"decline",
|
|
3629
|
+
"cancel",
|
|
3630
|
+
].includes(decision.kind)
|
|
3631
|
+
) {
|
|
3632
|
+
throw kernelError(
|
|
3633
|
+
"CC_GRAPH_HUMAN_DECISION_INVALID",
|
|
3634
|
+
"human decision kind is invalid",
|
|
3635
|
+
);
|
|
3636
|
+
}
|
|
3637
|
+
if (
|
|
3638
|
+
task.separationOfDuties &&
|
|
3639
|
+
task.decisions.some((entry) => entry.actorId === actorId)
|
|
3640
|
+
) {
|
|
3641
|
+
throw kernelError(
|
|
3642
|
+
"CC_GRAPH_HUMAN_SEPARATION_OF_DUTIES",
|
|
3643
|
+
"the same actor cannot satisfy multiple separated decisions",
|
|
3644
|
+
);
|
|
3645
|
+
}
|
|
3646
|
+
task.decisions.push({
|
|
3647
|
+
actorId,
|
|
3648
|
+
decision: clone(decision),
|
|
3649
|
+
decidedAt: nowIso(() => now),
|
|
3650
|
+
});
|
|
3651
|
+
const accepted = task.decisions.filter((entry) =>
|
|
3652
|
+
["acceptOnce", "acceptForTurn", "acceptForSession"].includes(
|
|
3653
|
+
entry.decision.kind,
|
|
3654
|
+
),
|
|
3655
|
+
).length;
|
|
3656
|
+
const isDecline = ["decline", "cancel"].includes(decision.kind);
|
|
3657
|
+
if (isDecline || accepted >= task.quorum) {
|
|
3658
|
+
task.status = "decided";
|
|
3659
|
+
task.decision = clone(decision);
|
|
3660
|
+
const attempt = run.attempts.get(task.attemptId);
|
|
3661
|
+
if (attempt && attempt.status === "waiting_human") {
|
|
3662
|
+
attempt.status = "expired";
|
|
3663
|
+
attempt.participationStatus = "human_decided";
|
|
3664
|
+
attempt.updatedAt = nowIso(() => now);
|
|
3665
|
+
}
|
|
3666
|
+
const state = run.nodeStates.get(task.nodeId);
|
|
3667
|
+
state.status = isDecline
|
|
3668
|
+
? decision.kind === "cancel"
|
|
3669
|
+
? "cancelled"
|
|
3670
|
+
: "failed"
|
|
3671
|
+
: "pending";
|
|
3672
|
+
state.blockedRoot = isDecline ? task.id : null;
|
|
3673
|
+
state.updatedAt = nowIso(() => now);
|
|
3674
|
+
} else {
|
|
3675
|
+
task.status = "open";
|
|
3676
|
+
task.claimActorId = null;
|
|
3677
|
+
task.claimLeaseId = null;
|
|
3678
|
+
task.claimExpiresAtMs = null;
|
|
3679
|
+
}
|
|
3680
|
+
task.updatedAt = nowIso(() => now);
|
|
3681
|
+
run.status = classifyQuiescence(run, now);
|
|
3682
|
+
return Object.freeze(clone(task));
|
|
3683
|
+
},
|
|
3684
|
+
);
|
|
3685
|
+
}
|
|
3686
|
+
|
|
3687
|
+
cancelHumanTask(runId, humanTaskId, reason = "cancelled") {
|
|
3688
|
+
const run = this._run(runId);
|
|
3689
|
+
const id = safeIdentifier(humanTaskId, "humanTaskId");
|
|
3690
|
+
return this._transaction(
|
|
3691
|
+
run,
|
|
3692
|
+
"human_task.cancelled",
|
|
3693
|
+
{ humanTaskId: id, reason },
|
|
3694
|
+
() => {
|
|
3695
|
+
const task = run.humanTasks.get(id);
|
|
3696
|
+
if (!task || !["open", "claimed"].includes(task.status)) {
|
|
3697
|
+
throw kernelError(
|
|
3698
|
+
"CC_GRAPH_HUMAN_TASK_TERMINAL",
|
|
3699
|
+
"human task is already terminal",
|
|
3700
|
+
);
|
|
3701
|
+
}
|
|
3702
|
+
task.status = "cancelled";
|
|
3703
|
+
task.reason = String(reason).slice(0, 1024);
|
|
3704
|
+
task.updatedAt = nowIso(this.now);
|
|
3705
|
+
const state = run.nodeStates.get(task.nodeId);
|
|
3706
|
+
state.status = "cancelled";
|
|
3707
|
+
state.blockedRoot = task.id;
|
|
3708
|
+
state.updatedAt = nowIso(this.now);
|
|
3709
|
+
return Object.freeze(clone(task));
|
|
3710
|
+
},
|
|
3711
|
+
);
|
|
3712
|
+
}
|
|
3713
|
+
|
|
3714
|
+
setWaitReason(runId, nodeId, reason) {
|
|
3715
|
+
const run = this._run(runId);
|
|
3716
|
+
const id = safeIdentifier(nodeId, "nodeId");
|
|
3717
|
+
return this._transaction(
|
|
3718
|
+
run,
|
|
3719
|
+
"wait.updated",
|
|
3720
|
+
{ nodeId: id, reason },
|
|
3721
|
+
() => {
|
|
3722
|
+
if (!run.nodeStates.has(id)) {
|
|
3723
|
+
throw kernelError(
|
|
3724
|
+
"CC_GRAPH_NODE_NOT_FOUND",
|
|
3725
|
+
`Graph node not found: ${id}`,
|
|
3726
|
+
);
|
|
3727
|
+
}
|
|
3728
|
+
if (reason == null) {
|
|
3729
|
+
run.waitReasons.delete(id);
|
|
3730
|
+
return null;
|
|
3731
|
+
}
|
|
3732
|
+
const normalized = {
|
|
3733
|
+
kind: String(reason.kind || "external"),
|
|
3734
|
+
resourceId:
|
|
3735
|
+
reason.resourceId == null
|
|
3736
|
+
? null
|
|
3737
|
+
: String(reason.resourceId).slice(0, 256),
|
|
3738
|
+
ownerNodeId:
|
|
3739
|
+
reason.ownerNodeId == null
|
|
3740
|
+
? null
|
|
3741
|
+
: safeIdentifier(reason.ownerNodeId, "ownerNodeId"),
|
|
3742
|
+
since: nowIso(this.now),
|
|
3743
|
+
};
|
|
3744
|
+
run.waitReasons.set(id, normalized);
|
|
3745
|
+
return Object.freeze(clone(normalized));
|
|
3746
|
+
},
|
|
3747
|
+
);
|
|
3748
|
+
}
|
|
3749
|
+
|
|
3750
|
+
recordProgressDigest(runId, value) {
|
|
3751
|
+
const run = this._run(runId);
|
|
3752
|
+
const digest = graphDigest(value, "cc.graph.progress/v1");
|
|
3753
|
+
return this._transaction(run, "progress.observed", { digest }, () => {
|
|
3754
|
+
const count = (run.progressDigests.get(digest) || 0) + 1;
|
|
3755
|
+
run.progressDigests.set(digest, count);
|
|
3756
|
+
if (count >= this.maxLivelockRepeats) {
|
|
3757
|
+
run.status = "reconciliation_required";
|
|
3758
|
+
}
|
|
3759
|
+
return Object.freeze({
|
|
3760
|
+
digest,
|
|
3761
|
+
count,
|
|
3762
|
+
livelockSuspected: count >= this.maxLivelockRepeats,
|
|
3763
|
+
});
|
|
3764
|
+
});
|
|
3765
|
+
}
|
|
3766
|
+
|
|
3767
|
+
classify(runId) {
|
|
3768
|
+
const run = this._run(runId);
|
|
3769
|
+
return Object.freeze({
|
|
3770
|
+
status: classifyQuiescence(run, this.now()),
|
|
3771
|
+
waitCycles: Object.freeze(waitGraphCycles(run).map(Object.freeze)),
|
|
3772
|
+
readyNodeIds: Object.freeze(
|
|
3773
|
+
this.readyNodes(runId).map((entry) => entry.nodeId),
|
|
3774
|
+
),
|
|
3775
|
+
});
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3778
|
+
|
|
3779
|
+
export const _graphKernelInternals = Object.freeze({
|
|
3780
|
+
classifyQuiescence,
|
|
3781
|
+
dependencySatisfied,
|
|
3782
|
+
nodeReadiness,
|
|
3783
|
+
propagate,
|
|
3784
|
+
restoreState,
|
|
3785
|
+
stateSnapshot,
|
|
3786
|
+
terminalAlgebra,
|
|
3787
|
+
waitGraphCycles,
|
|
3788
|
+
});
|