@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,430 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* journal.js — OPTIONAL, machine-local record of what colab actually did.
|
|
4
|
+
*
|
|
5
|
+
* Set `journal: true` in ~/.colab/config.json and colab appends one JSON object per line to
|
|
6
|
+
* ~/.colab/journal.jsonl (COLAB_HOME-aware, like every other artifact). Leave it unset — the
|
|
7
|
+
* default — and this module writes nothing, creates nothing, and touches no path at all. That
|
|
8
|
+
* silence is absolute and is the property the test suite scores first.
|
|
9
|
+
*
|
|
10
|
+
* ── Why this exists ───────────────────────────────────────────────────────────────────────────
|
|
11
|
+
* state.json is the CURRENT truth and only that: it is mutated in place, and a record is DELETED
|
|
12
|
+
* rather than retired. So the single number worth having — how long a thing lived — is destroyed at
|
|
13
|
+
* the exact moment it becomes knowable, because the record being deleted is the only thing that
|
|
14
|
+
* still carries `created`. This module reads that number one instruction before it is lost, which
|
|
15
|
+
* is why `livedMs` costs no new bookkeeping anywhere in the CLI.
|
|
16
|
+
*
|
|
17
|
+
* ── Append-only, and unable to corrupt state ──────────────────────────────────────────────────
|
|
18
|
+
* The journal is a separate file opened in append mode. It never reads, writes, locks or parses
|
|
19
|
+
* state.json. The one hook inside the state critical section (see state.mutate) computes a diff and
|
|
20
|
+
* nothing else; the write itself happens AFTER the lock is released, so a slow or failing journal
|
|
21
|
+
* can neither hold the lock nor fail a mutation. Every entry point here is wrapped so that an
|
|
22
|
+
* exception is swallowed: observability that can break what it observes is a bad trade, and that
|
|
23
|
+
* is the same argument that kept this feature out of repo hooks in the first place.
|
|
24
|
+
*
|
|
25
|
+
* ── The kind vocabulary is OURS, and it is not notify.js's ────────────────────────────────────
|
|
26
|
+
* lib/notify.js has ACTION_KIND: a deliberately CLOSED map owned by an external receiver, which
|
|
27
|
+
* answers 400 to anything it does not recognise. It is not widened here. This file needs kinds that
|
|
28
|
+
* receiver never agreed to (port churn, a status transition, an invocation, a truncation), and
|
|
29
|
+
* borrowing its names would either force a change on a contract we do not own or produce two
|
|
30
|
+
* vocabularies quietly sharing strings. They are separate on purpose. Reusing notify's CALL SITES
|
|
31
|
+
* is fine and we do; depending on its DELIVERY is not, and we do not — nothing here goes near a
|
|
32
|
+
* socket, and a journal line is written whether or not any observer is configured.
|
|
33
|
+
*
|
|
34
|
+
* ── Naming ────────────────────────────────────────────────────────────────────────────────────
|
|
35
|
+
* "Journal" is overloaded in this repo's docs: tools/README.md uses it for what a webhook RECEIVER
|
|
36
|
+
* keeps on the other side of `notifyUrl`. That one is remote, someone else's, and may never receive
|
|
37
|
+
* an event at all. This one is local, ours, and never leaves the machine. The docs disambiguate
|
|
38
|
+
* both senses explicitly; do not let them merge.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
const fs = require('fs');
|
|
42
|
+
const os = require('os');
|
|
43
|
+
const path = require('path');
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolved independently rather than imported from state.js, which requires THIS module — a cycle
|
|
47
|
+
* would leave one of the two holding a half-built exports object depending on load order. It is one
|
|
48
|
+
* line of duplication against a class of bug that only appears at require time. Must stay identical
|
|
49
|
+
* to state.js's COLAB_DIR, including the COLAB_HOME override.
|
|
50
|
+
*/
|
|
51
|
+
const COLAB_DIR = process.env.COLAB_HOME || path.join(os.homedir(), '.colab');
|
|
52
|
+
const JOURNAL_FILE = path.join(COLAB_DIR, 'journal.jsonl');
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Size cap, enforced by truncation on first write of a process (see capFile).
|
|
56
|
+
*
|
|
57
|
+
* A full rotation scheme (numbered files, an index, a compactor) is more machinery than an opt-in
|
|
58
|
+
* local file justifies, and every part of it is another thing that can fail inside a command doing
|
|
59
|
+
* real work. A cap that drops the OLDEST lines is the cheapest answer that is still honest: recent
|
|
60
|
+
* history is what gets queried, and the drop is itself recorded (`journal.truncated`) so the file
|
|
61
|
+
* never silently claims to be complete. 5 MiB is ~20k typical lines.
|
|
62
|
+
*/
|
|
63
|
+
const MAX_BYTES = 5 * 1024 * 1024;
|
|
64
|
+
/** Fraction of the cap kept when truncating. Keeping only a sliver would truncate constantly. */
|
|
65
|
+
const KEEP_RATIO = 0.5;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Our kinds. Frozen for the same reason notify.js freezes its own: a fact with two spellings makes
|
|
69
|
+
* every count that groups by kind quietly half-right, and the whole point of this file is counting.
|
|
70
|
+
*/
|
|
71
|
+
const KIND = Object.freeze({
|
|
72
|
+
INVOKED: 'colab.invoked',
|
|
73
|
+
WORKTREE_CREATED: 'worktree.created',
|
|
74
|
+
WORKTREE_CHANGED: 'worktree.changed',
|
|
75
|
+
WORKTREE_REMOVED: 'worktree.removed',
|
|
76
|
+
CLAIM_CREATED: 'claim.created',
|
|
77
|
+
CLAIM_CHANGED: 'claim.changed',
|
|
78
|
+
CLAIM_REMOVED: 'claim.removed',
|
|
79
|
+
PORT_ALLOCATED: 'port.allocated',
|
|
80
|
+
PORT_FREED: 'port.freed',
|
|
81
|
+
TRUNCATED: 'journal.truncated',
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
/** The three state collections, and the record fields worth carrying into the journal. */
|
|
85
|
+
const SECTIONS = Object.freeze([
|
|
86
|
+
{ key: 'worktrees', created: KIND.WORKTREE_CREATED, changed: KIND.WORKTREE_CHANGED, removed: KIND.WORKTREE_REMOVED,
|
|
87
|
+
fields: ['repo', 'branch', 'base', 'ports', 'host', 'session', 'sessionName', 'status'] },
|
|
88
|
+
{ key: 'claims', created: KIND.CLAIM_CREATED, changed: KIND.CLAIM_CHANGED, removed: KIND.CLAIM_REMOVED,
|
|
89
|
+
fields: ['issue', 'repo', 'worktree', 'branch', 'host', 'session', 'sessionName'] },
|
|
90
|
+
{ key: 'ports', created: KIND.PORT_ALLOCATED, changed: null, removed: KIND.PORT_FREED,
|
|
91
|
+
fields: ['port', 'owner', 'host'] },
|
|
92
|
+
]);
|
|
93
|
+
|
|
94
|
+
// ─────────────────────────────────────────────────────────────── enablement
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Enabled ONLY by the boolean true. A string "true", a 1, a truthy object — all off.
|
|
98
|
+
*
|
|
99
|
+
* Strict because this is the switch between "writes nothing, ever" and "grows a file". A config
|
|
100
|
+
* typo must fall on the side that surprises nobody, and `journal: true` is the one documented form.
|
|
101
|
+
*/
|
|
102
|
+
function enabled(cfg) {
|
|
103
|
+
return !!cfg && cfg.journal === true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Per-process config cache. mutate() runs many times per invocation and would otherwise re-read
|
|
108
|
+
* config.json each time. Read lazily: a process that never journals never opens the file.
|
|
109
|
+
*/
|
|
110
|
+
let _cfg;
|
|
111
|
+
let _cfgRead = false;
|
|
112
|
+
function config() {
|
|
113
|
+
if (_cfgRead) return _cfg;
|
|
114
|
+
_cfgRead = true;
|
|
115
|
+
try {
|
|
116
|
+
_cfg = JSON.parse(fs.readFileSync(path.join(COLAB_DIR, 'config.json'), 'utf8'));
|
|
117
|
+
} catch (_) {
|
|
118
|
+
_cfg = null; // absent or unparseable config = disabled, exactly like an unset key
|
|
119
|
+
}
|
|
120
|
+
return _cfg;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** True when this process should journal. The single gate every entry point checks first. */
|
|
124
|
+
function on() {
|
|
125
|
+
return enabled(config());
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Test seam: forget the cached config (and the once-per-process cap check). */
|
|
129
|
+
function _resetForTests() {
|
|
130
|
+
_cfg = undefined;
|
|
131
|
+
_cfgRead = false;
|
|
132
|
+
_capped = false;
|
|
133
|
+
_repo = null;
|
|
134
|
+
_cmd = undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ─────────────────────────────────────────────────────────────── writing
|
|
138
|
+
|
|
139
|
+
let _capped = false;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Enforce MAX_BYTES once per process, before the first append.
|
|
143
|
+
*
|
|
144
|
+
* Reads the whole file only when it is already over the cap — the common path is a single stat.
|
|
145
|
+
* The kept tail is cut at a newline so the first surviving line is never half a JSON object; a
|
|
146
|
+
* reader that hits a truncated line would drop a whole record for no reason.
|
|
147
|
+
*/
|
|
148
|
+
function capFile() {
|
|
149
|
+
if (_capped) return;
|
|
150
|
+
_capped = true;
|
|
151
|
+
let size;
|
|
152
|
+
try {
|
|
153
|
+
size = fs.statSync(JOURNAL_FILE).size;
|
|
154
|
+
} catch (_) {
|
|
155
|
+
return; // no file yet — nothing to cap
|
|
156
|
+
}
|
|
157
|
+
if (size <= MAX_BYTES) return;
|
|
158
|
+
const keep = Math.floor(MAX_BYTES * KEEP_RATIO);
|
|
159
|
+
const buf = fs.readFileSync(JOURNAL_FILE);
|
|
160
|
+
let cut = buf.length - keep;
|
|
161
|
+
const nl = buf.indexOf(0x0a, cut);
|
|
162
|
+
cut = nl === -1 ? buf.length : nl + 1;
|
|
163
|
+
const dropped = cut;
|
|
164
|
+
const tmp = `${JOURNAL_FILE}.tmp.${process.pid}.${Date.now()}`;
|
|
165
|
+
fs.writeFileSync(tmp, buf.subarray(cut));
|
|
166
|
+
fs.renameSync(tmp, JOURNAL_FILE);
|
|
167
|
+
// Record the loss in the file itself, so a count taken from it can never mistake a truncated
|
|
168
|
+
// history for a complete one.
|
|
169
|
+
fs.appendFileSync(JOURNAL_FILE, JSON.stringify({
|
|
170
|
+
kind: KIND.TRUNCATED, ts: new Date().toISOString(), droppedBytes: dropped, capBytes: MAX_BYTES,
|
|
171
|
+
}) + '\n');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Append records. No-op — and no filesystem call whatsoever — when disabled.
|
|
176
|
+
*
|
|
177
|
+
* Never throws: a full disk, a read-only COLAB_HOME or a vanished directory must not turn a command
|
|
178
|
+
* that already did its work into a failure.
|
|
179
|
+
*
|
|
180
|
+
* @param {object[]} records
|
|
181
|
+
* @returns {number} how many lines were written (0 when off; for tests)
|
|
182
|
+
*/
|
|
183
|
+
function append(records) {
|
|
184
|
+
if (!records || records.length === 0) return 0;
|
|
185
|
+
if (!on()) return 0;
|
|
186
|
+
try {
|
|
187
|
+
fs.mkdirSync(COLAB_DIR, { recursive: true });
|
|
188
|
+
capFile();
|
|
189
|
+
let out = '';
|
|
190
|
+
for (const r of records) out += JSON.stringify(r) + '\n';
|
|
191
|
+
fs.appendFileSync(JOURNAL_FILE, out);
|
|
192
|
+
return records.length;
|
|
193
|
+
} catch (_) {
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ─────────────────────────────────────────────────────────────── state diff
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Copy the fields we journal out of a live state object.
|
|
202
|
+
*
|
|
203
|
+
* Called INSIDE the state lock, twice per mutation, so it stays shallow and allocation-light: a
|
|
204
|
+
* deep clone of state on every claim would be a real cost paid for nothing. Shallow is sufficient
|
|
205
|
+
* because every field read afterwards is a scalar or an array we only stringify.
|
|
206
|
+
*
|
|
207
|
+
* Returns null when journalling is off, which is what makes the disabled path free — state.mutate
|
|
208
|
+
* skips the whole diff on a null.
|
|
209
|
+
*/
|
|
210
|
+
function snapshot(st) {
|
|
211
|
+
if (!on() || !st) return null;
|
|
212
|
+
const snap = {};
|
|
213
|
+
for (const s of SECTIONS) {
|
|
214
|
+
const src = st[s.key] || {};
|
|
215
|
+
const dst = {};
|
|
216
|
+
for (const k of Object.keys(src)) {
|
|
217
|
+
const rec = src[k] || {};
|
|
218
|
+
const kept = { created: rec.created };
|
|
219
|
+
for (const f of s.fields) if (rec[f] !== undefined) kept[f] = rec[f];
|
|
220
|
+
dst[k] = kept;
|
|
221
|
+
}
|
|
222
|
+
snap[s.key] = dst;
|
|
223
|
+
}
|
|
224
|
+
return snap;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Elapsed ms between an ISO `created` and `now`, or undefined when unusable. */
|
|
228
|
+
function lifespan(created, now) {
|
|
229
|
+
if (!created) return undefined;
|
|
230
|
+
const t = Date.parse(created);
|
|
231
|
+
if (!Number.isFinite(t)) return undefined;
|
|
232
|
+
const ms = now - t;
|
|
233
|
+
// A negative lifespan means a clock moved, not that the record lived backwards. Drop it rather
|
|
234
|
+
// than emit a number an aggregate would happily average in.
|
|
235
|
+
return ms >= 0 ? ms : undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Fields that changed between two snapshots of one record, as {field: [before, after]}. */
|
|
239
|
+
function changedFields(before, after) {
|
|
240
|
+
const out = {};
|
|
241
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
242
|
+
for (const k of keys) {
|
|
243
|
+
if (k === 'created') continue;
|
|
244
|
+
const a = before[k], b = after[k];
|
|
245
|
+
if (JSON.stringify(a) === JSON.stringify(b)) continue;
|
|
246
|
+
out[k] = [a === undefined ? null : a, b === undefined ? null : b];
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Diff two snapshots into journal records. PURE — no I/O, no clock of its own — so every shape
|
|
253
|
+
* below is testable without a filesystem, which is how the acceptance queries are scored.
|
|
254
|
+
*
|
|
255
|
+
* `livedMs` on a removal is the reason this function exists. `created` is on the record being
|
|
256
|
+
* destroyed, so the subtraction is available exactly once: here, or never.
|
|
257
|
+
*
|
|
258
|
+
* @param {object|null} before snapshot()
|
|
259
|
+
* @param {object|null} after snapshot()
|
|
260
|
+
* @param {number} now Date.now() (injected so tests are deterministic)
|
|
261
|
+
* @param {object} [ctx] extra fields stamped on every record (e.g. {cmd:'worktree rm'})
|
|
262
|
+
*/
|
|
263
|
+
function diff(before, after, now, ctx) {
|
|
264
|
+
if (!before || !after) return [];
|
|
265
|
+
const ts = new Date(now).toISOString();
|
|
266
|
+
const out = [];
|
|
267
|
+
const base = ctx || {};
|
|
268
|
+
for (const s of SECTIONS) {
|
|
269
|
+
const b = before[s.key] || {};
|
|
270
|
+
const a = after[s.key] || {};
|
|
271
|
+
for (const k of Object.keys(a)) {
|
|
272
|
+
if (k in b) {
|
|
273
|
+
if (!s.changed) continue;
|
|
274
|
+
const ch = changedFields(b[k], a[k]);
|
|
275
|
+
if (Object.keys(ch).length === 0) continue;
|
|
276
|
+
out.push({ kind: s.changed, ts, ...base, name: k, repo: a[k].repo, changed: ch,
|
|
277
|
+
ageMs: lifespan(a[k].created, now) });
|
|
278
|
+
} else {
|
|
279
|
+
out.push({ kind: s.created, ts, ...base, name: k, ...strip(a[k]) });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for (const k of Object.keys(b)) {
|
|
283
|
+
if (k in a) continue;
|
|
284
|
+
out.push({ kind: s.removed, ts, ...base, name: k, ...strip(b[k]),
|
|
285
|
+
livedMs: lifespan(b[k].created, now) });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Record fields for a line, minus `created` (an ISO string the ts/livedMs pair already covers). */
|
|
292
|
+
function strip(rec) {
|
|
293
|
+
const out = {};
|
|
294
|
+
for (const k of Object.keys(rec)) {
|
|
295
|
+
if (k === 'created' || rec[k] === undefined) continue;
|
|
296
|
+
out[k] = rec[k];
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ─────────────────────────────────────────────────────────────── invocation
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Repo attribution for the invocation record. Set from a state diff when one is available (that
|
|
305
|
+
* path knows the canonical MAIN repo root), otherwise guessed from cwd.
|
|
306
|
+
*/
|
|
307
|
+
let _repo = null;
|
|
308
|
+
function noteRepo(repo) {
|
|
309
|
+
if (!_repo && repo) _repo = String(repo);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The command each state record is attributed to. Set once by the CLI; absent when this module is
|
|
314
|
+
* used as a library. Without it a `worktree.removed` line cannot say whether it came from
|
|
315
|
+
* `worktree rm`, `ship` or `doctor --prune` — three very different facts that state cannot tell
|
|
316
|
+
* apart afterwards, because the record is gone either way.
|
|
317
|
+
*/
|
|
318
|
+
let _cmd;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Commands that are containers for a sub-command. For these the sub-command is the fact worth
|
|
322
|
+
* having: `worktree new` and `worktree rm` are opposites, and recording both as "worktree" makes
|
|
323
|
+
* the creation/teardown split — the whole lifespan story — unrecoverable from the file.
|
|
324
|
+
*
|
|
325
|
+
* The list is explicit rather than "take argv[1] when it isn't a flag", because for `claim 115`
|
|
326
|
+
* argv[1] is an issue number and every claim would then be its own distinct command name.
|
|
327
|
+
*/
|
|
328
|
+
const SUBCOMMANDED = Object.freeze(['worktree', 'port', 'config']);
|
|
329
|
+
|
|
330
|
+
/** Derive the command label from argv. Exported for the test that pins the two cases apart. */
|
|
331
|
+
function cmdOf(argv) {
|
|
332
|
+
const a = (argv || []).map(String);
|
|
333
|
+
if (!a.length) return undefined;
|
|
334
|
+
if (SUBCOMMANDED.includes(a[0]) && a[1] && !a[1].startsWith('-')) return `${a[0]} ${a[1]}`;
|
|
335
|
+
return a[0];
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function setCmd(argv) { _cmd = cmdOf(argv); }
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* diff() with the clock and the per-process context supplied — the form state.mutate calls, and
|
|
342
|
+
* the only one that reads a wall clock. Kept separate so diff() itself stays pure and testable.
|
|
343
|
+
*/
|
|
344
|
+
function recordDiff(before, after) {
|
|
345
|
+
const recs = diff(before, after, Date.now(), _cmd ? { cmd: _cmd } : {});
|
|
346
|
+
// A state record names the canonical MAIN repo root; the cwd guess used by invoked() does not
|
|
347
|
+
// always. Prefer this one when the invocation touched state at all.
|
|
348
|
+
for (const r of recs) if (r.repo) { noteRepo(r.repo); break; }
|
|
349
|
+
return recs;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Nearest repo root above `dir`, resolved with plain fs and NO subprocess.
|
|
354
|
+
*
|
|
355
|
+
* `git rev-parse` would be authoritative but costs a process spawn on every invocation, which is
|
|
356
|
+
* precisely the kind of tax an optional feature must not levy. Walking up for `.git` is a few
|
|
357
|
+
* stats. A LINKED WORKTREE's `.git` is a FILE (`gitdir: <main>/.git/worktrees/<n>`), so it is read
|
|
358
|
+
* and followed — a worktree that reported itself as its own repo would split one repo's totals in
|
|
359
|
+
* two, which is exactly the count the acceptance criteria ask for.
|
|
360
|
+
*/
|
|
361
|
+
function repoRootOf(dir) {
|
|
362
|
+
try {
|
|
363
|
+
let cur = path.resolve(dir);
|
|
364
|
+
for (let i = 0; i < 64; i++) {
|
|
365
|
+
const dot = path.join(cur, '.git');
|
|
366
|
+
let stat;
|
|
367
|
+
try { stat = fs.statSync(dot); } catch (_) { stat = null; }
|
|
368
|
+
if (stat && stat.isDirectory()) return cur;
|
|
369
|
+
if (stat && stat.isFile()) {
|
|
370
|
+
const m = /gitdir:\s*(.+)/.exec(fs.readFileSync(dot, 'utf8'));
|
|
371
|
+
if (!m) return cur;
|
|
372
|
+
const gitdir = path.resolve(cur, m[1].trim());
|
|
373
|
+
const marker = `${path.sep}.git${path.sep}worktrees${path.sep}`;
|
|
374
|
+
const at = gitdir.indexOf(marker);
|
|
375
|
+
return at === -1 ? cur : gitdir.slice(0, at);
|
|
376
|
+
}
|
|
377
|
+
const up = path.dirname(cur);
|
|
378
|
+
if (up === cur) break;
|
|
379
|
+
cur = up;
|
|
380
|
+
}
|
|
381
|
+
} catch (_) { /* fall through */ }
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* argv as recorded. One value is dropped: `config set <key> <value>`.
|
|
387
|
+
*
|
|
388
|
+
* The value can be a URL with a token in it (`notifyUrl`), and a local file that quietly accumulates
|
|
389
|
+
* credentials is a worse problem than the one this feature solves. The KEY is kept, so "who changed
|
|
390
|
+
* config and when" still answers; only the secret-shaped half goes.
|
|
391
|
+
*/
|
|
392
|
+
function safeArgv(argv) {
|
|
393
|
+
const a = (argv || []).map(String);
|
|
394
|
+
if (a[0] === 'config' && a[1] === 'set' && a.length > 3) return [...a.slice(0, 3), '<redacted>'];
|
|
395
|
+
return a;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* One record per CLI invocation: what was run, how it ended, how long it took.
|
|
400
|
+
*
|
|
401
|
+
* `durationMs` is wall clock for the whole process as seen from main(), which is the number that
|
|
402
|
+
* answers "where does time go" at the granularity v1 offers. Per-STEP timing inside ship is
|
|
403
|
+
* deliberately not here: it is the only part of this feature that is not free, since it means
|
|
404
|
+
* editing the ship path itself, and putting new code on the path that merges work is a poor trade
|
|
405
|
+
* for a first version. Invocation totals plus lifespans answer every acceptance question without it.
|
|
406
|
+
*/
|
|
407
|
+
function invoked({ argv, exit, durationMs, cwd, error } = {}) {
|
|
408
|
+
if (!on()) return 0;
|
|
409
|
+
const a = safeArgv(argv);
|
|
410
|
+
const rec = {
|
|
411
|
+
kind: KIND.INVOKED,
|
|
412
|
+
ts: new Date().toISOString(),
|
|
413
|
+
cmd: cmdOf(a) || '(none)',
|
|
414
|
+
argv: a,
|
|
415
|
+
exit: Number.isInteger(exit) ? exit : 0,
|
|
416
|
+
durationMs: Number.isFinite(durationMs) ? durationMs : undefined,
|
|
417
|
+
repo: _repo || repoRootOf(cwd || process.cwd()) || undefined,
|
|
418
|
+
cwd: cwd || process.cwd(),
|
|
419
|
+
pid: process.pid,
|
|
420
|
+
};
|
|
421
|
+
if (error) rec.error = String(error).split('\n')[0].slice(0, 300);
|
|
422
|
+
for (const k of Object.keys(rec)) if (rec[k] === undefined) delete rec[k];
|
|
423
|
+
return append([rec]);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
module.exports = {
|
|
427
|
+
COLAB_DIR, JOURNAL_FILE, MAX_BYTES, KIND, SECTIONS,
|
|
428
|
+
enabled, on, snapshot, diff, recordDiff, append, invoked, noteRepo, setCmd, cmdOf, repoRootOf, safeArgv,
|
|
429
|
+
lifespan, changedFields, _resetForTests,
|
|
430
|
+
};
|