@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.0-rc.9

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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13785 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +481 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,782 @@
1
+ 'use strict';
2
+ /**
3
+ * Place-claims (CONVENTIONS.md, "Place-claims") — the writer-verifiable hold `writes: serial`
4
+ * needs and `isolated` does not (#136).
5
+ *
6
+ * WHAT THIS IS NOT. Three partial mechanisms already exist in this fleet and none is a
7
+ * place-claim: the claim registry (lib/state.js `claims`) holds an ISSUE, not a PLACE; a
8
+ * worktree's existence implies nothing about who is writing to it right now (creating one is
9
+ * taking it — there is no separate act); and a session dashboard's own spawn-time trunk-lock is
10
+ * keyed to spawning a ship/sweep-kind session, which cannot answer "may I write here right now"
11
+ * for work that never came through a spawn (an implementer agent fanned out by a coordinator,
12
+ * for instance). This module is that missing, general primitive.
13
+ *
14
+ * RELEASE IS A LIVENESS LOOKUP AT READ TIME, NEVER A STATE TRANSITION WRITTEN AT KILL TIME.
15
+ * "Dies with its session" is what a reader assumes and is not what a stored flag can promise —
16
+ * nothing reliable runs at the moment a session dies. Measured on the one such lock already
17
+ * running in this fleet (the dashboard's spawn-time trunk-lock): it releases only once a poller
18
+ * NOTICES the holder died, roughly a minute later, so a caller that kills a session and
19
+ * immediately retries gets a refusal indistinguishable from a genuine conflict. This module does
20
+ * not write a `released` flag at all — `isLive`/`holderOf`/`conflict` re-derive liveness on every
21
+ * call, so a dead holder's record disappears from a caller's point of view the instant it is next
22
+ * read, with no lag and no poller.
23
+ *
24
+ * MACHINE-LOCAL ONLY, DELIBERATELY (#128 §10 Q3, out of scope). A place-claim lives in
25
+ * ~/.colab/state.json, keyed by absolute checkout PATH — not by repo, so a repo running several
26
+ * worktrees needs one hold per checkout in use. Two machines each holding their own local lock on
27
+ * what happens to be the same logical repo is a distributed-systems question this module does not
28
+ * answer; the existing backstop (separate working trees, git's own push rejection on a stale ref)
29
+ * remains what prevents two machines from landing the same conflict undetected. A record that is not
30
+ * this machine (`tools/lib/machine.js` `isLocal` — a hardware id compare when both sides have one,
31
+ * else a canonicalized-hostname compare, #289) is proof `~/.colab` itself is being synced across
32
+ * machines, which `syncedStateProblem` below treats as the same hazard as a synced lock file. Before
33
+ * #289 this was a raw `rec.host !== os.hostname()` string compare, which false-refused the SAME
34
+ * machine the instant its short hostname drifted from its FQDN (`devbox.local` vs `devbox`)
35
+ * — `machine.isLocal` is strictly more permissive, never less, than that check.
36
+ *
37
+ * NEVER IN A FILE-SYNCED LOCATION. A Resilio/Syncthing/Dropbox/iCloud path has no atomicity and no
38
+ * consistency guarantee inside its sync window: two sessions can each read "unlocked", each write
39
+ * "held by me", and both proceed WITH CONFIDENCE — worse than having no lock. `syncedStateProblem`
40
+ * refuses an acquire from such a path; it is a heuristic (a marker scan), and the foreign-host
41
+ * check in `isLive` is the behavioural backstop that fires even when the marker scan misses.
42
+ *
43
+ * DEGRADED MODE: SERIAL FALLS BACK TO ISOLATED, NEVER TO UNLOCKED. If the lock cannot be reached —
44
+ * state unreadable, the lock directory stuck — callers are told to use a worktree and branch
45
+ * instead, which needs no lock. Speed degrades; safety never does. THIS MODULE DOES NOT IMPLEMENT
46
+ * THAT ITSELF — `state.loadState()`/`state.mutate()` are what can throw on an unreadable file or a
47
+ * stuck lock, and `place.js` never calls either (every function here takes an already-loaded state
48
+ * object). The catch lives in `tools/colab`'s `placeState()`/`placeMutate()` helpers, used by every
49
+ * caller that acquires or checks a place-claim (`cmdSolo`, `cmdClaim`'s trunk-checkout path,
50
+ * `cmdPlace`) — see those for the actual degrade behaviour, exit code 2 on `cmdPlace`.
51
+ *
52
+ * BLANK-SESSION SELF-RECOGNITION IS A CALLER RESPONSIBILITY, NOT SOMETHING THIS MODULE GUESSES
53
+ * (#242). `conflict`'s same-holder exemption matches ONLY a truthy, matching `session` — two
54
+ * invocations that both carry a blank one are never recognized as the same holder, even when a
55
+ * hold's recorded `pid` matches the caller's own. That is deliberate: `pid` was unconditionally
56
+ * `process.ppid`, the parent shell, not a unique per-command identity, so matching on it could
57
+ * exempt a genuine conflict (two unrelated commands sharing a shell) — the one failure mode this
58
+ * primitive must never have. `tools/colab`'s `cmdClaim`/`cmdSolo` instead make a non-blank `session`
59
+ * MANDATORY at the two call sites that mint a shared-checkout hold, so the gap is closed by requiring
60
+ * identity up front rather than by weakening what counts as a match here. See `conflict`'s own
61
+ * doc comment for the full argument, including a falsifier run that measured agent tool calls
62
+ * NOT sharing a stable pid across commands, which is what rules a BARE pid out as a fix.
63
+ * `resolveAnchor` (#288, below) governs a DIFFERENT question — whether a recorded pid may ever be
64
+ * PROBED for liveness at all — and leaves this exemption rule untouched.
65
+ *
66
+ * IDENTITY GAINED A SECOND, INDEPENDENT PROOF IN #317 — AND THE PARAGRAPH ABOVE STILL HOLDS. A hold
67
+ * whose recorded anchor process is PROVABLY this invocation's own (`ownsAnchor`: `pidKind: 'anchor'`
68
+ * AND `anchorProof` `'verified'`/`'declared'` AND alive AND containing this pid right now) is the
69
+ * caller's, whatever string either side carries. That is not the pid match rejected above: the
70
+ * rejected one was `process.ppid`, a parent shell two unrelated commands share, and every record
71
+ * carrying one — `anchorProof: 'default'`, plus every record written before #317 — is excluded by
72
+ * construction and always will be. The population that gained self-recognition is the one #288
73
+ * taught this module to identify properly in the first place: a long-lived agent session process,
74
+ * verified as an ancestor at write time. It was measured being locked out by its own hold for 8.5
75
+ * hours. `sessionName` remains never an ownership key, on any path. Full argument: `ownsAnchor`, and
76
+ * docs/adr/317-anchor-pid-self-ownership.md.
77
+ */
78
+
79
+ const fs = require('fs');
80
+ const path = require('path');
81
+ const os = require('os');
82
+ const procs = require('./procs');
83
+ const machine = require('./machine');
84
+ const { humanAge } = require('./util');
85
+
86
+ /**
87
+ * Resolve a checkout path to the canonical string every caller keys against — `realpath` so a
88
+ * symlink or a `./`-suffixed path resolves to the SAME key as its canonical form. Falls back to
89
+ * `path.resolve` when the path does not exist on disk (e.g. checking a place that may already have
90
+ * been torn down) rather than throwing, because a missing directory is a legitimate thing to ask
91
+ * "is anything holding this?" about.
92
+ */
93
+ function placeKey(pathAbs) {
94
+ const resolved = path.resolve(pathAbs);
95
+ try {
96
+ return fs.realpathSync(resolved);
97
+ } catch (_) {
98
+ return resolved;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Build a hold record. `branch` follows the SAME representation a claim's does — `null` for "the
104
+ * trunk checkout" (never the literal word `trunk`, refused by `records.branchProblem` at write
105
+ * time in lib/state.js's `mutate`), a real name for a worktree. `pid` is optional: a hold acquired
106
+ * on behalf of a process this module cannot introspect (e.g. relayed from a session id alone) may
107
+ * omit it, and its absence makes the hold's liveness `unknown` — see `isLive` below.
108
+ *
109
+ * `pidKind` (#288) says what KIND of process `pid` names, because "no pid recorded" and "a pid is
110
+ * recorded but naming it would be a false signal" need to be told apart:
111
+ * - `'anchor'` (default, and every legacy record with no `pidKind` at all) — `pid` is the
112
+ * long-lived process whose death means the work is over; it MAY be probed for liveness. CALLERS
113
+ * SHOULD PASS THE LONG-LIVED PROCESS's pid, never a short-lived CLI invocation's own — `tools/colab`
114
+ * used to pass `process.ppid` unconditionally for exactly this reason: the `colab` process that
115
+ * acquires a hold exits the moment the command returns, so its own pid would already read dead
116
+ * by the time anything checks. `resolveAnchor` below is what now decides, per call, whether
117
+ * `process.ppid` is actually that long-lived process (#288's bug: an agent's `ppid` is a
118
+ * short-lived per-tool-call shell, not the session).
119
+ * - `'invocation'` — `pid` is kept ONLY as a human lead for `holderLabel` (#235); it is NEVER
120
+ * probed, so it can never produce a false "dead" verdict. See `defaultProbe`/`isLive` below.
121
+ *
122
+ * `anchorProof` (#317) is `resolveAnchor`'s `proof` for that same pid — `'declared'`/`'verified'`
123
+ * (a pid somebody named or proved), `'default'` (a bare `ppid`, assumed), `'none'`, or `null` for a
124
+ * record written before this field existed. It is stored ONLY so `ownsAnchor` can tell a session's
125
+ * own process from whatever shell happened to run the command; nothing about liveness reads it.
126
+ *
127
+ * `machine` (#289) is this machine's hardware-bound id (`tools/lib/machine.js` `localMachine().id`),
128
+ * recorded alongside `host` so a reader can tell "genuinely a different machine" from "the same
129
+ * machine under a drifted hostname" without re-deriving it — `host` stays what `holderLabel` and
130
+ * every refusal message print, unchanged.
131
+ */
132
+ function holdRecord({ pathAbs, repo, branch = null, host, session, sessionName, pid = null, pidKind, anchorProof, since }) {
133
+ return {
134
+ path: placeKey(pathAbs),
135
+ repo,
136
+ branch,
137
+ host: host || os.hostname(),
138
+ machine: machine.localMachine().id,
139
+ session: session || null,
140
+ sessionName: sessionName || null,
141
+ pid: pid || null,
142
+ pidKind: pidKind || null,
143
+ anchorProof: anchorProof || null,
144
+ since: since || new Date().toISOString(),
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Decide what pid a NEW hold should anchor on, and whether that pid may ever be probed (#288).
150
+ * Pure — every real-world source (`alive`, `isAncestor`) is injected, so this is testable with no
151
+ * real process tree. Returns `{ pid, pidKind, proof, why }`; `why` is a short human-readable trace of
152
+ * which rule fired, for callers that want to say more than "trust me" when `--pid` was not given.
153
+ *
154
+ * `proof` (#317) says HOW the anchor was established, which `pidKind` alone cannot express: rules 1
155
+ * and 2 below record a pid somebody either NAMED deliberately or PROVED contains this invocation,
156
+ * while rule 4 records a bare `process.ppid` — the parent SHELL, which two unrelated commands share.
157
+ * All three are `pidKind: 'anchor'` (all three may be probed for liveness), so a predicate that has
158
+ * to tell "a session's own process" from "whatever shell happened to run me" needs this second term:
159
+ *
160
+ * `'declared'` rule 1, numeric — a caller named it and it was verified alive.
161
+ * `'verified'` rule 2 — `CLAUDE_PID`, alive AND proven an ancestor of this invocation.
162
+ * `'default'` rule 4 — `ppid`, assumed, never proven. NOT a self-ownership signal (#242).
163
+ * `'none'` rules 1-`none` and 3 — fail-closed, `pidKind: 'invocation'`.
164
+ * absent every record written before #317 — read exactly like `'default'`: never self-owned.
165
+ *
166
+ * `ownsAnchor` below is the only consumer; `defaultProbe`/`isLive` deliberately never read it, so
167
+ * liveness, `stalePlaces` and every prune path behave identically to before this field existed.
168
+ *
169
+ * Precedence, first match wins:
170
+ * 1. An explicit anchor — `pidOpt` (`--pid <n|none>` at the CLI, or `COLAB_PLACE_PID`). The literal
171
+ * string `'none'` means "I know there is nothing worth anchoring on", and resolves to the same
172
+ * fail-closed `'invocation'` shape as rule 3 — but as a caller's explicit statement, not a
173
+ * default. A numeric value must pass `alive()`; a caller naming a dead pid is a mistake worth
174
+ * surfacing (`UserError` at the CLI call site), never a silently-adopted dead anchor.
175
+ * 2. `env.CLAUDE_PID`, numeric, alive, AND `isAncestor(n, process.pid)` — an agent session's
176
+ * long-lived `claude` process, verified to actually contain this invocation (not merely named by
177
+ * an env var that could be stale, forged, or left over from a different session). Adopted as
178
+ * `'anchor'`: this is the #288 fix that needs no recipe change from any caller.
179
+ * 3. `env.CLAUDECODE === '1' || env.AI_AGENT` with no anchor proven by rule 2 — an agent shell with
180
+ * nothing safe to anchor on. Fails closed: `pid` is kept (as `ppid`) ONLY as a human lead, never
181
+ * probed (`pidKind: 'invocation'`). This is #288's own caller shape: a short-lived per-tool-call
182
+ * shell whose `ppid` is NOT the session, so probing it produces exactly the false-dead verdict
183
+ * #288 reports.
184
+ * 4. Default — `{ pid: ppid, pidKind: 'anchor' }`, today's exact behaviour, unchanged for every
185
+ * interactive-terminal caller and every record already on disk (absence of `pidKind` takes this
186
+ * same branch on read, per `defaultProbe`/`isLive` above).
187
+ */
188
+ function resolveAnchor({ pidOpt, env = {}, ppid, alive = procs.alive, isAncestor = procs.isAncestor } = {}) {
189
+ if (pidOpt !== undefined && pidOpt !== null && pidOpt !== '') {
190
+ if (String(pidOpt).trim().toLowerCase() === 'none') {
191
+ return { pid: ppid, pidKind: 'invocation', proof: 'none', why: '--pid none: caller states no anchor exists' };
192
+ }
193
+ const n = Number(pidOpt);
194
+ if (!Number.isFinite(n) || !alive(n)) {
195
+ return { pid: null, pidKind: null, proof: null, why: `--pid ${pidOpt} is not a live process`, invalid: true };
196
+ }
197
+ return { pid: n, pidKind: 'anchor', proof: 'declared', why: `--pid ${n}: caller-supplied anchor` };
198
+ }
199
+ const claudePid = Number(env.CLAUDE_PID);
200
+ if (env.CLAUDE_PID && Number.isFinite(claudePid) && alive(claudePid) && isAncestor(claudePid, process.pid)) {
201
+ return { pid: claudePid, pidKind: 'anchor', proof: 'verified', why: `CLAUDE_PID ${claudePid}: alive and proven an ancestor` };
202
+ }
203
+ if (env.CLAUDECODE === '1' || env.AI_AGENT) {
204
+ return { pid: ppid, pidKind: 'invocation', proof: 'none', why: 'agent shell (CLAUDECODE/AI_AGENT), no proven anchor — failing closed' };
205
+ }
206
+ return { pid: ppid, pidKind: 'anchor', proof: 'default', why: 'default: ppid is the long-lived invoking process' };
207
+ }
208
+
209
+ /**
210
+ * The default liveness probe — a pure function of one record, injectable so tests never depend on
211
+ * what happens to be running on the machine. Returns `true` (live, hold stands), `false` (dead,
212
+ * not a hold), or `null` (cannot tell, FAILS CLOSED — the hold stands and the message says why).
213
+ *
214
+ * Order matters, in three steps: a foreign-machine record is checked before anything about pid,
215
+ * because it is not "unknown" in the ordinary sense — it is evidence of the sync hazard this module
216
+ * exists to refuse, and that is worth a distinct message (`machine.isLocal`, #289, replaces a raw
217
+ * `os.hostname()` string compare so a drifted-but-same-machine record is no longer misread as
218
+ * foreign). Then `pidKind: 'invocation'` (#288) — a pid recorded ONLY as a human lead, never a
219
+ * liveness signal — is checked before ordinary pid probing, because probing it would produce a
220
+ * false-dead verdict on a still-running holder (the #288 bug: an agent's short-lived per-tool-call
221
+ * shell pid, mistaken for the long-lived session). Finally an `'anchor'` pid (the default, and
222
+ * every legacy record with no `pidKind` at all) is probed as before.
223
+ */
224
+ function defaultProbe(rec) {
225
+ if (!rec) return false;
226
+ if (!machine.isLocal(rec)) return null; // foreign-machine — see isLive's message
227
+ if (rec.pidKind === 'invocation') return null; // never probed — see isLive's message
228
+ if (rec.pid) return procs.alive(rec.pid);
229
+ return null; // no pid recorded — cannot probe locally, fails closed
230
+ }
231
+
232
+ /**
233
+ * Liveness of one hold record, as `{live, reason}`. `live` is `true`/`false`/`null` (unknown,
234
+ * fails closed — treated as held everywhere in this module). Never trusts a stored flag; every
235
+ * call re-runs `probe` against the record as it stands right now.
236
+ */
237
+ function isLive(rec, probe = defaultProbe) {
238
+ if (!rec) return { live: false, reason: 'no record' };
239
+ if (!machine.isLocal(rec)) {
240
+ const local = machine.localMachine();
241
+ return {
242
+ live: null,
243
+ reason: `recorded on host "${rec.host}"${rec.machine ? ` (machine ${rec.machine})` : ''}, not this ` +
244
+ `machine ("${local.host}"${local.id ? `, machine ${local.id}` : ''}) — either a genuinely ` +
245
+ 'different machine (place-claims are machine-local only, CONVENTIONS.md "Place-claims") or ' +
246
+ '~/.colab is itself being synced, which is the same hazard this module refuses for the lock ' +
247
+ 'file itself',
248
+ };
249
+ }
250
+ if (rec.pidKind === 'invocation') {
251
+ return {
252
+ live: null,
253
+ reason: rec.pid
254
+ ? `pid ${rec.pid} is an invocation shell, not the anchor process (#288) — never probed for ` +
255
+ 'liveness, failing closed (hold stands)'
256
+ : 'no anchor pid recorded — cannot probe liveness locally, failing closed (hold stands)',
257
+ };
258
+ }
259
+ const verdict = probe(rec);
260
+ if (verdict === true) return { live: true, reason: `pid ${rec.pid} is alive` };
261
+ if (verdict === false) return { live: false, reason: rec.pid ? `pid ${rec.pid} is gone` : 'no longer live' };
262
+ return {
263
+ live: null,
264
+ reason: 'no pid recorded — cannot probe liveness locally, failing closed (hold stands)',
265
+ };
266
+ }
267
+
268
+ /**
269
+ * The hold on `pathAbs`, if any, with its liveness resolved right now. Returns `null` when there
270
+ * is no record at all — genuinely free, not merely "nothing found yet".
271
+ */
272
+ function holderOf(st, pathAbs, probe = defaultProbe) {
273
+ const key = placeKey(pathAbs);
274
+ const rec = (st && st.places && st.places[key]) || null;
275
+ if (!rec) return null;
276
+ const { live, reason } = isLive(rec, probe);
277
+ return { rec, live, reason };
278
+ }
279
+
280
+ /**
281
+ * A holder identity that always resolves to SOMETHING a human can act on — never the bare
282
+ * "unknown" that leaves a live-hold refusal with no remedy but COLAB_HUMAN=1 and nobody to ask
283
+ * (#235). Preference order: the human-supplied label, the session URL, then the (pid, host) every
284
+ * real acquire site already records (`tools/colab` passes `process.ppid` at every write site) — a
285
+ * human blocked by a hold with neither a name nor a URL can still `ps -p <pid>` on `<host>` and
286
+ * find out what that process is, which is a real lead where "unknown" is none. Only a record with
287
+ * NEITHER identity NOR a pid — not producible by any current write site, but not impossible in a
288
+ * hand-edited state.json — falls all the way back to the literal 'unknown'.
289
+ */
290
+ function holderLabel(rec) {
291
+ if (!rec) return 'unknown';
292
+ if (rec.sessionName) return rec.sessionName;
293
+ if (rec.session) return rec.session;
294
+ if (rec.pid) return `pid ${rec.pid} on ${rec.host || os.hostname()}`;
295
+ return 'unknown';
296
+ }
297
+
298
+ /**
299
+ * How long `rec` has been held, self-evident on sight ("3h ago", "4d ago") — never a raw
300
+ * timestamp a reader has to subtract by hand (#238). The one thing that distinguishes a hold a
301
+ * live session parked at a prompt for an hour from one somebody genuinely forgot days ago; both
302
+ * render identically as "[live]" otherwise, which is precisely the gap #238 measured. `rec.since`
303
+ * is missing only on a hand-edited state.json — every real write site sets it (`holdRecord`
304
+ * above defaults it at construction) — so this still resolves to something rather than throwing.
305
+ */
306
+ function holdAge(rec) {
307
+ return rec && rec.since ? humanAge(rec.since) : 'age unknown';
308
+ }
309
+
310
+ /**
311
+ * The sentence appended to a `held`/`unknown` message when neither side of the comparison
312
+ * carries a session id (#242). Blank-blank is NOT recognized as a re-acquire by the SAME
313
+ * holder — `conflict`'s exemption only fires on a truthy, matching `session` — so this is
314
+ * where that silence would otherwise leave a caller with no explanation and no remedy.
315
+ *
316
+ * `likelySelf` names a real, useful hint (the hold's pid is this invocation's own parent
317
+ * process) WITHOUT turning it into an exemption — see the `conflict` doc comment for why a
318
+ * pid is never used to decide `null` vs refuse.
319
+ */
320
+ function identityGap(rec, self, likelySelf) {
321
+ let msg = ' — neither this hold nor this attempt carries a session id, so it cannot be ' +
322
+ 'told apart from your own (#242): supply --session <stable-id> on the acquiring command, ' +
323
+ 'or export COLAB_SESSION="<stable-id>" once for the shell, so a re-acquire is recognized ' +
324
+ 'as yours. If you know this holder is gone, COLAB_HUMAN=1 colab place release ' +
325
+ `"${rec.path}".`;
326
+ if (likelySelf) {
327
+ msg += ` (This hold's recorded pid (${rec.pid}) is this invocation's own parent process, ` +
328
+ 'so it is very likely yours — but a pid is process lineage, not a session, and this ' +
329
+ 'module will not exempt on it.)';
330
+ }
331
+ return msg;
332
+ }
333
+
334
+ /**
335
+ * Would acquiring `pathAbs` for `self` (an optional {session, pid} to exempt the caller's own
336
+ * re-acquire/renew) conflict with an existing hold? Returns `null` for clear ground, or
337
+ * `{holder, kind, message, unidentified, likelySelf}` — `kind` is `'held'` (a live other
338
+ * holder, refuse), `'unknown'` (liveness could not be resolved, refuse and name the remedy),
339
+ * or `'foreign-host'` (refuse, citing the sync hazard). `unidentified` is true when neither
340
+ * side carries a session id (blank-blank); `likelySelf` is additionally true when, in that
341
+ * same blank-blank case, the hold's recorded pid equals `self.pid`.
342
+ *
343
+ * A BARE PID IS NEVER AN EXEMPTION KEY (#242, boundary restated by #317). Two things return `null`
344
+ * here: a matching, non-blank `session`, and — since #317 — a hold whose PROVEN anchor process
345
+ * (`anchorProof` `'verified'`/`'declared'`, alive, and containing this invocation right now)
346
+ * identifies the caller as the same writer. Everything the paragraph below rules out is still ruled
347
+ * out: a `sessionName` match, a blank-against-blank match, and above all a match on a `'default'` or
348
+ * legacy pid — `process.ppid`, the parent shell — which is the population the argument is about and
349
+ * which `ownsAnchor`'s term 3 excludes permanently. The measured falsifier runs below are what that
350
+ * exclusion exists to honour, so they are kept, not deleted. Two reasons, both measured rather than
351
+ * assumed: (1) this fleet's own
352
+ * agents are told to pass `--session` as a FLAG, never rely on an `export`, precisely
353
+ * because shell state does not persist between an agent's separate tool calls — and if the
354
+ * shell does not persist, its pid does not either, so pid-matching buys agents nothing; a
355
+ * live falsifier run (two `colab place acquire` calls from two separate tool-call shells)
356
+ * recorded two DIFFERENT pids and the second silently superseded the first because its
357
+ * holder had already died — the self-collision this module has to worry about needs a
358
+ * still-ALIVE prior holder, which the agent-tool-call model rarely produces. (2) `pid` WAS
359
+ * `process.ppid` unconditionally — the parent SHELL, not a unique invocation — so two unrelated
360
+ * commands run in the same shell (or a recycled pid) would share one, and this primitive's whole
361
+ * value is refusing when it cannot prove safety: a pid match could exempt a genuine conflict, which
362
+ * is the one failure mode it must never have. Reason (2) is exactly why #317 did NOT simply start
363
+ * matching on `pid`: it matches only where #288's `resolveAnchor` already replaced that `ppid` with
364
+ * a pid it PROVED contains the caller, and the shared-shell population keeps refusing. The population that genuinely needs self-recognition
365
+ * across commands (a persistent interactive shell) already has a free, correct fix: `export
366
+ * COLAB_SESSION=<id>` once. `sessionName` is likewise never an exemption key — it is display
367
+ * text a caller picks about the WORK, not a join key, and two concurrent sessions can
368
+ * plausibly choose the same one (a consumer that tried name-matching measured exactly this
369
+ * and reverted it).
370
+ */
371
+ function conflict(st, pathAbs, self = {}, probe = defaultProbe) {
372
+ const h = holderOf(st, pathAbs, probe);
373
+ if (!h) return null;
374
+ // Re-acquire by the same holder — proved by the session string, or (#317) by the anchor process
375
+ // that took the hold provably containing this invocation. `self.anchorOpts` is the injection seam
376
+ // for `ownsAnchor`'s process sources; absent, it reads the real process tree.
377
+ if (ownsPlace(h.rec, self && self.session, (self && self.anchorOpts) || {})) return null;
378
+ const unidentified = !!(self && !self.session && !h.rec.session);
379
+ const likelySelf = !!(unidentified && self.pid && h.rec.pid === self.pid);
380
+
381
+ if (!machine.isLocal(h.rec)) {
382
+ return {
383
+ holder: h.rec,
384
+ kind: 'foreign-host',
385
+ unidentified,
386
+ likelySelf,
387
+ message: `place "${h.rec.path}" is recorded held from host "${h.rec.host}" ` +
388
+ `(held ${holdAge(h.rec)}) — ${h.reason}`,
389
+ };
390
+ }
391
+ if (h.live === false) return null; // dead holder — clear ground, nothing to refuse
392
+ if (h.live === null) {
393
+ return {
394
+ holder: h.rec,
395
+ kind: 'unknown',
396
+ unidentified,
397
+ likelySelf,
398
+ message: `place "${h.rec.path}" is held by session "${holderLabel(h.rec)}" (held ${holdAge(h.rec)}) ` +
399
+ `and its liveness cannot be confirmed locally (${h.reason}) — wait a moment and check again if it may ` +
400
+ 'have just died, or override with COLAB_HUMAN=1 once you know that session is gone' +
401
+ (unidentified ? identityGap(h.rec, self, likelySelf) : ''),
402
+ };
403
+ }
404
+ return {
405
+ holder: h.rec,
406
+ kind: 'held',
407
+ unidentified,
408
+ likelySelf,
409
+ message: `place "${h.rec.path}" is held by session "${holderLabel(h.rec)}" (${h.reason}, held ${holdAge(h.rec)})` +
410
+ (unidentified ? identityGap(h.rec, self, likelySelf) : ''),
411
+ };
412
+ }
413
+
414
+ /**
415
+ * Decide AND write, in one pass, over the state object the caller hands in (#285).
416
+ *
417
+ * WHY THIS EXISTS — the defect it closes. Every shared-checkout write site in `tools/colab` was a
418
+ * check-then-act pair straddling the state lock: `placeState()` loaded state with NO lock,
419
+ * `conflict()` judged that snapshot, and only then `placeMutate()` -> `state.mutate` -> `withLock`
420
+ * re-read state and wrote `st.places[key]` UNCONDITIONALLY — never re-checking the fact the
421
+ * decision rested on. Two processes could each read "free", each write "held by me", and both exit
422
+ * 0, with the second silently superseding the first. That is precisely the "two sessions can each
423
+ * read unlocked, each write held by me, and both proceed WITH CONFIDENCE" failure CONVENTIONS.md
424
+ * ("Place-claims") names as worse than having no lock at all — it was simply being caused by the
425
+ * check/write split rather than by a synced filesystem.
426
+ *
427
+ * So the decision moves INSIDE the critical section. Callers pass this as `state.mutate`'s
428
+ * function: the `st` it receives is the one loaded under the lock, microseconds before the write,
429
+ * and the same `conflict()` that judged the earlier snapshot judges THIS one. The outer, lock-free
430
+ * pre-check stays where it is at every call site — it is a cheap refusal that avoids taking the
431
+ * lock at all in the common case, and it owns the `--force`/`COLAB_HUMAN=1` policy — but it is no
432
+ * longer the authority. This one is.
433
+ *
434
+ * PURE WITH RESPECT TO THE FILESYSTEM, deliberately, exactly like every other function in this
435
+ * module (see the header): it mutates the object it is given and returns a verdict. It never loads
436
+ * or saves state, never reads `process.env`, and never decides policy — `syncedStateProblem`,
437
+ * `resolveAnchor`, `requirePlaceIdentity` and the `COLAB_HUMAN` bar all stay at the call site,
438
+ * because those are questions about the CALLER, not about the record.
439
+ *
440
+ * `force` writes over a live holder. It is not an override this module grants — the caller has
441
+ * already cleared the `COLAB_HUMAN=1` bar CONVENTIONS.md ("Place-claims": "override is a human
442
+ * act") requires before it may pass it. Passing it here is the caller stating that bar was met.
443
+ *
444
+ * Returns `{ok: true, rec, superseded}` — `superseded` is the record this write replaced, if any
445
+ * (a confirmed-dead holder, or a forced takeover), so a caller can SAY what it displaced rather
446
+ * than silently overwriting it — or `{ok: false, conflict}`, where `conflict` is exactly what
447
+ * `conflict()` returns, so a refusal message composed from it cannot drift from the pre-check's.
448
+ */
449
+ function acquire(st, opts = {}, probe = defaultProbe) {
450
+ const {
451
+ pathAbs, repo, branch = null, host, session, sessionName, pid = null, pidKind, anchorProof,
452
+ anchorOpts = {}, force = false,
453
+ } = opts;
454
+ const key = placeKey(pathAbs);
455
+ const prior = (st && st.places && st.places[key]) || null;
456
+ const conf = conflict(st, pathAbs, { session, pid, anchorOpts }, probe);
457
+ if (conf && !force) return { ok: false, conflict: conf };
458
+ const rec = holdRecord({ pathAbs, repo, branch, host, session, sessionName, pid, pidKind, anchorProof });
459
+ st.places = st.places || {};
460
+ st.places[key] = rec;
461
+ // `prior` is reported as superseded only when it was somebody ELSE's — a re-acquire by the same
462
+ // holder (`conflict` returned null on a matching session) is a renewal, not a takeover, and
463
+ // calling it "superseded" would put a scary word in an ordinary message.
464
+ // #317: "the same holder" is the same question `conflict` just answered, so it is asked with the
465
+ // same predicate — a hold this caller's own proven anchor took is a RENEWAL, not a takeover, even
466
+ // when the session string presented this time differs from the one recorded.
467
+ const sameHolder = !!(prior && ownsPlace(prior, session, anchorOpts));
468
+ return { ok: true, rec, superseded: prior && !sameHolder ? prior : null };
469
+ }
470
+
471
+ /**
472
+ * Every place record whose holder is confirmed dead — `colab doctor`'s report, same shape as
473
+ * `staleClaims`. Deliberately excludes `unknown` liveness: a record this module cannot disprove is
474
+ * held stays out of a report that implies "safe to prune".
475
+ */
476
+ function stalePlaces(st, probe = defaultProbe) {
477
+ const out = [];
478
+ for (const [key, rec] of Object.entries((st && st.places) || {})) {
479
+ const { live, reason } = isLive(rec, probe);
480
+ if (live === false) out.push({ path: key, rec, reason });
481
+ }
482
+ return out;
483
+ }
484
+
485
+ /**
486
+ * Every place record whose liveness cannot be proven either way (`live === null`) — `colab doctor`'s
487
+ * companion to `stalePlaces` (#288/#289). This is what makes an `'invocation'`-anchored hold, or a
488
+ * genuinely unreachable foreign-machine one, VISIBLE instead of silently accumulating: neither is
489
+ * "confirmed dead" (so `stalePlaces`/`--prune` correctly never touch it), but a human left with no
490
+ * report at all has no way to notice one exists short of stumbling on it in `colab places`.
491
+ * Deliberately excludes `live === false` (that is `stalePlaces`'s own report) and `live === true` —
492
+ * this is only ever the middle, unprovable case.
493
+ */
494
+ function unprovablePlaces(st, probe = defaultProbe) {
495
+ const out = [];
496
+ for (const [key, rec] of Object.entries((st && st.places) || {})) {
497
+ const { live, reason } = isLive(rec, probe);
498
+ if (live === null) out.push({ path: key, rec, reason });
499
+ }
500
+ return out;
501
+ }
502
+
503
+ /** Marker files/directories that mean "this ancestor is a file-sync root" — heuristic, not exhaustive. */
504
+ const SYNC_MARKERS = [
505
+ '.sync', // Resilio Sync
506
+ '.stfolder', // Syncthing
507
+ '.dropbox', // Dropbox (legacy marker; newer clients vary)
508
+ ];
509
+
510
+ function hasSyncMarker(dir) {
511
+ for (const m of SYNC_MARKERS) {
512
+ try {
513
+ if (fs.existsSync(path.join(dir, m))) return m;
514
+ } catch (_) { /* unreadable — not evidence either way */ }
515
+ }
516
+ try {
517
+ for (const entry of fs.readdirSync(dir)) {
518
+ if (/^\.sync-conflict-/.test(entry) || /\.!sync$/.test(entry)) return entry;
519
+ }
520
+ } catch (_) { /* ignore */ }
521
+ return null;
522
+ }
523
+
524
+ /**
525
+ * Is `colabDir` (normally ~/.colab) sitting under a file-synced location? Walks ancestors up to
526
+ * `$HOME`, since a sync root is commonly declared a level or two above the folder itself (e.g.
527
+ * `~/.colab` living inside a synced `~` on a misconfigured machine, or a sync client's marker
528
+ * appearing beside the folder it manages rather than inside it). Returns a problem string, or
529
+ * `null` for clean ground. iCloud's "Library/Mobile Documents" convention is checked by substring
530
+ * on the path itself, since iCloud drops no marker file inside an arbitrary synced folder.
531
+ */
532
+ function syncedStateProblem(colabDir) {
533
+ const resolved = path.resolve(colabDir);
534
+ const degradeInstruction = 'Degrading: fall back to a worktree + branch, which needs no lock ' +
535
+ '(CONVENTIONS.md, Place-claims — "serial falls back to isolated, never to unlocked").';
536
+ if (/Library\/Mobile Documents/.test(resolved)) {
537
+ return `${colabDir} is under iCloud Drive ("Library/Mobile Documents") — a place-claim must never ` +
538
+ 'live in a file-synced location (CONVENTIONS.md "Place-claims"): no atomicity, no consistency ' +
539
+ `guarantee inside the sync window, and two sessions could each read "unlocked" with confidence. ` +
540
+ degradeInstruction;
541
+ }
542
+ const home = path.resolve(os.homedir());
543
+ let dir = resolved;
544
+ for (let i = 0; i < 8 && dir.length >= home.length; i++) {
545
+ const marker = hasSyncMarker(dir);
546
+ if (marker) {
547
+ return `${colabDir} appears to be under a file-synced directory (found "${marker}" in ${dir}) — a ` +
548
+ 'place-claim must never live in a file-synced location (CONVENTIONS.md "Place-claims"): no ' +
549
+ 'atomicity, no consistency guarantee inside the sync window, and two sessions could each read ' +
550
+ `"unlocked" with confidence. ${degradeInstruction}`;
551
+ }
552
+ if (dir === home) break;
553
+ const parent = path.dirname(dir);
554
+ if (parent === dir) break;
555
+ dir = parent;
556
+ }
557
+ return null;
558
+ }
559
+
560
+ /**
561
+ * Is `rec` a hold this `session` may act on as its own? (#306, naming what was already there.)
562
+ *
563
+ * This is EXACTLY `conflict`'s same-holder exemption above — a truthy, exactly-equal `session` —
564
+ * given a name and a test file, because `cmdPlace release`'s `mine` test and that exemption are
565
+ * required to be the same comparison. Two spellings of one rule is how a CLI ends up with two
566
+ * different answers to "is this hold mine", and a hold that answers that inconsistently is worse
567
+ * than one that refuses.
568
+ *
569
+ * ⚠ NEVER widen THIS function — to `sessionName`, or to `pid`. Both were considered and rejected on
570
+ * measured evidence — see `conflict`'s doc comment above (a consumer that tried name-matching
571
+ * reverted it after a worktree sat beside a live session with a near-identical name and was NOT it)
572
+ * and CONVENTIONS.md, "Place-claims". #306 proposed exactly that widening as one of two candidate
573
+ * fixes; it was rejected for these reasons and the fix went to write time instead. A blank session
574
+ * never matches, including blank-against-blank (#242). Every word of that still holds, and this
575
+ * function's body is unchanged.
576
+ *
577
+ * What #317 added is a SECOND, independent proof of the same fact beside it — `ownsAnchor` below —
578
+ * not a loosening of this one. The boundary it draws is precise, and worth stating here because a
579
+ * reader arriving at "never widen to pid" needs to know which pid: a `sessionName` is still never an
580
+ * ownership key on any path; a bare, defaulted or legacy pid (`anchorProof` `'default'` or absent —
581
+ * #242's `process.ppid`, shared by every command in one shell) is still never one either; only a pid
582
+ * that was PROVED an ancestor at write time, or explicitly named by a caller, and that still
583
+ * contains this very invocation, is. Consumers ask `ownsPlace`, which is this OR that.
584
+ */
585
+ function ownsHold(rec, session) {
586
+ return !!session && !!rec && rec.session === session;
587
+ }
588
+
589
+ /**
590
+ * Is `rec` a hold whose ANCHOR PROCESS provably contains this invocation — i.e. is this the very
591
+ * session that took the hold, reached through process lineage instead of through a typed string?
592
+ * (#317.)
593
+ *
594
+ * WHY THIS EXISTS. A ship session recovered an issue with a no-worktree claim, which minted a
595
+ * checkout hold under the identity string `coding-dashboard-1545`. It then shipped, and every later
596
+ * squash-merge was refused by ITS OWN hold: the identity `colab ship` resolves comes from the
597
+ * worktree record or a branch-keyed claim, and a no-worktree claim carries `branch: null`, so the
598
+ * session presented a blank one. `ownsHold` is exact string equality and blank never matches, so a
599
+ * session was locked out by a lock it had taken itself. One merge in 8.5 hours on that repo, cleared
600
+ * only when a human ran `COLAB_HUMAN=1 colab place release` at 01:35. The string was never the
601
+ * durable fact; the process was.
602
+ *
603
+ * FIVE TERMS, ALL REQUIRED — and term 3 is the one that keeps #242 closed:
604
+ * 1. `machine.isLocal(rec)` — an ancestry walk across machines is meaningless (#289).
605
+ * 2. `rec.pidKind === 'anchor'` — an `'invocation'` pid is a human lead, never a signal (#288).
606
+ * 3. `rec.anchorProof` is `'verified'` or `'declared'` — the pid was PROVED an ancestor at write
607
+ * time, or NAMED by a caller. A `'default'` proof (rule 4: a bare `process.ppid`) and every
608
+ * legacy record with no `anchorProof` at all are excluded, permanently.
609
+ * 4. `alive(rec.pid)` — a dead anchor is class `dead`, never class `own`.
610
+ * 5. the anchor is this process, or an ancestor of it, RIGHT NOW (`isAncestor`) — not "an env var
611
+ * names it" (#288's own lesson), not "equals my ppid" (#242's rejected form).
612
+ *
613
+ * ⚠ WHY THIS IS NOT #242 REOPENED, and why term 3 is load-bearing rather than cautious. #242
614
+ * rejected `rec.pid === self.pid` where `pid` was UNCONDITIONALLY `process.ppid` — the parent shell
615
+ * — so two unrelated commands sharing one shell shared one pid, and a match could exempt a genuine
616
+ * conflict. Term 3 excludes exactly that population: a `'default'`-proof record can never be
617
+ * self-owned no matter how the ancestry walk comes out. This repo's own suite is the falsifier —
618
+ * `ship-promote-place-claim.test.js` acquires a hold as a deliberately DIFFERENT session through
619
+ * `colab place acquire`, whose recorded pid is the CLI's `ppid`, the node test runner; the `colab
620
+ * ship` invocation in the same test is also a child of that runner, so terms 1/2/4/5 alone would
621
+ * return true and ship would self-own a live foreign hold. Term 3 is what makes that record
622
+ * ineligible, and that test going red is the sentinel if anybody removes it.
623
+ *
624
+ * The equivalence class this admits is ONE verified long-lived session process, which is never
625
+ * coarser than the `session` string beside it: everything `ownsAnchor` exempts is something the same
626
+ * session could already exempt by exporting `COLAB_SESSION` once (the remedy #242 named). It removes
627
+ * the requirement to type that string identically on a later command — which is precisely #306's
628
+ * complaint — without widening WHO counts as one writer. Falsifier for the whole rule: if two
629
+ * concurrent writers of one checkout are ever measured sharing a `'verified'` anchor but NOT sharing
630
+ * a session string, term 5 is insufficient and `docs/adr/317-…` must be superseded.
631
+ *
632
+ * ⚠ `sessionName` remains never an ownership key, on any path — display text is not a join key
633
+ * (#306, and the consumer that measured a false name match and reverted it).
634
+ *
635
+ * Every real-world source is injected, so this is testable with no real process tree.
636
+ */
637
+ function ownsAnchor(rec, { pid = process.pid, alive = procs.alive, isAncestor = procs.isAncestor } = {}) {
638
+ if (!rec || !rec.pid) return false;
639
+ if (!machine.isLocal(rec)) return false; // 1
640
+ if (rec.pidKind !== 'anchor') return false; // 2
641
+ if (rec.anchorProof !== 'verified' && rec.anchorProof !== 'declared') return false; // 3
642
+ if (!alive(rec.pid)) return false; // 4
643
+ if (Number(rec.pid) === Number(pid)) return true; // 5 — the anchor IS me
644
+ return !!isAncestor(rec.pid, pid); // 5 — …or contains me
645
+ }
646
+
647
+ /**
648
+ * "Is this hold mine?", as every consumer should ask it (#317) — the session string OR the proven
649
+ * anchor. Two independent proofs of one fact, and a caller that can supply either is the same
650
+ * writer; neither widens who counts as one writer (see `ownsAnchor`'s doc for that argument).
651
+ *
652
+ * `ownsHold`'s own implementation is deliberately untouched: `cmdPlace release`'s `mine` test and
653
+ * `conflict`'s exemption must stay ONE comparison, so the widening happens here, in a predicate both
654
+ * call, rather than by two separate edits that could drift.
655
+ */
656
+ function ownsPlace(rec, session, anchorOpts = {}) {
657
+ return ownsHold(rec, session) || ownsAnchor(rec, anchorOpts);
658
+ }
659
+
660
+
661
+ /**
662
+ * WHO holds `pathAbs`, relative to ME — one word, computed once, so no consumer re-derives it and
663
+ * no two consumers disagree (#317). Returns `{cls, rec, live, reason, remedy, conflict}`.
664
+ *
665
+ * The live specimen this closes was not a wrong answer; it was an UNCLASSIFIED one. `colab ship`
666
+ * printed `place "…" is held by session "coding-dashboard-1545"` and stopped — true, and useless:
667
+ * the reader could not tell from it whether the holder was itself, a corpse, or a live sibling, and
668
+ * those three need three different next moves. The refusal now names the class and the exact next
669
+ * command, and two of the six classes are not refusals at all.
670
+ *
671
+ * `free` no record — proceed.
672
+ * `foreign-machine` recorded by another machine — refuse; the sync hazard (#289), unchanged.
673
+ * `own` mine, by session string or proven anchor — proceed, and DO NOT release it at
674
+ * cleanup: a hold this caller renewed is one somebody else's claim may still be
675
+ * relying on (`cmdShip`/`cmdPromote` used to delete it on the way out).
676
+ * `dead` holder confirmed gone — proceed; the record lapses at the next write here.
677
+ * `unknown` liveness unprovable — REFUSE, fail closed. #288's invariant: a record this
678
+ * module cannot disprove is held is never treated as absent and never pruned.
679
+ * `live-other` a live holder that is not me — refuse; `COLAB_HUMAN=1` is the human bar.
680
+ *
681
+ * Precedence is `conflict`'s own order, deliberately: `foreign-machine` outranks everything because
682
+ * it is evidence about the STATE FILE rather than about a process, and `own` outranks `dead`/
683
+ * `unknown` because a caller's own hold needs no liveness argument at all.
684
+ *
685
+ * `conflict` is carried on the result, non-null exactly for the three refusing classes, so a caller
686
+ * composing a message cannot drift from `conflict()`'s wording — the same guarantee #285 gave the
687
+ * pre-check and the under-lock check.
688
+ */
689
+ function classify(st, pathAbs, self = {}, probe = defaultProbe) {
690
+ const h = holderOf(st, pathAbs, probe);
691
+ if (!h) return { cls: 'free', rec: null, live: null, reason: 'no record', remedy: null, conflict: null };
692
+ const anchorOpts = (self && self.anchorOpts) || {};
693
+ const conf = conflict(st, pathAbs, self, probe);
694
+ const base = { rec: h.rec, live: h.live, reason: h.reason };
695
+ if (!machine.isLocal(h.rec)) {
696
+ return { ...base, cls: 'foreign-machine', conflict: conf, remedy: `COLAB_HUMAN=1 colab place release "${h.rec.path}"` };
697
+ }
698
+ if (ownsPlace(h.rec, self && self.session, anchorOpts)) {
699
+ return { ...base, cls: 'own', conflict: null, remedy: null };
700
+ }
701
+ if (h.live === false) return { ...base, cls: 'dead', conflict: null, remedy: null };
702
+ if (h.live === null) {
703
+ return { ...base, cls: 'unknown', conflict: conf, remedy: `COLAB_HUMAN=1 colab place release "${h.rec.path}"` };
704
+ }
705
+ return { ...base, cls: 'live-other', conflict: conf, remedy: `COLAB_HUMAN=1 colab place release "${h.rec.path}"` };
706
+ }
707
+
708
+ /**
709
+ * Drop the record at `pathAbs` IF its holder is CONFIRMED dead — the read-time lapse (#317).
710
+ *
711
+ * Read-time liveness already meant a dead holder refuses nothing (`conflict` returns `null` on
712
+ * `live === false`, and `acquire` supersedes the record). What it did NOT mean was that the record
713
+ * went away: only `colab doctor --prune` ever removed one, and only when a human thought to run it.
714
+ * So a dead-anchor hold sat in `colab places` looking like a hold — one on this very repo had sat
715
+ * for five days — and `colab place release` demanded `COLAB_HUMAN=1` to clear a corpse. This makes
716
+ * every command that already writes at that path clear it on the way past.
717
+ *
718
+ * ⚠ `live === null` is NEVER touched — not "unknown, probably fine", but the exact case #288/#289
719
+ * fail closed on: an `'invocation'`-anchored hold, or an unreachable foreign-machine one. Pruning on
720
+ * a signal that was never trustworthy is the failure `stalePlaces` was written to avoid, and this
721
+ * function must never become a second, weaker copy of it.
722
+ *
723
+ * Returns the removed record, or `null` when there was nothing to lapse.
724
+ */
725
+ function lapseDead(st, pathAbs, probe = defaultProbe) {
726
+ const key = placeKey(pathAbs);
727
+ const rec = (st && st.places && st.places[key]) || null;
728
+ if (!rec) return null;
729
+ if (isLive(rec, probe).live !== false) return null; // live, or unprovable — #288 fails closed
730
+ delete st.places[key];
731
+ return rec;
732
+ }
733
+
734
+ /**
735
+ * Release the hold at `pathAbs` IF AND ONLY IF the caller provably owns it — the AUTOMATIC
736
+ * counterpart to `cmdPlace release`'s deliberate, human-typed act (#305).
737
+ *
738
+ * Decide-and-write over the caller's `st`, mirroring `acquire`'s post-#285 shape so the decision
739
+ * is made against the state the write actually sees, inside the caller's existing lock. It never
740
+ * throws and never prompts: every non-release is a named `reason` the caller reports and carries
741
+ * on from, because this runs as a rider on `colab release`, whose real job (dropping the claim)
742
+ * has already succeeded by then.
743
+ *
744
+ * Stricter than `ownsHold` alone by one term — `machine.isLocal`. A human naming a path is
745
+ * asserting intent about that path; a side effect of another command must never delete a record
746
+ * another machine wrote, where "held" cannot even be evaluated (this module is machine-local by
747
+ * design — see the module doc). That asymmetry is deliberate and lives HERE, not in `ownsHold`:
748
+ * adding it to the shared predicate would change `cmdPlace release`'s behaviour, which is beyond
749
+ * what #305/#306 decided.
750
+ *
751
+ * #317 changed two things here, both additive. Ownership is now `ownsPlace` — the session string OR
752
+ * the proven anchor — so a claim minted with a mis-shaped `--session` (#306's population) still gives
753
+ * its hold back. And a CONFIRMED-DEAD holder lapses before ownership is consulted at all, whatever
754
+ * identity it names: that is what makes every caller of this function a dead-anchor sweeper, instead
755
+ * of leaving a corpse for `colab doctor --prune` and a human who remembers to run it. An
756
+ * unprovable (`live === null`) holder is still never touched — #288's invariant.
757
+ *
758
+ * Returns `{released: false, reason: 'no-record'|'foreign-machine'|'other-session', rec}` or
759
+ * `{released: true, rec}` / `{released: true, reason: 'lapsed-dead', rec}` — `rec` is the record
760
+ * inspected (or removed) so a caller can name the holder it left alone, or the corpse it cleared.
761
+ */
762
+ function releaseOwnedBy(st, pathAbs, session, opts = {}) {
763
+ const { anchorOpts = {}, probe = defaultProbe } = opts;
764
+ const key = placeKey(pathAbs);
765
+ const rec = (st && st.places && st.places[key]) || null; // `places` may be absent entirely
766
+ if (!rec) return { released: false, reason: 'no-record', rec: null };
767
+ // #317: a confirmed-dead holder lapses here, before ownership is even asked — whoever it names.
768
+ // This is what turns every claim-deletion site into a dead-anchor sweeper without any of them
769
+ // growing its own liveness logic. `live === null` is untouched (see `lapseDead`).
770
+ const lapsed = lapseDead(st, pathAbs, probe);
771
+ if (lapsed) return { released: true, reason: 'lapsed-dead', rec: lapsed };
772
+ if (!machine.isLocal(rec)) return { released: false, reason: 'foreign-machine', rec };
773
+ if (!ownsPlace(rec, session, anchorOpts)) return { released: false, reason: 'other-session', rec };
774
+ delete st.places[key];
775
+ return { released: true, rec };
776
+ }
777
+
778
+ module.exports = {
779
+ placeKey, holdRecord, resolveAnchor, defaultProbe, isLive, holderOf, holderLabel, holdAge, conflict, acquire,
780
+ stalePlaces, unprovablePlaces, syncedStateProblem, ownsHold, ownsAnchor, ownsPlace, classify, lapseDead,
781
+ releaseOwnedBy,
782
+ };