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
@@ -1,16 +1,14 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { randomUUID } from 'crypto';
4
- import { resolvePaths } from '../../paths.js';
4
+ import { agentOwnerBindingRejectionPath, 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
- import { logger } from '../../utils/logger.js';
8
+ import { logger, logOwnershipEvent, ownershipErrorCode } from '../../utils/logger.js';
9
9
  import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
10
10
  export const OWNERSHIP_CACHE_MAX_AGE_MS = 30 * 60_000;
11
11
  export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS = 5 * 60_000;
12
- // Background refreshes should heal a short outage without retrying on every tool call.
13
- const OWNERSHIP_BACKGROUND_REFRESH_MIN_INTERVAL_MS = 60_000;
14
12
  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;
15
13
  /** Only use the task returned by this create's bind call. Never select a latest task. */
16
14
  export function creationOwnershipBinding(task, subjectAid, ownerAid) {
@@ -41,10 +39,11 @@ export class OwnerResolver {
41
39
  options;
42
40
  subjects = new Map();
43
41
  daemonAid;
44
- /** Local owner configuration remains an independent authorization source during rollout. */
42
+ /** Compatibility binding targets loaded from config; never an Owner authorization source. */
45
43
  configuredOwners = new Map();
46
44
  configuredOwnerFileRevision = new Map();
47
45
  listeners = new Set();
46
+ updateListeners = new Set();
48
47
  constructor(options = {}) {
49
48
  this.options = options;
50
49
  }
@@ -68,9 +67,10 @@ export class OwnerResolver {
68
67
  else
69
68
  this.configuredOwners.delete(subjectAid);
70
69
  const subject = this.subjects.get(subjectAid);
71
- if (subject) {
72
- this.invalidate(subject, 'Configured Owners changed; fresh consensus is required');
73
- this.schedule(subjectAid, subject);
70
+ const removesConfirmedTarget = normalized.length === 0 && subject?.verifiedRelation
71
+ && previous.every(owner => owner === subject.verifiedRelation.ownerAid);
72
+ if (subject && !removesConfirmedTarget) {
73
+ this.invalidate(subject, 'Configured Owners changed; fresh consensus is required', true);
74
74
  }
75
75
  }
76
76
  setAgentConfiguredOwners(subjectAid, owners) {
@@ -88,7 +88,12 @@ export class OwnerResolver {
88
88
  isOwner(subjectAid, ownerAid) {
89
89
  if (!subjectAid || !ownerAid)
90
90
  return false;
91
- return this.owners(subjectAid).includes(ownerAid);
91
+ if (subjectAid === ownerAid && this.owner(subjectAid) === subjectAid)
92
+ return true;
93
+ if (this.protocolOwners(subjectAid).includes(ownerAid))
94
+ return true;
95
+ return !this.hasObservedProtocolConsensus(subjectAid)
96
+ && this.configuredOwnerList(subjectAid).includes(ownerAid);
92
97
  }
93
98
  assertLocalSubject(subjectAid) {
94
99
  this.assertAid(subjectAid);
@@ -100,6 +105,11 @@ export class OwnerResolver {
100
105
  this.listeners.add(listener);
101
106
  return () => { this.listeners.delete(listener); };
102
107
  }
108
+ /** Includes invalidation and recovery even when the verified Owner stays the same. */
109
+ onUpdate(listener) {
110
+ this.updateListeners.add(listener);
111
+ return () => { this.updateListeners.delete(listener); };
112
+ }
103
113
  attachClient(subjectAid, client, connected = false) {
104
114
  this.assertAid(subjectAid);
105
115
  const clientAid = client.currentAid;
@@ -121,32 +131,70 @@ export class OwnerResolver {
121
131
  const record = this.record(payload);
122
132
  if (!record)
123
133
  return;
134
+ const task = this.task(record, event);
135
+ if (task?.operation === 'transfer'
136
+ && subject.transferTerminalOperations.get(task.sub_aid)?.has(task.operation_id))
137
+ return;
124
138
  this.trackBindingRequest(subjectAid, subject, event, record);
125
- // When this AID is the prospective owner, the request concerns the
126
- // remote sub's ownership, not this AID's own Owner authorization.
127
- if (record.sub_aid !== subjectAid)
139
+ // A transfer is initiated by the current Owner, while its sub is a
140
+ // different AID. Keep the Owner's local task projection in sync, but
141
+ // do not invalidate the Owner's own authorization merely because the
142
+ // remote sub emitted a progress event.
143
+ const isTransferOwnerEvent = task?.operation === 'transfer' && task.owner_aid === subjectAid
144
+ && (subject.transferIntents.get(task.sub_aid) === task.new_owner_aid
145
+ || subject.transferTasks.get(task.sub_aid)?.operation_id === task.operation_id);
146
+ if (record.sub_aid !== subjectAid && !isTransferOwnerEvent)
128
147
  return;
129
148
  if (typeof record.operation_id === 'string') {
130
149
  const key = JSON.stringify([event, record.operation_id, record.step, record.status,
131
- record.owner_aid, record.relation_version, record.code, record.reason]);
150
+ record.owner_aid, record.new_owner_aid, record.relation_version, record.code]);
132
151
  if (subject.taskEvents.has(key))
133
152
  return;
134
153
  subject.taskEvents.add(key);
135
154
  if (subject.taskEvents.size > 256)
136
155
  subject.taskEvents.delete(subject.taskEvents.values().next().value);
137
156
  }
138
- this.invalidate(subject, 'Ownership changed; fresh consensus is required');
139
- const task = this.task(record, event);
140
- logger.info(`[ownership] ${event} ${JSON.stringify({ subjectAid, ownerAid: task?.owner_aid,
157
+ if (event === 'ownership.rejected' && task?.operation === 'bind'
158
+ && task.sub_aid === subjectAid && task.status === 'rejected') {
159
+ this.rememberRejectedOwnerBinding(task);
160
+ }
161
+ if (record.sub_aid === subjectAid) {
162
+ this.invalidate(subject, 'Ownership changed; fresh consensus is required', true);
163
+ }
164
+ logOwnershipEvent('task.changed', { subjectAid, ownerAid: task?.owner_aid, eventType: event,
141
165
  operationId: task?.operation_id, taskStatus: task?.status, step: task?.step,
142
- code: task?.code, reason: task?.reason })}`);
143
- if (task && subject.view.requestedOwnerAid === task.owner_aid
166
+ relationVersion: task?.target_relation_version, errorCode: task?.code,
167
+ }, task?.status === 'error' || task?.status === 'stopped' || task?.status === 'rejected');
168
+ const terminalTaskEvent = subject.view.task?.status === 'completed'
169
+ && subject.view.task.step === 'local_actions'
170
+ && ['ownership.rejected', 'ownership.stopped'].includes(event);
171
+ const requestedParticipant = task?.operation === 'transfer' ? task.new_owner_aid : task?.owner_aid;
172
+ if (task && subject.view.requestedOwnerAid === requestedParticipant
144
173
  && (!subject.view.task || (subject.view.task.operation_id === task.operation_id
145
- && (subject.view.task.status === 'pending' || subject.view.task.status === task.status)))) {
174
+ && (subject.view.task.status === 'pending'
175
+ || subject.view.task.status === task.status || terminalTaskEvent)))) {
146
176
  subject.view.task = task;
147
177
  subject.view.requestStatus = 'submitted';
148
178
  }
149
- this.schedule(subjectAid, subject);
179
+ if (isTransferOwnerEvent) {
180
+ subject.transferTasks.set(task.sub_aid, task);
181
+ subject.transferIntents.set(task.sub_aid, task.new_owner_aid);
182
+ this.syncTransferViews(subject);
183
+ subject.view.task = task;
184
+ subject.view.requestedOwnerAid = task.new_owner_aid;
185
+ subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
186
+ subject.view.reason = task.reason;
187
+ if (task.status === 'rejected' || task.status === 'stopped'
188
+ || (task.status === 'error' && task.retryable !== true)) {
189
+ this.markTransferTerminal(subject, task.sub_aid, task.operation_id);
190
+ subject.transferTasks.delete(task.sub_aid);
191
+ subject.transferIntents.delete(task.sub_aid);
192
+ subject.transferConsensuses.delete(task.sub_aid);
193
+ if (subject.view.task?.operation_id === task.operation_id)
194
+ this.restoreLatestTransferView(subject);
195
+ this.syncTransferViews(subject);
196
+ }
197
+ }
150
198
  }));
151
199
  }
152
200
  subject.subscriptions.push(client.on('agentmd.changed', payload => {
@@ -182,8 +230,6 @@ export class OwnerResolver {
182
230
  this.setConnected(subjectAid, client, false);
183
231
  }));
184
232
  }
185
- if (subject.view.connected)
186
- this.schedule(subjectAid, subject);
187
233
  }
188
234
  setConnected(subjectAid, client, connected) {
189
235
  const subject = this.subjects.get(subjectAid);
@@ -195,22 +241,14 @@ export class OwnerResolver {
195
241
  // Transport loss does not revoke unexpired consensus. Retire work from
196
242
  // the old connection without clearing the cached authorization.
197
243
  subject.epoch += 1;
198
- if (subject.timer)
199
- clearTimeout(subject.timer);
200
- subject.timer = undefined;
201
244
  }
202
245
  subject.view.connected = connected;
203
- if (connected)
204
- this.schedule(subjectAid, subject);
205
246
  }
