@coasys/ad4m 0.13.0-test-model-layer → 0.13.0-test-flows-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.
Files changed (55) hide show
  1. package/lib/index.cjs +817 -65
  2. package/lib/index.js +814 -66
  3. package/lib/src/ai/AIClient.d.ts +13 -0
  4. package/lib/src/ai/AIClient.js +15 -0
  5. package/lib/src/ai/AITypes.d.ts +5 -0
  6. package/lib/src/index.js +2 -0
  7. package/lib/src/model/Ad4mModel.d.ts +6 -1
  8. package/lib/src/model/Ad4mModel.js +41 -6
  9. package/lib/src/model/ModelQueryBuilder.d.ts +47 -3
  10. package/lib/src/model/ModelQueryBuilder.js +97 -6
  11. package/lib/src/model/query-common.d.ts +10 -1
  12. package/lib/src/model/query-common.js +16 -0
  13. package/lib/src/model/query-sparql.d.ts +11 -0
  14. package/lib/src/model/query-sparql.js +93 -1
  15. package/lib/src/model/query-utils.js +16 -0
  16. package/lib/src/model/shacl-gen.js +12 -0
  17. package/lib/src/model/types.d.ts +320 -3
  18. package/lib/src/model/types.js +9 -0
  19. package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
  20. package/lib/src/perspectives/FlowInstance.d.ts +176 -12
  21. package/lib/src/perspectives/FlowInstance.js +77 -13
  22. package/lib/src/perspectives/FlowModels.d.ts +40 -9
  23. package/lib/src/perspectives/FlowModels.js +59 -13
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -0
  25. package/lib/src/perspectives/PerspectiveClient.js +30 -0
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +69 -2
  27. package/lib/src/perspectives/PerspectiveProxy.js +157 -7
  28. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
  29. package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
  30. package/lib/src/shacl/SHACLFlow.d.ts +43 -0
  31. package/package.json +1 -1
  32. package/src/ai/AIClient.ts +16 -0
  33. package/src/ai/AITypes.ts +5 -0
  34. package/src/index.ts +2 -0
  35. package/src/model/Ad4mModel.test.ts +442 -0
  36. package/src/model/Ad4mModel.ts +39 -7
  37. package/src/model/ModelQueryBuilder.ts +101 -10
  38. package/src/model/query-common.ts +20 -1
  39. package/src/model/query-sparql.test.ts +115 -0
  40. package/src/model/query-sparql.ts +97 -1
  41. package/src/model/query-utils.ts +18 -0
  42. package/src/model/relation-filtering.test.ts +7 -0
  43. package/src/model/shacl-gen.ts +12 -0
  44. package/src/model/shacl-roundtrip.test.ts +71 -0
  45. package/src/model/types-typed-query.test.ts +42 -0
  46. package/src/model/types.ts +316 -6
  47. package/src/perspectives/AutoProcessor.ts +8 -0
  48. package/src/perspectives/FlowInstance.ts +194 -13
  49. package/src/perspectives/FlowModels.ts +53 -13
  50. package/src/perspectives/PerspectiveClient.ts +62 -0
  51. package/src/perspectives/PerspectiveProxy.test.ts +272 -0
  52. package/src/perspectives/PerspectiveProxy.ts +163 -7
  53. package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
  54. package/src/perspectives/WakerSubscriptionManager.ts +197 -9
  55. package/src/shacl/SHACLFlow.ts +44 -0
@@ -17,7 +17,7 @@
17
17
  * than the `wrap` escape hatch, which exists for tests that already own
18
18
  * a matched (record, shape) pair.
19
19
  *
20
- * # What's here vs. what's coming in §7 / slice 10.6
20
+ * # What's here, and what is still absent
21
21
  *
