@feltdb/feltkit 0.3.18 → 0.3.20

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 (130) hide show
  1. package/dist/app.d.ts +57 -14
  2. package/dist/app.js +71 -9
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +25 -0
  5. package/dist/appboundry/build.js +10 -1
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest.js +18 -2
  8. package/dist/appboundry/guest.js.map +1 -1
  9. package/dist/appboundry/host.js +3 -0
  10. package/dist/appboundry/host.js.map +1 -1
  11. package/dist/cli/compose.d.ts +31 -0
  12. package/dist/cli/compose.js +274 -0
  13. package/dist/cli/compose.js.map +1 -0
  14. package/dist/cli/create.d.ts +201 -0
  15. package/dist/cli/create.js +1139 -0
  16. package/dist/cli/create.js.map +1 -0
  17. package/dist/cli/deploy.d.ts +1 -0
  18. package/dist/cli/deploy.js +66 -6
  19. package/dist/cli/deploy.js.map +1 -1
  20. package/dist/cli/domain.d.ts +174 -0
  21. package/dist/cli/domain.js +1119 -0
  22. package/dist/cli/domain.js.map +1 -0
  23. package/dist/cli/main.d.ts +2 -0
  24. package/dist/cli/main.js +135 -6
  25. package/dist/cli/main.js.map +1 -1
  26. package/dist/cli/shell.d.ts +7 -0
  27. package/dist/cli/shell.js +59 -0
  28. package/dist/cli/shell.js.map +1 -0
  29. package/dist/component.d.ts +174 -0
  30. package/dist/component.js +77 -0
  31. package/dist/component.js.map +1 -0
  32. package/dist/composition/catalog.d.ts +3 -0
  33. package/dist/composition/catalog.js +217 -0
  34. package/dist/composition/catalog.js.map +1 -0
  35. package/dist/composition/contract.d.ts +165 -0
  36. package/dist/composition/contract.js +12 -0
  37. package/dist/composition/contract.js.map +1 -0
  38. package/dist/composition/execute.d.ts +110 -0
  39. package/dist/composition/execute.js +350 -0
  40. package/dist/composition/execute.js.map +1 -0
  41. package/dist/composition/generate.d.ts +105 -0
  42. package/dist/composition/generate.js +274 -0
  43. package/dist/composition/generate.js.map +1 -0
  44. package/dist/composition/plan.d.ts +131 -0
  45. package/dist/composition/plan.js +558 -0
  46. package/dist/composition/plan.js.map +1 -0
  47. package/dist/composition/profiles.d.ts +20 -0
  48. package/dist/composition/profiles.js +81 -0
  49. package/dist/composition/profiles.js.map +1 -0
  50. package/dist/composition/reconcile.d.ts +153 -0
  51. package/dist/composition/reconcile.js +282 -0
  52. package/dist/composition/reconcile.js.map +1 -0
  53. package/dist/composition/recover.d.ts +89 -0
  54. package/dist/composition/recover.js +407 -0
  55. package/dist/composition/recover.js.map +1 -0
  56. package/dist/composition/resolve.d.ts +2 -0
  57. package/dist/composition/resolve.js +208 -0
  58. package/dist/composition/resolve.js.map +1 -0
  59. package/dist/dashboard/assets/{index-DnIOVGF-.js → index-BrC1AtZ1.js} +5 -5
  60. package/dist/dashboard/index.html +1 -1
  61. package/dist/docs.d.ts +1 -1
  62. package/dist/docs.js +1 -0
  63. package/dist/docs.js.map +1 -1
  64. package/dist/index.d.ts +4 -0
  65. package/dist/index.js +2 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/runtime/activity.d.ts +8 -1
  68. package/dist/runtime/activity.js.map +1 -1
  69. package/dist/runtime/audit.d.ts +43 -0
  70. package/dist/runtime/audit.js +52 -0
  71. package/dist/runtime/audit.js.map +1 -0
  72. package/dist/runtime/claims.d.ts +76 -0
  73. package/dist/runtime/claims.js +100 -0
  74. package/dist/runtime/claims.js.map +1 -0
  75. package/dist/runtime/context.d.ts +6 -5
  76. package/dist/runtime/contract.js +4 -1
  77. package/dist/runtime/contract.js.map +1 -1
  78. package/dist/runtime/data.d.ts +14 -2
  79. package/dist/runtime/data.js +62 -23
  80. package/dist/runtime/data.js.map +1 -1
  81. package/dist/runtime/escape-hatch.d.ts +37 -0
  82. package/dist/runtime/escape-hatch.js +76 -0
  83. package/dist/runtime/escape-hatch.js.map +1 -0
  84. package/dist/runtime/instance.js +2 -1
  85. package/dist/runtime/instance.js.map +1 -1
  86. package/dist/runtime/outbox.js +3 -0
  87. package/dist/runtime/outbox.js.map +1 -1
  88. package/dist/runtime/runtime.d.ts +33 -0
  89. package/dist/runtime/runtime.js +127 -12
  90. package/dist/runtime/runtime.js.map +1 -1
  91. package/dist/runtime/services-rules.d.ts +12 -0
  92. package/dist/runtime/services-rules.js +8 -0
  93. package/dist/runtime/services-rules.js.map +1 -0
  94. package/dist/runtime/services.js +5 -3
  95. package/dist/runtime/services.js.map +1 -1
  96. package/dist/runtime/tenancy.d.ts +13 -4
  97. package/dist/runtime/tenancy.js +30 -9
  98. package/dist/runtime/tenancy.js.map +1 -1
  99. package/dist/runtime/transactions.d.ts +38 -1
  100. package/dist/runtime/transactions.js +20 -5
  101. package/dist/runtime/transactions.js.map +1 -1
  102. package/dist/server/admin.js +52 -0
  103. package/dist/server/admin.js.map +1 -1
  104. package/dist/server/components.d.ts +44 -0
  105. package/dist/server/components.js +212 -0
  106. package/dist/server/components.js.map +1 -0
  107. package/dist/server/index.d.ts +2 -0
  108. package/dist/server/index.js +24 -5
  109. package/dist/server/index.js.map +1 -1
  110. package/dist/server/project.d.ts +27 -0
  111. package/dist/server/project.js +63 -0
  112. package/dist/server/project.js.map +1 -1
  113. package/dist/server/public.d.ts +2 -0
  114. package/dist/server/public.js +2 -0
  115. package/dist/server/public.js.map +1 -1
  116. package/dist/testing/index.d.ts +12 -0
  117. package/dist/testing/index.js +15 -0
  118. package/dist/testing/index.js.map +1 -1
  119. package/docs/ARCHITECTURE.md +1 -1
  120. package/docs/AUTH.md +8 -3
  121. package/docs/COMPONENTS.md +91 -0
  122. package/docs/GUARANTEES.md +24 -4
  123. package/docs/README.md +3 -2
  124. package/docs/RESOLVER.md +4 -2
  125. package/docs/SECURITY.md +2 -2
  126. package/docs/TRANSACTIONS.md +1 -1
  127. package/package.json +14 -12
  128. package/skills/.claude-plugin/marketplace.json +1 -1
  129. package/skills/.claude-plugin/plugin.json +1 -1
  130. package/skills/feltkit-services/SKILL.md +1 -1
