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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13785 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +481 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+ /**
3
+ * Write-time validation for the fields of ~/.colab/state.json that other commands later RESOLVE
4
+ * AGAINST GIT: a worktree's `branch` and `path`, and a claim's `branch`.
5
+ *
6
+ * WHY THIS MODULE EXISTS. A worktree/claim pair was once found recorded as
7
+ * `{"branch": "trunk", "path": null}`. The real branch existed and was healthy; only the record was
8
+ * wrong — and it failed silently in three places at once: `landed` could not resolve the ref and
9
+ * answered `unknown`, `doctor` did not classify it as drift (a null path is not a *missing*
10
+ * directory), and `ship` matched claims to the branch BY NAME, found none, and merged with no
11
+ * `Closes #N` — the failure CONVENTIONS.md §4 measured at 26/30 issues, reached by a path nothing
12
+ * checked.
13
+ *
14
+ * THE TRIGGER WAS NOT EXOTIC. `colab claim <N> --worktree <name>` — the first command in code-start —
15
+ * defaulted `--branch` to the literal string `trunk` and stubbed the not-yet-created worktree with
16
+ * `path: null`. `trunk` is a ROLE (the branch sessions merge into: `main` or `dev`), never a branch
17
+ * name; the conventions forbid creating one so named. It was being used as a SENTINEL for "no
18
+ * branch — working on the trunk checkout", stored in the same value space as real branch names, and
19
+ * every consumer read it as a name.
20
+ *
21
+ * So the absence of a branch is now `null`. Null is not a name: nothing can try to resolve it and
22
+ * quietly get a wrong answer, and a `null` branch cannot match a real one in `ship`'s claim lookup.
23
+ *
24
+ * ONLY NEW PROBLEMS ARE REFUSED. Records already on disk in the bad shape must not turn every later
25
+ * `colab` invocation into a crash — that state is precisely what a person runs `colab doctor` to
26
+ * find out about. So this refuses the write that INTRODUCES a problem and passes through one a
27
+ * record already carried, which is what keeps `doctor`'s own writes (flipping a status, repairing a
28
+ * path) working on the very records it exists to fix.
29
+ */
30
+
31
+ /**
32
+ * Words that name a ROLE rather than a branch. `main` and `dev` are absent on purpose: those are
33
+ * real branch names that a record SHOULD hold. `trunk` never is — it is the word for "whichever of
34
+ * those this repo merges into", and a repo's `project.yml` says which.
35
+ */
36
+ const ROLE_WORDS = new Set(['trunk']);
37
+
38
+ /**
39
+ * The one status a worktree record may carry with no path: a stub written by `colab claim
40
+ * --worktree <name>` for a worktree that does not exist yet. It exists so the claim is not read as
41
+ * an orphan (doctor prunes claims whose worktree is not in state); `colab worktree new` replaces it
42
+ * with the real record. Every other status asserts a directory on disk.
43
+ */
44
+ const PENDING = 'pending';
45
+
46
+ function statusOf(rec) { return (rec && rec.status) || 'running'; }
47
+
48
+ /** Problem with a branch VALUE, or null. `null`/absent is legitimate and means "no branch". */
49
+ function branchProblem(branch) {
50
+ if (branch === null || branch === undefined) return null;
51
+ if (typeof branch !== 'string') return `branch must be a string or null (got ${typeof branch})`;
52
+ const b = branch.trim();
53
+ if (!b) return 'branch is an empty string — write null for "no branch", never ""';
54
+ if (ROLE_WORDS.has(b.toLowerCase())) {
55
+ return `"${branch}" is a ROLE, not a branch name (CONVENTIONS.md §4) — it resolves to no ref, ` +
56
+ 'so `landed` cannot classify it and `ship` matches no claims. Use null for "no branch".';
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /** Problem with a worktree record's `path`/`status` pairing, or null. */
62
+ function pathProblem(rec) {
63
+ const status = statusOf(rec);
64
+ if (rec.path === null || rec.path === undefined) {
65
+ if (status === PENDING) return null;
66
+ return `path is null while status is "${status}" — only a ${PENDING} claim stub may claim no ` +
67
+ 'directory. A record nothing can act on should not be writable.';
68
+ }
69
+ if (typeof rec.path !== 'string' || !rec.path.trim()) {
70
+ return `path must be a non-empty absolute path (got ${JSON.stringify(rec.path)})`;
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * Every problem a worktree record currently has, as {code, message}. The CODE is what the guard
77
+ * compares across a mutation — message text carries the current status and would read as a fresh
78
+ * problem the moment doctor flipped `running` → `merged` on an already-broken record, which is the
79
+ * one case the guard must stay out of the way for.
80
+ */
81
+ function worktreeProblems(rec) {
82
+ const out = [];
83
+ const b = branchProblem(rec && rec.branch);
84
+ if (b) out.push({ code: 'branch', message: b });
85
+ const p = pathProblem(rec || {});
86
+ if (p) out.push({ code: 'path', message: p });
87
+ return out;
88
+ }
89
+
90
+ function claimProblems(rec) {
91
+ const b = branchProblem(rec && rec.branch);
92
+ return b ? [{ code: 'branch', message: b }] : [];
93
+ }
94
+
95
+ /**
96
+ * A place-claim's (#136) `branch` field carries the SAME representation a claim's does — `null`
97
+ * for "the trunk checkout", a real name for a worktree, never the role word `trunk` — so it is
98
+ * validated through the identical `branchProblem` rather than inventing a second check.
99
+ */
100
+ function placeProblems(rec) {
101
+ const b = branchProblem(rec && rec.branch);
102
+ return b ? [{ code: 'branch', message: b }] : [];
103
+ }
104
+
105
+ /**
106
+ * The problem CODES each record carries right now — the "before" picture the guard compares
107
+ * against. Cheap enough to take on every mutation, and it holds no values, so a mutation is free to
108
+ * rewrite anything as long as it does not make a record worse.
109
+ */
110
+ function snapshot(st) {
111
+ const out = { worktrees: {}, claims: {}, places: {} };
112
+ if (!st) return out;
113
+ for (const [k, w] of Object.entries(st.worktrees || {})) out.worktrees[k] = worktreeProblems(w).map((p) => p.code);
114
+ for (const [k, c] of Object.entries(st.claims || {})) out.claims[k] = claimProblems(c).map((p) => p.code);
115
+ for (const [k, p] of Object.entries(st.places || {})) out.places[k] = placeProblems(p).map((x) => x.code);
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Problems this mutation INTRODUCED: a record that is new, or that has acquired a problem it did
121
+ * not have before. Everything a record was already carrying passes through untouched — that is
122
+ * `colab doctor`'s to report, and refusing it here would mean a legacy-bad record makes every later
123
+ * command fail, including the ones trying to repair it. Returns human-readable strings.
124
+ */
125
+ function changedProblems(before, afterState) {
126
+ const out = [];
127
+ const prevW = (before && before.worktrees) || {};
128
+ const prevC = (before && before.claims) || {};
129
+
130
+ for (const [name, rec] of Object.entries((afterState && afterState.worktrees) || {})) {
131
+ const had = new Set(prevW[name] || []);
132
+ const isNew = !Object.prototype.hasOwnProperty.call(prevW, name);
133
+ for (const p of worktreeProblems(rec)) {
134
+ if (isNew || !had.has(p.code)) out.push(`worktree "${name}": ${p.message}`);
135
+ }
136
+ }
137
+ for (const [key, rec] of Object.entries((afterState && afterState.claims) || {})) {
138
+ const had = new Set(prevC[key] || []);
139
+ const isNew = !Object.prototype.hasOwnProperty.call(prevC, key);
140
+ for (const p of claimProblems(rec)) {
141
+ if (isNew || !had.has(p.code)) out.push(`claim ${key}: ${p.message}`);
142
+ }
143
+ }
144
+ const prevP = (before && before.places) || {};
145
+ for (const [key, rec] of Object.entries((afterState && afterState.places) || {})) {
146
+ const had = new Set(prevP[key] || []);
147
+ const isNew = !Object.prototype.hasOwnProperty.call(prevP, key);
148
+ for (const p of placeProblems(rec)) {
149
+ if (isNew || !had.has(p.code)) out.push(`place ${key}: ${p.message}`);
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /**
156
+ * Problems that applying `patch` to one worktree record would INTRODUCE — the same codes-compared
157
+ * rule `changedProblems` applies to a whole-state mutation, asked ahead of time about a single write.
158
+ * Returns human-readable strings; empty means the write would pass the state guard.
159
+ *
160
+ * WHY (#389): `colab ship` flips its worktree to `status: merged` only AFTER the push to trunk, and
161
+ * that write goes through the guard. A `pending` stub with `path: null` passes every precondition
162
+ * and then refuses exactly that flip ("path is null while status is merged") — with trunk already
163
+ * moved, so every bookkeeping step after the push was skipped. A write the real run would refuse
164
+ * must be a failed precondition, measured before anything irreversible, so it is asked here.
165
+ */
166
+ function flipProblems(name, rec, patch) {
167
+ if (!rec) return [];
168
+ const had = new Set(worktreeProblems(rec).map((p) => p.code));
169
+ return worktreeProblems({ ...rec, ...patch })
170
+ .filter((p) => !had.has(p.code))
171
+ .map((p) => `worktree "${name}": ${p.message}`);
172
+ }
173
+
174
+ /** The refusal text for a non-empty changedProblems() list. */
175
+ function refusalMessage(problems) {
176
+ return ['Refusing to write ~/.colab/state.json — the change would record something nothing can act on:']
177
+ .concat(problems.map((p) => ` • ${p}`))
178
+ .concat([' (a record that cannot be resolved makes `landed` answer unknown and `ship` merge with no Closes)'])
179
+ .join('\n');
180
+ }
181
+
182
+ module.exports = {
183
+ ROLE_WORDS, PENDING, statusOf, branchProblem, pathProblem,
184
+ worktreeProblems, claimProblems, placeProblems, snapshot, changedProblems, flipProblems, refusalMessage,
185
+ };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+ /**
3
+ * The `--refs` brake reminder (#385). PURE — labels/body in, finding out; all `gh` I/O stays in
4
+ * the CLI, same split as `lib/checklist.js`.
5
+ *
6
+ * THE INCIDENT. A ship landed an issue's code with `colab ship --refs #N`, deliberately keeping
7
+ * it open: its only unticked "done when" items were a live end-to-end proof no code session can
8
+ * produce. After the merge the issue was open, `deps-checked`, unclaimed and carried no hold, so
9
+ * it was startable again AS CODE WORK. An implementer session picked it up, found nothing to do,
10
+ * and sat holding a concurrency slot for about an hour until a human-side watch parked it.
11
+ *
12
+ * `--refs` is a deliberate choice and stays ungated (CONVENTIONS.md §4, #263). What it did not do
13
+ * is ask for the other half of that choice: an issue kept open for a non-code leftover has to say
14
+ * "do not start me" in a form a scheduler reads — a hold label (§5, *Disposition* / *Holds*).
15
+ * This module decides when to remind. It never refuses, and never writes the label itself: which
16
+ * hold, whose wake and which date are the shipper's judgement, the same authorship argument #263
17
+ * made for not auto-filing a `Remainder: #M`.
18
+ *
19
+ * WHEN IT FIRES — all three:
20
+ * 1. the issue was kept open by the `--refs` FLAG (the caller filters; the `tracking` label and
21
+ * the checklist gate are not this path);
22
+ * 2. its body still has at least one unticked `- [ ]` box ANYWHERE — not only under `## Plan`.
23
+ * The incident's leftovers sat under a "Done when" heading, which the close gate's parser
24
+ * (Plan-only, on purpose) cannot see. A reminder may over-fire; a gate may not.
25
+ * 3. it carries NOTHING that already stops a start (`brakeLabel` below).
26
+ */
27
+
28
+ const labels = require('./labels');
29
+
30
+ /** A GitHub checklist line, same shape as checklist.js ITEM_RE. */
31
+ const ITEM_RE = /^\s*[-*]\s*\[([ xX])\]\s*\S/;
32
+
33
+ /** Count checklist boxes anywhere in a body. */
34
+ function countBoxes(body) {
35
+ let total = 0, unticked = 0;
36
+ for (const line of String(body || '').split('\n')) {
37
+ const m = ITEM_RE.exec(line);
38
+ if (!m) continue;
39
+ total++;
40
+ if (m[1] === ' ') unticked++;
41
+ }
42
+ return { total, unticked };
43
+ }
44
+
45
+ function names(present) {
46
+ return (present || []).map((n) => (n && typeof n === 'object' ? n.name : n)).filter((n) => n !== undefined && n !== null).map(String);
47
+ }
48
+
49
+ /**
50
+ * The first label already stopping a start, or `null`. Recognised:
51
+ * - `deferred:*` a park (CONVENTIONS.md §5, *Disposition*)
52
+ * - `needs-decision` waiting on a human ruling
53
+ * - a non-code `delivery:*` value routed, not started (`labels.isRouteNotStart`)
54
+ * - `tracking` long-lived memory, referenced by design
55
+ * - any label declared under `holds:` (§5, *Holds*, #360) — passed in as `declaredHolds`
56
+ */
57
+ function brakeLabel(present, declaredHolds) {
58
+ const have = names(present);
59
+ const declared = new Set((Array.isArray(declaredHolds) ? declaredHolds : []).map(String));
60
+ for (const n of have) {
61
+ if (n.startsWith(labels.DEFERRED_LABEL_PREFIX)) return n;
62
+ if (n === labels.NEEDS_DECISION_LABEL) return n;
63
+ if (n === labels.TRACKING_LABEL) return n;
64
+ if (declared.has(n)) return n;
65
+ }
66
+ if (labels.isRouteNotStart(present)) return have.find((n) => n.startsWith('delivery:')) || 'delivery:*';
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * The finding for one `--refs`'d issue, or `null` when no reminder is due.
72
+ * Shape: `{ issue, unticked, total, reason }`.
73
+ */
74
+ function refsBrakeFinding({ issue, body, labels: present, declaredHolds } = {}) {
75
+ const { total, unticked } = countBoxes(body);
76
+ if (unticked === 0) return null;
77
+ if (brakeLabel(present, declaredHolds)) return null;
78
+ return {
79
+ issue, unticked, total,
80
+ reason: `kept open by --refs with ${unticked}/${total} unticked box(es) and no hold — it reads as startable code work after this ship`,
81
+ };
82
+ }
83
+
84
+ /** The operator-facing lines for one finding — the two shapes §4 offers, in order of preference. */
85
+ function reminderLines(f) {
86
+ return [
87
+ `#${f.issue}: ${f.reason}.`,
88
+ ` Leftover is NOT code (a live proof, an ops check, a measurement)? Park it in the same step:`,
89
+ ` gh issue edit ${f.issue} --add-label deferred:<date|measurement|external-party> --add-label review-by:<YYYY-MM-DD>`,
90
+ ` + one comment: "Hold: deferred:<kind> — owner: <who posts it> — wake: <wake>" / "Because: <what is left>"`,
91
+ ` Leftover IS code? Prefer \`Remainder: #M\` on #${f.issue} over --refs, and let it close.`,
92
+ ];
93
+ }
94
+
95
+ module.exports = { countBoxes, brakeLabel, refsBrakeFinding, reminderLines };
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/release-channel.js — the release CHANNELS `next` and `stable` (#445).
4
+ *
5
+ * Adopters follow a channel, not a hand-bumped pin:
6
+ *
7
+ * next always the newest CANDIDATE (vX.Y.Z-rc.N) — moved by `colab release cut`
8
+ * stable always the newest FINAL (vX.Y.Z) — moved by `colab release finalize`
9
+ *
10
+ * They are BRANCHES, not tags. A moving tag is refused by every clone that already fetched it
11
+ * (`would clobber existing tag`), and a non-semver tag can be read as "the newest version" by tag
12
+ * readers (`git describe --tags`, stamps). A branch moves cleanly and no tag reader sees it. Version
13
+ * tags stay immutable.
14
+ *
15
+ * Forward only. A channel is fast-forwarded to the commit the tag names, never forced: a channel
16
+ * that is not an ancestor of that commit is a finding (somebody moved it by hand, or a branch of the
17
+ * same name means something else in this repo) and is reported, never overwritten. `stable` lagging
18
+ * behind `next` is the design, not drift — they are two channels, each moving forward on its own.
19
+ *
20
+ * Best-effort, like the GitHub pre-release (#443): the tag is already on the remote when a channel
21
+ * moves, so a channel that could not move is reported (warning, --json `channel.ok: false`) and
22
+ * never a reason to undo the tag. The next cut / finalize retries, and finalize's already-final path
23
+ * repairs a `stable` a dead run left behind.
24
+ *
25
+ * The push carries COLAB_RELEASE=1 — the process-identity assertion templates/pre-push-guard reads
26
+ * for these two refs, the COLAB_SHIP precedent. Nothing else writes them.
27
+ *
28
+ * Two halves: decideMove is pure (facts in, an action out); moveChannel measures and writes through
29
+ * git, on the remote it is given.
30
+ */
31
+
32
+ const git = require('./git');
33
+
34
+ const CHANNELS = Object.freeze({ next: 'next', stable: 'stable' });
35
+ /** The env a release command pushes a channel with — what pre-push-guard lets through. */
36
+ const RELEASE_ENV = 'COLAB_RELEASE';
37
+
38
+ /**
39
+ * What to do with `channel`, given where it is now and where it should be.
40
+ *
41
+ * current the channel's commit on the remote, or null when the branch does not exist
42
+ * target the commit the tag names
43
+ * currentIsAncestor current is an ancestor of target (a fast-forward)
44
+ * targetIsAncestor target is an ancestor of current (the channel is already past it)
45
+ *
46
+ * Returns { action: 'create' | 'move' | 'noop' | 'refuse', detail }.
47
+ */
48
+ function decideMove({ channel, current, target, label, currentIsAncestor, targetIsAncestor }) {
49
+ const at = label ? `${label} (${short(target)})` : short(target);
50
+ if (!target) return { action: 'refuse', detail: `${channel}: no target commit` };
51
+ if (!current) return { action: 'create', detail: `${channel} created at ${at}` };
52
+ if (current === target) return { action: 'noop', detail: `${channel} already at ${at}` };
53
+ if (currentIsAncestor) return { action: 'move', detail: `${channel} fast-forwarded ${short(current)} -> ${at}` };
54
+ if (targetIsAncestor) return { action: 'noop', detail: `${channel} already past ${at} (at ${short(current)}) — a channel only moves forward` };
55
+ return {
56
+ action: 'refuse',
57
+ detail: `${channel} NOT moved: it is at ${short(current)}, which is not an ancestor of ${at} — a channel only fast-forwards; find out who moved it before moving it back by hand`,
58
+ };
59
+ }
60
+
61
+ function short(sha) { return sha ? String(sha).slice(0, 7) : '—'; }
62
+
63
+ /**
64
+ * Move `channel` on `remote` to `sha` (the commit `label`, a tag, names). Forward only, never forced.
65
+ * Returns { channel, ok, action, detail } — ok is false only on a refusal or a failed push/read.
66
+ * With `dry`, measures and reports what it would do, writing nothing.
67
+ */
68
+ function moveChannel(repoAbs, { remote, channel, sha, label, dry = false, env = process.env }) {
69
+ const fail = (detail) => ({ channel, ok: false, action: 'refuse', detail });
70
+ const ls = git.git(['ls-remote', '--heads', remote, `refs/heads/${channel}`], repoAbs);
71
+ if (!ls.ok) return fail(`${channel} NOT moved: could not read it on ${remote} (${(ls.stderr || '').split('\n')[0] || ls.code})`);
72
+ const line = ls.stdout.split('\n').find((l) => l.endsWith(`\trefs/heads/${channel}`));
73
+ const current = line ? line.split('\t')[0] : null;
74
+
75
+ let currentIsAncestor = false;
76
+ let targetIsAncestor = false;
77
+ if (current && current !== sha) {
78
+ // The channel's commit is not necessarily local yet (a clone that never fetched the branch).
79
+ const have = git.git(['cat-file', '-e', `${current}^{commit}`], repoAbs);
80
+ if (!have.ok) {
81
+ const f = git.git(['fetch', '--quiet', remote, `refs/heads/${channel}`], repoAbs);
82
+ if (!f.ok) return fail(`${channel} NOT moved: could not fetch it from ${remote} to check it only moves forward (${(f.stderr || '').split('\n')[0] || f.code})`);
83
+ }
84
+ currentIsAncestor = git.git(['merge-base', '--is-ancestor', current, sha], repoAbs).ok;
85
+ if (!currentIsAncestor) targetIsAncestor = git.git(['merge-base', '--is-ancestor', sha, current], repoAbs).ok;
86
+ }
87
+
88
+ const d = decideMove({ channel, current, target: sha, label, currentIsAncestor, targetIsAncestor });
89
+ if (d.action === 'refuse') return { channel, ok: false, ...d };
90
+ if (d.action === 'noop' || dry) return { channel, ok: true, ...d, ...(dry && d.action !== 'noop' ? { detail: `[--dry] would be: ${d.detail}` } : {}) };
91
+
92
+ // No --force, no lease: git itself refuses a non-fast-forward, so a channel moved meanwhile is
93
+ // refused here too rather than overwritten.
94
+ const push = git.run('git', ['push', remote, `${sha}:refs/heads/${channel}`], { cwd: repoAbs, env: { ...env, [RELEASE_ENV]: '1' } });
95
+ if (!push.ok) return fail(`${channel} NOT moved: git push ${remote} ${short(sha)}:refs/heads/${channel} failed (${(push.stderr || '').split('\n').filter(Boolean).pop() || push.code})`);
96
+ return { channel, ok: true, ...d };
97
+ }
98
+
99
+ module.exports = { CHANNELS, RELEASE_ENV, decideMove, moveChannel };