evolcore 0.0.43-test.1 → 0.0.43-test.2
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.
- package/CHANGELOG.md +24 -1
- package/README.md +22 -0
- package/dist/agents/claude-runner.js +26 -2
- package/dist/agents/codex/app-server-client.js +12 -0
- package/dist/agents/codex-runner.js +49 -8
- package/dist/agents/ecagent-runner.js +26 -9
- package/dist/agents/gemini-runner.js +15 -12
- package/dist/agents/tool-time-context.js +55 -0
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/model-headers.js +17 -0
- package/dist/aun/msg/p2p.js +3 -0
- package/dist/channels/aun.js +484 -43
- package/dist/channels/builtin-plugins.js +16 -11
- package/dist/channels/dingtalk.js +83 -31
- package/dist/channels/feishu.js +29 -13
- package/dist/channels/qqbot.js +32 -11
- package/dist/channels/wechat.js +13 -3
- package/dist/channels/wecom.js +67 -27
- package/dist/cli/agent-command.js +3 -86
- package/dist/cli/agent-create.js +22 -6
- package/dist/cli/agent.js +1 -79
- package/dist/cli/aun-commands.js +1 -0
- package/dist/cli/config.js +1 -1
- package/dist/cli/daemon-commands.js +47 -2
- package/dist/cli/data-command.js +9 -1
- package/dist/cli/debug-mode.js +1 -1
- package/dist/cli/diag.js +1 -1
- package/dist/cli/directory.js +77 -64
- package/dist/cli/getmeta-command.js +1 -1
- package/dist/cli/index.js +79 -22
- package/dist/cli/init.js +1 -23
- package/dist/cli/link-rules.js +1 -1
- package/dist/cli/managed-command-guard.js +0 -1
- package/dist/cli/pa-workspace-command.js +36 -2
- package/dist/cli/peer.js +1 -1
- package/dist/cli/restart-monitor.js +17 -3
- package/dist/cli/role.js +1 -1
- package/dist/cli/session-command.js +1 -1
- package/dist/cli/stats.js +2 -2
- package/dist/cli/thread-command.js +1 -1
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/access-policy.js +1 -0
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +7 -0
- package/dist/config/role-schema.js +4 -3
- package/dist/config/role-service.js +3 -3
- package/dist/config-store.js +75 -4
- package/dist/core/agent-ipc-registration.js +16 -59
- package/dist/core/auth/authorization-audit.js +52 -14
- package/dist/core/auth/operation-authorizer.js +0 -11
- package/dist/core/auth/operation-catalog.js +0 -18
- package/dist/core/channel-loader.js +152 -16
- package/dist/core/command/agent-control.js +2 -1
- package/dist/core/command/cli-intent-parser.js +0 -8
- package/dist/core/command/command-handler.js +17 -46
- package/dist/core/command/connect-menu.js +7 -3
- package/dist/core/command/menu-catalog.js +3 -2
- package/dist/core/command/menu-handler.js +51 -8
- package/dist/core/command/menu-protocol.js +20 -0
- package/dist/core/command/slash-handler.js +101 -40
- package/dist/core/daemon-file-cache.js +3 -3
- package/dist/core/evolagent-registry.js +5 -4
- package/dist/core/evolagent.js +5 -8
- package/dist/core/handoff/argv-parse.js +115 -0
- package/dist/core/handoff/ipc-registration.js +1 -1
- package/dist/core/ipc-registration.js +19 -2
- package/dist/core/memory/consolidation.js +8 -1
- package/dist/core/memory/relation-sweep.js +20 -8
- package/dist/core/message/aun-ipc-sender.js +28 -1
- package/dist/core/message/contact-admission.js +548 -0
- package/dist/core/message/im-renderer.js +69 -10
- package/dist/core/message/message-admission.js +28 -3
- package/dist/core/message/message-bridge.js +46 -5
- package/dist/core/message/message-utils.js +0 -5
- package/dist/core/message/peer-mode.js +44 -10
- package/dist/core/message/response-engine.js +268 -69
- package/dist/core/message/retry-scheduler.js +4 -0
- package/dist/core/permission/ec-command-parser.js +1 -28
- package/dist/core/permission/readonly-shell-query.js +34 -8
- package/dist/core/permission/tool-policy.js +50 -5
- package/dist/core/role/runtime-policy.js +14 -2
- package/dist/core/session/session-manager.js +9 -1
- package/dist/core/soul.js +66 -0
- package/dist/core/system-session/memory.js +2 -2
- package/dist/directory/contact-admission-paths.js +9 -0
- package/dist/directory/owner-directory-admission.js +128 -29
- package/dist/directory/owner-directory-cache.js +364 -50
- package/dist/directory/owner-directory-identity.js +60 -0
- package/dist/directory/owner-directory-markdown.js +120 -47
- package/dist/directory/owner-directory-policy.js +108 -0
- package/dist/directory/owner-directory-query-operation.js +219 -32
- package/dist/directory/owner-directory-remarks.js +29 -2
- package/dist/directory/owner-directory-search.js +50 -18
- package/dist/directory/owner-directory-store.js +150 -30
- package/dist/eck/kit-renderer.js +12 -5
- package/dist/eck/manifest-engine.js +55 -6
- package/dist/eck/message-renderer.js +5 -2
- package/dist/eck/paactive-context.js +45 -0
- package/dist/ecweb/basic-settings-service.js +2 -2
- package/dist/ecweb/message-context-service.js +24 -16
- package/dist/index.js +9 -5
- package/dist/ipc.js +1 -1
- package/dist/paths.js +26 -0
- package/dist/response-system/config-resolver.js +1 -1
- package/dist/response-system/engines/v1/index.js +4 -1
- package/dist/response-system/engines/v1/paactive-flow.js +18 -0
- package/dist/response-system/modes/single-session/index.js +7 -2
- package/dist/trigger/scheduler.js +3 -5
- package/dist/trigger/validation.js +4 -0
- package/dist/utils/error-utils.js +5 -2
- package/dist/utils/logger.js +13 -4
- package/dist/utils/npm-ops.js +2 -2
- package/dist/utils/windows-autostart.js +1 -1
- package/ecagent/dist/agent-loop.js +43 -1
- package/kits/docs/INDEX.md +1 -0
- package/kits/docs/context-assembly.md +21 -6
- package/kits/docs/eck_templates/INDEX.template.md +1 -2
- package/kits/docs/evolcore/INDEX.md +1 -1
- package/kits/docs/evolcore/agent-create.md +5 -5
- package/kits/docs/evolcore/agent.md +4 -9
- package/kits/docs/evolcore/directory.md +137 -0
- package/kits/docs/evolcore/menu-protocol.md +55 -0
- package/kits/docs/evolcore/response.md +7 -1
- package/kits/docs/evolcore/tool-authorization.md +1 -1
- package/kits/docs/evolcore/trigger.md +4 -0
- package/kits/docs/prompt-loading-architecture.md +6 -2
- package/kits/eck_manifest.auxiliary.json +1 -0
- package/kits/eck_manifest.json +57 -4
- package/kits/eck_manifest.memory.json +67 -3
- package/kits/eck_manifest.paactive.json +528 -0
- package/kits/eck_message_manifest.paactive.json +233 -0
- package/kits/rules/01-overview.md +2 -2
- package/kits/rules/03-identity.md +10 -9
- package/kits/rules/05-venue.md +2 -4
- package/kits/rules/06-channel.md +1 -1
- package/kits/schemas/_meta.json +31 -3
- package/kits/schemas/agent-config.schema.18.json +5 -0
- package/kits/schemas/agent-config.schema.19.json +924 -0
- package/kits/schemas/relation-config.schema.12.json +289 -0
- package/kits/schemas/role-config.schema.2.json +215 -0
- package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
- package/kits/skills/ec-trigger/SKILL.md +4 -4
- package/kits/skills/personal-assistant/SKILL.md +109 -53
- package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
- package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
- package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
- package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
- package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
- package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
- package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
- package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
- package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
- package/kits/templates/message-fragments/paactive/item.md +3 -0
- package/kits/templates/soul/00-GUIDE.md +61 -0
- package/kits/templates/soul/01-identity.md +5 -0
- package/kits/templates/soul/02-persona.md +11 -0
- package/kits/templates/soul/03-duties.md +5 -0
- package/kits/templates/soul/04-working-style.md +5 -0
- package/kits/templates/system-fragments/bootstrap.md +7 -7
- package/kits/templates/system-fragments/commands.md +3 -2
- package/kits/templates/system-fragments/directory-contacts.md +9 -0
- package/kits/templates/system-fragments/memory.md +1 -1
- package/kits/templates/system-fragments/paactive/channel.md +25 -0
- package/kits/templates/system-fragments/paactive/reply.md +25 -0
- package/kits/templates/system-fragments/paactive/session.md +32 -0
- package/kits/templates/system-fragments/personal-assistant.md +65 -0
- package/package.json +3 -2
- package/dist/cli/handoff-command.js +0 -353
- package/dist/directory/owner-directory-remark-operation.js +0 -147
- package/kits/docs/evolcore/self-summary.md +0 -29
|
@@ -4,10 +4,13 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { isValidAid } from '../aun/aid/validation.js';
|
|
5
5
|
import { normalizeGroupAid } from '../aun/group/identity.js';
|
|
6
6
|
import { readAuthoritativePersonalFsObject } from '../aun/group/fs-download.js';
|
|
7
|
-
import { atomicRead, atomicReadBytes,
|
|
7
|
+
import { atomicRead, atomicReadBytes, atomicRemove, atomicWriteBytes, atomicWriteJson, atomicWriteText, existsAtomic } from '../utils/atomic-write.js';
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
import { resolveRoot } from '../paths.js';
|
|
10
|
+
import { contactAdmissionDirectory } from './contact-admission-paths.js';
|
|
10
11
|
import { OWNER_DIRECTORY_MARKDOWN_FILE, renderOwnerDirectoryMarkdown } from './owner-directory-markdown.js';
|
|
12
|
+
import { OWNER_DIRECTORY_IDENTITY_FILE, buildOwnerDirectoryIdentity } from './owner-directory-identity.js';
|
|
13
|
+
import { resolveOwnerDirectoryRenderPolicy } from './owner-directory-policy.js';
|
|
11
14
|
import { directoryContentDigest } from './canonical-digest.js';
|
|
12
15
|
import { readAllRemarks, OWNER_DIRECTORY_REMARKS_DIR } from './owner-directory-remarks.js';
|
|
13
16
|
import { archiveSnapshot, appendChanges, diffSnapshots, collectAgentMdRefreshAids, isValidContentDigest, } from './owner-directory-store.js';
|
|
@@ -87,6 +90,9 @@ export class OwnerDirectoryCacheError extends Error {
|
|
|
87
90
|
/** Per-Agent durable snapshots plus the derived directory.md that ECK loads. */
|
|
88
91
|
export class OwnerDirectoryCache {
|
|
89
92
|
options;
|
|
93
|
+
pendingInFlight;
|
|
94
|
+
applyTail = Promise.resolve();
|
|
95
|
+
fetchGeneration = 0;
|
|
90
96
|
now;
|
|
91
97
|
/**
|
|
92
98
|
* 落地单飞。消息并发进来时,后到的调用方复用同一轮落地,而不是各自再跑一遍
|
|
@@ -120,12 +126,50 @@ export class OwnerDirectoryCache {
|
|
|
120
126
|
this.now = options.now ?? Date.now;
|
|
121
127
|
}
|
|
122
128
|
// ── Authorization ───────────────────────────────────────────────────────────
|
|
129
|
+
/** A retired runtime must never mutate the current relation's shared files. */
|
|
130
|
+
canMutate() {
|
|
131
|
+
if (this.options.isCurrent && !this.options.isCurrent())
|
|
132
|
+
return false;
|
|
133
|
+
const version = this.options.relationVersion;
|
|
134
|
+
for (const file of [path.join(contactAdmissionDirectory(this.options.selfAid), 'binding.json'), this.authorizationPath(), this.cachePath('contacts')]) {
|
|
135
|
+
let raw;
|
|
136
|
+
try {
|
|
137
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error.code === 'ENOENT')
|
|
141
|
+
continue;
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
// A newer disk generation is authoritative even for standalone cache users.
|
|
145
|
+
if (version === undefined && raw.relationVersion !== undefined)
|
|
146
|
+
return false;
|
|
147
|
+
if (version !== undefined && typeof raw.relationVersion === 'number' && raw.relationVersion > version)
|
|
148
|
+
return false;
|
|
149
|
+
if (raw.ownerAid !== this.options.ownerAid && (!this.options.isCurrent || !this.options.isCurrent()))
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
/** Local probes must not remove another runtime's in-progress atomic write. */
|
|
155
|
+
readLocalJson(file) {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (error.code === 'ENOENT')
|
|
161
|
+
return undefined;
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
123
165
|
/**
|
|
124
166
|
* 记录 Owner 的授权。只保留"能不能读、读到什么时候"。
|
|
125
167
|
*
|
|
126
168
|
* 收到新授权意味着重新开始:失败计数清零,之前被拉黑的范围一并解除。
|
|
127
169
|
*/
|
|
128
170
|
saveAuthorization(result) {
|
|
171
|
+
if (!this.canMutate())
|
|
172
|
+
return;
|
|
129
173
|
logger.info(`[OwnerDirectoryCache] Saving authorization for Owner ${this.options.ownerAid}, status: ${result.status}`);
|
|
130
174
|
if (result.owner_aid !== this.options.ownerAid || result.grantee_aid !== this.options.selfAid) {
|
|
131
175
|
throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access result identity is invalid');
|
|
@@ -133,6 +177,11 @@ export class OwnerDirectoryCache {
|
|
|
133
177
|
if (!GRANT_STATUSES.has(result.status)) {
|
|
134
178
|
throw new OwnerDirectoryCacheError('INVALID_GRANT', 'directory/access status is invalid');
|
|
135
179
|
}
|
|
180
|
+
if (this.options.relationVersion !== undefined) {
|
|
181
|
+
const marker = path.join(contactAdmissionDirectory(this.options.selfAid), 'binding.json');
|
|
182
|
+
fs.mkdirSync(path.dirname(marker), { recursive: true, mode: 0o700 });
|
|
183
|
+
atomicWriteJson(marker, { ownerAid: this.options.ownerAid, granteeAid: this.options.selfAid, relationVersion: this.options.relationVersion });
|
|
184
|
+
}
|
|
136
185
|
// 撤销/拒绝:不留凭证也不留快照,准入随即回落到"名录不可用"。
|
|
137
186
|
if (result.status !== 'active' && result.status !== 'sync_pending' && result.status !== 'revoke_pending') {
|
|
138
187
|
this.revokeAuthorization(result.status);
|
|
@@ -140,6 +189,7 @@ export class OwnerDirectoryCache {
|
|
|
140
189
|
}
|
|
141
190
|
const grant = {
|
|
142
191
|
schemaVersion: 2,
|
|
192
|
+
relationVersion: this.options.relationVersion,
|
|
143
193
|
ownerAid: this.options.ownerAid,
|
|
144
194
|
granteeAid: this.options.selfAid,
|
|
145
195
|
grantedAt: this.now(),
|
|
@@ -158,29 +208,38 @@ export class OwnerDirectoryCache {
|
|
|
158
208
|
* 这就是全部判断:有授权、未过期、没被远端明确拒绝过。**不按 scope 区分**——
|
|
159
209
|
* 名录只有一份文件,能不能读由 storage 的 ACL 决定,不在这里重复判一次。
|
|
160
210
|
*/
|
|
161
|
-
scopeAccess(
|
|
211
|
+
scopeAccess(scope) {
|
|
212
|
+
return this.scopeAccessUnavailableReason(scope) ? 'unavailable' : 'authorized';
|
|
213
|
+
}
|
|
214
|
+
scopeAccessUnavailableReason(_scope) {
|
|
162
215
|
const grant = this.loadGrant();
|
|
163
216
|
if (!grant)
|
|
164
|
-
return '
|
|
217
|
+
return 'authorization_missing_or_invalid';
|
|
165
218
|
if (grant.expiresAt > 0 && grant.expiresAt <= this.now())
|
|
166
|
-
return '
|
|
219
|
+
return 'authorization_expired';
|
|
167
220
|
if (this.readSyncState().blockedScopes.length > 0)
|
|
168
|
-
return '
|
|
169
|
-
return
|
|
221
|
+
return 'scope_blocked';
|
|
222
|
+
return undefined;
|
|
170
223
|
}
|
|
171
224
|
// ── Pending update ──────────────────────────────────────────────────────────
|
|
172
225
|
writePendingUpdate(update) {
|
|
173
|
-
|
|
226
|
+
if (!this.canMutate())
|
|
227
|
+
return;
|
|
228
|
+
const stored = { schemaVersion: 1, ...update, relationVersion: this.options.relationVersion };
|
|
174
229
|
fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
|
|
175
230
|
atomicWriteJson(this.pendingPath(), stored);
|
|
176
231
|
}
|
|
177
232
|
readPendingUpdate() {
|
|
178
|
-
const raw =
|
|
233
|
+
const raw = this.readLocalJson(this.pendingPath());
|
|
179
234
|
if (!isRecord(raw) || raw.schemaVersion !== 1 || raw.ownerAid !== this.options.ownerAid)
|
|
180
235
|
return undefined;
|
|
236
|
+
if (this.options.relationVersion !== undefined && typeof raw.relationVersion === 'number' && raw.relationVersion !== this.options.relationVersion)
|
|
237
|
+
return undefined;
|
|
181
238
|
return raw;
|
|
182
239
|
}
|
|
183
240
|
clearPendingUpdate() {
|
|
241
|
+
if (!this.canMutate())
|
|
242
|
+
return;
|
|
184
243
|
try {
|
|
185
244
|
atomicRemove(this.pendingPath());
|
|
186
245
|
}
|
|
@@ -204,6 +263,8 @@ export class OwnerDirectoryCache {
|
|
|
204
263
|
}
|
|
205
264
|
/** 授权被明确撤销或拒绝时,清掉本地快照,避免继续拿旧数据做准入判断。 */
|
|
206
265
|
revokeAuthorization(status) {
|
|
266
|
+
if (!this.canMutate())
|
|
267
|
+
return;
|
|
207
268
|
this.clearPullFailures();
|
|
208
269
|
atomicRemove(this.authorizationPath());
|
|
209
270
|
atomicRemove(this.cachePath(OWNER_DIRECTORY_SCOPES[0]));
|
|
@@ -223,14 +284,14 @@ export class OwnerDirectoryCache {
|
|
|
223
284
|
* 不产生网络请求:只写 pending,真正的拉取推迟到下一条入站消息。
|
|
224
285
|
*/
|
|
225
286
|
writeStartupPendingIfEmpty() {
|
|
226
|
-
const key = this.options.directory
|
|
287
|
+
const key = `${this.options.directory}:${this.options.relationVersion ?? 'legacy'}`;
|
|
227
288
|
if (_startupCheckDone.has(key))
|
|
228
289
|
return;
|
|
229
290
|
_startupCheckDone.add(key);
|
|
230
291
|
const scope = OWNER_DIRECTORY_SCOPES[0];
|
|
231
292
|
if (this.scopeAccess(scope) !== 'authorized')
|
|
232
293
|
return;
|
|
233
|
-
if (this.readCachedSnapshot(scope))
|
|
294
|
+
if (this.options.relationVersion === undefined && this.readCachedSnapshot(scope))
|
|
234
295
|
return;
|
|
235
296
|
if (this.readPendingUpdate())
|
|
236
297
|
return;
|
|
@@ -251,6 +312,31 @@ export class OwnerDirectoryCache {
|
|
|
251
312
|
* 代价都不一样——混在一起会让"来一条消息"既可能发网络请求又可能写盘。
|
|
252
313
|
*/
|
|
253
314
|
async processPendingIfNeeded() {
|
|
315
|
+
if (this.options.relationVersion === undefined)
|
|
316
|
+
return this.processPendingOnce();
|
|
317
|
+
if (this.pendingInFlight)
|
|
318
|
+
return this.pendingInFlight;
|
|
319
|
+
const run = (async () => {
|
|
320
|
+
while (true) {
|
|
321
|
+
const before = this.readPendingUpdate();
|
|
322
|
+
if (!before || (this.options.isCurrent && !this.options.isCurrent()))
|
|
323
|
+
return;
|
|
324
|
+
await this.processPendingOnce();
|
|
325
|
+
const after = this.readPendingUpdate();
|
|
326
|
+
if (!after || (after.operationId === before.operationId && after.markedAtMs === before.markedAtMs))
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
})();
|
|
330
|
+
this.pendingInFlight = run;
|
|
331
|
+
try {
|
|
332
|
+
await run;
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
if (this.pendingInFlight === run)
|
|
336
|
+
this.pendingInFlight = undefined;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
async processPendingOnce() {
|
|
254
340
|
const pending = this.readPendingUpdate();
|
|
255
341
|
if (!pending)
|
|
256
342
|
return;
|
|
@@ -262,7 +348,9 @@ export class OwnerDirectoryCache {
|
|
|
262
348
|
}
|
|
263
349
|
logger.info(`[OwnerDirectoryCache] Processing pending for ${this.options.ownerAid}, op=${pending.operationId}, attempt=${this.pullFailures + 1}`);
|
|
264
350
|
try {
|
|
265
|
-
await this.fetchToSharedCache(pending.digests);
|
|
351
|
+
const fetched = await this.fetchToSharedCache(pending.digests);
|
|
352
|
+
if (this.options.relationVersion !== undefined)
|
|
353
|
+
await this._applyAll(fetched);
|
|
266
354
|
this.clearPullFailures();
|
|
267
355
|
this.clearPendingUnlessSuperseded(pending);
|
|
268
356
|
}
|
|
@@ -330,7 +418,7 @@ export class OwnerDirectoryCache {
|
|
|
330
418
|
*/
|
|
331
419
|
async fetchToSharedCache(digests) {
|
|
332
420
|
// ① 检查共享缓存:通知 digest 与共享缓存一致时,跳过网络请求
|
|
333
|
-
const sharedFresh = OWNER_DIRECTORY_SCOPES.every(scope => {
|
|
421
|
+
const sharedFresh = this.options.relationVersion === undefined && OWNER_DIRECTORY_SCOPES.every(scope => {
|
|
334
422
|
const hintDigest = digests?.[scope];
|
|
335
423
|
if (!hintDigest)
|
|
336
424
|
return false; // 无 hint(startup),需要拉
|
|
@@ -342,19 +430,22 @@ export class OwnerDirectoryCache {
|
|
|
342
430
|
return this._assertComplete(this._readSharedCache());
|
|
343
431
|
}
|
|
344
432
|
// ② 模块级单飞:同进程只发一次网络请求
|
|
345
|
-
const
|
|
433
|
+
const flightKey = this.options.relationVersion === undefined ? this.options.ownerAid
|
|
434
|
+
: `${this.options.ownerAid}:${this.options.selfAid}:${this.options.relationVersion}`;
|
|
435
|
+
const existing = _fetchInFlight.get(flightKey);
|
|
346
436
|
const outcome = existing
|
|
347
437
|
? await existing
|
|
348
438
|
: await (() => {
|
|
349
439
|
const fetchPromise = this._doFetch().then(result => {
|
|
350
|
-
this.
|
|
440
|
+
if (this.options.relationVersion === undefined && (!this.options.isCurrent || this.options.isCurrent()))
|
|
441
|
+
this._writeSharedCache(result.data);
|
|
351
442
|
return result;
|
|
352
443
|
}).finally(() => {
|
|
353
|
-
if (_fetchInFlight.get(
|
|
354
|
-
_fetchInFlight.delete(
|
|
444
|
+
if (_fetchInFlight.get(flightKey) === fetchPromise) {
|
|
445
|
+
_fetchInFlight.delete(flightKey);
|
|
355
446
|
}
|
|
356
447
|
});
|
|
357
|
-
_fetchInFlight.set(
|
|
448
|
+
_fetchInFlight.set(flightKey, fetchPromise);
|
|
358
449
|
return fetchPromise;
|
|
359
450
|
})();
|
|
360
451
|
// 远端明确拒绝:作废本地快照并标记 blocked,重试没有意义。逐个 scope 处理,
|
|
@@ -363,7 +454,8 @@ export class OwnerDirectoryCache {
|
|
|
363
454
|
if (this.scopeAccess(scope) === 'authorized')
|
|
364
455
|
await this.blockScope(scope);
|
|
365
456
|
}
|
|
366
|
-
|
|
457
|
+
const complete = this._assertComplete(outcome.data, outcome.failures);
|
|
458
|
+
return complete;
|
|
367
459
|
}
|
|
368
460
|
/**
|
|
369
461
|
* 已授权范围一个都没拿到,就不算拉取成功。
|
|
@@ -403,6 +495,9 @@ export class OwnerDirectoryCache {
|
|
|
403
495
|
return promise;
|
|
404
496
|
}
|
|
405
497
|
async _applyFromSharedCacheOnce() {
|
|
498
|
+
// Never relabel an older relationship's shared bytes as a newly verified snapshot.
|
|
499
|
+
if (this.options.relationVersion !== undefined)
|
|
500
|
+
return false;
|
|
406
501
|
// 热路径早退:每条入站消息都会调到这里,而绝大多数消息发生时名录早就落过盘。
|
|
407
502
|
// 先只比 content_digest,命中就连 JSON 都不解析——`_readSharedCache` 会做
|
|
408
503
|
// 逐条校验 + 全量摘要重算,那是拉取期才需要的成本。
|
|
@@ -470,7 +565,10 @@ export class OwnerDirectoryCache {
|
|
|
470
565
|
* 需求路径(`lookupByAid`、准入)用这个:用户正等着结果,不能只拉不落。
|
|
471
566
|
*/
|
|
472
567
|
async pullAndApply(digests) {
|
|
568
|
+
const generation = ++this.fetchGeneration;
|
|
473
569
|
const fetched = await this.fetchToSharedCache(digests);
|
|
570
|
+
if (generation !== this.fetchGeneration)
|
|
571
|
+
return;
|
|
474
572
|
await this._applyAll(fetched);
|
|
475
573
|
}
|
|
476
574
|
/**
|
|
@@ -479,14 +577,19 @@ export class OwnerDirectoryCache {
|
|
|
479
577
|
* 完整性由阶段一保证(`_assertComplete`);这里只跳过"拉取之后权限被撤"的范围。
|
|
480
578
|
*/
|
|
481
579
|
async _applyAll(fetched) {
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
580
|
+
const apply = async () => {
|
|
581
|
+
for (const scope of OWNER_DIRECTORY_SCOPES) {
|
|
582
|
+
if (this.scopeAccess(scope) !== 'authorized')
|
|
583
|
+
continue;
|
|
584
|
+
const file = fetched[scope];
|
|
585
|
+
if (!file)
|
|
586
|
+
continue;
|
|
587
|
+
await this._applyFile(scope, file);
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
const next = this.applyTail.then(apply);
|
|
591
|
+
this.applyTail = next.catch(() => { });
|
|
592
|
+
await next;
|
|
490
593
|
}
|
|
491
594
|
// ── 共享缓存($EVOLCORE_HOME/data/owner-directory/<ownerAid>/) ────────────
|
|
492
595
|
_sharedCacheDir() {
|
|
@@ -669,7 +772,8 @@ export class OwnerDirectoryCache {
|
|
|
669
772
|
const code = normalized instanceof OwnerDirectoryCacheError ? normalized.code : 'FETCH_ERROR';
|
|
670
773
|
failures[scope] = `${code}: ${errorText(normalized)}`;
|
|
671
774
|
logger.warn(`[OwnerDirectoryCache] Fetch failed for ${scope}: ${errorText(normalized)} (raw kept for diagnosis)`);
|
|
672
|
-
this.
|
|
775
|
+
if (this.canMutate())
|
|
776
|
+
this.options.onError?.(scope, normalized);
|
|
673
777
|
this._appendFetchFailure(scope, code, errorText(normalized));
|
|
674
778
|
// 远端拒绝随结果返回,由调用方作废自己的本地快照;其它错误保持 pending,
|
|
675
779
|
// 交给时间退避重试。拒绝信息必须在返回值里走——单飞复用者也要看得到。
|
|
@@ -765,6 +869,7 @@ export class OwnerDirectoryCache {
|
|
|
765
869
|
for (const entry of entries) {
|
|
766
870
|
if (!isRecord(entry))
|
|
767
871
|
throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has a non-object entry`);
|
|
872
|
+
normalizeEntry(entry); // Validate known optional admission fields before caching the raw object.
|
|
768
873
|
if (typeof entry.aid !== 'string' || !entry.aid || !isValidAid(entry.aid)) {
|
|
769
874
|
throw new OwnerDirectoryCacheError('INVALID_ENTRY', `${scope}.json has an entry with invalid aid`);
|
|
770
875
|
}
|
|
@@ -900,6 +1005,8 @@ export class OwnerDirectoryCache {
|
|
|
900
1005
|
}
|
|
901
1006
|
// ── Internal: applyFile ──────────────────────────────────────────────────────
|
|
902
1007
|
async _applyFile(scope, file) {
|
|
1008
|
+
if (!this.canMutate())
|
|
1009
|
+
return;
|
|
903
1010
|
const prev = this.readCachedSnapshot(scope);
|
|
904
1011
|
const localDigest = prev?.contentDigest;
|
|
905
1012
|
if (file.contentDigest && localDigest && file.contentDigest === localDigest) {
|
|
@@ -911,12 +1018,18 @@ export class OwnerDirectoryCache {
|
|
|
911
1018
|
}
|
|
912
1019
|
const attemptedAt = this.now();
|
|
913
1020
|
await this.updateFileState(scope, { lastAttemptAt: attemptedAt, status: 'syncing', error: undefined });
|
|
1021
|
+
if (!this.canMutate())
|
|
1022
|
+
return;
|
|
914
1023
|
try {
|
|
915
1024
|
const entries = file.entries.map(e => normalizeEntry(e));
|
|
916
1025
|
const aids = new Set(entries.map(e => e.aid));
|
|
917
1026
|
if (aids.size !== entries.length)
|
|
918
1027
|
throw new OwnerDirectoryCacheError('DUPLICATE_AID', `${scope} has duplicate AIDs`);
|
|
919
1028
|
const snapshot = {
|
|
1029
|
+
sourceRevision: file.raw.source_revision,
|
|
1030
|
+
...(this.options.relationVersion !== undefined ? { relationVersion: this.options.relationVersion } : {}),
|
|
1031
|
+
blockedAids: file.blockedAids.filter(value => isRecord(value) && value.target_type === 'aid')
|
|
1032
|
+
.map(value => value.target_id),
|
|
920
1033
|
ownerAid: this.options.ownerAid,
|
|
921
1034
|
granteeAid: this.options.selfAid,
|
|
922
1035
|
scope,
|
|
@@ -929,7 +1042,18 @@ export class OwnerDirectoryCache {
|
|
|
929
1042
|
...(file.owner ? { owner: file.owner } : {}),
|
|
930
1043
|
...(file.personalAssistant ? { personalAssistant: file.personalAssistant } : {}),
|
|
931
1044
|
};
|
|
932
|
-
|
|
1045
|
+
this.options.onSnapshotApplying?.(snapshot);
|
|
1046
|
+
if (!this.canMutate())
|
|
1047
|
+
return;
|
|
1048
|
+
archiveSnapshot(path.dirname(this.cachePath(scope)), scope);
|
|
1049
|
+
const prevMeta = prev ? { owner: prev.owner, personalAssistant: prev.personalAssistant } : undefined;
|
|
1050
|
+
const nextMeta = { owner: snapshot.owner, personalAssistant: snapshot.personalAssistant };
|
|
1051
|
+
const changes = diffSnapshots(scope, snapshot, prev, nextMeta, prevMeta);
|
|
1052
|
+
// 变更日志必须先于快照落盘:快照一覆盖,`prev` 就没了,日志里缺的那批
|
|
1053
|
+
// 永远补不回来。appendChanges 失败会抛,走下面的 catch → status=error,
|
|
1054
|
+
// 下次同步重试;重试时同一批变更会重新生成,appendChanges 自己按
|
|
1055
|
+
// contentDigest 去重,不会重复追加。
|
|
1056
|
+
appendChanges(this.options.directory, changes);
|
|
933
1057
|
const stored = { schemaVersion: 2, ...snapshot };
|
|
934
1058
|
fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
|
|
935
1059
|
atomicWriteJson(this.cachePath(scope), stored);
|
|
@@ -939,10 +1063,6 @@ export class OwnerDirectoryCache {
|
|
|
939
1063
|
// 一起删,否则 atomicRead 会把 `agents.json_` 当成中断的 rename 恢复回来。
|
|
940
1064
|
atomicRemove(path.join(this.options.directory, 'agents.json'));
|
|
941
1065
|
logger.info(`[OwnerDirectoryCache] Applied ${scope}: total=${snapshot.total}`);
|
|
942
|
-
const prevMeta = prev ? { owner: prev.owner, personalAssistant: prev.personalAssistant } : undefined;
|
|
943
|
-
const nextMeta = { owner: snapshot.owner, personalAssistant: snapshot.personalAssistant };
|
|
944
|
-
const changes = diffSnapshots(scope, snapshot, prev, nextMeta, prevMeta);
|
|
945
|
-
appendChanges(this.options.directory, changes);
|
|
946
1066
|
await this.updateFileState(scope, {
|
|
947
1067
|
lastAttemptAt: attemptedAt,
|
|
948
1068
|
lastSuccessAt: snapshot.fetchedAt,
|
|
@@ -952,6 +1072,8 @@ export class OwnerDirectoryCache {
|
|
|
952
1072
|
});
|
|
953
1073
|
this.refreshMarkdown();
|
|
954
1074
|
try {
|
|
1075
|
+
if (!this.canMutate())
|
|
1076
|
+
return;
|
|
955
1077
|
if (this.options.onSnapshotChanged && changes.length > 0) {
|
|
956
1078
|
const agentMdAids = collectAgentMdRefreshAids(changes, nextMeta, prevMeta, snapshot);
|
|
957
1079
|
if (agentMdAids.length > 0)
|
|
@@ -970,7 +1092,8 @@ export class OwnerDirectoryCache {
|
|
|
970
1092
|
else {
|
|
971
1093
|
await this.updateFileState(scope, { lastAttemptAt: attemptedAt, status: 'error', error: errorText(error) });
|
|
972
1094
|
}
|
|
973
|
-
this.
|
|
1095
|
+
if (this.canMutate())
|
|
1096
|
+
this.options.onError?.(scope, error);
|
|
974
1097
|
throw error;
|
|
975
1098
|
}
|
|
976
1099
|
}
|
|
@@ -982,12 +1105,13 @@ export class OwnerDirectoryCache {
|
|
|
982
1105
|
const cached = this.snapshotCache.get(scope);
|
|
983
1106
|
if (cached !== undefined && cached.stamp === stamp)
|
|
984
1107
|
return cached.snapshot ?? undefined;
|
|
985
|
-
const raw = stamp ?
|
|
1108
|
+
const raw = stamp ? this.readLocalJson(this.cachePath(scope)) : undefined;
|
|
986
1109
|
const store = (snapshot) => {
|
|
987
1110
|
this.snapshotCache.set(scope, { snapshot, stamp });
|
|
988
1111
|
return snapshot ?? undefined;
|
|
989
1112
|
};
|
|
990
1113
|
if (!isRecord(raw) || raw.schemaVersion !== 2 || raw.ownerAid !== this.options.ownerAid
|
|
1114
|
+
|| (this.options.relationVersion !== undefined && typeof raw.relationVersion === 'number' && raw.relationVersion !== this.options.relationVersion)
|
|
991
1115
|
|| raw.granteeAid !== this.options.selfAid || raw.scope !== scope
|
|
992
1116
|
|| !Array.isArray(raw.entries) || raw.entries.length !== raw.total) {
|
|
993
1117
|
return store(null);
|
|
@@ -998,6 +1122,9 @@ export class OwnerDirectoryCache {
|
|
|
998
1122
|
if (aids.size !== entries.length || entries.length > MAX_DIRECTORY_ENTRIES)
|
|
999
1123
|
return store(null);
|
|
1000
1124
|
return store({
|
|
1125
|
+
...(typeof raw.sourceRevision === 'string' ? { sourceRevision: raw.sourceRevision } : {}),
|
|
1126
|
+
...(Number.isSafeInteger(raw.relationVersion) ? { relationVersion: raw.relationVersion } : {}),
|
|
1127
|
+
blockedAids: parseBlockedAids(raw.blockedAids ?? []),
|
|
1001
1128
|
ownerAid: this.options.ownerAid,
|
|
1002
1129
|
granteeAid: this.options.selfAid,
|
|
1003
1130
|
scope,
|
|
@@ -1034,6 +1161,8 @@ export class OwnerDirectoryCache {
|
|
|
1034
1161
|
}
|
|
1035
1162
|
// ── Internal: authorization / sync state / paths ────────────────────────────
|
|
1036
1163
|
async blockScope(scope) {
|
|
1164
|
+
if (!this.canMutate())
|
|
1165
|
+
return;
|
|
1037
1166
|
atomicRemove(this.cachePath(scope));
|
|
1038
1167
|
this.snapshotCache.delete(scope);
|
|
1039
1168
|
await this.updateSyncState(state => ({
|
|
@@ -1051,7 +1180,10 @@ export class OwnerDirectoryCache {
|
|
|
1051
1180
|
}
|
|
1052
1181
|
async updateSyncState(transform) {
|
|
1053
1182
|
const run = this.stateWriteTail.then(() => {
|
|
1183
|
+
if (!this.canMutate())
|
|
1184
|
+
return;
|
|
1054
1185
|
const state = transform(this.readSyncState());
|
|
1186
|
+
state.relationVersion = this.options.relationVersion;
|
|
1055
1187
|
fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
|
|
1056
1188
|
atomicWriteJson(this.syncStatePath(), state);
|
|
1057
1189
|
fs.chmodSync(this.syncStatePath(), 0o600);
|
|
@@ -1060,9 +1192,10 @@ export class OwnerDirectoryCache {
|
|
|
1060
1192
|
await run;
|
|
1061
1193
|
}
|
|
1062
1194
|
readSyncState() {
|
|
1063
|
-
const raw =
|
|
1195
|
+
const raw = this.readLocalJson(this.syncStatePath());
|
|
1064
1196
|
if (!isRecord(raw) || raw.schemaVersion !== 1 || raw.ownerAid !== this.options.ownerAid
|
|
1065
|
-
|| raw.granteeAid !== this.options.selfAid || !isRecord(raw.files)
|
|
1197
|
+
|| raw.granteeAid !== this.options.selfAid || !isRecord(raw.files)
|
|
1198
|
+
|| (this.options.relationVersion !== undefined && typeof raw.relationVersion === 'number' && raw.relationVersion !== this.options.relationVersion)) {
|
|
1066
1199
|
return { schemaVersion: 1, ownerAid: this.options.ownerAid, granteeAid: this.options.selfAid, files: {}, blockedScopes: [] };
|
|
1067
1200
|
}
|
|
1068
1201
|
return {
|
|
@@ -1080,11 +1213,13 @@ export class OwnerDirectoryCache {
|
|
|
1080
1213
|
* contacts 的那一份。
|
|
1081
1214
|
*/
|
|
1082
1215
|
loadGrant() {
|
|
1083
|
-
const raw =
|
|
1216
|
+
const raw = this.readLocalJson(this.authorizationPath());
|
|
1084
1217
|
if (!isRecord(raw))
|
|
1085
1218
|
return undefined;
|
|
1086
1219
|
if (raw.ownerAid !== this.options.ownerAid || raw.granteeAid !== this.options.selfAid)
|
|
1087
1220
|
return undefined;
|
|
1221
|
+
if (this.options.relationVersion !== undefined && typeof raw.relationVersion === 'number' && raw.relationVersion !== this.options.relationVersion)
|
|
1222
|
+
return undefined;
|
|
1088
1223
|
if (raw.schemaVersion === 2) {
|
|
1089
1224
|
if (!Number.isSafeInteger(raw.grantedAt) || !Number.isSafeInteger(raw.expiresAt))
|
|
1090
1225
|
return undefined;
|
|
@@ -1133,15 +1268,18 @@ export class OwnerDirectoryCache {
|
|
|
1133
1268
|
* 授权真的不存在或快照文件真的不在盘上。其余情形保留现有内容不动。
|
|
1134
1269
|
*/
|
|
1135
1270
|
refreshMarkdown() {
|
|
1271
|
+
if (!this.canMutate())
|
|
1272
|
+
return;
|
|
1136
1273
|
const target = path.join(this.options.directory, OWNER_DIRECTORY_MARKDOWN_FILE);
|
|
1137
1274
|
try {
|
|
1138
1275
|
const snapshot = this.readCachedSnapshot('contacts');
|
|
1276
|
+
// 开关每次现读:`ec connect access set` 改完就调一个 refresh,不必让调用方再传一份。
|
|
1139
1277
|
const markdown = renderOwnerDirectoryMarkdown({
|
|
1140
1278
|
ownerAid: this.options.ownerAid,
|
|
1141
1279
|
selfAid: this.options.selfAid,
|
|
1142
1280
|
snapshot,
|
|
1143
1281
|
remarks: this.remarksSnapshot(),
|
|
1144
|
-
|
|
1282
|
+
policy: resolveOwnerDirectoryRenderPolicy(this.options.selfAid, snapshot),
|
|
1145
1283
|
});
|
|
1146
1284
|
if (!markdown) {
|
|
1147
1285
|
if (!this.directoryGone()) {
|
|
@@ -1149,22 +1287,49 @@ export class OwnerDirectoryCache {
|
|
|
1149
1287
|
return;
|
|
1150
1288
|
}
|
|
1151
1289
|
// 确证不可用时连同热备名一起删,避免 atomicRead 把中断的 rename 恢复回来。
|
|
1290
|
+
// identity.json 必须一起删:它是 PA / Owner 身份的唯一来源,留着等于让
|
|
1291
|
+
// 一个已作废的名录继续决定注入哪一段。
|
|
1152
1292
|
atomicRemove(target);
|
|
1293
|
+
atomicRemove(path.join(this.options.directory, OWNER_DIRECTORY_IDENTITY_FILE));
|
|
1153
1294
|
return;
|
|
1154
1295
|
}
|
|
1155
1296
|
fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
|
|
1156
1297
|
// 内容不变就不写盘:ECK 的注入按文件指纹走,无谓的写入会触发无谓的重新加载。
|
|
1298
|
+
let written = false;
|
|
1157
1299
|
try {
|
|
1158
|
-
|
|
1159
|
-
return;
|
|
1300
|
+
written = atomicRead(target) === markdown;
|
|
1160
1301
|
}
|
|
1161
1302
|
catch { /* 读不出来就照写 */ }
|
|
1162
|
-
|
|
1303
|
+
if (!written)
|
|
1304
|
+
atomicWriteText(target, markdown);
|
|
1305
|
+
// 身份文件跟着渲染产物走:名录换了、PA 换了、开关换了,都会经过这里。
|
|
1306
|
+
this.writeIdentity(snapshot);
|
|
1163
1307
|
}
|
|
1164
1308
|
catch (error) {
|
|
1165
1309
|
logger.warn(`[OwnerDirectoryCache] refreshMarkdown failed: ${errorText(error)}`);
|
|
1166
1310
|
}
|
|
1167
1311
|
}
|
|
1312
|
+
/**
|
|
1313
|
+
* 写 `directory/identity.json`:只存 Owner 与个人助理的身份字段。
|
|
1314
|
+
*
|
|
1315
|
+
* ECK 变量 `ownerAid` / `ownerName` / `personalAssistantAid` / `personalAssistantName`
|
|
1316
|
+
* 每轮都读它,所以字段必须窄——这里不存快照、不存条目、不存任何开关布尔。
|
|
1317
|
+
* `isPersonalAssistant` / `isOwner` 由调用方用 `selfAid` 即时比较,不落盘:
|
|
1318
|
+
* 落盘的布尔会过期,而且可以被手改文件伪造角色。
|
|
1319
|
+
*
|
|
1320
|
+
* 内容不变就不写盘,与 `directory.md` 同理。
|
|
1321
|
+
*/
|
|
1322
|
+
writeIdentity(snapshot) {
|
|
1323
|
+
const target = path.join(this.options.directory, OWNER_DIRECTORY_IDENTITY_FILE);
|
|
1324
|
+
const payload = buildOwnerDirectoryIdentity(snapshot);
|
|
1325
|
+
const text = `${JSON.stringify(payload, null, 2)}\n`;
|
|
1326
|
+
try {
|
|
1327
|
+
if (atomicRead(target) === text)
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
catch { /* 不存在或读不出,照写 */ }
|
|
1331
|
+
atomicWriteText(target, text);
|
|
1332
|
+
}
|
|
1168
1333
|
/**
|
|
1169
1334
|
* 名录是否**确证**已不可用。
|
|
1170
1335
|
*
|
|
@@ -1201,7 +1366,12 @@ export class OwnerDirectoryCache {
|
|
|
1201
1366
|
authorizationPath() { return path.join(this.options.directory, 'authorization.json'); }
|
|
1202
1367
|
syncStatePath() { return path.join(this.options.directory, 'sync-state.json'); }
|
|
1203
1368
|
pendingPath() { return path.join(this.options.directory, 'pending.json'); }
|
|
1204
|
-
cachePath(scope) {
|
|
1369
|
+
cachePath(scope) {
|
|
1370
|
+
// 快照只有一份,app-v1 与 legacy 共用同一路径。准入依据放在 daemon 管理的
|
|
1371
|
+
// data/contact-admission/ 下会让 App 侧写入、人工排查、目录命令各看一份副本;
|
|
1372
|
+
// 版本安全性由 relationVersion 校验负责,不靠换目录。
|
|
1373
|
+
return path.join(this.options.directory, `${scope}.json`);
|
|
1374
|
+
}
|
|
1205
1375
|
}
|
|
1206
1376
|
// ── Module-level helpers ─────────────────────────────────────────────────────
|
|
1207
1377
|
/**
|
|
@@ -1228,11 +1398,24 @@ function parseIdentityField(value) {
|
|
|
1228
1398
|
};
|
|
1229
1399
|
}
|
|
1230
1400
|
/**
|
|
1231
|
-
*
|
|
1232
|
-
*
|
|
1401
|
+
* 把远端条目收敛成唯一的内部形状。
|
|
1402
|
+
*
|
|
1403
|
+
* 这是条目形态的唯一收敛点:apply 路径(远端文件)和 readCachedSnapshot(本地
|
|
1404
|
+
* 快照)都从这里出,所以下游看到的永远是同一种形状。
|
|
1405
|
+
*
|
|
1406
|
+
* 规则:
|
|
1407
|
+
* - 未知字段收进 `extra` 原样保留,不丢弃:远端新增字段时,本端旧版本仍要能
|
|
1408
|
+
* 在本地快照里看到它、在变更日志里记录它。丢弃只发生在本地快照这一层——
|
|
1409
|
+
* 共享缓存是远端原始字节,不受此影响,但准入和排查读的都是本地快照。
|
|
1410
|
+
* - `remark` / `type` / `exttype` / `description` / `baseagent` / `ownership_status`
|
|
1411
|
+
* **恒存在**,非字符串一律写成 `''`。远端有时发 `exttype: ""`、有时整个键不写,
|
|
1412
|
+
* 这两种在业务上是同一件事;若让它们分别变成 `''` 和 `undefined`,比较会判"变了",
|
|
1413
|
+
* 上游换一种序列化就把整份名录刷成变更。收敛到 `''` 后这类噪音消失。
|
|
1414
|
+
* - `ownerAid` 保持可选:它承载内外判据,缺失是真实状态(未归属),不能补空串。
|
|
1415
|
+
* - 数值字段只在是安全整数时保留;`null` / 缺失都落到"没有"。
|
|
1233
1416
|
*
|
|
1234
1417
|
* 注意:`content_digest` 必须在**原始**条目上计算,不能拿这里的输出回算——
|
|
1235
|
-
*
|
|
1418
|
+
* 归一化会丢未知字段、补默认值、截断长字段。
|
|
1236
1419
|
*/
|
|
1237
1420
|
function normalizeEntry(value) {
|
|
1238
1421
|
if (!isRecord(value) || typeof value.aid !== 'string' || !isValidAid(value.aid)) {
|
|
@@ -1242,16 +1425,32 @@ function normalizeEntry(value) {
|
|
|
1242
1425
|
aid: value.aid,
|
|
1243
1426
|
name: typeof value.name === 'string' ? value.name : value.aid,
|
|
1244
1427
|
};
|
|
1428
|
+
if (value.agent_scope !== undefined) {
|
|
1429
|
+
const scope = value.agent_scope;
|
|
1430
|
+
if (!isRecord(scope) || (scope.mode !== 'all' && scope.mode !== 'selected')) {
|
|
1431
|
+
throw new OwnerDirectoryCacheError('INVALID_ENTRY', 'invalid agent_scope');
|
|
1432
|
+
}
|
|
1433
|
+
if (scope.mode === 'all')
|
|
1434
|
+
entry.agent_scope = { mode: 'all' };
|
|
1435
|
+
else {
|
|
1436
|
+
if (!Array.isArray(scope.agent_aids) || scope.agent_aids.length === 0
|
|
1437
|
+
|| scope.agent_aids.some(aid => typeof aid !== 'string' || !isValidAid(aid))
|
|
1438
|
+
|| new Set(scope.agent_aids).size !== scope.agent_aids.length) {
|
|
1439
|
+
throw new OwnerDirectoryCacheError('INVALID_ENTRY', 'invalid selected agent_scope');
|
|
1440
|
+
}
|
|
1441
|
+
entry.agent_scope = { mode: 'selected', agent_aids: [...scope.agent_aids] };
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1245
1444
|
// 本地缓存用 camelCase 存,远端文档用 snake_case;两种都认,否则读回本地快照会丢字段。
|
|
1246
1445
|
if (typeof value.owner_aid === 'string' && value.owner_aid.trim())
|
|
1247
1446
|
entry.ownerAid = value.owner_aid.trim();
|
|
1248
1447
|
else if (typeof value.ownerAid === 'string' && value.ownerAid.trim())
|
|
1249
1448
|
entry.ownerAid = value.ownerAid.trim();
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1449
|
+
// 恒存在的字符串字段:缺失 ≡ 空串。
|
|
1450
|
+
const textFields = ['remark', 'type', 'exttype', 'description', 'baseagent', 'ownership_status'];
|
|
1451
|
+
for (const key of textFields) {
|
|
1452
|
+
const raw = value[key];
|
|
1453
|
+
entry[key] = typeof raw === 'string' ? truncateCodePoints(raw, 128) : '';
|
|
1255
1454
|
}
|
|
1256
1455
|
if (Number.isSafeInteger(value.ownership_checked_at_ms)) {
|
|
1257
1456
|
entry.ownership_checked_at_ms = value.ownership_checked_at_ms;
|
|
@@ -1259,8 +1458,123 @@ function normalizeEntry(value) {
|
|
|
1259
1458
|
if (Number.isSafeInteger(value.agent_md_signed_at)) {
|
|
1260
1459
|
entry.agent_md_signed_at = value.agent_md_signed_at;
|
|
1261
1460
|
}
|
|
1461
|
+
// 读回本地快照时未知字段已经在 `extra` 里;远端原文里没有这个键。两条路径都要出同一种形状。
|
|
1462
|
+
const carried = isRecord(value.extra) ? sanitizeExtra(value.extra) : undefined;
|
|
1463
|
+
const fresh = collectUnknownFields(value);
|
|
1464
|
+
const extra = carried || fresh ? { ...(carried ?? {}), ...(fresh ?? {}) } : undefined;
|
|
1465
|
+
if (extra)
|
|
1466
|
+
entry.extra = extra;
|
|
1262
1467
|
return entry;
|
|
1263
1468
|
}
|
|
1469
|
+
function parseBlockedAids(value) {
|
|
1470
|
+
if (!Array.isArray(value) || value.some(aid => typeof aid !== 'string' || !isValidAid(aid))) {
|
|
1471
|
+
throw new OwnerDirectoryCacheError('INVALID_ENTRY', 'invalid blocked aids');
|
|
1472
|
+
}
|
|
1473
|
+
return [...value];
|
|
1474
|
+
}
|
|
1475
|
+
/** 已有 `extra` 读回来时限一遍大小,防止被本实例以外的途径写大的本地文件撑爆内存。 */
|
|
1476
|
+
function sanitizeExtra(value) {
|
|
1477
|
+
let bytes = 0;
|
|
1478
|
+
const kept = {};
|
|
1479
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
1480
|
+
if (KNOWN_ENTRY_FIELDS.has(key))
|
|
1481
|
+
continue;
|
|
1482
|
+
let serialized;
|
|
1483
|
+
try {
|
|
1484
|
+
serialized = JSON.stringify(raw);
|
|
1485
|
+
}
|
|
1486
|
+
catch {
|
|
1487
|
+
continue;
|
|
1488
|
+
}
|
|
1489
|
+
if (serialized === undefined)
|
|
1490
|
+
continue;
|
|
1491
|
+
const size = Buffer.byteLength(key, 'utf8') + Buffer.byteLength(serialized, 'utf8');
|
|
1492
|
+
if (size > UNKNOWN_FIELD_MAX_BYTES || bytes + size > UNKNOWN_FIELDS_MAX_BYTES)
|
|
1493
|
+
continue;
|
|
1494
|
+
bytes += size;
|
|
1495
|
+
kept[key] = raw;
|
|
1496
|
+
}
|
|
1497
|
+
return Object.keys(kept).length > 0 ? kept : undefined;
|
|
1498
|
+
}
|
|
1499
|
+
/** 本版本认识的条目字段(两种拼写都算),其余进 `extra`。 */
|
|
1500
|
+
const KNOWN_ENTRY_FIELDS = new Set([
|
|
1501
|
+
'aid', 'name', 'owner_aid', 'ownerAid', 'remark', 'type', 'exttype', 'description',
|
|
1502
|
+
'baseagent', 'ownership_status', 'ownership_checked_at_ms', 'agent_md_signed_at',
|
|
1503
|
+
'agent_scope',
|
|
1504
|
+
// `extra` 是本地快照自己的形状;读回时不能把它当成又一层未知字段。
|
|
1505
|
+
'extra',
|
|
1506
|
+
]);
|
|
1507
|
+
/**
|
|
1508
|
+
* 单条目未知字段的总字节上限。
|
|
1509
|
+
*
|
|
1510
|
+
* 目录对象整体受 `OWNER_DIRECTORY_MAX_OBJECT_BYTES`(128 KiB)约束,但那条是
|
|
1511
|
+
* 拉取前的预算;这里防的是"本地快照比远端还大"。远端以后若往条目里塞大字段,
|
|
1512
|
+
* 超出部分按字段粒度丢弃,并记一条 WARN——丢的是新字段,不能悄悄丢。
|
|
1513
|
+
*/
|
|
1514
|
+
const UNKNOWN_FIELDS_MAX_BYTES = 4 * 1024;
|
|
1515
|
+
/** 单个未知字段的字节上限;超出整条丢弃(截断 JSON 值没有意义)。 */
|
|
1516
|
+
const UNKNOWN_FIELD_MAX_BYTES = 1 * 1024;
|
|
1517
|
+
/**
|
|
1518
|
+
* 收集本版本不认识的条目字段。
|
|
1519
|
+
*
|
|
1520
|
+
* 值原样保留(已经过 `JSON.parse`,一定是可序列化的 JSON 值),不递归改形。
|
|
1521
|
+
* 顺序按出现顺序落盘,但比较时由调用方规范化——字段顺序不同不算变化。
|
|
1522
|
+
*/
|
|
1523
|
+
function collectUnknownFields(value) {
|
|
1524
|
+
let extra;
|
|
1525
|
+
let bytes = 0;
|
|
1526
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
1527
|
+
if (KNOWN_ENTRY_FIELDS.has(key))
|
|
1528
|
+
continue;
|
|
1529
|
+
let serialized;
|
|
1530
|
+
try {
|
|
1531
|
+
serialized = JSON.stringify(raw);
|
|
1532
|
+
}
|
|
1533
|
+
catch {
|
|
1534
|
+
// 循环引用的对象不可能来自 JSON.parse,走到这里说明调用方传了非常规值。
|
|
1535
|
+
logger.warn(`[OwnerDirectoryCache] entry field ${key} is not JSON-serializable, dropped`);
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
if (serialized === undefined)
|
|
1539
|
+
continue;
|
|
1540
|
+
const size = Buffer.byteLength(key, 'utf8') + Buffer.byteLength(serialized, 'utf8');
|
|
1541
|
+
if (size > UNKNOWN_FIELD_MAX_BYTES) {
|
|
1542
|
+
logger.warn(`[OwnerDirectoryCache] entry field ${key} exceeds ${UNKNOWN_FIELD_MAX_BYTES}B, dropped`);
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
if (bytes + size > UNKNOWN_FIELDS_MAX_BYTES) {
|
|
1546
|
+
logger.warn(`[OwnerDirectoryCache] entry unknown fields exceed ${UNKNOWN_FIELDS_MAX_BYTES}B, ${key} and later dropped`);
|
|
1547
|
+
break;
|
|
1548
|
+
}
|
|
1549
|
+
bytes += size;
|
|
1550
|
+
extra ??= {};
|
|
1551
|
+
extra[key] = raw;
|
|
1552
|
+
}
|
|
1553
|
+
return extra;
|
|
1554
|
+
}
|
|
1555
|
+
/**
|
|
1556
|
+
* `extra` 的规范化序列化,用于"算不算变了"的比较。
|
|
1557
|
+
*
|
|
1558
|
+
* 放在这里而不是 store,是因为 store 已经 import 本模块;反向取值会形成运行时
|
|
1559
|
+
* 循环依赖,而这条路径在每条消息的准入上都会走到。
|
|
1560
|
+
*
|
|
1561
|
+
* `JSON.stringify` 依赖插入顺序,同一份远端数据换个字段顺序就会被判成变更;
|
|
1562
|
+
* 这里按键名排序后再序列化。值为 `undefined` 的键不会产生序列化输出,与缺失等价。
|
|
1563
|
+
*/
|
|
1564
|
+
export function extraFingerprint(value) {
|
|
1565
|
+
if (!value)
|
|
1566
|
+
return '';
|
|
1567
|
+
const keys = Object.keys(value).sort();
|
|
1568
|
+
if (keys.length === 0)
|
|
1569
|
+
return '';
|
|
1570
|
+
return JSON.stringify(keys.map(key => [key, value[key] ?? null]));
|
|
1571
|
+
}
|
|
1572
|
+
/** 按码位截断,避免把代理对劈成半个字符。 */
|
|
1573
|
+
function truncateCodePoints(text, max) {
|
|
1574
|
+
if (text.length <= max)
|
|
1575
|
+
return text;
|
|
1576
|
+
return Array.from(text).slice(0, max).join('');
|
|
1577
|
+
}
|
|
1264
1578
|
function isPermissionDenied(error) {
|
|
1265
1579
|
return error instanceof OwnerDirectoryCacheError
|
|
1266
1580
|
&& ['PERMISSION_DENIED', 'ACCESS_DENIED', 'FORBIDDEN'].includes(error.code);
|