evolcore 0.0.47 → 0.0.48

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 (218) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +31 -16
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/service-proxy.js +4 -2
  14. package/dist/build-identity.json +1 -0
  15. package/dist/channels/aun.js +81 -24
  16. package/dist/channels/daemon.js +9 -25
  17. package/dist/cli/aun-commands.js +86 -51
  18. package/dist/cli/code-stats.js +19 -8
  19. package/dist/cli/command-log.js +1 -1
  20. package/dist/cli/daemon-commands.js +44 -43
  21. package/dist/cli/directory.js +7 -1
  22. package/dist/cli/ecmsg-gateway.js +5 -2
  23. package/dist/cli/index.js +2 -8
  24. package/dist/cli/init-channel.js +4 -6
  25. package/dist/cli/init.js +72 -50
  26. package/dist/cli/invoke-command.js +1 -1
  27. package/dist/cli/provider-command.js +74 -13
  28. package/dist/cli/role.js +61 -17
  29. package/dist/cli/stats.js +3 -3
  30. package/dist/cli/thread-command.js +16 -51
  31. package/dist/config/boot-log.js +3 -9
  32. package/dist/config/builtin-roles.js +5 -7
  33. package/dist/config/config-manager.js +2 -6
  34. package/dist/config/daemon-services.js +30 -3
  35. package/dist/config/gateway-config.js +2 -2
  36. package/dist/config/invoke-ipc-service.js +6 -4
  37. package/dist/config/peer-bind-code.js +3 -4
  38. package/dist/config/peer-book-store.js +62 -229
  39. package/dist/config/peer-book.js +26 -27
  40. package/dist/config/peer-role-resolver.js +16 -1
  41. package/dist/config/provider-identity-migration.js +4 -1
  42. package/dist/config/provider-ipc-service.js +56 -11
  43. package/dist/config/provider-menu-request.js +24 -5
  44. package/dist/config/provider-templates.js +127 -0
  45. package/dist/config/providers-config.js +59 -8
  46. package/dist/config/providers-management.js +467 -49
  47. package/dist/config/role-command-service.js +248 -1
  48. package/dist/config/schema-migration.js +105 -4
  49. package/dist/core/agent-application-service.js +6 -1
  50. package/dist/core/agent-runtime.js +4 -0
  51. package/dist/core/auth/agent-delegation.js +2 -1
  52. package/dist/core/auth/auth-gateway.js +2 -1
  53. package/dist/core/auth/delegation-authorization.js +3 -0
  54. package/dist/core/auth/operation-authorizer.js +25 -0
  55. package/dist/core/auth/operation-catalog.js +28 -64
  56. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  57. package/dist/core/channel-loader.js +18 -0
  58. package/dist/core/command/agent-control.js +32 -0
  59. package/dist/core/command/command-handler.js +81 -85
  60. package/dist/core/command/menu-catalog.js +1 -0
  61. package/dist/core/command/menu-handler.js +61 -149
  62. package/dist/core/command/menu-protocol.js +7 -1
  63. package/dist/core/command/provider-menu.js +13 -3
  64. package/dist/core/command/role-menu.js +47 -23
  65. package/dist/core/command/slash-handler.js +26 -43
  66. package/dist/core/command/team-workspace-items.js +81 -12
  67. package/dist/core/command/team-workspace-team.js +9 -71
  68. package/dist/core/command/topic-slash.js +9 -30
  69. package/dist/core/daemon-bootstrap.js +8 -1
  70. package/dist/core/daemon-control.js +7 -7
  71. package/dist/core/evolagent-registry.js +14 -1
  72. package/dist/core/file-integrity/store.js +2 -0
  73. package/dist/core/handoff/runtime.js +37 -1
  74. package/dist/core/inference/text-inference.js +3 -1
  75. package/dist/core/initialization/service.js +11 -6
  76. package/dist/core/interaction-router.js +3 -0
  77. package/dist/core/invoke/executors/text.js +72 -19
  78. package/dist/core/ipc-registration.js +2 -1
  79. package/dist/core/message/aun-ipc-sender.js +165 -55
  80. package/dist/core/message/im-renderer.js +1 -1
  81. package/dist/core/message/message-bridge.js +51 -334
  82. package/dist/core/message/message-log.js +5 -0
  83. package/dist/core/message/message-queue.js +22 -0
  84. package/dist/core/message/message-utils.js +8 -0
  85. package/dist/core/message/response-engine.js +429 -116
  86. package/dist/core/message/send-routing.js +5 -1
  87. package/dist/core/model/catalog-service.js +31 -11
  88. package/dist/core/model/model-capabilities.js +22 -4
  89. package/dist/core/model/model-catalog.js +1 -0
  90. package/dist/core/ownership/owner-resolver.js +328 -50
  91. package/dist/core/permission/protected-paths.js +6 -6
  92. package/dist/core/relation/peer-identity.js +23 -1
  93. package/dist/core/relation/same-owner-proof.js +81 -112
  94. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  95. package/dist/core/session/session-file-health.js +13 -7
  96. package/dist/core/session/session-fs-store.js +91 -35
  97. package/dist/core/session/session-manager.js +68 -24
  98. package/dist/core/session/session-mapper.js +14 -34
  99. package/dist/core/session/session-transcript.js +5 -1
  100. package/dist/core/task/task-activity-store.js +84 -0
  101. package/dist/core/task/task-recovery-service.js +12 -0
  102. package/dist/core/thread/command-parser.js +7 -12
  103. package/dist/core/thread/thread-context-storage.js +3 -2
  104. package/dist/core/thread/thread-operation.js +2 -13
  105. package/dist/core/thread/thread-service.js +15 -46
  106. package/dist/directory/owner-directory-admission.js +1 -1
  107. package/dist/directory/owner-directory-cache.js +45 -28
  108. package/dist/directory/owner-directory-markdown.js +13 -1
  109. package/dist/directory/owner-directory-query-operation.js +29 -3
  110. package/dist/directory/owner-directory-remarks.js +11 -3
  111. package/dist/eck/message-renderer.js +84 -24
  112. package/dist/ecweb/basic-settings-service.js +3 -1
  113. package/dist/ecweb/message-context-service.js +1 -1
  114. package/dist/ecweb/pairing.js +4 -3
  115. package/dist/ecweb/providers-service.js +26 -1
  116. package/dist/ecweb/runtime/lifecycle.js +18 -8
  117. package/dist/ecweb/runtime/proxy-access.js +74 -0
  118. package/dist/ecweb/runtime/supervisor.js +4 -2
  119. package/dist/event-center/registry.js +13 -2
  120. package/dist/event-center/runtime.js +103 -11
  121. package/dist/event-center/script-runner.js +5 -5
  122. package/dist/index.js +92 -59
  123. package/dist/ipc.js +13 -2
  124. package/dist/outputs/events.js +62 -0
  125. package/dist/outputs/protocol.js +102 -0
  126. package/dist/outputs/service.js +279 -0
  127. package/dist/paths.js +3 -0
  128. package/dist/proxy/manager.js +43 -13
  129. package/dist/services/index.js +89 -4
  130. package/dist/services/ipc-operation.js +4 -15
  131. package/dist/services/pack-manager.js +12 -1
  132. package/dist/services/router.js +21 -6
  133. package/dist/services/script-runner.js +5 -4
  134. package/dist/services/validation.js +1 -1
  135. package/dist/stats/budget.js +1 -1
  136. package/dist/stats/db.js +19 -0
  137. package/dist/stats/index.js +1 -1
  138. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  139. package/dist/stats/normalizer.js +2 -0
  140. package/dist/stats/query.js +35 -27
  141. package/dist/stats/role-budget.js +5 -2
  142. package/dist/stats/writer.js +10 -6
  143. package/dist/trigger/audit.js +7 -0
  144. package/dist/trigger/authorization.js +105 -11
  145. package/dist/trigger/feedback.js +10 -0
  146. package/dist/trigger/history.js +37 -11
  147. package/dist/trigger/ipc-service.js +12 -1
  148. package/dist/trigger/manager.js +1 -0
  149. package/dist/trigger/scheduler.js +7 -5
  150. package/dist/trigger/script-executor.js +2 -1
  151. package/dist/trigger/script-sandbox.js +9 -3
  152. package/dist/trigger/validation.js +22 -0
  153. package/dist/utils/cross-platform.js +73 -26
  154. package/dist/utils/error-dict.json +94 -4
  155. package/dist/utils/error-utils.js +27 -4
  156. package/dist/utils/evolcore-version.js +36 -65
  157. package/dist/utils/msg-diag.js +1 -0
  158. package/dist/utils/process-introspect.js +12 -7
  159. package/dist/utils/process-tree.js +50 -2
  160. package/dist/utils/windows-shell-trust.js +2 -0
  161. package/dist/workbench/protocol.js +80 -0
  162. package/dist/workbench/service.js +359 -0
  163. package/ecagent/dist/types.d.ts +6 -2
  164. package/kits/docs/context-assembly.md +1 -1
  165. package/kits/docs/evolcore/INDEX.md +2 -2
  166. package/kits/docs/evolcore/config.md +12 -0
  167. package/kits/docs/evolcore/directory.md +22 -3
  168. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  169. package/kits/docs/evolcore/model.md +10 -0
  170. package/kits/docs/evolcore/peer.md +19 -65
  171. package/kits/docs/evolcore/provider.md +123 -3
  172. package/kits/docs/evolcore/role.md +80 -0
  173. package/kits/docs/evolcore/services.md +6 -6
  174. package/kits/docs/evolcore/team-workspace.md +1 -1
  175. package/kits/docs/evolcore/thread-chain.md +14 -15
  176. package/kits/docs/evolcore/tool-authorization.md +5 -0
  177. package/kits/docs/evolcore/trigger.md +10 -0
  178. package/kits/eck_message_manifest.json +12 -0
  179. package/kits/provider-templates.json +1213 -0
  180. package/kits/rules/04-relation.md +3 -3
  181. package/kits/schemas/_meta.json +14 -2
  182. package/kits/schemas/contact-book.schema.4.json +52 -0
  183. package/kits/schemas/providers.schema.3.json +200 -0
  184. package/kits/skills/.switches.json +4 -0
  185. package/kits/skills/ability/references/calling.md +1 -1
  186. package/kits/skills/ec-group/SKILL.md +2 -2
  187. package/kits/skills/ec-identity/SKILL.md +19 -72
  188. package/kits/skills/ec-provider/SKILL.md +221 -0
  189. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  190. package/kits/skills/ec-trigger/SKILL.md +1 -1
  191. package/kits/skills/thread-ops/SKILL.md +34 -21
  192. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  193. package/kits/templates/message-fragments/group-batch.md +1 -1
  194. package/kits/templates/message-fragments/inject-default.md +1 -1
  195. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  196. package/kits/templates/message-fragments/item-group.md +1 -1
  197. package/kits/templates/message-fragments/item-private.md +1 -1
  198. package/kits/templates/message-fragments/thread-context.md +1 -1
  199. package/kits/templates/message-fragments/trigger-session.md +1 -1
  200. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  201. package/kits/templates/roles/admin.json +2 -19
  202. package/kits/templates/roles/member.json +0 -3
  203. package/kits/templates/system-fragments/baseagent.md +6 -0
  204. package/kits/templates/system-fragments/commands.md +3 -3
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +1 -1
  207. package/kits/templates/system-fragments/thread.md +6 -5
  208. package/package.json +6 -4
  209. package/scripts/agent-template/inspect.mjs +4 -1
  210. package/scripts/agent-template/shared/common.mjs +2 -3
  211. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  212. package/scripts/agent-template/shared/template-package.mjs +9 -2
  213. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  214. package/scripts/agent-template/team-pack.mjs +6 -3
  215. package/dist/cli/peer.js +0 -127
  216. package/dist/config/peer-operation-service.js +0 -132
  217. package/dist/config/peer-request-service.js +0 -532
  218. package/dist/core/command/connect-menu.js +0 -624
