@appport/integration 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +126 -0
  2. package/README.md +35 -2
  3. package/dist/base64url.d.ts +4 -0
  4. package/dist/base64url.d.ts.map +1 -0
  5. package/dist/base64url.js +36 -0
  6. package/dist/base64url.js.map +1 -0
  7. package/dist/behavior.d.ts +164 -0
  8. package/dist/behavior.d.ts.map +1 -0
  9. package/dist/behavior.js +493 -0
  10. package/dist/behavior.js.map +1 -0
  11. package/dist/coverage.d.ts +44 -0
  12. package/dist/coverage.d.ts.map +1 -0
  13. package/dist/coverage.js +43 -0
  14. package/dist/coverage.js.map +1 -0
  15. package/dist/declarations.d.ts +53 -0
  16. package/dist/declarations.d.ts.map +1 -0
  17. package/dist/declarations.js +45 -0
  18. package/dist/declarations.js.map +1 -0
  19. package/dist/ed25519.d.ts +8 -0
  20. package/dist/ed25519.d.ts.map +1 -0
  21. package/dist/ed25519.js +128 -0
  22. package/dist/ed25519.js.map +1 -0
  23. package/dist/encodings.d.ts +9 -0
  24. package/dist/encodings.d.ts.map +1 -0
  25. package/dist/encodings.js +75 -0
  26. package/dist/encodings.js.map +1 -0
  27. package/dist/fields.d.ts +29 -0
  28. package/dist/fields.d.ts.map +1 -0
  29. package/dist/fields.js +76 -0
  30. package/dist/fields.js.map +1 -0
  31. package/dist/findings.d.ts +189 -0
  32. package/dist/findings.d.ts.map +1 -0
  33. package/dist/findings.js +195 -0
  34. package/dist/findings.js.map +1 -0
  35. package/dist/footprint.d.ts +67 -0
  36. package/dist/footprint.d.ts.map +1 -0
  37. package/dist/footprint.js +78 -0
  38. package/dist/footprint.js.map +1 -0
  39. package/dist/graph.d.ts +111 -0
  40. package/dist/graph.d.ts.map +1 -0
  41. package/dist/graph.js +396 -0
  42. package/dist/graph.js.map +1 -0
  43. package/dist/index.d.ts +38 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +38 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/lint.d.ts +57 -0
  48. package/dist/lint.d.ts.map +1 -0
  49. package/dist/lint.js +281 -0
  50. package/dist/lint.js.map +1 -0
  51. package/dist/mapping.d.ts +28 -0
  52. package/dist/mapping.d.ts.map +1 -0
  53. package/dist/mapping.js +282 -0
  54. package/dist/mapping.js.map +1 -0
  55. package/dist/normalize.d.ts +27 -0
  56. package/dist/normalize.d.ts.map +1 -0
  57. package/dist/normalize.js +56 -0
  58. package/dist/normalize.js.map +1 -0
  59. package/dist/plan.d.ts +240 -0
  60. package/dist/plan.d.ts.map +1 -0
  61. package/dist/plan.js +746 -0
  62. package/dist/plan.js.map +1 -0
  63. package/dist/readiness.d.ts +146 -0
  64. package/dist/readiness.d.ts.map +1 -0
  65. package/dist/readiness.js +346 -0
  66. package/dist/readiness.js.map +1 -0
  67. package/dist/reference.d.ts +39 -0
  68. package/dist/reference.d.ts.map +1 -0
  69. package/dist/reference.js +74 -0
  70. package/dist/reference.js.map +1 -0
  71. package/dist/scenario.d.ts +114 -0
  72. package/dist/scenario.d.ts.map +1 -0
  73. package/dist/scenario.js +117 -0
  74. package/dist/scenario.js.map +1 -0
  75. package/dist/select.d.ts +41 -0
  76. package/dist/select.d.ts.map +1 -0
  77. package/dist/select.js +71 -0
  78. package/dist/select.js.map +1 -0
  79. package/dist/trust.d.ts +237 -0
  80. package/dist/trust.d.ts.map +1 -0
  81. package/dist/trust.js +511 -0
  82. package/dist/trust.js.map +1 -0
  83. package/dist/types.d.ts +130 -0
  84. package/dist/types.d.ts.map +1 -0
  85. package/dist/types.js +19 -0
  86. package/dist/types.js.map +1 -0
  87. package/dist/units.d.ts +20 -0
  88. package/dist/units.d.ts.map +1 -0
  89. package/dist/units.js +47 -0
  90. package/dist/units.js.map +1 -0
  91. package/dist/verification.d.ts +54 -0
  92. package/dist/verification.d.ts.map +1 -0
  93. package/dist/verification.js +115 -0
  94. package/dist/verification.js.map +1 -0
  95. package/package.json +28 -4
