@atrib/verify 0.1.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 (43) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +177 -0
  3. package/dist/calculate.d.ts +32 -0
  4. package/dist/calculate.d.ts.map +1 -0
  5. package/dist/calculate.js +495 -0
  6. package/dist/calculate.js.map +1 -0
  7. package/dist/graph-fetch.d.ts +22 -0
  8. package/dist/graph-fetch.d.ts.map +1 -0
  9. package/dist/graph-fetch.js +60 -0
  10. package/dist/graph-fetch.js.map +1 -0
  11. package/dist/index.d.ts +15 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +24 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/policy-builder.d.ts +26 -0
  16. package/dist/policy-builder.d.ts.map +1 -0
  17. package/dist/policy-builder.js +49 -0
  18. package/dist/policy-builder.js.map +1 -0
  19. package/dist/recommendation.d.ts +29 -0
  20. package/dist/recommendation.d.ts.map +1 -0
  21. package/dist/recommendation.js +91 -0
  22. package/dist/recommendation.js.map +1 -0
  23. package/dist/resolve-identity.d.ts +84 -0
  24. package/dist/resolve-identity.d.ts.map +1 -0
  25. package/dist/resolve-identity.js +121 -0
  26. package/dist/resolve-identity.js.map +1 -0
  27. package/dist/revocations.d.ts +73 -0
  28. package/dist/revocations.d.ts.map +1 -0
  29. package/dist/revocations.js +83 -0
  30. package/dist/revocations.js.map +1 -0
  31. package/dist/types.d.ts +200 -0
  32. package/dist/types.d.ts.map +1 -0
  33. package/dist/types.js +25 -0
  34. package/dist/types.js.map +1 -0
  35. package/dist/verifier.d.ts +54 -0
  36. package/dist/verifier.d.ts.map +1 -0
  37. package/dist/verifier.js +213 -0
  38. package/dist/verifier.js.map +1 -0
  39. package/dist/verify-record.d.ts +149 -0
  40. package/dist/verify-record.d.ts.map +1 -0
  41. package/dist/verify-record.js +136 -0
  42. package/dist/verify-record.js.map +1 -0
  43. package/package.json +47 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or otherwise designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or a Contribution
