@smthrs/plan 0.0.0-stage → 1.0.0-rc.12

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 (209) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/LICENSE +21 -0
  3. package/README.md +230 -2
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/dist/cjs/CachePolicy.d.ts +131 -0
  6. package/dist/cjs/CachePolicy.d.ts.map +1 -0
  7. package/dist/cjs/CachePolicy.js +50 -0
  8. package/dist/cjs/CachePolicy.js.map +7 -0
  9. package/dist/cjs/Effects.d.ts +258 -0
  10. package/dist/cjs/Effects.d.ts.map +1 -0
  11. package/dist/cjs/Effects.js +76 -0
  12. package/dist/cjs/Effects.js.map +7 -0
  13. package/dist/cjs/FileSet.d.ts +366 -0
  14. package/dist/cjs/FileSet.d.ts.map +1 -0
  15. package/dist/cjs/FileSet.js +196 -0
  16. package/dist/cjs/FileSet.js.map +7 -0
  17. package/dist/cjs/GraphBuildError.d.ts +120 -0
  18. package/dist/cjs/GraphBuildError.d.ts.map +1 -0
  19. package/dist/cjs/GraphBuildError.js +71 -0
  20. package/dist/cjs/GraphBuildError.js.map +7 -0
  21. package/dist/cjs/KeyMaterial.d.ts +107 -0
  22. package/dist/cjs/KeyMaterial.d.ts.map +1 -0
  23. package/dist/cjs/KeyMaterial.js +64 -0
  24. package/dist/cjs/KeyMaterial.js.map +7 -0
  25. package/dist/cjs/Node.d.ts +677 -0
  26. package/dist/cjs/Node.d.ts.map +1 -0
  27. package/dist/cjs/Node.js +229 -0
  28. package/dist/cjs/Node.js.map +7 -0
  29. package/dist/cjs/Placement.d.ts +117 -0
  30. package/dist/cjs/Placement.d.ts.map +1 -0
  31. package/dist/cjs/Placement.js +46 -0
  32. package/dist/cjs/Placement.js.map +7 -0
  33. package/dist/cjs/Plan.d.ts +489 -0
  34. package/dist/cjs/Plan.d.ts.map +1 -0
  35. package/dist/cjs/Plan.js +511 -0
  36. package/dist/cjs/Plan.js.map +7 -0
  37. package/dist/cjs/PlanDiff.d.ts +77 -0
  38. package/dist/cjs/PlanDiff.d.ts.map +1 -0
  39. package/dist/cjs/PlanDiff.js +149 -0
  40. package/dist/cjs/PlanDiff.js.map +7 -0
  41. package/dist/cjs/Planned.d.ts +121 -0
  42. package/dist/cjs/Planned.d.ts.map +1 -0
  43. package/dist/cjs/Planned.js +72 -0
  44. package/dist/cjs/Planned.js.map +7 -0
  45. package/dist/cjs/Repetition.d.ts +31 -0
  46. package/dist/cjs/Repetition.d.ts.map +1 -0
  47. package/dist/cjs/Repetition.js +36 -0
  48. package/dist/cjs/Repetition.js.map +7 -0
  49. package/dist/cjs/Scheduling.d.ts +89 -0
  50. package/dist/cjs/Scheduling.d.ts.map +1 -0
  51. package/dist/cjs/Scheduling.js +76 -0
  52. package/dist/cjs/Scheduling.js.map +7 -0
  53. package/dist/cjs/StepKey.d.ts +354 -0
  54. package/dist/cjs/StepKey.d.ts.map +1 -0
  55. package/dist/cjs/StepKey.js +313 -0
  56. package/dist/cjs/StepKey.js.map +7 -0
  57. package/dist/cjs/index.d.ts +91 -0
  58. package/dist/cjs/index.d.ts.map +1 -0
  59. package/dist/cjs/index.js +59 -0
  60. package/dist/cjs/index.js.map +7 -0
  61. package/dist/cjs/internal/ConflictAnnotation.d.ts +59 -0
  62. package/dist/cjs/internal/ConflictAnnotation.d.ts.map +1 -0
  63. package/dist/cjs/internal/ConflictAnnotation.js +247 -0
  64. package/dist/cjs/internal/ConflictAnnotation.js.map +7 -0
  65. package/dist/cjs/internal/EffectCandidates.d.ts +19 -0
  66. package/dist/cjs/internal/EffectCandidates.d.ts.map +1 -0
  67. package/dist/cjs/internal/EffectCandidates.js +92 -0
  68. package/dist/cjs/internal/EffectCandidates.js.map +7 -0
  69. package/dist/cjs/internal/JsonMirror.d.ts +34 -0
  70. package/dist/cjs/internal/JsonMirror.d.ts.map +1 -0
  71. package/dist/cjs/internal/JsonMirror.js +195 -0
  72. package/dist/cjs/internal/JsonMirror.js.map +7 -0
  73. package/dist/cjs/internal/SchemaIdentity.d.ts +140 -0
  74. package/dist/cjs/internal/SchemaIdentity.d.ts.map +1 -0
  75. package/dist/cjs/internal/SchemaIdentity.js +718 -0
  76. package/dist/cjs/internal/SchemaIdentity.js.map +7 -0
  77. package/dist/cjs/internal/effects.d.ts +245 -0
  78. package/dist/cjs/internal/effects.d.ts.map +1 -0
  79. package/dist/cjs/internal/effects.js +290 -0
  80. package/dist/cjs/internal/effects.js.map +7 -0
  81. package/dist/cjs/internal/node.d.ts +526 -0
  82. package/dist/cjs/internal/node.d.ts.map +1 -0
  83. package/dist/cjs/internal/node.js +313 -0
  84. package/dist/cjs/internal/node.js.map +7 -0
  85. package/dist/cjs/package.json +1 -0
  86. package/dist/cjs/test/PlanFixtures.d.ts +127 -0
  87. package/dist/cjs/test/PlanFixtures.d.ts.map +1 -0
  88. package/dist/cjs/test/PlanFixtures.js +59 -0
  89. package/dist/cjs/test/PlanFixtures.js.map +7 -0
  90. package/dist/esm/CachePolicy.d.ts +131 -0
  91. package/dist/esm/CachePolicy.d.ts.map +1 -0
  92. package/dist/esm/CachePolicy.js +117 -0
  93. package/dist/esm/CachePolicy.js.map +1 -0
  94. package/dist/esm/Effects.d.ts +258 -0
  95. package/dist/esm/Effects.d.ts.map +1 -0
  96. package/dist/esm/Effects.js +178 -0
  97. package/dist/esm/Effects.js.map +1 -0
  98. package/dist/esm/FileSet.d.ts +366 -0
  99. package/dist/esm/FileSet.d.ts.map +1 -0
  100. package/dist/esm/FileSet.js +398 -0
  101. package/dist/esm/FileSet.js.map +1 -0
  102. package/dist/esm/GraphBuildError.d.ts +120 -0
  103. package/dist/esm/GraphBuildError.d.ts.map +1 -0
  104. package/dist/esm/GraphBuildError.js +145 -0
  105. package/dist/esm/GraphBuildError.js.map +1 -0
  106. package/dist/esm/KeyMaterial.d.ts +107 -0
  107. package/dist/esm/KeyMaterial.d.ts.map +1 -0
  108. package/dist/esm/KeyMaterial.js +92 -0
  109. package/dist/esm/KeyMaterial.js.map +1 -0
  110. package/dist/esm/Node.d.ts +677 -0
  111. package/dist/esm/Node.d.ts.map +1 -0
  112. package/dist/esm/Node.js +586 -0
  113. package/dist/esm/Node.js.map +1 -0
  114. package/dist/esm/Placement.d.ts +117 -0
  115. package/dist/esm/Placement.d.ts.map +1 -0
  116. package/dist/esm/Placement.js +65 -0
  117. package/dist/esm/Placement.js.map +1 -0
  118. package/dist/esm/Plan.d.ts +489 -0
  119. package/dist/esm/Plan.d.ts.map +1 -0
  120. package/dist/esm/Plan.js +718 -0
  121. package/dist/esm/Plan.js.map +1 -0
  122. package/dist/esm/PlanDiff.d.ts +77 -0
  123. package/dist/esm/PlanDiff.d.ts.map +1 -0
  124. package/dist/esm/PlanDiff.js +205 -0
  125. package/dist/esm/PlanDiff.js.map +1 -0
  126. package/dist/esm/Planned.d.ts +121 -0
  127. package/dist/esm/Planned.d.ts.map +1 -0
  128. package/dist/esm/Planned.js +147 -0
  129. package/dist/esm/Planned.js.map +1 -0
  130. package/dist/esm/Repetition.d.ts +31 -0
  131. package/dist/esm/Repetition.d.ts.map +1 -0
  132. package/dist/esm/Repetition.js +24 -0
  133. package/dist/esm/Repetition.js.map +1 -0
  134. package/dist/esm/Scheduling.d.ts +89 -0
  135. package/dist/esm/Scheduling.d.ts.map +1 -0
  136. package/dist/esm/Scheduling.js +82 -0
  137. package/dist/esm/Scheduling.js.map +1 -0
  138. package/dist/esm/StepKey.d.ts +354 -0
  139. package/dist/esm/StepKey.d.ts.map +1 -0
  140. package/dist/esm/StepKey.js +503 -0
  141. package/dist/esm/StepKey.js.map +1 -0
  142. package/dist/esm/index.d.ts +91 -0
  143. package/dist/esm/index.d.ts.map +1 -0
  144. package/dist/esm/index.js +91 -0
  145. package/dist/esm/index.js.map +1 -0
  146. package/dist/esm/internal/ConflictAnnotation.d.ts +59 -0
  147. package/dist/esm/internal/ConflictAnnotation.d.ts.map +1 -0
  148. package/dist/esm/internal/ConflictAnnotation.js +332 -0
  149. package/dist/esm/internal/ConflictAnnotation.js.map +1 -0
  150. package/dist/esm/internal/EffectCandidates.d.ts +19 -0
  151. package/dist/esm/internal/EffectCandidates.d.ts.map +1 -0
  152. package/dist/esm/internal/EffectCandidates.js +86 -0
  153. package/dist/esm/internal/EffectCandidates.js.map +1 -0
  154. package/dist/esm/internal/JsonMirror.d.ts +34 -0
  155. package/dist/esm/internal/JsonMirror.d.ts.map +1 -0
  156. package/dist/esm/internal/JsonMirror.js +204 -0
  157. package/dist/esm/internal/JsonMirror.js.map +1 -0
  158. package/dist/esm/internal/SchemaIdentity.d.ts +140 -0
  159. package/dist/esm/internal/SchemaIdentity.d.ts.map +1 -0
  160. package/dist/esm/internal/SchemaIdentity.js +1002 -0
  161. package/dist/esm/internal/SchemaIdentity.js.map +1 -0
  162. package/dist/esm/internal/effects.d.ts +245 -0
  163. package/dist/esm/internal/effects.d.ts.map +1 -0
  164. package/dist/esm/internal/effects.js +459 -0
  165. package/dist/esm/internal/effects.js.map +1 -0
  166. package/dist/esm/internal/node.d.ts +526 -0
  167. package/dist/esm/internal/node.d.ts.map +1 -0
  168. package/dist/esm/internal/node.js +565 -0
  169. package/dist/esm/internal/node.js.map +1 -0
  170. package/dist/esm/test/PlanFixtures.d.ts +127 -0
  171. package/dist/esm/test/PlanFixtures.d.ts.map +1 -0
  172. package/dist/esm/test/PlanFixtures.js +60 -0
  173. package/dist/esm/test/PlanFixtures.js.map +1 -0
  174. package/docs/README.md +167 -0
  175. package/docs/api.md +1485 -0
  176. package/docs/concepts/authoring-ast.md +204 -0
  177. package/docs/concepts/effects-and-conflicts.md +135 -0
  178. package/docs/concepts/plan-value.md +168 -0
  179. package/docs/concepts/step-keys.md +179 -0
  180. package/docs/guides/author-a-node-graph.md +182 -0
  181. package/docs/guides/compile-a-plan.md +146 -0
  182. package/docs/guides/declare-file-effects.md +143 -0
  183. package/docs/guides/diff-two-plans.md +310 -0
  184. package/docs/installation.md +75 -0
  185. package/docs/quickstart.md +128 -0
  186. package/docs/testing.md +73 -0
  187. package/docs/troubleshooting.md +314 -0
  188. package/package.json +255 -3
  189. package/src/CachePolicy.ts +143 -0
  190. package/src/Effects.ts +302 -0
  191. package/src/FileSet.ts +493 -0
  192. package/src/GraphBuildError.ts +156 -0
  193. package/src/KeyMaterial.ts +111 -0
  194. package/src/Node.ts +969 -0
  195. package/src/Placement.ts +99 -0
  196. package/src/Plan.ts +911 -0
  197. package/src/PlanDiff.ts +244 -0
  198. package/src/Planned.ts +208 -0
  199. package/src/Repetition.ts +33 -0
  200. package/src/Scheduling.ts +154 -0
  201. package/src/StepKey.ts +736 -0
  202. package/src/index.ts +103 -0
  203. package/src/internal/ConflictAnnotation.ts +374 -0
  204. package/src/internal/EffectCandidates.ts +89 -0
  205. package/src/internal/JsonMirror.ts +255 -0
  206. package/src/internal/SchemaIdentity.ts +1096 -0
  207. package/src/internal/effects.ts +543 -0
  208. package/src/internal/node.ts +859 -0
  209. package/src/test/PlanFixtures.ts +76 -0
