@futurelastic/colab-handbook 1.13.0-rc.1 → 1.13.0-rc.11

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.
package/README.md CHANGED
@@ -113,6 +113,11 @@ Also in [`skills/`](skills/): `code-plan` (a full plan for a hard issue, run by
113
113
  handbook), and `migration-review` (review a branch's migrations, for whoever a
114
114
  repo binds to that role).
115
115
 
116
+ **Running the loop by hand at a terminal?** With no `--session`, `colab` names
117
+ you `person:<git user.email>/<host token>`, so claims and ship evidence say who
118
+ you are. If you work on several units at once from separate shells, give each
119
+ shell its own `COLAB_SESSION=<any stable id>` so their holds stay apart.
120
+
116
121
  **Words you will meet:**
117
122
 
118
123
  - **Trunk** — the branch sessions merge into (`trunk:` in `project.yml`).
package/README.vi.md CHANGED
@@ -112,6 +112,12 @@ Cũng trong [`skills/`](skills/): `code-plan` (plan đầy đủ cho issue khó,
112
112
  nhất), và `migration-review` (review migration của một nhánh, cho người/agent
113
113
  được repo gán vai đó).
114
114
 
115
+ **Tự chạy vòng này bằng tay ở terminal?** Không có `--session` thì `colab` đặt
116
+ tên bạn là `person:<git user.email>/<host token>`, nên claim và bằng chứng ship
117
+ đều ghi rõ ai làm. Nếu làm nhiều đơn vị việc cùng lúc ở các shell khác nhau,
118
+ đặt cho mỗi shell một `COLAB_SESSION=<id ổn định bất kỳ>` để các hold không lẫn
119
+ vào nhau.
120
+
115
121
  **Mấy từ sẽ gặp:**
116
122
 
117
123
  - **Trunk** — nhánh các phiên merge vào (`trunk:` trong `project.yml`).
package/package.json CHANGED
@@ -17,6 +17,7 @@
17
17
  "tools/colab",
18
18
  "tools/lib/*.js",
19
19
  "!tools/lib/*.test.js",
20
+ "!tools/lib/refusal-sites.js",
20
21
  "tools/lib/tracker-scenarios.json",
21
22
  "tools/lib/codec/*.js",
22
23
  "tools/lib/codec/*.d.ts",
@@ -32,5 +33,5 @@
32
33
  "engines": {
33
34
  "node": ">=18"
34
35
  },
35
- "version": "1.13.0-rc.1"
36
+ "version": "1.13.0-rc.11"
36
37
  }
package/tools/colab CHANGED
@@ -77,6 +77,7 @@ const shipRoles = require('./lib/ship-roles'); // #372
77
77
  const refsBrake = require('./lib/refs-brake'); // #385
78
78
  const localAdopt = require('./lib/local-adopt'); // #393
79
79
  const ownerBranch = require('./lib/owner-branch'); // #394