22
22
  * Read surface (implemented today, PR #929):
23
23
  * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
@@ -28,16 +28,143 @@
28
28
  * - `proposals()` — queries `FlowTransitionProposal` records that
29
29
  * target this instance's URI.
30
30
  *
31
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
32
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
33
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
34
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
35
- * lie the caller only discovers at runtime — they are simply absent from
36
- * this class until the engine is wired.
31
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
32
+ * accept counts your DID toward the flow's consensusRule and fires the
33
+ * transition at quorum; reject withdraws only the links you signed and
34
+ * resolves to how many went. Reject is not a cancel — another agent's
35
+ * proposal is theirs, and because state is recomputed from the links
36
+ * present now, withdrawing a vote that had settled an edge moves the
37
+ * flow back to where it stood before it.
38
+ *
39
+ * - `proposeTransition()` — the manual write path: propose an edge as this
40
+ * agent, or co-sign the equivalent proposal another agent already opened.
41
+ * Its `FlowProposeResult` is what tells queued from no-op from stalled.
42
+ *
43
+ * Still absent (rather than shipped as `throw new Error("not yet")`
44
+ * stubs): `fireAction`, and the subscriptions (`onStateChange`,
45
+ * `onProposalAdded`, `onProposalResolved`) — they land with the
46
+ * subscription-topic slice.
47
+ *
48
+ * ## The guard-free rule
49
+ *
50
+ * A state with no `requires` guard is **never** proposed by the engine, on
51
+ * any replica, ever — `flow_evaluator`'s auto-proposal composer skips it by
52
+ * design. Nothing in the graph implies a human started work; they said so.
53
+ * So states like "in progress" and "in review" only ever advance through
54
+ * `proposeTransition`. This is a permanent contract, not a gap: wire the
55
+ * button, or the instance sits there.
37
56
  */
38
57
  import { PerspectiveProxy } from "./PerspectiveProxy";
39
58
  import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
40
59
  import { SHACLFlow, FlowState, FlowTransition } from "../shacl/SHACLFlow";
60
+ /** One fired flow transition, as returned by {@link FlowInstance.acceptProposal}
61
+ * (and, engine-side, by every consensus pass). */
62
+ export interface FlowFireOutcome {
63
+ instanceUri: string;
64
+ fromState: string;
65
+ toState: string;
66
+ voters: string[];
67
+ contributingProposalUris: string[];
68
+ }
69
+ /** What one {@link FlowInstance.proposeTransition} call did, and where the
70
+ * flow stands after it.
71
+ *
72
+ * A bare `FlowFireOutcome[]` could not distinguish "queued, waiting for other
73
+ * voters" from "you had already voted on this" from "the instance is stalled":
74
+ * all three are the empty array, and all three want different UI.
75
+ *
76
+ * Read the result like this:
77
+ *
78
+ * | `outcomes` | `recordedVote` | `contested` | meaning |
79
+ * |---|---|---|---|
80
+ * | non-empty | — | — | the transition fired |
81
+ * | `[]` | `true` | `false` | your vote landed; waiting for other voters |
82
+ * | `[]` | `false` | `false` | you had already voted; nothing was written |
83
+ * | `[]` | — | `true` | the flow is stalled — do not show "awaiting votes" |
84
+ */
85
+ /**
86
+ * One output of a run, named when proposing a transition into a terminal
87
+ * state: an instance, and the class it is an instance of. Every co-signer
88
+ * loads it through that class and hashes its content, so the proposal
89
+ * commits to the instance as it is now, not just to its id.
90
+ */
91
+ export interface FlowOutputRef {
92
+ className: string;
93
+ id: string;
94
+ }
95
+ export interface FlowProposeResult {
96
+ /** The live proposal this call minted or joined — always the one for the
97
+ * edge, whether this call wrote it or found it open. Hand it to another
98
+ * agent's `acceptProposal`, offer `rejectProposal` on it, or render it as
99
+ * "pending — withdraw?". */
100
+ proposalUri: string;
101
+ /** `true` when this call wrote the proposal; `false` when an equivalent
102
+ * one was already open and this call joined it. */
103
+ minted: boolean;
104
+ /** `true` when this call recorded a vote for the calling agent — its own
105
+ * vote on a mint, an `acceptedBy` on a join. `false` means the agent had
106
+ * already voted and nothing was written. */
107
+ recordedVote: boolean;
108
+ /** Consensus events this call recorded for the first time. Empty while
109
+ * the edge is short of quorum. */
110
+ outcomes: FlowFireOutcome[];
111
+ /** The instance's derived state after the call. */
112
+ derivedState: string;
113
+ /** `true` when two edges out of `derivedState` both carry quorum: the flow
114
+ * is irreversibly stalled and must not be shown as "awaiting votes". */
115
+ contested: boolean;
116
+ }
117
+ /**
118
+ * One instance a verified flow receipt speaks for — an entry of
119
+ * `PerspectiveProxy.flowValidOutputs(flow, state?)`.
120
+ *
121
+ * Every entry has already passed the whole verification chain executor-side:
122
+ * the receipt's signatures and quorum re-checked, its outputs bound to the
123
+ * quorum-signed commitment (#1104), and the instance's *live* content still
124
+ * equal to what the quorum committed to. An output edited since the run
125
+ * completed is not listed, although the receipt itself stays verifiable.
126
+ */
127
+ export interface FlowValidOutput {
128
+ /** The instance, as the `(className, id)` pair the quorum committed to. */
129
+ output: FlowOutputRef;
130
+ /** The instance's content as committed at completion (its `modelQuery`
131
+ * hydration, JSON-encoded). */
132
+ content: string;
133
+ /** The terminal state the granting run settled into, re-derived by the
134
+ * verifier. */
135
+ terminalState: string;
136
+ /** Content-derived URI of the receipt that proves this output. */
137
+ receiptUri: string;
138
+ }
139
+ /**
140
+ * What `PerspectiveProxy.verifyFlowReceipt` learned — a THREE-way answer,
141
+ * not a boolean, and collapsing it to one is the classic mistake:
142
+ *
143
+ * - `"verified"` — the carried material re-derives the claim;
144
+ * - `"rejected"` — the material was checked and does not hold up;
145
+ * - `"undecidable"`— this replica cannot decide (it lacks the flow
146
+ * definition, or holds a different one). Refuse to act on it exactly as
147
+ * on `"rejected"`, but do NOT treat it as evidence against the receipt
148
+ * or its minter — sync the definition and ask again.
149
+ */
150
+ export interface FlowReceiptVerdict {
151
+ outcome: "verified" | "rejected" | "undecidable";
152
+ /** Human-readable reason, phrased for the outcome it accompanies. */
153
+ detail: string;
154
+ /** Only on `"verified"`: the terminal state the reader's own fold reached. */
155
+ terminalState?: string;
156
+ /** Only on `"verified"`: the outputs the receipt speaks for. */
157
+ outputs?: FlowOutputRef[];
158
+ /** Only on `"verified"`: the distinct eligible DIDs that made the quorum. */
159
+ voters?: string[];
160
+ }
161
+ /** What `PerspectiveProxy.mintFlowReceipt` wrote: the receipt's
162
+ * content-derived node URI and its body (opaque to clients — verify it with
163
+ * `verifyFlowReceipt`, never by inspection). */
164
+ export interface FlowMintedReceipt {
165
+ receiptUri: string;
166
+ receipt: object;
167
+ }
41
168
  export declare class FlowInstance {
42
169
  private readonly perspective;
43
170
  /** The flow definition this instance was minted against. */
@@ -74,9 +201,15 @@ export declare class FlowInstance {
74
201
  *
75
202
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
76
203
  * on-graph record, so `currentState` / `availableTransitions` /
77
- * `proposals` accessors work without further round-trips. The consensus
78
- * engine (slice 10.6) will read the record's `currentState` when it
79
- * fires transitions.
204
+ * `proposals` accessors work without further round-trips.
205
+ *
206
+ * The record's `currentState` is a per-replica cache the consensus engine
207
+ * writes as a local link. It is read back only for display — the cache-first
208
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
209
+ * context — and **never as authority**: anything that decides something
210
+ * (the fold, the mint pass) derives state from the signed links present now
211
+ * and does not consult the cache. Treat it as a display hint, not as the
212
+ * flow's state.
80
213
  *
81
214
  * @param perspective - The perspective the flow instance lives on
82
215
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -180,8 +313,39 @@ export declare class FlowInstance {
180
313
  * for the where-filter — one SPARQL round-trip, no client-side
181
314
  * filtering.
182
315
  *
183
- * Note: the consensus engine (slice 10.6) will start writing these; today
184
- * they only exist when a client wrote one directly (or a test seeded one).
316
+ * These are written by the executor's consensus pass when it mints a
317
+ * transition, and by clients proposing directly. Superseded proposals are
318
+ * not swept here — a stale one is simply never counted by the fold, and
319
+ * accepting it fails with a stale-state error.
185
320
  */
186
321
  proposals(): Promise<FlowTransitionProposal[]>;
322
+ /**
323
+ * Propose a flow transition for this instance, as the calling agent.
324
+ *
325
+ * The executor evaluates the guard on its own replica, seals the evidence,
326
+ * and either writes a new proposal or — when an equivalent one is already
327
+ * open, i.e. another agent pressed the same button first — co-signs that
328
+ * one. When the resulting vote reaches the target state's
329
+ * `consensusRule.n`, the transition fires in the same call.
330
+ *
331
+ * How to read the result — fired vs. queued vs. no-op vs. stalled — is
332
+ * documented on {@link FlowProposeResult} itself.
333
+ *
334
+ * `outputs` names the instances the run produces, as `{ className, id }`
335
+ * pairs, for a transition into a terminal state. The proposal signs a hash
336
+ * over their content, every co-signer recomputes it on its own replica,
337
+ * and a receipt for the run speaks for exactly these instances as they
338
+ * stood at completion.
339
+ *
340
+ * Throws when `toState` is not reachable from the derived state, when the
341
+ * target state carries a `requires` guard that is not currently satisfied
342
+ * on this replica, when the instance is already contested, when `outputs`
343
+ * is given for a non-terminal state or names something that is not an
344
+ * instance of its class, or
345
+ * when an open proposal on the same edge names different outputs.
346
+ */
347
+ proposeTransition(toState: string, rationale?: string, outputs?: FlowOutputRef[]): Promise<FlowProposeResult>;
348
+ acceptProposal(proposal: FlowTransitionProposal | string): Promise<FlowFireOutcome[]>;
349
+ /** Withdraw our own links from a proposal; resolves to how many went. */
350
+ rejectProposal(proposal: FlowTransitionProposal | string): Promise<number>;
187
351
  }
@@ -17,7 +17,7 @@
17
17
  * than the `wrap` escape hatch, which exists for tests that already own
18
18
  * a matched (record, shape) pair.
19
19
  *
20
- * # What's here vs. what's coming in §7 / slice 10.6
20
+ * # What's here, and what is still absent
21
21
  *
22
22
  * Read surface (implemented today, PR #929):
23
23
  * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
@@ -28,12 +28,31 @@
28
28
  * - `proposals()` — queries `FlowTransitionProposal` records that
29
29
  * target this instance's URI.
30
30
  *
31
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
32
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
33
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
34
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
35
- * lie the caller only discovers at runtime — they are simply absent from
36
- * this class until the engine is wired.
31
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
32
+ * accept counts your DID toward the flow's consensusRule and fires the
33
+ * transition at quorum; reject withdraws only the links you signed and
34
+ * resolves to how many went. Reject is not a cancel — another agent's
35
+ * proposal is theirs, and because state is recomputed from the links
36
+ * present now, withdrawing a vote that had settled an edge moves the
37
+ * flow back to where it stood before it.
38
+ *
39
+ * - `proposeTransition()` — the manual write path: propose an edge as this
40
+ * agent, or co-sign the equivalent proposal another agent already opened.
41
+ * Its `FlowProposeResult` is what tells queued from no-op from stalled.
42
+ *
43
+ * Still absent (rather than shipped as `throw new Error("not yet")`
44
+ * stubs): `fireAction`, and the subscriptions (`onStateChange`,
45
+ * `onProposalAdded`, `onProposalResolved`) — they land with the
46
+ * subscription-topic slice.
47
+ *
48
+ * ## The guard-free rule
49
+ *
50
+ * A state with no `requires` guard is **never** proposed by the engine, on
51
+ * any replica, ever — `flow_evaluator`'s auto-proposal composer skips it by
52
+ * design. Nothing in the graph implies a human started work; they said so.
53
+ * So states like "in progress" and "in review" only ever advance through
54
+ * `proposeTransition`. This is a permanent contract, not a gap: wire the
55
+ * button, or the instance sits there.
37
56
  */
38
57
  import { Ad4mModel } from "../model/Ad4mModel";
39
58
  import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
@@ -98,9 +117,15 @@ export class FlowInstance {
98
117
  *
99
118
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
100
119
  * on-graph record, so `currentState` / `availableTransitions` /
101
- * `proposals` accessors work without further round-trips. The consensus
102
- * engine (slice 10.6) will read the record's `currentState` when it
103
- * fires transitions.
120
+ * `proposals` accessors work without further round-trips.
121
+ *
122
+ * The record's `currentState` is a per-replica cache the consensus engine
123
+ * writes as a local link. It is read back only for display — the cache-first
124
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
125
+ * context — and **never as authority**: anything that decides something
126
+ * (the fold, the mint pass) derives state from the signed links present now
127
+ * and does not consult the cache. Treat it as a display hint, not as the
128
+ * flow's state.
104
129
  *
105
130
  * @param perspective - The perspective the flow instance lives on
106
131
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -260,7 +285,7 @@ export class FlowInstance {
260
285
  * `FlowTransitionProposal.flowInstance` references).
261
286
  */
262
287
  get uri() {
263
- return this.record.baseExpression;
288
+ return this.record.id;
264
289
  }
265
290
  /**
266
291
  * URI of the base expression this flow runs on — matches the
@@ -325,12 +350,51 @@ export class FlowInstance {
325
350
  * for the where-filter — one SPARQL round-trip, no client-side
326
351
  * filtering.
327
352
  *
328
- * Note: the consensus engine (slice 10.6) will start writing these; today
329
- * they only exist when a client wrote one directly (or a test seeded one).
353
+ * These are written by the executor's consensus pass when it mints a
354
+ * transition, and by clients proposing directly. Superseded proposals are
355
+ * not swept here — a stale one is simply never counted by the fold, and
356
+ * accepting it fails with a stale-state error.
330
357
  */
331
358
  async proposals() {
332
359
  return FlowTransitionProposal.findAll(this.perspective, {
333
360
  where: { flowInstance: this.uri },
334
361
  });
335
362
  }
363
+ /**
364
+ * Propose a flow transition for this instance, as the calling agent.
365
+ *
366
+ * The executor evaluates the guard on its own replica, seals the evidence,
367
+ * and either writes a new proposal or — when an equivalent one is already
368
+ * open, i.e. another agent pressed the same button first — co-signs that
369
+ * one. When the resulting vote reaches the target state's
370
+ * `consensusRule.n`, the transition fires in the same call.
371
+ *
372
+ * How to read the result — fired vs. queued vs. no-op vs. stalled — is
373
+ * documented on {@link FlowProposeResult} itself.
374
+ *
375
+ * `outputs` names the instances the run produces, as `{ className, id }`
376
+ * pairs, for a transition into a terminal state. The proposal signs a hash
377
+ * over their content, every co-signer recomputes it on its own replica,
378
+ * and a receipt for the run speaks for exactly these instances as they
379
+ * stood at completion.
380
+ *
381
+ * Throws when `toState` is not reachable from the derived state, when the
382
+ * target state carries a `requires` guard that is not currently satisfied
383
+ * on this replica, when the instance is already contested, when `outputs`
384
+ * is given for a non-terminal state or names something that is not an
385
+ * instance of its class, or
386
+ * when an open proposal on the same edge names different outputs.
387
+ */
388
+ async proposeTransition(toState, rationale, outputs) {
389
+ return this.perspective.proposeFlowTransition(this.uri, toState, rationale, outputs);
390
+ }
391
+ async acceptProposal(proposal) {
392
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
393
+ return this.perspective.acceptFlowProposal(uri);
394
+ }
395
+ /** Withdraw our own links from a proposal; resolves to how many went. */
396
+ async rejectProposal(proposal) {
397
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
398
+ return this.perspective.rejectFlowProposal(uri);
399
+ }
336
400
  }
@@ -9,14 +9,14 @@
9
9
  * Querying:
10
10
  * const pending = await FlowTransitionProposal.findAll(perspective);
11
11
  *
12
- * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
13
- * engine does not yet mint these — that lands with the consensus firing
14
- * work in a later PR arc. This class defines the on-graph shape so:
15
- * - clients can build UI over proposals immediately (Deliberation demo);
16
- * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
17
- * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
18
- * - the engine can start writing into this shape when consensus lands
19
- * without touching the client-side surface.
12
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust engine
13
+ * mints these as of #987 — see `flow_classes.rs` (`mint_proposal`, URIs at
14
+ * `ad4m://flow/proposal/{id}`) — and reads them back in
15
+ * `flow_instance/atom.rs`. A UI mints or joins them through
16
+ * `FlowInstance.proposeTransition`. This class is the client-side mirror:
17
+ * - clients build UI over proposals without knowing the raw link predicates;
18
+ * - the SDNA-parity test locks TS/Rust drift against
19
+ * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
20
20
  */
21
21
  import { Ad4mModel } from "../model/Ad4mModel";
22
22
  export declare class FlowTransitionProposal extends Ad4mModel {
@@ -49,6 +49,31 @@ export declare class FlowTransitionProposal extends Ad4mModel {
49
49
  * no rich-object type; the engine parses it back into a map.
50
50
  */
51
51
  evidenceHashes: string;
52
+ /**
53
+ * The instances the proposer names as the run's outputs. Written only on
54
+ * a proposal into a terminal state; one link per output, ordering not
55
+ * significant. Each entry is the canonical JSON text of a
56
+ * `{ className, id }` pair (`FlowOutputRef`); `JSON.parse` it to read one.
57
+ */
58
+ outputs: string[];
59
+ /**
60
+ * SHA-256 (hex) over the named outputs' content (each instance as
61
+ * `model_query` returns it through its class), signed by the proposer
62
+ * next to the evidence seal. Co-signers load the outputs and recompute it
63
+ * before voting, and a flow receipt's output preimages must hash to it.
64
+ * Empty on a proposal into a non-terminal state.
65
+ */
66
+ outputsHash: string;
67
+ /**
68
+ * The proposer's uniqueness salt for this proposal's content-addressed
69
+ * URI (`ad4m://flow/proposal/<hash>`; the hash covers the instance, the
70
+ * edge, the seal, the outputs commitment, the proposer DID and this
71
+ * nonce). The engine writes a UUID. A proposal without one — or whose URI
72
+ * does not match its own signed fields — is not engine-visible:
73
+ * co-signatures name the URI, so the URI must commit to what they sign
74
+ * (#1108).
75
+ */
76
+ nonce: string;
52
77
  /**
53
78
  * URI of the `InterpretationRun` node that produced this proposal, when
54
79
  * the proposal came from an LLM extraction pass. Absent when a human
@@ -89,6 +114,12 @@ export declare class FlowInstanceRecord extends Ad4mModel {
89
114
  * on read.
90
115
  */
91
116
  subject: string;
92
- /** Name of the state the flow is currently in. */
117
+ /**
118
+ * The state name this replica's executor last derived for the flow — a
119
+ * per-replica cache written as a `local` link, never the authority (the
120
+ * fold over the signed proposals is). Optional on the shape: a row that
121
+ * synced in from a peer carries no value until the local consensus pass
122
+ * has run, so an empty string means "not yet derived here".
123
+ */
93
124
  currentState: string;
94
125
  }
@@ -9,14 +9,14 @@
9
9
  * Querying:
10
10
  * const pending = await FlowTransitionProposal.findAll(perspective);
11
11
  *
12
- * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
13
- * engine does not yet mint these — that lands with the consensus firing
14
- * work in a later PR arc. This class defines the on-graph shape so:
15
- * - clients can build UI over proposals immediately (Deliberation demo);
16
- * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
17
- * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
18
- * - the engine can start writing into this shape when consensus lands
19
- * without touching the client-side surface.
12
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust engine
13
+ * mints these as of #987 — see `flow_classes.rs` (`mint_proposal`, URIs at
14
+ * `ad4m://flow/proposal/{id}`) — and reads them back in
15
+ * `flow_instance/atom.rs`. A UI mints or joins them through
16
+ * `FlowInstance.proposeTransition`. This class is the client-side mirror:
17
+ * - clients build UI over proposals without knowing the raw link predicates;
18
+ * - the SDNA-parity test locks TS/Rust drift against
19
+ * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
20
20
  */
21
21
  var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
22
22
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -33,9 +33,12 @@ import { Model } from "../model/decorators";
33
33
  // ── FlowTransitionProposal ──────────────────────────────────────────────────
34
34
  // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
35
35
  // on the engine side; see file header). One node per proposed transition; the
36
- // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
37
- // carries no URI-format constraint — apps constructing proposals directly may
38
- // choose any URI they can defend as unique.
36
+ // URI the engine mints is `ad4m://flow/proposal/<hash>` — the content address
37
+ // of the proposer-signed fields under the `nonce` (#1108). The class carries
38
+ // no URI-format constraint, but a proposal whose URI is not that content
39
+ // address (including any app-chosen URI) is not engine-visible: co-signatures
40
+ // name the URI, so the engine only counts proposals whose URI commits to
41
+ // their fields.
39
42
  let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
40
43
  constructor() {
41
44
  super(...arguments);
@@ -68,6 +71,31 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
68
71
  * no rich-object type; the engine parses it back into a map.
69
72
  */
70
73
  this.evidenceHashes = "";
74
+ /**
75
+ * The instances the proposer names as the run's outputs. Written only on
76
+ * a proposal into a terminal state; one link per output, ordering not
77
+ * significant. Each entry is the canonical JSON text of a
78
+ * `{ className, id }` pair (`FlowOutputRef`); `JSON.parse` it to read one.
79
+ */
80
+ this.outputs = [];
81
+ /**
82
+ * SHA-256 (hex) over the named outputs' content (each instance as
83
+ * `model_query` returns it through its class), signed by the proposer
84
+ * next to the evidence seal. Co-signers load the outputs and recompute it
85
+ * before voting, and a flow receipt's output preimages must hash to it.
86
+ * Empty on a proposal into a non-terminal state.
87
+ */
88
+ this.outputsHash = "";
89
+ /**
90
+ * The proposer's uniqueness salt for this proposal's content-addressed
91
+ * URI (`ad4m://flow/proposal/<hash>`; the hash covers the instance, the
92
+ * edge, the seal, the outputs commitment, the proposer DID and this
93
+ * nonce). The engine writes a UUID. A proposal without one — or whose URI
94
+ * does not match its own signed fields — is not engine-visible:
95
+ * co-signatures name the URI, so the URI must commit to what they sign
96
+ * (#1108).
97
+ */
98
+ this.nonce = "";
71
99
  // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
72
100
  // `createdAt`, synthesized on hydration from the earliest link timestamp
73
101
  // of the proposal's own links (all written together during create_subject).
@@ -97,6 +125,18 @@ __decorate([
97
125
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
98
126
  __metadata("design:type", String)
99
127
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
128
+ __decorate([
129
+ HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
130
+ __metadata("design:type", Array)
131
+ ], FlowTransitionProposal.prototype, "outputs", void 0);
132
+ __decorate([
133
+ Property({ through: "ad4m://flow/outputs_hash" }),
134
+ __metadata("design:type", String)
135
+ ], FlowTransitionProposal.prototype, "outputsHash", void 0);
136
+ __decorate([
137
+ Property({ through: "ad4m://flow/nonce" }),
138
+ __metadata("design:type", String)
139
+ ], FlowTransitionProposal.prototype, "nonce", void 0);
100
140
  __decorate([
101
141
  Optional({ through: "ad4m://flow/run_uri" }),
102
142
  __metadata("design:type", String)
@@ -157,7 +197,13 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
157
197
  * on read.
158
198
  */
159
199
  this.subject = "";
160
- /** Name of the state the flow is currently in. */
200
+ /**
201
+ * The state name this replica's executor last derived for the flow — a
202
+ * per-replica cache written as a `local` link, never the authority (the
203
+ * fold over the signed proposals is). Optional on the shape: a row that
204
+ * synced in from a peer carries no value until the local consensus pass
205
+ * has run, so an empty string means "not yet derived here".
206
+ */
161
207
  this.currentState = "";
162
208
  // "When was this flow started?" is answered by `Ad4mModel`'s built-in
163
209
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -173,7 +219,7 @@ __decorate([
173
219
  __metadata("design:type", String)
174
220
  ], FlowInstanceRecord.prototype, "subject", void 0);
175
221
  __decorate([
176
- Property({ through: "ad4m://flow/current_state", required: true }),
222
+ Property({ through: "ad4m://flow/current_state", local: true }),
177
223
  __metadata("design:type", String)
178
224
  ], FlowInstanceRecord.prototype, "currentState", void 0);
179
225
  FlowInstanceRecord = __decorate([
@@ -12,6 +12,7 @@ import { AIClient } from "../ai/AIClient";
12
12
  import { AllInstancesResult } from "../model/types";
13
13
  import type { TranscriptTurn } from "../generated/api";
14
14
  import type { AddAutoProcessorConfig, AutoProcessorEvent, AutoProcessorNeighbourhoodStateEvent, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
15
+ import type { FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult, FlowReceiptVerdict, FlowValidOutput } from "./FlowInstance";
15
16
  export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null;
16
17
  export type UuidCallback = (uuid: string) => null;
17
18
  export type LinkCallback = (link: LinkExpression) => null;
@@ -108,6 +109,23 @@ export declare class PerspectiveClient {
108
109
  /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
109
110
  * (a rejected `create` deletes the suggested instance). */
110
111
  rejectInterpretation(uuid: string, base: string, property?: string): Promise<boolean>;
112
+ proposeFlowTransition(uuid: string, instanceUri: string, toState: string, rationale?: string, outputs?: FlowOutputRef[]): Promise<FlowProposeResult>;
113
+ acceptFlowProposal(uuid: string, proposalUri: string): Promise<FlowFireOutcome[]>;
114
+ /**
115
+ * Withdraw this agent's own links from a proposal. Resolves to how many
116
+ * were retracted — one for a withdrawn vote, more when retracting a
117
+ * proposal this agent opened.
118
+ */
119
+ rejectFlowProposal(uuid: string, proposalUri: string): Promise<number>;
120
+ /** Re-decide a flow receipt under this perspective's own flow catalogue. */
121
+ verifyFlowReceipt(uuid: string, receipt: object): Promise<FlowReceiptVerdict>;
122
+ /** The instances that are, as they stand, valid outputs of `flow`
123
+ * (optionally: of runs settled into terminal state `state`). */
124
+ flowValidOutputs(uuid: string, flow: string, state?: string): Promise<FlowValidOutput[]>;
125
+ /** Mint and store the receipt for a completed flow run. Fails while the
126
+ * run has not settled into a terminal state, and when an output's
127
+ * content no longer matches what the quorum committed to. */
128
+ mintFlowReceipt(uuid: string, instanceUri: string): Promise<FlowMintedReceipt>;
111
129
  /**
112
130
  * Subscribe to auto-processor step signals. `cb` fires for every
113
131
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -291,6 +291,36 @@ export class PerspectiveClient {
291
291
  async rejectInterpretation(uuid, base, property) {
292
292
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
293
293
  }
294
+ async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
295
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
296
+ }
297
+ async acceptFlowProposal(uuid, proposalUri) {
298
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
299
+ }
300
+ /**
301
+ * Withdraw this agent's own links from a proposal. Resolves to how many
302
+ * were retracted — one for a withdrawn vote, more when retracting a
303
+ * proposal this agent opened.
304
+ */
305
+ async rejectFlowProposal(uuid, proposalUri) {
306
+ const result = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
307
+ return result.retractedLinks;
308
+ }
309
+ /** Re-decide a flow receipt under this perspective's own flow catalogue. */
310
+ async verifyFlowReceipt(uuid, receipt) {
311
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.verifyFlowReceipt', { uuid, receipt });
312
+ }
313
+ /** The instances that are, as they stand, valid outputs of `flow`
314
+ * (optionally: of runs settled into terminal state `state`). */
315
+ async flowValidOutputs(uuid, flow, state) {
316
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.flowValidOutputs', { uuid, flow, state });
317
+ }
318
+ /** Mint and store the receipt for a completed flow run. Fails while the
319
+ * run has not settled into a terminal state, and when an output's
320
+ * content no longer matches what the quorum committed to. */
321
+ async mintFlowReceipt(uuid, instanceUri) {
322
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
323
+ }
294
324
  /**
295
325
  * Subscribe to auto-processor step signals. `cb` fires for every
296
326
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →