@thinkrun/cli 0.1.35 → 0.1.36

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 (39) hide show
  1. package/README.md +13 -2
  2. package/dist/shared/local-audit-sync.js +1 -0
  3. package/dist/src/adapters/cloud.d.ts.map +1 -1
  4. package/dist/src/adapters/cloud.js +27 -1
  5. package/dist/src/adapters/cloud.js.map +1 -1
  6. package/dist/src/adapters/local.d.ts +18 -7
  7. package/dist/src/adapters/local.d.ts.map +1 -1
  8. package/dist/src/adapters/local.js +242 -58
  9. package/dist/src/adapters/local.js.map +1 -1
  10. package/dist/src/commands/actions.d.ts +2 -0
  11. package/dist/src/commands/actions.d.ts.map +1 -1
  12. package/dist/src/commands/actions.js +176 -43
  13. package/dist/src/commands/actions.js.map +1 -1
  14. package/dist/src/commands/audit.d.ts.map +1 -1
  15. package/dist/src/commands/audit.js +35 -5
  16. package/dist/src/commands/audit.js.map +1 -1
  17. package/dist/src/commands/cloud.d.ts.map +1 -1
  18. package/dist/src/commands/cloud.js +14 -6
  19. package/dist/src/commands/cloud.js.map +1 -1
  20. package/dist/src/commands/doctor.d.ts +7 -0
  21. package/dist/src/commands/doctor.d.ts.map +1 -1
  22. package/dist/src/commands/doctor.js +72 -9
  23. package/dist/src/commands/doctor.js.map +1 -1
  24. package/dist/src/commands/release.d.ts.map +1 -1
  25. package/dist/src/commands/release.js +303 -23
  26. package/dist/src/commands/release.js.map +1 -1
  27. package/dist/src/session/cli-session-sync.d.ts +18 -3
  28. package/dist/src/session/cli-session-sync.d.ts.map +1 -1
  29. package/dist/src/session/cli-session-sync.js +188 -31
  30. package/dist/src/session/cli-session-sync.js.map +1 -1
  31. package/dist/src/session/context.d.ts +22 -3
  32. package/dist/src/session/context.d.ts.map +1 -1
  33. package/dist/src/session/context.js +132 -16
  34. package/dist/src/session/context.js.map +1 -1
  35. package/dist/src/working-location.d.ts +52 -4
  36. package/dist/src/working-location.d.ts.map +1 -1
  37. package/dist/src/working-location.js +648 -22
  38. package/dist/src/working-location.js.map +1 -1
  39. package/package.json +1 -1
@@ -20,10 +20,12 @@
20
20
  * `THINKBROWSE_LOCK_DIR` / `~/.thinkbrowse/` state if the new dir is not
21
21
  * established yet.
22
22
  */
23
- import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync, openSync, writeSync, closeSync, renameSync } from 'node:fs';
23
+ import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync, openSync, writeSync, closeSync, renameSync, statSync } from 'node:fs';
24
24
  import { homedir } from 'node:os';
25
- import { join } from 'node:path';
26
- import { resolveAgentId } from './session/agent-identity.js';
25
+ import { dirname, join } from 'node:path';
26
+ import { randomUUID } from 'node:crypto';
27
+ import { getAgentFilePath, resolveAgentId } from './session/agent-identity.js';
28
+ import { config } from './config/store.js';
27
29
  // ─── Directory resolution ────────────────────────────────────────────────────
