evolcore 0.0.41-test.1 → 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 (127) hide show
  1. package/CHANGELOG.md +49 -36
  2. package/dist/agents/baseagent.js +68 -6
  3. package/dist/agents/codex-runner.js +62 -43
  4. package/dist/aun/aid/agentmd.js +98 -11
  5. package/dist/aun/aid/client.js +1 -1
  6. package/dist/aun/aid/control-aid.js +26 -2
  7. package/dist/aun/aid/identity.js +91 -0
  8. package/dist/aun/aid/index.js +1 -1
  9. package/dist/aun/aid/managed-operation.js +1 -1
  10. package/dist/aun/aid/ownership-operation.js +23 -22
  11. package/dist/aun/menu/client.js +27 -0
  12. package/dist/aun/msg/p2p.js +3 -8
  13. package/dist/aun/service-proxy.js +17 -0
  14. package/dist/channels/aun.js +321 -34
  15. package/dist/cli/agent-command.js +5 -2
  16. package/dist/cli/agent-create.js +991 -233
  17. package/dist/cli/agent.js +49 -10
  18. package/dist/cli/aid-bind-command.js +48 -19
  19. package/dist/cli/aun-commands.js +44 -16
  20. package/dist/cli/daemon-commands.js +1 -0
  21. package/dist/cli/index.js +24 -1
  22. package/dist/cli/init-channel.js +1 -1
  23. package/dist/cli/init.js +75 -1
  24. package/dist/cli/managed-command-guard.js +13 -1
  25. package/dist/cli/provider-command.js +57 -0
  26. package/dist/cli/restart-monitor.js +4 -2
  27. package/dist/cli/stats.js +10 -3
  28. package/dist/cli/task-context.js +19 -0
  29. package/dist/config/boot-log.js +3 -2
  30. package/dist/config/config-field-policy.js +12 -7
  31. package/dist/config/config-manager.js +138 -6
  32. package/dist/config/owner-config.js +2 -2
  33. package/dist/config/peer-role-resolver.js +2 -1
  34. package/dist/config/provider-ipc-service.js +132 -0
  35. package/dist/config/provider-menu-request.js +58 -0
  36. package/dist/config/providers-management.js +78 -5
  37. package/dist/config/resolved-config-op.js +8 -1
  38. package/dist/config/schema-migration.js +322 -8
  39. package/dist/config-store.js +10 -1
  40. package/dist/contracts/ecweb-service-protocol.js +2 -1
  41. package/dist/core/agent-application-service.js +60 -11
  42. package/dist/core/agent-create-status.js +203 -0
  43. package/dist/core/agent-creation-claim.js +177 -0
  44. package/dist/core/agent-ipc-registration.js +39 -18
  45. package/dist/core/agent-runtime.js +193 -23
  46. package/dist/core/auth/agent-delegation.js +4 -2
  47. package/dist/core/auth/auth-gateway.js +66 -1
  48. package/dist/core/auth/authorization-audit.js +41 -5
  49. package/dist/core/auth/delegation-authorization.js +2 -1
  50. package/dist/core/auth/operation-authorizer.js +28 -6
  51. package/dist/core/auth/operation-catalog.js +14 -1
  52. package/dist/core/channel-loader.js +2 -0
  53. package/dist/core/command/agent-control.js +257 -14
  54. package/dist/core/command/cli-intent-parser.js +6 -2
  55. package/dist/core/command/command-handler.js +64 -55
  56. package/dist/core/command/memory-slash.js +1 -1
  57. package/dist/core/command/menu-catalog.js +5 -0
  58. package/dist/core/command/menu-handler.js +64 -18
  59. package/dist/core/command/menu-protocol.js +15 -1
  60. package/dist/core/command/provider-menu.js +46 -0
  61. package/dist/core/command/slash-handler.js +2 -1
  62. package/dist/core/daemon-control.js +18 -13
  63. package/dist/core/event-catalog.js +10 -0
  64. package/dist/core/evolagent-registry.js +3 -1
  65. package/dist/core/evolagent.js +8 -6
  66. package/dist/core/file-integrity/store.js +11 -0
  67. package/dist/core/handoff/ipc-registration.js +3 -0
  68. package/dist/core/initialization/service.js +491 -0
  69. package/dist/core/ipc-registration.js +34 -22
  70. package/dist/core/memory/consolidation-ops-records.js +95 -0
  71. package/dist/core/memory/consolidation-trigger.js +19 -2
  72. package/dist/core/memory/consolidation.js +19 -8
  73. package/dist/core/memory/memory-admin.js +1 -1
  74. package/dist/core/memory/relation-sweep.js +11 -6
  75. package/dist/core/message/aun-ipc-sender.js +73 -67
  76. package/dist/core/message/im-renderer.js +18 -0
  77. package/dist/core/message/message-bridge.js +35 -3
  78. package/dist/core/message/response-engine.js +32 -28
  79. package/dist/core/model/catalog-service.js +1 -1
  80. package/dist/core/model/config-scope.js +5 -7
  81. package/dist/core/ownership/owner-resolver.js +755 -143
  82. package/dist/core/permission/approval-gateway.js +103 -403
  83. package/dist/core/permission/ec-command-parser.js +32 -4
  84. package/dist/core/permission/index.js +1 -0
  85. package/dist/core/permission/permission-result.js +78 -0
  86. package/dist/core/permission/tool-policy.js +7 -43
  87. package/dist/core/system-session/memory.js +37 -7
  88. package/dist/directory/owner-directory-cache.js +2 -2
  89. package/dist/ecweb/init-menu.js +32 -0
  90. package/dist/index.js +17 -5
  91. package/dist/ipc.js +85 -25
  92. package/dist/paths.js +3 -0
  93. package/dist/proxy/manager.js +6 -7
  94. package/dist/trigger/authorization.js +27 -17
  95. package/dist/trigger/feedback.js +2 -3
  96. package/dist/trigger/ipc-service.js +105 -78
  97. package/dist/trigger/local-files.js +2 -1
  98. package/dist/trigger/manager.js +5 -3
  99. package/dist/trigger/scheduler.js +88 -6
  100. package/dist/utils/atomic-write.js +28 -0
  101. package/dist/utils/error-utils.js +24 -0
  102. package/dist/utils/logger.js +68 -1
  103. package/dist/utils/welcome.js +1 -1
  104. package/kits/docs/INDEX.md +1 -0
  105. package/kits/docs/aun/SDK.md +4 -1
  106. package/kits/docs/evolcore/INDEX.md +1 -0
  107. package/kits/docs/evolcore/agent.md +8 -1
  108. package/kits/docs/evolcore/aid.md +67 -17
  109. package/kits/docs/evolcore/config.md +11 -1
  110. package/kits/docs/evolcore/group.md +1 -1
  111. package/kits/docs/evolcore/provider.md +50 -0
  112. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  113. package/kits/rules/01-overview.md +3 -0
  114. package/kits/rules/04-relation.md +1 -1
  115. package/kits/schemas/_meta.json +2 -2
  116. package/kits/schemas/agent-config.schema.16.json +3 -3
  117. package/kits/schemas/relation-config.schema.11.json +17 -0
  118. package/kits/skills/.switches.json +8 -0
  119. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  120. package/kits/skills/ec-identity/SKILL.md +2 -2
  121. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  122. package/kits/skills/ec-trigger/SKILL.md +5 -13
  123. package/kits/skills/thread-ops/SKILL.md +5 -0
  124. package/kits/templates/system-fragments/venue.md +1 -1
  125. package/package.json +3 -3
  126. package/dist/core/memory/forget-log.js +0 -96
  127. package/dist/core/message/create-status.js +0 -96