81
+ incorporated within the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this License
83
+ for that Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works
91
+ a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the attribution
104
+ notices contained within such NOTICE file, in at least one
105
+ of the following places: within a NOTICE text file distributed
106
+ as part of the Derivative Works; within the Source form or
107
+ documentation, if provided along with the Derivative Works; or,
108
+ within a display generated by the Derivative Works, if and
109
+ wherever such third-party notices normally appear. The contents
110
+ of the NOTICE file are for informational purposes only and
111
+ do not modify the License. You may add Your own attribution
112
+ notices within Derivative Works that You distribute, alongside
113
+ or as an addendum to the NOTICE text from the Work, provided
114
+ that such additional attribution notices cannot be construed
115
+ as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, modify, or distribute
119
+ those modifications in accordance with this License.
120
+
121
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
122
+ any Contribution intentionally submitted for inclusion in the Work
123
+ by You to the Licensor shall be under the terms and conditions of
124
+ this License, without any additional terms or conditions.
125
+ Notwithstanding the above, nothing herein shall supersede or modify
126
+ the terms of any separate license agreement you may have executed
127
+ with Licensor regarding such Contributions.
128
+
129
+ 6. Trademarks. This License does not grant permission to use the trade
130
+ names, trademarks, service marks, or product names of the Licensor,
131
+ except as required for reasonable and customary use in describing the
132
+ origin of the Work and reproducing the content of the NOTICE file.
133
+
134
+ 7. Disclaimer of Warranty. Unless required by applicable law or
135
+ agreed to in writing, Licensor provides the Work (and each
136
+ Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
138
+ implied, including, without limitation, any warranties or conditions
139
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
140
+ PARTICULAR PURPOSE. You are solely responsible for determining the
141
+ appropriateness of using or reproducing the Work and assume any
142
+ risks associated with Your exercise of permissions under this License.
143
+
144
+ 8. Limitation of Liability. In no event and under no legal theory,
145
+ whether in tort (including negligence), contract, or otherwise,
146
+ unless required by applicable law (such as deliberate and grossly
147
+ negligent acts) or agreed to in writing, shall any Contributor be
148
+ liable to You for damages, including any direct, indirect, special,
149
+ incidental, or exemplary damages of any character arising as a
150
+ result of this License or out of the use or inability to use the
151
+ Work (including but not limited to damages for loss of goodwill,
152
+ work stoppage, computer failure or malfunction, or all other
153
+ commercial damages or losses), even if such Contributor has been
154
+ advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability. While redistributing
157
+ the Work or Derivative Works thereof, You may choose to offer,
158
+ and charge a fee for, acceptance of support, warranty, indemnity,
159
+ or other liability obligations and/or rights consistent with this
160
+ License. However, in accepting such obligations, You may act only
161
+ on Your own behalf and on Your sole responsibility, not on behalf
162
+ of any other Contributor, and only if You agree to indemnify,
163
+ defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason
165
+ of your accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work.
170
+
171
+ To apply the Apache License to your work, attach the following
172
+ boilerplate notice, with the fields enclosed by brackets "[]"
173
+ replaced with your own identifying information. (Don't include
174
+ the brackets!) The text should be enclosed in the appropriate
175
+ comment syntax for the file format in question. Also, an optional
176
+ "Statement of Purpose" appears after the copyright notice.
177
+
178
+ Copyright 2025-2026 Atrib contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
189
+ implied. See the License for the specific language governing
190
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # `@atrib/verify`
2
+
3
+ **Independent verification of atrib records and settlement documents. Re-runs the spec [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) calculation algorithm locally and checks the result against what a recommendation document claims. Verifies any signed record against its creator key. No trust in any intermediary required.**
4
+
5
+ This is the **verifier half** of the atrib protocol, used by merchants closing transactions, auditors checking agent activity, regulators querying historical state, and any party that needs to validate atrib data independently. The agent and tool servers produce signed attribution records. The Merkle log stores them. This package answers the questions any verifier has to answer: _given the graph and the policy, is this distribution actually correct? Was this record actually signed by the key it claims? Did this action actually happen at the time it claims?_
6
+
7
+ ## Quick start
8
+
9
+ ```typescript
10
+ import { AtribVerifier } from '@atrib/verify'
11
+
12
+ const verifier = new AtribVerifier({
13
+ merchantKey: process.env.ATRIB_MERCHANT_KEY, // optional, base64url Ed25519 seed
14
+ graphEndpoint: 'https://graph.atrib.dev/v1', // defaults to atrib.dev endpoints
15
+ logEndpoint: 'https://log.atrib.dev/v1',
16
+ })
17
+
18
+ const result = await verifier.verify(recommendationDoc)
19
+ // {
20
+ // valid: true,
21
+ // signatureOk: true,
22
+ // calcMatch: true,
23
+ // distribution: { 'sha256:...': 0.4, 'sha256:...': 0.6 },
24
+ // warnings: [],
25
+ // graph_node_count: 7,
26
+ // }
27
+ ```
28
+
29
+ `valid === true` means **both** the document's Ed25519 signature verified against the calculator's published key **and** the local recalculation produced the same distribution within `1e-9`. Either failing flips `valid` to `false` and the specific failure is reported in `signatureOk` / `calcMatch` / `warnings` so you know exactly what went wrong.
30
+
31
+ ## What `verify()` actually does (per spec §5.5.2)
32
+
33
+ 1. **Resolves the calculator's public key** from `recommendationDoc.calculated_by`. For the well-known `resolve.atrib.dev` service, the key is fetched from the `/pubkey` endpoint. For other calculators, the merchant supplies the key out-of-band.
34
+ 2. **Verifies the Ed25519 signature** over the JCS-canonicalized recommendation document (excluding the `signature` field).
35
+ 3. **Fetches the attribution graph** at `recommendationDoc.graph_tree_size` from the configured graph endpoint. Pinning to a specific tree size makes the verification reproducible; the graph is fixed, not "live."
36
+ 4. **Fetches the session policy record** referenced by `policy_record_id`, or uses the spec [§4.3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#43-the-default-policy) default policy if `policy_record_id === 'default'`.
37
+ 5. **Re-runs `calculate(graph, policy, sessionPolicyRecord)`** locally; a pure function with no network calls and no randomness.
38
+ 6. **Compares distributions** using `distributionsMatch()` (within `1e-9` per recipient, accounting for floating-point drift across implementations).
39
+
40
+ The key invariant per spec [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm): any party with the same graph and the same policy MUST get the same distribution. If they don't, either the calculator cheated, the document was tampered with, or one party has a buggy implementation. Either way the merchant should not pay against this document.
41
+
42
+ ## Post-hoc calculation (§5.5.3)
43
+
44
+ If the agent that drove the session was not atrib-aware (no `@atrib/agent` middleware), the merchant can still produce a signed recommendation after the fact, as long as the tools were attributed:
45
+
46
+ ```typescript
47
+ const recommendation = await verifier.calculate({
48
+ context_id: 'sess_abc123...',
49
+ policy: 'default', // or a full PolicyDocument
50
+ signWith: 'merchant', // signs with merchantKey if present
51
+ })
52
+ // → fully-shaped RecommendationDocument, ready to settle against
53
+ ```
54
+
55
+ Per the [§5.8](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#58-degradation-contract) degradation contract, this never throws on a missing key; if `signWith === 'merchant'` but `merchantKey` is unset, the document is returned **unsigned** with a warning rather than crashing the merchant pipeline.
56
+
57
+ ## API reference
58
+
59
+ ### `new AtribVerifier(options)`
60
+
61
+ | Field | Type | Default | Description |
62
+ | ----------------- | -------- | ----------------------------- | ----------------------------------------------------------------------- |
63
+ | `logEndpoint` | `string` | `https://log.atrib.dev/v1` | The Merkle log to fetch checkpoints and proofs from. |
64
+ | `graphEndpoint` | `string` | `https://graph.atrib.dev/v1` | The graph query endpoint (spec [§3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#3-graph-query-interface)). |
65
+ | `resolveEndpoint` | `string` | `https://resolve.atrib.dev/v1` | Reserved for v2 remote calculation. |
66
+ | `merchantKey` | `string` | unset | Base64url Ed25519 32-byte seed. Optional. `verify()` works without it. |
67
+
68
+ ### `verify(doc): Promise<VerificationResult>`
69
+
70
+ Independently re-runs the [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) calculation and verifies the document signature. Always returns a result object; never throws. Inspect `valid`, `signatureOk`, `calcMatch`, and `warnings` to understand the outcome.
71
+
72
+ This method operates on `RecommendationDocument` shapes (settlement-recommendation flow per spec [§5.5.2](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#552-verify)). For verifying individual `AtribRecord`s, see `verifyRecord` below.
73
+
74
+ ### `verifyRecord(record, options): Promise<RecordVerificationResult>`
75
+
76
+ Per-record verification. Verifies a single signed record's Ed25519 signature and surfaces per-record annotations defined by spec sections [§1.2.5](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#125-informed_by) ([D041](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d041-informed_by-linking-primitive-and-informed_by-edge-type)), [§1.2.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#126-provenance_token) ([D044](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d044-provenance_token-field-for-cross-session-causal-anchoring)), and [§8.4](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#84-coarsened-timing-posture) ([D045](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d045-privacy-postures-normative-spec-section)).
77
+
78
+ ```typescript
79
+ import { verifyRecord } from '@atrib/verify'
80
+
81
+ const result = await verifyRecord(record, {
82
+ upstreamCandidate, // optional, for provenance_token resolution
83
+ informedByCandidates: [], // optional, for informed_by[] resolution
84
+ })
85
+ // result: {
86
+ // valid: boolean
87
+ // signatureOk: boolean
88
+ // posture: { timestamp_granularity, timestamp_consistent, timestamp_granularity_explicit }
89
+ // provenance?: { token, upstream_record_hash, upstream_resolved }
90
+ // informed_by_resolution?: { resolved: string[], dangling: string[] }
91
+ // warnings: string[]
92
+ // }
93
+ ```
94
+
95
+ **Implemented per-record annotations:**
96
+
97
+ - `provenance`: `{ token, upstream_record_hash, upstream_resolved }` per session-genesis record carrying `provenance_token` ([D044](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d044-provenance_token-field-for-cross-session-causal-anchoring) / [§1.2.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#126-provenance_token)). The 16-byte token truncation is irreversible: `upstream_record_hash` populates only when the caller supplies a candidate whose canonical-form SHA-256[:16] matches the token.
98
+ - `informed_by_resolution`: `{ resolved: string[], dangling: string[] }` per record carrying `informed_by` ([D041](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d041-informed_by-linking-primitive-and-informed_by-edge-type) / [§1.2.5](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#125-informed_by)). Dangling references are flagged but do not fail verification: they signal "the verifier has not seen upstream context," not "the record is invalid."
99
+ - `posture`: `{ timestamp_granularity, timestamp_consistent, timestamp_granularity_explicit }` ([D045](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d045-privacy-postures-normative-spec-section) / [§8.4](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#84-coarsened-timing-posture)). Always populated. Surfaces the declared timing granularity, whether the timestamp value structurally matches the spec's trailing-zero invariant for that granularity, and whether the field was explicitly set vs defaulted from absence.
100
+
101
+ **Pending per-record annotations** (tracked as a Pending decision in [DECISIONS.md P005](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#p005-reconcile-atribverify-readme-per-record-annotations-with-actual-code-surface)):
102
+
103
+ - `capability_check` ([D051](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d051-capability-scoped-records-via-directory-published-envelopes) / [§6.7](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#67-capability-declarations)): requires `@atrib/directory` integration to look up the signing key's capability envelope.
104
+ - `cross_attestation` ([D052](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d052-cross-attestation-requirement-for-transaction-records) / [§1.7.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#176-cross-attestation-requirement-for-transaction-records)): requires a `signers[]` field on `AtribRecord` plus a transaction-record canonicalization variant in `@atrib/mcp`.
105
+ - `cross_log_proof_count` / `cross_log_threshold_met` / `cross_log_equivocation_detected` ([D050](https://github.com/creatornader/atrib/blob/main/DECISIONS.md#d050-cross-log-replication-for-equivocation-defense) / [§2.11](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#211-cross-log-replication)): requires multi-log proof-bundle parsing and trusted-log-set config.
106
+ - `tool_name_form` / `args_commitment_form` ([§8.2](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#82-opaque-name-posture) / [§8.3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#83-salted-commitment-posture)): requires `tool_name`, `args_hash`, and `args_salt` fields on `AtribRecord` (the standard record shape currently exposes only the derived `content_id`).
107
+
108
+ Each pending annotation is its own ADR scope when external consumers need it.
109
+
110
+ ### `calculate(options): Promise<RecommendationDocument>`
111
+
112
+ Post-hoc calculation when no agent SDK was present. Always returns a fully-shaped document, unsigned with a warning if the merchant key is missing.
113
+
114
+ ### Lower-level primitives
115
+
116
+ For advanced use (custom calculators, alternative signing flows), the package also exports:
117
+
118
+ - `calculate(graph, policy, sessionPolicyRecord)`: the pure [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) calculation function
119
+ - `DEFAULT_POLICY`: the spec [§4.3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#43-the-default-policy) default policy document
120
+ - `isValidPolicy(doc)`: schema check for `PolicyDocument`
121
+ - `signRecommendation(unsigned, privateKey)`: JCS + Ed25519 signing
122
+ - `verifyRecommendationSignature(doc, publicKey)`: signature verification
123
+ - `recommendationSigningInput(doc)`: the canonical bytes that get signed
124
+ - `distributionsMatch(a, b)`: float-tolerant equality (within `1e-9` per recipient)
125
+ - `fetchGraph(endpoint, contextId, treeSize?)`, `fetchSessionPolicyRecord`, `fetchPolicyDocument`
126
+
127
+ ## Why pure functions matter
128
+
129
+ The [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) calculation algorithm is intentionally a **pure function** of `(graph, policy)`:
130
+
131
+ - **No network calls** during calculation. The graph and policy are fetched up front and then `calculate()` runs in-memory.
132
+ - **No timestamps** beyond those already embedded in the records. Two runs an hour apart on the same inputs produce the same output.
133
+ - **No randomness**. No "tie-breaker by hash of current time" or anything like that. Ties are broken deterministically per the spec.
134
+ - **No floating-point ordering surprises**. The algorithm walks the graph in a deterministic order so two implementations on identical input produce identical output (within `1e-9` for the final distribution shares).
135
+
136
+ This is what makes verification possible: the merchant's local recalculation is the same code the calculator ran, producing the same output, so any disagreement is a real signal; not implementation drift.
137
+
138
+ ## §5.8 degradation contract
139
+
140
+ Per the absolute invariant (also enforced in `@atrib/mcp` and `@atrib/agent`), atrib failures never break the host:
141
+
142
+ - Missing or invalid `merchantKey` → constructor logs `atrib: ...` warning, `merchantPrivateKey = null`, no throw.
143
+ - `verify()` errors during signature resolution, graph fetch, or calculation are caught and surfaced as `warnings: string[]` with `valid = false`.
144
+ - `calculate({ signWith: 'merchant' })` with a missing key returns an unsigned document plus a warning, rather than throwing.
145
+
146
+ The merchant's payment pipeline never crashes because of an atrib problem. It just gets `valid: false` and decides what to do with that.
147
+
148
+ ## Test coverage
149
+
150
+ 184 tests across 10 test files covering the [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) calculation algorithm, graph endpoint client, JCS canonicalization, Ed25519 signing, settlement recommendations, policy templates, policy builder, calculation edge cases, property-based testing with fast-check, and full `verify()` / `calculate()` paths including [§5.8](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#58-degradation-contract) degradation.
151
+
152
+ Run them with `pnpm --filter @atrib/verify test`.
153
+
154
+ ## Spec references
155
+
156
+ | Spec section | What this package implements |
157
+ | ------------ | ---------------------------------------------------- |
158
+ | [§3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#3-graph-query-interface) | Graph query interface (client side) |
159
+ | [§4.3](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#43-the-default-policy) | Default policy document |
160
+ | [§4.6](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#46-the-calculation-algorithm) | Pure calculation algorithm |
161
+ | [§4.7](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#47-settlement-recommendation-document) | Recommendation document signing/verification |
162
+ | [§5.5](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#55-atribverify-merchant-verification-library) | `AtribVerifier` class. `verify()` and `calculate()` |
163
+ | [§5.8](https://github.com/creatornader/atrib/blob/main/atrib-spec.md#58-degradation-contract) | Degradation contract; failures never break the host |
164
+
165
+ The full protocol spec is at [`atrib-spec.md`](https://github.com/creatornader/atrib/blob/main/atrib-spec.md).
166
+
167
+ ## See also
168
+
169
+ - [`@atrib/mcp`](https://github.com/creatornader/atrib/blob/main/packages/mcp/README.md), server-side middleware that produces the signed records `verify()` ultimately validates
170
+ - [`@atrib/agent`](https://github.com/creatornader/atrib/blob/main/packages/agent/README.md), agent-side interceptor + framework adapters
171
+ - [`@atrib/log-dev`](https://github.com/creatornader/atrib/blob/main/packages/log-dev/README.md), development-mode Merkle log stub. Returns placeholder Merkle hashes that **will not pass** strict cryptographic verification, fine for end-to-end shape testing, not for production verification.
172
+ - [`packages/integration/examples/end-to-end/`](https://github.com/creatornader/atrib/blob/main/packages/integration/examples/end-to-end/), runnable demo wiring everything together
173
+ - [`DECISIONS.md`](https://github.com/creatornader/atrib/blob/main/DECISIONS.md), architectural decision log
174
+
175
+ ---
176
+
177
+ > **A note on documentation links.** The atrib protocol repository is currently private (in-progress public preparation). Links in this README to the spec and sister packages (`atrib-spec.md`, `packages/agent/README.md`, etc.) point at `github.com/creatornader/atrib/blob/main/...` URLs that will resolve once the repository goes public. Until then, see [`atrib.dev`](https://atrib.dev) for the protocol overview.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The calculation algorithm (§4.6). pure function from
3
+ * (graph, policy, sessionPolicyRecord?) → distribution.
4
+ *
5
+ * INVARIANT: This function is deterministic. Two runs on identical input
6
+ * MUST produce identical output bit-for-bit. No network calls. No timestamps
7
+ * beyond what's in the records. No randomness. No iteration order dependencies.
8
+ */
9
+ import type { Distribution, GraphResponse, PolicyDocument, SessionPolicyRecord } from './types.js';
10
+ /**
11
+ * §4.6.1 / §4.2 / §4.5.2 Rule 6: validate a policy document.
12
+ * Returns true iff the policy is structurally usable for calculation.
13
+ *
14
+ * Reasons a policy fails validation:
15
+ * - missing or wrong spec_version
16
+ * - contradictory constraints (minimum_share > maximum_share)
17
+ * - any negative constraint value
18
+ * - any negative edge weight
19
+ */
20
+ export declare function isValidPolicy(policy: unknown): policy is PolicyDocument;
21
+ /** §4.3 default policy. */
22
+ export declare const DEFAULT_POLICY: PolicyDocument;
23
+ /**
24
+ * Run the full calculation pipeline (§4.6 closing pseudocode).
25
+ *
26
+ * @param graph. graph snapshot for the session
27
+ * @param policy. agreed policy document
28
+ * @param sessionPolicyRecord. optional; provides per-creator floors (§4.6.7)
29
+ * @returns final distribution (creator_key → share, sums to 1.0 ± 1e-9)
30
+ */
31
+ export declare function calculate(graph: GraphResponse, policy: PolicyDocument, sessionPolicyRecord?: SessionPolicyRecord | null): Distribution;
32
+ //# sourceMappingURL=calculate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculate.d.ts","sourceRoot":"","sources":["../src/calculate.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,KAAK,EACV,YAAY,EAGZ,aAAa,EAGb,cAAc,EACd,mBAAmB,EACpB,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,cAAc,CAwBvE;AAED,2BAA2B;AAC3B,eAAO,MAAM,cAAc,EAAE,cAe5B,CAAA;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,aAAa,EACpB,MAAM,EAAE,cAAc,EACtB,mBAAmB,CAAC,EAAE,mBAAmB,GAAG,IAAI,GAC/C,YAAY,CAmCd"}