80
+ const humanDoor = require('./lib/ship-human-door'); // #525
80
81
  const {
81
82
  HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
82
83
  parseArgs, table, shortRepo,
@@ -283,11 +284,38 @@ function myMachineId() { return machine.localMachine().id || null; }
283
284
 
284
285
  /**
285
286
  * Resolve the Claude session URL for this invocation: --session flag > COLAB_SESSION env >
286
- * '' (absent, never an error). Free-form — typically a session URL.
287
+ * a DERIVED person identity (#528) > '' (absent, never an error). Free-form — typically a session URL.
288
+ *
289
+ * The derived step exists for a person at a plain terminal, who has no session runtime and so no
290
+ * id to pass: without it their first trunk `colab claim` refused (#242's gate), `worktree new`
291
+ * warned three lines every time, and ship evidence read `implemented by: unknown`. It applies only
292
+ * when `COLAB_SESSION` is unset and the shell is not an agent's (`claimIdentity.
293
+ * shouldDerivePersonSession` has why) — an explicit flag or env value always wins.
287
294
  */
288
295
  function resolveSession(opts) {
289
- const s = opts.session || process.env.COLAB_SESSION || '';
290
- return String(s).trim();
296
+ const s = String(opts.session || process.env.COLAB_SESSION || '').trim();
297
+ return s || derivedPersonSession();
298
+ }
299
+
300
+ /**
301
+ * The derived person identity for this invocation, or ''. Memoized — one `git config` spawn, and
302
+ * the "derived" note is printed once per invocation (stderr, so `--json` stdout stays clean).
303
+ */
304
+ let derivedSessionCache = null;
305
+ function derivedPersonSession() {
306
+ if (derivedSessionCache !== null) return derivedSessionCache;
307
+ derivedSessionCache = '';
308
+ if (!claimIdentity.shouldDerivePersonSession(process.env)) return derivedSessionCache;
309
+ const r = spawnSync('git', ['config', '--get', 'user.email'], { encoding: 'utf8' });
310
+ const email = r.status === 0 ? String(r.stdout || '').trim() : '';
311
+ let user = process.env.USER || '';
312
+ if (!user) { try { user = os.userInfo().username; } catch { user = ''; } }
313
+ derivedSessionCache = claimIdentity.derivePersonSession({ email, user, hostToken: machine.hostToken(HOST) });
314
+ if (derivedSessionCache) {
315
+ process.stderr.write(`· session: ${derivedSessionCache} (derived — no --session or COLAB_SESSION given; ` +
316
+ `either one overrides it)\n`);
317
+ }
318
+ return derivedSessionCache;
291
319
  }
292
320
 
293
321
  /**
@@ -5677,7 +5705,8 @@ function cmdWorktreeNew(argv) {
5677
5705
 
5678
5706
  // #488: the scratch dirs (plans, briefs) are hidden in the clone's shared info/exclude — one
5679
5707
  // write covers the main checkout and every worktree, with no per-repo .gitignore diff.
5680
- ensureScratchExcluded(repoAbs);
5708
+ // #527: and the worktree subdir itself, or trunk's `git add -A` stages this worktree as a gitlink.
5709
+ ensureScratchExcluded(repoAbs, config);
5681
5710
 
5682
5711
  // 5. optional repo hook (machine-specific steps plug in here)
5683
5712
  const hook = runHook(repoAbs, 'post-create', { wtPath, name, branch, ports: alloc.chosenPorts, trunk, base, issues });
@@ -8023,13 +8052,17 @@ function gitExcludePath(repoAbs) {
8023
8052
  /**
8024
8053
  * #488: append the scratch-dir exclude lines (scratch-dirs.js `excludeLines`) to the clone's shared
8025
8054
  * info/exclude, idempotently. Best-effort: a failure warns and never blocks the caller.
8055
+ * #527: `config` given → the worktree subdir's line too (`worktreeExcludeLine`), so whatever creates
8056
+ * the default worktree dir also hides it — an adopted repo's `.gitignore` has never heard of it.
8026
8057
  */
8027
- function ensureScratchExcluded(repoAbs) {
8058
+ function ensureScratchExcluded(repoAbs, config = null) {
8028
8059
  const excludeFile = gitExcludePath(repoAbs);
8029
8060
  if (!excludeFile) return [];
8030
8061
  let before = null;
8031
8062
  try { before = fs.readFileSync(excludeFile, 'utf8'); } catch (_) { /* absent */ }
8032
8063
  const lines = scratchDirs.excludeLines();
8064
+ const wtLine = config ? scratchDirs.worktreeExcludeLine(worktreeSubdir(config)) : null;
8065
+ if (wtLine && !lines.includes(wtLine)) lines.push(wtLine);
8033
8066
  const missing = localAdopt.missingExcludeLines(before, lines);
8034
8067
  if (!missing.length) return [];
8035
8068
  try {
@@ -8348,7 +8381,9 @@ async function askMenu(rl, axis, promptFn) {
8348
8381
  if (resolved.ok) return resolved;
8349
8382
  process.stdout.write(` ${resolved.message}\n`);
8350
8383
  }
8351
- throw new UserError(`${axis}: no valid answer after one re-prompt`);
8384
+ throw new UserError(`${axis}: no valid answer after one re-prompt — nothing was written. Run \`colab adopt --axis ${axis}\` ` +
8385
+ `to be asked again, or pass the value directly: \`colab adopt ${axis === 'tier' ? '--deploy' : `--${axis}`} <value>\` ` +
8386
+ `(\`colab adopt --help\` lists them).`);
8352
8387
  }
8353
8388
 
8354
8389
  /**
@@ -8408,7 +8443,10 @@ async function adoptAskInteractive(rl, axesToAsk, cfg, checkExposure) {
8408
8443
  if (!problem) { chosen = resolved; break; }
8409
8444
  process.stdout.write(` ✗ ${problem}\n choose again (or skip):\n`);
8410
8445
  }
8411
- if (!chosen) throw new UserError('exposure: no answer this repo\'s shape supports after one re-prompt');
8446
+ // #532: this refusal comes after a long interaction, so it names the way through, not just the stop.
8447
+ if (!chosen) throw new UserError('exposure: no answer this repo\'s shape supports after one re-prompt — nothing was written. ' +
8448
+ 'Each "✗" above says why its value was refused. Run `colab adopt --axis exposure` and pick a value it accepts, ' +
8449
+ 'or `colab adopt --exposure <value>` non-interactively; choosing "skip" leaves exposure unanswered for now.');
8412
8450
  if (chosen.skip) continue; // decline — the fallback tier derivation picks this up
8413
8451
  answers.exposure = { values: { exposure: chosen.value }, mode: 'interactive' };
8414
8452
  } else {
@@ -8498,6 +8536,12 @@ async function cmdAdopt(argv) {
8498
8536
  local = adoptLocalPrepare(repoAbs, opts);
8499
8537
  if (local.exit !== undefined) return local.exit;
8500
8538
  }
8539
+ // #527: a repo adopted before `worktree new` hid its own dir gets the same exclude lines here —
8540
+ // machine-local (info/exclude), idempotent, never a committed diff. --local already wrote them.
8541
+ if (!opts.local) {
8542
+ const hidden = ensureScratchExcluded(repoAbs, state.loadConfig());
8543
+ if (hidden.length && !opts.json) print(`✓ hid ${hidden.join(' ')} in .git/info/exclude (machine-local)`);
8544
+ }
8501
8545
  const io = adoptIo(repoAbs);
8502
8546
  const extra = adoptGitExtras(repoAbs, opts);
8503
8547
  if (local) { extra.trunk = local.trunk; extra.trunkSource = 'local-integration'; }
@@ -9986,14 +10030,18 @@ function ciCureTrailerLine(cureVerdict, branch, trunk) {
9986
10030
  return `CI-Cure: branch ${branch} over-red ${trunk}@${shortSha(cureVerdict.redSha)} evidence ${shortSha(cureVerdict.evidenceSha)}${via}${admittedSuffix}${progressSuffix}`;
9987
10031
  }
9988
10032
 
9989
- const HELP_SHIP = `colab ship [--repo <path>] [--worktree <name> | --branch <br> | --direct] [--message "<msg>"] [--refs <N[,M]>] [--keep-worktree] [--delete-branch | --keep-branch] [--adopt] [--session <id>] [--session-name <s>] [--dry] [--json]
10033
+ const HELP_SHIP = `colab ship [--repo <path>] [--worktree <name> | --branch <br> | --direct] [--message "<msg>"] [--refs <N[,M]>] [--keep-worktree] [--delete-branch | --keep-branch] [--adopt] [--answered-by <name>] [--session <id>] [--session-name <s>] [--dry] [--json]
9990
10034
  colab ship --batch <b1,b2[,b3]> [--repo <path>] [--keep-worktree] [--delete-branch | --keep-branch] [--session <id>] [--session-name <s>] [--dry]
9991
10035
 
9992
10036
  The ONE sanctioned door for code-wrap Phase B: squash-merge a session branch into the BASE IT WAS
9993
10037
  CUT FROM — trunk for an ordinary session, or the declared integration line recorded on its worktree
9994
10038
  (project.yml \`integration:\`). Autonomy is granted by the repo's .github/project.yml
9995
10039
  (\`autonomy: auto-trunk\`) — NOT by any flag. Without that grant, ship refuses and a human must run
9996
- Phase B — unless the change is DOCS-ONLY, computed from git (#345, below). ship NEVER touches main (when trunk≠main), NEVER tags, NEVER promotes.
10040
+ Phase B — unless the change is DOCS-ONLY, computed from git (#345, below). That human runs ship
10041
+ too, through the HUMAN DOOR (#525): at an interactive terminal (outside an agent shell) ship asks
10042
+ them to confirm; non-interactively, COLAB_HUMAN=1 plus --answered-by <name>. Every other
10043
+ precondition still applies, and the 🚢 comment records that the human door opened the gate.
10044
+ ship NEVER touches main (when trunk≠main), NEVER tags, NEVER promotes.
9997
10045
 
9998
10046
  Base and target are ONE decision. A branch cut from a long-lived line and shipped into trunk would
9999
10047
  drag the entire line in behind it, as a single squash commit that reads like a small change — so
@@ -10003,6 +10051,8 @@ promotes is an integration event of the same weight as a promotion, and stays hu
10003
10051
 
10004
10052
  Sequence (each step gated; any failure aborts before the push — the target is never half-shipped):
10005
10053
  a. autonomy gate repo must grant auto-trunk (no --force override) — or the diff is docs-only (#345)
10054
+ — or a person runs ship through the human door (#525): a confirmed interactive
10055
+ terminal, or COLAB_HUMAN=1 + --answered-by <name>. An agent shell is no terminal.
10006
10056
  b. preconditions target CI alive+green (UNLESS the branch proves the CURE RULE, #281 — no
10007
10057
  human step needed — OR every issue the branch carries holds a valid
10008
10058
  \`colab ci-grant\` over trunk's CURRENT red sha, #105 — see below) · no new
@@ -11049,7 +11099,7 @@ function applyRedTrunkExemptions(raw, target, trunk, redSha, grantThunk, cureThu
11049
11099
  return {
11050
11100
  name: raw.name, ok: true, class: null,
11051
11101
  detail: `PRECONDITION OVERRIDDEN by the cure rule (#281) — branch contains red ${shortSha(redSha)} and is green at its own head${via}${viaDry} (raw: ${raw.detail})`,
11052
- grantVerdict: null, cureVerdict,
11102
+ grantVerdict: null, cureVerdict, redSha,
11053
11103
  };
11054
11104
  }
11055
11105
 
@@ -11064,10 +11114,45 @@ function applyRedTrunkExemptions(raw, target, trunk, redSha, grantThunk, cureThu
11064
11114
  return {
11065
11115
  name: raw.name, ok: true, class: null,
11066
11116
  detail: `PRECONDITION OVERRIDDEN by ${who} on ${by} — trunk was red at ${shortSha(redSha)} (raw: ${raw.detail})`,
11067
- grantVerdict, cureVerdict,
11117
+ grantVerdict, cureVerdict, redSha,
11068
11118
  };
11069
11119
  }
11070
- return { ...raw, grantVerdict, cureVerdict };
11120
+ // #534: both doors were consulted and both refused — say WHY on the row itself, so the prose table,
11121
+ // `--dry`, and B1's abort line all tell "needs a grant" from "missing evidence" from "stacked". The
11122
+ // JSON payload already carried `ciCure.reason`; the prose detail used to end at the raw trunk read.
11123
+ return { ...raw, detail: `${raw.detail}${doorRefusalNote(cureVerdict, grantVerdict)}`, grantVerdict, cureVerdict, redSha };
11124
+ }
11125
+
11126
+ /**
11127
+ * Which red-trunk door let a trunk-CI row pass — `'cure rule'`, `'ci-grant'`, or null for a row that
11128
+ * passed on its own (green) or did not pass (#538: B1 re-measures only a door the table relied on).
11129
+ */
11130
+ function doorThatAdmitted(ciResult) {
11131
+ if (!ciResult || !ciResult.ok) return null;
11132
+ if (ciResult.cureVerdict && ciResult.cureVerdict.ok) return 'cure rule';
11133
+ if (ciResult.grantVerdict && ciResult.grantVerdict.ok) return 'ci-grant';
11134
+ return null;
11135
+ }
11136
+
11137
+ /** #538: the pause before B1's one re-measure — long enough for a transient `gh` failure to clear. */
11138
+ const B1_REMEASURE_MS = Number.isFinite(Number(process.env.COLAB_B1_REMEASURE_MS))
11139
+ && process.env.COLAB_B1_REMEASURE_MS !== '' ? Number(process.env.COLAB_B1_REMEASURE_MS) : 3000;
11140
+
11141
+ /**
11142
+ * The " — cure rule (#281): …; ci-grant (#105): …" suffix of a refused trunk-CI row (#534). Empty
11143
+ * when neither door was consulted. One clause per door, each its own refusal reason verbatim — the
11144
+ * cure's `reason`, the grant's per-issue `missing[].reason` — never a re-wording, so the prose and
11145
+ * the `--dry --json` fields cannot read differently.
11146
+ */
11147
+ function doorRefusalNote(cureVerdict, grantVerdict) {
11148
+ const parts = [];
11149
+ if (cureVerdict && !cureVerdict.ok && cureVerdict.reason) parts.push(`cure rule (#281): ${cureVerdict.reason}`);
11150
+ if (grantVerdict && !grantVerdict.ok) {
11151
+ const why = (grantVerdict.missing || []).map((m) => (m.issue ? `#${m.issue}: ` : '') + m.reason)
11152
+ .map((s) => s.replace(/^(#\d+): \1/, '$1')).join('; ');
11153
+ if (why) parts.push(`ci-grant (#105): ${why}`);
11154
+ }
11155
+ return parts.length ? ` — ${parts.join(' · ')}` : '';
11071
11156
  }
11072
11157
 
11073
11158
  /**
@@ -11609,7 +11694,8 @@ function cmdShipDryJson(opts) {
11609
11694
  }
11610
11695
 
11611
11696
  // ---- (a) AUTONOMY GATE — does NOT short-circuit here; an unattended caller wants the whole table ----
11612
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)));
11697
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
11698
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
11613
11699
  autonomyGatePayloadVal = autonomyGatePayload(autonomyGate);
11614
11700
  checks.push({ name: 'autonomy granted', ok: autonomyGate.ok, class: autonomyGate.ok ? null : HUMAN_GATED, detail: autonomyGate.detail });
11615
11701
 
@@ -12008,7 +12094,7 @@ function shipEvidenceClose({ repoAbs, st, sess, target, trunk, gh, closeIssues,
12008
12094
  `The deliverable is recorded on this issue (see the comment(s) above), which is what authorised ` +
12009
12095
  `the close — colab closes a zero-diff issue only when it already carries a comment colab did not ` +
12010
12096
  `write. The zero-diff fact was measured from git: ${mode.why}.${shipSess}`;
12011
- const c = git.ghIssueComment(repoAbs, num, body);
12097
+ const c = git.ghIssueComment(repoAbs, num, body + (opts.humanDoorEvidence || '')); // #525
12012
12098
  if (!c.ok) warn(`could not post the evidence-close comment on #${num} — closing anyway`);
12013
12099
  const r = tracker.forRepo(repoAbs).issueClose(num, { reason: 'completed' });
12014
12100
  if (!r.ok) { skipped.push({ num, why: `gh issue close failed: ${(r.stderr || '').split('\n')[0]}` }); continue; }
@@ -12170,7 +12256,8 @@ function cmdShipDirect(opts) {
12170
12256
  // #345: a trunk-direct unit has no branch diff. Its change set is every trunk commit since its
12171
12257
  // earliest claim — by anyone, so the verdict can only err toward refusing (lib/docs-only.js).
12172
12258
  const since = claims.map((c) => c.created).filter(Boolean).sort()[0];
12173
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.directChanges(git, repoAbs, trunk, since));
12259
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.directChanges(git, repoAbs, trunk, since),
12260
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
12174
12261
  autonomyGatePayloadVal = autonomyGatePayload(autonomyGate);
12175
12262
  checks.push({ name: 'autonomy granted', ok: autonomyGate.ok, class: autonomyGate.ok ? null : HUMAN_GATED, detail: autonomyGate.detail });
12176
12263
 
@@ -12249,6 +12336,7 @@ function cmdShipDirect(opts) {
12249
12336
  process.stderr.write(`✗ ${shortRepo(repoAbs)} does not grant auto-trunk (project.yml autonomy: ${autonomyGate.declared}).\n`);
12250
12337
  process.stderr.write(' A human must close this unit. (Autonomy is granted by the repo, not by a flag — --force cannot override.)\n');
12251
12338
  process.stderr.write(` The docs-only exception (#345) does not apply either: ${autonomyGate.docsOnly.reason}.\n`);
12339
+ process.stderr.write(shipHumanDoorRefusal(autonomyGate, '--direct'));
12252
12340
  return 1;
12253
12341
  }
12254
12342
  if (!coreOk && coreReview.corePaths.length) {
@@ -12260,6 +12348,7 @@ function cmdShipDirect(opts) {
12260
12348
  process.stderr.write(' unit\'s reviewed landing, a human closes this issue by hand.\n');
12261
12349
  }
12262
12350
  if (autonomyGate.via === 'docs-only') print(`→ AUTONOMY: ${autonomyGate.detail} (#345) — project.yml autonomy: ${autonomyGate.declared}`);
12351
+ if (autonomyGate.via === 'human') print(`→ AUTONOMY: ${autonomyGate.detail}`);
12263
12352
  print(`→ MODE: evidence-close (trunk-direct — the work is already on ${trunk}; nothing to merge)`);
12264
12353
  if (opts.dry) {
12265
12354
  print(preOk ? '→ READY: preconditions pass. Re-run without --dry to close.' : '→ NOT READY: fix the ✗ rows above.');
@@ -12271,6 +12360,7 @@ function cmdShipDirect(opts) {
12271
12360
  return preOk ? 0 : 1;
12272
12361
  }
12273
12362
  if (!preOk) { process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was closed.\n'); return 1; }
12363
+ if (!shipHumanDoorGo(autonomyGate, opts, `close ${issues.map((n) => '#' + n).join(' ')} on ${trunk} (trunk-direct)`)) return 1;
12274
12364
 
12275
12365
  const tip = shortSha(git.git(['rev-parse', trunk], repoAbs).stdout);
12276
12366
  const mode = { evidenceClose: true, direct: true, why: `trunk-direct unit — ${trunk}@${tip} is checked out clean and published to ${git.remoteInfo(repoAbs).name || 'origin'}/${trunk}` };
@@ -12488,20 +12578,81 @@ function shipOpenCorePr(repoAbs, cr, { target, branch, title, body }) {
12488
12578
  *
12489
12579
  * Returns `{ ok, via: 'auto-trunk'|'docs-only'|null, declared, docsOnly: verdict|null, detail }`.
12490
12580
  */
12491
- function shipAutonomyGate(doc, readDocsOnly) {
12581
+ function shipAutonomyGate(doc, readDocsOnly, door = null) {
12492
12582
  const declared = doc.autonomy ? String(doc.autonomy) : 'absent';
12493
- if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, detail: 'auto-trunk' };
12583
+ if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, human: null, detail: 'auto-trunk' };
12494
12584
  const verdict = readDocsOnly();
12495
12585
  if (verdict.docsOnly) {
12496
- return { ok: true, via: 'docs-only', declared, docsOnly: verdict, detail: `${verdict.reason} — autonomy exception` };
12586
+ return { ok: true, via: 'docs-only', declared, docsOnly: verdict, human: null, detail: `${verdict.reason} — autonomy exception` };
12497
12587
  }
12498
- return { ok: false, via: null, declared, docsOnly: verdict,
12499
- detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason})` };
12588
+ // #525: the human door — the person running ship IS the go (ruling on #525, option 1). Checked
12589
+ // after docs-only, so a docs-only change keeps its own (agent-usable) door and record.
12590
+ if (door && door.open) {
12591
+ return { ok: true, via: 'human', declared, docsOnly: verdict, human: door,
12592
+ detail: `human door (#525): ${door.why} — project.yml autonomy: ${declared}` };
12593
+ }
12594
+ return { ok: false, via: null, declared, docsOnly: verdict, human: door,
12595
+ detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason}; human door closed: ${door ? door.why : 'not offered'})` };
12596
+ }
12597
+
12598
+ /** #525: the human-door refusal lines — what a person runs, never just "a human must". */
12599
+ function shipHumanDoorRefusal(gate, selector) {
12600
+ const lines = [];
12601
+ if (gate.human && gate.human.why) lines.push(` The human door (#525) did not open: ${gate.human.why}.`);
12602
+ lines.push(' A person gives the go by running ship themselves — every other precondition still applies:');
12603
+ for (const l of humanDoor.humanDoorCommands(selector)) lines.push(` ${l}`);
12604
+ lines.push(' An agent does not pass this door on its own (CONVENTIONS.md §2, *The human door*).');
12605
+ return lines.join('\n') + '\n';
12606
+ }
12607
+
12608
+ /** #525: the ship selector to paste into the refusal's command line. */
12609
+ function shipSelector(opts, sess) {
12610
+ if (opts.direct) return '--direct';
12611
+ if (opts.worktree) return `--worktree ${opts.worktree}`;
12612
+ if (sess && sess.name) return `--worktree ${sess.name}`;
12613
+ if (opts.branch) return `--branch ${opts.branch}`;
12614
+ return sess && sess.branch ? `--branch ${sess.branch}` : '';
12615
+ }
12616
+
12617
+ /**
12618
+ * #525: confirm the TTY door by a typed answer. Synchronous on purpose — ship is a sync pipeline,
12619
+ * and the prompt sits before any write. Anything but `y`/`yes` is a no; EOF is a no.
12620
+ */
12621
+ function shipConfirmAtTerminal(question) {
12622
+ process.stdout.write(`${question} [y/N] `);
12623
+ const buf = Buffer.alloc(256);
12624
+ let line = '';
12625
+ for (;;) {
12626
+ let n = 0;
12627
+ try { n = fs.readSync(0, buf, 0, buf.length, null); } catch (e) { if (e.code === 'EAGAIN') continue; return false; }
12628
+ if (n <= 0) break;
12629
+ line += buf.toString('utf8', 0, n);
12630
+ if (line.includes('\n')) break;
12631
+ }
12632
+ return /^\s*y(es)?\s*$/i.test(line.split('\n')[0]);
12633
+ }
12634
+
12635
+ /**
12636
+ * #525: the last step before any write when the human door opened the gate. A TTY door asks the
12637
+ * person to confirm; a COLAB_HUMAN door already carries its go (`--answered-by`). Either way the
12638
+ * evidence clause is stashed on `opts` for the comment writers. Returns false on a declined prompt.
12639
+ */
12640
+ function shipHumanDoorGo(gate, opts, what) {
12641
+ if (gate.via !== 'human') return true;
12642
+ if (gate.human.how === 'tty' && !shipConfirmAtTerminal(`Human door (#525): ${what}. This is your go — proceed?`)) {
12643
+ process.stderr.write('✗ Not confirmed at the terminal. Nothing was changed.\n');
12644
+ return false;
12645
+ }
12646
+ opts.humanDoorEvidence = humanDoor.humanDoorEvidence(gate.human);
12647
+ return true;
12500
12648
  }
12501
12649
 
12502
12650
  /** #345: the additive `autonomyGate` field of the `--dry --json` output. */
12503
12651
  function autonomyGatePayload(gate) {
12504
- return { via: gate.via, docsOnly: gate.docsOnly };
12652
+ // #525: `human` is additive and present only when the human door was consulted, so an
12653
+ // auto-trunk / docs-only payload stays byte-identical to before.
12654
+ return gate.human ? { via: gate.via, docsOnly: gate.docsOnly, human: { open: gate.human.open, how: gate.human.how, why: gate.human.why } }
12655
+ : { via: gate.via, docsOnly: gate.docsOnly };
12505
12656
  }
12506
12657
 
12507
12658
  /** The sha a branch name resolves to, local first, else origin's copy (#324's remote-only shape). */
@@ -12512,7 +12663,7 @@ function shipRefFor(repoAbs, branch) {
12512
12663
 
12513
12664
  function cmdShip(argv) {
12514
12665
  const opts = parseArgs(argv, {
12515
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
12666
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch', '--answered-by': 'answeredBy' },
12516
12667
  // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
12517
12668
  // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
12518
12669
  // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
@@ -12587,11 +12738,13 @@ function cmdShip(argv) {
12587
12738
 
12588
12739
  // ---- (a) AUTONOMY GATE — granted by the repo file, never by the caller ----
12589
12740
  // #345: …or the branch's diff is documentation only, computed here from git — never asserted.
12590
- const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)));
12741
+ const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
12742
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
12591
12743
  if (!autonomyGate.ok) {
12592
12744
  process.stderr.write(`✗ ${shortRepo(repoAbs)} does not grant auto-trunk (project.yml autonomy: ${autonomyGate.declared}).\n`);
12593
12745
  process.stderr.write(' A human must trigger Phase B. (Autonomy is granted by the repo, not by a flag — --force cannot override.)\n');
12594
12746
  process.stderr.write(` The docs-only exception (#345) does not apply either: ${autonomyGate.docsOnly.reason}.\n`);
12747
+ process.stderr.write(shipHumanDoorRefusal(autonomyGate, shipSelector(opts, sess)));
12595
12748
  return 1;
12596
12749
  }
12597
12750
 
@@ -12984,6 +13137,9 @@ function cmdShip(argv) {
12984
13137
  }
12985
13138
  process.stderr.write('✗ Aborting: one or more preconditions failed (see ✗ above). Nothing was pushed.\n'); return 1;
12986
13139
  }
13140
+ if (!shipHumanDoorGo(autonomyGate, opts, mode.evidenceClose
13141
+ ? `evidence-close ${sess.issues.map((n) => '#' + n).join(' ')} (${sess.branch} has nothing to merge)`
13142
+ : `squash-merge ${sess.branch} into ${target}`)) return 1;
12987
13143
 
12988
13144
  // ---- (b3) evidence-close: the whole B0–B2 sequence is skipped, because there is nothing to merge ----
12989
13145
  if (mode.evidenceClose) return shipEvidenceClose({
@@ -13108,12 +13264,29 @@ function cmdShip(argv) {
13108
13264
  let ciGrantForTrailer = null; // #105: set below when B1 shipped UNDER a grant — read at commit-message time
13109
13265
  let ciCureForTrailer = null; // #281: set below when B1 shipped UNDER the cure rule — read at commit-message time
13110
13266
  if (gh) {
13111
- const ciResultB1 = shipCiCheck(repoAbs, gh, target, trunk,
13267
+ const measureB1 = () => shipCiCheck(repoAbs, gh, target, trunk,
13112
13268
  (redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
13113
13269
  (redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
13270
+ let ciResultB1 = measureB1();
13271
+ // #538: the table admitted this branch through a door (cure or grant) at red sha X, and B1 —
13272
+ // seconds later, at the SAME red sha — refused. Nothing the door judges moved (trunk's head is
13273
+ // X in both reads), so the likeliest cause is one of the ~10 `gh` reads a door makes failing
13274
+ // once, which every door reads as a refusal (fail closed). Measured: `--dry` said READY and the
13275
+ // real ship aborted here with only the raw "conclusion=failure". Re-measure ONCE, in full —
13276
+ // never reuse the table's verdict (B1 exists to catch a change) — and if it refuses again, abort
13277
+ // saying it was the door, with the door's own reason.
13278
+ const tableDoor = doorThatAdmitted(ciResult);
13279
+ if (!ciResultB1.ok && tableDoor && ciResultB1.redSha && ciResultB1.redSha === ciResult.redSha) {
13280
+ warn(` B1: the ${tableDoor} admitted this branch in the table at ${target}@${shortSha(ciResult.redSha)} but refused on the re-check at the same sha — re-measuring once (a failed read refuses).`);
13281
+ ciWait.sleepSync(B1_REMEASURE_MS);
13282
+ ciResultB1 = measureB1();
13283
+ }
13114
13284
  if (!ciResultB1.ok) {
13115
13285
  cleanupEphemeral();
13116
- process.stderr.write(`✗ B1: CI for ${target} is no longer green — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`);
13286
+ const sameRed = tableDoor && ciResultB1.redSha && ciResultB1.redSha === ciResult.redSha;
13287
+ process.stderr.write(sameRed
13288
+ ? `✗ B1: the ${tableDoor} admitted this branch in the precondition table, then refused twice on the re-check at the same ${target}@${shortSha(ciResult.redSha)} — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`
13289
+ : `✗ B1: CI for ${target} is no longer green — aborting before merge. Nothing pushed. (${ciResultB1.detail})\n`);
13117
13290
  return 1;
13118
13291
  }
13119
13292
  if (ciResultB1.cureVerdict && ciResultB1.cureVerdict.ok) {
@@ -13483,7 +13656,8 @@ function cmdShip(argv) {
13483
13656
  // last — see warnDeferred's own comment for why this is scoped to exactly this window. The
13484
13657
  // window itself now OPENS at the push (e2, #304), not here: post-ship's warnings belong in the
13485
13658
  // same block, and re-assigning the collector here would silently discard them.
13486
- shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts });
13659
+ shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, refsIssues, refsSet, integration, opts,
13660
+ evidenceExtra: opts.humanDoorEvidence || '' }); // #525
13487
13661
 
13488
13662
  print('');
13489
13663
  print(`✓ Shipped ${sess.branch} → ${target} @ ${sha}${sess.issues.length ? ' (' + sess.issues.map((n) => '#' + n).join(' ') + ')' : ''}`);
@@ -14222,13 +14396,15 @@ Wait for CI and exit with its outcome. The ONE way to wait for a run: never hand
14222
14396
  --sha <sha> wait for EVERY repo-owned workflow at the sha (the verdict colab ship reads:
14223
14397
  newest run per workflow, dynamic workflows dropped — #451/#461; only runs that
14224
14398
  verify the code, so a post-CI release/deploy run is set aside — #503); a sha
14225
- with no run yet counts as pending until the deadline
14399
+ with no run yet counts as pending until the deadline. An abbreviated sha is
14400
+ resolved in the repo first, and refused (exit 2) when it does not resolve — #529
14226
14401
  --branch <b> narrow --sha to runs on that branch
14227
14402
  --timeout <d> deadline: 45m (default), 90s, 1h, or seconds
14228
14403
 
14229
14404
  Polls at 0s, then +30s, +60s, +120s, +120s … until the deadline. Every poll after the first is a
14230
- conditional request (If-None-Match); a 304 is not counted against the REST rate limit. A 15-minute
14231
- run costs about 10 requests. One wait per run per checkout: a second waiter is refused.
14405
+ conditional request (If-None-Match); a 304 is not counted against the REST rate limit. After two
14406
+ 304s in a row, and on the last poll before the deadline, it re-reads unconditionally: a stale ETag
14407
+ can cost one paid call, never the whole wait (#505). A 15-minute run costs about 10 requests. One wait per run per checkout: a second waiter is refused.
14232
14408
 
14233
14409
  Exit codes — branch on these, never on the text:
14234
14410
  0 GREEN the run (every judged run at the sha) succeeded
@@ -14240,7 +14416,7 @@ Exit codes — branch on these, never on the text:
14240
14416
  6 ALREADY_WAITING another live ci-wait on this checkout holds the same run/sha
14241
14417
 
14242
14418
  It prints the wait it did: outcome, elapsed time, polls, and how many were 304s.
14243
- --json { outcome, exit, target, polls, notModified, waitedSec, detail, status, conclusion, url }`;
14419
+ --json { outcome, exit, target, polls, notModified, forced, waitedSec, detail, status, conclusion, url }`;
14244
14420
 
14245
14421
  function cmdCiWait(argv) {
14246
14422
  const opts = parseArgs(argv, {
@@ -14256,6 +14432,17 @@ function cmdCiWait(argv) {
14256
14432
  const deadlineSec = opts.timeout !== undefined ? ciWait.parseDuration(opts.timeout) : ciWait.DEFAULT_DEADLINE_SEC;
14257
14433
  if (!deadlineSec) { warn(`--timeout: cannot read "${opts.timeout}" (try 45m, 90s, 1h)`); return ciWait.EXIT.USAGE; }
14258
14434
  const repoAbs = resolveRepo(opts);
14435
+ if (opts.sha) {
14436
+ // #529: the API reports a 40-hex head_sha and the rows are matched by equality, so an
14437
+ // abbreviated --sha would match nothing and wait out the whole deadline as "pending" — on a run
14438
+ // that finished green in minutes. Resolve it here, or refuse; never poll with it.
14439
+ const full = git.fullSha(repoAbs, opts.sha);
14440
+ if (!full) {
14441
+ warn(`--sha ${opts.sha}: not a full 40-hex sha and it does not resolve to one commit in ${repoAbs} — pass the full sha (\`git rev-parse <sha>\`), or fetch first`);
14442
+ return ciWait.EXIT.USAGE;
14443
+ }
14444
+ opts.sha = full;
14445
+ }
14259
14446
  if (!git.ghInstalled()) { warn('gh is not installed — cannot read CI'); return ciWait.EXIT.UNKNOWN; }
14260
14447
 
14261
14448
  const target = runId ? `run ${runId}` : `sha ${shortSha(opts.sha)}${opts.branch ? ` on ${opts.branch}` : ''}`;
@@ -14294,7 +14481,7 @@ function cmdCiWait(argv) {
14294
14481
  try {
14295
14482
  res = ciWait.waitLoop({
14296
14483
  poll, sleep: ciWait.sleepSync, deadlineSec,
14297
- onPoll: (p) => { if (!opts.json) process.stderr.write(`ci-wait: poll ${p.poll} at +${ciWait.fmtDuration(p.elapsedMs)} — ${p.state}${p.notModified ? ' (304, not counted)' : ''}\n`); },
14484
+ onPoll: (p) => { if (!opts.json) process.stderr.write(`ci-wait: poll ${p.poll} at +${ciWait.fmtDuration(p.elapsedMs)} — ${p.state}${p.notModified ? ' (304, not counted)' : ''}${p.forced ? ' (unconditional re-read — #505)' : ''}\n`); },
14298
14485
  });
14299
14486
  } finally {
14300
14487
  lock.release();
@@ -14302,7 +14489,7 @@ function cmdCiWait(argv) {
14302
14489
  const s = (res.last && res.last.summary) || {};
14303
14490
  const code = ciWait.EXIT[res.outcome];
14304
14491
  const out = {
14305
- outcome: res.outcome, exit: code, target, polls: res.polls, notModified: res.notModified,
14492
+ outcome: res.outcome, exit: code, target, polls: res.polls, notModified: res.notModified, forced: res.forced,
14306
14493
  waitedSec: Math.round(res.waitedMs / 1000), detail: res.detail || null,
14307
14494
  status: s.status || null, conclusion: s.conclusion || null, url: s.url || null,
14308
14495
  ...(Array.isArray(s.setAside) && s.setAside.length ? { setAside: s.setAside } : {}),
@@ -13,7 +13,8 @@
13
13
  * run costs ~10 polls instead of ~180 at `sleep 5`;
14
14
  * - conditional requests: every poll after the first sends `If-None-Match`, and a `304 Not
15
15
  * Modified` is not counted against the primary rate limit (GitHub REST docs, "conditional
16
- * requests");
16
+ * requests") — capped (#505): after two 304s in a row, and on the deadline's poll, it re-reads
17
+ * unconditionally, because a validator that never changes would otherwise pin a stale state;
17
18
  * - a rate limit (403 with remaining 0, or 429) ENDS the wait with its own outcome — never a retry;
18
19
  * - an unreadable or unrecognised state ends it too (UNKNOWN), never "keep waiting";
19
20
  * - one wait per run per checkout: a second waiter on the same key is refused (ALREADY_WAITING).
@@ -112,19 +113,32 @@ function runState(s) {
112
113
  return 'unknown';
113
114
  }
114
115
 
116
+ /**
117
+ * #505: how many 304s in a row may stand for the state before the next poll re-reads without
118
+ * `If-None-Match`. Measured: the runs-list read kept answering 304 for ten minutes while every run
119
+ * at the sha had completed green — the validator never changed, so a loop that trusted it would
120
+ * have reported TIMEOUT on a green sha. A cap of 2 bounds that to one paid call per three polls.
121
+ */
122
+ const DEFAULT_MAX_NOT_MODIFIED = 2;
123
+
115
124
  /**
116
125
  * The wait loop. `poll(etag)` returns a classifyResponse() result, plus `state` (runState) and
117
- * `summary` on `ok`. `sleep(ms)` blocks; `now()` is epoch ms. A 304 keeps the previous state.
126
+ * `summary` on `ok`. `sleep(ms)` blocks; `now()` is epoch ms. A 304 keeps the previous state — but
127
+ * only for `maxNotModified` polls in a row, and never on the last poll before the deadline: those
128
+ * polls send no ETag (`poll(null)`), so a stale validator costs one paid read, not the wait (#505).
118
129
  *
119
- * Returns `{ outcome, polls, notModified, waitedMs, last, detail }`, outcome one of the EXIT keys.
130
+ * Returns `{ outcome, polls, notModified, forced, waitedMs, last, detail }`, outcome one of the
131
+ * EXIT keys; `forced` counts the unconditional re-reads #505 added.
120
132
  */
121
133
  function waitLoop({ poll, sleep, now = Date.now, deadlineSec = DEFAULT_DEADLINE_SEC,
122
- schedule = DEFAULT_SCHEDULE_SEC, onPoll = () => {} }) {
134
+ schedule = DEFAULT_SCHEDULE_SEC, maxNotModified = DEFAULT_MAX_NOT_MODIFIED, onPoll = () => {} }) {
123
135
  const start = now();
124
136
  let etag = null;
125
137
  let last = null;
126
138
  let polls = 0;
127
139
  let notModified = 0;
140
+ let streak = 0; // consecutive 304s
141
+ let forced = 0;
128
142
  for (let i = 0; ; i++) {
129
143
  const d = delayFor(i, schedule) * 1000;
130
144
  if (d) {
@@ -132,25 +146,31 @@ function waitLoop({ poll, sleep, now = Date.now, deadlineSec = DEFAULT_DEADLINE_
132
146
  if (left <= 0) return done('TIMEOUT', `still ${last ? last.state : 'unread'} at the ${fmtDuration(deadlineSec * 1000)} deadline`);
133
147
  sleep(Math.min(d, left));
134
148
  }
135
- const r = poll(etag);
149
+ // The poll that lands on the deadline is the last one: it must read the truth, not a 304.
150
+ const final = now() - start >= deadlineSec * 1000;
151
+ const force = Boolean(etag) && (streak >= maxNotModified || final);
152
+ if (force) forced++;
153
+ const r = poll(force ? null : etag);
136
154
  polls++;
137
155
  if (r.kind === 'rate-limited') return done('RATE_LIMITED', r.detail + (r.resetAt ? ` — quota resets ${new Date(r.resetAt).toISOString()}` : ''), r);
138
156
  if (r.kind === 'error') return done('UNKNOWN', `read failed: ${r.detail}`, r);
139
157
  if (r.kind === 'not-modified') {
140
158
  notModified++;
159
+ streak++;
141
160
  if (!last) return done('UNKNOWN', '304 on the first read — nothing to compare against', r);
142
161
  } else {
162
+ streak = 0;
143
163
  etag = r.etag || etag;
144
164
  last = r;
145
165
  }
146
- onPoll({ poll: polls, state: last.state, notModified: r.kind === 'not-modified', elapsedMs: now() - start });
166
+ onPoll({ poll: polls, state: last.state, notModified: r.kind === 'not-modified', forced: force, elapsedMs: now() - start });
147
167
  if (last.state === 'green') return done('GREEN', null);
148
168
  if (last.state === 'red') return done('RED', null);
149
169
  if (last.state !== 'pending') return done('UNKNOWN', `unrecognised state (${JSON.stringify(last.summary || null)})`);
150
170
  if (now() - start >= deadlineSec * 1000) return done('TIMEOUT', `still pending at the ${fmtDuration(deadlineSec * 1000)} deadline`);
151
171
  }
152
172
  function done(outcome, detail, r) {
153
- return { outcome, polls, notModified, waitedMs: now() - start, last: last || r || null, detail };
173
+ return { outcome, polls, notModified, forced, waitedMs: now() - start, last: last || r || null, detail };
154
174
  }
155
175
  }
156
176
 
@@ -197,7 +217,7 @@ function sleepSync(ms) {
197
217
  }
198
218
 
199
219
  module.exports = {
200
- EXIT, DEFAULT_SCHEDULE_SEC, DEFAULT_DEADLINE_SEC,
220
+ EXIT, DEFAULT_SCHEDULE_SEC, DEFAULT_DEADLINE_SEC, DEFAULT_MAX_NOT_MODIFIED,
201
221
  delayFor, parseHttp, classifyResponse, restRow, runState, waitLoop, fmtDuration, parseDuration,
202
222
  acquireLock, sleepSync,
203
223
  };
@@ -95,6 +95,43 @@ function isIntentSession(s) {
95
95
  return /^intent:\S/.test(String(s == null ? '' : s).trim());
96
96
  }
97
97
 
98
+ /**
99
+ * Should a blank session be DERIVED for a person at a plain terminal (#528)? Only when nothing was
100
+ * said at all: `COLAB_SESSION` is UNSET (an explicit `COLAB_SESSION=''` is a deliberate "present no
101
+ * identity" and is honoured as one), and the shell is not an agent's (`CLAUDECODE=1` / `AI_AGENT`,
102
+ * the same signal `place.resolveAnchor` reads). An agent keeps #242's refusal: two concurrent agent
103
+ * sessions on one machine would derive the SAME person id, and `place.conflict`'s same-holder
104
+ * exemption would then read one session's hold as the other's — the collision #242 exists to stop.
105
+ * A person running several units at once from separate shells has the same problem, which is why
106
+ * the README tells them to give each shell its own `COLAB_SESSION`.
107
+ */
108
+ function shouldDerivePersonSession(env) {
109
+ const e = env || {};
110
+ if (Object.prototype.hasOwnProperty.call(e, 'COLAB_SESSION')) return false;
111
+ if (e.CLAUDECODE === '1' || e.AI_AGENT) return false;
112
+ return true;
113
+ }
114
+
115
+ /**
116
+ * The derived identity for a person (#528): `person:<who>/<hostToken>`, where `<who>` is git's
117
+ * `user.email`, else the OS user. The host is the opaque `h:` token (`machine.hostToken`), never
118
+ * the raw name: this value is written verbatim into claim comments, and a public tracker must not
119
+ * learn a machine's name from it (#369). Stable across invocations — the same person on the same
120
+ * machine always derives the same value, which is what a re-acquire needs. '' when no `<who>` or
121
+ * no host is available: then nothing is derived and the blank-session paths apply unchanged.
122
+ */
123
+ function derivePersonSession({ email, user, hostToken } = {}) {
124
+ const who = String(email || '').trim() || String(user || '').trim();
125
+ const host = String(hostToken || '').trim();
126
+ if (!who || !host || /\s/.test(who)) return '';
127
+ return `person:${who}/${host}`;
128
+ }
129
+
130
+ /** Is `s` a derived person identity (#528)? */
131
+ function isPersonSession(s) {
132
+ return /^person:\S+$/.test(String(s == null ? '' : s).trim());
133
+ }
134
+
98
135
  /**
99
136
  * Are `a` and `b` on the SAME machine (#327)? Both carry a `machine` → compare those (a raw id or
100
137
  * the `m:` digest a claim comment carries — `machineToken` makes the two comparable); raw ids of
@@ -189,4 +226,5 @@ module.exports = {
189
226
  DEFAULT_COMPONENTS, FINE_COMPONENTS,
190
227
  claimIdentityProblem, components, identityString, sameClaimant, mergeClaimRecord,
191
228
  looksLikeSessionId, isIntentSession, sameHost,
229
+ shouldDerivePersonSession, derivePersonSession, isPersonSession,
192
230
  };
@@ -41,7 +41,9 @@ const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
41
41
  function looksLikeSessionId(v) {
42
42
  const s = String(v == null ? '' : v).trim();
43
43
  if (!s) return false;
44
- return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s);
44
+ // #528: a derived person identity (`claim-identity.js` `derivePersonSession`) is a session id
45
+ // too — a stable join key, not a display name — so it reads back as one from a claim comment.
46
+ return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s) || /^person:\S+$/.test(s);
45
47
  }
46
48
 
47
49
  /**
@@ -169,6 +169,11 @@
169
169
  * this entry, plus the matching `code-triage` verdict, is what makes those readings
170
170
  * reconcilable instead of silently contradictory.
171
171
  *
172
+ * `priority:now` / `priority:high` joined the set in #537: the upward rank beside `low-priority`
173
+ * (CONVENTIONS.md §5, *Priority*). Fixed values, not a prefix kind — they decode as plain
174
+ * `convention` labels. Same malignant-absence reason: a rank only the owner may set must be
175
+ * appliable the moment the owner says so, which a label the repo never created is not.
176
+ *
172
177
  * `deferred:date` / `deferred:measurement` / `deferred:external-party` joined the set in
173
178
  * #279: `deps-checked` was being asked to carry two orthogonal facts at once — "has a
174
179
  * reasoning session evaluated this?" (process state, monotonic — the label's own
@@ -222,6 +227,8 @@ const CONVENTION_LABELS = [
222
227
  { name: 'needs-migration-grant', color: 'D4C5F9', description: 'Agent-flagged: deliverable is a schema migration; surfaces the grant request for a human to Accept' },
223
228
  { name: 'ci-granted', color: 'D73A4A', description: "A human granted this branch a one-shot exemption from ship's trunk-CI-green gate" },
224
229
  { name: 'low-priority', color: 'C2E0C6', description: 'Throttle, not a veto — startable, but code-triage ranks it behind every other ready group' },
230
+ { name: 'priority:now', color: 'B60205', description: "Rank first among ready work — the owner's order; never skips a gate or overrides a file hold" },
231
+ { name: 'priority:high', color: 'D93F0B', description: 'Rank ahead of default among ready work — owner or coordinator; never skips a gate' },
225
232
  { name: 'delivery:code', color: '1D76DB', description: 'Delivery is a code commit — the ordinary code pipeline applies' },
226
233
  { name: 'delivery:content', color: 'FEF2C0', description: 'Delivery is a content push, not a code commit — route, do not start in the code pipeline' },
227
234
  { name: 'delivery:ops', color: 'D4C5F9', description: 'Delivery is an ops/production check, not a code commit — route, do not start in the code pipeline' },
@@ -81,6 +81,22 @@
81
81
  "known": true
82
82
  }
83
83
  },
84
+ {
85
+ "wire": "priority:now",
86
+ "decoded": {
87
+ "kind": "convention",
88
+ "value": "priority:now",
89
+ "known": true
90
+ }
91
+ },
92
+ {
93
+ "wire": "priority:high",
94
+ "decoded": {
95
+ "kind": "convention",
96
+ "value": "priority:high",
97
+ "known": true
98
+ }
99
+ },
84
100
  {
85
101
  "wire": "release-hold",
86
102
  "decoded": {
package/tools/lib/git.js CHANGED
@@ -886,6 +886,10 @@ function ghRunForSha(repo, branch, limit = 10, remote = remoteInfo(repo).name ||
886
886
  * branch head.
887
887
  */
888
888
  function ghRunsForCommit(repo, branch, sha, limit = 10) {
889
+ // #529: every row filter below is strict equality against a 40-hex head_sha. An abbreviated sha
890
+ // would filter to [] — read by every caller as "no runs yet" — so resolve it, and when it cannot
891
+ // be resolved answer null ("the read failed"), never an empty set.
892
+ sha = fullSha(repo, sha);
889
893
  if (!sha) return null;
890
894
 
891
895
  // #495: one REST call (`actions/runs?head_sha=&branch=`) instead of `gh run list`'s two (runs +
@@ -940,12 +944,29 @@ function ghApiConditional(repo, apiPath, etag) {
940
944
  return ciWait.classifyResponse({ ...http, stderr: r.stderr });
941
945
  }
942
946
 
947
+ /**
948
+ * #529: `sha` as the full 40-hex object name the Actions API reports as `head_sha`, or null. A
949
+ * 40-hex value passes through (lowercased) without a local lookup — the commit may exist only on
950
+ * the remote. Anything shorter is resolved with `git rev-parse --verify <sha>^{commit}` in `repo`;
951
+ * unresolvable (unknown here, or ambiguous) is null. Never a prefix match: a short sha can be
952
+ * ambiguous across runs, and a match against the wrong run is worse than a refusal.
953
+ */
954
+ function fullSha(repo, sha) {
955
+ const s = String(sha || '').trim();
956
+ if (/^[0-9a-f]{40}$/i.test(s)) return s.toLowerCase();
957
+ if (!/^[0-9a-f]{4,39}$/i.test(s)) return null;
958
+ const r = git(['rev-parse', '--verify', '--quiet', `${s}^{commit}`], repo);
959
+ const out = r.ok ? r.stdout.trim() : '';
960
+ return /^[0-9a-f]{40}$/.test(out) ? out : null;
961
+ }
962
+
943
963
  /**
944
964
  * Every workflow run at `sha` in ONE REST call (#495) — `actions/runs?head_sha=<sha>[&branch=<b>]`,
945
965
  * rows in `gh run list --json` shape. Returns `{ rows }` on success, `{ rateLimited: true }` on a
946
966
  * rate limit, `{}` on any other failure (the caller decides whether to fall back).
947
967
  */
948
968
  function ghRunsAtShaRest(repo, sha, branch) {
969
+ sha = fullSha(repo, sha); // #529: the API's head_sha is 40-hex; an abbreviated one matches no row
949
970
  if (!sha) return {};
950
971
  const ciWait = require('./ci-wait');
951
972
  const q = `head_sha=${encodeURIComponent(sha)}${branch ? `&branch=${encodeURIComponent(branch)}` : ''}&per_page=100`;
@@ -1311,7 +1332,7 @@ module.exports = {
1311
1332
  claimRemote, remoteHeads,
1312
1333
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1313
1334
  dirtyTracked, dirtyUntracked, dirtyAny,
1314
- ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
1335
+ ghAvailable, ghState, ghInstalled, ghApiConditional, ghRunsAtShaRest, fullSha, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
1315
1336
  ghCurrentLogin, ghIssueView, ghIssueComment, ghRunForSha, ghRunForCommit, ghRunsForCommit, ghRunsForRef, ghRunsAtCommit, ghRunForCommitAnyRef, commitTimeMs, ghRunsSince, summarizeRunsForCommit, isRepoOwnedRun,
1316
1337
  ghRunJobCount, ghRunJobs, ghWorkflowDispatch,
1317
1338
  ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
@@ -81,6 +81,18 @@ function excludeLines(env = process.env) {
81
81
  return out;
82
82
  }
83
83
 
84
+ /**
85
+ * #527: the root-anchored exclude line for the worktree subdir (`colab worktree new` creates
86
+ * worktrees INSIDE the clone, `.worktrees/` by default), or null when the configured subdir is
87
+ * absolute or climbs out of the repo. Deliberately NOT part of `excludeLines`: those are scratch
88
+ * (disposable, filtered out of the uncommitted-work gate by `isScratchPath`); a worktree is live
89
+ * work and must never be filtered — it only has to stay out of the main checkout's `git status`,
90
+ * where one habitual `git add -A` would otherwise commit it as an embedded-repo gitlink.
91
+ */
92
+ function worktreeExcludeLine(worktreeSubdir) {
93
+ return anchoredLine(normalise(worktreeSubdir, '.worktrees'));
94
+ }
95
+
84
96
  /**
85
97
  * Is a repo-relative path (as `git status --porcelain` prints it) inside a scratch dir? Used to
86
98
  * keep scratch out of the uncommitted-work gate: a plan or brief left in a worktree is disposable
@@ -102,5 +114,5 @@ function withoutScratch(porcelainText, env = process.env) {
102
114
  module.exports = {
103
115
  DEFAULT_PLANS_DIR, DEFAULT_BRIEFS_DIR, LEGACY_PLANS_DIR, LEGACY_BRIEFS_DIR,
104
116
  plansDirSetting, briefsDirSetting, planWriteDir, briefsWriteDir, planReadDirs,
105
- excludeLines, isScratchPath, withoutScratch,
117
+ excludeLines, worktreeExcludeLine, isScratchPath, withoutScratch,
106
118
  };
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+ /**
3
+ * #525 — the human door on `colab ship`'s autonomy gate.
4
+ *
5
+ * Without `autonomy: auto-trunk` the gate used to have two answers: docs-only (#345) or refuse.
6
+ * The refusal said "a human must trigger Phase B", but refused that human too, so on the default
7
+ * (`manual`) repo the person meant to give the go had no tool to give it with. Ruling on #525
8
+ * (option 1): a person running `colab ship` IS the go, measured on the bar the CLI already applies
9
+ * to human-only acts (`colab adopt --autonomy`, `colab release finalize`):
10
+ *
11
+ * - an interactive terminal (stdin AND stdout a TTY) outside an agent shell, confirmed by typing
12
+ * at the prompt — `how: 'tty'`; or
13
+ * - `COLAB_HUMAN=1` AND `--answered-by <name>` — `how: 'colab-human'`.
14
+ *
15
+ * An agent never passes on its own: an agent shell (`CLAUDECODE=1` / `AI_AGENT`, the signals
16
+ * `lib/place.js` already reads) does not count as a terminal, and setting `COLAB_HUMAN=1` is
17
+ * governed by the handbook's existing rule — never on the agent's own say-so.
18
+ *
19
+ * Pure: every input is passed in, so the TTY branch is unit-testable without a pty.
20
+ */
21
+
22
+ /** Is this process running inside an agent's shell? Same signals as lib/place.js rule 3. */
23
+ function isAgentShell(env) {
24
+ return env.CLAUDECODE === '1' || !!env.AI_AGENT;
25
+ }
26
+
27
+ /**
28
+ * @returns {{ open: boolean, how: 'tty'|'colab-human'|null, why: string }}
29
+ */
30
+ function humanDoorVerdict({ isTTY, colabHuman, answeredBy, agentShell }) {
31
+ if (colabHuman && answeredBy) {
32
+ return { open: true, how: 'colab-human', why: `COLAB_HUMAN=1, answered by ${answeredBy}` };
33
+ }
34
+ if (colabHuman && !answeredBy) {
35
+ return { open: false, how: null, why: 'COLAB_HUMAN=1 also needs --answered-by "<name>"' };
36
+ }
37
+ if (isTTY && !agentShell) {
38
+ return { open: true, how: 'tty', why: 'a person at an interactive terminal' };
39
+ }
40
+ if (isTTY && agentShell) {
41
+ return { open: false, how: null, why: 'an agent shell is not a person at a terminal' };
42
+ }
43
+ return { open: false, how: null, why: 'unattended (no interactive terminal, no COLAB_HUMAN=1)' };
44
+ }
45
+
46
+ /** Read the door's inputs from a real process. */
47
+ function humanDoorFromProcess(proc, answeredBy) {
48
+ return humanDoorVerdict({
49
+ isTTY: !!(proc.stdin.isTTY && proc.stdout.isTTY),
50
+ colabHuman: proc.env.COLAB_HUMAN === '1',
51
+ answeredBy: answeredBy || null,
52
+ agentShell: isAgentShell(proc.env),
53
+ });
54
+ }
55
+
56
+ /**
57
+ * The exact commands a human runs, for the refusal. `target` is the ship selector the caller
58
+ * used (`--worktree x`, `--branch y`, `--direct`), so the line can be pasted as it stands.
59
+ */
60
+ function humanDoorCommands(selector) {
61
+ const sel = selector ? ` ${selector}` : '';
62
+ return [
63
+ `at your own terminal: colab ship${sel} (asks you to confirm)`,
64
+ `or, non-interactive: COLAB_HUMAN=1 colab ship${sel} --answered-by "<your name>"`,
65
+ ];
66
+ }
67
+
68
+ /** The clause the 🚢 / ✅ evidence comment carries when the human door opened the gate. */
69
+ function humanDoorEvidence(door) {
70
+ if (!door || !door.open) return '';
71
+ return door.how === 'tty'
72
+ ? ' · merged through the human door (#525): a person confirmed at an interactive terminal'
73
+ : ` · merged through the human door (#525): ${door.why}`;
74
+ }
75
+
76
+ module.exports = { isAgentShell, humanDoorVerdict, humanDoorFromProcess, humanDoorCommands, humanDoorEvidence };
@@ -190,10 +190,21 @@ function bodyShaClaims(message) {
190
190
  * an issue that carries no delivery-type label is still covered.
191
191
  */
192
192
  const TOOL_MARKS = ['🔒 Claimed', '✅ Released', '🚢 Shipped', '🔖 Referenced', '↩️ Sent back'];
193
+ /**
194
+ * #535: a comment whose WHOLE body is one signature line (`— <name> · <machine>/<session>`) is
195
+ * not evidence either. Some deployments post one after every comment; it records who spoke, never
196
+ * what was delivered. Only the bare line is excluded — a distill that merely ENDS in a signature
197
+ * still counts, so the test is on the whole trimmed body, single line, no `m` flag.
198
+ */
199
+ const SIGNATURE_ONLY = /^—[^\S\n][^\n]*\S$/;
200
+ function isSignatureOnly(body) {
201
+ return SIGNATURE_ONLY.test(body);
202
+ }
193
203
  function evidenceComments(comments) {
194
204
  return (Array.isArray(comments) ? comments : []).filter((c) => {
195
205
  const body = String((c && c.body) || '').trim();
196
206
  if (!body) return false;
207
+ if (isSignatureOnly(body)) return false;
197
208
  return !TOOL_MARKS.some((mark) => body.startsWith(mark));
198
209
  });
199
210
  }
@@ -312,6 +323,6 @@ function zeroClaimVerdict(issuesCount, branchName, brokenClaimsCount, { remoteOn
312
323
 
313
324
  module.exports = {
314
325
  branchIssueNumbers, commitIssueNumbers, corroborateIssues, branchType,
315
- subjectSanity, bodyShaClaims, evidenceComments, hasEvidence, TOOL_MARKS,
326
+ subjectSanity, bodyShaClaims, evidenceComments, hasEvidence, isSignatureOnly, TOOL_MARKS,
316
327
  closesCoverage, zeroClaimVerdict,
317
328
  };