@@ -1,11 +1,11 @@
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;
@@ -39,10 +39,11 @@ export class OwnerResolver {
39
39
  options;
40
40
  subjects = new Map();
41
41
  daemonAid;
42
- /** Local owner configuration remains an independent authorization source during rollout. */
42
+ /** Compatibility binding targets loaded from config; never an Owner authorization source. */
43
43
  configuredOwners = new Map();
44
44
  configuredOwnerFileRevision = new Map();
45
45
  listeners = new Set();
46
+ updateListeners = new Set();
46
47
  constructor(options = {}) {
47
48
  this.options = options;
48
49
  }
@@ -66,9 +67,10 @@ export class OwnerResolver {
66
67
  else
67
68
  this.configuredOwners.delete(subjectAid);
68
69
  const subject = this.subjects.get(subjectAid);
69
- if (subject) {
70
- this.invalidate(subject, 'Configured Owners changed; fresh consensus is required');
71
- 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);
72
74
  }
73
75
  }
74
76
  setAgentConfiguredOwners(subjectAid, owners) {
@@ -86,7 +88,12 @@ export class OwnerResolver {
86
88
  isOwner(subjectAid, ownerAid) {
87
89
  if (!subjectAid || !ownerAid)
88
90
  return false;
89
- 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);
90
97
  }
91
98
  assertLocalSubject(subjectAid) {
92
99
  this.assertAid(subjectAid);
@@ -98,6 +105,11 @@ export class OwnerResolver {
98
105
  this.listeners.add(listener);
99
106
  return () => { this.listeners.delete(listener); };
100
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
+ }
101
113
  attachClient(subjectAid, client, connected = false) {
102
114
  this.assertAid(subjectAid);
103
115
  const clientAid = client.currentAid;
@@ -119,32 +131,70 @@ export class OwnerResolver {
119
131
  const record = this.record(payload);
120
132
  if (!record)
121
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;
122
138
  this.trackBindingRequest(subjectAid, subject, event, record);
123
- // When this AID is the prospective owner, the request concerns the
124
- // remote sub's ownership, not this AID's own Owner authorization.
125
- 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)
126
147
  return;
127
148
  if (typeof record.operation_id === 'string') {
128
149
  const key = JSON.stringify([event, record.operation_id, record.step, record.status,
129
- record.owner_aid, record.relation_version, record.code, record.reason]);
150
+ record.owner_aid, record.new_owner_aid, record.relation_version, record.code]);
130
151
  if (subject.taskEvents.has(key))
131
152
  return;
132
153
  subject.taskEvents.add(key);
133
154
  if (subject.taskEvents.size > 256)
134
155
  subject.taskEvents.delete(subject.taskEvents.values().next().value);
135
156
  }
136
- this.invalidate(subject, 'Ownership changed; fresh consensus is required');
137
- const task = this.task(record, event);
138
- 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,
139
165
  operationId: task?.operation_id, taskStatus: task?.status, step: task?.step,
140
- code: task?.code, reason: task?.reason })}`);
141
- 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
142
173
  && (!subject.view.task || (subject.view.task.operation_id === task.operation_id
143
- && (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)))) {
144
176
  subject.view.task = task;
145
177
  subject.view.requestStatus = 'submitted';
146
178
  }
147
- 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
+ }
148
198
  }));
149
199
  }
150
200
  subject.subscriptions.push(client.on('agentmd.changed', payload => {
@@ -180,8 +230,6 @@ export class OwnerResolver {
180
230
  this.setConnected(subjectAid, client, false);
181
231
  }));
182
232
  }
183
- if (subject.view.connected)
184
- this.schedule(subjectAid, subject);
185
233
  }
186
234
  setConnected(subjectAid, client, connected) {
187
235
  const subject = this.subjects.get(subjectAid);
@@ -193,22 +241,14 @@ export class OwnerResolver {
193
241
  // Transport loss does not revoke unexpired consensus. Retire work from
194
242
  // the old connection without clearing the cached authorization.
195
243
  subject.epoch += 1;
196
- if (subject.timer)
197
- clearTimeout(subject.timer);
198
- subject.timer = undefined;
199
244
  }
200
245
  subject.view.connected = connected;
201
- if (connected)
202
- this.schedule(subjectAid, subject);
203
246
  }
204
247
  detachClient(subjectAid, client) {
205
248
  const subject = this.subjects.get(subjectAid);
206
249
  if (!subject || (client && subject.client !== client))
207
250
  return;
208
251
  subject.generation += 1;
209
- if (subject.timer)
210
- clearTimeout(subject.timer);
211
- subject.timer = undefined;
212
252
  subject.taskEvents.clear();
213
253
  subject.requests.clear();
214
254
  subject.decisionTasks.clear();
@@ -228,29 +268,46 @@ export class OwnerResolver {
228
268
  return undefined;
229
269
  const view = this.subjects.get(subjectAid)?.view;
230
270
  return view?.consensusStatus === 'consensus'
231
- && (view.validUntil ?? 0) > this.now() ? view.ownerAid : undefined;
271
+ && ((view.validUntil ?? 0) > this.now() || view.refreshFailure?.fallbackUsed === true)
272
+ ? view.ownerAid : undefined;
232
273
  }
233
274
  owners(subjectAid) {
234
275
  if (!subjectAid)
235
276
  return [];
236
- return [...new Set([
237
- ...this.configuredOwnerList(subjectAid),
238
- ...this.protocolOwners(subjectAid),
239
- ])];
277
+ const protocol = this.protocolOwners(subjectAid);
278
+ if (protocol.length > 0 || this.hasObservedProtocolConsensus(subjectAid))
279
+ return protocol;
280
+ return this.configuredOwnerList(subjectAid);
240
281
  }
241
282
  protocolOwners(subjectAid) {
242
283
  const owner = this.owner(subjectAid);
243
284
  return owner ? [owner] : [];
244
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
+ }
245
296
  primaryOwner(subjectAid) {
246
297
  return this.owners(subjectAid)[0];
247
298
  }
248
299
  knownOwners(subjectAid) {
249
300
  if (!subjectAid)
250
301
  return [];
251
- const configuredOwners = this.configuredOwnerList(subjectAid);
252
- const ownerAid = this.subjects.get(subjectAid)?.view.relation?.ownerAid;
253
- 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);
254
311
  }
255
312
  knownOwner(subjectAid) {
256
313
  return this.knownOwners(subjectAid)[0];
@@ -288,9 +345,6 @@ export class OwnerResolver {
288
345
  async refresh(subjectAid, options = {}) {
289
346
  const subject = this.subject(subjectAid);
290
347
  this.refreshConfiguredOwnersFromDisk(subjectAid);
291
- if (subject.timer)
292
- clearTimeout(subject.timer);
293
- subject.timer = undefined;
294
348
  const inFlight = subject.refreshing?.epoch === subject.epoch ? subject.refreshing : undefined;
295
349
  const refreshing = inFlight?.promise;
296
350
  const initialEpoch = subject.epoch;
@@ -303,13 +357,30 @@ export class OwnerResolver {
303
357
  return this.snapshot(subjectAid);
304
358
  const attemptId = inFlight?.attemptId ?? ++subject.query;
305
359
  const attemptedAt = inFlight?.attemptedAt ?? this.now();
306
- const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt);
307
- 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 };
308
375
  try {
309
376
  await promise;
310
- if (subject.epoch !== initialEpoch && subject.view.consensusStatus === 'consensus'
311
- && subject.view.checkedAt === initialCheckedAt) {
312
- 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
+ }
313
384
  }
314
385
  if (!subject.view.connected && subject.view.consensusStatus === 'consensus' && !isFresh()
315
386
  && subject.view.refreshFailure?.fallbackUsed !== true) {
@@ -326,11 +397,12 @@ export class OwnerResolver {
326
397
  subject.refreshing = undefined;
327
398
  }
328
399
  }
329
- async refreshSubject(subjectAid, subject, attemptId, attemptedAt) {
400
+ async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic) {
401
+ logOwnershipEvent('refresh.started', { subjectAid, ...diagnostic });
330
402
  const client = subject.client;
331
403
  if (!client || !subject.view.connected) {
332
404
  const reason = 'Subject AID has no connected SDK client';
333
- this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId);
405
+ this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId, diagnostic);
334
406
  return this.snapshot(subjectAid);
335
407
  }
336
408
  const generation = subject.generation;
@@ -341,16 +413,20 @@ export class OwnerResolver {
341
413
  const consensus = await Promise.race([
342
414
  client.checkOwnershipConsensus(subjectAid),
343
415
  new Promise((_resolve, reject) => {
344
- 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);
345
417
  timeout.unref?.();
346
418
  }),
347
419
  ]);
348
420
  if (subject.client !== client || subject.generation !== generation || subject.epoch !== epoch
349
- || 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
+ });
350
425
  return this.snapshot(subjectAid);
426
+ }
351
427
  const ownerAid = consensus.status === 'consensus' && consensus.sub_aid === subjectAid
352
428
  && typeof consensus.owner_aid === 'string' && isValidAid(consensus.owner_aid)
353
- && consensus.owner_aid !== subjectAid ? consensus.owner_aid : undefined;
429
+ ? consensus.owner_aid : undefined;
354
430
  if (consensus.sub_aid !== subjectAid || (consensus.status === 'consensus' && !ownerAid)) {
355
431
  throw new Error('Ownership consensus contains a mismatched subject or invalid owner');
356
432
  }
@@ -361,19 +437,18 @@ export class OwnerResolver {
361
437
  const reason = consensus.reason ?? 'Ownership consensus is temporarily unavailable';
362
438
  this.handleRefreshFailure(subjectAid, subject, {
363
439
  code: consensus.code ?? 'UNAVAILABLE', message: reason, retryable: true,
364
- }, attemptedAt, attemptId);
440
+ }, attemptedAt, attemptId, diagnostic);
365
441
  return this.snapshot(subjectAid);
366
442
  }
367
443
  const previousOwner = this.owner(subjectAid);
368
444
  const previousStatus = subject.view.consensusStatus;
445
+ const previousConsensus = subject.view.consensus;
369
446
  const checkedAt = this.now();
370
447
  const pending = subject.view.task?.status === 'pending' || subject.view.requestStatus === 'requesting';
371
448
  subject.view = {
372
449
  ...subject.view,
373
450
  ownerAid,
374
- relation: consensus.status === 'consensus' || consensus.status === 'unbound' || consensus.status === 'released'
375
- ? { consensusStatus: consensus.status, ownerAid, checkedAt, relationVersion: consensus.relation_version }
376
- : subject.view.relation,
451
+ relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
377
452
  authorizationStatus: ownerAid ? 'verified' : 'unavailable',
378
453
  consensusStatus: consensus.status,
379
454
  consensus: JSON.parse(JSON.stringify(consensus)),
@@ -393,16 +468,37 @@ export class OwnerResolver {
393
468
  runtimeOwnerAid: ownerAid,
394
469
  },
395
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);
396
489
  if (previousOwner !== ownerAid || previousStatus !== consensus.status)
397
490
  this.notify(subjectAid, ownerAid);
398
- if (ownerAid === subject.view.requestedOwnerAid && subject.view.requestStatus === 'interrupted') {
399
- subject.view.requestStatus = 'submitted';
400
- }
491
+ this.notifyUpdate(subjectAid);
401
492
  }
402
493
  catch (error) {
403
494
  if (subject.client === client && subject.generation === generation && subject.epoch === epoch && subject.query === query) {
404
495
  const reason = error instanceof Error ? error.message : String(error);
405
- 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
+ });
406
502
  }
407
503
  }
408
504
  finally {
@@ -411,7 +507,7 @@ export class OwnerResolver {
411
507
  }
412
508
  return this.snapshot(subjectAid);
413
509
  }
414
- handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId) {
510
+ handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId, diagnostic) {
415
511
  const details = error && typeof error === 'object' ? error : {};
416
512
  const reason = error instanceof Error ? error.message
417
513
  : typeof details.message === 'string' ? details.message : String(error);
@@ -420,17 +516,45 @@ export class OwnerResolver {
420
516
  // Keep the shared cache intact for ordinary callers; strict waiters receive
421
517
  // an unavailable view for this attempt and cannot consume the fallback.
422
518
  const fallbackUsed = transient && this.canUseTransientAuthorization(subject, attemptedAt);
423
- if (!fallbackUsed)
424
- this.invalidate(subject, reason);
425
- subject.view.refreshFailure = {
426
- kind: transient ? 'transient' : 'permanent', code, reason, attemptedAt, attemptId, fallbackUsed,
427
- };
428
519
  if (fallbackUsed) {
429
- 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
+ };
430
534
  }
431
535
  else {
432
- logger.warn(`[ownership] refresh failed subject=${subjectAid} attempt=${attemptId} code=${code} transient=${transient} reason=${reason}`);
536
+ this.invalidate(subject, reason);
433
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);
434
558
  }
435
559
  unavailableSnapshot(subjectAid, failure) {
436
560
  const view = this.snapshot(subjectAid);
@@ -438,20 +562,23 @@ export class OwnerResolver {
438
562
  view.consensusStatus = 'unavailable';
439
563
  view.authorizationStatus = 'unavailable';
440
564
  view.validUntil = undefined;
565
+ if (view.relation)
566
+ view.relation.isCurrent = false;
441
567
  view.reason = failure.reason;
442
568
  view.synchronization = { status: 'unavailable' };
443
569
  return view;
444
570
  }
445
571
  canUseTransientAuthorization(subject, attemptedAt) {
446
- const view = subject.view;
572
+ const verified = subject.verifiedRelation;
447
573
  const now = this.now();
448
- return view.consensusStatus === 'consensus'
449
- && !!view.ownerAid
450
- && view.checkedAt !== undefined
451
- && view.checkedAt <= attemptedAt
452
- && view.checkedAt <= now
453
- && now - view.checkedAt < OWNERSHIP_AUTHORIZATION_MAX_AGE_MS
454
- && (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;
455
582
  }
456
583
  isTransientRefreshFailure(error) {
457
584
  const details = error && typeof error === 'object' ? error : {};
@@ -474,31 +601,169 @@ export class OwnerResolver {
474
601
  || code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
475
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);
476
603
  }
477
- 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) {
478
626
  this.assertAid(subjectAid);
479
627
  this.assertAid(ownerAid);
480
628
  if (ownerAid === subjectAid)
481
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();
482
636
  const subject = this.subject(subjectAid);
483
637
  if (subject.binding) {
484
638
  if (subject.binding.ownerAid !== ownerAid)
485
639
  throw new OwnershipError('BIND_CONFLICT', 'Another owner binding is in progress');
486
640
  return subject.binding.promise;
487
641
  }
488
- const promise = this.submitBinding(subjectAid, ownerAid, subject);
642
+ const previousTask = subject.view.task;
643
+ const promise = this.submitBinding(subjectAid, ownerAid, subject, assertCurrent);
489
644
  subject.binding = { ownerAid, promise };
490
645
  try {
491
- 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;
492
663
  }
493
664
  finally {
494
665
  if (subject.binding?.promise === promise)
495
666
  subject.binding = undefined;
496
667
  }
497
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
+ }
498
764
  async decide(subjectAid, operationId, decision, reason) {
499
765
  const subject = this.subject(subjectAid);
500
766
  const generation = subject.generation;
501
- logger.info(`[ownership] ${decision} requested local=${subjectAid} operationId=${operationId}`);
502
767
  try {
503
768
  return await this.withSubjectClient(subjectAid, async (client, attached) => {
504
769
  // SDK 0.5.24 can recover an authenticated request from message history;
@@ -519,33 +784,51 @@ export class OwnerResolver {
519
784
  subject.requests.delete(operationId);
520
785
  delete subject.view.decisionConsensus;
521
786
  if (task.sub_aid === subjectAid) {
522
- this.invalidate(subject, 'Binding decision submitted; fresh consensus is required');
523
- this.schedule(subjectAid, subject);
787
+ this.invalidate(subject, 'Binding decision submitted; fresh consensus is required', true);
524
788
  }
525
- logger.info(`[ownership] ${decision} result ${JSON.stringify(task)}`);
526
789
  if (task.status === 'error' || task.status === 'stopped' || (decision === 'accept' && task.status === 'rejected')) {
527
790
  throw Object.assign(new OwnershipError(task.code ?? 'OWNERSHIP_DECISION_FAILED', task.reason ?? `Ownership task ${task.status}`), { retryable: task.retryable });
528
791
  }
529
- 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
+ });
530
809
  return this.snapshot(subjectAid);
531
810
  });
532
811
  }
533
812
  catch (error) {
534
- logger.warn(`[ownership] ${decision} failed ${JSON.stringify({
535
- localAid: subjectAid, operationId, error: error instanceof Error ? error.message : String(error),
536
- })}`);
813
+ logOwnershipEvent('decision.failed', { localAid: subjectAid, operationId, decision,
814
+ errorCode: ownershipErrorCode(error),
815
+ }, true);
537
816
  throw error;
538
817
  }
539
818
  }
540
- async status(subjectAid) {
819
+ async status(subjectAid, options = {}) {
541
820
  const subject = this.subject(subjectAid);
542
821
  // Status display reuses the resolve snapshot; consensus verification is
543
822
  // reserved for operations that actually depend on Owner permission.
544
- if (subject.client && subject.view.connected)
545
- return this.refresh(subjectAid);
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
+ }
546
829
  // A fresh snapshot survives transport loss; serve it instead of loading a
547
830
  // short-lived client. Only a stale unattached subject needs a live check.
548
- if (this.isCacheFresh(subject, this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS)) {
831
+ if (!options.force && this.isCacheFresh(subject, this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS)) {
549
832
  return this.snapshot(subjectAid);
550
833
  }
551
834
  const generation = subject.generation;
@@ -555,13 +838,32 @@ export class OwnerResolver {
555
838
  throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
556
839
  }
557
840
  this.applyConsensus(subjectAid, subject, consensus);
841
+ if (options.force)
842
+ await this.refreshTransferTargets(subjectAid, client, false);
558
843
  return this.snapshot(subjectAid);
559
844
  });
560
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
+ }
561
862
  isCacheFresh(subject, maxAgeMs) {
562
863
  const { checkedAt, validUntil, consensusStatus } = subject.view;
563
864
  const now = this.now();
564
- return consensusStatus !== 'unavailable' && consensusStatus !== 'not_applicable'
865
+ // A transient fallback can authorize callers, but is not a successful fresh check.
866
+ return !subject.view.refreshFailure && consensusStatus !== 'unavailable' && consensusStatus !== 'not_applicable'
565
867
  && checkedAt !== undefined && checkedAt <= now && (validUntil ?? 0) > now
566
868
  && now - checkedAt < maxAgeMs;
567
869
  }
@@ -606,14 +908,16 @@ export class OwnerResolver {
606
908
  stop() {
607
909
  for (const subjectAid of this.subjects.keys())
608
910
  this.detachClient(subjectAid);
911
+ this.subjects.clear();
609
912
  this.configuredOwners.clear();
913
+ this.configuredOwnerFileRevision.clear();
610
914
  }
611
- async submitBinding(subjectAid, ownerAid, subject) {
915
+ async submitBinding(subjectAid, ownerAid, subject, assertCurrent) {
612
916
  const client = subject.client;
613
917
  const generation = subject.generation;
614
918
  subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
615
919
  try {
616
- const local = await this.tryLocalBind(subjectAid, ownerAid);
920
+ const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
617
921
  if (local) {
618
922
  if (client && (subject.client !== client || subject.generation !== generation)) {
619
923
  throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during local binding');
@@ -626,7 +930,7 @@ export class OwnerResolver {
626
930
  }
627
931
  if (!client || !subject.view.connected)
628
932
  throw new OwnershipError('SUBJECT_UNAVAILABLE', 'Subject AID SDK client is not ready');
629
- const current = await this.refresh(subjectAid, { force: true });
933
+ const current = await this.refresh(subjectAid, { force: true, source: 'ownership.bind' });
630
934
  if (current.consensusStatus === 'consensus') {
631
935
  if (current.ownerAid === ownerAid)
632
936
  return current;
@@ -635,6 +939,7 @@ export class OwnerResolver {
635
939
  if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus)) {
636
940
  throw new OwnershipError('CONSENSUS_REQUIRED', 'Binding requires a fresh readable ownership baseline');
637
941
  }
942
+ assertCurrent();
638
943
  const task = this.task(await client.bindOwneraid(ownerAid));
639
944
  if (subject.client !== client || subject.generation !== generation) {
640
945
  throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during binding; the request may have been submitted');
@@ -645,13 +950,14 @@ export class OwnerResolver {
645
950
  subject.view.task = task;
646
951
  subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
647
952
  subject.view.reason = task.reason;
953
+ if (task.status === 'rejected')
954
+ this.rememberRejectedOwnerBinding(task);
648
955
  if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
649
956
  throw Object.assign(new OwnershipError(task.code ?? 'BIND_FAILED', task.reason ?? `Binding ended with ${task.status}`), {
650
957
  retryable: task.retryable,
651
958
  });
652
959
  }
653
- this.invalidate(subject, 'Binding submitted; waiting for explicit owner approval and fresh consensus');
654
- this.schedule(subjectAid, subject);
960
+ this.invalidate(subject, 'Binding submitted; waiting for explicit owner approval and fresh consensus', true);
655
961
  return this.snapshot(subjectAid);
656
962
  }
657
963
  catch (error) {
@@ -662,7 +968,246 @@ export class OwnerResolver {
662
968
  throw error;
663
969
  }
664
970
  }
665
- 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) {
666
1211
  let store;
667
1212
  let ownerClient;
668
1213
  let subClient;
@@ -680,6 +1225,7 @@ export class OwnerResolver {
680
1225
  if (typeof ownerClient.bindSubaid !== 'function'
681
1226
  || ownerClient.getType() !== 'agent' || subClient.getType() !== 'agent')
682
1227
  return undefined;
1228
+ assertCurrent();
683
1229
  invoked = true;
684
1230
  const task = this.task(await ownerClient.bindSubaid(subjectAid));
685
1231
  if (!task || task.operation !== 'bind' || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid
@@ -695,8 +1241,11 @@ export class OwnerResolver {
695
1241
  return { task, consensus };
696
1242
  }
697
1243
  catch (error) {
1244
+ if (error instanceof OwnershipError && error.code === 'BIND_CANCELLED')
1245
+ throw error;
698
1246
  if (!invoked) {
699
- 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.
700
1249
  return undefined;
701
1250
  }
702
1251
  throw error;
@@ -721,21 +1270,28 @@ export class OwnerResolver {
721
1270
  }
722
1271
  }
723
1272
  applyConsensus(subjectAid, subject, consensus) {
724
- if (consensus.sub_aid !== subjectAid)
1273
+ if (consensus.sub_aid !== subjectAid) {
1274
+ this.invalidate(subject, 'Ownership consensus subject does not match');
725
1275
  throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus subject does not match');
1276
+ }
726
1277
  const ownerAid = consensus.status === 'consensus' && typeof consensus.owner_aid === 'string'
727
- && isValidAid(consensus.owner_aid) && consensus.owner_aid !== subjectAid ? consensus.owner_aid : undefined;
728
- 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');
729
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
+ }
730
1287
  const previousOwner = this.owner(subjectAid);
731
1288
  const previousStatus = subject.view.consensusStatus;
1289
+ const previousConsensus = subject.view.consensus;
732
1290
  const checkedAt = this.now();
733
1291
  const pending = subject.view.task?.status === 'pending' || subject.view.requestStatus === 'requesting';
734
1292
  subject.view = {
735
1293
  ...subject.view, ownerAid,
736
- relation: consensus.status === 'consensus' || consensus.status === 'unbound' || consensus.status === 'released'
737
- ? { consensusStatus: consensus.status, ownerAid, checkedAt, relationVersion: consensus.relation_version }
738
- : subject.view.relation,
1294
+ relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
739
1295
  authorizationStatus: ownerAid ? 'verified' : 'unavailable', consensusStatus: consensus.status,
740
1296
  consensus: JSON.parse(JSON.stringify(consensus)),
741
1297
  checkedAt, validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
@@ -743,6 +1299,7 @@ export class OwnerResolver {
743
1299
  || subject.view.consensus?.relation_version !== consensus.relation_version
744
1300
  || subject.view.consensus?.lock !== consensus.lock ? 1 : 0),
745
1301
  reason: consensus.reason,
1302
+ refreshFailure: undefined,
746
1303
  synchronization: {
747
1304
  status: consensus.status === 'unavailable' || consensus.status === 'not_applicable' ? 'unavailable'
748
1305
  : consensus.status === 'invalid' ? 'conflict'
@@ -751,8 +1308,47 @@ export class OwnerResolver {
751
1308
  runtimeOwnerAid: ownerAid,
752
1309
  },
753
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
+ }
754
1321
  if (previousOwner !== ownerAid || previousStatus !== consensus.status)
755
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
+ }
756
1352
  }
757
1353
  subject(subjectAid) {
758
1354
  this.assertAid(subjectAid);
@@ -762,6 +1358,8 @@ export class OwnerResolver {
762
1358
  subject = {
763
1359
  generation: 0, epoch: 0, query: 0, subscriptions: [], taskEvents: new Set(),
764
1360
  requests: new Map(), decisionTasks: new Map(),
1361
+ transferTasks: new Map(), transferConsensuses: new Map(), transferIntents: new Map(),
1362
+ transferTerminalOperations: new Map(), transferFlights: new Map(),
765
1363
  view: {
766
1364
  subjectAid, consensusStatus: 'unavailable', authorizationStatus: 'unavailable', connected: false, revision: 0,
767
1365
  synchronization: { status: 'unavailable' },
@@ -770,16 +1368,34 @@ export class OwnerResolver {
770
1368
  this.subjects.set(subjectAid, subject);
771
1369
  return subject;
772
1370
  }
773
- invalidate(subject, reason) {
1371
+ invalidate(subject, reason, preserveVerifiedRelation = false) {
774
1372
  const previousOwner = subject.view.ownerAid;
1373
+ if (!preserveVerifiedRelation)
1374
+ subject.verifiedRelation = undefined;
775
1375
  subject.epoch += 1;
776
1376
  subject.view = {
777
1377
  ...subject.view, ownerAid: undefined, consensusStatus: 'unavailable', authorizationStatus: 'unavailable', validUntil: undefined,
1378
+ ...(subject.view.relation ? { relation: { ...subject.view.relation, isCurrent: false } } : {}),
778
1379
  revision: subject.view.revision + 1, reason, refreshFailure: undefined,
779
1380
  synchronization: { status: 'unavailable' },
780
1381
  };
781
1382
  if (previousOwner)
782
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
+ }
783
1399
  }
784
1400
  notify(subjectAid, ownerAid) {
785
1401
  for (const listener of this.listeners) {
@@ -796,22 +1412,10 @@ export class OwnerResolver {
796
1412
  const ownerAid = subject.view.relation?.ownerAid;
797
1413
  if ((!targetAid && changedAid === subjectAid) || changedAid === ownerAid
798
1414
  || changedAid === subject.view.requestedOwnerAid) {
799
- this.invalidate(subject, 'Ownership material changed; fresh consensus is required');
800
- this.schedule(subjectAid, subject);
1415
+ this.invalidate(subject, 'Ownership material changed; fresh consensus is required', true);
801
1416
  }
802
1417
  }
803
1418
  }
804
- schedule(subjectAid, subject) {
805
- if (subject.timer || !subject.client || !subject.view.connected)
806
- return;
807
- subject.timer = setTimeout(() => {
808
- subject.timer = undefined;
809
- void this.refresh(subjectAid, { force: true, allowTransient: true }).catch(error => {
810
- logger.warn(`[ownership] Event refresh failed for ${subjectAid}: ${error instanceof Error ? error.message : String(error)}`);
811
- });
812
- }, 0);
813
- subject.timer.unref?.();
814
- }
815
1419
  now() {
816
1420
  return this.options.now?.() ?? Date.now();
817
1421
  }
@@ -853,12 +1457,12 @@ export class OwnerResolver {
853
1457
  trackBindingRequest(localAid, subject, event, record) {
854
1458
  const requestAction = record.action === 'bind.request' || record.action === 'transfer.request';
855
1459
  if (event === 'ownership.request'
856
- && (record.operation !== 'bind' || (record.action !== undefined && !requestAction)))
1460
+ && (!['bind', 'transfer'].includes(String(record.operation)) || (record.action !== undefined && !requestAction)))
857
1461
  return;
858
1462
  const task = this.bindingTask(event === 'ownership.request'
859
1463
  ? { ...record, status: 'pending', step: 'approval' }
860
1464
  : record, event);
861
- 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))
862
1466
  return;
863
1467
  const request = subject.requests.get(task.operation_id);
864
1468
  const decisionTask = subject.decisionTasks.get(task.operation_id);
@@ -867,15 +1471,21 @@ export class OwnerResolver {
867
1471
  return;
868
1472
  if (event === 'ownership.request') {
869
1473
  const requester = record.requester_aid;
870
- const remote = task.sub_aid === localAid ? task.owner_aid : task.sub_aid;
871
- 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)
872
1480
  return;
873
1481
  subject.requests.set(task.operation_id, {
874
- ...task, requester_aid: remote, local_role: task.sub_aid === localAid ? 'sub' : 'owner',
1482
+ ...task, requester_aid: remote, local_role: localRole,
875
1483
  });
876
- logger.info(`[ownership] inbound binding ${JSON.stringify({
877
- localAid, operationId: task.operation_id, subAid: task.sub_aid, ownerAid: task.owner_aid,
878
- })}`);
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
+ });
879
1489
  }
880
1490
  else {
881
1491
  const awaitingApproval = task.step === 'approval'
@@ -906,12 +1516,12 @@ export class OwnerResolver {
906
1516
  /** Only public task fields are exposed; raw SDK records remain SDK-owned. */
907
1517
  bindingTask(value, event) {
908
1518
  const task = this.task(value, event);
909
- if (!task || task.operation !== 'bind' || !CREATION_BIND_OPERATION_ID.test(task.operation_id)
910
- || 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)
911
1521
  || task.base_relation_version < 0 || !Number.isSafeInteger(task.target_relation_version)
912
- || task.target_relation_version !== task.base_relation_version + 1)
913
- return undefined;
914
- 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)))
915
1525
  return undefined;
916
1526
  return {
917
1527
  operation_id: task.operation_id, operation: task.operation, sub_aid: task.sub_aid, owner_aid: task.owner_aid,
@@ -931,6 +1541,7 @@ export class OwnerResolver {
931
1541
  || !['bind', 'transfer'].includes(String(record.operation)) || typeof record.sub_aid !== 'string' || !isValidAid(record.sub_aid)
932
1542
  || typeof record.owner_aid !== 'string' || !isValidAid(record.owner_aid)
933
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)
934
1545
  || typeof baseRelationVersion !== 'number' || !Number.isSafeInteger(baseRelationVersion) || baseRelationVersion < 0
935
1546
  || typeof targetRelationVersion !== 'number' || !Number.isSafeInteger(targetRelationVersion)
936
1547
  || targetRelationVersion !== baseRelationVersion + 1)
@@ -963,12 +1574,13 @@ export const getDaemonOwners = () => ownerResolver.daemonOwners();
963
1574
  export async function refreshOwnershipForAuthorization(subjectAid, options = {}) {
964
1575
  const daemonAid = ownerResolver.getDaemonAid();
965
1576
  const ownershipSubjectAid = daemonAid && subjectAid === `${daemonAid}#daemon` ? daemonAid : subjectAid;
