@fgv/ts-agent-memory 5.1.0-36 → 5.1.0-39
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/.rush/temp/{f6a88bfdd66517ccb98c2c7ae1be6e6fe9e15d38.tar.log → b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log} +116 -2
- package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +4 -4
- package/.rush/temp/operation/build/all.log +4 -4
- package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
- package/.rush/temp/operation/build/state.json +1 -1
- package/.rush/temp/shrinkwrap-deps.json +222 -221
- package/config/jest.config.json +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/packlets/ingest/cycleGuard.js +111 -0
- package/dist/packlets/ingest/cycleGuard.js.map +1 -0
- package/dist/packlets/ingest/hostStages.js +6 -0
- package/dist/packlets/ingest/hostStages.js.map +1 -0
- package/dist/packlets/ingest/index.js +9 -0
- package/dist/packlets/ingest/index.js.map +1 -0
- package/dist/packlets/ingest/model.js +6 -0
- package/dist/packlets/ingest/model.js.map +1 -0
- package/dist/packlets/ingest/orchestrator.js +438 -0
- package/dist/packlets/ingest/orchestrator.js.map +1 -0
- package/dist/packlets/retrieve/index.js +1 -0
- package/dist/packlets/retrieve/index.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +172 -0
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -0
- package/dist/packlets/store/fileTreeMemoryStore.js +323 -41
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/tools/index.js +6 -0
- package/dist/packlets/tools/index.js.map +1 -0
- package/dist/packlets/tools/memoryTools.js +337 -0
- package/dist/packlets/tools/memoryTools.js.map +1 -0
- package/dist/packlets/types/identityCodec.js +115 -0
- package/dist/packlets/types/identityCodec.js.map +1 -1
- package/dist/packlets/types/index.js +1 -0
- package/dist/packlets/types/index.js.map +1 -1
- package/dist/packlets/types/temporal.js +85 -0
- package/dist/packlets/types/temporal.js.map +1 -0
- package/dist/packlets/types/writePolicy.js +96 -0
- package/dist/packlets/types/writePolicy.js.map +1 -1
- package/dist/test/unit/converters/antagonistRoundTrip.test.js +95 -0
- package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +273 -0
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
- package/dist/test/unit/ingest/cycleGuard.test.js +54 -0
- package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -0
- package/dist/test/unit/ingest/orchestrator.test.js +913 -0
- package/dist/test/unit/ingest/orchestrator.test.js.map +1 -0
- package/dist/test/unit/retrieve/temporalRetrievers.test.js +182 -0
- package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js +120 -0
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
- package/dist/test/unit/store/fileTreeMemoryStore.test.js +74 -7
- package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
- package/dist/test/unit/store/temporalStore.test.js +398 -0
- package/dist/test/unit/store/temporalStore.test.js.map +1 -0
- package/dist/test/unit/tools/memoryTools.test.js +572 -0
- package/dist/test/unit/tools/memoryTools.test.js.map +1 -0
- package/dist/test/unit/types/temporalCodec.test.js +203 -0
- package/dist/test/unit/types/temporalCodec.test.js.map +1 -0
- package/dist/test/unit/types/temporalPolicy.test.js +62 -0
- package/dist/test/unit/types/temporalPolicy.test.js.map +1 -0
- package/dist/ts-agent-memory.d.ts +1042 -10
- package/dist/tsdoc-metadata.json +1 -1
- package/etc/ts-agent-memory.api.md +284 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +2 -0
- package/lib/index.js.map +1 -1
- package/lib/packlets/ingest/cycleGuard.d.ts +41 -0
- package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -0
- package/lib/packlets/ingest/cycleGuard.js +115 -0
- package/lib/packlets/ingest/cycleGuard.js.map +1 -0
- package/lib/packlets/ingest/hostStages.d.ts +88 -0
- package/lib/packlets/ingest/hostStages.d.ts.map +1 -0
- package/lib/packlets/ingest/hostStages.js +7 -0
- package/lib/packlets/ingest/hostStages.js.map +1 -0
- package/lib/packlets/ingest/index.d.ts +5 -0
- package/lib/packlets/ingest/index.d.ts.map +1 -0
- package/lib/packlets/ingest/index.js +25 -0
- package/lib/packlets/ingest/index.js.map +1 -0
- package/lib/packlets/ingest/model.d.ts +177 -0
- package/lib/packlets/ingest/model.d.ts.map +1 -0
- package/lib/packlets/ingest/model.js +7 -0
- package/lib/packlets/ingest/model.js.map +1 -0
- package/lib/packlets/ingest/orchestrator.d.ts +206 -0
- package/lib/packlets/ingest/orchestrator.d.ts.map +1 -0
- package/lib/packlets/ingest/orchestrator.js +442 -0
- package/lib/packlets/ingest/orchestrator.js.map +1 -0
- package/lib/packlets/retrieve/index.d.ts +1 -0
- package/lib/packlets/retrieve/index.d.ts.map +1 -1
- package/lib/packlets/retrieve/index.js +1 -0
- package/lib/packlets/retrieve/index.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.d.ts +78 -0
- package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -0
- package/lib/packlets/retrieve/temporalRetrievers.js +178 -0
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -0
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +118 -9
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +322 -40
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/tools/index.d.ts +2 -0
- package/lib/packlets/tools/index.d.ts.map +1 -0
- package/lib/packlets/tools/index.js +22 -0
- package/lib/packlets/tools/index.js.map +1 -0
- package/lib/packlets/tools/memoryTools.d.ts +139 -0
- package/lib/packlets/tools/memoryTools.d.ts.map +1 -0
- package/lib/packlets/tools/memoryTools.js +341 -0
- package/lib/packlets/tools/memoryTools.js.map +1 -0
- package/lib/packlets/types/identityCodec.d.ts +86 -0
- package/lib/packlets/types/identityCodec.d.ts.map +1 -1
- package/lib/packlets/types/identityCodec.js +118 -1
- package/lib/packlets/types/identityCodec.js.map +1 -1
- package/lib/packlets/types/index.d.ts +1 -0
- package/lib/packlets/types/index.d.ts.map +1 -1
- package/lib/packlets/types/index.js +1 -0
- package/lib/packlets/types/index.js.map +1 -1
- package/lib/packlets/types/temporal.d.ts +40 -0
- package/lib/packlets/types/temporal.d.ts.map +1 -0
- package/lib/packlets/types/temporal.js +92 -0
- package/lib/packlets/types/temporal.js.map +1 -0
- package/lib/packlets/types/writePolicy.d.ts +49 -0
- package/lib/packlets/types/writePolicy.d.ts.map +1 -1
- package/lib/packlets/types/writePolicy.js +98 -1
- package/lib/packlets/types/writePolicy.js.map +1 -1
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +10 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +1 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.js +97 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +9 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +275 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
- package/lib/test/unit/ingest/cycleGuard.test.d.ts +2 -0
- package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/cycleGuard.test.js +56 -0
- package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -0
- package/lib/test/unit/ingest/orchestrator.test.d.ts +2 -0
- package/lib/test/unit/ingest/orchestrator.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/orchestrator.test.js +915 -0
- package/lib/test/unit/ingest/orchestrator.test.js.map +1 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +2 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +1 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.js +184 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +9 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +1 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js +122 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
- package/lib/test/unit/store/fileTreeMemoryStore.test.js +74 -7
- package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
- package/lib/test/unit/store/temporalStore.test.d.ts +2 -0
- package/lib/test/unit/store/temporalStore.test.d.ts.map +1 -0
- package/lib/test/unit/store/temporalStore.test.js +400 -0
- package/lib/test/unit/store/temporalStore.test.js.map +1 -0
- package/lib/test/unit/tools/memoryTools.test.d.ts +2 -0
- package/lib/test/unit/tools/memoryTools.test.d.ts.map +1 -0
- package/lib/test/unit/tools/memoryTools.test.js +574 -0
- package/lib/test/unit/tools/memoryTools.test.js.map +1 -0
- package/lib/test/unit/types/temporalCodec.test.d.ts +2 -0
- package/lib/test/unit/types/temporalCodec.test.d.ts.map +1 -0
- package/lib/test/unit/types/temporalCodec.test.js +205 -0
- package/lib/test/unit/types/temporalCodec.test.js.map +1 -0
- package/lib/test/unit/types/temporalPolicy.test.d.ts +2 -0
- package/lib/test/unit/types/temporalPolicy.test.d.ts.map +1 -0
- package/lib/test/unit/types/temporalPolicy.test.js +64 -0
- package/lib/test/unit/types/temporalPolicy.test.js.map +1 -0
- package/package.json +19 -19
- package/rush-logs/ts-agent-memory.build.cache.log +1 -1
- package/rush-logs/ts-agent-memory.build.log +4 -4
- package/src/index.ts +2 -0
- package/src/packlets/ingest/cycleGuard.ts +142 -0
- package/src/packlets/ingest/hostStages.ts +111 -0
- package/src/packlets/ingest/index.ts +9 -0
- package/src/packlets/ingest/model.ts +184 -0
- package/src/packlets/ingest/orchestrator.ts +797 -0
- package/src/packlets/retrieve/index.ts +1 -0
- package/src/packlets/retrieve/temporalRetrievers.ts +210 -0
- package/src/packlets/store/fileTreeMemoryStore.ts +460 -66
- package/src/packlets/tools/index.ts +6 -0
- package/src/packlets/tools/memoryTools.ts +579 -0
- package/src/packlets/types/identityCodec.ts +184 -0
- package/src/packlets/types/index.ts +1 -0
- package/src/packlets/types/temporal.ts +96 -0
- package/src/packlets/types/writePolicy.ts +127 -0
- package/src/test/unit/converters/antagonistRoundTrip.test.ts +110 -0
- package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +362 -0
- package/src/test/unit/ingest/cycleGuard.test.ts +68 -0
- package/src/test/unit/ingest/orchestrator.test.ts +1158 -0
- package/src/test/unit/retrieve/temporalRetrievers.test.ts +226 -0
- package/src/test/unit/store/antagonistTemporalBoundary.test.ts +158 -0
- package/src/test/unit/store/fileTreeMemoryStore.test.ts +98 -7
- package/src/test/unit/store/temporalStore.test.ts +469 -0
- package/src/test/unit/tools/memoryTools.test.ts +771 -0
- package/src/test/unit/types/temporalCodec.test.ts +259 -0
- package/src/test/unit/types/temporalPolicy.test.ts +96 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +122 -46
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/ts-agent-memory.api.json +11984 -6314
- package/temp/ts-agent-memory.api.md +284 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
import { captureResult, fail, succeed } from '@fgv/ts-utils';
|
|
6
|
+
import { JsonSchema } from '@fgv/ts-json-base';
|
|
7
|
+
import { Convert } from '../types';
|
|
8
|
+
import { envelopeConverter } from '../converters';
|
|
9
|
+
/**
|
|
10
|
+
* The default tool subset when {@link ICreateMemoryToolsParams.tools | tools} is
|
|
11
|
+
* omitted: the read-only set. Mutating tools (`memory_write` / `memory_delete`)
|
|
12
|
+
* are **off by default** and must be named explicitly — writes stay
|
|
13
|
+
* curation-mediated unless the host opts in.
|
|
14
|
+
* @public
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_MEMORY_TOOLS = ['memory_search', 'memory_context'];
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Parameter schemas — authored once via JsonSchema.object(...); the schema IS
|
|
19
|
+
// both the wire schema (.toJson()) and the runtime validator (.convert()).
|
|
20
|
+
// NONE of these declare a `scope` (or scope-widening) property — the adoption
|
|
21
|
+
// gate is enforced structurally and asserted in the tests.
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
/** A single attributed link edge as authored by the agent on a write. */
|
|
24
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
25
|
+
const linkEdgeSchema = JsonSchema.object({
|
|
26
|
+
type: JsonSchema.string({ description: 'The relation type of the link.' }),
|
|
27
|
+
target: JsonSchema.string({ description: 'The MemoryId this edge points at.' }),
|
|
28
|
+
confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))
|
|
29
|
+
});
|
|
30
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
31
|
+
const writeSchema = JsonSchema.object({
|
|
32
|
+
kind: JsonSchema.string({ description: 'The record kind (must be an enabled, registered kind).' }),
|
|
33
|
+
entityId: JsonSchema.string({
|
|
34
|
+
description: 'The domain entity id. For composite (e.g. medium-term) kinds this is the full composite key.'
|
|
35
|
+
}),
|
|
36
|
+
body: JsonSchema.string({ description: "The serialized record body; validated by the kind's converter." }),
|
|
37
|
+
tags: JsonSchema.optional(JsonSchema.array(JsonSchema.string({ description: 'A tag label.' }))),
|
|
38
|
+
links: JsonSchema.optional(JsonSchema.array(linkEdgeSchema))
|
|
39
|
+
});
|
|
40
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
41
|
+
const readSchema = JsonSchema.object({
|
|
42
|
+
kind: JsonSchema.string({ description: 'The record kind.' }),
|
|
43
|
+
entityId: JsonSchema.string({ description: 'The domain entity id to read.' })
|
|
44
|
+
});
|
|
45
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
46
|
+
const deleteSchema = JsonSchema.object({
|
|
47
|
+
kind: JsonSchema.string({ description: 'The record kind.' }),
|
|
48
|
+
entityId: JsonSchema.string({ description: 'The domain entity id to delete.' })
|
|
49
|
+
});
|
|
50
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
51
|
+
const searchSchema = JsonSchema.object({
|
|
52
|
+
kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),
|
|
53
|
+
tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),
|
|
54
|
+
semantic: JsonSchema.optional(JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })),
|
|
55
|
+
limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
|
|
56
|
+
});
|
|
57
|
+
// eslint-disable-next-line @rushstack/typedef-var
|
|
58
|
+
const contextSchema = JsonSchema.object({
|
|
59
|
+
from: JsonSchema.string({ description: 'The seed MemoryId to traverse links from.' }),
|
|
60
|
+
kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),
|
|
61
|
+
tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),
|
|
62
|
+
hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),
|
|
63
|
+
limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
|
|
64
|
+
});
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// Behavior annotations (Component 4) — host-advisory hints; never serialized to
|
|
67
|
+
// the model. openWorldHint is false throughout (a closed, local store).
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
const READ_ONLY_ANNOTATIONS = {
|
|
70
|
+
readOnlyHint: true,
|
|
71
|
+
openWorldHint: false
|
|
72
|
+
};
|
|
73
|
+
const WRITE_ANNOTATIONS = {
|
|
74
|
+
destructiveHint: false,
|
|
75
|
+
idempotentHint: false,
|
|
76
|
+
openWorldHint: false
|
|
77
|
+
};
|
|
78
|
+
const DELETE_ANNOTATIONS = {
|
|
79
|
+
destructiveHint: true,
|
|
80
|
+
idempotentHint: true,
|
|
81
|
+
openWorldHint: false
|
|
82
|
+
};
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Shared validation / projection helpers
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
/** Validate a `kind` string and assert it is an enabled, registered toolable kind. */
|
|
87
|
+
function assertKindEnabled(ctx, kindStr) {
|
|
88
|
+
return Convert.kind.convert(kindStr).onSuccess((kind) => {
|
|
89
|
+
if (!ctx.registry.has(kind)) {
|
|
90
|
+
return fail(`memory tools: kind '${kind}' has no registered body converter`);
|
|
91
|
+
}
|
|
92
|
+
if (ctx.kinds !== undefined && !ctx.kinds.includes(kind)) {
|
|
93
|
+
return fail(`memory tools: kind '${kind}' is not enabled for memory tools`);
|
|
94
|
+
}
|
|
95
|
+
return succeed(kind);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/** Validate an optional `kind` string (enabled when present; `undefined` passes through). */
|
|
99
|
+
function resolveOptionalKind(ctx, kindStr) {
|
|
100
|
+
if (kindStr === undefined) {
|
|
101
|
+
return succeed(undefined);
|
|
102
|
+
}
|
|
103
|
+
return assertKindEnabled(ctx, kindStr);
|
|
104
|
+
}
|
|
105
|
+
/** Project a record into an agent-visible result item, applying the host handle hook when present. */
|
|
106
|
+
function projectItem(ctx, record) {
|
|
107
|
+
// `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than
|
|
108
|
+
// escaping the Result chain (and crashing the whole search/context call).
|
|
109
|
+
const handle = ctx.handleFor !== undefined
|
|
110
|
+
? captureResult(() => ctx.handleFor(record)).orDefault(record.envelope.id)
|
|
111
|
+
: record.envelope.id;
|
|
112
|
+
return {
|
|
113
|
+
handle,
|
|
114
|
+
kind: record.envelope.kind,
|
|
115
|
+
entityId: record.envelope.entityId,
|
|
116
|
+
tags: record.envelope.tags,
|
|
117
|
+
body: record.body
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Resolve the identity codec used by `memory_write` to derive the storage id. */
|
|
121
|
+
function codecForWrite(ctx, kind) {
|
|
122
|
+
var _a, _b;
|
|
123
|
+
const codec = (_b = (_a = ctx.codecs) === null || _a === void 0 ? void 0 : _a.get(kind)) !== null && _b !== void 0 ? _b : ctx.defaultCodec;
|
|
124
|
+
if (codec === undefined) {
|
|
125
|
+
return fail(`memory_write: no identity codec available for kind '${kind}'`);
|
|
126
|
+
}
|
|
127
|
+
return succeed(codec);
|
|
128
|
+
}
|
|
129
|
+
/** Build the record to persist from validated write args (store stamps txn-time metadata). */
|
|
130
|
+
function buildWriteRecord(typed, kind, entityId, idStem) {
|
|
131
|
+
var _a, _b;
|
|
132
|
+
// Plain shapes handed to `envelopeConverter`, which validates each field
|
|
133
|
+
// (type → LinkType, target → MemoryId) and produces the branded IEdge[].
|
|
134
|
+
const links = ((_a = typed.links) !== null && _a !== void 0 ? _a : []).map((link) => (Object.assign({ type: link.type, target: link.target }, (link.confidence !== undefined ? { confidence: link.confidence } : {}))));
|
|
135
|
+
return envelopeConverter
|
|
136
|
+
.convert({
|
|
137
|
+
id: idStem,
|
|
138
|
+
entityId,
|
|
139
|
+
kind,
|
|
140
|
+
tags: (_b = typed.tags) !== null && _b !== void 0 ? _b : [],
|
|
141
|
+
links,
|
|
142
|
+
created: 0,
|
|
143
|
+
updated: 0,
|
|
144
|
+
seq: 0,
|
|
145
|
+
contentHash: '',
|
|
146
|
+
provenance: { source: 'agent' }
|
|
147
|
+
})
|
|
148
|
+
.withErrorFormat((msg) => `memory_write: invalid record: ${msg}`)
|
|
149
|
+
.onSuccess((envelope) => succeed({ envelope, body: typed.body }));
|
|
150
|
+
}
|
|
151
|
+
/** Resolve the validated write args into the storage id + record (all synchronous). */
|
|
152
|
+
function prepareWrite(ctx, typed) {
|
|
153
|
+
return assertKindEnabled(ctx, typed.kind).onSuccess((kind) => Convert.entityId.convert(typed.entityId).onSuccess((entityId) => codecForWrite(ctx, kind).onSuccess((codec) => codec.encode(entityId).onSuccess((addr) => {
|
|
154
|
+
if (addr.isVersioned) {
|
|
155
|
+
return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);
|
|
156
|
+
}
|
|
157
|
+
return buildWriteRecord(typed, kind, entityId, addr.idStem).onSuccess((record) => succeed({ kind, entityId, record }));
|
|
158
|
+
}))));
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Discriminate the write outcome from a pre-put snapshot and the returned record.
|
|
162
|
+
* A dedup no-op returns either a different entity (content-scope dedup) or the
|
|
163
|
+
* same-id record with an unchanged `seq` (entity-scope re-put); a fresh write or
|
|
164
|
+
* update advances `seq`.
|
|
165
|
+
*/
|
|
166
|
+
function writeOutcome(before, written, entityId) {
|
|
167
|
+
if (written.envelope.entityId !== entityId) {
|
|
168
|
+
return 'deduped';
|
|
169
|
+
}
|
|
170
|
+
if (before !== undefined && written.envelope.seq === before.envelope.seq) {
|
|
171
|
+
return 'deduped';
|
|
172
|
+
}
|
|
173
|
+
return 'written';
|
|
174
|
+
}
|
|
175
|
+
// ---------------------------------------------------------------------------
|
|
176
|
+
// Tool builders — config with a JsonSchema.object(...) parametersSchema; execute
|
|
177
|
+
// validates/narrows → delegates to store/retriever → returns the Result (never
|
|
178
|
+
// swallowed), following the ts-extras-mcp adapter shape.
|
|
179
|
+
//
|
|
180
|
+
// Each `execute` re-runs its own `parametersSchema.convert(args)` even though the
|
|
181
|
+
// `executeClientToolTurn` harness already validates against the same schema. This
|
|
182
|
+
// is deliberate: the factory returns a heterogeneous `ReadonlyArray<IAiClientTool>`
|
|
183
|
+
// (TParams erased to `unknown`, since the members carry different param shapes), so
|
|
184
|
+
// `execute` receives `unknown` and must narrow it back to the typed args. The
|
|
185
|
+
// re-validation is also the narrowing step exercised by the direct-call tests (which
|
|
186
|
+
// invoke `execute` with raw args, bypassing the harness). Re-validating an
|
|
187
|
+
// already-conforming shape is a cheap, side-effect-free identity.
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
function buildWriteTool(ctx) {
|
|
190
|
+
return {
|
|
191
|
+
config: {
|
|
192
|
+
type: 'client_tool',
|
|
193
|
+
name: 'memory_write',
|
|
194
|
+
description: 'Store a new memory record or update an existing one by (kind, entityId). ' +
|
|
195
|
+
'Identical content is a no-op that returns the existing record.',
|
|
196
|
+
parametersSchema: writeSchema,
|
|
197
|
+
annotations: WRITE_ANNOTATIONS
|
|
198
|
+
},
|
|
199
|
+
execute: async (args) => writeSchema
|
|
200
|
+
.convert(args)
|
|
201
|
+
.withErrorFormat((msg) => `memory_write: invalid arguments: ${msg}`)
|
|
202
|
+
.onSuccess((typed) => prepareWrite(ctx, typed))
|
|
203
|
+
.thenOnSuccess(async ({ kind, entityId, record }) =>
|
|
204
|
+
// Read the prior record to discriminate written-vs-deduped. A `Failure`
|
|
205
|
+
// here (corrupt file, I/O error, codec round-trip failure) is a real
|
|
206
|
+
// condition distinct from the "not found" success (`undefined`); propagate
|
|
207
|
+
// it rather than defaulting it away, so a genuine store fault surfaces
|
|
208
|
+
// instead of being masked as a normal write.
|
|
209
|
+
(await ctx.store.get(kind, entityId)).thenOnSuccess(async (before) => (await ctx.store.put(record)).onSuccess((persisted) => succeed({
|
|
210
|
+
outcome: writeOutcome(before, persisted, entityId),
|
|
211
|
+
id: persisted.envelope.id,
|
|
212
|
+
entityId,
|
|
213
|
+
kind
|
|
214
|
+
}))))
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function buildReadTool(ctx) {
|
|
218
|
+
return {
|
|
219
|
+
config: {
|
|
220
|
+
type: 'client_tool',
|
|
221
|
+
name: 'memory_read',
|
|
222
|
+
description: 'Read a specific memory record by (kind, entityId).',
|
|
223
|
+
parametersSchema: readSchema,
|
|
224
|
+
annotations: READ_ONLY_ANNOTATIONS
|
|
225
|
+
},
|
|
226
|
+
execute: async (args) => readSchema
|
|
227
|
+
.convert(args)
|
|
228
|
+
.withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)
|
|
229
|
+
.onSuccess((typed) => assertKindEnabled(ctx, typed.kind).onSuccess((kind) => Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))))
|
|
230
|
+
.thenOnSuccess(async ({ kind, entityId }) => (await ctx.store.get(kind, entityId)).onSuccess((record) => record === undefined
|
|
231
|
+
? succeed({ found: false })
|
|
232
|
+
: succeed({ found: true, item: projectItem(ctx, record) })))
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
function buildSearchTool(ctx) {
|
|
236
|
+
return {
|
|
237
|
+
config: {
|
|
238
|
+
type: 'client_tool',
|
|
239
|
+
name: 'memory_search',
|
|
240
|
+
description: 'Search memories by tag, kind, or semantic text. Returns ranked results.',
|
|
241
|
+
parametersSchema: searchSchema,
|
|
242
|
+
annotations: READ_ONLY_ANNOTATIONS
|
|
243
|
+
},
|
|
244
|
+
execute: async (args) => searchSchema
|
|
245
|
+
.convert(args)
|
|
246
|
+
.withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)
|
|
247
|
+
.onSuccess((typed) => resolveOptionalKind(ctx, typed.kind).onSuccess((kind) => resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))))
|
|
248
|
+
.thenOnSuccess(async ({ typed, kind, tag }) => {
|
|
249
|
+
const query = Object.assign(Object.assign(Object.assign(Object.assign({}, (kind !== undefined ? { kind } : {})), (tag !== undefined ? { tag } : {})), (typed.semantic !== undefined ? { semantic: typed.semantic } : {})), (typed.limit !== undefined ? { limit: typed.limit } : {}));
|
|
250
|
+
return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r)) }));
|
|
251
|
+
})
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
function buildContextTool(ctx) {
|
|
255
|
+
return {
|
|
256
|
+
config: {
|
|
257
|
+
type: 'client_tool',
|
|
258
|
+
name: 'memory_context',
|
|
259
|
+
description: 'Build a context graph from a seed memory: returns the records linked from the seed, up to `hops` hops.',
|
|
260
|
+
parametersSchema: contextSchema,
|
|
261
|
+
annotations: READ_ONLY_ANNOTATIONS
|
|
262
|
+
},
|
|
263
|
+
execute: async (args) => contextSchema
|
|
264
|
+
.convert(args)
|
|
265
|
+
.withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)
|
|
266
|
+
.onSuccess((typed) => Convert.memoryId
|
|
267
|
+
.convert(typed.from)
|
|
268
|
+
.onSuccess((from) => resolveOptionalKind(ctx, typed.kind).onSuccess((kind) => resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag })))))
|
|
269
|
+
.thenOnSuccess(async ({ typed, from, kind, tag }) => {
|
|
270
|
+
const query = Object.assign(Object.assign(Object.assign(Object.assign({ linkedFrom: from }, (kind !== undefined ? { kind } : {})), (tag !== undefined ? { tag } : {})), (typed.hops !== undefined ? { hops: typed.hops } : {})), (typed.limit !== undefined ? { limit: typed.limit } : {}));
|
|
271
|
+
return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({ seed: from, count: records.length, results: records.map((r) => projectItem(ctx, r)) }));
|
|
272
|
+
})
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function buildDeleteTool(ctx) {
|
|
276
|
+
return {
|
|
277
|
+
config: {
|
|
278
|
+
type: 'client_tool',
|
|
279
|
+
name: 'memory_delete',
|
|
280
|
+
description: 'Delete a memory record by (kind, entityId). Destructive for non-temporal kinds.',
|
|
281
|
+
parametersSchema: deleteSchema,
|
|
282
|
+
annotations: DELETE_ANNOTATIONS
|
|
283
|
+
},
|
|
284
|
+
execute: async (args) => deleteSchema
|
|
285
|
+
.convert(args)
|
|
286
|
+
.withErrorFormat((msg) => `memory_delete: invalid arguments: ${msg}`)
|
|
287
|
+
.onSuccess((typed) => assertKindEnabled(ctx, typed.kind).onSuccess((kind) => Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))))
|
|
288
|
+
.thenOnSuccess(async ({ kind, entityId }) => (await ctx.store.delete(kind, entityId)).onSuccess((id) => succeed({ deleted: true, id, entityId, kind })))
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** Validate an optional `tag` string (`undefined` passes through). */
|
|
292
|
+
function resolveOptionalTag(tagStr) {
|
|
293
|
+
if (tagStr === undefined) {
|
|
294
|
+
return succeed(undefined);
|
|
295
|
+
}
|
|
296
|
+
return Convert.tag.convert(tagStr);
|
|
297
|
+
}
|
|
298
|
+
/** Ordered registry of the five tool builders, keyed by name. */
|
|
299
|
+
const TOOL_BUILDERS = [
|
|
300
|
+
{ name: 'memory_write', build: buildWriteTool },
|
|
301
|
+
{ name: 'memory_read', build: buildReadTool },
|
|
302
|
+
{ name: 'memory_search', build: buildSearchTool },
|
|
303
|
+
{ name: 'memory_context', build: buildContextTool },
|
|
304
|
+
{ name: 'memory_delete', build: buildDeleteTool }
|
|
305
|
+
];
|
|
306
|
+
/**
|
|
307
|
+
* Build the selected suite of memory `AiAssist.IAiClientTool`s over a
|
|
308
|
+
* pre-scoped store — ready to hand to `AiAssist.executeClientToolTurn` (and, via
|
|
309
|
+
* the shared `JsonSchema.object(...)` schemas, `@fgv/ts-extras-mcp`).
|
|
310
|
+
*
|
|
311
|
+
* @remarks
|
|
312
|
+
* **Scope isolation is make-or-break.** The returned tools close over the
|
|
313
|
+
* pre-scoped {@link ICreateMemoryToolsParams.store | store}; no tool's
|
|
314
|
+
* `parametersSchema` declares a `scope` (or any scope-widening) property, so an
|
|
315
|
+
* LLM cannot steer a tool at another actor's memory. The store instance is the
|
|
316
|
+
* sole scope authority.
|
|
317
|
+
*
|
|
318
|
+
* The default selection is {@link DEFAULT_MEMORY_TOOLS} (the read-only set) —
|
|
319
|
+
* `memory_write` / `memory_delete` are included only when named in
|
|
320
|
+
* {@link ICreateMemoryToolsParams.tools | tools}.
|
|
321
|
+
* @public
|
|
322
|
+
*/
|
|
323
|
+
export function createMemoryTools(params) {
|
|
324
|
+
var _a;
|
|
325
|
+
const ctx = {
|
|
326
|
+
store: params.store,
|
|
327
|
+
retriever: params.retriever,
|
|
328
|
+
registry: params.registry,
|
|
329
|
+
kinds: params.kinds,
|
|
330
|
+
codecs: params.codecs,
|
|
331
|
+
defaultCodec: params.defaultCodec,
|
|
332
|
+
handleFor: params.handleFor
|
|
333
|
+
};
|
|
334
|
+
const selected = new Set((_a = params.tools) !== null && _a !== void 0 ? _a : DEFAULT_MEMORY_TOOLS);
|
|
335
|
+
return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));
|
|
336
|
+
}
|
|
337
|
+
//# sourceMappingURL=memoryTools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memoryTools.js","sourceRoot":"","sources":["../../../src/packlets/tools/memoryTools.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,OAAO,EAAgE,MAAM,UAAU,CAAC;AACjG,OAAO,EAA0B,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAgB1E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAkC,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAsHvG,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2DAA2D;AAC3D,8EAA8E;AAE9E,yEAAyE;AACzE,kDAAkD;AAClD,MAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC;IACvC,IAAI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C,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5G,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport { JsonSchema } from '@fgv/ts-json-base';\nimport { AiAssist } from '@fgv/ts-extras';\nimport { Convert, EntityId, IIdentityCodec, IMemoryRecord, Kind, MemoryId, Tag } from '../types';\nimport { IBodyConverterRegistry, envelopeConverter } from '../converters';\nimport { IMemoryStore } from '../store';\nimport { IMemoryQuery, IMemoryRetriever } from '../retrieve';\n\n/**\n * The names of the five proof-set memory tools. A caller selects a subset via\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport type MemoryToolName =\n | 'memory_write'\n | 'memory_read'\n | 'memory_search'\n | 'memory_context'\n | 'memory_delete';\n\n/**\n * The default tool subset when {@link ICreateMemoryToolsParams.tools | tools} is\n * omitted: the read-only set. Mutating tools (`memory_write` / `memory_delete`)\n * are **off by default** and must be named explicitly — writes stay\n * curation-mediated unless the host opts in.\n * @public\n */\nexport const DEFAULT_MEMORY_TOOLS: ReadonlyArray<MemoryToolName> = ['memory_search', 'memory_context'];\n\n/**\n * Discriminates the outcome of a {@link createMemoryTools | memory_write} call so\n * the agent can reason about what its write actually did.\n *\n * @remarks\n * - `written` — a new record was persisted, or an existing entity was updated.\n * - `deduped` — the content already existed (content-hash dedup no-op); the\n * store returned the existing record unchanged.\n *\n * The store's public `put` return does not surface cap-cull evictions, so a\n * `culled` outcome is not distinguishable at this layer without an L1 change or\n * observer wiring (both out of scope for L2). The writer's own record is always\n * `written` even when the write triggers a cull of older siblings.\n * @public\n */\nexport type MemoryWriteOutcome = 'written' | 'deduped';\n\n/**\n * The success value returned by `memory_write.execute`.\n * @public\n */\nexport interface IMemoryWriteResult {\n /** What the write did — see {@link MemoryWriteOutcome}. */\n readonly outcome: MemoryWriteOutcome;\n /** The stored record's {@link MemoryId}. */\n readonly id: MemoryId;\n /** The domain {@link EntityId} the write targeted. */\n readonly entityId: EntityId;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n}\n\n/**\n * A single agent-visible search / context result item. The agent-facing key is\n * {@link IMemoryToolResultItem.handle | handle}: the host mnemonic when a\n * {@link ICreateMemoryToolsParams.handleFor | handleFor} hook is supplied, else\n * the raw {@link MemoryId}.\n * @public\n */\nexport interface IMemoryToolResultItem {\n /** The agent-visible key (host handle when supplied, raw {@link MemoryId} otherwise). */\n readonly handle: string;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n /** The record's domain {@link EntityId}. */\n readonly entityId: EntityId;\n /** The record's tags. */\n readonly tags: ReadonlyArray<string>;\n /** The record body (a markdown string in B1). */\n readonly body: unknown;\n}\n\n/**\n * Parameters for {@link createMemoryTools}.\n *\n * @remarks\n * **Scope isolation is constructor-fixed.** The {@link\n * ICreateMemoryToolsParams.store | store} is the sole scope authority — it is the\n * actor's own, pre-scoped memory root. No tool's `parametersSchema` declares a\n * `scope` (or any scope-widening) property, so an LLM cannot steer a tool at\n * another actor's memory.\n * @public\n */\nexport interface ICreateMemoryToolsParams {\n /**\n * The pre-scoped memory store (the actor's own memory root). Sole scope\n * authority — backs `memory_write` / `memory_read` / `memory_delete`.\n */\n readonly store: IMemoryStore;\n /** Retriever backing `memory_search` (and `memory_context` via link traversal). */\n readonly retriever: IMemoryRetriever;\n /** Body converter registry — gates the toolable kinds via `has(kind)`. */\n readonly registry: IBodyConverterRegistry;\n /**\n * The per-tool enable subset. Defaults to {@link DEFAULT_MEMORY_TOOLS} (the\n * read-only set). Name `memory_write` / `memory_delete` here to opt into the\n * mutating tools.\n */\n readonly tools?: ReadonlyArray<MemoryToolName>;\n /**\n * Optional whitelist of toolable kinds. When present, a tool `kind` argument\n * outside this set is rejected. When absent, {@link\n * IBodyConverterRegistry.has | registry.has} is the sole kind gate.\n */\n readonly kinds?: ReadonlyArray<Kind>;\n /**\n * Per-kind identity codecs, used by `memory_write` to map the domain\n * {@link EntityId} to the record's storage id (the store resolves codecs\n * internally for `get` / `delete`, so read / delete do not need them). Absent\n * → `memory_write` uses {@link ICreateMemoryToolsParams.defaultCodec |\n * defaultCodec}, and fails loudly for a kind with no resolvable codec. The\n * read-only default tool set needs no codecs.\n */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default identity codec for kinds without an explicit {@link ICreateMemoryToolsParams.codecs | codecs} entry. */\n readonly defaultCodec?: IIdentityCodec;\n /**\n * Optional host hook mapping a record to its agent-visible handle (an evocative\n * mnemonic tag). When supplied, `memory_search` / `memory_context` results use\n * the returned handle as the agent-visible key; when absent the raw\n * {@link MemoryId} is used.\n */\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n}\n\n/** The resolved factory context threaded into each tool's `execute`. */\ninterface IToolContext {\n readonly store: IMemoryStore;\n readonly retriever: IMemoryRetriever;\n readonly registry: IBodyConverterRegistry;\n readonly kinds?: ReadonlyArray<Kind>;\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n readonly defaultCodec?: IIdentityCodec;\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n}\n\n// ---------------------------------------------------------------------------\n// Parameter schemas — authored once via JsonSchema.object(...); the schema IS\n// both the wire schema (.toJson()) and the runtime validator (.convert()).\n// NONE of these declare a `scope` (or scope-widening) property — the adoption\n// gate is enforced structurally and asserted in the tests.\n// ---------------------------------------------------------------------------\n\n/** A single attributed link edge as authored by the agent on a write. */\n// eslint-disable-next-line @rushstack/typedef-var\nconst linkEdgeSchema = JsonSchema.object({\n type: JsonSchema.string({ description: 'The relation type of the link.' }),\n target: JsonSchema.string({ description: 'The MemoryId this edge points at.' }),\n confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst writeSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind (must be an enabled, registered kind).' }),\n entityId: JsonSchema.string({\n description:\n 'The domain entity id. For composite (e.g. medium-term) kinds this is the full composite key.'\n }),\n body: JsonSchema.string({ description: \"The serialized record body; validated by the kind's converter.\" }),\n tags: JsonSchema.optional(JsonSchema.array(JsonSchema.string({ description: 'A tag label.' }))),\n links: JsonSchema.optional(JsonSchema.array(linkEdgeSchema))\n});\ntype WriteArgs = JsonSchema.Static<typeof writeSchema>;\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst readSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to read.' })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst deleteSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to delete.' })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst searchSchema = JsonSchema.object({\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),\n semantic: JsonSchema.optional(\n JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })\n ),\n limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSchema = JsonSchema.object({\n from: JsonSchema.string({ description: 'The seed MemoryId to traverse links from.' }),\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),\n hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),\n limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))\n});\n\n// ---------------------------------------------------------------------------\n// Behavior annotations (Component 4) — host-advisory hints; never serialized to\n// the model. openWorldHint is false throughout (a closed, local store).\n// ---------------------------------------------------------------------------\n\nconst READ_ONLY_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n readOnlyHint: true,\n openWorldHint: false\n};\n\nconst WRITE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false\n};\n\nconst DELETE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false\n};\n\n// ---------------------------------------------------------------------------\n// Shared validation / projection helpers\n// ---------------------------------------------------------------------------\n\n/** Validate a `kind` string and assert it is an enabled, registered toolable kind. */\nfunction assertKindEnabled(ctx: IToolContext, kindStr: string): Result<Kind> {\n return Convert.kind.convert(kindStr).onSuccess((kind) => {\n if (!ctx.registry.has(kind)) {\n return fail(`memory tools: kind '${kind}' has no registered body converter`);\n }\n if (ctx.kinds !== undefined && !ctx.kinds.includes(kind)) {\n return fail(`memory tools: kind '${kind}' is not enabled for memory tools`);\n }\n return succeed(kind);\n });\n}\n\n/** Validate an optional `kind` string (enabled when present; `undefined` passes through). */\nfunction resolveOptionalKind(ctx: IToolContext, kindStr?: string): Result<Kind | undefined> {\n if (kindStr === undefined) {\n return succeed(undefined);\n }\n return assertKindEnabled(ctx, kindStr);\n}\n\n/** Project a record into an agent-visible result item, applying the host handle hook when present. */\nfunction projectItem(ctx: IToolContext, record: IMemoryRecord<unknown>): IMemoryToolResultItem {\n // `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than\n // escaping the Result chain (and crashing the whole search/context call).\n const handle =\n ctx.handleFor !== undefined\n ? captureResult(() => ctx.handleFor!(record)).orDefault(record.envelope.id)\n : record.envelope.id;\n return {\n handle,\n kind: record.envelope.kind,\n entityId: record.envelope.entityId,\n tags: record.envelope.tags,\n body: record.body\n };\n}\n\n/** Resolve the identity codec used by `memory_write` to derive the storage id. */\nfunction codecForWrite(ctx: IToolContext, kind: Kind): Result<IIdentityCodec> {\n const codec: IIdentityCodec | undefined = ctx.codecs?.get(kind) ?? ctx.defaultCodec;\n if (codec === undefined) {\n return fail(`memory_write: no identity codec available for kind '${kind}'`);\n }\n return succeed(codec);\n}\n\n/** Build the record to persist from validated write args (store stamps txn-time metadata). */\nfunction buildWriteRecord(\n typed: WriteArgs,\n kind: Kind,\n entityId: EntityId,\n idStem: string\n): Result<IMemoryRecord<unknown>> {\n // Plain shapes handed to `envelopeConverter`, which validates each field\n // (type → LinkType, target → MemoryId) and produces the branded IEdge[].\n const links: ReadonlyArray<Record<string, unknown>> = (typed.links ?? []).map((link) => ({\n type: link.type,\n target: link.target,\n ...(link.confidence !== undefined ? { confidence: link.confidence } : {})\n }));\n return envelopeConverter\n .convert({\n id: idStem,\n entityId,\n kind,\n tags: typed.tags ?? [],\n links,\n created: 0,\n updated: 0,\n seq: 0,\n contentHash: '',\n provenance: { source: 'agent' }\n })\n .withErrorFormat((msg) => `memory_write: invalid record: ${msg}`)\n .onSuccess((envelope) => succeed({ envelope, body: typed.body }));\n}\n\n/** Resolve the validated write args into the storage id + record (all synchronous). */\nfunction prepareWrite(\n ctx: IToolContext,\n typed: WriteArgs\n): Result<{ readonly kind: Kind; readonly entityId: EntityId; readonly record: IMemoryRecord<unknown> }> {\n return assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) =>\n codecForWrite(ctx, kind).onSuccess((codec) =>\n codec.encode(entityId).onSuccess((addr) => {\n if (addr.isVersioned) {\n return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);\n }\n return buildWriteRecord(typed, kind, entityId, addr.idStem).onSuccess((record) =>\n succeed({ kind, entityId, record })\n );\n })\n )\n )\n );\n}\n\n/**\n * Discriminate the write outcome from a pre-put snapshot and the returned record.\n * A dedup no-op returns either a different entity (content-scope dedup) or the\n * same-id record with an unchanged `seq` (entity-scope re-put); a fresh write or\n * update advances `seq`.\n */\nfunction writeOutcome(\n before: IMemoryRecord<unknown> | undefined,\n written: IMemoryRecord<unknown>,\n entityId: EntityId\n): MemoryWriteOutcome {\n if (written.envelope.entityId !== entityId) {\n return 'deduped';\n }\n if (before !== undefined && written.envelope.seq === before.envelope.seq) {\n return 'deduped';\n }\n return 'written';\n}\n\n// ---------------------------------------------------------------------------\n// Tool builders — config with a JsonSchema.object(...) parametersSchema; execute\n// validates/narrows → delegates to store/retriever → returns the Result (never\n// swallowed), following the ts-extras-mcp adapter shape.\n//\n// Each `execute` re-runs its own `parametersSchema.convert(args)` even though the\n// `executeClientToolTurn` harness already validates against the same schema. This\n// is deliberate: the factory returns a heterogeneous `ReadonlyArray<IAiClientTool>`\n// (TParams erased to `unknown`, since the members carry different param shapes), so\n// `execute` receives `unknown` and must narrow it back to the typed args. The\n// re-validation is also the narrowing step exercised by the direct-call tests (which\n// invoke `execute` with raw args, bypassing the harness). Re-validating an\n// already-conforming shape is a cheap, side-effect-free identity.\n// ---------------------------------------------------------------------------\n\nfunction buildWriteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_write',\n description:\n 'Store a new memory record or update an existing one by (kind, entityId). ' +\n 'Identical content is a no-op that returns the existing record.',\n parametersSchema: writeSchema,\n annotations: WRITE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n writeSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_write: invalid arguments: ${msg}`)\n .onSuccess((typed) => prepareWrite(ctx, typed))\n .thenOnSuccess(async ({ kind, entityId, record }) =>\n // Read the prior record to discriminate written-vs-deduped. A `Failure`\n // here (corrupt file, I/O error, codec round-trip failure) is a real\n // condition distinct from the \"not found\" success (`undefined`); propagate\n // it rather than defaulting it away, so a genuine store fault surfaces\n // instead of being masked as a normal write.\n (await ctx.store.get(kind, entityId)).thenOnSuccess(async (before) =>\n (await ctx.store.put(record)).onSuccess((persisted) =>\n succeed<IMemoryWriteResult>({\n outcome: writeOutcome(before, persisted, entityId),\n id: persisted.envelope.id,\n entityId,\n kind\n })\n )\n )\n )\n };\n}\n\nfunction buildReadTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_read',\n description: 'Read a specific memory record by (kind, entityId).',\n parametersSchema: readSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n readSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))\n )\n )\n .thenOnSuccess(async ({ kind, entityId }) =>\n (await ctx.store.get(kind, entityId)).onSuccess((record) =>\n record === undefined\n ? succeed({ found: false })\n : succeed({ found: true, item: projectItem(ctx, record) })\n )\n )\n };\n}\n\nfunction buildSearchTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_search',\n description: 'Search memories by tag, kind, or semantic text. Returns ranked results.',\n parametersSchema: searchSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n searchSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))\n )\n )\n .thenOnSuccess(async ({ typed, kind, tag }) => {\n const query: IMemoryQuery = {\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.semantic !== undefined ? { semantic: typed.semantic } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r)) })\n );\n })\n };\n}\n\nfunction buildContextTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_context',\n description:\n 'Build a context graph from a seed memory: returns the records linked from the seed, up to `hops` hops.',\n parametersSchema: contextSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n contextSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n Convert.memoryId\n .convert(typed.from)\n .onSuccess((from) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag }))\n )\n )\n )\n .thenOnSuccess(async ({ typed, from, kind, tag }) => {\n const query: IMemoryQuery = {\n linkedFrom: from,\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.hops !== undefined ? { hops: typed.hops } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({ seed: from, count: records.length, results: records.map((r) => projectItem(ctx, r)) })\n );\n })\n };\n}\n\nfunction buildDeleteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_delete',\n description: 'Delete a memory record by (kind, entityId). Destructive for non-temporal kinds.',\n parametersSchema: deleteSchema,\n annotations: DELETE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n deleteSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_delete: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))\n )\n )\n .thenOnSuccess(async ({ kind, entityId }) =>\n (await ctx.store.delete(kind, entityId)).onSuccess((id) =>\n succeed({ deleted: true, id, entityId, kind })\n )\n )\n };\n}\n\n/** Validate an optional `tag` string (`undefined` passes through). */\nfunction resolveOptionalTag(tagStr?: string): Result<Tag | undefined> {\n if (tagStr === undefined) {\n return succeed(undefined);\n }\n return Convert.tag.convert(tagStr);\n}\n\n/** Ordered registry of the five tool builders, keyed by name. */\nconst TOOL_BUILDERS: ReadonlyArray<{\n readonly name: MemoryToolName;\n readonly build: (ctx: IToolContext) => AiAssist.IAiClientTool;\n}> = [\n { name: 'memory_write', build: buildWriteTool },\n { name: 'memory_read', build: buildReadTool },\n { name: 'memory_search', build: buildSearchTool },\n { name: 'memory_context', build: buildContextTool },\n { name: 'memory_delete', build: buildDeleteTool }\n];\n\n/**\n * Build the selected suite of memory `AiAssist.IAiClientTool`s over a\n * pre-scoped store — ready to hand to `AiAssist.executeClientToolTurn` (and, via\n * the shared `JsonSchema.object(...)` schemas, `@fgv/ts-extras-mcp`).\n *\n * @remarks\n * **Scope isolation is make-or-break.** The returned tools close over the\n * pre-scoped {@link ICreateMemoryToolsParams.store | store}; no tool's\n * `parametersSchema` declares a `scope` (or any scope-widening) property, so an\n * LLM cannot steer a tool at another actor's memory. The store instance is the\n * sole scope authority.\n *\n * The default selection is {@link DEFAULT_MEMORY_TOOLS} (the read-only set) —\n * `memory_write` / `memory_delete` are included only when named in\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport function createMemoryTools(params: ICreateMemoryToolsParams): ReadonlyArray<AiAssist.IAiClientTool> {\n const ctx: IToolContext = {\n store: params.store,\n retriever: params.retriever,\n registry: params.registry,\n kinds: params.kinds,\n codecs: params.codecs,\n defaultCodec: params.defaultCodec,\n handleFor: params.handleFor\n };\n const selected: ReadonlySet<MemoryToolName> = new Set<MemoryToolName>(params.tools ?? DEFAULT_MEMORY_TOOLS);\n return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));\n}\n"]}
|
|
@@ -6,6 +6,121 @@ import { fail, succeed } from '@fgv/ts-utils';
|
|
|
6
6
|
import { Convert } from './ids';
|
|
7
7
|
import { assertPortableFilenameStem } from './filenameSafety';
|
|
8
8
|
/**
|
|
9
|
+
* Narrow an {@link IIdentityCodec} to {@link ITemporalIdentityCodec} by probing
|
|
10
|
+
* for the versioned methods. Used by the store when an `encode` result reports
|
|
11
|
+
* `isVersioned: true`.
|
|
12
|
+
* @public
|
|
13
|
+
*/
|
|
14
|
+
export function isTemporalIdentityCodec(codec) {
|
|
15
|
+
const candidate = codec;
|
|
16
|
+
return typeof candidate.encodeVersion === 'function' && typeof candidate.decodeVersion === 'function';
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Identity codec for a versioned (temporal) kind family, resolving OQ-11 to the
|
|
20
|
+
* subtree-per-entity layout: every version of an entity is a distinct file under
|
|
21
|
+
* a per-entity subtree.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* - `encode`: scope = `<baseScope>/entities/<entityId>`, idStem = `<entityId>`,
|
|
25
|
+
* `isVersioned = true`. The idStem is the stable entity prefix; the store forms
|
|
26
|
+
* each version's filename via {@link TemporalIdentityCodec.encodeVersion}.
|
|
27
|
+
* - `encodeVersion`: version stem = `<entityId>-v<seq>`.
|
|
28
|
+
* - `decode` / `decodeVersion`: recover `entityId` (and `seq`) from a
|
|
29
|
+
* `(subtree scope, version stem)` pair; the scope is authoritative for the
|
|
30
|
+
* `entityId`.
|
|
31
|
+
* - Escaping: `baseScope` and `entityId` must each match the POSIX portable
|
|
32
|
+
* filename set (they become path segments); `seq` is a non-negative integer.
|
|
33
|
+
* - Layout: `vault/<baseScope>/entities/<entityId>/<entityId>-v<seq>.md`.
|
|
34
|
+
* @public
|
|
35
|
+
*/
|
|
36
|
+
export class TemporalIdentityCodec {
|
|
37
|
+
constructor(baseScope) {
|
|
38
|
+
this.baseScope = baseScope;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Family-convention factory. Validates that `baseScope` is a single portable
|
|
42
|
+
* filename segment (it becomes the top-level path component).
|
|
43
|
+
*/
|
|
44
|
+
static create(baseScope) {
|
|
45
|
+
return assertPortableFilenameStem(baseScope)
|
|
46
|
+
.withErrorFormat((msg) => `temporal codec: baseScope '${baseScope}': ${msg}`)
|
|
47
|
+
.onSuccess(() => succeed(new TemporalIdentityCodec(baseScope)));
|
|
48
|
+
}
|
|
49
|
+
/** {@inheritDoc IIdentityCodec.encode} */
|
|
50
|
+
encode(entityId) {
|
|
51
|
+
return assertPortableFilenameStem(entityId)
|
|
52
|
+
.withErrorFormat((msg) => `temporal codec: entityId '${entityId}': ${msg}`)
|
|
53
|
+
.onSuccess((stem) => succeed({
|
|
54
|
+
scope: `${this.baseScope}/${TemporalIdentityCodec.entitiesSegment}/${stem}`,
|
|
55
|
+
idStem: stem,
|
|
56
|
+
isVersioned: true
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
/** {@inheritDoc ITemporalIdentityCodec.encodeVersion} */
|
|
60
|
+
encodeVersion(entityId, seq) {
|
|
61
|
+
return assertPortableFilenameStem(entityId)
|
|
62
|
+
.withErrorFormat((msg) => `temporal codec: entityId '${entityId}': ${msg}`)
|
|
63
|
+
.onSuccess((stem) => {
|
|
64
|
+
if (!Number.isInteger(seq) || seq < 0) {
|
|
65
|
+
return fail(`temporal codec: version seq '${seq}' must be a non-negative integer`);
|
|
66
|
+
}
|
|
67
|
+
return succeed(`${stem}${TemporalIdentityCodec.versionInfix}${seq}`);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** {@inheritDoc IIdentityCodec.decode} */
|
|
71
|
+
decode(scope, encodedStem) {
|
|
72
|
+
return this.decodeVersion(scope, encodedStem).onSuccess((addr) => Convert.entityId.convert(addr.entityId));
|
|
73
|
+
}
|
|
74
|
+
/** {@inheritDoc ITemporalIdentityCodec.decodeVersion} */
|
|
75
|
+
decodeVersion(scope, stem) {
|
|
76
|
+
return this._entityIdFromScope(scope).onSuccess((entityId) => {
|
|
77
|
+
const prefix = `${entityId}${TemporalIdentityCodec.versionInfix}`;
|
|
78
|
+
if (!stem.startsWith(prefix)) {
|
|
79
|
+
return fail(`temporal codec: version stem '${stem}' must begin with '${prefix}' (from scope '${scope}')`);
|
|
80
|
+
}
|
|
81
|
+
const seqText = stem.slice(prefix.length);
|
|
82
|
+
if (!TemporalIdentityCodec._versionSeqRe.test(seqText)) {
|
|
83
|
+
return fail(`temporal codec: version stem '${stem}' has a non-integer version suffix '${seqText}'`);
|
|
84
|
+
}
|
|
85
|
+
// The regex admits digit strings of unbounded length; `parseInt` would silently
|
|
86
|
+
// lose precision past MAX_SAFE_INTEGER, decoding a corrupt/tampered filename to a
|
|
87
|
+
// plausible-but-wrong `seq` that drives version ordering. Reject rather than corrupt.
|
|
88
|
+
const seq = Number.parseInt(seqText, 10);
|
|
89
|
+
if (!Number.isSafeInteger(seq)) {
|
|
90
|
+
return fail(`temporal codec: version stem '${stem}' has a version suffix '${seqText}' outside the safe integer range`);
|
|
91
|
+
}
|
|
92
|
+
return Convert.entityId.convert(entityId).onSuccess((branded) => succeed({ entityId: branded, seq }));
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** {@inheritDoc IIdentityCodec.verifyRoundTrip} */
|
|
96
|
+
verifyRoundTrip(scope, stem) {
|
|
97
|
+
return this.decodeVersion(scope, stem).onSuccess((addr) => this.encode(addr.entityId).onSuccess((encoded) => this.encodeVersion(addr.entityId, addr.seq).onSuccess((reStem) => {
|
|
98
|
+
if (encoded.scope !== scope || reStem !== stem) {
|
|
99
|
+
return fail(`temporal codec: round-trip mismatch for scope '${scope}' stem '${stem}' (re-encoded to scope '${encoded.scope}' stem '${reStem}')`);
|
|
100
|
+
}
|
|
101
|
+
return succeed(true);
|
|
102
|
+
})));
|
|
103
|
+
}
|
|
104
|
+
/** Validate and extract the `entityId` from a `<baseScope>/entities/<entityId>` scope. */
|
|
105
|
+
_entityIdFromScope(scope) {
|
|
106
|
+
const segments = scope.split('/');
|
|
107
|
+
if (segments.length !== 3 ||
|
|
108
|
+
segments[0] !== this.baseScope ||
|
|
109
|
+
segments[1] !== TemporalIdentityCodec.entitiesSegment) {
|
|
110
|
+
return fail(`temporal codec: scope '${scope}' must be '${this.baseScope}/${TemporalIdentityCodec.entitiesSegment}/<entityId>'`);
|
|
111
|
+
}
|
|
112
|
+
const entityId = segments[2];
|
|
113
|
+
return assertPortableFilenameStem(entityId)
|
|
114
|
+
.withErrorFormat((msg) => `temporal codec: entityId '${entityId}': ${msg}`)
|
|
115
|
+
.onSuccess(() => succeed(entityId));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** The fixed subtree segment separating an entity's versions from its scope. */
|
|
119
|
+
TemporalIdentityCodec.entitiesSegment = 'entities';
|
|
120
|
+
/** The version-stem infix: `<entityId>` + this + `<seq>`. */
|
|
121
|
+
TemporalIdentityCodec.versionInfix = '-v';
|
|
122
|
+
/** A non-negative integer string (the version seq). */
|
|
123
|
+
TemporalIdentityCodec._versionSeqRe = /^\d+$/;
|
|
9
124
|
/**
|
|
10
125
|
* Identity codec for the knowledge kind family. A knowledge entity is keyed
|
|
11
126
|
* by its consumer-supplied `docId`, which is used verbatim as the filename
|