package/dist/plan.js ADDED
@@ -0,0 +1,746 @@
1
+ /**
2
+ * Integration planning: from a stated task and the *published* contracts of the applications
3
+ * involved, produce a deterministic, machine-readable account of whether an integration can be
4
+ * attempted, what it would involve, and what stands in the way.
5
+ *
6
+ * What a plan is not: an authorization (`authorization.granted` is always false), an execution
7
+ * (nothing is called), or a claim that anything works. It is only as good as the contracts, and
8
+ * every place where a contract is silent becomes a finding rather than a default.
9
+ *
10
+ * Statuses, in precedence order:
11
+ * - `blocked`: a published fact stops the integration (incompatible, unauthorized, stale). Not fixable by acknowledging.
12
+ * - `needs_input`: the contracts are silent or ambiguous where the caller can supply or accept something.
13
+ * - `unverifiable`: it could be attempted, but its outcome could not be confirmed from published evidence.
14
+ * - `ready`: every decision rests on a published declaration or on a recorded acknowledgement, and verification exists.
15
+ * `ready` means "nothing in the contracts prevents attempting this", not "this will work".
16
+ */
17
+ import { contractDigest, compareManifests, digestOf, getIntegration, integrationKey, parseDependencyRef, satisfiesVersionConstraint } from "@appport/protocol";
18
+ import { summarizeCoverage, validateCoverage } from "./coverage.js";
19
+ import { classifyDeclarations } from "./declarations.js";
20
+ import { pairFields } from "./fields.js";
21
+ import { INVOCATION_BOUNDARY_SOURCE, STATE_BOUNDARY_SOURCE } from "./findings.js";
22
+ import { describeFootprint } from "./footprint.js";
23
+ import { lintMapping } from "./lint.js";
24
+ import { runVectors } from "./mapping.js";
25
+ import { verifyMappingArtifact } from "./reference.js";
26
+ import { findCapabilities } from "./select.js";
27
+ export const PLAN_FORMAT = "appport.integration-plan/1";
28
+ /**
29
+ * How a mapping the plan would use stands, from the five separate checks. Only `eligible` and `accepted-locally` make a mapping usable;
30
+ * `accepted-locally` means the caller explicitly acknowledged the finding(s) that stood in the way. It is not trust.
31
+ */
32
+ export const MAPPING_DISPOSITIONS = [
33
+ "eligible", "accepted-locally", "needs-local-acceptance", "unsigned", "untrusted", "rejected", "invalid", "unverifiable",
34
+ "policy-unavailable", "trust-not-assessed", "pin-missing", "pin-conflict", "incompatible", "artifact-missing", "not-needed"
35
+ ];
36
+ export const PLAN_LIMITS = [
37
+ "A plan is derived from published contracts only. It does not see hidden dependencies, handler behaviour, storage, or whether a provider honours its declarations.",
38
+ "Declared failure behaviour, idempotency, effects and verification are promises of the publisher; nothing here proves them.",
39
+ "Caller scopes and approvals are the caller's statements; they are neither verified nor granted.",
40
+ "Contract freshness cannot be established by the contract itself. Compare basis.contracts with a fresh fetch immediately before acting.",
41
+ "A mapping is used only if it is eligible (authentic, intact, from a publisher and key the supplied policy trusts, semantically valid, consistent with its pin) or the caller explicitly accepted the gap. A trusted publisher does not make a mapping correct, and nothing here authorizes its use or execution (spec/mapping-trust-1.md).",
42
+ "Trust is only as good as the supplied policy and pins; AppPort provides no authenticated distribution of key status, so a stale policy is a stale decision. Mappings are never executed while planning.",
43
+ "A plan that is feasible is not permission: authorization, approval and execution remain with the caller and the provider.",
44
+ "Declared dependency, access and effect lists prove nothing about hidden dependencies; runtime evidence covers only the boundaries it was collected through, and only for the interval observed.",
45
+ "A successful response (`ok: true`) is not evidence that an effect persisted. Only the declared verification, run by the caller's runtime, is."
46
+ ];
47
+ /** Relationships that make the caller wait on the target: a cycle of required ones cannot be satisfied. Same set as the dependency graph. */
48
+ const SYNCHRONOUS_RELATIONSHIPS = ["invokes", "observes"];
49
+ /** Safety cap on transitive dependency resolution. Visiting each capability once already guarantees termination, so reaching the cap is reported, never silent. */
50
+ const MAX_DEPENDENCY_DEPTH = 32;
51
+ const RANK = { blocker: 0, input: 1, unverifiable: 2, note: 3 };
52
+ class Collector {
53
+ acknowledge;
54
+ findings = new Map();
55
+ decisions = new Map();
56
+ steps = [];
57
+ constructor(acknowledge) {
58
+ this.acknowledge = acknowledge;
59
+ }
60
+ find(f) {
61
+ const { subject, ...rest } = f;
62
+ const id = `${f.code}:${[...f.capabilities].sort().join("+")}${subject ? `:${subject}` : ""}`;
63
+ if (this.findings.has(id))
64
+ return id;
65
+ const finding = { ...rest, id, missing: rest.missing ?? [], hints: rest.hints ?? [], acknowledgeable: rest.acknowledgeable ?? false };
66
+ if (finding.acknowledgeable && this.acknowledge.has(id)) {
67
+ finding.acknowledged = true;
68
+ finding.severity = "note";
69
+ }
70
+ this.findings.set(id, finding);
71
+ return id;
72
+ }
73
+ decide(d) {
74
+ if (!this.decisions.has(d.id))
75
+ this.decisions.set(d.id, { ...d, findings: d.findings ?? [] });
76
+ }
77
+ step(step) {
78
+ this.steps.push({ ...step, order: this.steps.length + 1 });
79
+ }
80
+ }
81
+ const find = (manifest, key) => {
82
+ const [name, version] = [key.split("@")[0], Number(key.split("@")[1])];
83
+ return manifest.capabilities.find((c) => c.name === name)?.definitions.find((d) => d.version === version);
84
+ };
85
+ /** Compares stated scopes with required ones. */
86
+ function scopeCheck(required, stated) {
87
+ if (stated === undefined)
88
+ return { state: "unstated", missing: [...required] };
89
+ const missing = required.filter((scope) => !stated.includes(scope));
90
+ return { state: missing.length ? "missing" : "ok", missing };
91
+ }
92
+ export function planIntegration(input) {
93
+ const c = new Collector(new Set(input.acknowledge ?? []));
94
+ const task = input.task;
95
+ const byApp = new Map(input.manifests.map((m) => [m.application.id, m]));
96
+ const selected = { candidates: [] };
97
+ const dependencies = [];
98
+ let fields = [];
99
+ const usedMappings = [];
100
+ const mappingAssessments = [];
101
+ const requirementsList = [];
102
+ const involved = new Set();
103
+ // ---- selection ---------------------------------------------------------------------------
104
+ const select = (role, selector) => {
105
+ const result = findCapabilities(input.manifests, selector);
106
+ const label = `${role} ${JSON.stringify(selector)}`;
107
+ if (result.matches.length === 1) {
108
+ const match = result.matches[0];
109
+ selected[role] = match;
110
+ const manifest = byApp.get(match.application);
111
+ const definition = find(manifest, match.capability);
112
+ const entry = getIntegration(manifest)?.capabilities[match.capability];
113
+ involved.add(match.application);
114
+ c.decide({ id: `select:${role}`, question: `Which capability satisfies the ${role} of the task?`, state: "declared", answer: `${match.application}/${match.capability}`, source: `${match.application}#${match.matchedOn.join(",")}`, provenance: "declared" });
115
+ return { manifest, application: match.application, key: match.capability, ref: `${match.application}/${match.capability}`, definition, facts: classifyDeclarations(definition, entry) };
116
+ }
117
+ if (result.matches.length > 1) {
118
+ selected.candidates.push(...result.matches);
119
+ const id = c.find({ severity: "input", code: "selection.ambiguous", state: "unknown", message: `${result.matches.length} capabilities satisfy the ${role} selector; the contracts do not say which is intended`, capabilities: result.matches.map((m) => `${m.application}/${m.capability}`), missing: [`${role}.capability`], hints: ["name the capability (application and name@version) in the selector"], subject: role });
120
+ c.decide({ id: `select:${role}`, question: `Which capability satisfies the ${role} of the task?`, state: "unknown", provenance: "declared", findings: [id] });
121
+ return undefined;
122
+ }
123
+ const missingContracts = selector.application !== undefined && !byApp.has(selector.application);
124
+ if (missingContracts || result.undeclared.length) {
125
+ const id = c.find({
126
+ severity: "input", code: "selection.not-found", state: "unknown", subject: role,
127
+ message: missingContracts ? `no contract for application ${selector.application} was supplied` : `no capability matched ${label}, but ${result.undeclared.length} publish no integration entry, so they could not be evaluated`,
128
+ capabilities: result.undeclared.map((u) => `${u.application}/${u.capability}`),
129
+ missing: missingContracts ? [`contract:${selector.application}`] : [`${role}.selector`],
130
+ hints: missingContracts ? ["fetch the application's manifest and supply it"] : ["select by capability name, or obtain a contract that declares access/effects"]
131
+ });
132
+ c.decide({ id: `select:${role}`, question: `Which capability satisfies the ${role} of the task?`, state: "unknown", provenance: "declared", findings: [id] });
133
+ }
134
+ else {
135
+ const id = c.find({ severity: "blocker", code: "selection.no-match", state: "incompatible", subject: role, message: `no supplied contract declares a capability matching ${label}`, capabilities: [], hints: ["the capability may exist but not be declared: absence from a contract is not proof it does not exist"] });
136
+ c.decide({ id: `select:${role}`, question: `Which capability satisfies the ${role} of the task?`, state: "incompatible", provenance: "declared", findings: [id] });
137
+ }
138
+ return undefined;
139
+ };
140
+ const source = task.kind === "transfer" ? select("source", task.source) : undefined;
141
+ const target = select("target", task.target);
142
+ // ---- per-capability assessment -------------------------------------------------------------
143
+ const stated = (application) => input.caller?.scopes?.[application];
144
+ const needScopes = (s, definition, purpose, capKey) => {
145
+ const facts = classifyDeclarations(definition, getIntegration(s.manifest)?.capabilities[capKey]);
146
+ const ref = `${s.application}/${capKey}`;
147
+ const id = `authorization:${purpose}:${ref}`;
148
+ const severity = purpose === "invoke" ? "blocker" : "unverifiable";
149
+ if (facts.authorization.state === "unknown") {
150
+ const fid = c.find({ severity: "input", code: "authorization.unstated", state: "unknown", subject: purpose, message: `${ref} publishes no authorization contract: whether it is public or scoped is unknown`, capabilities: [ref], acknowledgeable: purpose === "invoke", hints: ["obtain a contract that states authorization, or accept the uncertainty explicitly"] });
151
+ c.decide({ id, question: `What authorization does ${ref} require (${purpose})?`, state: "unknown", provenance: "declared", findings: [fid] });
152
+ return;
153
+ }
154
+ const value = facts.authorization.value;
155
+ if (value.mode === "public") {
156
+ c.decide({ id, question: `What authorization does ${ref} require (${purpose})?`, state: "declared", answer: "public", source: `${s.application}#/capabilities/${capKey}/authorizationContract`, provenance: "declared" });
157
+ return;
158
+ }
159
+ const check = scopeCheck(value.scopes, stated(s.application));
160
+ if (check.state === "ok") {
161
+ c.decide({ id, question: `What authorization does ${ref} require (${purpose})?`, state: "declared", answer: { scopes: value.scopes, callerStates: "holds" }, source: `${s.application}#/capabilities/${capKey}/authorizationContract`, provenance: "declared" });
162
+ return;
163
+ }
164
+ const fid = check.state === "unstated"
165
+ ? c.find({ severity: purpose === "invoke" ? "input" : "input", code: "caller.scopes-unstated", state: "unknown", subject: purpose, message: `${ref} requires scopes and the caller has not stated which it holds`, capabilities: [ref], missing: value.scopes.map((x) => `scope:${x}`), hints: ["state the scopes the caller's credential holds for this application"] })
166
+ : c.find({ severity, code: purpose === "invoke" ? "authorization.scopes-missing" : `${purpose}.probe-unauthorized`, state: "incompatible", subject: purpose, message: `the caller states it lacks ${check.missing.join(", ")} required by ${ref}`, capabilities: [ref], missing: check.missing.map((x) => `scope:${x}`), hints: ["obtain a credential with these scopes; the plan cannot grant them"] });
167
+ c.decide({ id, question: `What authorization does ${ref} require (${purpose})?`, state: check.state === "unstated" ? "unknown" : "incompatible", answer: { scopes: value.scopes }, source: `${s.application}#/capabilities/${capKey}/authorizationContract`, provenance: "declared", findings: [fid] });
168
+ };
169
+ const probeSteps = (s, items, purpose) => {
170
+ for (const item of items) {
171
+ if ("kind" in item && item.kind === "event")
172
+ continue;
173
+ const via = item.via;
174
+ const probe = find(s.manifest, integrationKey(via.capability, via.version));
175
+ if (probe)
176
+ needScopes(s, probe, purpose, integrationKey(via.capability, via.version));
177
+ }
178
+ };
179
+ const assess = (s, role) => {
180
+ const { facts, ref, definition } = s;
181
+ const entry = getIntegration(s.manifest)?.capabilities[s.key];
182
+ const base = `${s.application}#/capabilities/${s.key}`;
183
+ const at = `integration:${s.key}`;
184
+ // effect
185
+ if (facts.effect.state === "unknown") {
186
+ const fid = c.find({ severity: "input", code: "effect.undeclared", state: "unknown", subject: role, message: `${ref} does not declare whether it has side effects; "not declared" is not "read-only"`, capabilities: [ref], acknowledgeable: true, hints: ["obtain a contract that declares `effect`", "or acknowledge that the effect is unknown; the plan will treat retry as unknown"] });
187
+ c.decide({ id: `effect:${ref}`, question: `Does ${ref} change state?`, state: "unknown", provenance: "declared", findings: [fid] });
188
+ }
189
+ else {
190
+ c.decide({ id: `effect:${ref}`, question: `Does ${ref} change state?`, state: "declared", answer: facts.effect.value, source: `${base}/effect`, provenance: "declared" });
191
+ }
192
+ if (role === "source" && facts.effect.value === "consequential") {
193
+ c.find({ severity: "blocker", code: "selection.source-not-observation", state: "incompatible", message: `${ref} changes state; it cannot be used as a read-only source`, capabilities: [ref], hints: ["select an observation capability for the source"] });
194
+ }
195
+ // authorization and approval
196
+ needScopes(s, definition, "invoke", s.key);
197
+ if (facts.approval.state === "declared") {
198
+ const approval = facts.approval.value;
199
+ if (!approval.required)
200
+ c.decide({ id: `approval:${ref}`, question: `Does ${ref} need an approval?`, state: "declared", answer: false, source: `${base}/approval`, provenance: "declared" });
201
+ else if (input.caller?.approvals?.includes(ref)) {
202
+ c.decide({ id: `approval:${ref}`, question: `Does ${ref} need an approval?`, state: "declared", answer: { required: true, ...(approval.approver ? { approver: approval.approver } : {}), callerStates: "holds" }, source: `${base}/approval`, provenance: "declared" });
203
+ c.step({ action: "obtain-approval", application: s.application, capability: s.key, detail: { approver: approval.approver ?? null, status: "claimed-by-caller", note: "not verified by the plan" } });
204
+ }
205
+ else {
206
+ const fid = c.find({ severity: "input", code: "approval.required", state: "declared", message: `${ref} requires an approval${approval.approver ? ` from ${approval.approver}` : ""} that the caller has not stated it holds`, capabilities: [ref], missing: [`approval:${approval.approver ?? ref}`], hints: ["obtain the approval out of band, then state it in caller.approvals"] });
207
+ c.decide({ id: `approval:${ref}`, question: `Does ${ref} need an approval?`, state: "declared", answer: { required: true, ...(approval.approver ? { approver: approval.approver } : {}) }, source: `${base}/approval`, provenance: "declared", findings: [fid] });
208
+ c.step({ action: "obtain-approval", application: s.application, capability: s.key, detail: { approver: approval.approver ?? null, status: "required" } });
209
+ }
210
+ }
211
+ else {
212
+ const consequential = facts.effect.value !== "observation";
213
+ const fid = c.find({ severity: consequential ? "input" : "note", code: "approval.unstated", state: "unknown", message: `${ref} does not say whether an approval is required; absence is not "none required"`, capabilities: [ref], acknowledgeable: consequential, hints: ["obtain a contract that declares `approval`, or accept the uncertainty explicitly"] });
214
+ c.decide({ id: `approval:${ref}`, question: `Does ${ref} need an approval?`, state: "unknown", provenance: "declared", findings: [fid] });
215
+ }
216
+ // retry and failure behaviour
217
+ const retry = facts.retry;
218
+ if (retry === "unknown" || retry === "unsafe") {
219
+ const fid = c.find({ severity: "note", code: retry === "unknown" ? "retry.unknown" : "retry.unsafe", state: retry === "unknown" ? "unknown" : "declared", message: retry === "unknown" ? `${ref}: whether a repeated call is safe is unknown; do not retry automatically` : `${ref} has side effects and does not support idempotency keys; a repeated call may repeat the effect`, capabilities: [ref], hints: ["after a timeout or transport error, verify before any retry"] });
220
+ c.decide({ id: `retry:${ref}`, question: `May a failed call to ${ref} be retried?`, state: retry === "unknown" ? "unknown" : "declared", answer: retry, source: retry === "unknown" ? undefined : `${base}/idempotency`, provenance: "declared", findings: [fid] });
221
+ }
222
+ else
223
+ c.decide({ id: `retry:${ref}`, question: `May a failed call to ${ref} be retried?`, state: "declared", answer: retry, source: `${base}/${retry === "safe" ? "effect" : "idempotency"}`, provenance: "declared" });
224
+ const failures = entry?.failures ?? [];
225
+ if (failures.length)
226
+ c.decide({ id: `failures:${ref}`, question: `What do failures of ${ref} mean?`, state: "declared", answer: failures.map((f) => ({ code: f.code, retry: f.retry, effect: f.effect })), source: `${at}/failures`, provenance: "declared" });
227
+ if (facts.failures.state !== "declared" && facts.effect.value !== "observation") {
228
+ const fid = c.find({ severity: "note", code: "failures.unstated", state: facts.failures.state, message: `${ref}: ${facts.failures.state === "declared-absence" ? "the publisher declares no failure behaviour beyond the protocol's" : "failure behaviour is not published; treat every failure after the request was sent as possibly having taken effect"}`, capabilities: [ref] });
229
+ c.decide({ id: `failures:${ref}`, question: `What do failures of ${ref} mean?`, state: facts.failures.state, provenance: "declared", findings: [fid] });
230
+ }
231
+ // preconditions
232
+ const pre = entry?.preconditions ?? [];
233
+ if (pre.length) {
234
+ c.decide({ id: `preconditions:${ref}`, question: `What must hold before calling ${ref}?`, state: "declared", answer: pre.map((p) => p.id), source: `${at}/preconditions`, provenance: "declared" });
235
+ probeSteps(s, pre, "precondition");
236
+ for (const p of pre)
237
+ c.step({ action: "check-precondition", application: s.application, capability: s.key, detail: { id: p.id, via: `${p.via.capability}@${p.via.version}`, input: p.via.input, require: p.require, ...(p.expect ? { expect: p.expect } : {}) } });
238
+ }
239
+ if (facts.preconditions.state !== "declared") {
240
+ const fid = c.find({ severity: "note", code: "preconditions.unstated", state: facts.preconditions.state === "declared-absence" ? "declared-absence" : "requires-observation", message: facts.preconditions.state === "declared-absence" ? `${ref}: the publisher declares no preconditions` : `${ref}: preconditions are not declared complete; others may exist and surface only as runtime errors`, capabilities: [ref] });
241
+ c.decide({ id: `preconditions:${ref}`, question: `What must hold before calling ${ref}?`, state: facts.preconditions.state === "declared-absence" ? "declared-absence" : "requires-observation", provenance: "declared", findings: [fid] });
242
+ }
243
+ // verification
244
+ const methods = entry?.verify ?? [];
245
+ const stateMethods = methods.filter((m) => m.kind === "state");
246
+ if (facts.effect.value === "observation") {
247
+ c.decide({ id: `verification:${ref}`, question: `How is the effect of ${ref} verified?`, state: "declared-absence", answer: "an observation has no effect to verify", source: `${base}/effect`, provenance: "declared" });
248
+ }
249
+ else if (stateMethods.length) {
250
+ c.decide({ id: `verification:${ref}`, question: `How is the effect of ${ref} verified?`, state: "declared", answer: methods.map((m) => ({ id: m.id, kind: m.kind })), source: `${at}/verify`, provenance: "declared" });
251
+ probeSteps(s, stateMethods, "verification");
252
+ }
253
+ else {
254
+ const only = methods.length > 0;
255
+ const fid = c.find({
256
+ severity: "unverifiable", code: only ? "verification.corroborating-only" : "verification.unavailable", state: "unknown",
257
+ message: only ? `${ref} declares only event verification, which can corroborate but never establish an effect` : `${ref} declares no state verification: an \`ok: true\` response would be the only evidence, and it is not evidence of persistence`,
258
+ capabilities: [ref], missing: ["verification.method:state"], hints: ["obtain a contract that declares a state verification through an observation capability", "or verify by an out-of-band mechanism the plan cannot know about"]
259
+ });
260
+ c.decide({ id: `verification:${ref}`, question: `How is the effect of ${ref} verified?`, state: "unknown", provenance: "declared", findings: [fid] });
261
+ }
262
+ // dependencies
263
+ resolveDependencies(s, entry?.requires ?? [], 0, new Set([ref]));
264
+ const claimed = entry?.coverage?.requires === "complete";
265
+ if (!claimed) {
266
+ const fid = c.find({ severity: "note", code: "dependencies.coverage-unknown", state: "requires-observation", message: `${ref} does not claim its declared dependencies are complete; hidden dependencies are not excluded`, capabilities: [ref], hints: ["only analysis or runtime observation can find a dependency the publisher did not declare"] });
267
+ c.decide({ id: `dependencies:${ref}`, question: `Is the dependency list of ${ref} complete?`, state: "requires-observation", provenance: "declared", findings: [fid] });
268
+ }
269
+ else {
270
+ c.decide({ id: `dependencies:${ref}`, question: `Is the dependency list of ${ref} complete?`, state: "declared", answer: "the publisher claims completeness (a claim, not proof)", source: `${at}/coverage/requires`, provenance: "declared" });
271
+ }
272
+ // resources: what it reads and changes, by logical identity
273
+ const descriptor = getIntegration(s.manifest);
274
+ const resourceDeclarations = new Map((descriptor?.resources ?? []).map((r) => [r.id, r]));
275
+ const accessList = entry?.access ?? [];
276
+ for (const a of accessList) {
277
+ const declaration = resourceDeclarations.get(a.resource);
278
+ if (!declaration) {
279
+ c.find({ severity: "input", code: "resources.incomplete", state: "unknown", subject: a.resource, message: `${ref} ${a.mode} ${a.resource}, but the application does not declare that resource, so its meaning and owner are unknown`, capabilities: [ref], missing: [`resource:${a.resource}`], hints: ["obtain a contract that declares the resource (identity, concept, owner)"] });
280
+ }
281
+ else if (a.mode === "changes" && typeof declaration.owner === "object" && declaration.owner.application !== s.application) {
282
+ c.find({ severity: "note", code: "resources.foreign-owner", state: "declared", subject: a.resource, message: `${ref} changes ${a.resource}, whose declared owner is ${declaration.owner.application}`, capabilities: [ref], hints: ["the owner's capabilities are the intended way to change it"] });
283
+ }
284
+ }
285
+ if (facts.access.state === "declared") {
286
+ c.decide({ id: `access:${ref}`, question: `Which resources does ${ref} read or change?`, state: "declared", answer: accessList.map((a) => `${a.mode}:${a.resource}`), source: `${at}/access`, provenance: "declared" });
287
+ }
288
+ else {
289
+ const fid = c.find({ severity: "note", code: "access.unstated", state: facts.access.state === "declared-absence" ? "declared-absence" : "unknown", message: facts.access.state === "declared-absence" ? `${ref}: the publisher declares it reads and changes no resources` : `${ref} does not say which state it reads or changes (and does not claim its list is complete); absence of a declaration is not absence of access`, capabilities: [ref] });
290
+ c.decide({ id: `access:${ref}`, question: `Which resources does ${ref} read or change?`, state: facts.access.state === "declared-absence" ? "declared-absence" : "unknown", provenance: "declared", findings: [fid] });
291
+ }
292
+ if (facts.authorization.value?.mode === "public" && facts.effect.value === "consequential") {
293
+ c.find({ severity: "input", code: "authorization.consequential-public", state: "declared", subject: role, message: `${ref} declares a state-changing effect and requires no authorization: anyone who can reach it can change state`, capabilities: [ref], acknowledgeable: true, hints: ["ask the publisher to require authorization, or acknowledge that you are relying on a public consequential capability"] });
294
+ }
295
+ {
296
+ const declaredEffects = (entry?.effects ?? []).map((e) => e.type).sort();
297
+ const required = (entry?.requires ?? []).filter((d) => d.required);
298
+ const optional = (entry?.requires ?? []).filter((d) => !d.required);
299
+ const label = (d) => { const t = d.target; return `${d.relationship}:${t.application ?? s.application}/${t.capability ?? t.event}`; };
300
+ const unknowns = [];
301
+ const facetState = (name, facet) => { if (facet.state === "unknown" || facet.state === "requires-observation")
302
+ unknowns.push(name); };
303
+ for (const [name, facet] of [["effect", facts.effect], ["authorization", facts.authorization], ["approval", facts.approval], ["idempotency", facts.idempotency], ["verification", facts.verification], ["preconditions", facts.preconditions], ["failures", facts.failures], ["access", facts.access], ["dependencies", facts.requires]])
304
+ facetState(name, facet);
305
+ if (entry?.coverage?.requires !== "complete")
306
+ unknowns.push("hidden-dependencies");
307
+ requirementsList.push({
308
+ capability: ref, role,
309
+ purpose: entry?.purpose !== undefined ? { state: "declared", value: entry.purpose } : { state: "unknown" },
310
+ authority: entry?.authority !== undefined ? { state: "declared", value: entry.authority } : { state: "unknown" },
311
+ authorization: facts.authorization, approval: facts.approval, effect: facts.effect,
312
+ declaredEffects: declaredEffects.length ? { state: "declared", value: declaredEffects } : { state: "unknown" },
313
+ emits: [...(definition.emits ?? [])].sort(),
314
+ access: { state: facts.access.state, reads: accessList.filter((a) => a.mode === "reads").map((a) => a.resource).sort(), changes: accessList.filter((a) => a.mode === "changes").map((a) => ({ resource: a.resource, ...(a.operations ? { operations: [...a.operations] } : {}) })).sort((x, y) => x.resource.localeCompare(y.resource)) },
315
+ idempotency: facts.idempotency, retry: facts.retry,
316
+ failures: (entry?.failures ?? []).map((f) => ({ code: f.code, retry: f.retry, effect: f.effect })),
317
+ preconditions: (entry?.preconditions ?? []).map((p) => p.id),
318
+ verification: { state: facts.verification.state, methods: (entry?.verify ?? []).map((m) => ({ id: m.id, kind: m.kind })), evidence: facts.effect.value === "observation" ? "none needed: an observation has no effect to verify" : "a VerificationEvidence (appport.verification-evidence/1) with outcome verified, produced by the caller's runtime from the declared state method; a response of ok:true is not evidence" },
319
+ dependencies: { state: facts.requires.state, required: required.map(label).sort(), optional: optional.map(label).sort() },
320
+ unknowns: unknowns.sort()
321
+ });
322
+ }
323
+ // Evidence from outside the contract: an observed call the contract does not declare.
324
+ const declared = new Set((entry?.requires ?? []).map((d) => `${d.target.application ?? s.application}/${d.target.capability ?? ""}`));
325
+ for (const finding of input.findings ?? []) {
326
+ if (!["invokes", "observes", "delegates"].includes(finding.relation))
327
+ continue;
328
+ if (finding.subject.capability !== s.key || (finding.subject.application ?? s.application) !== s.application)
329
+ continue;
330
+ const to = `${finding.object.application ?? s.application}/${finding.object.capability ?? ""}`;
331
+ const covered = [...declared].some((d) => d === to || (d.endsWith("/" + (parseDependencyRef(finding.object.capability ?? "")?.name ?? "")) && d.startsWith(finding.object.application ?? s.application)));
332
+ if (!covered) {
333
+ c.find({ severity: "input", code: "dependency.undeclared-observed", state: "requires-observation", subject: to, message: `${finding.provenance} evidence (${finding.evidence.source}) shows ${ref} ${finding.relation} ${to}, which its contract does not declare`, capabilities: [ref, to], acknowledgeable: true, hints: ["supply that application's contract, or ask the publisher to declare the dependency"] });
334
+ }
335
+ }
336
+ };
337
+ const resolveDependencies = (s, deps, depth, seen) => {
338
+ for (const dep of deps) {
339
+ const t = dep.target;
340
+ const app = t.application ?? s.application;
341
+ const label = `${app}/${t.capability ?? t.event}`;
342
+ const manifest = byApp.get(app);
343
+ const required = dep.required;
344
+ if (!manifest) {
345
+ const severity = required ? "input" : "note";
346
+ const fid = c.find({ severity, code: "dependency.contract-missing", state: "unknown", subject: dep.id, message: `${s.ref} ${required ? "requires" : "optionally uses"} ${label} but no contract for ${app} was supplied`, capabilities: [s.ref, label], missing: [`contract:${app}`], hints: ["fetch the application's manifest and supply it; AppPort has no registry to find it"] });
347
+ c.decide({ id: `dependency:${s.ref}:${dep.id}`, question: `Is ${label} available and compatible?`, state: "unknown", provenance: "declared", findings: [fid] });
348
+ dependencies.push({ from: s.ref, relationship: dep.relationship, target: label, required, resolved: false, provenance: "declared" });
349
+ continue;
350
+ }
351
+ involved.add(app);
352
+ if (t.event !== undefined) {
353
+ const ok = manifest.events.some((e) => e.name === t.event);
354
+ const fid = ok ? undefined : c.find({ severity: required ? "blocker" : "note", code: "dependency.incompatible", state: "incompatible", subject: dep.id, message: `${app} does not declare event ${t.event}`, capabilities: [s.ref, label], hints: ["the provider's contract no longer offers what this capability depends on"] });
355
+ c.decide({ id: `dependency:${s.ref}:${dep.id}`, question: `Is ${label} available and compatible?`, state: ok ? "declared" : "incompatible", ...(ok ? { answer: "declared", source: `${app}#/events/${t.event}` } : {}), provenance: "declared", findings: fid ? [fid] : [] });
356
+ dependencies.push({ from: s.ref, relationship: dep.relationship, target: label, required, resolved: ok, provenance: "declared" });
357
+ continue;
358
+ }
359
+ const ref = parseDependencyRef(t.capability);
360
+ const candidates = (manifest.capabilities.find((x) => x.name === ref.name)?.definitions ?? []).filter((d) => ref.version !== undefined ? d.version === ref.version : satisfiesVersionConstraint(d.version, dep.versionConstraint ?? ""));
361
+ const live = candidates.filter((d) => !d.deprecated);
362
+ const chosen = (live.length ? live : candidates).sort((a, b) => b.version - a.version)[0];
363
+ if (!chosen) {
364
+ const fid = c.find({ severity: required ? "blocker" : "note", code: "dependency.incompatible", state: "incompatible", subject: dep.id, message: `${app} declares no ${t.capability}${dep.versionConstraint ? ` satisfying ${dep.versionConstraint}` : ""}`, capabilities: [s.ref, label], hints: ["the provider's contract no longer offers what this capability depends on"] });
365
+ c.decide({ id: `dependency:${s.ref}:${dep.id}`, question: `Is ${label} available and compatible?`, state: "incompatible", provenance: "declared", findings: [fid] });
366
+ dependencies.push({ from: s.ref, relationship: dep.relationship, target: label, required, resolved: false, provenance: "declared" });
367
+ continue;
368
+ }
369
+ const key = integrationKey(ref.name, chosen.version);
370
+ const targetFacts = classifyDeclarations(chosen, getIntegration(manifest)?.capabilities[key]);
371
+ let fid;
372
+ if (dep.relationship === "observes" && targetFacts.effect.value === "consequential") {
373
+ fid = c.find({ severity: required ? "blocker" : "note", code: "dependency.incompatible", state: "incompatible", subject: dep.id, message: `${s.ref} observes ${app}/${key}, which is declared consequential`, capabilities: [s.ref, `${app}/${key}`], hints: ["an observes dependency must be an observation; the dependent's declaration or the dependency's effect is wrong"] });
374
+ }
375
+ else if (targetFacts.effect.state === "unknown") {
376
+ fid = c.find({ severity: required ? "input" : "note", code: "effect.undeclared", state: "unknown", subject: "dependency", message: `${app}/${key} (a dependency of ${s.ref}) does not declare its effect`, capabilities: [`${app}/${key}`], acknowledgeable: true });
377
+ }
378
+ else if (chosen.deprecated) {
379
+ fid = c.find({ severity: "note", code: "dependency.deprecated", state: "declared", subject: dep.id, message: `${app}/${key} is deprecated`, capabilities: [s.ref, `${app}/${key}`] });
380
+ }
381
+ c.decide({ id: `dependency:${s.ref}:${dep.id}`, question: `Is ${label} available and compatible?`, state: fid && c.findings.get(fid)?.state === "incompatible" ? "incompatible" : fid && c.findings.get(fid)?.state === "unknown" ? "unknown" : "declared", ...(fid && c.findings.get(fid)?.state !== "declared" ? {} : { answer: key, source: `${app}#/capabilities/${key}` }), provenance: "declared", findings: fid ? [fid] : [] });
382
+ dependencies.push({ from: s.ref, relationship: dep.relationship, target: `${app}/${key}`, required, resolved: true, provenance: "declared" });
383
+ const fidAuth = c.find({ severity: "note", code: "dependency.authority-unobserved", state: "requires-observation", subject: `${s.ref}->${app}/${key}`, message: `how ${s.application} authenticates to ${app}/${key} is not part of either contract`, capabilities: [s.ref, `${app}/${key}`] });
384
+ c.decide({ id: `dependency-authority:${s.ref}:${dep.id}`, question: `What credential does ${s.application} use to call ${app}/${key}?`, state: "requires-observation", provenance: "declared", findings: [fidAuth] });
385
+ const next = `${app}/${key}`;
386
+ if (!seen.has(next)) {
387
+ const further = getIntegration(manifest)?.capabilities[key]?.requires ?? [];
388
+ if (depth >= MAX_DEPENDENCY_DEPTH) {
389
+ // Never silently stop: what lies beyond is unanalysed, so neither "no cycle" nor "all dependencies satisfied" can be concluded.
390
+ if (further.length)
391
+ c.find({ severity: required ? "unverifiable" : "note", code: "dependency.analysis-incomplete", state: "unknown", subject: next, message: `dependencies of ${next} were not analysed: the chain from ${s.ref} exceeds ${MAX_DEPENDENCY_DEPTH} levels, so cycles and unsatisfied requirements beyond it are unknown`, capabilities: [s.ref, next], hints: ["plan from a capability nearer the end of the chain, or analyse that dependency's contract separately"] });
392
+ }
393
+ else {
394
+ seen.add(next);
395
+ const sub = { manifest, application: app, key, ref: next, definition: chosen, facts: targetFacts };
396
+ resolveDependencies(sub, further, depth + 1, seen);
397
+ }
398
+ }
399
+ }
400
+ };
401
+ if (source)
402
+ assess(source, "source");
403
+ if (target)
404
+ assess(target, "target");
405
+ // ---- required synchronous dependency cycles among what the declarations resolve to
406
+ {
407
+ const adjacency = new Map();
408
+ for (const d of dependencies)
409
+ if (d.required && d.resolved && SYNCHRONOUS_RELATIONSHIPS.includes(d.relationship))
410
+ adjacency.set(d.from, [...(adjacency.get(d.from) ?? []), d.target]);
411
+ const state = new Map();
412
+ const reported = new Set();
413
+ const visit = (node, trail) => {
414
+ state.set(node, "visiting");
415
+ for (const next of adjacency.get(node) ?? []) {
416
+ if (state.get(next) === "visiting") {
417
+ const members = [...new Set(trail.slice(trail.indexOf(next)))].sort();
418
+ const id = members.join("+");
419
+ if (!reported.has(id)) {
420
+ reported.add(id);
421
+ const path = [...trail.slice(trail.indexOf(next)), next];
422
+ c.find({ severity: "blocker", code: "dependency.cycle", state: "incompatible", subject: "cycle", message: `required synchronous dependency cycle: ${path.join(" → ")}; none of these can complete before the others`, capabilities: members, hints: ["the publishers' declarations are mutually unsatisfiable: ask them to break the cycle (make one edge optional or asynchronous)"] });
423
+ }
424
+ }
425
+ else if (!state.has(next))
426
+ visit(next, [...trail, next]);
427
+ }
428
+ state.set(node, "done");
429
+ };
430
+ for (const node of [...adjacency.keys()].sort())
431
+ if (!state.has(node))
432
+ visit(node, [node]);
433
+ }
434
+ // ---- staleness and compatibility ------------------------------------------------------------
435
+ const contracts = {};
436
+ for (const application of [...involved].sort()) {
437
+ const manifest = byApp.get(application);
438
+ const digest = contractDigest(manifest);
439
+ contracts[application] = digest;
440
+ const pin = input.pins?.[application];
441
+ if (pin !== undefined && pin !== digest) {
442
+ c.find({ severity: "blocker", code: "contract.stale", state: "incompatible", subject: application, message: `${application}'s contract changed since it was pinned (${pin} → ${digest})`, capabilities: [application], hints: ["re-plan against the current contract; do not execute a plan made from the pinned one"] });
443
+ }
444
+ const previous = input.previous?.find((m) => m.application.id === application);
445
+ if (previous) {
446
+ const report = compareManifests(previous, manifest);
447
+ const touched = [source, target].filter((x) => !!x && x.application === application);
448
+ for (const change of report.breaking) {
449
+ if (touched.some((s) => change.target === s.key || change.target.startsWith(`${s.key} `) || change.target === s.key.split("@")[0])) {
450
+ c.find({ severity: "blocker", code: "contract.breaking-change", state: "incompatible", subject: `${change.kind}:${change.target}`, message: `since the previous contract: ${change.message}`, capabilities: [`${application}/${change.target}`], hints: ["the change breaks consumers of the previous contract in the direction that matters for them"] });
451
+ }
452
+ }
453
+ }
454
+ }
455
+ // ---- what the runtime evidence could see
456
+ for (const application of [...involved].sort()) {
457
+ const statements = (input.coverage ?? []).filter((x) => x.application === application);
458
+ const evidenced = (input.findings ?? []).some((f) => f.provenance === "observed" && (f.evidence.source === INVOCATION_BOUNDARY_SOURCE || f.evidence.source === STATE_BOUNDARY_SOURCE) && (f.subject.application ?? "") === application);
459
+ for (const statement of statements) {
460
+ const problems = validateCoverage(statement);
461
+ const summary = summarizeCoverage(statement);
462
+ c.find({ severity: "note", code: problems.length ? "observation.unusable" : "observation.limited", state: "requires-observation", subject: application, message: problems.length ? `the coverage statement for ${application} is unusable (${problems.join("; ")})` : `${application} was observed through ${summary.observedThrough.join(" and ")} from ${statement.interval.from} to ${statement.interval.to}; not observed: ${summary.notObserved.join("; ")}`, capabilities: [application], hints: ["observed means seen during the interval through those boundaries, not that nothing else happens"] });
463
+ }
464
+ if (evidenced && statements.length === 0) {
465
+ c.find({ severity: "note", code: "observation.unstated", state: "requires-observation", subject: application, message: `runtime evidence about ${application} was supplied without a coverage statement: which boundaries and interval were instrumented is unknown`, capabilities: [application] });
466
+ }
467
+ }
468
+ // ---- semantic compatibility (transfer) ------------------------------------------------------
469
+ if (task.kind === "transfer" && source && target) {
470
+ const sf = describeFootprint(source.manifest, source.key.split("@")[0], Number(source.key.split("@")[1]));
471
+ const tf = describeFootprint(target.manifest, target.key.split("@")[0], Number(target.key.split("@")[1]));
472
+ fields = pairFields(sf, tf, input.bindings ?? {});
473
+ const pair = `${source.ref} → ${target.ref}`;
474
+ const hardRows = fields.filter((f) => f.verdict !== "exact");
475
+ // Mappings: declared by either side, supplied by the consumer, verified, linted, run against their own vectors.
476
+ const sDesc = getIntegration(source.manifest);
477
+ const tDesc = getIntegration(target.manifest);
478
+ const refs = new Map();
479
+ for (const r of sDesc?.mappings ?? [])
480
+ if (r.for === source.key && r.direction === "outbound")
481
+ refs.set(`${r.id}@${r.version}`, r);
482
+ for (const r of tDesc?.mappings ?? [])
483
+ if (r.for === target.key && r.direction === "inbound")
484
+ refs.set(`${r.id}@${r.version}`, r);
485
+ const covered = new Set();
486
+ let mapped;
487
+ const sortedRefs = [...refs].sort(([a], [b]) => a.localeCompare(b));
488
+ for (const [mappingKey, reference] of sortedRefs) {
489
+ const base = { id: reference.id, version: reference.version, direction: reference.direction, for: reference.for, origin: reference.origin, needed: hardRows.length > 0, expectedDigest: reference.digest, eligible: false, disposition: hardRows.length ? "artifact-missing" : "not-needed", acceptedLocally: false, reasons: [] };
490
+ if (!hardRows.length) {
491
+ mappingAssessments.push(base);
492
+ continue;
493
+ }
494
+ const digestOfSafe = (a) => { try {
495
+ return digestOf(a);
496
+ }
497
+ catch {
498
+ return undefined;
499
+ } };
500
+ const supplied = [...(reference.artifact !== undefined ? [reference.artifact] : []), ...(input.artifacts ?? [])];
501
+ const raw = supplied.find((a) => digestOfSafe(a) === reference.digest);
502
+ if (raw === undefined) {
503
+ const sameIdentity = supplied.filter((a) => { const x = a; return x !== null && typeof x === "object" && x.id === reference.id && x.version === reference.version; });
504
+ if (sameIdentity.length) {
505
+ const actual = digestOfSafe(sameIdentity[0]);
506
+ c.find({ severity: "blocker", code: "mapping.digest-mismatch", state: "incompatible", subject: mappingKey, message: `${mappingKey}: the supplied artifact hashes to ${actual}, the contract references ${reference.digest}`, capabilities: [source.ref, target.ref], missing: [`digest:${reference.digest}`], hints: ["the bytes are not the ones the contract points to; fetch the referenced artifact, or have the publisher publish a new version"] });
507
+ mappingAssessments.push({ ...base, ...(actual ? { actualDigest: actual } : {}), disposition: "invalid", reasons: ["digest.mismatch"] });
508
+ }
509
+ else {
510
+ c.find({ severity: "input", code: "mapping.artifact-missing", state: "unknown", subject: mappingKey, message: `${mappingKey} is referenced by a contract but its artifact was not supplied`, capabilities: [source.ref, target.ref], missing: [`mapping:${mappingKey}`, `digest:${reference.digest}`], hints: [`fetch it from ${(reference.uri ?? ["a location you trust"]).join(" or ")} and supply it; it is accepted only if it hashes to the digest. Where it came from confers no trust`] });
511
+ mappingAssessments.push({ ...base, reasons: ["artifact.missing"] });
512
+ }
513
+ continue;
514
+ }
515
+ let artifact;
516
+ try {
517
+ artifact = verifyMappingArtifact(reference, raw);
518
+ }
519
+ catch (error) {
520
+ c.find({ severity: "blocker", code: "mapping.invalid", state: "incompatible", subject: mappingKey, message: `${mappingKey}: ${error instanceof Error ? error.message : String(error)}`, capabilities: [source.ref, target.ref] });
521
+ mappingAssessments.push({ ...base, actualDigest: reference.digest, disposition: "invalid", reasons: ["artifact.malformed"] });
522
+ continue;
523
+ }
524
+ const matches = artifact.from.application === source.application && artifact.from.capability === source.key && artifact.from.side === "output" && artifact.to.application === target.application && artifact.to.capability === target.key && artifact.to.side === "input";
525
+ if (!matches) {
526
+ mappingAssessments.push({ ...base, actualDigest: reference.digest, needed: false, disposition: "not-needed", reasons: ["endpoints.differ"] });
527
+ continue;
528
+ }
529
+ const assessed = { ...base, actualDigest: reference.digest };
530
+ const trustResult = () => {
531
+ const candidates = (input.trust?.results ?? []).filter((r) => r.mapping.id === artifact.id && r.mapping.version === artifact.version && r.mapping.digest === reference.digest);
532
+ return [...candidates].sort((x, y) => Number(y.eligible) - Number(x.eligible) || x.reasons.length - y.reasons.length || (x.authenticity.keyId ?? "").localeCompare(y.authenticity.keyId ?? ""))[0];
533
+ };
534
+ /** The verifier's checks that do not depend on semantics. A mapping that no longer fits the contracts keeps its signature, trust and pin answers: they are separate questions. */
535
+ const withTrustChecks = (a) => {
536
+ const r = trustResult();
537
+ return r ? { ...a, publisher: r.authenticity.publisher, keyId: r.authenticity.keyId, authenticity: r.authenticity.status, integrity: r.integrity.status, trust: { status: r.trust.status, rule: r.trust.rule }, pins: r.pins.status } : a;
538
+ };
539
+ const issues = lintMapping(artifact, { from: source.manifest, to: target.manifest });
540
+ const errors = issues.filter((i) => i.level === "error");
541
+ if (errors.length) {
542
+ c.find({ severity: "blocker", code: "mapping.invalid", state: "incompatible", subject: mappingKey, message: `${mappingKey} does not hold against the current contracts`, capabilities: [source.ref, target.ref], hints: errors.map((e) => `${e.path}: ${e.message}`) });
543
+ mappingAssessments.push(withTrustChecks({ ...assessed, semantic: "invalid", disposition: "incompatible", reasons: ["semantic.invalid"] }));
544
+ continue;
545
+ }
546
+ const failed = runVectors(artifact);
547
+ if (failed.length) {
548
+ c.find({ severity: "blocker", code: "mapping.vectors-failed", state: "incompatible", subject: mappingKey, message: `${mappingKey} fails its own vectors`, capabilities: [source.ref, target.ref], hints: failed });
549
+ mappingAssessments.push(withTrustChecks({ ...assessed, semantic: "invalid", disposition: "incompatible", reasons: ["semantic.vectors-failed"] }));
550
+ continue;
551
+ }
552
+ // Trust: the verifier's five answers, from the supplied assessment. Nothing is inferred when they are missing.
553
+ const subject = mappingKey;
554
+ const caps = [source.ref, target.ref];
555
+ const emitted = [];
556
+ const note = (severity, code, state, message, hints, acknowledgeable, missing) => emitted.push(c.find({ severity, code, state, subject, message: `${mappingKey}: ${message}`, capabilities: caps, hints, acknowledgeable, ...(missing ? { missing } : {}) }));
557
+ const result = trustResult();
558
+ const reasons = new Set();
559
+ let disposition = "eligible";
560
+ const rank = (d) => ["invalid", "rejected", "pin-conflict", "policy-unavailable", "untrusted", "unverifiable", "unsigned", "trust-not-assessed", "pin-missing"].indexOf(d);
561
+ const worse = (d) => { if (disposition === "eligible" || rank(d) < rank(disposition))
562
+ disposition = d; };
563
+ if (!input.trust) {
564
+ note("input", "mapping.trust-not-assessed", "unknown", "its trust was not assessed: no trust assessment was supplied, so it cannot be considered trusted", ["run assessMappingTrust with the artifact, its signature envelope, your trust policy and pins, and pass the result as `trust`", "or acknowledge this finding to accept the mapping on your own responsibility (local acceptance, not trust)"], true);
565
+ reasons.add("trust.not-assessed");
566
+ worse("trust-not-assessed");
567
+ }
568
+ else if (!result) {
569
+ const unsigned = input.trust.unsigned.some((u) => u.id === artifact.id && u.version === artifact.version && u.digest === reference.digest);
570
+ note("input", unsigned ? "mapping.unsigned" : "mapping.trust-not-assessed", "unknown", unsigned ? "no signature envelope was supplied, so its publisher is unknown" : "the trust assessment does not cover this artifact", ["obtain the publisher's signature envelope and supply it to assessMappingTrust", "or acknowledge this finding to accept the mapping on your own responsibility (local acceptance, not trust)"], true);
571
+ reasons.add(unsigned ? "envelope.missing" : "trust.not-assessed");
572
+ worse(unsigned ? "unsigned" : "trust-not-assessed");
573
+ }
574
+ else {
575
+ for (const r of result.reasons)
576
+ reasons.add(r);
577
+ Object.assign(assessed, { publisher: result.authenticity.publisher, keyId: result.authenticity.keyId, authenticity: result.authenticity.status, integrity: result.integrity.status, trust: { status: result.trust.status, rule: result.trust.rule }, semantic: result.semantic.status, pins: result.pins.status });
578
+ if (result.integrity.status === "invalid") {
579
+ note("blocker", "mapping.integrity-failed", "incompatible", `the artifact does not match what was signed (${result.integrity.reasons.join(", ")})`, ["fetch the artifact the signature covers; do not use altered bytes"], false);
580
+ worse("invalid");
581
+ }
582
+ if (result.authenticity.status === "invalid") {
583
+ note("blocker", "mapping.invalid-signature", "incompatible", `the signature does not verify (${result.authenticity.reasons.join(", ")})`, ["obtain a correct signature envelope from the publisher"], false);
584
+ worse("invalid");
585
+ }
586
+ else if (result.authenticity.status === "unverifiable" && result.trust.status !== "unavailable") {
587
+ note("input", "mapping.signature-unverifiable", "unknown", `authenticity could not be established (${result.authenticity.reasons.join(", ")})`, ["supply the key material through your trust policy, or run where Ed25519 verification is available", "or acknowledge this finding to accept the mapping on your own responsibility (local acceptance, not trust)"], true);
588
+ worse("unverifiable");
589
+ }
590
+ if (result.trust.status === "rejected" || result.trust.status === "revoked" || result.trust.status === "out-of-scope") {
591
+ note("blocker", "mapping.publisher-rejected", "incompatible", `your trust policy rejects it (${result.trust.status}, rule ${result.trust.rule})`, ["choose a mapping from a publisher and key your policy trusts, or change your policy deliberately"], false);
592
+ worse("rejected");
593
+ }
594
+ else if (result.trust.status === "unavailable") {
595
+ note("input", "mapping.trust-policy-unavailable", "unknown", "no trust policy was supplied, so no publisher or key can be trusted", ["supply a trust policy (appport.mapping-trust-policy/1) to assessMappingTrust", "or acknowledge this finding to accept the mapping on your own responsibility (local acceptance, not trust)"], true);
596
+ worse("policy-unavailable");
597
+ }
598
+ else if (result.trust.status === "untrusted") {
599
+ note("input", "mapping.untrusted", "unknown", `its publisher and key are not trusted by your policy (rule ${result.trust.rule})`, ["add the publisher's key to your trust policy as trusted if you trust it", "or acknowledge this finding to accept the mapping on your own responsibility (local acceptance, not trust)"], true);
600
+ worse("untrusted");
601
+ }
602
+ if (result.pins.status === "conflict") {
603
+ note("blocker", "mapping.pin-conflict", "incompatible", `the identity is pinned to ${result.pins.pinned}, not ${reference.digest}; an identity never denotes different bytes`, ["treat this as a publisher error or an attack; do not use it", "a legitimate change is a new version"], false);
604
+ worse("pin-conflict");
605
+ }
606
+ else if (result.pins.status === "unchecked") {
607
+ note("input", "mapping.pins-unavailable", "unknown", "pins were not supplied, so identity reuse is not being checked", ["supply a MappingPins store to assessMappingTrust"], false);
608
+ worse("pin-missing");
609
+ }
610
+ if (result.semantic.status !== "valid" && !result.semantic.reasons.every((x) => x === "semantic.generated-origin")) {
611
+ note("blocker", "mapping.invalid", "incompatible", `the trust assessment found it semantically invalid (${result.semantic.reasons.join(", ")})`, ["re-run the assessment against the current manifests"], false);
612
+ disposition = "incompatible";
613
+ }
614
+ }
615
+ const open = emitted.map((id) => c.findings.get(id));
616
+ const blocked = open.some((f) => f.severity === "blocker" || (f.severity === "input" && !f.acknowledged));
617
+ const acceptedLocally = open.length > 0 && !blocked && open.some((f) => f.acknowledged);
618
+ const usable = (open.length === 0 && Boolean(result?.eligible)) || acceptedLocally;
619
+ const finalDisposition = usable ? (acceptedLocally ? "accepted-locally" : "eligible") : blocked && open.every((f) => f.acknowledgeable && f.severity === "input") ? "needs-local-acceptance" : disposition;
620
+ mappingAssessments.push({ ...assessed, eligible: Boolean(result?.eligible), disposition: finalDisposition, acceptedLocally, reasons: [...reasons].sort() });
621
+ if (!usable)
622
+ continue;
623
+ mapped ??= artifact;
624
+ usedMappings.push({ id: artifact.id, version: artifact.version, digest: reference.digest });
625
+ for (const rule of artifact.rules)
626
+ covered.add(rule.to);
627
+ if (artifact.origin === "generated")
628
+ c.find({ severity: "input", code: "mapping.untrusted-origin", state: "unknown", subject: mappingKey, message: `${mappingKey} was generated; it is untrusted until accepted by local policy`, capabilities: [source.ref, target.ref], acknowledgeable: true });
629
+ if (artifact.lossy.length) {
630
+ c.find({ severity: task.tolerateLossy ? "note" : "input", code: "mapping.lossy", state: "declared", subject: mappingKey, message: `${mappingKey} declares loss: ${artifact.lossy.map((l) => `${l.kind} (${l.note})`).join("; ")}`, capabilities: [source.ref, target.ref], acknowledgeable: !task.tolerateLossy, hints: ["set tolerateLossy, or acknowledge this finding, if the loss is acceptable for the task"] });
631
+ }
632
+ for (const rule of artifact.rules) {
633
+ if (rule.op === "enum" && Object.values(rule.table).some((v) => typeof v === "object" && v !== null && "ambiguous" in v) && !(input.choices ?? []).includes(rule.to)) {
634
+ c.find({ severity: "input", code: "mapping.choices-required", state: "unknown", subject: rule.to, message: `${mappingKey} maps some values of ${rule.from} ambiguously; the caller must choose for ${rule.to}`, capabilities: [source.ref, target.ref], missing: [`choice:${rule.to}`], hints: ["state the target pointer in `choices` and pass the chosen values at mapping time"] });
635
+ }
636
+ }
637
+ c.step({ action: "map", application: target.application, detail: { mapping: artifact.id, version: artifact.version, digest: reference.digest, from: source.ref, to: target.ref, disposition: finalDisposition } });
638
+ }
639
+ const provide = new Set(input.provide ?? []);
640
+ for (const row of fields) {
641
+ const id = `field:${pair}:${row.target}`;
642
+ const question = `How is ${target.ref} input ${row.target} obtained from ${source.ref}?`;
643
+ if (row.verdict === "exact") {
644
+ c.decide({ id, question, state: "declared", answer: { from: row.source, concept: row.concept }, source: `${source.application}#${source.key}/output${row.source},${target.application}#${target.key}/input${row.target}`, provenance: "declared" });
645
+ continue;
646
+ }
647
+ if (covered.has(row.target)) {
648
+ c.decide({ id, question, state: "declared", answer: { mapping: mapped.id, version: mapped.version }, source: `${mapped.id}@${mapped.version}`, provenance: "declared" });
649
+ continue;
650
+ }
651
+ if (row.verdict === "no-source" && provide.has(row.target)) {
652
+ c.decide({ id, question, state: "declared", answer: "supplied by the caller", provenance: "caller", source: "caller.provide" });
653
+ continue;
654
+ }
655
+ const spec = {
656
+ exact: { severity: "note", code: "", state: "declared", ack: false, hint: "" },
657
+ "needs-conversion": { severity: "input", code: "semantics.conversion-required", state: "unknown", ack: false, hint: "supply a mapping artifact that performs and declares this conversion" },
658
+ incompatible: { severity: "blocker", code: "semantics.incompatible", state: "incompatible", ack: false, hint: "the two contracts describe quantities that cannot be converted" },
659
+ "unit-unstated": { severity: "input", code: "semantics.unit-unstated", state: "unknown", ack: false, hint: "a missing unit is the classic silent conversion error; obtain a contract that declares it, or supply a mapping" },
660
+ "encoding-unstated": { severity: "input", code: "semantics.encoding-unstated", state: "unknown", ack: false, hint: "obtain a contract that declares the encoding, or supply a mapping" },
661
+ "enum-unmapped": { severity: "input", code: "semantics.enum-unmapped", state: "unknown", ack: false, hint: "supply a mapping that states how the enumerations correspond" },
662
+ "ambiguous-source": { severity: "input", code: "semantics.ambiguous-source", state: "unknown", ack: false, hint: "state which source field to use in `bindings`" },
663
+ "no-source": { severity: "input", code: "input.required", state: "unknown", ack: false, hint: "list the target pointer in `provide` if the caller will supply it" },
664
+ "concept-missing-target": { severity: "input", code: "semantics.missing", state: "unknown", ack: true, hint: "obtain a contract that declares the concept, or supply a mapping" },
665
+ "concept-missing-source": { severity: "input", code: "semantics.missing", state: "unknown", ack: true, hint: "obtain a contract that declares the concept, or bind the field explicitly" }
666
+ };
667
+ const sp = spec[row.verdict];
668
+ const fid = c.find({ severity: sp.severity, code: sp.code, state: sp.state, subject: row.target, message: `${row.target}: ${row.detail ?? row.verdict}`, capabilities: [source.ref, target.ref], missing: [`field:${row.target}`], hints: [sp.hint, ...(row.candidates ? [`candidates: ${row.candidates.join(", ")}`] : [])], acknowledgeable: sp.ack });
669
+ c.decide({ id, question, state: sp.state, provenance: "declared", findings: [fid] });
670
+ }
671
+ }
672
+ // ---- steps ---------------------------------------------------------------------------------
673
+ const ordered = [];
674
+ const add = (action, rest) => ordered.push({ action, order: 0, ...rest });
675
+ for (const s of c.steps.filter((x) => x.action === "check-precondition"))
676
+ ordered.push(s);
677
+ for (const s of c.steps.filter((x) => x.action === "obtain-approval"))
678
+ ordered.push(s);
679
+ for (const role of ["source", "target"]) {
680
+ const subject = role === "source" ? source : target;
681
+ if (!subject)
682
+ continue;
683
+ if (role === "target")
684
+ for (const s of c.steps.filter((x) => x.action === "map"))
685
+ ordered.push(s);
686
+ const facts = subject.facts;
687
+ add("invoke", { application: subject.application, capability: subject.key, detail: { role, effect: facts.effect.value ?? null, retry: facts.retry, ...(facts.retry === "safe-with-idempotency-key" ? { idempotencyKey: "required: bind one key to this exact input" } : {}), ...(facts.retry === "unknown" || facts.retry === "unsafe" ? { onFailure: "do not retry before verifying" } : {}) } });
688
+ const methods = (getIntegration(subject.manifest)?.capabilities[subject.key]?.verify ?? []).filter((m) => m.kind === "state");
689
+ if (methods.length && facts.effect.value !== "observation") {
690
+ add("verify", { application: subject.application, capability: subject.key, detail: { methods: methods.map((m) => m.id), evidence: "appport.verification-evidence/1", required: "outcome verified", note: "ok: true is not evidence of a persisted effect" } });
691
+ }
692
+ }
693
+ const steps = ordered.map((s, i) => ({ ...s, order: i + 1 }));
694
+ // ---- result --------------------------------------------------------------------------------
695
+ const findingsEarly = [...c.findings.values()];
696
+ const conditions = [];
697
+ for (const r of requirementsList) {
698
+ if (r.approval.value?.required)
699
+ conditions.push({ kind: "approval", capability: r.capability, detail: `approval${r.approval.value.approver ? ` from ${r.approval.value.approver}` : ""} is required before invoking; the plan only records the caller's statement` });
700
+ if (r.authorization.value?.mode === "scoped")
701
+ conditions.push({ kind: "scope", capability: r.capability, detail: `the caller's credential must hold ${r.authorization.value.scopes.join(", ")}` });
702
+ for (const id of r.preconditions)
703
+ conditions.push({ kind: "precondition", capability: r.capability, detail: `check precondition ${id} immediately before invoking` });
704
+ if (r.retry === "safe-with-idempotency-key")
705
+ conditions.push({ kind: "idempotency-key", capability: r.capability, detail: "send one idempotency key bound to this exact input; retry only with the same key" });
706
+ if (r.effect.value !== "observation" && r.verification.methods.some((m) => m.kind === "state"))
707
+ conditions.push({ kind: "verification-after", capability: r.capability, detail: `run ${r.verification.methods.filter((m) => m.kind === "state").map((m) => m.id).join(", ")} and require outcome verified; ok:true is not evidence` });
708
+ }
709
+ for (const m of mappingAssessments)
710
+ if (m.needed && (m.disposition === "eligible" || m.disposition === "accepted-locally"))
711
+ conditions.push({ kind: "mapping", detail: `apply ${m.id}@${m.version} (${m.disposition}${m.publisher ? `, publisher ${m.publisher}` : ""}); the planner did not run it${m.eligible ? "; trust is as of the supplied policy, whose currency is not established" : ""}` });
712
+ const relyingOnPolicy = mappingAssessments.filter((m) => m.needed && m.eligible);
713
+ if (relyingOnPolicy.length)
714
+ c.find({ severity: "note", code: "trust.policy-currency-unestablished", state: "unknown", subject: "policy", message: `${relyingOnPolicy.map((m) => `${m.id}@${m.version}`).join(", ")} ${relyingOnPolicy.length === 1 ? "is" : "are"} trusted by the supplied policy only; whether that policy is current (key status, revocations) is not established`, capabilities: [], hints: ["refresh the trust policy from its own source immediately before relying on the plan; AppPort distributes no key status"] });
715
+ for (const f of findingsEarly)
716
+ if (f.acknowledged)
717
+ conditions.push({ kind: "acknowledged", ...(f.capabilities[0] ? { capability: f.capabilities[0] } : {}), detail: `accepted on the caller's word: ${f.code} (${f.message})` });
718
+ conditions.sort((a, b) => `${a.kind}|${a.capability ?? ""}|${a.detail}`.localeCompare(`${b.kind}|${b.capability ?? ""}|${b.detail}`));
719
+ const findings = [...c.findings.values()].sort((a, b) => RANK[a.severity] - RANK[b.severity] || a.id.localeCompare(b.id));
720
+ const status = findings.some((f) => f.severity === "blocker") ? "blocked" : findings.some((f) => f.severity === "input") ? "needs_input" : findings.some((f) => f.severity === "unverifiable") ? "unverifiable" : "ready";
721
+ const nextActions = findings
722
+ .filter((f) => f.severity !== "note")
723
+ .map((f) => ({ finding: f.id, severity: f.severity, action: f.hints[0] ?? (f.missing.length ? `provide ${f.missing.join(", ")}` : f.message) }));
724
+ const feasibility = status === "ready" ? "feasible" : status === "blocked" ? "not-feasible" : "undetermined";
725
+ const clean = (value) => JSON.parse(JSON.stringify(value));
726
+ return clean({
727
+ format: PLAN_FORMAT,
728
+ status,
729
+ task: task,
730
+ basis: { contracts, mappings: usedMappings.sort((a, b) => a.id.localeCompare(b.id) || a.version - b.version) },
731
+ selected: { ...(selected.source ? { source: selected.source } : {}), ...(selected.target ? { target: selected.target } : {}), candidates: selected.candidates },
732
+ decisions: [...c.decisions.values()].sort((a, b) => a.id.localeCompare(b.id)),
733
+ findings,
734
+ fields,
735
+ dependencies: dependencies.sort((a, b) => `${a.from}${a.target}`.localeCompare(`${b.from}${b.target}`)),
736
+ mappings: mappingAssessments.sort((a, b) => `${a.id}@${a.version}`.localeCompare(`${b.id}@${b.version}`)),
737
+ requirements: requirementsList.sort((a, b) => a.role.localeCompare(b.role) || a.capability.localeCompare(b.capability)),
738
+ feasibility,
739
+ conditions,
740
+ nextActions,
741
+ steps,
742
+ authorization: { granted: false, note: "A plan authorizes nothing. Calling a capability requires the caller's own credentials and any approval the publisher requires." },
743
+ limits: [...PLAN_LIMITS]
744
+ });
745
+ }
746
+ //# sourceMappingURL=plan.js.map