agent-memory-hub 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/cli.d.ts +45 -0
  4. package/dist/cli.js +736 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/core/approval.d.ts +23 -0
  7. package/dist/core/approval.js +18 -0
  8. package/dist/core/approval.js.map +1 -0
  9. package/dist/core/atomic.d.ts +6 -0
  10. package/dist/core/atomic.js +37 -0
  11. package/dist/core/atomic.js.map +1 -0
  12. package/dist/core/errors.d.ts +17 -0
  13. package/dist/core/errors.js +22 -0
  14. package/dist/core/errors.js.map +1 -0
  15. package/dist/core/extract.d.ts +48 -0
  16. package/dist/core/extract.js +71 -0
  17. package/dist/core/extract.js.map +1 -0
  18. package/dist/core/frontmatter.d.ts +26 -0
  19. package/dist/core/frontmatter.js +310 -0
  20. package/dist/core/frontmatter.js.map +1 -0
  21. package/dist/core/hub.d.ts +25 -0
  22. package/dist/core/hub.js +151 -0
  23. package/dist/core/hub.js.map +1 -0
  24. package/dist/core/ids.d.ts +13 -0
  25. package/dist/core/ids.js +45 -0
  26. package/dist/core/ids.js.map +1 -0
  27. package/dist/core/inject.d.ts +44 -0
  28. package/dist/core/inject.js +62 -0
  29. package/dist/core/inject.js.map +1 -0
  30. package/dist/core/journal.d.ts +25 -0
  31. package/dist/core/journal.js +73 -0
  32. package/dist/core/journal.js.map +1 -0
  33. package/dist/core/ledger.d.ts +32 -0
  34. package/dist/core/ledger.js +35 -0
  35. package/dist/core/ledger.js.map +1 -0
  36. package/dist/core/lock.d.ts +51 -0
  37. package/dist/core/lock.js +109 -0
  38. package/dist/core/lock.js.map +1 -0
  39. package/dist/core/registry.d.ts +44 -0
  40. package/dist/core/registry.js +89 -0
  41. package/dist/core/registry.js.map +1 -0
  42. package/dist/core/search.d.ts +59 -0
  43. package/dist/core/search.js +189 -0
  44. package/dist/core/search.js.map +1 -0
  45. package/dist/core/store.d.ts +89 -0
  46. package/dist/core/store.js +296 -0
  47. package/dist/core/store.js.map +1 -0
  48. package/dist/core/time.d.ts +5 -0
  49. package/dist/core/time.js +21 -0
  50. package/dist/core/time.js.map +1 -0
  51. package/dist/core/transcript.d.ts +42 -0
  52. package/dist/core/transcript.js +77 -0
  53. package/dist/core/transcript.js.map +1 -0
  54. package/dist/core/types.d.ts +47 -0
  55. package/dist/core/types.js +10 -0
  56. package/dist/core/types.js.map +1 -0
  57. package/dist/core/validate.d.ts +19 -0
  58. package/dist/core/validate.js +94 -0
  59. package/dist/core/validate.js.map +1 -0
  60. package/dist/index.d.ts +34 -0
  61. package/dist/index.js +36 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/transport/autocommit.d.ts +11 -0
  64. package/dist/transport/autocommit.js +25 -0
  65. package/dist/transport/autocommit.js.map +1 -0
  66. package/dist/transport/http.d.ts +13 -0
  67. package/dist/transport/http.js +56 -0
  68. package/dist/transport/http.js.map +1 -0
  69. package/dist/transport/mcp.d.ts +27 -0
  70. package/dist/transport/mcp.js +498 -0
  71. package/dist/transport/mcp.js.map +1 -0
  72. package/dist/transport/panel.d.ts +8 -0
  73. package/dist/transport/panel.js +207 -0
  74. package/dist/transport/panel.js.map +1 -0
  75. package/dist/transport/server.d.ts +23 -0
  76. package/dist/transport/server.js +349 -0
  77. package/dist/transport/server.js.map +1 -0
  78. package/package.json +60 -4
