@hol-org/cigar 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/README.md +68 -0
  4. package/dist/client.d.ts +16 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/client.js +839 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/digest.d.ts +21 -0
  9. package/dist/digest.d.ts.map +1 -0
  10. package/dist/digest.js +406 -0
  11. package/dist/digest.js.map +1 -0
  12. package/dist/errors.d.ts +35 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +54 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/examples/quickstart.d.ts +2 -0
  17. package/dist/examples/quickstart.d.ts.map +1 -0
  18. package/dist/examples/quickstart.js +32 -0
  19. package/dist/examples/quickstart.js.map +1 -0
  20. package/dist/examples/two-agent-observer.d.ts +9 -0
  21. package/dist/examples/two-agent-observer.d.ts.map +1 -0
  22. package/dist/examples/two-agent-observer.js +59 -0
  23. package/dist/examples/two-agent-observer.js.map +1 -0
  24. package/dist/examples/verify-shared-bundle.d.ts +2 -0
  25. package/dist/examples/verify-shared-bundle.d.ts.map +1 -0
  26. package/dist/examples/verify-shared-bundle.js +13 -0
  27. package/dist/examples/verify-shared-bundle.js.map +1 -0
  28. package/dist/generated/cigar_service_pb.d.ts +642 -0
  29. package/dist/generated/cigar_service_pb.d.ts.map +1 -0
  30. package/dist/generated/cigar_service_pb.js +55 -0
  31. package/dist/generated/cigar_service_pb.js.map +1 -0
  32. package/dist/generated/context_abi_pb.d.ts +3429 -0
  33. package/dist/generated/context_abi_pb.d.ts.map +1 -0
  34. package/dist/generated/context_abi_pb.js +1386 -0
  35. package/dist/generated/context_abi_pb.js.map +1 -0
  36. package/dist/generated/errors.d.ts +242 -0
  37. package/dist/generated/errors.d.ts.map +1 -0
  38. package/dist/generated/errors.js +38 -0
  39. package/dist/generated/errors.js.map +1 -0
  40. package/dist/generated/generated/error_codes_pb.d.ts +188 -0
  41. package/dist/generated/generated/error_codes_pb.d.ts.map +1 -0
  42. package/dist/generated/generated/error_codes_pb.js +191 -0
  43. package/dist/generated/generated/error_codes_pb.js.map +1 -0
  44. package/dist/generated/models.d.ts +472 -0
  45. package/dist/generated/models.d.ts.map +1 -0
  46. package/dist/generated/models.js +314 -0
  47. package/dist/generated/models.js.map +1 -0
  48. package/dist/generated/operations.d.ts +912 -0
  49. package/dist/generated/operations.d.ts.map +1 -0
  50. package/dist/generated/operations.js +50 -0
  51. package/dist/generated/operations.js.map +1 -0
  52. package/dist/idempotency.d.ts +3 -0
  53. package/dist/idempotency.d.ts.map +1 -0
  54. package/dist/idempotency.js +16 -0
  55. package/dist/idempotency.js.map +1 -0
  56. package/dist/index.d.ts +13 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +13 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/release.json +6 -0
  61. package/dist/types.d.ts +115 -0
  62. package/dist/types.d.ts.map +1 -0
  63. package/dist/types.js +3 -0
  64. package/dist/types.js.map +1 -0
  65. package/dist/verify-replay.d.ts +3 -0
  66. package/dist/verify-replay.d.ts.map +1 -0
  67. package/dist/verify-replay.js +391 -0
  68. package/dist/verify-replay.js.map +1 -0
  69. package/dist/verify-vectors.d.ts +3 -0
  70. package/dist/verify-vectors.d.ts.map +1 -0
  71. package/dist/verify-vectors.js +383 -0
  72. package/dist/verify-vectors.js.map +1 -0
  73. package/dist/workflow-session.d.ts +93 -0
  74. package/dist/workflow-session.d.ts.map +1 -0
  75. package/dist/workflow-session.js +550 -0
  76. package/dist/workflow-session.js.map +1 -0
  77. package/fixtures/semantic-bundle-v1.json +13 -0
  78. package/package.json +60 -0
