@0xmaxma/claude-gateway 1.6.8 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +149 -20
- package/config.template.json +59 -1
- package/dist/agent/dreaming/accept.d.ts +43 -0
- package/dist/agent/dreaming/accept.d.ts.map +1 -0
- package/dist/agent/dreaming/accept.js +230 -0
- package/dist/agent/dreaming/accept.js.map +1 -0
- package/dist/agent/dreaming/applier.d.ts +77 -0
- package/dist/agent/dreaming/applier.d.ts.map +1 -0
- package/dist/agent/dreaming/applier.js +406 -0
- package/dist/agent/dreaming/applier.js.map +1 -0
- package/dist/agent/dreaming/audit.d.ts +27 -0
- package/dist/agent/dreaming/audit.d.ts.map +1 -0
- package/dist/agent/dreaming/audit.js +100 -0
- package/dist/agent/dreaming/audit.js.map +1 -0
- package/dist/agent/dreaming/compactor.d.ts +66 -0
- package/dist/agent/dreaming/compactor.d.ts.map +1 -0
- package/dist/agent/dreaming/compactor.js +306 -0
- package/dist/agent/dreaming/compactor.js.map +1 -0
- package/dist/agent/dreaming/config.d.ts +19 -0
- package/dist/agent/dreaming/config.d.ts.map +1 -0
- package/dist/agent/dreaming/config.js +107 -0
- package/dist/agent/dreaming/config.js.map +1 -0
- package/dist/agent/dreaming/episodic.d.ts +42 -0
- package/dist/agent/dreaming/episodic.d.ts.map +1 -0
- package/dist/agent/dreaming/episodic.js +116 -0
- package/dist/agent/dreaming/episodic.js.map +1 -0
- package/dist/agent/dreaming/gather.d.ts +31 -0
- package/dist/agent/dreaming/gather.d.ts.map +1 -0
- package/dist/agent/dreaming/gather.js +55 -0
- package/dist/agent/dreaming/gather.js.map +1 -0
- package/dist/agent/dreaming/index.d.ts +87 -0
- package/dist/agent/dreaming/index.d.ts.map +1 -0
- package/dist/agent/dreaming/index.js +377 -0
- package/dist/agent/dreaming/index.js.map +1 -0
- package/dist/agent/dreaming/migrate-cli.d.ts +17 -0
- package/dist/agent/dreaming/migrate-cli.d.ts.map +1 -0
- package/dist/agent/dreaming/migrate-cli.js +42 -0
- package/dist/agent/dreaming/migrate-cli.js.map +1 -0
- package/dist/agent/dreaming/migrate.d.ts +72 -0
- package/dist/agent/dreaming/migrate.d.ts.map +1 -0
- package/dist/agent/dreaming/migrate.js +374 -0
- package/dist/agent/dreaming/migrate.js.map +1 -0
- package/dist/agent/dreaming/report.d.ts +39 -0
- package/dist/agent/dreaming/report.d.ts.map +1 -0
- package/dist/agent/dreaming/report.js +121 -0
- package/dist/agent/dreaming/report.js.map +1 -0
- package/dist/agent/dreaming/reviewer.d.ts +43 -0
- package/dist/agent/dreaming/reviewer.d.ts.map +1 -0
- package/dist/agent/dreaming/reviewer.js +249 -0
- package/dist/agent/dreaming/reviewer.js.map +1 -0
- package/dist/agent/dreaming/staleness.d.ts +68 -0
- package/dist/agent/dreaming/staleness.d.ts.map +1 -0
- package/dist/agent/dreaming/staleness.js +281 -0
- package/dist/agent/dreaming/staleness.js.map +1 -0
- package/dist/agent/dreaming/types.d.ts +130 -0
- package/dist/agent/dreaming/types.d.ts.map +1 -0
- package/dist/agent/dreaming/types.js +10 -0
- package/dist/agent/dreaming/types.js.map +1 -0
- package/dist/agent/knowledge/archive-db.d.ts +114 -0
- package/dist/agent/knowledge/archive-db.d.ts.map +1 -0
- package/dist/agent/knowledge/archive-db.js +474 -0
- package/dist/agent/knowledge/archive-db.js.map +1 -0
- package/dist/agent/knowledge/chunk.d.ts +21 -0
- package/dist/agent/knowledge/chunk.d.ts.map +1 -0
- package/dist/agent/knowledge/chunk.js +67 -0
- package/dist/agent/knowledge/chunk.js.map +1 -0
- package/dist/agent/knowledge/config.d.ts +20 -0
- package/dist/agent/knowledge/config.d.ts.map +1 -0
- package/dist/agent/knowledge/config.js +143 -0
- package/dist/agent/knowledge/config.js.map +1 -0
- package/dist/agent/knowledge/graph-demo.d.ts +25 -0
- package/dist/agent/knowledge/graph-demo.d.ts.map +1 -0
- package/dist/agent/knowledge/graph-demo.js +132 -0
- package/dist/agent/knowledge/graph-demo.js.map +1 -0
- package/dist/agent/knowledge/index.d.ts +24 -0
- package/dist/agent/knowledge/index.d.ts.map +1 -0
- package/dist/agent/knowledge/index.js +50 -0
- package/dist/agent/knowledge/index.js.map +1 -0
- package/dist/agent/knowledge/indexer.d.ts +34 -0
- package/dist/agent/knowledge/indexer.d.ts.map +1 -0
- package/dist/agent/knowledge/indexer.js +271 -0
- package/dist/agent/knowledge/indexer.js.map +1 -0
- package/dist/agent/knowledge/lifecycle.d.ts +91 -0
- package/dist/agent/knowledge/lifecycle.d.ts.map +1 -0
- package/dist/agent/knowledge/lifecycle.js +205 -0
- package/dist/agent/knowledge/lifecycle.js.map +1 -0
- package/dist/agent/knowledge/provenance.d.ts +15 -0
- package/dist/agent/knowledge/provenance.d.ts.map +1 -0
- package/dist/agent/knowledge/provenance.js +37 -0
- package/dist/agent/knowledge/provenance.js.map +1 -0
- package/dist/agent/knowledge/reindex-cli.d.ts +13 -0
- package/dist/agent/knowledge/reindex-cli.d.ts.map +1 -0
- package/dist/agent/knowledge/reindex-cli.js +53 -0
- package/dist/agent/knowledge/reindex-cli.js.map +1 -0
- package/dist/agent/knowledge/reindex-spawn.d.ts +30 -0
- package/dist/agent/knowledge/reindex-spawn.d.ts.map +1 -0
- package/dist/agent/knowledge/reindex-spawn.js +97 -0
- package/dist/agent/knowledge/reindex-spawn.js.map +1 -0
- package/dist/agent/knowledge/shared-promote.d.ts +18 -0
- package/dist/agent/knowledge/shared-promote.d.ts.map +1 -0
- package/dist/agent/knowledge/shared-promote.js +29 -0
- package/dist/agent/knowledge/shared-promote.js.map +1 -0
- package/dist/agent/knowledge/shared-writer.d.ts +24 -0
- package/dist/agent/knowledge/shared-writer.d.ts.map +1 -0
- package/dist/agent/knowledge/shared-writer.js +97 -0
- package/dist/agent/knowledge/shared-writer.js.map +1 -0
- package/dist/agent/knowledge/types.d.ts +83 -0
- package/dist/agent/knowledge/types.d.ts.map +1 -0
- package/dist/agent/knowledge/types.js +12 -0
- package/dist/agent/knowledge/types.js.map +1 -0
- package/dist/agent/knowledge/wiki.d.ts +107 -0
- package/dist/agent/knowledge/wiki.d.ts.map +1 -0
- package/dist/agent/knowledge/wiki.js +415 -0
- package/dist/agent/knowledge/wiki.js.map +1 -0
- package/dist/agent/memory-metrics.d.ts +48 -0
- package/dist/agent/memory-metrics.d.ts.map +1 -0
- package/dist/agent/memory-metrics.js +156 -0
- package/dist/agent/memory-metrics.js.map +1 -0
- package/dist/agent/runner.d.ts +24 -1
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +82 -6
- package/dist/agent/runner.js.map +1 -1
- package/dist/agent/skill-learning/config.d.ts +18 -0
- package/dist/agent/skill-learning/config.d.ts.map +1 -0
- package/dist/agent/skill-learning/config.js +71 -0
- package/dist/agent/skill-learning/config.js.map +1 -0
- package/dist/agent/skill-learning/curator.d.ts +45 -0
- package/dist/agent/skill-learning/curator.d.ts.map +1 -0
- package/dist/agent/skill-learning/curator.js +171 -0
- package/dist/agent/skill-learning/curator.js.map +1 -0
- package/dist/agent/skill-learning/index.d.ts +79 -0
- package/dist/agent/skill-learning/index.d.ts.map +1 -0
- package/dist/agent/skill-learning/index.js +308 -0
- package/dist/agent/skill-learning/index.js.map +1 -0
- package/dist/agent/skill-learning/metrics.d.ts +13 -0
- package/dist/agent/skill-learning/metrics.d.ts.map +1 -0
- package/dist/agent/skill-learning/metrics.js +109 -0
- package/dist/agent/skill-learning/metrics.js.map +1 -0
- package/dist/agent/skill-learning/notifier.d.ts +111 -0
- package/dist/agent/skill-learning/notifier.d.ts.map +1 -0
- package/dist/agent/skill-learning/notifier.js +398 -0
- package/dist/agent/skill-learning/notifier.js.map +1 -0
- package/dist/agent/skill-learning/reviewer.d.ts +61 -0
- package/dist/agent/skill-learning/reviewer.d.ts.map +1 -0
- package/dist/agent/skill-learning/reviewer.js +271 -0
- package/dist/agent/skill-learning/reviewer.js.map +1 -0
- package/dist/agent/skill-learning/telemetry.d.ts +22 -0
- package/dist/agent/skill-learning/telemetry.d.ts.map +1 -0
- package/dist/agent/skill-learning/telemetry.js +90 -0
- package/dist/agent/skill-learning/telemetry.js.map +1 -0
- package/dist/agent/skill-learning/trigger.d.ts +23 -0
- package/dist/agent/skill-learning/trigger.d.ts.map +1 -0
- package/dist/agent/skill-learning/trigger.js +44 -0
- package/dist/agent/skill-learning/trigger.js.map +1 -0
- package/dist/agent/skill-learning/types.d.ts +165 -0
- package/dist/agent/skill-learning/types.d.ts.map +1 -0
- package/dist/agent/skill-learning/types.js +11 -0
- package/dist/agent/skill-learning/types.js.map +1 -0
- package/dist/agent/skill-learning/writer.d.ts +37 -0
- package/dist/agent/skill-learning/writer.d.ts.map +1 -0
- package/dist/agent/skill-learning/writer.js +223 -0
- package/dist/agent/skill-learning/writer.js.map +1 -0
- package/dist/agent/workspace-loader.d.ts +83 -6
- package/dist/agent/workspace-loader.d.ts.map +1 -1
- package/dist/agent/workspace-loader.js +207 -14
- package/dist/agent/workspace-loader.js.map +1 -1
- package/dist/api/gateway-router.d.ts +2 -0
- package/dist/api/gateway-router.d.ts.map +1 -1
- package/dist/api/gateway-router.js +293 -6
- package/dist/api/gateway-router.js.map +1 -1
- package/dist/api/share-router.d.ts.map +1 -1
- package/dist/api/share-router.js +27 -1
- package/dist/api/share-router.js.map +1 -1
- package/dist/api/skills-router.d.ts +2 -2
- package/dist/api/skills-router.d.ts.map +1 -1
- package/dist/api/skills-router.js +61 -1
- package/dist/api/skills-router.js.map +1 -1
- package/dist/apps/agent-manager.d.ts +7 -0
- package/dist/apps/agent-manager.d.ts.map +1 -1
- package/dist/apps/agent-manager.js +13 -1
- package/dist/apps/agent-manager.js.map +1 -1
- package/dist/config/migrator.d.ts +2 -0
- package/dist/config/migrator.d.ts.map +1 -1
- package/dist/config/migrator.js +72 -1
- package/dist/config/migrator.js.map +1 -1
- package/dist/history/cleanup.d.ts +7 -0
- package/dist/history/cleanup.d.ts.map +1 -1
- package/dist/history/cleanup.js +27 -0
- package/dist/history/cleanup.js.map +1 -1
- package/dist/history/db.d.ts +65 -0
- package/dist/history/db.d.ts.map +1 -1
- package/dist/history/db.js +261 -0
- package/dist/history/db.js.map +1 -1
- package/dist/index.js +122 -20
- package/dist/index.js.map +1 -1
- package/dist/session/process.d.ts +10 -0
- package/dist/session/process.d.ts.map +1 -1
- package/dist/session/process.js +86 -1
- package/dist/session/process.js.map +1 -1
- package/dist/share/share-store.d.ts +11 -0
- package/dist/share/share-store.d.ts.map +1 -1
- package/dist/share/share-store.js +3 -1
- package/dist/share/share-store.js.map +1 -1
- package/dist/skills/loader.d.ts +8 -0
- package/dist/skills/loader.d.ts.map +1 -1
- package/dist/skills/loader.js +29 -1
- package/dist/skills/loader.js.map +1 -1
- package/dist/types.d.ts +116 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/ui/web-ui.d.ts.map +1 -1
- package/dist/ui/web-ui.js +1126 -3
- package/dist/ui/web-ui.js.map +1 -1
- package/mcp/package.json +2 -1
- package/mcp/server.ts +2 -0
- package/mcp/tools/image/module.ts +114 -9
- package/mcp/tools/memory/archive-reader.test.ts +212 -0
- package/mcp/tools/memory/archive-reader.ts +253 -0
- package/mcp/tools/memory/module.ts +152 -0
- package/mcp/tools/memory/retrieval-recorder.ts +66 -0
- package/mcp/tools/shared/share-client.ts +20 -1
- package/mcp/tools/skills/module.ts +28 -0
- package/package.json +1 -1
- package/resource/claude_gateway.svg +1038 -112
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only reader for the per-agent knowledge archive (planning-64 K1).
|
|
3
|
+
*
|
|
4
|
+
* The archive `kb.sqlite` is BUILT by src/ under Node via `node:sqlite`
|
|
5
|
+
* (src/agent/knowledge). These MCP tools run under **Bun**, which has no
|
|
6
|
+
* `node:sqlite`, so the read path here uses **`bun:sqlite`** instead. Same
|
|
7
|
+
* on-disk SQLite/FTS5 file — verified that node:sqlite writes and bun:sqlite
|
|
8
|
+
* reads it back via `bm25()`. This is a deliberate, read-only mirror of the
|
|
9
|
+
* query half of `src/agent/knowledge/archive-db.ts`; keep the two in sync.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Database } from 'bun:sqlite';
|
|
13
|
+
import * as fs from 'fs';
|
|
14
|
+
import * as path from 'path';
|
|
15
|
+
import { recordRetrievalHits } from './retrieval-recorder';
|
|
16
|
+
|
|
17
|
+
export interface SearchHit {
|
|
18
|
+
path: string;
|
|
19
|
+
startLine: number;
|
|
20
|
+
endLine: number;
|
|
21
|
+
score: number; // bm25 (lower = more relevant); surfaced for transparency
|
|
22
|
+
snippet: string;
|
|
23
|
+
originClass: string | null;
|
|
24
|
+
importance: number | null;
|
|
25
|
+
/** Stable archive-entry identity (planning-66); null outside any entry block. */
|
|
26
|
+
entryHash: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Archive DB path for an agent: sibling of history.db at agents/<id>/kb.sqlite. */
|
|
30
|
+
export function archiveDbPath(workspaceDir: string): string {
|
|
31
|
+
return path.join(path.dirname(workspaceDir), 'kb.sqlite');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Shared, cross-agent vault DB path from the gateway-provided env
|
|
36
|
+
* (`GATEWAY_SHARED_KB_DIR` = the resolved <root>/<project> dir), or null when
|
|
37
|
+
* shared KB is disabled / not configured (planning-64 K3).
|
|
38
|
+
*/
|
|
39
|
+
export function sharedDbPathFromEnv(): string | null {
|
|
40
|
+
const dir = process.env.GATEWAY_SHARED_KB_DIR;
|
|
41
|
+
if (!dir || !dir.trim()) return null;
|
|
42
|
+
return path.join(dir, 'kb.sqlite');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Merge hit lists (per-agent + shared), keeping the best `limit`. bm25 scores are
|
|
47
|
+
* corpus-relative — the value depends on each index's term/document statistics —
|
|
48
|
+
* so scores from two independent FTS indexes are NOT on a comparable scale and a
|
|
49
|
+
* global sort can spuriously rank one corpus over the other. Each list is already
|
|
50
|
+
* sorted best-first within its own corpus, so interleave them round-robin for a
|
|
51
|
+
* fair blend instead of a cross-corpus numeric sort.
|
|
52
|
+
*/
|
|
53
|
+
export function mergeHits<T extends SearchHit>(a: T[], b: T[], limit: number): T[] {
|
|
54
|
+
const out: T[] = [];
|
|
55
|
+
const max = Math.max(a.length, b.length);
|
|
56
|
+
for (let i = 0; i < max && out.length < limit; i++) {
|
|
57
|
+
if (i < a.length) out.push(a[i]);
|
|
58
|
+
if (out.length < limit && i < b.length) out.push(b[i]);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Build an FTS5 MATCH string: quote each token so punctuation can't inject syntax. */
|
|
64
|
+
function toFtsMatch(query: string): string {
|
|
65
|
+
return query
|
|
66
|
+
.split(/[^\p{L}\p{N}_]+/u)
|
|
67
|
+
.filter(Boolean)
|
|
68
|
+
.map((t) => `"${t.replace(/"/g, '""')}"`)
|
|
69
|
+
.join(' ');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Keyword search over the archive (FTS5 BM25). Returns [] when the index does
|
|
74
|
+
* not exist yet or the query has no usable tokens. Read-only; never creates a DB.
|
|
75
|
+
*
|
|
76
|
+
* When `recordRetrievals` is set (planning-66), each returned entry's stable
|
|
77
|
+
* `entry_hash` is appended to `kb_retrieval_log` through a SEPARATE, dedicated
|
|
78
|
+
* writable handle AFTER the results are built — append-only and fire-and-forget,
|
|
79
|
+
* so the read path never read-modify-writes chunk rows and never blocks/locks the
|
|
80
|
+
* search response. The Node side folds this log into per-entry recency at GC time.
|
|
81
|
+
*/
|
|
82
|
+
/** True when kb_chunks carries the planning-66 `entry_hash` column. */
|
|
83
|
+
function hasEntryHashColumn(db: Database): boolean {
|
|
84
|
+
const cols = db.query(`PRAGMA table_info(kb_chunks)`).all() as Array<{ name: string }>;
|
|
85
|
+
return cols.some((c) => c.name === 'entry_hash');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Idempotent, best-effort heal for a pre-#346 archive DB. The `entry_hash`
|
|
90
|
+
* column is only added by the writer (`ArchiveDb` constructor migration); a
|
|
91
|
+
* `kb.sqlite` that has not been reindexed since #346 still lacks it, so the
|
|
92
|
+
* read-only search query below crashes with `no such column: entry_hash`. Add
|
|
93
|
+
* the column in place via a short writable handle (mirroring the recall-logging
|
|
94
|
+
* handle further down). A read-only filesystem simply skips — the column-aware
|
|
95
|
+
* query then falls back to a NULL `entryHash` so search still returns hits.
|
|
96
|
+
*/
|
|
97
|
+
function ensureEntryHashColumn(dbPath: string): void {
|
|
98
|
+
try {
|
|
99
|
+
const w = new Database(dbPath);
|
|
100
|
+
try {
|
|
101
|
+
w.exec('PRAGMA busy_timeout=2000');
|
|
102
|
+
if (!hasEntryHashColumn(w)) {
|
|
103
|
+
w.exec(`ALTER TABLE kb_chunks ADD COLUMN entry_hash TEXT`);
|
|
104
|
+
w.exec(`CREATE INDEX IF NOT EXISTS idx_kb_chunks_entry_hash ON kb_chunks(entry_hash)`);
|
|
105
|
+
}
|
|
106
|
+
} finally {
|
|
107
|
+
w.close();
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
/* read-only / locked DB — the column-aware query below degrades gracefully */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function searchArchive(
|
|
115
|
+
dbPath: string,
|
|
116
|
+
query: string,
|
|
117
|
+
maxResults: number,
|
|
118
|
+
opts?: { recordRetrievals?: boolean; now?: number },
|
|
119
|
+
): SearchHit[] {
|
|
120
|
+
if (!fs.existsSync(dbPath)) return [];
|
|
121
|
+
const match = toFtsMatch(query);
|
|
122
|
+
if (!match) return [];
|
|
123
|
+
|
|
124
|
+
// Heal pre-#346 DBs in place so the query never crashes on a missing column.
|
|
125
|
+
ensureEntryHashColumn(dbPath);
|
|
126
|
+
|
|
127
|
+
const db = new Database(dbPath, { readonly: true });
|
|
128
|
+
// If the heal above could not run (read-only FS), select a NULL entry_hash
|
|
129
|
+
// rather than referencing a column that does not exist.
|
|
130
|
+
const entryHashSelect = hasEntryHashColumn(db) ? 'c.entry_hash' : 'NULL';
|
|
131
|
+
let hits: SearchHit[];
|
|
132
|
+
try {
|
|
133
|
+
const rows = db
|
|
134
|
+
.query(
|
|
135
|
+
`SELECT c.id AS id, c.path AS path, c.start_line AS startLine, c.end_line AS endLine,
|
|
136
|
+
c.text AS text, ${entryHashSelect} AS entryHash, bm25(kb_chunks_fts) AS score,
|
|
137
|
+
p.origin_class AS originClass, r.importance AS importance
|
|
138
|
+
FROM kb_chunks_fts f
|
|
139
|
+
JOIN kb_chunks c ON c.rowid_id = f.rowid
|
|
140
|
+
LEFT JOIN kb_chunk_provenance p ON p.chunk_id = c.id
|
|
141
|
+
LEFT JOIN kb_chunk_recall r ON r.chunk_id = c.id
|
|
142
|
+
WHERE kb_chunks_fts MATCH ?
|
|
143
|
+
ORDER BY bm25(kb_chunks_fts)
|
|
144
|
+
LIMIT ?`,
|
|
145
|
+
)
|
|
146
|
+
.all(match, maxResults) as Array<{
|
|
147
|
+
path: string;
|
|
148
|
+
startLine: number;
|
|
149
|
+
endLine: number;
|
|
150
|
+
text: string;
|
|
151
|
+
entryHash: string | null;
|
|
152
|
+
score: number;
|
|
153
|
+
originClass: string | null;
|
|
154
|
+
importance: number | null;
|
|
155
|
+
}>;
|
|
156
|
+
hits = rows.map((r) => ({
|
|
157
|
+
path: r.path,
|
|
158
|
+
startLine: r.startLine,
|
|
159
|
+
endLine: r.endLine,
|
|
160
|
+
score: r.score,
|
|
161
|
+
snippet: r.text.length > 500 ? `${r.text.slice(0, 500)}…` : r.text,
|
|
162
|
+
originClass: r.originClass,
|
|
163
|
+
importance: r.importance,
|
|
164
|
+
entryHash: r.entryHash,
|
|
165
|
+
}));
|
|
166
|
+
} finally {
|
|
167
|
+
db.close();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Recall counter (planning-66): fire-and-forget, append-only, best-effort. A
|
|
171
|
+
// dedicated writable handle (WAL + busy_timeout so it never fails a concurrent
|
|
172
|
+
// reindex) logs the retrieved entries AFTER the read handle is closed. Any error
|
|
173
|
+
// is swallowed inside recordRetrievalHits — telemetry never fails a search.
|
|
174
|
+
if (opts?.recordRetrievals && hits.length > 0) {
|
|
175
|
+
try {
|
|
176
|
+
const w = new Database(dbPath);
|
|
177
|
+
try {
|
|
178
|
+
w.exec('PRAGMA busy_timeout=2000');
|
|
179
|
+
recordRetrievalHits(
|
|
180
|
+
{ run: (sql, params = []) => void w.query(sql).run(...(params as never[])) },
|
|
181
|
+
hits.map((h) => h.entryHash),
|
|
182
|
+
opts.now ?? Date.now(),
|
|
183
|
+
);
|
|
184
|
+
} finally {
|
|
185
|
+
w.close();
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
/* best-effort telemetry — never affect the search response */
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return hits;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A memory-scoped path: MEMORY.md, USER.md, or memory/**.md — no traversal. */
|
|
195
|
+
export function isMemoryScopedPath(relPath: string): boolean {
|
|
196
|
+
const p = relPath.replace(/\\/g, '/');
|
|
197
|
+
if (p.includes('..') || path.isAbsolute(p)) return false;
|
|
198
|
+
if (p === 'MEMORY.md' || p === 'USER.md') return true;
|
|
199
|
+
return p.startsWith('memory/') && p.endsWith('.md');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export interface Excerpt {
|
|
203
|
+
path: string;
|
|
204
|
+
from: number;
|
|
205
|
+
to: number;
|
|
206
|
+
text: string;
|
|
207
|
+
totalLines: number;
|
|
208
|
+
truncated: boolean;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Bounded exact excerpt of a memory file by line range (1-indexed). Reads the
|
|
213
|
+
* file directly (it is the source of truth). Returns null for an out-of-scope
|
|
214
|
+
* path or a missing file.
|
|
215
|
+
*/
|
|
216
|
+
export function getExcerpt(
|
|
217
|
+
workspaceDir: string,
|
|
218
|
+
relPath: string,
|
|
219
|
+
from = 1,
|
|
220
|
+
lines = 200,
|
|
221
|
+
): Excerpt | null {
|
|
222
|
+
// Validate and read the SAME normalized path so the check can't diverge from
|
|
223
|
+
// what is actually opened.
|
|
224
|
+
const rel = relPath.replace(/\\/g, '/');
|
|
225
|
+
if (!isMemoryScopedPath(rel)) return null;
|
|
226
|
+
const abs = path.join(workspaceDir, rel);
|
|
227
|
+
if (!fs.existsSync(abs)) return null;
|
|
228
|
+
// Containment against symlink escape: a memory/x.md symlink pointing outside
|
|
229
|
+
// the workspace passes the string check but must not be readable through the
|
|
230
|
+
// tool. Resolve real paths and require the target stays under the workspace.
|
|
231
|
+
try {
|
|
232
|
+
const realBase = fs.realpathSync(workspaceDir);
|
|
233
|
+
const realTarget = fs.realpathSync(abs);
|
|
234
|
+
if (realTarget !== realBase && !realTarget.startsWith(realBase + path.sep)) return null;
|
|
235
|
+
} catch {
|
|
236
|
+
return null; // realpath failed (broken symlink, race) → refuse
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const all = fs.readFileSync(abs, 'utf8').split('\n');
|
|
240
|
+
const total = all.length;
|
|
241
|
+
const start = Math.max(1, Math.floor(from));
|
|
242
|
+
const count = Math.max(1, Math.floor(lines));
|
|
243
|
+
const end = Math.min(total, start + count - 1);
|
|
244
|
+
const slice = start > total ? [] : all.slice(start - 1, end);
|
|
245
|
+
return {
|
|
246
|
+
path: relPath,
|
|
247
|
+
from: start,
|
|
248
|
+
to: start > total ? start : end,
|
|
249
|
+
text: slice.join('\n'),
|
|
250
|
+
totalLines: total,
|
|
251
|
+
truncated: end < total,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory tool module (planning-64 K1) — implements ToolModule.
|
|
3
|
+
*
|
|
4
|
+
* Read-only, on-demand retrieval over the per-agent knowledge archive
|
|
5
|
+
* (`kb.sqlite`, built by src/ under Node). Two lanes of memory: the small core
|
|
6
|
+
* (MEMORY.md/USER.md) is injected every turn; everything else lives in the
|
|
7
|
+
* searchable archive and is reached here via `memory_search` / `memory_get` —
|
|
8
|
+
* so the bulk never has to sit in the prompt. Runs under Bun; reads via
|
|
9
|
+
* `bun:sqlite` (see archive-reader.ts).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } from '../../types';
|
|
13
|
+
import { searchArchive, getExcerpt, archiveDbPath, sharedDbPathFromEnv, mergeHits } from './archive-reader';
|
|
14
|
+
|
|
15
|
+
/** Corpora the tool can serve. */
|
|
16
|
+
const SUPPORTED_CORPORA = new Set(['memory', 'shared', 'all']);
|
|
17
|
+
|
|
18
|
+
export class MemoryModule implements ToolModule {
|
|
19
|
+
id = 'memory';
|
|
20
|
+
toolVisibility: ToolVisibility = 'all-configured';
|
|
21
|
+
|
|
22
|
+
isEnabled(): boolean {
|
|
23
|
+
// Available whenever the agent's workspace dir is known (same gate as skills).
|
|
24
|
+
return Boolean(process.env.GATEWAY_WORKSPACE_DIR);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
getTools(): McpToolDefinition[] {
|
|
28
|
+
return [
|
|
29
|
+
{
|
|
30
|
+
name: 'memory_search',
|
|
31
|
+
description:
|
|
32
|
+
'Search your long-term memory archive (past notes under memory/, plus MEMORY.md/USER.md) by keyword and get the most relevant snippets with their file + line range. Use this to recall details that are NOT in the memory currently loaded into your context — the archive holds far more than fits in the prompt. Read-only.',
|
|
33
|
+
inputSchema: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
query: { type: 'string', description: 'Keywords to search for.' },
|
|
37
|
+
maxResults: {
|
|
38
|
+
type: 'number',
|
|
39
|
+
description: 'Max snippets to return (default 6, max 20).',
|
|
40
|
+
},
|
|
41
|
+
corpus: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
enum: ['memory', 'shared', 'all'],
|
|
44
|
+
description:
|
|
45
|
+
'Which corpus to search: "memory" (this agent, default), "shared" (the cross-agent shared KB), or "all" (both).',
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
required: ['query'],
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: 'memory_get',
|
|
54
|
+
description:
|
|
55
|
+
'Read an exact line range from one of your memory files (a path returned by memory_search, e.g. "memory/foo.md", or "MEMORY.md"/"USER.md"). Use after memory_search to pull the full context around a snippet. Read-only.',
|
|
56
|
+
inputSchema: {
|
|
57
|
+
type: 'object',
|
|
58
|
+
properties: {
|
|
59
|
+
path: { type: 'string', description: 'Memory-scoped path (memory/*.md, MEMORY.md, USER.md).' },
|
|
60
|
+
from: { type: 'number', description: '1-indexed start line (default 1).' },
|
|
61
|
+
lines: { type: 'number', description: 'Number of lines to return (default 200).' },
|
|
62
|
+
},
|
|
63
|
+
required: ['path'],
|
|
64
|
+
additionalProperties: false,
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async handleTool(name: string, args: Record<string, unknown>): Promise<McpToolResult> {
|
|
71
|
+
const workspaceDir = process.env.GATEWAY_WORKSPACE_DIR;
|
|
72
|
+
if (!workspaceDir) {
|
|
73
|
+
return this.err('Memory archive unavailable: no workspace directory configured.');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
switch (name) {
|
|
78
|
+
case 'memory_search': {
|
|
79
|
+
const query = typeof args.query === 'string' ? args.query.trim() : '';
|
|
80
|
+
if (!query) return this.err('memory_search requires a non-empty "query".');
|
|
81
|
+
|
|
82
|
+
// Fail closed on an unsupported corpus rather than silently widening scope.
|
|
83
|
+
const corpus = typeof args.corpus === 'string' ? args.corpus : 'memory';
|
|
84
|
+
if (!SUPPORTED_CORPORA.has(corpus)) {
|
|
85
|
+
return this.json({
|
|
86
|
+
results: [],
|
|
87
|
+
unavailable: true,
|
|
88
|
+
warning: `corpus "${corpus}" is not available yet (shared/all arrive in a later phase). Use "memory".`,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const rawMax = Number.isFinite(args.maxResults as number) ? (args.maxResults as number) : 6;
|
|
93
|
+
const maxResults = Math.max(1, Math.min(20, Math.floor(rawMax)));
|
|
94
|
+
|
|
95
|
+
const personalDb = archiveDbPath(workspaceDir);
|
|
96
|
+
const sharedDb = sharedDbPathFromEnv();
|
|
97
|
+
// Recall counter (planning-66): record retrievals ONLY against the
|
|
98
|
+
// per-agent archive (the GC tier). Gated by the gateway via env, mirroring
|
|
99
|
+
// GATEWAY_SHARED_KB_DIR — off unless dreaming.staleness.recordRetrievals.
|
|
100
|
+
const rec = { recordRetrievals: process.env.GATEWAY_RECORD_RETRIEVALS === '1' };
|
|
101
|
+
let results;
|
|
102
|
+
if (corpus === 'memory') {
|
|
103
|
+
results = searchArchive(personalDb, query, maxResults, rec).map((h) => ({ ...h, corpus: 'memory' }));
|
|
104
|
+
} else if (corpus === 'shared') {
|
|
105
|
+
if (!sharedDb) return this.json({ results: [], unavailable: true, warning: 'shared KB is not enabled.' });
|
|
106
|
+
results = searchArchive(sharedDb, query, maxResults).map((h) => ({ ...h, corpus: 'shared' }));
|
|
107
|
+
} else {
|
|
108
|
+
// "all": merge personal + shared, keep the best by bm25.
|
|
109
|
+
type Tagged = ReturnType<typeof searchArchive>[number] & { corpus: string };
|
|
110
|
+
const mine: Tagged[] = searchArchive(personalDb, query, maxResults, rec).map((h) => ({ ...h, corpus: 'memory' }));
|
|
111
|
+
const shared: Tagged[] = sharedDb
|
|
112
|
+
? searchArchive(sharedDb, query, maxResults).map((h) => ({ ...h, corpus: 'shared' }))
|
|
113
|
+
: [];
|
|
114
|
+
results = mergeHits(mine, shared, maxResults);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (results.length === 0) {
|
|
118
|
+
return this.json({
|
|
119
|
+
results: [],
|
|
120
|
+
note: 'No matches (or the archive has not been indexed yet).',
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return this.json({ results, corpus });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
case 'memory_get': {
|
|
127
|
+
const p = typeof args.path === 'string' ? args.path : '';
|
|
128
|
+
const from = Number.isFinite(args.from as number) ? (args.from as number) : 1;
|
|
129
|
+
const lines = Number.isFinite(args.lines as number) ? (args.lines as number) : 200;
|
|
130
|
+
const excerpt = getExcerpt(workspaceDir, p, from, lines);
|
|
131
|
+
if (!excerpt) {
|
|
132
|
+
return this.err(`memory_get: "${p}" is not a readable memory-scoped file (memory/*.md, MEMORY.md, USER.md).`);
|
|
133
|
+
}
|
|
134
|
+
return this.json(excerpt);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
default:
|
|
138
|
+
return this.err(`Unknown memory tool: ${name}`);
|
|
139
|
+
}
|
|
140
|
+
} catch (e) {
|
|
141
|
+
return this.err(`memory tool error: ${e instanceof Error ? e.message : String(e)}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private json(obj: unknown): McpToolResult {
|
|
146
|
+
return { content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }] };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private err(text: string): McpToolResult {
|
|
150
|
+
return { content: [{ type: 'text', text }], isError: true };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime-agnostic append-only retrieval recorder (planning-66).
|
|
3
|
+
*
|
|
4
|
+
* The read path (`archive-reader.ts`) runs under Bun (`bun:sqlite`); the tests and
|
|
5
|
+
* the src/ aggregator run under Node (`node:sqlite`). Both need to write the SAME
|
|
6
|
+
* append-only `kb_retrieval_log` table, so the actual SQL lives here behind a tiny
|
|
7
|
+
* `SqlRunner` seam that each runtime adapts to its own driver. This file imports
|
|
8
|
+
* NO sqlite driver, so it is safe to import from a Node/jest test (importing
|
|
9
|
+
* `archive-reader.ts` directly is not — it top-level-imports `bun:sqlite`).
|
|
10
|
+
*
|
|
11
|
+
* The recall counter is deliberately APPEND-ONLY and fire-and-forget: the Bun read
|
|
12
|
+
* path must never read-modify-write chunk rows (that would break the "mcp reads
|
|
13
|
+
* only / src writes" invariant and risk locking the hot search path). It only ever
|
|
14
|
+
* INSERTs into a dedicated log table; the Node side aggregates that log into
|
|
15
|
+
* `kb_entry_lifecycle.last_retrieved`/`retrieval_count` at GC time.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Minimal write surface both `bun:sqlite` and `node:sqlite` can satisfy. */
|
|
19
|
+
export interface SqlRunner {
|
|
20
|
+
run(sql: string, params?: unknown[]): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** DDL for the append-only retrieval log. Idempotent; safe to call every write. */
|
|
24
|
+
export const RETRIEVAL_LOG_DDL =
|
|
25
|
+
'CREATE TABLE IF NOT EXISTS kb_retrieval_log (' +
|
|
26
|
+
'rowid_id INTEGER PRIMARY KEY AUTOINCREMENT, entry_hash TEXT NOT NULL, retrieved_at INTEGER NOT NULL)';
|
|
27
|
+
|
|
28
|
+
/** Ensure the log table exists (the Bun side may run before any Node index pass). */
|
|
29
|
+
export function ensureRetrievalLog(db: SqlRunner): void {
|
|
30
|
+
db.run(RETRIEVAL_LOG_DDL);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Append one retrieval event, keyed by the STABLE `entry_hash` (never the line-
|
|
35
|
+
* based chunk id). Best-effort: a null/empty hash is ignored (a chunk outside any
|
|
36
|
+
* entry block carries no lifecycle identity). Callers wrap this in try/catch and
|
|
37
|
+
* never block their response on it.
|
|
38
|
+
*/
|
|
39
|
+
export function appendRetrieval(db: SqlRunner, entryHash: string | null | undefined, retrievedAt: number): void {
|
|
40
|
+
if (!entryHash) return;
|
|
41
|
+
ensureRetrievalLog(db);
|
|
42
|
+
db.run('INSERT INTO kb_retrieval_log (entry_hash, retrieved_at) VALUES (?, ?)', [entryHash, retrievedAt]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Record a batch of retrieval hits (the entry_hashes of one search's results),
|
|
47
|
+
* de-duplicated so a single search that returns two chunks of the same entry
|
|
48
|
+
* counts once. Fire-and-forget; never throws out (errors are swallowed so a
|
|
49
|
+
* telemetry write can never fail a search response).
|
|
50
|
+
*/
|
|
51
|
+
export function recordRetrievalHits(
|
|
52
|
+
db: SqlRunner,
|
|
53
|
+
entryHashes: Array<string | null | undefined>,
|
|
54
|
+
retrievedAt: number,
|
|
55
|
+
): void {
|
|
56
|
+
try {
|
|
57
|
+
const seen = new Set<string>();
|
|
58
|
+
for (const h of entryHashes) {
|
|
59
|
+
if (!h || seen.has(h)) continue;
|
|
60
|
+
seen.add(h);
|
|
61
|
+
appendRetrieval(db, h, retrievedAt);
|
|
62
|
+
}
|
|
63
|
+
} catch {
|
|
64
|
+
/* best-effort telemetry — never affect the search response */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -12,7 +12,26 @@ const REQUEST_TIMEOUT_MS = 15_000;
|
|
|
12
12
|
|
|
13
13
|
export type ShareRef = { artifact_id?: string; path?: string };
|
|
14
14
|
|
|
15
|
-
export type ShareItem = {
|
|
15
|
+
export type ShareItem = {
|
|
16
|
+
share_id: string;
|
|
17
|
+
token: string;
|
|
18
|
+
url?: string;
|
|
19
|
+
expires_at: string;
|
|
20
|
+
/** Present only when this share was minted from an artifact_id ref whose
|
|
21
|
+
* generation recorded a provider task id — the hook a resume-capable
|
|
22
|
+
* provider needs to continue that generation's session. Duplicated from
|
|
23
|
+
* ArtifactRow
|
|
24
|
+
* (src/share/share-store.ts) rather than imported — this file must stay
|
|
25
|
+
* self-contained (see the module comment above). */
|
|
26
|
+
task_id?: string;
|
|
27
|
+
provider?: string;
|
|
28
|
+
/** The prompt that produced this artifact, when recorded
|
|
29
|
+
* (handoff-on-model-switch) — deterministic reuse source for continuing
|
|
30
|
+
* an edit across a model switch where session resume isn't possible.
|
|
31
|
+
* Independent of task_id: present even when resume isn't. Duplicated from
|
|
32
|
+
* ArtifactRow rather than imported — see the module comment above. */
|
|
33
|
+
prior_prompt?: string;
|
|
34
|
+
};
|
|
16
35
|
|
|
17
36
|
export type ArtifactItem = { artifact_id: string; artifact_ref: string; index: number; path: string };
|
|
18
37
|
|
|
@@ -108,6 +108,15 @@ export class SkillsModule implements ToolModule {
|
|
|
108
108
|
additionalProperties: false,
|
|
109
109
|
},
|
|
110
110
|
},
|
|
111
|
+
{
|
|
112
|
+
name: 'skill_metrics',
|
|
113
|
+
description: 'Read the skill self-improvement effectiveness rollup for this agent: adoption funnel (auto-skill stickiness), cost-to-complete deltas, recovery-rate trend, enabled/disabled cohort, and the net-token ledger (tokens saved by reuse minus tokens spent reviewing). Read-only.',
|
|
114
|
+
inputSchema: {
|
|
115
|
+
type: 'object',
|
|
116
|
+
properties: {},
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
},
|
|
119
|
+
},
|
|
111
120
|
];
|
|
112
121
|
}
|
|
113
122
|
|
|
@@ -152,6 +161,25 @@ export class SkillsModule implements ToolModule {
|
|
|
152
161
|
const result = await installSkill(params);
|
|
153
162
|
return { content: [{ type: 'text', text: result }] };
|
|
154
163
|
}
|
|
164
|
+
case 'skill_metrics': {
|
|
165
|
+
const apiUrl = (process.env.GATEWAY_API_URL || '').replace(/\/+$/, '');
|
|
166
|
+
const apiKey = process.env.GATEWAY_API_KEY;
|
|
167
|
+
const agentId = process.env.GATEWAY_AGENT_ID;
|
|
168
|
+
if (!apiUrl || !apiKey || !agentId) {
|
|
169
|
+
return {
|
|
170
|
+
content: [{ type: 'text', text: 'skill_metrics unavailable: gateway API env not configured' }],
|
|
171
|
+
isError: true,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const res = await fetch(`${apiUrl}/api/v1/agents/${encodeURIComponent(agentId)}/skill-metrics`, {
|
|
175
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
176
|
+
});
|
|
177
|
+
const body = await res.text();
|
|
178
|
+
if (!res.ok) {
|
|
179
|
+
return { content: [{ type: 'text', text: `skill_metrics failed (${res.status}): ${body}` }], isError: true };
|
|
180
|
+
}
|
|
181
|
+
return { content: [{ type: 'text', text: body }] };
|
|
182
|
+
}
|
|
155
183
|
default:
|
|
156
184
|
return { content: [{ type: 'text', text: `unknown tool: ${name}` }], isError: true };
|
|
157
185
|
}
|