@affiant/core 0.1.0-alpha.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 (96) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +354 -0
  3. package/dist/context.d.ts +136 -0
  4. package/dist/context.d.ts.map +1 -0
  5. package/dist/context.js +30 -0
  6. package/dist/context.js.map +1 -0
  7. package/dist/docket/entry.d.ts +421 -0
  8. package/dist/docket/entry.d.ts.map +1 -0
  9. package/dist/docket/entry.js +155 -0
  10. package/dist/docket/entry.js.map +1 -0
  11. package/dist/docket/expiry.d.ts +82 -0
  12. package/dist/docket/expiry.d.ts.map +1 -0
  13. package/dist/docket/expiry.js +106 -0
  14. package/dist/docket/expiry.js.map +1 -0
  15. package/dist/docket/memory.d.ts +163 -0
  16. package/dist/docket/memory.d.ts.map +1 -0
  17. package/dist/docket/memory.js +528 -0
  18. package/dist/docket/memory.js.map +1 -0
  19. package/dist/docket/store.d.ts +387 -0
  20. package/dist/docket/store.d.ts.map +1 -0
  21. package/dist/docket/store.js +51 -0
  22. package/dist/docket/store.js.map +1 -0
  23. package/dist/errors.d.ts +153 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +164 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/gate/coverage.d.ts +152 -0
  28. package/dist/gate/coverage.d.ts.map +1 -0
  29. package/dist/gate/coverage.js +114 -0
  30. package/dist/gate/coverage.js.map +1 -0
  31. package/dist/gate/decide.d.ts +207 -0
  32. package/dist/gate/decide.d.ts.map +1 -0
  33. package/dist/gate/decide.js +559 -0
  34. package/dist/gate/decide.js.map +1 -0
  35. package/dist/gate/gate.d.ts +212 -0
  36. package/dist/gate/gate.d.ts.map +1 -0
  37. package/dist/gate/gate.js +175 -0
  38. package/dist/gate/gate.js.map +1 -0
  39. package/dist/gate/pipeline.d.ts +285 -0
  40. package/dist/gate/pipeline.d.ts.map +1 -0
  41. package/dist/gate/pipeline.js +515 -0
  42. package/dist/gate/pipeline.js.map +1 -0
  43. package/dist/gate/policy.d.ts +272 -0
  44. package/dist/gate/policy.d.ts.map +1 -0
  45. package/dist/gate/policy.js +396 -0
  46. package/dist/gate/policy.js.map +1 -0
  47. package/dist/gate/wrap.d.ts +107 -0
  48. package/dist/gate/wrap.d.ts.map +1 -0
  49. package/dist/gate/wrap.js +164 -0
  50. package/dist/gate/wrap.js.map +1 -0
  51. package/dist/index.d.ts +95 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +111 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/model/affidavit.d.ts +354 -0
  56. package/dist/model/affidavit.d.ts.map +1 -0
  57. package/dist/model/affidavit.js +417 -0
  58. package/dist/model/affidavit.js.map +1 -0
  59. package/dist/model/amendments.d.ts +160 -0
  60. package/dist/model/amendments.d.ts.map +1 -0
  61. package/dist/model/amendments.js +183 -0
  62. package/dist/model/amendments.js.map +1 -0
  63. package/dist/model/canonical.d.ts +311 -0
  64. package/dist/model/canonical.d.ts.map +1 -0
  65. package/dist/model/canonical.js +665 -0
  66. package/dist/model/canonical.js.map +1 -0
  67. package/dist/model/money.d.ts +127 -0
  68. package/dist/model/money.d.ts.map +1 -0
  69. package/dist/model/money.js +177 -0
  70. package/dist/model/money.js.map +1 -0
  71. package/dist/model/provenance.d.ts +315 -0
  72. package/dist/model/provenance.d.ts.map +1 -0
  73. package/dist/model/provenance.js +223 -0
  74. package/dist/model/provenance.js.map +1 -0
  75. package/dist/ports.d.ts +269 -0
  76. package/dist/ports.d.ts.map +1 -0
  77. package/dist/ports.js +34 -0
  78. package/dist/ports.js.map +1 -0
  79. package/dist/store-memory.d.ts +21 -0
  80. package/dist/store-memory.d.ts.map +1 -0
  81. package/dist/store-memory.js +20 -0
  82. package/dist/store-memory.js.map +1 -0
  83. package/dist/telemetry-keys.d.ts +65 -0
  84. package/dist/telemetry-keys.d.ts.map +1 -0
  85. package/dist/telemetry-keys.js +72 -0
  86. package/dist/telemetry-keys.js.map +1 -0
  87. package/dist/telemetry.d.ts +77 -0
  88. package/dist/telemetry.d.ts.map +1 -0
  89. package/dist/telemetry.js +43 -0
  90. package/dist/telemetry.js.map +1 -0
  91. package/dist/testing.d.ts +574 -0
  92. package/dist/testing.d.ts.map +1 -0
  93. package/dist/testing.js +1291 -0
  94. package/dist/testing.js.map +1 -0
  95. package/package.json +75 -0
  96. package/telemetry-keys.json +92 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Seevali Rathnayake
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,354 @@
1
+ # @affiant/core
2
+
3
+ The [Affiant](https://affiant.dev) gate for TypeScript: the thing that stands between
4
+ an AI agent and your database.
5
+
6
+ Put it in front of your write tools and a tool call stops being a write. It becomes an
7
+ **Affidavit** — per field, the value the agent wants to write, the value that is there
8
+ now, where the value came from and how confident the producer is — filed as a **Docket**
9
+ entry and handed to you as an **Evidence Card** for a person to approve, amend or reject.
10
+ A **Standing Order** is a policy verdict that approves a write with no person present,
11
+ and it files an attestation naming the policy in the same operation, so even the
12
+ unattended writes are attributable. Your own executor performs the write, after the
13
+ decision, and reports what happened; the gate never touches your database. Nothing about
14
+ this depends on which model you use, which database you write to, or how the card
15
+ reaches the person — those are ports you supply.
16
+
17
+ > **Publishable; awaiting the npm scope.** This package lives in its repository and is
18
+ > consumed through the workspace. The condition for publishing was exact: a **public
19
+ > parity report** — the per-implementation list of conformance fixtures each
20
+ > implementation does not yet pass — and a **green, merge-blocking TypeScript
21
+ > conformance driver** running the shared fixture suite against this package. Both now
22
+ > hold, at the rulebook's [`v0.1.0`](https://github.com/Sakwala/affiant-protocol/releases/tag/v0.1.0)
23
+ > tag: the [.NET parity report](https://github.com/Sakwala/affiant-protocol/blob/v0.1.0/conformance/parity/dotnet-v0.1.json)
24
+ > is public, with its oracle run log alongside it under `conformance/results/`, and
25
+ > this package's own [conformance parity manifest](../conformance-driver/conformance/parity/typescript-v0.1.json)
26
+ > is green on Node, Bun and workerd, asserted by the `conformance` job that is
27
+ > required on `main`. What remains is not a fixture or a check — it is the
28
+ > maintainer's npm token. The gate is still enforced rather than relaxed on trust:
29
+ > `prepack` refuses, so `npm pack` and `npm publish` both fail with the reason, until
30
+ > the maintainer sets `AFFIANT_ALLOW_PUBLISH=1` once the `@affiant` scope and a
31
+ > publish token for it exist.
32
+
33
+ ## The rules this package is held to
34
+
35
+ Everything below cites a rule id — `GT-5`, `AZ-2`, `DK-3`. They resolve in
36
+ [`INVARIANTS.md`](https://github.com/Sakwala/affiant-protocol/blob/main/INVARIANTS.md)
37
+ in the rulebook, [Sakwala/affiant-protocol](https://github.com/Sakwala/affiant-protocol):
38
+ numbered, testable rules that both the .NET implementation and this one are held to,
39
+ with a shared conformance fixture suite. A citation here is not a gesture at a
40
+ philosophy; it is a pointer to a sentence somebody can disagree with, and to a fixture
41
+ that fails when this package stops obeying it.
42
+
43
+ ## Using it
44
+
45
+ ```ts
46
+ import { createGate } from "@affiant/core";
47
+ import type { Operation, TurnContext } from "@affiant/core";
48
+ import { InMemoryDocketStore, InMemorySessionStore } from "@affiant/core/store-memory";
49
+
50
+ const store = new InMemoryDocketStore();
51
+
52
+ const gate = createGate({
53
+ store,
54
+ sessions: new InMemorySessionStore(store),
55
+ // Your model, asked once for structured values against the unmodified turn.
56
+ inference: { infer: async (turn, schema) => extract(turn, schema) },
57
+ // What the entity holds now, so every field can swear to what it replaces (AF-3).
58
+ projection: { previousValues: async (op) => db.read(op.entityType, op.entityId) },
59
+ // Who may decide. Asked before every transition; `false` refuses it (AZ-2).
60
+ authorization: { mayDecide: async (principal) => reviewers.has(principal.id) },
61
+ policies: [routineStatusChange], // your Standing Orders and confirmations (AZ-4)
62
+ defaultTtlMs: 30 * 60_000, // every filed entry carries a deadline (GT-4)
63
+ });
64
+
65
+ const ctx: TurnContext = {
66
+ conversationId: "conv-1",
67
+ tenantId: "acme",
68
+ channel: "chat",
69
+ principal: { kind: "member", id: "ana" },
70
+ turn: { utterance: "Set invoice INV-2 to Active", messageId: "msg-1", at: now() },
71
+ };
72
+
73
+ // One write tool, wrapped for this turn. Its own `execute` is never called (GT-6).
74
+ const updateInvoice = gate.wrap(
75
+ {
76
+ name: "update_invoice",
77
+ description: "Update an invoice",
78
+ writeCapable: true,
79
+ inputSchema: {
80
+ entityType: "Invoice",
81
+ fields: [
82
+ {
83
+ name: "status",
84
+ kind: "enum",
85
+ description: "The invoice status",
86
+ required: true,
87
+ allowedValues: ["Draft", "Active", "Retired"],
88
+ pattern: null,
89
+ },
90
+ ],
91
+ },
92
+ operation: (args: UpdateArgs): Operation => ({
93
+ kind: "update",
94
+ entityType: "Invoice",
95
+ entityId: args.id,
96
+ fields: ["status"],
97
+ }),
98
+ execute: async (args: UpdateArgs) => db.updateInvoice(args),
99
+ },
100
+ ctx,
101
+ );
102
+
103
+ const called = await updateInvoice.execute({ id: "invoice-1", status: "Active" });
104
+ if (called.kind === "write") {
105
+ await deliver(called.card); // the Evidence Card a person reads
106
+ const entry = await gate.decide(called.entryId, { kind: "approve" }, ctx);
107
+ await db.write(entry); // your executor — this package never writes (AZ-7)
108
+ await gate.markExecuted(entry.entryId, "executed", null, ctx);
109
+ }
110
+
111
+ // After a reconnect: what awaits a decision, then what awaits execution (DK-5).
112
+ const { items } = await gate.rehydrate({ tenantId: "acme" }, { limit: 20 });
113
+ ```
114
+
115
+ The in-memory stores are behind their own entry point on purpose. They are the
116
+ **reference** implementation — what the store-semantics fixtures are written against,
117
+ and what a durable store earns the name by passing — but a host in production should
118
+ never be one careless import away from an approval record that lives only in an isolate
119
+ about to be recycled.
120
+
121
+ ## The pipeline, in order
122
+
123
+ Every proposal runs the same nine steps (GT-1). Two entry points reach them:
124
+ `gate.wrap` for a tool a model calls, `gate.file` for a capture your host assembled
125
+ (a relay's message, a form, a replay), which enters at step 5 when its provenance is
126
+ already settled.
127
+
128
+ 1. **Turn context.** Every entry point takes it as a parameter; nothing is read from a
129
+ global. Two conversations interleaved in one process never share fields, pending
130
+ inference or proposals (GT-2).
131
+ 2. **Deterministic interceptors.** Your resolvers run first and set `External` or
132
+ `Computed` values with the binding that points at the artifact. They may not mint
133
+ `UserStated` — only a person can say what a person said (PV-3).
134
+ 3. **One structured inference**, tool-free, against the **unmodified** turn. What the
135
+ model returns is tagged `Conversation` when the value is literally in the utterance
136
+ (with the character span, when your port can give one) and `Inferred` when it is
137
+ not. Confidence is clamped into `[0, 1]` (PV-1).
138
+ 4. **Merge.** Per field the higher confidence wins, a tie goes to the more
139
+ deterministic source, and the loser stays on the record in the chain behind the
140
+ winner (PV-1).
141
+ 5. **Projection.** Your `ProjectionPort` supplies the previous values for an update; a
142
+ create carries `previousValue: null` on every field (AF-3). The Affidavit carries the
143
+ proposed fields and nothing else, a proposed field nothing produced a value for is
144
+ tagged `Empty` rather than dropped, and the three confidence numbers are computed
145
+ (AF-1, AF-2).
146
+ 6. **Substance refusal.** A proposal that swears to nothing — no field with a known
147
+ value, or a value sitting under an `Empty` tag — is refused before anything is filed
148
+ (GT-3). A green test suite over a gate that files empty Affidavits is the failure
149
+ this step exists to make impossible.
150
+ 7. **The policy chain.** Your policies run in order and the first non-null verdict
151
+ wins; no verdict means a person confirms. A `StandingOrder` verdict is honoured only
152
+ if it survives three checks (below). A requirement this version does not run is filed
153
+ verbatim and blocked, never quietly weakened (AZ-4).
154
+ 8. **The deadline**, from the verdict's own `ttlMs`, else the policy's default, else
155
+ the gate's — after the chain, so a policy that knows a capture is worthless in five
156
+ minutes can say so (GT-4).
157
+ 9. **Filing.** Idempotent by entry id: a retried tool call is a replay of one entry
158
+ with its **original** deadline, not a second review. A Standing Order writes the
159
+ status, the execution outcome and the attestation in the same operation as the
160
+ filing, so there is no window in which an approved write has no attribution (DK-1,
161
+ AZ-1).
162
+
163
+ ### The three checks on a person-free approval
164
+
165
+ A `StandingOrder` verdict degrades to `ReviewerConfirmation` — a person is asked — when
166
+ any of these is true. Degrading _toward_ a person is always safe; the prohibition is on
167
+ degrading to something weaker (AZ-4). Each degrade emits `standing-order.blocked`
168
+ carrying a stable `blocked.reason` code an operator can alert on.
169
+
170
+ 1. **A required field has no known value** (GT-5). A proposed field marked mandatory
171
+ that reads `Empty` blocks the Standing Order whatever the numbers say. A person may
172
+ still approve — they can see the hole, and an approval is of what was sworn to, not a
173
+ licence to invent the missing value. An **optional** empty field does not block by
174
+ rule.
175
+ 2. **The verdict rests on an unbound claim** (PV-4). A policy declares the provenance
176
+ sources it predicates on; if a declared source above `Conversation` carries no
177
+ binding — a grade any caller could assert with nothing behind it — the verdict is not
178
+ honoured. A policy that predicates only on values or host state is unaffected.
179
+ 3. **The risk score is above the policy's threshold** (GT-5). A verdict naming a
180
+ threshold fires iff `score <= threshold`, using **your** scorer. A threshold with no
181
+ scorer is refused at wire-up, never a silent non-fire.
182
+
183
+ ## The ports you supply
184
+
185
+ `createGate` refuses a wiring it can tell is wrong — a missing port, a deadline that is
186
+ not a deadline, a policy that declares a threshold with no scorer to compare against —
187
+ at wire-up, with a message naming what is missing. There is no option that turns the
188
+ gate off for a covered tool (CV-1).
189
+
190
+ | Port | What you implement |
191
+ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
192
+ | `InferencePort` | One tool-free structured call to your model, given the turn and the field schema, returning a value and a confidence per field. It is the only place a model is spoken to, and it is yours — this package ships no model client. |
193
+ | `ProjectionPort` | What the entity holds right now, so an update's fields can swear to what they replace. Return `null` for an entity that does not exist; the pipeline reads that as "nothing to project", not as "every field was empty". |
194
+ | `AuthorizationPort` | Whether this principal may decide this entry. Consulted on every decision, execution report and resubmission, after the tenant check and before any transition. A `false` — or a throw — refuses (AZ-2). |
195
+ | `RiskScorer` | Your risk function, returning a number the gate compares against a policy's threshold. Required only if a policy declares one. This package ships no formula and no floor (GT-5). |
196
+ | `Clock` | Where every instant on the record comes from. Defaults to the system clock; a test replaces it, which is how a deadline becomes something a fixture can drive rather than wait for. |
197
+ | `TelemetryPort` | Where the events go — filings, refusals, transitions, expiries, Standing Orders fired and blocked — named in a versioned registry so an operator can alert on a refusal rate without reading this source. Defaults to a port that drops them. |
198
+
199
+ Two more, both optional: a `FieldInterceptor` is a deterministic resolver for step 2,
200
+ and a `SessionStore` is the rehydration surface a reconnecting client needs. The
201
+ `DocketStore` is not optional — it is where entries live, and the in-memory one is a
202
+ real implementation of the whole contract, not a stub.
203
+
204
+ ## What this package deliberately does not ship
205
+
206
+ Each of these is absent because a rule says a framework that shipped it would be
207
+ non-conformant, not because it has not been written yet.
208
+
209
+ - **No executor.** No package here writes to your store. The only path to
210
+ `execution: "executed"` is `markExecuted` — your executor reporting what it did. A
211
+ framework that shipped a default executor that writes would be non-conformant (AZ-7).
212
+ - **No scoring formula and no floor.** The risk function is yours, and so is the
213
+ threshold. This package owns the comparison and nothing else (GT-5).
214
+ - **No transport.** No SignalR, SSE, REST or MCP framing; no rule here depends on any
215
+ of them, and hub names and invoke names are yours. You deliver the card
216
+ ([`@affiant/evidence-card`](../evidence-card) renders it) and you carry the decision
217
+ back (SR-5).
218
+ - **No timer.** The expiry sweep is bounded, paged and scheduled by you. Nothing here
219
+ runs a periodic sweep of its own, and nothing here loads a whole Docket into memory
220
+ (DK-3).
221
+ - **No model client**, for the same reason as the scorer: the inference step is a port.
222
+
223
+ ## Decisions: what a host must know
224
+
225
+ - **Identity fails closed.** An unresolved principal, a mismatch between the entry's
226
+ tenant and the caller's, or an authorization port that says no — or throws — refuses
227
+ the decision. There is no "identity unknown, allow" (AZ-2). The refusal happens before
228
+ the Docket is read, so a caller who may not decide cannot use a decision to learn
229
+ whether an entry exists.
230
+ - **The tenant is the boundary.** Every store operation is tenant-scoped: a lookup in
231
+ the wrong tenant is a miss, never another tenant's row. Reading an entry is scoped to
232
+ the tenant rather than the conversation, deliberately — a reviewer opens a queue or
233
+ follows a link, and the entry they are deciding was filed in some other conversation
234
+ of the same tenant.
235
+ - **Three attestation kinds, and no fourth** (AZ-1). `member` — a human-verified
236
+ session decided. `member-via-relay` — a person decided _through_ a trusted machine
237
+ caller, naming both the person and the relay. `standing-order` — a policy approved
238
+ with nobody present, naming the policy and its version. The kind _is_ the mode; there
239
+ is no separate field to drift from it.
240
+ - **A machine caller can never attest a person** (AZ-3). A relay asserts an identity;
241
+ it does not authenticate one. So a decision arriving with a `service` principal that
242
+ names a person attests `member-via-relay`, never `member`, and the record shows the
243
+ relay that carried it. The distinction is the difference between "Ana approved this"
244
+ and "something claiming to speak for Ana approved this", and an audit six months later
245
+ cannot reconstruct it from a record that flattened them.
246
+ - **A decision is a guarded compare-and-set.** Two decisions racing for one entry: one
247
+ wins, the other is refused. Never applied twice.
248
+ - **An execution outcome is recorded once, and a host that retries a write reports
249
+ once, when it knows the outcome.** `markExecuted` is a guarded compare-and-set too:
250
+ the row moves out of `unexecuted` exactly once, and a second report is refused with
251
+ `execution-already-recorded` rather than written over the first. Your outbox may
252
+ retry the write as many times as it likes — retries are yours (AZ-5) — but the
253
+ Docket carries the one fact about what happened, not the last thing anybody said.
254
+ Overwriting would let an approved-and-committed row later read `failed`: an edit in
255
+ place of a recorded fact (DK-4), and the loss of exactly the distinction DK-1
256
+ requires the row to keep.
257
+ - **An amendment is an approval with corrections.** The corrected fields are tagged
258
+ `UserStated` bound to the reviewer's act, and the three numbers are recomputed
259
+ (DK-2, AF-4). The row keeps both the Affidavit **as the agent proposed it**, never
260
+ edited, and the state the approval accepted — so a row can always show what the agent
261
+ originally said (DK-4).
262
+
263
+ ### Expiry is a state, not an event
264
+
265
+ An entry past its deadline reads `expired` on every query, whether or not a sweep has
266
+ run. Nothing depends on a background job having fired: a host whose sweep is broken
267
+ gets entries that cannot be approved, not entries that quietly stay approvable (DK-1).
268
+
269
+ `gate.expireDue(now, scope, limit)` is the sweep, and **you** schedule it — a cron, a
270
+ queue consumer, a Worker's scheduled handler. It processes at most `limit` entries and
271
+ tells you whether more remain, so it can never become an unbounded pass over every
272
+ pending row on every instance (DK-3). What it adds is the transition and the
273
+ `docket.expired` event; the state was already true.
274
+
275
+ A decision that arrives late is refused as expired, and the amendments it carried are
276
+ **preserved on the row** with the instant and principal of the act that carried them —
277
+ so `gate.resubmit` files a fresh entry that prefills what the person had already typed
278
+ rather than making them type it twice (DK-1).
279
+
280
+ ## What this package does not claim
281
+
282
+ - **It swears to the field, not to the database.** An Affidavit is a record of what an
283
+ agent proposed and where each value came from. It is not proof that your executor
284
+ wrote what was approved; that is what the execution outcome is for, and it is your
285
+ executor that reports it.
286
+ - **It does not sign and it does not hash-chain.** `canonicalize` and `canonicalHash`
287
+ give a deterministic byte sequence and a SHA-256 over the Affidavit and its accepted
288
+ amendments (SR-1), which is what an execution grant binds to. That is a fingerprint,
289
+ not a signature and not a tamper-evident chain: it detects a substituted Affidavit,
290
+ it does not prove who produced one, and a host that needs either builds it above the
291
+ gate.
292
+ - **A tool that writes inside its own body is outside the guarantee** (GT-6). The
293
+ public types make the gated path the only way a proposal reaches an executor, and a
294
+ write-capable tool the gate cannot intercept — no `execute`, provider-executed, a
295
+ hosted MCP server writing server-side — is refused at wire-up or filed `blocked`,
296
+ never silently allowed (CV-4). But a function that opens its own connection and writes
297
+ is a write no wire-up check can see. This is the honest boundary, and it is a boundary
298
+ rather than a rule an implementation can enforce.
299
+ - **The three confidence numbers are reported, never enforced.** `aggregateConfidence`
300
+ is the **minimum** over proposed fields with `Empty` counting as `0.0`;
301
+ `populatedConfidence` is the minimum over the fields that were filled;
302
+ `emptyFieldCount` is how many were not. All three are on every card, because a mean
303
+ that first discards the empty fields lets a mostly-empty Affidavit report high
304
+ confidence. Neither the rulebook nor this package defines a threshold on any of them
305
+ (AF-2): a floor is a policy, a policy is yours, and a framework that shipped one would
306
+ be deciding your risk appetite for you.
307
+
308
+ ## Runtimes
309
+
310
+ Node 22 or newer, Cloudflare workerd and Bun. There is no Node-only API here, no
311
+ filesystem, no timer and **Web Crypto only** — which is why `canonicalHash` is
312
+ asynchronous on every runtime, including the ones where a synchronous digest exists
313
+ (RT-1). The whole suite runs on all three in CI from the first commit, and a lint fails
314
+ the build if anything under `src/` can reach Durable Object storage (RT-3).
315
+
316
+ ESM only. Types are published under `strict` with `exactOptionalPropertyTypes` and
317
+ `noUncheckedIndexedAccess`.
318
+
319
+ ## Testing your host against the reference behaviour
320
+
321
+ `@affiant/core/testing` exports the fixture format, the runner and the stub ports the
322
+ fixtures are wired from. The documents under `test/fixtures/` are not tests of this
323
+ implementation — each is a statement about what a rule requires, written so a second
324
+ implementation in another language can be handed the same file and told to make it pass.
325
+
326
+ ```ts
327
+ import { runFixture, runFixtureDir, scriptedInference, fixedClock } from "@affiant/core/testing";
328
+
329
+ const result = await runFixture(myFixture);
330
+ // { id, rules, title, pass, failures: [{ at, expected, actual }] }
331
+ ```
332
+
333
+ Two ways a host uses this. Swap a stub for your own port — your real inference, your
334
+ real projection — and run the fixtures against it, and you find out whether your ports
335
+ behave the way the rules assume before you trust them in production. Or write your own
336
+ fixtures in the same shape for your own operations, and get the same reporting.
337
+ `runFixture` never throws on a mismatch; it returns every failure with the path it was
338
+ found at, which is what lets the same documents produce a parity report rather than a
339
+ first-failure message. See [`test/README.md`](test/README.md) for the format.
340
+
341
+ ## Links
342
+
343
+ - [Sakwala/affiant-protocol](https://github.com/Sakwala/affiant-protocol) — the rulebook:
344
+ wire schemas, the conformance fixtures, and
345
+ [`INVARIANTS.md`](https://github.com/Sakwala/affiant-protocol/blob/main/INVARIANTS.md),
346
+ the numbered rules cited throughout this file
347
+ - [`@affiant/contract`](../contract) — the wire types and the JSON Schemas
348
+ - [`@affiant/evidence-card`](../evidence-card) — the card a person reads
349
+ ([try it](https://sakwala.github.io/affiant-ts/))
350
+ - [Sakwala/affiant](https://github.com/Sakwala/affiant) — the .NET implementation
351
+
352
+ ## Licence
353
+
354
+ Apache-2.0. The full text ships in the package as `LICENSE`.