evolcore 0.0.41 → 0.0.42-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -1,18 +1,40 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
3
4
  import { isValidAid } from '../aun/aid/validation.js';
4
5
  import { readAuthoritativePersonalFsObject } from '../aun/group/fs-download.js';
5
- import { atomicReadJson, atomicWriteJson } from '../utils/atomic-write.js';
6
+ import { atomicRead, atomicReadJson, atomicRemove, atomicWriteJson, atomicWriteText } from '../utils/atomic-write.js';
6
7
  import { logger } from '../utils/logger.js';
7
- export const OWNER_DIRECTORY_SCOPES = ['contacts', 'agents'];
8
- export const OWNER_DIRECTORY_MAX_OBJECT_BYTES = 24 * 1024;
9
- export const OWNER_DIRECTORY_STALE_AFTER_MS = 30 * 24 * 60 * 60_000;
10
- export const OWNER_DIRECTORY_RETRY_BACKOFF_MS = 60 * 60_000;
8
+ import { resolveRoot } from '../paths.js';
9
+ import { OWNER_DIRECTORY_MARKDOWN_FILE, renderOwnerDirectoryMarkdown } from './owner-directory-markdown.js';
10
+ import { directoryContentDigest } from './canonical-digest.js';
11
+ import { readAllRemarks, OWNER_DIRECTORY_REMARKS_DIR } from './owner-directory-remarks.js';
12
+ import { archiveSnapshot, appendChanges, diffSnapshots, collectAgentMdRefreshAids, isValidContentDigest, } from './owner-directory-store.js';
13
+ /**
14
+ * 名录只有一份 contacts.json:agents 已经并入其中(条目用 owner_aid 分内外、
15
+ * 用 type 分主体类型),不再有独立的 agents 文件。保留 scope 这一层是因为
16
+ * 授权结果、pending 标记和通知摘要都按 scope 组织。
17
+ */
18
+ export { OWNER_DIRECTORY_SCOPES, isOwnerDirectoryScope } from './owner-directory-scope.js';
19
+ import { OWNER_DIRECTORY_SCOPES, isOwnerDirectoryScope } from './owner-directory-scope.js';
20
+ // 单文件要装下 Owner 名下全部 Agent 加全部联系人,24KB 对真实数据太紧;
21
+ // 内存由 MAX_DIRECTORY_ENTRIES 和单字段长度限制兜底,字节数对齐通道上限。
22
+ export const OWNER_DIRECTORY_MAX_OBJECT_BYTES = 128 * 1024;
11
23
  export const OWNER_DIRECTORY_INITIAL_WAIT_MS = 3_000;
24
+ /**
25
+ * 拉取失败后的最大尝试次数。到顶就停下,等下一次 `owner.directory.grant`
26
+ * 事件或 daemon 重启——避免一条拉不下来的名录把每条入站消息都拖成一次网络请求。
27
+ */
28
+ /**
29
+ * 拉取失败后的退避窗口(毫秒),按连续失败次数取,取满后一直用最后一档。
30
+ *
31
+ * 早先的实现是"连续失败 3 次就停,直到重启或新授",但通知是一次性 ACK 的——
32
+ * App 收到 ack 就不再重发,而三条入站消息在几秒内就能烧光 3 次预算。结果是
33
+ * 一次网络抖动就让名录停在旧版本直到 daemon 重启,App 那边却以为已经同步成功。
34
+ * 退避按时间而不是按次数,既不会造成拉取风暴,也不会永久放弃。
35
+ */
36
+ export const OWNER_DIRECTORY_PULL_BACKOFF_MS = [30_000, 120_000, 600_000];
12
37
  const MAX_DIRECTORY_ENTRIES = 100_000;
13
- const MAX_SNAPSHOT_OBJECTS = 2_000;
14
- const MAX_INDEX_SEGMENTS = 1_000;
15
- const MAX_PAGES_PER_INDEX = 50;
16
38
  const SNAPSHOT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
17
39
  const SHA256_RE = /^[a-f0-9]{64}$/;
