@agent-custody/state 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 +202 -0
- package/README.md +74 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/ledger.d.ts +82 -0
- package/dist/ledger.js +122 -0
- package/package.json +40 -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 [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# @agent-custody/state
|
|
2
|
+
|
|
3
|
+
Governed memory for AI agents. Not a vector store: a ledger of facts where every write cites the receipt that caused it, carries valid time and transaction time, and can be superseded or retracted without losing what the agent believed at any earlier moment.
|
|
4
|
+
|
|
5
|
+
Retrieval stays with whatever store you already use. This package owns provenance, time, and undo.
|
|
6
|
+
|
|
7
|
+
## Getting started
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @agent-custody/state # or bun add, pnpm add
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Not on npm yet: the `@agent-custody` scope is still to be claimed. Until then, build from a clone and install the tarball:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
bun install && bun run build # at the repository root
|
|
17
|
+
cd packages/state && bun pm pack # writes agent-custody-state-0.1.0.tgz here
|
|
18
|
+
npm install /path/to/agent-custody/packages/state/agent-custody-state-0.1.0.tgz # in your project
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { Ledger } from "@agent-custody/state";
|
|
23
|
+
|
|
24
|
+
const ledger = new Ledger("./state/ledger.jsonl");
|
|
25
|
+
const a = ledger.assert({ subject: "acct:42", predicate: "plan", value: "pro", space: "org", actor: "agent:support", source: { receiptId } });
|
|
26
|
+
ledger.assert({ subject: "acct:42", predicate: "plan", value: "enterprise", space: "org", actor: "agent:sales", supersedes: a.fact.factId });
|
|
27
|
+
ledger.retract({ factId: a.fact.factId, actor: "user:admin", reason: "poisoned by a tool result" });
|
|
28
|
+
ledger.asOf({ validAt: "2026-09-01T00:00:00Z", txAt: "2026-09-01T00:00:00Z" });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
[examples/01-ledger.ts](examples/01-ledger.ts) walks through a wrong write and its undo, step by step; run it with `node examples/01-ledger.ts` from this directory. The test suite runs it too.
|
|
32
|
+
|
|
33
|
+
## The ledger
|
|
34
|
+
|
|
35
|
+
`src/ledger.ts` is an append-only JSONL log of two kinds of event.
|
|
36
|
+
|
|
37
|
+
- **assert** creates a fact: subject, predicate, value, the space it lives in (a person, a team, an org), the actor that wrote it, the source receipt id if the write went through a receipts producer, and the valid-time interval. An assert may **supersede** an earlier fact, which ends that fact's validity where the new one begins.
|
|
38
|
+
- **retract** says a fact should never have been believed. This is the undo. The record stays, so queries about earlier moments still see the fact, and anything the retracted fact had superseded is believed again.
|
|
39
|
+
|
|
40
|
+
Two clocks, kept apart on purpose:
|
|
41
|
+
|
|
42
|
+
| | question it answers | set by |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| valid time | was this true in the world at T | the writer, defaults to now |
|
|
45
|
+
| transaction time | did the ledger know it at T | the ledger, never the writer |
|
|
46
|
+
|
|
47
|
+
`asOf({ validAt, txAt, space, subject, predicate })` returns the facts believed at a moment. Setting both times to the same instant answers "what did the agent believe on Tuesday", including beliefs later retracted. `history(factId)` returns every event that touched a fact.
|
|
48
|
+
|
|
49
|
+
The ledger refuses to supersede a fact that is unknown, already superseded, or retracted, and refuses a replacement whose validity starts before the fact it replaces.
|
|
50
|
+
|
|
51
|
+
## Layout
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
src/ledger.ts the fact record, the two event kinds, as-of queries, supersession, retraction, JSONL persistence
|
|
55
|
+
src/index.ts public surface
|
|
56
|
+
examples/ runnable walkthroughs, each ends with OK and is run by the test suite
|
|
57
|
+
test/ one test per question a platform owner asks after a memory incident
|
|
58
|
+
tsconfig.build.json emits dist/ for consumers; the repo itself runs the .ts directly
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Plan
|
|
62
|
+
|
|
63
|
+
**Done**
|
|
64
|
+
|
|
65
|
+
- Bitemporal fact ledger with supersession, retraction, as-of and history queries, persisted as JSONL.
|
|
66
|
+
|
|
67
|
+
**Next, in the order it pays off**
|
|
68
|
+
|
|
69
|
+
1. A memory MCP server exposing write, read, supersede, and forget as tools, run behind the receipts gateway so every call is receipted and policy-checked and the source receipt id is filled in by the gateway rather than the caller.
|
|
70
|
+
2. A consumed-facts field on receipts: the gateway records which fact ids a read returned, so later receipts in the session show what the agent relied on.
|
|
71
|
+
3. Blast radius: given a fact id, every downstream receipt and derived fact that cited it.
|
|
72
|
+
4. Trust tiers as Cedar policies over spaces and receipt provenance: a self-reported write cannot overwrite an org-space fact that was attested through the gateway.
|
|
73
|
+
5. Write-through adapters for existing memory stores, tested against the real packages.
|
|
74
|
+
6. Signed forget statements: a retention or deletion request produces a verifiable record of which facts were removed.
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/ledger.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Where a write came from. A receipt id means the write went through a receipts producer and can be verified there. */
|
|
2
|
+
export interface Source {
|
|
3
|
+
receiptId: string | null;
|
|
4
|
+
}
|
|
5
|
+
export interface Fact {
|
|
6
|
+
factId: string;
|
|
7
|
+
subject: string;
|
|
8
|
+
predicate: string;
|
|
9
|
+
value: unknown;
|
|
10
|
+
/** Which shared space the fact lives in: a person, a team, an org. ACLs attach here later. */
|
|
11
|
+
space: string;
|
|
12
|
+
/** Who wrote it: a user id, an agent id, a tool name. */
|
|
13
|
+
actor: string;
|
|
14
|
+
source: Source;
|
|
15
|
+
/** ISO timestamps. validTo is null while the fact is believed to still hold. */
|
|
16
|
+
validFrom: string;
|
|
17
|
+
validTo: string | null;
|
|
18
|
+
confidence: number | null;
|
|
19
|
+
}
|
|
20
|
+
/** An assert creates a fact version. If it supersedes an earlier fact, that fact's validity ends where this one begins. */
|
|
21
|
+
export interface AssertEvent {
|
|
22
|
+
eventId: string;
|
|
23
|
+
kind: "assert";
|
|
24
|
+
txTime: string;
|
|
25
|
+
fact: Fact;
|
|
26
|
+
supersedes: string | null;
|
|
27
|
+
}
|
|
28
|
+
/** A retract says the fact should never have been believed. It is the undo. The record stays; queries before txTime still see it. */
|
|
29
|
+
export interface RetractEvent {
|
|
30
|
+
eventId: string;
|
|
31
|
+
kind: "retract";
|
|
32
|
+
txTime: string;
|
|
33
|
+
factId: string;
|
|
34
|
+
actor: string;
|
|
35
|
+
reason: string;
|
|
36
|
+
source: Source;
|
|
37
|
+
}
|
|
38
|
+
export type LedgerEvent = AssertEvent | RetractEvent;
|
|
39
|
+
export interface AssertInput {
|
|
40
|
+
subject: string;
|
|
41
|
+
predicate: string;
|
|
42
|
+
value: unknown;
|
|
43
|
+
space: string;
|
|
44
|
+
actor: string;
|
|
45
|
+
source?: Source;
|
|
46
|
+
validFrom?: string;
|
|
47
|
+
confidence?: number;
|
|
48
|
+
supersedes?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface RetractInput {
|
|
51
|
+
factId: string;
|
|
52
|
+
actor: string;
|
|
53
|
+
reason: string;
|
|
54
|
+
source?: Source;
|
|
55
|
+
}
|
|
56
|
+
export interface AsOf {
|
|
57
|
+
/** Facts whose validity interval contains this instant. Default: now. */
|
|
58
|
+
validAt?: string;
|
|
59
|
+
/** Only events the ledger had recorded by this instant. Default: now. "What did the agent believe on Tuesday" sets both. */
|
|
60
|
+
txAt?: string;
|
|
61
|
+
space?: string;
|
|
62
|
+
subject?: string;
|
|
63
|
+
predicate?: string;
|
|
64
|
+
}
|
|
65
|
+
export declare class Ledger {
|
|
66
|
+
private readonly events;
|
|
67
|
+
private readonly file;
|
|
68
|
+
private readonly now;
|
|
69
|
+
constructor(file: string, opts?: {
|
|
70
|
+
now?: () => Date;
|
|
71
|
+
});
|
|
72
|
+
get size(): number;
|
|
73
|
+
assert(input: AssertInput): AssertEvent;
|
|
74
|
+
retract(input: RetractInput): RetractEvent;
|
|
75
|
+
/** The facts believed at a moment. Valid time answers "was it true then"; transaction time answers "did the ledger know it then". */
|
|
76
|
+
asOf(q?: AsOf): Fact[];
|
|
77
|
+
/** Every event that touched a fact, oldest first: its assert, the assert that superseded it, its retraction. */
|
|
78
|
+
history(factId: string): LedgerEvent[];
|
|
79
|
+
private factById;
|
|
80
|
+
private retractedAt;
|
|
81
|
+
private append;
|
|
82
|
+
}
|
package/dist/ledger.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// The fact ledger: an append-only JSONL log of events about what an agent believes.
|
|
2
|
+
// Bitemporal. Valid time is when a fact was true in the world; transaction time is when the ledger learned of it.
|
|
3
|
+
// Nothing is ever edited in place. Correcting a belief is a new event, so "what did the agent believe at T" is always answerable.
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
export class Ledger {
|
|
8
|
+
events = [];
|
|
9
|
+
file;
|
|
10
|
+
now;
|
|
11
|
+
constructor(file, opts = {}) {
|
|
12
|
+
this.file = file;
|
|
13
|
+
this.now = opts.now ?? (() => new Date());
|
|
14
|
+
if (existsSync(file)) {
|
|
15
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
16
|
+
if (line.trim())
|
|
17
|
+
this.events.push(JSON.parse(line));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
get size() {
|
|
25
|
+
return this.events.length;
|
|
26
|
+
}
|
|
27
|
+
assert(input) {
|
|
28
|
+
const txTime = this.now().toISOString();
|
|
29
|
+
const validFrom = input.validFrom ?? txTime;
|
|
30
|
+
if (input.supersedes !== undefined) {
|
|
31
|
+
const prior = this.factById(input.supersedes);
|
|
32
|
+
if (!prior)
|
|
33
|
+
throw new Error(`cannot supersede unknown fact ${input.supersedes}`);
|
|
34
|
+
if (prior.fact.validTo !== null)
|
|
35
|
+
throw new Error(`fact ${input.supersedes} is already superseded`);
|
|
36
|
+
if (this.retractedAt(input.supersedes))
|
|
37
|
+
throw new Error(`fact ${input.supersedes} is retracted`);
|
|
38
|
+
if (validFrom < prior.fact.validFrom)
|
|
39
|
+
throw new Error(`replacement cannot start before the fact it supersedes`);
|
|
40
|
+
}
|
|
41
|
+
const event = {
|
|
42
|
+
eventId: randomUUID(),
|
|
43
|
+
kind: "assert",
|
|
44
|
+
txTime,
|
|
45
|
+
fact: {
|
|
46
|
+
factId: randomUUID(),
|
|
47
|
+
subject: input.subject,
|
|
48
|
+
predicate: input.predicate,
|
|
49
|
+
value: input.value,
|
|
50
|
+
space: input.space,
|
|
51
|
+
actor: input.actor,
|
|
52
|
+
source: input.source ?? { receiptId: null },
|
|
53
|
+
validFrom,
|
|
54
|
+
validTo: null,
|
|
55
|
+
confidence: input.confidence ?? null,
|
|
56
|
+
},
|
|
57
|
+
supersedes: input.supersedes ?? null,
|
|
58
|
+
};
|
|
59
|
+
this.append(event);
|
|
60
|
+
return event;
|
|
61
|
+
}
|
|
62
|
+
retract(input) {
|
|
63
|
+
if (!this.factById(input.factId))
|
|
64
|
+
throw new Error(`cannot retract unknown fact ${input.factId}`);
|
|
65
|
+
if (this.retractedAt(input.factId))
|
|
66
|
+
throw new Error(`fact ${input.factId} is already retracted`);
|
|
67
|
+
const event = {
|
|
68
|
+
eventId: randomUUID(),
|
|
69
|
+
kind: "retract",
|
|
70
|
+
txTime: this.now().toISOString(),
|
|
71
|
+
factId: input.factId,
|
|
72
|
+
actor: input.actor,
|
|
73
|
+
reason: input.reason,
|
|
74
|
+
source: input.source ?? { receiptId: null },
|
|
75
|
+
};
|
|
76
|
+
this.append(event);
|
|
77
|
+
return event;
|
|
78
|
+
}
|
|
79
|
+
/** The facts believed at a moment. Valid time answers "was it true then"; transaction time answers "did the ledger know it then". */
|
|
80
|
+
asOf(q = {}) {
|
|
81
|
+
const validAt = q.validAt ?? this.now().toISOString();
|
|
82
|
+
const txAt = q.txAt ?? this.now().toISOString();
|
|
83
|
+
const known = this.events.filter((e) => e.txTime <= txAt);
|
|
84
|
+
const retracted = new Set(known.filter((e) => e.kind === "retract").map((e) => e.factId));
|
|
85
|
+
const facts = new Map();
|
|
86
|
+
for (const e of known) {
|
|
87
|
+
if (e.kind !== "assert")
|
|
88
|
+
continue;
|
|
89
|
+
facts.set(e.fact.factId, { ...e.fact });
|
|
90
|
+
if (e.supersedes && facts.has(e.supersedes) && !retracted.has(e.fact.factId)) {
|
|
91
|
+
facts.get(e.supersedes).validTo = e.fact.validFrom;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return [...facts.values()].filter((f) => !retracted.has(f.factId) &&
|
|
95
|
+
f.validFrom <= validAt &&
|
|
96
|
+
(f.validTo === null || validAt < f.validTo) &&
|
|
97
|
+
(q.space === undefined || f.space === q.space) &&
|
|
98
|
+
(q.subject === undefined || f.subject === q.subject) &&
|
|
99
|
+
(q.predicate === undefined || f.predicate === q.predicate));
|
|
100
|
+
}
|
|
101
|
+
/** Every event that touched a fact, oldest first: its assert, the assert that superseded it, its retraction. */
|
|
102
|
+
history(factId) {
|
|
103
|
+
return this.events.filter((e) => (e.kind === "assert" ? e.fact.factId === factId || e.supersedes === factId : e.factId === factId));
|
|
104
|
+
}
|
|
105
|
+
factById(factId) {
|
|
106
|
+
let found;
|
|
107
|
+
for (const e of this.events) {
|
|
108
|
+
if (e.kind === "assert" && e.fact.factId === factId)
|
|
109
|
+
found = { ...e, fact: { ...e.fact } };
|
|
110
|
+
else if (e.kind === "assert" && e.supersedes === factId && found && !this.retractedAt(e.fact.factId))
|
|
111
|
+
found.fact.validTo = e.fact.validFrom;
|
|
112
|
+
}
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
retractedAt(factId) {
|
|
116
|
+
return this.events.some((e) => e.kind === "retract" && e.factId === factId);
|
|
117
|
+
}
|
|
118
|
+
append(event) {
|
|
119
|
+
appendFileSync(this.file, JSON.stringify(event) + "\n");
|
|
120
|
+
this.events.push(event);
|
|
121
|
+
}
|
|
122
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agent-custody/state",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Governed memory for AI agents: a fact ledger with provenance, valid time, rollback, and lineage, built on @agent-custody/receipts",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ch4r10t33r/agent-custody.git",
|
|
9
|
+
"directory": "packages/state"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.build.json",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"test": "vitest run"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@agent-custody/receipts": "0.1.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^26.4.1",
|
|
37
|
+
"typescript": "^7.0.2",
|
|
38
|
+
"vitest": "^5.0.0"
|
|
39
|
+
}
|
|
40
|
+
}
|