evolcore 0.0.42 → 0.0.43-test.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 (189) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bin/ec-safe-output.js +4 -1
  3. package/dist/ability/application-service.js +882 -0
  4. package/dist/ability/authorization.js +70 -0
  5. package/dist/ability/command-contract.js +105 -0
  6. package/dist/ability/daemon.js +137 -0
  7. package/dist/ability/development.js +450 -0
  8. package/dist/ability/environment.js +75 -0
  9. package/dist/ability/interop-v1.js +547 -0
  10. package/dist/ability/management.js +79 -0
  11. package/dist/ability/package.js +264 -0
  12. package/dist/ability/provider.js +73 -0
  13. package/dist/ability/publication.js +107 -0
  14. package/dist/ability/resources.js +106 -0
  15. package/dist/ability/runtime.js +212 -0
  16. package/dist/ability/secrets.js +47 -0
  17. package/dist/ability/store.js +112 -0
  18. package/dist/ability/toolchain.js +69 -0
  19. package/dist/ability/types.js +14 -0
  20. package/dist/ability/versions.js +32 -0
  21. package/dist/agents/baseagent.js +2 -2
  22. package/dist/agents/claude-runner.js +4 -0
  23. package/dist/agents/codex-runner.js +81 -17
  24. package/dist/agents/ecagent-plugin-lazy.js +41 -0
  25. package/dist/agents/ecagent-runner.js +18 -11
  26. package/dist/aun/ability-device-routing.js +12 -1
  27. package/dist/aun/aid/agentmd.js +2 -2
  28. package/dist/aun/aid/client.js +1 -1
  29. package/dist/aun/aid/identity.js +45 -0
  30. package/dist/aun/aid/index.js +1 -0
  31. package/dist/aun/aid/managed-operation.js +73 -2
  32. package/dist/channels/aun.js +64 -18
  33. package/dist/channels/builtin-plugins.js +14 -0
  34. package/dist/channels/dingtalk.js +78 -26
  35. package/dist/channels/feishu.js +89 -14
  36. package/dist/channels/qqbot.js +84 -19
  37. package/dist/channels/wechat.js +77 -19
  38. package/dist/channels/wecom.js +67 -22
  39. package/dist/cli/ability-command.js +92 -0
  40. package/dist/cli/aun-commands.js +124 -85
  41. package/dist/cli/daemon-commands.js +37 -85
  42. package/dist/cli/index.js +14 -0
  43. package/dist/cli/init.js +11 -13
  44. package/dist/cli/managed-command-guard.js +6 -0
  45. package/dist/cli/model.js +101 -104
  46. package/dist/cli/provider-command.js +6 -4
  47. package/dist/cli/restart-monitor.js +52 -11
  48. package/dist/cli/upgrade-command.js +102 -0
  49. package/dist/cli/version.js +1 -1
  50. package/dist/config/access-policy.js +4 -2
  51. package/dist/config/builtin-roles.js +1 -0
  52. package/dist/config/config-field-policy.js +4 -0
  53. package/dist/config/config-manager.js +7 -0
  54. package/dist/config/provider-ipc-service.js +10 -0
  55. package/dist/config/providers-config.js +12 -3
  56. package/dist/config/providers-management.js +45 -9
  57. package/dist/config/schema-migration.js +40 -22
  58. package/dist/contracts/ecweb-service-protocol.js +2 -1
  59. package/dist/core/agent-runtime.js +2 -1
  60. package/dist/core/auth/agent-delegation.js +21 -5
  61. package/dist/core/auth/auth-gateway.js +31 -9
  62. package/dist/core/auth/authorization-audit.js +52 -4
  63. package/dist/core/auth/delegation-authorization.js +140 -4
  64. package/dist/core/auth/operation-authorizer.js +114 -13
  65. package/dist/core/auth/operation-catalog.js +118 -4
  66. package/dist/core/baseagent-loader.js +14 -1
  67. package/dist/core/channel-loader.js +47 -9
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-storage-menu.js +1 -1
  70. package/dist/core/command/cli-intent-parser.js +26 -13
  71. package/dist/core/command/command-handler.js +232 -76
  72. package/dist/core/command/connect-menu.js +10 -4
  73. package/dist/core/command/daemon-diagnostics.js +3 -3
  74. package/dist/core/command/data-root-resolver.js +2 -3
  75. package/dist/core/command/menu-catalog.js +10 -3
  76. package/dist/core/command/menu-handler.js +321 -46
  77. package/dist/core/command/menu-protocol.js +53 -7
  78. package/dist/core/command/pa-workspace-calendar.js +1 -2
  79. package/dist/core/command/pa-workspace-items.js +486 -0
  80. package/dist/core/command/pa-workspace-store.js +10 -1
  81. package/dist/core/command/slash-gate.js +2 -2
  82. package/dist/core/command/slash-handler.js +67 -25
  83. package/dist/core/contact-bind-registry.js +27 -0
  84. package/dist/core/daemon-control.js +3 -3
  85. package/dist/core/daemon-lifecycle.js +2 -1
  86. package/dist/core/event-bus.js +9 -2
  87. package/dist/core/handoff/ipc-registration.js +1 -0
  88. package/dist/core/host-snapshot.js +1 -2
  89. package/dist/core/initialization/service.js +32 -11
  90. package/dist/core/ipc-registration.js +18 -5
  91. package/dist/core/memory/consolidation-context.js +2 -2
  92. package/dist/core/message/aun-request-registry.js +99 -18
  93. package/dist/core/message/im-renderer.js +16 -11
  94. package/dist/core/message/message-admission.js +25 -20
  95. package/dist/core/message/message-bridge.js +21 -47
  96. package/dist/core/message/message-queue.js +3 -0
  97. package/dist/core/message/response-engine.js +7 -5
  98. package/dist/core/model/catalog-service.js +1 -1
  99. package/dist/core/permission/ec-command-parser.js +41 -9
  100. package/dist/core/permission/permission-result.js +1 -0
  101. package/dist/core/permission/protected-paths.js +25 -14
  102. package/dist/core/permission/tool-policy.js +108 -107
  103. package/dist/core/plugin-lifecycle.js +133 -0
  104. package/dist/core/runner-reload-transaction.js +4 -1
  105. package/dist/core/system-session/memory.js +16 -3
  106. package/dist/core/task/task-activity-store.js +50 -0
  107. package/dist/core/task/task-image-resources.js +140 -0
  108. package/dist/core/thread/ipc-operation.js +1 -1
  109. package/dist/core/thread/thread-service.js +0 -1
  110. package/dist/directory/canonical-digest.js +5 -3
  111. package/dist/directory/owner-directory-admission.js +22 -2
  112. package/dist/directory/owner-directory-cache.js +394 -60
  113. package/dist/directory/owner-directory-markdown.js +29 -2
  114. package/dist/directory/owner-directory-scope.js +35 -16
  115. package/dist/ecweb/basic-settings-service.js +4 -1
  116. package/dist/ecweb/pairing.js +41 -0
  117. package/dist/ecweb/providers-service.js +8 -1
  118. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  119. package/dist/ecweb/runtime/lifecycle.js +184 -0
  120. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  121. package/dist/index.js +34 -25
  122. package/dist/ipc.js +124 -7
  123. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  124. package/dist/trigger/authorization.js +2 -2
  125. package/dist/utils/atomic-write.js +24 -0
  126. package/dist/utils/avatar-upload.js +3 -1
  127. package/dist/utils/cross-platform.js +31 -2
  128. package/dist/utils/host-info.js +36 -0
  129. package/dist/utils/instance-registry.js +38 -11
  130. package/dist/utils/logger.js +9 -0
  131. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  132. package/dist/utils/tool-summary.js +9 -1
  133. package/dist/utils/upgrade-jobs.js +96 -15
  134. package/dist/utils/windows-autostart.js +1 -1
  135. package/ecagent/README.md +19 -0
  136. package/ecagent/dist/harness/agent-harness.js +9 -0
  137. package/ecagent/dist/harness/env/nodejs.js +71 -11
  138. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  139. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  140. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  141. package/kits/docs/evolcore/INDEX.md +5 -1
  142. package/kits/docs/evolcore/ability.md +181 -0
  143. package/kits/docs/evolcore/aid.md +20 -0
  144. package/kits/docs/evolcore/config.md +10 -6
  145. package/kits/docs/evolcore/menu-protocol.md +40 -1
  146. package/kits/docs/evolcore/provider.md +2 -2
  147. package/kits/docs/evolcore/tool-authorization.md +270 -0
  148. package/kits/runtime/ability-job.ps1 +41 -0
  149. package/kits/runtime/ability-runner.mjs +67 -0
  150. package/kits/runtime/ability-secret.ps1 +59 -0
  151. package/kits/runtime/ability-templates/go/main.go +59 -0
  152. package/kits/runtime/ability-templates/java/Json.java +67 -0
  153. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  154. package/kits/runtime/ability-templates/python/runner.py +48 -0
  155. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  156. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  157. package/kits/schemas/_meta.json +12 -1
  158. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  159. package/kits/schemas/ability-project.schema.1.json +31 -0
  160. package/kits/schemas/agent-config.schema.16.json +20 -0
  161. package/kits/schemas/agent-config.schema.17.json +20 -0
  162. package/kits/schemas/agent-config.schema.18.json +917 -0
  163. package/kits/skills/.switches.json +4 -0
  164. package/kits/skills/aid-ability/SKILL.md +5 -4
  165. package/kits/skills/ec-ability/SKILL.md +67 -0
  166. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  167. package/kits/skills/ec-ability/references/development.md +104 -0
  168. package/kits/skills/ec-ability/references/management.md +117 -0
  169. package/kits/skills/ec-ability/references/recovery.md +27 -0
  170. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  171. package/kits/skills/ec-ability/references/workflows.md +15 -0
  172. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  173. package/kits/skills/personal-assistant/SKILL.md +240 -6
  174. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  175. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  176. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  177. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  178. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  179. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  180. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  181. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  182. package/kits/templates/memory-consolidation/notes.md +1 -1
  183. package/kits/templates/system-fragments/channel.md +2 -1
  184. package/kits/templates/system-fragments/commands.md +1 -0
  185. package/package.json +5 -3
  186. package/dist/core/command/data-root-error.js +0 -10
  187. package/dist/utils/machine-info.js +0 -46
  188. package/dist/utils/process-tree-worker.js +0 -31
  189. package/dist/utils/windows-output.js +0 -36