@@ -0,0 +1,498 @@
1
+ import { appendFileSync, readFileSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ErrorCode, HubError } from '../core/errors.js';
4
+ import { isHubInitialized, readHubConfig } from '../core/hub.js';
5
+ import { appendLedger, ledgerPath, readSequences, writeSequences, } from '../core/ledger.js';
6
+ import { acquireLock, assertFencing, heartbeatLock, lockInfo, releaseLock, } from '../core/lock.js';
7
+ import { registerWorkspace, resolveWorkspace } from '../core/registry.js';
8
+ import { buildIndex, emptyMetrics, searchWithMetrics, } from '../core/search.js';
9
+ import { commitKnowledge, createProposal, findTitleConflict, getEntry, listProposals, } from '../core/store.js';
10
+ import { requireApproval } from '../core/approval.js';
11
+ import { preflight } from '../core/inject.js';
12
+ import { appendJournal, readJournal } from '../core/journal.js';
13
+ import { detectDejaVu, indexTranscript, readTranscriptIndex } from '../core/transcript.js';
14
+ /**
15
+ * MCP stdio transport — zero-dependency JSON-RPC 2.0. The protocol surface is
16
+ * small (initialize / tools/list / tools/call), so we implement it directly
17
+ * (dependency policy) with the same tool contract as the CLI (one behavior,
18
+ * one implementation — tests are shared).
19
+ */
20
+ const SUPPORTED_PROTOCOL_VERSIONS = ['2024-11-05', '2025-03-26', '2025-06-18'];
21
+ const SERVER_INFO = { name: 'memhub', version: '0.1.0' };
22
+ export function createState(hubRoot, workspaceArg) {
23
+ if (!isHubInitialized(hubRoot)) {
24
+ throw new HubError(ErrorCode.E_HUB_NOT_INITIALIZED, `hub not initialized at ${hubRoot} — run \`memhub init --root ${hubRoot}\``, { hubRoot });
25
+ }
26
+ const workspace = resolveWorkspace(process.cwd(), workspaceArg);
27
+ const index = buildIndex(hubRoot, () => new Date().toISOString());
28
+ return { hubRoot, workspace, index, metrics: emptyMetrics(index) };
29
+ }
30
+ export const TOOLS = {
31
+ memory_search: {
32
+ description: 'Search accepted knowledge by keywords or a natural-language intent. Scope-filtered: the workspace sees itself + global. Ranked results; default detail (L1) returns summaries — pass detail=L2 only when the full body is needed.',
33
+ inputSchema: {
34
+ type: 'object',
35
+ properties: {
36
+ query: { type: 'string' },
37
+ detail: { type: 'string', enum: ['L0', 'L1', 'L2'] },
38
+ limit: { type: 'number' },
39
+ minScore: { type: 'number' },
40
+ types: { type: 'array', items: { type: 'string' } },
41
+ },
42
+ required: ['query'],
43
+ },
44
+ handler: (state, args) => {
45
+ const hits = searchWithMetrics(state.index, state.metrics, String(args['query']), {
46
+ workspaceId: state.workspace.workspaceId,
47
+ detail: args['detail'] ?? 'L1',
48
+ limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,
49
+ minScore: typeof args['minScore'] === 'number' ? args['minScore'] : 0,
50
+ types: args['types'],
51
+ });
52
+ return {
53
+ hits,
54
+ workspace: workspaceStatus(state.workspace),
55
+ metrics: metricsSnapshot(state.metrics),
56
+ };
57
+ },
58
+ },
59
+ memory_get: {
60
+ description: 'Read one knowledge entry by ID. Returns metadata + summary by default; pass full=true (or section=<heading>) only when the whole body is needed.',
61
+ inputSchema: {
62
+ type: 'object',
63
+ properties: {
64
+ id: { type: 'string' },
65
+ full: { type: 'boolean' },
66
+ section: { type: 'string' },
67
+ },
68
+ required: ['id'],
69
+ },
70
+ handler: (state, args) => {
71
+ const entry = getEntry(state.hubRoot, String(args['id']));
72
+ const full = args['full'] === true;
73
+ const section = typeof args['section'] === 'string' ? args['section'] : undefined;
74
+ let body;
75
+ if (section !== undefined) {
76
+ const marker = `# ${section}`;
77
+ const start = entry.body.indexOf(marker);
78
+ body = start === -1 ? undefined : entry.body.slice(start, entry.body.indexOf('\n# ', start + 1));
79
+ }
80
+ else if (full) {
81
+ body = entry.body;
82
+ }
83
+ return { frontmatter: entry.frontmatter, body, path: entry.path };
84
+ },
85
+ },
86
+ memory_status: {
87
+ description: 'Read-only self check: hub root, workspace identity (exact flag is honest — false means synthetic fallback), writer lock holder, metrics, pending count, DATA FRESHNESS (when this hub last pulled from / published to the remote). Runtime tools never need the remote — if it is down, search/propose/approve keep working; only cross-team NEW knowledge visibility pauses until the next pull.',
88
+ inputSchema: { type: 'object', properties: {} },
89
+ handler: (state) => ({
90
+ hubRoot: state.hubRoot,
91
+ initialized: true,
92
+ workspace: workspaceStatus(state.workspace),
93
+ lock: lockInfo(state.hubRoot),
94
+ metrics: metricsSnapshot(state.metrics),
95
+ proposals: listProposals(state.hubRoot).length,
96
+ freshness: readFreshness(state.hubRoot),
97
+ }),
98
+ },
99
+ memory_propose: {
100
+ description: 'Create a pending candidate (pending/PRO-*.md). This NEVER writes knowledge/ directly — a human must approve via the panel or `memhub inbox`. Always include sourceRefs evidence. To RE-EXTRACT an existing entry (e.g. generalize an environment-specific flow), pass supersedes: [entryId] — approval upgrades that entry\'s version instead of creating a duplicate.',
101
+ inputSchema: {
102
+ type: 'object',
103
+ properties: {
104
+ type: {
105
+ type: 'string',
106
+ enum: ['decision', 'constraint', 'knowledge', 'api-catalog', 'process', 'open-questions', 'runtime-base', 'playbooks', 'assets'],
107
+ },
108
+ title: { type: 'string' },
109
+ summary: { type: 'string' },
110
+ tags: { type: 'array', items: { type: 'string' } },
111
+ body: { type: 'string' },
112
+ sourceRefs: { type: 'array', items: { type: 'string' } },
113
+ supersedes: { type: 'array', items: { type: 'string' }, description: 'Entry id(s) this proposal re-extracts; approval upgrades their version.' },
114
+ },
115
+ required: ['type', 'title', 'summary', 'body'],
116
+ },
117
+ handler: (state, args) => withWriteLock(state, () => {
118
+ const supersedes = args['supersedes'];
119
+ const proposal = createProposal(state.hubRoot, {
120
+ type: args['type'],
121
+ title: String(args['title']),
122
+ summary: String(args['summary']),
123
+ scope: scopeFor(state.workspace),
124
+ tags: args['tags'],
125
+ body: String(args['body']),
126
+ sourceRefs: args['sourceRefs'] ?? [],
127
+ ...(supersedes !== undefined && supersedes.length > 0 ? { supersedes } : {}),
128
+ actor: 'model',
129
+ }, {
130
+ readSequences,
131
+ writeSequences,
132
+ appendLedger: (root, record) => appendLedger(ledgerPath(root), record),
133
+ });
134
+ registerWorkspaceIfNew(state);
135
+ return {
136
+ proposalId: proposal.id,
137
+ path: proposal.path,
138
+ nextStep: 'human approval via panel or `memhub inbox approve`',
139
+ };
140
+ }),
141
+ },
142
+ memory_commit: {
143
+ description: 'Move an approved candidate into knowledge/. Only a human-carried channel can pass: over MCP this tool ALWAYS fails closed with E_APPROVAL_REQUIRED — use the panel or `memhub inbox approve <ID>`.',
144
+ inputSchema: {
145
+ type: 'object',
146
+ properties: {
147
+ proposalId: { type: 'string' },
148
+ channel: { type: 'string' },
149
+ },
150
+ required: ['proposalId'],
151
+ },
152
+ handler: (state, args) => withWriteLock(state, () => {
153
+ const proposalId = String(args['proposalId']);
154
+ requireApproval(args['channel'] ?? 'mcp-model', {
155
+ id: proposalId,
156
+ ledgerAppend: (record) => appendLedger(ledgerPath(state.hubRoot), record),
157
+ });
158
+ return commitFromProposal(state, proposalId);
159
+ }),
160
+ },
161
+ memory_cite: {
162
+ description: 'Record that a knowledge entry influenced the current task (audit + aging signal). Cite after actually using an entry — search hits are not citations.',
163
+ inputSchema: {
164
+ type: 'object',
165
+ properties: {
166
+ id: { type: 'string' },
167
+ purpose: { type: 'string' },
168
+ },
169
+ required: ['id', 'purpose'],
170
+ },
171
+ handler: (state, args) => {
172
+ const id = String(args['id']);
173
+ getEntry(state.hubRoot, id); // must exist
174
+ appendLedger(ledgerPath(state.hubRoot), {
175
+ type: 'citation.added',
176
+ id,
177
+ purpose: String(args['purpose']),
178
+ at: new Date().toISOString(),
179
+ });
180
+ return { cited: id };
181
+ },
182
+ },
183
+ memory_close_task: {
184
+ description: 'Close the current task with a writeback assessment (proposed / no_new_knowledge / needs_evidence / deferred). Bookkeeping only.',
185
+ inputSchema: {
186
+ type: 'object',
187
+ properties: {
188
+ assessment: { type: 'string', enum: ['proposed', 'no_new_knowledge', 'needs_evidence', 'deferred'] },
189
+ note: { type: 'string' },
190
+ },
191
+ required: ['assessment'],
192
+ },
193
+ handler: (state, args) => {
194
+ appendLedger(ledgerPath(state.hubRoot), {
195
+ type: 'task.closed',
196
+ assessment: args['assessment'],
197
+ note: typeof args['note'] === 'string' ? args['note'] : undefined,
198
+ at: new Date().toISOString(),
199
+ });
200
+ return { closed: true };
201
+ },
202
+ },
203
+ memory_duplicates: {
204
+ description: 'Read-only near-duplicate check for a candidate title. Never writes files.',
205
+ inputSchema: {
206
+ type: 'object',
207
+ properties: { title: { type: 'string' } },
208
+ required: ['title'],
209
+ },
210
+ handler: (state, args) => {
211
+ const conflict = findTitleConflict(state.hubRoot, String(args['title']));
212
+ return {
213
+ conflict: conflict === null ? null : { id: conflict.frontmatter.id, title: conflict.frontmatter.title },
214
+ };
215
+ },
216
+ },
217
+ memory_preflight: {
218
+ description: 'Build the L0 static pack for this turn: top-3 hits (replay-calibrated), one line each, with a documented token estimate. Records a preflight.recorded event. Inject the pack only when status=ready.',
219
+ inputSchema: {
220
+ type: 'object',
221
+ properties: {
222
+ intent: { type: 'string' },
223
+ limit: { type: 'number' },
224
+ types: { type: 'array', items: { type: 'string' } },
225
+ },
226
+ required: ['intent'],
227
+ },
228
+ handler: (state, args) => {
229
+ const result = preflight(state.index, state.hubRoot, state.workspace.workspaceId, String(args['intent']), {
230
+ limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,
231
+ types: args['types'],
232
+ });
233
+ state.metrics.queryCount += 1;
234
+ return result;
235
+ },
236
+ },
237
+ memory_journal: {
238
+ description: 'Episodic layer: append (action=append; auto-capture is fine here — journal is disposable and never becomes knowledge) or read (action=read; optional day=YYYY-MM-DD local stamp).',
239
+ inputSchema: {
240
+ type: 'object',
241
+ properties: {
242
+ action: { type: 'string', enum: ['append', 'read'] },
243
+ text: { type: 'string' },
244
+ sessionId: { type: 'string' },
245
+ day: { type: 'string' },
246
+ },
247
+ required: ['action'],
248
+ },
249
+ handler: (state, args) => {
250
+ const action = String(args['action']);
251
+ if (action === 'append') {
252
+ const text = String(args['text'] ?? '');
253
+ if (text === '')
254
+ throw new HubError(ErrorCode.E_VALIDATION, 'journal append requires text');
255
+ return withWriteLock(state, () => appendJournal(state.hubRoot, { sessionId: args['sessionId'], text }));
256
+ }
257
+ return { entries: readJournal(state.hubRoot, args['day']) };
258
+ },
259
+ },
260
+ memory_dejavu: {
261
+ description: 'Day-zero deja-vu check: was a similar conversation already had? Index a session transcript (action=index; tokens + preview only — the body stays with the host) or query overlaps (action=check).',
262
+ inputSchema: {
263
+ type: 'object',
264
+ properties: {
265
+ action: { type: 'string', enum: ['index', 'check'] },
266
+ sessionId: { type: 'string' },
267
+ text: { type: 'string' },
268
+ location: { type: 'string' },
269
+ query: { type: 'string' },
270
+ threshold: { type: 'number' },
271
+ },
272
+ required: ['action'],
273
+ },
274
+ handler: (state, args) => {
275
+ const action = String(args['action']);
276
+ if (action === 'index') {
277
+ const sessionId = args['sessionId'];
278
+ const text = String(args['text'] ?? '');
279
+ const location = String(args['location'] ?? '');
280
+ if (sessionId === undefined || text === '' || location === '') {
281
+ throw new HubError(ErrorCode.E_VALIDATION, 'dejavu index requires sessionId, text and location');
282
+ }
283
+ return withWriteLock(state, () => indexTranscript(state.hubRoot, { sessionId, text, location }));
284
+ }
285
+ const query = String(args['query'] ?? '');
286
+ if (query === '')
287
+ throw new HubError(ErrorCode.E_VALIDATION, 'dejavu check requires query');
288
+ return {
289
+ sessions: readTranscriptIndex(state.hubRoot).length,
290
+ dejaVu: detectDejaVu(state.hubRoot, query, typeof args['threshold'] === 'number' ? args['threshold'] : undefined),
291
+ };
292
+ },
293
+ },
294
+ };
295
+ // ---------------------------------------------------------------------------
296
+ // Write-lock + helpers
297
+ // ---------------------------------------------------------------------------
298
+ function withWriteLock(state, fn) {
299
+ const acquired = acquireLock(state.hubRoot);
300
+ if (!acquired.ok) {
301
+ throw new HubError(ErrorCode.E_READONLY, 'another writer holds the lease (read-only for this process)', {
302
+ holder: acquired.holder,
303
+ });
304
+ }
305
+ // acquired.ok guarantees a lock with a token; '' would fail fencing loudly anyway.
306
+ const token = acquired.lock?.token ?? '';
307
+ state.lockToken = token;
308
+ try {
309
+ assertFencing(state.hubRoot, token);
310
+ return fn();
311
+ }
312
+ finally {
313
+ releaseLock(state.hubRoot, token);
314
+ state.lockToken = undefined;
315
+ }
316
+ }
317
+ function scopeFor(workspace) {
318
+ return { level: 'project', workspaceId: workspace.workspaceId };
319
+ }
320
+ function workspaceStatus(workspace) {
321
+ return {
322
+ workspaceId: workspace.workspaceId,
323
+ name: workspace.name,
324
+ path: workspace.path,
325
+ exact: workspace.exact,
326
+ origin: workspace.origin,
327
+ };
328
+ }
329
+ /**
330
+ * Data freshness — lets any host's agent reason about its knowledge boundary
331
+ * WITHOUT touching the remote: if the remote is down, everything above still
332
+ * works; these watermarks just say how recent the cross-team view is.
333
+ */
334
+ function readFreshness(hubRoot) {
335
+ const readWatermark = (file, key) => {
336
+ try {
337
+ const raw = JSON.parse(readFileSync(join(hubRoot, 'records', file), 'utf8'));
338
+ return typeof raw[key] === 'string' ? raw[key] : '';
339
+ }
340
+ catch {
341
+ return '';
342
+ }
343
+ };
344
+ const lastPullAt = readWatermark('hub-pull-state.json', 'lastPulledAt');
345
+ const lastPublishedAt = readWatermark('publish-state.json', 'lastPublishedAt');
346
+ const lastExtractAt = readWatermark('extract-state.json', 'lastExtractedAt');
347
+ const stale = [];
348
+ if (lastPullAt === '')
349
+ stale.push('pull: never synced from the remote — team knowledge may be missing locally');
350
+ if (lastPublishedAt === '')
351
+ stale.push('publish: never published — local approvals are not on the remote yet');
352
+ return { lastPullAt, lastPublishedAt, lastExtractAt, ...(stale.length > 0 ? { notes: stale } : {}) };
353
+ }
354
+ function metricsSnapshot(metrics) {
355
+ const { indexedCount, queryCount, totalHits, lastHitCount, lastQuery, builtAt } = metrics;
356
+ return {
357
+ indexedCount,
358
+ queryCount,
359
+ avgHits: queryCount === 0 ? 0 : Math.round((totalHits / queryCount) * 100) / 100,
360
+ lastHitCount,
361
+ lastQuery,
362
+ builtAt,
363
+ };
364
+ }
365
+ function registerWorkspaceIfNew(state) {
366
+ registerWorkspace(state.hubRoot, state.workspace, () => new Date().toISOString(), readHubConfig, (root, content) => {
367
+ appendFileSync(join(root, 'hub.yaml'), content, 'utf8');
368
+ });
369
+ }
370
+ function commitFromProposal(state, proposalId) {
371
+ const proposal = listProposals(state.hubRoot).find((p) => p.id === proposalId);
372
+ if (proposal === undefined) {
373
+ throw new HubError(ErrorCode.E_NOT_FOUND, `pending proposal not found: ${proposalId}`, { proposalId });
374
+ }
375
+ const committed = commitKnowledge(state.hubRoot, {
376
+ type: proposal.frontmatter.type,
377
+ title: proposal.frontmatter.title,
378
+ summary: proposal.frontmatter.summary,
379
+ scope: proposal.frontmatter.scope,
380
+ tags: proposal.frontmatter.tags,
381
+ body: readFileSync(proposal.path, 'utf8').split('---')[2]?.trim() ?? '',
382
+ actor: 'panel',
383
+ }, {
384
+ readSequences,
385
+ writeSequences,
386
+ appendLedger: (root, record) => appendLedger(ledgerPath(root), record),
387
+ });
388
+ unlinkSync(proposal.path);
389
+ appendLedger(ledgerPath(state.hubRoot), {
390
+ type: 'proposal.committed',
391
+ proposalId,
392
+ knowledgeId: committed.id,
393
+ channel: 'panel',
394
+ at: new Date().toISOString(),
395
+ });
396
+ state.index = buildIndex(state.hubRoot, () => new Date().toISOString());
397
+ state.metrics = emptyMetrics(state.index);
398
+ return { knowledgeId: committed.id, version: committed.version, path: committed.path };
399
+ }
400
+ export function heartbeat(state) {
401
+ return state.lockToken !== undefined && heartbeatLock(state.hubRoot, state.lockToken);
402
+ }
403
+ export function handleRpc(state, line) {
404
+ let request;
405
+ try {
406
+ request = JSON.parse(line);
407
+ }
408
+ catch {
409
+ return rpcError(null, -32700, 'Parse error');
410
+ }
411
+ const { id = null, method } = request;
412
+ if (method === undefined)
413
+ return rpcError(id, -32600, 'Invalid Request');
414
+ try {
415
+ switch (method) {
416
+ case 'initialize': {
417
+ const requested = String(request.params?.['protocolVersion'] ?? '');
418
+ const version = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
419
+ ? requested
420
+ : SUPPORTED_PROTOCOL_VERSIONS[SUPPORTED_PROTOCOL_VERSIONS.length - 1];
421
+ return rpcResult(id, { protocolVersion: version, capabilities: { tools: {} }, serverInfo: SERVER_INFO });
422
+ }
423
+ case 'notifications/initialized':
424
+ return null; // notification: no response
425
+ case 'tools/list':
426
+ return rpcResult(id, {
427
+ tools: Object.entries(TOOLS).map(([name, def]) => ({
428
+ name,
429
+ description: def.description,
430
+ inputSchema: def.inputSchema,
431
+ })),
432
+ });
433
+ case 'tools/call': {
434
+ const name = String(request.params?.['name'] ?? '');
435
+ const tool = TOOLS[name];
436
+ if (tool === undefined)
437
+ return rpcError(id, -32602, `Unknown tool: ${name}`);
438
+ const args = request.params?.['arguments'] ?? {};
439
+ try {
440
+ const result = tool.handler(state, args);
441
+ return rpcResult(id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] });
442
+ }
443
+ catch (error) {
444
+ const detail = error instanceof HubError ? { code: error.code, details: error.details } : undefined;
445
+ const message = error instanceof Error ? error.message : String(error);
446
+ return rpcResult(id, {
447
+ content: [{ type: 'text', text: message }],
448
+ isError: true,
449
+ error: detail,
450
+ });
451
+ }
452
+ }
453
+ case 'ping':
454
+ return rpcResult(id, {});
455
+ default:
456
+ return rpcError(id, -32601, `Method not found: ${method}`);
457
+ }
458
+ }
459
+ catch (error) {
460
+ const message = error instanceof Error ? error.message : String(error);
461
+ return rpcError(id, -32603, message);
462
+ }
463
+ }
464
+ function rpcResult(id, result) {
465
+ return JSON.stringify({ jsonrpc: '2.0', id, result });
466
+ }
467
+ function rpcError(id, code, message) {
468
+ return JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
469
+ }
470
+ /** Blocking stdio loop (server mode). Exits cleanly on EOF. */
471
+ export function serveStdio(state) {
472
+ process.stdin.setEncoding('utf8');
473
+ let data = '';
474
+ const lines = [];
475
+ process.stdin.on('data', (chunk) => {
476
+ data += chunk;
477
+ let newline = data.indexOf('\n');
478
+ while (newline !== -1) {
479
+ const line = data.slice(0, newline).trim();
480
+ data = data.slice(newline + 1);
481
+ if (line !== '')
482
+ lines.push(line);
483
+ newline = data.indexOf('\n');
484
+ }
485
+ while (lines.length > 0) {
486
+ const line = lines.shift();
487
+ if (line === undefined)
488
+ break;
489
+ const response = handleRpc(state, line);
490
+ if (response !== null)
491
+ process.stdout.write(`${response}\n`);
492
+ }
493
+ });
494
+ process.stdin.on('end', () => {
495
+ process.exit(0);
496
+ });
497
+ }
498
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot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C,IAAI,CAAC,CAAA;QAC9B,CAAC;QACD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,EAAE,CAAA;YAC1B,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAK;YAC7B,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACvC,IAAI,QAAQ,KAAK,IAAI;gBAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,QAAQ,IAAI,CAAC,CAAA;QAC9D,CAAC;IACH,CAAC,CAAC,CAAA;IACF,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;QAC3B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACjB,CAAC,CAAC,CAAA;AACJ,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Zero-dependency single-file console (no build step). ADR-0010: the
3
+ * standalone web console is the first-class human management surface for
4
+ * every host. Tabs: approval inbox (graded), knowledge browser (search /
5
+ * detail / deprecate / hard-delete), audit (ledger + journal). Human
6
+ * clicking approve = panel channel.
7
+ */
8
+ export declare const PANEL_HTML = "<!doctype html>\n<html lang=\"zh\">\n<head>\n<meta charset=\"utf-8\">\n<title>memhub console</title>\n<style>\n :root { color-scheme: dark; }\n body { font-family: ui-sans-serif, system-ui; margin: 0; background: #0f1115; color: #e6e6e6; }\n header { padding: 14px 20px; border-bottom: 1px solid #262b36; display: flex; gap: 16px; align-items: baseline; }\n header h1 { font-size: 16px; margin: 0; }\n header span { color: #8b93a7; font-size: 12px; }\n nav { display: flex; gap: 4px; padding: 0 20px; border-bottom: 1px solid #262b36; }\n nav button { border: none; background: none; color: #8b93a7; padding: 10px 16px; font-size: 14px; cursor: pointer; border-bottom: 2px solid transparent; }\n nav button.active { color: #e6e6e6; border-bottom-color: #4d7cff; }\n main { max-width: 900px; margin: 0 auto; padding: 16px; }\n .card { border: 1px solid #262b36; border-radius: 10px; padding: 14px 16px; margin: 10px 0; background: #161a22; }\n .card h3 { margin: 0 0 6px; font-size: 14px; }\n .meta { color: #8b93a7; font-size: 12px; margin-bottom: 8px; }\n .grade { border-radius: 6px; padding: 1px 8px; font-size: 11px; }\n .grade.individual { background: #3a2a2a; color: #ff9e9e; }\n .grade.batch { background: #233a2c; color: #8ee39b; }\n .status-tag { border-radius: 6px; padding: 1px 8px; font-size: 11px; background: #262b36; color: #a9b1c2; }\n .status-tag.deprecated { background: #3a2f1e; color: #e3b98e; }\n button { border: 1px solid #2f3542; background: #1d2330; color: #e6e6e6; border-radius: 8px; padding: 6px 14px; cursor: pointer; font-size: 13px; }\n button:hover { background: #262d3d; }\n button.primary { background: #245639; border-color: #2f7a4d; }\n button.danger { background: #5a2a2a; border-color: #7a3a3a; }\n .row { display: flex; gap: 8px; margin-top: 8px; }\n #statusbar { font-size: 12px; color: #8b93a7; }\n pre { white-space: pre-wrap; font-size: 12px; color: #a9b1c2; }\n .empty { color: #8b93a7; padding: 30px 0; text-align: center; }\n #batchbar { display: none; margin: 10px 0; }\n .tabpane { display: none; }\n .tabpane.active { display: block; }\n .entryline { border-bottom: 1px solid #20242e; padding: 9px 4px; cursor: pointer; display: flex; gap: 10px; align-items: baseline; }\n .entryline:hover { background: #1a1f29; }\n .entryline .id { color: #6f9bff; font-size: 12px; min-width: 90px; }\n .entryline .title { flex: 1; font-size: 13px; }\n .entryline .type { color: #8b93a7; font-size: 11px; }\n .detail pre { background: #12151c; border-radius: 8px; padding: 12px; max-height: 320px; overflow: auto; }\n</style>\n</head>\n<body>\n<header><h1>memhub console</h1><span id=\"statusbar\">loading\u2026</span></header>\n<nav>\n <button id=\"tab-inbox\" class=\"active\" onclick=\"showTab('inbox')\">\u6536\u4EF6\u7BB1</button>\n <button id=\"tab-entries\" onclick=\"showTab('entries')\">\u8BB0\u5FC6\u5E93</button>\n <button id=\"tab-audit\" onclick=\"showTab('audit')\">\u5BA1\u8BA1</button>\n</nav>\n<main>\n <div id=\"pane-inbox\" class=\"tabpane active\">\n <div id=\"batchbar\"><button class=\"primary\" onclick=\"approveBatch()\">\u6279\u51C6\u6240\u9009\u4F4E\u98CE\u9669\u6761\u76EE\uFF08\u6279\u91CF\uFF09</button></div>\n <div id=\"inbox\"><div class=\"empty\">\u52A0\u8F7D\u4E2D\u2026</div></div>\n </div>\n <div id=\"pane-entries\" class=\"tabpane\">\n <div class=\"row\"><input id=\"q\" placeholder=\"BM25 \u68C0\u7D22\u2026\" style=\"flex:1\" onkeydown=\"if(event.key==='Enter')doSearch()\"><button onclick=\"doSearch()\">\u641C\u7D22</button><button onclick=\"loadEntries()\">\u5168\u90E8</button></div>\n <div id=\"entrylist\"><div class=\"empty\">\u70B9\u51FB\u300C\u5168\u90E8\u300D\u6D4F\u89C8\u6216\u8F93\u5165\u68C0\u7D22\u8BCD</div></div>\n <div id=\"entrydetail\" class=\"detail\"></div>\n </div>\n <div id=\"pane-audit\" class=\"tabpane\">\n <div class=\"row\"><button onclick=\"loadLedger()\">\u5237\u65B0\u8D26\u672C</button><button onclick=\"loadJournal()\">\u5237\u65B0\u60C5\u666F\u65E5\u5FD7</button></div>\n <div id=\"auditview\"><div class=\"empty\">\u70B9\u51FB\u5237\u65B0\u52A0\u8F7D</div></div>\n </div>\n</main>\n<script>\nlet inbox = [];\nasync function j(url, opts) { const r = await fetch(url, opts); return { ok: r.ok, status: r.status, data: await r.json().catch(() => ({})) }; }\nfunction esc(s) { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;'); }\nfunction showTab(name) {\n document.querySelectorAll('.tabpane').forEach(p => p.classList.remove('active'));\n document.getElementById('pane-' + name).classList.add('active');\n document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));\n document.getElementById('tab-' + name).classList.add('active');\n if (name === 'inbox') refreshInbox();\n if (name === 'entries' && document.getElementById('entrylist').dataset.loaded !== '1') loadEntries();\n}\nasync function refreshStatus() {\n const s = await j('/api/status');\n document.getElementById('statusbar').textContent =\n (s.data.workspace ? s.data.workspace.workspaceId + (s.data.workspace.exact ? '' : ' (synthetic)') : '?') +\n ' \u00B7 accepted ' + (s.data.acceptedCount ?? 0) + ' \u00B7 hub ' + (s.data.hubRoot ?? '?');\n}\nasync function refreshInbox() {\n refreshStatus();\n const i = await j('/api/inbox');\n inbox = i.data.proposals ?? [];\n const el = document.getElementById('inbox');\n if (inbox.length === 0) { el.innerHTML = '<div class=\"empty\">\u2713 inbox \u6E05\u7A7A\uFF0C\u65E0\u5F85\u5BA1\u6761\u76EE</div>'; }\n else {\n el.innerHTML = inbox.map(p => `\n <div class=\"card\" id=\"card-${p.id}\">\n <h3>${esc(p.title)} <span class=\"grade ${p.grade}\">${p.grade === 'individual' ? '\u9010\u6761\u5BA1\u6279' : '\u53EF\u6279\u91CF'}</span></h3>\n <div class=\"meta\">${esc(p.id)} \u00B7 ${esc(p.type)} \u00B7 ${esc((p.tags ?? []).join(', '))}</div>\n <div>${esc(p.summary)}</div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"approveOne('${p.id}')\">\u6279\u51C6</button>\n <button class=\"danger\" onclick=\"rejectOne('${p.id}')\">\u62D2\u7EDD</button>\n </div>\n </div>`).join('');\n }\n const batchables = inbox.filter(p => p.grade === 'batch');\n document.getElementById('batchbar').style.display = batchables.length > 1 ? 'block' : 'none';\n}\nasync function approveOne(id) { await j('/api/inbox/' + id + '/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function rejectOne(id) { await j('/api/inbox/' + id + '/reject', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function approveBatch() {\n const ids = inbox.filter(p => p.grade === 'batch').map(p => p.id);\n await j('/api/inbox/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ ids }) });\n refreshInbox();\n}\nasync function loadEntries() {\n const r = await j('/api/entries');\n renderEntries(r.data.entries ?? []);\n document.getElementById('entrylist').dataset.loaded = '1';\n}\nasync function doSearch() {\n const q = document.getElementById('q').value;\n if (q === '') return loadEntries();\n const r = await j('/api/search', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ query: q, limit: 25 }) });\n renderEntries((r.data.hits ?? []).map(h => ({ id: h.id, type: h.type, status: 'accepted', title: h.title, summary: h.abstract, score: h.score })));\n}\nfunction renderEntries(entries) {\n const el = document.getElementById('entrylist');\n if (entries.length === 0) { el.innerHTML = '<div class=\"empty\">\u65E0\u6761\u76EE</div>'; return; }\n el.innerHTML = entries.map(e => `\n <div class=\"entryline\" onclick=\"openEntry('${esc(e.id)}')\">\n <span class=\"id\">${esc(e.id)}@v${e.version ?? '?'}</span>\n <span class=\"title\">${esc(e.title)} <span class=\"status-tag ${e.status === 'deprecated' ? 'deprecated' : ''}\">${esc(e.status ?? '')}</span>${e.score !== undefined ? ' \u00B7 ' + Number(e.score).toFixed(2) : ''}</span>\n <span class=\"type\">${esc(e.type)}</span>\n </div>`).join('');\n}\nasync function openEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u52A0\u8F7D\u5931\u8D25: ' + esc(r.data.error ?? r.status) + '</div>'; return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = `\n <div class=\"card\">\n <h3>${esc(fm.title)} <span class=\"status-tag\">${esc(fm.status)}</span></h3>\n <div class=\"meta\">${esc(fm.id)}@v${fm.version} \u00B7 ${esc(fm.type)} \u00B7 ${esc(JSON.stringify(fm.scope))} \u00B7 ${esc((fm.tags ?? []).join(', '))}</div>\n <div class=\"meta\">path: ${esc(r.data.path)}</div>\n <pre id=\"entry-body\">${esc(r.data.body)}</pre>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"editEntry('${esc(id)}')\">\u7F16\u8F91\uFF08\u91CD\u65B0\u8403\u53D6\uFF09</button>\n <button class=\"danger\" onclick=\"deprecateEntry('${esc(id)}')\">\u5E9F\u5F03\uFF08\u8F6F\u5220\u9664\uFF09</button>\n <button class=\"danger\" onclick=\"hardDeleteEntry('${esc(id)}')\">\u6C38\u4E45\u5220\u9664\uFF08\u4E0D\u53EF\u6062\u590D\uFF09</button>\n </div>\n </div>`;\n}\nasync function editEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { alert('\u52A0\u8F7D\u5931\u8D25: ' + (r.data.error ?? r.status)); return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = `\n <div class=\"card\">\n <h3>\u7F16\u8F91 ${esc(fm.id)}\uFF08\u4FDD\u5B58 = v${(fm.version ?? 1) + 1}\uFF0C\u65E7\u7248\u672C\u8FDB history/\uFF09</h3>\n <div class=\"meta\">\u6807\u9898\u4E0E\u7C7B\u578B\u4E0D\u53EF\u6539\uFF1B\u6458\u8981\u4E0E\u6B63\u6587\u901A\u7528\u5316\u6539\u5199\u540E\u4FDD\u5B58\u5373\u91CD\u65B0\u8403\u53D6\u3002</div>\n <div style=\"margin:8px 0\"><label>\u6458\u8981</label><br><textarea id=\"edit-summary\" rows=\"3\" style=\"width:98%\">${esc(fm.summary)}</textarea></div>\n <div style=\"margin:8px 0\"><label>\u6B63\u6587</label><br><textarea id=\"edit-body\" rows=\"14\" style=\"width:98%;font-family:monospace\">${esc(r.data.body)}</textarea></div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"saveEntry('${esc(id)}')\">\u4FDD\u5B58\u4E3A\u65B0\u7248\u672C</button>\n <button onclick=\"openEntry('${esc(id)}')\">\u53D6\u6D88</button>\n </div>\n </div>`;\n}\nasync function saveEntry(id) {\n const payload = { summary: document.getElementById('edit-summary').value, body: document.getElementById('edit-body').value };\n const r = await j('/api/entries/' + id + '/update', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(payload) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u4FDD\u5B58 ' + esc(r.data.updated) + '@v' + esc(r.data.version) + '\uFF08\u65E7\u7248\u672C\u8FDB history/\uFF0C\u8D26\u672C\u5DF2\u8BB0\u5F55\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function deprecateEntry(id) {\n if (!confirm('\u786E\u8BA4\u5E9F\u5F03 ' + id + '\uFF1F\uFF08status=deprecated\uFF0C\u53EF\u8FFD\u6EAF\uFF09')) return;\n const reason = prompt('\u5E9F\u5F03\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/deprecate', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u5E9F\u5F03 ' + esc(id) + '</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function hardDeleteEntry(id) {\n if (!confirm('\u6C38\u4E45\u5220\u9664 ' + id + '\uFF1F\u6587\u4EF6\u5C06\u88AB\u7269\u7406\u5220\u9664\uFF0C\u4E0D\u53EF\u6062\u590D\uFF08\u8D26\u672C\u7559\u75D5\uFF09\u3002')) return;\n if (!confirm('\u518D\u6B21\u786E\u8BA4\uFF1A\u771F\u7684\u8981\u6C38\u4E45\u5220\u9664 ' + id + ' \u5417\uFF1F')) return;\n const reason = prompt('\u5220\u9664\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/delete', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u6C38\u4E45\u5220\u9664 ' + esc(id) + '\uFF08\u8D26\u672C\u7559\u75D5\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function loadLedger() {\n const r = await j('/api/ledger');\n const records = r.data.records ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u8D26\u672C\u4E8B\u4EF6\uFF08\u6700\u8FD1 ' + records.length + ' / \u5171 ' + (r.data.total ?? 0) + '\uFF09</h3><pre>' + esc(JSON.stringify(records, null, 2)) + '</pre></div>';\n}\nasync function loadJournal() {\n const r = await j('/api/journal');\n const entries = r.data.entries ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u60C5\u666F\u65E5\u5FD7\uFF08\u6700\u8FD1 ' + entries.length + '\uFF09</h3><pre>' + esc(JSON.stringify(entries, null, 2)) + '</pre></div>';\n}\nrefreshInbox();\n</script>\n</body>\n</html>";