@@ -1,14 +1,17 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import { randomUUID } from 'crypto';
4
- import { agentOwnerBindingRejectionPath, resolvePaths } from '../../paths.js';
3
+ import { createHash, randomUUID } from 'crypto';
4
+ import { agentMdPath, agentOwnerBindingRejectionPath, ownershipCachePath, resolvePaths } from '../../paths.js';
5
5
  import { isValidAid } from '../../aun/aid/validation.js';
6
6
  import { atomicReadJson } from '../../utils/atomic-write.js';
7
7
  import { configuredOwnerList as readConfiguredOwnerList } from '../../config/owner-config.js';
8
8
  import { logger, logOwnershipEvent, ownershipErrorCode } from '../../utils/logger.js';
9
9
  import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
10
+ import { registerContent, verifyFile } from '../file-integrity/store.js';
11
+ import { atomicWrite } from '../../utils/atomic-write.js';
10
12
  export const OWNERSHIP_CACHE_MAX_AGE_MS = 30 * 60_000;
11
- export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS = 5 * 60_000;
13
+ export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS = OWNERSHIP_CACHE_MAX_AGE_MS;
14
+ export const OWNERSHIP_RETRY_BASE_MS = 5_000;
12
15
  const CREATION_BIND_OPERATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
13
16
  /** Only use the task returned by this create's bind call. Never select a latest task. */