@@ -1,9 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
4
  import { isValidAid } from '../aun/aid/validation.js';
5
+ import { normalizeGroupAid } from '../aun/group/identity.js';
5
6
  import { readAuthoritativePersonalFsObject } from '../aun/group/fs-download.js';
6
- import { atomicRead, atomicReadJson, atomicRemove, atomicWriteJson, atomicWriteText } from '../utils/atomic-write.js';
7
+ import { atomicRead, atomicReadBytes, atomicReadJson, atomicRemove, atomicWriteBytes, atomicWriteJson, atomicWriteText, existsAtomic } from '../utils/atomic-write.js';
7
8
  import { logger } from '../utils/logger.js';
8
9
  import { resolveRoot } from '../paths.js';
9
10
  import { OWNER_DIRECTORY_MARKDOWN_FILE, renderOwnerDirectoryMarkdown } from './owner-directory-markdown.js';
@@ -21,6 +22,14 @@ import { OWNER_DIRECTORY_SCOPES, isOwnerDirectoryScope } from './owner-directory
21
22
  // 内存由 MAX_DIRECTORY_ENTRIES 和单字段长度限制兜底,字节数对齐通道上限。
22
23
  export const OWNER_DIRECTORY_MAX_OBJECT_BYTES = 128 * 1024;
23
24
  export const OWNER_DIRECTORY_INITIAL_WAIT_MS = 3_000;
