@senselab-ai/amfs 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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * AmfsAdapter — interface that every TS adapter must implement.
3
+ */
4
+ import type { MemoryEntry, OutcomeRecord } from "./models.js";
5
+ export interface WatchHandle {
6
+ cancel(): void;
7
+ readonly cancelled: boolean;
8
+ }
9
+ export interface AmfsAdapter {
10
+ read(entityPath: string, key: string, options?: {
11
+ minConfidence?: number;
12
+ }): MemoryEntry | null;
13
+ write(entry: MemoryEntry): MemoryEntry;
14
+ list(entityPath?: string, options?: {
15
+ includeSuperseded?: boolean;
16
+ }): MemoryEntry[];
17
+ watch(entityPath: string, callback: (entry: MemoryEntry) => void): WatchHandle;
18
+ commitOutcome(record: OutcomeRecord): MemoryEntry[];
19
+ }
20
+ export declare function createWatchHandle(cancelFn: () => void): WatchHandle;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * AmfsAdapter — interface that every TS adapter must implement.
3
+ */
4
+ export function createWatchHandle(cancelFn) {
5
+ let _cancelled = false;
6
+ return {
7
+ cancel() {
8
+ if (!_cancelled) {
9
+ cancelFn();
10
+ _cancelled = true;
11
+ }
12
+ },
13
+ get cancelled() {
14
+ return _cancelled;
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * In-memory adapter for TypeScript SDK.
3
+ *
4
+ * A full filesystem adapter (matching Python's FilesystemAdapter with
5
+ * atomic rename) would require Node.js `fs` and `chokidar`. This
6
+ * in-memory implementation passes all contract tests and is suitable
7
+ * for browser/edge environments and testing.
8
+ */
9
+ import type { AmfsAdapter, WatchHandle } from "../adapter.js";
10
+ import type { MemoryEntry, OutcomeRecord } from "../models.js";
11
+ export declare class InMemoryAdapter implements AmfsAdapter {
12
+ private store;
13
+ private watchers;
14
+ private storeKey;
15
+ read(entityPath: string, key: string, options?: {
16
+ minConfidence?: number;
17
+ }): MemoryEntry | null;
18
+ write(entry: MemoryEntry): MemoryEntry;
19
+ list(entityPath?: string, options?: {
20
+ includeSuperseded?: boolean;
21
+ }): MemoryEntry[];
22
+ watch(entityPath: string, callback: (entry: MemoryEntry) => void): WatchHandle;
23
+ commitOutcome(record: OutcomeRecord): MemoryEntry[];
24
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * In-memory adapter for TypeScript SDK.
3
+ *
4
+ * A full filesystem adapter (matching Python's FilesystemAdapter with
5
+ * atomic rename) would require Node.js `fs` and `chokidar`. This
6
+ * in-memory implementation passes all contract tests and is suitable
7
+ * for browser/edge environments and testing.
8
+ */
9
+ import { createWatchHandle } from "../adapter.js";
10
+ import { OUTCOME_MULTIPLIERS } from "../models.js";
11
+ export class InMemoryAdapter {
12
+ store = new Map();
13
+ watchers = new Map();
14
+ storeKey(entityPath, key) {
15
+ return `${entityPath}/${key}`;
16
+ }
17
+ read(entityPath, key, options) {
18
+ const versions = this.store.get(this.storeKey(entityPath, key));
19
+ if (!versions || versions.length === 0)
20
+ return null;
21
+ const current = versions[versions.length - 1];
22
+ if (options?.minConfidence && current.confidence < options.minConfidence) {
23
+ return null;
24
+ }
25
+ return current;
26
+ }
27
+ write(entry) {
28
+ const sk = this.storeKey(entry.entityPath, entry.key);
29
+ const versions = this.store.get(sk) ?? [];
30
+ const currentVersion = versions.length > 0 ? versions[versions.length - 1].version : 0;
31
+ const newVersion = currentVersion + 1;
32
+ const written = { ...entry, version: newVersion };
33
+ versions.push(written);
34
+ this.store.set(sk, versions);
35
+ // Notify watchers
36
+ for (const [ep, callbacks] of this.watchers) {
37
+ if (entry.entityPath === ep || entry.entityPath.startsWith(ep + "/")) {
38
+ for (const cb of callbacks) {
39
+ cb(written);
40
+ }
41
+ }
42
+ }
43
+ return written;
44
+ }
45
+ list(entityPath, options) {
46
+ const result = [];
47
+ for (const [sk, versions] of this.store) {
48
+ if (entityPath && !sk.startsWith(entityPath + "/"))
49
+ continue;
50
+ if (options?.includeSuperseded) {
51
+ result.push(...versions);
52
+ }
53
+ else {
54
+ result.push(versions[versions.length - 1]);
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+ watch(entityPath, callback) {
60
+ if (!this.watchers.has(entityPath)) {
61
+ this.watchers.set(entityPath, new Set());
62
+ }
63
+ this.watchers.get(entityPath).add(callback);
64
+ return createWatchHandle(() => {
65
+ this.watchers.get(entityPath)?.delete(callback);
66
+ });
67
+ }
68
+ commitOutcome(record) {
69
+ const multiplier = OUTCOME_MULTIPLIERS[record.outcomeType];
70
+ const updated = [];
71
+ for (const spec of record.causalEntryKeys) {
72
+ const lastSlash = spec.lastIndexOf("/");
73
+ if (lastSlash === -1)
74
+ continue;
75
+ const ep = spec.substring(0, lastSlash);
76
+ const key = spec.substring(lastSlash + 1);
77
+ const current = this.read(ep, key);
78
+ if (!current)
79
+ continue;
80
+ const newEntry = {
81
+ ...current,
82
+ confidence: current.confidence * multiplier * record.causalConfidence,
83
+ outcomeCount: current.outcomeCount + 1,
84
+ };
85
+ const written = this.write(newEntry);
86
+ updated.push(written);
87
+ }
88
+ return updated;
89
+ }
90
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * HttpAdapter — connects the TS SDK to a remote AMFS HTTP API server.
3
+ */
4
+ import type { MemoryEntry, OutcomeRecord } from "../models.js";
5
+ import type { AmfsAdapter, WatchHandle } from "../adapter.js";
6
+ export interface HttpAdapterOptions {
7
+ url: string;
8
+ apiKey?: string;
9
+ headers?: Record<string, string>;
10
+ }
11
+ export declare class HttpAdapter implements AmfsAdapter {
12
+ private readonly baseUrl;
13
+ private readonly headers;
14
+ constructor(opts: HttpAdapterOptions);
15
+ private fetch;
16
+ read(entityPath: string, key: string, options?: {
17
+ minConfidence?: number;
18
+ }): MemoryEntry | null;
19
+ readAsync(entityPath: string, key: string): Promise<MemoryEntry | null>;
20
+ write(entry: MemoryEntry): MemoryEntry;
21
+ writeAsync(entry: {
22
+ entityPath: string;
23
+ key: string;
24
+ value: unknown;
25
+ confidence?: number;
26
+ memoryType?: string;
27
+ }): Promise<MemoryEntry>;
28
+ list(entityPath?: string, options?: {
29
+ includeSuperseded?: boolean;
30
+ }): MemoryEntry[];
31
+ listAsync(entityPath?: string, options?: {
32
+ includeSuperseded?: boolean;
33
+ }): Promise<MemoryEntry[]>;
34
+ searchAsync(query: {
35
+ query?: string;
36
+ entityPath?: string;
37
+ minConfidence?: number;
38
+ limit?: number;
39
+ }): Promise<MemoryEntry[]>;
40
+ watch(entityPath: string, callback: (entry: MemoryEntry) => void): WatchHandle;
41
+ commitOutcome(record: OutcomeRecord): MemoryEntry[];
42
+ commitOutcomeAsync(record: {
43
+ outcomeRef: string;
44
+ outcomeType: string;
45
+ }): Promise<unknown>;
46
+ statsAsync(): Promise<Record<string, unknown>>;
47
+ healthAsync(): Promise<Record<string, unknown>>;
48
+ listTracesAsync(options?: {
49
+ entityPath?: string;
50
+ agentId?: string;
51
+ outcomeType?: string;
52
+ limit?: number;
53
+ }): Promise<DecisionTraceSummary[]>;
54
+ getTraceAsync(traceId: string): Promise<DecisionTrace | null>;
55
+ }
56
+ export interface DecisionTraceSummary {
57
+ id: string;
58
+ agent_id: string;
59
+ outcome_ref: string;
60
+ outcome_type: string;
61
+ decision_summary?: string;
62
+ causal_entries: number;
63
+ external_contexts: number;
64
+ session_duration_ms?: number;
65
+ created_at: string;
66
+ }
67
+ export interface DecisionTrace {
68
+ id: string;
69
+ agent_id: string;
70
+ session_id: string;
71
+ outcome_ref: string;
72
+ outcome_type: string;
73
+ decision_summary?: string;
74
+ causal_entries: Array<{
75
+ entity_path: string;
76
+ key: string;
77
+ version: number;
78
+ confidence: number;
79
+ value?: unknown;
80
+ memory_type?: string;
81
+ written_by?: string;
82
+ read_at?: string;
83
+ }>;
84
+ external_contexts: Array<{
85
+ label: string;
86
+ summary: string;
87
+ source?: string;
88
+ recorded_at?: string;
89
+ }>;
90
+ query_events: Array<{
91
+ operation: string;
92
+ parameters: Record<string, unknown>;
93
+ result_count: number;
94
+ duration_ms?: number;
95
+ occurred_at?: string;
96
+ }>;
97
+ error_events: Array<{
98
+ operation: string;
99
+ error_type: string;
100
+ message: string;
101
+ stack_trace?: string;
102
+ occurred_at?: string;
103
+ }>;
104
+ state_diff?: {
105
+ entries_created: number;
106
+ entries_updated: number;
107
+ };
108
+ session_started_at?: string;
109
+ session_ended_at?: string;
110
+ session_duration_ms?: number;
111
+ created_at: string;
112
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * HttpAdapter — connects the TS SDK to a remote AMFS HTTP API server.
3
+ */
4
+ import { createWatchHandle } from "../adapter.js";
5
+ export class HttpAdapter {
6
+ baseUrl;
7
+ headers;
8
+ constructor(opts) {
9
+ this.baseUrl = opts.url.replace(/\/+$/, "");
10
+ this.headers = {
11
+ "Content-Type": "application/json",
12
+ ...opts.headers,
13
+ };
14
+ if (opts.apiKey) {
15
+ this.headers["X-AMFS-API-Key"] = opts.apiKey;
16
+ }
17
+ }
18
+ async fetch(path, init) {
19
+ const resp = await globalThis.fetch(`${this.baseUrl}${path}`, {
20
+ ...init,
21
+ headers: { ...this.headers, ...init?.headers },
22
+ });
23
+ if (!resp.ok) {
24
+ const body = await resp.text().catch(() => "");
25
+ throw new Error(`AMFS API ${resp.status}: ${body}`);
26
+ }
27
+ return resp.json();
28
+ }
29
+ read(entityPath, key, options) {
30
+ // Synchronous interface — return null and let callers use readAsync
31
+ return null;
32
+ }
33
+ async readAsync(entityPath, key) {
34
+ try {
35
+ return await this.fetch(`/api/v1/entries/${encodeURIComponent(entityPath)}/${encodeURIComponent(key)}`);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ write(entry) {
42
+ // Synchronous interface — callers should use writeAsync for HTTP
43
+ return entry;
44
+ }
45
+ async writeAsync(entry) {
46
+ return this.fetch("/api/v1/entries", {
47
+ method: "POST",
48
+ body: JSON.stringify({
49
+ entity_path: entry.entityPath,
50
+ key: entry.key,
51
+ value: entry.value,
52
+ confidence: entry.confidence ?? 1.0,
53
+ memory_type: entry.memoryType ?? "fact",
54
+ }),
55
+ });
56
+ }
57
+ list(entityPath, options) {
58
+ // Synchronous interface — return empty, callers should use listAsync
59
+ return [];
60
+ }
61
+ async listAsync(entityPath, options) {
62
+ const params = new URLSearchParams();
63
+ if (entityPath)
64
+ params.set("entity_path", entityPath);
65
+ if (options?.includeSuperseded)
66
+ params.set("include_superseded", "true");
67
+ const qs = params.toString();
68
+ return this.fetch(`/api/v1/entries${qs ? `?${qs}` : ""}`);
69
+ }
70
+ async searchAsync(query) {
71
+ return this.fetch("/api/v1/search", {
72
+ method: "POST",
73
+ body: JSON.stringify({
74
+ query: query.query,
75
+ entity_path: query.entityPath,
76
+ min_confidence: query.minConfidence ?? 0.0,
77
+ limit: query.limit ?? 100,
78
+ }),
79
+ });
80
+ }
81
+ watch(entityPath, callback) {
82
+ const controller = new AbortController();
83
+ const connect = async () => {
84
+ try {
85
+ const resp = await globalThis.fetch(`${this.baseUrl}/api/v1/stream?entity_path=${encodeURIComponent(entityPath)}`, { headers: this.headers, signal: controller.signal });
86
+ if (!resp.ok || !resp.body)
87
+ return;
88
+ const reader = resp.body.getReader();
89
+ const decoder = new TextDecoder();
90
+ let buffer = "";
91
+ while (true) {
92
+ const { done, value } = await reader.read();
93
+ if (done)
94
+ break;
95
+ buffer += decoder.decode(value, { stream: true });
96
+ while (buffer.includes("\n\n")) {
97
+ const [msg, rest] = buffer.split("\n\n", 2);
98
+ buffer = rest;
99
+ for (const line of msg.split("\n")) {
100
+ if (line.startsWith("data:")) {
101
+ const raw = line.slice(5).trim();
102
+ if (raw) {
103
+ try {
104
+ callback(JSON.parse(raw));
105
+ }
106
+ catch { /* skip malformed */ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+ }
113
+ catch {
114
+ // aborted or network error
115
+ }
116
+ };
117
+ connect();
118
+ return createWatchHandle(() => controller.abort());
119
+ }
120
+ commitOutcome(record) {
121
+ // Synchronous interface — return empty, callers should use commitOutcomeAsync
122
+ return [];
123
+ }
124
+ async commitOutcomeAsync(record) {
125
+ return this.fetch("/api/v1/outcomes", {
126
+ method: "POST",
127
+ body: JSON.stringify({
128
+ outcome_ref: record.outcomeRef,
129
+ outcome_type: record.outcomeType,
130
+ }),
131
+ });
132
+ }
133
+ async statsAsync() {
134
+ return this.fetch("/api/v1/stats");
135
+ }
136
+ async healthAsync() {
137
+ return this.fetch("/api/v1/health");
138
+ }
139
+ async listTracesAsync(options) {
140
+ const params = new URLSearchParams();
141
+ if (options?.entityPath)
142
+ params.set("entity_path", options.entityPath);
143
+ if (options?.agentId)
144
+ params.set("agent_id", options.agentId);
145
+ if (options?.outcomeType)
146
+ params.set("outcome_type", options.outcomeType);
147
+ if (options?.limit)
148
+ params.set("limit", String(options.limit));
149
+ const qs = params.toString();
150
+ const data = await this.fetch(`/api/v1/traces${qs ? `?${qs}` : ""}`);
151
+ return data.traces ?? [];
152
+ }
153
+ async getTraceAsync(traceId) {
154
+ try {
155
+ return await this.fetch(`/api/v1/traces/${encodeURIComponent(traceId)}`);
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Configuration types and defaults for AMFS TS SDK.
3
+ */
4
+ import type { AMFSConfig } from "./models.js";
5
+ export declare function defaultConfig(): AMFSConfig;
package/dist/config.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Configuration types and defaults for AMFS TS SDK.
3
+ */
4
+ export function defaultConfig() {
5
+ return {
6
+ namespace: "default",
7
+ layers: {
8
+ primary: {
9
+ adapter: "in-memory",
10
+ options: {},
11
+ },
12
+ },
13
+ };
14
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * CoWEngine and CausalTagger — TypeScript port.
3
+ */
4
+ import type { AmfsAdapter } from "./adapter.js";
5
+ import type { MemoryEntry, Provenance } from "./models.js";
6
+ import { ReadTracker } from "./tracker.js";
7
+ export declare class CausalTagger {
8
+ readonly agentId: string;
9
+ readonly sessionId: string;
10
+ constructor(agentId: string, sessionId?: string);
11
+ tag(patternRefs?: string[]): Provenance;
12
+ }
13
+ export declare class CoWEngine {
14
+ readonly adapter: AmfsAdapter;
15
+ readonly tagger: CausalTagger;
16
+ readonly readTracker: ReadTracker | null;
17
+ constructor(adapter: AmfsAdapter, tagger: CausalTagger, readTracker?: ReadTracker);
18
+ read(entityPath: string, key: string, options?: {
19
+ minConfidence?: number;
20
+ }): MemoryEntry | null;
21
+ write(entityPath: string, key: string, value: unknown, options?: {
22
+ confidence?: number;
23
+ ttlAt?: string | null;
24
+ patternRefs?: string[];
25
+ shared?: boolean;
26
+ }): MemoryEntry;
27
+ list(entityPath?: string, options?: {
28
+ includeSuperseded?: boolean;
29
+ }): MemoryEntry[];
30
+ history(entityPath: string, key: string, options?: {
31
+ since?: string;
32
+ until?: string;
33
+ }): MemoryEntry[];
34
+ }
package/dist/engine.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * CoWEngine and CausalTagger — TypeScript port.
3
+ */
4
+ export class CausalTagger {
5
+ agentId;
6
+ sessionId;
7
+ constructor(agentId, sessionId) {
8
+ this.agentId = agentId;
9
+ this.sessionId =
10
+ sessionId ?? `sess-${Math.random().toString(36).substring(2, 10)}`;
11
+ }
12
+ tag(patternRefs = []) {
13
+ return {
14
+ agentId: this.agentId,
15
+ sessionId: this.sessionId,
16
+ writtenAt: new Date().toISOString(),
17
+ patternRefs,
18
+ };
19
+ }
20
+ }
21
+ export class CoWEngine {
22
+ adapter;
23
+ tagger;
24
+ readTracker;
25
+ constructor(adapter, tagger, readTracker) {
26
+ this.adapter = adapter;
27
+ this.tagger = tagger;
28
+ this.readTracker = readTracker ?? null;
29
+ }
30
+ read(entityPath, key, options) {
31
+ const entry = this.adapter.read(entityPath, key, options);
32
+ if (entry && this.readTracker) {
33
+ this.readTracker.record(entry);
34
+ }
35
+ return entry;
36
+ }
37
+ write(entityPath, key, value, options) {
38
+ const current = this.adapter.read(entityPath, key);
39
+ const nextVersion = current ? current.version + 1 : 1;
40
+ const entry = {
41
+ amfsVersion: "0.1.0",
42
+ entityPath,
43
+ key,
44
+ version: nextVersion,
45
+ value,
46
+ provenance: this.tagger.tag(options?.patternRefs),
47
+ confidence: options?.confidence ?? 1.0,
48
+ outcomeCount: current?.outcomeCount ?? 0,
49
+ ttlAt: options?.ttlAt ?? null,
50
+ shared: options?.shared ?? true,
51
+ };
52
+ return this.adapter.write(entry);
53
+ }
54
+ list(entityPath, options) {
55
+ return this.adapter.list(entityPath, options);
56
+ }
57
+ history(entityPath, key, options) {
58
+ const all = this.adapter.list(entityPath, { includeSuperseded: true });
59
+ let versions = all
60
+ .filter((e) => e.key === key)
61
+ .sort((a, b) => a.version - b.version);
62
+ if (options?.since) {
63
+ versions = versions.filter((e) => e.provenance.writtenAt >= options.since);
64
+ }
65
+ if (options?.until) {
66
+ versions = versions.filter((e) => e.provenance.writtenAt <= options.until);
67
+ }
68
+ return versions;
69
+ }
70
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @amfs/sdk — Agent Memory File System TypeScript SDK
3
+ */
4
+ export { AgentMemory, MemoryScope } from "./memory.js";
5
+ export type { AgentMemoryOptions, SearchOptions, MemoryStats } from "./memory.js";
6
+ export type { AmfsAdapter, WatchHandle } from "./adapter.js";
7
+ export { createWatchHandle } from "./adapter.js";
8
+ export { InMemoryAdapter } from "./adapters/filesystem.js";
9
+ export { HttpAdapter } from "./adapters/http.js";
10
+ export type { HttpAdapterOptions, DecisionTrace, DecisionTraceSummary } from "./adapters/http.js";
11
+ export { CausalTagger, CoWEngine } from "./engine.js";
12
+ export { ReadTracker } from "./tracker.js";
13
+ export type { ExternalContext } from "./tracker.js";
14
+ export { OutcomeBackPropagator } from "./outcome.js";
15
+ export { defaultConfig } from "./config.js";
16
+ export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
17
+ export type { MemoryEntry, OutcomeRecord, Provenance, ArtifactRef, AMFSConfig, LayerConfig, RecallConfig, ScopeInfo, ScoredEntry, } from "./models.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @amfs/sdk — Agent Memory File System TypeScript SDK
3
+ */
4
+ export { AgentMemory, MemoryScope } from "./memory.js";
5
+ export { createWatchHandle } from "./adapter.js";
6
+ export { InMemoryAdapter } from "./adapters/filesystem.js";
7
+ export { HttpAdapter } from "./adapters/http.js";
8
+ export { CausalTagger, CoWEngine } from "./engine.js";
9
+ export { ReadTracker } from "./tracker.js";
10
+ export { OutcomeBackPropagator } from "./outcome.js";
11
+ export { defaultConfig } from "./config.js";
12
+ export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
@@ -0,0 +1,140 @@
1
+ /**
2
+ * AgentMemory — the main SDK entry point for TypeScript agents.
3
+ */
4
+ import type { AmfsAdapter, WatchHandle } from "./adapter.js";
5
+ import type { AMFSConfig, MemoryEntry, RecallConfig, ScopeInfo, ScoredEntry } from "./models.js";
6
+ import { OutcomeType } from "./models.js";
7
+ import { ReadTracker } from "./tracker.js";
8
+ export interface AgentMemoryOptions {
9
+ sessionId?: string;
10
+ adapter?: AmfsAdapter;
11
+ config?: AMFSConfig;
12
+ }
13
+ export interface SearchOptions {
14
+ entityPath?: string;
15
+ entityPaths?: string[];
16
+ minConfidence?: number;
17
+ maxConfidence?: number;
18
+ agentId?: string;
19
+ since?: string;
20
+ patternRef?: string;
21
+ limit?: number;
22
+ sortBy?: "confidence" | "recency" | "version";
23
+ recallConfig?: RecallConfig;
24
+ }
25
+ export interface MemoryStats {
26
+ totalEntries: number;
27
+ totalEntities: number;
28
+ totalAgents: number;
29
+ agents: Record<string, number>;
30
+ entities: Record<string, number>;
31
+ confidenceAvg: number;
32
+ outcomeLinkedCount: number;
33
+ }
34
+ export declare class AgentMemory {
35
+ readonly agentId: string;
36
+ readonly sessionId: string;
37
+ readonly namespace: string;
38
+ readonly adapter: AmfsAdapter;
39
+ readonly readTracker: ReadTracker;
40
+ private engine;
41
+ private propagator;
42
+ constructor(agentId: string, options?: AgentMemoryOptions);
43
+ read(entityPath: string, key: string, options?: {
44
+ minConfidence?: number;
45
+ }): MemoryEntry | null;
46
+ write(entityPath: string, key: string, value: unknown, options?: {
47
+ confidence?: number;
48
+ ttlAt?: string | null;
49
+ patternRefs?: string[];
50
+ shared?: boolean;
51
+ }): MemoryEntry;
52
+ list(entityPath?: string, options?: {
53
+ includeSuperseded?: boolean;
54
+ }): MemoryEntry[];
55
+ watch(entityPath: string, callback: (entry: MemoryEntry) => void): WatchHandle;
56
+ /** Return the full version history of a key, ordered by version. */
57
+ history(entityPath: string, key: string, options?: {
58
+ since?: string;
59
+ until?: string;
60
+ }): MemoryEntry[];
61
+ /** Search entries with filters. Supports multi-scope via entityPaths and composite scoring via recallConfig. */
62
+ search(options: SearchOptions & {
63
+ recallConfig: RecallConfig;
64
+ }): ScoredEntry[];
65
+ search(options?: SearchOptions): MemoryEntry[];
66
+ /** Aggregate statistics about current memory state. */
67
+ stats(): MemoryStats;
68
+ /**
69
+ * Record external context in the causal chain without writing to storage.
70
+ * Call after consulting external tools/APIs so explain() is complete.
71
+ */
72
+ recordContext(label: string, summary: string, options?: {
73
+ source?: string;
74
+ }): void;
75
+ /**
76
+ * Return the causal chain for the current session.
77
+ * Shows which memories were read, external contexts, and their order.
78
+ */
79
+ explain(outcomeRef?: string): Record<string, unknown>;
80
+ /**
81
+ * Commit an outcome and back-propagate confidence changes.
82
+ * If causalEntryKeys is omitted, uses the session's read log automatically.
83
+ */
84
+ commitOutcome(outcomeRef: string, outcomeType: OutcomeType, causalEntryKeys?: string[], options?: {
85
+ causalConfidence?: number;
86
+ }): MemoryEntry[];
87
+ /**
88
+ * Recall this agent's own memory for a key.
89
+ * Unlike read(), returns only entries written by this agent.
90
+ */
91
+ recall(entityPath: string, key: string, options?: {
92
+ minConfidence?: number;
93
+ }): MemoryEntry | null;
94
+ /** List entries written by this agent — the contents of this brain. */
95
+ myEntries(entityPath?: string): MemoryEntry[];
96
+ /**
97
+ * Read a specific key from another agent's memory.
98
+ * Makes cross-agent knowledge transfer explicit and trackable.
99
+ */
100
+ readFrom(agentId: string, entityPath: string, key: string): MemoryEntry | null;
101
+ /** Return a MemoryScope bound to the given entity path. */
102
+ scope(entityPath: string, options?: {
103
+ readonly?: boolean;
104
+ }): MemoryScope;
105
+ /** Return all unique entity paths that contain at least one entry. */
106
+ listScopes(): string[];
107
+ /** Return summary information about a single scope. */
108
+ info(entityPath: string): ScopeInfo;
109
+ /** Render all entity paths as an indented tree with entry counts. */
110
+ tree(maxDepth?: number): string;
111
+ /** Reset the session read log. */
112
+ clearReadLog(): void;
113
+ }
114
+ /**
115
+ * A scoped view of AgentMemory bound to a fixed entity path.
116
+ * When readonly is true, writes throw an error.
117
+ */
118
+ export declare class MemoryScope {
119
+ readonly entityPath: string;
120
+ readonly isReadonly: boolean;
121
+ private memory;
122
+ constructor(memory: AgentMemory, entityPath: string, isReadonly?: boolean);
123
+ read(key: string, options?: {
124
+ minConfidence?: number;
125
+ }): MemoryEntry | null;
126
+ write(key: string, value: unknown, options?: {
127
+ confidence?: number;
128
+ ttlAt?: string | null;
129
+ patternRefs?: string[];
130
+ }): MemoryEntry;
131
+ list(options?: {
132
+ includeSuperseded?: boolean;
133
+ }): MemoryEntry[];
134
+ search(options?: Omit<SearchOptions, "entityPath" | "entityPaths">): MemoryEntry[];
135
+ history(key: string, options?: {
136
+ since?: string;
137
+ until?: string;
138
+ }): MemoryEntry[];
139
+ info(): ScopeInfo;
140
+ }
package/dist/memory.js ADDED
@@ -0,0 +1,331 @@
1
+ /**
2
+ * AgentMemory — the main SDK entry point for TypeScript agents.
3
+ */
4
+ import { InMemoryAdapter } from "./adapters/filesystem.js";
5
+ import { defaultConfig } from "./config.js";
6
+ import { CausalTagger, CoWEngine } from "./engine.js";
7
+ import { OutcomeBackPropagator } from "./outcome.js";
8
+ import { ReadTracker } from "./tracker.js";
9
+ export class AgentMemory {
10
+ agentId;
11
+ sessionId;
12
+ namespace;
13
+ adapter;
14
+ readTracker;
15
+ engine;
16
+ propagator;
17
+ constructor(agentId, options) {
18
+ const config = options?.config ?? defaultConfig();
19
+ this.agentId = agentId;
20
+ this.adapter = options?.adapter ?? new InMemoryAdapter();
21
+ this.namespace = config.namespace;
22
+ this.readTracker = new ReadTracker();
23
+ const tagger = new CausalTagger(agentId, options?.sessionId);
24
+ this.sessionId = tagger.sessionId;
25
+ this.engine = new CoWEngine(this.adapter, tagger, this.readTracker);
26
+ this.propagator = new OutcomeBackPropagator(this.adapter);
27
+ }
28
+ read(entityPath, key, options) {
29
+ const entry = this.engine.read(entityPath, key, options);
30
+ if (entry && !entry.shared && entry.provenance.agentId !== this.agentId) {
31
+ return null;
32
+ }
33
+ return entry;
34
+ }
35
+ write(entityPath, key, value, options) {
36
+ return this.engine.write(entityPath, key, value, options);
37
+ }
38
+ list(entityPath, options) {
39
+ return this.engine.list(entityPath, options).filter((e) => e.shared || e.provenance.agentId === this.agentId);
40
+ }
41
+ watch(entityPath, callback) {
42
+ return this.adapter.watch(entityPath, callback);
43
+ }
44
+ /** Return the full version history of a key, ordered by version. */
45
+ history(entityPath, key, options) {
46
+ return this.engine.history(entityPath, key, options);
47
+ }
48
+ search(options) {
49
+ const paths = options?.entityPaths ??
50
+ (options?.entityPath ? [options.entityPath] : [undefined]);
51
+ const seenKeys = new Set();
52
+ let merged = [];
53
+ for (const ep of paths) {
54
+ let entries = this.engine.list(ep);
55
+ if (options?.minConfidence) {
56
+ entries = entries.filter((e) => e.confidence >= options.minConfidence);
57
+ }
58
+ if (options?.maxConfidence != null) {
59
+ entries = entries.filter((e) => e.confidence <= options.maxConfidence);
60
+ }
61
+ if (options?.agentId) {
62
+ entries = entries.filter((e) => e.provenance.agentId === options.agentId);
63
+ }
64
+ if (options?.since) {
65
+ const sinceTs = options.since;
66
+ entries = entries.filter((e) => e.provenance.writtenAt >= sinceTs);
67
+ }
68
+ if (options?.patternRef) {
69
+ const ref = options.patternRef;
70
+ entries = entries.filter((e) => e.provenance.patternRefs.includes(ref));
71
+ }
72
+ for (const entry of entries) {
73
+ if (!entry.shared && entry.provenance.agentId !== this.agentId)
74
+ continue;
75
+ const ek = `${entry.entityPath}/${entry.key}`;
76
+ if (!seenKeys.has(ek)) {
77
+ seenKeys.add(ek);
78
+ merged.push(entry);
79
+ }
80
+ }
81
+ }
82
+ const sortBy = options?.sortBy ?? "confidence";
83
+ if (sortBy === "confidence") {
84
+ merged.sort((a, b) => b.confidence - a.confidence);
85
+ }
86
+ else if (sortBy === "recency") {
87
+ merged.sort((a, b) => b.provenance.writtenAt.localeCompare(a.provenance.writtenAt));
88
+ }
89
+ else if (sortBy === "version") {
90
+ merged.sort((a, b) => b.version - a.version);
91
+ }
92
+ const limited = merged.slice(0, options?.limit ?? 100);
93
+ if (!options?.recallConfig) {
94
+ return limited;
95
+ }
96
+ const rc = options.recallConfig;
97
+ const semanticWeight = rc.semanticWeight ?? 0.5;
98
+ const recencyWeight = rc.recencyWeight ?? 0.3;
99
+ const confidenceWeight = rc.confidenceWeight ?? 0.2;
100
+ const halfLife = rc.recencyHalfLifeDays ?? 30.0;
101
+ const now = Date.now();
102
+ const LN2 = Math.LN2;
103
+ const scored = limited.map((entry) => {
104
+ const writtenMs = new Date(entry.provenance.writtenAt).getTime();
105
+ const ageDays = (now - writtenMs) / 86_400_000;
106
+ const recencyScore = halfLife > 0 ? Math.exp(-LN2 * ageDays / halfLife) : 0;
107
+ const confidenceScore = Math.max(0, Math.min(1, entry.confidence));
108
+ const semanticComponent = semanticWeight * 1.0;
109
+ const recencyComponent = recencyWeight * recencyScore;
110
+ const confidenceComponent = confidenceWeight * confidenceScore;
111
+ return {
112
+ entry,
113
+ score: semanticComponent + recencyComponent + confidenceComponent,
114
+ breakdown: {
115
+ semantic: semanticComponent,
116
+ recency: recencyComponent,
117
+ confidence: confidenceComponent,
118
+ },
119
+ };
120
+ });
121
+ scored.sort((a, b) => b.score - a.score);
122
+ return scored;
123
+ }
124
+ /** Aggregate statistics about current memory state. */
125
+ stats() {
126
+ const entries = this.engine.list();
127
+ const agents = {};
128
+ const entities = {};
129
+ let totalConfidence = 0;
130
+ let outcomeLinked = 0;
131
+ for (const e of entries) {
132
+ agents[e.provenance.agentId] = (agents[e.provenance.agentId] ?? 0) + 1;
133
+ entities[e.entityPath] = (entities[e.entityPath] ?? 0) + 1;
134
+ totalConfidence += e.confidence;
135
+ if (e.outcomeCount > 0)
136
+ outcomeLinked++;
137
+ }
138
+ return {
139
+ totalEntries: entries.length,
140
+ totalEntities: Object.keys(entities).length,
141
+ totalAgents: Object.keys(agents).length,
142
+ agents,
143
+ entities,
144
+ confidenceAvg: entries.length > 0 ? totalConfidence / entries.length : 0,
145
+ outcomeLinkedCount: outcomeLinked,
146
+ };
147
+ }
148
+ /**
149
+ * Record external context in the causal chain without writing to storage.
150
+ * Call after consulting external tools/APIs so explain() is complete.
151
+ */
152
+ recordContext(label, summary, options) {
153
+ this.readTracker.recordContext(label, summary, options);
154
+ }
155
+ /**
156
+ * Return the causal chain for the current session.
157
+ * Shows which memories were read, external contexts, and their order.
158
+ */
159
+ explain(outcomeRef) {
160
+ const causalKeys = this.readTracker.causalKeys;
161
+ const entries = [];
162
+ for (const ek of causalKeys) {
163
+ const lastSlash = ek.lastIndexOf("/");
164
+ if (lastSlash === -1)
165
+ continue;
166
+ const ep = ek.substring(0, lastSlash);
167
+ const k = ek.substring(lastSlash + 1);
168
+ const entry = this.adapter.read(ep, k);
169
+ if (entry) {
170
+ entries.push({
171
+ ...entry,
172
+ readVersion: this.readTracker.readVersion(ek),
173
+ });
174
+ }
175
+ }
176
+ return {
177
+ outcomeRef: outcomeRef ?? null,
178
+ agentId: this.agentId,
179
+ sessionId: this.sessionId,
180
+ causalChainLength: causalKeys.length,
181
+ causalEntries: entries,
182
+ externalContexts: this.readTracker.externalContexts,
183
+ };
184
+ }
185
+ /**
186
+ * Commit an outcome and back-propagate confidence changes.
187
+ * If causalEntryKeys is omitted, uses the session's read log automatically.
188
+ */
189
+ commitOutcome(outcomeRef, outcomeType, causalEntryKeys, options) {
190
+ const keys = causalEntryKeys ?? this.readTracker.causalKeys;
191
+ const record = OutcomeBackPropagator.makeRecord(outcomeRef, outcomeType, keys, this.agentId, { causalConfidence: options?.causalConfidence });
192
+ return this.propagator.propagate(record);
193
+ }
194
+ // ------------------------------------------------------------------
195
+ // Agent brain — scoped recall & cross-agent reads
196
+ // ------------------------------------------------------------------
197
+ /**
198
+ * Recall this agent's own memory for a key.
199
+ * Unlike read(), returns only entries written by this agent.
200
+ */
201
+ recall(entityPath, key, options) {
202
+ const entry = this.engine.read(entityPath, key);
203
+ if (!entry)
204
+ return null;
205
+ const minConf = options?.minConfidence ?? 0;
206
+ if (entry.provenance.agentId === this.agentId) {
207
+ return entry.confidence >= minConf ? entry : null;
208
+ }
209
+ const versions = this.engine.history(entityPath, key);
210
+ for (let i = versions.length - 1; i >= 0; i--) {
211
+ const v = versions[i];
212
+ if (v.provenance.agentId === this.agentId) {
213
+ return v.confidence >= minConf ? v : null;
214
+ }
215
+ }
216
+ return null;
217
+ }
218
+ /** List entries written by this agent — the contents of this brain. */
219
+ myEntries(entityPath) {
220
+ return this.search({ entityPath, agentId: this.agentId });
221
+ }
222
+ /**
223
+ * Read a specific key from another agent's memory.
224
+ * Makes cross-agent knowledge transfer explicit and trackable.
225
+ */
226
+ readFrom(agentId, entityPath, key) {
227
+ const entries = this.search({ entityPath, agentId });
228
+ const match = entries.find((e) => e.key === key && e.shared);
229
+ if (!match)
230
+ return null;
231
+ this.readTracker.record(match);
232
+ return match;
233
+ }
234
+ /** Return a MemoryScope bound to the given entity path. */
235
+ scope(entityPath, options) {
236
+ return new MemoryScope(this, entityPath, options?.readonly ?? false);
237
+ }
238
+ /** Return all unique entity paths that contain at least one entry. */
239
+ listScopes() {
240
+ const entries = this.engine.list();
241
+ const paths = new Set(entries.map((e) => e.entityPath));
242
+ return [...paths].sort();
243
+ }
244
+ /** Return summary information about a single scope. */
245
+ info(entityPath) {
246
+ const entries = this.engine.list().filter((e) => e.entityPath === entityPath);
247
+ if (entries.length === 0) {
248
+ return { path: entityPath, entryCount: 0, avgConfidence: 0, keys: [], oldest: null, newest: null };
249
+ }
250
+ const timestamps = entries.map((e) => e.provenance.writtenAt);
251
+ return {
252
+ path: entityPath,
253
+ entryCount: entries.length,
254
+ avgConfidence: entries.reduce((s, e) => s + e.confidence, 0) / entries.length,
255
+ keys: entries.map((e) => e.key),
256
+ oldest: timestamps.reduce((a, b) => (a < b ? a : b)),
257
+ newest: timestamps.reduce((a, b) => (a > b ? a : b)),
258
+ };
259
+ }
260
+ /** Render all entity paths as an indented tree with entry counts. */
261
+ tree(maxDepth = 3) {
262
+ const entries = this.engine.list();
263
+ const pathCounts = {};
264
+ for (const e of entries) {
265
+ pathCounts[e.entityPath] = (pathCounts[e.entityPath] ?? 0) + 1;
266
+ }
267
+ const root = {};
268
+ for (const path of Object.keys(pathCounts).sort()) {
269
+ const parts = path.split("/").slice(0, maxDepth);
270
+ let node = root;
271
+ for (const part of parts) {
272
+ node[part] ??= {};
273
+ node = node[part];
274
+ }
275
+ }
276
+ const lines = [];
277
+ const walk = (node, prefix, depth) => {
278
+ for (const name of Object.keys(node).sort()) {
279
+ const current = prefix ? `${prefix}/${name}` : name;
280
+ let count = 0;
281
+ for (const [p, c] of Object.entries(pathCounts)) {
282
+ if (p === current || p.startsWith(`${current}/`))
283
+ count += c;
284
+ }
285
+ lines.push(`${" ".repeat(depth)}${name} (${count})`);
286
+ if (depth < maxDepth - 1)
287
+ walk(node[name], current, depth + 1);
288
+ }
289
+ };
290
+ walk(root, "", 0);
291
+ return lines.join("\n");
292
+ }
293
+ /** Reset the session read log. */
294
+ clearReadLog() {
295
+ this.readTracker.clear();
296
+ }
297
+ }
298
+ /**
299
+ * A scoped view of AgentMemory bound to a fixed entity path.
300
+ * When readonly is true, writes throw an error.
301
+ */
302
+ export class MemoryScope {
303
+ entityPath;
304
+ isReadonly;
305
+ memory;
306
+ constructor(memory, entityPath, isReadonly = false) {
307
+ this.memory = memory;
308
+ this.entityPath = entityPath;
309
+ this.isReadonly = isReadonly;
310
+ }
311
+ read(key, options) {
312
+ return this.memory.read(this.entityPath, key, options);
313
+ }
314
+ write(key, value, options) {
315
+ if (this.isReadonly)
316
+ throw new Error("Read-only scope");
317
+ return this.memory.write(this.entityPath, key, value, options);
318
+ }
319
+ list(options) {
320
+ return this.memory.list(this.entityPath, options);
321
+ }
322
+ search(options) {
323
+ return this.memory.search({ ...options, entityPath: this.entityPath });
324
+ }
325
+ history(key, options) {
326
+ return this.memory.history(this.entityPath, key, options);
327
+ }
328
+ info() {
329
+ return this.memory.info(this.entityPath);
330
+ }
331
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * AMFS TypeScript types — mirrors the Python Pydantic models.
3
+ */
4
+ export declare enum OutcomeType {
5
+ SUCCESS = "success",
6
+ MINOR_FAILURE = "minor_failure",
7
+ FAILURE = "failure",
8
+ CRITICAL_FAILURE = "critical_failure",
9
+ /** @deprecated Use SUCCESS */ CLEAN_DEPLOY = "clean_deploy",
10
+ /** @deprecated Use MINOR_FAILURE */ REGRESSION = "regression",
11
+ /** @deprecated Use FAILURE */ P2_INCIDENT = "p2_incident",
12
+ /** @deprecated Use CRITICAL_FAILURE */ P1_INCIDENT = "p1_incident"
13
+ }
14
+ export declare const OUTCOME_MULTIPLIERS: Record<string, number>;
15
+ export interface Provenance {
16
+ agentId: string;
17
+ sessionId: string;
18
+ writtenAt: string;
19
+ patternRefs: string[];
20
+ }
21
+ export interface ArtifactRef {
22
+ uri: string;
23
+ mediaType?: string | null;
24
+ label?: string | null;
25
+ sizeBytes?: number | null;
26
+ }
27
+ export interface MemoryEntry {
28
+ amfsVersion: string;
29
+ entityPath: string;
30
+ key: string;
31
+ version: number;
32
+ value: unknown;
33
+ provenance: Provenance;
34
+ confidence: number;
35
+ outcomeCount: number;
36
+ ttlAt: string | null;
37
+ artifactRefs?: ArtifactRef[];
38
+ shared: boolean;
39
+ }
40
+ export interface OutcomeRecord {
41
+ outcomeRef: string;
42
+ outcomeType: OutcomeType;
43
+ causalConfidence: number;
44
+ committedAt: string;
45
+ causalEntryKeys: string[];
46
+ agentId: string;
47
+ }
48
+ export interface ScopeInfo {
49
+ path: string;
50
+ entryCount: number;
51
+ avgConfidence: number;
52
+ keys: string[];
53
+ oldest: string | null;
54
+ newest: string | null;
55
+ }
56
+ export interface LayerConfig {
57
+ adapter: string;
58
+ options: Record<string, unknown>;
59
+ }
60
+ export interface AMFSConfig {
61
+ namespace: string;
62
+ layers: Record<string, LayerConfig>;
63
+ }
64
+ export interface RecallConfig {
65
+ semanticWeight?: number;
66
+ recencyWeight?: number;
67
+ confidenceWeight?: number;
68
+ recencyHalfLifeDays?: number;
69
+ }
70
+ export interface ScoredEntry {
71
+ entry: MemoryEntry;
72
+ score: number;
73
+ breakdown: Record<string, number>;
74
+ }
package/dist/models.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * AMFS TypeScript types — mirrors the Python Pydantic models.
3
+ */
4
+ export var OutcomeType;
5
+ (function (OutcomeType) {
6
+ OutcomeType["SUCCESS"] = "success";
7
+ OutcomeType["MINOR_FAILURE"] = "minor_failure";
8
+ OutcomeType["FAILURE"] = "failure";
9
+ OutcomeType["CRITICAL_FAILURE"] = "critical_failure";
10
+ /** @deprecated Use SUCCESS */ OutcomeType["CLEAN_DEPLOY"] = "clean_deploy";
11
+ /** @deprecated Use MINOR_FAILURE */ OutcomeType["REGRESSION"] = "regression";
12
+ /** @deprecated Use FAILURE */ OutcomeType["P2_INCIDENT"] = "p2_incident";
13
+ /** @deprecated Use CRITICAL_FAILURE */ OutcomeType["P1_INCIDENT"] = "p1_incident";
14
+ })(OutcomeType || (OutcomeType = {}));
15
+ export const OUTCOME_MULTIPLIERS = {
16
+ [OutcomeType.CRITICAL_FAILURE]: 1.15,
17
+ [OutcomeType.FAILURE]: 1.1,
18
+ [OutcomeType.MINOR_FAILURE]: 1.08,
19
+ [OutcomeType.SUCCESS]: 0.97,
20
+ [OutcomeType.P1_INCIDENT]: 1.15,
21
+ [OutcomeType.P2_INCIDENT]: 1.1,
22
+ [OutcomeType.REGRESSION]: 1.08,
23
+ [OutcomeType.CLEAN_DEPLOY]: 0.97,
24
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * OutcomeBackPropagator — TypeScript port.
3
+ */
4
+ import type { AmfsAdapter } from "./adapter.js";
5
+ import type { MemoryEntry, OutcomeRecord } from "./models.js";
6
+ import { OutcomeType } from "./models.js";
7
+ export declare class OutcomeBackPropagator {
8
+ private adapter;
9
+ constructor(adapter: AmfsAdapter);
10
+ propagate(record: OutcomeRecord): MemoryEntry[];
11
+ propagateBatch(records: OutcomeRecord[]): MemoryEntry[];
12
+ static computeNewConfidence(currentConfidence: number, outcomeType: OutcomeType, causalConfidence?: number): number;
13
+ static makeRecord(outcomeRef: string, outcomeType: OutcomeType, causalEntryKeys: string[], agentId: string, options?: {
14
+ causalConfidence?: number;
15
+ committedAt?: string;
16
+ }): OutcomeRecord;
17
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * OutcomeBackPropagator — TypeScript port.
3
+ */
4
+ import { OUTCOME_MULTIPLIERS } from "./models.js";
5
+ export class OutcomeBackPropagator {
6
+ adapter;
7
+ constructor(adapter) {
8
+ this.adapter = adapter;
9
+ }
10
+ propagate(record) {
11
+ return this.adapter.commitOutcome(record);
12
+ }
13
+ propagateBatch(records) {
14
+ const allUpdated = [];
15
+ for (const record of records) {
16
+ allUpdated.push(...this.propagate(record));
17
+ }
18
+ return allUpdated;
19
+ }
20
+ static computeNewConfidence(currentConfidence, outcomeType, causalConfidence = 1.0) {
21
+ return currentConfidence * OUTCOME_MULTIPLIERS[outcomeType] * causalConfidence;
22
+ }
23
+ static makeRecord(outcomeRef, outcomeType, causalEntryKeys, agentId, options) {
24
+ return {
25
+ outcomeRef,
26
+ outcomeType,
27
+ causalConfidence: options?.causalConfidence ?? 1.0,
28
+ committedAt: options?.committedAt ?? new Date().toISOString(),
29
+ causalEntryKeys,
30
+ agentId,
31
+ };
32
+ }
33
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * ReadTracker — automatically records every read within a session for
3
+ * causal linking and conflict detection.
4
+ *
5
+ * TypeScript port of the Python ReadTracker from amfs-core.
6
+ */
7
+ import type { MemoryEntry } from "./models.js";
8
+ export interface ExternalContext {
9
+ label: string;
10
+ summary: string;
11
+ source?: string | null;
12
+ recordedAt: string;
13
+ }
14
+ export declare class ReadTracker {
15
+ private reads;
16
+ private versions;
17
+ private contexts;
18
+ /** Record that an entry was read during this session. */
19
+ record(entry: MemoryEntry): void;
20
+ /**
21
+ * Record external context that influenced decisions in this session.
22
+ * Included in the causal chain returned by explain().
23
+ */
24
+ recordContext(label: string, summary: string, options?: {
25
+ source?: string;
26
+ }): void;
27
+ /** All entry keys read in this session, ordered by read time. */
28
+ get causalKeys(): string[];
29
+ /** All external contexts recorded in this session, in order. */
30
+ get externalContexts(): ExternalContext[];
31
+ get readCount(): number;
32
+ /** Return the version we last read for an entry, or undefined if never read. */
33
+ readVersion(entryKey: string): number | undefined;
34
+ /** Reset the read log (e.g. between sub-tasks within a session). */
35
+ clear(): void;
36
+ contains(entryKey: string): boolean;
37
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * ReadTracker — automatically records every read within a session for
3
+ * causal linking and conflict detection.
4
+ *
5
+ * TypeScript port of the Python ReadTracker from amfs-core.
6
+ */
7
+ export class ReadTracker {
8
+ reads = new Map(); // entry_key -> ISO timestamp
9
+ versions = new Map(); // entry_key -> version
10
+ contexts = [];
11
+ /** Record that an entry was read during this session. */
12
+ record(entry) {
13
+ const entryKey = `${entry.entityPath}/${entry.key}`;
14
+ this.reads.set(entryKey, new Date().toISOString());
15
+ this.versions.set(entryKey, entry.version);
16
+ }
17
+ /**
18
+ * Record external context that influenced decisions in this session.
19
+ * Included in the causal chain returned by explain().
20
+ */
21
+ recordContext(label, summary, options) {
22
+ this.contexts.push({
23
+ label,
24
+ summary,
25
+ source: options?.source ?? null,
26
+ recordedAt: new Date().toISOString(),
27
+ });
28
+ }
29
+ /** All entry keys read in this session, ordered by read time. */
30
+ get causalKeys() {
31
+ return [...this.reads.entries()]
32
+ .sort(([, a], [, b]) => a.localeCompare(b))
33
+ .map(([k]) => k);
34
+ }
35
+ /** All external contexts recorded in this session, in order. */
36
+ get externalContexts() {
37
+ return [...this.contexts];
38
+ }
39
+ get readCount() {
40
+ return this.reads.size;
41
+ }
42
+ /** Return the version we last read for an entry, or undefined if never read. */
43
+ readVersion(entryKey) {
44
+ return this.versions.get(entryKey);
45
+ }
46
+ /** Reset the read log (e.g. between sub-tasks within a session). */
47
+ clear() {
48
+ this.reads.clear();
49
+ this.versions.clear();
50
+ this.contexts = [];
51
+ }
52
+ contains(entryKey) {
53
+ return this.reads.has(entryKey);
54
+ }
55
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@senselab-ai/amfs",
3
+ "version": "0.1.0",
4
+ "description": "AMFS TypeScript SDK — Agent Memory File System",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "test": "vitest run",
17
+ "test:watch": "vitest"
18
+ },
19
+ "dependencies": {},
20
+ "devDependencies": {
21
+ "typescript": "^5.4",
22
+ "vitest": "^3.1"
23
+ },
24
+ "files": ["dist"],
25
+ "license": "BSL-1.1"
26
+ }