weir-harness 1.1.6 → 1.1.7

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.
@@ -213,8 +213,64 @@ export function createBlackboardStorage({ home, hook = async (_op, _path) => {},
213
213
  return result.publish()
214
214
  } finally { await release() }
215
215
  }
216
+ // One-time fork seeding: a forked Session is its own board root, but its
217
+ // board starts as a snapshot of the fork source's durable root board. Both
218
+ // directories stay under the writer lock in deterministic path order, and
219
+ // the fork is only ever seeded while it has no sidecar of its own — a
220
+ // re-seed can never overwrite or merge an initialized board.
221
+ async function seedFork(id, parentId, cwd) {
222
+ sessionId(id)
223
+ let hopId = sessionId(parentId)
224
+ // The source's durable root is resolved on disk: a delegated source has
225
+ // no sidecar of its own, so ascend its parent chain to the root board it
226
+ // actually used.
227
+ const seen = new Set()
228
+ let source
229
+ for (let hop = 0; hop < 64; hop++) {
230
+ if (seen.has(hopId)) throw new Error('blackboard: cyclic Session parent chain')
231
+ seen.add(hopId)
232
+ const located = await locateSession(home, hopId)
233
+ const depth = located.header.delegationDepth ?? 0
234
+ if (!Number.isSafeInteger(depth) || depth < 0) throw new Error('blackboard: invalid Session delegation depth')
235
+ if (depth === 0) { source = located; break }
236
+ hopId = sessionId(located.header.parentSession)
237
+ }
238
+ if (!source) throw new Error('blackboard: Session ancestry exceeds safety limit')
239
+ const child = await locateSession(home, id, cwd)
240
+ // Two directories need two writer locks; taking them in deterministic
241
+ // path-string order means single-lock users (transact) can never
242
+ // deadlock with this pair. Distinct Session ids never share a directory.
243
+ const [first, second] = source.dir < child.dir ? [source.dir, child.dir] : [child.dir, source.dir]
244
+ const releaseFirst = await lock(first)
245
+ let releaseSecond
246
+ try { releaseSecond = await lock(second) } catch (error) { await releaseFirst(); throw error }
247
+ try {
248
+ const records = []
249
+ for (const name of (await fs.readdir(source.dir)).filter(name => SIDE.test(name))) {
250
+ records.push(decodeRecord(await safeRead(join(source.dir, name)), source.id))
251
+ }
252
+ if (!records.length) return false
253
+ if (records.some(record => JSON.stringify(record) !== JSON.stringify(records[0]))) throw new Error('blackboard: conflicting sidecars; originals preserved')
254
+ // Idempotence: any existing fork sidecar means the board is already
255
+ // initialized — never overwrite or merge.
256
+ if ((await fs.readdir(child.dir)).some(name => SIDE.test(name))) return false
257
+ // Volatile state (tokens/subscriptions/timers) is never persisted, so
258
+ // the snapshot carries durable entry fields only; the fork starts at
259
+ // revision 0 under its own root identity.
260
+ const seeded = { schemaVersion: 1, rootSessionId: id, revision: 0, entries: structuredClone(records[0].entries) }
261
+ const encoded = JSON.stringify(decodeRecord(JSON.stringify(seeded), id)) + '\n'
262
+ await publish(child.file, encoded)
263
+ return true
264
+ } finally {
265
+ let failure
266
+ try { await releaseSecond() } catch (error) { failure ??= error }
267
+ try { await releaseFirst() } catch (error) { failure ??= error }
268
+ if (failure) throw failure
269
+ }
270
+ }
216
271
  return {
217
272
  locate: (id, cwd) => locateSession(home, id, cwd),
273
+ seedFork,
218
274
  async releaseWriter(id, cwd) {
219
275
  let where
220
276
  try { where = await locateSession(home, id, cwd) } catch { return }
@@ -2,6 +2,7 @@
2
2
  * @param {number | undefined} pid @param {string} attestation */
3
3
  export function bindingRefusalReason(pid, attestation) {
4
4
  const holder = attestation === 'serving' ? 'serving'
5
+ : attestation === 'serving-idle' ? 'serving-idle'
5
6
  : pid === process.pid ? 'same-process-unattestable'
6
7
  : pid !== undefined ? 'cross-process-pid' : 'unknown'
7
8
  return `session already bound: holder=${holder}${pid !== undefined ? `; pid=${pid}` : ''}`
@@ -10,12 +11,20 @@ export function bindingRefusalReason(pid, attestation) {
10
11
  /** Render only publisher-classified facts. Unrecognized/legacy reasons are unknown.
11
12
  * @param {string} sessionId @param {string} reason */
12
13
  export function bindingGuidance(sessionId, reason) {
13
- const facts = /^session already bound: holder=(serving|same-process-unattestable|cross-process-pid|unknown)(?:; pid=([1-9]\d*))?$/.exec(reason)
14
+ const facts = /^session already bound: holder=(serving-idle|serving|same-process-unattestable|cross-process-pid|unknown)(?:; pid=([1-9]\d*))?$/.exec(reason)
14
15
  const classification = facts?.[1]
15
16
  const pid = facts?.[2]
16
17
  let holder
17
- if (classification === 'serving') {
18
- holder = `session ${sessionId} is already active in the DeepSeek Harness window that publishes this project. Use the session in that window, close it there, or quit that Harness process.`
18
+ if (classification === 'serving-idle') {
19
+ // Transferable (change edit-lock-binding-transfer): an idle same-process
20
+ // holder is taken over by the next driving ingress — calm copy, no pid,
21
+ // no window hunt, and NEVER the publisher-reservation warning.
22
+ holder = `session ${sessionId} is held by an inactive attachment of this same session. Editing attaches here automatically when you next send a message; /edit-lock retry also takes it over now. Retry does not Continue editing.`
23
+ } else if (classification === 'serving') {
24
+ // The holder is provably live and not transferable (mid-turn or a live
25
+ // channel proxy): name what is happening and when to retry. No window
26
+ // hunt (single-instance hosts exist) and no process management.
27
+ holder = `session ${sessionId} is being edited in another attachment right now. Wait for that turn to finish, then use /edit-lock retry in this session; retry does not Continue editing.`
19
28
  } else if (classification === 'same-process-unattestable' && pid !== undefined) {
20
29
  holder = `session ${sessionId} has a binding in this same process (pid ${pid}) that cannot be safely reclaimed. A stale runtime incarnation may still hold its channel. Wait for the original holder to disconnect or for confirmed process shutdown.`
21
30
  } else if (classification === 'cross-process-pid' && pid !== undefined) {
@@ -23,6 +32,7 @@ export function bindingGuidance(sessionId, reason) {
23
32
  } else {
24
33
  holder = `session ${sessionId} has a binding whose holder cannot be attested. Wait for the original holder to disconnect or for confirmed process shutdown.`
25
34
  }
35
+ if (classification === 'serving-idle' || classification === 'serving') return holder
26
36
  return `${holder} Then use /edit-lock retry in the original session when available; retry does not Continue editing. Do NOT remove the publisher reservation (.weir/.edit-lock.publisher-reservation) while its process is alive — removing it would split the edit authority.`
27
37
  }
28
38
 
@@ -32,7 +42,8 @@ export function bindingGuidance(sessionId, reason) {
32
42
  export function bindingFailure(pid, attestation, revocationFailed = false) {
33
43
  return { code: 'binding-duplicate', retryable: true,
34
44
  holderKind: revocationFailed ? 'revocation-failed' : attestation === 'serving' ? 'serving'
35
- : pid !== undefined && pid !== process.pid ? 'cross-process' : 'unknown',
45
+ : attestation === 'serving-idle' ? 'transferable'
46
+ : pid !== undefined && pid !== process.pid ? 'cross-process' : 'unknown',
36
47
  holderPid: pid ?? null }
37
48
  }
38
49
  /** @param {number | undefined} pid @param {string} attestation @param {boolean} [revocationFailed] */
@@ -15,6 +15,14 @@ export function localDomain(lifecycle, endpoint) {
15
15
  lifecycle.assertStartable(agent)
16
16
  return endpoint?.startLocal ? endpoint.startLocal(agent, true) : lifecycle.start(agent)
17
17
  },
18
+ /** Trusted binding transfer (change edit-lock-binding-transfer): the
19
+ * explicit driving-ingress counterpart of retryStart — the holder-side
20
+ * admission (local, registry-named, provably idle holder) is re-adjudicated
21
+ * at execution and refuses exactly like start() otherwise. @param {object} agent */
22
+ transferStart: async agent => {
23
+ lifecycle.assertStartable(agent)
24
+ return endpoint?.startLocal ? endpoint.startLocal(agent, true, true) : lifecycle.transferStart(agent)
25
+ },
18
26
  /** Synchronous admission fence for an aborted turn. @param {object} agent */
19
27
  latch: agent => { lifecycle.stop(agent).catch(() => {}) },
20
28
  /** @param {object} agent */
@@ -86,6 +94,10 @@ export function remoteDomain(remote) {
86
94
  start: async agent => (await remote.channelFor(agent)).state,
87
95
  /** @param {object} agent */
88
96
  retryStart: async agent => (await remote.channelFor(agent, true)).state,
97
+ /** The wire retry flag carries the transfer admission to the publisher
98
+ * (its lifecycle re-adjudicates holder idleness); the client adds nothing. */
99
+ /** @param {object} agent */
100
+ transferStart: async agent => (await remote.channelFor(agent, true)).state,
89
101
  /** @param {object} agent */
90
102
  forget: async agent => { try { await remote.call(agent, 'stop') } finally { remote.drop(agent) } },
91
103
  /** Closing the channel makes the publisher revoke on EOF. @param {object} agent */
@@ -258,7 +258,7 @@ function registerLockTools(ctx, service) {
258
258
  output: text('message'),
259
259
  async execute(/** @type {any} */ _args, /** @type {any} */ exec) {
260
260
  const unavailable = service.startupFailure(exec.agent)
261
- if (unavailable) return { ...unavailable, message: `Edit Lock unavailable: ${unavailable.reason}. ${unavailable.bindingFailure?.retryable ? 'Do not retry failed edits: the binding is retried automatically when the user next sends a message, and /edit-lock retry also retries the connection; neither resumes editing by itself.' : 'Inspect Edit Lock maintenance before continuing.'}` }
261
+ if (unavailable) return { ...unavailable, message: `Edit Lock unavailable: ${unavailable.reason}. ${statusRetryHint(unavailable.bindingFailure)}` }
262
262
  const locks = await service.locks(exec)
263
263
  const lines = locks.map((/** @type {any} */ lock) => `- ${lock.resourceId} owner=${lock.mine ? 'this session' : lock.owner} status=${lock.status} generation=${lock.generation}${lock.reason ? ` reason=${lock.reason}` : ''}`)
264
264
  // The reservation is part of what the holder needs to know: without it the
@@ -310,6 +310,41 @@ function describe(status) {
310
310
  return lines.join('\n')
311
311
  }
312
312
 
313
+ /** In-session binding-failure notice copy (change edit-lock-binding-transfer,
314
+ * design D4): the transferable class (same-process idle holder) is a calm
315
+ * self-heal announcement rather than an editing-disabled alarm and never
316
+ * carries the raw holder classification or the reservation warning; a mid-turn
317
+ * holder names the real state and the retry moment. Template layer stays
318
+ * English (AGENTS §3.7). @param {string} reason @param {any} failure */
319
+ function bindingFailureNotice(reason, failure) {
320
+ if (failure?.code === 'binding-duplicate' && failure.holderKind === 'transferable') {
321
+ return "Edit Lock: this session's editing authority is held by an inactive attachment of this same session; it transfers automatically when you send a message."
322
+ }
323
+ if (failure?.code === 'binding-duplicate' && failure.holderKind === 'serving') {
324
+ return "Edit Lock: this session is being edited in another attachment right now; managed file editing stays unavailable until that turn finishes. Do not retry the failed edit; use /edit-lock retry (or the panel's Retry connection) once it finishes — retry does not Continue editing."
325
+ }
326
+ return `Edit Lock could not start this session's edit domain (${reason}); managed file editing is temporarily unavailable. ${failure?.code === 'binding-duplicate' ? 'Do not retry the failed edit: the binding is retried automatically when the user next sends a message, after which editing works normally. Never remove a live publisher reservation.' : 'Inspect Edit Lock maintenance before continuing.'}`
327
+ }
328
+
329
+ /** Read-only binding-unavailable guidance tail for the tool/service surfaces
330
+ * (domainFor and edit_lock_status), split by the recorded holder class.
331
+ * @param {string} failure @param {any} bindingFailure */
332
+ function bindingUnavailableMessage(failure, bindingFailure) {
333
+ const kind = bindingFailure?.holderKind
334
+ if (kind === 'transferable') return `Edit Lock binding is unavailable (${failure}). The holder is an inactive attachment of this same session: the binding transfers automatically when the user next sends a message, and /edit-lock retry also takes it over; neither resumes editing by itself. Do not retry the failed edit.`
335
+ if (kind === 'serving') return `Edit Lock binding is unavailable (${failure}). This session is being edited in another attachment right now; retry the connection once that turn finishes. Do not retry the failed edit.`
336
+ return `Edit Lock binding is unavailable (${failure}). Do not retry the failed edit: the binding is retried automatically when the user next sends a message, after which editing works normally. Never remove a live publisher reservation.`
337
+ }
338
+
339
+ /** edit_lock_status read-only guidance tail, split by the recorded holder
340
+ * class (change edit-lock-binding-transfer). @param {any} bindingFailure */
341
+ function statusRetryHint(bindingFailure) {
342
+ if (bindingFailure?.retryable !== true) return 'Inspect Edit Lock maintenance before continuing.'
343
+ if (bindingFailure.holderKind === 'transferable') return 'The holder is an inactive attachment of this same session: editing attaches automatically when you next send a message, and /edit-lock retry also takes it over; neither resumes editing by itself.'
344
+ if (bindingFailure.holderKind === 'serving') return 'This session is being edited in another attachment right now; /edit-lock retry retries the connection once that turn finishes — it does not resume editing by itself.'
345
+ return 'Do not retry failed edits: the binding is retried automatically when the user next sends a message, and /edit-lock retry also retries the connection; neither resumes editing by itself.'
346
+ }
347
+
313
348
  /** Composition dependencies, not persisted settings. Defaults are the host paths.
314
349
  * @param {{ platform?: string, resolveRoot?: typeof managementRootFor, endpoint?: typeof endpointFor, exclude?: typeof excludeFromGit }} [dependencies] */
315
350
  export function createEditLockPlugin({ platform = process.platform, resolveRoot = managementRootFor, endpoint = endpointFor, exclude = excludeFromGit } = {}) {
@@ -474,11 +509,18 @@ return (ctx, config = {}) => {
474
509
  })
475
510
  let server
476
511
  try { server = await serveEditLockEndpoint(lifecycle, endpoint(directory), sinks, attestBinding,
477
- (agent, requireProof) => {
512
+ (agent, requireProof, transfer = false) => {
478
513
  if (closed || disposedAgents.has(agent)) return false
479
514
  const agents = ctx.get?.('agents')
480
515
  if (typeof agents?.get === 'function') {
481
- if (agents.get(agent.id) !== agent) return false
516
+ if (transfer === true) {
517
+ // A transfer claimant is NEVER the registry's serving agent —
518
+ // that mismatch is the defect being repaired (change
519
+ // edit-lock-binding-transfer). Its liveness proof is listing
520
+ // among the live root agents; holder-side admission is the
521
+ // lifecycle's transferStart.
522
+ if (typeof agents.roots !== 'function' || !agents.roots().includes(agent)) return false
523
+ } else if (agents.get(agent.id) !== agent) return false
482
524
  } else if (requireProof) return false
483
525
  // Fresh creation keeps the established missing/throwing-registry
484
526
  // fallback. A reclaim or retry never uses that fallback as proof.
@@ -520,7 +562,7 @@ return (ctx, config = {}) => {
520
562
  await setupInFlight.get(agent)
521
563
  if (settled.has(agent)) return settled.get(agent)
522
564
  const failure = startFailures.get(agent)
523
- if (failure && bindingFailures.has(agent)) throw new Error(`Edit Lock binding is unavailable (${failure}). Do not retry the failed edit: the binding is retried automatically when the user next sends a message, after which editing works normally. Never remove a live publisher reservation.`)
565
+ if (failure && bindingFailures.has(agent)) throw new Error(bindingUnavailableMessage(failure, bindingFailures.get(agent)))
524
566
  if (failure) throw new Error(`this session has no Edit Lock domain: setup failed under the current preset generation (${failure}); the automatic re-bind was already attempted. Recovery: restart DeepSeek Harness or start a new conversation.`)
525
567
  // No fence match (foreign preset) or unmount: keep the stock refusal.
526
568
  return registry.forAgent(agent)
@@ -623,7 +665,17 @@ return (ctx, config = {}) => {
623
665
  if (platformFailure) return { state: 'unavailable', reason: platformFailure.message, bindingFailure: null }
624
666
  if (!agent || settled.has(agent) || !startFailures.has(agent)) return null
625
667
  let eligible = false
626
- try { eligible = !closed && !disposedAgents.has(agent) && ownAgent(agent) && servingRuntime(agent.id) === agent } catch { /* no trusted live identity */ }
668
+ try {
669
+ const serving = servingRuntime(agent.id)
670
+ eligible = !closed && !disposedAgents.has(agent) && ownAgent(agent)
671
+ && (serving === agent
672
+ // The registry names ANOTHER live local agent — the dual-agent defect
673
+ // this change heals (edit-lock-binding-transfer). The recorded
674
+ // duplicate-binding failure is still THIS agent's honest panel state:
675
+ // show it, with its Retry action, instead of hiding behind the ghost's
676
+ // healthy binding. An empty registry stays hidden (unattestable).
677
+ || (serving !== undefined && bindingFailures.get(agent)?.code === 'binding-duplicate'))
678
+ } catch { /* no trusted live identity */ }
627
679
  if (!eligible) return null
628
680
  const failure = bindingFailures.get(agent)
629
681
  return { state: 'unavailable', reason: startFailures.get(agent),
@@ -700,6 +752,15 @@ return (ctx, config = {}) => {
700
752
  const agent = exec?.agent
701
753
  if (!closed && agent && !registry.rootOf(agent) && !startFailures.has(agent) && (agent?.session?.header?.delegationDepth ?? 0) === 0 && ownAgent(agent)) {
702
754
  await setupAgent(agent)
755
+ // The lazy re-bind is a driving ingress (design D1, change
756
+ // edit-lock-binding-transfer): when the re-setup just recorded a
757
+ // duplicate-binding failure, ONE transfer-capable retry runs here — an
758
+ // idle same-process holder hands the binding over mid-turn. The recorded
759
+ // failure then suppresses further attempts for the rest of this mount
760
+ // generation, so arbitrary write calls never loop retries.
761
+ if (bindingFailures.get(agent)?.code === 'binding-duplicate') {
762
+ try { await retryBinding(agent, 'write-guard') } catch { /* audited inside retryBinding; the denial below names the recorded cause */ }
763
+ }
703
764
  if (admitted()) return next()
704
765
  }
705
766
  const failure = /** @type {any} */ (agent) ? startFailures.get(agent) : undefined
@@ -728,8 +789,12 @@ return (ctx, config = {}) => {
728
789
  * re-bind, so the paths can never diverge. Root selection and successful
729
790
  * startup are separate: explicit binding retry reuses the existing scope
730
791
  * and root, while ordinary entry points never repeat a failed startup.
731
- * @param {any} agent */
732
- async function setupAgentOnce(agent, retry = false) {
792
+ * @param {any} agent @param {boolean} [retry] @param {boolean} [transfer]
793
+ * transfer (change edit-lock-binding-transfer) marks the driving-ingress
794
+ * transfer admission: the domain's transferStart re-adjudicates holder
795
+ * idleness at execution, and the post-bind registry-identity check is
796
+ * skipped because the registry legitimately still names the idle holder. */
797
+ async function setupAgentOnce(agent, retry = false, transfer = false) {
733
798
  if (closed || settled.has(agent)) return
734
799
  // No writer scope, root resolution, directory, reservation or session
735
800
  // authority may be installed when the mount preflight failed.
@@ -764,9 +829,10 @@ return (ctx, config = {}) => {
764
829
  }
765
830
  try {
766
831
  const domain = await domainOf(agent)
767
- if (retry) await domain.retryStart(agent)
832
+ if (transfer) await domain.transferStart(agent)
833
+ else if (retry) await domain.retryStart(agent)
768
834
  else await domain.start(agent)
769
- if (closed || disposedAgents.has(agent) || (retry && (!ownAgent(agent) || servingRuntime(agent.id) !== agent))) {
835
+ if (closed || disposedAgents.has(agent) || (retry && (!ownAgent(agent) || (!transfer && servingRuntime(agent.id) !== agent)))) {
770
836
  await domain.forget(agent)
771
837
  throw new Error('Edit Lock mount changed during binding')
772
838
  }
@@ -790,7 +856,7 @@ return (ctx, config = {}) => {
790
856
  if (failure?.code === 'binding-duplicate') bindingFailures.set(agent, failure)
791
857
  else bindingFailures.delete(agent)
792
858
  try { evidence?.recordSessionFailure?.(sessionOf(agent), reason) } catch { /* reporting only */ }
793
- try { deliverLocal(agent, `Edit Lock could not start this session's edit domain (${reason}); managed file editing is temporarily unavailable. ${failure?.code === 'binding-duplicate' ? 'Do not retry the failed edit: the binding is retried automatically when the user next sends a message, after which editing works normally. Never remove a live publisher reservation.' : 'Inspect Edit Lock maintenance before continuing.'}`) } catch { /* the panel record remains */ }
859
+ try { deliverLocal(agent, bindingFailureNotice(reason, failure)) } catch { /* the panel record remains */ }
794
860
  ctx.logger?.warn?.(`edit lock registration failed for ${sessionOf(agent)}: ${reason}`)
795
861
  }
796
862
  }
@@ -806,20 +872,64 @@ return (ctx, config = {}) => {
806
872
  setupInFlight.set(agent, task)
807
873
  return task
808
874
  }
809
- /** Trusted command ingress only. Same Agent/root/mount; no writer reinstallation.
810
- * @param {any} agent */
811
- async function retryBinding(agent) {
812
- if (closed || disposedAgents.has(agent) || !ownAgent(agent) || servingRuntime(agent.id) !== agent) throw new Error('Edit Lock retry requires the current live Agent of this mount')
875
+ /** Trusted driving ingresses only: the explicit /edit-lock retry (and panel
876
+ * action), the message-armed pre-step retry, and the write-guard lazy
877
+ * re-bind. Same Agent/root/mount; no writer reinstallation. Every attempt
878
+ * past the eligibility gate is audited — a silently swallowed refusal is a
879
+ * defect (change edit-lock-binding-transfer, design D3/D5).
880
+ * @param {any} agent @param {'command' | 'message' | 'write-guard'} [via] */
881
+ async function retryBinding(agent, via = 'command') {
882
+ if (closed || disposedAgents.has(agent) || !ownAgent(agent)) throw new Error('Edit Lock retry requires the current live Agent of this mount')
813
883
  if (!registry.rootOf(agent) || bindingFailures.get(agent)?.code !== 'binding-duplicate') throw new Error('Edit Lock startup failure is not eligible for binding retry')
814
- let task = setupInFlight.get(agent)
815
- if (!task) {
816
- const inner = setupAgentOnce(agent, true)
817
- task = inner.finally(() => { if (setupInFlight.get(agent) === task) setupInFlight.delete(agent) })
818
- setupInFlight.set(agent, task)
884
+ const cause = bindingFailures.get(agent)
885
+ const sessionId = sessionOf(agent) ?? null
886
+ const root = registry.rootOf(agent) ?? undefined
887
+ /** @param {string} result @param {Record<string, unknown>} [extra] */
888
+ const record = (result, extra = {}) => audit(agent?.session ?? null, AUDIT_TYPES.editLockMaintenance, {
889
+ kind: 'binding-transfer', sessionId, code: cause?.code ?? 'binding-duplicate', result, ...extra,
890
+ }, { root })
891
+ // Attestation trichotomy (design D5): the registry naming THIS claimant
892
+ // keeps the existing superseded rebind; naming ANOTHER live local agent
893
+ // routes to the transfer admission (holder idleness is re-adjudicated at
894
+ // execution, publisher-side); an unavailable or empty registry stays
895
+ // fail-closed — the holder cannot be attested.
896
+ let serving
897
+ try { serving = servingRuntime(agent.id) } catch { serving = undefined }
898
+ if (serving === undefined) {
899
+ const error = new Error('Edit Lock binding retry refused: the agent registry is unavailable or names no live agent for this session, so the holder cannot be attested. The recorded cause stays; a later retry remains possible.')
900
+ record('refused', { reason: 'registry-unattestable', detail: error.message })
901
+ throw error
902
+ }
903
+ const transfer = serving !== agent
904
+ try {
905
+ let task = setupInFlight.get(agent)
906
+ if (!task) {
907
+ const inner = setupAgentOnce(agent, true, transfer)
908
+ task = inner.finally(() => { if (setupInFlight.get(agent) === task) setupInFlight.delete(agent) })
909
+ setupInFlight.set(agent, task)
910
+ }
911
+ await task
912
+ } catch (error) {
913
+ record('refused', { reason: /** @type {any} */ (error)?.bindingFailure?.holderKind ?? 'retry-refused', detail: String(/** @type {any} */ (error)?.message ?? error) })
914
+ throw error
819
915
  }
820
- await task
821
916
  const failure = startFailures.get(agent)
822
- if (failure || !settled.has(agent)) throw new Error(failure ?? 'Edit Lock binding remains unavailable')
917
+ if (failure || !settled.has(agent)) {
918
+ // setupAgentOnce records instead of rethrowing: the refusal's holder
919
+ // class comes from the freshly re-recorded structured failure.
920
+ const error = new Error(failure ?? 'Edit Lock binding remains unavailable')
921
+ record('refused', { reason: bindingFailures.get(agent)?.holderKind ?? 'binding-unavailable', detail: error.message })
922
+ throw error
923
+ }
924
+ if (transfer) {
925
+ record('transferred', { holder: cause?.holderKind ?? null })
926
+ } else if (via === 'message') {
927
+ // The message-armed superseded success keeps its established audit shape
928
+ // (pinned by the editlock-binding-auto-retry integration scenario).
929
+ audit(agent?.session ?? null, AUDIT_TYPES.editLockMaintenance, {
930
+ kind: 'binding-auto-retry', sessionId, code: cause?.code ?? 'binding-duplicate', result: 'recovered',
931
+ }, { root })
932
+ }
823
933
  return 'Edit Lock connection recovered. Editing remains interrupted; use Continue editing when ready. No failed edit was replayed.'
824
934
  }
825
935
  ctx.on('agent/created', (/** @type {any} */ { agent }) => setupAgent(agent))
@@ -953,17 +1063,17 @@ return (ctx, config = {}) => {
953
1063
  lastTurn.set(agent, turn)
954
1064
  if (pendingBindingRetry.get(agent) === true) {
955
1065
  pendingBindingRetry.delete(agent)
956
- const cause = bindingFailures.get(agent)
957
1066
  try {
958
- await retryBinding(agent)
1067
+ await retryBinding(agent, 'message')
959
1068
  // The genuine message that armed this retry is also this turn's
960
1069
  // Continue receipt: re-arm what setupAgentOnce(retry) cleared, then
961
- // fall through to the ordinary auto-resume consumption below.
1070
+ // fall through to the ordinary auto-resume consumption below. A
1071
+ // transfer success (registry named an idle same-process holder)
1072
+ // lands here identically: bound interrupted, then resumed in-turn.
962
1073
  pendingAutoResume.set(agent, true)
963
- audit(agent?.session ?? null, AUDIT_TYPES.editLockMaintenance, {
964
- kind: 'binding-auto-retry', sessionId: sessionOf(agent) ?? null,
965
- code: cause?.code ?? 'binding-duplicate', result: 'recovered',
966
- }, { root: registry.rootOf(agent) ?? undefined })
1074
+ // The outcome audit (transferred / refused) was written inside
1075
+ // retryBinding — success AND refusal alike; the catch below is not
1076
+ // a silent swallow any more (design D3).
967
1077
  } catch { /* a safe refusal keeps the recorded cause; the turn proceeds with edits denied */ }
968
1078
  }
969
1079
  const domain = settled.get(agent)
@@ -169,6 +169,17 @@ export function createEditLockLifecycle(runtime, sessionForAgent, options = {})
169
169
  }
170
170
  return result
171
171
  }
172
+ /** Holder liveness signal (change edit-lock-binding-transfer, task 1.1): the
173
+ * DSH agent `status` vocabulary is exactly 'idle' | 'running' (idle covers the
174
+ * idle and maintenance phases). Only 'idle' proves the holder is not mid-turn;
175
+ * a missing, non-string or throwing read is undeterminable and never admits.
176
+ * @param {object} holder @returns {string | undefined} */
177
+ function holderStatus(holder) {
178
+ try {
179
+ const status = /** @type {any} */ (holder)?.status
180
+ return typeof status === 'string' ? status : undefined
181
+ } catch { return undefined }
182
+ }
172
183
  /** Read-only startup admission. A revoked session is startable: it binds as
173
184
  * interrupted and its revocation ends only through the trusted resume path
174
185
  * (the epoch advance is the repair; binding alone grants no authority).
@@ -195,11 +206,17 @@ export function createEditLockLifecycle(runtime, sessionForAgent, options = {})
195
206
  if (prior) {
196
207
  let serving
197
208
  try { serving = options.servingRuntime?.(sessionId) } catch { /* unknown: refuse */ }
209
+ // A registry-named local holder that is provably not mid-turn is the
210
+ // TRANSFERABLE class (serving-idle): passive paths still refuse, but the
211
+ // refusal announces the automatic takeover instead of a window hunt.
212
+ const attestation = serving === prior[0]
213
+ ? (/** @type {any} */ (prior[0]).remote !== true && holderStatus(prior[0]) === 'idle' ? 'serving-idle' : 'serving')
214
+ : 'unknown'
198
215
  const refusal = () => {
199
- const reason = bindingRefusalReason(/** @type {any} */ (prior[0]).remote === true ? undefined : process.pid, serving === prior[0] ? 'serving' : 'unknown')
216
+ const reason = bindingRefusalReason(/** @type {any} */ (prior[0]).remote === true ? undefined : process.pid, attestation)
200
217
  // Remote callers render after their retry budget; local callers have no wire.
201
218
  return Object.assign(new Error(/** @type {any} */ (agent).remote === true ? reason : `${reason}: ${bindingGuidance(sessionId, reason)}`),
202
- { bindingFailure: bindingFailure(/** @type {any} */ (prior[0]).remote === true ? undefined : process.pid, serving === prior[0] ? 'serving' : 'unknown') })
219
+ { bindingFailure: bindingFailure(/** @type {any} */ (prior[0]).remote === true ? undefined : process.pid, attestation) })
203
220
  }
204
221
  // Remote entries are channel proxies, NOT runtime identities. Only the
205
222
  // endpoint's nonce attestation may reclaim them (including same-process).
@@ -236,6 +253,39 @@ export function createEditLockLifecycle(runtime, sessionForAgent, options = {})
236
253
  })()
237
254
  return entry.ready
238
255
  }
256
+ /** Trusted driving-ingress transfer admission (change
257
+ * edit-lock-binding-transfer, design D1/D2): take the binding from a
258
+ * same-process, local (non-remote-proxy) holder that is registry-named and
259
+ * provably not mid-turn, reusing the exact superseded-reclaim semantics —
260
+ * durable revocation and forget, no lock is released, the claimant binds as
261
+ * interrupted. Every other shape (remote proxy, holder not registry-named,
262
+ * mid-turn, undeterminable liveness, unavailable registry) delegates to the
263
+ * ordinary start(), keeping its fail-closed refusal and its classification.
264
+ * Passive entry points (creation setup, catch-up, preset switch) never call
265
+ * this. @param {object} agent @returns {Promise<'active'|'interrupted'>} */
266
+ function transferStart(agent) {
267
+ if (closed) return Promise.reject(new Error('edit lifecycle closed'))
268
+ if (entries.has(agent)) return Promise.reject(new Error('agent already registered'))
269
+ const sessionId = sessionForAgent(agent)
270
+ if (!sessionId) return Promise.reject(new Error('unregistered lifecycle agent'))
271
+ const prior = [...entries].find(([, entry]) => entry.sessionId === sessionId)
272
+ if (!prior) return start(agent)
273
+ let serving
274
+ try { serving = options.servingRuntime?.(sessionId) } catch { /* unattestable: fall through to the ordinary refusal */ }
275
+ if (/** @type {any} */ (prior[0]).remote !== true && serving === prior[0] && holderStatus(prior[0]) === 'idle') {
276
+ // Concurrent claimants re-check after the shared revocation settles;
277
+ // no file lock is released and the claimant starts interrupted. A failed
278
+ // revocation keeps the transferable refusal: the holder entry is retained
279
+ // (start()'s reclaim-failure discipline) and the next driving ingress
280
+ // re-attempts the transfer.
281
+ return forget(prior[0]).then(() => start(agent), () => {
282
+ const reason = bindingRefusalReason(process.pid, 'serving-idle')
283
+ throw Object.assign(new Error(/** @type {any} */ (agent).remote === true ? reason : `${reason}: ${bindingGuidance(sessionId, reason)}`),
284
+ { bindingFailure: bindingFailure(process.pid, 'serving-idle') })
285
+ })
286
+ }
287
+ return start(agent)
288
+ }
239
289
  return Object.freeze({
240
290
  assertStartable,
241
291
  /** Local bindings only; endpoint arbitration reports channel proxies. */
@@ -283,6 +333,8 @@ export function createEditLockLifecycle(runtime, sessionForAgent, options = {})
283
333
  pendingRequests(exec) { return negotiation.pending(host.executionFor(exec.agent).sessionId) },
284
334
  }),
285
335
  start,
336
+ /** Explicit driving-ingress transfer entry; ordinary start() never transfers. */
337
+ transferStart,
286
338
  stop,
287
339
  /** Normal end of an agent: an agent that is still active (never stopped,
288
340
  * not recovering) can never edit again, so its active locks are released
@@ -172,6 +172,22 @@ export async function serveEditLockEndpoint(lifecycle, endpoint, sinks, attest,
172
172
  const agent = Object.freeze({ id: sessionId, remote: true })
173
173
  sinks.set(agent, event => transport.notify(event))
174
174
  inner = createEditLockPeer(lifecycle, agent)
175
+ // A retry open is a trusted driving ingress (change
176
+ // edit-lock-binding-transfer): when the ordinary start is refused by
177
+ // a duplicate LOCAL holder, the transfer admission re-adjudicates the
178
+ // holder's idleness publisher-side. start() runs first and refuses
179
+ // without side effects, so a non-transferable refusal keeps its
180
+ // original classification and is evaluated exactly once per caller.
181
+ if (message.request.retry === true && typeof lifecycle.transferStart === 'function') {
182
+ try {
183
+ const state = await lifecycle.start(agent)
184
+ return { peer: inner, state }
185
+ } catch (error) {
186
+ if (/** @type {any} */ (error)?.bindingFailure?.code !== 'binding-duplicate') throw error
187
+ const state = await lifecycle.transferStart(agent)
188
+ return { peer: inner, state }
189
+ }
190
+ }
175
191
  const state = await lifecycle.start(agent)
176
192
  return { peer: inner, state }
177
193
  }, { nonce: typeof message.request.nonce === 'string' && message.request.nonce.length <= 256 ? message.request.nonce : undefined,
@@ -199,14 +215,17 @@ export async function serveEditLockEndpoint(lifecycle, endpoint, sinks, attest,
199
215
  })
200
216
  return Object.freeze({
201
217
  bindings: arbitration.bindings,
202
- /** @param {any} agent @param {boolean} [retry] */
203
- startLocal(agent, retry = false) {
218
+ /** @param {any} agent @param {boolean} [retry] @param {boolean} [transfer]
219
+ * transfer: the claimant arrives through a driving ingress whose registry
220
+ * identity is the defect being repaired — the lifecycle transfer admission
221
+ * decides, and the currency proof relaxes accordingly (isCurrentLocal). */
222
+ startLocal(agent, retry = false, transfer = false) {
204
223
  return arbitration.openLocal(agent.id, async reclaimed => {
205
224
  const current = () => {
206
- try { return !closed && (isCurrentLocal ? isCurrentLocal(agent, reclaimed || retry) : !(reclaimed || retry)) } catch { return false }
225
+ try { return !closed && (isCurrentLocal ? isCurrentLocal(agent, reclaimed || retry, transfer) : !(reclaimed || retry)) } catch { return false }
207
226
  }
208
227
  if (!current()) throw new Error('local edit binding claimant is no longer current')
209
- const state = await lifecycle.start(agent)
228
+ const state = transfer && typeof lifecycle.transferStart === 'function' ? await lifecycle.transferStart(agent) : await lifecycle.start(agent)
210
229
  if (!current()) {
211
230
  // A stopped entry still has subtractive cleanup authority. Forget it
212
231
  // only after durable revocation; never dispose (which releases locks).