@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.0-rc.10
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/LICENSE +21 -0
- package/README.md +310 -3
- package/README.vi.md +280 -0
- package/audit/audit.mjs +3035 -0
- package/package.json +26 -5
- package/templates/README.md +257 -0
- package/templates/adr-README.md +57 -0
- package/templates/branch-name.yml +51 -0
- package/templates/ci-laravel.yml +540 -0
- package/templates/ci-node.yml +291 -0
- package/templates/ci-python.yml +281 -0
- package/templates/deploy-xserver.yml +531 -0
- package/templates/dist-refs.yml +177 -0
- package/templates/docs-lint.mjs +993 -0
- package/templates/docs-lint.yml +55 -0
- package/templates/gotchas-d-README.md +41 -0
- package/templates/identity-vocabulary.example +58 -0
- package/templates/npx-launcher.mjs +213 -0
- package/templates/pre-commit-dispatch +88 -0
- package/templates/pre-commit-identity +267 -0
- package/templates/pre-push-guard +137 -0
- package/templates/release-auto.yml +475 -0
- package/templates/release-tag.yml +245 -0
- package/templates/repo-CLAUDE-block.md +21 -0
- package/tools/colab +13790 -0
- package/tools/lib/adopt.js +882 -0
- package/tools/lib/axis-authority.js +96 -0
- package/tools/lib/base-ci-verdict.js +93 -0
- package/tools/lib/blocked-by.js +262 -0
- package/tools/lib/branch-name.js +137 -0
- package/tools/lib/checklist.js +143 -0
- package/tools/lib/ci-cure.js +512 -0
- package/tools/lib/ci-grant.js +307 -0
- package/tools/lib/ci-verdict.js +113 -0
- package/tools/lib/claim-comments.js +212 -0
- package/tools/lib/claim-identity.js +195 -0
- package/tools/lib/codeowners.js +208 -0
- package/tools/lib/consumer-evidence.js +74 -0
- package/tools/lib/container-close.js +141 -0
- package/tools/lib/cure-diff.js +267 -0
- package/tools/lib/decision-record.js +335 -0
- package/tools/lib/dirty-owner.js +150 -0
- package/tools/lib/disposition.js +378 -0
- package/tools/lib/docs-only.js +156 -0
- package/tools/lib/exposure-shape.js +207 -0
- package/tools/lib/gate.js +80 -0
- package/tools/lib/git.js +1059 -0
- package/tools/lib/group-labels.js +120 -0
- package/tools/lib/hermetic.js +193 -0
- package/tools/lib/identity.js +187 -0
- package/tools/lib/install-check.js +259 -0
- package/tools/lib/instruction-file.js +302 -0
- package/tools/lib/journal.js +430 -0
- package/tools/lib/labels.js +653 -0
- package/tools/lib/landed.js +230 -0
- package/tools/lib/local-adopt.js +133 -0
- package/tools/lib/lockfile-drift.js +119 -0
- package/tools/lib/machine-trailer.js +83 -0
- package/tools/lib/machine.js +238 -0
- package/tools/lib/migration-grant.js +641 -0
- package/tools/lib/migration-paths.js +135 -0
- package/tools/lib/notify.js +188 -0
- package/tools/lib/npm-publish-guard.js +242 -0
- package/tools/lib/orphan-worktree.js +127 -0
- package/tools/lib/owner-branch.js +182 -0
- package/tools/lib/place.js +782 -0
- package/tools/lib/ports.js +167 -0
- package/tools/lib/procs.js +185 -0
- package/tools/lib/readiness.js +240 -0
- package/tools/lib/records.js +185 -0
- package/tools/lib/refs-brake.js +95 -0
- package/tools/lib/release-channel.js +99 -0
- package/tools/lib/release-cut.js +822 -0
- package/tools/lib/release-finalize.js +521 -0
- package/tools/lib/release-policy.js +358 -0
- package/tools/lib/release-tag.js +225 -0
- package/tools/lib/ship-batch.js +277 -0
- package/tools/lib/ship-roles.js +71 -0
- package/tools/lib/ship-target-sync.js +181 -0
- package/tools/lib/shipguard.js +317 -0
- package/tools/lib/shipped-branch.js +56 -0
- package/tools/lib/solo.js +213 -0
- package/tools/lib/squash.js +515 -0
- package/tools/lib/stale-base.js +70 -0
- package/tools/lib/stamp.js +740 -0
- package/tools/lib/state.js +262 -0
- package/tools/lib/teardown.js +83 -0
- package/tools/lib/trust-humans.js +104 -0
- package/tools/lib/util.js +98 -0
- package/tools/lib/wake.js +188 -0
- package/tools/lib/workflow-triggers.js +273 -0
- package/tools/lib/writes-authority.js +237 -0
- package/tools/lib/yaml.js +101 -0
- package/bin/cli.js +0 -3
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Machine-local state + config for colab.
|
|
4
|
+
*
|
|
5
|
+
* ~/.colab/state.json — the single source of truth for this machine (worktrees, claims, ports)
|
|
6
|
+
* ~/.colab/config.json — configuration (repo roots to scan, extra reserved ports, TTL, port range)
|
|
7
|
+
* ~/.colab/state.lock — mkdir-based lock (survives concurrent sessions; same technique as the
|
|
8
|
+
* original shell scripts). Held only for the read-modify-write critical section.
|
|
9
|
+
*
|
|
10
|
+
* State is GLOBAL per machine: ports must be unique across ALL repos, not per-repo, so everything
|
|
11
|
+
* lives in one file. Writes are atomic (temp file + rename).
|
|
12
|
+
*
|
|
13
|
+
* THIS SCHEMA HAS CONSUMERS OUTSIDE THIS REPO. At least one internal dashboard reads
|
|
14
|
+
* ~/.colab/state.json directly to join worktrees and claims to the sessions that own them. So the
|
|
15
|
+
* shape below is a published contract, not an implementation detail: adding a field is safe,
|
|
16
|
+
* renaming or removing one is a breaking change for readers you cannot grep for. The authoritative
|
|
17
|
+
* annotated version lives in tools/README.md ("~/.colab/state.json (version 1)") — keep the two in
|
|
18
|
+
* step, and prefer to extend the prose there rather than here.
|
|
19
|
+
*
|
|
20
|
+
* State shape (version 1):
|
|
21
|
+
* {
|
|
22
|
+
* version: 1,
|
|
23
|
+
* worktrees: { // the port-OWNING entity
|
|
24
|
+
* "<name>": { name, repo, branch, base, path, ports: [5230,...], host,
|
|
25
|
+
* session, sessionName, status, created }
|
|
26
|
+
* },
|
|
27
|
+
* claims: { // many claims may reference one worktree (group of issues)
|
|
28
|
+
* "<repoAbs>#<n>": { issue:"#115", repo, worktree:<name>|null, branch, host,
|
|
29
|
+
* session, sessionName, created }
|
|
30
|
+
* },
|
|
31
|
+
* ports: { // flat registry — one entry per allocated port
|
|
32
|
+
* "5230": { port:5230, owner:{type:"worktree"|"claim"|"manual", ref:"<name|key|label>"}, host, created }
|
|
33
|
+
* },
|
|
34
|
+
* solo: { // `ceremony: light` only — one lock per repo per machine
|
|
35
|
+
* "<repoAbs>": { host, session, sessionName, since }
|
|
36
|
+
* },
|
|
37
|
+
* places: { // #136 — path-scoped place-claims, machine-local only
|
|
38
|
+
* "<checkoutPathAbs>": { path, repo, branch, host, machine, session, sessionName, pid, pidKind,
|
|
39
|
+
* since }
|
|
40
|
+
* }
|
|
41
|
+
* }
|
|
42
|
+
*
|
|
43
|
+
* Field notes for the four that carry weight beyond storage:
|
|
44
|
+
* base the branch the worktree was cut from AND the one `colab ship` merges back into —
|
|
45
|
+
* trunk normally, a declared `integration:` line by request. Not derived at ship time.
|
|
46
|
+
* session the ONLY join key to a live session; `sessionName` is display text and joins nothing.
|
|
47
|
+
* A name with no URL is a half-identity — the row reads as owned and links nowhere.
|
|
48
|
+
* branch a real branch name, or `null` for "no branch" (a claim held on the trunk checkout).
|
|
49
|
+
* NEVER the word `trunk`: that is a role, not a name, and a reader resolving it gets
|
|
50
|
+
* nothing. Enforced on write by lib/records.js; readers must tolerate null.
|
|
51
|
+
* status `running` → `merged` (killed = entry removed), plus `pending`: a stub written by
|
|
52
|
+
* `colab claim --worktree <name>` for a worktree that does not exist yet. It is the one
|
|
53
|
+
* status allowed a null `path`, and `colab worktree new` replaces it with the real record.
|
|
54
|
+
*
|
|
55
|
+
* `session`, `sessionName`, `status` and `base` are backward-compatible: entries written before
|
|
56
|
+
* they existed simply lack them, and readers must tolerate that — no migration is performed.
|
|
57
|
+
*
|
|
58
|
+
* `solo` is keyed by repo, not by issue or worktree: solo flow (CONVENTIONS.md, Solo flow) makes
|
|
59
|
+
* no claim and creates no worktree, so it needs its own lock or two solo sessions on one machine
|
|
60
|
+
* could commit to the same trunk checkout at once with nothing recording either. `colab solo`
|
|
61
|
+
* is the only writer; `--done` is the only remover.
|
|
62
|
+
*
|
|
63
|
+
* `places` is keyed by absolute checkout PATH, not by repo or issue (CONVENTIONS.md, Place-claims;
|
|
64
|
+
* lib/place.js) — a repo running several worktrees needs one hold per checkout in use, not one per
|
|
65
|
+
* repo. `pid` is optional (a hold acquired by a process other than the one whose liveness matters
|
|
66
|
+
* may omit it) but its absence makes the hold's liveness `unknown`, which FAILS CLOSED (the hold
|
|
67
|
+
* stands) rather than reading as released. Nothing here is ever read as "released" from a stored
|
|
68
|
+
* flag — every reader re-derives liveness at read time (lib/place.js `isLive`); a record surviving
|
|
69
|
+
* past its holder's death is the expected, harmless shape, not a bug to migrate away. `places` and
|
|
70
|
+
* `solo` deliberately coexist rather than merge: `solo` is the published contract noted above, and
|
|
71
|
+
* converging the two is out of scope for #133/#136 (tracked for after #175).
|
|
72
|
+
*
|
|
73
|
+
* `machine` and `pidKind` (#288/#289) are backward-compatible the same way: a record written before
|
|
74
|
+
* they existed simply lacks them, and readers must tolerate that — no migration. `machine` is this
|
|
75
|
+
* machine's hardware-bound id (lib/machine.js `localMachine().id`), recorded alongside `host` so a
|
|
76
|
+
* reader can tell a genuinely different machine from the same machine under a drifted hostname
|
|
77
|
+
* without re-deriving it. `pidKind` (`'anchor'` or absent = today's exact behaviour; `'invocation'`
|
|
78
|
+
* = kept only as a human lead, never probed) says whether `pid` may be used for liveness at all —
|
|
79
|
+
* see lib/place.js `resolveAnchor`/`defaultProbe`.
|
|
80
|
+
*/
|
|
81
|
+
|
|
82
|
+
const fs = require('fs');
|
|
83
|
+
const os = require('os');
|
|
84
|
+
const path = require('path');
|
|
85
|
+
|
|
86
|
+
// Optional local journal. Requires nothing back from this module (it resolves COLAB_DIR itself), so
|
|
87
|
+
// there is no require cycle; see the note on COLAB_DIR in lib/journal.js.
|
|
88
|
+
const journal = require('./journal');
|
|
89
|
+
// Write-time validation of the fields other commands resolve against git. Same reason the journal
|
|
90
|
+
// hooks into mutate() and nowhere else: one place every fact enters state, so no write site can
|
|
91
|
+
// forget. Neither module requires this one back.
|
|
92
|
+
const records = require('./records');
|
|
93
|
+
const { UserError } = require('./util');
|
|
94
|
+
|
|
95
|
+
const HOME = os.homedir();
|
|
96
|
+
const COLAB_DIR = process.env.COLAB_HOME || path.join(HOME, '.colab');
|
|
97
|
+
const STATE_FILE = path.join(COLAB_DIR, 'state.json');
|
|
98
|
+
const CONFIG_FILE = path.join(COLAB_DIR, 'config.json');
|
|
99
|
+
const LOCK_DIR = path.join(COLAB_DIR, 'state.lock');
|
|
100
|
+
|
|
101
|
+
const STATE_VERSION = 1;
|
|
102
|
+
|
|
103
|
+
const DEFAULT_CONFIG = {
|
|
104
|
+
repos: [], // absolute repo roots to scan for .github/project.yml `ports:`
|
|
105
|
+
extraReserved: [], // reserved ports for non-repo services (e.g. a preview server)
|
|
106
|
+
reservedFiles: [], // machine-local files of reserved ports (lenient: whitespace ints, # comments)
|
|
107
|
+
claimTTLHours: 24, // worktree-less claims older than this are flagged by `doctor`
|
|
108
|
+
plannerClaimTTLMinutes: 30, // #326: a planner `--session intent:<id>` claim older than this never got its session
|
|
109
|
+
portRange: '5200-5999', // default search window for `port alloc` / `worktree new`
|
|
110
|
+
// Optional observer endpoint. Unset (the default) = colab makes no network call of its own, ever.
|
|
111
|
+
// Set it and state-changing commands POST one best-effort event each; see lib/notify.js for why
|
|
112
|
+
// it is deliberately undependable. Absent rather than '' so `config show` does not advertise it.
|
|
113
|
+
//
|
|
114
|
+
// Optional LOCAL journal (`journal: true`). Unset = colab writes no journal file, ever. Set it and
|
|
115
|
+
// every state transition and every invocation is appended to ~/.colab/journal.jsonl; see
|
|
116
|
+
// lib/journal.js. Absent rather than false, for the same reason as notifyUrl. Unrelated to
|
|
117
|
+
// notifyUrl: one is a local append-only file, the other a push to somebody else's receiver.
|
|
118
|
+
//
|
|
119
|
+
// Optional claim tie-break identity granularity (`claimIdentity: "login,host,session"`). Unset =
|
|
120
|
+
// "login,host" (unchanged behaviour): two sessions of one GitHub account on one host are
|
|
121
|
+
// indistinguishable to the tie-break (#267). See tools/lib/claim-identity.js and `colab config
|
|
122
|
+
// set claimIdentity` for the tradeoff (only safe where --session is stable across a resume).
|
|
123
|
+
// Absent rather than the coarse string, for the same reason as journal/notifyUrl.
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
function ensureDir() {
|
|
127
|
+
fs.mkdirSync(COLAB_DIR, { recursive: true });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function emptyState() {
|
|
131
|
+
return { version: STATE_VERSION, worktrees: {}, claims: {}, ports: {}, solo: {}, places: {} };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function loadConfig() {
|
|
135
|
+
try {
|
|
136
|
+
const raw = fs.readFileSync(CONFIG_FILE, 'utf8');
|
|
137
|
+
return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
|
|
138
|
+
} catch (e) {
|
|
139
|
+
if (e.code === 'ENOENT') return { ...DEFAULT_CONFIG };
|
|
140
|
+
throw new Error(`config.json is not valid JSON (${CONFIG_FILE}): ${e.message}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function saveConfig(cfg) {
|
|
145
|
+
ensureDir();
|
|
146
|
+
atomicWrite(CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function loadState() {
|
|
150
|
+
try {
|
|
151
|
+
const raw = fs.readFileSync(STATE_FILE, 'utf8');
|
|
152
|
+
const st = JSON.parse(raw);
|
|
153
|
+
return migrate(st);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
if (e.code === 'ENOENT') return emptyState();
|
|
156
|
+
throw new Error(`state.json is not valid JSON (${STATE_FILE}): ${e.message}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function migrate(st) {
|
|
161
|
+
if (!st || typeof st !== 'object') return emptyState();
|
|
162
|
+
if (!st.version) st.version = STATE_VERSION;
|
|
163
|
+
st.worktrees = st.worktrees || {};
|
|
164
|
+
st.claims = st.claims || {};
|
|
165
|
+
st.ports = st.ports || {};
|
|
166
|
+
st.solo = st.solo || {};
|
|
167
|
+
st.places = st.places || {};
|
|
168
|
+
// Future migrations key off st.version here.
|
|
169
|
+
return st;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function atomicWrite(file, content) {
|
|
173
|
+
const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
|
|
174
|
+
fs.writeFileSync(tmp, content);
|
|
175
|
+
fs.renameSync(tmp, file);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function saveState(st) {
|
|
179
|
+
ensureDir();
|
|
180
|
+
st.version = STATE_VERSION;
|
|
181
|
+
atomicWrite(STATE_FILE, JSON.stringify(st, null, 2) + '\n');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function sleep(ms) {
|
|
185
|
+
// Busy-wait sleep; keeps the lock helper synchronous (no async plumbing through the CLI).
|
|
186
|
+
const end = Date.now() + ms;
|
|
187
|
+
while (Date.now() < end) { /* spin */ }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Acquire the mkdir lock, run fn, always release. Returns fn's result. */
|
|
191
|
+
function withLock(fn, { tries = 100, waitMs = 100 } = {}) {
|
|
192
|
+
ensureDir();
|
|
193
|
+
let acquired = false;
|
|
194
|
+
for (let i = 0; i < tries; i++) {
|
|
195
|
+
try {
|
|
196
|
+
fs.mkdirSync(LOCK_DIR);
|
|
197
|
+
acquired = true;
|
|
198
|
+
break;
|
|
199
|
+
} catch (e) {
|
|
200
|
+
if (e.code !== 'EEXIST') throw e;
|
|
201
|
+
sleep(waitMs);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (!acquired) {
|
|
205
|
+
throw new Error(`Lock stuck: ${LOCK_DIR} (remove it by hand if you are sure no session holds it)`);
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
return fn();
|
|
209
|
+
} finally {
|
|
210
|
+
try { fs.rmdirSync(LOCK_DIR); } catch (_) { /* already gone */ }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Load → mutate under lock → save, in one atomic critical section.
|
|
216
|
+
*
|
|
217
|
+
* Also the ONE place every fact enters or leaves state, which is why the optional journal
|
|
218
|
+
* (lib/journal.js) hooks here and nowhere else: a before/after diff taken around `fn` captures all
|
|
219
|
+
* 13 delete sites and every write, with no per-command plumbing and no chance of a caller
|
|
220
|
+
* forgetting to report. It is off unless `journal: true` is configured, and when off `snapshot()`
|
|
221
|
+
* returns null on its first line, so the disabled path costs one boolean and allocates nothing.
|
|
222
|
+
*
|
|
223
|
+
* It is also where the write-time record validation runs (lib/records.js), for the same structural
|
|
224
|
+
* reason and with one deliberate difference: the journal observes and cannot fail a mutation, while
|
|
225
|
+
* validation REFUSES one. It throws before saveState, so a refused write leaves the file exactly as
|
|
226
|
+
* it was — and it only judges fields this mutation CHANGED, so a legacy-bad record already on disk
|
|
227
|
+
* does not turn every later command into a crash. That record is `colab doctor`'s to report.
|
|
228
|
+
*
|
|
229
|
+
* Two properties the journal must never cost us, both structural rather than promised:
|
|
230
|
+
* - It cannot fail a mutation. Everything journal-related is inside try/catch, and the catch is
|
|
231
|
+
* empty on purpose — a full disk must not roll back a claim that succeeded.
|
|
232
|
+
* - It cannot hold the lock. Only the diff is computed inside the critical section; the append
|
|
233
|
+
* happens after withLock has returned, so a slow filesystem blocks no other session.
|
|
234
|
+
*/
|
|
235
|
+
function mutate(fn) {
|
|
236
|
+
// NOT named `records`: that shadowed the module of the same name for the whole closure, so the
|
|
237
|
+
// guard below read `null.snapshot` and every state write died. Caught by the new tests.
|
|
238
|
+
let journalRecords = null;
|
|
239
|
+
const result = withLock(() => {
|
|
240
|
+
const st = loadState();
|
|
241
|
+
let before = null;
|
|
242
|
+
try { before = journal.snapshot(st); } catch (_) { before = null; }
|
|
243
|
+
const guard = records.snapshot(st);
|
|
244
|
+
const r = fn(st);
|
|
245
|
+
const problems = records.changedProblems(guard, st);
|
|
246
|
+
if (problems.length) throw new UserError(records.refusalMessage(problems));
|
|
247
|
+
saveState(st);
|
|
248
|
+
if (before) {
|
|
249
|
+
try { journalRecords = journal.recordDiff(before, journal.snapshot(st)); } catch (_) { journalRecords = null; }
|
|
250
|
+
}
|
|
251
|
+
return r;
|
|
252
|
+
});
|
|
253
|
+
if (journalRecords && journalRecords.length) {
|
|
254
|
+
try { journal.append(journalRecords); } catch (_) { /* never at the expense of the mutation */ }
|
|
255
|
+
}
|
|
256
|
+
return result;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
module.exports = {
|
|
260
|
+
COLAB_DIR, STATE_FILE, CONFIG_FILE, LOCK_DIR, STATE_VERSION, DEFAULT_CONFIG,
|
|
261
|
+
loadConfig, saveConfig, loadState, saveState, withLock, mutate, emptyState, atomicWrite,
|
|
262
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Pure decision logic for tearing down a worktree DIRECTORY (the `git worktree remove` step of
|
|
4
|
+
* `colab worktree rm` / `colab doctor --prune`). Side effects (fs, git, timing) live in tools/colab;
|
|
5
|
+
* this module only maps observable state to an action, so the matrix is unit-testable without a
|
|
6
|
+
* real repo, a real slow filesystem, or a real hung process.
|
|
7
|
+
*
|
|
8
|
+
* Why this exists (#62): `git worktree remove` validates that `<path>/.git` exists before it will
|
|
9
|
+
* touch anything. An earlier attempt that got as far as deleting `.git` — then was interrupted, by
|
|
10
|
+
* a kill after a hang with no timeout, or by anything else — leaves a directory that still exists
|
|
11
|
+
* but that git can no longer recognize as a worktree AT ALL. Every subsequent `git worktree remove`
|
|
12
|
+
* on that path fails "validation failed: cannot remove working tree" FOREVER; retrying the identical
|
|
13
|
+
* command is not a fix, because the precondition it needs is exactly the thing that is gone. That
|
|
14
|
+
* shape is called a "husk" below, and the fix is to recognize it BEFORE asking git to do a job git
|
|
15
|
+
* is structurally unable to do, and finish the deletion by hand instead.
|
|
16
|
+
*
|
|
17
|
+
* The second half of the bug was silent success: the caller used to proceed to release claims and
|
|
18
|
+
* delete the worktree's state record even when the directory removal failed or hung, because
|
|
19
|
+
* nothing checked. That turned "we could not remove this" into "we did remove this" from every
|
|
20
|
+
* consumer's point of view — the registry said gone, the disk said still there, and the only way
|
|
21
|
+
* back was manual surgery. `decideTeardown` returning `'blocked'` is what a caller uses to refuse
|
|
22
|
+
* that silent success (see cmdWorktreeRm's use of it in tools/colab).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What shape is the worktree directory in, BEFORE any removal is attempted?
|
|
27
|
+
*
|
|
28
|
+
* @param {object} state
|
|
29
|
+
* @param {boolean} state.pathExists - does the worktree directory exist on disk at all?
|
|
30
|
+
* @param {boolean} state.gitEntryExists - does `<path>/.git` exist? Only meaningful when
|
|
31
|
+
* pathExists is true; pass false (or anything falsy) when the path itself is gone.
|
|
32
|
+
* @returns {'gone'|'husk'|'live'}
|
|
33
|
+
* - 'gone': nothing on disk. Already torn down (or never created) — nothing to do.
|
|
34
|
+
* - 'husk': the directory exists but `.git` does not. An earlier removal was interrupted;
|
|
35
|
+
* `git worktree remove` will never succeed against this path again. Finish by hand.
|
|
36
|
+
* - 'live': an ordinary, still-registered worktree. Attempt the normal git removal.
|
|
37
|
+
*/
|
|
38
|
+
function classifyWorktreeDir({ pathExists, gitEntryExists }) {
|
|
39
|
+
if (!pathExists) return 'gone';
|
|
40
|
+
if (!gitEntryExists) return 'husk';
|
|
41
|
+
return 'live';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Decide the next action from a shape (see classifyWorktreeDir) and, for 'live' only, the outcome
|
|
46
|
+
* of having attempted `git worktree remove --force`.
|
|
47
|
+
*
|
|
48
|
+
* @param {'gone'|'husk'|'live'} shape
|
|
49
|
+
* @param {object} [removeOutcome] - required when shape === 'live'; ignored otherwise.
|
|
50
|
+
* @param {boolean} removeOutcome.ok
|
|
51
|
+
* @param {boolean} [removeOutcome.timedOut]
|
|
52
|
+
* @param {string} [removeOutcome.stderr]
|
|
53
|
+
* @returns {{action: 'noop'|'rm-rf'|'done'|'blocked', reason: string}}
|
|
54
|
+
* - 'noop': nothing on disk to remove — treat as already torn down.
|
|
55
|
+
* - 'rm-rf': shape was a husk — the caller should `git worktree prune` (best-effort, to clear
|
|
56
|
+
* git's admin-dir reference) then delete the directory itself directly; git cannot help here.
|
|
57
|
+
* - 'done': `git worktree remove` succeeded — normal path, fully torn down.
|
|
58
|
+
* - 'blocked': the directory is NOT gone and NOT cleanly removed. The caller must NOT proceed to
|
|
59
|
+
* release claims or delete the worktree's state record — doing so is exactly the bug this
|
|
60
|
+
* module exists to prevent. The caller should surface `reason` and let a human (or --force)
|
|
61
|
+
* decide, and a retry against the same path will very likely reclassify as 'husk' next time.
|
|
62
|
+
*/
|
|
63
|
+
function decideTeardown(shape, removeOutcome) {
|
|
64
|
+
if (shape === 'gone') return { action: 'noop', reason: 'nothing on disk — already removed' };
|
|
65
|
+
if (shape === 'husk') {
|
|
66
|
+
return {
|
|
67
|
+
action: 'rm-rf',
|
|
68
|
+
reason: '.git missing — an earlier removal was interrupted partway through; finishing it directly instead of asking git (which can never remove a path once .git is gone)',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// shape === 'live'
|
|
72
|
+
if (!removeOutcome) throw new Error('decideTeardown: shape "live" requires a removeOutcome');
|
|
73
|
+
if (removeOutcome.ok) return { action: 'done', reason: 'git worktree remove succeeded' };
|
|
74
|
+
if (removeOutcome.timedOut) {
|
|
75
|
+
return {
|
|
76
|
+
action: 'blocked',
|
|
77
|
+
reason: 'git worktree remove timed out with no output — directory left as-is; re-run to retry (if it made partial progress, the retry will detect a husk and finish by hand)',
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return { action: 'blocked', reason: removeOutcome.stderr || 'git worktree remove failed' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = { classifyWorktreeDir, decideTeardown };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* `trust-humans:` (#407): an optional repo policy naming which logins count as HUMAN for a grant
|
|
4
|
+
* (migration-grant, ci-grant) or a ruling (decision-record).
|
|
5
|
+
*
|
|
6
|
+
* WHY. Those readers judged an author by `authorAssociation` alone (OWNER/MEMBER/COLLABORATOR).
|
|
7
|
+
* That class cannot tell a separate agent account from the human: once an adopter gives its agents
|
|
8
|
+
* their own GitHub login with write access, the agent's comments report `MEMBER` exactly like the
|
|
9
|
+
* operator's, and a well-formed grant comment the agent posted reads as a human grant. The account
|
|
10
|
+
* difference exists on the platform; these readers threw it away. This module keeps it.
|
|
11
|
+
*
|
|
12
|
+
* THE RULE.
|
|
13
|
+
* - key absent → today's behaviour, byte-identical: a trusted association is human enough.
|
|
14
|
+
* - key present → an author counts as human only when their login is LISTED (case-insensitive —
|
|
15
|
+
* GitHub logins are) AND their association is still trusted. The association check stays on
|
|
16
|
+
* purpose: a listed person who has since lost repo access is not someone whose grant a
|
|
17
|
+
* scheduled driver should act on.
|
|
18
|
+
* - key present but malformed (not a list, empty, a non-login entry) → fail CLOSED: nobody counts
|
|
19
|
+
* as human, and the audit fails the descriptor. Falling back to the association class would
|
|
20
|
+
* silently reopen exactly the hole the adopter declared the key to close.
|
|
21
|
+
*
|
|
22
|
+
* WHAT IT DOES NOT DECIDE. Reviewer grants (#397/#401) are judged by policy + review record + HEAD
|
|
23
|
+
* + round-trip, not by this list — the list says what a *human* grant is. And WHERE the list is read
|
|
24
|
+
* from is the caller's job: always trunk's (or the merge target's) committed project.yml, never the
|
|
25
|
+
* branch being shipped, so a branch cannot add its own author (tools/colab `trustAt`).
|
|
26
|
+
*
|
|
27
|
+
* PURE, like its callers: parsed doc in, verdict out. No git, no network.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** GitHub's login shape: alphanumerics and single hyphens, no leading hyphen, ≤ 39 chars. Bot
|
|
31
|
+
* logins carry a `[bot]` suffix; accepted so an adopter can list one deliberately. */
|
|
32
|
+
const LOGIN_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?$/;
|
|
33
|
+
|
|
34
|
+
/** Same set every grant reader has used since #98 — the association gate this module keeps. */
|
|
35
|
+
const TRUSTED_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
|
|
36
|
+
|
|
37
|
+
/** The project.yml key. A FLAT key holding a list — not `trust: { humans: [...] }` — for the same
|
|
38
|
+
* reason `migration-grant:` is flat (#398): the audit's descriptor reader refuses nesting on
|
|
39
|
+
* purpose (a named allow-list of one-level maps, never a list inside one), and this key is a list. */
|
|
40
|
+
const KEY = 'trust-humans';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `trust-humans:` from a parsed project.yml → { declared, valid, humans, reason }.
|
|
44
|
+
* humans — a Set of lowercased logins when declared (EMPTY when invalid: fail closed), or null
|
|
45
|
+
* when the key is absent (the association class decides, as before).
|
|
46
|
+
* Both list spellings parse identically: `trust-humans: [a, b]` and a `- a` block sequence.
|
|
47
|
+
*/
|
|
48
|
+
function parseTrustHumans(doc) {
|
|
49
|
+
const has = !!doc && typeof doc === 'object' && Object.prototype.hasOwnProperty.call(doc, KEY);
|
|
50
|
+
const list = has ? doc[KEY] : undefined;
|
|
51
|
+
if (!has || list === null || list === undefined) {
|
|
52
|
+
return { declared: false, valid: true, humans: null, reason: `${KEY} absent — a trusted association counts as human` };
|
|
53
|
+
}
|
|
54
|
+
const bad = (why) => ({ declared: true, valid: false, humans: new Set(),
|
|
55
|
+
reason: `${KEY} ${why} — read as "nobody is human" until fixed (a malformed list never falls back to the association class)` });
|
|
56
|
+
if (!Array.isArray(list)) return bad(`must be a list of logins, got ${JSON.stringify(list)}`);
|
|
57
|
+
if (list.length === 0) return bad('is an empty list');
|
|
58
|
+
const wrong = list.filter((l) => typeof l !== 'string' || !LOGIN_RE.test(l.trim()));
|
|
59
|
+
if (wrong.length) return bad(`has entr${wrong.length > 1 ? 'ies' : 'y'} that ${wrong.length > 1 ? 'are' : 'is'} not a GitHub login: ${wrong.map((w) => JSON.stringify(w)).join(', ')}`);
|
|
60
|
+
const humans = new Set(list.map((l) => l.trim().toLowerCase()));
|
|
61
|
+
return { declared: true, valid: true, humans, reason: `${KEY}: ${[...humans].join(', ')}` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether one comment author counts as human. `author` = { login, authorAssociation } (the shape
|
|
66
|
+
* every grant/decision reader already extracts). `trust` = parseTrustHumans(...)'s result, or
|
|
67
|
+
* null/undefined for "not supplied" — identical to absent.
|
|
68
|
+
* Returns { ok, reason } — `reason` is '' when ok, and otherwise names the login.
|
|
69
|
+
*/
|
|
70
|
+
function authorIsHuman(author, trust) {
|
|
71
|
+
const login = String((author && author.login) || '');
|
|
72
|
+
const assoc = String((author && author.authorAssociation) || '');
|
|
73
|
+
const assocOk = TRUSTED_ASSOCIATIONS.has(assoc);
|
|
74
|
+
const who = `${login || '(unknown)'} (${assoc || 'unknown association'})`;
|
|
75
|
+
if (!trust || !trust.declared) {
|
|
76
|
+
return assocOk ? { ok: true, reason: '' } : { ok: false, reason: `${who} — not a repo owner/member/collaborator` };
|
|
77
|
+
}
|
|
78
|
+
if (!login) return { ok: false, reason: `the author could not be read — trust-humans is set, and an unknown author is never human` };
|
|
79
|
+
if (!trust.humans || !trust.humans.has(login.toLowerCase())) {
|
|
80
|
+
return { ok: false, reason: `${who} is not listed in trust-humans${trust.valid ? '' : ' (the list is malformed, so nobody is)'}` };
|
|
81
|
+
}
|
|
82
|
+
if (!assocOk) return { ok: false, reason: `${who} is listed in trust-humans but is no longer a repo owner/member/collaborator` };
|
|
83
|
+
return { ok: true, reason: '' };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The label half (#407 Wanted 2): who applied the grant label. Only consulted when trust-humans is
|
|
88
|
+
* DECLARED — absent key, no extra read, no change. `actors` = the logins of every `labeled` event
|
|
89
|
+
* for the label, oldest-first (tools/lib/git.js ghIssueLabelActors), or null when that read failed.
|
|
90
|
+
* The LATEST applier decides — a label re-added by an agent after a human's is the agent's label.
|
|
91
|
+
* Returns { ok, reason }.
|
|
92
|
+
*/
|
|
93
|
+
function labelApplierIsHuman(actors, trust, labelName) {
|
|
94
|
+
if (!trust || !trust.declared) return { ok: true, reason: '' };
|
|
95
|
+
if (!Array.isArray(actors)) return { ok: false, reason: `who applied \`${labelName}\` could not be read — trust-humans is set, and an unread applier is never human` };
|
|
96
|
+
if (actors.length === 0) return { ok: false, reason: `no \`labeled\` event for \`${labelName}\` could be found — trust-humans is set, and a label nobody can be shown to have applied is not a human's` };
|
|
97
|
+
const last = String(actors[actors.length - 1] || '');
|
|
98
|
+
if (!last || !trust.humans || !trust.humans.has(last.toLowerCase())) {
|
|
99
|
+
return { ok: false, reason: `\`${labelName}\` was last applied by ${last || '(unknown)'}, who is not listed in trust-humans` };
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, reason: '' };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { KEY, LOGIN_RE, TRUSTED_ASSOCIATIONS, parseTrustHumans, authorIsHuman, labelApplierIsHuman };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const os = require('os');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
const HOST = os.hostname();
|
|
6
|
+
|
|
7
|
+
function normIssueNum(x) {
|
|
8
|
+
const n = parseInt(String(x).replace(/^#/, ''), 10);
|
|
9
|
+
if (!Number.isInteger(n) || n <= 0) throw new UserError(`Bad issue "${x}" (expected a number like 115 or #115)`);
|
|
10
|
+
return n;
|
|
11
|
+
}
|
|
12
|
+
function issueTag(n) { return `#${n}`; }
|
|
13
|
+
function claimKey(repoAbs, num) { return `${repoAbs}#${num}`; }
|
|
14
|
+
|
|
15
|
+
/** A user-facing error → printed without a stack trace, exit 1. */
|
|
16
|
+
class UserError extends Error {}
|
|
17
|
+
|
|
18
|
+
function today() { return new Date().toISOString().slice(0, 10); }
|
|
19
|
+
function nowISO() { return new Date().toISOString(); }
|
|
20
|
+
|
|
21
|
+
function hoursSince(iso) {
|
|
22
|
+
const t = Date.parse(iso);
|
|
23
|
+
if (Number.isNaN(t)) return Infinity;
|
|
24
|
+
return (Date.now() - t) / 3_600_000;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A hold's age, rendered so it is self-evident on sight — never a raw timestamp a reader has to
|
|
29
|
+
* subtract by hand (#238). "A hold taken four minutes ago and one taken three hours ago are
|
|
30
|
+
* rendered identically" was the whole complaint; this is the fix, used everywhere a place-claim
|
|
31
|
+
* or a solo lock names its holder. Buckets widen as the number would otherwise get unreadable
|
|
32
|
+
* (minutes under an hour, hours under a day, days beyond) — a record observed during #238's own
|
|
33
|
+
* design was DAYS old, which is exactly the case "23847m ago" would fail to make legible.
|
|
34
|
+
*/
|
|
35
|
+
function humanAge(iso) {
|
|
36
|
+
const t = Date.parse(iso);
|
|
37
|
+
if (Number.isNaN(t)) return 'age unknown';
|
|
38
|
+
const ms = Date.now() - t;
|
|
39
|
+
if (ms < 0) return 'just now'; // clock skew — never render a negative age
|
|
40
|
+
const mins = Math.floor(ms / 60_000);
|
|
41
|
+
if (mins < 1) return 'just now';
|
|
42
|
+
if (mins < 60) return `${mins}m ago`;
|
|
43
|
+
const hours = Math.floor(mins / 60);
|
|
44
|
+
if (hours < 24) return `${hours}h ago`;
|
|
45
|
+
const days = Math.floor(hours / 24);
|
|
46
|
+
return `${days}d ago`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Tiny arg parser.
|
|
51
|
+
* spec.flags : { '--json': 'json', '--force': 'force' } boolean flags
|
|
52
|
+
* spec.values : { '--repo': 'repo', '--count': 'count' } flags that take a value
|
|
53
|
+
* spec.aliases : { '--issue': '--issues' } map an alias to its canonical flag
|
|
54
|
+
* Positionals collected into result._ .
|
|
55
|
+
*/
|
|
56
|
+
function parseArgs(argv, spec = {}) {
|
|
57
|
+
const flags = spec.flags || {};
|
|
58
|
+
const values = spec.values || {};
|
|
59
|
+
const aliases = spec.aliases || {};
|
|
60
|
+
const out = { _: [] };
|
|
61
|
+
for (let i = 0; i < argv.length; i++) {
|
|
62
|
+
let a = argv[i];
|
|
63
|
+
if (aliases[a]) a = aliases[a];
|
|
64
|
+
// support --key=value
|
|
65
|
+
let inlineVal = null;
|
|
66
|
+
const eq = a.indexOf('=');
|
|
67
|
+
if (a.startsWith('--') && eq !== -1) { inlineVal = a.slice(eq + 1); a = a.slice(0, eq); }
|
|
68
|
+
if (flags[a]) { out[flags[a]] = true; }
|
|
69
|
+
else if (values[a]) {
|
|
70
|
+
const v = inlineVal !== null ? inlineVal : argv[++i];
|
|
71
|
+
if (v === undefined) throw new UserError(`Option ${a} needs a value`);
|
|
72
|
+
out[values[a]] = v;
|
|
73
|
+
} else if (a.startsWith('-') && a !== '-') {
|
|
74
|
+
throw new UserError(`Unknown option: ${a}`);
|
|
75
|
+
} else {
|
|
76
|
+
out._.push(a);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- pretty printing ----
|
|
83
|
+
function table(rows, headers) {
|
|
84
|
+
const cols = headers.length;
|
|
85
|
+
const widths = headers.map((h, i) =>
|
|
86
|
+
Math.max(h.length, ...rows.map((r) => String(r[i] ?? '').length)));
|
|
87
|
+
const fmt = (r) => r.map((c, i) => String(c ?? '').padEnd(widths[i])).join(' ');
|
|
88
|
+
const out = [fmt(headers), fmt(widths.map((w) => '-'.repeat(w)))];
|
|
89
|
+
for (const r of rows) out.push(fmt(r));
|
|
90
|
+
return out.join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function shortRepo(repoAbs) { return path.basename(repoAbs); }
|
|
94
|
+
|
|
95
|
+
module.exports = {
|
|
96
|
+
HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
|
|
97
|
+
parseArgs, table, shortRepo,
|
|
98
|
+
};
|