@@ -0,0 +1,558 @@
1
+ /**
2
+ * Planning (M4): from the application's current composition and a target, what would have to change,
3
+ * what it would affect, and what decisions stand in the way. A plan is a derived, versioned, read-only
4
+ * representation (`feltkit.composition-plan/1`): it executes nothing, writes nothing, and is not an
5
+ * authority for anything. The record and lock stay the composition's authorities (generate.ts); the
6
+ * application stays the authority for its own declaration (reconcile.ts reads it, nothing more).
7
+ *
8
+ * The planner reuses what exists: `reconcile()` for the current state and the application's
9
+ * consumption of the foundation, `generateFoundation()` to resolve and validate the target (the
10
+ * resolver and the SDK's own `feltkit({...})` checks), and the on-disk declaration for the current
11
+ * foundation. It compares as data, path by path. Where a change touches application-owned behavior,
12
+ * an authorization or identity boundary, or something the planner cannot see, the operation is
13
+ * `REVIEW_REQUIRED`, never silently deterministic. A target the profile, catalog or resolver cannot
14
+ * express is `UNSUPPORTED`, never approximated.
15
+ */
16
+ import { readFileSync } from "node:fs";
17
+ import { join, relative, sep } from "node:path";
18
+ import { backendModules } from "../runtime/loader.js";
19
+ import { CATALOG } from "./catalog.js";
20
+ import { DECLARATION_PATH, GENERATOR, LOCK_PATH, RECORD_PATH, canonical, generateFoundation, sha256, } from "./generate.js";
21
+ import { PROFILES } from "./profiles.js";
22
+ import { APPLICATION_DECLARATION, RECONCILIATION_FORMAT, RECONCILIATION_RULES, get, leaves, loadFoundation, reconcile } from "./reconcile.js";
23
+ export const PLAN_FORMAT = "feltkit.composition-plan/1";
24
+ /** The planning rules. Bumped when the same inputs would plan differently (2: the plan carries the application sources' hashes; 3: a change of profile is an UNSUPPORTED operation, and a required capability's exclusion names the profile without it). */
25
+ export const PLAN_RULES = 3;
26
+ // ── The graph ────────────────────────────────────────────────────────────────
27
+ /** Dependencies first, then by id. Throws on a cycle or a dependency that is not in the plan. */
28
+ export function orderOperations(operations) {
29
+ const ids = new Set(operations.map((o) => o.id));
30
+ if (ids.size !== operations.length)
31
+ throw new Error("duplicate operation id");
32
+ const byId = new Map(operations.map((o) => [o.id, o]));
33
+ for (const o of operations)
34
+ for (const d of o.dependsOn)
35
+ if (!ids.has(d))
36
+ throw new Error(`${o.id} depends on ${d}, which is not in the plan`);
37
+ // Kahn's algorithm by levels: everything whose dependencies are done, sorted by id, then the next level.
38
+ const order = [];
39
+ const done = new Set();
40
+ let pending = [...ids].sort();
41
+ while (pending.length) {
42
+ const ready = pending.filter((id) => byId.get(id).dependsOn.every((d) => done.has(d)));
43
+ if (!ready.length)
44
+ throw new Error(`cycle among ${pending.join(", ")}`);
45
+ for (const id of ready) {
46
+ order.push(id);
47
+ done.add(id);
48
+ }
49
+ pending = pending.filter((id) => !done.has(id));
50
+ }
51
+ return order;
52
+ }
53
+ // ── Boundaries and decisions ─────────────────────────────────────────────────
54
+ /** Declaration paths whose change alters who may do what, or who is who. Always a person's decision. */
55
+ const AUTHORITY_PATH = /^(roles(\.|$)|auth\.tenant\.(roles|name|claims|create)(\.|$)|auth\.accounts\.roles(\.|$))/;
56
+ const show = (v) => (v === undefined ? "absent" : JSON.stringify(v));
57
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
58
+ function describe(e) {
59
+ return `${e.code}${e.capability ? ` ${e.capability}${e.parameter ? `.${e.parameter}` : ""}` : ""}${e.path ? ` ${e.path}` : ""}: ${e.message}`;
60
+ }
61
+ /** A target the composition model cannot express, as opposed to one it refuses. */
62
+ const UNSUPPORTED_CODES = new Set(["UNKNOWN_PROFILE", "UNKNOWN_CAPABILITY", "NOT_IN_PROFILE", "UNKNOWN_PARAMETER"]);
63
+ /** A target that needs a choice nobody has made. */
64
+ const DECISION_CODES = new Set(["MISSING_PARAMETER"]);
65
+ // ── Planning ─────────────────────────────────────────────────────────────────
66
+ /**
67
+ * Plan from the application in `projectDir` to `request` (an overlay on the recorded inputs), or, with
68
+ * no request, to the target the installed definitions imply for the recorded inputs. Reads only.
69
+ */
70
+ export async function planComposition(projectDir, request = {}, options = {}) {
71
+ const catalog = options.catalog ?? CATALOG;
72
+ const profiles = options.profiles ?? PROFILES;
73
+ const report = await reconcile(projectDir, { ...options, catalog, profiles });
74
+ const recorded = report.recorded;
75
+ const ops = [];
76
+ const add = (o) => {
77
+ const op = { id: `${o.type}:${o.target}`, ...o };
78
+ ops.push(op);
79
+ return op;
80
+ };
81
+ // The current inputs, from the record (reconcile already parsed it; it is the authority for them).
82
+ const currentInputs = recorded.profile ? await currentInputsOf(projectDir) : null;
83
+ const explicit = request.profile !== undefined || (request.include?.length ?? 0) > 0 || (request.exclude?.length ?? 0) > 0 || Object.keys(request.params ?? {}).length > 0;
84
+ const base = currentInputs ?? { profile: request.profile ?? "", include: [], params: {} };
85
+ const targetInputs = {
86
+ profile: request.profile ?? base.profile,
87
+ include: [...new Set([...base.include.filter((c) => !(request.exclude ?? []).includes(c)), ...(request.include ?? [])])].sort(),
88
+ params: mergeParams(base.params, request.params ?? {}),
89
+ };
90
+ const targetHash = sha256(canonical({ profile: targetInputs.profile, include: targetInputs.include, params: JSON.parse(canonical(targetInputs.params)) }));
91
+ // 0a. A different profile for a composed application: a change of its identity or tenancy boundary (workspaces
92
+ // appearing or disappearing under existing data and memberships). Not a migration FeltKit performs: UNSUPPORTED,
93
+ // never approximated by regenerating the declaration under the other profile.
94
+ const targetProfile = profiles.get(targetInputs.profile);
95
+ if (currentInputs && request.profile !== undefined && request.profile !== currentInputs.profile) {
96
+ const from = profiles.get(currentInputs.profile);
97
+ add({
98
+ type: "change-profile",
99
+ classification: "UNSUPPORTED",
100
+ boundary: "capability-dependency",
101
+ target: `${currentInputs.profile}->${request.profile}`,
102
+ current: currentInputs.profile,
103
+ proposed: request.profile,
104
+ reason: "Requested by the target.",
105
+ evidence: [`${RECORD_PATH} profile ${currentInputs.profile}`, `${from ? `requires ${from.required.join(", ")}` : "profile not installed"}`, `${targetProfile ? `${request.profile} requires ${targetProfile.required.join(", ")}` : `${request.profile} is not an installed profile`}`],
106
+ dependsOn: [],
107
+ preconditions: [],
108
+ expected: "Not expressible.",
109
+ validation: { before: [], after: [] },
110
+ decision: `Changing the foundation from ${currentInputs.profile} to ${request.profile} would ${from?.required.includes("workspace.tenancy") && !targetProfile?.required.includes("workspace.tenancy") ? "remove workspaces, memberships and invitations from under the application's data" : !from?.required.includes("workspace.tenancy") && targetProfile?.required.includes("workspace.tenancy") ? "put workspaces, memberships and invitations under data that has none" : "change what identity and tenancy mean for the application"}. FeltKit does not migrate between foundations: compose a new application with the other profile and move the data deliberately.`,
111
+ });
112
+ }
113
+ // 0b. An exclusion the model cannot express: a required capability, or one that is not selected.
114
+ for (const id of [...new Set(request.exclude ?? [])].sort()) {
115
+ const required = targetProfile?.required.includes(id) ?? false;
116
+ const selected = base.include.includes(id) || required;
117
+ if (!required && selected)
118
+ continue;
119
+ add({
120
+ type: "remove-capability",
121
+ classification: "UNSUPPORTED",
122
+ boundary: "capability-dependency",
123
+ target: id,
124
+ current: required ? `${id} (required by ${targetInputs.profile})` : "not selected",
125
+ proposed: "not selected",
126
+ reason: "Requested by the target.",
127
+ evidence: required ? [`profile ${targetInputs.profile} requires ${id}`] : [`${RECORD_PATH} include does not list ${id}`],
128
+ dependsOn: [],
129
+ preconditions: [],
130
+ expected: "Not expressible.",
131
+ validation: { before: [], after: [] },
132
+ decision: required ? `${id} is required by the ${targetInputs.profile} profile: no composition of this profile is without it. ${[...profiles.values()].filter((p) => !p.required.includes(id)).map((p) => p.id).join(", ") ? `A profile without it exists (${[...profiles.values()].filter((p) => !p.required.includes(id)).map((p) => p.id).join(", ")}), but a composed application does not change profile (see change-profile).` : "No profile is without it."}` : `${id} is not part of the recorded composition; there is nothing to remove.`,
133
+ });
134
+ }
135
+ // 1. Resolve and validate the target (pure: nothing is written).
136
+ const target = generateFoundation(targetInputs, catalog, profiles);
137
+ const resolveErrors = target.ok ? [] : target.errors;
138
+ const unsupported = resolveErrors.filter((e) => UNSUPPORTED_CODES.has(e.code));
139
+ const decisions = resolveErrors.filter((e) => DECISION_CODES.has(e.code));
140
+ const sdkRejects = resolveErrors.filter((e) => e.code === "DECLARATION_INVALID" || e.code === "UNSUPPORTED_OPTION");
141
+ const otherRefusals = resolveErrors.filter((e) => !UNSUPPORTED_CODES.has(e.code) && !DECISION_CODES.has(e.code) && e.code !== "DECLARATION_INVALID" && e.code !== "UNSUPPORTED_OPTION");
142
+ const resolveOp = add({
143
+ type: "resolve-target",
144
+ classification: unsupported.length ? "UNSUPPORTED" : decisions.length || otherRefusals.length ? "BLOCKED" : "DETERMINISTIC",
145
+ boundary: "capability-dependency",
146
+ target: targetInputs.profile || "(no profile)",
147
+ current: recorded.composition ?? undefined,
148
+ proposed: target.ok ? target.record.composition : undefined,
149
+ reason: explicit ? "The requested target must resolve against the installed profile and catalog." : "The recorded inputs are resolved against the installed definitions (the implied target).",
150
+ evidence: [`target inputs ${targetHash}`, ...(recorded.inputs ? [`recorded inputs ${recorded.inputs}`] : []), ...resolveErrors.filter((e) => e.code !== "DECLARATION_INVALID" && e.code !== "UNSUPPORTED_OPTION").map(describe)],
151
+ dependsOn: [],
152
+ preconditions: ["The installed FeltKit's catalog and profile are the ones the change is meant for."],
153
+ expected: target.ok ? `Capabilities ${target.resolved.capabilities.map((c) => `${c.id}@${c.version}`).join(", ")}.` : "The target does not resolve.",
154
+ validation: { before: [], after: ["resolveComposition accepts the target"] },
155
+ ...(unsupported.length ? { decision: `The target is outside what the ${targetInputs.profile || "profile"} and catalog can express: ${unsupported.map(describe).join("; ")}` } : {}),
156
+ ...(decisions.length ? { decision: `A parameter must be chosen: ${decisions.map((e) => `${e.capability}.${e.parameter} (${e.hint})`).join("; ")}` } : {}),
157
+ ...(otherRefusals.length && !decisions.length ? { decision: otherRefusals.map(describe).join("; ") } : {}),
158
+ });
159
+ add({
160
+ type: "validate-target",
161
+ classification: !target.ok && !sdkRejects.length ? "BLOCKED" : sdkRejects.length ? "BLOCKED" : "DETERMINISTIC",
162
+ boundary: "sdk-contract",
163
+ target: `feltkit ${report.installed.sdk}`,
164
+ current: recorded.sdk ? `recorded against FeltKit ${recorded.sdk}` : undefined,
165
+ proposed: `validated by FeltKit ${report.installed.sdk} (${GENERATOR})`,
166
+ reason: "The SDK's own declaration checks (feltkit({...})) must accept the target foundation.",
167
+ evidence: sdkRejects.length ? sdkRejects.map(describe) : target.ok ? ["feltkit({...}) accepted the resolved target"] : ["not reached: the target did not resolve"],
168
+ dependsOn: [resolveOp.id],
169
+ preconditions: [],
170
+ expected: "feltkit({ name, ...foundation }) raises no declaration error.",
171
+ validation: { before: [], after: ["feltkit({...}) accepts the target", "`feltkit build` succeeds with the regenerated foundation"] },
172
+ ...(sdkRejects.length ? { decision: `This FeltKit rejects the target: ${sdkRejects.map((e) => e.message).join("; ")}` } : !target.ok ? { decision: "Not reached: the target did not resolve." } : {}),
173
+ });
174
+ // 2. The current generated state must be intact before anything may be regenerated.
175
+ const stateCodes = report.findings.filter((f) => ["GENERATED_FILE_MODIFIED", "GENERATED_FILE_MISSING", "RECORD_MISSING", "LOCK_MISSING", "INCOMPLETE", "NOT_COMPOSED", "INCOMPATIBLE"].includes(f.state));
176
+ const verifyOp = add({
177
+ type: "verify-current-state",
178
+ classification: stateCodes.length ? "BLOCKED" : "DETERMINISTIC",
179
+ boundary: "composition-lock",
180
+ target: LOCK_PATH,
181
+ current: `reconciliation ${report.state}`,
182
+ proposed: "reconciliation CURRENT, GENERATION_STALE or DEFINITION_CHANGED (an intact generated state)",
183
+ reason: "Only files that are exactly what `feltkit compose` wrote may be regenerated; anything else is someone's unrecorded work or missing provenance.",
184
+ evidence: report.findings.length ? report.findings.map((f) => `${f.state}/${f.code}${f.paths.length ? ` ${f.paths.join(",")}` : ""}`) : [`reconciliation CURRENT; ${DECLARATION_PATH} ${report.observed.files[DECLARATION_PATH]}`],
185
+ dependsOn: [],
186
+ preconditions: [`${RECORD_PATH}, ${LOCK_PATH} and ${DECLARATION_PATH} are present, well-formed and match the lock.`],
187
+ expected: "The generated state is intact and its provenance is known.",
188
+ validation: { before: ["`feltkit compose --check` or `feltkit compose reconcile` shows no file problem"], after: [] },
189
+ ...(stateCodes.length ? { decision: `Not planned past this point: ${stateCodes.map((f) => `${f.code} (${f.paths.join(", ") || f.state}): ${f.next[0] ?? ""}`).join("; ")}. Repair is a person's action, never implied by a plan.` } : {}),
190
+ });
191
+ const stateIntact = !stateCodes.length;
192
+ // 3. Capabilities and parameters: current (recorded) against target (resolved).
193
+ const currentCaps = new Map(recorded.capabilities.map((c) => [c.id, c]));
194
+ const targetCaps = new Map(target.ok ? target.resolved.capabilities.map((c) => [c.id, c]) : []);
195
+ const consumption = report.application.status === "analyzed" ? report.application.consumption ?? {} : null;
196
+ const extensions = report.application.additions ?? [];
197
+ if (target.ok) {
198
+ for (const [id, cap] of [...targetCaps].sort(([a], [b]) => a.localeCompare(b))) {
199
+ if (!currentCaps.has(id)) {
200
+ const def = catalog.get(id);
201
+ add({
202
+ type: "add-capability",
203
+ classification: "DETERMINISTIC",
204
+ boundary: "capability-dependency",
205
+ target: id,
206
+ current: "not selected",
207
+ proposed: `${id}@${cap.version} with ${JSON.stringify(cap.params)}`,
208
+ reason: explicit ? "Requested by the target." : "Selected by the recorded inputs under the installed profile.",
209
+ evidence: [`profile ${targetInputs.profile} lists ${id}`, `requires ${def.requires.join(", ") || "nothing"}`, `contributes ${Object.keys(leaves(def.contribute(cap.params, { has: (x) => targetCaps.has(x), params: (x) => targetCaps.get(x)?.params ?? {} }))).join(", ") || "nothing"}`],
210
+ dependsOn: [resolveOp.id],
211
+ preconditions: def.requires.length ? [`${def.requires.join(", ")} selected`] : [],
212
+ expected: `${id} is part of the composition; its declaration paths are generated.`,
213
+ validation: { before: [], after: ["the regenerated declaration carries the capability's paths"] },
214
+ });
215
+ }
216
+ }
217
+ for (const [id, cap] of [...currentCaps].sort(([a], [b]) => a.localeCompare(b))) {
218
+ if (!targetCaps.has(id)) {
219
+ const def = catalog.get(id);
220
+ const contributed = def && currentInputs ? Object.keys(leaves(def.contribute(paramsFor(def, currentInputs, id), { has: (x) => currentCaps.has(x), params: (x) => paramsFor(catalog.get(x), currentInputs, x) }))) : [];
221
+ const extended = contributed.filter((p) => consumption?.[p] === "extended" || consumption?.[p] === "overridden" || extensions.some((a) => a.startsWith(`${p}.`) || a === p));
222
+ const dependents = [...targetCaps.keys()].filter((t) => catalog.get(t)?.requires.includes(id));
223
+ add({
224
+ type: "remove-capability",
225
+ classification: dependents.length ? "BLOCKED" : extended.length || contributed.some((p) => AUTHORITY_PATH.test(p)) ? "REVIEW_REQUIRED" : "DETERMINISTIC",
226
+ boundary: extended.length ? "application-declaration" : "capability-dependency",
227
+ target: id,
228
+ current: `${id}@${cap.version}`,
229
+ proposed: "not selected",
230
+ reason: "Removed by the target.",
231
+ evidence: [`contributed ${contributed.join(", ") || "nothing"}`, ...(consumption ? contributed.map((p) => `${p}: ${consumption[p] ?? "not in the foundation"} by ${APPLICATION_DECLARATION}`) : ["application not analyzed"]), ...(dependents.length ? [`required by ${dependents.join(", ")}`] : [])],
232
+ dependsOn: [resolveOp.id],
233
+ preconditions: dependents.length ? [`${dependents.join(", ")} removed first or kept out of the target`] : [],
234
+ expected: `${id}'s paths leave the generated declaration.`,
235
+ validation: { before: [], after: ["`feltkit compose reconcile` shows no FOUNDATION_* finding for the removed paths", "the application's tests pass"] },
236
+ ...(dependents.length ? { decision: `${dependents.join(", ")} requires ${id}: the resolver will refuse the target.` } : extended.length ? { decision: `${APPLICATION_DECLARATION} extends or overrides ${extended.join(", ")}: decide what the application keeps once the foundation stops providing them.` } : contributed.some((p) => AUTHORITY_PATH.test(p)) ? { decision: `Removing ${id} changes authorization or identity paths (${contributed.filter((p) => AUTHORITY_PATH.test(p)).join(", ")}).` } : {}),
237
+ });
238
+ }
239
+ else {
240
+ const t = targetCaps.get(id);
241
+ const installed = report.installed.capabilities.find((c) => c.id === id);
242
+ const lockedFp = recorded.capabilities.find((c) => c.id === id)?.fingerprint ?? null;
243
+ const currentParams = currentInputs ? paramsFor(catalog.get(id), currentInputs, id) : null;
244
+ if (cap.version !== t.version || (lockedFp && installed?.fingerprint && lockedFp !== installed.fingerprint)) {
245
+ add({
246
+ type: "update-capability",
247
+ classification: "DETERMINISTIC",
248
+ boundary: "capability-dependency",
249
+ target: id,
250
+ current: `${id}@${cap.version}${lockedFp ? ` ${lockedFp}` : ""}`,
251
+ proposed: `${id}@${t.version}${installed?.fingerprint ? ` ${installed.fingerprint}` : ""}`,
252
+ reason: cap.version !== t.version ? "The installed capability is a new contract version." : "The installed capability's definition (parameters, dependencies or conflicts) changed.",
253
+ evidence: [`lock fingerprint ${lockedFp ?? "none"}`, `installed fingerprint ${installed?.fingerprint ?? "none"}`],
254
+ dependsOn: [resolveOp.id],
255
+ preconditions: [],
256
+ expected: `The lock records ${id}@${t.version} with the installed fingerprint.`,
257
+ validation: { before: [], after: ["`feltkit compose --check` passes"] },
258
+ });
259
+ }
260
+ if (currentParams && !same(currentParams, t.params)) {
261
+ for (const key of [...new Set([...Object.keys(currentParams), ...Object.keys(t.params)])].sort()) {
262
+ if (same(currentParams[key], t.params[key]))
263
+ continue;
264
+ add({
265
+ type: "change-parameter",
266
+ classification: "DETERMINISTIC",
267
+ boundary: "composition-record",
268
+ target: `${id}.${key}`,
269
+ current: show(currentParams[key]),
270
+ proposed: show(t.params[key]),
271
+ reason: explicit && request.params?.[id]?.[key] !== undefined ? "Requested by the target." : request.profile !== undefined ? "The target profile's defaults differ." : "The installed definition's default differs.",
272
+ evidence: [`recorded ${RECORD_PATH} params`, `resolved target params`],
273
+ dependsOn: [resolveOp.id],
274
+ preconditions: [],
275
+ expected: `${RECORD_PATH} records ${id}.${key} = ${show(t.params[key])}${(request.params?.[id]?.[key] === undefined) ? " (a default: not written to the record)" : ""}.`,
276
+ validation: { before: [], after: ["the regenerated declaration reflects the parameter"] },
277
+ });
278
+ }
279
+ }
280
+ }
281
+ }
282
+ }
283
+ // 4. Generator.
284
+ if (recorded.generator && recorded.generator !== GENERATOR) {
285
+ add({
286
+ type: "adopt-generator",
287
+ classification: "DETERMINISTIC",
288
+ boundary: "generated-declaration",
289
+ target: GENERATOR,
290
+ current: recorded.generator,
291
+ proposed: GENERATOR,
292
+ reason: "This FeltKit's generator differs from the one that wrote the files.",
293
+ evidence: [`lock generator ${recorded.generator}`, `installed generator ${GENERATOR}`],
294
+ dependsOn: [resolveOp.id],
295
+ preconditions: [],
296
+ expected: "The regenerated files carry the installed generator's format.",
297
+ validation: { before: [], after: ["review the regenerated declaration's diff"] },
298
+ });
299
+ }
300
+ // 5. The declaration: current (on disk, when intact) against the target, path by path.
301
+ let currentDeclaration = report.observed.files[DECLARATION_PATH] ?? null;
302
+ let currentFoundation = null;
303
+ if (stateIntact && recorded.profile) {
304
+ try {
305
+ currentFoundation = await (options.loadFoundation ?? loadFoundation)(projectDir);
306
+ }
307
+ catch (error) {
308
+ add({ type: "verify-current-state", classification: "BLOCKED", boundary: "generated-declaration", target: DECLARATION_PATH, current: "does not load", reason: "The current foundation must load to be compared with the target.", evidence: [error.message.split("\n")[0]], dependsOn: [], preconditions: [], expected: `${DECLARATION_PATH} exports \`foundation\`.`, validation: { before: [], after: [] }, decision: `${DECLARATION_PATH} could not be loaded.` });
309
+ }
310
+ }
311
+ const pathOps = [];
312
+ const targetDeclaration = target.ok ? target.lock.files[DECLARATION_PATH].sha256 : null;
313
+ const declarationChanges = target.ok && currentFoundation && targetDeclaration !== currentDeclaration;
314
+ if (target.ok && currentFoundation) {
315
+ const before = leaves(currentFoundation);
316
+ const after = leaves(target.resolved.options);
317
+ for (const path of [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()) {
318
+ if (same(before[path], after[path]))
319
+ continue;
320
+ const isNew = !(path in before);
321
+ const kind = consumption ? (isNew ? "new" : consumption[path] ?? "unknown") : "unknown";
322
+ const appExtends = extensions.some((a) => a === path || a.startsWith(`${path}.`));
323
+ const authority = AUTHORITY_PATH.test(path);
324
+ const removed = !(path in after);
325
+ let classification = "DETERMINISTIC";
326
+ let decision;
327
+ let boundary = "generated-declaration";
328
+ if (!consumption) {
329
+ classification = "REVIEW_REQUIRED";
330
+ boundary = "application-declaration";
331
+ decision = `${APPLICATION_DECLARATION} was not analyzed (${report.application.reason ?? "unknown"}), so how it holds ${path} is unknown.`;
332
+ }
333
+ else if (kind === "overridden") {
334
+ classification = "REVIEW_REQUIRED";
335
+ boundary = "application-declaration";
336
+ decision = `${APPLICATION_DECLARATION} overrides ${path} (observed ${show(get(await effectiveOf(report, projectDir, options), path))}); the foundation's value changes from ${show(before[path])} to ${show(after[path])}. Keep the override, or take the new foundation value.`;
337
+ }
338
+ else if (kind === "extended" || appExtends) {
339
+ classification = "REVIEW_REQUIRED";
340
+ boundary = "application-declaration";
341
+ decision = removed
342
+ ? `${APPLICATION_DECLARATION} extends ${path}, which the target no longer provides: decide what the application keeps.`
343
+ : `${APPLICATION_DECLARATION} extends ${path}: confirm the extension still means what it should once the foundation value is ${show(after[path])}.`;
344
+ }
345
+ else if (kind === "omitted") {
346
+ classification = removed ? "DETERMINISTIC" : "REVIEW_REQUIRED";
347
+ if (!removed) {
348
+ boundary = "application-declaration";
349
+ decision = `${APPLICATION_DECLARATION} leaves ${path} out; the foundation's value changes to ${show(after[path])} but the application would not take it. Decide whether it should.`;
350
+ }
351
+ }
352
+ else if (kind === "unknown") {
353
+ classification = "REVIEW_REQUIRED";
354
+ boundary = "application-declaration";
355
+ decision = `How ${APPLICATION_DECLARATION} holds ${path} is unknown.`;
356
+ }
357
+ else if (kind === "new" && appExtends && same(get(await effectiveOf(report, projectDir, options), path), after[path])) {
358
+ // The effective declaration already holds exactly this value (an SDK default, or the application's own): nothing changes in effect.
359
+ classification = "DETERMINISTIC";
360
+ }
361
+ else if (kind === "new" && appExtends) {
362
+ classification = "REVIEW_REQUIRED";
363
+ boundary = "application-declaration";
364
+ decision = `${APPLICATION_DECLARATION} already sets something under ${path} (${extensions.filter((a) => a === path || a.startsWith(`${path}.`)).join(", ")}); the foundation would now set it too. Decide which wins.`;
365
+ }
366
+ else if (kind === "new" && !report.application.spreads && !authority) {
367
+ classification = "REVIEW_REQUIRED";
368
+ boundary = "application-declaration";
369
+ decision = `${APPLICATION_DECLARATION} does not spread the whole foundation (\`...foundation\`), so a new path like ${path} would not reach feltkit({...}) by itself. Add \`...foundation\` or \`${path.split(".")[0]}: foundation.${path.split(".")[0]}\`, or decide the application does not want it.`;
370
+ }
371
+ if (authority && classification === "DETERMINISTIC") {
372
+ classification = "REVIEW_REQUIRED";
373
+ boundary = "runtime-behavior";
374
+ decision = `${path} changes who may do what, or who is who (${show(before[path])} → ${show(after[path])}). Confirm the authorization or identity change is intended.`;
375
+ }
376
+ pathOps.push(add({
377
+ type: "change-declaration-path",
378
+ classification,
379
+ boundary,
380
+ target: path,
381
+ current: show(before[path]),
382
+ proposed: show(after[path]),
383
+ reason: removed ? "The target no longer sets this path." : !(path in before) ? "The target sets this path." : "The target sets this path to another value.",
384
+ evidence: [kind === "new" ? `new path: whether ${APPLICATION_DECLARATION} takes it depends on how it spreads the foundation (reconcile after regeneration)` : `${APPLICATION_DECLARATION} holds it: ${kind}${appExtends ? " (with additions under it)" : ""}`, `current ${DECLARATION_PATH} ${currentDeclaration}`, `target declaration ${targetDeclaration}`],
385
+ dependsOn: [resolveOp.id, verifyOp.id],
386
+ preconditions: [`${DECLARATION_PATH} is the locked file`],
387
+ expected: removed ? `${path} is absent from the regenerated foundation.` : `The regenerated foundation sets ${path} = ${show(after[path])}.`,
388
+ validation: { before: ["the application's tests pass on the current foundation"], after: ["`feltkit compose reconcile` is CURRENT", "the application's tests pass"] },
389
+ ...(decision ? { decision } : {}),
390
+ }));
391
+ }
392
+ }
393
+ // 6. Writing the three files, and revalidating: planned, not done.
394
+ // Nothing is planned past a blocker or an inexpressible target: a plan never shows writes it could not stand behind.
395
+ const viable = !ops.some((o) => o.classification === "BLOCKED" || o.classification === "UNSUPPORTED");
396
+ const changesFiles = viable && target.ok && stateIntact && (declarationChanges || ops.some((o) => ["add-capability", "remove-capability", "update-capability", "change-parameter", "adopt-generator"].includes(o.type)) || (recorded.inputs !== null && recorded.inputs !== targetHash));
397
+ if (changesFiles) {
398
+ const regen = add({
399
+ type: "regenerate-declaration",
400
+ classification: "DETERMINISTIC",
401
+ boundary: "generated-declaration",
402
+ target: DECLARATION_PATH,
403
+ current: currentDeclaration ?? undefined,
404
+ proposed: targetDeclaration ?? undefined,
405
+ reason: "The generated declaration must become the target's output.",
406
+ evidence: [`${pathOps.length} declaration path(s) change`],
407
+ dependsOn: [verifyOp.id, "validate-target:" + `feltkit ${report.installed.sdk}`, ...pathOps.map((o) => o.id), ...ops.filter((o) => ["add-capability", "remove-capability", "update-capability", "change-parameter", "adopt-generator"].includes(o.type)).map((o) => o.id)],
408
+ preconditions: ["every REVIEW_REQUIRED operation above is decided", `${DECLARATION_PATH} still hashes to ${currentDeclaration}`],
409
+ expected: `${DECLARATION_PATH} hashes to ${targetDeclaration}.`,
410
+ validation: { before: ["`feltkit compose --check` passes"], after: ["the file typechecks (`tsc --strict`)"] },
411
+ });
412
+ const record = add({
413
+ type: "update-record",
414
+ classification: "DETERMINISTIC",
415
+ boundary: "composition-record",
416
+ target: RECORD_PATH,
417
+ current: recorded.inputs ?? undefined,
418
+ proposed: targetHash,
419
+ reason: "The record must carry the target's inputs and resolution.",
420
+ evidence: [`composition ${recorded.composition} → ${target.ok ? target.record.composition : "n/a"}`],
421
+ dependsOn: [regen.id],
422
+ preconditions: [],
423
+ expected: `${RECORD_PATH} records inputs ${targetHash}.`,
424
+ validation: { before: [], after: [] },
425
+ });
426
+ const lock = add({
427
+ type: "update-lock",
428
+ classification: "DETERMINISTIC",
429
+ boundary: "composition-lock",
430
+ target: LOCK_PATH,
431
+ reason: "The lock must carry the regenerated files' hashes and the installed fingerprints.",
432
+ evidence: [`generator ${GENERATOR}`, ...(target.ok ? target.lock.capabilities.map((c) => `${c.id}@${c.version} ${c.fingerprint}`) : [])],
433
+ dependsOn: [record.id],
434
+ preconditions: [],
435
+ expected: "`feltkit compose --check` passes.",
436
+ validation: { before: [], after: ["`feltkit compose --check` passes", "`feltkit compose reconcile` is CURRENT"] },
437
+ });
438
+ add({
439
+ type: "revalidate-application",
440
+ classification: "DETERMINISTIC",
441
+ boundary: "application-logic",
442
+ target: APPLICATION_DECLARATION,
443
+ reason: "The application must still build, typecheck and pass its tests on the new foundation; its behavior is its own and is proven only by its tests.",
444
+ evidence: ["the application's tests are the only evidence of its behavior"],
445
+ dependsOn: [lock.id],
446
+ preconditions: [],
447
+ expected: "Build, typecheck, tests and reconciliation pass.",
448
+ validation: { before: [], after: ["`feltkit build`", "`tsc --noEmit`", "`feltkit test`", "`feltkit compose reconcile` is CURRENT"] },
449
+ });
450
+ }
451
+ const order = orderOperations(ops);
452
+ const status = ops.some((o) => o.classification === "UNSUPPORTED")
453
+ ? "UNSUPPORTED"
454
+ : ops.some((o) => o.classification === "BLOCKED")
455
+ ? "BLOCKED"
456
+ : ops.some((o) => o.classification === "REVIEW_REQUIRED")
457
+ ? "REVIEW_REQUIRED"
458
+ : changesFiles
459
+ ? "READY"
460
+ : "NO_CHANGE";
461
+ const body = {
462
+ format: PLAN_FORMAT,
463
+ rules: PLAN_RULES,
464
+ status,
465
+ current: {
466
+ composition: recorded.composition,
467
+ inputs: currentInputs,
468
+ inputs_hash: recorded.inputs,
469
+ profile: recorded.profile ? { id: recorded.profile.id, version: recorded.profile.version } : null,
470
+ capabilities: recorded.capabilities.map((c) => ({ id: c.id, version: c.version })),
471
+ generator: recorded.generator,
472
+ sdk: recorded.sdk,
473
+ declaration: currentDeclaration,
474
+ reconciliation: { format: report.format, rules: report.rules, state: report.state, findings: report.findings.map((f) => f.code) },
475
+ application: report.application,
476
+ sources: applicationSources(projectDir),
477
+ },
478
+ target: {
479
+ source: explicit ? "explicit" : "implied",
480
+ inputs: targetInputs,
481
+ inputs_hash: targetHash,
482
+ composition: target.ok ? target.record.composition : null,
483
+ profile: target.ok ? { ...target.resolved.profile } : null,
484
+ capabilities: target.ok ? target.resolved.capabilities.map((c) => ({ id: c.id, version: c.version })) : [],
485
+ generator: GENERATOR,
486
+ sdk: report.installed.sdk,
487
+ declaration: targetDeclaration,
488
+ },
489
+ operations: ops,
490
+ order,
491
+ affected: {
492
+ files: [...new Set(ops.filter((o) => ["regenerate-declaration", "update-record", "update-lock"].includes(o.type)).map((o) => o.target))].sort(),
493
+ paths: pathOps.map((o) => o.target),
494
+ boundaries: [...new Set(ops.filter((o) => o.classification !== "DETERMINISTIC" || ["regenerate-declaration", "update-record", "update-lock", "change-declaration-path"].includes(o.type)).map((o) => o.boundary))].sort(),
495
+ },
496
+ preconditions: [...new Set(ops.flatMap((o) => o.preconditions))],
497
+ validation: [...new Set(ops.flatMap((o) => [...o.validation.before, ...o.validation.after]))],
498
+ decisions: ops.filter((o) => o.classification === "REVIEW_REQUIRED" && o.decision).map((o) => ({ operation: o.id, decision: o.decision })),
499
+ blockers: ops.filter((o) => o.classification === "BLOCKED").map((o) => ({ operation: o.id, reason: o.decision ?? o.reason })),
500
+ unsupported: ops.filter((o) => o.classification === "UNSUPPORTED").map((o) => ({ operation: o.id, reason: o.decision ?? o.reason })),
501
+ };
502
+ return { ...body, id: sha256(canonical(JSON.parse(JSON.stringify(body)))) };
503
+ }
504
+ // ── Helpers ──────────────────────────────────────────────────────────────────
505
+ /** The application's backend sources (what `feltkit build` loads), each hashed. Relative paths, sorted. */
506
+ export function applicationSources(projectDir) {
507
+ let modules = [];
508
+ try {
509
+ modules = backendModules(projectDir);
510
+ }
511
+ catch {
512
+ return {};
513
+ }
514
+ return Object.fromEntries(modules.map((m) => [relative(projectDir, m.path).split(sep).join("/"), sha256(readFileSync(m.path, "utf8"))]).sort(([a], [b]) => a.localeCompare(b)));
515
+ }
516
+ async function currentInputsOf(projectDir) {
517
+ try {
518
+ const record = JSON.parse(readFileSync(join(projectDir, RECORD_PATH), "utf8"));
519
+ if (!record.profile?.id)
520
+ return null;
521
+ return { profile: record.profile.id, include: [...(record.include ?? [])].sort(), params: JSON.parse(canonical(record.params ?? {})) };
522
+ }
523
+ catch {
524
+ return null;
525
+ }
526
+ }
527
+ function mergeParams(base, overlay) {
528
+ const out = {};
529
+ for (const cap of [...new Set([...Object.keys(base), ...Object.keys(overlay)])].sort())
530
+ out[cap] = { ...(base[cap] ?? {}), ...(overlay[cap] ?? {}) };
531
+ return out;
532
+ }
533
+ /** A capability's resolved parameters for given inputs: the given ones over the profile's defaults over its own. */
534
+ function paramsFor(def, inputs, id) {
535
+ const profile = PROFILES.get(inputs.profile);
536
+ const out = {};
537
+ for (const [k, spec] of Object.entries(def.parameters))
538
+ if (spec.default !== undefined)
539
+ out[k] = spec.default;
540
+ Object.assign(out, profile?.defaults[id] ?? {}, inputs.params[id] ?? {});
541
+ return out;
542
+ }
543
+ const effectiveCache = new WeakMap();
544
+ /** The application's effective options, for the observed value of an override. Loaded once per plan. */
545
+ function effectiveOf(report, projectDir, options) {
546
+ let p = effectiveCache.get(report);
547
+ if (!p) {
548
+ p = (async () => {
549
+ if (options.loadApplication)
550
+ return (await options.loadApplication(projectDir)).options;
551
+ const { loadSources } = await import("../runtime/loader.js");
552
+ return (await loadSources(projectDir)).app.options;
553
+ })();
554
+ effectiveCache.set(report, p);
555
+ }
556
+ return p;
557
+ }
558
+ //# sourceMappingURL=plan.js.map