agent-memory-hub 0.1.0 → 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 (45) hide show
  1. package/README.md +21 -0
  2. package/dist/cli.d.ts +37 -0
  3. package/dist/cli.js +487 -7
  4. package/dist/cli.js.map +1 -1
  5. package/dist/core/extract.d.ts +48 -0
  6. package/dist/core/extract.js +71 -0
  7. package/dist/core/extract.js.map +1 -0
  8. package/dist/core/frontmatter.d.ts +7 -1
  9. package/dist/core/frontmatter.js +70 -8
  10. package/dist/core/frontmatter.js.map +1 -1
  11. package/dist/core/hub.js +32 -0
  12. package/dist/core/hub.js.map +1 -1
  13. package/dist/core/inject.js +3 -1
  14. package/dist/core/inject.js.map +1 -1
  15. package/dist/core/ledger.d.ts +1 -1
  16. package/dist/core/ledger.js.map +1 -1
  17. package/dist/core/lock.d.ts +2 -1
  18. package/dist/core/lock.js +8 -3
  19. package/dist/core/lock.js.map +1 -1
  20. package/dist/core/registry.js +5 -1
  21. package/dist/core/registry.js.map +1 -1
  22. package/dist/core/store.d.ts +6 -1
  23. package/dist/core/store.js +46 -5
  24. package/dist/core/store.js.map +1 -1
  25. package/dist/core/validate.d.ts +19 -0
  26. package/dist/core/validate.js +94 -0
  27. package/dist/core/validate.js.map +1 -0
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +3 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/transport/autocommit.d.ts +11 -0
  32. package/dist/transport/autocommit.js +25 -0
  33. package/dist/transport/autocommit.js.map +1 -0
  34. package/dist/transport/http.d.ts +2 -0
  35. package/dist/transport/http.js +12 -1
  36. package/dist/transport/http.js.map +1 -1
  37. package/dist/transport/mcp.js +31 -2
  38. package/dist/transport/mcp.js.map +1 -1
  39. package/dist/transport/panel.d.ts +6 -4
  40. package/dist/transport/panel.js +147 -26
  41. package/dist/transport/panel.js.map +1 -1
  42. package/dist/transport/server.d.ts +4 -2
  43. package/dist/transport/server.js +144 -6
  44. package/dist/transport/server.js.map +1 -1
  45. package/package.json +1 -1
package/README.md CHANGED
@@ -12,6 +12,27 @@
12
12
  - **Cross-host by design** — one MCP server + one CLI (`memhub`) + one optional local dashboard, all backed by the same files. Register once, every agent shares the same memory.
13
13
  - **Scoped** — project → domain → global knowledge hierarchy with ancestor-chain search. Each agent sees exactly the layers it should.
14
14
 
15
+ ## Install
16
+
17
+ **DSH plugin** (DeepSeek Harness users):
18
+
19
+ ```
20
+ install_bundle dsh-agent-memory-hub
21
+ ```
22
+
23
+ Tool surface: 8 `memory_*` tools (search / get / status / propose / preflight / cite / journal / close-task). Runtime is **zero-network** — a dead remote never degrades your host. Details: [host/dsh/README.md](host/dsh/README.md) · [部署对接指南](docs/03-usage/memory-hub-deployment.md).
24
+
25
+ **CLI / MCP server** (Claude Code, OpenCode, Codex, gemini-cli, any MCP host):
26
+
27
+ ```sh
28
+ npm i -g agent-memory-hub
29
+ memhub mcp --root <hub> # register in any MCP client
30
+ memhub extract material # scheduled-extraction material for any workflow platform
31
+ memhub publish # publish approved entries to your team's memory-hub API (ADR-0015)
32
+ ```
33
+
34
+ **Team memory-hub service**: implement or deploy [docs/02-spec/memory-hub-api-v1.md](docs/02-spec/memory-hub-api-v1.md) (reference server included: `examples/memory-hub-server.mjs`).
35
+
15
36
  ## Status
16
37
 