966
- const subjects = new Set([ownershipSubjectAid, ...(!ownershipSubjectAid || options.includeDaemon !== false ? [daemonAid] : [])]
1577
+ const subjects = new Set([ownershipSubjectAid ?? daemonAid, ...(options.includeDaemon === true ? [daemonAid] : [])]
967
1578
  .filter((aid) => !!aid));
968
1579
  const views = await Promise.all([...subjects].map(aid => ownerResolver.refresh(aid, {
969
1580
  maxAgeMs: options.maxAgeMs ?? OWNERSHIP_AUTHORIZATION_MAX_AGE_MS,
970
1581
  force: options.force,
971
1582
  allowTransient: options.allowTransient,
1583
+ source: options.source ?? 'authorization',
972
1584
  })));
973
1585
  if (!options.allowTransient) {
974
1586
  const failure = views.find(view => view.consensusStatus === 'unavailable' && view.refreshFailure);
@@ -983,32 +1595,32 @@ export async function assertOwnershipAuthorization(context) {
983
1595
  const ownerActor = hasTrustedPrincipal(context?.actor) ? context.actor.principalId : undefined;
984
1596
  if (!authorization && !ownerRole)
985
1597
  return;
986
- await refreshOwnershipForAuthorization(context?.selfAid ?? authorization?.agentAid, { allowTransient: true });
1598
+ await refreshOwnershipForAuthorization(context?.selfAid ?? authorization?.agentAid, {
1599
+ allowTransient: true, includeDaemon: !!authorization,
1600
+ });
987
1601
  const subjectAid = context?.selfAid ?? authorization?.agentAid;
988
1602
  if (authorization) {
989
1603
  if (!getDaemonOwners().includes(authorization.authorizedBy)
990
1604
  || (authorization.source === 'agent-policy'
991
1605
  && !ownerResolver.isOwner(authorization.agentAid ?? '', authorization.authorizedBy))) {
992
1606
  const view = subjectAid ? ownerResolver.snapshot(subjectAid) : undefined;
993
- logger.warn(`[ownership] authorization denied ${JSON.stringify({
994
- subjectAid, authorizedBy: authorization.authorizedBy,
1607
+ logOwnershipEvent('authorization.denied', {
1608
+ subjectAid, actorAid: authorization.authorizedBy, ownerAid: view?.relation?.ownerAid,
995
1609
  consensusStatus: view?.consensusStatus,
996
- failureCode: view?.refreshFailure?.code,
997
- refreshFailure: view?.refreshFailure?.reason,
998
- refreshFailureKind: view?.refreshFailure?.kind,
999
- })}`);
1610
+ relationVersion: view?.consensus?.relation_version,
1611
+ errorCode: view?.refreshFailure?.code ?? 'OWNER_UNAVAILABLE',
1612
+ }, true);
1000
1613
  throw new OwnershipError('OWNER_UNAVAILABLE', 'Current Owner no longer authorizes this execution');
1001
1614
  }
1002
1615
  }
1003
1616
  else if (!context?.selfAid || !ownerResolver.isOwner(context.selfAid, ownerActor)) {
1004
1617
  const view = context?.selfAid ? ownerResolver.snapshot(context.selfAid) : undefined;
1005
- logger.warn(`[ownership] authorization denied ${JSON.stringify({
1006
- subjectAid: context?.selfAid, actorAid: ownerActor,
1618
+ logOwnershipEvent('authorization.denied', {
1619
+ subjectAid: context?.selfAid, actorAid: ownerActor, ownerAid: view?.relation?.ownerAid,
1007
1620
  consensusStatus: view?.consensusStatus,
1008
- failureCode: view?.refreshFailure?.code,
1009
- refreshFailure: view?.refreshFailure?.reason,
1010
- refreshFailureKind: view?.refreshFailure?.kind,
1011
- })}`);
1621
+ relationVersion: view?.consensus?.relation_version,
1622
+ errorCode: view?.refreshFailure?.code ?? 'OWNER_UNAVAILABLE',
1623
+ }, true);
1012
1624
  throw new OwnershipError('OWNER_UNAVAILABLE', 'Current Owner could not be verified; start a new task with the current role');
1013
1625
  }
1014
1626
  }