@zanii/custody 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.
- package/LICENSE +159 -0
- package/README.md +48 -0
- package/dist/index.d.ts +108 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +139 -0
- package/dist/index.js.map +1 -0
- package/package.json +42 -0
- package/src/index.ts +184 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
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, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work; and
|
|
103
|
+
|
|
104
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
105
|
+
distribution, then any Derivative Works that You distribute must
|
|
106
|
+
include a readable copy of the attribution notices contained
|
|
107
|
+
within such NOTICE file.
|
|
108
|
+
|
|
109
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
110
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
111
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
112
|
+
this License, without any additional terms or conditions.
|
|
113
|
+
|
|
114
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
115
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
116
|
+
except as required for reasonable and customary use in describing the
|
|
117
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
118
|
+
|
|
119
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed
|
|
120
|
+
to in writing, Licensor provides the Work (and each Contributor
|
|
121
|
+
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
|
|
122
|
+
OR CONDITIONS OF ANY KIND, either express or implied, including,
|
|
123
|
+
without limitation, any warranties or conditions of TITLE,
|
|
124
|
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
|
125
|
+
|
|
126
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
127
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
128
|
+
unless required by applicable law (such as deliberate and grossly
|
|
129
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
130
|
+
liable to You for damages, including any direct, indirect, special,
|
|
131
|
+
incidental, or consequential damages of any character arising as a
|
|
132
|
+
result of this License or out of the use or inability to use the
|
|
133
|
+
Work.
|
|
134
|
+
|
|
135
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
136
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
137
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
138
|
+
or other liability obligations and/or rights consistent with this
|
|
139
|
+
License. However, in accepting such obligations, You may act only
|
|
140
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
141
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
142
|
+
defend, and hold each Contributor harmless for any liability
|
|
143
|
+
incurred by, or claims asserted against, such Contributor.
|
|
144
|
+
|
|
145
|
+
END OF TERMS AND CONDITIONS
|
|
146
|
+
|
|
147
|
+
Copyright 2026 Zanii
|
|
148
|
+
|
|
149
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
150
|
+
you may not use this file except in compliance with the License.
|
|
151
|
+
You may obtain a copy of the License at
|
|
152
|
+
|
|
153
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
154
|
+
|
|
155
|
+
Unless required by applicable law or agreed to in writing, software
|
|
156
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
157
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
158
|
+
See the License for the specific language governing permissions and
|
|
159
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# @zanii/custody
|
|
2
|
+
|
|
3
|
+
**Supply-chain provenance.** "Where did this actually come from" — verifiable without any
|
|
4
|
+
party trusting another's database. Each **handoff** (factory → shipper → customs →
|
|
5
|
+
retailer) is a 2-party **co-signed** receipt (giver + receiver sign one neutral statement;
|
|
6
|
+
`POST /v1/interactions`); a **multi-party event** (a customs inspection witnessed by N
|
|
7
|
+
parties) is an M-of-N swarm receipt (`POST /v1/swarm`). This package adds the item layer:
|
|
8
|
+
|
|
9
|
+
- **`itemTag(itemId, namespace)`** — pseudonymous item identity. The serial/batch never
|
|
10
|
+
appears on-ledger (competitors can't enumerate your volumes), but any holder of the real
|
|
11
|
+
id can find and verify the item's full history via `GET /v1/subjects/{tag}`.
|
|
12
|
+
- **`buildHandoff` / `buildCustodyEvent`** — co-signable bodies stamped with the item tag
|
|
13
|
+
*inside the signed bytes*; sensitive details (weights, values, seals, docs) are
|
|
14
|
+
salt-committed, disclosable later via `@zanii/redact` / `verifyPayload`.
|
|
15
|
+
- **`verifyCustodyChain(entries, { tag })`** — continuity: the receiver of handoff *n* is
|
|
16
|
+
the giver of handoff *n + 1*, timestamps monotonic, every entry valid and tag-bound;
|
|
17
|
+
returns the first break. `custodySummary` gives the human answer.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install @zanii/custody @zanii/core @zanii/swarm
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { itemTag, buildHandoff, verifyCustodyChain } from '@zanii/custody';
|
|
25
|
+
import { signA2ABody, assembleA2AReceipt } from '@zanii/core';
|
|
26
|
+
|
|
27
|
+
const draft = buildHandoff({ itemId: 'SN-12345', namespace: 'acme-logistics',
|
|
28
|
+
step: 'factory-out', from: factoryStub, to: shipperStub, ts, evidence: { seal: 'S-9', kg: 12.4 } });
|
|
29
|
+
const receipt = assembleA2AReceipt(draft.body,
|
|
30
|
+
signA2ABody(draft.body, factoryKey), signA2ABody(draft.body, shipperKey));
|
|
31
|
+
// POST /v1/interactions — keep draft.nonce to later prove the evidence
|
|
32
|
+
|
|
33
|
+
verifyCustodyChain(chain, { tag: itemTag('SN-12345', 'acme-logistics') }).ok;
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Honest limit — the oracle problem, stated plainly
|
|
37
|
+
Cryptography verifies **attestations, not atoms**. A custody chain proves *who signed for
|
|
38
|
+
the goods at each step, under whose authority, in what order, unalterable after the fact* —
|
|
39
|
+
it cannot prove box contents weren't swapped by a party willing to sign falsely. What it
|
|
40
|
+
changes: fraud now requires a **specific, identified party to sign a false statement** with
|
|
41
|
+
their accountable key. Detection becomes attribution. Bind the physical world (seals,
|
|
42
|
+
weights, photos) in the salted `evidence`, disclosable selectively.
|
|
43
|
+
|
|
44
|
+
## Changelog
|
|
45
|
+
- **0.1.0** — initial release: `itemTag`, `buildHandoff`, `buildCustodyEvent`, `verifyCustodyChain`, `custodySummary`.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/custody — supply-chain provenance: co-signed custody chains for physical goods.
|
|
3
|
+
*
|
|
4
|
+
* "Where did this actually come from" without any party trusting another's database.
|
|
5
|
+
* A **handoff** (factory → shipper → customs → retailer) is a 2-party co-signed a2a
|
|
6
|
+
* receipt (live at `POST /v1/interactions`); a **multi-party event** (an inspection
|
|
7
|
+
* witnessed by N parties) is a swarm receipt (`POST /v1/swarm`). This package adds the
|
|
8
|
+
* *item layer* on top — no new crypto, no new server verification:
|
|
9
|
+
*
|
|
10
|
+
* - `itemTag(itemId, namespace)` — pseudonymous item identity (the serial/batch never
|
|
11
|
+
* appears on-ledger; competitors can't enumerate volumes; any holder of the real id
|
|
12
|
+
* can find + verify the item's history via the subject index, `GET /v1/subjects/{tag}`).
|
|
13
|
+
* - `buildHandoff` / `buildCustodyEvent` — receipt bodies stamped with the item tag,
|
|
14
|
+
* sensitive details (weights, values, docs) salt-committed, disclosable later.
|
|
15
|
+
* - `verifyCustodyChain` — the custody-specific check on top of receipt validity:
|
|
16
|
+
* **continuity** — the receiver of handoff *n* is the giver of handoff *n+1*,
|
|
17
|
+
* timestamps monotonic; returns the first break.
|
|
18
|
+
*
|
|
19
|
+
* Honest limit (the oracle problem, stated plainly): cryptography verifies
|
|
20
|
+
* **attestations, not atoms**. A chain proves who signed for the goods at each step,
|
|
21
|
+
* under whose authority, in what order, unalterable after the fact — it cannot prove
|
|
22
|
+
* box contents weren't swapped by a party willing to sign falsely. What changes: fraud
|
|
23
|
+
* now requires a specific, identified party to sign a false statement with their
|
|
24
|
+
* accountable key. Detection becomes attribution. Bind the physical world (seals,
|
|
25
|
+
* weights, photos) in the salted `evidence` payload, disclosable via `@zanii/redact`.
|
|
26
|
+
*/
|
|
27
|
+
import { type A2AReceipt, type DelegationCert } from '@zanii/core';
|
|
28
|
+
import { type SwarmBody, type SwarmLedgerReceipt } from '@zanii/swarm';
|
|
29
|
+
/** Pseudonymous, namespace-scoped item identity. Deterministic (RFC 8785), cross-language. */
|
|
30
|
+
export declare function itemTag(itemId: string, namespace: string): string;
|
|
31
|
+
export interface HandoffInput {
|
|
32
|
+
/** The raw item id (serial/batch/EPC — opaque string, caller normalizes)… */
|
|
33
|
+
itemId?: string;
|
|
34
|
+
namespace?: string;
|
|
35
|
+
/** …or a precomputed `itemTag`. */
|
|
36
|
+
tag?: string;
|
|
37
|
+
/** Custody step, e.g. `factory-out`, `customs-in`. Becomes `custody.handoff.<step>`. */
|
|
38
|
+
step: string;
|
|
39
|
+
/** Giver / receiver party stubs: `{ agent_id, delegation, prev }` (no sig yet). */
|
|
40
|
+
from: {
|
|
41
|
+
agent_id: string;
|
|
42
|
+
delegation: DelegationCert[];
|
|
43
|
+
prev: string | null;
|
|
44
|
+
};
|
|
45
|
+
to: {
|
|
46
|
+
agent_id: string;
|
|
47
|
+
delegation: DelegationCert[];
|
|
48
|
+
prev: string | null;
|
|
49
|
+
};
|
|
50
|
+
ts: string;
|
|
51
|
+
/** Sensitive details (location, weights, seals, docs) — salt-committed, never raw on-ledger. */
|
|
52
|
+
evidence?: Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
export interface HandoffDraft {
|
|
55
|
+
/** The a2a body both parties sign (stamped with the item tag; sign with `signA2ABody`). */
|
|
56
|
+
body: Record<string, unknown>;
|
|
57
|
+
tag: string;
|
|
58
|
+
/** Keep to later prove the evidence with `verifyPayload` (evidence is always salt-committed). */
|
|
59
|
+
nonce: string;
|
|
60
|
+
}
|
|
61
|
+
/** Build the co-signable handoff body. Giver + receiver sign it; submit via `POST /v1/interactions`. */
|
|
62
|
+
export declare function buildHandoff(input: HandoffInput): HandoffDraft;
|
|
63
|
+
export interface CustodyEventInput {
|
|
64
|
+
itemId?: string;
|
|
65
|
+
namespace?: string;
|
|
66
|
+
tag?: string;
|
|
67
|
+
/** e.g. `customs-inspection`. Becomes task `custody.event.<kind>`. */
|
|
68
|
+
kind: string;
|
|
69
|
+
target: string;
|
|
70
|
+
participants: string[];
|
|
71
|
+
threshold: number;
|
|
72
|
+
ts: string;
|
|
73
|
+
evidence?: Record<string, unknown>;
|
|
74
|
+
}
|
|
75
|
+
/** Build the N-party event body (swarm). Participants sign it; submit via `POST /v1/swarm`. */
|
|
76
|
+
export declare function buildCustodyEvent(input: CustodyEventInput): {
|
|
77
|
+
body: SwarmBody & {
|
|
78
|
+
subject_tag?: string;
|
|
79
|
+
};
|
|
80
|
+
tag: string;
|
|
81
|
+
nonce: string;
|
|
82
|
+
};
|
|
83
|
+
export interface CustodyCheck {
|
|
84
|
+
ok: boolean;
|
|
85
|
+
reasons: string[];
|
|
86
|
+
/** Ordered custodian DIDs (giver of the first handoff, then each receiver). */
|
|
87
|
+
custodians: string[];
|
|
88
|
+
handoffs: number;
|
|
89
|
+
events: number;
|
|
90
|
+
}
|
|
91
|
+
type Entry = A2AReceipt | SwarmLedgerReceipt | Record<string, unknown>;
|
|
92
|
+
/**
|
|
93
|
+
* Verify an item's custody chain: every entry cryptographically valid AND stamped with
|
|
94
|
+
* this item's tag, handoffs continuous (receiver of *n* = giver of *n+1*), timestamps
|
|
95
|
+
* monotonic. Events are validated + tag-matched but don't transfer custody.
|
|
96
|
+
*/
|
|
97
|
+
export declare function verifyCustodyChain(entries: Entry[], opts: {
|
|
98
|
+
tag: string;
|
|
99
|
+
revoked?: Set<string>;
|
|
100
|
+
}): CustodyCheck;
|
|
101
|
+
/** The human answer: origin, every custodian, every step. */
|
|
102
|
+
export declare function custodySummary(entries: Entry[]): {
|
|
103
|
+
origin: string | null;
|
|
104
|
+
custodians: string[];
|
|
105
|
+
steps: string[];
|
|
106
|
+
};
|
|
107
|
+
export {};
|
|
108
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAEL,KAAK,UAAU,EAAE,KAAK,cAAc,EACrC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAsC,KAAK,SAAS,EAAE,KAAK,kBAAkB,EAAE,MAAM,cAA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B,SAAS,EAAE,MAAM,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,+FAA+F;AAC/F,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,iBAAiB,GAAG;IAAE,IAAI,EAAE,SAAS,GAAG;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAatI;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,OAAO,CAAC;IACZ,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,+EAA+E;IAC/E,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,KAAK,GAAG,UAAU,GAAG,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAMvE;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,GAAG,YAAY,CAmC/G;AAED,6DAA6D;AAC7D,wBAAgB,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG;IAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,CAgBjH"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/custody — supply-chain provenance: co-signed custody chains for physical goods.
|
|
3
|
+
*
|
|
4
|
+
* "Where did this actually come from" without any party trusting another's database.
|
|
5
|
+
* A **handoff** (factory → shipper → customs → retailer) is a 2-party co-signed a2a
|
|
6
|
+
* receipt (live at `POST /v1/interactions`); a **multi-party event** (an inspection
|
|
7
|
+
* witnessed by N parties) is a swarm receipt (`POST /v1/swarm`). This package adds the
|
|
8
|
+
* *item layer* on top — no new crypto, no new server verification:
|
|
9
|
+
*
|
|
10
|
+
* - `itemTag(itemId, namespace)` — pseudonymous item identity (the serial/batch never
|
|
11
|
+
* appears on-ledger; competitors can't enumerate volumes; any holder of the real id
|
|
12
|
+
* can find + verify the item's history via the subject index, `GET /v1/subjects/{tag}`).
|
|
13
|
+
* - `buildHandoff` / `buildCustodyEvent` — receipt bodies stamped with the item tag,
|
|
14
|
+
* sensitive details (weights, values, docs) salt-committed, disclosable later.
|
|
15
|
+
* - `verifyCustodyChain` — the custody-specific check on top of receipt validity:
|
|
16
|
+
* **continuity** — the receiver of handoff *n* is the giver of handoff *n+1*,
|
|
17
|
+
* timestamps monotonic; returns the first break.
|
|
18
|
+
*
|
|
19
|
+
* Honest limit (the oracle problem, stated plainly): cryptography verifies
|
|
20
|
+
* **attestations, not atoms**. A chain proves who signed for the goods at each step,
|
|
21
|
+
* under whose authority, in what order, unalterable after the fact — it cannot prove
|
|
22
|
+
* box contents weren't swapped by a party willing to sign falsely. What changes: fraud
|
|
23
|
+
* now requires a specific, identified party to sign a false statement with their
|
|
24
|
+
* accountable key. Detection becomes attribution. Bind the physical world (seals,
|
|
25
|
+
* weights, photos) in the salted `evidence` payload, disclosable via `@zanii/redact`.
|
|
26
|
+
*/
|
|
27
|
+
import { buildA2ABody, jcsHash, saltedPayloadHash, verifyA2AReceipt, } from '@zanii/core';
|
|
28
|
+
import { verifySwarmReceipt, buildSwarmBody } from '@zanii/swarm';
|
|
29
|
+
/** Pseudonymous, namespace-scoped item identity. Deterministic (RFC 8785), cross-language. */
|
|
30
|
+
export function itemTag(itemId, namespace) {
|
|
31
|
+
if (!itemId || !namespace)
|
|
32
|
+
throw new Error('itemId and namespace are required');
|
|
33
|
+
return jcsHash({ v: 1, type: 'item_tag', namespace, item: itemId });
|
|
34
|
+
}
|
|
35
|
+
/** Build the co-signable handoff body. Giver + receiver sign it; submit via `POST /v1/interactions`. */
|
|
36
|
+
export function buildHandoff(input) {
|
|
37
|
+
if (!input.step)
|
|
38
|
+
throw new Error('step is required');
|
|
39
|
+
const tag = input.tag ?? itemTag(input.itemId ?? '', input.namespace ?? '');
|
|
40
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.evidence ?? {}));
|
|
41
|
+
const body = buildA2ABody({
|
|
42
|
+
action: 'handoff',
|
|
43
|
+
target: `custody.handoff.${input.step}`,
|
|
44
|
+
payloadHash: payload_hash,
|
|
45
|
+
ts: input.ts,
|
|
46
|
+
initiator: input.from,
|
|
47
|
+
responder: input.to,
|
|
48
|
+
});
|
|
49
|
+
// Stamped INSIDE the co-signed body: both signatures cover the item tag.
|
|
50
|
+
body.subject_tag = tag;
|
|
51
|
+
return { body, tag, nonce };
|
|
52
|
+
}
|
|
53
|
+
/** Build the N-party event body (swarm). Participants sign it; submit via `POST /v1/swarm`. */
|
|
54
|
+
export function buildCustodyEvent(input) {
|
|
55
|
+
const tag = input.tag ?? itemTag(input.itemId ?? '', input.namespace ?? '');
|
|
56
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.evidence ?? {}));
|
|
57
|
+
const body = buildSwarmBody({
|
|
58
|
+
task: `custody.event.${input.kind}`,
|
|
59
|
+
target: input.target,
|
|
60
|
+
participants: input.participants,
|
|
61
|
+
threshold: input.threshold,
|
|
62
|
+
ts: input.ts,
|
|
63
|
+
payloadHash: payload_hash,
|
|
64
|
+
});
|
|
65
|
+
body.subject_tag = tag; // inside the signed body — every co-signer covers the item tag
|
|
66
|
+
return { body, tag, nonce };
|
|
67
|
+
}
|
|
68
|
+
function isSwarm(e) {
|
|
69
|
+
return e.type === 'swarm';
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Verify an item's custody chain: every entry cryptographically valid AND stamped with
|
|
73
|
+
* this item's tag, handoffs continuous (receiver of *n* = giver of *n+1*), timestamps
|
|
74
|
+
* monotonic. Events are validated + tag-matched but don't transfer custody.
|
|
75
|
+
*/
|
|
76
|
+
export function verifyCustodyChain(entries, opts) {
|
|
77
|
+
const reasons = [];
|
|
78
|
+
const custodians = [];
|
|
79
|
+
let holder = null;
|
|
80
|
+
let lastTs = '';
|
|
81
|
+
let handoffs = 0;
|
|
82
|
+
let events = 0;
|
|
83
|
+
entries.forEach((e, i) => {
|
|
84
|
+
if (isSwarm(e)) {
|
|
85
|
+
events += 1;
|
|
86
|
+
const check = verifySwarmReceipt(e, { revoked: opts.revoked });
|
|
87
|
+
if (!check.ok)
|
|
88
|
+
reasons.push(`entry ${i} (event): ${check.error}`);
|
|
89
|
+
if (e.body.subject_tag !== opts.tag)
|
|
90
|
+
reasons.push(`entry ${i} (event): wrong or missing item tag`);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const r = e;
|
|
94
|
+
handoffs += 1;
|
|
95
|
+
const check = verifyA2AReceipt(r, { revoked: opts.revoked });
|
|
96
|
+
if (!check.ok) {
|
|
97
|
+
reasons.push(`entry ${i} (handoff): ${check.error}`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (r.subject_tag !== opts.tag)
|
|
101
|
+
reasons.push(`entry ${i} (handoff): wrong or missing item tag`);
|
|
102
|
+
if (holder === null) {
|
|
103
|
+
custodians.push(r.initiator.agent_id);
|
|
104
|
+
}
|
|
105
|
+
else if (r.initiator.agent_id !== holder) {
|
|
106
|
+
reasons.push(`entry ${i} (handoff): custody break — giver ${r.initiator.agent_id} is not the current holder ${holder}`);
|
|
107
|
+
}
|
|
108
|
+
if (lastTs && r.ts < lastTs)
|
|
109
|
+
reasons.push(`entry ${i} (handoff): timestamp goes backwards`);
|
|
110
|
+
holder = r.responder.agent_id;
|
|
111
|
+
custodians.push(holder);
|
|
112
|
+
lastTs = r.ts;
|
|
113
|
+
});
|
|
114
|
+
if (handoffs === 0)
|
|
115
|
+
reasons.push('no handoffs in chain');
|
|
116
|
+
return { ok: reasons.length === 0, reasons, custodians, handoffs, events };
|
|
117
|
+
}
|
|
118
|
+
/** The human answer: origin, every custodian, every step. */
|
|
119
|
+
export function custodySummary(entries) {
|
|
120
|
+
const steps = [];
|
|
121
|
+
const custodians = [];
|
|
122
|
+
let origin = null;
|
|
123
|
+
for (const e of entries) {
|
|
124
|
+
if (isSwarm(e)) {
|
|
125
|
+
steps.push(String(e.body.task));
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const r = e;
|
|
129
|
+
if (origin === null)
|
|
130
|
+
origin = r.initiator.agent_id;
|
|
131
|
+
steps.push(r.target);
|
|
132
|
+
if (!custodians.includes(r.initiator.agent_id))
|
|
133
|
+
custodians.push(r.initiator.agent_id);
|
|
134
|
+
if (!custodians.includes(r.responder.agent_id))
|
|
135
|
+
custodians.push(r.responder.agent_id);
|
|
136
|
+
}
|
|
137
|
+
return { origin, custodians, steps };
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EACL,YAAY,EAAE,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,GAE3D,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAA2C,MAAM,cAAc,CAAC;AAE3G,8FAA8F;AAC9F,MAAM,UAAU,OAAO,CAAC,MAAc,EAAE,SAAiB;IACvD,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAChF,OAAO,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,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EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC7E,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,cAAc,CAAC,OAAgB;IAC7C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;YACf,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,CAAC,GAAG,CAAe,CAAC;QAC1B,IAAI,MAAM,KAAK,IAAI;YAAE,MAAM,GAAG,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC;QACnD,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC;YAAE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QACtF,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC;YAAE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AACvC,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zanii/custody",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Supply-chain provenance: co-signed custody chains for physical goods. Each handoff (factory→shipper→customs→retailer) is a 2-party co-signed receipt, multi-party events are N-party swarm receipts, and item history is a pseudonymous verifiable slice — no party trusts another's database.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://ledger.zanii.agency",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^26.1.0",
|
|
30
|
+
"typescript": "^5.8.2",
|
|
31
|
+
"vitest": "^3.0.9"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@zanii/core": "0.4.0",
|
|
35
|
+
"@zanii/swarm": "0.2.0"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsc -p tsconfig.build.json",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"typecheck": "tsc --noEmit"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/custody — supply-chain provenance: co-signed custody chains for physical goods.
|
|
3
|
+
*
|
|
4
|
+
* "Where did this actually come from" without any party trusting another's database.
|
|
5
|
+
* A **handoff** (factory → shipper → customs → retailer) is a 2-party co-signed a2a
|
|
6
|
+
* receipt (live at `POST /v1/interactions`); a **multi-party event** (an inspection
|
|
7
|
+
* witnessed by N parties) is a swarm receipt (`POST /v1/swarm`). This package adds the
|
|
8
|
+
* *item layer* on top — no new crypto, no new server verification:
|
|
9
|
+
*
|
|
10
|
+
* - `itemTag(itemId, namespace)` — pseudonymous item identity (the serial/batch never
|
|
11
|
+
* appears on-ledger; competitors can't enumerate volumes; any holder of the real id
|
|
12
|
+
* can find + verify the item's history via the subject index, `GET /v1/subjects/{tag}`).
|
|
13
|
+
* - `buildHandoff` / `buildCustodyEvent` — receipt bodies stamped with the item tag,
|
|
14
|
+
* sensitive details (weights, values, docs) salt-committed, disclosable later.
|
|
15
|
+
* - `verifyCustodyChain` — the custody-specific check on top of receipt validity:
|
|
16
|
+
* **continuity** — the receiver of handoff *n* is the giver of handoff *n+1*,
|
|
17
|
+
* timestamps monotonic; returns the first break.
|
|
18
|
+
*
|
|
19
|
+
* Honest limit (the oracle problem, stated plainly): cryptography verifies
|
|
20
|
+
* **attestations, not atoms**. A chain proves who signed for the goods at each step,
|
|
21
|
+
* under whose authority, in what order, unalterable after the fact — it cannot prove
|
|
22
|
+
* box contents weren't swapped by a party willing to sign falsely. What changes: fraud
|
|
23
|
+
* now requires a specific, identified party to sign a false statement with their
|
|
24
|
+
* accountable key. Detection becomes attribution. Bind the physical world (seals,
|
|
25
|
+
* weights, photos) in the salted `evidence` payload, disclosable via `@zanii/redact`.
|
|
26
|
+
*/
|
|
27
|
+
import {
|
|
28
|
+
buildA2ABody, jcsHash, saltedPayloadHash, verifyA2AReceipt,
|
|
29
|
+
type A2AReceipt, type DelegationCert, type VerifyResult,
|
|
30
|
+
} from '@zanii/core';
|
|
31
|
+
import { verifySwarmReceipt, buildSwarmBody, type SwarmBody, type SwarmLedgerReceipt } from '@zanii/swarm';
|
|
32
|
+
|
|
33
|
+
/** Pseudonymous, namespace-scoped item identity. Deterministic (RFC 8785), cross-language. */
|
|
34
|
+
export function itemTag(itemId: string, namespace: string): string {
|
|
35
|
+
if (!itemId || !namespace) throw new Error('itemId and namespace are required');
|
|
36
|
+
return jcsHash({ v: 1, type: 'item_tag', namespace, item: itemId });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface HandoffInput {
|
|
40
|
+
/** The raw item id (serial/batch/EPC — opaque string, caller normalizes)… */
|
|
41
|
+
itemId?: string;
|
|
42
|
+
namespace?: string;
|
|
43
|
+
/** …or a precomputed `itemTag`. */
|
|
44
|
+
tag?: string;
|
|
45
|
+
/** Custody step, e.g. `factory-out`, `customs-in`. Becomes `custody.handoff.<step>`. */
|
|
46
|
+
step: string;
|
|
47
|
+
/** Giver / receiver party stubs: `{ agent_id, delegation, prev }` (no sig yet). */
|
|
48
|
+
from: { agent_id: string; delegation: DelegationCert[]; prev: string | null };
|
|
49
|
+
to: { agent_id: string; delegation: DelegationCert[]; prev: string | null };
|
|
50
|
+
ts: string;
|
|
51
|
+
/** Sensitive details (location, weights, seals, docs) — salt-committed, never raw on-ledger. */
|
|
52
|
+
evidence?: Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface HandoffDraft {
|
|
56
|
+
/** The a2a body both parties sign (stamped with the item tag; sign with `signA2ABody`). */
|
|
57
|
+
body: Record<string, unknown>;
|
|
58
|
+
tag: string;
|
|
59
|
+
/** Keep to later prove the evidence with `verifyPayload` (evidence is always salt-committed). */
|
|
60
|
+
nonce: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Build the co-signable handoff body. Giver + receiver sign it; submit via `POST /v1/interactions`. */
|
|
64
|
+
export function buildHandoff(input: HandoffInput): HandoffDraft {
|
|
65
|
+
if (!input.step) throw new Error('step is required');
|
|
66
|
+
const tag = input.tag ?? itemTag(input.itemId ?? '', input.namespace ?? '');
|
|
67
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.evidence ?? {}));
|
|
68
|
+
const body = buildA2ABody({
|
|
69
|
+
action: 'handoff',
|
|
70
|
+
target: `custody.handoff.${input.step}`,
|
|
71
|
+
payloadHash: payload_hash,
|
|
72
|
+
ts: input.ts,
|
|
73
|
+
initiator: input.from,
|
|
74
|
+
responder: input.to,
|
|
75
|
+
}) as unknown as Record<string, unknown>;
|
|
76
|
+
// Stamped INSIDE the co-signed body: both signatures cover the item tag.
|
|
77
|
+
body.subject_tag = tag;
|
|
78
|
+
return { body, tag, nonce };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface CustodyEventInput {
|
|
82
|
+
itemId?: string;
|
|
83
|
+
namespace?: string;
|
|
84
|
+
tag?: string;
|
|
85
|
+
/** e.g. `customs-inspection`. Becomes task `custody.event.<kind>`. */
|
|
86
|
+
kind: string;
|
|
87
|
+
target: string;
|
|
88
|
+
participants: string[];
|
|
89
|
+
threshold: number;
|
|
90
|
+
ts: string;
|
|
91
|
+
evidence?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Build the N-party event body (swarm). Participants sign it; submit via `POST /v1/swarm`. */
|
|
95
|
+
export function buildCustodyEvent(input: CustodyEventInput): { body: SwarmBody & { subject_tag?: string }; tag: string; nonce: string } {
|
|
96
|
+
const tag = input.tag ?? itemTag(input.itemId ?? '', input.namespace ?? '');
|
|
97
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.evidence ?? {}));
|
|
98
|
+
const body = buildSwarmBody({
|
|
99
|
+
task: `custody.event.${input.kind}`,
|
|
100
|
+
target: input.target,
|
|
101
|
+
participants: input.participants,
|
|
102
|
+
threshold: input.threshold,
|
|
103
|
+
ts: input.ts,
|
|
104
|
+
payloadHash: payload_hash,
|
|
105
|
+
}) as SwarmBody & { subject_tag?: string };
|
|
106
|
+
body.subject_tag = tag; // inside the signed body — every co-signer covers the item tag
|
|
107
|
+
return { body, tag, nonce };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface CustodyCheck {
|
|
111
|
+
ok: boolean;
|
|
112
|
+
reasons: string[];
|
|
113
|
+
/** Ordered custodian DIDs (giver of the first handoff, then each receiver). */
|
|
114
|
+
custodians: string[];
|
|
115
|
+
handoffs: number;
|
|
116
|
+
events: number;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
type Entry = A2AReceipt | SwarmLedgerReceipt | Record<string, unknown>;
|
|
120
|
+
|
|
121
|
+
function isSwarm(e: Entry): e is SwarmLedgerReceipt {
|
|
122
|
+
return (e as { type?: string }).type === 'swarm';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Verify an item's custody chain: every entry cryptographically valid AND stamped with
|
|
127
|
+
* this item's tag, handoffs continuous (receiver of *n* = giver of *n+1*), timestamps
|
|
128
|
+
* monotonic. Events are validated + tag-matched but don't transfer custody.
|
|
129
|
+
*/
|
|
130
|
+
export function verifyCustodyChain(entries: Entry[], opts: { tag: string; revoked?: Set<string> }): CustodyCheck {
|
|
131
|
+
const reasons: string[] = [];
|
|
132
|
+
const custodians: string[] = [];
|
|
133
|
+
let holder: string | null = null;
|
|
134
|
+
let lastTs = '';
|
|
135
|
+
let handoffs = 0;
|
|
136
|
+
let events = 0;
|
|
137
|
+
entries.forEach((e, i) => {
|
|
138
|
+
if (isSwarm(e)) {
|
|
139
|
+
events += 1;
|
|
140
|
+
const check: VerifyResult = verifySwarmReceipt(e, { revoked: opts.revoked });
|
|
141
|
+
if (!check.ok) reasons.push(`entry ${i} (event): ${check.error}`);
|
|
142
|
+
if ((e.body as { subject_tag?: string }).subject_tag !== opts.tag) reasons.push(`entry ${i} (event): wrong or missing item tag`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const r = e as A2AReceipt & { subject_tag?: string };
|
|
146
|
+
handoffs += 1;
|
|
147
|
+
const check = verifyA2AReceipt(r, { revoked: opts.revoked });
|
|
148
|
+
if (!check.ok) {
|
|
149
|
+
reasons.push(`entry ${i} (handoff): ${check.error}`);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (r.subject_tag !== opts.tag) reasons.push(`entry ${i} (handoff): wrong or missing item tag`);
|
|
153
|
+
if (holder === null) {
|
|
154
|
+
custodians.push(r.initiator.agent_id);
|
|
155
|
+
} else if (r.initiator.agent_id !== holder) {
|
|
156
|
+
reasons.push(`entry ${i} (handoff): custody break — giver ${r.initiator.agent_id} is not the current holder ${holder}`);
|
|
157
|
+
}
|
|
158
|
+
if (lastTs && r.ts < lastTs) reasons.push(`entry ${i} (handoff): timestamp goes backwards`);
|
|
159
|
+
holder = r.responder.agent_id;
|
|
160
|
+
custodians.push(holder);
|
|
161
|
+
lastTs = r.ts;
|
|
162
|
+
});
|
|
163
|
+
if (handoffs === 0) reasons.push('no handoffs in chain');
|
|
164
|
+
return { ok: reasons.length === 0, reasons, custodians, handoffs, events };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The human answer: origin, every custodian, every step. */
|
|
168
|
+
export function custodySummary(entries: Entry[]): { origin: string | null; custodians: string[]; steps: string[] } {
|
|
169
|
+
const steps: string[] = [];
|
|
170
|
+
const custodians: string[] = [];
|
|
171
|
+
let origin: string | null = null;
|
|
172
|
+
for (const e of entries) {
|
|
173
|
+
if (isSwarm(e)) {
|
|
174
|
+
steps.push(String(e.body.task));
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const r = e as A2AReceipt;
|
|
178
|
+
if (origin === null) origin = r.initiator.agent_id;
|
|
179
|
+
steps.push(r.target);
|
|
180
|
+
if (!custodians.includes(r.initiator.agent_id)) custodians.push(r.initiator.agent_id);
|
|
181
|
+
if (!custodians.includes(r.responder.agent_id)) custodians.push(r.responder.agent_id);
|
|
182
|
+
}
|
|
183
|
+
return { origin, custodians, steps };
|
|
184
|
+
}
|