evolcore 0.0.41-test.0 → 0.0.41-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.
Files changed (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -14,31 +14,58 @@ import fs from 'fs';
14
14
  import path from 'path';
15
15
  import { ensureManagedLockParent, resolveManagedLockPath } from '../core/runtime-lock.js';
16
16
  import crypto from 'crypto';
17
- import { resolvePaths, agentConfig as agentConfigPath, agentContactConfig, agentRelationConfig, agentDir, agentRelationsDir, agentRolesIndex, agentRoleConfig, } from '../paths.js';
17
+ import { resolvePaths, agentConfig as agentConfigPath, agentContactConfig, agentRelationConfig, agentRolesIndex, agentRoleConfig, } from '../paths.js';
18
18
  import { atomicReadJson, atomicWriteJson } from '../utils/atomic-write.js';
19
19
  import { fileCache } from '../core/daemon-file-cache.js';
20
20
  import { registerFile } from '../core/file-integrity/store.js';
21
21
  import { isValidAid } from '../aun/aid/validation.js';
22
22
  import { normalizeAidDomain } from '../aun/aid/domain.js';
23
- import { isExplicitGroupId } from '../aun/group/index.js';
24
23
  import { ensureRelationSharedDirectory } from '../core/relation/shared-data.js';
25
24
  import { parseContactAlias } from './contact-alias.js';
26
25
  import { loadSchema, listSchemaVersions, currentVersion, isSchemaName, } from './schema-registry.js';
27
- import { mergeLayers, expandVars, buildEnvResolver } from './merge.js';
26
+ import { mergeLayers } from './merge.js';
28
27
  import { normalizeAgentLifecycle } from './lifecycle.js';
29
- import { isBehaviorConfigFieldPath } from './config-field-policy.js';
28
+ import { isAgentOnlyBaseagentField, isBehaviorConfigFieldPath } from './config-field-policy.js';
30
29
  import { clearRoleStoreCache, isRoleName } from './role-store.js';
31
30
  import { writeRoleDefinition, writeRoleRegistry } from './role-service.js';
32
- import { mutateContactBookTransactionSync } from './contact-book-store.js';
31
+ import { mutateContactBookTransactionSync, resolveContactAidKind } from './contact-book-store.js';
33
32
  import { DAEMON_SCHEMA_NAME } from '../product.js';
34
33
  import { normalizeDaemonServices } from './daemon-services.js';
35
34
  import { assertProviderSelectionWrite, resolveProviderModelOverrides, validateProvidersFile } from './providers-config.js';
36
- import { assertOwnerConfigRecord, configuredOwnerList, firstConfiguredOwner, normalizeOwnerConfigTree, withOwnerListCompatibility } from './owner-config.js';
35
+ import { assertOwnerConfigRecord, configuredOwnerList, normalizeOwnerConfigTree, withOwnerListCompatibility } from './owner-config.js';
37
36
  import { getOwners, getPrimaryOwner, ownerResolver } from '../core/ownership/owner-resolver.js';
38
37
  // AUN gateway discovery belongs to fastaun. Keep the retired gatewayUrl
39
38
  // compatibility handling beside the rest of the configuration read/write
40
39
  // policy so all config callers share one implementation.
41
40
  const warnedLegacyGatewayFiles = new Set();
41
+ /** Control identities must never acquire an Agent runtime, regardless of their name. */
42
+ export function assertAgentAidAvailable(aid) {
43
+ if (typeof aid !== 'string')
44
+ return;
45
+ const normalized = aid.trim().toLowerCase();
46
+ const configured = atomicReadJson(resolvePaths().daemonConfig)?.aid;
47
+ // Keep the live control identity reserved until the daemon restarts after a
48
+ // daemon.json change; persisted and in-process identities can differ briefly.
49
+ const active = ownerResolver.getDaemonAid();
50
+ if ([configured, active].some(control => typeof control === 'string' && control.trim().toLowerCase() === normalized)) {
51
+ throw new ConfigError('CONTROL_AID_RESERVED', `AID "${aid}" is reserved for the daemon control identity`);
52
+ }
53
+ }
54
+ /** Only identity changes are rejected; unrelated writes can preserve a legacy conflict for diagnosis. */
55
+ export function assertControlAidAvailable(aid) {
56
+ if (typeof aid !== 'string' || !isValidAid(aid))
57
+ return;
58
+ const paths = resolvePaths();
59
+ const normalized = aid.toLowerCase();
60
+ const previous = atomicReadJson(paths.daemonConfig)?.aid;
61
+ if (typeof previous === 'string' && previous.toLowerCase() === normalized)
62
+ return;
63
+ const directories = fs.existsSync(paths.agentsDir) ? fs.readdirSync(paths.agentsDir, { withFileTypes: true }) : [];
64
+ if (directories.some(entry => entry.isDirectory() && entry.name.toLowerCase() === normalized
65
+ && fs.existsSync(path.join(paths.agentsDir, entry.name, 'config.json')))) {
66
+ throw new ConfigError('CONTROL_AID_CONFLICT', `AID "${aid}" is already registered as an Agent`);
67
+ }
68
+ }
42
69
  export function legacyAunGatewayConfigPaths(value) {
43
70
  if (!value || typeof value !== 'object' || Array.isArray(value))
44
71
  return [];
@@ -339,13 +366,14 @@ export function assertContactBookV2Ready() {
339
366
  if (!fs.existsSync(agentsRoot))
340
367
  return;
341
368
  const issues = [];
369
+ const contactMigrationAgentSchemaMax = 6;
342
370
  const supportedSchemas = (name, minimumVersion) => (listSchemaVersions(name)
343
371
  .filter(version => version >= minimumVersion)
344
372
  .map(version => loadSchema(name, version)));
345
- const agentSchemas = supportedSchemas('agent-config', 6);
373
+ const agentSchemas = supportedSchemas('agent-config', contactMigrationAgentSchemaMax);
346
374
  const contactSchemas = supportedSchemas('contact-book', 2);
347
375
  const relationSchemas = supportedSchemas('relation-config', 5);
348
- const inspect = (file, schemas) => {
376
+ const inspect = (file, schemas, skipNewerAgentSchema = false) => {
349
377
  let value;
350
378
  try {
351
379
  value = JSON.parse(fs.readFileSync(file, 'utf8'));
@@ -356,6 +384,14 @@ export function assertContactBookV2Ready() {
356
384
  }
357
385
  value = stripLegacyAunGatewayConfig(value, file, message => configWarn(message));
358
386
  const candidates = Array.isArray(schemas) ? schemas : [schemas];
387
+ const schemaVersion = value?.$schema_version;
388
+ if (skipNewerAgentSchema && typeof schemaVersion === 'number'
389
+ && schemaVersion > contactMigrationAgentSchemaMax
390
+ && candidates.some(schema => schema.version === schemaVersion)) {
391
+ // Contact book v2 only migrates Agent schemas through v6; later Agent
392
+ // config is left untouched by that migration and validated elsewhere.
393
+ return;
394
+ }
359
395
  if (!candidates.some(schema => schema.validate(value))) {
360
396
  const detail = (candidates.at(-1)?.validate.errors ?? [])
361
397
  .map(error => `${error.instancePath || '/'} ${error.message}`)
@@ -383,7 +419,7 @@ export function assertContactBookV2Ready() {
383
419
  const agentFile = path.join(dir, 'config.json');
384
420
  if (!fs.existsSync(agentFile))
385
421
  continue;
386
- inspect(agentFile, agentSchemas);
422
+ inspect(agentFile, agentSchemas, true);
387
423
  const contactFile = path.join(dir, 'contact.json');
388
424
  if (fs.existsSync(contactFile)) {
389
425
  inspect(contactFile, contactSchemas);
@@ -435,8 +471,11 @@ function inspectContactBookDomain(contactFile, agentFile, issues) {
435
471
  .filter(Boolean));
436
472
  const aliases = new Map();
437
473
  for (const [primaryId, entry] of Object.entries(contact?.contacts ?? {})) {
438
- if (isExplicitGroupId(primaryId)) {
439
- issues.push({ file: contactFile, detail: `group contact ${primaryId} is not supported` });
474
+ const identity = resolveContactAidKind(String(agent?.aid ?? ''), primaryId);
475
+ if (identity.kind === 'group' || ['conflict', 'invalid', 'unavailable'].includes(identity.reason)) {
476
+ issues.push({ file: contactFile, detail: identity.kind === 'group'
477
+ ? `group contact ${primaryId} is not supported`
478
+ : `contact type for ${primaryId} is unknown (${identity.reason}); explicit type evidence is required` });
440
479
  }
441
480
  if (entry?.status === 'blocked' && owners.has(primaryId)) {
442
481
  issues.push({ file: contactFile, detail: `owner contact ${primaryId} cannot be blocked` });
@@ -592,16 +631,6 @@ function requirePeer(sel, target) {
592
631
  if (!sel?.self || !sel?.peerKey)
593
632
  throw new ConfigError('PEER_REQUIRED', `${target} 需要 selector.self + peerKey`);
594
633
  }
595
- // ── env 作用域 ────────────────────────────────────────────────────────────
596
- function envScopeFor(sel) {
597
- const root = resolvePaths().root;
598
- const scope = { rootDir: root };
599
- if (sel?.self)
600
- scope.agentDir = agentDir(sel.self);
601
- if (sel?.self && sel?.peerKey)
602
- scope.relationDir = path.join(agentRelationsDir(sel.self), sel.peerKey);
603
- return scope;
604
- }
605
634
  /** 读单个配置文件,返回强类型对象;不存在返回 null(不自动创建)。未知字段保留但不校验。 */
606
635
  export function read(target, sel, opts = {}) {
607
636
  const file = targetPath(target, sel);
@@ -631,11 +660,8 @@ export function read(target, sel, opts = {}) {
631
660
  : migrated;
632
661
  // Agent read compatibility may move the legacy top-level `agents` block to
633
662
  // `baseagents`, so canonicalize effort after that structural migration.
634
- const canonicalized = normalizeBaseagentEffortCompat(normalized);
635
- if (!opts.expand)
636
- return canonicalized;
637
- const resolver = buildEnvResolver(envScopeFor(sel));
638
- return expandVars(canonicalized, resolver);
663
+ // config.json 不做 ${VAR} 展开:网关凭证与端点只在 providers.json,那里有独立展开实现。
664
+ return normalizeBaseagentEffortCompat(normalized);
639
665
  }
640
666
  /**
641
667
  * Canonicalize the legacy Codex `reasoning` config key to the public `effort`
@@ -819,6 +845,30 @@ export function normalizeProcessConfigCompat(value) {
819
845
  }
820
846
  function normalizeRelationConfigForWrite(value) {
821
847
  const mutable = normalizeBaseagentEffortCompat({ ...value });
848
+ if (mutable.baseagents && typeof mutable.baseagents === 'object' && !Array.isArray(mutable.baseagents)) {
849
+ for (const rawBlock of Object.values(mutable.baseagents)) {
850
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock))
851
+ continue;
852
+ if (Object.keys(rawBlock).some(field => ['headers', 'queryParams', 'apiKey', 'baseUrl'].includes(field))) {
853
+ throw new ConfigError('READ_ONLY_LEGACY_CONFIG', 'relation baseagent gateway metadata is read-only legacy configuration; use providers.json');
854
+ }
855
+ }
856
+ }
857
+ const agentOnlyFields = ['active_baseagent', 'model', 'models']
858
+ .filter(field => Object.prototype.hasOwnProperty.call(mutable, field));
859
+ if (mutable.baseagents && typeof mutable.baseagents === 'object' && !Array.isArray(mutable.baseagents)) {
860
+ for (const [baseagent, rawBlock] of Object.entries(mutable.baseagents)) {
861
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock))
862
+ continue;
863
+ for (const field of ['model', 'effort', 'reasoning']) {
864
+ if (Object.prototype.hasOwnProperty.call(rawBlock, field))
865
+ agentOnlyFields.push(`baseagents.${baseagent}.${field}`);
866
+ }
867
+ }
868
+ }
869
+ if (agentOnlyFields.length > 0) {
870
+ throw new ConfigError('SCOPE_MISMATCH', `Relation config cannot store Agent-level model settings: ${agentOnlyFields.join(', ')}`);
871
+ }
822
872
  normalizeShowActivitiesCompat(mutable);
823
873
  return mutable;
824
874
  }
@@ -898,6 +948,13 @@ export function write(target, value, sel, opts = {}) {
898
948
  : target === ConfigTarget.Providers
899
949
  ? normalizeProvidersConfig(canonicalized)
900
950
  : canonicalized;
951
+ if (target === ConfigTarget.Agent && (normalized.enabled !== false || !fs.existsSync(file))) {
952
+ assertAgentAidAvailable(normalized.aid);
953
+ if (sel?.self)
954
+ assertAgentAidAvailable(sel.self);
955
+ }
956
+ if (target === ConfigTarget.Process)
957
+ assertControlAidAvailable(normalized.aid);
901
958
  // 1. Schema 校验
902
959
  if (!opts.skipValidate) {
903
960
  validateOrThrow(schema, normalized, target);
@@ -996,6 +1053,34 @@ export function mutateConfig(target, sel, mutate) {
996
1053
  release();
997
1054
  }
998
1055
  }
1056
+ /** Remove only the local compatibility entries matching a freshly confirmed protocol Owner. */
1057
+ export function clearConfiguredOwnerAfterConsensus(subjectAid, ownerAid) {
1058
+ const normalizedOwnerAid = ownerAid.trim();
1059
+ if (!isValidAid(normalizedOwnerAid) || subjectAid === ownerResolver.getDaemonAid())
1060
+ return false;
1061
+ const isConfirmed = () => {
1062
+ const state = ownerResolver.snapshot(subjectAid);
1063
+ return ownerResolver.owner(subjectAid) === normalizedOwnerAid && state.authorizationStatus === 'verified'
1064
+ && state.consensus?.lock === 'locked' && state.consensus.sub_aid === subjectAid && !state.refreshFailure;
1065
+ };
1066
+ if (!isConfirmed())
1067
+ return false;
1068
+ return mutateConfig(ConfigTarget.Agent, { self: subjectAid }, config => {
1069
+ if (!isConfirmed())
1070
+ return;
1071
+ if (typeof config.owner === 'string' && config.owner.trim() === normalizedOwnerAid)
1072
+ delete config.owner;
1073
+ if (!Array.isArray(config.owners))
1074
+ return;
1075
+ const owners = config.owners.filter((owner) => typeof owner !== 'string' || owner.trim() !== normalizedOwnerAid);
1076
+ if (owners.length === config.owners.length)
1077
+ return;
1078
+ if (owners.length > 0)
1079
+ config.owners = owners;
1080
+ else
1081
+ delete config.owners;
1082
+ }).changed;
1083
+ }
999
1084
  function cloneConfigValue(value) {
1000
1085
  return JSON.parse(JSON.stringify(value));
1001
1086
  }
@@ -1285,6 +1370,14 @@ export function validateConfig(target, value) {
1285
1370
  ...validateProcessAidDomain(target, normalized),
1286
1371
  ...validateProcessServiceNames(target, normalized),
1287
1372
  ];
1373
+ if (target === ConfigTarget.Agent) {
1374
+ try {
1375
+ assertAgentAidAvailable(normalized?.aid);
1376
+ }
1377
+ catch (error) {
1378
+ errors.push(`CONTROL_AID_RESERVED: ${error.message}`);
1379
+ }
1380
+ }
1288
1381
  if (target === ConfigTarget.Defaults || target === ConfigTarget.Agent || target === ConfigTarget.Relation) {
1289
1382
  try {
1290
1383
  validateResponseModeParams(normalized?.responseModeParams, target);
@@ -1342,6 +1435,8 @@ export function ensureFile(target, sel) {
1342
1435
  if (fs.existsSync(file))
1343
1436
  return;
1344
1437
  const skeleton = configSkeleton(target, sel);
1438
+ if (target === ConfigTarget.Agent)
1439
+ assertAgentAidAvailable(sel?.self ?? skeleton.aid);
1345
1440
  if (target === ConfigTarget.Providers) {
1346
1441
  write(target, skeleton, sel);
1347
1442
  return;
@@ -1390,15 +1485,13 @@ export function resolveAgentConfig(sel, opts = {}) {
1390
1485
  const agentConfig = sel.self ? read(ConfigTarget.Agent, sel, opts) : null;
1391
1486
  const relationConfig = (sel.self && sel.peerKey) ? read(ConfigTarget.Relation, sel, opts) : null;
1392
1487
  const layers = [
1393
- stripStaticOwnerField(normalizeDefaultsBehaviorCompat(read(ConfigTarget.Defaults, undefined, opts))),
1488
+ stripDefaultsLegacyModelFields(stripStaticOwnerField(normalizeDefaultsBehaviorCompat(read(ConfigTarget.Defaults, undefined, opts)))),
1394
1489
  agentConfig,
1395
1490
  stripRelationRoleData(stripStaticOwnerField(relationConfig)),
1396
1491
  ];
1397
1492
  const merged = mergeLayers(layers, fields);
1398
- // A baseagent block is a configuration record rather than an atomic value:
1399
- // selecting a model at Agent or relation scope must retain the defaults
1400
- // gateway credentials and endpoint. Keep the generic dictionary merge
1401
- // contract unchanged for every other field.
1493
+ // Model and service selections inherit defaults and are overridden by Agent;
1494
+ // relation config remains role-only for these fields.
1402
1495
  merged.baseagents = mergeBaseagentBlocks(layers);
1403
1496
  merged.Services = layers.reduce((selections, layer) => {
1404
1497
  for (const [serviceType, selection] of Object.entries(layer?.Services ?? {})) {
@@ -1461,18 +1554,47 @@ function stripStaticOwnerField(config) {
1461
1554
  && !Object.prototype.hasOwnProperty.call(config, 'groupSlashRequireMentions')
1462
1555
  && !Object.prototype.hasOwnProperty.call(config, 'fullaccess'))
1463
1556
  return config;
1464
- // fullaccess and groupSlashRequireMentions are Agent-only. Relation/defaults
1465
- // files allow forward-compatible unknown properties, so strip it before the
1466
- // generic merge chain can treat a manually written value as an override.
1467
1557
  const { owner: _owner, owners: _owners, admins: _admins, access: _access, groupSlashRequireMentions: _groupSlashRequireMentions, fullaccess: _fullaccess, ...rest } = config;
1468
1558
  return rest;
1469
1559
  }
1560
+ function stripDefaultsLegacyModelFields(config) {
1561
+ if (!config)
1562
+ return config;
1563
+ const { models: _models, decision_model: _decisionModel, ...rest } = config;
1564
+ return rest;
1565
+ }
1470
1566
  function stripRelationRoleData(config) {
1471
1567
  if (!config || (!Object.prototype.hasOwnProperty.call(config, 'role')
1472
1568
  && !Object.prototype.hasOwnProperty.call(config, 'roles')
1473
- && !Object.prototype.hasOwnProperty.call(config, 'decision_model')))
1569
+ && !Object.prototype.hasOwnProperty.call(config, 'active_baseagent')
1570
+ && !Object.prototype.hasOwnProperty.call(config, 'baseagents')
1571
+ && !Object.prototype.hasOwnProperty.call(config, 'model')
1572
+ && !Object.prototype.hasOwnProperty.call(config, 'models')
1573
+ && !Object.prototype.hasOwnProperty.call(config, 'Services')
1574
+ && !Object.prototype.hasOwnProperty.call(config, 'decision_model')
1575
+ && !Object.prototype.hasOwnProperty.call(config, 'sessionFullAccess')))
1474
1576
  return config;
1475
- const { role: _role, roles: _legacyRoles, decision_model: _decisionModel, ...rest } = config;
1577
+ const { role: _role, roles: _legacyRoles, active_baseagent: _activeBaseagent, model: _model, models: _models, Services: _services, decision_model: _decisionModel, sessionFullAccess: _sessionFullAccess, ...rest } = config;
1578
+ if (rest.baseagents && typeof rest.baseagents === 'object' && !Array.isArray(rest.baseagents)) {
1579
+ const baseagents = {};
1580
+ for (const [baseagent, rawBlock] of Object.entries(rest.baseagents)) {
1581
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock)) {
1582
+ baseagents[baseagent] = rawBlock;
1583
+ continue;
1584
+ }
1585
+ const block = { ...rawBlock };
1586
+ delete block.model;
1587
+ delete block.effort;
1588
+ delete block.reasoning;
1589
+ if (Object.keys(block).length > 0)
1590
+ baseagents[baseagent] = block;
1591
+ }
1592
+ const mutableRest = rest;
1593
+ if (Object.keys(baseagents).length > 0)
1594
+ mutableRest.baseagents = baseagents;
1595
+ else
1596
+ delete mutableRest.baseagents;
1597
+ }
1476
1598
  return rest;
1477
1599
  }
1478
1600
  // ── effective(合并视图)─────────────────────────────────────────────────
@@ -1490,13 +1612,11 @@ export function resolveEffective(sel, opts = {}) {
1490
1612
  lifecycle: config.lifecycle,
1491
1613
  initialized: config.initialized,
1492
1614
  initialization: config.initialization,
1493
- owner: getPrimaryOwner(sel.self ?? config.aid ?? '') ?? firstConfiguredOwner(config),
1494
- owners: [...new Set([...getOwners(sel.self ?? config.aid ?? ''), ...configuredOwnerList(config)])],
1615
+ owner: getPrimaryOwner(sel.self ?? config.aid ?? ''),
1616
+ owners: getOwners(sel.self ?? config.aid ?? ''),
1495
1617
  fullaccess: config.fullaccess,
1496
1618
  aun: config.aun,
1497
- decision_model: config.decision_model,
1498
1619
  channels: config.channels ?? [],
1499
- models: config.models,
1500
1620
  projects: config.projects,
1501
1621
  capabilities: config.capabilities,
1502
1622
  readonlySourceDiagnostics: config.readonlySourceDiagnostics,
@@ -1513,7 +1633,6 @@ export function resolveEffective(sel, opts = {}) {
1513
1633
  autoMentionQuietWindowMs: config.autoMentionQuietWindowMs
1514
1634
  ?? (typeof autoMentionQuietWindowMsDefault === 'number' ? autoMentionQuietWindowMsDefault : 3000),
1515
1635
  groupSlashRequireMentions: config.groupSlashRequireMentions ?? true,
1516
- model: config.model,
1517
1636
  responseMode: config.responseMode,
1518
1637
  responseModeParams: config.responseModeParams,
1519
1638
  flush_delay: config.flush_delay,
@@ -1528,6 +1647,17 @@ export function resolveEffective(sel, opts = {}) {
1528
1647
  };
1529
1648
  return normalizeEffectiveCompatibility(effective);
1530
1649
  }
1650
+ /** Validate the same effective selection used by runtime before enabling or switching an Agent. */
1651
+ export function assertAgentModelConfigured(self, baseagent) {
1652
+ const config = resolveEffective({ self }, { cache: false });
1653
+ const backend = baseagent ?? config.active_baseagent;
1654
+ if (!backend)
1655
+ throw new ConfigError('BASEAGENT_REQUIRED', 'Configure active_baseagent before enabling this Agent');
1656
+ const model = config.baseagents?.[backend]?.model;
1657
+ if (typeof model !== 'string' || !model.trim()) {
1658
+ throw new ConfigError('MODEL_NOT_CONFIGURED', `Configure baseagents.${backend}.model before enabling or selecting this backend`);
1659
+ }
1660
+ }
1531
1661
  function normalizeEffectiveCompatibility(effective) {
1532
1662
  normalizeShowActivitiesCompat(effective);
1533
1663
  const behavior = {};
@@ -1569,15 +1699,23 @@ export function routeField(topField, scope) {
1569
1699
  */
1570
1700
  export function routeFieldPath(fieldPath, scope) {
1571
1701
  const topField = fieldPath.split('.')[0];
1702
+ if (scope === 'relation' && isAgentOnlyBaseagentField(fieldPath)) {
1703
+ throw new ConfigError('SCOPE_MISMATCH', `${fieldPath} is Agent-scoped and cannot be configured per relation`);
1704
+ }
1572
1705
  if (topField === 'sessionLoop') {
1573
1706
  throw new ConfigError('SESSION_LOOP_MANAGED', 'sessionLoop is managed through the dedicated /loop or session Menu entry');
1574
1707
  }
1708
+ if (topField === 'sessionFullAccess') {
1709
+ throw new ConfigError('SESSION_FULLACCESS_MANAGED', 'sessionFullAccess is managed through the dedicated /fa or session Menu entry');
1710
+ }
1575
1711
  if (scope === 'process')
1576
1712
  return routeIn(DAEMON_SCHEMA_NAME, ConfigTarget.Process, topField);
1577
1713
  if (scope === 'defaults') {
1578
1714
  if (isBehaviorConfigFieldPath(fieldPath)
1579
1715
  && topField !== 'session_renew'
1580
- && topField !== 'autoMentionQuietWindowMs') {
1716
+ && topField !== 'autoMentionQuietWindowMs'
1717
+ && topField !== 'active_baseagent'
1718
+ && topField !== 'baseagents') {
1581
1719
  throw new ConfigError('DEFAULT_BEHAVIOR_REJECT', `--default 不支持行为字段: ${fieldPath}`);
1582
1720
  }
1583
1721
  return routeIn('defaults', ConfigTarget.Defaults, topField);
@@ -1650,7 +1788,7 @@ export function listFields(scope) {
1650
1788
  const add = (name, target) => {
1651
1789
  const s = loadSchema(name);
1652
1790
  for (const f of s.fields.keys()) {
1653
- if (f !== 'sessionLoop')
1791
+ if (f !== 'sessionLoop' && f !== 'sessionFullAccess')
1654
1792
  out.push(mkRoute(s, target, f));
1655
1793
  }
1656
1794
  };
@@ -1680,8 +1818,9 @@ export function readConfiguredFieldWithSource(field, sel, opts = {}) {
1680
1818
  const topField = parts[0];
1681
1819
  // 按覆盖链顺序查找:relation → agent → defaults
1682
1820
  const targets = [];
1683
- if (sel.self && sel.peerKey)
1821
+ if (sel.self && sel.peerKey && !isAgentOnlyBaseagentField(field) && !['Services', 'model', 'models', 'decision_model'].includes(topField)) {
1684
1822
  targets.push(ConfigTarget.Relation);
1823
+ }
1685
1824
  if (sel.self)
1686
1825
  targets.push(ConfigTarget.Agent);
1687
1826
  targets.push(ConfigTarget.Defaults);
@@ -6,9 +6,7 @@ import fs from 'fs';
6
6
  import path from 'path';
7
7
  import { resolvePaths, agentDir, agentRelationConfig } from '../paths.js';
8
8
  import { roleMenuQuery, roleMenuUpdate } from '../core/command/role-menu.js';
9
- import { parseAgentMdFrontmatter, parsePeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
10
- import { agentmdGet } from '../aun/aid/agentmd.js';
11
- import { isLegacyNamedGroupIdHint } from '../aun/group/index.js';
9
+ import { parsePeerKey, resolveAunPeerKind } from '../core/relation/peer-identity.js';
12
10
  import { isUnsupportedBaseagentConfigField } from './config-field-policy.js';
13
11
  export const AUTHENTICATED_CONFIG_ROLE_ENV = 'EVOLCORE_AUTHENTICATED_CONFIG_ROLE';
14
12
  export function executeResolvedConfigCommand(command, options = {}) {
@@ -152,23 +150,11 @@ async function roleTargetFromPeerKey(self, peerKey) {
152
150
  if (parsed.channelType !== 'aun') {
153
151
  throw new ConfigError('NOT_SUPPORTED', 'Relation role assignments currently support AUN peers only');
154
152
  }
155
- const relation = read(ConfigTarget.Relation, { self, peerKey });
156
- const identity = PeerIdentityCache.get('aun', parsed.channelId, agentDir(self));
157
- let verifiedType = identity?.aid === parsed.channelId && identity.source === 'agentmd' && identity.verifiedAt > 0
158
- ? identity.type : undefined;
159
- if (!relation?.targetKind && !verifiedType) {
160
- try {
161
- const result = await agentmdGet(parsed.channelId, { withVerification: true });
162
- if (result.verification.status === 'verified') {
163
- const metadata = parseAgentMdFrontmatter(result.content);
164
- verifiedType = typeof metadata.type === 'string' ? metadata.type : undefined;
165
- }
166
- }
167
- catch { }
153
+ const resolution = await resolveAunPeerKind(self, parsed.channelId);
154
+ if (resolution.kind === 'unknown') {
155
+ throw new ConfigError('TARGET_TYPE_UNKNOWN', `Cannot establish relation type (${resolution.reason}): ${parsed.channelId}`);
168
156
  }
169
- const isGroup = relation?.targetKind ? relation.targetKind === 'group'
170
- : verifiedType ? verifiedType.toLowerCase() === 'group' : isLegacyNamedGroupIdHint(parsed.channelId);
171
- return isGroup
157
+ return resolution.kind === 'group'
172
158
  ? { kind: 'group', groupId: parsed.channelId }
173
159
  : { kind: 'private', peerAid: parsed.channelId };
174
160
  }
@@ -2,13 +2,12 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { isValidAid } from '../aun/aid/validation.js';
5
- import { isExplicitGroupId } from '../aun/group/index.js';
6
- import { agentConfig, agentContactAuditPath, agentContactConfig, agentDir, agentRelationsDir, resolvePaths } from '../paths.js';
5
+ import { agentConfig, agentContactAuditPath, agentContactConfig, agentDir, agentRelationConfig, agentRelationsDir, resolvePaths } from '../paths.js';
7
6
  import { atomicReadJson, atomicWrite, atomicWriteJson } from '../utils/atomic-write.js';
8
7
  import { fileCache } from '../core/daemon-file-cache.js';
9
8
  import { unregisterFile } from '../core/file-integrity/store.js';
10
9
  import { ensureManagedLockParent, resolveManagedLockPath } from '../core/runtime-lock.js';
11
- import { parsePeerKey } from '../core/relation/peer-identity.js';
10
+ import { formatPeerKey, parsePeerKey, readAunPeerKind, recordAunPeerRoute } from '../core/relation/peer-identity.js';
12
11
  import { ConfigTarget, notifyConfigWrite, validateConfig } from './config-manager.js';
13
12
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
14
13
  import { parseContactAlias } from './contact-alias.js';
@@ -98,8 +97,13 @@ export function synchronizeManagementContactsSync(selfAid) {
98
97
  export function synchronizeOwnershipContactsSync(subjectAid) {
99
98
  synchronizeManagementContactsSync(subjectAid);
100
99
  const ownerAid = ownerResolver.owner(subjectAid);
101
- if (!ownerAid || !fs.existsSync(agentConfig(ownerAid)))
100
+ if (!ownerAid || !fs.existsSync(agentConfig(subjectAid)) || !fs.existsSync(agentConfig(ownerAid)))
102
101
  return;
102
+ // The registered local Agent establishes the type; ownership only selects its Owner's Contact Book.
103
+ const kind = recordAunPeerRoute(ownerAid, subjectAid, 'private');
104
+ if (kind.kind !== 'private') {
105
+ throw new ContactMutationError('CONTACT_TYPE_UNKNOWN', `Managed Agent type conflicts with Owner relation: ${subjectAid}`);
106
+ }
103
107
  // Add the subject to its local Owner's contacts, preserving existing admission decisions.
104
108
  mutateContactBookSync({
105
109
  selfAid: ownerAid,
@@ -107,10 +111,15 @@ export function synchronizeOwnershipContactsSync(subjectAid) {
107
111
  mutation: { type: 'ensure-contacts', primaryIds: [subjectAid] },
108
112
  });
109
113
  }
114
+ /** Read pending relation changes together with verified identity evidence. */
115
+ export function resolveContactAidKind(selfAid, aid, changes = []) {
116
+ const relation = readTransactionJson(agentRelationConfig(selfAid, formatPeerKey('aun', aid)), changes);
117
+ return readAunPeerKind(selfAid, aid, { relation });
118
+ }
110
119
  function managementRoleMapForAgent(selfAid, changes) {
111
120
  const roles = {};
112
121
  for (const owner of ownerResolver.protocolOwners(selfAid)) {
113
- if (isValidAid(owner) && !isExplicitGroupId(owner))
122
+ if (isValidAid(owner))
114
123
  roles[owner] = 'owner';
115
124
  }
116
125
  const relationsRoot = agentRelationsDir(selfAid);
@@ -138,9 +147,11 @@ function managementRoleMapForAgent(selfAid, changes) {
138
147
  catch {
139
148
  continue;
140
149
  }
141
- if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId) || isExplicitGroupId(parsed.channelId))
150
+ if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId))
142
151
  continue;
143
152
  const config = readTransactionJson(path.join(relationsRoot, peerKey, 'config.json'), changes);
153
+ if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind !== 'private')
154
+ continue;
144
155
  if (config?.targetKind !== 'group' && config?.role === 'admin' && roles[parsed.channelId] !== 'owner') {
145
156
  roles[parsed.channelId] = 'admin';
146
157
  }
@@ -206,7 +217,7 @@ function mutateContactBookSyncInternal(request, transactionChanges) {
206
217
  }
207
218
  validateTransactionChanges(selfAid, transactionChanges);
208
219
  const next = cloneBook(current);
209
- applyMutation(next, request.mutation, selfAid);
220
+ applyMutation(next, request.mutation, selfAid, transactionChanges);
210
221
  synchronizeManagementRoles(next, selfAid, transactionChanges);
211
222
  if (request.mutation.type === 'replace') {
212
223
  const errors = validateConfig(ConfigTarget.Contact, next);
@@ -326,7 +337,7 @@ function mutateContactBookPreparedSyncInternal(selfAid, prepare) {
326
337
  release();
327
338
  }
328
339
  }
329
- function applyMutation(book, mutation, selfAid) {
340
+ function applyMutation(book, mutation, selfAid, changes = []) {
330
341
  if (mutation.type === 'replace') {
331
342
  book.contacts = cloneBook(mutation.contact).contacts;
332
343
  return;
@@ -334,12 +345,12 @@ function applyMutation(book, mutation, selfAid) {
334
345
  const contacts = book.contacts;
335
346
  if (mutation.type === 'batch') {
336
347
  for (const item of mutation.mutations)
337
- applyMutation(book, item, selfAid);
348
+ applyMutation(book, item, selfAid, changes);
338
349
  return;
339
350
  }
340
351
  if (mutation.type === 'ensure-contacts') {
341
352
  for (const rawPrimaryId of mutation.primaryIds) {
342
- const primaryId = normalizeContactAid(rawPrimaryId);
353
+ const primaryId = normalizeContactAid(rawPrimaryId, selfAid, changes);
343
354
  if (!contacts[primaryId])
344
355
  contacts[primaryId] = {};
345
356
  }
@@ -348,12 +359,23 @@ function applyMutation(book, mutation, selfAid) {
348
359
  if (mutation.type === 'sync-management-roles') {
349
360
  return;
350
361
  }
351
- const primaryId = normalizeContactAid(mutation.primaryId);
352
- const existing = contacts[primaryId];
353
- if (mutation.type === 'set-status') {
354
- if (isOwner(selfAid, primaryId) && mutation.status !== 'active') {
362
+ const rawPrimaryId = String(mutation.primaryId || '').trim();
363
+ if (isOwner(selfAid, rawPrimaryId)) {
364
+ if (mutation.type === 'set-status' && mutation.status !== 'active') {
355
365
  throw new ContactMutationError('OWNER_PROTECTED', 'An Agent owner must remain active');
356
366
  }
367
+ if (mutation.type === 'set-request') {
368
+ throw new ContactMutationError('OWNER_PROTECTED', 'An Agent owner cannot submit a contact request');
369
+ }
370
+ }
371
+ const prior = contacts[rawPrimaryId];
372
+ const preservesAdmission = !!prior && (mutation.type === 'set-display-name' || mutation.type === 'unbind-alias'
373
+ || mutation.type === 'expire-request'
374
+ || (mutation.type === 'review-request' && mutation.decision !== 'approve')
375
+ || (mutation.type === 'set-status' && mutation.status !== 'active'));
376
+ const primaryId = normalizeContactAid(mutation.primaryId, selfAid, changes, preservesAdmission);
377
+ const existing = contacts[primaryId];
378
+ if (mutation.type === 'set-status') {
357
379
  contacts[primaryId] = compactEntry({
358
380
  ...existing,
359
381
  status: mutation.status === 'active' ? undefined : mutation.status,
@@ -363,9 +385,6 @@ function applyMutation(book, mutation, selfAid) {
363
385
  return;
364
386
  }
365
387
  if (mutation.type === 'set-request') {
366
- if (isOwner(selfAid, primaryId)) {
367
- throw new ContactMutationError('OWNER_PROTECTED', 'An Agent owner cannot submit a contact request');
368
- }
369
388
  contacts[primaryId] = compactEntry({
370
389
  ...existing,
371
390
  status: 'pending',
@@ -458,7 +477,11 @@ function validateContactBook(book, selfAid, changes = []) {
458
477
  const agent = readTransactionJson(agentConfig(selfAid), changes);
459
478
  const configuredChannelKeys = readConfiguredContactChannelKeys(selfAid, agent);
460
479
  for (const [primaryId, entry] of Object.entries(book.contacts)) {
461
- if (!isValidAid(primaryId) || isExplicitGroupId(primaryId)) {
480
+ const kind = resolveContactAidKind(selfAid, primaryId, changes);
481
+ // Retain an existing record when type evidence was removed (for example
482
+ // an Owner or relation was revoked). Registration still requires private
483
+ // evidence in normalizeContactAid, and permission consumers recheck type.
484
+ if (!isValidAid(primaryId) || kind.kind === 'group' || (kind.kind === 'unknown' && kind.reason !== 'missing')) {
462
485
  throw new ContactMutationError('INVALID_CONTACT_BOOK', `Invalid contact AID: ${primaryId}`);
463
486
  }
464
487
  if (entry.status && isOwner(selfAid, primaryId)) {
@@ -748,10 +771,13 @@ function normalizeAid(value, label) {
748
771
  throw new ContactMutationError('INVALID_AID', `Invalid ${label}: ${JSON.stringify(value)}`);
749
772
  return aid;
750
773
  }
751
- function normalizeContactAid(value) {
774
+ function normalizeContactAid(value, selfAid, changes = [], preservesAdmission = false) {
752
775
  const aid = normalizeAid(value, 'contact AID');
753
- if (isExplicitGroupId(aid)) {
754
- throw new ContactMutationError('INVALID_AID', `Contact Book does not support group AID: ${JSON.stringify(value)}`);
776
+ const resolution = resolveContactAidKind(selfAid, aid, changes);
777
+ if (resolution.kind !== 'private' && !(preservesAdmission && resolution.reason === 'missing')) {
778
+ throw new ContactMutationError('INVALID_AID', resolution.kind === 'group'
779
+ ? `Contact Book does not support group AID: ${JSON.stringify(value)}`
780
+ : `Contact AID type is unknown (${resolution.reason}): ${JSON.stringify(value)}`);
755
781
  }
756
782
  return aid;
757
783
  }