25
+ /**
26
+ * 单条入站消息处理前,等待「共享缓存 → 本 agent 目录」落地的上限。
27
+ *
28
+ * 这一步只读本机文件、写本机文件,不碰网络,正常在毫秒级完成;300ms 是给
29
+ * 目录里条目多、磁盘慢的机器留的余量,不是预期耗时。网络拉取(owner 级
30
+ * 更新 → 共享缓存)不在这个窗口里,它继续在后台跑,落地会随之下一次补上。
31
+ */
32
+ export const OWNER_DIRECTORY_APPLY_WAIT_MS = 300;
24
33
  /**
25
34
  * 拉取失败后的最大尝试次数。到顶就停下,等下一次 `owner.directory.grant`
26
35
  * 事件或 daemon 重启——避免一条拉不下来的名录把每条入站消息都拖成一次网络请求。
@@ -34,6 +43,15 @@ export const OWNER_DIRECTORY_INITIAL_WAIT_MS = 3_000;
34
43
  * 退避按时间而不是按次数,既不会造成拉取风暴,也不会永久放弃。
35
44
  */
36
45
  export const OWNER_DIRECTORY_PULL_BACKOFF_MS = [30_000, 120_000, 600_000];
46
+ /** 共享缓存下保存"最近一次拉到但还没通过校验"的原始字节的子目录。 */
47
+ const RAW_DIR = 'raw';
48
+ /** 拉取失败记录文件名,与共享缓存同目录。 */
49
+ const FAILURES_FILE = 'failures.jsonl';
50
+ /** 失败记录保留条数与字节上限;超出从头丢,只留最近的。 */
51
+ const FAILURE_KEEP_LINES = 20;
52
+ const FAILURE_MAX_BYTES = 256 * 1024;
53
+ /** 连续失败到这个次数就把 WARN 升级成 ERROR,避免"没人看见的一行 WARN"。 */
54
+ const FAILURE_ESCALATE_AFTER = 3;
37
55
  const MAX_DIRECTORY_ENTRIES = 100_000;
38
56
  const SNAPSHOT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
39
57
  const SHA256_RE = /^[a-f0-9]{64}$/;