206
247
  detachClient(subjectAid, client) {
207
248
  const subject = this.subjects.get(subjectAid);
208
249
  if (!subject || (client && subject.client !== client))
209
250
  return;
210
251
  subject.generation += 1;
211
- if (subject.timer)
212
- clearTimeout(subject.timer);
213
- subject.timer = undefined;
214
252
  subject.taskEvents.clear();
215
253
  subject.requests.clear();
216
254
  subject.decisionTasks.clear();
@@ -230,29 +268,46 @@ export class OwnerResolver {
230
268
  return undefined;
231
269
  const view = this.subjects.get(subjectAid)?.view;
232
270
  return view?.consensusStatus === 'consensus'
233
- && (view.validUntil ?? 0) > this.now() ? view.ownerAid : undefined;
271
+ && ((view.validUntil ?? 0) > this.now() || view.refreshFailure?.fallbackUsed === true)
272
+ ? view.ownerAid : undefined;
234
273
  }
235
274
  owners(subjectAid) {
236
275
  if (!subjectAid)
237
276
  return [];
238
- return [...new Set([
239
- ...this.configuredOwnerList(subjectAid),
240
- ...this.protocolOwners(subjectAid),
241
- ])];
277
+ const protocol = this.protocolOwners(subjectAid);
278
+ if (protocol.length > 0 || this.hasObservedProtocolConsensus(subjectAid))
279
+ return protocol;
280
+ return this.configuredOwnerList(subjectAid);
242
281
  }
243
282
  protocolOwners(subjectAid) {
244
283
  const owner = this.owner(subjectAid);
245
284
  return owner ? [owner] : [];
246
285
  }
286
+ /** True once this process has observed an established protocol relation. */
287
+ hasObservedProtocolConsensus(subjectAid) {
288
+ if (!subjectAid)
289
+ return false;
290
+ const subject = this.subjects.get(subjectAid);
291
+ const relation = subject?.view.relation;
292
+ return !!relation
293
+ && relation.relationVersion > 0
294
+ && (relation.consensusStatus === 'consensus' || relation.consensusStatus === 'released');
295
+ }
247
296
  primaryOwner(subjectAid) {
248
297
  return this.owners(subjectAid)[0];
249
298
  }
250
299
  knownOwners(subjectAid) {
251
300
  if (!subjectAid)
252
301
  return [];
253
- const configuredOwners = this.configuredOwnerList(subjectAid);
254
- const ownerAid = this.subjects.get(subjectAid)?.view.relation?.ownerAid;
255
- return [...new Set([...configuredOwners, ...(ownerAid ? [ownerAid] : [])])];
302
+ const protocol = this.protocolOwners(subjectAid);
303
+ if (protocol.length > 0)
304
+ return protocol;
305
+ const relation = this.subjects.get(subjectAid)?.view.relation;
306
+ if (relation?.consensusStatus === 'consensus' && relation.ownerAid)
307
+ return [relation.ownerAid];
308
+ if (this.hasObservedProtocolConsensus(subjectAid))
309
+ return [];
310
+ return this.configuredOwnerList(subjectAid);
256
311
  }
257
312
  knownOwner(subjectAid) {
258
313
  return this.knownOwners(subjectAid)[0];
@@ -290,37 +345,42 @@ export class OwnerResolver {
290
345
  async refresh(subjectAid, options = {}) {
291
346
  const subject = this.subject(subjectAid);
292
347
  this.refreshConfiguredOwnersFromDisk(subjectAid);
293
- if (subject.timer)
294
- clearTimeout(subject.timer);
295
- subject.timer = undefined;
296
348
  const inFlight = subject.refreshing?.epoch === subject.epoch ? subject.refreshing : undefined;
297
349
  const refreshing = inFlight?.promise;
298
350
  const initialEpoch = subject.epoch;
299
351
  const initialCheckedAt = subject.view.checkedAt;
300
352
  const maxAgeMs = options.maxAgeMs ?? this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS;
301
- const isFresh = () => {
302
- const { checkedAt, validUntil, consensusStatus } = subject.view;
303
- const now = this.now();
304
- return consensusStatus !== 'unavailable' && consensusStatus !== 'not_applicable'
305
- && checkedAt !== undefined && checkedAt <= now && (validUntil ?? 0) > now
306
- && now - checkedAt < maxAgeMs;
307
- };
308
- if (!refreshing && !options.force && isFresh()) {
309
- if (options.allowTransient
310
- && this.now() - (subject.lastRefreshAttemptAt ?? 0) >= OWNERSHIP_BACKGROUND_REFRESH_MIN_INTERVAL_MS) {
311
- this.schedule(subjectAid, subject, true);
312
- }
353
+ const isFresh = () => this.isCacheFresh(subject, maxAgeMs);
354
+ // A valid cache never schedules a supplementary consensus check; identity
355
+ // verification only runs when the cache is stale or an operation forces it.
356
+ if (!refreshing && !options.force && isFresh())
313
357
  return this.snapshot(subjectAid);
314
- }
315
358
  const attemptId = inFlight?.attemptId ?? ++subject.query;
316
359
  const attemptedAt = inFlight?.attemptedAt ?? this.now();
317
- const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt);
318
- subject.refreshing = { epoch: subject.epoch, attemptId, attemptedAt, promise };
360
+ const caller = new Error().stack?.replace(/\\/g, '/').split('\n')
361
+ .filter(frame => !/\/core\/ownership\/owner-resolver\.[cm]?[jt]s:/.test(frame))
362
+ .map(frame => frame.match(/\/((?:src|dist)\/[a-zA-Z0-9_./-]+\.[cm]?[jt]s:\d+:\d+)/)?.[1])
363
+ .find(frame => !!frame);
364
+ const configuredOwners = this.configuredOwnerList(subjectAid);
365
+ const diagnostic = inFlight?.diagnostic ?? {
366
+ startedAt: performance.now(), source: options.source ?? 'direct', caller,
367
+ attemptId, processId: process.pid, connected: subject.view.connected,
368
+ sdkReady: subject.client?.isReady === true,
369
+ force: !!options.force, maxAgeMs, timeoutMs: this.options.timeoutMs ?? 8_000,
370
+ firstObservation: !subject.view.consensus, previousConsensusStatus: subject.view.consensusStatus,
371
+ configuredOwnerAid: configuredOwners[0], configuredOwnerCount: configuredOwners.length,
372
+ };
373
+ const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic);
374
+ subject.refreshing = { epoch: subject.epoch, attemptId, attemptedAt, diagnostic, promise };
319
375
  try {
320
376
  await promise;
321
- if (subject.epoch !== initialEpoch && subject.view.consensusStatus === 'consensus'
322
- && subject.view.checkedAt === initialCheckedAt) {
323
- this.handleRefreshFailure(subjectAid, subject, Object.assign(new Error('Ownership refresh was interrupted by a connection state change'), { code: 'CLIENT_DISCONNECTED' }), attemptedAt, attemptId);
377
+ if (subject.epoch !== initialEpoch && !isFresh()
378
+ && subject.view.refreshFailure?.attemptId !== attemptId) {
379
+ if (subject.view.connected)
380
+ return this.refresh(subjectAid, options);
381
+ if (subject.view.checkedAt === initialCheckedAt) {
382
+ this.handleRefreshFailure(subjectAid, subject, Object.assign(new Error('Ownership refresh was interrupted by a connection state change'), { code: 'CLIENT_DISCONNECTED' }), attemptedAt, attemptId, diagnostic);
383
+ }
324
384
  }
325
385
  if (!subject.view.connected && subject.view.consensusStatus === 'consensus' && !isFresh()
326
386
  && subject.view.refreshFailure?.fallbackUsed !== true) {
@@ -337,12 +397,12 @@ export class OwnerResolver {
337
397
  subject.refreshing = undefined;
338
398
  }
339
399
  }
340
- async refreshSubject(subjectAid, subject, attemptId, attemptedAt) {
400
+ async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic) {
401
+ logOwnershipEvent('refresh.started', { subjectAid, ...diagnostic });
341
402
  const client = subject.client;
342
- subject.lastRefreshAttemptAt = attemptedAt;
343
403
  if (!client || !subject.view.connected) {
344
404
  const reason = 'Subject AID has no connected SDK client';
345
- this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId);
405
+ this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId, diagnostic);
346
406
  return this.snapshot(subjectAid);
347
407
  }
348
408
  const generation = subject.generation;
@@ -353,16 +413,20 @@ export class OwnerResolver {
353
413
  const consensus = await Promise.race([
354
414
  client.checkOwnershipConsensus(subjectAid),
355
415
  new Promise((_resolve, reject) => {
356
- timeout = setTimeout(() => reject(new Error('Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
416
+ timeout = setTimeout(() => reject(new OwnershipError('OWNERSHIP_REFRESH_TIMEOUT', 'Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
357
417
  timeout.unref?.();
358
418
  }),
359
419
  ]);
360
420
  if (subject.client !== client || subject.generation !== generation || subject.epoch !== epoch
361
- || subject.query !== query || !subject.view.connected)
421
+ || subject.query !== query || !subject.view.connected) {
422
+ logOwnershipEvent('refresh.discarded', { subjectAid, ...diagnostic,
423
+ durationMs: Math.round(Math.max(0, performance.now() - diagnostic.startedAt)), connected: subject.view.connected,
424
+ });
362
425
  return this.snapshot(subjectAid);
426
+ }
363
427
  const ownerAid = consensus.status === 'consensus' && consensus.sub_aid === subjectAid
364
428
  && typeof consensus.owner_aid === 'string' && isValidAid(consensus.owner_aid)
365
- && consensus.owner_aid !== subjectAid ? consensus.owner_aid : undefined;
429
+ ? consensus.owner_aid : undefined;
366
430
  if (consensus.sub_aid !== subjectAid || (consensus.status === 'consensus' && !ownerAid)) {
367
431
  throw new Error('Ownership consensus contains a mismatched subject or invalid owner');
368
432
  }
@@ -373,19 +437,18 @@ export class OwnerResolver {
373
437
  const reason = consensus.reason ?? 'Ownership consensus is temporarily unavailable';
374
438
  this.handleRefreshFailure(subjectAid, subject, {
375
439
  code: consensus.code ?? 'UNAVAILABLE', message: reason, retryable: true,
376
- }, attemptedAt, attemptId);
440
+ }, attemptedAt, attemptId, diagnostic);
377
441
  return this.snapshot(subjectAid);
378
442
  }
379
443
  const previousOwner = this.owner(subjectAid);
380
444
  const previousStatus = subject.view.consensusStatus;
445
+ const previousConsensus = subject.view.consensus;
381
446
  const checkedAt = this.now();
382
447
  const pending = subject.view.task?.status === 'pending' || subject.view.requestStatus === 'requesting';
383
448
  subject.view = {
384
449
  ...subject.view,
385
450
  ownerAid,
386
- relation: consensus.status === 'consensus' || consensus.status === 'unbound' || consensus.status === 'released'
387
- ? { consensusStatus: consensus.status, ownerAid, checkedAt, relationVersion: consensus.relation_version }
388
- : subject.view.relation,
451
+ relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
389
452
  authorizationStatus: ownerAid ? 'verified' : 'unavailable',
390
453
  consensusStatus: consensus.status,
391
454
  consensus: JSON.parse(JSON.stringify(consensus)),
@@ -405,16 +468,37 @@ export class OwnerResolver {
405
468
  runtimeOwnerAid: ownerAid,
406
469
  },
407
470
  };
471
+ this.rememberVerifiedRelation(subject);
472
+ this.clearConfirmedRequest(subject, consensus, ownerAid);
473
+ this.clearResolvedRequests(subject, consensus);
474
+ if (previousOwner !== ownerAid || previousStatus !== consensus.status
475
+ || previousConsensus?.relation_version !== consensus.relation_version
476
+ || previousConsensus?.lock !== consensus.lock) {
477
+ logOwnershipEvent('consensus.changed', { subjectAid, ownerAid, ...diagnostic,
478
+ consensusStatus: consensus.status, relationVersion: consensus.relation_version, lock: consensus.lock,
479
+ });
480
+ }
481
+ const durationMs = Math.round(Math.max(0, performance.now() - diagnostic.startedAt));
482
+ logOwnershipEvent('refresh.completed', { subjectAid, ownerAid, ...diagnostic,
483
+ consensusStatus: consensus.status, relationVersion: consensus.relation_version, lock: consensus.lock,
484
+ durationMs, slow: durationMs >= 1_000,
485
+ ...(consensus.status === 'unbound' ? {
486
+ unboundCause: consensus.agent_md_sha256 ? 'signed_declaration_missing' : 'agent_card_missing',
487
+ } : {}),
488
+ }, durationMs >= 1_000);
408
489
  if (previousOwner !== ownerAid || previousStatus !== consensus.status)
409
490
  this.notify(subjectAid, ownerAid);
410
- if (ownerAid === subject.view.requestedOwnerAid && subject.view.requestStatus === 'interrupted') {
411
- subject.view.requestStatus = 'submitted';
412
- }
491
+ this.notifyUpdate(subjectAid);
413
492
  }
414
493
  catch (error) {
415
494
  if (subject.client === client && subject.generation === generation && subject.epoch === epoch && subject.query === query) {
416
495
  const reason = error instanceof Error ? error.message : String(error);
417
- this.handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId);
496
+ this.handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId, diagnostic);
497
+ }
498
+ else {
499
+ logOwnershipEvent('refresh.discarded', { subjectAid, ...diagnostic,
500
+ durationMs: Math.round(Math.max(0, performance.now() - diagnostic.startedAt)), connected: subject.view.connected,
501
+ });
418
502
  }
419
503
  }
420
504
  finally {
@@ -423,7 +507,7 @@ export class OwnerResolver {
423
507
  }
424
508
  return this.snapshot(subjectAid);
425
509
  }
426
- handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId) {
510
+ handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId, diagnostic) {
427
511
  const details = error && typeof error === 'object' ? error : {};
428
512
  const reason = error instanceof Error ? error.message
429
513
  : typeof details.message === 'string' ? details.message : String(error);
@@ -432,17 +516,45 @@ export class OwnerResolver {
432
516
  // Keep the shared cache intact for ordinary callers; strict waiters receive
433
517
  // an unavailable view for this attempt and cannot consume the fallback.
434
518
  const fallbackUsed = transient && this.canUseTransientAuthorization(subject, attemptedAt);
435
- if (!fallbackUsed)
436
- this.invalidate(subject, reason);
437
- subject.view.refreshFailure = {
438
- kind: transient ? 'transient' : 'permanent', code, reason, attemptedAt, attemptId, fallbackUsed,
439
- };
440
519
  if (fallbackUsed) {
441
- logger.warn(`[ownership] transient refresh failure subject=${subjectAid} attempt=${attemptId} code=${code} fallback=true reason=${reason}`);
520
+ const verified = subject.verifiedRelation;
521
+ subject.view = {
522
+ ...subject.view,
523
+ ownerAid: verified.ownerAid,
524
+ consensusStatus: 'consensus',
525
+ consensus: verified.consensus,
526
+ checkedAt: verified.checkedAt,
527
+ validUntil: verified.validUntil,
528
+ ...(subject.view.relation ? { relation: { ...subject.view.relation, isCurrent: false } } : {}),
529
+ authorizationStatus: 'expired',
530
+ reason,
531
+ synchronization: { status: 'unavailable' },
532
+ revision: subject.view.revision + 1,
533
+ };
442
534
  }
443
535
  else {
444
- logger.warn(`[ownership] refresh failed subject=${subjectAid} attempt=${attemptId} code=${code} transient=${transient} reason=${reason}`);
536
+ this.invalidate(subject, reason);
445
537
  }
538
+ subject.view.refreshFailure = {
539
+ kind: transient ? 'transient' : 'permanent', code, reason, attemptedAt, attemptId, fallbackUsed,
540
+ };
541
+ this.notifyUpdate(subjectAid);
542
+ const cause = this.record(details.cause);
543
+ const transportCode = cause?.code ?? details.code;
544
+ const httpStatus = /\bHTTP\s+(\d{3})\b/i.exec(reason)?.[1];
545
+ const failureKind = /timed out|timeout/i.test(reason) ? 'timeout'
546
+ : ['EAI_AGAIN', 'ENOTFOUND'].includes(String(transportCode)) ? 'dns'
547
+ : code === 'CLIENT_DISCONNECTED' || /ECONN|ENETUNREACH|EHOSTUNREACH/.test(String(transportCode)) ? 'connection'
548
+ : /certificate|\bTLS\b|\bSSL\b/i.test(reason) ? 'tls'
549
+ : httpStatus ? 'http' : /projection/i.test(reason) ? 'projection'
550
+ : /metadata/i.test(reason) ? 'metadata' : /signature|verify|verification|digest/i.test(reason) ? 'verification'
551
+ : details.code !== undefined || details.stringCode !== undefined ? 'sdk' : 'unknown';
552
+ logOwnershipEvent('refresh.failed', { subjectAid, ownerAid: subject.view.relation?.ownerAid, ...diagnostic,
553
+ consensusStatus: subject.view.consensusStatus, relationVersion: subject.view.consensus?.relation_version,
554
+ errorCode: ownershipErrorCode(error, 'OWNERSHIP_REFRESH_FAILED'), transient, fallbackUsed,
555
+ durationMs: Math.round(Math.max(0, performance.now() - diagnostic.startedAt)), failureKind, transportCode,
556
+ ...(httpStatus ? { httpStatus: Number(httpStatus) } : {}),
557
+ }, true);
446
558
  }
447
559
  unavailableSnapshot(subjectAid, failure) {
448
560
  const view = this.snapshot(subjectAid);
@@ -450,20 +562,23 @@ export class OwnerResolver {
450
562
  view.consensusStatus = 'unavailable';
451
563
  view.authorizationStatus = 'unavailable';
452
564
  view.validUntil = undefined;
565
+ if (view.relation)
566
+ view.relation.isCurrent = false;
453
567
  view.reason = failure.reason;
454
568
  view.synchronization = { status: 'unavailable' };
455
569
  return view;
456
570
  }
457
571
  canUseTransientAuthorization(subject, attemptedAt) {
458
- const view = subject.view;
572
+ const verified = subject.verifiedRelation;
459
573
  const now = this.now();
460
- return view.consensusStatus === 'consensus'
461
- && !!view.ownerAid
462
- && view.checkedAt !== undefined
463
- && view.checkedAt <= attemptedAt
464
- && view.checkedAt <= now
465
- && now - view.checkedAt < OWNERSHIP_AUTHORIZATION_MAX_AGE_MS
466
- && (view.validUntil ?? 0) > now;
574
+ return !!verified && verified.checkedAt <= attemptedAt && verified.checkedAt <= now;
575
+ }
576
+ rememberVerifiedRelation(subject) {
577
+ const view = subject.view;
578
+ subject.verifiedRelation = view.consensusStatus === 'consensus' && view.ownerAid && view.consensus
579
+ && view.consensus.lock === 'locked' && view.checkedAt !== undefined && view.validUntil !== undefined
580
+ ? { ownerAid: view.ownerAid, consensus: view.consensus, checkedAt: view.checkedAt, validUntil: view.validUntil }
581
+ : undefined;
467
582
  }
468
583
  isTransientRefreshFailure(error) {
469
584
  const details = error && typeof error === 'object' ? error : {};
@@ -486,31 +601,169 @@ export class OwnerResolver {
486
601
  || code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
487
602
  || /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);
488
603
  }
489
- async bind(subjectAid, ownerAid) {
604
+ hasRejectedOwnerBinding(subjectAid, ownerAid) {
605
+ this.assertAid(subjectAid);
606
+ this.assertAid(ownerAid);
607
+ return fs.existsSync(agentOwnerBindingRejectionPath(subjectAid, ownerAid));
608
+ }
609
+ rememberRejectedOwnerBinding(task) {
610
+ const file = agentOwnerBindingRejectionPath(task.sub_aid, task.owner_aid);
611
+ try {
612
+ fs.mkdirSync(path.dirname(file), { recursive: true });
613
+ fs.writeFileSync(file, JSON.stringify({
614
+ subjectAid: task.sub_aid, ownerAid: task.owner_aid,
615
+ operationId: task.operation_id, rejectedAt: Date.now(),
616
+ }) + '\n', { encoding: 'utf8', mode: 0o600, flag: 'wx' });
617
+ }
618
+ catch (error) {
619
+ if (error.code === 'EEXIST')
620
+ return;
621
+ const reason = error instanceof Error ? error.message : String(error);
622
+ logger.warn(`[ownership] Failed to persist rejected binding for ${task.sub_aid}: ${reason}`);
623
+ }
624
+ }
625
+ async bind(subjectAid, ownerAid, isCurrent) {
490
626
  this.assertAid(subjectAid);
491
627
  this.assertAid(ownerAid);
492
628
  if (ownerAid === subjectAid)
493
629
  throw new OwnershipError('INVALID_OWNER', 'Subject cannot own itself');
630
+ const assertCurrent = () => {
631
+ if (isCurrent && !isCurrent()) {
632
+ throw new OwnershipError('BIND_CANCELLED', 'Binding configuration or connection changed during preparation');
633
+ }
634
+ };
635
+ assertCurrent();
494
636
  const subject = this.subject(subjectAid);
495
637
  if (subject.binding) {
496
638
  if (subject.binding.ownerAid !== ownerAid)
497
639
  throw new OwnershipError('BIND_CONFLICT', 'Another owner binding is in progress');
498
640
  return subject.binding.promise;
499
641
  }
500
- const promise = this.submitBinding(subjectAid, ownerAid, subject);
642
+ const previousTask = subject.view.task;
643
+ const promise = this.submitBinding(subjectAid, ownerAid, subject, assertCurrent);
501
644
  subject.binding = { ownerAid, promise };
502
645
  try {
503
- return await promise;
646
+ const result = await promise;
647
+ const task = result.task;
648
+ if (task && (previousTask?.operation_id !== task.operation_id || previousTask.status !== task.status
649
+ || previousTask.step !== task.step)) {
650
+ logOwnershipEvent('bind.result', { subjectAid, ownerAid, operationId: task.operation_id,
651
+ taskStatus: task.status, step: task.step, consensusStatus: result.consensusStatus,
652
+ relationVersion: result.consensus?.relation_version ?? task.target_relation_version,
653
+ });
654
+ }
655
+ return result;
656
+ }
657
+ catch (error) {
658
+ logOwnershipEvent('bind.failed', { subjectAid, ownerAid, operationId: subject.view.task?.operation_id,
659
+ errorCode: ownershipErrorCode(error), consensusStatus: subject.view.consensusStatus,
660
+ relationVersion: subject.view.consensus?.relation_version,
661
+ }, true);
662
+ throw error;
504
663
  }
505
664
  finally {
506
665
  if (subject.binding?.promise === promise)
507
666
  subject.binding = undefined;
508
667
  }
509
668
  }
669
+ async transfer(ownerAid, subAid, newOwnerAid, isCurrent) {
670
+ this.assertAid(ownerAid);
671
+ this.assertAid(subAid);
672
+ this.assertAid(newOwnerAid);
673
+ if (ownerAid === newOwnerAid) {
674
+ throw new OwnershipError('INVALID_OWNER', 'The new Owner must differ from the current Owner');
675
+ }
676
+ const assertCurrent = () => {
677
+ if (isCurrent && !isCurrent()) {
678
+ throw new OwnershipError('TRANSFER_CANCELLED', 'Transfer configuration or connection changed during preparation');
679
+ }
680
+ };
681
+ assertCurrent();
682
+ const subject = this.subject(ownerAid);
683
+ const existingFlight = subject.transferFlights.get(subAid);
684
+ if (existingFlight) {
685
+ if (existingFlight.newOwnerAid !== newOwnerAid) {
686
+ throw new OwnershipError('TRANSFER_CONFLICT', 'Another transfer for this sub is in progress');
687
+ }
688
+ return existingFlight.promise;
689
+ }
690
+ if (subject.binding) {
691
+ throw new OwnershipError('BIND_CONFLICT', 'Another ownership operation is in progress');
692
+ }
693
+ if (subject.transferIntents.has(subAid) || subject.transferTasks.has(subAid)) {
694
+ const generation = subject.generation;
695
+ const current = await this.withSubjectClient(ownerAid, client => client.checkOwnershipConsensus(subAid));
696
+ if (subject.generation !== generation) {
697
+ throw new OwnershipError('CLIENT_REPLACED', 'Ownership state changed during transfer preflight; retry');
698
+ }
699
+ assertCurrent();
700
+ const task = subject.transferTasks.get(subAid);
701
+ if (task)
702
+ this.reconcileTransferTask(subject, subAid, task, current);
703
+ }
704
+ const existingIntent = subject.transferIntents.get(subAid);
705
+ if (existingIntent && existingIntent !== newOwnerAid) {
706
+ throw new OwnershipError('TRANSFER_CONFLICT', 'A different transfer for this sub is already pending');
707
+ }
708
+ const existingTask = subject.transferTasks.get(subAid);
709
+ if (existingTask && existingTask.new_owner_aid !== newOwnerAid) {
710
+ throw new OwnershipError('TRANSFER_CONFLICT', 'A different transfer for this sub is already pending');
711
+ }
712
+ for (const [oldSubAid, oldTask] of subject.transferTasks) {
713
+ if (oldSubAid !== subAid && oldTask.sub_aid === subAid)
714
+ subject.transferTasks.delete(oldSubAid);
715
+ }
716
+ subject.transferIntents.set(subAid, newOwnerAid);
717
+ const promise = this.submitTransfer(ownerAid, subAid, newOwnerAid, subject, assertCurrent);
718
+ const flight = { newOwnerAid, promise };
719
+ subject.transferFlights.set(subAid, flight);
720
+ try {
721
+ const result = await promise;
722
+ const task = result.task;
723
+ if (task) {
724
+ logOwnershipEvent('transfer.result', { subjectAid: subAid, ownerAid: newOwnerAid, operationId: task.operation_id,
725
+ taskStatus: task.status, step: task.step, consensusStatus: result.targetConsensus?.status,
726
+ relationVersion: result.targetConsensus?.relation_version ?? task.target_relation_version,
727
+ });
728
+ if (this.isTransferConsensus(result.targetConsensus, task)) {
729
+ this.finishTransfer(subject, subAid);
730
+ }
731
+ else if (task.status === 'rejected' || task.status === 'stopped'
732
+ || (task.status === 'error' && task.retryable !== true)) {
733
+ this.markTransferTerminal(subject, subAid, task.operation_id);
734
+ subject.transferTasks.delete(subAid);
735
+ subject.transferConsensuses.delete(subAid);
736
+ subject.transferIntents.delete(subAid);
737
+ this.restoreLatestTransferView(subject);
738
+ this.syncTransferViews(subject);
739
+ }
740
+ else {
741
+ subject.transferTasks.set(subAid, task);
742
+ if (result.targetConsensus)
743
+ subject.transferConsensuses.set(subAid, result.targetConsensus);
744
+ this.syncTransferViews(subject);
745
+ }
746
+ }
747
+ return result;
748
+ }
749
+ catch (error) {
750
+ if (!subject.transferTasks.has(subAid) && subject.transferIntents.get(subAid) === newOwnerAid) {
751
+ subject.transferIntents.delete(subAid);
752
+ }
753
+ logOwnershipEvent('transfer.failed', { subjectAid: subAid, ownerAid: newOwnerAid, operationId: subject.view.task?.operation_id,
754
+ errorCode: ownershipErrorCode(error), consensusStatus: subject.view.targetConsensus?.status,
755
+ relationVersion: subject.view.targetConsensus?.relation_version,
756
+ }, true);
757
+ throw error;
758
+ }
759
+ finally {
760
+ if (subject.transferFlights.get(subAid) === flight)
761
+ subject.transferFlights.delete(subAid);
762
+ }
763
+ }
510
764
  async decide(subjectAid, operationId, decision, reason) {
511
765
  const subject = this.subject(subjectAid);
512
766
  const generation = subject.generation;
513
- logger.info(`[ownership] ${decision} requested local=${subjectAid} operationId=${operationId}`);
514
767
  try {
515
768
  return await this.withSubjectClient(subjectAid, async (client, attached) => {
516
769
  // SDK 0.5.24 can recover an authenticated request from message history;
@@ -531,38 +784,89 @@ export class OwnerResolver {
531
784
  subject.requests.delete(operationId);
532
785
  delete subject.view.decisionConsensus;
533
786
  if (task.sub_aid === subjectAid) {
534
- this.invalidate(subject, 'Binding decision submitted; fresh consensus is required');
535
- this.schedule(subjectAid, subject);
787
+ this.invalidate(subject, 'Binding decision submitted; fresh consensus is required', true);
536
788
  }
537
- logger.info(`[ownership] ${decision} result ${JSON.stringify(task)}`);
538
789
  if (task.status === 'error' || task.status === 'stopped' || (decision === 'accept' && task.status === 'rejected')) {
539
790
  throw Object.assign(new OwnershipError(task.code ?? 'OWNERSHIP_DECISION_FAILED', task.reason ?? `Ownership task ${task.status}`), { retryable: task.retryable });
540
791
  }
541
- subject.view.decisionConsensus = await client.checkOwnershipConsensus(task.sub_aid);
792
+ const decisionConsensus = await client.checkOwnershipConsensus(task.sub_aid);
793
+ if (decisionConsensus?.sub_aid === task.sub_aid) {
794
+ subject.view.decisionConsensus = decisionConsensus;
795
+ if (task.sub_aid === subjectAid)
796
+ this.applyConsensus(subjectAid, subject, decisionConsensus);
797
+ delete subject.view.reason;
798
+ }
799
+ else {
800
+ delete subject.view.decisionConsensus;
801
+ subject.view.reason = 'Decision submitted; fresh ownership consensus is unavailable';
802
+ }
803
+ logOwnershipEvent('decision.result', { localAid: subjectAid, subjectAid: task.sub_aid,
804
+ ownerAid: task.owner_aid, operationId, decision, taskStatus: task.status, step: task.step,
805
+ consensusStatus: decisionConsensus?.status,
806
+ relationVersion: decisionConsensus?.relation_version,
807
+ ...(!decisionConsensus ? { errorCode: 'CONSENSUS_UNAVAILABLE' } : {}),
808
+ });
542
809
  return this.snapshot(subjectAid);
543
810
  });
544
811
  }
545
812
  catch (error) {
546
- logger.warn(`[ownership] ${decision} failed ${JSON.stringify({
547
- localAid: subjectAid, operationId, error: error instanceof Error ? error.message : String(error),
548
- })}`);
813
+ logOwnershipEvent('decision.failed', { localAid: subjectAid, operationId, decision,
814
+ errorCode: ownershipErrorCode(error),
815
+ }, true);
549
816
  throw error;
550
817
  }
551
818
  }
552
- async status(subjectAid) {
819
+ async status(subjectAid, options = {}) {
553
820
  const subject = this.subject(subjectAid);
821
+ // Status display reuses the resolve snapshot; consensus verification is
822
+ // reserved for operations that actually depend on Owner permission.
823
+ if (subject.client && subject.view.connected) {
824
+ await this.refresh(subjectAid, { force: options.force, source: 'ownership.status' });
825
+ if (options.force)
826
+ await this.refreshTransferTargets(subjectAid, subject.client, true);
827
+ return this.snapshot(subjectAid);
828
+ }
829
+ // A fresh snapshot survives transport loss; serve it instead of loading a
830
+ // short-lived client. Only a stale unattached subject needs a live check.
831
+ if (!options.force && this.isCacheFresh(subject, this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS)) {
832
+ return this.snapshot(subjectAid);
833
+ }
554
834
  const generation = subject.generation;
555
- return this.withSubjectClient(subjectAid, async (client, attached) => {
556
- if (attached)
557
- return this.refresh(subjectAid, { force: true });
835
+ return this.withSubjectClient(subjectAid, async (client) => {
558
836
  const consensus = await client.checkOwnershipConsensus(subjectAid);
559
837
  if (subject.generation !== generation) {
560
838
  throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
561
839
  }
562
840
  this.applyConsensus(subjectAid, subject, consensus);
841
+ if (options.force)
842
+ await this.refreshTransferTargets(subjectAid, client, false);
563
843
  return this.snapshot(subjectAid);
564
844
  });
565
845
  }
846
+ async refreshTransferTargets(ownerAid, client, attached) {
847
+ const subject = this.subject(ownerAid);
848
+ const generation = subject.generation;
849
+ for (const [subAid, task] of [...subject.transferTasks]) {
850
+ try {
851
+ const consensus = await client.checkOwnershipConsensus(subAid);
852
+ if ((attached && subject.client !== client) || subject.generation !== generation
853
+ || subject.transferTasks.get(subAid)?.operation_id !== task.operation_id)
854
+ return;
855
+ this.reconcileTransferTask(subject, subAid, task, consensus);
856
+ }
857
+ catch {
858
+ // Keep the last observed task and consensus for a later explicit refresh.
859
+ }
860
+ }
861
+ }
862
+ isCacheFresh(subject, maxAgeMs) {
863
+ const { checkedAt, validUntil, consensusStatus } = subject.view;
864
+ const now = this.now();
865
+ // A transient fallback can authorize callers, but is not a successful fresh check.
866
+ return !subject.view.refreshFailure && consensusStatus !== 'unavailable' && consensusStatus !== 'not_applicable'
867
+ && checkedAt !== undefined && checkedAt <= now && (validUntil ?? 0) > now
868
+ && now - checkedAt < maxAgeMs;
869
+ }
566
870
  async withSubjectClient(subjectAid, operation) {
567
871
  const subject = this.subject(subjectAid);
568
872
  if (subject.client && subject.view.connected)
@@ -604,14 +908,16 @@ export class OwnerResolver {
604
908
  stop() {
605
909
  for (const subjectAid of this.subjects.keys())
606
910
  this.detachClient(subjectAid);
911
+ this.subjects.clear();
607
912
  this.configuredOwners.clear();
913
+ this.configuredOwnerFileRevision.clear();
608
914
  }
609
- async submitBinding(subjectAid, ownerAid, subject) {
915
+ async submitBinding(subjectAid, ownerAid, subject, assertCurrent) {
610
916
  const client = subject.client;
611
917
  const generation = subject.generation;
612
918
  subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
613
919
  try {
614
- const local = await this.tryLocalBind(subjectAid, ownerAid);
920
+ const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
615
921
  if (local) {
616
922
  if (client && (subject.client !== client || subject.generation !== generation)) {
617
923
  throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during local binding');
@@ -624,7 +930,7 @@ export class OwnerResolver {
624
930
  }
625
931
  if (!client || !subject.view.connected)
626
932
  throw new OwnershipError('SUBJECT_UNAVAILABLE', 'Subject AID SDK client is not ready');
627
- const current = await this.refresh(subjectAid, { force: true });
933
+ const current = await this.refresh(subjectAid, { force: true, source: 'ownership.bind' });
628
934
  if (current.consensusStatus === 'consensus') {
629
935
  if (current.ownerAid === ownerAid)
630
936
  return current;
@@ -633,6 +939,7 @@ export class OwnerResolver {
633
939
  if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus)) {
634
940
  throw new OwnershipError('CONSENSUS_REQUIRED', 'Binding requires a fresh readable ownership baseline');
635
941
  }
942
+ assertCurrent();
636
943
  const task = this.task(await client.bindOwneraid(ownerAid));
637
944
  if (subject.client !== client || subject.generation !== generation) {
638
945
  throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during binding; the request may have been submitted');
@@ -643,13 +950,14 @@ export class OwnerResolver {
643
950
  subject.view.task = task;
644
951
  subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
645
952
  subject.view.reason = task.reason;
953
+ if (task.status === 'rejected')
954
+ this.rememberRejectedOwnerBinding(task);
646
955
  if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
647
956
  throw Object.assign(new OwnershipError(task.code ?? 'BIND_FAILED', task.reason ?? `Binding ended with ${task.status}`), {
648
957
  retryable: task.retryable,
649
958
  });
650
959
  }
651
- this.invalidate(subject, 'Binding submitted; waiting for explicit owner approval and fresh consensus');
652
- this.schedule(subjectAid, subject);
960
+ this.invalidate(subject, 'Binding submitted; waiting for explicit owner approval and fresh consensus', true);
653
961
  return this.snapshot(subjectAid);
654
962
  }
655
963
  catch (error) {
@@ -660,7 +968,246 @@ export class OwnerResolver {
660
968
  throw error;
661
969
  }
662
970
  }
663
- async tryLocalBind(subjectAid, ownerAid) {
971
+ async submitTransfer(ownerAid, subAid, newOwnerAid, subject, assertCurrent) {
972
+ const generation = subject.generation;
973
+ let targetConsensus;
974
+ try {
975
+ return await this.withSubjectClient(ownerAid, async (client, attached) => {
976
+ if (attached && (subject.client !== client || subject.generation !== generation)) {
977
+ throw new OwnershipError('CLIENT_REPLACED', 'Owner SDK client changed before transfer');
978
+ }
979
+ const current = await client.checkOwnershipConsensus(subAid);
980
+ this.assertTransferBaseline(current, ownerAid, subAid, newOwnerAid);
981
+ targetConsensus = current;
982
+ subject.view.targetConsensus = current;
983
+ assertCurrent();
984
+ const local = await this.tryLocalTransfer(ownerAid, subAid, newOwnerAid, current, assertCurrent);
985
+ if (local) {
986
+ subject.view.task = local.task;
987
+ subject.view.targetConsensus = local.consensus;
988
+ subject.transferTasks.set(subAid, local.task);
989
+ subject.transferConsensuses.set(subAid, local.consensus);
990
+ this.syncTransferViews(subject);
991
+ if (local.task.status !== 'completed' || this.isTransferConsensus(local.consensus, local.task)) {
992
+ subject.view.requestedOwnerAid = undefined;
993
+ subject.view.requestStatus = undefined;
994
+ subject.view.reason = local.task.reason;
995
+ if (this.isTransferConsensus(local.consensus, local.task))
996
+ this.finishTransfer(subject, subAid);
997
+ this.invalidateRelatedSubjects(subAid);
998
+ }
999
+ else {
1000
+ throw new OwnershipError('CONSENSUS_REQUIRED', 'Local transfer did not produce the expected fresh ownership consensus');
1001
+ }
1002
+ return this.snapshot(ownerAid);
1003
+ }
1004
+ const task = this.task(await client.transferSubaid(subAid, newOwnerAid));
1005
+ if (subject.client && (subject.client !== client || subject.generation !== generation)) {
1006
+ throw new OwnershipError('CLIENT_REPLACED', 'Owner SDK client changed during transfer; the request may have been submitted');
1007
+ }
1008
+ if (!task || task.operation !== 'transfer' || task.sub_aid !== subAid
1009
+ || task.owner_aid !== ownerAid || task.new_owner_aid !== newOwnerAid
1010
+ || task.base_relation_version !== current.relation_version
1011
+ || task.target_relation_version !== current.relation_version + 1) {
1012
+ throw new OwnershipError('TASK_MISMATCH', 'SDK returned a transfer result for different participants');
1013
+ }
1014
+ subject.transferTasks.set(subAid, task);
1015
+ subject.transferIntents.set(subAid, newOwnerAid);
1016
+ this.syncTransferViews(subject);
1017
+ subject.view.task = task;
1018
+ const after = await client.checkOwnershipConsensus(subAid);
1019
+ if (subject.client && (subject.client !== client || subject.generation !== generation)) {
1020
+ throw new OwnershipError('CLIENT_REPLACED', 'Owner SDK client changed during transfer verification; query status before retrying');
1021
+ }
1022
+ subject.view.targetConsensus = after;
1023
+ subject.transferConsensuses.set(subAid, after);
1024
+ this.syncTransferViews(subject);
1025
+ subject.view.requestedOwnerAid = newOwnerAid;
1026
+ subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
1027
+ subject.view.reason = task.reason;
1028
+ if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
1029
+ throw Object.assign(new OwnershipError(task.code ?? 'TRANSFER_FAILED', task.reason ?? `Transfer ended with ${task.status}`), {
1030
+ retryable: task.retryable,
1031
+ });
1032
+ }
1033
+ if (this.isTransferConsensus(after, task)) {
1034
+ this.finishTransfer(subject, subAid);
1035
+ this.invalidateRelatedSubjects(subAid);
1036
+ }
1037
+ return this.snapshot(ownerAid);
1038
+ });
1039
+ }
1040
+ catch (error) {
1041
+ if (subject.generation === generation) {
1042
+ if (targetConsensus && (!subject.view.targetConsensus
1043
+ || subject.view.targetConsensus.sub_aid !== subAid))
1044
+ subject.view.targetConsensus = targetConsensus;
1045
+ if (!subject.view.task) {
1046
+ subject.view.requestedOwnerAid = undefined;
1047
+ subject.view.requestStatus = undefined;
1048
+ }
1049
+ else if (subject.view.task.operation === 'transfer') {
1050
+ subject.view.requestStatus = subject.view.task.status === 'error' ? 'error' : 'submitted';
1051
+ }
1052
+ subject.view.reason = error instanceof Error ? error.message : String(error);
1053
+ }
1054
+ throw error;
1055
+ }
1056
+ }
1057
+ isTransferConsensus(consensus, task) {
1058
+ return consensus.status === 'consensus' && consensus.owner_aid === task.new_owner_aid
1059
+ && consensus.sub_aid === task.sub_aid && consensus.relation_version === task.target_relation_version
1060
+ && consensus.lock === 'locked';
1061
+ }
1062
+ reconcileTransferTask(subject, subAid, task, consensus) {
1063
+ if (!consensus || consensus.sub_aid !== subAid
1064
+ || subject.transferTasks.get(subAid)?.operation_id !== task.operation_id)
1065
+ return;
1066
+ subject.view.targetConsensus = consensus;
1067
+ subject.transferConsensuses.set(subAid, consensus);
1068
+ this.syncTransferViews(subject);
1069
+ if (this.isTransferConsensus(consensus, task)) {
1070
+ this.finishTransfer(subject, subAid);
1071
+ this.invalidateRelatedSubjects(subAid);
1072
+ return;
1073
+ }
1074
+ const superseded = consensus.status === 'consensus' && consensus.lock === 'locked'
1075
+ && (consensus.relation_version > task.target_relation_version
1076
+ || (consensus.relation_version === task.target_relation_version && consensus.owner_aid !== task.new_owner_aid));
1077
+ if (!superseded)
1078
+ return;
1079
+ this.markTransferTerminal(subject, subAid, task.operation_id);
1080
+ subject.transferTasks.delete(subAid);
1081
+ subject.transferConsensuses.delete(subAid);
1082
+ subject.transferIntents.delete(subAid);
1083
+ if (subject.view.task?.operation_id === task.operation_id)
1084
+ this.restoreLatestTransferView(subject);
1085
+ this.syncTransferViews(subject);
1086
+ logOwnershipEvent('transfer.superseded', { subjectAid: subAid, ownerAid: consensus.owner_aid,
1087
+ operationId: task.operation_id, relationVersion: consensus.relation_version,
1088
+ });
1089
+ }
1090
+ finishTransfer(subject, subAid) {
1091
+ const completedTask = subject.transferTasks.get(subAid);
1092
+ const completedConsensus = subject.transferConsensuses.get(subAid);
1093
+ if (completedTask)
1094
+ this.markTransferTerminal(subject, subAid, completedTask.operation_id);
1095
+ subject.transferTasks.delete(subAid);
1096
+ subject.transferConsensuses.delete(subAid);
1097
+ subject.transferIntents.delete(subAid);
1098
+ if (completedConsensus)
1099
+ subject.view.targetConsensus = completedConsensus;
1100
+ if (subject.view.task?.sub_aid === subAid && subject.view.task.operation === 'transfer')
1101
+ this.restoreLatestTransferView(subject);
1102
+ this.syncTransferViews(subject);
1103
+ }
1104
+ markTransferTerminal(subject, subAid, operationId) {
1105
+ const operations = subject.transferTerminalOperations.get(subAid) ?? new Set();
1106
+ operations.add(operationId);
1107
+ while (operations.size > 32)
1108
+ operations.delete(operations.values().next().value);
1109
+ subject.transferTerminalOperations.set(subAid, operations);
1110
+ }
1111
+ restoreLatestTransferView(subject) {
1112
+ const remaining = [...subject.transferTasks.values()].at(-1);
1113
+ subject.view.task = remaining;
1114
+ if (remaining)
1115
+ subject.view.targetConsensus = subject.transferConsensuses.get(remaining.sub_aid);
1116
+ subject.view.requestedOwnerAid = remaining?.new_owner_aid;
1117
+ subject.view.requestStatus = remaining ? 'submitted' : undefined;
1118
+ }
1119
+ syncTransferViews(subject) {
1120
+ subject.view.transfers = [...subject.transferTasks.entries()].map(([subAid, task]) => ({
1121
+ task, consensus: subject.transferConsensuses.get(subAid),
1122
+ }));
1123
+ }
1124
+ assertTransferBaseline(consensus, ownerAid, subAid, newOwnerAid) {
1125
+ if (consensus.status !== 'consensus' || consensus.sub_aid !== subAid
1126
+ || consensus.owner_aid !== ownerAid || consensus.lock !== 'locked') {
1127
+ throw new OwnershipError('CONSENSUS_REQUIRED', 'Transfer requires a fresh locked consensus for the current Owner');
1128
+ }
1129
+ if (newOwnerAid === ownerAid) {
1130
+ throw new OwnershipError('INVALID_OWNER', 'The new Owner must differ from the current Owner');
1131
+ }
1132
+ }
1133
+ async tryLocalTransfer(ownerAid, subAid, newOwnerAid, current, assertCurrent) {
1134
+ let store;
1135
+ let ownerClient;
1136
+ let subClient;
1137
+ let newOwnerClient;
1138
+ let invoked = false;
1139
+ try {
1140
+ const sdkStore = await import('../../aun/aid/store.js');
1141
+ store = await sdkStore.getAidStore({ slotId: sdkStore.SLOT.cli });
1142
+ const ownerIdentity = store.load(ownerAid);
1143
+ const subIdentity = store.load(subAid);
1144
+ const newOwnerIdentity = store.load(newOwnerAid);
1145
+ if (!ownerIdentity.ok || !subIdentity.ok || !newOwnerIdentity.ok
1146
+ || !ownerIdentity.data.aid.isCertValid() || !ownerIdentity.data.aid.isPrivateKeyValid()
1147
+ || !subIdentity.data.aid.isCertValid() || !subIdentity.data.aid.isPrivateKeyValid()
1148
+ || !newOwnerIdentity.data.aid.isCertValid() || !newOwnerIdentity.data.aid.isPrivateKeyValid())
1149
+ return undefined;
1150
+ ownerClient = await sdkStore.loadClient(store, ownerAid);
1151
+ subClient = await sdkStore.loadClient(store, subAid);
1152
+ newOwnerClient = await sdkStore.loadClient(store, newOwnerAid);
1153
+ if (ownerClient.getType() !== 'agent' || subClient.getType() !== 'agent' || newOwnerClient.getType() !== 'agent'
1154
+ || typeof ownerClient.transferLocalSubaid !== 'function')
1155
+ return undefined;
1156
+ assertCurrent();
1157
+ invoked = true;
1158
+ const task = this.task(await ownerClient.transferLocalSubaid(subClient, newOwnerClient));
1159
+ if (!task || task.operation !== 'transfer' || task.sub_aid !== subAid
1160
+ || task.owner_aid !== ownerAid || task.new_owner_aid !== newOwnerAid
1161
+ || task.base_relation_version !== current.relation_version
1162
+ || task.target_relation_version !== current.relation_version + 1) {
1163
+ throw new OwnershipError('TASK_MISMATCH', 'SDK returned a transfer result for different local identities');
1164
+ }
1165
+ if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
1166
+ throw Object.assign(new OwnershipError(task.code ?? 'TRANSFER_FAILED', task.reason ?? `Transfer ended with ${task.status}`), {
1167
+ retryable: task.retryable,
1168
+ });
1169
+ }
1170
+ const consensus = await ownerClient.checkOwnershipConsensus(subAid);
1171
+ if (task.status === 'completed' && (consensus.status !== 'consensus' || consensus.owner_aid !== newOwnerAid
1172
+ || consensus.sub_aid !== subAid || consensus.relation_version !== task.target_relation_version
1173
+ || consensus.lock !== 'locked')) {
1174
+ throw new OwnershipError('CONSENSUS_REQUIRED', 'Local transfer did not produce the expected fresh ownership consensus');
1175
+ }
1176
+ return { task, consensus };
1177
+ }
1178
+ catch (error) {
1179
+ if (error instanceof OwnershipError && error.code === 'TRANSFER_CANCELLED')
1180
+ throw error;
1181
+ if (!invoked)
1182
+ return undefined;
1183
+ throw error;
1184
+ }
1185
+ finally {
1186
+ if (ownerClient) {
1187
+ try {
1188
+ await ownerClient.close();
1189
+ }
1190
+ catch { }
1191
+ }
1192
+ if (subClient) {
1193
+ try {
1194
+ await subClient.close();
1195
+ }
1196
+ catch { }
1197
+ }
1198
+ if (newOwnerClient) {
1199
+ try {
1200
+ await newOwnerClient.close();
1201
+ }
1202
+ catch { }
1203
+ }
1204
+ try {
1205
+ store?.close();
1206
+ }
1207
+ catch { }
1208
+ }
1209
+ }
1210
+ async tryLocalBind(subjectAid, ownerAid, assertCurrent) {
664
1211
  let store;
665
1212
  let ownerClient;
666
1213
  let subClient;
@@ -678,6 +1225,7 @@ export class OwnerResolver {
678
1225
  if (typeof ownerClient.bindSubaid !== 'function'
679
1226
  || ownerClient.getType() !== 'agent' || subClient.getType() !== 'agent')
680
1227
  return undefined;
1228
+ assertCurrent();
681
1229
  invoked = true;
682
1230
  const task = this.task(await ownerClient.bindSubaid(subjectAid));
683
1231
  if (!task || task.operation !== 'bind' || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid
@@ -693,8 +1241,11 @@ export class OwnerResolver {
693
1241
  return { task, consensus };
694
1242
  }
695
1243
  catch (error) {
1244
+ if (error instanceof OwnershipError && error.code === 'BIND_CANCELLED')
1245
+ throw error;
696
1246
  if (!invoked) {
697
- logger.debug(`[ownership] local identity pair unavailable for ${subjectAid}/${ownerAid}: ${error instanceof Error ? error.message : String(error)}`);
1247
+ // Missing optional local Owner credentials is a normal remote-bind
1248
+ // fallback, not a failed Ownership operation.
698
1249
  return undefined;
699
1250
  }
700
1251
  throw error;
@@ -719,21 +1270,28 @@ export class OwnerResolver {
719
1270
  }
720
1271
  }
721
1272
  applyConsensus(subjectAid, subject, consensus) {
722
- if (consensus.sub_aid !== subjectAid)
1273
+ if (consensus.sub_aid !== subjectAid) {
1274
+ this.invalidate(subject, 'Ownership consensus subject does not match');
723
1275
  throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus subject does not match');
1276
+ }
724
1277
  const ownerAid = consensus.status === 'consensus' && typeof consensus.owner_aid === 'string'
725
- && isValidAid(consensus.owner_aid) && consensus.owner_aid !== subjectAid ? consensus.owner_aid : undefined;
726
- if (consensus.status === 'consensus' && !ownerAid)
1278
+ && isValidAid(consensus.owner_aid) ? consensus.owner_aid : undefined;
1279
+ if (consensus.status === 'consensus' && !ownerAid) {
1280
+ this.invalidate(subject, 'Ownership consensus owner is invalid');
727
1281
  throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus owner is invalid');
1282
+ }
1283
+ if (consensus.status === 'consensus' && consensus.lock !== 'locked') {
1284
+ this.invalidate(subject, 'Ownership consensus reports an unlocked relation');
1285
+ throw new OwnershipError('CONSENSUS_MISMATCH', 'Ownership consensus reports an unlocked relation');
1286
+ }
728
1287
  const previousOwner = this.owner(subjectAid);
729
1288
  const previousStatus = subject.view.consensusStatus;
1289
+ const previousConsensus = subject.view.consensus;
730
1290
  const checkedAt = this.now();
731
1291
  const pending = subject.view.task?.status === 'pending' || subject.view.requestStatus === 'requesting';
732
1292
  subject.view = {
733
1293
  ...subject.view, ownerAid,
734
- relation: consensus.status === 'consensus' || consensus.status === 'unbound' || consensus.status === 'released'
735
- ? { consensusStatus: consensus.status, ownerAid, checkedAt, relationVersion: consensus.relation_version }
736
- : subject.view.relation,
1294
+ relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
737
1295
  authorizationStatus: ownerAid ? 'verified' : 'unavailable', consensusStatus: consensus.status,
738
1296
  consensus: JSON.parse(JSON.stringify(consensus)),
739
1297
  checkedAt, validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
@@ -741,6 +1299,7 @@ export class OwnerResolver {
741
1299
  || subject.view.consensus?.relation_version !== consensus.relation_version
742
1300
  || subject.view.consensus?.lock !== consensus.lock ? 1 : 0),
743
1301
  reason: consensus.reason,
1302
+ refreshFailure: undefined,
744
1303
  synchronization: {
745
1304
  status: consensus.status === 'unavailable' || consensus.status === 'not_applicable' ? 'unavailable'
746
1305
  : consensus.status === 'invalid' ? 'conflict'
@@ -749,8 +1308,47 @@ export class OwnerResolver {
749
1308
  runtimeOwnerAid: ownerAid,
750
1309
  },
751
1310
  };
1311
+ this.rememberVerifiedRelation(subject);
1312
+ this.clearConfirmedRequest(subject, consensus, ownerAid);
1313
+ this.clearResolvedRequests(subject, consensus);
1314
+ if (previousOwner !== ownerAid || previousStatus !== consensus.status
1315
+ || previousConsensus?.relation_version !== consensus.relation_version
1316
+ || previousConsensus?.lock !== consensus.lock) {
1317
+ logOwnershipEvent('consensus.changed', { subjectAid, ownerAid,
1318
+ consensusStatus: consensus.status, relationVersion: consensus.relation_version,
1319
+ });
1320
+ }
752
1321
  if (previousOwner !== ownerAid || previousStatus !== consensus.status)
753
1322
  this.notify(subjectAid, ownerAid);
1323
+ this.notifyUpdate(subjectAid);
1324
+ }
1325
+ relationAfterConsensus(previous, consensus, ownerAid, checkedAt) {
1326
+ if (consensus.status === 'consensus' || consensus.status === 'unbound' || consensus.status === 'released') {
1327
+ return {
1328
+ consensusStatus: consensus.status,
1329
+ ownerAid,
1330
+ checkedAt,
1331
+ relationVersion: consensus.relation_version,
1332
+ isCurrent: true,
1333
+ };
1334
+ }
1335
+ return previous ? { ...previous, isCurrent: false } : undefined;
1336
+ }
1337
+ clearConfirmedRequest(subject, consensus, ownerAid) {
1338
+ if (consensus.status !== 'consensus')
1339
+ return;
1340
+ subject.view.requestStatus = undefined;
1341
+ if (ownerAid && ownerAid === subject.view.requestedOwnerAid)
1342
+ subject.view.requestedOwnerAid = undefined;
1343
+ }
1344
+ clearResolvedRequests(subject, consensus) {
1345
+ if (consensus.status !== 'consensus' || consensus.lock !== 'locked')
1346
+ return;
1347
+ for (const [operationId, request] of subject.requests) {
1348
+ if (request.sub_aid === consensus.sub_aid && consensus.relation_version >= request.target_relation_version) {
1349
+ subject.requests.delete(operationId);
1350
+ }
1351
+ }
754
1352
  }
755
1353
  subject(subjectAid) {
756
1354
  this.assertAid(subjectAid);
@@ -760,6 +1358,8 @@ export class OwnerResolver {
760
1358
  subject = {
761
1359
  generation: 0, epoch: 0, query: 0, subscriptions: [], taskEvents: new Set(),
762
1360
  requests: new Map(), decisionTasks: new Map(),
1361
+ transferTasks: new Map(), transferConsensuses: new Map(), transferIntents: new Map(),
1362
+ transferTerminalOperations: new Map(), transferFlights: new Map(),
763
1363
  view: {
764
1364
  subjectAid, consensusStatus: 'unavailable', authorizationStatus: 'unavailable', connected: false, revision: 0,
765
1365
  synchronization: { status: 'unavailable' },
@@ -768,16 +1368,34 @@ export class OwnerResolver {
768
1368
  this.subjects.set(subjectAid, subject);
769
1369
  return subject;
770
1370
  }
771
- invalidate(subject, reason) {
1371
+ invalidate(subject, reason, preserveVerifiedRelation = false) {
772
1372
  const previousOwner = subject.view.ownerAid;
1373
+ if (!preserveVerifiedRelation)
1374
+ subject.verifiedRelation = undefined;
773
1375
  subject.epoch += 1;
774
1376
  subject.view = {
775
1377
  ...subject.view, ownerAid: undefined, consensusStatus: 'unavailable', authorizationStatus: 'unavailable', validUntil: undefined,
1378
+ ...(subject.view.relation ? { relation: { ...subject.view.relation, isCurrent: false } } : {}),
776
1379
  revision: subject.view.revision + 1, reason, refreshFailure: undefined,
777
1380
  synchronization: { status: 'unavailable' },
778
1381
  };
779
1382
  if (previousOwner)
780
1383
  this.notify(subject.view.subjectAid);
1384
+ this.notifyUpdate(subject.view.subjectAid);
1385
+ }
1386
+ notifyUpdate(subjectAid) {
1387
+ for (const listener of this.updateListeners) {
1388
+ queueMicrotask(() => {
1389
+ if (!this.updateListeners.has(listener))
1390
+ return;
1391
+ try {
1392
+ listener(subjectAid);
1393
+ }
1394
+ catch (error) {
1395
+ logger.warn(`[ownership] Update listener failed: ${ownershipErrorCode(error)}`);
1396
+ }
1397
+ });
1398
+ }
781
1399
  }
782
1400
  notify(subjectAid, ownerAid) {
783
1401
  for (const listener of this.listeners) {
@@ -794,22 +1412,10 @@ export class OwnerResolver {
794
1412
  const ownerAid = subject.view.relation?.ownerAid;
795
1413
  if ((!targetAid && changedAid === subjectAid) || changedAid === ownerAid
796
1414
  || changedAid === subject.view.requestedOwnerAid) {
797
- this.invalidate(subject, 'Ownership material changed; fresh consensus is required');
798
- this.schedule(subjectAid, subject);
1415
+ this.invalidate(subject, 'Ownership material changed; fresh consensus is required', true);
799
1416
  }
800
1417
  }
801
1418
  }
802
- schedule(subjectAid, subject, allowTransient = true) {
803
- if (subject.timer || !subject.client || !subject.view.connected)
804
- return;
805
- subject.timer = setTimeout(() => {
806
- subject.timer = undefined;
807
- void this.refresh(subjectAid, { force: true, allowTransient }).catch(error => {
808
- logger.warn(`[ownership] Event refresh failed for ${subjectAid}: ${error instanceof Error ? error.message : String(error)}`);
809
- });
810
- }, 0);
811
- subject.timer.unref?.();
812
- }
813
1419
  now() {
814
1420
  return this.options.now?.() ?? Date.now();
815
1421
  }
@@ -851,12 +1457,12 @@ export class OwnerResolver {
851
1457
  trackBindingRequest(localAid, subject, event, record) {
852
1458
  const requestAction = record.action === 'bind.request' || record.action === 'transfer.request';
853
1459
  if (event === 'ownership.request'
854
- && (record.operation !== 'bind' || (record.action !== undefined && !requestAction)))
1460
+ && (!['bind', 'transfer'].includes(String(record.operation)) || (record.action !== undefined && !requestAction)))
855
1461
  return;
856
1462
  const task = this.bindingTask(event === 'ownership.request'
857
1463
  ? { ...record, status: 'pending', step: 'approval' }
858
1464
  : record, event);
859
- if (!task || (task.sub_aid !== localAid && task.owner_aid !== localAid))
1465
+ if (!task || (task.sub_aid !== localAid && task.owner_aid !== localAid && task.new_owner_aid !== localAid))
860
1466
  return;
861
1467
  const request = subject.requests.get(task.operation_id);
862
1468
  const decisionTask = subject.decisionTasks.get(task.operation_id);
@@ -865,15 +1471,21 @@ export class OwnerResolver {
865
1471
  return;
866
1472
  if (event === 'ownership.request') {
867
1473
  const requester = record.requester_aid;
868
- const remote = task.sub_aid === localAid ? task.owner_aid : task.sub_aid;
869
- if (task.status !== 'pending' || task.step !== 'approval' || requester !== remote || decisionTask)
1474
+ const localRole = task.operation === 'transfer'
1475
+ ? task.new_owner_aid === localAid ? 'new_owner' : task.sub_aid === localAid ? 'sub' : 'owner'
1476
+ : task.sub_aid === localAid ? 'sub' : 'owner';
1477
+ const remote = localRole === 'owner' ? task.sub_aid : task.owner_aid;
1478
+ if (task.status !== 'pending' || task.step !== 'approval' || decisionTask
1479
+ || (task.operation === 'transfer' && localRole === 'owner') || requester !== remote)
870
1480
  return;
871
1481
  subject.requests.set(task.operation_id, {
872
- ...task, requester_aid: remote, local_role: task.sub_aid === localAid ? 'sub' : 'owner',
1482
+ ...task, requester_aid: remote, local_role: localRole,
873
1483
  });
874
- logger.info(`[ownership] inbound binding ${JSON.stringify({
875
- localAid, operationId: task.operation_id, subAid: task.sub_aid, ownerAid: task.owner_aid,
876
- })}`);
1484
+ if (!request)
1485
+ logOwnershipEvent('request.received', {
1486
+ localAid, operationId: task.operation_id, subjectAid: task.sub_aid, ownerAid: task.owner_aid,
1487
+ eventType: event, taskStatus: task.status, step: task.step, relationVersion: task.target_relation_version,
1488
+ });
877
1489
  }
878
1490
  else {
879
1491
  const awaitingApproval = task.step === 'approval'
@@ -904,12 +1516,12 @@ export class OwnerResolver {
904
1516
  /** Only public task fields are exposed; raw SDK records remain SDK-owned. */
905
1517
  bindingTask(value, event) {
906
1518
  const task = this.task(value, event);
907
- if (!task || task.operation !== 'bind' || !CREATION_BIND_OPERATION_ID.test(task.operation_id)
908
- || task.sub_aid === task.owner_aid || !Number.isSafeInteger(task.base_relation_version)
1519
+ if (!task || !['bind', 'transfer'].includes(task.operation) || !CREATION_BIND_OPERATION_ID.test(task.operation_id)
1520
+ || !Number.isSafeInteger(task.base_relation_version)
909
1521
  || task.base_relation_version < 0 || !Number.isSafeInteger(task.target_relation_version)
910
- || task.target_relation_version !== task.base_relation_version + 1)
911
- return undefined;
912
- if (task.new_owner_aid !== undefined)
1522
+ || task.target_relation_version !== task.base_relation_version + 1
1523
+ || (task.operation === 'bind' && task.new_owner_aid !== undefined)
1524
+ || (task.operation === 'transfer' && (!task.new_owner_aid || task.new_owner_aid === task.owner_aid)))
913
1525
  return undefined;
914
1526
  return {
915
1527
  operation_id: task.operation_id, operation: task.operation, sub_aid: task.sub_aid, owner_aid: task.owner_aid,
@@ -929,6 +1541,7 @@ export class OwnerResolver {
929
1541
  || !['bind', 'transfer'].includes(String(record.operation)) || typeof record.sub_aid !== 'string' || !isValidAid(record.sub_aid)
930
1542
  || typeof record.owner_aid !== 'string' || !isValidAid(record.owner_aid)
931
1543
  || (record.new_owner_aid !== undefined && (typeof record.new_owner_aid !== 'string' || !isValidAid(record.new_owner_aid)))
1544
+ || (record.operation === 'transfer' && record.new_owner_aid === record.owner_aid)
932
1545
  || typeof baseRelationVersion !== 'number' || !Number.isSafeInteger(baseRelationVersion) || baseRelationVersion < 0
933
1546
  || typeof targetRelationVersion !== 'number' || !Number.isSafeInteger(targetRelationVersion)
934
1547
  || targetRelationVersion !== baseRelationVersion + 1)
@@ -961,12 +1574,13 @@ export const getDaemonOwners = () => ownerResolver.daemonOwners();
961
1574
  export async function refreshOwnershipForAuthorization(subjectAid, options = {}) {
962
1575
  const daemonAid = ownerResolver.getDaemonAid();
963
1576
  const ownershipSubjectAid = daemonAid && subjectAid === `${daemonAid}#daemon` ? daemonAid : subjectAid;
964
- const subjects = new Set([ownershipSubjectAid, ...(!ownershipSubjectAid || options.includeDaemon !== false ? [daemonAid] : [])]
1577
+ const subjects = new Set([ownershipSubjectAid ?? daemonAid, ...(options.includeDaemon === true ? [daemonAid] : [])]
965
1578
  .filter((aid) => !!aid));
966
1579
  const views = await Promise.all([...subjects].map(aid => ownerResolver.refresh(aid, {
967
1580
  maxAgeMs: options.maxAgeMs ?? OWNERSHIP_AUTHORIZATION_MAX_AGE_MS,
968
1581
  force: options.force,
969
1582
  allowTransient: options.allowTransient,
1583
+ source: options.source ?? 'authorization',
970
1584
  })));
971
1585
  if (!options.allowTransient) {
972
1586
  const failure = views.find(view => view.consensusStatus === 'unavailable' && view.refreshFailure);
@@ -981,32 +1595,32 @@ export async function assertOwnershipAuthorization(context) {
981
1595
  const ownerActor = hasTrustedPrincipal(context?.actor) ? context.actor.principalId : undefined;
982
1596
  if (!authorization && !ownerRole)
983
1597
  return;
984
- await refreshOwnershipForAuthorization(context?.selfAid ?? authorization?.agentAid, { allowTransient: true });
1598
+ await refreshOwnershipForAuthorization(context?.selfAid ?? authorization?.agentAid, {
1599
+ allowTransient: true, includeDaemon: !!authorization,
1600
+ });
985
1601
  const subjectAid = context?.selfAid ?? authorization?.agentAid;
986
1602
  if (authorization) {
987
1603
  if (!getDaemonOwners().includes(authorization.authorizedBy)
988
1604
  || (authorization.source === 'agent-policy'
989
1605
  && !ownerResolver.isOwner(authorization.agentAid ?? '', authorization.authorizedBy))) {
990
1606
  const view = subjectAid ? ownerResolver.snapshot(subjectAid) : undefined;
991
- logger.warn(`[ownership] authorization denied ${JSON.stringify({
992
- subjectAid, authorizedBy: authorization.authorizedBy,
1607
+ logOwnershipEvent('authorization.denied', {
1608
+ subjectAid, actorAid: authorization.authorizedBy, ownerAid: view?.relation?.ownerAid,
993
1609
  consensusStatus: view?.consensusStatus,
994
- failureCode: view?.refreshFailure?.code,
995
- refreshFailure: view?.refreshFailure?.reason,
996
- refreshFailureKind: view?.refreshFailure?.kind,
997
- })}`);
1610
+ relationVersion: view?.consensus?.relation_version,
1611
+ errorCode: view?.refreshFailure?.code ?? 'OWNER_UNAVAILABLE',
1612
+ }, true);
998
1613
  throw new OwnershipError('OWNER_UNAVAILABLE', 'Current Owner no longer authorizes this execution');
999
1614
  }
1000
1615
  }
1001
1616
  else if (!context?.selfAid || !ownerResolver.isOwner(context.selfAid, ownerActor)) {
1002
1617
  const view = context?.selfAid ? ownerResolver.snapshot(context.selfAid) : undefined;
1003
- logger.warn(`[ownership] authorization denied ${JSON.stringify({
1004
- subjectAid: context?.selfAid, actorAid: ownerActor,
1618
+ logOwnershipEvent('authorization.denied', {
1619
+ subjectAid: context?.selfAid, actorAid: ownerActor, ownerAid: view?.relation?.ownerAid,
1005
1620
  consensusStatus: view?.consensusStatus,
1006
- failureCode: view?.refreshFailure?.code,
1007
- refreshFailure: view?.refreshFailure?.reason,
1008
- refreshFailureKind: view?.refreshFailure?.kind,
1009
- })}`);
1621
+ relationVersion: view?.consensus?.relation_version,
1622
+ errorCode: view?.refreshFailure?.code ?? 'OWNER_UNAVAILABLE',
1623
+ }, true);
1010
1624
  throw new OwnershipError('OWNER_UNAVAILABLE', 'Current Owner could not be verified; start a new task with the current role');
1011
1625
  }
1012
1626
  }