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
package/dist/cli.js ADDED
@@ -0,0 +1,736 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { join, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { ErrorCode, HubError } from './core/errors.js';
6
+ import { atomicWrite } from './core/atomic.js';
7
+ import { initHub, isHubInitialized, LEDGER_FILE, readHubConfig } from './core/hub.js';
8
+ import { appendLedger, ledgerPath, readLedger, readSequences, writeSequences } from './core/ledger.js';
9
+ import { acquireLock, assertFencing, lockInfo, releaseLock } from './core/lock.js';
10
+ import { registerWorkspace, resolveWorkspace } from './core/registry.js';
11
+ import { buildIndex, emptyMetrics, search } from './core/search.js';
12
+ import { commitKnowledge, getEntry, listEntries, listProposals } from './core/store.js';
13
+ import { validateHub } from './core/validate.js';
14
+ import { requireApproval } from './core/approval.js';
15
+ import { createApiState } from './transport/server.js';
16
+ import { autoCommit } from './transport/autocommit.js';
17
+ import { startServer, serverUrl } from './transport/http.js';
18
+ import { createState, handleRpc, serveStdio, TOOLS } from './transport/mcp.js';
19
+ import { buildExtractionMaterial, readExtractState, writeExtractState } from './core/extract.js';
20
+ function parseArgs(argv) {
21
+ const args = { _: [], root: process.env['MEMHUB_ROOT'] ?? process.cwd() };
22
+ for (let i = 0; i < argv.length; i += 1) {
23
+ const arg = argv[i];
24
+ if (arg === undefined)
25
+ break;
26
+ switch (arg) {
27
+ case '--root':
28
+ args.root = argv[i + 1] ?? args.root;
29
+ i += 1;
30
+ break;
31
+ case '--workspace':
32
+ args.workspace = argv[i + 1];
33
+ i += 1;
34
+ break;
35
+ case '--json':
36
+ args.json = true;
37
+ break;
38
+ case '--limit':
39
+ args.limit = Number(argv[i + 1]);
40
+ i += 1;
41
+ break;
42
+ case '--detail':
43
+ args.detail = argv[i + 1];
44
+ i += 1;
45
+ break;
46
+ case '--full':
47
+ args.full = true;
48
+ break;
49
+ case '--channel':
50
+ args.channel = argv[i + 1];
51
+ i += 1;
52
+ break;
53
+ case '--note':
54
+ args.note = argv[i + 1];
55
+ i += 1;
56
+ break;
57
+ case '--port':
58
+ args.port = Number(argv[i + 1]);
59
+ i += 1;
60
+ break;
61
+ case '--no-open':
62
+ args.open = false;
63
+ break;
64
+ case '--remote':
65
+ args.remote = argv[i + 1];
66
+ i += 1;
67
+ break;
68
+ case '--message':
69
+ args.message = argv[i + 1];
70
+ i += 1;
71
+ break;
72
+ case '--since':
73
+ args.since = argv[i + 1];
74
+ i += 1;
75
+ break;
76
+ case '--branch':
77
+ args.branch = argv[i + 1];
78
+ i += 1;
79
+ break;
80
+ default:
81
+ args._.push(arg);
82
+ }
83
+ }
84
+ return args;
85
+ }
86
+ /** Open the URL in the OS default browser (best effort, never throws). */
87
+ function openInBrowser(url) {
88
+ const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
89
+ const spawnArgs = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
90
+ try {
91
+ spawn(command, spawnArgs, { detached: true, stdio: 'ignore' }).unref();
92
+ }
93
+ catch {
94
+ console.error(`(自动打开浏览器失败:请手动访问 ${url})`);
95
+ }
96
+ }
97
+ function out(value, json) {
98
+ if (json) {
99
+ console.log(JSON.stringify(value, null, 2));
100
+ }
101
+ else {
102
+ console.log(JSON.stringify(value, null, 2));
103
+ }
104
+ }
105
+ /** Print a failure to stderr; never exits (tests import main directly). */
106
+ function fail(error) {
107
+ if (error instanceof HubError) {
108
+ console.error(`[${error.code}] ${error.message}`);
109
+ if (error.details !== undefined)
110
+ console.error(JSON.stringify(error.details));
111
+ }
112
+ else {
113
+ console.error(error instanceof Error ? error.message : String(error));
114
+ }
115
+ }
116
+ function requireHub(args) {
117
+ const root = resolve(args.root);
118
+ if (!isHubInitialized(root)) {
119
+ throw new HubError(ErrorCode.E_HUB_NOT_INITIALIZED, `hub not initialized at ${root} — run \`memhub init --root ${root}\``, { root });
120
+ }
121
+ return root;
122
+ }
123
+ function humanLedger(root, record) {
124
+ appendLedger(ledgerPath(root), record);
125
+ }
126
+ /** Sentinel: the command keeps the process alive (stdio loop) — caller must not exit. */
127
+ export const KEEP_ALIVE = -1;
128
+ export function main(argv) {
129
+ const args = parseArgs(argv);
130
+ const command = args._[0];
131
+ try {
132
+ switch (command) {
133
+ case 'init': {
134
+ const root = resolve(args.root);
135
+ const result = initHub(root);
136
+ out({ root, ...result });
137
+ return 0;
138
+ }
139
+ case 'mcp': {
140
+ const root = requireHub(args);
141
+ const state = createState(root, args.workspace);
142
+ serveStdio(state);
143
+ return KEEP_ALIVE;
144
+ }
145
+ case 'serve': {
146
+ const root = requireHub(args);
147
+ const state = createApiState(root, args.workspace);
148
+ const port = args.port ?? 7777;
149
+ const server = startServer(state, { port });
150
+ // Port 0 resolves asynchronously — print inside the listening event.
151
+ server.on('listening', () => {
152
+ const url = serverUrl(server);
153
+ console.error(`memhub console: ${url} (hub: ${root})`);
154
+ console.error('保持此终端窗口开启 —— 关闭终端即停止控制台。按 Ctrl+C 退出。');
155
+ if (args.open !== false)
156
+ openInBrowser(url);
157
+ });
158
+ server.on('error', (error) => {
159
+ if (error.code === 'EADDRINUSE') {
160
+ console.error(`[EADDRINUSE] 端口 ${port} 已被占用 —— 换一个端口:memhub serve --port 8080`);
161
+ }
162
+ else {
163
+ console.error(`[serve error] ${error.message}`);
164
+ }
165
+ process.exit(1);
166
+ });
167
+ const shutdown = () => {
168
+ server.close();
169
+ process.exit(0);
170
+ };
171
+ process.on('SIGINT', shutdown);
172
+ process.on('SIGTERM', shutdown);
173
+ return KEEP_ALIVE;
174
+ }
175
+ case 'search': {
176
+ const root = requireHub(args);
177
+ const query = args._.slice(1).join(' ');
178
+ if (query === '')
179
+ throw new HubError(ErrorCode.E_VALIDATION, 'usage: memhub search <query> [--detail L0|L1|L2] [--limit n]');
180
+ const state = createState(root, args.workspace);
181
+ const hits = search(state.index, query, {
182
+ workspaceId: state.workspace.workspaceId,
183
+ detail: args.detail ?? 'L1',
184
+ limit: args.limit,
185
+ });
186
+ out({ hits, workspace: state.workspace.workspaceId }, args.json);
187
+ return 0;
188
+ }
189
+ case 'get': {
190
+ const root = requireHub(args);
191
+ const id = args._[1];
192
+ if (id === undefined)
193
+ throw new HubError(ErrorCode.E_VALIDATION, 'usage: memhub get <ID> [--full]');
194
+ const entry = getEntry(root, id);
195
+ out({ frontmatter: entry.frontmatter, body: args.full === true ? entry.body : undefined, path: entry.path }, args.json);
196
+ return 0;
197
+ }
198
+ case 'status': {
199
+ const root = requireHub(args);
200
+ const workspace = resolveWorkspace(process.cwd(), args.workspace);
201
+ const index = buildIndex(root, () => new Date().toISOString());
202
+ out({
203
+ hubRoot: root,
204
+ workspace,
205
+ lock: lockInfo(root),
206
+ metrics: emptyMetrics(index),
207
+ acceptedCount: listEntries(root).length,
208
+ pendingCount: listProposals(root).length,
209
+ }, true);
210
+ return 0;
211
+ }
212
+ case 'inbox': {
213
+ const root = requireHub(args);
214
+ const sub = args._[1] ?? 'list';
215
+ if (sub === 'list') {
216
+ out({ proposals: listProposals(root).map((p) => ({ id: p.id, title: p.frontmatter.title, type: p.frontmatter.type, path: p.path })) }, true);
217
+ return 0;
218
+ }
219
+ const proposalId = args._[2];
220
+ if (proposalId === undefined)
221
+ throw new HubError(ErrorCode.E_VALIDATION, `usage: memhub inbox ${sub} <PRO-id>`);
222
+ if (sub === 'reject') {
223
+ humanLedger(root, { type: 'proposal.rejected', proposalId, note: args.note, at: new Date().toISOString() });
224
+ out({ rejected: proposalId });
225
+ return 0;
226
+ }
227
+ if (sub !== 'approve')
228
+ throw new HubError(ErrorCode.E_VALIDATION, `unknown inbox subcommand: ${sub}`);
229
+ // Human-carried channel: the person typed this command.
230
+ requireApproval('cli-human', {
231
+ id: proposalId,
232
+ ledgerAppend: (record) => humanLedger(root, record),
233
+ });
234
+ const state = createState(root, args.workspace);
235
+ const acquired = acquireLock(root);
236
+ if (!acquired.ok)
237
+ throw new HubError(ErrorCode.E_READONLY, 'another writer holds the lease', { holder: acquired.holder });
238
+ try {
239
+ assertFencing(root, acquired.lock?.token ?? '');
240
+ const proposals = listProposals(root);
241
+ const proposal = proposals.find((p) => p.id === proposalId);
242
+ if (proposal === undefined)
243
+ throw new HubError(ErrorCode.E_NOT_FOUND, `pending proposal not found: ${proposalId}`);
244
+ const committed = commitKnowledge(root, {
245
+ type: proposal.frontmatter.type,
246
+ title: proposal.frontmatter.title,
247
+ summary: proposal.frontmatter.summary,
248
+ scope: proposal.frontmatter.scope,
249
+ tags: proposal.frontmatter.tags,
250
+ body: readFileSync(proposal.path, 'utf8').split('---')[2]?.trim() ?? '',
251
+ actor: 'cli-human',
252
+ }, { readSequences, writeSequences, appendLedger: humanLedger });
253
+ humanLedger(root, { type: 'proposal.committed', proposalId, knowledgeId: committed.id, channel: 'cli-human', at: new Date().toISOString() });
254
+ const gitCommit = autoCommit(root, `approve: ${committed.id}@v${committed.version} ${proposal.frontmatter.title}`);
255
+ out({ knowledgeId: committed.id, version: committed.version, path: committed.path, git: gitCommit }, true);
256
+ return 0;
257
+ }
258
+ finally {
259
+ releaseLock(root, acquired.lock?.token ?? '');
260
+ }
261
+ }
262
+ case 'tools': {
263
+ out(Object.keys(TOOLS), true);
264
+ return 0;
265
+ }
266
+ case 'validate': {
267
+ const root = requireHub(args);
268
+ const report = validateHub(root);
269
+ out(report, args.json);
270
+ return report.ok ? 0 : 1;
271
+ }
272
+ case 'hub': {
273
+ const root = requireHub(args);
274
+ const sub = args._[1];
275
+ const central = args.remote;
276
+ if (sub === undefined || central === undefined) {
277
+ throw new HubError(ErrorCode.E_VALIDATION, 'usage: memhub hub <push|pull> --remote <central-serve-url> [--since <iso>]');
278
+ }
279
+ // main() is synchronous; hubSync is async — stash the promise so the
280
+ // entry guard can await it (main never blocks an in-process server).
281
+ pendingHubSync = (async () => {
282
+ const result = await hubSync(root, sub, central.replace(/\/$/, ''), args.since);
283
+ out(result, args.json);
284
+ return result.ok ? 0 : 1;
285
+ })();
286
+ return KEEP_ALIVE;
287
+ }
288
+ case 'extract': {
289
+ const root = requireHub(args);
290
+ const sub = args._[1];
291
+ if (sub === 'material') {
292
+ const material = buildExtractionMaterial(root, args.since);
293
+ out(material, true); // always JSON — it is consumed by an agent, not a human
294
+ return 0;
295
+ }
296
+ if (sub === 'done') {
297
+ const at = args.since ?? new Date().toISOString();
298
+ writeExtractState(root, at);
299
+ const state = readExtractState(root);
300
+ out({ ok: true, watermark: state.lastExtractedAt, extractionCount: state.extractionCount }, args.json);
301
+ return 0;
302
+ }
303
+ throw new HubError(ErrorCode.E_VALIDATION, 'usage: memhub extract <material|done> [--since <iso>]\n material: what changed since the last watermark (feed to your workflow agent)\n done: advance the watermark after a successful extraction run');
304
+ }
305
+ case 'sync': {
306
+ const root = requireHub(args);
307
+ const sub = args._[1];
308
+ if (sub === undefined)
309
+ throw new HubError(ErrorCode.E_VALIDATION, 'usage: memhub sync <status|init|push|pull> [--remote url] [--message text]');
310
+ const result = syncCommand(root, sub, args.remote, args.message, args.branch);
311
+ out(result, args.json);
312
+ return result.ok ? 0 : 1;
313
+ }
314
+ case 'publish': {
315
+ // ADR-0015: the outbound API is the team's own to define — either a
316
+ // configurable HTTP endpoint or their own script (which may call the
317
+ // Tencent memory-hub API however it evolves). memhub never hardcodes it.
318
+ const root = requireHub(args);
319
+ const ids = args._.slice(1);
320
+ pendingHubSync = (async () => {
321
+ const result = await publishCommand(root, ids);
322
+ out(result, args.json);
323
+ return result.ok ? 0 : 1;
324
+ })();
325
+ return KEEP_ALIVE;
326
+ }
327
+ case 'help':
328
+ case undefined:
329
+ printHelp();
330
+ return 0;
331
+ default:
332
+ console.error(`unknown command: ${command}`);
333
+ printHelp();
334
+ return 1;
335
+ }
336
+ }
337
+ catch (error) {
338
+ fail(error);
339
+ return 1;
340
+ }
341
+ }
342
+ function git(root, argv) {
343
+ const result = spawnSync('git', argv, { cwd: root, encoding: 'utf8' });
344
+ if (result.error !== undefined) {
345
+ return { ok: false, output: `git not available: ${result.error.message}` };
346
+ }
347
+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
348
+ return { ok: result.status === 0, output };
349
+ }
350
+ function readJsonState(root, file, fallback) {
351
+ const path = join(root, 'records', file);
352
+ if (!existsSync(path))
353
+ return fallback;
354
+ try {
355
+ return { ...fallback, ...JSON.parse(readFileSync(path, 'utf8')) };
356
+ }
357
+ catch {
358
+ return fallback;
359
+ }
360
+ }
361
+ function writeJsonState(root, file, value) {
362
+ atomicWrite(join(root, 'records', file), JSON.stringify(value, null, 2) + '\n');
363
+ }
364
+ const PUSH_STATE_FILE = 'hub-push-state.json';
365
+ const PULL_STATE_FILE = 'hub-pull-state.json';
366
+ const hubFetchHttp = async (url, init) => {
367
+ const r = await fetch(url, {
368
+ method: init?.method,
369
+ headers: { 'content-type': 'application/json' },
370
+ body: init?.body,
371
+ signal: AbortSignal.timeout(20000),
372
+ });
373
+ return { ok: r.ok, status: r.status, body: (await r.json().catch(() => ({}))) };
374
+ };
375
+ /** Exported for tests: hub-to-hub sync roundtrip (ADR-0012). */
376
+ export async function hubSync(root, sub, central, since, fetchImpl = hubFetchHttp) {
377
+ if (sub === 'push') {
378
+ const state = readJsonState(root, PUSH_STATE_FILE, { lastPushedAt: '' });
379
+ const effectiveSince = since ?? state.lastPushedAt;
380
+ const all = listEntries(root, { includeSoftRemoved: false });
381
+ const entries = effectiveSince === '' ? all : all.filter((e) => (e.frontmatter.updated ?? '') > effectiveSince);
382
+ if (entries.length === 0)
383
+ return { ok: true, pushed: 0, note: 'nothing new since last push' };
384
+ const results = [];
385
+ for (const e of entries) {
386
+ try {
387
+ const r = await fetchImpl(`${central}/api/propose`, {
388
+ method: 'POST',
389
+ body: JSON.stringify({
390
+ type: e.frontmatter.type,
391
+ title: e.frontmatter.title,
392
+ summary: e.frontmatter.summary,
393
+ tags: e.frontmatter.tags,
394
+ body: readFileSync(e.path, 'utf8').split('---')[2]?.trim() ?? '',
395
+ sourceRefs: [`hub:${e.frontmatter.id}@v${e.frontmatter.version}`],
396
+ originId: e.frontmatter.id,
397
+ origin: `hub-push:${root.replace(/\\/g, '/').split('/').pop() ?? 'local'}`,
398
+ }),
399
+ });
400
+ const body = r.body;
401
+ results.push({ localId: e.frontmatter.id, ok: r.ok, ...(body.proposalId !== undefined ? { proposalId: body.proposalId } : {}), ...(body.error !== undefined ? { error: body.error } : {}) });
402
+ }
403
+ catch (error) {
404
+ results.push({ localId: e.frontmatter.id, ok: false, error: error instanceof Error ? error.message : String(error) });
405
+ }
406
+ }
407
+ const pushed = results.filter((r) => r.ok).length;
408
+ if (pushed === entries.length)
409
+ writeJsonState(root, PUSH_STATE_FILE, { lastPushedAt: new Date().toISOString() });
410
+ return { ok: pushed > 0, pushed, total: entries.length, results, nextStep: 'central inbox review: approve = merge into the central knowledge base' };
411
+ }
412
+ if (sub === 'pull') {
413
+ const state = readJsonState(root, PULL_STATE_FILE, { lastPulledAt: '' });
414
+ const effectiveSince = since ?? state.lastPulledAt;
415
+ const q = effectiveSince === '' ? '' : `?since=${encodeURIComponent(effectiveSince)}`;
416
+ // Remote-down resilience: transport exceptions degrade to an error
417
+ // result (never escape — the hubSync caller must not crash on a dead
418
+ // central hub).
419
+ let listResult;
420
+ try {
421
+ listResult = await fetchImpl(`${central}/api/entries${q}`, { method: 'GET' });
422
+ }
423
+ catch (error) {
424
+ return { ok: false, error: `central hub unreachable: ${error instanceof Error ? error.message : String(error)}` };
425
+ }
426
+ if (!listResult.ok)
427
+ return { ok: false, error: `central hub list failed: ${JSON.stringify(listResult.body).slice(0, 200)}` };
428
+ const listed = listResult.body.entries ?? [];
429
+ const applied = [];
430
+ const skipped = [];
431
+ const errors = [];
432
+ for (const listedEntry of listed) {
433
+ if (listedEntry.status !== 'accepted')
434
+ continue;
435
+ try {
436
+ let detail;
437
+ try {
438
+ detail = await fetchImpl(`${central}/api/entries/${encodeURIComponent(listedEntry.id)}`, { method: 'GET' });
439
+ }
440
+ catch (error) {
441
+ errors.push(`${listedEntry.id}: detail fetch failed (${error instanceof Error ? error.message : String(error)})`);
442
+ continue;
443
+ }
444
+ if (!detail.ok) {
445
+ errors.push(`${listedEntry.id}: detail fetch failed (${detail.status})`);
446
+ continue;
447
+ }
448
+ const d = detail.body;
449
+ let localVersion = 0;
450
+ try {
451
+ localVersion = getEntry(root, d.frontmatter.id).frontmatter.version;
452
+ }
453
+ catch {
454
+ localVersion = 0; // not present locally
455
+ }
456
+ if (d.frontmatter.version <= localVersion) {
457
+ skipped.push(d.frontmatter.id);
458
+ continue;
459
+ }
460
+ commitKnowledge(root, {
461
+ ...(localVersion > 0 ? { id: d.frontmatter.id } : {}),
462
+ type: d.frontmatter.type,
463
+ title: d.frontmatter.title,
464
+ summary: d.frontmatter.summary,
465
+ scope: d.frontmatter.scope,
466
+ tags: d.frontmatter.tags,
467
+ body: d.body,
468
+ sourceRefs: [`central-hub:${d.frontmatter.id}@v${d.frontmatter.version}`],
469
+ actor: 'remote-hub',
470
+ }, { readSequences, writeSequences, appendLedger: (r, record) => appendLedger(ledgerPath(r), record) });
471
+ applied.push(`${d.frontmatter.id}@v${d.frontmatter.version}`);
472
+ }
473
+ catch (error) {
474
+ errors.push(`${listedEntry.id}: ${error instanceof Error ? error.message : String(error)}`);
475
+ }
476
+ }
477
+ writeJsonState(root, PULL_STATE_FILE, { lastPulledAt: new Date().toISOString() });
478
+ autoCommit(root, `pull: applied ${applied.length} central entries`);
479
+ return { ok: errors.length === 0, applied, skipped, errors, from: effectiveSince || '(beginning)' };
480
+ }
481
+ return { ok: false, error: `unknown hub subcommand: ${sub} (push|pull)` };
482
+ }
483
+ function readPublishConfig(root) {
484
+ const config = readHubConfig(root);
485
+ const headers = {};
486
+ const env = {};
487
+ for (const [key, value] of Object.entries(config)) {
488
+ const header = /^publish\.header\.(.+)$/.exec(key);
489
+ if (header !== null && header[1] !== undefined)
490
+ headers[header[1]] = value;
491
+ const envVar = /^publish\.env\.(.+)$/.exec(key);
492
+ if (envVar !== null && envVar[1] !== undefined)
493
+ env[envVar[1]] = value;
494
+ }
495
+ return {
496
+ adapter: config['publish.adapter'] ?? 'none',
497
+ endpoint: config['publish.endpoint'],
498
+ headers,
499
+ env,
500
+ script: config['publish.script'],
501
+ };
502
+ }
503
+ const PUBLISH_STATE_FILE = 'publish-state.json';
504
+ function buildPublishPayload(root, ids) {
505
+ const all = listEntries(root, { includeSoftRemoved: false });
506
+ const selected = ids.length > 0 ? all.filter((e) => ids.includes(e.frontmatter.id)) : all;
507
+ return selected.map((e) => ({
508
+ id: e.frontmatter.id,
509
+ version: e.frontmatter.version,
510
+ type: e.frontmatter.type,
511
+ title: e.frontmatter.title,
512
+ summary: e.frontmatter.summary,
513
+ scope: e.frontmatter.scope,
514
+ tags: e.frontmatter.tags,
515
+ updated: e.frontmatter.updated ?? '',
516
+ sourceRefs: String(e.frontmatter.extra['source_refs'] ?? ''),
517
+ body: readFileSync(e.path, 'utf8').split('---')[2]?.trim() ?? '',
518
+ }));
519
+ }
520
+ const publishHttpTransport = async (url, init) => {
521
+ const r = await fetch(url, { method: init.method, headers: init.headers, body: init.body, signal: AbortSignal.timeout(30000) });
522
+ return { ok: r.ok, status: r.status, body: (await r.text().catch(() => '')).slice(0, 400) };
523
+ };
524
+ /** Exported for tests: ADR-0015 publish with a definable outbound API. */
525
+ export async function publishCommand(root, ids, transport = publishHttpTransport) {
526
+ const config = readPublishConfig(root);
527
+ if (config.adapter === 'none') {
528
+ return {
529
+ ok: false,
530
+ error: 'no publish outlet configured',
531
+ hint: '在 hub.yaml 里定义你的出口(API 由你们自定义,ADR-0015):\n publish.adapter: http + publish.endpoint: <你们的记忆库 API>\n publish.adapter: exec + publish.script: <你的脚本,stdin 收条目 JSON>\n publish.adapter: none # 不发布',
532
+ };
533
+ }
534
+ const entries = buildPublishPayload(root, ids);
535
+ if (entries.length === 0) {
536
+ if (ids.length > 0)
537
+ return { ok: false, error: `no accepted entry matching: ${ids.join(', ')}` };
538
+ return { ok: true, published: 0, note: 'nothing to publish' };
539
+ }
540
+ const body = JSON.stringify({ entries, publishedAt: new Date().toISOString() }, null, 2);
541
+ let detail = '';
542
+ let delivered = false;
543
+ if (config.adapter === 'http') {
544
+ if (config.endpoint === undefined || config.endpoint === '') {
545
+ return { ok: false, error: 'publish.adapter is http but publish.endpoint is not set' };
546
+ }
547
+ // A dead/misbehaving outlet must degrade to an error result — NEVER let
548
+ // the transport exception escape (that is exactly the crash class the
549
+ // direct-to-remote integration suffered: a 404 taking the host down).
550
+ let r;
551
+ try {
552
+ r = await transport(config.endpoint, { method: 'POST', headers: { 'content-type': 'application/json', ...config.headers }, body });
553
+ }
554
+ catch (error) {
555
+ return { ok: false, error: `publish transport failed (remote down?): ${error instanceof Error ? error.message : String(error)}`, adapter: config.adapter };
556
+ }
557
+ delivered = r.ok;
558
+ detail = `HTTP ${r.status} ${r.body}`;
559
+ }
560
+ else if (config.adapter === 'exec') {
561
+ if (config.script === undefined || config.script === '') {
562
+ return { ok: false, error: 'publish.adapter is exec but publish.script is not set' };
563
+ }
564
+ const scriptPath = join(root, config.script);
565
+ if (!existsSync(scriptPath))
566
+ return { ok: false, error: `publish script not found: ${scriptPath}` };
567
+ // Async spawn — NOT spawnSync: a blocked event loop cannot answer any
568
+ // in-process server, and the script's fetches would deadlock (same
569
+ // lesson as hubSync). Inherit the parent environment, then layer
570
+ // publish.env.<NAME> on top (a token can come from the system env so
571
+ // it never lands in hub.yaml).
572
+ const run = await new Promise((resolve) => {
573
+ const child = spawn(process.execPath, [scriptPath], { cwd: root, env: { ...process.env, ...config.env }, stdio: ['pipe', 'pipe', 'pipe'] });
574
+ child.stdin.write(body);
575
+ child.stdin.end();
576
+ let stdout = '';
577
+ let stderr = '';
578
+ child.stdout.on('data', (c) => { stdout += c.toString(); });
579
+ child.stderr.on('data', (c) => { stderr += c.toString(); });
580
+ const timer = setTimeout(() => child.kill('SIGKILL'), 120000);
581
+ child.on('close', (code) => {
582
+ clearTimeout(timer);
583
+ resolve({ status: code, stdout, stderr });
584
+ });
585
+ });
586
+ delivered = run.status === 0;
587
+ detail = run.stdout.trim().slice(0, 400);
588
+ if (!delivered)
589
+ detail = `${detail}\n${run.stderr.trim().slice(0, 400)}`.trim();
590
+ }
591
+ else {
592
+ return { ok: false, error: `unknown publish.adapter: ${config.adapter} (http|exec|none)` };
593
+ }
594
+ if (!delivered)
595
+ return { ok: false, error: `publish failed: ${detail}`, adapter: config.adapter };
596
+ const ts = new Date().toISOString();
597
+ if (ids.length === 0)
598
+ writeJsonState(root, PUBLISH_STATE_FILE, { lastPublishedAt: ts });
599
+ appendLedger(ledgerPath(root), { ts, actor: 'cli-human', action: 'publish', id: entries.map((e) => e.id).join(','), version: 0, source_refs: [] });
600
+ return {
601
+ ok: true,
602
+ adapter: config.adapter,
603
+ published: entries.length,
604
+ ids: entries.map((e) => e.id),
605
+ detail,
606
+ nextStep: '已发布到你们定义的记忆库出口;水位线已记录,下次增量发布从 lastPublishedAt 开始',
607
+ };
608
+ }
609
+ /** ADR-0011: the hub root IS a git repository — sync delegates to git. */
610
+ /** Exported for tests: git-backed center sync (ADR-0013). */
611
+ export function syncCommand(root, sub, remote, message, branch) {
612
+ const inside = git(root, ['rev-parse', '--is-inside-work-tree']);
613
+ if (sub === 'init') {
614
+ if (!inside.ok) {
615
+ const init = git(root, ['init']);
616
+ if (!init.ok)
617
+ return { ok: false, error: init.output };
618
+ }
619
+ if (remote !== undefined) {
620
+ const existing = git(root, ['remote', 'get-url', 'origin']);
621
+ if (existing.ok)
622
+ git(root, ['remote', 'set-url', 'origin', remote]);
623
+ else
624
+ git(root, ['remote', 'add', 'origin', remote]);
625
+ }
626
+ // Keep pending/ out of the repository: proposals are a local queue.
627
+ const gitignore = join(root, '.gitignore');
628
+ if (!existsSync(gitignore))
629
+ atomicWrite(gitignore, 'pending/\n');
630
+ return { ok: true, action: 'init', nextStep: 'memhub sync push --message "initial memory snapshot"' };
631
+ }
632
+ if (!inside.ok)
633
+ return { ok: false, error: `hub root is not a git repository — run: memhub sync init --remote <url>` };
634
+ if (sub === 'status') {
635
+ const branch = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
636
+ const dirty = git(root, ['status', '--porcelain']);
637
+ const remoteUrl = git(root, ['remote', 'get-url', 'origin']);
638
+ return {
639
+ ok: true,
640
+ branch: branch.output || '(none)',
641
+ dirtyFiles: dirty.output === '' ? 0 : dirty.output.split('\n').length,
642
+ remote: remoteUrl.ok ? remoteUrl.output : '(none configured)',
643
+ hint: remoteUrl.ok ? 'memhub sync push / memhub sync pull' : 'memhub sync init --remote <url>',
644
+ };
645
+ }
646
+ if (sub === 'push') {
647
+ // ADR-0013: the center is the team's existing git service. Personal
648
+ // branch mode (--branch) enables MR review without GitHub specifics:
649
+ // push the branch, then open the MR on the git service's own UI.
650
+ if (branch !== undefined) {
651
+ const hasBranch = git(root, ['rev-parse', '--verify', branch]);
652
+ const switchTo = hasBranch.ok ? git(root, ['checkout', branch]) : git(root, ['checkout', '-b', branch]);
653
+ if (!switchTo.ok)
654
+ return { ok: false, error: switchTo.output };
655
+ }
656
+ const add = git(root, ['add', '-A']);
657
+ if (!add.ok)
658
+ return { ok: false, error: add.output };
659
+ const commit = git(root, ['commit', '-m', message ?? 'memhub sync: memory update']);
660
+ const push = branch !== undefined ? git(root, ['push', '-u', 'origin', branch]) : git(root, ['push', '-u', 'origin', 'HEAD']);
661
+ return {
662
+ ok: push.ok,
663
+ committed: commit.ok ? 'yes' : 'nothing to commit',
664
+ pushed: push.ok ? 'yes' : 'no',
665
+ branch: branch ?? '(current)',
666
+ output: push.output || commit.output,
667
+ ...(push.ok && branch !== undefined
668
+ ? { nextStep: `在你的 git 服务上从分支 ${branch} 发起 MR —— 审查意见见 MR,改完再 push 即可;合入后其他人 memhub sync pull 同步` }
669
+ : push.ok
670
+ ? { nextStep: '已推送。团队协作建议:memhub sync push --branch <你的名字>,用 git 服务自带的 MR 审查合入' }
671
+ : {}),
672
+ ...(push.ok ? {} : { hint: 'if the remote uses PR review, open a PR from your branch' }),
673
+ };
674
+ }
675
+ if (sub === 'pull') {
676
+ const pull = git(root, ['pull', '--rebase']);
677
+ return { ok: pull.ok, output: pull.output };
678
+ }
679
+ return { ok: false, error: `unknown sync subcommand: ${sub}` };
680
+ }
681
+ function printHelp() {
682
+ console.log(`memhub — agent-memory-hub CLI
683
+
684
+ memhub init --root <dir> initialize a hub directory
685
+ memhub mcp --root <dir> start the MCP stdio server
686
+ memhub serve --root <dir> [--port n] [--no-open]
687
+ start the web console (auto-opens your browser;
688
+ inbox + knowledge browser + audit; Ctrl+C stops)
689
+ memhub search <query> search accepted knowledge
690
+ [--detail L0|L1|L2] [--limit n] [--workspace id] [--json]
691
+ memhub get <ID> [--full] read one entry
692
+ memhub status hub/workspace/lock/metrics snapshot
693
+ memhub inbox list list pending proposals
694
+ memhub inbox approve <PRO-id> human approval -> knowledge (ledgered)
695
+ memhub inbox reject <PRO-id> reject with optional --note
696
+ memhub validate extraction validation over knowledge/ + pending/
697
+ (exit 1 on errors — usable as CI gate)
698
+ memhub extract material [--since] extraction material since the watermark (JSON for
699
+ ANY scheduler's agent: cron / workflow platform / CI)
700
+ memhub extract done [--since iso] advance the extraction watermark after a run
701
+ memhub hub <push|pull> --remote <central-serve-url> [--since iso]
702
+ ADR-0012 hub-to-hub sync: push local approved entries
703
+ as central proposals (central inbox = review gate);
704
+ pull central-approved entries into local knowledge
705
+ memhub sync <status|init|push|pull> [--remote url] [--message text] [--branch name]
706
+ THE center: publish knowledge to the team's existing
707
+ git service (no dedicated server, ADR-0013); --branch
708
+ pushes a personal branch for MR review on the git UI;
709
+ serve stays local-only (inbox/browser/audit)
710
+ memhub publish [IDs...] publish approved entries to YOUR definable outlet
711
+ (hub.yaml: publish.adapter http|exec — the API
712
+ contract is yours, e.g. the Tencent memory hub)
713
+ memhub tools list MCP tool names
714
+ memhub help this text
715
+ `);
716
+ }
717
+ /** Entry guard: run the loop only when invoked directly as the bin target. */
718
+ const invokedDirectly = process.argv[1] !== undefined &&
719
+ (import.meta.url === pathToFileURL(process.argv[1]).href ||
720
+ process.argv[1].replace(/\\/g, '/').endsWith('/dist/cli.js'));
721
+ /** Set when a command (hub) defers its work to an async continuation. */
722
+ let pendingHubSync = null;
723
+ if (invokedDirectly && process.argv.length > 2) {
724
+ const code = main(process.argv.slice(2));
725
+ // TS narrows pendingHubSync to null here (assignment happens inside main);
726
+ // cast through unknown so the async continuation still runs.
727
+ const job = pendingHubSync;
728
+ if (code === KEEP_ALIVE && job !== null) {
729
+ job.then((exitCode) => process.exit(exitCode)).catch(() => process.exit(1));
730
+ }
731
+ else if (code !== KEEP_ALIVE) {
732
+ process.exit(code);
733
+ }
734
+ }
735
+ export { createState, handleRpc, readHubConfig, readLedger, registerWorkspace, LEDGER_FILE };
736
+ //# sourceMappingURL=cli.js.map