14
17
  export function creationOwnershipBinding(task, subjectAid, ownerAid) {
@@ -35,15 +38,44 @@ export class OwnershipError extends Error {
35
38
  this.name = 'OwnershipError';
36
39
  }
37
40
  }
41
+ /** Shared classification for Ownership and same-Owner authorization evidence. */
42
+ export function isTransientOwnershipRefreshFailure(error) {
43
+ const details = error && typeof error === 'object' ? error : {};
44
+ const code = String(details.code ?? details.stringCode ?? '').toUpperCase();
45
+ const message = error instanceof Error ? error.message
46
+ : typeof details.message === 'string' ? details.message : String(error);
47
+ if (['INVALID', 'CONFLICT', 'FORBIDDEN', 'NOT_APPLICABLE', 'OWNER_LOCKED', 'TASK_MISMATCH',
48
+ 'CONSENSUS_MISMATCH', 'UNSUPPORTED_PROTOCOL', 'PERSISTENCE_UNAVAILABLE'].includes(code))
49
+ return false;
50
+ if (/projection.*(?:does not match|conflict)|(?:agent|owner)\.md changed (?:while|during)|NS relation changed .*consensus check|digest does not match authoritative observation|Storage material changed during authoritative read/i.test(message))
51
+ return false;
52
+ if (details.retryable === false)
53
+ return false;
54
+ if (details.retryable === true)
55
+ return true;
56
+ return code === 'TIMEOUT' || code === 'NETWORK_ERROR' || code === 'UNAVAILABLE'
57
+ || code === 'CLIENT_DISCONNECTED' || code === 'CONNECTION_FAILED'
58
+ || code === 'GATEWAY_UNAVAILABLE' || code === 'CONNECTION_UNAVAILABLE'
59
+ || code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT'
60
+ || code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
61
+ || /timed out|timeout|connection reset|connection refused|connection closed|socket hang up|not connected|network error|fetch failed|gateway unavailable|gateway timeout|temporarily unavailable/i.test(message);
62
+ }
38
63
  export class OwnerResolver {
39
64
  options;
40
65
  subjects = new Map();
66
+ authorizationChecks = new Map();
41
67
  daemonAid;
42
68
  /** Compatibility binding targets loaded from config; never an Owner authorization source. */
43
69
  configuredOwners = new Map();
44
70
  configuredOwnerFileRevision = new Map();
45
71
  listeners = new Set();
46
72
  updateListeners = new Set();
73
+ cacheFile;
74
+ rootScope;
75
+ cacheEntries = new Map();
76
+ cacheWriteQueued = false;
77
+ activeQueries = 0;
78
+ queryWaiters = [];
47
79
  constructor(options = {}) {
48
80
  this.options = options;
49
81
  }
@@ -54,6 +86,170 @@ export class OwnerResolver {
54
86
  getDaemonAid() {
55
87
  return this.daemonAid;
56
88
  }
89
+ registerEvidenceClient(subjectAid, client, store) {
90
+ const subject = this.subject(subjectAid);
91
+ if (subject.client && subject.client !== client) {
92
+ subject.generation++;
93
+ subject.epoch++;
94
+ }
95
+ subject.client = client;
96
+ subject.store = store;
97
+ subject.view.connected = client.isReady;
98
+ }
99
+ unregisterEvidenceClient(subjectAid, client) {
100
+ const subject = this.subjects.get(subjectAid);
101
+ if (subject?.client === client) {
102
+ subject.store = undefined;
103
+ this.detachClient(subjectAid, client);
104
+ }
105
+ }
106
+ invalidateEvidence(aid) {
107
+ this.loadCache();
108
+ for (const [subjectAid, cached] of this.cacheEntries) {
109
+ if (subjectAid === aid || cached.ownerAid === aid)
110
+ this.cacheEntries.delete(subjectAid);
111
+ }
112
+ this.writeCache();
113
+ for (const subject of this.subjects.values()) {
114
+ if (subject.view.subjectAid === aid || subject.view.relation?.ownerAid === aid) {
115
+ this.invalidate(subject, 'Ownership material changed; fresh consensus is required');
116
+ }
117
+ }
118
+ }
119
+ async queryConsensus(client, aid) {
120
+ return this.query(() => client.checkOwnershipConsensus(aid, true));
121
+ }
122
+ /** One bounded network budget shared by all subjects and both authorization consumers. */
123
+ async query(operation) {
124
+ const limit = Math.max(1, this.options.queryConcurrency ?? 4);
125
+ if (this.activeQueries >= limit)
126
+ await new Promise(resolve => this.queryWaiters.push(resolve));
127
+ else
128
+ this.activeQueries++;
129
+ try {
130
+ return await operation();
131
+ }
132
+ finally {
133
+ const next = this.queryWaiters.shift();
134
+ if (next)
135
+ next();
136
+ else
137
+ this.activeQueries--;
138
+ }
139
+ }
140
+ loadCache() {
141
+ const file = this.options.cachePath?.() ?? ownershipCachePath();
142
+ if (this.cacheFile === file)
143
+ return;
144
+ this.cacheFile = file;
145
+ this.cacheEntries.clear();
146
+ try {
147
+ const checked = verifyFile(file, { requireRegistered: true });
148
+ if (checked.status !== 'verified' || !checked.bytes)
149
+ return;
150
+ const raw = JSON.parse(checked.bytes.toString('utf8'));
151
+ const now = this.now();
152
+ if (raw.schemaVersion !== 1 || !Number.isSafeInteger(raw.savedAt) || raw.savedAt > now
153
+ || !raw.entries || typeof raw.entries !== 'object' || Array.isArray(raw.entries))
154
+ return;
155
+ for (const [aid, value] of Object.entries(raw.entries)) {
156
+ const view = value;
157
+ if (!view || typeof view !== 'object' || !isValidAid(aid) || view.subjectAid !== aid || view.consensusStatus !== 'consensus'
158
+ || !view.consensus || view.consensus.sub_aid !== aid || view.consensus.status !== 'consensus'
159
+ || view.consensus.lock !== 'locked' || !view.ownerAid || !isValidAid(view.ownerAid)
160
+ || view.ownerAid === aid || view.consensus.owner_aid !== view.ownerAid
161
+ || !Number.isSafeInteger(view.consensus.relation_version) || view.consensus.relation_version < 1
162
+ || !/^[a-f0-9]{64}$/.test(view.consensus.agent_md_sha256 ?? '')
163
+ || !Number.isSafeInteger(view.checkedAt) || view.checkedAt > now
164
+ || view.checkedAt > raw.savedAt || now - view.checkedAt >= OWNERSHIP_CACHE_MAX_AGE_MS
165
+ || view.validUntil !== view.checkedAt + OWNERSHIP_CACHE_MAX_AGE_MS
166
+ || (view.profile && (view.profile.sha256 !== view.consensus.agent_md_sha256
167
+ || typeof view.profile.type !== 'string')))
168
+ continue;
169
+ this.cacheEntries.set(aid, { ...view, connected: false, refreshFailure: undefined });
170
+ }
171
+ }
172
+ catch (error) {
173
+ logger.warn(`[ownership] Cache ignored: ${error instanceof Error ? error.message : String(error)}`);
174
+ }
175
+ }
176
+ restoreCache(subjectAid, subject) {
177
+ this.loadCache();
178
+ if (subject.view.consensus || subject.view.refreshFailure
179
+ || (subject.view.reason && subject.view.reason !== 'AUN client is unavailable'))
180
+ return;
181
+ const cached = this.cacheEntries.get(subjectAid);
182
+ if (!cached || (cached.validUntil ?? 0) <= this.now() || cached.checkedAt > this.now())
183
+ return;
184
+ // If the SDK has observed a different local card while we were down, do not restore the old proof.
185
+ const cardFile = agentMdPath(subjectAid);
186
+ try {
187
+ if (fs.existsSync(cardFile) && createHash('sha256').update(fs.readFileSync(cardFile)).digest('hex')
188
+ !== cached.consensus?.agent_md_sha256) {
189
+ this.cacheEntries.delete(subjectAid);
190
+ this.writeCache();
191
+ return;
192
+ }
193
+ }
194
+ catch {
195
+ return;
196
+ }
197
+ subject.view = { ...JSON.parse(JSON.stringify(cached)), connected: subject.view.connected };
198
+ this.rememberVerifiedRelation(subject);
199
+ }
200
+ persistCache(subject, invalidate = false) {
201
+ // The daemon is the sole production writer. Short-lived CLI processes may read, never replace its snapshot.
202
+ if (!this.daemonAid && !this.options.cachePath)
203
+ return;
204
+ this.loadCache();
205
+ const view = subject.view;
206
+ if (!invalidate && view.consensusStatus === 'consensus' && view.consensus
207
+ && Number.isSafeInteger(view.consensus.relation_version)
208
+ && /^[a-f0-9]{64}$/.test(view.consensus.agent_md_sha256 ?? '')
209
+ && !view.refreshFailure && view.checkedAt !== undefined) {
210
+ const { subjectAid, ownerAid, consensusStatus, consensus, checkedAt, validUntil, profile, relation } = view;
211
+ this.cacheEntries.set(subjectAid, { subjectAid, ownerAid, consensusStatus, consensus, checkedAt, validUntil,
212
+ profile, relation, authorizationStatus: 'verified', revision: view.revision, connected: false,
213
+ synchronization: { status: 'synced', runtimeOwnerAid: ownerAid } });
214
+ }
215
+ else
216
+ this.cacheEntries.delete(view.subjectAid);
217
+ for (const [aid, cached] of this.cacheEntries) {
218
+ if ((cached.validUntil ?? 0) <= this.now() || cached.checkedAt > this.now())
219
+ this.cacheEntries.delete(aid);
220
+ }
221
+ if (invalidate)
222
+ this.writeCache();
223
+ else if (!this.cacheWriteQueued) {
224
+ const file = this.cacheFile;
225
+ this.cacheWriteQueued = true;
226
+ queueMicrotask(() => {
227
+ if (this.cacheFile !== file || !this.cacheWriteQueued)
228
+ return;
229
+ this.cacheWriteQueued = false;
230
+ this.writeCache();
231
+ });
232
+ }
233
+ }
234
+ writeCache() {
235
+ if (!this.daemonAid && !this.options.cachePath)
236
+ return;
237
+ const content = JSON.stringify({ schemaVersion: 1, savedAt: this.now(), entries: Object.fromEntries(this.cacheEntries) });
238
+ try {
239
+ // Cache evidence is usable only when the strict integrity registration also succeeds.
240
+ registerContent(this.cacheFile, content);
241
+ atomicWrite(this.cacheFile, content);
242
+ fs.chmodSync(this.cacheFile, 0o600);
243
+ }
244
+ catch (error) {
245
+ // Never leave an old usable snapshot behind after a failed revocation write.
246
+ try {
247
+ fs.rmSync(this.cacheFile, { force: true });
248
+ }
249
+ catch { }
250
+ logger.warn(`[ownership] Cache write failed: ${error instanceof Error ? error.message : String(error)}`);
251
+ }
252
+ }
57
253
  setConfiguredOwners(subjectAid, owners) {
58
254
  this.assertAid(subjectAid);
59
255
  const normalized = [...new Set(owners
@@ -121,6 +317,7 @@ export class OwnerResolver {
121
317
  this.detachClient(subjectAid);
122
318
  const subject = this.subject(subjectAid);
123
319
  subject.client = client;
320
+ subject.store = undefined;
124
321
  const connectionState = String(client.state ?? '');
125
322
  subject.view.connected = connected || client.isReady === true || connectionState === 'ready' || connectionState === 'connected';
126
323
  const generation = subject.generation;
@@ -262,13 +459,15 @@ export class OwnerResolver {
262
459
  }
263
460
  subject.client = undefined;
264
461
  subject.view.connected = false;
265
- this.invalidate(subject, 'AUN client is unavailable');
462
+ // A transport replacement must not erase a still-valid restart snapshot.
463
+ this.invalidate(subject, 'AUN client is unavailable', false, false);
266
464
  }
267
465
  owner(subjectAid) {
268
466
  if (!subjectAid)
269
467
  return undefined;
270
468
  const view = this.subjects.get(subjectAid)?.view;
271
469
  return view?.consensusStatus === 'consensus'
470
+ && view.checkedAt !== undefined && view.checkedAt <= this.now()
272
471
  && ((view.validUntil ?? 0) > this.now() || view.refreshFailure?.fallbackUsed === true)
273
472
  ? view.ownerAid : undefined;
274
473
  }
@@ -345,17 +544,23 @@ export class OwnerResolver {
345
544
  }
346
545
  async refresh(subjectAid, options = {}) {
347
546
  const subject = this.subject(subjectAid);
547
+ this.restoreCache(subjectAid, subject);
348
548
  this.refreshConfiguredOwnersFromDisk(subjectAid);
349
549
  const inFlight = subject.refreshing?.epoch === subject.epoch ? subject.refreshing : undefined;
350
550
  const refreshing = inFlight?.promise;
351
551
  const initialEpoch = subject.epoch;
352
552
  const initialCheckedAt = subject.view.checkedAt;
353
553
  const maxAgeMs = options.maxAgeMs ?? this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS;
354
- const isFresh = () => this.isCacheFresh(subject, maxAgeMs);
554
+ const isFresh = () => this.isCacheFresh(subject, maxAgeMs)
555
+ && (!options.requireProfile || !!subject.view.profile);
355
556
  // A valid cache never schedules a supplementary consensus check; identity
356
557
  // verification only runs when the cache is stale or an operation forces it.
357
558
  if (!refreshing && !options.force && isFresh())
358
559
  return this.snapshot(subjectAid);
560
+ if (!refreshing && !options.force && (subject.retryAt ?? 0) > this.now()) {
561
+ return !options.allowTransient && subject.view.refreshFailure
562
+ ? this.unavailableSnapshot(subjectAid, subject.view.refreshFailure) : this.snapshot(subjectAid);
563
+ }
359
564
  const attemptId = inFlight?.attemptId ?? ++subject.query;
360
565
  const attemptedAt = inFlight?.attemptedAt ?? this.now();
361
566
  const caller = new Error().stack?.replace(/\\/g, '/').split('\n')
@@ -371,10 +576,16 @@ export class OwnerResolver {
371
576
  firstObservation: !subject.view.consensus, previousConsensusStatus: subject.view.consensusStatus,
372
577
  configuredOwnerAid: configuredOwners[0], configuredOwnerCount: configuredOwners.length,
373
578
  };
374
- const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic);
579
+ const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic, options);
375
580
  subject.refreshing = { epoch: subject.epoch, attemptId, attemptedAt, diagnostic, promise };
376
581
  try {
377
582
  await promise;
583
+ if (options.requireProfile && !subject.view.profile && !subject.view.refreshFailure
584
+ && subject.view.consensusStatus === 'consensus' && refreshing) {
585
+ if (subject.refreshing?.promise === refreshing)
586
+ subject.refreshing = undefined;
587
+ return this.refresh(subjectAid, options);
588
+ }
378
589
  if (subject.epoch !== initialEpoch && !isFresh()
379
590
  && subject.view.refreshFailure?.attemptId !== attemptId) {
380
591
  if (subject.view.connected)
@@ -398,10 +609,13 @@ export class OwnerResolver {
398
609
  subject.refreshing = undefined;
399
610
  }
400
611
  }
401
- async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic) {
612
+ async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic, options) {
402
613
  logOwnershipEvent('refresh.started', { subjectAid, ...diagnostic });
403
- const client = subject.client;
404
- if (!client || !subject.view.connected) {
614
+ const observer = options.observerAid ? this.subjects.get(options.observerAid) : undefined;
615
+ const transport = subject.client && subject.view.connected && (!options.requireProfile || subject.store)
616
+ ? subject : observer ?? subject;
617
+ const client = transport?.client;
618
+ if (!client || !transport?.view.connected) {
405
619
  const reason = 'Subject AID has no connected SDK client';
406
620
  this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId, diagnostic);
407
621
  return this.snapshot(subjectAid);
@@ -409,17 +623,44 @@ export class OwnerResolver {
409
623
  const generation = subject.generation;
410
624
  const epoch = subject.epoch;
411
625
  const query = attemptId;
626
+ const transportGeneration = transport.generation;
627
+ const transportEpoch = transport.epoch;
412
628
  let timeout;
413
629
  try {
414
- const consensus = await Promise.race([
415
- client.checkOwnershipConsensus(subjectAid, true),
416
- new Promise((_resolve, reject) => {
417
- timeout = setTimeout(() => reject(new OwnershipError('OWNERSHIP_REFRESH_TIMEOUT', 'Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
418
- timeout.unref?.();
419
- }),
420
- ]);
421
- if (subject.client !== client || subject.generation !== generation || subject.epoch !== epoch
422
- || subject.query !== query || !subject.view.connected) {
630
+ const { consensus, profile } = await this.query(async () => {
631
+ if (subject.generation !== generation || subject.epoch !== epoch || transport.client !== client
632
+ || transport.generation !== transportGeneration || transport.epoch !== transportEpoch || !transport.view.connected) {
633
+ throw Object.assign(new Error('Ownership transport changed while queued'), { code: 'CLIENT_DISCONNECTED' });
634
+ }
635
+ return await Promise.race([
636
+ (async () => {
637
+ const consensus = await client.checkOwnershipConsensus(subjectAid, true);
638
+ let profile;
639
+ if ((options.requireProfile || transport.store) && consensus.status === 'consensus') {
640
+ if (!transport.store)
641
+ throw Object.assign(new Error('Verified profile transport is unavailable'), { code: 'UNAVAILABLE' });
642
+ const { agentmdGet } = await import('../../aun/aid/agentmd.js');
643
+ const { parseAgentMdFrontmatter } = await import('../relation/peer-identity.js');
644
+ const card = await agentmdGet(subjectAid, { store: transport.store, withVerification: true, remoteOnly: true });
645
+ const identity = parseAgentMdFrontmatter(card.content);
646
+ const sha256 = createHash('sha256').update(card.content, 'utf8').digest('hex');
647
+ if (card.source !== 'remote' || card.verification.status !== 'verified' || identity.aid !== subjectAid
648
+ || identity.owner !== consensus.owner_aid || sha256 !== consensus.agent_md_sha256) {
649
+ throw Object.assign(new Error('Verified agent.md does not match Ownership consensus'), { code: 'CONSENSUS_MISMATCH' });
650
+ }
651
+ profile = { type: String(identity.type ?? '').trim().toLowerCase(), sha256 };
652
+ }
653
+ return { consensus, profile };
654
+ })(),
655
+ new Promise((_resolve, reject) => {
656
+ timeout = setTimeout(() => reject(new OwnershipError('OWNERSHIP_REFRESH_TIMEOUT', 'Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
657
+ timeout.unref?.();
658
+ }),
659
+ ]);
660
+ });
661
+ if (subject.generation !== generation || subject.epoch !== epoch
662
+ || subject.query !== query || transport.client !== client || transport.generation !== transportGeneration
663
+ || transport.epoch !== transportEpoch || !transport.view.connected) {
423
664
  logOwnershipEvent('refresh.discarded', { subjectAid, ...diagnostic,
424
665
  durationMs: Math.round(Math.max(0, performance.now() - diagnostic.startedAt)), connected: subject.view.connected,
425
666
  });
@@ -453,6 +694,7 @@ export class OwnerResolver {
453
694
  authorizationStatus: ownerAid ? 'verified' : 'unavailable',
454
695
  consensusStatus: consensus.status,
455
696
  consensus: JSON.parse(JSON.stringify(consensus)),
697
+ profile: profile ?? (subject.view.profile?.sha256 === consensus.agent_md_sha256 ? subject.view.profile : undefined),
456
698
  checkedAt,
457
699
  validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
458
700
  revision: subject.view.revision + (previousOwner !== ownerAid
@@ -470,6 +712,9 @@ export class OwnerResolver {
470
712
  },
471
713
  };
472
714
  this.rememberVerifiedRelation(subject);
715
+ subject.failures = 0;
716
+ subject.retryAt = undefined;
717
+ this.persistCache(subject);
473
718
  this.clearConfirmedRequest(subject, consensus, ownerAid);
474
719
  this.clearResolvedRequests(subject, consensus);
475
720
  if (previousOwner !== ownerAid || previousStatus !== consensus.status
@@ -492,7 +737,7 @@ export class OwnerResolver {
492
737
  this.notifyUpdate(subjectAid);
493
738
  }
494
739
  catch (error) {
495
- if (subject.client === client && subject.generation === generation && subject.epoch === epoch && subject.query === query) {
740
+ if (subject.generation === generation && subject.epoch === epoch && subject.query === query) {
496
741
  const reason = error instanceof Error ? error.message : String(error);
497
742
  this.handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId, diagnostic);
498
743
  }
@@ -513,7 +758,7 @@ export class OwnerResolver {
513
758
  const reason = error instanceof Error ? error.message
514
759
  : typeof details.message === 'string' ? details.message : String(error);
515
760
  const code = String(details.stringCode ?? details.code ?? 'OWNERSHIP_REFRESH_FAILED');
516
- const transient = this.isTransientRefreshFailure(error);
761
+ const transient = isTransientOwnershipRefreshFailure(error);
517
762
  // Keep the shared cache intact for ordinary callers; strict waiters receive
518
763
  // an unavailable view for this attempt and cannot consume the fallback.
519
764
  const fallbackUsed = transient && this.canUseTransientAuthorization(subject, attemptedAt);
@@ -539,6 +784,10 @@ export class OwnerResolver {
539
784
  subject.view.refreshFailure = {
540
785
  kind: transient ? 'transient' : 'permanent', code, reason, attemptedAt, attemptId, fallbackUsed,
541
786
  };
787
+ subject.failures = (subject.failures ?? 0) + 1;
788
+ subject.retryAt = transient
789
+ ? attemptedAt + Math.min(60_000, OWNERSHIP_RETRY_BASE_MS * 2 ** Math.min(subject.failures - 1, 4))
790
+ : attemptedAt + OWNERSHIP_RETRY_BASE_MS;
542
791
  this.notifyUpdate(subjectAid);
543
792
  const cause = this.record(details.cause);
544
793
  const transportCode = cause?.code ?? details.code;
@@ -581,27 +830,6 @@ export class OwnerResolver {
581
830
  ? { ownerAid: view.ownerAid, consensus: view.consensus, checkedAt: view.checkedAt, validUntil: view.validUntil }
582
831
  : undefined;
583
832
  }
584
- isTransientRefreshFailure(error) {
585
- const details = error && typeof error === 'object' ? error : {};
586
- const code = String(details.code ?? details.stringCode ?? '').toUpperCase();
587
- const message = error instanceof Error ? error.message
588
- : typeof details.message === 'string' ? details.message : String(error);
589
- if (['INVALID', 'CONFLICT', 'FORBIDDEN', 'NOT_APPLICABLE', 'OWNER_LOCKED', 'TASK_MISMATCH',
590
- 'CONSENSUS_MISMATCH', 'UNSUPPORTED_PROTOCOL', 'PERSISTENCE_UNAVAILABLE'].includes(code))
591
- return false;
592
- if (/projection.*(?:does not match|conflict)|(?:agent|owner)\.md changed (?:while|during)|NS relation changed .*consensus check|digest does not match authoritative observation|Storage material changed during authoritative read/i.test(message))
593
- return false;
594
- if (details.retryable === false)
595
- return false;
596
- if (details.retryable === true)
597
- return true;
598
- return code === 'TIMEOUT' || code === 'NETWORK_ERROR' || code === 'UNAVAILABLE'
599
- || code === 'CLIENT_DISCONNECTED' || code === 'CONNECTION_FAILED'
600
- || code === 'GATEWAY_UNAVAILABLE' || code === 'CONNECTION_UNAVAILABLE'
601
- || code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT'
602
- || code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
603
- || /timed out|timeout|connection reset|connection refused|connection closed|socket hang up|not connected|network error|fetch failed|gateway unavailable|gateway timeout|temporarily unavailable/i.test(message);
604
- }
605
833
  hasRejectedOwnerBinding(subjectAid, ownerAid) {
606
834
  this.assertAid(subjectAid);
607
835
  this.assertAid(ownerAid);
@@ -727,7 +955,7 @@ export class OwnerResolver {
727
955
  }
728
956
  if (subject.transferIntents.has(subAid) || subject.transferTasks.has(subAid)) {
729
957
  const generation = subject.generation;
730
- const current = await this.withSubjectClient(ownerAid, client => client.checkOwnershipConsensus(subAid, true));
958
+ const current = await this.withSubjectClient(ownerAid, client => this.queryConsensus(client, subAid));
731
959
  if (subject.generation !== generation) {
732
960
  throw new OwnershipError('CLIENT_REPLACED', 'Ownership state changed during transfer preflight; retry');
733
961
  }
@@ -858,6 +1086,34 @@ export class OwnerResolver {
858
1086
  throw error;
859
1087
  }
860
1088
  }
1089
+ /** Fresh authorization never refreshes unrelated transfers or falls back to an old relation. */
1090
+ async refreshForAuthorization(subjectAid) {
1091
+ const subject = this.subject(subjectAid);
1092
+ if (subject.client && subject.view.connected) {
1093
+ return this.refresh(subjectAid, { force: true, allowTransient: false, source: 'authorization' });
1094
+ }
1095
+ const epoch = subject.epoch;
1096
+ const existing = this.authorizationChecks.get(subjectAid);
1097
+ if (existing?.epoch === epoch)
1098
+ return existing.promise;
1099
+ const generation = subject.generation;
1100
+ const promise = this.withSubjectClient(subjectAid, async (client) => {
1101
+ const consensus = await this.queryConsensus(client, subjectAid);
1102
+ if (subject.generation !== generation || subject.epoch !== epoch) {
1103
+ throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during authorization; retry');
1104
+ }
1105
+ this.applyConsensus(subjectAid, subject, consensus);
1106
+ return this.snapshot(subjectAid);
1107
+ });
1108
+ this.authorizationChecks.set(subjectAid, { epoch, promise });
1109
+ try {
1110
+ return await promise;
1111
+ }
1112
+ finally {
1113
+ if (this.authorizationChecks.get(subjectAid)?.promise === promise)
1114
+ this.authorizationChecks.delete(subjectAid);
1115
+ }
1116
+ }
861
1117
  async status(subjectAid, options = {}) {
862
1118
  const subject = this.subject(subjectAid);
863
1119
  // Status display reuses the resolve snapshot; consensus verification is
@@ -875,7 +1131,7 @@ export class OwnerResolver {
875
1131
  }
876
1132
  const generation = subject.generation;
877
1133
  return this.withSubjectClient(subjectAid, async (client) => {
878
- const consensus = await client.checkOwnershipConsensus(subjectAid, true);
1134
+ const consensus = await this.queryConsensus(client, subjectAid);
879
1135
  if (subject.generation !== generation) {
880
1136
  throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
881
1137
  }
@@ -890,7 +1146,7 @@ export class OwnerResolver {
890
1146
  const generation = subject.generation;
891
1147
  for (const [subAid, task] of [...subject.transferTasks]) {
892
1148
  try {
893
- const consensus = await client.checkOwnershipConsensus(subAid, true);
1149
+ const consensus = await this.queryConsensus(client, subAid);
894
1150
  if ((attached && subject.client !== client) || subject.generation !== generation
895
1151
  || subject.transferTasks.get(subAid)?.operation_id !== task.operation_id)
896
1152
  return;
@@ -953,6 +1209,10 @@ export class OwnerResolver {
953
1209
  this.subjects.clear();
954
1210
  this.configuredOwners.clear();
955
1211
  this.configuredOwnerFileRevision.clear();
1212
+ this.authorizationChecks.clear();
1213
+ this.cacheEntries.clear();
1214
+ this.cacheFile = undefined;
1215
+ this.cacheWriteQueued = false;
956
1216
  }
957
1217
  async submitBinding(subjectAid, ownerAid, subject, assertCurrent, onSubmissionStart) {
958
1218
  const generation = subject.generation;
@@ -1433,6 +1693,7 @@ export class OwnerResolver {
1433
1693
  relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
1434
1694
  authorizationStatus: ownerAid ? 'verified' : 'unavailable', consensusStatus: consensus.status,
1435
1695
  consensus: JSON.parse(JSON.stringify(consensus)),
1696
+ profile: subject.view.profile?.sha256 === consensus.agent_md_sha256 ? subject.view.profile : undefined,
1436
1697
  checkedAt, validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
1437
1698
  revision: subject.view.revision + (previousOwner !== ownerAid || subject.view.consensusStatus !== consensus.status
1438
1699
  || subject.view.consensus?.relation_version !== consensus.relation_version
@@ -1448,6 +1709,9 @@ export class OwnerResolver {
1448
1709
  },
1449
1710
  };
1450
1711
  this.rememberVerifiedRelation(subject);
1712
+ this.persistCache(subject);
1713
+ subject.retryAt = undefined;
1714
+ subject.failures = 0;
1451
1715
  this.clearConfirmedRequest(subject, consensus, ownerAid);
1452
1716
  this.clearResolvedRequests(subject, consensus);
1453
1717
  if (previousOwner !== ownerAid || previousStatus !== consensus.status
@@ -1491,6 +1755,14 @@ export class OwnerResolver {
1491
1755
  }
1492
1756
  subject(subjectAid) {
1493
1757
  this.assertAid(subjectAid);
1758
+ const rootScope = this.options.cachePath?.() ?? ownershipCachePath();
1759
+ if (this.rootScope && this.rootScope !== rootScope) {
1760
+ this.subjects.clear();
1761
+ this.configuredOwners.clear();
1762
+ this.configuredOwnerFileRevision.clear();
1763
+ this.authorizationChecks.clear();
1764
+ }
1765
+ this.rootScope = rootScope;
1494
1766
  let subject = this.subjects.get(subjectAid);
1495
1767
  if (subject)
1496
1768
  return subject;
@@ -1507,7 +1779,7 @@ export class OwnerResolver {
1507
1779
  this.subjects.set(subjectAid, subject);
1508
1780
  return subject;
1509
1781
  }
1510
- invalidate(subject, reason, preserveVerifiedRelation = false) {
1782
+ invalidate(subject, reason, preserveVerifiedRelation = false, persist = true) {
1511
1783
  const previousOwner = subject.view.ownerAid;
1512
1784
  if (!preserveVerifiedRelation)
1513
1785
  subject.verifiedRelation = undefined;
@@ -1517,7 +1789,11 @@ export class OwnerResolver {
1517
1789
  ...(subject.view.relation ? { relation: { ...subject.view.relation, isCurrent: false } } : {}),
1518
1790
  revision: subject.view.revision + 1, reason, refreshFailure: undefined,
1519
1791
  synchronization: { status: 'unavailable' },
1792
+ profile: undefined,
1520
1793
  };
1794
+ subject.retryAt = undefined;
1795
+ if (persist)
1796
+ this.persistCache(subject, true);
1521
1797
  if (previousOwner)
1522
1798
  this.notify(subject.view.subjectAid);
1523
1799
  this.notifyUpdate(subject.view.subjectAid);
@@ -1550,7 +1826,7 @@ export class OwnerResolver {
1550
1826
  }
1551
1827
  invalidateRelatedSubjects(changedAid, targetAid) {
1552
1828
  for (const [subjectAid, subject] of this.subjects) {
1553
- if (!subject.client || !subject.view.connected || (targetAid && targetAid !== subjectAid))
1829
+ if (targetAid && targetAid !== subjectAid)
1554
1830
  continue;
1555
1831
  const ownerAid = subject.view.relation?.ownerAid;
1556
1832
  if ((!targetAid && changedAid === subjectAid) || changedAid === ownerAid
@@ -1741,15 +2017,17 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
1741
2017
  return views;
1742
2018
  }
1743
2019
  export async function assertOwnershipAuthorization(context) {
2020
+ await context?.revalidateExecutionIdentity?.();
1744
2021
  if (context?.internalContactAuthorization && context.selfAid && context.actor?.principalId) {
1745
- const { prepareSameOwnerProof } = await import('../relation/same-owner-proof.js');
1746
- const { resolvePeerRoleDetail } = await import('../../config/peer-role-resolver.js');
2022
+ const { resolveFreshPeerRoleDetail } = await import('../../config/peer-role-resolver.js');
1747
2023
  const { getRoleDefinition } = await import('../../config/roles.js');
1748
- await prepareSameOwnerProof(context.selfAid, context.actor.principalId);
1749
- const current = resolvePeerRoleDetail({
2024
+ const current = await resolveFreshPeerRoleDetail({
1750
2025
  selfAid: context.selfAid, channelKey: context.actor.operatorChannelKey, channelType: 'aun',
1751
2026
  chatType: 'private', actorId: context.actor.principalId, conversationId: context.actor.principalId,
1752
2027
  });
2028
+ if (current.authorizationFailure) {
2029
+ throw Object.assign(new OwnershipError('INTERNAL_CONTACT_AUTHORIZATION_UNAVAILABLE', current.authorizationFailure.reason), { retryable: current.authorizationFailure.retryable });
2030
+ }
1753
2031
  if (!current.allowAccess || current.effectiveRole !== context.role
1754
2032
  || (context.internalContactDefaultRole && current.source !== 'internal-contact-default')
1755
2033
  || (context.internalContactPolicy !== undefined && context.internalContactPolicy !== JSON.stringify(getRoleDefinition(context.role ?? '', context.selfAid)))) {
@@ -43,7 +43,7 @@ const L_CLASS_RELATIVE_PATTERNS = [
43
43
  /^daemon\.json$/,
44
44
  /^agents\/defaults\.json$/,
45
45
  /^agents\/[^/]+\/config\.json$/,
46
- /^agents\/[^/]+\/contact\.json$/,
46
+ /^agents\/[^/]+\/(?:contact|peers)\.json$/,
47
47
  /^agents\/[^/]+\/contact-operations\.jsonl$/,
48
48
  /^agents\/[^/]+\/relations\/[^/]+\/config\.json$/,
49
49
  /^backups\/config(?:\/|$)/,
@@ -54,7 +54,7 @@ const L_CLASS_RELATIVE_PATTERNS = [
54
54
  ];
55
55
  const L_CLASS_REFERENCE_PATTERNS = [
56
56
  /(?:^|[^A-Za-z0-9_.-])daemon\.json(?=$|[^A-Za-z0-9_.-])/,
57
- /(?:^|[^A-Za-z0-9_.-])agents[\\/](?:defaults\.json|[^/\\\s"']+[\\/](?:(?:config|contact)\.json|contact-operations\.jsonl|relations[\\/][^/\\\s"']+[\\/]config\.json))(?=$|[\s"';&|<>)},])/,
57
+ /(?:^|[^A-Za-z0-9_.-])agents[\\/](?:defaults\.json|[^/\\\s"']+[\\/](?:(?:config|contact|peers)\.json|contact-operations\.jsonl|relations[\\/][^/\\\s"']+[\\/]config\.json))(?=$|[\s"';&|<>)},])/,
58
58
  /(?:^|[^A-Za-z0-9_.-])backups[\\/]config(?:[\\/]|$|[\s"';&|<>)},])/,
59
59
  /(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]triggers(?:[\\/]|$|[\s"';&|<>)},])/,
60
60
  /(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]roles(?:[\\/]|$|[\s"';&|<>)},])/,
@@ -375,7 +375,7 @@ function getLegacyHClassSandboxPatterns(root) {
375
375
  'daemon.json',
376
376
  path.join('agents', 'defaults.json'),
377
377
  path.join('agents', '*', 'config.json'),
378
- path.join('agents', '*', 'contact.json'),
378
+ path.join('agents', '*', 'contact.json'), path.join('agents', '*', 'peers.json'),
379
379
  path.join('agents', '*', 'contact-operations.jsonl'),
380
380
  path.join('agents', '*', 'relations', '*', 'config.json'),
381
381
  path.join('backups', 'config'), path.join('backups', 'config', '**'),
@@ -560,7 +560,7 @@ export function getExistingHClassMaskTargets(root = resolveRoot(), options = {})
560
560
  if (!entry.isDirectory())
561
561
  continue;
562
562
  const agentRoot = path.join(agentsDir, entry.name);
563
- for (const fileName of ['config.json', 'config.json_', 'contact.json', 'contact.json_', 'contact-operations.jsonl']) {
563
+ for (const fileName of ['config.json', 'config.json_', 'contact.json', 'contact.json_', 'peers.json', 'peers.json_', 'contact-operations.jsonl']) {
564
564
  addExistingTarget(targets, path.join(agentRoot, fileName));
565
565
  }
566
566
  const relationsDir = path.join(agentRoot, 'relations');
@@ -614,7 +614,7 @@ export function getExistingLClassReadOnlyTargets(root = resolveRoot(), options =
614
614
  }
615
615
  const ownRoot = path.join(agentsDir, selfAid);
616
616
  for (const relative of [
617
- 'config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services',
617
+ 'config.json', 'contact.json', 'peers.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services',
618
618
  ])
619
619
  addExistingTarget(targets, path.join(ownRoot, relative));
620
620
  try {
@@ -1027,7 +1027,7 @@ export function lClassGrantIncludesProtectedPath(value, options = {}) {
1027
1027
  // relations/<peer> 本身时才覆盖它,更深的路径(如 relations/<peer>/memory/…)不会。
1028
1028
  if (segments[2] === 'relations')
1029
1029
  return segments.length <= 4;
1030
- return ['config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services']
1030
+ return ['config.json', 'contact.json', 'peers.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services']
1031
1031
  .includes(segments[2]);
1032
1032
  }
1033
1033
  return false;