17
38
  🚧 **Under active development** (this repo was founded 2026-11-15). The stable, working edition of the same memory format is [`dsh-memory-hub`](https://www.npmjs.com/package/dsh-memory-hub) (DSH plugin, v0.8.x). `agent-memory-hub` generalizes it into a standalone cross-host service; the first stable release targets **0.1.0**.
package/dist/cli.d.ts CHANGED
@@ -5,4 +5,41 @@ import { createState, handleRpc, type TransportState } from './transport/mcp.js'
5
5
  /** Sentinel: the command keeps the process alive (stdio loop) — caller must not exit. */
6
6
  export declare const KEEP_ALIVE = -1;
7
7
  export declare function main(argv: string[]): number;
8
+ interface HubFetchResult {
9
+ ok: boolean;
10
+ status: number;
11
+ body: Record<string, unknown>;
12
+ }
13
+ /** Injectable for tests; production hits the central hub over HTTP. */
14
+ export type HubFetch = (url: string, init?: {
15
+ method?: string;
16
+ body?: string;
17
+ }) => Promise<HubFetchResult>;
18
+ /** Exported for tests: hub-to-hub sync roundtrip (ADR-0012). */
19
+ export declare function hubSync(root: string, sub: string, central: string, since?: string, fetchImpl?: HubFetch): Promise<{
20
+ ok: boolean;
21
+ [key: string]: unknown;
22
+ }>;
23
+ export interface PublishTransport {
24
+ (url: string, init: {
25
+ method: string;
26
+ headers: Record<string, string>;
27
+ body: string;
28
+ }): Promise<{
29
+ ok: boolean;
30
+ status: number;
31
+ body: string;
32
+ }>;
33
+ }
34
+ /** Exported for tests: ADR-0015 publish with a definable outbound API. */
35
+ export declare function publishCommand(root: string, ids: string[], transport?: PublishTransport): Promise<{
36
+ ok: boolean;
37
+ [key: string]: unknown;
38
+ }>;
39
+ /** ADR-0011: the hub root IS a git repository — sync delegates to git. */
40
+ /** Exported for tests: git-backed center sync (ADR-0013). */
41
+ export declare function syncCommand(root: string, sub: string, remote?: string, message?: string, branch?: string): {
42
+ ok: boolean;
43
+ [key: string]: unknown;
44
+ };
8
45
  export { createState, handleRpc, type TransportState, readHubConfig, readLedger, registerWorkspace, LEDGER_FILE };
package/dist/cli.js CHANGED
@@ -1,17 +1,22 @@
1
- import { readFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { join, resolve } from 'node:path';
3
4
  import { pathToFileURL } from 'node:url';
4
5
  import { ErrorCode, HubError } from './core/errors.js';
6
+ import { atomicWrite } from './core/atomic.js';
5
7
  import { initHub, isHubInitialized, LEDGER_FILE, readHubConfig } from './core/hub.js';
6
8
  import { appendLedger, ledgerPath, readLedger, readSequences, writeSequences } from './core/ledger.js';
7
9
  import { acquireLock, assertFencing, lockInfo, releaseLock } from './core/lock.js';
8
10
  import { registerWorkspace, resolveWorkspace } from './core/registry.js';
9
11
  import { buildIndex, emptyMetrics, search } from './core/search.js';
10
12
  import { commitKnowledge, getEntry, listEntries, listProposals } from './core/store.js';
13
+ import { validateHub } from './core/validate.js';
11
14
  import { requireApproval } from './core/approval.js';
12
15
  import { createApiState } from './transport/server.js';
13
- import { startServer } from './transport/http.js';
16
+ import { autoCommit } from './transport/autocommit.js';
17
+ import { startServer, serverUrl } from './transport/http.js';
14
18
  import { createState, handleRpc, serveStdio, TOOLS } from './transport/mcp.js';
19
+ import { buildExtractionMaterial, readExtractState, writeExtractState } from './core/extract.js';
15
20
  function parseArgs(argv) {
16
21
  const args = { _: [], root: process.env['MEMHUB_ROOT'] ?? process.cwd() };
17
22
  for (let i = 0; i < argv.length; i += 1) {
@@ -53,12 +58,42 @@ function parseArgs(argv) {
53
58
  args.port = Number(argv[i + 1]);
54
59
  i += 1;
55
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;
56
80
  default:
57
81
  args._.push(arg);
58
82
  }
59
83
  }
60
84
  return args;
61
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
+ }
62
97
  function out(value, json) {
63
98
  if (json) {
64
99
  console.log(JSON.stringify(value, null, 2));
@@ -112,7 +147,23 @@ export function main(argv) {
112
147
  const state = createApiState(root, args.workspace);
113
148
  const port = args.port ?? 7777;
114
149
  const server = startServer(state, { port });
115
- console.error(`memhub panel: http://127.0.0.1:${port}/ (hub: ${root})`);
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
+ });
116
167
  const shutdown = () => {
117
168
  server.close();
118
169
  process.exit(0);
@@ -200,7 +251,8 @@ export function main(argv) {
200
251
  actor: 'cli-human',
201
252
  }, { readSequences, writeSequences, appendLedger: humanLedger });
202
253
  humanLedger(root, { type: 'proposal.committed', proposalId, knowledgeId: committed.id, channel: 'cli-human', at: new Date().toISOString() });
203
- out({ knowledgeId: committed.id, version: committed.version, path: committed.path }, true);
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);
204
256
  return 0;
205
257
  }
206
258
  finally {
@@ -211,6 +263,67 @@ export function main(argv) {
211
263
  out(Object.keys(TOOLS), true);
212
264
  return 0;
213
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
+ }
214
327
  case 'help':
215
328
  case undefined:
216
329
  printHelp();
@@ -226,12 +339,353 @@ export function main(argv) {
226
339
  return 1;
227
340
  }
228
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
+ }
229
681
  function printHelp() {
230
682
  console.log(`memhub — agent-memory-hub CLI
231
683
 
232
684
  memhub init --root <dir> initialize a hub directory
233
685
  memhub mcp --root <dir> start the MCP stdio server
234
- memhub serve --root <dir> [--port n] start the panel (127.0.0.1, graded inbox)
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)
235
689
  memhub search <query> search accepted knowledge
236
690
  [--detail L0|L1|L2] [--limit n] [--workspace id] [--json]
237
691
  memhub get <ID> [--full] read one entry
@@ -239,6 +693,23 @@ function printHelp() {
239
693
  memhub inbox list list pending proposals
240
694
  memhub inbox approve <PRO-id> human approval -> knowledge (ledgered)
241
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)
242
713
  memhub tools list MCP tool names
243
714
  memhub help this text
244
715
  `);
@@ -247,10 +718,19 @@ function printHelp() {
247
718
  const invokedDirectly = process.argv[1] !== undefined &&
248
719
  (import.meta.url === pathToFileURL(process.argv[1]).href ||
249
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;
250
723
  if (invokedDirectly && process.argv.length > 2) {
251
724
  const code = main(process.argv.slice(2));
252
- if (code !== KEEP_ALIVE)
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) {
253
732
  process.exit(code);
733
+ }
254
734
  }
255
735
  export { createState, handleRpc, readHubConfig, readLedger, registerWorkspace, LEDGER_FILE };
256
736
  //# sourceMappingURL=cli.js.map