@atcn/core 0.0.0-stage → 1.3.2
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.
- package/LICENSE +202 -0
- package/README.md +15 -2
- package/dist/allocation.d.ts +16 -0
- package/dist/allocation.js +32 -0
- package/dist/clearing.d.ts +46 -0
- package/dist/clearing.js +221 -0
- package/dist/delegation.d.ts +30 -0
- package/dist/delegation.js +87 -0
- package/dist/evidence.d.ts +12 -0
- package/dist/evidence.js +42 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/journal.d.ts +73 -0
- package/dist/journal.js +130 -0
- package/dist/package.d.ts +20 -0
- package/dist/package.js +214 -0
- package/dist/service.d.ts +11 -0
- package/dist/service.js +17 -0
- package/dist/templates.d.ts +8 -0
- package/dist/templates.js +62 -0
- package/package.json +35 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @atcn/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The ATCN clearing engine. It turns verifier results into a decision under the agreed policy, posts the balanced journal (payee amount and platform fee), builds service events, and exports closure packages. It also exports `verifyClosurePackage`, the offline verifier for those packages. The package includes the reference policies (`REFERENCE_POLICIES`).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @atcn/core
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { verifyClosurePackage } from "@atcn/core";
|
|
11
|
+
|
|
12
|
+
const report = verifyClosurePackage(closurePackage, { trustedKeys });
|
|
13
|
+
console.log(report.valid, report.checks);
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
See [`examples/local-runner/src/network.ts`](../../examples/local-runner/src/network.ts) for the full flow: evaluation, clearing and settlement. Part of [ATCN](../../README.md). Apache-2.0.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface Share {
|
|
2
|
+
key: string;
|
|
3
|
+
weight: number;
|
|
4
|
+
}
|
|
5
|
+
export interface AllocationResult {
|
|
6
|
+
amounts: Record<string, number>;
|
|
7
|
+
method: "largest_remainder";
|
|
8
|
+
/** Human-readable record of how remainders were distributed (LJ-7). */
|
|
9
|
+
detail: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Splits an integer amount by integer weights using the largest-remainder method.
|
|
13
|
+
* Ties on the remainder are broken by key in ascending order, so the result is
|
|
14
|
+
* deterministic and always sums exactly to `total`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function allocateLargestRemainder(total: number, shares: Share[]): AllocationResult;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits an integer amount by integer weights using the largest-remainder method.
|
|
3
|
+
* Ties on the remainder are broken by key in ascending order, so the result is
|
|
4
|
+
* deterministic and always sums exactly to `total`.
|
|
5
|
+
*/
|
|
6
|
+
export function allocateLargestRemainder(total, shares) {
|
|
7
|
+
if (!Number.isSafeInteger(total) || total < 0)
|
|
8
|
+
throw new Error("total must be a non-negative safe integer");
|
|
9
|
+
const weightSum = shares.reduce((sum, s) => sum + s.weight, 0);
|
|
10
|
+
if (weightSum <= 0)
|
|
11
|
+
throw new Error("weights must sum to a positive number");
|
|
12
|
+
const rows = shares.map((share) => {
|
|
13
|
+
const exactNumerator = total * share.weight;
|
|
14
|
+
const floor = Math.floor(exactNumerator / weightSum);
|
|
15
|
+
const remainder = exactNumerator - floor * weightSum;
|
|
16
|
+
return { key: share.key, floor, remainder };
|
|
17
|
+
});
|
|
18
|
+
let leftover = total - rows.reduce((sum, r) => sum + r.floor, 0);
|
|
19
|
+
const order = [...rows].sort((a, b) => b.remainder - a.remainder || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
20
|
+
const bonus = {};
|
|
21
|
+
for (const row of order) {
|
|
22
|
+
if (leftover === 0)
|
|
23
|
+
break;
|
|
24
|
+
bonus[row.key] = 1;
|
|
25
|
+
leftover -= 1;
|
|
26
|
+
}
|
|
27
|
+
const amounts = {};
|
|
28
|
+
for (const row of rows)
|
|
29
|
+
amounts[row.key] = row.floor + (bonus[row.key] ?? 0);
|
|
30
|
+
const remainderNotes = rows.map((r) => `${r.key}=${r.floor}+${bonus[r.key] ?? 0}(rem ${r.remainder}/${weightSum})`);
|
|
31
|
+
return { amounts, method: "largest_remainder", detail: `total=${total}; ${remainderNotes.join("; ")}` };
|
|
32
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type DecisionBody, type EvidenceEnvelope, type ObligationTerms, type PolicyCheck, type PolicyTemplate, type VerifierResult, type ClearingOutcome, type EventType } from "@atcn/schema";
|
|
2
|
+
export declare const CLEARING_ENGINE_ID = "atcn-clearing-engine@1.0.0";
|
|
3
|
+
/** The service event that records each decision outcome. */
|
|
4
|
+
export declare const OUTCOME_EVENT: Record<ClearingOutcome, EventType>;
|
|
5
|
+
export type ProducerRole = "issuer" | "counterparty" | "verifier" | "other";
|
|
6
|
+
export interface EvidenceInput {
|
|
7
|
+
envelope: EvidenceEnvelope;
|
|
8
|
+
event_id: string;
|
|
9
|
+
producer_role: ProducerRole;
|
|
10
|
+
superseded: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface ClearingInput {
|
|
13
|
+
terms: ObligationTerms;
|
|
14
|
+
terms_digest: string;
|
|
15
|
+
policy: PolicyTemplate;
|
|
16
|
+
policy_digest: string;
|
|
17
|
+
acceptance_event_id: string;
|
|
18
|
+
completion_event_id: string | null;
|
|
19
|
+
evidence: EvidenceInput[];
|
|
20
|
+
verifier_results: VerifierResult[];
|
|
21
|
+
decision_maker?: {
|
|
22
|
+
type: "automated" | "human";
|
|
23
|
+
id: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export declare function isAdmissible(evidence: EvidenceInput, policy: PolicyTemplate): boolean;
|
|
27
|
+
/** Latest admissible evidence of a type covering a deliverable (ordered by created_at, then evidence_id). */
|
|
28
|
+
export declare function selectEvidence(evidence: EvidenceInput[], policy: PolicyTemplate, evidenceType: string, deliverableId: string): EvidenceInput | null;
|
|
29
|
+
export interface CheckPlanItem {
|
|
30
|
+
deliverable_id: string;
|
|
31
|
+
check: PolicyCheck;
|
|
32
|
+
evidence: EvidenceInput | null;
|
|
33
|
+
}
|
|
34
|
+
/** Which verifier runs are needed for an evaluation: one per (deliverable, required check). */
|
|
35
|
+
export declare function planChecks(input: Pick<ClearingInput, "terms" | "policy" | "evidence">): CheckPlanItem[];
|
|
36
|
+
/** Digest of a verifier result over its immutable fields (execution time excluded). */
|
|
37
|
+
export declare function verifierOutputDigest(result: VerifierResult): string;
|
|
38
|
+
/** Decision digest (CL-5): covers inputs and outcome; excludes ids and timestamps. */
|
|
39
|
+
export declare function decisionDigest(body: DecisionBody): string;
|
|
40
|
+
/** Role of an evidence producer, derived only from the signed terms. */
|
|
41
|
+
export declare function producerRole(terms: ObligationTerms, producerId: string): ProducerRole;
|
|
42
|
+
/**
|
|
43
|
+
* Deterministic clearing (CL-2 .. CL-7). Pure function of the accepted terms, the
|
|
44
|
+
* policy version, admissible evidence metadata, and recorded verifier results.
|
|
45
|
+
*/
|
|
46
|
+
export declare function evaluateClearing(input: ClearingInput): DecisionBody;
|
package/dist/clearing.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { digestOf, } from "@atcn/schema";
|
|
2
|
+
export const CLEARING_ENGINE_ID = "atcn-clearing-engine@1.0.0";
|
|
3
|
+
/** The service event that records each decision outcome. */
|
|
4
|
+
export const OUTCOME_EVENT = {
|
|
5
|
+
accepted: "completion.accepted",
|
|
6
|
+
partially_accepted: "completion.partially_accepted",
|
|
7
|
+
rejected: "completion.rejected",
|
|
8
|
+
insufficient_evidence: "completion.insufficient_evidence",
|
|
9
|
+
disputed: "completion.disputed",
|
|
10
|
+
cancelled: "obligation.cancelled",
|
|
11
|
+
expired: "obligation.expired",
|
|
12
|
+
};
|
|
13
|
+
export function isAdmissible(evidence, policy) {
|
|
14
|
+
if (evidence.superseded)
|
|
15
|
+
return false;
|
|
16
|
+
return policy.evidence_admissibility.allowed_producers.includes(evidence.producer_role);
|
|
17
|
+
}
|
|
18
|
+
function covers(envelope, deliverableId) {
|
|
19
|
+
return envelope.deliverable_ids.length === 0 || envelope.deliverable_ids.includes(deliverableId);
|
|
20
|
+
}
|
|
21
|
+
/** Latest admissible evidence of a type covering a deliverable (ordered by created_at, then evidence_id). */
|
|
22
|
+
export function selectEvidence(evidence, policy, evidenceType, deliverableId) {
|
|
23
|
+
const candidates = evidence
|
|
24
|
+
.filter((e) => isAdmissible(e, policy) && e.envelope.evidence_type === evidenceType && covers(e.envelope, deliverableId))
|
|
25
|
+
.sort((a, b) => {
|
|
26
|
+
if (a.envelope.created_at !== b.envelope.created_at)
|
|
27
|
+
return a.envelope.created_at < b.envelope.created_at ? 1 : -1;
|
|
28
|
+
return a.envelope.evidence_id < b.envelope.evidence_id ? 1 : -1;
|
|
29
|
+
});
|
|
30
|
+
return candidates[0] ?? null;
|
|
31
|
+
}
|
|
32
|
+
/** Which verifier runs are needed for an evaluation: one per (deliverable, required check). */
|
|
33
|
+
export function planChecks(input) {
|
|
34
|
+
const plan = [];
|
|
35
|
+
for (const deliverable of input.terms.deliverables) {
|
|
36
|
+
for (const checkId of deliverable.required_checks) {
|
|
37
|
+
const check = input.policy.checks.find((c) => c.check_id === checkId);
|
|
38
|
+
if (!check)
|
|
39
|
+
continue;
|
|
40
|
+
plan.push({
|
|
41
|
+
deliverable_id: deliverable.deliverable_id,
|
|
42
|
+
check,
|
|
43
|
+
evidence: selectEvidence(input.evidence, input.policy, check.evidence_type, deliverable.deliverable_id),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return plan;
|
|
48
|
+
}
|
|
49
|
+
/** Digest of a verifier result over its immutable fields (execution time excluded). */
|
|
50
|
+
export function verifierOutputDigest(result) {
|
|
51
|
+
const { executed_at: _executedAt, result_id: _resultId, ...stable } = result;
|
|
52
|
+
return digestOf(stable);
|
|
53
|
+
}
|
|
54
|
+
/** Decision digest (CL-5): covers inputs and outcome; excludes ids and timestamps. */
|
|
55
|
+
export function decisionDigest(body) {
|
|
56
|
+
return digestOf(body);
|
|
57
|
+
}
|
|
58
|
+
function sortResultsNewestFirst(results) {
|
|
59
|
+
return [...results].sort((a, b) => {
|
|
60
|
+
if (a.executed_at !== b.executed_at)
|
|
61
|
+
return a.executed_at < b.executed_at ? 1 : -1;
|
|
62
|
+
return a.result_id < b.result_id ? 1 : -1;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Role of an evidence producer, derived only from the signed terms. */
|
|
66
|
+
export function producerRole(terms, producerId) {
|
|
67
|
+
if (producerId === terms.issuer_agent_id || producerId === terms.principal_id)
|
|
68
|
+
return "issuer";
|
|
69
|
+
if (producerId === terms.counterparty_agent_id)
|
|
70
|
+
return "counterparty";
|
|
71
|
+
if (terms.verifier_agent_ids.includes(producerId))
|
|
72
|
+
return "verifier";
|
|
73
|
+
return "other";
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Deterministic clearing (CL-2 .. CL-7). Pure function of the accepted terms, the
|
|
77
|
+
* policy version, admissible evidence metadata, and recorded verifier results.
|
|
78
|
+
*/
|
|
79
|
+
export function evaluateClearing(input) {
|
|
80
|
+
const { terms, policy } = input;
|
|
81
|
+
const usedEvidence = new Map();
|
|
82
|
+
const usedResults = new Map();
|
|
83
|
+
const deliverableOutcomes = [];
|
|
84
|
+
for (const deliverable of terms.deliverables) {
|
|
85
|
+
const reasons = [];
|
|
86
|
+
const verdicts = [];
|
|
87
|
+
for (const evidenceType of policy.required_evidence) {
|
|
88
|
+
const found = selectEvidence(input.evidence, policy, evidenceType, deliverable.deliverable_id);
|
|
89
|
+
if (!found) {
|
|
90
|
+
reasons.push({ code: "missing_evidence", evidence_type: evidenceType });
|
|
91
|
+
verdicts.push("insufficient_evidence");
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
usedEvidence.set(found.envelope.evidence_id, found);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const checkId of deliverable.required_checks) {
|
|
98
|
+
const check = policy.checks.find((c) => c.check_id === checkId);
|
|
99
|
+
if (!check) {
|
|
100
|
+
reasons.push({ code: "verifier_unavailable", check_id: checkId, detail: "check not defined by policy" });
|
|
101
|
+
verdicts.push(policy.verifier_unavailable_outcome);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const evidence = selectEvidence(input.evidence, policy, check.evidence_type, deliverable.deliverable_id);
|
|
105
|
+
if (!evidence) {
|
|
106
|
+
reasons.push({ code: "missing_evidence", check_id: checkId, evidence_type: check.evidence_type });
|
|
107
|
+
verdicts.push("insufficient_evidence");
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
usedEvidence.set(evidence.envelope.evidence_id, evidence);
|
|
111
|
+
const results = sortResultsNewestFirst(input.verifier_results).filter((r) => r.check_id === checkId &&
|
|
112
|
+
r.deliverable_id === deliverable.deliverable_id &&
|
|
113
|
+
r.evidence_ids.includes(evidence.envelope.evidence_id) &&
|
|
114
|
+
r.verifier_name === check.verifier &&
|
|
115
|
+
r.verifier_version === check.verifier_version);
|
|
116
|
+
const deterministic = results.find((r) => r.kind === "deterministic");
|
|
117
|
+
const probabilistic = results.find((r) => r.kind === "probabilistic");
|
|
118
|
+
const result = deterministic ?? probabilistic;
|
|
119
|
+
if (!result) {
|
|
120
|
+
reasons.push({ code: "verifier_unavailable", check_id: checkId, detail: "no verifier result recorded" });
|
|
121
|
+
verdicts.push(policy.verifier_unavailable_outcome);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
usedResults.set(verifierOutputDigest(result), result);
|
|
125
|
+
if (result.status === "missing_evidence") {
|
|
126
|
+
reasons.push({ code: "missing_evidence", check_id: checkId, evidence_type: check.evidence_type });
|
|
127
|
+
verdicts.push("insufficient_evidence");
|
|
128
|
+
}
|
|
129
|
+
else if (result.status === "invalid_evidence") {
|
|
130
|
+
reasons.push({ code: "invalid_evidence", check_id: checkId, evidence_type: check.evidence_type });
|
|
131
|
+
verdicts.push("insufficient_evidence");
|
|
132
|
+
}
|
|
133
|
+
else if (result.status === "unavailable") {
|
|
134
|
+
reasons.push({ code: "verifier_unavailable", check_id: checkId });
|
|
135
|
+
verdicts.push(policy.verifier_unavailable_outcome);
|
|
136
|
+
}
|
|
137
|
+
else if (result.kind === "probabilistic") {
|
|
138
|
+
reasons.push({ code: "probabilistic_review_required", check_id: checkId, detail: `probabilistic result: ${result.status}` });
|
|
139
|
+
verdicts.push(policy.probabilistic_routing === "human_review" ? "disputed" : "insufficient_evidence");
|
|
140
|
+
}
|
|
141
|
+
else if (result.status === "fail") {
|
|
142
|
+
reasons.push({ code: "failed_criteria", check_id: checkId });
|
|
143
|
+
verdicts.push("rejected");
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
reasons.push({ code: "passed", check_id: checkId });
|
|
147
|
+
verdicts.push("accepted");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
deliverableOutcomes.push({
|
|
151
|
+
deliverable_id: deliverable.deliverable_id,
|
|
152
|
+
amount_minor: deliverable.amount_minor,
|
|
153
|
+
outcome: combineVerdicts(verdicts),
|
|
154
|
+
reasons,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const outcome = overallOutcome(deliverableOutcomes, policy);
|
|
158
|
+
applyPortionPolicy(deliverableOutcomes, outcome, policy);
|
|
159
|
+
const sumBy = (verdict) => deliverableOutcomes.filter((d) => d.outcome === verdict).reduce((sum, d) => sum + d.amount_minor, 0);
|
|
160
|
+
const inputEventIds = new Set([input.acceptance_event_id]);
|
|
161
|
+
if (input.completion_event_id)
|
|
162
|
+
inputEventIds.add(input.completion_event_id);
|
|
163
|
+
for (const e of usedEvidence.values())
|
|
164
|
+
inputEventIds.add(e.event_id);
|
|
165
|
+
return {
|
|
166
|
+
obligation_id: terms.obligation_id,
|
|
167
|
+
terms_version: terms.terms_version,
|
|
168
|
+
terms_digest: input.terms_digest,
|
|
169
|
+
policy: { policy_id: policy.policy_id, policy_version: policy.policy_version, policy_digest: input.policy_digest },
|
|
170
|
+
outcome,
|
|
171
|
+
currency: terms.currency,
|
|
172
|
+
accepted_amount_minor: outcome === "insufficient_evidence" ? 0 : sumBy("accepted"),
|
|
173
|
+
rejected_amount_minor: sumBy("rejected"),
|
|
174
|
+
disputed_amount_minor: sumBy("disputed"),
|
|
175
|
+
pending_amount_minor: sumBy("insufficient_evidence") + (outcome === "insufficient_evidence" ? sumBy("accepted") : 0),
|
|
176
|
+
deliverable_outcomes: deliverableOutcomes,
|
|
177
|
+
input_event_ids: [...inputEventIds].sort(),
|
|
178
|
+
evidence_digests: [...new Set([...usedEvidence.values()].map((e) => e.envelope.content_digest))].sort(),
|
|
179
|
+
verifier_output_digests: [...usedResults.keys()].sort(),
|
|
180
|
+
decision_maker: input.decision_maker ?? { type: "automated", id: CLEARING_ENGINE_ID },
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Worst verdict wins: insufficient_evidence > disputed > rejected > accepted. */
|
|
184
|
+
function combineVerdicts(verdicts) {
|
|
185
|
+
if (verdicts.includes("insufficient_evidence"))
|
|
186
|
+
return "insufficient_evidence";
|
|
187
|
+
if (verdicts.includes("disputed"))
|
|
188
|
+
return "disputed";
|
|
189
|
+
if (verdicts.includes("rejected"))
|
|
190
|
+
return "rejected";
|
|
191
|
+
return "accepted";
|
|
192
|
+
}
|
|
193
|
+
function overallOutcome(outcomes, policy) {
|
|
194
|
+
const has = (v) => outcomes.some((d) => d.outcome === v);
|
|
195
|
+
const all = (v) => outcomes.every((d) => d.outcome === v);
|
|
196
|
+
if (has("insufficient_evidence"))
|
|
197
|
+
return "insufficient_evidence";
|
|
198
|
+
if (all("accepted"))
|
|
199
|
+
return "accepted";
|
|
200
|
+
if (has("disputed") && !has("accepted"))
|
|
201
|
+
return "disputed";
|
|
202
|
+
if (!has("accepted"))
|
|
203
|
+
return "rejected";
|
|
204
|
+
if (!policy.thresholds.partial_acceptance)
|
|
205
|
+
return "rejected";
|
|
206
|
+
if (has("disputed"))
|
|
207
|
+
return "disputed";
|
|
208
|
+
return "partially_accepted";
|
|
209
|
+
}
|
|
210
|
+
/** Applies failed-portion handling and the all-or-nothing rule after the overall outcome is known. */
|
|
211
|
+
function applyPortionPolicy(outcomes, outcome, policy) {
|
|
212
|
+
for (const d of outcomes) {
|
|
213
|
+
if (outcome === "rejected" && d.outcome === "accepted") {
|
|
214
|
+
d.outcome = "rejected";
|
|
215
|
+
d.reasons.push({ code: "partial_not_permitted" });
|
|
216
|
+
}
|
|
217
|
+
if (outcome === "partially_accepted" && d.outcome === "rejected" && policy.thresholds.failed_portion_outcome === "disputed") {
|
|
218
|
+
d.outcome = "disputed";
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ObligationTerms } from "@atcn/schema";
|
|
2
|
+
/** The amount both parties agree to on acceptance: the sum of the deliverables' amounts. */
|
|
3
|
+
export declare function agreedAmount(terms: ObligationTerms): number;
|
|
4
|
+
export interface ParentContext {
|
|
5
|
+
terms: ObligationTerms;
|
|
6
|
+
state: string;
|
|
7
|
+
/** Depth of the parent in its tree; root = 0. */
|
|
8
|
+
depth: number;
|
|
9
|
+
/** Subdelegation depth still permitted below the parent's own issuer chain (null = unlimited by ancestors). */
|
|
10
|
+
inheritedMaxDepth: number | null;
|
|
11
|
+
/** Sum of max_amount_minor of the parent's existing exposure-holding children (excluding the child being checked). */
|
|
12
|
+
committedChildExposureMinor: number;
|
|
13
|
+
/** Obligation ids from the parent up to the root, parent first. */
|
|
14
|
+
ancestorIds: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface DelegationViolation {
|
|
17
|
+
code: "subdelegation_not_allowed" | "exceeds_remaining_exposure" | "exceeds_subdelegation_total" | "depth_exceeded" | "currency_mismatch" | "deadline_exceeds_parent" | "principal_mismatch" | "issuer_must_be_parent_counterparty" | "payer_must_be_parent_counterparty" | "policy_not_permitted" | "cycle_detected" | "parent_not_active";
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
/** Remaining authorized exposure for new children (OB-3). */
|
|
21
|
+
export declare function remainingExposure(parent: ParentContext): number;
|
|
22
|
+
/**
|
|
23
|
+
* Checks a proposed child obligation against its parent (OB-2, OB-3, OB-5, OB-7).
|
|
24
|
+
* Returns every violation found; an empty list means the child is within bounds.
|
|
25
|
+
*/
|
|
26
|
+
export declare function checkChildAgainstParent(parent: ParentContext, child: ObligationTerms): DelegationViolation[];
|
|
27
|
+
/** Depth budget a child inherits from its parent chain. */
|
|
28
|
+
export declare function inheritedDepthForChild(parent: ParentContext): number;
|
|
29
|
+
/** Generic cycle check over parent links (OB-7). */
|
|
30
|
+
export declare function hasCycle(parentOf: Map<string, string | null>): boolean;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** The amount both parties agree to on acceptance: the sum of the deliverables' amounts. */
|
|
2
|
+
export function agreedAmount(terms) {
|
|
3
|
+
return terms.deliverables.reduce((sum, d) => sum + d.amount_minor, 0);
|
|
4
|
+
}
|
|
5
|
+
const PARENT_STATES_ALLOWING_DELEGATION = ["accepted", "active"];
|
|
6
|
+
/** Remaining authorized exposure for new children (OB-3). */
|
|
7
|
+
export function remainingExposure(parent) {
|
|
8
|
+
const ceiling = Math.min(parent.terms.max_amount_minor, parent.terms.subdelegation_limits?.max_total_minor ?? parent.terms.max_amount_minor);
|
|
9
|
+
return Math.max(0, ceiling - parent.committedChildExposureMinor);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Checks a proposed child obligation against its parent (OB-2, OB-3, OB-5, OB-7).
|
|
13
|
+
* Returns every violation found; an empty list means the child is within bounds.
|
|
14
|
+
*/
|
|
15
|
+
export function checkChildAgainstParent(parent, child) {
|
|
16
|
+
const violations = [];
|
|
17
|
+
const p = parent.terms;
|
|
18
|
+
if (child.obligation_id === p.obligation_id || parent.ancestorIds.includes(child.obligation_id)) {
|
|
19
|
+
violations.push({ code: "cycle_detected", message: "child obligation id already appears in the parent chain" });
|
|
20
|
+
}
|
|
21
|
+
if (!PARENT_STATES_ALLOWING_DELEGATION.includes(parent.state)) {
|
|
22
|
+
violations.push({ code: "parent_not_active", message: `parent is ${parent.state}; delegation requires accepted or active` });
|
|
23
|
+
}
|
|
24
|
+
if (!p.allow_subdelegation || !p.subdelegation_limits) {
|
|
25
|
+
violations.push({ code: "subdelegation_not_allowed", message: "parent obligation does not permit subdelegation" });
|
|
26
|
+
return violations;
|
|
27
|
+
}
|
|
28
|
+
if (child.issuer_agent_id !== p.counterparty_agent_id) {
|
|
29
|
+
violations.push({ code: "issuer_must_be_parent_counterparty", message: "only the parent's counterparty may delegate" });
|
|
30
|
+
}
|
|
31
|
+
if (child.payer_id !== p.counterparty_agent_id) {
|
|
32
|
+
violations.push({ code: "payer_must_be_parent_counterparty", message: "the delegating agent pays for the child" });
|
|
33
|
+
}
|
|
34
|
+
if (child.principal_id !== p.principal_id) {
|
|
35
|
+
violations.push({ code: "principal_mismatch", message: "child must carry the root principal" });
|
|
36
|
+
}
|
|
37
|
+
if (child.currency !== p.currency) {
|
|
38
|
+
violations.push({ code: "currency_mismatch", message: `child currency ${child.currency} differs from parent ${p.currency}` });
|
|
39
|
+
}
|
|
40
|
+
if (Date.parse(child.deadline) > Date.parse(p.deadline)) {
|
|
41
|
+
violations.push({ code: "deadline_exceeds_parent", message: "child deadline is later than parent deadline" });
|
|
42
|
+
}
|
|
43
|
+
const remaining = remainingExposure(parent);
|
|
44
|
+
if (child.max_amount_minor > remaining) {
|
|
45
|
+
violations.push({
|
|
46
|
+
code: "exceeds_remaining_exposure",
|
|
47
|
+
message: `child max_amount_minor ${child.max_amount_minor} exceeds parent's remaining authorized exposure ${remaining}`,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const allowedPolicies = [p.acceptance_policy.policy_id, ...p.subdelegation_limits.allowed_policy_ids];
|
|
51
|
+
if (!allowedPolicies.includes(child.acceptance_policy.policy_id)) {
|
|
52
|
+
violations.push({ code: "policy_not_permitted", message: `policy ${child.acceptance_policy.policy_id} is not permitted by the parent` });
|
|
53
|
+
}
|
|
54
|
+
const depthBudget = Math.min(p.subdelegation_limits.max_depth, parent.inheritedMaxDepth ?? Number.MAX_SAFE_INTEGER);
|
|
55
|
+
if (depthBudget < 1) {
|
|
56
|
+
violations.push({ code: "depth_exceeded", message: "no subdelegation depth remains" });
|
|
57
|
+
}
|
|
58
|
+
else if (child.allow_subdelegation) {
|
|
59
|
+
const childDepth = child.subdelegation_limits?.max_depth ?? 0;
|
|
60
|
+
if (childDepth > depthBudget - 1) {
|
|
61
|
+
violations.push({ code: "depth_exceeded", message: `child may subdelegate at most ${depthBudget - 1} further level(s)` });
|
|
62
|
+
}
|
|
63
|
+
if ((child.subdelegation_limits?.max_total_minor ?? 0) > child.max_amount_minor) {
|
|
64
|
+
violations.push({ code: "exceeds_subdelegation_total", message: "child subdelegation total exceeds its own ceiling" });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return violations;
|
|
68
|
+
}
|
|
69
|
+
/** Depth budget a child inherits from its parent chain. */
|
|
70
|
+
export function inheritedDepthForChild(parent) {
|
|
71
|
+
const own = parent.terms.subdelegation_limits?.max_depth ?? 0;
|
|
72
|
+
return Math.min(own, parent.inheritedMaxDepth ?? Number.MAX_SAFE_INTEGER) - 1;
|
|
73
|
+
}
|
|
74
|
+
/** Generic cycle check over parent links (OB-7). */
|
|
75
|
+
export function hasCycle(parentOf) {
|
|
76
|
+
for (const start of parentOf.keys()) {
|
|
77
|
+
const seen = new Set();
|
|
78
|
+
let current = start;
|
|
79
|
+
while (current) {
|
|
80
|
+
if (seen.has(current))
|
|
81
|
+
return true;
|
|
82
|
+
seen.add(current);
|
|
83
|
+
current = parentOf.get(current) ?? null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
87
|
+
}
|