@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +312 -3
  3. package/README.vi.md +281 -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 +13806 -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 +278 -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-endpoint.js +170 -0
  63. package/tools/lib/notify.js +188 -0
  64. package/tools/lib/npm-publish-guard.js +242 -0
  65. package/tools/lib/orphan-worktree.js +127 -0
  66. package/tools/lib/owner-branch.js +182 -0
  67. package/tools/lib/place.js +782 -0
  68. package/tools/lib/ports.js +167 -0
  69. package/tools/lib/procs.js +185 -0
  70. package/tools/lib/readiness.js +240 -0
  71. package/tools/lib/records.js +185 -0
  72. package/tools/lib/refs-brake.js +95 -0
  73. package/tools/lib/release-channel.js +99 -0
  74. package/tools/lib/release-cut.js +822 -0
  75. package/tools/lib/release-finalize.js +521 -0
  76. package/tools/lib/release-policy.js +358 -0
  77. package/tools/lib/release-tag.js +225 -0
  78. package/tools/lib/ship-batch.js +277 -0
  79. package/tools/lib/ship-roles.js +71 -0
  80. package/tools/lib/ship-target-sync.js +181 -0
  81. package/tools/lib/shipguard.js +317 -0
  82. package/tools/lib/shipped-branch.js +56 -0
  83. package/tools/lib/solo.js +213 -0
  84. package/tools/lib/squash.js +515 -0
  85. package/tools/lib/stale-base.js +70 -0
  86. package/tools/lib/stamp.js +740 -0
  87. package/tools/lib/state.js +262 -0
  88. package/tools/lib/teardown.js +83 -0
  89. package/tools/lib/trust-humans.js +104 -0
  90. package/tools/lib/util.js +98 -0
  91. package/tools/lib/wake.js +188 -0
  92. package/tools/lib/workflow-triggers.js +273 -0
  93. package/tools/lib/writes-authority.js +237 -0
  94. package/tools/lib/yaml.js +101 -0
  95. package/bin/cli.js +0 -3
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/axis-authority.js — the precedence ladder behind #144's authority flip.
4
+ *
5
+ * Before this unit, `tier` alone counted the gates between a merge and users. `exposure`
6
+ * (#132) landed as a strictly additive, optional key answering the same question in a
7
+ * strictly more precise vocabulary — but `tier` stayed authoritative, on purpose, until this
8
+ * unit existed to cut the weld safely. This module IS that cut: given a parsed
9
+ * `.github/project.yml`, it says which key is the axis of record for gate count, and what
10
+ * exposure value that resolves to.
11
+ *
12
+ * `tier -> exposure` is a FUNCTION, not a BIJECTION. `A -> released` holds; `released -> A`
13
+ * does not, because `released` covers two legal shapes — a tag deploying to a live server
14
+ * (the historical `tier: A` shape), and adopters copying files out of a tag with no server at
15
+ * all (this handbook's own shape: `tier: B`, `exposure: released`, `production: null`). A
16
+ * descriptor that answers with `exposure` is therefore answering a STRICTLY MORE PRECISE
17
+ * question than one that only ever answered with `tier`, which is why the ladder below trusts
18
+ * `exposure` first and reads `tier` only when nothing more precise is on record.
19
+ *
20
+ * CommonJS, matching stamp.js: `audit/audit.mjs` (ESM) consumes this through `createRequire`,
21
+ * exactly as it already does for stamp.js and labels.js; `tools/colab` (CJS) can `require` it
22
+ * directly. One implementation, not two, for the identical reason stamp reading lives in one
23
+ * place — two readings of "which axis governs" disagreeing is the two-places-drift disease
24
+ * this handbook exists to kill.
25
+ */
26
+
27
+ // The one exposure value each LEGACY tier maps to, when no `exposure` key is present at all.
28
+ // `B -> null` is the load-bearing entry, not an oversight: a bare `tier: B` descriptor carries
29
+ // no derivable opinion about what consumes it. `none`, `self` and `released` are all measured
30
+ // under `B` in this very fleet (the 5-5 split #144's plan cites, plus this repo's own shape),
31
+ // so nothing here may GUESS which one a bare `B` means — that guess is exactly the naive flip
32
+ // this module exists to avoid writing. The `null` is the code-level reason phase 3 of the epic
33
+ // (ten repos answering the exposure question by hand) still has to happen: it is what a lossy
34
+ // legacy read looks like, in the type system, for the one tier where the mapping is genuinely
35
+ // unknown rather than merely unwritten.
36
+ const LEGACY = Object.freeze({ A: 'released', C: 'live', B: null });
37
+
38
+ // The one exposure value each tier is CONSISTENT with, used only when both keys are declared
39
+ // and might disagree. `B` is deliberately absent: per LEGACY.B above, `tier: B` carries no
40
+ // opinion, so no exposure value declared alongside it can ever contradict it — `tier: B` +
41
+ // `exposure: live` is `B` contradicting nothing, not `B` agreeing with `live`.
42
+ const CONSISTENT_WITH = Object.freeze({ A: 'released', C: 'live' });
43
+
44
+ // Gate count a resolved exposure value implies — additive `--json` reporting only in this
45
+ // unit (#144's oracle: "`--json`: `tier` continues to report the DECLARED letter... New keys
46
+ // are additive"). `self` is 0, the same as `none`: both describe a consumer set with no
47
+ // external gate to guard, `self` merely a non-empty one bounded by the room.
48
+ const GATE_COUNT = Object.freeze({ none: 0, self: 0, live: 1, released: 2 });
49
+
50
+ /**
51
+ * Which key is the axis of record for `cfg` (a parsed `.github/project.yml`, possibly
52
+ * null/undefined for an unparseable or missing file — treated the same as an empty object),
53
+ * and what exposure value it resolves to. Returns exactly one of:
54
+ *
55
+ * { source: 'exposure', tier, exposure } — `exposure` was declared; it wins outright,
56
+ * `tier` (declared or not) is carried through
57
+ * unread by this function's own logic.
58
+ * { source: 'tier-legacy', tier, exposure } — only `tier` was declared; `exposure` is
59
+ * DERIVED via LEGACY (`null` for `tier: B`).
60
+ * { source: 'none', tier: null, exposure: null } — neither key was declared: no
61
+ * axis of record at all.
62
+ */
63
+ function axisOfRecord(cfg) {
64
+ const c = cfg || {};
65
+ const hasExposure = 'exposure' in c && c.exposure !== null && c.exposure !== undefined;
66
+ const hasTier = 'tier' in c && c.tier !== null && c.tier !== undefined;
67
+ if (hasExposure) {
68
+ return { source: 'exposure', tier: hasTier ? c.tier : null, exposure: c.exposure };
69
+ }
70
+ if (hasTier) {
71
+ const exposure = Object.prototype.hasOwnProperty.call(LEGACY, c.tier) ? LEGACY[c.tier] : null;
72
+ return { source: 'tier-legacy', tier: c.tier, exposure };
73
+ }
74
+ return { source: 'none', tier: null, exposure: null };
75
+ }
76
+
77
+ /**
78
+ * When BOTH `tier` and `exposure` are declared, do they disagree about gate count? Returns a
79
+ * finding string — the one disagreement `fail` #144's plan calls for — or `null` when they
80
+ * agree, INCLUDING every `tier: B` pairing (see CONSISTENT_WITH above: `B` contradicts
81
+ * nothing). Silent, not merely non-failing, on an invalid `tier` — the enum check elsewhere
82
+ * already reports that; this function only ever compares two values it can compare.
83
+ */
84
+ function contradiction(tier, exposure) {
85
+ if (!tier || !exposure) return null;
86
+ if (!(tier in CONSISTENT_WITH)) return null; // tier B (contradicts nothing) or an invalid tier
87
+ const want = CONSISTENT_WITH[tier];
88
+ if (want === exposure) return null;
89
+ return (
90
+ `tier: ${tier} and exposure: ${exposure} disagree about how many gates stand between a ` +
91
+ `merge and users — tier ${tier} means exposure: ${want}. Fix whichever is stale, or drop ` +
92
+ `it: exposure is now the axis of record (CONVENTIONS.md §2)`
93
+ );
94
+ }
95
+
96
+ module.exports = { LEGACY, CONSISTENT_WITH, GATE_COUNT, axisOfRecord, contradiction };
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+ /**
3
+ * "Was the sha this branch was CUT FROM actually green?" (#293).
4
+ *
5
+ * `colab ship`'s trunk-CI-green precondition (tools/lib/ci-verdict.js, `shipCiCheck` in
6
+ * tools/colab) answers "is trunk green RIGHT NOW". It never asks whether the commit a branch was
7
+ * cut from was green AT THE TIME — and those are different questions once trunk has moved. #293's
8
+ * measured incident: three branches cut from one byte-identical RED base sha. Two drew a green run
9
+ * of their own and shipped unchallenged; one drew red and cost a coordinator a hand diagnosis. None
10
+ * of the three touched the failing harness — the differing verdicts were a flaky test on the base,
11
+ * not a property of any diff.
12
+ *
13
+ * THE DANGEROUS CASE IS THE GREEN ONE. A branch whose base was red and whose own run is green
14
+ * currently looks safest of all — a green run actively argues against looking further — so this is
15
+ * the one severity that must be flagged LOUDEST, not folded quietly into "still needs a look".
16
+ *
17
+ * PURE BY CONSTRUCTION, same posture as ci-verdict.js / ci-grant.js / migration-grant.js /
18
+ * shipguard.js: signals in, verdict out. No git, no gh, no clock — the caller (tools/colab, via
19
+ * git.js's `ghRunForCommit`/`ghRunForSha`) does every network/subprocess read and hands this module
20
+ * the two conclusions it needs. Every branch is directly reachable from `node --test`.
21
+ *
22
+ * ADVISORY, NOT A GATE. This module never says "block the merge" — it says "here is a fact a human
23
+ * or a coordinator (code-ship / colab ship's grading) should see before treating this branch's own
24
+ * green CI as sufficient evidence". Wiring it into an actual precondition that can flip `ship`'s
25
+ * exit code is a decision this module deliberately does not make; #293 only asks for VISIBILITY
26
+ * ("a coordinator does not re-derive the stale-base diagnosis by hand for every branch in a
27
+ * sweep"), not for a new refusal.
28
+ */
29
+
30
+ // Same allowlist the CI-green checks elsewhere in this toolchain use (ghRunForSha/ghRunForCommit,
31
+ // shipCiCheck): a completed run counts as GREEN only for 'success' — 'cancelled' is neutral (a
32
+ // passing sibling on the same sha is what answers the question, see git.js doc comment) and every
33
+ // other completed conclusion is red. Non-completed/absent is neither green nor red — it is simply
34
+ // not yet known, which is exactly the distinction 'unresolved' below exists to preserve.
35
+ function isGreen(status, conclusion) {
36
+ return status === 'completed' && conclusion === 'success';
37
+ }
38
+
39
+ function isMeasuredRed(status, conclusion) {
40
+ return status === 'completed' && conclusion !== 'success' && conclusion !== 'cancelled';
41
+ }
42
+
43
+ /**
44
+ * `base` / `own` are each `{status, conclusion}` — the shape `ghRunForCommit`/`ghRunForSha` return
45
+ * (a subset of it; extra fields are ignored, so a caller may pass the whole verdict object as-is).
46
+ *
47
+ * Returns `{ severity, why }`:
48
+ * - `severity: null` — nothing to flag. The base was not measurably red (green, cancelled,
49
+ * still running, or no run ever existed for it) — there is no red-base
50
+ * claim to be wrong about, so this stays silent rather than guessing.
51
+ * - `'suspect-green'` — base measurably red, branch's own head measurably GREEN. The loudest
52
+ * case: the branch's CI verdict may be inherited from the base's flake,
53
+ * not earned by this branch's own diff.
54
+ * - `'inherited-red'` — base measurably red, branch's own head ALSO measurably red. Honest —
55
+ * the branch is reporting the base's problem, not hiding it — but still
56
+ * worth naming so a human does not waste time bisecting this branch's
57
+ * diff for a failure that predates it.
58
+ * - `'unresolved'` — base measurably red, branch's own head has no completed verdict yet
59
+ * (still running, or no run at all). Neither confirms nor clears the
60
+ * suspicion; say so rather than silently waiting.
61
+ */
62
+ function classify(base, own) {
63
+ const baseStatus = base && base.status;
64
+ const baseConclusion = base && base.conclusion;
65
+ if (!isMeasuredRed(baseStatus, baseConclusion)) {
66
+ return { severity: null, why: 'base sha is not measurably red — nothing to flag' };
67
+ }
68
+
69
+ const ownStatus = own && own.status;
70
+ const ownConclusion = own && own.conclusion;
71
+
72
+ if (isGreen(ownStatus, ownConclusion)) {
73
+ return {
74
+ severity: 'suspect-green',
75
+ why: `base was red (${baseConclusion}) but this branch's own head reads green — ` +
76
+ 'that green verdict may be inherited from the base, not earned by this diff',
77
+ };
78
+ }
79
+ if (isMeasuredRed(ownStatus, ownConclusion)) {
80
+ return {
81
+ severity: 'inherited-red',
82
+ why: `base was red (${baseConclusion}) and this branch's own head is red too (${ownConclusion}) — ` +
83
+ 'may be the SAME pre-existing failure, not something this diff introduced',
84
+ };
85
+ }
86
+ return {
87
+ severity: 'unresolved',
88
+ why: `base was red (${baseConclusion}) and this branch's own head has no completed CI verdict yet ` +
89
+ `(status=${ownStatus || 'none'}) — cannot yet say whether this branch clears it`,
90
+ };
91
+ }
92
+
93
+ module.exports = { classify, isGreen, isMeasuredRed };
@@ -0,0 +1,262 @@
1
+ 'use strict';
2
+ /**
3
+ * The `blocked_by` dependency-edge verb (#251) — makes `colab` the owner of the one triage write
4
+ * that was still hand-rolled `gh api`, and the one with two independent SILENT-failure modes,
5
+ * both measured live on this repo:
6
+ *
7
+ * 1. WRONG ID ATTACHES A STRANGER'S ISSUE. The REST endpoint's payload is a global DATABASE id,
8
+ * not the issue number a human types. An empty variable, a failed subshell, or the issue
9
+ * *number* pasted where the id goes is still a valid integer — the POST returns 200 and
10
+ * attaches whichever issue holds that id anywhere on GitHub (measured: `issue_id=34`
11
+ * attached a blocker from an unrelated repo — CONVENTIONS.md, dependency graph section). At
12
+ * the moment of the write, a wrong id is indistinguishable from success.
13
+ * 2. THE READ-BEFORE-WRITE GUARD IS EASY TO WRITE WRONG. `blockedBy` is a connection object
14
+ * (`{nodes, totalCount}`), not an array — `| length` returns 2 for an issue with ZERO
15
+ * blockers, so a guard written that way concludes "already present" forever and never writes
16
+ * the edge (#250, measured live 2026-08-21).
17
+ *
18
+ * This module owns the JUDGEMENT (arg validity, edge-shape normalisation, presence, the resolved
19
+ * blocker's usability, the read-back verdict, the `--clear` guard). `tools/colab`'s cmdBlocked /
20
+ * cmdBlockedClear own the gh I/O and printing only — the same split `decision-record.js` /
21
+ * `readiness.js` keep from their own `tools/colab` callers.
22
+ *
23
+ * PURE BY CONSTRUCTION: signals in, verdict out. No git, no network, no `gh`, no `fs`. That is
24
+ * what lets `#250`'s exact trap be pinned by a three-line unit test instead of a subprocess
25
+ * fixture, and what lets a vendored reader reach the same verdicts from facts it collected its
26
+ * own way (same posture as readiness.js / decision-record.js / migration-grant.js).
27
+ *
28
+ * WHY NUMBERS ONLY, NEVER IDS, AT THIS MODULE'S BOUNDARY. Failure mode 1 exists because a
29
+ * database id looks exactly like any other integer. Every public function here takes issue
30
+ * NUMBERS (and normalised edge records already carrying a verified id) — never a bare id a
31
+ * caller could have gotten from anywhere. The one place a database id enters this module's view
32
+ * is inside a record `resolvedBlockerProblem` has already validated against the number that was
33
+ * asked for.
34
+ *
35
+ * WHY CROSS-REPO IS OUT OF SCOPE HERE, STRUCTURALLY, NOT BY A CHECK. The blocker is always
36
+ * resolved through `gh api repos/{owner}/{repo}/issues/<M>` — `{owner}/{repo}` is `gh`'s own
37
+ * placeholder for the CURRENT repo, so a foreign blocker can never enter through that call. This
38
+ * module still tracks each edge's repo (`foreignEdges`) so a caller can WARN about a foreign edge
39
+ * it finds already present — one it did not write and must not report as its own failure.
40
+ */
41
+
42
+ /** repository_url -> "owner/name", or null. Both call sites this module reads from (a single
43
+ * resolved issue, and each entry of a blocked_by list) carry this field — both are REST issue
44
+ * payloads, measured live against this repo's own tracker. */
45
+ function repoSlugFromUrl(url) {
46
+ const m = /^https:\/\/api\.github\.com\/repos\/(.+)$/.exec(String(url || ''));
47
+ return m ? m[1] : null;
48
+ }
49
+
50
+ /** #388: an issue's html `url` -> "owner/name", or null. `gh issue view --json blockedBy` nodes
51
+ * carry `url` (https://<host>/<owner>/<name>/issues/<n>) and NO `repository` field — measured
52
+ * live 2026-09-27; the node keys are id/number/state/title/url. Without this fallback every real
53
+ * non-empty `gh issue view` read failed normaliseEdges, i.e. read as "unreadable". */
54
+ function repoSlugFromHtmlUrl(url) {
55
+ const m = /^https:\/\/[^/]+\/([^/]+\/[^/]+)\/(?:issues|pull)\/\d+\/?$/.exec(String(url || ''));
56
+ return m ? m[1] : null;
57
+ }
58
+
59
+ function edgeKey(e) { return `${e && e.repo}#${e && e.number}`; }
60
+
61
+ /**
62
+ * Turn a raw read into a flat `{ok, edges}` list, or `{ok:false, edges:null}` on anything that is
63
+ * not confidently a list of edges — NEVER `{ok:true, edges:[]}` on an unreadable input. A caller
64
+ * that cannot tell "confirmed empty" from "could not read" is the exact ambiguity `ghIssueView`'s
65
+ * own null-means-unreadable contract exists to prevent, reproduced one layer up.
66
+ *
67
+ * Accepts TWO shapes, on purpose:
68
+ * - the REST list this module's own callers actually use (`gh api .../dependencies/blocked_by`
69
+ * — an array of full issue objects, each carrying `id`, `number`, `state`, `repository_url`);
70
+ * - `{blockedBy:{nodes,totalCount}}` (a `gh issue view --json blockedBy` / GraphQL read), for a
71
+ * caller that already has one lying around. `.blockedBy` is read ONLY via `.nodes` — never
72
+ * `.blockedBy.length` or `blockedBy`'s own key count, which is exactly the #250 trap: a
73
+ * connection object has 2 keys regardless of how many edges it holds.
74
+ */
75
+ function normaliseEdges(raw) {
76
+ let list;
77
+ if (Array.isArray(raw)) {
78
+ list = raw;
79
+ } else if (raw && typeof raw === 'object' && raw.blockedBy && typeof raw.blockedBy === 'object') {
80
+ if (!Array.isArray(raw.blockedBy.nodes)) return { ok: false, edges: null };
81
+ list = raw.blockedBy.nodes;
82
+ } else {
83
+ return { ok: false, edges: null };
84
+ }
85
+
86
+ const edges = [];
87
+ for (const item of list) {
88
+ if (!item || typeof item !== 'object') return { ok: false, edges: null };
89
+ const number = item.number;
90
+ if (!Number.isInteger(number)) return { ok: false, edges: null };
91
+ const repo = item.repository_url
92
+ ? repoSlugFromUrl(item.repository_url)
93
+ : (item.repository && item.repository.nameWithOwner) || repoSlugFromHtmlUrl(item.url);
94
+ if (!repo) return { ok: false, edges: null };
95
+ const id = Number.isInteger(item.id) ? item.id : null;
96
+ const state = item.state != null ? String(item.state).toLowerCase() : null;
97
+ edges.push({ id, number, repo, state });
98
+ }
99
+ return { ok: true, edges };
100
+ }
101
+
102
+ /** Is `target` ({number, repo}) already among `edges`? Matches on number+repo — the id is not
103
+ * always available from every read shape (`normaliseEdges` above), so identity here is what
104
+ * every shape can supply. */
105
+ function edgePresent(edges, target) {
106
+ if (!Array.isArray(edges) || !target) return false;
107
+ return edges.some((e) => e.number === target.number && e.repo === target.repo);
108
+ }
109
+
110
+ /** Edges whose repo is NOT `thisRepo` — pre-existing foreign edges this command did not write
111
+ * and must only ever WARN about, never treat as its own failure (this module never produces
112
+ * one: the blocker is always resolved same-repo — see the file header). */
113
+ function foreignEdges(edges, thisRepo) {
114
+ if (!Array.isArray(edges)) return [];
115
+ return edges.filter((e) => e.repo && e.repo !== thisRepo);
116
+ }
117
+
118
+ /**
119
+ * #388: what a `gh issue view --json blockedBy` read says about OPEN blockers — a report, never a
120
+ * gate. `colab readiness <N>` (the deps-checked path) reads this once so its success line can say
121
+ * what the graph holds instead of asserting "no open blocker" it never checked; it does NOT refuse
122
+ * on a non-empty count (that is `--mechanical`'s job): under §5 (#279) an open edge carries the
123
+ * block by itself, and deps-checked records only that a reasoning session reviewed the deps.
124
+ *
125
+ * Returns `{ ok:false }` for an unreadable/malformed read (null means "could not read", never
126
+ * "empty" — the same contract as normaliseEdges), else
127
+ * { ok:true, total, read, open, unknownState }
128
+ * `total` is the connection's totalCount when present (falls back to the nodes read); `read` is
129
+ * how many nodes came back — fewer than `total` means the page was truncated, so `open` is a floor.
130
+ * `unknownState` counts nodes with no `state` field: they are neither open nor closed as far as
131
+ * this read can tell, and the caller must not fold them into either.
132
+ */
133
+ function openBlockerSummary(raw) {
134
+ const n = normaliseEdges(raw);
135
+ if (!n.ok) return { ok: false };
136
+ const edges = n.edges;
137
+ const tc = raw && raw.blockedBy && Number.isInteger(raw.blockedBy.totalCount) ? raw.blockedBy.totalCount : null;
138
+ const total = tc != null && tc >= edges.length ? tc : edges.length;
139
+ return {
140
+ ok: true,
141
+ total,
142
+ read: edges.length,
143
+ open: edges.filter((e) => e.state === 'open').length,
144
+ unknownState: edges.filter((e) => e.state == null).length,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Argument-level problems, checkable with NO gh call — the guard that keeps a malformed
150
+ * invocation from spending a single network round-trip before refusing.
151
+ */
152
+ function argProblem({ blocked, blocker, clear, reason, force } = {}) {
153
+ if (blocker == null) return '--by <blocker> is required';
154
+ if (blocked === blocker) return `#${blocked} cannot block itself`;
155
+ if (!clear && force) return '--force only applies together with --clear';
156
+ if (!clear && reason) return '--reason only applies together with --clear';
157
+ if (clear && (!reason || !String(reason).trim())) {
158
+ return '--clear requires --reason "<why>" — colab cannot verify intent, so it records yours '
159
+ + 'instead of guessing it (code-triage §4: delete only when the edge itself is false, '
160
+ + 'never merely because the blocker landed)';
161
+ }
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * Is the RESOLVED blocker usable as a write target? This is failure mode 1's guard: a missing or
167
+ * non-integer database id, or a resolved issue whose OWN number does not match what was asked
168
+ * for (an empty/garbled response, or a resolution that silently landed on the wrong issue),
169
+ * refuses before any POST is attempted.
170
+ */
171
+ function resolvedBlockerProblem(json, requestedNumber) {
172
+ if (!json || typeof json !== 'object') {
173
+ return `could not read blocker #${requestedNumber} from the tracker — refusing to resolve its database id blind`;
174
+ }
175
+ if (!Number.isInteger(json.id) || json.id <= 0) {
176
+ return `blocker #${requestedNumber} resolved with no usable database id (got ${JSON.stringify(json.id)}) — refusing a write built on an unverified id`;
177
+ }
178
+ if (json.number !== requestedNumber) {
179
+ return `resolved issue is #${json.number}, not the requested #${requestedNumber} — refusing a write that could attach a stranger's issue (the exact hazard this verb exists to close)`;
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /** The four ADD-path verdicts, in the order a caller should check for them. */
185
+ const ADD_CONFIRMED = 'confirmed'; // read-back shows exactly the intended edge added
186
+ const ADD_WRONG = 'wrong'; // read-back shows a DIFFERENT edge added — WRONG BLOCKER
187
+ const ADD_MISSING = 'missing'; // POST reported success, but nothing new reads back
188
+ const ADD_UNCONFIRMED = 'unconfirmed'; // the read-back itself could not be completed
189
+
190
+ /**
191
+ * The read-back verdict for an ADD: `before`/`after` are normalised edge lists (from the SAME
192
+ * blocked issue, read before and after the POST), `target` is `{number, repo}` for the blocker
193
+ * that was just written. `after === null` means the read-back call itself failed — that is
194
+ * `unconfirmed`, and is a DIFFERENT thing from "read fine, edge absent" (`missing`).
195
+ *
196
+ * The comparison is `added = after \ before`, never `after` alone — an issue may already carry
197
+ * unrelated blockers, and none of those are this write's business to judge.
198
+ */
199
+ function confirmVerdict(before, after, target) {
200
+ if (after === null || after === undefined) {
201
+ return { verdict: ADD_UNCONFIRMED, why: 'the read-back could not be completed', intruders: [] };
202
+ }
203
+ const beforeKeys = new Set((Array.isArray(before) ? before : []).map(edgeKey));
204
+ const added = after.filter((e) => !beforeKeys.has(edgeKey(e)));
205
+ const targetKey = edgeKey(target);
206
+ const intruders = added.filter((e) => edgeKey(e) !== targetKey);
207
+ const gotTarget = added.some((e) => edgeKey(e) === targetKey);
208
+
209
+ if (intruders.length) {
210
+ return {
211
+ verdict: ADD_WRONG,
212
+ why: `the read-back shows #${target && target.number} newly blocked by `
213
+ + `${intruders.map((e) => `${e.repo}#${e.number}`).join(', ')}, not the requested ${targetKey}`,
214
+ intruders,
215
+ };
216
+ }
217
+ if (gotTarget) {
218
+ return { verdict: ADD_CONFIRMED, why: `#${target && target.number} is now confirmed blocked by ${targetKey}`, intruders: [] };
219
+ }
220
+ return { verdict: ADD_MISSING, why: 'the POST reported success but the edge is not present on read-back', intruders: [] };
221
+ }
222
+
223
+ /**
224
+ * The `--clear` guard (code-triage §4): "remove an edge only when the edge is false — not
225
+ * because the blocker moved." `colab` cannot read intent, so it encodes only the one detectable
226
+ * SIGNATURE of the exact mistake §4 names — deleting an edge because the blocker CLOSED — and
227
+ * refuses on it by default. `--force` releases only this guard; it never touches the read-back.
228
+ *
229
+ * A closed blocker is neither necessary nor sufficient for the edge being false; it is the
230
+ * correlate of the wrong reason, and that is enough to be worth a speed bump before a
231
+ * destructive write.
232
+ */
233
+ function clearProblem({ closed, force } = {}) {
234
+ if (closed && !force) {
235
+ return 'the blocker is CLOSED — a closed blocker is not proof the edge is false (its code may '
236
+ + 'simply have landed; the dependency and the edge both survive that — code-triage §4). '
237
+ + 'Refusing --clear without --force.';
238
+ }
239
+ return null;
240
+ }
241
+
242
+ /** Stable wire format for the `--clear` receipt comment — mirrors CLAIM_MARK / DECISION_MARK's
243
+ * shape in tools/colab / decision-record.js. Posted ONCE per actual deletion (never on an
244
+ * already-absent edge), because the write records itself in `blockedBy` and the timeline
245
+ * forever, while a delete leaves only a `blocked_by_removed` event with no WHY attached — this
246
+ * comment is that why. */
247
+ const REMOVAL_MARK = '🗑 Dependency edge cleared';
248
+ const REMOVAL_RE = /^🗑 Dependency edge cleared — blocked-by `(\d+)` · host `([^`]*)` · (\S+)/;
249
+
250
+ function removalReceiptBody(blockerNumber, host, iso, reason) {
251
+ const head = `${REMOVAL_MARK} — blocked-by \`${blockerNumber}\` · host \`${host}\` · ${iso}`;
252
+ return `${head}\n\n${reason}`;
253
+ }
254
+
255
+ module.exports = {
256
+ normaliseEdges, edgePresent, foreignEdges, openBlockerSummary,
257
+ argProblem, resolvedBlockerProblem, clearProblem,
258
+ confirmVerdict, ADD_CONFIRMED, ADD_WRONG, ADD_MISSING, ADD_UNCONFIRMED,
259
+ removalReceiptBody, REMOVAL_MARK, REMOVAL_RE,
260
+ // exported for tests / a caller building its own target key consistently
261
+ edgeKey, repoSlugFromUrl, repoSlugFromHtmlUrl,
262
+ };
@@ -0,0 +1,137 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The session-branch NAME, per CONVENTIONS.md §4 — the one place its shape is defined (#348).
5
+ *
6
+ * Two shapes, both conforming:
7
+ *
8
+ * <type>/<slug>-<N…> the original shape, and still the default
9
+ * <login>/<machine>/<type>/<slug>-<N…> the machine-carried shape, emitted once a repo declares
10
+ * `branchPrefix: machine` in .github/project.yml
11
+ *
12
+ * The prefix is what makes a branch pushed to origin read as ONE MACHINE's work claim: the forge
13
+ * account that holds it and the machine it was cut on, readable by any other machine from the ref
14
+ * alone. The issue numbers stay in the TRAILING `-<N>` run in both shapes, so every reader that
15
+ * anchors at the end of the name (ship's harvest, the remote-claim check, the skills' `(-[0-9]+)+$`)
16
+ * reads either shape without knowing the prefix exists.
17
+ *
18
+ * The shapes cannot be confused: the unprefixed slug class has no `/`, so a name with four
19
+ * `/`-separated segments can only be the prefixed shape, and a name with two only the original one.
20
+ * `test/box/feat/x-1` is login `test`, machine `box`, type `feat` — never type `test`.
21
+ *
22
+ * Pure: no git, no network. `machineLabel` reads nothing — the caller hands it the hostname.
23
+ */
24
+
25
+ const { canonHost } = require('./machine.js');
26
+
27
+ const TYPES = ['feat', 'fix', 'docs', 'chore', 'refactor', 'test', 'perf', 'design'];
28
+
29
+ // Kept as a SOURCE STRING, not only a RegExp, because it is shared verbatim with places that cannot
30
+ // `require` this file — CONVENTIONS.md §4 prints it, and templates/branch-name.yml runs it in bash.
31
+ // branch-name.test.js asserts both copies are byte-identical to this one.
32
+ const BRANCH_RE_SOURCE =
33
+ '^([a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*/)?(feat|fix|docs|chore|refactor|test|perf|design)/[a-z0-9._-]+$';
34
+ const BRANCH_RE = new RegExp(BRANCH_RE_SOURCE);
35
+
36
+ // One prefix segment (a login or a machine label): same class the regex's prefix group uses.
37
+ const SEGMENT_RE = /^[a-z0-9][a-z0-9-]*$/;
38
+
39
+ /**
40
+ * Issue numbers a branch NAME claims: the numbers live in one trailing run.
41
+ *
42
+ * Anchored to the trailing run deliberately — a naive sweep for every `\d+` reads
43
+ * `feat/oauth2-login-88` as issues 2 and 88, and an invented issue number is exactly the class of
44
+ * error this exists to prevent. `fix/import-fixes-115-114-113` → [115, 114, 113], and the prefixed
45
+ * `ada/box-a/fix/import-fixes-115-114-113` → the same, because the prefix is at the other end.
46
+ *
47
+ * Returns [] for a branch that carries no trailing number group. That is not an error: plenty of
48
+ * legitimate branches predate the rule (§4 grandfathers them), so callers must treat [] as "this
49
+ * source has nothing to say", never as "this branch claims no issues".
50
+ */
51
+ function branchIssueNumbers(branchName) {
52
+ const m = /-(\d+(?:-\d+)*)$/.exec(String(branchName || ''));
53
+ if (!m) return [];
54
+ return m[1].split('-').map(Number).filter((n) => Number.isInteger(n) && n > 0);
55
+ }
56
+
57
+ /**
58
+ * A §4-conforming name → `{ login, machine, type, rest, slug, issues, prefixed }`, or `null` when the
59
+ * name conforms to neither shape. `rest` is `<slug>-<N…>` (everything after the type); `slug` is
60
+ * `rest` minus its trailing issue run. `login`/`machine` are `null` on the unprefixed shape.
61
+ */
62
+ function parse(name) {
63
+ const s = String(name || '');
64
+ if (!BRANCH_RE.test(s)) return null;
65
+ const parts = s.split('/');
66
+ const prefixed = parts.length === 4;
67
+ const [login, machine] = prefixed ? parts.slice(0, 2) : [null, null];
68
+ const type = prefixed ? parts[2] : parts[0];
69
+ const rest = parts[parts.length - 1];
70
+ const slug = rest.replace(/-\d+(?:-\d+)*$/, '');
71
+ return { login, machine, type, rest, slug, issues: branchIssueNumbers(s), prefixed };
72
+ }
73
+
74
+ /** The inverse of `parse`: `{ login?, machine?, type, rest }` → a branch name. */
75
+ function format({ login, machine, type, rest }) {
76
+ const base = `${type}/${rest}`;
77
+ return login && machine ? `${login}/${machine}/${base}` : base;
78
+ }
79
+
80
+ /**
81
+ * The machine segment of the prefix, from a hostname: `canonHost` (first label, lowercased), then
82
+ * every character outside `[a-z0-9-]` becomes `-`, repeats collapse, edges trim. `Box_A.local` →
83
+ * `box-a`. A LABEL, not an identity: two machines with the same canonical hostname share it. Claim
84
+ * comparisons stay on the hardware digest (lib/machine.js) — never on this.
85
+ */
86
+ function machineLabel(host) {
87
+ return canonHost(host).replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
88
+ }
89
+
90
+ /**
91
+ * The branch `colab worktree new` should create, given what the caller passed and whether the repo
92
+ * adopted the prefix. Returns `{ branch }` or `{ error }` (a sentence for the operator).
93
+ *
94
+ * - not adopted → the name as given, unchanged (any shape — the unprefixed default stays legal).
95
+ * - adopted, already prefixed → accepted only if the prefix names THIS login (when known) and THIS
96
+ * machine label; a prefix naming another machine would plant a claim record in its name.
97
+ * - adopted, unprefixed → `<login>/<machine>/` prepended. No resolvable login → error: the operator
98
+ * may spell the full prefixed name instead, which needs no network (#325: a tracker outage never
99
+ * blocks a claim).
100
+ */
101
+ function sessionBranch(name, { adopted, login, machine }) {
102
+ if (!adopted) return { branch: name };
103
+ const p = parse(name);
104
+ if (!p) {
105
+ return { error: `"${name}" does not match CONVENTIONS.md §4 (${BRANCH_RE_SOURCE}) — this repo declares branchPrefix: machine, so the name is checked before anything is created` };
106
+ }
107
+ const me = login ? String(login).toLowerCase() : '';
108
+ if (!machine || !SEGMENT_RE.test(machine)) {
109
+ return { error: `cannot derive a machine label for the branch prefix from this host's name ("${machine || ''}")` };
110
+ }
111
+ if (p.prefixed) {
112
+ if (p.machine !== machine) return { error: `"${name}" names machine "${p.machine}", but this machine's label is "${machine}" — a prefix is a claim in that machine's name` };
113
+ if (me && p.login !== me) return { error: `"${name}" names login "${p.login}", but this account is "${me}"` };
114
+ return { branch: name };
115
+ }
116
+ if (!me || !SEGMENT_RE.test(me)) {
117
+ return { error: `this repo declares branchPrefix: machine, but the forge login could not be resolved (gh api user). Pass the full name instead: <login>/${machine}/${name}` };
118
+ }
119
+ return { branch: format({ login: me, machine, type: p.type, rest: p.rest }) };
120
+ }
121
+
122
+ /**
123
+ * The default worktree directory name for a branch: `rest` for a §4 name (`feat/x-23` and
124
+ * `ada/box-a/feat/x-23` both → `x-23`), else everything after the first `/` — the rule that
125
+ * predates this module, kept for grandfathered names.
126
+ */
127
+ function worktreeName(branch) {
128
+ const p = parse(branch);
129
+ if (p) return p.rest;
130
+ const s = String(branch || '');
131
+ return s.includes('/') ? s.slice(s.indexOf('/') + 1) : s;
132
+ }
133
+
134
+ module.exports = {
135
+ TYPES, BRANCH_RE_SOURCE, BRANCH_RE,
136
+ branchIssueNumbers, parse, format, machineLabel, sessionBranch, worktreeName,
137
+ };