@zanii/constitution 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 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,62 @@
1
+ # @zanii/constitution
2
+
3
+ Machine-checkable behavioral constraints as **signed policy**. The walls packages
4
+ (`fta`, `walls`) each hard-code one vertical's rules; this is the framework: **publish
5
+ the agent's rules as a signed document, then prove every action was evaluated against
6
+ them** — and prove they didn't change mid-process.
7
+
8
+ The mechanism reuses what already exists (zero server changes): a constitution's
9
+ canonical hash IS the `manifest_hash` an agent stamps on its receipts.
10
+
11
+ ```sh
12
+ npm install @zanii/constitution @zanii/core
13
+ ```
14
+
15
+ ```ts
16
+ import { createConstitution, constitutionHash, evaluate, verifyGovernance, governanceTrail } from '@zanii/constitution';
17
+
18
+ const c = createConstitution({
19
+ issuer: owner.did,
20
+ name: 'support-agent-rules',
21
+ rules: [ // FIRST MATCH WINS
22
+ { id: 'no-payments', effect: 'forbid', targets: ['payments.*'] },
23
+ { id: 'gate-outbound', effect: 'require_approval', targets: ['email.send', 'sms.*'] },
24
+ { id: 'crm-ok', effect: 'allow', targets: ['crm.*'] },
25
+ ],
26
+ defaultEffect: 'allow', // 'forbid' = deny-by-default (strict form)
27
+ createdAt: now,
28
+ }, ownerKey);
29
+
30
+ // at act time: evaluate + stamp the hash on every receipt
31
+ evaluate(c, 'payments.transfer'); // { effect: 'forbid', rule: {...} }
32
+ await zanii.record({ target, payload, provenance: { manifestHash: constitutionHash(c) } });
33
+
34
+ // at audit time: the deterministic governance verdict
35
+ const report = verifyGovernance(c, receipts);
36
+ report.violations; // 'forbidden' (stamped AND hit a forbid rule — self-incriminating)
37
+ // 'ungoverned' (missing/foreign stamp — visible, not silently fine)
38
+ report.approvals_required; // demand the owner-signed confirmations for these
39
+
40
+ governanceTrail(receipts); // which rulebooks governed the stream; interleaving = red flag
41
+ ```
42
+
43
+ Python: `from zanii.constitution import create_constitution, verify_governance, governance_trail, ...`
44
+ — byte-identical JCS objects and hashes.
45
+
46
+ ## Why this closes the loop
47
+
48
+ 1. **Prove the rules** — issuer-signed, content-addressed: change one rule and every
49
+ subsequent receipt visibly points at a different rulebook.
50
+ 2. **Prove they were followed** — a stamped receipt whose target hits a `forbid` rule
51
+ is a provable violation the agent recorded itself.
52
+ 3. **Prove they held** — `governanceTrail` flags interleaved rulebooks (A,B,A): the
53
+ same red flag `@zanii/gov` raises when a state algorithm's rules change mid-process.
54
+
55
+ ## The limit, stated up front
56
+
57
+ The stamp proves an action was *recorded as governed* — act-time **enforcement** is
58
+ `@zanii/runtime`/`@zanii/policy`'s job, and `require_approval` *verification*
59
+ (matching owner-signed confirmations) stays with the runtime; we report which actions
60
+ required approval so the auditor can demand the confirmations. An agent holding raw
61
+ credentials can still act off the rails entirely — credential custody, unchanged. A
62
+ constitution binds only when the verifier demands the stamp.
@@ -0,0 +1,93 @@
1
+ import { type Receipt } from '@zanii/core';
2
+ export type RuleEffect = 'forbid' | 'require_approval' | 'allow';
3
+ export interface Rule {
4
+ id: string;
5
+ effect: RuleEffect;
6
+ /** Scope patterns this rule applies to, e.g. `payments.*`, `email.send`. */
7
+ targets: string[];
8
+ note?: string;
9
+ }
10
+ export interface Constitution {
11
+ v: 1;
12
+ type: 'constitution';
13
+ /** Who binds the agent to these rules — normally the owner. */
14
+ issuer: string;
15
+ name: string;
16
+ /** Evaluated FIRST MATCH WINS, top to bottom. */
17
+ rules: Rule[];
18
+ /** Effect when no rule matches. A deny-by-default constitution is the strict form. */
19
+ default: 'allow' | 'forbid';
20
+ created_at: string;
21
+ /** `ed25519:<hex>` by the issuer. */
22
+ sig?: string;
23
+ }
24
+ export interface ConstitutionInput {
25
+ issuer: string;
26
+ name: string;
27
+ rules: Rule[];
28
+ /** Defaults to 'allow' (permissive: rules carve out the exceptions). */
29
+ defaultEffect?: 'allow' | 'forbid';
30
+ createdAt: string;
31
+ }
32
+ /** Build + sign the rulebook with the issuer's key. */
33
+ export declare function createConstitution(input: ConstitutionInput, issuerPrivateKey: Uint8Array): Constitution;
34
+ /** Verify structure + the issuer's signature. */
35
+ export declare function verifyConstitution(c: Constitution | undefined): boolean;
36
+ /**
37
+ * Canonical hash of the signed constitution — the value to stamp on receipts as
38
+ * `manifest_hash` (`record({ provenance: { manifestHash } })`). Content-addressed:
39
+ * change one rule and every subsequent receipt visibly points at a different rulebook.
40
+ */
41
+ export declare function constitutionHash(c: Constitution): string;
42
+ export interface Evaluation {
43
+ effect: RuleEffect;
44
+ /** The first matching rule, or null when the default applied. */
45
+ rule: Rule | null;
46
+ }
47
+ /** Evaluate one target — FIRST MATCH WINS, then the constitution's default. Pure. */
48
+ export declare function evaluate(c: Constitution, target: string): Evaluation;
49
+ export interface Violation {
50
+ /** JCS hash of the offending receipt. */
51
+ receipt: string;
52
+ target: string;
53
+ /** `forbidden` = stamped AND hit a forbid rule (self-incriminating). `ungoverned` = missing/foreign stamp. */
54
+ kind: 'forbidden' | 'ungoverned';
55
+ rule_id?: string;
56
+ }
57
+ export interface GovernanceReport {
58
+ ok: boolean;
59
+ violations: Violation[];
60
+ /** Actions that required approval — demand the owner-signed confirmations for these. */
61
+ approvals_required: Array<{
62
+ receipt: string;
63
+ target: string;
64
+ rule_id: string;
65
+ }>;
66
+ /** Receipts checked. */
67
+ actions: number;
68
+ }
69
+ /**
70
+ * The governance verdict — deterministic. Every receipt must carry THIS constitution's
71
+ * hash as its `manifest_hash` (else `ungoverned`), and no stamped receipt's target may
72
+ * hit a `forbid` rule (else `forbidden` — the agent recorded its own violation).
73
+ * Receipt signature validity is `verifyReceipt`'s job; this checks governance only.
74
+ */
75
+ export declare function verifyGovernance(c: Constitution, receipts: Receipt[]): GovernanceReport;
76
+ export interface GovernanceTrail {
77
+ /** Distinct manifest_hashes in order of first appearance ('' for unstamped). */
78
+ manifests: string[];
79
+ /** Receipts per manifest. */
80
+ counts: Record<string, number>;
81
+ /** true when manifests interleave (A…B…A) — rules flip-flopping mid-stream. */
82
+ interleaved: boolean;
83
+ /** Receipts with no manifest_hash at all. */
84
+ unstamped: number;
85
+ }
86
+ /**
87
+ * Which rulebooks governed this stream, and did they change cleanly? A clean upgrade
88
+ * looks like A,A,A,B,B; interleaving (A,B,A) means different rules governed
89
+ * interchangeable moments — the same red flag `gov` raises for state decisions.
90
+ * Pass receipts in ledger (ts) order.
91
+ */
92
+ export declare function governanceTrail(receipts: Receipt[]): GovernanceTrail;
93
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgCA,OAAO,EAA0D,KAAK,OAAO,EAAE,MAAM,aAAa,CAAC;AAEnG,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,kBAAkB,GAAG,OAAO,CAAC;AAEjE,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,UAAU,CAAC;IACnB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,cAAc,CAAC;IACrB,+DAA+D;IAC/D,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,sFAAsF;IACtF,OAAO,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;IAC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,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,gBAAgB,CAmBvF;AAED,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,6BAA6B;IAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,+EAA+E;IAC/E,WAAW,EAAE,OAAO,CAAC;IACrB,6CAA6C;IAC7C,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,eAAe,CAepE"}
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * @zanii/constitution — machine-checkable behavioral constraints as signed policy.
3
+ *
4
+ * The walls packages (`fta`, `sca`, `walls`) each hard-code one vertical's rules. This
5
+ * generalizes the pattern into a framework: **publish the agent's rules as a signed
6
+ * document, then prove every action was evaluated against them.**
7
+ *
8
+ * The mechanism reuses what already exists — no new receipt fields, zero server
9
+ * changes. A constitution's canonical hash IS the `manifest_hash` an agent stamps on
10
+ * its receipts (SPEC §3, same field the walls use). That closes the loop three ways:
11
+ *
12
+ * 1. **"Prove the agent's rules"** — the constitution is issuer-signed and content-
13
+ * addressed; the stamp on each receipt commits that action to that exact rulebook.
14
+ * 2. **"Prove they were followed"** — `verifyGovernance` is deterministic: a receipt
15
+ * whose target hits a `forbid` rule *while carrying the stamp* is a **provable,
16
+ * self-incriminating violation**; a receipt missing the stamp is an **ungoverned
17
+ * action** — visible, not silently fine.
18
+ * 3. **"Prove they didn't change mid-process"** — `governanceTrail` (the `gov` trick,
19
+ * generalized) lists which rulebooks governed the stream and flags interleaving:
20
+ * rules that flip back and forth mid-stream are a red flag everywhere.
21
+ *
22
+ * ## The limit, stated up front
23
+ *
24
+ * The stamp proves an action was *recorded as governed* — enforcement at act-time is
25
+ * `@zanii/runtime`/`@zanii/policy`'s job, and `require_approval` **verification**
26
+ * (matching owner-signed confirmations) stays with the runtime; we report which
27
+ * actions required approval so an auditor can demand the confirmations. And an agent
28
+ * still holding raw credentials can act off the rails entirely — the credential-custody
29
+ * problem, unchanged. A constitution binds only when the verifier demands the stamp.
30
+ */
31
+ import { ed25519 } from '@noble/curves/ed25519';
32
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
33
+ import { canonicalBytes, jcsHash, publicKeyFromDid, scopeCovers } from '@zanii/core';
34
+ /** Build + sign the rulebook with the issuer's key. */
35
+ export function createConstitution(input, issuerPrivateKey) {
36
+ if (!input.issuer)
37
+ throw new Error('issuer is required');
38
+ if (!input.name)
39
+ throw new Error('name is required');
40
+ if (!input.rules?.length)
41
+ throw new Error('a constitution with no rules constrains nothing');
42
+ const ids = new Set();
43
+ for (const r of input.rules) {
44
+ if (!r.id)
45
+ throw new Error('every rule needs an id');
46
+ if (ids.has(r.id))
47
+ throw new Error(`duplicate rule id '${r.id}'`);
48
+ ids.add(r.id);
49
+ if (!['forbid', 'require_approval', 'allow'].includes(r.effect))
50
+ throw new Error(`rule '${r.id}': invalid effect '${r.effect}'`);
51
+ if (!r.targets?.length)
52
+ throw new Error(`rule '${r.id}' has no targets`);
53
+ }
54
+ if (Number.isNaN(Date.parse(input.createdAt)))
55
+ throw new Error('createdAt must be an ISO timestamp');
56
+ const unsigned = {
57
+ v: 1,
58
+ type: 'constitution',
59
+ issuer: input.issuer,
60
+ name: input.name,
61
+ rules: input.rules,
62
+ default: input.defaultEffect ?? 'allow',
63
+ created_at: input.createdAt,
64
+ };
65
+ const sig = ed25519.sign(canonicalBytes(unsigned), issuerPrivateKey);
66
+ return { ...unsigned, sig: `ed25519:${bytesToHex(sig)}` };
67
+ }
68
+ /** Verify structure + the issuer's signature. */
69
+ export function verifyConstitution(c) {
70
+ const p = c ?? {};
71
+ if (p.v !== 1 || p.type !== 'constitution' || !p.issuer || !p.name)
72
+ return false;
73
+ if (!Array.isArray(p.rules) || p.rules.length === 0)
74
+ return false;
75
+ if (new Set(p.rules.map((r) => r?.id)).size !== p.rules.length)
76
+ return false;
77
+ if (!p.rules.every((r) => r && ['forbid', 'require_approval', 'allow'].includes(r.effect) && Array.isArray(r.targets) && r.targets.length > 0))
78
+ return false;
79
+ if (p.default !== 'allow' && p.default !== 'forbid')
80
+ return false;
81
+ const pub = publicKeyFromDid(p.issuer);
82
+ const hex = typeof p.sig === 'string' && p.sig.startsWith('ed25519:') ? p.sig.slice(8) : '';
83
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex))
84
+ return false;
85
+ const { sig: _omit, ...unsigned } = p;
86
+ try {
87
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned), pub);
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ /**
94
+ * Canonical hash of the signed constitution — the value to stamp on receipts as
95
+ * `manifest_hash` (`record({ provenance: { manifestHash } })`). Content-addressed:
96
+ * change one rule and every subsequent receipt visibly points at a different rulebook.
97
+ */
98
+ export function constitutionHash(c) {
99
+ return jcsHash(c);
100
+ }
101
+ /** Evaluate one target — FIRST MATCH WINS, then the constitution's default. Pure. */
102
+ export function evaluate(c, target) {
103
+ for (const r of c.rules) {
104
+ if (r.targets.some((t) => scopeCovers(t, target)))
105
+ return { effect: r.effect, rule: r };
106
+ }
107
+ return { effect: c.default, rule: null };
108
+ }
109
+ /**
110
+ * The governance verdict — deterministic. Every receipt must carry THIS constitution's
111
+ * hash as its `manifest_hash` (else `ungoverned`), and no stamped receipt's target may
112
+ * hit a `forbid` rule (else `forbidden` — the agent recorded its own violation).
113
+ * Receipt signature validity is `verifyReceipt`'s job; this checks governance only.
114
+ */
115
+ export function verifyGovernance(c, receipts) {
116
+ if (!verifyConstitution(c))
117
+ throw new Error('constitution does not verify — refuse to audit against an unsigned rulebook');
118
+ const hash = constitutionHash(c);
119
+ const violations = [];
120
+ const approvals = [];
121
+ for (const r of receipts) {
122
+ const rHash = jcsHash(r);
123
+ if (r.manifest_hash !== hash) {
124
+ violations.push({ receipt: rHash, target: r.target, kind: 'ungoverned' });
125
+ continue;
126
+ }
127
+ const ev = evaluate(c, r.target);
128
+ if (ev.effect === 'forbid') {
129
+ violations.push({ receipt: rHash, target: r.target, kind: 'forbidden', ...(ev.rule ? { rule_id: ev.rule.id } : {}) });
130
+ }
131
+ else if (ev.effect === 'require_approval' && ev.rule) {
132
+ approvals.push({ receipt: rHash, target: r.target, rule_id: ev.rule.id });
133
+ }
134
+ }
135
+ return { ok: violations.length === 0, violations, approvals_required: approvals, actions: receipts.length };
136
+ }
137
+ /**
138
+ * Which rulebooks governed this stream, and did they change cleanly? A clean upgrade
139
+ * looks like A,A,A,B,B; interleaving (A,B,A) means different rules governed
140
+ * interchangeable moments — the same red flag `gov` raises for state decisions.
141
+ * Pass receipts in ledger (ts) order.
142
+ */
143
+ export function governanceTrail(receipts) {
144
+ const order = [];
145
+ const counts = {};
146
+ let interleaved = false;
147
+ let unstamped = 0;
148
+ let prev = null;
149
+ for (const r of receipts) {
150
+ const m = r.manifest_hash ?? '';
151
+ if (m === '')
152
+ unstamped++;
153
+ counts[m] = (counts[m] ?? 0) + 1;
154
+ if (!order.includes(m))
155
+ order.push(m);
156
+ else if (prev !== m)
157
+ interleaved = true;
158
+ prev = m;
159
+ }
160
+ return { manifests: order, counts, interleaved, unstamped };
161
+ }
162
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAgB,MAAM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EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC;AAC9D,CAAC"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@zanii/constitution",
3
+ "version": "0.1.0",
4
+ "description": "Machine-checkable behavioral constraints as signed policy - publish an agent's rules (forbid / require_approval / allow over scope patterns), stamp the constitution hash on every receipt via the existing manifest_hash field, then PROVE each action was governed: a forbidden action with the stamp is a provable violation, and a rulebook change mid-stream is visible. Generalizes the fta/sca walls into a framework.",
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
+ "@noble/curves": "^1.8.1",
35
+ "@noble/hashes": "^1.7.1",
36
+ "@zanii/core": "0.4.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.build.json",
40
+ "test": "vitest run",
41
+ "typecheck": "tsc --noEmit"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @zanii/constitution — machine-checkable behavioral constraints as signed policy.
3
+ *
4
+ * The walls packages (`fta`, `sca`, `walls`) each hard-code one vertical's rules. This
5
+ * generalizes the pattern into a framework: **publish the agent's rules as a signed
6
+ * document, then prove every action was evaluated against them.**
7
+ *
8
+ * The mechanism reuses what already exists — no new receipt fields, zero server
9
+ * changes. A constitution's canonical hash IS the `manifest_hash` an agent stamps on
10
+ * its receipts (SPEC §3, same field the walls use). That closes the loop three ways:
11
+ *
12
+ * 1. **"Prove the agent's rules"** — the constitution is issuer-signed and content-
13
+ * addressed; the stamp on each receipt commits that action to that exact rulebook.
14
+ * 2. **"Prove they were followed"** — `verifyGovernance` is deterministic: a receipt
15
+ * whose target hits a `forbid` rule *while carrying the stamp* is a **provable,
16
+ * self-incriminating violation**; a receipt missing the stamp is an **ungoverned
17
+ * action** — visible, not silently fine.
18
+ * 3. **"Prove they didn't change mid-process"** — `governanceTrail` (the `gov` trick,
19
+ * generalized) lists which rulebooks governed the stream and flags interleaving:
20
+ * rules that flip back and forth mid-stream are a red flag everywhere.
21
+ *
22
+ * ## The limit, stated up front
23
+ *
24
+ * The stamp proves an action was *recorded as governed* — enforcement at act-time is
25
+ * `@zanii/runtime`/`@zanii/policy`'s job, and `require_approval` **verification**
26
+ * (matching owner-signed confirmations) stays with the runtime; we report which
27
+ * actions required approval so an auditor can demand the confirmations. And an agent
28
+ * still holding raw credentials can act off the rails entirely — the credential-custody
29
+ * problem, unchanged. A constitution binds only when the verifier demands the stamp.
30
+ */
31
+ import { ed25519 } from '@noble/curves/ed25519';
32
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
33
+ import { canonicalBytes, jcsHash, publicKeyFromDid, scopeCovers, type Receipt } from '@zanii/core';
34
+
35
+ export type RuleEffect = 'forbid' | 'require_approval' | 'allow';
36
+
37
+ export interface Rule {
38
+ id: string;
39
+ effect: RuleEffect;
40
+ /** Scope patterns this rule applies to, e.g. `payments.*`, `email.send`. */
41
+ targets: string[];
42
+ note?: string;
43
+ }
44
+
45
+ export interface Constitution {
46
+ v: 1;
47
+ type: 'constitution';
48
+ /** Who binds the agent to these rules — normally the owner. */
49
+ issuer: string;
50
+ name: string;
51
+ /** Evaluated FIRST MATCH WINS, top to bottom. */
52
+ rules: Rule[];
53
+ /** Effect when no rule matches. A deny-by-default constitution is the strict form. */
54
+ default: 'allow' | 'forbid';
55
+ created_at: string;
56
+ /** `ed25519:<hex>` by the issuer. */
57
+ sig?: string;
58
+ }
59
+
60
+ export interface ConstitutionInput {
61
+ issuer: string;
62
+ name: string;
63
+ rules: Rule[];
64
+ /** Defaults to 'allow' (permissive: rules carve out the exceptions). */
65
+ defaultEffect?: 'allow' | 'forbid';
66
+ createdAt: string;
67
+ }
68
+
69
+ /** Build + sign the rulebook with the issuer's key. */
70
+ export function createConstitution(input: ConstitutionInput, issuerPrivateKey: Uint8Array): Constitution {
71
+ if (!input.issuer) throw new Error('issuer is required');
72
+ if (!input.name) throw new Error('name is required');
73
+ if (!input.rules?.length) throw new Error('a constitution with no rules constrains nothing');
74
+ const ids = new Set<string>();
75
+ for (const r of input.rules) {
76
+ if (!r.id) throw new Error('every rule needs an id');
77
+ if (ids.has(r.id)) throw new Error(`duplicate rule id '${r.id}'`);
78
+ ids.add(r.id);
79
+ if (!['forbid', 'require_approval', 'allow'].includes(r.effect)) throw new Error(`rule '${r.id}': invalid effect '${r.effect}'`);
80
+ if (!r.targets?.length) throw new Error(`rule '${r.id}' has no targets`);
81
+ }
82
+ if (Number.isNaN(Date.parse(input.createdAt))) throw new Error('createdAt must be an ISO timestamp');
83
+ const unsigned = {
84
+ v: 1 as const,
85
+ type: 'constitution' as const,
86
+ issuer: input.issuer,
87
+ name: input.name,
88
+ rules: input.rules,
89
+ default: input.defaultEffect ?? ('allow' as const),
90
+ created_at: input.createdAt,
91
+ };
92
+ const sig = ed25519.sign(canonicalBytes(unsigned), issuerPrivateKey);
93
+ return { ...unsigned, sig: `ed25519:${bytesToHex(sig)}` };
94
+ }
95
+
96
+ /** Verify structure + the issuer's signature. */
97
+ export function verifyConstitution(c: Constitution | undefined): boolean {
98
+ const p = c ?? ({} as Constitution);
99
+ if (p.v !== 1 || p.type !== 'constitution' || !p.issuer || !p.name) return false;
100
+ if (!Array.isArray(p.rules) || p.rules.length === 0) return false;
101
+ if (new Set(p.rules.map((r) => r?.id)).size !== p.rules.length) return false;
102
+ if (!p.rules.every((r) => r && ['forbid', 'require_approval', 'allow'].includes(r.effect) && Array.isArray(r.targets) && r.targets.length > 0)) return false;
103
+ if (p.default !== 'allow' && p.default !== 'forbid') return false;
104
+ const pub = publicKeyFromDid(p.issuer);
105
+ const hex = typeof p.sig === 'string' && p.sig.startsWith('ed25519:') ? p.sig.slice(8) : '';
106
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex)) return false;
107
+ const { sig: _omit, ...unsigned } = p;
108
+ try {
109
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned as unknown as Record<string, unknown>), pub);
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Canonical hash of the signed constitution — the value to stamp on receipts as
117
+ * `manifest_hash` (`record({ provenance: { manifestHash } })`). Content-addressed:
118
+ * change one rule and every subsequent receipt visibly points at a different rulebook.
119
+ */
120
+ export function constitutionHash(c: Constitution): string {
121
+ return jcsHash(c as unknown as Record<string, unknown>);
122
+ }
123
+
124
+ export interface Evaluation {
125
+ effect: RuleEffect;
126
+ /** The first matching rule, or null when the default applied. */
127
+ rule: Rule | null;
128
+ }
129
+
130
+ /** Evaluate one target — FIRST MATCH WINS, then the constitution's default. Pure. */
131
+ export function evaluate(c: Constitution, target: string): Evaluation {
132
+ for (const r of c.rules) {
133
+ if (r.targets.some((t) => scopeCovers(t, target))) return { effect: r.effect, rule: r };
134
+ }
135
+ return { effect: c.default, rule: null };
136
+ }
137
+
138
+ export interface Violation {
139
+ /** JCS hash of the offending receipt. */
140
+ receipt: string;
141
+ target: string;
142
+ /** `forbidden` = stamped AND hit a forbid rule (self-incriminating). `ungoverned` = missing/foreign stamp. */
143
+ kind: 'forbidden' | 'ungoverned';
144
+ rule_id?: string;
145
+ }
146
+
147
+ export interface GovernanceReport {
148
+ ok: boolean;
149
+ violations: Violation[];
150
+ /** Actions that required approval — demand the owner-signed confirmations for these. */
151
+ approvals_required: Array<{ receipt: string; target: string; rule_id: string }>;
152
+ /** Receipts checked. */
153
+ actions: number;
154
+ }
155
+
156
+ /**
157
+ * The governance verdict — deterministic. Every receipt must carry THIS constitution's
158
+ * hash as its `manifest_hash` (else `ungoverned`), and no stamped receipt's target may
159
+ * hit a `forbid` rule (else `forbidden` — the agent recorded its own violation).
160
+ * Receipt signature validity is `verifyReceipt`'s job; this checks governance only.
161
+ */
162
+ export function verifyGovernance(c: Constitution, receipts: Receipt[]): GovernanceReport {
163
+ if (!verifyConstitution(c)) throw new Error('constitution does not verify — refuse to audit against an unsigned rulebook');
164
+ const hash = constitutionHash(c);
165
+ const violations: Violation[] = [];
166
+ const approvals: GovernanceReport['approvals_required'] = [];
167
+ for (const r of receipts) {
168
+ const rHash = jcsHash(r as unknown as Record<string, unknown>);
169
+ if (r.manifest_hash !== hash) {
170
+ violations.push({ receipt: rHash, target: r.target, kind: 'ungoverned' });
171
+ continue;
172
+ }
173
+ const ev = evaluate(c, r.target);
174
+ if (ev.effect === 'forbid') {
175
+ violations.push({ receipt: rHash, target: r.target, kind: 'forbidden', ...(ev.rule ? { rule_id: ev.rule.id } : {}) });
176
+ } else if (ev.effect === 'require_approval' && ev.rule) {
177
+ approvals.push({ receipt: rHash, target: r.target, rule_id: ev.rule.id });
178
+ }
179
+ }
180
+ return { ok: violations.length === 0, violations, approvals_required: approvals, actions: receipts.length };
181
+ }
182
+
183
+ export interface GovernanceTrail {
184
+ /** Distinct manifest_hashes in order of first appearance ('' for unstamped). */
185
+ manifests: string[];
186
+ /** Receipts per manifest. */
187
+ counts: Record<string, number>;
188
+ /** true when manifests interleave (A…B…A) — rules flip-flopping mid-stream. */
189
+ interleaved: boolean;
190
+ /** Receipts with no manifest_hash at all. */
191
+ unstamped: number;
192
+ }
193
+
194
+ /**
195
+ * Which rulebooks governed this stream, and did they change cleanly? A clean upgrade
196
+ * looks like A,A,A,B,B; interleaving (A,B,A) means different rules governed
197
+ * interchangeable moments — the same red flag `gov` raises for state decisions.
198
+ * Pass receipts in ledger (ts) order.
199
+ */
200
+ export function governanceTrail(receipts: Receipt[]): GovernanceTrail {
201
+ const order: string[] = [];
202
+ const counts: Record<string, number> = {};
203
+ let interleaved = false;
204
+ let unstamped = 0;
205
+ let prev: string | null = null;
206
+ for (const r of receipts) {
207
+ const m = r.manifest_hash ?? '';
208
+ if (m === '') unstamped++;
209
+ counts[m] = (counts[m] ?? 0) + 1;
210
+ if (!order.includes(m)) order.push(m);
211
+ else if (prev !== m) interleaved = true;
212
+ prev = m;
213
+ }
214
+ return { manifests: order, counts, interleaved, unstamped };
215
+ }