@@ -0,0 +1,93 @@
1
+ /** Identity-only state tracking for deterministic workflow context cycles. */
2
+ import { CigarError } from "./errors.js";
3
+ export declare const MAX_WORKFLOW_DELTA_CHAIN_LENGTH = 8;
4
+ export declare const MAX_WORKFLOW_REPLAY_CYCLES = 64;
5
+ export declare const WORKFLOW_CONTEXT_PHASES: readonly ["new", "plan_created", "target_bundle_loaded", "delta_compiled", "bundle_ready", "materialized", "model_invocation_pending", "model_result_recorded", "effect_prepared", "observation_recorded", "effect_authorization_revalidated", "effect_authorized", "effect_revalidated", "effect_dispatching", "effect_ambiguous", "effect_settled", "checkpointed", "finished", "replay_verified", "quarantined"];
6
+ export type WorkflowContextPhase = typeof WORKFLOW_CONTEXT_PHASES[number];
7
+ export declare const WORKFLOW_RESUME_ACTIONS: readonly ["create_context_plan", "compile_context_bundle", "compile_context_delta", "apply_context_delta", "materialize_context_bundle", "begin_model_invocation", "resume_model_invocation", "prepare_effect_or_ingest_observation", "ingest_observation", "authorize_effect_or_checkpoint", "revalidate_context_bundle", "dispatch_effect", "observe_effect", "reconcile_effect", "checkpoint", "materialize_or_finish", "replay", "complete"];
8
+ export type WorkflowResumeAction = typeof WORKFLOW_RESUME_ACTIONS[number];
9
+ export declare const WORKFLOW_SESSION_ERROR_CODES: readonly ["invalid_transition", "invalid_event", "identity_mismatch", "invalidated", "limit_exceeded"];
10
+ export type WorkflowSessionErrorCode = typeof WORKFLOW_SESSION_ERROR_CODES[number];
11
+ export declare const WORKFLOW_SESSION_EVENT_NAMES: readonly ["plan_created", "bundle_compiled", "delta_compiled", "delta_applied", "materialized", "model_invocation_started", "model_result_recorded", "effect_prepared", "observation_recorded", "effect_authorized", "effect_revalidated", "effect_dispatched", "effect_observed", "cycle_checkpointed", "finished", "replay_verified", "context_quarantined"];
12
+ export declare const WORKFLOW_QUARANTINE_REASONS: readonly ["cancelled", "revoked", "invalidated"];
13
+ export type WorkflowQuarantineReason = typeof WORKFLOW_QUARANTINE_REASONS[number];
14
+ export declare function workflowOperationId(action: WorkflowResumeAction): string | null;
15
+ export declare class WorkflowSessionError extends CigarError {
16
+ readonly code: WorkflowSessionErrorCode;
17
+ constructor(code: WorkflowSessionErrorCode);
18
+ }
19
+ export type WorkflowEffectState = "prepared" | "authorized" | "dispatching" | "unknown" | "authorized_for_retry" | "succeeded" | "failed" | "manual_resolution" | "rejected" | "expired" | "cancelled" | "compensated" | "compensation_failed";
20
+ type EffectIdentity = Readonly<{
21
+ effectId: string;
22
+ intentDigest: string;
23
+ effectVersion: bigint;
24
+ state: WorkflowEffectState;
25
+ attemptCount: number;
26
+ reconciliationCount: number;
27
+ }>;
28
+ export type WorkflowReplayDiffStatus = "equal" | "different";
29
+ export type WorkflowDeltaReplayIdentity = Readonly<{
30
+ baseBundleId: string;
31
+ targetBundleId: string;
32
+ deltaDigest: string;
33
+ }>;
34
+ export type WorkflowEffectReplayIdentity = Readonly<EffectIdentity>;
35
+ export type WorkflowContextCycleIdentity = Readonly<{
36
+ planId: string;
37
+ bundleId: string;
38
+ contractDigest: string;
39
+ selectedDelta?: WorkflowDeltaReplayIdentity;
40
+ materializedBundleId: string;
41
+ tokenizerFingerprint: string;
42
+ materializerFingerprint: string;
43
+ physicalInputTokens: number;
44
+ invocationId: string;
45
+ requestDigest: string;
46
+ idempotencyKeyDigest: string;
47
+ modelResultDigest: string;
48
+ effect?: WorkflowEffectReplayIdentity;
49
+ outcomeDigest: string;
50
+ outcomeRevision: bigint;
51
+ }>;
52
+ export type WorkflowContextReplayIdentity = Readonly<{
53
+ cycles: readonly WorkflowContextCycleIdentity[];
54
+ }>;
55
+ export type WorkflowContextReplayComparison = Readonly<{
56
+ bundleDeltaSelection: WorkflowReplayDiffStatus;
57
+ materialization: WorkflowReplayDiffStatus;
58
+ modelResultIdentity: WorkflowReplayDiffStatus;
59
+ toolEffectDecisions: WorkflowReplayDiffStatus;
60
+ outcome: WorkflowReplayDiffStatus;
61
+ exactMatch: boolean;
62
+ }>;
63
+ /** Mutable, content-safe helper for one context lifecycle. Successful boundaries advance it atomically. */
64
+ export declare class WorkflowContextSession {
65
+ #private;
66
+ get phase(): WorkflowContextPhase;
67
+ get completedTurns(): number;
68
+ get deltaChainLength(): number;
69
+ get activeBundleId(): string | undefined;
70
+ replayIdentity(): WorkflowContextReplayIdentity;
71
+ compareReplay(candidate: WorkflowContextReplayIdentity): WorkflowContextReplayComparison;
72
+ get resumeAction(): WorkflowResumeAction;
73
+ toString(): string;
74
+ recordPlanCreated(planId: string, bundleId: string, contractDigest: string): void;
75
+ recordBundleCompiled(bundleId: string, contractDigest: string): void;
76
+ recordDeltaCompiled(baseBundleId: string, targetBundleId: string, deltaDigest: string): void;
77
+ recordDeltaApplied(baseBundleId: string, targetBundleId: string, deltaDigest: string): void;
78
+ recordMaterialized(bundleId: string, tokenizerFingerprint: string, materializerFingerprint: string, physicalInputTokens: number): void;
79
+ beginModelInvocation(invocationId: string, requestDigest: string, idempotencyKeyDigest: string): void;
80
+ recordModelResult(invocationId: string, resultDigest: string): void;
81
+ recordEffectPrepared(effectId: string, intentDigest: string, effectVersion: bigint, state?: WorkflowEffectState, attemptCount?: number, reconciliationCount?: number): void;
82
+ recordObservation(publicationDigest: string, revision: bigint): void;
83
+ recordEffectAuthorized(effectId: string, intentDigest: string, effectVersion: bigint, state?: WorkflowEffectState, attemptCount?: number, reconciliationCount?: number): void;
84
+ recordEffectRevalidated(bundleId: string, valid: boolean): void;
85
+ quarantineContext(bundleId: string, reason: WorkflowQuarantineReason): void;
86
+ recordEffectDispatched(effectId: string, intentDigest: string, effectVersion: bigint, state: WorkflowEffectState, attemptCount: number, reconciliationCount: number): void;
87
+ recordEffectObserved(effectId: string, intentDigest: string, effectVersion: bigint, state: WorkflowEffectState, attemptCount: number, reconciliationCount: number): void;
88
+ checkpointCycle(): void;
89
+ finish(): void;
90
+ recordReplayVerified(decisionId: string, executionId: string, candidate: WorkflowContextReplayIdentity): WorkflowContextReplayComparison;
91
+ }
92
+ export {};
93
+ //# sourceMappingURL=workflow-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-session.d.ts","sourceRoot":"","sources":["../src/workflow-session.ts"],"names":[],"mappings":"AAAA,8EAA8E;A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AY9D;IAED,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,wBAAwB,GAAG,IAAI,CAQ1E;IAED,sBAAsB,CACpB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,mBAAmB,EAC1B,YAAY,EAAE,MAAM,EACpB,mBAAmB,EAAE,MAAM,GAC1B,IAAI,CASN;IAED,oBAAoB,CAClB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,mBAAmB,EAC1B,YAAY,EAAE,MAAM,EACpB,mBAAmB,EAAE,MAAM,GAC1B,IAAI,CAYN;IAED,eAAe,IAAI,IAAI,CA4CtB;IAED,MAAM,IAAI,IAAI,CAIb;IAED,oBAAoB,CAClB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,6BAA6B,GACvC,+BAA+B,CAQjC;CA0CF","sourcesContent":["/** Identity-only state tracking for deterministic workflow context cycles. */\n\nimport { CigarError } from \"./errors.js\";\n\nexport const MAX_WORKFLOW_DELTA_CHAIN_LENGTH = 8;\nexport const MAX_WORKFLOW_REPLAY_CYCLES = 64;\n\nexport const WORKFLOW_CONTEXT_PHASES = [\n \"new\", \"plan_created\", \"target_bundle_loaded\", \"delta_compiled\", \"bundle_ready\", \"materialized\",\n \"model_invocation_pending\", \"model_result_recorded\", \"effect_prepared\", \"observation_recorded\",\n \"effect_authorization_revalidated\", \"effect_authorized\", \"effect_revalidated\", \"effect_dispatching\",\n \"effect_ambiguous\", \"effect_settled\", \"checkpointed\", \"finished\", \"replay_verified\", \"quarantined\",\n] as const;\nexport type WorkflowContextPhase = typeof WORKFLOW_CONTEXT_PHASES[number];\n\nexport const WORKFLOW_RESUME_ACTIONS = [\n \"create_context_plan\", \"compile_context_bundle\", \"compile_context_delta\", \"apply_context_delta\",\n \"materialize_context_bundle\", \"begin_model_invocation\", \"resume_model_invocation\",\n \"prepare_effect_or_ingest_observation\", \"ingest_observation\", \"authorize_effect_or_checkpoint\",\n \"revalidate_context_bundle\", \"dispatch_effect\", \"observe_effect\", \"reconcile_effect\", \"checkpoint\",\n \"materialize_or_finish\", \"replay\", \"complete\",\n] as const;\nexport type WorkflowResumeAction = typeof WORKFLOW_RESUME_ACTIONS[number];\n\nexport const WORKFLOW_SESSION_ERROR_CODES = [\n \"invalid_transition\", \"invalid_event\", \"identity_mismatch\", \"invalidated\", \"limit_exceeded\",\n] as const;\nexport type WorkflowSessionErrorCode = typeof WORKFLOW_SESSION_ERROR_CODES[number];\n\nexport const WORKFLOW_SESSION_EVENT_NAMES = [\n \"plan_created\", \"bundle_compiled\", \"delta_compiled\", \"delta_applied\", \"materialized\",\n \"model_invocation_started\", \"model_result_recorded\", \"effect_prepared\", \"observation_recorded\",\n \"effect_authorized\", \"effect_revalidated\", \"effect_dispatched\", \"effect_observed\", \"cycle_checkpointed\",\n \"finished\", \"replay_verified\", \"context_quarantined\",\n] as const;\n\nexport const WORKFLOW_QUARANTINE_REASONS = [\"cancelled\", \"revoked\", \"invalidated\"] as const;\nexport type WorkflowQuarantineReason = typeof WORKFLOW_QUARANTINE_REASONS[number];\n\nconst ACTION_OPERATIONS = {\n create_context_plan: \"createContextPlan\",\n compile_context_bundle: \"compileContextBundle\",\n compile_context_delta: \"compileContextDelta\",\n apply_context_delta: null,\n materialize_context_bundle: \"materializeContextBundle\",\n begin_model_invocation: null,\n resume_model_invocation: null,\n prepare_effect_or_ingest_observation: null,\n ingest_observation: \"ingestCatalog\",\n authorize_effect_or_checkpoint: \"authorizeEffect\",\n revalidate_context_bundle: \"revalidateContextBundle\",\n dispatch_effect: \"dispatchEffect\",\n observe_effect: \"getEffectStatus\",\n reconcile_effect: \"reconcileEffect\",\n checkpoint: null,\n materialize_or_finish: null,\n replay: \"createReplay\",\n complete: null,\n} as const satisfies Readonly<Record<WorkflowResumeAction, string | null>>;\n\nexport function workflowOperationId(action: WorkflowResumeAction): string | null {\n return ACTION_OPERATIONS[action];\n}\n\nexport class WorkflowSessionError extends CigarError {\n readonly code: WorkflowSessionErrorCode;\n\n constructor(code: WorkflowSessionErrorCode) {\n super(`workflow context transition failed: ${code}`);\n this.code = code;\n }\n}\n\ntype ContextIdentity = Readonly<{ planId: string; bundleId: string; contractDigest: string }>;\ntype DeltaIdentity = Readonly<{ baseBundleId: string; targetBundleId: string; deltaDigest: string }>;\nexport type WorkflowEffectState =\n | \"prepared\" | \"authorized\" | \"dispatching\" | \"unknown\" | \"authorized_for_retry\"\n | \"succeeded\" | \"failed\" | \"manual_resolution\" | \"rejected\" | \"expired\" | \"cancelled\"\n | \"compensated\" | \"compensation_failed\";\ntype EffectIdentity = Readonly<{\n effectId: string;\n intentDigest: string;\n effectVersion: bigint;\n state: WorkflowEffectState;\n attemptCount: number;\n reconciliationCount: number;\n}>;\n\nexport type WorkflowReplayDiffStatus = \"equal\" | \"different\";\nexport type WorkflowDeltaReplayIdentity = Readonly<{\n baseBundleId: string;\n targetBundleId: string;\n deltaDigest: string;\n}>;\nexport type WorkflowEffectReplayIdentity = Readonly<EffectIdentity>;\nexport type WorkflowContextCycleIdentity = Readonly<{\n planId: string;\n bundleId: string;\n contractDigest: string;\n selectedDelta?: WorkflowDeltaReplayIdentity;\n materializedBundleId: string;\n tokenizerFingerprint: string;\n materializerFingerprint: string;\n physicalInputTokens: number;\n invocationId: string;\n requestDigest: string;\n idempotencyKeyDigest: string;\n modelResultDigest: string;\n effect?: WorkflowEffectReplayIdentity;\n outcomeDigest: string;\n outcomeRevision: bigint;\n}>;\nexport type WorkflowContextReplayIdentity = Readonly<{\n cycles: readonly WorkflowContextCycleIdentity[];\n}>;\nexport type WorkflowContextReplayComparison = Readonly<{\n bundleDeltaSelection: WorkflowReplayDiffStatus;\n materialization: WorkflowReplayDiffStatus;\n modelResultIdentity: WorkflowReplayDiffStatus;\n toolEffectDecisions: WorkflowReplayDiffStatus;\n outcome: WorkflowReplayDiffStatus;\n exactMatch: boolean;\n}>;\n\ntype MaterializationIdentity = Readonly<{\n bundleId: string;\n tokenizerFingerprint: string;\n materializerFingerprint: string;\n physicalInputTokens: number;\n}>;\ntype InvocationIdentity = Readonly<{\n invocationId: string;\n requestDigest: string;\n idempotencyKeyDigest: string;\n}>;\n\nconst DIGEST = /^1220[0-9a-f]{64}$/;\nconst UUID_V7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\nconst TERMINAL_EFFECT_STATES: ReadonlySet<WorkflowEffectState> = new Set([\n \"succeeded\", \"failed\", \"manual_resolution\", \"rejected\", \"expired\", \"cancelled\", \"compensated\",\n \"compensation_failed\",\n]);\n\n/** Mutable, content-safe helper for one context lifecycle. Successful boundaries advance it atomically. */\nexport class WorkflowContextSession {\n #phase: WorkflowContextPhase = \"new\";\n #completedTurns = 0;\n #deltaChainLength = 0;\n #activeContext: ContextIdentity | undefined;\n #pendingContext: ContextIdentity | undefined;\n #pendingDelta: DeltaIdentity | undefined;\n #selectedDelta: DeltaIdentity | undefined;\n #materialization: MaterializationIdentity | undefined;\n #invocation: InvocationIdentity | undefined;\n #modelResultDigest: string | undefined;\n #observationDigest: string | undefined;\n #observationRevision: bigint | undefined;\n #effect: EffectIdentity | undefined;\n #completedCycles: WorkflowContextCycleIdentity[] = [];\n #replayVerified = false;\n #quarantineReason: WorkflowQuarantineReason | undefined;\n\n get phase(): WorkflowContextPhase { return this.#phase; }\n get completedTurns(): number { return this.#completedTurns; }\n get deltaChainLength(): number { return this.#deltaChainLength; }\n get activeBundleId(): string | undefined { return this.#activeContext?.bundleId; }\n\n replayIdentity(): WorkflowContextReplayIdentity {\n this.#requirePhase(\"finished\", \"replay_verified\");\n if (this.#completedCycles.length === 0) fail(\"invalid_transition\");\n return cloneReplayIdentity({ cycles: this.#completedCycles });\n }\n\n compareReplay(candidate: WorkflowContextReplayIdentity): WorkflowContextReplayComparison {\n const baseline = this.replayIdentity();\n validateReplayIdentity(candidate);\n return compareWorkflowReplay(baseline, candidate);\n }\n\n get resumeAction(): WorkflowResumeAction {\n switch (this.#phase) {\n case \"new\": case \"observation_recorded\": return \"create_context_plan\";\n case \"plan_created\": return \"compile_context_bundle\";\n case \"target_bundle_loaded\": return \"compile_context_delta\";\n case \"delta_compiled\": return \"apply_context_delta\";\n case \"bundle_ready\":\n if (this.#modelResultDigest === undefined) return \"materialize_context_bundle\";\n return this.#effect === undefined ? \"checkpoint\" : \"revalidate_context_bundle\";\n case \"materialized\": return \"begin_model_invocation\";\n case \"model_invocation_pending\": return \"resume_model_invocation\";\n case \"model_result_recorded\": return \"prepare_effect_or_ingest_observation\";\n case \"effect_prepared\": return \"ingest_observation\";\n case \"effect_authorization_revalidated\": return \"authorize_effect_or_checkpoint\";\n case \"effect_authorized\": return \"revalidate_context_bundle\";\n case \"effect_revalidated\": return \"dispatch_effect\";\n case \"effect_dispatching\": return \"observe_effect\";\n case \"effect_ambiguous\": return \"reconcile_effect\";\n case \"effect_settled\": return \"checkpoint\";\n case \"checkpointed\": return \"materialize_or_finish\";\n case \"finished\": return \"replay\";\n case \"replay_verified\": case \"quarantined\": return \"complete\";\n }\n }\n\n toString(): string {\n return `WorkflowContextSession(phase=${this.#phase}, completedTurns=${this.#completedTurns}, `\n + `deltaChainLength=${this.#deltaChainLength}, hasActiveContext=${this.#activeContext !== undefined}, `\n + `hasPendingContext=${this.#pendingContext !== undefined}, hasPendingDelta=${this.#pendingDelta !== undefined}, `\n + `hasSelectedDelta=${this.#selectedDelta !== undefined}, hasInvocation=${this.#invocation !== undefined}, `\n + `hasProviderIdempotencyKey=${this.#invocation !== undefined}, `\n + `hasModelResult=${this.#modelResultDigest !== undefined}, `\n + `hasObservation=${this.#observationDigest !== undefined}, effectState=${this.#effect?.state ?? \"none\"}, `\n + `completedCycleCount=${this.#completedCycles.length}, `\n + `quarantineReason=${this.#quarantineReason ?? \"none\"})`;\n }\n\n recordPlanCreated(planId: string, bundleId: string, contractDigest: string): void {\n this.#requirePhase(\"new\", \"observation_recorded\");\n record(planId); digest(bundleId); digest(contractDigest);\n this.#pendingContext = { planId, bundleId, contractDigest };\n this.#pendingDelta = undefined;\n this.#phase = \"plan_created\";\n }\n\n recordBundleCompiled(bundleId: string, contractDigest: string): void {\n this.#requirePhase(\"plan_created\");\n digest(bundleId); digest(contractDigest);\n const pending = this.#pendingContext;\n if (pending === undefined) fail(\"invalid_transition\");\n if (pending.bundleId !== bundleId || pending.contractDigest !== contractDigest) fail(\"identity_mismatch\");\n if (this.#activeContext === undefined || this.#activeContext.bundleId === bundleId) {\n this.#activeContext = pending;\n this.#pendingContext = undefined;\n this.#selectedDelta = undefined;\n if (this.#deltaChainLength >= MAX_WORKFLOW_DELTA_CHAIN_LENGTH) this.#deltaChainLength = 0;\n this.#phase = \"bundle_ready\";\n } else if (this.#deltaChainLength >= MAX_WORKFLOW_DELTA_CHAIN_LENGTH) {\n this.#activeContext = pending;\n this.#pendingContext = undefined;\n this.#selectedDelta = undefined;\n this.#deltaChainLength = 0;\n this.#phase = \"bundle_ready\";\n } else {\n this.#phase = \"target_bundle_loaded\";\n }\n }\n\n recordDeltaCompiled(baseBundleId: string, targetBundleId: string, deltaDigest: string): void {\n this.#requirePhase(\"target_bundle_loaded\");\n if (this.#deltaChainLength >= MAX_WORKFLOW_DELTA_CHAIN_LENGTH) fail(\"limit_exceeded\");\n digest(baseBundleId); digest(targetBundleId); digest(deltaDigest);\n if (this.#activeContext === undefined || this.#pendingContext === undefined) fail(\"invalid_transition\");\n if (this.#activeContext.bundleId !== baseBundleId || this.#pendingContext.bundleId !== targetBundleId) {\n fail(\"identity_mismatch\");\n }\n this.#pendingDelta = { baseBundleId, targetBundleId, deltaDigest };\n this.#phase = \"delta_compiled\";\n }\n\n recordDeltaApplied(baseBundleId: string, targetBundleId: string, deltaDigest: string): void {\n this.#requirePhase(\"delta_compiled\");\n digest(baseBundleId); digest(targetBundleId); digest(deltaDigest);\n const pending = this.#pendingDelta;\n if (pending === undefined) fail(\"invalid_transition\");\n if (pending.baseBundleId !== baseBundleId || pending.targetBundleId !== targetBundleId\n || pending.deltaDigest !== deltaDigest) fail(\"identity_mismatch\");\n if (this.#deltaChainLength >= MAX_WORKFLOW_DELTA_CHAIN_LENGTH) fail(\"limit_exceeded\");\n this.#deltaChainLength += 1;\n this.#selectedDelta = pending;\n this.#activeContext = this.#pendingContext;\n this.#pendingContext = undefined;\n this.#pendingDelta = undefined;\n this.#phase = \"bundle_ready\";\n }\n\n recordMaterialized(\n bundleId: string,\n tokenizerFingerprint: string,\n materializerFingerprint: string,\n physicalInputTokens: number,\n ): void {\n this.#requirePhase(\"bundle_ready\", \"checkpointed\");\n digest(bundleId); digest(tokenizerFingerprint); digest(materializerFingerprint);\n if (this.#modelResultDigest !== undefined || !positiveInteger(physicalInputTokens, 0xffff_ffff)) {\n fail(\"invalid_event\");\n }\n if (this.activeBundleId !== bundleId) fail(\"identity_mismatch\");\n this.#materialization = {\n bundleId, tokenizerFingerprint, materializerFingerprint, physicalInputTokens,\n };\n this.#phase = \"materialized\";\n }\n\n beginModelInvocation(invocationId: string, requestDigest: string, idempotencyKeyDigest: string): void {\n this.#requirePhase(\"materialized\");\n record(invocationId); digest(requestDigest); digest(idempotencyKeyDigest);\n this.#invocation = { invocationId, requestDigest, idempotencyKeyDigest };\n this.#phase = \"model_invocation_pending\";\n }\n\n recordModelResult(invocationId: string, resultDigest: string): void {\n this.#requirePhase(\"model_invocation_pending\");\n record(invocationId); digest(resultDigest);\n if (this.#invocation?.invocationId !== invocationId) fail(\"identity_mismatch\");\n this.#modelResultDigest = resultDigest;\n this.#phase = \"model_result_recorded\";\n }\n\n recordEffectPrepared(\n effectId: string,\n intentDigest: string,\n effectVersion: bigint,\n state: WorkflowEffectState = \"prepared\",\n attemptCount = 0,\n reconciliationCount = 0,\n ): void {\n this.#requirePhase(\"model_result_recorded\");\n record(effectId); digest(intentDigest); positiveBigint(effectVersion);\n if (this.#effect !== undefined || state !== \"prepared\" || !count(attemptCount)\n || !count(reconciliationCount) || attemptCount !== 0 || reconciliationCount !== 0) fail(\"invalid_event\");\n this.#effect = { effectId, intentDigest, effectVersion, state, attemptCount, reconciliationCount };\n this.#phase = \"effect_prepared\";\n }\n\n recordObservation(publicationDigest: string, revision: bigint): void {\n this.#requirePhase(\"model_result_recorded\", \"effect_prepared\");\n digest(publicationDigest); positiveBigint(revision);\n this.#observationDigest = publicationDigest;\n this.#observationRevision = revision;\n this.#phase = \"observation_recorded\";\n }\n\n recordEffectAuthorized(\n effectId: string,\n intentDigest: string,\n effectVersion: bigint,\n state: WorkflowEffectState = \"authorized\",\n attemptCount = 0,\n reconciliationCount = 0,\n ): void {\n this.#requirePhase(\"effect_authorization_revalidated\");\n if (this.#modelResultDigest === undefined || state !== \"authorized\") fail(\"invalid_event\");\n if (this.#effect === undefined || attemptCount !== this.#effect.attemptCount\n || reconciliationCount !== this.#effect.reconciliationCount) fail(\"invalid_event\");\n this.#updateEffect(effectId, intentDigest, effectVersion, state, attemptCount, reconciliationCount, true);\n this.#phase = \"effect_authorized\";\n }\n\n recordEffectRevalidated(bundleId: string, valid: boolean): void {\n const beforeAuthorization = this.#phase === \"bundle_ready\"\n && this.#modelResultDigest !== undefined && this.#effect?.state === \"prepared\";\n if (!beforeAuthorization && this.#phase !== \"effect_authorized\") fail(\"invalid_transition\");\n digest(bundleId);\n if (typeof valid !== \"boolean\") fail(\"invalid_event\");\n if (this.activeBundleId !== bundleId) fail(\"identity_mismatch\");\n if (!valid) {\n this.#enterQuarantine(\"invalidated\");\n } else {\n this.#phase = beforeAuthorization ? \"effect_authorization_revalidated\" : \"effect_revalidated\";\n }\n }\n\n quarantineContext(bundleId: string, reason: WorkflowQuarantineReason): void {\n digest(bundleId);\n if (!(WORKFLOW_QUARANTINE_REASONS as readonly string[]).includes(reason)) fail(\"invalid_event\");\n if ([\"new\", \"finished\", \"replay_verified\", \"quarantined\"].includes(this.#phase)) {\n fail(\"invalid_transition\");\n }\n if (this.activeBundleId !== bundleId) fail(\"identity_mismatch\");\n this.#enterQuarantine(reason);\n }\n\n recordEffectDispatched(\n effectId: string,\n intentDigest: string,\n effectVersion: bigint,\n state: WorkflowEffectState,\n attemptCount: number,\n reconciliationCount: number,\n ): void {\n this.#requirePhase(\"effect_revalidated\");\n if (state !== \"dispatching\" && state !== \"unknown\" && !TERMINAL_EFFECT_STATES.has(state)) {\n fail(\"invalid_event\");\n }\n if (this.#effect === undefined || attemptCount !== this.#effect.attemptCount + 1\n || reconciliationCount !== this.#effect.reconciliationCount) fail(\"invalid_event\");\n this.#updateEffect(effectId, intentDigest, effectVersion, state, attemptCount, reconciliationCount, true);\n this.#phase = effectPhase(state);\n }\n\n recordEffectObserved(\n effectId: string,\n intentDigest: string,\n effectVersion: bigint,\n state: WorkflowEffectState,\n attemptCount: number,\n reconciliationCount: number,\n ): void {\n const allowed = this.#phase === \"effect_dispatching\"\n ? state === \"dispatching\" || state === \"unknown\" || TERMINAL_EFFECT_STATES.has(state)\n : this.#phase === \"effect_ambiguous\"\n && (state === \"unknown\" || state === \"authorized_for_retry\" || TERMINAL_EFFECT_STATES.has(state));\n if (!allowed) fail(\"invalid_transition\");\n if (this.#effect === undefined || attemptCount < this.#effect.attemptCount\n || reconciliationCount < this.#effect.reconciliationCount\n || state === \"authorized_for_retry\" && (attemptCount !== this.#effect.attemptCount\n || reconciliationCount <= this.#effect.reconciliationCount)) fail(\"invalid_event\");\n this.#updateEffect(effectId, intentDigest, effectVersion, state, attemptCount, reconciliationCount, false);\n this.#phase = effectPhase(state);\n }\n\n checkpointCycle(): void {\n const effectComplete = this.#effect === undefined\n ? this.#phase === \"bundle_ready\"\n : this.#phase === \"effect_settled\" && TERMINAL_EFFECT_STATES.has(this.#effect.state);\n if (!effectComplete || this.#modelResultDigest === undefined || this.#observationDigest === undefined) {\n fail(\"invalid_transition\");\n }\n if (this.#completedCycles.length >= MAX_WORKFLOW_REPLAY_CYCLES || this.#completedTurns >= 0xffff_ffff) {\n fail(\"limit_exceeded\");\n }\n const selected = this.#activeContext;\n const materialization = this.#materialization;\n const invocation = this.#invocation;\n const outcomeRevision = this.#observationRevision;\n if (selected === undefined || materialization === undefined || invocation === undefined\n || outcomeRevision === undefined) fail(\"invalid_transition\");\n this.#completedCycles.push({\n planId: selected.planId,\n bundleId: selected.bundleId,\n contractDigest: selected.contractDigest,\n ...(this.#selectedDelta === undefined ? {} : { selectedDelta: { ...this.#selectedDelta } }),\n materializedBundleId: materialization.bundleId,\n tokenizerFingerprint: materialization.tokenizerFingerprint,\n materializerFingerprint: materialization.materializerFingerprint,\n physicalInputTokens: materialization.physicalInputTokens,\n invocationId: invocation.invocationId,\n requestDigest: invocation.requestDigest,\n idempotencyKeyDigest: invocation.idempotencyKeyDigest,\n modelResultDigest: this.#modelResultDigest,\n ...(this.#effect === undefined ? {} : { effect: { ...this.#effect } }),\n outcomeDigest: this.#observationDigest,\n outcomeRevision,\n });\n this.#completedTurns += 1;\n this.#pendingContext = undefined;\n this.#pendingDelta = undefined;\n this.#selectedDelta = undefined;\n this.#materialization = undefined;\n this.#invocation = undefined;\n this.#modelResultDigest = undefined;\n this.#observationDigest = undefined;\n this.#observationRevision = undefined;\n this.#effect = undefined;\n this.#phase = \"checkpointed\";\n }\n\n finish(): void {\n this.#requirePhase(\"checkpointed\");\n if (this.#completedTurns === 0) fail(\"invalid_transition\");\n this.#phase = \"finished\";\n }\n\n recordReplayVerified(\n decisionId: string,\n executionId: string,\n candidate: WorkflowContextReplayIdentity,\n ): WorkflowContextReplayComparison {\n this.#requirePhase(\"finished\");\n digest(decisionId); record(executionId);\n const comparison = this.compareReplay(candidate);\n if (!comparison.exactMatch) fail(\"identity_mismatch\");\n this.#replayVerified = true;\n this.#phase = \"replay_verified\";\n return comparison;\n }\n\n #requirePhase(...allowed: readonly WorkflowContextPhase[]): void {\n if (!allowed.includes(this.#phase)) fail(\"invalid_transition\");\n }\n\n #updateEffect(\n effectId: string,\n intentDigest: string,\n effectVersion: bigint,\n state: WorkflowEffectState,\n attemptCount: number,\n reconciliationCount: number,\n requireNewVersion: boolean,\n ): void {\n record(effectId); digest(intentDigest); positiveBigint(effectVersion);\n if (!count(attemptCount) || !count(reconciliationCount)\n || !effectCountsValid(state, attemptCount, reconciliationCount)) fail(\"invalid_event\");\n const current = this.#effect;\n if (current === undefined) fail(\"invalid_transition\");\n const versionValid = effectVersion > current.effectVersion\n || (!requireNewVersion && effectVersion === current.effectVersion && state === current.state);\n if (effectId !== current.effectId || intentDigest !== current.intentDigest || !versionValid) {\n fail(\"identity_mismatch\");\n }\n this.#effect = { effectId, intentDigest, effectVersion, state, attemptCount, reconciliationCount };\n }\n\n #enterQuarantine(reason: WorkflowQuarantineReason): void {\n this.#pendingContext = undefined;\n this.#pendingDelta = undefined;\n this.#selectedDelta = undefined;\n this.#materialization = undefined;\n this.#invocation = undefined;\n this.#modelResultDigest = undefined;\n this.#observationDigest = undefined;\n this.#observationRevision = undefined;\n this.#effect = undefined;\n this.#replayVerified = false;\n this.#quarantineReason = reason;\n this.#phase = \"quarantined\";\n }\n}\n\nfunction cloneReplayIdentity(identity: WorkflowContextReplayIdentity): WorkflowContextReplayIdentity {\n return {\n cycles: identity.cycles.map((cycle) => ({\n ...cycle,\n ...(cycle.selectedDelta === undefined ? {} : { selectedDelta: { ...cycle.selectedDelta } }),\n ...(cycle.effect === undefined ? {} : { effect: { ...cycle.effect } }),\n })),\n };\n}\n\nfunction validateReplayIdentity(identity: WorkflowContextReplayIdentity): void {\n if (typeof identity !== \"object\" || identity === null || !Array.isArray(identity.cycles)\n || identity.cycles.length === 0 || identity.cycles.length > MAX_WORKFLOW_REPLAY_CYCLES) {\n fail(\"invalid_event\");\n }\n for (const cycle of identity.cycles) {\n record(cycle.planId); digest(cycle.bundleId); digest(cycle.contractDigest);\n digest(cycle.materializedBundleId); digest(cycle.tokenizerFingerprint);\n digest(cycle.materializerFingerprint); record(cycle.invocationId); digest(cycle.requestDigest);\n digest(cycle.idempotencyKeyDigest); digest(cycle.modelResultDigest); digest(cycle.outcomeDigest);\n if (!positiveInteger(cycle.physicalInputTokens, 0xffff_ffff)) fail(\"invalid_event\");\n positiveBigint(cycle.outcomeRevision);\n if (cycle.selectedDelta !== undefined) {\n digest(cycle.selectedDelta.baseBundleId); digest(cycle.selectedDelta.targetBundleId);\n digest(cycle.selectedDelta.deltaDigest);\n if (cycle.selectedDelta.targetBundleId !== cycle.bundleId\n || cycle.selectedDelta.baseBundleId !== cycle.materializedBundleId\n || cycle.selectedDelta.baseBundleId === cycle.selectedDelta.targetBundleId) {\n fail(\"identity_mismatch\");\n }\n }\n if (cycle.effect !== undefined) {\n record(cycle.effect.effectId); digest(cycle.effect.intentDigest);\n positiveBigint(cycle.effect.effectVersion);\n if (!TERMINAL_EFFECT_STATES.has(cycle.effect.state) || !count(cycle.effect.attemptCount)\n || !count(cycle.effect.reconciliationCount)\n || !effectCountsValid(\n cycle.effect.state, cycle.effect.attemptCount, cycle.effect.reconciliationCount,\n )) fail(\"invalid_event\");\n }\n }\n}\n\nfunction compareWorkflowReplay(\n baseline: WorkflowContextReplayIdentity,\n candidate: WorkflowContextReplayIdentity,\n): WorkflowContextReplayComparison {\n const sameLength = baseline.cycles.length === candidate.cycles.length;\n const pairs = baseline.cycles.map((cycle, index) => [cycle, candidate.cycles[index]!] as const);\n const bundleDeltaSelection = comparisonStatus(sameLength && pairs.every(([left, right]) =>\n left.planId === right.planId && left.bundleId === right.bundleId\n && left.contractDigest === right.contractDigest && equalDelta(left.selectedDelta, right.selectedDelta)));\n const materialization = comparisonStatus(sameLength && pairs.every(([left, right]) =>\n left.materializedBundleId === right.materializedBundleId\n && left.tokenizerFingerprint === right.tokenizerFingerprint\n && left.materializerFingerprint === right.materializerFingerprint\n && left.physicalInputTokens === right.physicalInputTokens));\n const modelResultIdentity = comparisonStatus(sameLength && pairs.every(([left, right]) =>\n left.invocationId === right.invocationId && left.requestDigest === right.requestDigest\n && left.idempotencyKeyDigest === right.idempotencyKeyDigest\n && left.modelResultDigest === right.modelResultDigest));\n const toolEffectDecisions = comparisonStatus(sameLength && pairs.every(([left, right]) =>\n equalEffect(left.effect, right.effect)));\n const outcome = comparisonStatus(sameLength && pairs.every(([left, right]) =>\n left.outcomeDigest === right.outcomeDigest && left.outcomeRevision === right.outcomeRevision));\n return {\n bundleDeltaSelection,\n materialization,\n modelResultIdentity,\n toolEffectDecisions,\n outcome,\n exactMatch: [bundleDeltaSelection, materialization, modelResultIdentity, toolEffectDecisions, outcome]\n .every((status) => status === \"equal\"),\n };\n}\n\nfunction comparisonStatus(equal: boolean): WorkflowReplayDiffStatus {\n return equal ? \"equal\" : \"different\";\n}\n\nfunction equalDelta(\n left: WorkflowDeltaReplayIdentity | undefined,\n right: WorkflowDeltaReplayIdentity | undefined,\n): boolean {\n return left === undefined || right === undefined\n ? left === right\n : left.baseBundleId === right.baseBundleId && left.targetBundleId === right.targetBundleId\n && left.deltaDigest === right.deltaDigest;\n}\n\nfunction equalEffect(\n left: WorkflowEffectReplayIdentity | undefined,\n right: WorkflowEffectReplayIdentity | undefined,\n): boolean {\n return left === undefined || right === undefined\n ? left === right\n : left.effectId === right.effectId && left.intentDigest === right.intentDigest\n && left.effectVersion === right.effectVersion && left.state === right.state\n && left.attemptCount === right.attemptCount && left.reconciliationCount === right.reconciliationCount;\n}\n\nfunction fail(code: WorkflowSessionErrorCode): never { throw new WorkflowSessionError(code); }\nfunction digest(value: string): void { if (!DIGEST.test(value)) fail(\"invalid_event\"); }\nfunction record(value: string): void { if (!UUID_V7.test(value)) fail(\"invalid_event\"); }\nfunction positiveBigint(value: bigint): void {\n if (typeof value !== \"bigint\" || value <= 0n || value > 0xffff_ffff_ffff_ffffn) fail(\"invalid_event\");\n}\nfunction positiveInteger(value: number, maximum: number): boolean {\n return Number.isSafeInteger(value) && value > 0 && value <= maximum;\n}\nfunction count(value: number): boolean { return Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff; }\nfunction effectCountsValid(state: WorkflowEffectState, attempts: number, reconciliations: number): boolean {\n if (reconciliations !== 0 && attempts === 0) return false;\n if ([\"prepared\", \"authorized\", \"rejected\"].includes(state)) {\n return attempts === 0 && reconciliations === 0;\n }\n if ([\n \"dispatching\", \"succeeded\", \"failed\", \"unknown\", \"compensated\", \"compensation_failed\",\n ].includes(state)) return attempts !== 0;\n if (state === \"authorized_for_retry\" || state === \"manual_resolution\") {\n return attempts !== 0 && reconciliations !== 0;\n }\n return state === \"expired\" || state === \"cancelled\";\n}\nfunction effectPhase(state: WorkflowEffectState): WorkflowContextPhase {\n if (state === \"dispatching\") return \"effect_dispatching\";\n if (state === \"unknown\") return \"effect_ambiguous\";\n if (state === \"authorized_for_retry\") return \"effect_authorized\";\n if (TERMINAL_EFFECT_STATES.has(state)) return \"effect_settled\";\n return fail(\"invalid_event\");\n}\n"]}