18
40
  const GRANT_STATUSES = new Set([
@@ -25,6 +47,17 @@ export function parseOwnerDirectoryGrantAbilityResponse(value) {
25
47
  return undefined;
26
48
  return value.result;
27
49
  }
50
+ /** Module-level fetch dedup: ownerAid → in-flight fetch */
51
+ const _fetchInFlight = new Map();
52
+ /**
53
+ * 本进程已做过"启动时无快照检查"的 agent 目录。
54
+ *
55
+ * 键用目录路径:生产环境里每个 agent 的目录是稳定的,等价于按 agent 记;
56
+ * 测试里每个 fixture 用独立目录,天然隔离。进程重启后清空,所以语义是
57
+ * "每次启动检查一次,重连不重复检查"——既保住重启自愈,又不会反复读盘。
58
+ */
59
+ const _startupCheckDone = new Set();
60
+ // ── OwnerDirectoryCache ───────────────────────────────────────────────────────
28
61
  export class OwnerDirectoryCacheError extends Error {
29
62
  code;
30
63
  constructor(code, message) {
@@ -33,15 +66,26 @@ export class OwnerDirectoryCacheError extends Error {
33
66
  this.name = 'OwnerDirectoryCacheError';
34
67
  }
35
68
  }
36
- /** Per-Agent durable snapshots; ECK and prompt rendering are intentionally outside this service. */
69
+ /** Per-Agent durable snapshots plus the derived directory.md that ECK loads. */
37
70
  export class OwnerDirectoryCache {
38
71
  options;
39
72
  now;
40
73
  initialWaitMs;
41
- staleAfterMs;
42
- retryBackoffMs;
43
- inFlight = new Map();
74
+ /** 连续拉取失败次数,决定下一档退避窗口。仅内存,重启清零(重启本身是自愈路径)。 */
75
+ pullFailures = 0;
76
+ /** 上一次拉取失败的时间点;仅在 `pullFailures > 0` 时有意义。 */
77
+ lastPullFailureAt;
44
78
  stateWriteTail = Promise.resolve();
79
+ /**
80
+ * 本 agent 快照的进程内缓存,`null` 表示"读过了,磁盘上没有可用快照"。
81
+ *
82
+ * daemon 进程里 `contacts.json` 只有本实例一个写者,写盘时同步更新这里即可。
83
+ * 额外记一个 mtime+size 指纹,是为了兜住"文件被本实例以外的途径改写"——
84
+ * 比如 CLI 进程直写、或者测试直接落文件。指纹一致时不解析、不一致时重载。
85
+ */
86
+ snapshotCache = new Map();
87
+ /** 备注集合的指纹缓存;目录指纹不变就复用上次解析结果。 */
88
+ remarksStampCache;
45
89
  constructor(options) {
46
90
  this.options = options;
47
91
  if (!isValidAid(options.selfAid) || !isValidAid(options.ownerAid)) {
@@ -52,208 +96,596 @@ export class OwnerDirectoryCache {
52
96
  }
53
97
  this.now = options.now ?? Date.now;
54
98
  this.initialWaitMs = options.initialWaitMs ?? OWNER_DIRECTORY_INITIAL_WAIT_MS;
55
- this.staleAfterMs = options.staleAfterMs ?? OWNER_DIRECTORY_STALE_AFTER_MS;
56
- this.retryBackoffMs = options.retryBackoffMs ?? OWNER_DIRECTORY_RETRY_BACKOFF_MS;
57
99
  }
58
- /** Persist a directory/access result only after validating its subject and active scopes. */
100
+ // ── Authorization ───────────────────────────────────────────────────────────
101
+ /**
102
+ * 记录 Owner 的授权。只保留"能不能读、读到什么时候"。
103
+ *
104
+ * 收到新授权意味着重新开始:失败计数清零,之前被拉黑的范围一并解除。
105
+ */
59
106
  saveAuthorization(result) {
60
107
  logger.info(`[OwnerDirectoryCache] Saving authorization for Owner ${this.options.ownerAid}, status: ${result.status}`);
61
- if (!isRecord(result) || result.owner_aid !== this.options.ownerAid
62
- || result.grantee_aid !== this.options.selfAid || !GRANT_STATUSES.has(result.status)) {
63
- logger.error(`[OwnerDirectoryCache] Authorization validation failed`);
64
- throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access result identity or status is invalid');
65
- }
66
- const rawScopes = result.active_scopes ?? [];
67
- if (!Array.isArray(rawScopes) || rawScopes.some(scope => !isScope(scope))) {
68
- throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access active_scopes is invalid');
69
- }
70
- const activeScopes = [...new Set(rawScopes)];
71
- const expiry = isRecord(result.expires_at_by_scope) ? result.expires_at_by_scope : {};
72
- const expiresAtByScope = {};
73
- for (const scope of activeScopes) {
74
- const expiresAt = expiry[scope];
75
- if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {
76
- throw new OwnerDirectoryCacheError('INVALID_GRANT', `directory/access has invalid expiry for ${scope}`);
77
- }
78
- expiresAtByScope[scope] = expiresAt;
79
- }
80
- const refs = isRecord(result.manifest_refs) ? result.manifest_refs : {};
81
- const manifestRefs = {};
82
- for (const scope of activeScopes) {
83
- if (refs[scope] !== undefined) {
84
- const serialized = JSON.stringify(refs[scope]);
85
- if (!serialized || Buffer.byteLength(serialized, 'utf8') > OWNER_DIRECTORY_MAX_OBJECT_BYTES) {
86
- throw new OwnerDirectoryCacheError('INVALID_GRANT', `directory/access manifest ref for ${scope} is invalid`);
87
- }
88
- manifestRefs[scope] = JSON.parse(serialized);
89
- }
108
+ if (result.owner_aid !== this.options.ownerAid || result.grantee_aid !== this.options.selfAid) {
109
+ throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access result identity is invalid');
110
+ }
111
+ if (!GRANT_STATUSES.has(result.status)) {
112
+ throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access status is invalid');
90
113
  }
91
- const effectiveScopes = ['active', 'sync_pending', 'revoke_pending'].includes(result.status)
92
- ? activeScopes
93
- : [];
94
- if (result.status === 'active' && effectiveScopes.length === 0) {
95
- throw new OwnerDirectoryCacheError('INVALID_GRANT', 'active directory/access result has no active scopes');
114
+ // 撤销/拒绝:不留凭证也不留快照,准入随即回落到"名录不可用"。
115
+ if (result.status !== 'active' && result.status !== 'sync_pending' && result.status !== 'revoke_pending') {
116
+ this.revokeAuthorization(result.status);
117
+ return;
96
118
  }
97
119
  const grant = {
98
- schemaVersion: 1,
99
- status: result.status,
100
- ownerAid: result.owner_aid,
101
- granteeAid: result.grantee_aid,
102
- activeScopes: effectiveScopes,
103
- knownScopes: [...new Set([...(this.loadGrant()?.knownScopes ?? []), ...activeScopes])],
104
- expiresAtByScope,
105
- manifestRefs,
106
- storedAt: this.now(),
120
+ schemaVersion: 2,
121
+ ownerAid: this.options.ownerAid,
122
+ granteeAid: this.options.selfAid,
123
+ grantedAt: this.now(),
124
+ expiresAt: grantExpiryMs(result),
107
125
  };
108
- logger.info(`[OwnerDirectoryCache] Persisting authorization: activeScopes=${JSON.stringify(effectiveScopes)}, path=${this.authorizationPath()}`);
109
126
  fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
110
127
  atomicWriteJson(this.authorizationPath(), grant);
111
128
  fs.chmodSync(this.authorizationPath(), 0o600);
112
- logger.info(`[OwnerDirectoryCache] Authorization saved successfully`);
113
- void this.updateSyncState(state => ({
114
- ...state,
115
- blockedScopes: state.blockedScopes.filter(scope => !effectiveScopes.includes(scope)),
116
- }));
117
- }
118
- /** At startup, wait at most three seconds for first snapshots; stale refreshes stay in background. */
119
- async refreshIfNeeded() {
129
+ this.clearPullFailures();
130
+ logger.info(`[OwnerDirectoryCache] Authorization saved: status=${result.status} expiresAt=${grant.expiresAt}`);
131
+ void this.updateSyncState(state => ({ ...state, blockedScopes: [] })).then(() => this.refreshMarkdown());
132
+ }
133
+ /**
134
+ * 是否具备拉取条件。
135
+ *
136
+ * 这就是全部判断:有授权、未过期、没被远端明确拒绝过。**不按 scope 区分**——
137
+ * 名录只有一份文件,能不能读由 storage 的 ACL 决定,不在这里重复判一次。
138
+ */
139
+ scopeAccess(_scope) {
120
140
  const grant = this.loadGrant();
121
- logger.debug(`[OwnerDirectoryCache] refreshIfNeeded called for ${this.options.ownerAid}, grant exists: ${!!grant}`);
122
- if (!grant) {
123
- logger.debug(`[OwnerDirectoryCache] No authorization grant found, cannot refresh`);
124
- return {};
141
+ if (!grant)
142
+ return 'unavailable';
143
+ if (grant.expiresAt > 0 && grant.expiresAt <= this.now())
144
+ return 'unavailable';
145
+ if (this.readSyncState().blockedScopes.length > 0)
146
+ return 'unavailable';
147
+ return 'authorized';
148
+ }
149
+ // ── Pending update ──────────────────────────────────────────────────────────
150
+ writePendingUpdate(update) {
151
+ const stored = { schemaVersion: 1, ...update };
152
+ fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
153
+ atomicWriteJson(this.pendingPath(), stored);
154
+ }
155
+ readPendingUpdate() {
156
+ const raw = atomicReadJson(this.pendingPath());
157
+ if (!isRecord(raw) || raw.schemaVersion !== 1 || raw.ownerAid !== this.options.ownerAid)
158
+ return undefined;
159
+ return raw;
160
+ }
161
+ clearPendingUpdate() {
162
+ try {
163
+ atomicRemove(this.pendingPath());
125
164
  }
126
- logger.info(`[OwnerDirectoryCache] Active scopes: ${JSON.stringify(grant.activeScopes)}`);
127
- const firstSyncs = [];
128
- const result = {};
129
- for (const scope of grant.activeScopes) {
130
- if (!this.isAuthorized(grant, scope)) {
131
- logger.debug(`[OwnerDirectoryCache] Scope ${scope} not authorized, skipping`);
165
+ catch { /* ignore */ }
166
+ }
167
+ // ── handleOwnerChangedEvent ────────────────────────────────────────────────
168
+ async handleOwnerChangedEvent(senderAid, digests) {
169
+ if (senderAid !== this.options.ownerAid) {
170
+ throw new OwnerDirectoryCacheError('UNTRUSTED_OWNER_EVENT', 'directory change sender is not the authorized Owner');
171
+ }
172
+ // 每条通知都是独立的变更事件:退避在这里归零,立即重试一次。
173
+ // 通知本身是有来源保证的(App 对未 ACK 的通知会退避重发),不会造成风暴。
174
+ this.clearPullFailures();
175
+ this.writePendingUpdate({
176
+ ownerAid: this.options.ownerAid,
177
+ operationId: `notification-${randomUUID()}`,
178
+ digests: digests ?? {},
179
+ markedAtMs: this.now(),
180
+ });
181
+ logger.info(`[OwnerDirectoryCache] Pending written for ${this.options.ownerAid}`);
182
+ }
183
+ /** 授权被明确撤销或拒绝时,清掉本地快照,避免继续拿旧数据做准入判断。 */
184
+ revokeAuthorization(status) {
185
+ this.clearPullFailures();
186
+ atomicRemove(this.authorizationPath());
187
+ atomicRemove(this.cachePath(OWNER_DIRECTORY_SCOPES[0]));
188
+ this.snapshotCache.clear();
189
+ logger.info(`[OwnerDirectoryCache] Authorization revoked (${status}) for ${this.options.ownerAid}`);
190
+ this.refreshMarkdown();
191
+ }
192
+ /**
193
+ * 启动时补一次标记:**只在本 agent 级目录里没有任何快照时**。
194
+ *
195
+ * 这是"从没同步成功过"的唯一自愈路径。有快照就什么都不做——重连、重启都不该
196
+ * 触发全量拉取,名录更新由 `owner.directory.changed` 通知驱动。
197
+ *
198
+ * **每个进程每个 agent 只检查一次**:检查结果记在模块级内存里,重连不再重复
199
+ * 读盘。进程重启后标记清空,所以"重启检查一次、重连不检查"的语义成立。
200
+ *
201
+ * 不产生网络请求:只写 pending,真正的拉取推迟到下一条入站消息。
202
+ */
203
+ writeStartupPendingIfEmpty() {
204
+ const key = this.options.directory;
205
+ if (_startupCheckDone.has(key))
206
+ return;
207
+ _startupCheckDone.add(key);
208
+ const scope = OWNER_DIRECTORY_SCOPES[0];
209
+ if (this.scopeAccess(scope) !== 'authorized')
210
+ return;
211
+ if (this.readCachedSnapshot(scope))
212
+ return;
213
+ if (this.readPendingUpdate())
214
+ return;
215
+ this.writePendingUpdate({
216
+ ownerAid: this.options.ownerAid,
217
+ operationId: 'startup',
218
+ digests: {},
219
+ markedAtMs: this.now(),
220
+ });
221
+ logger.info(`[OwnerDirectoryCache] No local snapshot, startup pending written for ${this.options.ownerAid}`);
222
+ }
223
+ // ── processPendingIfNeeded ─────────────────────────────────────────────────
224
+ /**
225
+ * 阶段一入口:有 pending 就把共享缓存拉新。**只写共享缓存,不落地到 agent 目录。**
226
+ *
227
+ * 落地是独立的一步(`applyFromSharedCache`),由每条进入消息队列的消息触发。
228
+ * 拆开的理由:网络拉取是所有 agent 共享的,落地是每个 agent 自己的,时机和
229
+ * 代价都不一样——混在一起会让"来一条消息"既可能发网络请求又可能写盘。
230
+ */
231
+ async processPendingIfNeeded() {
232
+ const pending = this.readPendingUpdate();
233
+ if (!pending)
234
+ return;
235
+ // 退避窗口内不发请求:pending 留着,到点自动重试。见 OWNER_DIRECTORY_PULL_BACKOFF_MS。
236
+ const wait = this.pullBackoffRemainingMs();
237
+ if (wait > 0) {
238
+ logger.debug(`[OwnerDirectoryCache] Pull backed off for ${wait}ms (${this.pullFailures} failures) for ${this.options.ownerAid}`);
239
+ return;
240
+ }
241
+ logger.info(`[OwnerDirectoryCache] Processing pending for ${this.options.ownerAid}, op=${pending.operationId}, attempt=${this.pullFailures + 1}`);
242
+ try {
243
+ await this.fetchToSharedCache(pending.digests);
244
+ this.clearPullFailures();
245
+ this.clearPendingUnlessSuperseded(pending);
246
+ }
247
+ catch (error) {
248
+ this.pullFailures++;
249
+ this.lastPullFailureAt = this.now();
250
+ const next = OWNER_DIRECTORY_PULL_BACKOFF_MS[Math.min(this.pullFailures, OWNER_DIRECTORY_PULL_BACKOFF_MS.length) - 1];
251
+ logger.warn(`[OwnerDirectoryCache] Pending pull failed (${this.pullFailures} in a row, next retry in ${next}ms): ${errorText(error)}`);
252
+ }
253
+ }
254
+ /**
255
+ * 拉取成功后清 pending,但拉取途中若有新通知覆盖写(`operationId` 或 `markedAtMs` 变了)就保留。
256
+ *
257
+ * 本次拿到的数据未必对应该通知,清掉等于把这次变更永久丢掉——留给下一轮。
258
+ * 需求路径(`lookupByAid`)也走这里,否则同一批 digest 会被反复处理。
259
+ */
260
+ clearPendingUnlessSuperseded(pending) {
261
+ const latest = this.readPendingUpdate();
262
+ if (latest && (latest.operationId !== pending.operationId || latest.markedAtMs !== pending.markedAtMs)) {
263
+ logger.info(`[OwnerDirectoryCache] Pending superseded during pull for ${this.options.ownerAid}, keeping newer mark`);
264
+ return;
265
+ }
266
+ this.clearPendingUpdate();
267
+ }
268
+ /** 距离退避窗口结束还有多久;0 表示可以立刻拉取。 */
269
+ pullBackoffRemainingMs() {
270
+ if (this.pullFailures === 0 || this.lastPullFailureAt === undefined)
271
+ return 0;
272
+ const window = OWNER_DIRECTORY_PULL_BACKOFF_MS[Math.min(this.pullFailures, OWNER_DIRECTORY_PULL_BACKOFF_MS.length) - 1];
273
+ return Math.max(0, this.lastPullFailureAt + window - this.now());
274
+ }
275
+ clearPullFailures() {
276
+ this.pullFailures = 0;
277
+ this.lastPullFailureAt = undefined;
278
+ }
279
+ // ── 阶段一 / 阶段二 / 组合 ─────────────────────────────────────────────────
280
+ /**
281
+ * 阶段一:把 Owner 名录拉到**共享缓存**,不碰任何 agent 目录。
282
+ *
283
+ * 共享缓存是同一台机器上所有 agent 共用的(`$EVOLCORE_HOME/data/owner-directory/<ownerAid>/`),
284
+ * 所以这一步只需要发一次网络请求:
285
+ * - 通知 digest 与共享缓存 digest 一致 → 0 次网络请求,直接读共享缓存
286
+ * - 否则模块级单飞 get_object:同进程内并发调用共用同一个 Promise
287
+ *
288
+ * 写盘失败只 warn 不抛(共享缓存坏了下一次会重写);返回的是本次拿到的数据,
289
+ * 即使共享缓存写失败,调用方仍可据此落地。
290
+ */
291
+ async fetchToSharedCache(digests) {
292
+ // ① 检查共享缓存:通知 digest 与共享缓存一致时,跳过网络请求
293
+ const sharedFresh = OWNER_DIRECTORY_SCOPES.every(scope => {
294
+ const hintDigest = digests?.[scope];
295
+ if (!hintDigest)
296
+ return false; // 无 hint(startup),需要拉
297
+ const sharedDigest = this._readSharedCacheDigest(scope);
298
+ return sharedDigest === hintDigest;
299
+ });
300
+ if (sharedFresh) {
301
+ logger.debug(`[OwnerDirectoryCache] All scopes fresh in shared cache for ${this.options.ownerAid}, skipping fetch`);
302
+ return this._assertComplete(this._readSharedCache());
303
+ }
304
+ // ② 模块级单飞:同进程只发一次网络请求
305
+ const existing = _fetchInFlight.get(this.options.ownerAid);
306
+ const outcome = existing
307
+ ? await existing
308
+ : await (() => {
309
+ const fetchPromise = this._doFetch().then(result => {
310
+ this._writeSharedCache(result.data);
311
+ return result;
312
+ }).finally(() => {
313
+ if (_fetchInFlight.get(this.options.ownerAid) === fetchPromise) {
314
+ _fetchInFlight.delete(this.options.ownerAid);
315
+ }
316
+ });
317
+ _fetchInFlight.set(this.options.ownerAid, fetchPromise);
318
+ return fetchPromise;
319
+ })();
320
+ // 远端明确拒绝:作废本地快照并标记 blocked,重试没有意义。逐个 scope 处理,
321
+ // 因为一次拉取里可能多个 scope 都被拒;单飞复用的调用方也要各自执行这一步。
322
+ for (const scope of outcome.denied) {
323
+ if (this.scopeAccess(scope) === 'authorized')
324
+ await this.blockScope(scope);
325
+ }
326
+ return this._assertComplete(outcome.data);
327
+ }
328
+ /**
329
+ * 已授权范围一个都没拿到,就不算拉取成功。
330
+ *
331
+ * `_doFetch` 对每个 scope 单独兜错,全部失败也只是返回空对象——缺项判定必须
332
+ * 在这里做,否则调用方会把"一个字节都没拉下来"当成成功,把 pending 清掉。
333
+ */
334
+ _assertComplete(fetched) {
335
+ const missing = OWNER_DIRECTORY_SCOPES.filter(scope => this.scopeAccess(scope) === 'authorized' && !fetched[scope]);
336
+ if (missing.length > 0) {
337
+ throw new OwnerDirectoryCacheError('FETCH_INCOMPLETE', `owner directory fetch incomplete: ${missing.join(', ')}`);
338
+ }
339
+ return fetched;
340
+ }
341
+ /**
342
+ * 阶段二:共享缓存 → 本 agent 目录。
343
+ *
344
+ * 判重全靠 `_applyFile` 内部的 content_digest 比对,没有新内容时几乎零成本,
345
+ * 所以调用方可以无条件、每条消息都调一次。
346
+ *
347
+ * 共享缓存里没有可用内容(首次启动、文件损坏)时返回 false,不抛错——
348
+ * 这不是失败,只是还没有东西可落地。
349
+ */
350
+ async applyFromSharedCache() {
351
+ // 热路径早退:每条入站消息都会调到这里,而绝大多数消息发生时名录早就落过盘。
352
+ // 先只比 content_digest,命中就连 JSON 都不解析——`_readSharedCache` 会做
353
+ // 逐条校验 + 全量摘要重算,那是拉取期才需要的成本。
354
+ if (OWNER_DIRECTORY_SCOPES.every(scope => this._isSharedCacheApplied(scope))) {
355
+ this.refreshMarkdown();
356
+ return true;
357
+ }
358
+ const fetched = this._readSharedCache();
359
+ if (OWNER_DIRECTORY_SCOPES.every(scope => !fetched[scope])) {
360
+ logger.debug(`[OwnerDirectoryCache] Shared cache empty for ${this.options.ownerAid}, nothing to apply`);
361
+ return false;
362
+ }
363
+ await this._applyAll(fetched);
364
+ return true;
365
+ }
366
+ /**
367
+ * 共享缓存与本地快照内容是否已一致。
368
+ *
369
+ * 只读共享缓存里的声明 digest 与本地快照的 digest 做比较。这一层会让
370
+ * "第一个拉取的 agent 替后续 agent 做了校验"——与 `_readSharedCache` 不同,
371
+ * 这里不做摘要重算。判据是:共享缓存是由本进程的 `_writeSharedCache` 写的,
372
+ * 而写入前已经过 `parseDirectoryObject` 校验;本地快照的 digest 同样来自
373
+ * 校验通过的文档。两边一致即意味着"没有新内容",不存在需要重新校验的输入。
374
+ */
375
+ _isSharedCacheApplied(scope) {
376
+ const sharedDigest = this._readSharedCacheDigest(scope);
377
+ if (!sharedDigest)
378
+ return false;
379
+ return this.readCachedSnapshot(scope)?.contentDigest === sharedDigest;
380
+ }
381
+ /**
382
+ * 拉取 + 落地,一次做完。
383
+ *
384
+ * 需求路径(`lookupByAid`、准入)用这个:用户正等着结果,不能只拉不落。
385
+ */
386
+ async pullAndApply(digests) {
387
+ const fetched = await this.fetchToSharedCache(digests);
388
+ await this._applyAll(fetched);
389
+ }
390
+ /**
391
+ * 各 agent 各自写盘(权限检查 per-agent)。
392
+ *
393
+ * 完整性由阶段一保证(`_assertComplete`);这里只跳过"拉取之后权限被撤"的范围。
394
+ */
395
+ async _applyAll(fetched) {
396
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
397
+ if (this.scopeAccess(scope) !== 'authorized')
132
398
  continue;
133
- }
134
- const snapshot = this.readCachedSnapshot(scope);
135
- if (!snapshot) {
136
- logger.info(`[OwnerDirectoryCache] No cached snapshot for ${scope}, triggering first sync`);
137
- firstSyncs.push(this.sync(scope).catch(error => {
138
- logger.error(`[OwnerDirectoryCache] First sync failed for ${scope}: ${error}`);
139
- this.options.onError?.(scope, error);
140
- }));
399
+ const file = fetched[scope];
400
+ if (!file)
141
401
  continue;
402
+ await this._applyFile(scope, file);
403
+ }
404
+ }
405
+ // ── 共享缓存($EVOLCORE_HOME/data/owner-directory/<ownerAid>/) ────────────
406
+ _sharedCacheDir() {
407
+ return path.join(resolveRoot(), 'data', 'owner-directory', this.options.ownerAid);
408
+ }
409
+ _sharedCachePath(scope) {
410
+ return path.join(this._sharedCacheDir(), `${scope}.json`);
411
+ }
412
+ _readSharedCacheDigest(scope) {
413
+ try {
414
+ const raw = atomicReadJson(this._sharedCachePath(scope));
415
+ if (!isRecord(raw) || raw.schemaVersion !== 2)
416
+ return undefined;
417
+ const document = raw.document;
418
+ if (!isRecord(document))
419
+ return undefined;
420
+ const digest = document.content_digest;
421
+ return isValidContentDigest(digest) ? digest : undefined;
422
+ }
423
+ catch {
424
+ return undefined;
425
+ }
426
+ }
427
+ /**
428
+ * 从共享缓存读出原始文档,再走一遍和网络拉取完全相同的校验。
429
+ *
430
+ * 共享缓存是我们自己写的,但它同样是磁盘上的字节:可能是旧版本格式、
431
+ * 可能被别的 agent 写坏。只信任 sha256 而不重算摘要,等于让第一个拉取的
432
+ * agent 替所有后续 agent 做了校验。
433
+ */
434
+ _readSharedCache() {
435
+ const result = {};
436
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
437
+ try {
438
+ const raw = atomicReadJson(this._sharedCachePath(scope));
439
+ if (!isRecord(raw) || raw.schemaVersion !== 2)
440
+ continue;
441
+ if (!isRecord(raw.document))
442
+ continue;
443
+ if (raw.ownerAid !== this.options.ownerAid || raw.scope !== scope)
444
+ continue;
445
+ const sha256 = typeof raw.sha256 === 'string' ? raw.sha256.toLowerCase() : '';
446
+ if (!SHA256_RE.test(sha256))
447
+ continue;
448
+ result[scope] = this.parseDirectoryObject(raw.document, sha256, scope);
142
449
  }
143
- logger.info(`[OwnerDirectoryCache] Found cached snapshot for ${scope}, total entries: ${snapshot.total}`);
144
- result[scope] = snapshot;
145
- if (this.isStale(scope)) {
146
- logger.info(`[OwnerDirectoryCache] Snapshot for ${scope} is stale, triggering background refresh`);
147
- this.startAutomaticSync(scope);
450
+ catch (error) {
451
+ logger.warn(`[OwnerDirectoryCache] Shared cache for ${scope} rejected: ${errorText(error)}`);
148
452
  }
149
453
  }
150
- if (firstSyncs.length > 0) {
151
- await waitAtMost(Promise.all(firstSyncs), this.initialWaitMs);
152
- for (const scope of grant.activeScopes) {
153
- if (this.isAuthorized(grant, scope)) {
154
- const snapshot = this.readCachedSnapshot(scope);
155
- if (snapshot)
156
- result[scope] = snapshot;
157
- }
454
+ return result;
455
+ }
456
+ _writeSharedCache(data) {
457
+ try {
458
+ const dir = this._sharedCacheDir();
459
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
460
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
461
+ const file = data[scope];
462
+ if (!file)
463
+ continue;
464
+ // 存远端原始文档(snake_case、未归一化):摘要只能在原样 entries 上重算。
465
+ const stored = {
466
+ schemaVersion: 2,
467
+ ownerAid: file.ownerAid,
468
+ scope: file.scope,
469
+ sha256: file.sha256,
470
+ document: file.raw,
471
+ };
472
+ atomicWriteJson(this._sharedCachePath(scope), stored);
473
+ fs.chmodSync(this._sharedCachePath(scope), 0o600);
158
474
  }
159
475
  }
160
- return result;
476
+ catch (error) {
477
+ logger.warn(`[OwnerDirectoryCache] Failed to write shared cache: ${errorText(error)}`);
478
+ }
479
+ }
480
+ // ── readSnapshot / lookupByAid ─────────────────────────────────────────────
481
+ readSnapshot(scope) {
482
+ if (!isOwnerDirectoryScope(scope))
483
+ return undefined;
484
+ return this.readCachedSnapshot(scope);
161
485
  }
162
- /** Cache hits are local. A miss forces a complete remote sync before reporting not_found. */
163
486
  async lookupByAid(scope, aid) {
164
- if (!isScope(scope) || !isValidAid(aid)) {
487
+ if (!isOwnerDirectoryScope(scope) || !isValidAid(aid)) {
165
488
  return { status: 'unavailable', error: new OwnerDirectoryCacheError('INVALID_QUERY', 'scope or AID is invalid') };
166
489
  }
167
- logger.info(`[OwnerDirectoryCache] Looking up AID ${aid} in scope ${scope}`);
168
490
  const current = this.readCachedSnapshot(scope);
169
- const cachedEntry = current?.entries.find(entry => entry.aid === aid);
170
- if (current && cachedEntry) {
171
- logger.info(`[OwnerDirectoryCache] Found ${aid} in cached snapshot, name: ${cachedEntry.name}`);
172
- if (this.isStale(scope))
173
- this.startAutomaticSync(scope);
491
+ const cachedEntry = current?.entries.find(e => e.aid === aid);
492
+ if (current && cachedEntry)
174
493
  return { status: 'found', entry: cachedEntry, snapshot: current };
175
- }
176
- logger.info(`[OwnerDirectoryCache] AID ${aid} not in cache, forcing sync`);
177
494
  try {
178
- const refreshed = await this.sync(scope);
179
- const entry = refreshed.entries.find(item => item.aid === aid);
180
- if (entry) {
181
- logger.info(`[OwnerDirectoryCache] Found ${aid} after sync, name: ${entry.name}`);
182
- }
183
- else {
184
- logger.info(`[OwnerDirectoryCache] AID ${aid} not found in Owner directory ${scope}`);
185
- }
186
- return entry ? { status: 'found', entry, snapshot: refreshed } : { status: 'not_found', snapshot: refreshed };
495
+ // 需求路径必须"拉 + 落"一次做完:调用方在等这个结果,
496
+ // 只更新共享缓存的话本地快照还是旧的,刚加的人照样查不到。
497
+ const pending = this.readPendingUpdate();
498
+ await this.pullAndApply(pending?.digests);
499
+ // 这次拉取已经覆盖了 pending 的内容,标记可以清了;否则下一条消息
500
+ // 会拿同一批 digest 再走一遍拉取路径。失败时不清,交给退避重试。
501
+ if (pending)
502
+ this.clearPendingUnlessSuperseded(pending);
503
+ const refreshed = this.readCachedSnapshot(scope);
504
+ const entry = refreshed?.entries.find(e => e.aid === aid);
505
+ if (!refreshed)
506
+ return { status: 'unavailable', error: new OwnerDirectoryCacheError('NOT_AUTHORIZED', 'scope unavailable') };
507
+ return entry
508
+ ? { status: 'found', entry, snapshot: refreshed }
509
+ : { status: 'not_found', snapshot: refreshed };
187
510
  }
188
511
  catch (error) {
189
- logger.error(`[OwnerDirectoryCache] Lookup failed for ${aid}: ${errorText(error)}`);
190
512
  return { status: 'unavailable', error };
191
513
  }
192
514
  }
193
- /** Called by an authenticated Owner-directory change handler; event data itself is ignored. */
194
- async handleOwnerChangedEvent(senderAid) {
195
- if (senderAid !== this.options.ownerAid) {
196
- throw new OwnerDirectoryCacheError('UNTRUSTED_OWNER_EVENT', 'directory change sender is not the authorized Owner');
515
+ // ── Internal: fetch ──────────────────────────────────────────────────────────
516
+ async _doFetch() {
517
+ if (!this.options.client)
518
+ throw new OwnerDirectoryCacheError('CLIENT_UNAVAILABLE', 'fetch requires a connected AUN client');
519
+ const result = {};
520
+ const denied = [];
521
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
522
+ try {
523
+ const key = `data/directories/v2/${scope}.json`;
524
+ const { bytes, metadata } = await readAuthoritativePersonalFsObject(this.options.client, `/${key}`, this.options.ownerAid, OWNER_DIRECTORY_MAX_OBJECT_BYTES);
525
+ const sha256 = typeof metadata.sha256 === 'string' ? metadata.sha256.toLowerCase() : '';
526
+ if (!SHA256_RE.test(sha256))
527
+ throw new OwnerDirectoryCacheError('INVALID_DIGEST', `bad sha256 for ${scope}`);
528
+ let text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
529
+ if (text.charCodeAt(0) === 0xfeff)
530
+ text = text.slice(1);
531
+ const parsed = JSON.parse(text);
532
+ result[scope] = this.parseDirectoryObject(parsed, sha256, scope);
533
+ logger.info(`[OwnerDirectoryCache] Fetched ${scope}: total=${result[scope].total} digest=${result[scope].contentDigest?.slice(0, 8) ?? 'none'}`);
534
+ }
535
+ catch (error) {
536
+ const normalized = toDirectoryError(error);
537
+ logger.warn(`[OwnerDirectoryCache] Fetch failed for ${scope}: ${errorText(normalized)}`);
538
+ this.options.onError?.(scope, normalized);
539
+ // 远端拒绝随结果返回,由调用方作废自己的本地快照;其它错误保持 pending,
540
+ // 交给时间退避重试。拒绝信息必须在返回值里走——单飞复用者也要看得到。
541
+ if (isPermissionDenied(normalized))
542
+ denied.push(scope);
543
+ }
197
544
  }
198
- const grant = this.loadGrant();
199
- if (!grant)
200
- return {};
201
- const scopes = grant.activeScopes.filter(scope => this.isAuthorized(grant, scope));
202
- const results = await Promise.allSettled(scopes.map(async (scope) => [scope, await this.sync(scope)]));
203
- return Object.fromEntries(results
204
- .filter((result) => result.status === 'fulfilled')
205
- .map(result => result.value));
206
- }
207
- async sync(scope) {
208
- if (!isScope(scope))
209
- throw new OwnerDirectoryCacheError('INVALID_SCOPE', 'unknown Owner directory scope');
210
- const current = this.inFlight.get(scope);
211
- if (current) {
212
- logger.debug(`[OwnerDirectoryCache] Sync already in flight for ${scope}`);
213
- return current;
545
+ return { data: result, denied };
546
+ }
547
+ /**
548
+ * 校验并解析一份名录快照。网络拉取和共享缓存读回走同一条路径——
549
+ * 共享缓存里的内容同样不可信,不能因为"是我们自己写的"就跳过校验。
550
+ *
551
+ * 摘要必须在原始 `entries` 上重算:normalizeEntry 会丢未知字段、把 null
552
+ * 变成缺失,用归一化后的数据算必然对不上。
553
+ */
554
+ parseDirectoryObject(parsed, sha256, scope) {
555
+ if (!isRecord(parsed))
556
+ throw new OwnerDirectoryCacheError('INVALID_FORMAT', `${scope}.json is not a JSON object`);
557
+ if (parsed.schema_version !== 2)
558
+ throw new OwnerDirectoryCacheError('SCHEMA_VERSION', `${scope}.json is not schema_version 2`);
559
+ if (parsed.owner_aid !== this.options.ownerAid)
560
+ throw new OwnerDirectoryCacheError('OWNER_MISMATCH', `${scope}.json owner_aid mismatch`);
561
+ if (parsed.scope !== scope)
562
+ throw new OwnerDirectoryCacheError('SCOPE_MISMATCH', `${scope}.json scope field mismatch`);
563
+ const entries = parsed.entries;
564
+ if (!Array.isArray(entries))
565
+ throw new OwnerDirectoryCacheError('INVALID_FORMAT', `${scope}.json entries is not an array`);
566
+ if (entries.length > MAX_DIRECTORY_ENTRIES)
567
+ throw new OwnerDirectoryCacheError('TOO_MANY_ENTRIES', `${scope}.json exceeds entry limit`);
568
+ // total 是声明值,必须和实际条目数一致:以 entries 为准推导等于接受截断的文件。
569
+ if (parsed.total !== entries.length) {
570
+ throw new OwnerDirectoryCacheError('TOTAL_MISMATCH', `${scope}.json total=${String(parsed.total)} but entries.length=${entries.length}`);
214
571
  }
215
- const grant = this.loadGrant();
216
- if (!grant || !this.isAuthorized(grant, scope)) {
217
- logger.error(`[OwnerDirectoryCache] Not authorized to sync ${scope}`);
218
- throw new OwnerDirectoryCacheError('NOT_AUTHORIZED', `Owner directory scope ${scope} is not active`);
219
- }
220
- logger.info(`[OwnerDirectoryCache] Starting sync for ${scope}`);
221
- const task = this.runSync(scope, grant).finally(() => {
222
- if (this.inFlight.get(scope) === task)
223
- this.inFlight.delete(scope);
572
+ if (typeof parsed.source_revision !== 'string' || !SHA256_RE.test(parsed.source_revision)) {
573
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json source_revision is not a sha256 hex string`);
574
+ }
575
+ for (const field of ['source_observed_at_ms', 'updated_at_ms']) {
576
+ const value = parsed[field];
577
+ if (!Number.isSafeInteger(value) || value < 0) {
578
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json ${field} is not a non-negative integer`);
579
+ }
580
+ }
581
+ // 逐条语义校验:aid 合法且唯一,条目 owner_aid 合法(内外的判据,可以不同于根)。
582
+ const seen = new Set();
583
+ for (const entry of entries) {
584
+ if (!isRecord(entry))
585
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has a non-object entry`);
586
+ if (typeof entry.aid !== 'string' || !entry.aid || !isValidAid(entry.aid)) {
587
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has an entry with invalid aid`);
588
+ }
589
+ if (seen.has(entry.aid))
590
+ throw new OwnerDirectoryCacheError('DUPLICATE_AID', `${scope}.json repeats aid ${entry.aid}`);
591
+ seen.add(entry.aid);
592
+ // `owner_aid` 可选:外部人类、群、以及尚未补全的外部 agent 都可能没有。
593
+ // 有值时必须是合法 AID;它是否等于 `owner.aid` 决定内外,那是分组的事,不是校验的事。
594
+ if (entry.owner_aid !== undefined && entry.owner_aid !== null
595
+ && (typeof entry.owner_aid !== 'string' || (entry.owner_aid.trim() && !isValidAid(entry.owner_aid.trim())))) {
596
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json entry ${entry.aid} has invalid owner_aid`);
597
+ }
598
+ if (typeof entry.name !== 'string' || typeof entry.remark !== 'string') {
599
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json entry ${entry.aid} name/remark must be strings`);
600
+ }
601
+ const signedAt = entry.agent_md_signed_at;
602
+ if (signedAt !== null && !Number.isSafeInteger(signedAt)) {
603
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json entry ${entry.aid} agent_md_signed_at must be an integer or null`);
604
+ }
605
+ }
606
+ // 身份对象:owner 存在时其 aid 必须就是根 owner_aid;personal_assistant 是
607
+ // 身份元数据,不参与条目集合。两者都原样进入摘要输入。
608
+ const ownerIdentity = parsed.owner;
609
+ if (ownerIdentity !== undefined) {
610
+ if (!isRecord(ownerIdentity))
611
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json owner is not an object`);
612
+ if (ownerIdentity.aid !== this.options.ownerAid) {
613
+ throw new OwnerDirectoryCacheError('OWNER_MISMATCH', `${scope}.json owner.aid does not match root owner_aid`);
614
+ }
615
+ }
616
+ const personalAssistant = parsed.personal_assistant;
617
+ if (personalAssistant !== undefined && !isRecord(personalAssistant)) {
618
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json personal_assistant is not an object`);
619
+ }
620
+ // 重算摘要。声明值只是待校验的期望值;不一致说明文件被改坏或截断,整份拒绝。
621
+ const declared = parsed.content_digest;
622
+ if (typeof declared !== 'string' || !isValidContentDigest(declared)) {
623
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json content_digest is not a sha256 hex string`);
624
+ }
625
+ const recomputed = directoryContentDigest({
626
+ entries,
627
+ owner: ownerIdentity,
628
+ personalAssistant,
224
629
  });
225
- this.inFlight.set(scope, task);
226
- return task;
227
- }
228
- readSnapshot(scope) {
229
- if (!isScope(scope))
230
- return undefined;
231
- return this.readCachedSnapshot(scope);
232
- }
233
- /** A scope never granted is optional; an expired/revoked/blocked scope is unavailable. */
234
- scopeAccess(scope) {
235
- const grant = this.loadGrant();
236
- if (!grant || !['active', 'sync_pending', 'revoke_pending'].includes(grant.status))
237
- return 'unavailable';
238
- if (!grant.activeScopes.includes(scope))
239
- return grant.knownScopes.includes(scope) ? 'unavailable' : 'not_authorized';
240
- if (!this.isAuthorized(grant, scope) || this.readSyncState().blockedScopes.includes(scope))
241
- return 'unavailable';
242
- return 'authorized';
630
+ if (recomputed !== declared) {
631
+ throw new OwnerDirectoryCacheError('DIGEST_MISMATCH', `${scope}.json content_digest mismatch: declared=${declared.slice(0, 12)} recomputed=${recomputed.slice(0, 12)}`);
632
+ }
633
+ return {
634
+ raw: parsed, sha256, ownerAid: this.options.ownerAid, scope, schemaVersion: 2,
635
+ contentDigest: declared,
636
+ snapshotId: typeof parsed.snapshot_id === 'string' && SNAPSHOT_ID_RE.test(parsed.snapshot_id) ? parsed.snapshot_id : sha256.slice(0, 64),
637
+ total: entries.length,
638
+ updatedAtMs: parsed.updated_at_ms,
639
+ entries: entries,
640
+ owner: parseIdentityField(parsed.owner),
641
+ personalAssistant: parseIdentityField(parsed.personal_assistant),
642
+ };
243
643
  }
244
- async runSync(scope, grant) {
644
+ // ── Internal: applyFile ──────────────────────────────────────────────────────
645
+ async _applyFile(scope, file) {
646
+ const prev = this.readCachedSnapshot(scope);
647
+ const localDigest = prev?.contentDigest;
648
+ if (file.contentDigest && localDigest && file.contentDigest === localDigest) {
649
+ logger.debug(`[OwnerDirectoryCache] ${scope} content_digest matches local cache, skipping write`);
650
+ // 内容没变但渲染规则可能变了(分组规则、备注、外部开关),重算一次。
651
+ // refreshMarkdown 自己会比对字节,内容相同就不落盘。
652
+ this.refreshMarkdown();
653
+ return;
654
+ }
245
655
  const attemptedAt = this.now();
246
- logger.info(`[OwnerDirectoryCache] runSync starting for ${scope}`);
247
656
  await this.updateFileState(scope, { lastAttemptAt: attemptedAt, status: 'syncing', error: undefined });
248
657
  try {
249
- logger.info(`[OwnerDirectoryCache] Fetching complete snapshot for ${scope} from Owner storage`);
250
- const snapshot = await this.fetchCompleteSnapshot(scope);
251
- logger.info(`[OwnerDirectoryCache] Snapshot fetched successfully for ${scope}, entries: ${snapshot.total}, snapshotId: ${snapshot.snapshotId}`);
252
- const stored = { schemaVersion: 1, ...snapshot };
658
+ const entries = file.entries.map(e => normalizeEntry(e));
659
+ const aids = new Set(entries.map(e => e.aid));
660
+ if (aids.size !== entries.length)
661
+ throw new OwnerDirectoryCacheError('DUPLICATE_AID', `${scope} has duplicate AIDs`);
662
+ const snapshot = {
663
+ ownerAid: this.options.ownerAid,
664
+ granteeAid: this.options.selfAid,
665
+ scope,
666
+ snapshotId: file.snapshotId ?? file.sha256.slice(0, 64),
667
+ contentDigest: file.contentDigest,
668
+ total: entries.length,
669
+ fetchedAt: this.now(),
670
+ ...(file.updatedAtMs !== undefined ? { updatedAtMs: file.updatedAtMs } : {}),
671
+ entries,
672
+ ...(file.owner ? { owner: file.owner } : {}),
673
+ ...(file.personalAssistant ? { personalAssistant: file.personalAssistant } : {}),
674
+ };
675
+ archiveSnapshot(this.options.directory, scope);
676
+ const stored = { schemaVersion: 2, ...snapshot };
253
677
  fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
254
678
  atomicWriteJson(this.cachePath(scope), stored);
255
679
  fs.chmodSync(this.cachePath(scope), 0o600);
256
- logger.info(`[OwnerDirectoryCache] Snapshot saved to ${this.cachePath(scope)}`);
680
+ this.snapshotCache.set(scope, { snapshot, stamp: this.cacheStamp(scope) });
681
+ // agents.json 已并入 contacts.json:首次成功应用后清掉遗留文件。必须连热备
682
+ // 一起删,否则 atomicRead 会把 `agents.json_` 当成中断的 rename 恢复回来。
683
+ atomicRemove(path.join(this.options.directory, 'agents.json'));
684
+ logger.info(`[OwnerDirectoryCache] Applied ${scope}: total=${snapshot.total}`);
685
+ const prevMeta = prev ? { owner: prev.owner, personalAssistant: prev.personalAssistant } : undefined;
686
+ const nextMeta = { owner: snapshot.owner, personalAssistant: snapshot.personalAssistant };
687
+ const changes = diffSnapshots(scope, snapshot, prev, nextMeta, prevMeta);
688
+ appendChanges(this.options.directory, changes);
257
689
  await this.updateFileState(scope, {
258
690
  lastAttemptAt: attemptedAt,
259
691
  lastSuccessAt: snapshot.fetchedAt,
@@ -261,174 +693,98 @@ export class OwnerDirectoryCache {
261
693
  status: 'ready',
262
694
  error: undefined,
263
695
  });
264
- return snapshot;
696
+ this.refreshMarkdown();
697
+ try {
698
+ if (this.options.onSnapshotChanged && changes.length > 0) {
699
+ const agentMdAids = collectAgentMdRefreshAids(changes, nextMeta, prevMeta, snapshot);
700
+ if (agentMdAids.length > 0)
701
+ this.options.onSnapshotChanged(scope, agentMdAids);
702
+ }
703
+ }
704
+ catch (cbError) {
705
+ logger.warn(`[OwnerDirectoryCache] onSnapshotChanged threw: ${errorText(cbError)}`);
706
+ }
265
707
  }
266
708
  catch (error) {
267
- logger.error(`[OwnerDirectoryCache] Sync failed for ${scope}: ${errorText(error)}, code: ${errorCode(error)}`);
709
+ logger.error(`[OwnerDirectoryCache] Apply failed for ${scope}: ${errorText(error)}`);
268
710
  if (isPermissionDenied(error)) {
269
- logger.warn(`[OwnerDirectoryCache] Permission denied for ${scope}, blocking scope`);
270
711
  await this.blockScope(scope);
271
712
  }
272
713
  else {
273
- await this.updateFileState(scope, {
274
- lastAttemptAt: attemptedAt,
275
- status: 'error',
276
- error: errorText(error),
277
- });
714
+ await this.updateFileState(scope, { lastAttemptAt: attemptedAt, status: 'error', error: errorText(error) });
278
715
  }
279
716
  this.options.onError?.(scope, error);
280
717
  throw error;
281
718
  }
282
719
  }
283
- async fetchCompleteSnapshot(scope) {
284
- const base = `data/directories/v1/${scope}`;
285
- let lastError;
286
- for (let restart = 0; restart < 2; restart++) {
287
- const manifestObject = await this.readRemoteJson(`${base}/manifest.json`);
288
- const manifest = parseManifest(manifestObject.value, this.options.ownerAid, scope);
289
- try {
290
- const entries = [];
291
- const seenAids = new Set();
292
- const visitedIndexes = new Set();
293
- let indexRef = manifest.index_ref;
294
- let indexSegments = 0;
295
- let pageCount = 0;
296
- while (indexRef) {
297
- if (++indexSegments > MAX_INDEX_SEGMENTS || visitedIndexes.has(indexRef.object_key)) {
298
- throw snapshotChanged('index chain loops or exceeds the page limit');
299
- }
300
- visitedIndexes.add(indexRef.object_key);
301
- assertSnapshotPath(indexRef.object_key, scope, manifest.snapshot_id);
302
- const indexObject = await this.readRemoteJson(indexRef.object_key, indexRef.sha256);
303
- const index = parseIndex(indexObject.value, this.options.ownerAid, scope, manifest.snapshot_id);
304
- if (pageCount + index.pages.length > MAX_SNAPSHOT_OBJECTS) {
305
- throw snapshotChanged('snapshot exceeds the local object limit');
306
- }
307
- pageCount += index.pages.length;
308
- for (const pageRef of index.pages) {
309
- assertSnapshotPath(pageRef.object_key, scope, manifest.snapshot_id);
310
- const pageObject = await this.readRemoteJson(pageRef.object_key, pageRef.sha256);
311
- const pageEntries = parsePage(pageObject.value, this.options.ownerAid, scope, manifest.snapshot_id);
312
- if (pageEntries.length !== pageRef.count)
313
- throw snapshotChanged('page entry count does not match its index');
314
- for (const rawEntry of pageEntries) {
315
- const entry = normalizeEntry(scope, rawEntry);
316
- if (seenAids.has(entry.aid))
317
- throw snapshotChanged('duplicate AID in Owner directory snapshot');
318
- seenAids.add(entry.aid);
319
- entries.push(entry);
320
- if (entries.length > MAX_DIRECTORY_ENTRIES)
321
- throw snapshotChanged('directory exceeds the local entry limit');
322
- }
323
- }
324
- indexRef = index.next_ref;
325
- }
326
- if (entries.length !== manifest.total)
327
- throw snapshotChanged('manifest total does not match downloaded pages');
328
- return {
329
- ownerAid: this.options.ownerAid,
330
- granteeAid: this.options.selfAid,
331
- scope,
332
- snapshotId: manifest.snapshot_id,
333
- total: entries.length,
334
- fetchedAt: this.now(),
335
- ...(manifest.synced_at_ms !== undefined ? { syncedAtMs: manifest.synced_at_ms } : {}),
336
- ...(manifest.source_observed_at_ms !== undefined ? { sourceObservedAtMs: manifest.source_observed_at_ms } : {}),
337
- entries,
338
- };
339
- }
340
- catch (error) {
341
- lastError = error;
342
- if (restart === 0 && isSnapshotRestartable(error))
343
- continue;
344
- throw error;
345
- }
346
- }
347
- throw lastError ?? snapshotChanged('snapshot could not be read');
348
- }
349
- async readRemoteJson(objectKey, expectedSha256) {
350
- if (!this.options.client)
351
- throw new OwnerDirectoryCacheError('CLIENT_UNAVAILABLE', 'Owner directory synchronization requires a connected AUN client');
352
- assertCanonicalObjectKey(objectKey);
353
- const { bytes, metadata } = await readAuthoritativePersonalFsObject(this.options.client, `/${objectKey}`, this.options.ownerAid, OWNER_DIRECTORY_MAX_OBJECT_BYTES);
354
- const sha256 = typeof metadata.sha256 === 'string' ? metadata.sha256.toLowerCase() : '';
355
- if (!SHA256_RE.test(sha256) || (expectedSha256 && sha256 !== expectedSha256)) {
356
- throw snapshotChanged(`object digest mismatch: ${objectKey}`);
357
- }
358
- let parsed;
359
- try {
360
- let text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
361
- if (text.charCodeAt(0) === 0xfeff)
362
- text = text.slice(1);
363
- parsed = JSON.parse(text);
364
- }
365
- catch {
366
- throw snapshotChanged(`object is not valid UTF-8 JSON: ${objectKey}`);
367
- }
368
- if (!isRecord(parsed))
369
- throw snapshotChanged(`object is not a JSON object: ${objectKey}`);
370
- return { value: parsed, sha256 };
371
- }
720
+ // ── Internal: readCachedSnapshot ────────────────────────────────────────────
372
721
  readCachedSnapshot(scope) {
373
- const grant = this.loadGrant();
374
- if (!grant || !this.isAuthorized(grant, scope))
722
+ if (this.scopeAccess(scope) !== 'authorized')
375
723
  return undefined;
376
- const state = this.readSyncState();
377
- if (state.blockedScopes.includes(scope))
378
- return undefined;
379
- const raw = atomicReadJson(this.cachePath(scope));
380
- if (!isRecord(raw) || raw.schemaVersion !== 1 || raw.ownerAid !== this.options.ownerAid
724
+ const stamp = this.cacheStamp(scope);
725
+ const cached = this.snapshotCache.get(scope);
726
+ if (cached !== undefined && cached.stamp === stamp)
727
+ return cached.snapshot ?? undefined;
728
+ const raw = stamp ? atomicReadJson(this.cachePath(scope)) : undefined;
729
+ const store = (snapshot) => {
730
+ this.snapshotCache.set(scope, { snapshot, stamp });
731
+ return snapshot ?? undefined;
732
+ };
733
+ if (!isRecord(raw) || raw.schemaVersion !== 2 || raw.ownerAid !== this.options.ownerAid
381
734
  || raw.granteeAid !== this.options.selfAid || raw.scope !== scope
382
- || typeof raw.snapshotId !== 'string' || !SNAPSHOT_ID_RE.test(raw.snapshotId)
383
- || !Number.isSafeInteger(raw.fetchedAt) || !Number.isSafeInteger(raw.total)
384
- || !Array.isArray(raw.entries) || raw.entries.length !== raw.total)
385
- return undefined;
735
+ || !Array.isArray(raw.entries) || raw.entries.length !== raw.total) {
736
+ return store(null);
737
+ }
386
738
  try {
387
- const entries = raw.entries.map(entry => normalizeEntry(scope, entry));
388
- const aids = new Set(entries.map(entry => entry.aid));
739
+ const entries = raw.entries.map((e) => normalizeEntry(e));
740
+ const aids = new Set(entries.map(e => e.aid));
389
741
  if (aids.size !== entries.length || entries.length > MAX_DIRECTORY_ENTRIES)
390
- return undefined;
391
- return {
742
+ return store(null);
743
+ return store({
392
744
  ownerAid: this.options.ownerAid,
393
745
  granteeAid: this.options.selfAid,
394
746
  scope,
395
- snapshotId: raw.snapshotId,
747
+ snapshotId: typeof raw.snapshotId === 'string' ? raw.snapshotId : '',
748
+ contentDigest: isValidContentDigest(raw.contentDigest) ? raw.contentDigest : undefined,
396
749
  total: entries.length,
397
- fetchedAt: raw.fetchedAt,
398
- ...(Number.isSafeInteger(raw.syncedAtMs) ? { syncedAtMs: raw.syncedAtMs } : {}),
399
- ...(Number.isSafeInteger(raw.sourceObservedAtMs) ? { sourceObservedAtMs: raw.sourceObservedAtMs } : {}),
750
+ fetchedAt: Number.isSafeInteger(raw.fetchedAt) ? raw.fetchedAt : 0,
751
+ ...(Number.isSafeInteger(raw.updatedAtMs) ? { updatedAtMs: raw.updatedAtMs } : {}),
400
752
  entries,
401
- };
753
+ // 本地快照用 camelCase 存,远端文档是 snake_case,两边都认。
754
+ ...(isRecord(raw.owner) ? { owner: parseIdentityField(raw.owner) } : {}),
755
+ ...(isRecord(raw.personalAssistant)
756
+ ? { personalAssistant: parseIdentityField(raw.personalAssistant) }
757
+ : isRecord(raw.personal_assistant) ? { personalAssistant: parseIdentityField(raw.personal_assistant) } : {}),
758
+ });
402
759
  }
403
760
  catch {
404
- return undefined;
761
+ return store(null);
405
762
  }
406
763
  }
407
- isAuthorized(grant, scope) {
408
- if (!grant.activeScopes.includes(scope))
409
- return false;
410
- const expiresAt = grant.expiresAtByScope[scope];
411
- return typeof expiresAt === 'number' && (expiresAt === 0 || expiresAt > this.now());
412
- }
413
- isStale(scope) {
414
- const state = this.readSyncState();
415
- const lastSuccessAt = state.files[scope]?.lastSuccessAt;
416
- return typeof lastSuccessAt !== 'number' || this.now() - lastSuccessAt >= this.staleAfterMs;
417
- }
418
- startAutomaticSync(scope) {
419
- const state = this.readSyncState();
420
- const lastAttemptAt = state.files[scope]?.lastAttemptAt;
421
- if (typeof lastAttemptAt === 'number' && this.now() - lastAttemptAt < this.retryBackoffMs)
422
- return;
423
- void this.sync(scope).catch(() => { });
764
+ /**
765
+ * 快照文件的指纹(mtimeMs + size)。文件不存在时返回 null。
766
+ *
767
+ * 一次 stat 的成本远低于读取 JSON 再解析;指纹不变就复用已解析的 snapshot。
768
+ */
769
+ cacheStamp(scope) {
770
+ try {
771
+ const info = fs.statSync(this.cachePath(scope));
772
+ return `${info.mtimeMs}:${info.size}`;
773
+ }
774
+ catch {
775
+ return null;
776
+ }
424
777
  }
778
+ // ── Internal: authorization / sync state / paths ────────────────────────────
425
779
  async blockScope(scope) {
426
- fs.rmSync(this.cachePath(scope), { force: true });
780
+ atomicRemove(this.cachePath(scope));
781
+ this.snapshotCache.delete(scope);
427
782
  await this.updateSyncState(state => ({
428
783
  ...state,
429
784
  blockedScopes: [...new Set([...state.blockedScopes, scope])],
430
785
  files: { ...state.files, [scope]: { ...state.files[scope], status: 'blocked', error: 'remote storage denied access' } },
431
786
  }));
787
+ this.refreshMarkdown();
432
788
  }
433
789
  async updateFileState(scope, update) {
434
790
  await this.updateSyncState(state => ({
@@ -453,183 +809,215 @@ export class OwnerDirectoryCache {
453
809
  return { schemaVersion: 1, ownerAid: this.options.ownerAid, granteeAid: this.options.selfAid, files: {}, blockedScopes: [] };
454
810
  }
455
811
  return {
456
- schemaVersion: 1,
457
- ownerAid: this.options.ownerAid,
458
- granteeAid: this.options.selfAid,
812
+ schemaVersion: 1, ownerAid: this.options.ownerAid, granteeAid: this.options.selfAid,
459
813
  files: raw.files,
460
- blockedScopes: Array.isArray(raw.blockedScopes) ? raw.blockedScopes.filter(isScope) : [],
814
+ blockedScopes: Array.isArray(raw.blockedScopes) ? raw.blockedScopes.filter(isOwnerDirectoryScope) : [],
461
815
  };
462
816
  }
817
+ /**
818
+ * 读授权快照。
819
+ *
820
+ * 兼容 v1:旧版本按 scope 记录授权(`activeScopes: ['agents','contacts']`),
821
+ * 里面还可能带着已经废弃的 `agents`。**未知或多余的 scope 不会作废整份授权**——
822
+ * 那会让升级当场断掉拉取。v1 只要能证明"允许读名录"就算有效,过期时间取
823
+ * contacts 的那一份。
824
+ */
463
825
  loadGrant() {
464
826
  const raw = atomicReadJson(this.authorizationPath());
465
- if (!isRecord(raw) || raw.schemaVersion !== 1 || raw.ownerAid !== this.options.ownerAid
466
- || raw.granteeAid !== this.options.selfAid || typeof raw.status !== 'string'
467
- || !GRANT_STATUSES.has(raw.status) || !Array.isArray(raw.activeScopes)
468
- || raw.activeScopes.some(scope => !isScope(scope)) || !isRecord(raw.expiresAtByScope))
827
+ if (!isRecord(raw))
828
+ return undefined;
829
+ if (raw.ownerAid !== this.options.ownerAid || raw.granteeAid !== this.options.selfAid)
469
830
  return undefined;
470
- const activeScopes = raw.activeScopes;
471
- const knownScopes = [...new Set([
472
- ...activeScopes,
473
- ...(Array.isArray(raw.knownScopes) ? raw.knownScopes.filter(isScope) : []),
474
- ...OWNER_DIRECTORY_SCOPES.filter(scope => fs.existsSync(this.cachePath(scope)) || fs.existsSync(`${this.cachePath(scope)}_`)),
475
- ])];
476
- const expiresAtByScope = {};
477
- for (const scope of activeScopes) {
478
- const expiresAt = raw.expiresAtByScope[scope];
831
+ if (raw.schemaVersion === 2) {
832
+ if (!Number.isSafeInteger(raw.grantedAt) || !Number.isSafeInteger(raw.expiresAt))
833
+ return undefined;
834
+ return {
835
+ schemaVersion: 2,
836
+ ownerAid: this.options.ownerAid,
837
+ granteeAid: this.options.selfAid,
838
+ grantedAt: raw.grantedAt,
839
+ expiresAt: raw.expiresAt,
840
+ };
841
+ }
842
+ if (raw.schemaVersion === 1) {
843
+ if (typeof raw.status !== 'string' || !GRANT_STATUSES.has(raw.status))
844
+ return undefined;
845
+ if (!Array.isArray(raw.activeScopes) || !raw.activeScopes.includes('contacts'))
846
+ return undefined;
847
+ const expiryMap = isRecord(raw.expiresAtByScope) ? raw.expiresAtByScope : {};
848
+ const expiresAt = Number(expiryMap['contacts'] ?? 0);
479
849
  if (!Number.isSafeInteger(expiresAt) || expiresAt < 0)
480
850
  return undefined;
481
- expiresAtByScope[scope] = expiresAt;
851
+ return {
852
+ schemaVersion: 2,
853
+ ownerAid: this.options.ownerAid,
854
+ granteeAid: this.options.selfAid,
855
+ grantedAt: Number.isSafeInteger(raw.storedAt) ? raw.storedAt : 0,
856
+ expiresAt,
857
+ };
482
858
  }
483
- return {
484
- schemaVersion: 1,
485
- status: raw.status,
486
- ownerAid: this.options.ownerAid,
487
- granteeAid: this.options.selfAid,
488
- activeScopes,
489
- knownScopes,
490
- expiresAtByScope,
491
- manifestRefs: isRecord(raw.manifestRefs) ? raw.manifestRefs : {},
492
- storedAt: Number.isSafeInteger(raw.storedAt) ? raw.storedAt : 0,
493
- };
859
+ return undefined;
860
+ }
861
+ /**
862
+ * 重算并写回 `directory.md`。
863
+ *
864
+ * 只在两处调用:名录落地之后,以及备注被改写之后。不做定时刷新,也不在
865
+ * 消息路径上比对——名录和备注都不变时,注入内容本来就不会变。
866
+ */
867
+ refreshMarkdown() {
868
+ try {
869
+ const snapshot = this.readCachedSnapshot('contacts');
870
+ const markdown = renderOwnerDirectoryMarkdown({
871
+ ownerAid: this.options.ownerAid,
872
+ selfAid: this.options.selfAid,
873
+ snapshot,
874
+ remarks: this.remarksSnapshot(),
875
+ allowExternalContacts: this.options.allowExternalContacts?.(),
876
+ });
877
+ if (!markdown)
878
+ return;
879
+ const target = path.join(this.options.directory, OWNER_DIRECTORY_MARKDOWN_FILE);
880
+ fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
881
+ // 内容不变就不写盘:ECK 的注入按文件指纹走,无谓的写入会触发无谓的重新加载。
882
+ try {
883
+ if (atomicRead(target) === markdown)
884
+ return;
885
+ }
886
+ catch { /* 读不出来就照写 */ }
887
+ atomicWriteText(target, markdown);
888
+ }
889
+ catch (error) {
890
+ logger.warn(`[OwnerDirectoryCache] refreshMarkdown failed: ${errorText(error)}`);
891
+ }
892
+ }
893
+ /**
894
+ * 备注集合,带目录指纹缓存。
895
+ *
896
+ * `readAllRemarks` 要 readdir + 逐文件 stat + 读正文;而它只在备注变化时结果才变。
897
+ * 指纹取 `remarks/` 的 mtimeMs 与条目名(名字改了 mtime 不一定变,但增删会)。
898
+ *
899
+ * 每次仍然要 stat 一次目录——这是热路径的最后一道成本,也是判断"要不要重读"
900
+ * 的唯一依据。指纹一致就复用上次的 Map,避免 70 条备注每轮重新解析。
901
+ */
902
+ remarksSnapshot() {
903
+ const stamp = remarksStamp(this.options.directory);
904
+ if (stamp !== null && stamp === this.remarksStampCache?.stamp)
905
+ return this.remarksStampCache.remarks;
906
+ const remarks = readAllRemarks(this.options.directory);
907
+ this.remarksStampCache = stamp === null ? undefined : { stamp, remarks };
908
+ return remarks;
494
909
  }
495
910
  authorizationPath() { return path.join(this.options.directory, 'authorization.json'); }
496
911
  syncStatePath() { return path.join(this.options.directory, 'sync-state.json'); }
912
+ pendingPath() { return path.join(this.options.directory, 'pending.json'); }
497
913
  cachePath(scope) { return path.join(this.options.directory, `${scope}.json`); }
498
914
  }
499
- function parseManifest(value, ownerAid, scope) {
500
- if (value.schema_version !== 1 || value.owner_aid !== ownerAid || value.dataset !== scope
501
- || value.complete !== true || typeof value.snapshot_id !== 'string' || !SNAPSHOT_ID_RE.test(value.snapshot_id)
502
- || !Number.isSafeInteger(value.total) || value.total < 0 || value.total > MAX_DIRECTORY_ENTRIES) {
503
- throw snapshotChanged('manifest identity, schema, completeness or total is invalid');
504
- }
505
- const rawIndexRef = typeof value.index_ref === 'string'
506
- ? { object_key: value.index_ref, sha256: value.index_sha256 }
507
- : value.index_ref;
508
- const indexRef = parseRef(rawIndexRef);
509
- assertSnapshotPath(indexRef.object_key, scope, value.snapshot_id);
510
- return {
511
- schema_version: 1,
512
- owner_aid: ownerAid,
513
- dataset: scope,
514
- complete: true,
515
- snapshot_id: value.snapshot_id,
516
- total: value.total,
517
- index_ref: indexRef,
518
- ...(optionalTimestamp(value.synced_at_ms) !== undefined ? { synced_at_ms: optionalTimestamp(value.synced_at_ms) } : {}),
519
- ...(optionalTimestamp(value.source_observed_at_ms) !== undefined ? { source_observed_at_ms: optionalTimestamp(value.source_observed_at_ms) } : {}),
520
- };
521
- }
522
- function parseIndex(value, ownerAid, scope, snapshotId) {
523
- if (value.schema_version !== 1 || value.owner_aid !== ownerAid || value.dataset !== scope || value.snapshot_id !== snapshotId
524
- || !Array.isArray(value.pages) || value.pages.length > MAX_PAGES_PER_INDEX) {
525
- throw snapshotChanged('index identity, schema or page count is invalid');
526
- }
527
- const pages = value.pages.map(item => {
528
- if (!isRecord(item) || !Number.isSafeInteger(item.count) || item.count < 0) {
529
- throw snapshotChanged('index page count is invalid');
530
- }
531
- return { ...parseRef(item), count: item.count };
532
- });
533
- const nextRef = value.next_ref === undefined || value.next_ref === null ? undefined : parseRef(value.next_ref);
534
- if (pages.length === 0 && nextRef)
535
- throw snapshotChanged('empty index segment cannot point to another segment');
536
- return { pages, ...(nextRef ? { next_ref: nextRef } : {}) };
537
- }
538
- function parsePage(value, ownerAid, scope, snapshotId) {
539
- if (value.schema_version !== 1 || value.owner_aid !== ownerAid || value.dataset !== scope
540
- || value.snapshot_id !== snapshotId || !Array.isArray(value.entries)) {
541
- throw snapshotChanged('page identity, schema or entries are invalid');
542
- }
543
- return value.entries;
544
- }
545
- function parseRef(value) {
546
- if (!isRecord(value) || typeof value.object_key !== 'string' || typeof value.sha256 !== 'string'
547
- || !SHA256_RE.test(value.sha256))
548
- throw snapshotChanged('snapshot object reference is invalid');
549
- assertCanonicalObjectKey(value.object_key);
550
- return { object_key: value.object_key, sha256: value.sha256 };
915
+ // ── Module-level helpers ─────────────────────────────────────────────────────
916
+ /**
917
+ * 从 `directory/access` 的结果里取过期时间。
918
+ *
919
+ * 协议按 scope 给过期时间,名录只剩一份,取 contacts 的那份;都没给就不过期。
920
+ * 状态不是 active 的授权(revoked/expired)直接记 0,由 `scopeAccess` 之外的
921
+ * 语义处理——这里只回答"读到什么时候"。
922
+ */
923
+ function grantExpiryMs(result) {
924
+ if (result.status !== 'active' && result.status !== 'sync_pending' && result.status !== 'revoke_pending')
925
+ return 0;
926
+ const map = isRecord(result.expires_at_by_scope) ? result.expires_at_by_scope : {};
927
+ const value = Number(map['contacts'] ?? 0);
928
+ return Number.isSafeInteger(value) && value >= 0 ? value : 0;
551
929
  }
552
- function normalizeEntry(scope, value) {
553
- if (!isRecord(value) || typeof value.aid !== 'string' || !isValidAid(value.aid)
554
- || typeof value.name !== 'string' || value.name.length > 256) {
555
- throw snapshotChanged(`${scope} entry identity or name is invalid`);
556
- }
557
- if (scope === 'contacts') {
558
- if (value.remark !== undefined && (typeof value.remark !== 'string' || value.remark.length > 512)) {
559
- throw snapshotChanged('contacts entry remark is invalid');
560
- }
561
- return { aid: value.aid, name: value.name, ...(typeof value.remark === 'string' ? { remark: value.remark } : {}) };
562
- }
563
- for (const key of ['type', 'description', 'ownership_status']) {
564
- const max = key === 'description' ? 4096 : 128;
565
- if (value[key] !== undefined && (typeof value[key] !== 'string' || value[key].length > max)) {
566
- throw snapshotChanged(`agents entry ${key} is invalid`);
567
- }
568
- }
569
- if (value.ownership_checked_at_ms !== undefined
570
- && (!Number.isSafeInteger(value.ownership_checked_at_ms) || value.ownership_checked_at_ms < 0)) {
571
- throw snapshotChanged('agents entry ownership_checked_at_ms is invalid');
572
- }
930
+ function parseIdentityField(value) {
931
+ if (!isRecord(value) || typeof value.aid !== 'string' || typeof value.name !== 'string')
932
+ return undefined;
573
933
  return {
574
934
  aid: value.aid,
575
935
  name: value.name,
576
- ...(typeof value.type === 'string' ? { type: value.type } : {}),
577
- ...(typeof value.description === 'string' ? { description: value.description } : {}),
578
- ...(typeof value.ownership_status === 'string' ? { ownership_status: value.ownership_status } : {}),
579
- ...(typeof value.ownership_checked_at_ms === 'number' ? { ownership_checked_at_ms: value.ownership_checked_at_ms } : {}),
936
+ ...(Number.isSafeInteger(value.agent_md_signed_at) ? { agent_md_signed_at: value.agent_md_signed_at } : {}),
580
937
  };
581
938
  }
582
- function assertSnapshotPath(key, scope, snapshotId) {
583
- const prefix = `data/directories/v1/${scope}/snapshots/${snapshotId}/`;
584
- if (!key.startsWith(prefix) || key.slice(prefix.length).length === 0) {
585
- throw snapshotChanged('snapshot reference escapes its Owner/scope/snapshot directory');
939
+ /**
940
+ * 把远端条目收敛成内部形状。未知字段直接丢弃(协议允许后续新增可选字段,
941
+ * 解析器忽略即可);已知字符串字段一律截断到 128 字符。
942
+ *
943
+ * 注意:`content_digest` 必须在**原始**条目上计算,不能拿这里的输出回算——
944
+ * 归一化会把 null 变成缺失、把长字段截断。
945
+ */
946
+ function normalizeEntry(value) {
947
+ if (!isRecord(value) || typeof value.aid !== 'string' || !isValidAid(value.aid)) {
948
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', 'entry has invalid or missing aid');
949
+ }
950
+ const entry = {
951
+ aid: value.aid,
952
+ name: typeof value.name === 'string' ? value.name : value.aid,
953
+ };
954
+ // 本地缓存用 camelCase 存,远端文档用 snake_case;两种都认,否则读回本地快照会丢字段。
955
+ if (typeof value.owner_aid === 'string' && value.owner_aid.trim())
956
+ entry.ownerAid = value.owner_aid.trim();
957
+ else if (typeof value.ownerAid === 'string' && value.ownerAid.trim())
958
+ entry.ownerAid = value.ownerAid.trim();
959
+ const allowed = ['remark', 'type', 'exttype', 'description', 'baseagent', 'ownership_status'];
960
+ for (const key of allowed) {
961
+ if (typeof value[key] === 'string' && value[key].length <= 128) {
962
+ entry[key] = value[key];
963
+ }
586
964
  }
587
- }
588
- function assertCanonicalObjectKey(key) {
589
- if (!key || key.startsWith('/') || key.endsWith('/') || key.includes('\\') || /[\u0000-\u001f\u007f]/.test(key)
590
- || key.split('/').some(part => !part || part === '.' || part === '..')) {
591
- throw snapshotChanged('snapshot object key is not canonical');
965
+ if (Number.isSafeInteger(value.ownership_checked_at_ms)) {
966
+ entry.ownership_checked_at_ms = value.ownership_checked_at_ms;
592
967
  }
593
- }
594
- function optionalTimestamp(value) {
595
- return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
596
- }
597
- function isSnapshotRestartable(error) {
598
- if (error instanceof OwnerDirectoryCacheError)
599
- return error.code === 'SNAPSHOT_CHANGED';
600
- const code = errorCode(error).toUpperCase();
601
- return code === 'FS_NOT_FOUND' || code === 'NOT_FOUND' || code === 'ENOENT'
602
- || code === '-32008' || code === '404' || code === '4040' || code === 'SNAPSHOT_CHANGED'
603
- || (code === '-32602' && /not found|no such|不存在/i.test(errorText(error)));
968
+ if (Number.isSafeInteger(value.agent_md_signed_at)) {
969
+ entry.agent_md_signed_at = value.agent_md_signed_at;
970
+ }
971
+ return entry;
604
972
  }
605
973
  function isPermissionDenied(error) {
606
- const code = errorCode(error).toUpperCase();
607
- return code === 'PERMISSION_DENIED' || code === 'STORAGE_ACCESS_DENIED' || code === 'ACCESS_DENIED'
608
- || code === 'EACCES' || code === '-32004' || code === '403' || code === '4030';
609
- }
610
- function errorCode(error) {
611
- return error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
612
- }
613
- function errorText(error) {
614
- const text = error instanceof Error ? error.message : String(error);
615
- return text.slice(0, 500);
616
- }
617
- function snapshotChanged(message) {
618
- return new OwnerDirectoryCacheError('SNAPSHOT_CHANGED', message);
974
+ return error instanceof OwnerDirectoryCacheError
975
+ && ['PERMISSION_DENIED', 'ACCESS_DENIED', 'FORBIDDEN'].includes(error.code);
619
976
  }
620
- function isScope(value) {
621
- return value === 'contacts' || value === 'agents';
622
- }
623
- function isRecord(value) {
624
- return value !== null && typeof value === 'object' && !Array.isArray(value);
977
+ /**
978
+ * 把"远端明确拒绝"的各种错误形态归一成 `PERMISSION_DENIED`。
979
+ *
980
+ * `blockScope` 只在远端拒绝时生效:那是权限真的被撤了,本地快照必须作废,
981
+ * 否则准入会继续拿旧名录放行。而本地写盘失败(磁盘只读、文件被占用)不是
982
+ * 权限撤销,走普通错误分支重试即可——所以两种来源必须区分开,不能一概而论。
983
+ *
984
+ * 形态来源:
985
+ * - AUN RPC 拒绝:`code` 为 `-32004` / `403` / `4030`,或错误消息里带这些词
986
+ * - 本地文件系统:`EACCES` / `EPERM`,但只在**读取远端对象**这条路径上才认,
987
+ * 落地写盘的同名错误由 `_applyFile` 自己处理
988
+ */
989
+ function toDirectoryError(error) {
990
+ if (error instanceof OwnerDirectoryCacheError)
991
+ return error;
992
+ const code = isRecord(error) && typeof error.code === 'string' ? error.code : undefined;
993
+ const numericCode = isRecord(error) && typeof error.code === 'number' ? String(error.code) : undefined;
994
+ const message = errorText(error);
995
+ const denied = [code, numericCode].some(value => value !== undefined && ['-32004', '403', '4030', 'EACCES', 'EPERM'].includes(value))
996
+ || /PERMISSION_DENIED|ACCESS_DENIED|FORBIDDEN|permission denied/i.test(message);
997
+ if (denied)
998
+ return new OwnerDirectoryCacheError('PERMISSION_DENIED', `remote storage denied access: ${message}`);
999
+ return error;
625
1000
  }
626
- async function waitAtMost(promise, ms) {
627
- let timer;
1001
+ /**
1002
+ * `remarks/` 目录的指纹:mtimeMs + 文件名集合。
1003
+ *
1004
+ * 目录不存在返回 `null`——调用方据此不缓存空结果,否则第一次 `remark set`
1005
+ * 之后仍会命中"空"的旧指纹。
1006
+ */
1007
+ function remarksStamp(directory) {
1008
+ const dir = path.join(directory, OWNER_DIRECTORY_REMARKS_DIR);
628
1009
  try {
629
- await Promise.race([promise, new Promise(resolve => { timer = setTimeout(resolve, ms); })]);
1010
+ const info = fs.statSync(dir);
1011
+ const names = fs.readdirSync(dir).filter(name => name.endsWith('.md')).sort();
1012
+ return `${info.mtimeMs}:${names.join(',')}`;
630
1013
  }
631
- finally {
632
- if (timer)
633
- clearTimeout(timer);
1014
+ catch {
1015
+ return null;
634
1016
  }
635
1017
  }
1018
+ function isRecord(value) {
1019
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1020
+ }
1021
+ function errorText(error) {
1022
+ return error instanceof Error ? error.message : String(error);
1023
+ }