28
30
  function getLockDir() {
29
31
  const configuredDir = process.env['THINKRUN_LOCK_DIR'] ?? process.env['THINKBROWSE_LOCK_DIR'];
@@ -48,6 +50,60 @@ function workingLocationFilePath() {
48
50
  function legacyWorkingLocationFilePath() {
49
51
  return join(getLockDir(), 'working-location.json');
50
52
  }
53
+ function readWorkingLocationPointer() {
54
+ const validateLockOwner = (candidate) => {
55
+ const currentAgentId = resolveAgentId();
56
+ const lockedBy = getLockedBy(candidate.tabId);
57
+ if (lockedBy?.agentId && lockedBy.agentId !== currentAgentId)
58
+ return null;
59
+ if (lockedBy
60
+ && !lockedBy.agentId
61
+ && lockedBy.pid !== process.pid
62
+ && isPidAlive(lockedBy.pid))
63
+ return null;
64
+ if (lockedBy) {
65
+ const committedLease = lockedBy.reservationBase ?? lockedBy;
66
+ const exactLease = sameLeaseIdentity(committedLease, candidate);
67
+ const candidateSetAt = Date.parse(candidate.setAt);
68
+ const lockSetAt = Date.parse(committedLease.setAt);
69
+ const legacySameWrite = committedLease.pid === candidate.pid
70
+ && committedLease.agentId === candidate.agentId
71
+ && committedLease.ownerShellPid === candidate.ownerShellPid
72
+ && Number.isFinite(candidateSetAt)
73
+ && Number.isFinite(lockSetAt)
74
+ && Math.abs(candidateSetAt - lockSetAt) < 1_000;
75
+ if (!exactLease && !legacySameWrite)
76
+ return null;
77
+ }
78
+ return candidate;
79
+ };
80
+ try {
81
+ const path = workingLocationFilePath();
82
+ if (existsSync(path)) {
83
+ const current = JSON.parse(readFileSync(path, 'utf-8'));
84
+ return validateLockOwner(current);
85
+ }
86
+ }
87
+ catch {
88
+ // Fall through to the legacy pointer.
89
+ }
90
+ try {
91
+ const legacyPath = legacyWorkingLocationFilePath();
92
+ if (!existsSync(legacyPath))
93
+ return null;
94
+ const legacy = JSON.parse(readFileSync(legacyPath, 'utf-8'));
95
+ const currentAgentId = resolveAgentId();
96
+ const ownedByAgent = !!legacy.agentId && legacy.agentId === currentAgentId;
97
+ const ownedByPid = legacy.pid === process.pid;
98
+ const staleLegacy = !legacy.agentId && !isPidAlive(legacy.pid);
99
+ if (!ownedByAgent && !ownedByPid && !staleLegacy)
100
+ return null;
101
+ return validateLockOwner(legacy);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ }
51
107
  /** Path to the per-tab CLI session persistence file.
52
108
  * Stored alongside other lock files so THINKRUN_LOCK_DIR / THINKBROWSE_LOCK_DIR
53
109
  * test isolation applies.
@@ -63,6 +119,25 @@ function groupFilePath(group) {
63
119
  const safe = group.replace(/[^a-zA-Z0-9_-]/g, '_') || 'default';
64
120
  return join(getLockDir(), 'groups', `${safe}.lock`);
65
121
  }
122
+ function sharedLocalSessionTabId() {
123
+ try {
124
+ const freshConfig = JSON.parse(readFileSync(config.getPath(), 'utf-8'));
125
+ const tabId = Number(freshConfig.localTabId);
126
+ if (Number.isFinite(tabId) && tabId > 0)
127
+ return tabId;
128
+ }
129
+ catch { /* fall through to agent-private continuity */ }
130
+ const safeAgentId = resolveAgentId().replace(/[^a-zA-Z0-9._-]+/g, '_') || 'default';
131
+ const path = join(dirname(getAgentFilePath()), 'agent-sessions', `${safeAgentId}.json`);
132
+ try {
133
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
134
+ const tabId = Number(parsed.tabId);
135
+ return Number.isFinite(tabId) ? tabId : null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
66
141
  function reclaimAuditFilePath() {
67
142
  const safeAgentId = resolveAgentId().replace(/[^a-zA-Z0-9_-]/g, '_') || 'default';
68
143
  return join(getLockDir(), 'reclaim-audits', `${safeAgentId}.json`);
@@ -70,6 +145,13 @@ function reclaimAuditFilePath() {
70
145
  function reclaimClaimFilePath(tabId) {
71
146
  return join(getLockDir(), 'reclaim-claims', `${tabId}.claim`);
72
147
  }
148
+ function reservationClaimFilePath(tabId) {
149
+ return join(getLockDir(), 'reservation-claims', `${tabId}.claim`);
150
+ }
151
+ function agentBindingClaimFilePath() {
152
+ const safeAgentId = resolveAgentId().replace(/[^a-zA-Z0-9_-]/g, '_') || 'default';
153
+ return join(getLockDir(), 'binding-claims', `${safeAgentId}.claim`);
154
+ }
73
155
  function ensureDir(dir) {
74
156
  mkdirSync(dir, { recursive: true });
75
157
  }
@@ -96,6 +178,117 @@ function atomicWrite(destPath, content) {
96
178
  throw err;
97
179
  }
98
180
  }
181
+ function withReservationClaim(tabId, fn) {
182
+ const path = reservationClaimFilePath(tabId);
183
+ ensureDir(join(getLockDir(), 'reservation-claims'));
184
+ const claim = JSON.stringify({ tabId, pid: process.pid, claimedAt: new Date().toISOString() });
185
+ const acquire = () => {
186
+ const fd = openSync(path, 'wx');
187
+ try {
188
+ writeSync(fd, claim);
189
+ }
190
+ finally {
191
+ closeSync(fd);
192
+ }
193
+ };
194
+ try {
195
+ acquire();
196
+ }
197
+ catch (err) {
198
+ if (err.code !== 'EEXIST')
199
+ throw err;
200
+ if (existingClaimIsBusy(path)) {
201
+ throw new Error(`TAB_LOCKED: tab ${tabId} has a lock transaction in progress`);
202
+ }
203
+ rmSync(path, { force: true });
204
+ acquire();
205
+ }
206
+ try {
207
+ return fn();
208
+ }
209
+ finally {
210
+ try {
211
+ rmSync(path, { force: true });
212
+ }
213
+ catch { /* best-effort */ }
214
+ }
215
+ }
216
+ function existingClaimIsBusy(path) {
217
+ try {
218
+ const existing = JSON.parse(readFileSync(path, 'utf-8'));
219
+ if (typeof existing.pid === 'number')
220
+ return isPidAlive(existing.pid);
221
+ }
222
+ catch {
223
+ // A just-created claim may be observed before its small payload is fully
224
+ // written. Treat it as busy instead of deleting a live process's lock.
225
+ }
226
+ try {
227
+ return Date.now() - statSync(path).mtimeMs < 5_000;
228
+ }
229
+ catch {
230
+ return false;
231
+ }
232
+ }
233
+ function acquireAgentBindingClaim() {
234
+ const path = agentBindingClaimFilePath();
235
+ ensureDir(join(getLockDir(), 'binding-claims'));
236
+ const claim = JSON.stringify({ pid: process.pid, claimedAt: new Date().toISOString() });
237
+ const acquire = () => {
238
+ const fd = openSync(path, 'wx');
239
+ try {
240
+ writeSync(fd, claim);
241
+ }
242
+ finally {
243
+ closeSync(fd);
244
+ }
245
+ };
246
+ try {
247
+ acquire();
248
+ }
249
+ catch (err) {
250
+ if (err.code !== 'EEXIST')
251
+ throw err;
252
+ if (existingClaimIsBusy(path)) {
253
+ throw new Error('TAB_LOCKED: this agent has a binding transaction in progress');
254
+ }
255
+ rmSync(path, { force: true });
256
+ acquire();
257
+ }
258
+ return () => {
259
+ try {
260
+ rmSync(path, { force: true });
261
+ }
262
+ catch { /* best-effort */ }
263
+ };
264
+ }
265
+ /** Serialize synchronous mutations of the durable current binding. */
266
+ export function withAgentBindingClaim(fn) {
267
+ const release = acquireAgentBindingClaim();
268
+ try {
269
+ return fn();
270
+ }
271
+ finally {
272
+ release();
273
+ }
274
+ }
275
+ function recoverStaleReservation(tabId, existing) {
276
+ if (!existing?.reservationId || isPidAlive(existing.pid))
277
+ return existing;
278
+ if (existing.reservationBase) {
279
+ atomicWrite(lockFilePath(tabId), JSON.stringify(existing.reservationBase));
280
+ return existing.reservationBase;
281
+ }
282
+ rmSync(lockFilePath(tabId), { force: true });
283
+ return null;
284
+ }
285
+ function sameLeaseIdentity(a, b) {
286
+ return a.tabId === b.tabId
287
+ && a.pid === b.pid
288
+ && a.setAt === b.setAt
289
+ && (!a.agentId || !b.agentId || a.agentId === b.agentId)
290
+ && (!a.ownerShellPid || !b.ownerShellPid || a.ownerShellPid === b.ownerShellPid);
291
+ }
99
292
  function migrateLegacyWorkingLocation(legacy, lock) {
100
293
  const currentAgentId = resolveAgentId();
101
294
  const migrated = {
@@ -170,6 +363,9 @@ function isPidAlive(pid) {
170
363
  return false;
171
364
  }
172
365
  }
366
+ function waitForClaimRetry(ms) {
367
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
368
+ }
173
369
  // ─── Public API ──────────────────────────────────────────────────────────────
174
370
  /**
175
371
  * Acquire an exclusive lock on `tabId`. Throws with message starting
@@ -183,11 +379,12 @@ function isPidAlive(pid) {
183
379
  * dead → stale → overwrite
184
380
  * 3. No agentId in existing lock → fall back to PID-based logic (backward compat)
185
381
  */
186
- export function acquireLock(tabId, group) {
382
+ export function acquireLock(tabId, group, preserved, authorizedReservationId) {
187
383
  const path = lockFilePath(tabId);
188
384
  ensureDir(join(getLockDir(), 'locks'));
189
385
  const currentAgentId = resolveAgentId();
190
386
  const lockData = {
387
+ ...(preserved ?? {}),
191
388
  tabId,
192
389
  pid: process.pid,
193
390
  agentId: currentAgentId,
@@ -270,6 +467,17 @@ export function acquireLock(tabId, group) {
270
467
  // ── Agent-aware ownership check ─────────────────────────────────────────
271
468
  if (existing.agentId) {
272
469
  if (existing.agentId === currentAgentId) {
470
+ if (existing.reservationId) {
471
+ if (existing.reservationId === authorizedReservationId) {
472
+ atomicWrite(path, lockJson);
473
+ return;
474
+ }
475
+ if (isPidAlive(existing.pid)) {
476
+ throw new Error(`TAB_LOCKED: tab ${tabId} has a lock transaction in progress`);
477
+ }
478
+ recoverStaleReservation(tabId, existing);
479
+ return acquireLock(tabId, group, preserved, authorizedReservationId);
480
+ }
273
481
  // Same agent, new invocation — re-acquire idempotently
274
482
  atomicWrite(path, lockJson);
275
483
  return;
@@ -366,6 +574,209 @@ export function acquireLock(tabId, group) {
366
574
  });
367
575
  }
368
576
  }
577
+ /**
578
+ * Acquire a lock transactionally for attach. A later bridge failure can restore
579
+ * a prior same-controller lease, while stale/foreign records are never revived.
580
+ */
581
+ export function reserveLock(tabId, group) {
582
+ return withReservationClaim(tabId, () => {
583
+ const currentAgentId = resolveAgentId();
584
+ const existing = recoverStaleReservation(tabId, getLockedBy(tabId));
585
+ const base = existing?.agentId === currentAgentId
586
+ ? (existing.reservationId ? (existing.reservationBase ?? null) : existing)
587
+ : null;
588
+ acquireLock(tabId, group);
589
+ const path = lockFilePath(tabId);
590
+ const acquired = getLockedBy(tabId);
591
+ if (!acquired || acquired.agentId !== currentAgentId) {
592
+ throw new Error(`TAB_LOCKED: tab ${tabId} changed owner during reservation`);
593
+ }
594
+ const reservationId = randomUUID();
595
+ atomicWrite(path, JSON.stringify({
596
+ ...acquired,
597
+ reservationId,
598
+ reservationKind: 'attach',
599
+ reservationBase: base,
600
+ }));
601
+ return { tabId, reservationId, previousLock: base };
602
+ });
603
+ }
604
+ /** Acquire the durable right to release a tab before asynchronous bridge cleanup. */
605
+ export function reserveRelease(tabId) {
606
+ return withReservationClaim(tabId, () => {
607
+ const currentAgentId = resolveAgentId();
608
+ const existing = recoverStaleReservation(tabId, getLockedBy(tabId));
609
+ if (existing?.reservationId) {
610
+ throw new Error(`TAB_LOCKED: tab ${tabId} has a lock transaction in progress`);
611
+ }
612
+ const alreadyOwned = !!existing && (existing.agentId === currentAgentId
613
+ || (!existing.agentId && existing.pid === process.pid));
614
+ if (!alreadyOwned)
615
+ acquireLock(tabId, undefined, existing ?? undefined);
616
+ const acquired = getLockedBy(tabId);
617
+ if (!acquired || acquired.agentId !== currentAgentId) {
618
+ throw new Error(`TAB_LOCKED: tab ${tabId} changed owner during release reservation`);
619
+ }
620
+ const reservationId = randomUUID();
621
+ atomicWrite(lockFilePath(tabId), JSON.stringify({
622
+ ...acquired,
623
+ pid: process.pid,
624
+ agentId: currentAgentId,
625
+ ownerShellPid: process.ppid,
626
+ setAt: new Date().toISOString(),
627
+ reservationId,
628
+ reservationKind: 'release',
629
+ reservationBase: existing,
630
+ }));
631
+ return { tabId, reservationId, previousLock: existing };
632
+ });
633
+ }
634
+ /** Restore the exact pre-reservation lock if this reservation still owns it. */
635
+ export function rollbackLockReservation(reservation) {
636
+ const path = lockFilePath(reservation.tabId);
637
+ if (!existsSync(path))
638
+ return;
639
+ try {
640
+ const current = JSON.parse(readFileSync(path, 'utf-8'));
641
+ if (current.reservationId !== reservation.reservationId)
642
+ return;
643
+ if (reservation.previousLock) {
644
+ atomicWrite(path, JSON.stringify(reservation.previousLock));
645
+ }
646
+ else {
647
+ rmSync(path, { force: true });
648
+ }
649
+ }
650
+ catch {
651
+ // Unclear ownership must never trigger deletion or restoration.
652
+ }
653
+ }
654
+ /**
655
+ * Commit a release against the tab that was reserved, never whichever tab may
656
+ * have become current while asynchronous bridge cleanup was running.
657
+ */
658
+ export function commitReleaseReservation(reservation, group, bindingClaimHeld = false, preserveBinding, tabAlreadyClosed = false, onCommit) {
659
+ if (!bindingClaimHeld) {
660
+ try {
661
+ return withAgentBindingClaim(() => commitReleaseReservation(reservation, group, true, preserveBinding, tabAlreadyClosed, onCommit));
662
+ }
663
+ catch (err) {
664
+ if (!err?.message?.startsWith('TAB_LOCKED'))
665
+ throw err;
666
+ // Another binding mutation may or may not replace the working pointer.
667
+ // Restore the exact committed lease so state remains consistent and the
668
+ // caller can retry after the short transaction completes.
669
+ const current = getLockedBy(reservation.tabId);
670
+ if (current?.reservationId !== reservation.reservationId) {
671
+ return { released: false, contextCleared: false };
672
+ }
673
+ for (let attempt = 0; attempt < 100; attempt += 1) {
674
+ waitForClaimRetry(10);
675
+ try {
676
+ return withAgentBindingClaim(() => commitReleaseReservation(reservation, group, true, preserveBinding, tabAlreadyClosed, onCommit));
677
+ }
678
+ catch (retryError) {
679
+ if (!retryError?.message?.startsWith('TAB_LOCKED'))
680
+ throw retryError;
681
+ }
682
+ }
683
+ if (tabAlreadyClosed) {
684
+ const latest = getLockedBy(reservation.tabId);
685
+ if (latest?.reservationId === reservation.reservationId) {
686
+ rmSync(lockFilePath(reservation.tabId), { force: true });
687
+ }
688
+ return { released: false, contextCleared: false };
689
+ }
690
+ let durableTabId;
691
+ for (let attempt = 0; attempt < 100; attempt += 1) {
692
+ try {
693
+ durableTabId = withAgentBindingClaim(() => {
694
+ const durable = getDurableWorkingLocation();
695
+ const sharedTab = sharedLocalSessionTabId();
696
+ return durable?.tabId ?? (sharedTab ? Number(sharedTab) : undefined);
697
+ });
698
+ break;
699
+ }
700
+ catch (retryError) {
701
+ if (!retryError?.message?.startsWith('TAB_LOCKED'))
702
+ throw retryError;
703
+ waitForClaimRetry(10);
704
+ }
705
+ }
706
+ if (durableTabId == null) {
707
+ const durable = getDurableWorkingLocation();
708
+ const sharedTab = sharedLocalSessionTabId();
709
+ durableTabId = durable?.tabId ?? (sharedTab ? Number(sharedTab) : undefined);
710
+ }
711
+ if (durableTabId != null && durableTabId !== reservation.tabId) {
712
+ const latest = getLockedBy(reservation.tabId);
713
+ if (latest?.reservationId === reservation.reservationId) {
714
+ rmSync(lockFilePath(reservation.tabId), { force: true });
715
+ }
716
+ return { released: false, contextCleared: false };
717
+ }
718
+ rollbackLockReservation(reservation);
719
+ return { released: false, contextCleared: false };
720
+ }
721
+ }
722
+ const finalize = (result) => {
723
+ onCommit?.(result);
724
+ return result;
725
+ };
726
+ const activeLock = getLockedBy(reservation.tabId);
727
+ if (activeLock?.reservationId !== reservation.reservationId
728
+ || activeLock.reservationKind !== 'release') {
729
+ return finalize({ released: false, contextCleared: false });
730
+ }
731
+ if (preserveBinding?.()) {
732
+ rollbackLockReservation(reservation);
733
+ return finalize({ released: false, contextCleared: false });
734
+ }
735
+ let currentOnDisk = null;
736
+ try {
737
+ const path = workingLocationFilePath();
738
+ if (existsSync(path)) {
739
+ currentOnDisk = JSON.parse(readFileSync(path, 'utf-8'));
740
+ }
741
+ }
742
+ catch {
743
+ // A missing/corrupt current pointer must not redirect the reserved release.
744
+ }
745
+ // All inputs (working pointer, private agent session, typed config) are shared
746
+ // across CLI processes. Never fall back to
747
+ // `_currentLocation`: it is the snapshot from this command's start and can
748
+ // name the released tab after a concurrent invocation has attached elsewhere.
749
+ // If both shared records are unreadable, preserve context conservatively;
750
+ // there is no trustworthy durable pointer this command is authorized to clear.
751
+ const currentTabId = currentOnDisk?.tabId ?? sharedLocalSessionTabId();
752
+ if (currentTabId === reservation.tabId) {
753
+ const contextCleared = releaseWorkingLocation(group, reservation, undefined, false, true);
754
+ if (tabAlreadyClosed && !contextCleared) {
755
+ const latest = getLockedBy(reservation.tabId);
756
+ if (latest?.reservationId === reservation.reservationId) {
757
+ rmSync(lockFilePath(reservation.tabId), { force: true });
758
+ }
759
+ }
760
+ return finalize({ released: contextCleared, contextCleared });
761
+ }
762
+ rmSync(lockFilePath(reservation.tabId), { force: true });
763
+ const groupName = group ?? reservation.previousLock?.group;
764
+ if (groupName != null) {
765
+ const path = groupFilePath(groupName);
766
+ try {
767
+ if (existsSync(path)) {
768
+ const groupLoc = JSON.parse(readFileSync(path, 'utf-8'));
769
+ if (reservation.previousLock && sameLeaseIdentity(groupLoc, reservation.previousLock)) {
770
+ rmSync(path, { force: true });
771
+ }
772
+ }
773
+ }
774
+ catch {
775
+ // Preserve an ambiguous group pointer rather than deleting a newer binding.
776
+ }
777
+ }
778
+ return finalize({ released: true, contextCleared: false });
779
+ }
369
780
  /**
370
781
  * Release the lock for `tabId`. No-op if the file doesn't exist.
371
782
  *
@@ -386,6 +797,11 @@ export function releaseLock(tabId) {
386
797
  // Neither PID nor agentId matches — do not delete
387
798
  return;
388
799
  }
800
+ if (lock.reservationId) {
801
+ // An attach transaction owns this temporary record. Releasing it here
802
+ // would prevent a later bridge failure from restoring reservationBase.
803
+ return;
804
+ }
389
805
  rmSync(path, { force: true });
390
806
  }
391
807
  catch {
@@ -430,12 +846,106 @@ export function getLockedBy(tabId) {
430
846
  return null;
431
847
  }
432
848
  }
849
+ /** True only while a live command still owns a temporary lock transaction. */
850
+ export function hasLiveLockReservation(tabId) {
851
+ const lock = getLockedBy(tabId);
852
+ return !!lock?.reservationId && isPidAlive(lock.pid);
853
+ }
854
+ /**
855
+ * Whether a failed targeted release represents only stale local context.
856
+ * A newer durable pointer or a live transaction must be preserved.
857
+ */
858
+ export function canClearContextAfterTargetedReleaseFailure(tabId) {
859
+ const currentPointer = readWorkingLocationPointer();
860
+ if (currentPointer && currentPointer.tabId !== tabId)
861
+ return false;
862
+ const sharedTabId = sharedLocalSessionTabId();
863
+ if (sharedTabId != null && sharedTabId !== tabId)
864
+ return false;
865
+ return !hasLiveLockReservation(tabId);
866
+ }
867
+ /**
868
+ * Clear an unlocked working pointer that disagrees with the agent-private tab
869
+ * just released. A lock on the pointer tab means an attach may be in flight or
870
+ * already committed, so the newer state is preserved.
871
+ */
872
+ export function clearStaleWorkingLocationPointerAfterPrivateRelease(releasedTabId, bindingClaimHeld = false) {
873
+ if (!bindingClaimHeld) {
874
+ try {
875
+ return withAgentBindingClaim(() => clearStaleWorkingLocationPointerAfterPrivateRelease(releasedTabId, true));
876
+ }
877
+ catch (err) {
878
+ if (err?.message?.startsWith('TAB_LOCKED'))
879
+ return false;
880
+ throw err;
881
+ }
882
+ }
883
+ if (sharedLocalSessionTabId() !== releasedTabId)
884
+ return false;
885
+ let stalePointer;
886
+ try {
887
+ stalePointer = JSON.parse(readFileSync(workingLocationFilePath(), 'utf-8'));
888
+ }
889
+ catch {
890
+ return false;
891
+ }
892
+ if (stalePointer.tabId === releasedTabId)
893
+ return false;
894
+ try {
895
+ return withReservationClaim(stalePointer.tabId, () => {
896
+ if (sharedLocalSessionTabId() !== releasedTabId)
897
+ return false;
898
+ let currentPointer;
899
+ try {
900
+ currentPointer = JSON.parse(readFileSync(workingLocationFilePath(), 'utf-8'));
901
+ }
902
+ catch {
903
+ return false;
904
+ }
905
+ if (!sameLeaseIdentity(currentPointer, stalePointer)) {
906
+ return false;
907
+ }
908
+ const pointerLock = recoverStaleReservation(currentPointer.tabId, getLockedBy(currentPointer.tabId));
909
+ if (pointerLock && !isLockStale(currentPointer.tabId))
910
+ return false;
911
+ if (pointerLock)
912
+ rmSync(lockFilePath(currentPointer.tabId), { force: true });
913
+ const legacyPath = legacyWorkingLocationFilePath();
914
+ try {
915
+ const legacy = JSON.parse(readFileSync(legacyPath, 'utf-8'));
916
+ if (sameLeaseIdentity(legacy, currentPointer))
917
+ rmSync(legacyPath, { force: true });
918
+ }
919
+ catch { /* preserve absent, malformed, or ambiguous legacy state */ }
920
+ if (currentPointer.group != null) {
921
+ const path = groupFilePath(currentPointer.group);
922
+ try {
923
+ const groupPointer = JSON.parse(readFileSync(path, 'utf-8'));
924
+ if (sameLeaseIdentity(groupPointer, currentPointer))
925
+ rmSync(path, { force: true });
926
+ }
927
+ catch { /* preserve absent, malformed, or rebound group state */ }
928
+ }
929
+ rmSync(workingLocationFilePath(), { force: true });
930
+ _currentLocation = null;
931
+ return true;
932
+ });
933
+ }
934
+ catch (err) {
935
+ if (err?.message?.startsWith('TAB_LOCKED'))
936
+ return false;
937
+ throw err;
938
+ }
939
+ }
433
940
  /**
434
941
  * Set the working location for this process.
435
942
  * Acquires a lock on `tabId` (throws TAB_LOCKED if another live PID owns it)
436
943
  * and writes the stable working-location file for cross-command persistence.
437
944
  */
438
- export function setWorkingLocation(loc) {
945
+ export function setWorkingLocation(loc, bindingClaimHeld = false, reservation) {
946
+ if (!bindingClaimHeld) {
947
+ return withAgentBindingClaim(() => setWorkingLocation(loc, true, reservation));
948
+ }
439
949
  ensureLocationCacheForCurrentLockDir();
440
950
  const { tabId, windowId, group, controlSessionId } = loc;
441
951
  // Snapshot previous group BEFORE acquiring the new lock so we can clean up
@@ -447,7 +957,11 @@ export function setWorkingLocation(loc) {
447
957
  const prevTabId = (_currentLocation && _currentLocation.tabId !== tabId)
448
958
  ? _currentLocation.tabId
449
959
  : undefined;
450
- acquireLock(tabId, group);
960
+ if (reservation && reservation.tabId !== tabId) {
961
+ throw new Error(`TAB_LOCKED: reservation for tab ${reservation.tabId} cannot commit tab ${tabId}`);
962
+ }
963
+ acquireLock(tabId, group, undefined, reservation?.reservationId);
964
+ const acquiredLock = getLockedBy(tabId);
451
965
  if (prevTabId !== undefined) {
452
966
  releaseLock(prevTabId);
453
967
  }
@@ -456,7 +970,7 @@ export function setWorkingLocation(loc) {
456
970
  pid: process.pid,
457
971
  agentId: resolveAgentId(),
458
972
  ownerShellPid: process.ppid,
459
- setAt: new Date().toISOString(),
973
+ setAt: acquiredLock?.setAt ?? new Date().toISOString(),
460
974
  ...(windowId !== undefined ? { windowId } : {}),
461
975
  ...(group != null ? { group } : {}),
462
976
  ...(controlSessionId ? { controlSessionId } : {}),
@@ -493,9 +1007,12 @@ export function setWorkingLocation(loc) {
493
1007
  * Update the control-session identifier for the currently owned working location.
494
1008
  * Best-effort: no-op when no working location exists.
495
1009
  */
496
- export function updateWorkingLocationControlSession(controlSessionId) {
1010
+ export function updateWorkingLocationControlSession(controlSessionId, bindingClaimHeld = false) {
1011
+ if (!bindingClaimHeld) {
1012
+ return withAgentBindingClaim(() => updateWorkingLocationControlSession(controlSessionId, true));
1013
+ }
497
1014
  ensureLocationCacheForCurrentLockDir();
498
- const current = getWorkingLocation();
1015
+ const current = getDurableWorkingLocation();
499
1016
  if (!current)
500
1017
  return;
501
1018
  const next = {
@@ -566,6 +1083,11 @@ export function getWorkingLocation() {
566
1083
  _currentLocation = migrated;
567
1084
  return migrated;
568
1085
  }
1086
+ /** Read the current durable pointer without consulting process-local cache. */
1087
+ export function getDurableWorkingLocation() {
1088
+ ensureLocationCacheForCurrentLockDir();
1089
+ return readWorkingLocationPointer();
1090
+ }
569
1091
  /**
570
1092
  * Release the working location for this process (and optionally a named group).
571
1093
  * Deletes the lock file for the current tab and the working-location file.
@@ -574,34 +1096,125 @@ export function getWorkingLocation() {
574
1096
  * crash or on a different machine), the group file itself is used to look up
575
1097
  * the tabId so the lock can be released by group name alone.
576
1098
  */
577
- export function releaseWorkingLocation(group) {
1099
+ export function releaseWorkingLocation(group, reservation, tabIdHint, claimHeld = false, bindingClaimHeld = false) {
578
1100
  // Attempt to resolve location from the working-location file first.
579
1101
  // Fall back to the group file when group is provided and the wl file is absent.
580
- let loc = getWorkingLocation();
1102
+ const explicitGroupOnly = group != null && !reservation && tabIdHint == null;
1103
+ let loc = explicitGroupOnly
1104
+ ? null
1105
+ : tabIdHint != null
1106
+ ? readWorkingLocationPointer()
1107
+ : getWorkingLocation();
1108
+ let staleHintFallback = false;
1109
+ let usedTabIdHint = false;
1110
+ if (tabIdHint != null && loc && loc.tabId !== tabIdHint)
1111
+ return false;
1112
+ if (!loc && reservation) {
1113
+ const reservedLock = getLockedBy(reservation.tabId);
1114
+ if (reservedLock?.reservationId === reservation.reservationId
1115
+ && reservedLock.reservationKind === 'release') {
1116
+ loc = reservation.previousLock ?? reservedLock;
1117
+ }
1118
+ }
1119
+ if (!loc && tabIdHint != null) {
1120
+ const hinted = getLockedBy(tabIdHint);
1121
+ if (hinted) {
1122
+ const currentAgentId = resolveAgentId();
1123
+ const ownedByAgent = !!hinted.agentId && hinted.agentId === currentAgentId;
1124
+ const ownedByPid = hinted.pid === process.pid;
1125
+ const stale = !isPidAlive(hinted.ownerShellPid ?? hinted.pid);
1126
+ if (!ownedByAgent && !ownedByPid && !stale)
1127
+ return false;
1128
+ staleHintFallback = stale && !ownedByAgent && !ownedByPid;
1129
+ usedTabIdHint = true;
1130
+ loc = hinted;
1131
+ }
1132
+ }
1133
+ if (!loc && tabIdHint != null)
1134
+ return false;
581
1135
  let groupFallback = false; // tracks whether we resolved via the group file
1136
+ let groupFallbackStale = false;
582
1137
  if (!loc && group != null) {
583
1138
  const gPath = groupFilePath(group);
584
1139
  if (existsSync(gPath)) {
585
1140
  try {
586
1141
  const groupLoc = JSON.parse(readFileSync(gPath, 'utf-8'));
587
- // Only use the group file if the owning PID is us or is dead (stale).
588
- // If a live foreign PID owns it, we must not forcibly release it.
589
- if (groupLoc.pid === process.pid || !isPidAlive(groupLoc.pid)) {
1142
+ const currentAgentId = resolveAgentId();
1143
+ const ownedByAgent = !!groupLoc.agentId && groupLoc.agentId === currentAgentId;
1144
+ const ownedByPid = groupLoc.pid === process.pid;
1145
+ const ownerPid = groupLoc.ownerShellPid ?? groupLoc.pid;
1146
+ const stale = !isPidAlive(ownerPid);
1147
+ // A command PID can be gone while its owning shell remains live. Only
1148
+ // same-agent ownership, this process, or a genuinely stale owner may release it.
1149
+ if (ownedByAgent || ownedByPid || stale) {
590
1150
  loc = groupLoc;
591
1151
  groupFallback = true;
1152
+ groupFallbackStale = stale && !ownedByAgent && !ownedByPid;
592
1153
  }
593
1154
  else {
594
- process.stderr.write(`[thinkrun] warn: group '${group}' is held by live PID ${groupLoc.pid} — cannot release\n`);
1155
+ process.stderr.write(`[thinkrun] warn: group '${group}' is held by live owner PID ${ownerPid} — cannot release\n`);
1156
+ return false;
595
1157
  }
596
1158
  }
597
1159
  catch { /* corrupt group file — skip */ }
598
1160
  }
599
1161
  }
600
1162
  if (loc) {
1163
+ if (reservation && loc.tabId !== reservation.tabId)
1164
+ return false;
1165
+ if (!claimHeld) {
1166
+ try {
1167
+ return withReservationClaim(loc.tabId, () => releaseWorkingLocation(group, reservation, tabIdHint, true, bindingClaimHeld));
1168
+ }
1169
+ catch (err) {
1170
+ if (!err?.message?.startsWith('TAB_LOCKED'))
1171
+ throw err;
1172
+ process.stderr.write(`[thinkrun] warn: tab ${loc.tabId} has a lock transaction in progress — cannot release\n`);
1173
+ return false;
1174
+ }
1175
+ }
1176
+ if (!bindingClaimHeld) {
1177
+ try {
1178
+ return withAgentBindingClaim(() => releaseWorkingLocation(group, reservation, tabIdHint, true, true));
1179
+ }
1180
+ catch (err) {
1181
+ if (!err?.message?.startsWith('TAB_LOCKED'))
1182
+ throw err;
1183
+ process.stderr.write('[thinkrun] warn: this agent has a binding transaction in progress — cannot release\n');
1184
+ return false;
1185
+ }
1186
+ }
1187
+ const activeLock = recoverStaleReservation(loc.tabId, getLockedBy(loc.tabId));
1188
+ if (usedTabIdHint) {
1189
+ if (activeLock) {
1190
+ const currentAgentId = resolveAgentId();
1191
+ const ownedByAgent = !!activeLock.agentId && activeLock.agentId === currentAgentId;
1192
+ const ownedByPid = activeLock.pid === process.pid;
1193
+ const stale = !isPidAlive(activeLock.ownerShellPid ?? activeLock.pid);
1194
+ if (!ownedByAgent && !ownedByPid && !stale)
1195
+ return false;
1196
+ staleHintFallback = stale && !ownedByAgent && !ownedByPid;
1197
+ }
1198
+ else {
1199
+ staleHintFallback = false;
1200
+ }
1201
+ }
1202
+ const ownsReleaseReservation = !!reservation
1203
+ && activeLock?.reservationId === reservation.reservationId
1204
+ && activeLock.reservationKind === 'release';
1205
+ if (activeLock?.reservationId && !ownsReleaseReservation) {
1206
+ process.stderr.write(`[thinkrun] warn: tab ${loc.tabId} has an attach reservation in progress — cannot release\n`);
1207
+ return false;
1208
+ }
1209
+ if (tabIdHint != null) {
1210
+ const latestPointer = readWorkingLocationPointer();
1211
+ if (latestPointer && latestPointer.tabId !== tabIdHint)
1212
+ return false;
1213
+ }
601
1214
  // releaseLock() guards against deleting locks owned by other PIDs. When the
602
1215
  // group-file fallback resolved a stale lock (dead PID), bypass the PID check
603
1216
  // and remove the lock file directly — we already verified staleness above.
604
- if (groupFallback && loc.pid !== process.pid) {
1217
+ if (ownsReleaseReservation || staleHintFallback || (groupFallback && groupFallbackStale)) {
605
1218
  try {
606
1219
  rmSync(lockFilePath(loc.tabId), { force: true });
607
1220
  }
@@ -613,9 +1226,11 @@ export function releaseWorkingLocation(group) {
613
1226
  const currentWlPath = workingLocationFilePath();
614
1227
  if (existsSync(currentWlPath)) {
615
1228
  try {
616
- rmSync(currentWlPath, { force: true });
1229
+ const currentPointer = JSON.parse(readFileSync(currentWlPath, 'utf-8'));
1230
+ if (sameLeaseIdentity(currentPointer, loc))
1231
+ rmSync(currentWlPath, { force: true });
617
1232
  }
618
- catch { /* best-effort */ }
1233
+ catch { /* preserve ambiguous or different current pointer */ }
619
1234
  }
620
1235
  const legacyPath = legacyWorkingLocationFilePath();
621
1236
  if (existsSync(legacyPath)) {
@@ -624,7 +1239,7 @@ export function releaseWorkingLocation(group) {
624
1239
  const currentAgentId = resolveAgentId();
625
1240
  const ownedByAgent = !!legacy.agentId && legacy.agentId === currentAgentId;
626
1241
  const staleLegacy = !legacy.agentId && !isPidAlive(legacy.pid);
627
- if (ownedByAgent || staleLegacy) {
1242
+ if (sameLeaseIdentity(legacy, loc) && (ownedByAgent || staleLegacy)) {
628
1243
  rmSync(legacyPath, { force: true });
629
1244
  }
630
1245
  }
@@ -640,12 +1255,23 @@ export function releaseWorkingLocation(group) {
640
1255
  const gPath = groupFilePath(groupName);
641
1256
  if (existsSync(gPath)) {
642
1257
  try {
643
- rmSync(gPath, { force: true });
1258
+ const groupLoc = JSON.parse(readFileSync(gPath, 'utf-8'));
1259
+ if (sameLeaseIdentity(groupLoc, loc)) {
1260
+ rmSync(gPath, { force: true });
1261
+ }
1262
+ }
1263
+ catch {
1264
+ // Preserve an ambiguous or newer group pointer.
644
1265
  }
645
- catch { /* best-effort */ }
646
1266
  }
647
1267
  }
648
1268
  }
649
- _currentLocation = null;
1269
+ if (loc && _currentLocation?.tabId === loc.tabId)
1270
+ _currentLocation = null;
1271
+ return true;
1272
+ }
1273
+ /** Release a remembered local binding even when its working pointer is missing. */
1274
+ export function releaseWorkingLocationForTab(tabId, group) {
1275
+ return releaseWorkingLocation(group, undefined, tabId);
650
1276
  }
651
1277
  //# sourceMappingURL=working-location.js.map