@@ -70,7 +88,12 @@ export class OwnerDirectoryCacheError extends Error {
70
88
  export class OwnerDirectoryCache {
71
89
  options;
72
90
  now;
73
- initialWaitMs;
91
+ /**
92
+ * 落地单飞。消息并发进来时,后到的调用方复用同一轮落地,而不是各自再跑一遍
93
+ * `_readSharedCache` 的校验 + 写盘。热路径本身就是判重早退,这里只是兜住
94
+ * "多轮消息同时撞上同一份新共享缓存"的窗口。
95
+ */
96
+ applyInFlight;
74
97
  /** 连续拉取失败次数,决定下一档退避窗口。仅内存,重启清零(重启本身是自愈路径)。 */
75
98
  pullFailures = 0;
76
99
  /** 上一次拉取失败的时间点;仅在 `pullFailures > 0` 时有意义。 */
@@ -95,7 +118,6 @@ export class OwnerDirectoryCache {
95
118
  throw new TypeError('owner directory cache path must be absolute');
96
119
  }
97
120
  this.now = options.now ?? Date.now;
98
- this.initialWaitMs = options.initialWaitMs ?? OWNER_DIRECTORY_INITIAL_WAIT_MS;
99
121
  }
100
122
  // ── Authorization ───────────────────────────────────────────────────────────
101
123
  /**
@@ -248,7 +270,25 @@ export class OwnerDirectoryCache {
248
270
  this.pullFailures++;
249
271
  this.lastPullFailureAt = this.now();
250
272
  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)}`);
273
+ const message = `[OwnerDirectoryCache] Pending pull failed (${this.pullFailures} in a row, next retry in ${next}ms): ${errorText(error)}`;
274
+ // 连续失败不是抖动:升级日志级别,让"名录一直没更新"能被发现,
275
+ // 而不是翻两小时前的 WARN 才知道。
276
+ if (this.pullFailures >= FAILURE_ESCALATE_AFTER)
277
+ logger.error(message);
278
+ else
279
+ logger.warn(message);
280
+ void this.updateSyncState(state => ({
281
+ ...state,
282
+ files: {
283
+ ...state.files,
284
+ ...Object.fromEntries(OWNER_DIRECTORY_SCOPES.map(scope => [scope, {
285
+ ...state.files[scope],
286
+ status: 'error',
287
+ error: errorText(error),
288
+ failureCount: this.pullFailures,
289
+ }])),
290
+ },
291
+ })).catch(() => { });
252
292
  }
253
293
  }
254
294
  /**
@@ -323,7 +363,7 @@ export class OwnerDirectoryCache {
323
363
  if (this.scopeAccess(scope) === 'authorized')
324
364
  await this.blockScope(scope);
325
365
  }
326
- return this._assertComplete(outcome.data);
366
+ return this._assertComplete(outcome.data, outcome.failures);
327
367
  }
328
368
  /**
329
369
  * 已授权范围一个都没拿到,就不算拉取成功。
@@ -331,10 +371,14 @@ export class OwnerDirectoryCache {
331
371
  * `_doFetch` 对每个 scope 单独兜错,全部失败也只是返回空对象——缺项判定必须
332
372
  * 在这里做,否则调用方会把"一个字节都没拉下来"当成成功,把 pending 清掉。
333
373
  */
334
- _assertComplete(fetched) {
374
+ _assertComplete(fetched, failures) {
335
375
  const missing = OWNER_DIRECTORY_SCOPES.filter(scope => this.scopeAccess(scope) === 'authorized' && !fetched[scope]);
336
376
  if (missing.length > 0) {
337
- throw new OwnerDirectoryCacheError('FETCH_INCOMPLETE', `owner directory fetch incomplete: ${missing.join(', ')}`);
377
+ // 带上根因:上层只看到 "fetch incomplete" 会把内容不合格误判成"拉不到"。
378
+ const detail = missing
379
+ .map(scope => failures?.[scope] ? `${scope} (${failures[scope]})` : scope)
380
+ .join(', ');
381
+ throw new OwnerDirectoryCacheError('FETCH_INCOMPLETE', `owner directory fetch incomplete: ${detail}`);
338
382
  }
339
383
  return fetched;
340
384
  }
@@ -348,6 +392,17 @@ export class OwnerDirectoryCache {
348
392
  * 这不是失败,只是还没有东西可落地。
349
393
  */
350
394
  async applyFromSharedCache() {
395
+ const running = this.applyInFlight;
396
+ if (running)
397
+ return running;
398
+ const promise = this._applyFromSharedCacheOnce().finally(() => {
399
+ if (this.applyInFlight === promise)
400
+ this.applyInFlight = undefined;
401
+ });
402
+ this.applyInFlight = promise;
403
+ return promise;
404
+ }
405
+ async _applyFromSharedCacheOnce() {
351
406
  // 热路径早退:每条入站消息都会调到这里,而绝大多数消息发生时名录早就落过盘。
352
407
  // 先只比 content_digest,命中就连 JSON 都不解析——`_readSharedCache` 会做
353
408
  // 逐条校验 + 全量摘要重算,那是拉取期才需要的成本。
@@ -363,6 +418,37 @@ export class OwnerDirectoryCache {
363
418
  await this._applyAll(fetched);
364
419
  return true;
365
420
  }
421
+ /**
422
+ * 有界落地:最多等 `timeoutMs`,超时就放行调用方,落地继续在后台跑完。
423
+ *
424
+ * 入站消息走这条:落地是本地读写、正常毫秒级完成,但要保证它**先于**本轮
425
+ * 上下文渲染完成——否则这条消息的 ECK 会按 `hasOwnerDirectory` 的旧值
426
+ * 整段丢掉名录(尤其是 directory.md 此前根本不存在的时候)。
427
+ *
428
+ * 共享缓存为空(owner 级目录还没拉到过)时立刻返回 false,不等超时。
429
+ */
430
+ async applyFromSharedCacheWithin(timeoutMs) {
431
+ if (!OWNER_DIRECTORY_SCOPES.some(scope => this._sharedCacheExists(scope)))
432
+ return false;
433
+ let timer;
434
+ try {
435
+ return await Promise.race([
436
+ this.applyFromSharedCache().catch(error => {
437
+ logger.warn(`[OwnerDirectoryCache] Apply from shared cache failed: ${errorText(error)}`);
438
+ return false;
439
+ }),
440
+ new Promise(resolve => { timer = setTimeout(() => resolve(false), timeoutMs); }),
441
+ ]);
442
+ }
443
+ finally {
444
+ if (timer)
445
+ clearTimeout(timer);
446
+ }
447
+ }
448
+ /** 共享缓存里是否至少有一个 scope 的文件存在(存在性判定不做解析,用于快速跳过)。 */
449
+ _sharedCacheExists(scope) {
450
+ return existsAtomic(this._sharedCachePath(scope));
451
+ }
366
452
  /**
367
453
  * 共享缓存与本地快照内容是否已一致。
368
454
  *
@@ -409,15 +495,48 @@ export class OwnerDirectoryCache {
409
495
  _sharedCachePath(scope) {
410
496
  return path.join(this._sharedCacheDir(), `${scope}.json`);
411
497
  }
498
+ /**
499
+ * 读出共享缓存里的名录文档,兼容两种落盘形态。
500
+ *
501
+ * 现行形态是**远端对象的逐字节副本**:文件内容就是远端那一份 JSON,本地不
502
+ * 加信封、不重新序列化,摘要按字节重算。早期形态是
503
+ * `{ schemaVersion, ownerAid, scope, sha256, document }` 信封——别的 agent
504
+ * 进程、旧版本 daemon 都可能还在写它,读的时候认,下次拉取自然被覆盖。
505
+ *
506
+ * 判据是 `schemaVersion`(信封)与 `schema_version`(远端文档)这对大小写
507
+ * 不同的字段名,两者不会同时出现。
508
+ */
509
+ _readSharedCacheDocument(scope) {
510
+ const bytes = atomicReadBytes(this._sharedCachePath(scope));
511
+ if (!bytes)
512
+ return undefined;
513
+ // BOM 与远端那份一致时同样保留在盘上,只是解析前剥掉。
514
+ let text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
515
+ if (text.charCodeAt(0) === 0xfeff)
516
+ text = text.slice(1);
517
+ const parsed = JSON.parse(text);
518
+ if (!isRecord(parsed))
519
+ return undefined;
520
+ // 旧信封形态:摘要由信封声明,内容在 document 里。
521
+ if (parsed.schemaVersion === 2) {
522
+ if (!isRecord(parsed.document))
523
+ return undefined;
524
+ if (parsed.ownerAid !== this.options.ownerAid || parsed.scope !== scope)
525
+ return undefined;
526
+ const declared = typeof parsed.sha256 === 'string' ? parsed.sha256.toLowerCase() : '';
527
+ if (!SHA256_RE.test(declared))
528
+ return undefined;
529
+ const documentBytes = new TextEncoder().encode(JSON.stringify(parsed.document));
530
+ return { parsed: parsed.document, bytes: documentBytes, sha256: declared };
531
+ }
532
+ return { parsed, bytes, sha256: createHash('sha256').update(bytes).digest('hex') };
533
+ }
412
534
  _readSharedCacheDigest(scope) {
413
535
  try {
414
- const raw = atomicReadJson(this._sharedCachePath(scope));
415
- if (!isRecord(raw) || raw.schemaVersion !== 2)
536
+ const stored = this._readSharedCacheDocument(scope);
537
+ if (!stored || !isRecord(stored.parsed))
416
538
  return undefined;
417
- const document = raw.document;
418
- if (!isRecord(document))
419
- return undefined;
420
- const digest = document.content_digest;
539
+ const digest = stored.parsed.content_digest;
421
540
  return isValidContentDigest(digest) ? digest : undefined;
422
541
  }
423
542
  catch {
@@ -428,24 +547,19 @@ export class OwnerDirectoryCache {
428
547
  * 从共享缓存读出原始文档,再走一遍和网络拉取完全相同的校验。
429
548
  *
430
549
  * 共享缓存是我们自己写的,但它同样是磁盘上的字节:可能是旧版本格式、
431
- * 可能被别的 agent 写坏。只信任 sha256 而不重算摘要,等于让第一个拉取的
432
- * agent 替所有后续 agent 做了校验。
550
+ * 可能被别的 agent 写坏。摘要一律按字节重算,不信任文件里的任何声明值——
551
+ * 那等于让第一个拉取的 agent 替所有后续 agent 做了校验。
433
552
  */
434
553
  _readSharedCache() {
435
554
  const result = {};
436
555
  for (const scope of OWNER_DIRECTORY_SCOPES) {
437
556
  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))
557
+ const stored = this._readSharedCacheDocument(scope);
558
+ if (!stored)
447
559
  continue;
448
- result[scope] = this.parseDirectoryObject(raw.document, sha256, scope);
560
+ result[scope] = this.parseDirectoryObject(stored.parsed, stored.bytes, stored.sha256, scope, {
561
+ storageUpdatedAtMs: mtimeOf(this._sharedCachePath(scope)),
562
+ });
449
563
  }
450
564
  catch (error) {
451
565
  logger.warn(`[OwnerDirectoryCache] Shared cache for ${scope} rejected: ${errorText(error)}`);
@@ -453,6 +567,13 @@ export class OwnerDirectoryCache {
453
567
  }
454
568
  return result;
455
569
  }
570
+ /**
571
+ * 共享缓存落盘:**远端字节原样写入**,mtime 跟随 storage。
572
+ *
573
+ * 不做信封、不重新序列化——盘上这份文件与远端对象逐字节一致,`sha256`
574
+ * 和 `cmp` 都能直接对,排查时不用再区分"到底哪一份是真的"。本地需要的
575
+ * 元数据(摘要、条数、时间)全部从字节和文档自身推导,不再另存一份。
576
+ */
456
577
  _writeSharedCache(data) {
457
578
  try {
458
579
  const dir = this._sharedCacheDir();
@@ -461,16 +582,19 @@ export class OwnerDirectoryCache {
461
582
  const file = data[scope];
462
583
  if (!file)
463
584
  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);
585
+ const target = this._sharedCachePath(scope);
586
+ atomicWriteBytes(target, file.bytes);
587
+ fs.chmodSync(target, 0o600);
588
+ // mtime 必须在 rename 之后设:写入本身会把时间戳刷成本机当前时刻。
589
+ if (file.storageUpdatedAtMs !== undefined) {
590
+ const seconds = file.storageUpdatedAtMs / 1000;
591
+ try {
592
+ fs.utimesSync(target, seconds, seconds);
593
+ }
594
+ catch (error) {
595
+ logger.debug(`[OwnerDirectoryCache] utimes ${scope} failed: ${errorText(error)}`);
596
+ }
597
+ }
474
598
  }
475
599
  }
476
600
  catch (error) {
@@ -518,31 +642,87 @@ export class OwnerDirectoryCache {
518
642
  throw new OwnerDirectoryCacheError('CLIENT_UNAVAILABLE', 'fetch requires a connected AUN client');
519
643
  const result = {};
520
644
  const denied = [];
645
+ const failures = {};
521
646
  for (const scope of OWNER_DIRECTORY_SCOPES) {
522
647
  try {
523
648
  const key = `data/directories/v2/${scope}.json`;
524
649
  const { bytes, metadata } = await readAuthoritativePersonalFsObject(this.options.client, `/${key}`, this.options.ownerAid, OWNER_DIRECTORY_MAX_OBJECT_BYTES);
525
650
  const sha256 = typeof metadata.sha256 === 'string' ? metadata.sha256.toLowerCase() : '';
651
+ // 网络这一层已经拿回字节:先落盘留证,再谈内容合不合格。
652
+ // 校验失败时下游只看得到一行 WARN,靠这份原始字节才能判断"拉到了、
653
+ // 只是内容不对",而不是"拉不到"。
654
+ this._writeRawFetch(scope, bytes, sha256);
526
655
  if (!SHA256_RE.test(sha256))
527
656
  throw new OwnerDirectoryCacheError('INVALID_DIGEST', `bad sha256 for ${scope}`);
528
657
  let text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
529
658
  if (text.charCodeAt(0) === 0xfeff)
530
659
  text = text.slice(1);
531
660
  const parsed = JSON.parse(text);
532
- result[scope] = this.parseDirectoryObject(parsed, sha256, scope);
661
+ // 落盘字节保持原样(含 BOM 都留着),解析才剥——共享缓存必须与远端逐字节一致。
662
+ result[scope] = this.parseDirectoryObject(parsed, bytes, sha256, scope, {
663
+ storageUpdatedAtMs: storageMtimeMs(metadata) ?? numberField(parsed, 'updated_at_ms'),
664
+ });
533
665
  logger.info(`[OwnerDirectoryCache] Fetched ${scope}: total=${result[scope].total} digest=${result[scope].contentDigest?.slice(0, 8) ?? 'none'}`);
534
666
  }
535
667
  catch (error) {
536
668
  const normalized = toDirectoryError(error);
537
- logger.warn(`[OwnerDirectoryCache] Fetch failed for ${scope}: ${errorText(normalized)}`);
669
+ const code = normalized instanceof OwnerDirectoryCacheError ? normalized.code : 'FETCH_ERROR';
670
+ failures[scope] = `${code}: ${errorText(normalized)}`;
671
+ logger.warn(`[OwnerDirectoryCache] Fetch failed for ${scope}: ${errorText(normalized)} (raw kept for diagnosis)`);
538
672
  this.options.onError?.(scope, normalized);
673
+ this._appendFetchFailure(scope, code, errorText(normalized));
539
674
  // 远端拒绝随结果返回,由调用方作废自己的本地快照;其它错误保持 pending,
540
675
  // 交给时间退避重试。拒绝信息必须在返回值里走——单飞复用者也要看得到。
541
676
  if (isPermissionDenied(normalized))
542
677
  denied.push(scope);
543
678
  }
544
679
  }
545
- return { data: result, denied };
680
+ return { data: result, denied, failures };
681
+ }
682
+ /**
683
+ * 原始字节落盘:`<shared>/raw/<scope>.json` 与描述它的 `<scope>.meta.json`。
684
+ *
685
+ * 这一份**不参与**任何读取路径,只为排查——"到底拉到了什么"必须能从磁盘
686
+ * 直接看到,而不是只能从日志推断。所以它在校验之前写,失败也保留。
687
+ */
688
+ _writeRawFetch(scope, bytes, sha256) {
689
+ try {
690
+ const dir = path.join(this._sharedCacheDir(), RAW_DIR);
691
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
692
+ const target = path.join(dir, `${scope}.json`);
693
+ atomicWriteBytes(target, bytes);
694
+ fs.chmodSync(target, 0o600);
695
+ const meta = path.join(dir, `${scope}.meta.json`);
696
+ atomicWriteJson(meta, { sha256, bytes: bytes.byteLength, fetchedAt: this.now() });
697
+ fs.chmodSync(meta, 0o600);
698
+ }
699
+ catch (error) {
700
+ logger.warn(`[OwnerDirectoryCache] Failed to keep raw ${scope} bytes: ${errorText(error)}`);
701
+ }
702
+ }
703
+ /**
704
+ * 拉取失败记录:`<shared>/failures.jsonl`,一行一次,只保留最近若干条。
705
+ *
706
+ * 写入同样尽力而为——诊断设施本身的故障不能影响同步。
707
+ */
708
+ _appendFetchFailure(scope, code, error) {
709
+ try {
710
+ const dir = this._sharedCacheDir();
711
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
712
+ const target = path.join(dir, FAILURES_FILE);
713
+ const line = JSON.stringify({ ts: this.now(), scope, code, error });
714
+ const previous = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : '';
715
+ const lines = previous.split('\n').filter(Boolean);
716
+ lines.push(line);
717
+ const kept = lines.slice(-FAILURE_KEEP_LINES);
718
+ while (kept.length > 1 && Buffer.byteLength(kept.join('\n'), 'utf8') > FAILURE_MAX_BYTES)
719
+ kept.shift();
720
+ atomicWriteText(target, `${kept.join('\n')}\n`);
721
+ fs.chmodSync(target, 0o600);
722
+ }
723
+ catch (writeError) {
724
+ logger.warn(`[OwnerDirectoryCache] Failed to record ${scope} fetch failure: ${errorText(writeError)}`);
725
+ }
546
726
  }
547
727
  /**
548
728
  * 校验并解析一份名录快照。网络拉取和共享缓存读回走同一条路径——
@@ -551,13 +731,13 @@ export class OwnerDirectoryCache {
551
731
  * 摘要必须在原始 `entries` 上重算:normalizeEntry 会丢未知字段、把 null
552
732
  * 变成缺失,用归一化后的数据算必然对不上。
553
733
  */
554
- parseDirectoryObject(parsed, sha256, scope) {
734
+ parseDirectoryObject(parsed, bytes, sha256, scope, extra = {}) {
555
735
  if (!isRecord(parsed))
556
736
  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`);
737
+ const schemaVersion = parsed.schema_version;
738
+ if (schemaVersion !== 2 && schemaVersion !== 3) {
739
+ throw new OwnerDirectoryCacheError('SCHEMA_VERSION', `${scope}.json schema_version must be 2 or 3, got ${String(schemaVersion)}`);
740
+ }
561
741
  if (parsed.scope !== scope)
562
742
  throw new OwnerDirectoryCacheError('SCOPE_MISMATCH', `${scope}.json scope field mismatch`);
563
743
  const entries = parsed.entries;
@@ -569,8 +749,10 @@ export class OwnerDirectoryCache {
569
749
  if (parsed.total !== entries.length) {
570
750
  throw new OwnerDirectoryCacheError('TOTAL_MISMATCH', `${scope}.json total=${String(parsed.total)} but entries.length=${entries.length}`);
571
751
  }
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`);
752
+ // source_revision: v2 用 SHA256 十六进制,v3 用时间戳格式 (例如 "1793586588371271-727725120")
753
+ // 两者都接受,只要是非空字符串
754
+ if (typeof parsed.source_revision !== 'string' || !parsed.source_revision.trim()) {
755
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json source_revision must be a non-empty string`);
574
756
  }
575
757
  for (const field of ['source_observed_at_ms', 'updated_at_ms']) {
576
758
  const value = parsed[field];
@@ -578,7 +760,7 @@ export class OwnerDirectoryCache {
578
760
  throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json ${field} is not a non-negative integer`);
579
761
  }
580
762
  }
581
- // 逐条语义校验:aid 合法且唯一,条目 owner_aid 合法(内外的判据,可以不同于根)。
763
+ // 逐条语义校验:aid 合法且唯一,条目 owner_aid 合法(内外的判据,可以不同于 owner.aid)。
582
764
  const seen = new Set();
583
765
  for (const entry of entries) {
584
766
  if (!isRecord(entry))
@@ -603,15 +785,85 @@ export class OwnerDirectoryCache {
603
785
  throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json entry ${entry.aid} agent_md_signed_at must be an integer or null`);
604
786
  }
605
787
  }
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`);
788
+ // 校验 groups 和 blocked_aids(v2 扩展字段)
789
+ const groups = parsed.groups;
790
+ if (!Array.isArray(groups))
791
+ throw new OwnerDirectoryCacheError('INVALID_FORMAT', `${scope}.json groups is not an array`);
792
+ if (parsed.group_total !== groups.length) {
793
+ throw new OwnerDirectoryCacheError('TOTAL_MISMATCH', `${scope}.json group_total=${String(parsed.group_total)} but groups.length=${groups.length}`);
794
+ }
795
+ const groupAids = new Set();
796
+ const visibleIds = new Set();
797
+ for (const aid of seen)
798
+ visibleIds.add(`aid:${aid}`);
799
+ for (const group of groups) {
800
+ if (!isRecord(group))
801
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has a non-object group`);
802
+ if (typeof group.group_aid !== 'string' || !group.group_aid) {
803
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json group is missing group_aid`);
804
+ }
805
+ let normalized;
806
+ try {
807
+ normalized = normalizeGroupAid(group.group_aid);
808
+ }
809
+ catch (error) {
810
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json group has invalid group_aid: ${errorText(error)}`);
811
+ }
812
+ if (normalized !== group.group_aid) {
813
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json group_aid not normalized: ${group.group_aid}`);
614
814
  }
815
+ if (groupAids.has(normalized))
816
+ throw new OwnerDirectoryCacheError('DUPLICATE_AID', `${scope}.json repeats group_aid ${normalized}`);
817
+ groupAids.add(normalized);
818
+ visibleIds.add(`group:${normalized}`);
819
+ }
820
+ const blockedAids = parsed.blocked_aids;
821
+ if (!Array.isArray(blockedAids))
822
+ throw new OwnerDirectoryCacheError('INVALID_FORMAT', `${scope}.json blocked_aids is not an array`);
823
+ const blockedIds = new Set();
824
+ for (const block of blockedAids) {
825
+ if (!isRecord(block))
826
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has a non-object blocked_aid`);
827
+ const targetType = block.target_type;
828
+ const targetId = block.target_id;
829
+ if (targetType !== 'aid' && targetType !== 'group') {
830
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked_aid target_type must be "aid" or "group"`);
831
+ }
832
+ if (typeof targetId !== 'string' || !targetId || !isValidAid(targetId)) {
833
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked_aid has invalid target_id`);
834
+ }
835
+ const key = `${targetType}:${targetId}`;
836
+ if (visibleIds.has(key)) {
837
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked target ${targetId} also in ${targetType === 'aid' ? 'entries' : 'groups'}`);
838
+ }
839
+ if (blockedIds.has(key))
840
+ throw new OwnerDirectoryCacheError('DUPLICATE_AID', `${scope}.json repeats blocked ${key}`);
841
+ blockedIds.add(key);
842
+ // 校验规范化:aid 必须 lowercase trim,group_aid 必须已规范化
843
+ if (targetType === 'aid' && targetId.trim().toLowerCase() !== targetId) {
844
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked aid not normalized: ${targetId}`);
845
+ }
846
+ if (targetType === 'group') {
847
+ try {
848
+ if (normalizeGroupAid(targetId) !== targetId) {
849
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked group_aid not normalized: ${targetId}`);
850
+ }
851
+ }
852
+ catch (error) {
853
+ throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json blocked group_aid invalid: ${errorText(error)}`);
854
+ }
855
+ }
856
+ }
857
+ // 身份对象:`owner.aid` 是这份名录属于谁的**唯一**判据(顶层 owner_aid 已从
858
+ // 协议移除)。缺失就无法判断条目内外,整份拒绝——放行等于用一份身份不明的
859
+ // 名录做准入。personal_assistant 是身份元数据,不参与条目集合。两者都原样
860
+ // 进入摘要输入。
861
+ const ownerIdentity = parsed.owner;
862
+ if (!isRecord(ownerIdentity)) {
863
+ throw new OwnerDirectoryCacheError('INVALID_FIELD', `${scope}.json owner identity block is missing`);
864
+ }
865
+ if (ownerIdentity.aid !== this.options.ownerAid) {
866
+ throw new OwnerDirectoryCacheError('OWNER_MISMATCH', `${scope}.json owner.aid does not match the authorized Owner`);
615
867
  }
616
868
  const personalAssistant = parsed.personal_assistant;
617
869
  if (personalAssistant !== undefined && !isRecord(personalAssistant)) {
@@ -624,6 +876,8 @@ export class OwnerDirectoryCache {
624
876
  }
625
877
  const recomputed = directoryContentDigest({
626
878
  entries,
879
+ groups,
880
+ blockedAids,
627
881
  owner: ownerIdentity,
628
882
  personalAssistant,
629
883
  });
@@ -631,12 +885,15 @@ export class OwnerDirectoryCache {
631
885
  throw new OwnerDirectoryCacheError('DIGEST_MISMATCH', `${scope}.json content_digest mismatch: declared=${declared.slice(0, 12)} recomputed=${recomputed.slice(0, 12)}`);
632
886
  }
633
887
  return {
634
- raw: parsed, sha256, ownerAid: this.options.ownerAid, scope, schemaVersion: 2,
888
+ raw: parsed, bytes, sha256, ownerAid: this.options.ownerAid, scope, schemaVersion: schemaVersion,
635
889
  contentDigest: declared,
890
+ ...(extra.storageUpdatedAtMs !== undefined ? { storageUpdatedAtMs: extra.storageUpdatedAtMs } : {}),
636
891
  snapshotId: typeof parsed.snapshot_id === 'string' && SNAPSHOT_ID_RE.test(parsed.snapshot_id) ? parsed.snapshot_id : sha256.slice(0, 64),
637
892
  total: entries.length,
638
893
  updatedAtMs: parsed.updated_at_ms,
639
894
  entries: entries,
895
+ groups: groups,
896
+ blockedAids: blockedAids,
640
897
  owner: parseIdentityField(parsed.owner),
641
898
  personalAssistant: parseIdentityField(parsed.personal_assistant),
642
899
  };
@@ -861,10 +1118,22 @@ export class OwnerDirectoryCache {
861
1118
  /**
862
1119
  * 重算并写回 `directory.md`。
863
1120
  *
864
- * 只在两处调用:名录落地之后,以及备注被改写之后。不做定时刷新,也不在
865
- * 消息路径上比对——名录和备注都不变时,注入内容本来就不会变。
1121
+ * 调用点覆盖六种情形:授权保存、授权撤销、共享缓存已应用的热路径早退、
1122
+ * 名录落地、摘要一致时的重算、范围被 blocked。不做定时刷新,也不在消息
1123
+ * 路径上比对——名录、备注、开关都不变时,注入内容本来就不会变。
1124
+ *
1125
+ * **只有确证名录已不可用时才删文件**:`directory.md` 是 ECK 的注入源,
1126
+ * `hasOwnerDirectoryMarkdown` 只看"文件存在且非空"。授权被撤销后快照已经
1127
+ * 删了,旧注入却还在,等于让 agent 拿一份已作废的名录做判断——比没有名录
1128
+ * 更危险。
1129
+ *
1130
+ * 但"读不到快照"不等于"名录没了":快照文件可能正在原子写、指纹刚变、
1131
+ * 或单次读失败。在没有授权的重算路径上(如摘要一致时的早退),把这种瞬时
1132
+ * 读不到当成删除会误删注入源。所以删除条件收窄为 `directoryGone()`——
1133
+ * 授权真的不存在或快照文件真的不在盘上。其余情形保留现有内容不动。
866
1134
  */
867
1135
  refreshMarkdown() {
1136
+ const target = path.join(this.options.directory, OWNER_DIRECTORY_MARKDOWN_FILE);
868
1137
  try {
869
1138
  const snapshot = this.readCachedSnapshot('contacts');
870
1139
  const markdown = renderOwnerDirectoryMarkdown({
@@ -874,9 +1143,15 @@ export class OwnerDirectoryCache {
874
1143
  remarks: this.remarksSnapshot(),
875
1144
  allowExternalContacts: this.options.allowExternalContacts?.(),
876
1145
  });
877
- if (!markdown)
1146
+ if (!markdown) {
1147
+ if (!this.directoryGone()) {
1148
+ logger.debug(`[OwnerDirectoryCache] directory.md kept: snapshot unreadable but directory not provably gone for ${this.options.ownerAid}`);
1149
+ return;
1150
+ }
1151
+ // 确证不可用时连同热备名一起删,避免 atomicRead 把中断的 rename 恢复回来。
1152
+ atomicRemove(target);
878
1153
  return;
879
- const target = path.join(this.options.directory, OWNER_DIRECTORY_MARKDOWN_FILE);
1154
+ }
880
1155
  fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
881
1156
  // 内容不变就不写盘:ECK 的注入按文件指纹走,无谓的写入会触发无谓的重新加载。
882
1157
  try {
@@ -890,6 +1165,22 @@ export class OwnerDirectoryCache {
890
1165
  logger.warn(`[OwnerDirectoryCache] refreshMarkdown failed: ${errorText(error)}`);
891
1166
  }
892
1167
  }
1168
+ /**
1169
+ * 名录是否**确证**已不可用。
1170
+ *
1171
+ * 只在两种情况下为真:
1172
+ *
1173
+ * 1. 没有有效授权(未授权、已过期、范围被 blocked)——此时快照本就不该被使用;
1174
+ * 2. 授权有效但快照文件确实不在盘上(含热备)——此时没有可渲染的内容。
1175
+ *
1176
+ * 快照文件存在却读不出(解析失败、字段校验不过、原子写窗口)时返回 false:
1177
+ * 这是"暂时读不到",不是"名录没了",调用方应保留旧注入而不是删掉。
1178
+ */
1179
+ directoryGone() {
1180
+ if (this.scopeAccess('contacts') !== 'authorized')
1181
+ return true;
1182
+ return !existsAtomic(this.cachePath('contacts'));
1183
+ }
893
1184
  /**
894
1185
  * 备注集合,带目录指纹缓存。
895
1186
  *
@@ -1018,6 +1309,49 @@ function remarksStamp(directory) {
1018
1309
  function isRecord(value) {
1019
1310
  return typeof value === 'object' && value !== null && !Array.isArray(value);
1020
1311
  }
1312
+ /** 读取一个数字字段;缺失或非有限数返回 undefined。 */
1313
+ function numberField(obj, key) {
1314
+ if (!isRecord(obj))
1315
+ return undefined;
1316
+ const value = obj[key];
1317
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
1318
+ }
1319
+ /**
1320
+ * 从 `storage.get_object` 的元数据里取对象修改时间,归一化成毫秒。
1321
+ *
1322
+ * 服务端给的是 Unix 秒(`updated_at`),协议文档也允许其它时间字段;
1323
+ * 这里按"大于 1e10 就当毫秒"的惯例处理,另外认 ISO 字符串。
1324
+ */
1325
+ function storageMtimeMs(metadata) {
1326
+ for (const key of ['updated_at_ms', 'updatedAtMs', 'mtime_ms', 'mtimeMs']) {
1327
+ const value = numberField(metadata, key);
1328
+ if (value !== undefined && value > 0)
1329
+ return value;
1330
+ }
1331
+ for (const key of ['updated_at', 'updatedAt', 'mtime', 'last_modified', 'modified_at']) {
1332
+ const value = numberField(metadata, key);
1333
+ if (value !== undefined && value > 0)
1334
+ return value > 1e11 ? value : value * 1000;
1335
+ }
1336
+ for (const key of ['updated_at_iso', 'last_modified_iso', 'mtime_iso']) {
1337
+ const value = metadata[key];
1338
+ if (typeof value === 'string') {
1339
+ const parsed = Date.parse(value);
1340
+ if (Number.isFinite(parsed) && parsed > 0)
1341
+ return parsed;
1342
+ }
1343
+ }
1344
+ return undefined;
1345
+ }
1346
+ /** 文件当前的 mtime(毫秒);取不到返回 undefined。 */
1347
+ function mtimeOf(filePath) {
1348
+ try {
1349
+ return fs.statSync(filePath).mtimeMs;
1350
+ }
1351
+ catch {
1352
+ return undefined;
1353
+ }
1354
+ }
1021
1355
  function errorText(error) {
1022
1356
  return error instanceof Error ? error.message : String(error);
1023
1357
  }