@redditech/agent-protocol 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/adl.d.ts +141 -0
  5. package/dist/adl.js +3601 -0
  6. package/dist/agent-stack-fixtures.d.ts +743 -0
  7. package/dist/agent-stack-fixtures.js +1554 -0
  8. package/dist/ai-catalog.d.ts +128 -0
  9. package/dist/ai-catalog.js +373 -0
  10. package/dist/attestation-reputation.d.ts +102 -0
  11. package/dist/attestation-reputation.js +279 -0
  12. package/dist/audd-rail-config.d.ts +102 -0
  13. package/dist/audd-rail-config.js +294 -0
  14. package/dist/browser-wallet-approval.d.ts +293 -0
  15. package/dist/browser-wallet-approval.js +1201 -0
  16. package/dist/discovery-source.d.ts +115 -0
  17. package/dist/discovery-source.js +251 -0
  18. package/dist/evidence-archive.d.ts +73 -0
  19. package/dist/evidence-archive.js +238 -0
  20. package/dist/index.d.ts +23 -0
  21. package/dist/index.js +23 -0
  22. package/dist/mpp-tempo-receipt-shapes.d.ts +201 -0
  23. package/dist/mpp-tempo-receipt-shapes.js +330 -0
  24. package/dist/okf-adapter.d.ts +229 -0
  25. package/dist/okf-adapter.js +556 -0
  26. package/dist/okf-conformance.d.ts +208 -0
  27. package/dist/okf-conformance.js +651 -0
  28. package/dist/okf-instruction-safety.d.ts +192 -0
  29. package/dist/okf-instruction-safety.js +509 -0
  30. package/dist/onboarding-analyser-handoff.d.ts +391 -0
  31. package/dist/onboarding-analyser-handoff.js +959 -0
  32. package/dist/onboarding-state-machine.d.ts +228 -0
  33. package/dist/onboarding-state-machine.js +432 -0
  34. package/dist/payment-records.d.ts +181 -0
  35. package/dist/payment-records.js +599 -0
  36. package/dist/policy.d.ts +33 -0
  37. package/dist/policy.js +45 -0
  38. package/dist/provider-trust.d.ts +113 -0
  39. package/dist/provider-trust.js +346 -0
  40. package/dist/quasar-registry-compatibility.d.ts +113 -0
  41. package/dist/quasar-registry-compatibility.js +214 -0
  42. package/dist/ranking-explainability.d.ts +202 -0
  43. package/dist/ranking-explainability.js +302 -0
  44. package/dist/receipt-v2.d.ts +202 -0
  45. package/dist/receipt-v2.js +418 -0
  46. package/dist/repo-explorer-evidence-manifest.d.ts +387 -0
  47. package/dist/repo-explorer-evidence-manifest.js +1187 -0
  48. package/dist/source-diagnostics.d.ts +84 -0
  49. package/dist/source-diagnostics.js +193 -0
  50. package/dist/source-trust-conformance-matrix.d.ts +207 -0
  51. package/dist/source-trust-conformance-matrix.js +672 -0
  52. package/examples/ard-no-spend-ai-catalog.json +51 -0
  53. package/examples/ard-no-spend-demo.mjs +355 -0
  54. package/examples/interpretation-guide-scenarios.mjs +302 -0
  55. package/package.json +144 -4
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Onboarding assistant state-machine read model (#510).
3
+ *
4
+ * Defines the backend/read-model state machine for AI onboarding assistant
5
+ * drafts. It projects analyser outputs (#509 handoff contracts) and operator
6
+ * decisions into a local, append-only audit history without UI, publication
7
+ * side effects, or live execution.
8
+ *
9
+ * Twelve states are supported:
10
+ *
11
+ * draft -> probe_failed / needs_provider_input / payment_setup_required
12
+ * -> dry_run_required -> risk_review_required
13
+ * -> pending_operator_approval -> approved_unpublished
14
+ * -> published_candidate (INTERNAL candidate only)
15
+ * plus changes_requested, rejected (terminal), and suspended.
16
+ *
17
+ * This module is PURE and offline-only. It performs no network fetch, hosted
18
+ * registry write, public catalog write, trust or reputation mutation, payment
19
+ * activation, endpoint invocation, wallet/RPC call, secret read, or command
20
+ * execution. Every transition is a local/read-model event: it only re-shapes
21
+ * an in-memory read model the caller already holds. Timestamps are
22
+ * caller-supplied so replays are deterministic.
23
+ *
24
+ * `published_candidate` is an internal candidate state only. Reaching it never
25
+ * writes hosted registry output, public catalog output, trust/reputation
26
+ * mutations, or payment activation; those remain gated behind #395 publication
27
+ * surfaces outside this module.
28
+ */
29
+ export declare const ONBOARDING_STATE_MACHINE_SCHEMA_VERSION: "reddi.onboarding-state-machine.v1";
30
+ export declare const ONBOARDING_STATE_TRANSITION_EVENT_SCHEMA_VERSION: "reddi.onboarding-state-transition-event.v1";
31
+ export declare const ONBOARDING_ASSISTANT_READ_MODEL_SCHEMA_VERSION: "reddi.onboarding-assistant-read-model.v1";
32
+ /** Issue anchors so downstream implementations can trace contract ownership. */
33
+ export declare const ONBOARDING_STATE_MACHINE_ISSUE: 510;
34
+ export declare const ONBOARDING_STATE_MACHINE_RELATED_ISSUES: Readonly<{
35
+ readonly onboardingAssistantEpic: 370;
36
+ readonly guidedWorkflowFeature: 374;
37
+ readonly discoverabilityPackageFeature: 376;
38
+ readonly publicationGateFeature: 395;
39
+ readonly analyserHandoffContracts: 509;
40
+ }>;
41
+ /**
42
+ * Hard no-live boundary. Every guardrail is `false` by construction and every
43
+ * read model carries this object so downstream consumers can assert the
44
+ * boundary instead of trusting prose.
45
+ */
46
+ export declare const ONBOARDING_STATE_MACHINE_GUARDRAILS: Readonly<{
47
+ readonly hostedRegistryWriteAllowed: false;
48
+ readonly publicCatalogWriteAllowed: false;
49
+ readonly trustMutationAllowed: false;
50
+ readonly reputationMutationAllowed: false;
51
+ readonly paymentActivationAllowed: false;
52
+ readonly endpointInvocationAllowed: false;
53
+ readonly walletOrRpcAllowed: false;
54
+ readonly networkFetchAllowed: false;
55
+ readonly hostedWriteAllowed: false;
56
+ readonly publicationAllowed: false;
57
+ readonly secretReadAllowed: false;
58
+ readonly liveExecutionAllowed: false;
59
+ }>;
60
+ export type OnboardingStateMachineGuardrails = typeof ONBOARDING_STATE_MACHINE_GUARDRAILS;
61
+ export type OnboardingAssistantState = 'draft' | 'probe_failed' | 'needs_provider_input' | 'payment_setup_required' | 'dry_run_required' | 'risk_review_required' | 'pending_operator_approval' | 'approved_unpublished' | 'changes_requested' | 'rejected' | 'suspended' | 'published_candidate';
62
+ export declare const ONBOARDING_ASSISTANT_STATES: readonly OnboardingAssistantState[];
63
+ /**
64
+ * Allowed transitions. Anything not listed here fails closed. `rejected` is
65
+ * terminal: a rejected draft can only be re-onboarded as a brand new draft
66
+ * with a fresh intake, never mutated back into the flow.
67
+ */
68
+ export declare const ONBOARDING_STATE_TRANSITION_GRAPH: Readonly<Record<OnboardingAssistantState, readonly OnboardingAssistantState[]>>;
69
+ export type OnboardingStateActorType = 'operator' | 'provider' | 'analyser' | 'system';
70
+ export declare const ONBOARDING_STATE_ACTOR_TYPES: readonly OnboardingStateActorType[];
71
+ /**
72
+ * Target states an operator must drive. Approval, rejection, change requests,
73
+ * suspension, reinstatement out of suspension, and internal candidate
74
+ * publication are review decisions — they are recorded as local/read-model
75
+ * events only and never invoke any external system.
76
+ */
77
+ export declare const ONBOARDING_OPERATOR_ONLY_TARGET_STATES: readonly OnboardingAssistantState[];
78
+ export type OnboardingBlockingGateKey = 'probe' | 'provider_input' | 'payment_setup' | 'dry_run' | 'risk_review' | 'operator_approval' | 'readiness';
79
+ export declare const ONBOARDING_BLOCKING_GATE_KEYS: readonly OnboardingBlockingGateKey[];
80
+ /**
81
+ * Gate reason codes. The first eight mirror the #509 fail-closed reasons so
82
+ * readiness lane output can be projected directly onto blocking gates; the
83
+ * rest are state-machine-native reasons.
84
+ */
85
+ export type OnboardingGateReasonCode = 'private_url_blocked' | 'credential_leakage_rejected' | 'command_execution_rejected' | 'paid_call_rejected' | 'wallet_rpc_rejected' | 'missing_payment_metadata' | 'missing_evidence' | 'untrusted_imported_content_rejected' | 'probe_failure_recorded' | 'provider_input_required' | 'dry_run_receipt_required' | 'risk_review_pending' | 'operator_approval_pending' | 'readiness_blocked';
86
+ export type OnboardingBlockingGate = {
87
+ gate: OnboardingBlockingGateKey;
88
+ reasonCodes: OnboardingGateReasonCode[];
89
+ note?: string;
90
+ };
91
+ /** Gate that must still be open when entering each gate-shaped state. */
92
+ export declare const ONBOARDING_STATE_REQUIRED_GATES: Readonly<Partial<Record<OnboardingAssistantState, OnboardingBlockingGateKey>>>;
93
+ /**
94
+ * Readiness summary carried on every transition. Mirrors the #509
95
+ * `OnboardingOverallReadiness` union; re-declared locally so this module stays
96
+ * import-free while remaining structurally compatible.
97
+ */
98
+ export type OnboardingStateReadinessSummary = 'blocked' | 'needs_operator_review' | 'publish_ready';
99
+ export type OnboardingStateTransitionErrorCode = 'malformed_transition_event' | 'malformed_read_model' | 'unknown_state' | 'invalid_transition' | 'terminal_state' | 'missing_audit_reason' | 'invalid_actor_type' | 'operator_action_required' | 'invalid_timestamp' | 'timestamp_regression' | 'missing_source_snapshot_ref' | 'missing_readiness_result_ref' | 'blocked_readiness' | 'missing_blocking_gate' | 'unresolved_blocking_gates' | 'publication_side_effect_rejected';
100
+ export type OnboardingStateTransitionError = {
101
+ code: OnboardingStateTransitionErrorCode;
102
+ path: string;
103
+ message: string;
104
+ };
105
+ /**
106
+ * A requested transition. Every transition carries the audit reason, actor
107
+ * type, caller-supplied timestamp, source snapshot reference, readiness result
108
+ * reference, and the blocking gates that remain open after the transition.
109
+ *
110
+ * `requestedSideEffects` exists only so imported/queued events that ask for a
111
+ * live side effect (hosted write, publication, payment activation, wallet/RPC,
112
+ * endpoint invocation, trust/reputation mutation, ...) can be rejected fail-
113
+ * closed. This module never executes any side effect.
114
+ */
115
+ export type OnboardingStateTransitionEvent = {
116
+ schemaVersion: typeof ONBOARDING_STATE_TRANSITION_EVENT_SCHEMA_VERSION;
117
+ eventId: string;
118
+ to: OnboardingAssistantState;
119
+ /** Human-auditable reason for the transition. Required, non-empty. */
120
+ reason: string;
121
+ actorType: OnboardingStateActorType;
122
+ /** Opaque local reference to the acting operator/provider/analyser. */
123
+ actorRef?: string;
124
+ /** RFC3339 UTC timestamp, caller-supplied for deterministic replay. */
125
+ occurredAt: string;
126
+ /** Reference to the static source snapshot backing this transition. */
127
+ sourceSnapshotRef: string;
128
+ /** Reference to the #509 readiness result backing this transition. */
129
+ readinessResultRef: string;
130
+ /** Overall readiness recorded on the referenced readiness result. */
131
+ readinessOverall: OnboardingStateReadinessSummary;
132
+ /** Gates still blocking after this transition. */
133
+ blockingGates: OnboardingBlockingGate[];
134
+ requestedSideEffects?: string[];
135
+ };
136
+ /** An applied transition as recorded in the read-model audit history. */
137
+ export type OnboardingStateTransitionRecord = {
138
+ sequence: number;
139
+ from: OnboardingAssistantState;
140
+ to: OnboardingAssistantState;
141
+ eventId: string;
142
+ reason: string;
143
+ actorType: OnboardingStateActorType;
144
+ actorRef?: string;
145
+ occurredAt: string;
146
+ sourceSnapshotRef: string;
147
+ readinessResultRef: string;
148
+ readinessOverall: OnboardingStateReadinessSummary;
149
+ blockingGates: OnboardingBlockingGate[];
150
+ /** Every recorded action is a local/read-model event only. */
151
+ scope: 'local_read_model_only';
152
+ };
153
+ export type OnboardingAssistantReadModel = {
154
+ schemaVersion: typeof ONBOARDING_ASSISTANT_READ_MODEL_SCHEMA_VERSION;
155
+ stateMachineVersion: typeof ONBOARDING_STATE_MACHINE_SCHEMA_VERSION;
156
+ draftId: string;
157
+ state: OnboardingAssistantState;
158
+ /** Timestamp of the event that produced the current state. */
159
+ stateSince: string;
160
+ sourceSnapshotRef: string;
161
+ readinessResultRef: string;
162
+ readinessOverall: OnboardingStateReadinessSummary;
163
+ blockingGates: OnboardingBlockingGate[];
164
+ history: OnboardingStateTransitionRecord[];
165
+ /**
166
+ * `published_candidate` (and every other state) stays internal: nothing in
167
+ * this read model is a hosted, public, trusted, or payable surface.
168
+ */
169
+ internalCandidateOnly: true;
170
+ /** Side-effect ledger. Every entry is hard-coded false by construction. */
171
+ publication: {
172
+ hostedRegistryWritePerformed: false;
173
+ publicCatalogWritePerformed: false;
174
+ trustMutationPerformed: false;
175
+ reputationMutationPerformed: false;
176
+ paymentActivationPerformed: false;
177
+ endpointInvocationPerformed: false;
178
+ walletOrRpcCallPerformed: false;
179
+ };
180
+ guardrails: OnboardingStateMachineGuardrails;
181
+ localReadModelOnly: true;
182
+ staticOnly: true;
183
+ };
184
+ export type OnboardingStateTransitionResult = {
185
+ ok: true;
186
+ readModel: OnboardingAssistantReadModel;
187
+ record: OnboardingStateTransitionRecord;
188
+ } | {
189
+ ok: false;
190
+ failClosed: true;
191
+ errors: OnboardingStateTransitionError[];
192
+ };
193
+ export type OnboardingReadModelInitResult = {
194
+ ok: true;
195
+ readModel: OnboardingAssistantReadModel;
196
+ } | {
197
+ ok: false;
198
+ failClosed: true;
199
+ errors: OnboardingStateTransitionError[];
200
+ };
201
+ export type OnboardingReadModelInit = {
202
+ draftId: string;
203
+ sourceSnapshotRef: string;
204
+ readinessResultRef: string;
205
+ readinessOverall: OnboardingStateReadinessSummary;
206
+ /** RFC3339 UTC timestamp, caller-supplied for deterministic replay. */
207
+ createdAt: string;
208
+ blockingGates?: OnboardingBlockingGate[];
209
+ };
210
+ /**
211
+ * Create a read model for a new onboarding draft. Drafts always start in
212
+ * `draft`; there is no way to construct a read model already approved or
213
+ * published.
214
+ */
215
+ export declare function createOnboardingAssistantReadModel(init: unknown): OnboardingReadModelInitResult;
216
+ /**
217
+ * Apply a transition event to a read model. Pure and deterministic: the input
218
+ * read model is never mutated; a new read model with the appended audit record
219
+ * is returned. Invalid transitions fail closed with structured reasons and no
220
+ * state change.
221
+ */
222
+ export declare function applyOnboardingStateTransition(readModel: OnboardingAssistantReadModel, event: unknown): OnboardingStateTransitionResult;
223
+ /**
224
+ * List the allowed target states from a given state. Useful for read-model
225
+ * consumers (UI lanes in #384/#385/#386) that need to render next actions
226
+ * without re-encoding the graph.
227
+ */
228
+ export declare function listOnboardingStateTransitions(from: OnboardingAssistantState): readonly OnboardingAssistantState[];
@@ -0,0 +1,432 @@
1
+ /**
2
+ * Onboarding assistant state-machine read model (#510).
3
+ *
4
+ * Defines the backend/read-model state machine for AI onboarding assistant
5
+ * drafts. It projects analyser outputs (#509 handoff contracts) and operator
6
+ * decisions into a local, append-only audit history without UI, publication
7
+ * side effects, or live execution.
8
+ *
9
+ * Twelve states are supported:
10
+ *
11
+ * draft -> probe_failed / needs_provider_input / payment_setup_required
12
+ * -> dry_run_required -> risk_review_required
13
+ * -> pending_operator_approval -> approved_unpublished
14
+ * -> published_candidate (INTERNAL candidate only)
15
+ * plus changes_requested, rejected (terminal), and suspended.
16
+ *
17
+ * This module is PURE and offline-only. It performs no network fetch, hosted
18
+ * registry write, public catalog write, trust or reputation mutation, payment
19
+ * activation, endpoint invocation, wallet/RPC call, secret read, or command
20
+ * execution. Every transition is a local/read-model event: it only re-shapes
21
+ * an in-memory read model the caller already holds. Timestamps are
22
+ * caller-supplied so replays are deterministic.
23
+ *
24
+ * `published_candidate` is an internal candidate state only. Reaching it never
25
+ * writes hosted registry output, public catalog output, trust/reputation
26
+ * mutations, or payment activation; those remain gated behind #395 publication
27
+ * surfaces outside this module.
28
+ */
29
+ export const ONBOARDING_STATE_MACHINE_SCHEMA_VERSION = 'reddi.onboarding-state-machine.v1';
30
+ export const ONBOARDING_STATE_TRANSITION_EVENT_SCHEMA_VERSION = 'reddi.onboarding-state-transition-event.v1';
31
+ export const ONBOARDING_ASSISTANT_READ_MODEL_SCHEMA_VERSION = 'reddi.onboarding-assistant-read-model.v1';
32
+ /** Issue anchors so downstream implementations can trace contract ownership. */
33
+ export const ONBOARDING_STATE_MACHINE_ISSUE = 510;
34
+ export const ONBOARDING_STATE_MACHINE_RELATED_ISSUES = Object.freeze({
35
+ onboardingAssistantEpic: 370,
36
+ guidedWorkflowFeature: 374,
37
+ discoverabilityPackageFeature: 376,
38
+ publicationGateFeature: 395,
39
+ analyserHandoffContracts: 509,
40
+ });
41
+ /**
42
+ * Hard no-live boundary. Every guardrail is `false` by construction and every
43
+ * read model carries this object so downstream consumers can assert the
44
+ * boundary instead of trusting prose.
45
+ */
46
+ export const ONBOARDING_STATE_MACHINE_GUARDRAILS = Object.freeze({
47
+ hostedRegistryWriteAllowed: false,
48
+ publicCatalogWriteAllowed: false,
49
+ trustMutationAllowed: false,
50
+ reputationMutationAllowed: false,
51
+ paymentActivationAllowed: false,
52
+ endpointInvocationAllowed: false,
53
+ walletOrRpcAllowed: false,
54
+ networkFetchAllowed: false,
55
+ hostedWriteAllowed: false,
56
+ publicationAllowed: false,
57
+ secretReadAllowed: false,
58
+ liveExecutionAllowed: false,
59
+ });
60
+ export const ONBOARDING_ASSISTANT_STATES = Object.freeze([
61
+ 'draft',
62
+ 'probe_failed',
63
+ 'needs_provider_input',
64
+ 'payment_setup_required',
65
+ 'dry_run_required',
66
+ 'risk_review_required',
67
+ 'pending_operator_approval',
68
+ 'approved_unpublished',
69
+ 'changes_requested',
70
+ 'rejected',
71
+ 'suspended',
72
+ 'published_candidate',
73
+ ]);
74
+ /**
75
+ * Allowed transitions. Anything not listed here fails closed. `rejected` is
76
+ * terminal: a rejected draft can only be re-onboarded as a brand new draft
77
+ * with a fresh intake, never mutated back into the flow.
78
+ */
79
+ export const ONBOARDING_STATE_TRANSITION_GRAPH = Object.freeze({
80
+ draft: [
81
+ 'probe_failed',
82
+ 'needs_provider_input',
83
+ 'payment_setup_required',
84
+ 'dry_run_required',
85
+ 'risk_review_required',
86
+ 'pending_operator_approval',
87
+ 'rejected',
88
+ 'suspended',
89
+ ],
90
+ probe_failed: ['draft', 'needs_provider_input', 'rejected', 'suspended'],
91
+ needs_provider_input: ['draft', 'payment_setup_required', 'rejected', 'suspended'],
92
+ payment_setup_required: ['draft', 'dry_run_required', 'rejected', 'suspended'],
93
+ dry_run_required: ['probe_failed', 'risk_review_required', 'pending_operator_approval', 'rejected', 'suspended'],
94
+ risk_review_required: ['pending_operator_approval', 'changes_requested', 'rejected', 'suspended'],
95
+ pending_operator_approval: ['approved_unpublished', 'changes_requested', 'rejected', 'suspended'],
96
+ approved_unpublished: ['published_candidate', 'changes_requested', 'suspended'],
97
+ changes_requested: ['draft', 'pending_operator_approval', 'rejected', 'suspended'],
98
+ rejected: [],
99
+ suspended: ['draft', 'rejected'],
100
+ published_candidate: ['changes_requested', 'suspended'],
101
+ });
102
+ export const ONBOARDING_STATE_ACTOR_TYPES = Object.freeze([
103
+ 'operator',
104
+ 'provider',
105
+ 'analyser',
106
+ 'system',
107
+ ]);
108
+ /**
109
+ * Target states an operator must drive. Approval, rejection, change requests,
110
+ * suspension, reinstatement out of suspension, and internal candidate
111
+ * publication are review decisions — they are recorded as local/read-model
112
+ * events only and never invoke any external system.
113
+ */
114
+ export const ONBOARDING_OPERATOR_ONLY_TARGET_STATES = Object.freeze([
115
+ 'approved_unpublished',
116
+ 'changes_requested',
117
+ 'rejected',
118
+ 'suspended',
119
+ 'published_candidate',
120
+ ]);
121
+ export const ONBOARDING_BLOCKING_GATE_KEYS = Object.freeze([
122
+ 'probe',
123
+ 'provider_input',
124
+ 'payment_setup',
125
+ 'dry_run',
126
+ 'risk_review',
127
+ 'operator_approval',
128
+ 'readiness',
129
+ ]);
130
+ const GATE_REASON_CODES = [
131
+ 'private_url_blocked',
132
+ 'credential_leakage_rejected',
133
+ 'command_execution_rejected',
134
+ 'paid_call_rejected',
135
+ 'wallet_rpc_rejected',
136
+ 'missing_payment_metadata',
137
+ 'missing_evidence',
138
+ 'untrusted_imported_content_rejected',
139
+ 'probe_failure_recorded',
140
+ 'provider_input_required',
141
+ 'dry_run_receipt_required',
142
+ 'risk_review_pending',
143
+ 'operator_approval_pending',
144
+ 'readiness_blocked',
145
+ ];
146
+ /** Gate that must still be open when entering each gate-shaped state. */
147
+ export const ONBOARDING_STATE_REQUIRED_GATES = Object.freeze({
148
+ probe_failed: 'probe',
149
+ needs_provider_input: 'provider_input',
150
+ payment_setup_required: 'payment_setup',
151
+ dry_run_required: 'dry_run',
152
+ risk_review_required: 'risk_review',
153
+ pending_operator_approval: 'operator_approval',
154
+ });
155
+ const READINESS_SUMMARIES = [
156
+ 'blocked',
157
+ 'needs_operator_review',
158
+ 'publish_ready',
159
+ ];
160
+ // ---------------------------------------------------------------------------
161
+ // Validation internals
162
+ // ---------------------------------------------------------------------------
163
+ const RFC3339_UTC_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;
164
+ function transitionError(code, path, message) {
165
+ return { code, path, message };
166
+ }
167
+ function isPlainObject(value) {
168
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
169
+ return false;
170
+ const prototype = Object.getPrototypeOf(value);
171
+ return prototype === Object.prototype || prototype === null;
172
+ }
173
+ function isNonEmptyString(value) {
174
+ return typeof value === 'string' && value.trim().length > 0;
175
+ }
176
+ function isKnownState(value) {
177
+ return ONBOARDING_ASSISTANT_STATES.includes(value);
178
+ }
179
+ function parseUtcMillis(timestamp) {
180
+ return new Date(timestamp).getTime();
181
+ }
182
+ function validateBlockingGates(value, path, errors) {
183
+ if (!Array.isArray(value)) {
184
+ errors.push(transitionError('malformed_transition_event', path, 'blockingGates must be an array'));
185
+ return [];
186
+ }
187
+ const gates = [];
188
+ value.forEach((entry, index) => {
189
+ const entryPath = `${path}[${index}]`;
190
+ if (!isPlainObject(entry)) {
191
+ errors.push(transitionError('malformed_transition_event', entryPath, 'blocking gate must be an object'));
192
+ return;
193
+ }
194
+ if (!ONBOARDING_BLOCKING_GATE_KEYS.includes(entry.gate)) {
195
+ errors.push(transitionError('malformed_transition_event', `${entryPath}.gate`, 'blocking gate key is unsupported'));
196
+ return;
197
+ }
198
+ if (!Array.isArray(entry.reasonCodes)
199
+ || !entry.reasonCodes.every((code) => GATE_REASON_CODES.includes(code))) {
200
+ errors.push(transitionError('malformed_transition_event', `${entryPath}.reasonCodes`, 'reasonCodes must be an array of recognised gate reason codes'));
201
+ return;
202
+ }
203
+ if (entry.note !== undefined && !isNonEmptyString(entry.note)) {
204
+ errors.push(transitionError('malformed_transition_event', `${entryPath}.note`, 'note must be a non-empty string when present'));
205
+ return;
206
+ }
207
+ gates.push({
208
+ gate: entry.gate,
209
+ reasonCodes: [...entry.reasonCodes],
210
+ ...(entry.note !== undefined ? { note: entry.note } : {}),
211
+ });
212
+ });
213
+ return gates;
214
+ }
215
+ function validateTransitionEventShape(input, errors) {
216
+ if (!isPlainObject(input)) {
217
+ errors.push(transitionError('malformed_transition_event', '$', 'transition event must be a plain object'));
218
+ return undefined;
219
+ }
220
+ if (input.schemaVersion !== ONBOARDING_STATE_TRANSITION_EVENT_SCHEMA_VERSION) {
221
+ errors.push(transitionError('malformed_transition_event', '$.schemaVersion', `expected ${ONBOARDING_STATE_TRANSITION_EVENT_SCHEMA_VERSION}`));
222
+ }
223
+ if (!isNonEmptyString(input.eventId)) {
224
+ errors.push(transitionError('malformed_transition_event', '$.eventId', 'eventId must be a non-empty string'));
225
+ }
226
+ if (!isKnownState(input.to)) {
227
+ errors.push(transitionError('unknown_state', '$.to', 'target state is not one of the twelve onboarding assistant states'));
228
+ }
229
+ if (!isNonEmptyString(input.reason)) {
230
+ errors.push(transitionError('missing_audit_reason', '$.reason', 'every transition must carry a non-empty audit reason'));
231
+ }
232
+ if (!ONBOARDING_STATE_ACTOR_TYPES.includes(input.actorType)) {
233
+ errors.push(transitionError('invalid_actor_type', '$.actorType', 'actorType must be operator, provider, analyser, or system'));
234
+ }
235
+ if (input.actorRef !== undefined && !isNonEmptyString(input.actorRef)) {
236
+ errors.push(transitionError('malformed_transition_event', '$.actorRef', 'actorRef must be a non-empty string when present'));
237
+ }
238
+ if (!isNonEmptyString(input.occurredAt) || !RFC3339_UTC_PATTERN.test(input.occurredAt)) {
239
+ errors.push(transitionError('invalid_timestamp', '$.occurredAt', 'occurredAt must be a caller-supplied RFC3339 UTC timestamp'));
240
+ }
241
+ if (!isNonEmptyString(input.sourceSnapshotRef)) {
242
+ errors.push(transitionError('missing_source_snapshot_ref', '$.sourceSnapshotRef', 'every transition must reference the static source snapshot'));
243
+ }
244
+ if (!isNonEmptyString(input.readinessResultRef)) {
245
+ errors.push(transitionError('missing_readiness_result_ref', '$.readinessResultRef', 'every transition must reference the readiness result backing it'));
246
+ }
247
+ if (!READINESS_SUMMARIES.includes(input.readinessOverall)) {
248
+ errors.push(transitionError('malformed_transition_event', '$.readinessOverall', 'readinessOverall must be blocked, needs_operator_review, or publish_ready'));
249
+ }
250
+ const blockingGates = validateBlockingGates(input.blockingGates, '$.blockingGates', errors);
251
+ if (input.requestedSideEffects !== undefined) {
252
+ if (!Array.isArray(input.requestedSideEffects) || !input.requestedSideEffects.every((item) => typeof item === 'string')) {
253
+ errors.push(transitionError('malformed_transition_event', '$.requestedSideEffects', 'requestedSideEffects must be a string array when present'));
254
+ }
255
+ else {
256
+ input.requestedSideEffects.forEach((effect, index) => {
257
+ errors.push(transitionError('publication_side_effect_rejected', `$.requestedSideEffects[${index}]`, `requested side effect "${effect}" is rejected fail-closed: transitions are local/read-model events only`));
258
+ });
259
+ }
260
+ }
261
+ if (errors.length > 0)
262
+ return undefined;
263
+ return {
264
+ eventId: input.eventId,
265
+ to: input.to,
266
+ reason: input.reason,
267
+ actorType: input.actorType,
268
+ ...(input.actorRef !== undefined ? { actorRef: input.actorRef } : {}),
269
+ occurredAt: input.occurredAt,
270
+ sourceSnapshotRef: input.sourceSnapshotRef,
271
+ readinessResultRef: input.readinessResultRef,
272
+ readinessOverall: input.readinessOverall,
273
+ blockingGates,
274
+ };
275
+ }
276
+ const READ_MODEL_PUBLICATION_LEDGER = Object.freeze({
277
+ hostedRegistryWritePerformed: false,
278
+ publicCatalogWritePerformed: false,
279
+ trustMutationPerformed: false,
280
+ reputationMutationPerformed: false,
281
+ paymentActivationPerformed: false,
282
+ endpointInvocationPerformed: false,
283
+ walletOrRpcCallPerformed: false,
284
+ });
285
+ /**
286
+ * Create a read model for a new onboarding draft. Drafts always start in
287
+ * `draft`; there is no way to construct a read model already approved or
288
+ * published.
289
+ */
290
+ export function createOnboardingAssistantReadModel(init) {
291
+ const errors = [];
292
+ if (!isPlainObject(init)) {
293
+ return { ok: false, failClosed: true, errors: [transitionError('malformed_read_model', '$', 'read model init must be a plain object')] };
294
+ }
295
+ if (!isNonEmptyString(init.draftId)) {
296
+ errors.push(transitionError('malformed_read_model', '$.draftId', 'draftId must be a non-empty string'));
297
+ }
298
+ if (!isNonEmptyString(init.sourceSnapshotRef)) {
299
+ errors.push(transitionError('missing_source_snapshot_ref', '$.sourceSnapshotRef', 'sourceSnapshotRef must be a non-empty string'));
300
+ }
301
+ if (!isNonEmptyString(init.readinessResultRef)) {
302
+ errors.push(transitionError('missing_readiness_result_ref', '$.readinessResultRef', 'readinessResultRef must be a non-empty string'));
303
+ }
304
+ if (!READINESS_SUMMARIES.includes(init.readinessOverall)) {
305
+ errors.push(transitionError('malformed_read_model', '$.readinessOverall', 'readinessOverall must be blocked, needs_operator_review, or publish_ready'));
306
+ }
307
+ if (!isNonEmptyString(init.createdAt) || !RFC3339_UTC_PATTERN.test(init.createdAt)) {
308
+ errors.push(transitionError('invalid_timestamp', '$.createdAt', 'createdAt must be a caller-supplied RFC3339 UTC timestamp'));
309
+ }
310
+ const blockingGates = init.blockingGates === undefined
311
+ ? []
312
+ : validateBlockingGates(init.blockingGates, '$.blockingGates', errors);
313
+ if (errors.length > 0) {
314
+ return { ok: false, failClosed: true, errors };
315
+ }
316
+ return {
317
+ ok: true,
318
+ readModel: {
319
+ schemaVersion: ONBOARDING_ASSISTANT_READ_MODEL_SCHEMA_VERSION,
320
+ stateMachineVersion: ONBOARDING_STATE_MACHINE_SCHEMA_VERSION,
321
+ draftId: init.draftId,
322
+ state: 'draft',
323
+ stateSince: init.createdAt,
324
+ sourceSnapshotRef: init.sourceSnapshotRef,
325
+ readinessResultRef: init.readinessResultRef,
326
+ readinessOverall: init.readinessOverall,
327
+ blockingGates,
328
+ history: [],
329
+ internalCandidateOnly: true,
330
+ publication: { ...READ_MODEL_PUBLICATION_LEDGER },
331
+ guardrails: ONBOARDING_STATE_MACHINE_GUARDRAILS,
332
+ localReadModelOnly: true,
333
+ staticOnly: true,
334
+ },
335
+ };
336
+ }
337
+ // ---------------------------------------------------------------------------
338
+ // Transition application
339
+ // ---------------------------------------------------------------------------
340
+ /**
341
+ * Apply a transition event to a read model. Pure and deterministic: the input
342
+ * read model is never mutated; a new read model with the appended audit record
343
+ * is returned. Invalid transitions fail closed with structured reasons and no
344
+ * state change.
345
+ */
346
+ export function applyOnboardingStateTransition(readModel, event) {
347
+ if (!isPlainObject(readModel) || !isKnownState(readModel.state)) {
348
+ return {
349
+ ok: false,
350
+ failClosed: true,
351
+ errors: [transitionError('malformed_read_model', '$.readModel.state', 'read model must carry a known onboarding assistant state')],
352
+ };
353
+ }
354
+ const errors = [];
355
+ const core = validateTransitionEventShape(event, errors);
356
+ if (!core) {
357
+ return { ok: false, failClosed: true, errors };
358
+ }
359
+ const from = readModel.state;
360
+ const allowed = ONBOARDING_STATE_TRANSITION_GRAPH[from];
361
+ if (allowed.length === 0) {
362
+ errors.push(transitionError('terminal_state', '$.to', `state "${from}" is terminal; a rejected draft must be re-onboarded as a new draft`));
363
+ }
364
+ else if (!allowed.includes(core.to)) {
365
+ errors.push(transitionError('invalid_transition', '$.to', `transition ${from} -> ${core.to} is not allowed by the onboarding state machine`));
366
+ }
367
+ const operatorRequired = ONBOARDING_OPERATOR_ONLY_TARGET_STATES.includes(core.to) || from === 'suspended';
368
+ if (operatorRequired && core.actorType !== 'operator') {
369
+ errors.push(transitionError('operator_action_required', '$.actorType', `transition ${from} -> ${core.to} is an operator review decision and must be recorded by an operator actor`));
370
+ }
371
+ const requiredGate = ONBOARDING_STATE_REQUIRED_GATES[core.to];
372
+ if (requiredGate && !core.blockingGates.some((gate) => gate.gate === requiredGate)) {
373
+ errors.push(transitionError('missing_blocking_gate', '$.blockingGates', `entering ${core.to} requires the open "${requiredGate}" blocking gate to be carried on the transition`));
374
+ }
375
+ if (core.to === 'approved_unpublished' || core.to === 'published_candidate') {
376
+ if (core.readinessOverall === 'blocked') {
377
+ errors.push(transitionError('blocked_readiness', '$.readinessOverall', `cannot enter ${core.to} while the referenced readiness result is blocked`));
378
+ }
379
+ if (core.blockingGates.length > 0) {
380
+ errors.push(transitionError('unresolved_blocking_gates', '$.blockingGates', `cannot enter ${core.to} while blocking gates remain open: ${core.blockingGates.map((gate) => gate.gate).join(', ')}`));
381
+ }
382
+ }
383
+ if (RFC3339_UTC_PATTERN.test(core.occurredAt)
384
+ && parseUtcMillis(core.occurredAt) < parseUtcMillis(readModel.stateSince)) {
385
+ errors.push(transitionError('timestamp_regression', '$.occurredAt', 'occurredAt must not be earlier than the timestamp of the current state'));
386
+ }
387
+ if (errors.length > 0) {
388
+ return { ok: false, failClosed: true, errors };
389
+ }
390
+ const record = {
391
+ sequence: readModel.history.length + 1,
392
+ from,
393
+ to: core.to,
394
+ eventId: core.eventId,
395
+ reason: core.reason,
396
+ actorType: core.actorType,
397
+ ...(core.actorRef !== undefined ? { actorRef: core.actorRef } : {}),
398
+ occurredAt: core.occurredAt,
399
+ sourceSnapshotRef: core.sourceSnapshotRef,
400
+ readinessResultRef: core.readinessResultRef,
401
+ readinessOverall: core.readinessOverall,
402
+ blockingGates: core.blockingGates.map((gate) => ({ ...gate, reasonCodes: [...gate.reasonCodes] })),
403
+ scope: 'local_read_model_only',
404
+ };
405
+ return {
406
+ ok: true,
407
+ readModel: {
408
+ ...readModel,
409
+ state: core.to,
410
+ stateSince: core.occurredAt,
411
+ sourceSnapshotRef: core.sourceSnapshotRef,
412
+ readinessResultRef: core.readinessResultRef,
413
+ readinessOverall: core.readinessOverall,
414
+ blockingGates: record.blockingGates.map((gate) => ({ ...gate, reasonCodes: [...gate.reasonCodes] })),
415
+ history: [...readModel.history, record],
416
+ internalCandidateOnly: true,
417
+ publication: { ...READ_MODEL_PUBLICATION_LEDGER },
418
+ guardrails: ONBOARDING_STATE_MACHINE_GUARDRAILS,
419
+ localReadModelOnly: true,
420
+ staticOnly: true,
421
+ },
422
+ record,
423
+ };
424
+ }
425
+ /**
426
+ * List the allowed target states from a given state. Useful for read-model
427
+ * consumers (UI lanes in #384/#385/#386) that need to render next actions
428
+ * without re-encoding the graph.
429
+ */
430
+ export function listOnboardingStateTransitions(from) {
431
+ return ONBOARDING_STATE_TRANSITION_GRAPH[from] ?? Object.freeze([]);
432
+ }