@@ -0,0 +1,718 @@
1
+ /**
2
+ * The plan: a node graph with every step key computed, inert until run.
3
+ *
4
+ * The way a plan is produced is a law: **planning performs no I/O**.
5
+ * Everything in this module is therefore a pure function of declarations plus
6
+ * the injected `Crypto` service: no filesystem, no clock, no network. A node's
7
+ * key is a function of what it consumes, so an edited declaration re-keys that
8
+ * node and everything downstream of it, and nothing else. That is the entire
9
+ * invalidation mechanism. Invalidation is re-keying, which **rejects**
10
+ * Skyframe's reverse-dependency index and invalidating node visitor outright
11
+ * because content addressing subsumes them. Key invalidation never retains a
12
+ * reverse-dependency index; annotation uses only a temporary reachability cache.
13
+ *
14
+ * Growth is append-only: {@link append} adds a pre-keyed subgraph to the same
15
+ * plan and never rewrites a node already in it.
16
+ *
17
+ * @since 0.1.0
18
+ */
19
+ import { DerivedKey, StoredKey } from "@smthrs/keys";
20
+ import * as Effect from "effect/Effect";
21
+ import * as Inspectable from "effect/Inspectable";
22
+ import * as Schema from "effect/Schema";
23
+ import * as Effects from "./Effects.js";
24
+ import * as FileSet from "./FileSet.js";
25
+ import { GraphBuildError } from "./GraphBuildError.js";
26
+ import * as Conflicts from "./internal/ConflictAnnotation.js";
27
+ import { jsonMirror } from "./internal/JsonMirror.js";
28
+ import * as KeyMaterial from "./KeyMaterial.js";
29
+ import * as StepKey from "./StepKey.js";
30
+ /**
31
+ * What a node does to the world, declared. Paths only — measuring them is
32
+ * run-time work, so a digest here would break the no-I/O law.
33
+ *
34
+ * Decoding fails with a `SchemaError` when a path is not workspace-relative.
35
+ * {@link compile} also refuses a node whose `removes` overlaps its `writes`
36
+ * with an `invalid_effects` {@link PlanError}.
37
+ *
38
+ * @since 0.1.0
39
+ * @category schemas
40
+ */
41
+ export const NodeEffects = Schema.Struct({
42
+ /** Paths the node reads. A read orders the node after every writer of an overlapping path. */
43
+ reads: Schema.Array(FileSet.ReadDeclaration),
44
+ /** Paths the node writes. Two writers of an overlapping path form a conflict. */
45
+ writes: Schema.Array(FileSet.Declaration),
46
+ /**
47
+ * Paths the node declares it will DELETE. A removal mutates the world exactly
48
+ * as a write does, so {@link produces} folds the two together and both the
49
+ * conflict pass and the reader-after-writer pass see them as one set.
50
+ */
51
+ removes: Schema.optional(Schema.Array(FileSet.Pattern)),
52
+ /** How strictly the sandbox enforces these declarations. */
53
+ boundaryMode: FileSet.BoundaryMode
54
+ });
55
+ /**
56
+ * The plan-time verdict for two writers of an overlapping path:
57
+ * `serialize` gives the later writer an ordering edge, `lane` records a lane
58
+ * annotation on both writers and adds no edge, and `fail` refuses the plan
59
+ * with `overlap_forbidden`. For a pair, `fail` dominates `lane`, which
60
+ * dominates `serialize`. The same schema as `Effects.ConflictStrategy`.
61
+ *
62
+ * @since 0.1.0
63
+ * @category schemas
64
+ */
65
+ export const PairStrategy = Effects.ConflictStrategy;
66
+ /**
67
+ * The runtime half of a conflict annotation: what the scheduler
68
+ * does when the overlap the plan predicted actually bites, or when a
69
+ * scheduled node's inputs are invalidated under it. For a pair,
70
+ * `stop-merge` dominates `delay-rebase`.
71
+ *
72
+ * @since 0.1.0
73
+ * @category schemas
74
+ */
75
+ export const RuntimeStrategy = Schema.Literals(["delay-rebase", "stop-merge"]);
76
+ /** @private */
77
+ const NodeKind = Schema.Literals(["step", "agent", "merge"]);
78
+ /**
79
+ * One resolved overlap between two writers that no dependency path already
80
+ * orders. Conflict is a property of the PAIR, not of one declaration.
81
+ *
82
+ * `with` names the other node, `paths` lists the overlapping declarations,
83
+ * and `strategy` and `runtime` are the verdicts resolved for the pair.
84
+ *
85
+ * @since 0.1.0
86
+ * @category schemas
87
+ */
88
+ export const ConflictAnnotation = Schema.Struct({
89
+ with: Schema.NonEmptyString,
90
+ paths: Schema.Array(Schema.String),
91
+ strategy: PairStrategy,
92
+ runtime: RuntimeStrategy
93
+ });
94
+ /**
95
+ * A keyed node of the plan.
96
+ *
97
+ * `dependsOn` is the *edge* set: material references, any ordering edge a
98
+ * `serialize` verdict added, and the reader-after-writer edges that put a
99
+ * node behind whoever produces the paths it reads. Ordering edges are
100
+ * deliberately NOT part of the key — a node ordered behind another still
101
+ * computes the same result, so re-keying it would throw away a legitimate
102
+ * cache hit.
103
+ *
104
+ * `strategy` and `runtime` are this declaration's own preferences, recorded so
105
+ * a later elaboration can resolve a pair against them without re-reading the
106
+ * flow source.
107
+ *
108
+ * `generation` is 0 for nodes from {@link compile} and grows by one with each
109
+ * {@link append}.
110
+ *
111
+ * @since 0.1.0
112
+ * @category schemas
113
+ */
114
+ export const PlanNode = Schema.Struct({
115
+ id: Schema.NonEmptyString,
116
+ kind: NodeKind,
117
+ key: StoredKey,
118
+ material: KeyMaterial.KeyMaterial,
119
+ effects: NodeEffects,
120
+ dependsOn: Schema.Array(Schema.NonEmptyString),
121
+ conflicts: Schema.Array(ConflictAnnotation),
122
+ strategy: PairStrategy,
123
+ runtime: RuntimeStrategy,
124
+ priority: Schema.Int,
125
+ generation: Schema.Int
126
+ });
127
+ /**
128
+ * A plan: the whole keyed graph plus the digest an approval binds to.
129
+ *
130
+ * `nodes` follows material-dependency order within each generation. Inferred
131
+ * edges can point to later entries; schedule from the complete `dependsOn`
132
+ * graph, never by iterating the array alone.
133
+ *
134
+ * `baseDigest` is the digest at generation 0: what a human approved and what
135
+ * a `RUNNING` run pins. `digest` advances with every appended elaboration.
136
+ *
137
+ * Decoding checks only the shape. Use {@link verify} to check that keys,
138
+ * edges, and digests match the declarations.
139
+ *
140
+ * @since 0.1.0
141
+ * @category schemas
142
+ */
143
+ export const Plan = Schema.Struct({
144
+ planId: Schema.NonEmptyString,
145
+ flow: Schema.NonEmptyString,
146
+ generation: Schema.Int,
147
+ baseDigest: StoredKey,
148
+ digest: StoredKey,
149
+ nodes: Schema.Array(PlanNode)
150
+ });
151
+ /**
152
+ * A graph the compiler refuses. `code` names the rule:
153
+ *
154
+ * - `cycle`: material or inferred edges form a cycle.
155
+ * - `unknown_dependency`: a `Ref` names a node that is not in the plan.
156
+ * - `duplicate_node`: two nodes share an id.
157
+ * - `overlap_forbidden`: two unordered writers overlap and the pair's
158
+ * strategy is `fail`.
159
+ * - `invalid_effects`: a node both writes and removes one path.
160
+ * - `invalid_node`: a draft field, the plan id, or the flow name is malformed.
161
+ * - `invalid_plan`: {@link verify} found a plan that does not match its
162
+ * declarations.
163
+ * - `graph_too_large`: the plan exceeds {@link maximumPlanNodes} or the
164
+ * effect-analysis work budget.
165
+ *
166
+ * @since 0.1.0
167
+ * @category errors
168
+ */
169
+ export class PlanError extends Schema.TaggedError()("@smthrs/plan/PlanError", {
170
+ code: Schema.Literals([
171
+ "cycle",
172
+ "unknown_dependency",
173
+ "duplicate_node",
174
+ "overlap_forbidden",
175
+ "invalid_effects",
176
+ "invalid_node",
177
+ "invalid_plan",
178
+ "graph_too_large"
179
+ ]),
180
+ message: Schema.String
181
+ }) {
182
+ }
183
+ /**
184
+ * Maximum number of nodes retained by one compiled plan.
185
+ *
186
+ * Effect analysis also has a yielding work budget, since a node ceiling alone
187
+ * does not bound dense conflicts to practical work.
188
+ *
189
+ * @since 1.0.0
190
+ * @category limits
191
+ */
192
+ export const maximumPlanNodes = 10_000;
193
+ /** @private */
194
+ const graphSizeError = (size) => new PlanError({
195
+ code: "graph_too_large",
196
+ message: `A plan may contain at most ${maximumPlanNodes} nodes, received ${size}`
197
+ });
198
+ /**
199
+ * Topologically orders drafts by their MATERIAL dependencies — the only edges
200
+ * that exist before keys do.
201
+ *
202
+ * @private
203
+ */
204
+ const topological = (drafts, known) => {
205
+ const byId = new Map(drafts.map((draft) => [draft.id, draft]));
206
+ const ordered = [];
207
+ const state = new Map();
208
+ for (const draft of drafts) {
209
+ if (state.get(draft.id) === "done")
210
+ continue;
211
+ state.set(draft.id, "visiting");
212
+ const stack = [{ draft, dependencies: KeyMaterial.dependencies(draft.material), next: 0 }];
213
+ while (stack.length > 0) {
214
+ const frame = stack[stack.length - 1];
215
+ if (frame.next === frame.dependencies.length) {
216
+ state.set(frame.draft.id, "done");
217
+ ordered.push(frame.draft);
218
+ stack.pop();
219
+ continue;
220
+ }
221
+ const dependency = frame.dependencies[frame.next++];
222
+ if (known.has(dependency))
223
+ continue;
224
+ const next = byId.get(dependency);
225
+ if (next === undefined) {
226
+ return {
227
+ ok: false,
228
+ error: new PlanError({
229
+ code: "unknown_dependency",
230
+ message: `Node ${frame.draft.id} depends on unknown node ${dependency}`
231
+ })
232
+ };
233
+ }
234
+ const mark = state.get(next.id);
235
+ if (mark === "done")
236
+ continue;
237
+ if (mark === "visiting") {
238
+ return {
239
+ ok: false,
240
+ error: new PlanError({ code: "cycle", message: `Plan cycle through node ${next.id}` })
241
+ };
242
+ }
243
+ state.set(next.id, "visiting");
244
+ stack.push({ draft: next, dependencies: KeyMaterial.dependencies(next.material), next: 0 });
245
+ }
246
+ }
247
+ return { ok: true, drafts: ordered };
248
+ };
249
+ /**
250
+ * Runs the conflict and reader-after-writer passes and records what they found
251
+ * on every node outside `frozen`, whose rows an append never rewrites. A
252
+ * refused graph fails as a `PlanError` carrying the pass's code and message.
253
+ *
254
+ * @private
255
+ */
256
+ const annotate = (nodes, frozen, replayGenerations = false) => Conflicts.annotate(nodes, frozen.size, replayGenerations).pipe(Effect.mapError((refusal) => new PlanError(refusal)), Effect.map(({ conflicts, ordering }) => nodes.map((node) => {
257
+ if (frozen.has(node.id))
258
+ return node;
259
+ const added = ordering.get(node.id) ?? [];
260
+ return freezeNode({
261
+ ...node,
262
+ conflicts: conflicts.get(node.id) ?? [],
263
+ dependsOn: added.length === 0 ? node.dependsOn : [...node.dependsOn, ...added]
264
+ });
265
+ })));
266
+ /**
267
+ * The single approval projection. Its node list is the complete reviewable and
268
+ * behavior-bearing contract: id, kind, key, edges, conflict annotations,
269
+ * declared effects, conflict strategy, runtime strategy, and priority.
270
+ *
271
+ * @private
272
+ */
273
+ const approvalPayload = (planId, flow, nodes) => ({
274
+ body: { kind: "plan", planId, flow },
275
+ inputs: {
276
+ nodes: nodes.map((node) => ({
277
+ id: node.id,
278
+ kind: node.kind,
279
+ key: node.key,
280
+ dependsOn: node.dependsOn,
281
+ conflicts: node.conflicts,
282
+ effects: node.effects,
283
+ strategy: node.strategy,
284
+ runtime: node.runtime,
285
+ priority: node.priority
286
+ }))
287
+ },
288
+ layers: [],
289
+ capabilities: {}
290
+ });
291
+ /**
292
+ * The plan's digest: what an approval binds to. Deriving it only from
293
+ * {@link approvalPayload} keeps the approved field list in one place.
294
+ *
295
+ * @private
296
+ */
297
+ const digestOf = (planId, flow, nodes) => StepKey.content(approvalPayload(planId, flow, nodes));
298
+ /** @private */
299
+ const maximumDescriptionLength = 256;
300
+ /** @private */
301
+ const describeValue = (value) => {
302
+ const rendered = typeof value === "string" ? JSON.stringify(value) : Inspectable.toStringUnknown(value, 0);
303
+ return rendered.length > maximumDescriptionLength
304
+ ? `${rendered.slice(0, maximumDescriptionLength - 3)}...`
305
+ : rendered;
306
+ };
307
+ /** @private */
308
+ const describeNodeId = (id) => id.length > maximumDescriptionLength ? describeValue(id) : id;
309
+ /** @private */
310
+ const validateIdentity = (planId, flow) => {
311
+ if (typeof planId !== "string" || planId.length === 0) {
312
+ return new PlanError({
313
+ code: "invalid_node",
314
+ message: `Plan option planId must be a non-empty string, received ${describeValue(planId)}`
315
+ });
316
+ }
317
+ if (typeof flow !== "string" || flow.length === 0) {
318
+ return new PlanError({
319
+ code: "invalid_node",
320
+ message: `Plan option flow must be a non-empty string, received ${describeValue(flow)}`
321
+ });
322
+ }
323
+ return undefined;
324
+ };
325
+ /** Whether `value` is a container this module may safely copy. */
326
+ const isSnapshotContainer = (value) => {
327
+ if (typeof value !== "object" || value === null)
328
+ return false;
329
+ if (Array.isArray(value))
330
+ return true;
331
+ const prototype = Object.getPrototypeOf(value);
332
+ return prototype === Object.prototype || prototype === null;
333
+ };
334
+ /** Creates an empty container with the source container's supported prototype. */
335
+ const emptySnapshot = (source) => Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));
336
+ /**
337
+ * Copies and freezes plain structural containers without interpreting them as
338
+ * JSON. Shared references and cycles point at one cloned container through
339
+ * `memo`; every other value passes through by reference and remains unfrozen.
340
+ * In particular, this does not probe a `Planned` proxy. `validateDrafts`
341
+ * creates the inert material mirror inside the Effect while retaining that
342
+ * proxy, so the canonical serializer still reaches and refuses it.
343
+ */
344
+ const snapshot = (value) => {
345
+ const root = emptySnapshot(value);
346
+ const memo = new WeakMap([[value, root]]);
347
+ const pending = [{ source: value, target: root }];
348
+ const created = [root];
349
+ while (pending.length > 0) {
350
+ const { source, target } = pending.pop();
351
+ for (const key of Reflect.ownKeys(source)) {
352
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
353
+ if ("value" in descriptor && isSnapshotContainer(descriptor.value)) {
354
+ let child = memo.get(descriptor.value);
355
+ if (child === undefined) {
356
+ child = emptySnapshot(descriptor.value);
357
+ memo.set(descriptor.value, child);
358
+ pending.push({ source: descriptor.value, target: child });
359
+ created.push(child);
360
+ }
361
+ descriptor.value = child;
362
+ }
363
+ Object.defineProperty(target, key, descriptor);
364
+ }
365
+ }
366
+ for (const container of created)
367
+ Object.freeze(container);
368
+ return root;
369
+ };
370
+ /** Freezes one node built by this module while retaining its material snapshot. */
371
+ const freezeNode = (node) => Object.freeze({
372
+ ...node,
373
+ dependsOn: Object.freeze([...node.dependsOn]),
374
+ conflicts: Object.freeze(node.conflicts.map((conflict) => Object.freeze({ ...conflict, paths: Object.freeze([...conflict.paths]) })))
375
+ });
376
+ /** Plans whose complete immutable snapshot was created by this module. */
377
+ const frozenPlans = new WeakSet();
378
+ /** Freezes the plan envelope and its newly built node list. */
379
+ const freezePlan = (plan) => {
380
+ const frozen = Object.freeze({ ...plan, nodes: Object.freeze([...plan.nodes]) });
381
+ frozenPlans.add(frozen);
382
+ return frozen;
383
+ };
384
+ /**
385
+ * Validates the runtime-only parts of `NodeDraft` without replacing effect
386
+ * admission. Effect 4 Struct decoding strips excess properties and copies its
387
+ * schema arrays. The decoded effect declaration replaces any caller-supplied
388
+ * `material.effects`, and every accepted draft receives one deeply frozen JSON
389
+ * mirror for both storage and hashing.
390
+ *
391
+ * @private
392
+ */
393
+ const validateDrafts = (drafts) => Effect.forEach(drafts, (draft) => Effect.gen(function* () {
394
+ if (typeof draft.id !== "string" || draft.id.length === 0) {
395
+ return yield* Effect.fail(new PlanError({
396
+ code: "invalid_node",
397
+ message: `Node id must be a non-empty string, received ${describeValue(draft.id)}`
398
+ }));
399
+ }
400
+ const nodeId = describeNodeId(draft.id);
401
+ if (draft.priority !== undefined && !Number.isSafeInteger(draft.priority)) {
402
+ return yield* Effect.fail(new PlanError({
403
+ code: "invalid_node",
404
+ message: `Node ${nodeId} priority must be a safe integer, received ${describeValue(draft.priority)}`
405
+ }));
406
+ }
407
+ if (draft.kind !== undefined && !Schema.is(NodeKind)(draft.kind)) {
408
+ return yield* Effect.fail(new PlanError({
409
+ code: "invalid_node",
410
+ message: `Node ${nodeId} kind must be step, agent, or merge, received ${describeValue(draft.kind)}`
411
+ }));
412
+ }
413
+ if (draft.conflictStrategy !== undefined && !Schema.is(PairStrategy)(draft.conflictStrategy)) {
414
+ return yield* Effect.fail(new PlanError({
415
+ code: "invalid_node",
416
+ message: `Node ${nodeId} conflictStrategy must be serialize, lane, or fail, received ${describeValue(draft.conflictStrategy)}`
417
+ }));
418
+ }
419
+ if (draft.runtimeStrategy !== undefined && !Schema.is(RuntimeStrategy)(draft.runtimeStrategy)) {
420
+ return yield* Effect.fail(new PlanError({
421
+ code: "invalid_node",
422
+ message: `Node ${nodeId} runtimeStrategy must be delay-rebase or stop-merge, received ${describeValue(draft.runtimeStrategy)}`
423
+ }));
424
+ }
425
+ const decodedMaterial = yield* Schema.decodeUnknownEffect(KeyMaterial.KeyMaterial)(draft.material).pipe(Effect.mapError((cause) => new PlanError({
426
+ code: "invalid_node",
427
+ message: `Node ${nodeId} has invalid material: ${cause.message}`
428
+ })));
429
+ const decodedEffects = yield* Schema.decodeUnknownEffect(NodeEffects)(draft.effects).pipe(Effect.mapError((cause) => new PlanError({
430
+ code: "invalid_node",
431
+ message: `Node ${nodeId} has invalid effects: ${cause.message}`
432
+ })));
433
+ let material;
434
+ try {
435
+ material = snapshot(jsonMirror({ ...decodedMaterial, effects: decodedEffects }, (planned) => planned));
436
+ }
437
+ catch (cause) {
438
+ const path = cause instanceof GraphBuildError ? cause.path : [];
439
+ return yield* Effect.fail(new PlanError({
440
+ code: "invalid_node",
441
+ message: `Node ${nodeId} has invalid material payload at ${["$", ...path].join(".")}`
442
+ }));
443
+ }
444
+ return Object.freeze({
445
+ ...draft,
446
+ material,
447
+ effects: material.effects
448
+ });
449
+ }));
450
+ /**
451
+ * The effects schema admits each individual declaration in `validateDrafts`.
452
+ * This pass enforces the cross-field invariant that one path cannot be both a
453
+ * write and a removal.
454
+ *
455
+ * @private
456
+ */
457
+ const validateEffects = (id, effects) => {
458
+ const removes = effects.removes ?? [];
459
+ const writes = FileSet.expand(effects.writes);
460
+ for (const removal of removes) {
461
+ if (writes.some((entry) => FileSet.overlaps(entry, removal))) {
462
+ return new PlanError({
463
+ code: "invalid_effects",
464
+ message: `Node ${id} declares ${removal} as both a write and a removal`
465
+ });
466
+ }
467
+ }
468
+ return undefined;
469
+ };
470
+ /** @private */
471
+ const keyNodes = (drafts, existing, generation) => Effect.gen(function* () {
472
+ const digests = Object.create(null);
473
+ const known = new Set();
474
+ for (const node of existing) {
475
+ Object.defineProperty(digests, node.id, {
476
+ configurable: true,
477
+ enumerable: true,
478
+ value: node.key,
479
+ writable: true
480
+ });
481
+ known.add(node.id);
482
+ }
483
+ for (const draft of drafts) {
484
+ if (known.has(draft.id)) {
485
+ return yield* Effect.fail(new PlanError({ code: "duplicate_node", message: `Node ${draft.id} is already in the plan` }));
486
+ }
487
+ known.add(draft.id);
488
+ }
489
+ const sorted = topological(drafts, new Set(existing.map((node) => node.id)));
490
+ if (!sorted.ok)
491
+ return yield* Effect.fail(sorted.error);
492
+ const keyed = [];
493
+ for (const draft of sorted.drafts) {
494
+ const invalid = validateEffects(draft.id, draft.effects);
495
+ if (invalid !== undefined)
496
+ return yield* Effect.fail(invalid);
497
+ const key = yield* StepKey.planIdentity(draft.material, digests);
498
+ Object.defineProperty(digests, draft.id, {
499
+ configurable: true,
500
+ enumerable: true,
501
+ value: key,
502
+ writable: true
503
+ });
504
+ keyed.push(freezeNode({
505
+ id: draft.id,
506
+ kind: draft.kind ?? "step",
507
+ key,
508
+ material: draft.material,
509
+ effects: draft.effects,
510
+ dependsOn: KeyMaterial.dependencies(draft.material),
511
+ conflicts: [],
512
+ strategy: draft.conflictStrategy ?? "serialize",
513
+ runtime: draft.runtimeStrategy ?? "delay-rebase",
514
+ priority: draft.priority ?? 0,
515
+ generation
516
+ }));
517
+ }
518
+ return keyed;
519
+ });
520
+ /**
521
+ * Compiles drafts into a plan: material-dependency order, dependency-digest
522
+ * substitution, overlap annotation, and the plan digest. No I/O.
523
+ * Inferred edges extend `dependsOn` without reordering the node array.
524
+ *
525
+ * Traversal uses explicit stacks. Because the conflict and reader/writer
526
+ * passes consider a quadratic number of node pairs, plans are bounded by
527
+ * {@link maximumPlanNodes} and fail with `graph_too_large` above that limit
528
+ * or the effect-analysis work budget. Analysis yields periodically.
529
+ *
530
+ * The options and drafts are copied when `compile` is called, so later
531
+ * caller mutation does not reach the plan. The result is deeply frozen.
532
+ *
533
+ * @param options - `planId` and `flow` name the plan; `nodes` are the drafts.
534
+ * @returns The generation-0 plan, whose `baseDigest` equals its `digest`.
535
+ * Fails with {@link PlanError} for a refused graph, `KeyMaterialError` or
536
+ * `SchemaError` when a key cannot be derived.
537
+ * @since 0.1.0
538
+ * @category constructors
539
+ */
540
+ export const compile = (options) => {
541
+ const captured = snapshot(options);
542
+ return Effect.gen(function* () {
543
+ const invalidIdentity = validateIdentity(captured.planId, captured.flow);
544
+ if (invalidIdentity !== undefined)
545
+ return yield* Effect.fail(invalidIdentity);
546
+ if (captured.nodes.length > maximumPlanNodes)
547
+ return yield* Effect.fail(graphSizeError(captured.nodes.length));
548
+ const drafts = yield* validateDrafts(captured.nodes);
549
+ const keyed = yield* keyNodes(drafts, [], 0);
550
+ const nodes = yield* annotate(keyed, new Set());
551
+ const digest = yield* digestOf(captured.planId, captured.flow, nodes);
552
+ return freezePlan({
553
+ planId: captured.planId,
554
+ flow: captured.flow,
555
+ generation: 0,
556
+ baseDigest: digest,
557
+ digest,
558
+ nodes
559
+ });
560
+ });
561
+ };
562
+ /**
563
+ * Appends an elaborated subgraph to an existing plan.
564
+ *
565
+ * The plan GROWS; it is never invalidated. Nodes already in it keep their id,
566
+ * key, edges, and generation byte for byte, and the new nodes arrive pre-keyed
567
+ * against them, so a `hit` shows instantly. New nodes retain their material
568
+ * dependency order; scheduling must honor their complete `dependsOn` graph.
569
+ * Re-ordering after a reconciliation happens by re-keying *future* steps,
570
+ * never by rewriting history.
571
+ *
572
+ * A plan not produced by this module is checked with {@link verify} first.
573
+ *
574
+ * @param plan - The plan to grow.
575
+ * @param drafts - At least one new node. Ids must not repeat existing ones;
576
+ * `Ref` inputs may name existing nodes.
577
+ * @returns The plan with one more generation and a new `digest`. Fails with
578
+ * {@link PlanError} (`invalid_node` for an empty `drafts`, `invalid_plan` for a
579
+ * plan that fails verification), `KeyMaterialError`, or `SchemaError`.
580
+ * @since 0.1.0
581
+ * @category constructors
582
+ */
583
+ export const append = (plan, drafts) => {
584
+ const candidate = frozenPlans.has(plan) ? plan : snapshot(plan);
585
+ const capturedDrafts = snapshot(drafts);
586
+ return Effect.gen(function* () {
587
+ const invalidIdentity = validateIdentity(candidate.planId, candidate.flow);
588
+ if (invalidIdentity !== undefined)
589
+ return yield* Effect.fail(invalidIdentity);
590
+ const capturedPlan = yield* verify(candidate);
591
+ const nextSize = capturedPlan.nodes.length + capturedDrafts.length;
592
+ if (nextSize > maximumPlanNodes)
593
+ return yield* Effect.fail(graphSizeError(nextSize));
594
+ const validated = yield* validateDrafts(capturedDrafts);
595
+ if (validated.length === 0) {
596
+ return yield* Effect.fail(new PlanError({
597
+ code: "invalid_node",
598
+ message: `Plan ${capturedPlan.planId} append requires at least one draft`
599
+ }));
600
+ }
601
+ const generation = capturedPlan.generation + 1;
602
+ const keyed = yield* keyNodes(validated, capturedPlan.nodes, generation);
603
+ const nodes = yield* annotate([...capturedPlan.nodes, ...keyed], new Set(capturedPlan.nodes.map((node) => node.id)));
604
+ const digest = yield* digestOf(capturedPlan.planId, capturedPlan.flow, nodes);
605
+ return freezePlan({ ...capturedPlan, generation, digest, nodes });
606
+ });
607
+ };
608
+ /**
609
+ * Verifies an imported plan against the same key and topology rules as the
610
+ * compiler. Valid compiler-owned immutable values need no second compilation.
611
+ *
612
+ * Generation boundaries are replayed when reconstructing conflict annotations:
613
+ * an append may annotate new nodes, but cannot rewrite an earlier generation.
614
+ * Recorded material-dependency order is verified without sorting inferred edges.
615
+ * Keys and approval digests retain their existing format. The returned snapshot
616
+ * is immutable; later caller mutation cannot change the verified value.
617
+ *
618
+ * @since 1.0.0
619
+ * @category validation
620
+ */
621
+ export const verify = (input) => Effect.gen(function* () {
622
+ if (typeof input === "object" && input !== null && frozenPlans.has(input))
623
+ return input;
624
+ // Check the array ceiling before schema decoding copies its members.
625
+ if (typeof input === "object" && input !== null && "nodes" in input && Array.isArray(input.nodes)) {
626
+ if (input.nodes.length > maximumPlanNodes)
627
+ return yield* Effect.fail(graphSizeError(input.nodes.length));
628
+ }
629
+ const decoded = yield* Schema.decodeUnknownEffect(Plan)(input);
630
+ const invalid = (message) => new PlanError({ code: "invalid_plan", message });
631
+ if (!Number.isSafeInteger(decoded.generation) || decoded.generation < 0 || decoded.generation > decoded.nodes.length) {
632
+ return yield* Effect.fail(invalid("Plan generation must be a non-negative safe integer with a nonempty appended generation"));
633
+ }
634
+ const generations = new Map();
635
+ let previous = 0;
636
+ for (const node of decoded.nodes) {
637
+ if (!Number.isSafeInteger(node.generation) || node.generation < previous || node.generation > previous + 1) {
638
+ return yield* Effect.fail(invalid(`Node ${node.id} has an invalid or out-of-order generation`));
639
+ }
640
+ generations.set(node.id, node.generation);
641
+ previous = node.generation;
642
+ }
643
+ if (previous !== decoded.generation) {
644
+ return yield* Effect.fail(invalid("Plan generation does not match its newest nodes"));
645
+ }
646
+ for (const node of decoded.nodes) {
647
+ for (const dependency of KeyMaterial.dependencies(node.material)) {
648
+ const generation = generations.get(dependency);
649
+ if (generation !== undefined && generation > node.generation) {
650
+ return yield* Effect.fail(invalid(`Node ${node.id} refers to a future generation`));
651
+ }
652
+ }
653
+ }
654
+ const drafts = yield* validateDrafts(decoded.nodes.map((node) => ({
655
+ id: node.id,
656
+ kind: node.kind,
657
+ material: node.material,
658
+ effects: node.effects,
659
+ conflictStrategy: node.strategy,
660
+ runtimeStrategy: node.runtime,
661
+ priority: node.priority
662
+ })));
663
+ const keyed = (yield* keyNodes(drafts, [], 0)).map((node) => freezeNode({ ...node, generation: generations.get(node.id) }));
664
+ // Replay boundaries within one annotation pass, retaining its expansion
665
+ // map, candidate trie, inferred graph and reachability cache throughout.
666
+ const nodes = yield* annotate(keyed, new Set(), true);
667
+ const baseDigest = yield* digestOf(decoded.planId, decoded.flow, nodes.filter((node) => node.generation === 0));
668
+ const digest = decoded.generation === 0 ? baseDigest : yield* digestOf(decoded.planId, decoded.flow, nodes);
669
+ if (decoded.baseDigest !== baseDigest || decoded.digest !== digest) {
670
+ return yield* Effect.fail(invalid("Plan approval digest does not match its compiled content"));
671
+ }
672
+ // Compare the complete node contract, including material and generation,
673
+ // rather than trusting the claimed keys or the approval projection alone.
674
+ const hash = Schema.decodeUnknownEffect(DerivedKey);
675
+ if ((yield* hash(decoded.nodes)) !== (yield* hash(nodes))) {
676
+ return yield* Effect.fail(invalid("Plan nodes do not match their compiled keys, effects, ordering, or generations"));
677
+ }
678
+ return freezePlan({ ...decoded, nodes });
679
+ });
680
+ /**
681
+ * The nodes added by the newest generation: what {@link module:PlanStore}
682
+ * appends and what the `subgraph-appended` journal record names.
683
+ *
684
+ * @param plan - A plan.
685
+ * @returns The nodes whose generation equals `plan.generation`, in order.
686
+ * @since 0.1.0
687
+ * @category accessors
688
+ */
689
+ export const generationNodes = (plan) => plan.nodes.filter((node) => node.generation === plan.generation);
690
+ /**
691
+ * Whether `input` is a compiler-owned immutable snapshot that already passed
692
+ * {@link verify}: such values take verify's trusted fast path and need no
693
+ * second schema validation.
694
+ *
695
+ * @param input - Any value.
696
+ * @returns `true` only for a plan returned by {@link compile},
697
+ * {@link append}, or {@link verify}; a structurally equal copy returns `false`.
698
+ * @since 1.0.0
699
+ * @category guards
700
+ */
701
+ export const isVerified = (input) => typeof input === "object" && input !== null && frozenPlans.has(input);
702
+ /**
703
+ * The approval digest of every generation before the newest: the digest this
704
+ * plan carried before its last append. {@link module:PlanStore}'s append
705
+ * matches it against the stored envelope, so an append proves the recorded
706
+ * plan's integrity from the already-verified prefix instead of decoding and
707
+ * re-verifying every stored row.
708
+ *
709
+ * For a generation-0 plan no generation precedes the newest, so this is the
710
+ * digest of an empty node list.
711
+ *
712
+ * @param plan - A plan.
713
+ * @returns The approval digest of the nodes older than `plan.generation`.
714
+ * @since 1.0.0
715
+ * @category accessors
716
+ */
717
+ export const prefixDigest = (plan) => digestOf(plan.planId, plan.flow, plan.nodes.filter((node) => node.generation < plan.generation));
718
+ //# sourceMappingURL=Plan.js.map