@futurelastic/colab-handbook 1.13.0-rc.27 → 1.13.0-rc.28

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/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.13.0-rc.27"
36
+ "version": "1.13.0-rc.28"
37
37
  }
package/tools/colab CHANGED
@@ -68,6 +68,7 @@ const shipBatch = require('./lib/ship-batch');
68
68
  const batchStats = require('./lib/batch-stats');
69
69
  const conflictMarkers = require('./lib/conflict-markers');
70
70
  const docsOnly = require('./lib/docs-only');
71
+ const configSet = require('./lib/config-set'); // #561
71
72
  const cureDiff = require('./lib/cure-diff');
72
73
  const codeowners = require('./lib/codeowners');
73
74
  const releasePolicy = require('./lib/release-policy');
@@ -7657,6 +7658,10 @@ const HELP_CONFIG = `colab config [show|add-repo <path>|rm-repo <path>|add-reser
7657
7658
  rm-notify-url <url> remove one receiver from notifyUrl; removing the last unsets the key
7658
7659
  set <key> <value> set claimTTLHours | plannerClaimTTLMinutes | portRange | worktreeSubdir | notifyUrl | journal |
7659
7660
  claimIdentity
7661
+ set <tuning-key> <value> --evidence "<why>"
7662
+ a kebab-case key is this REPO's .github/project.yml, not this machine (#561):
7663
+ one tuning value, committed on a short branch, shippable with no issue —
7664
+ see: colab config set ship-batch --help
7660
7665
 
7661
7666
  notifyUrl is OPTIONAL and off by default: unset, colab makes no network call of its own. Set it to
7662
7667
  an http(s) endpoint and claim / release / ship / worktree new / worktree rm each push one small
@@ -7684,6 +7689,91 @@ changes on resume makes that session's own earlier claim comment read as a diffe
7684
7689
  it will yield to itself. Unset it again with: colab config set claimIdentity ""
7685
7690
  `;
7686
7691
 
7692
+ // config set <tuning-key> (#561) — one TUNING value of this repo's .github/project.yml, committed on
7693
+ // a short branch without touching any checkout, shippable by `colab ship` with no issue.
7694
+ const HELP_CONFIG_SET_DESCRIPTOR = `colab config set <tuning-key> <value> --evidence "<why>" [--repo <path>] [--no-push] [--dry]
7695
+
7696
+ Change ONE tuning value of this repo's .github/project.yml (#561). Tuning keys:
7697
+ ${configSet.TUNING_KEYS.filter((k) => k !== 'thresholds').join(', ')}, thresholds.<name>
7698
+
7699
+ The value is validated by the parser every reader of that key uses (the same verdict \`colab ship\`
7700
+ computes), then committed on top of a freshly fetched <remote>/<trunk> as branch
7701
+ chore/tune-<key> — with no checkout touched and no issue. The subject is
7702
+ \`chore(project): <key> <old> → <new>\`; --evidence (required) goes in the body, which the squash
7703
+ carries, so the reason for the number lives in trunk's history.
7704
+
7705
+ Then: wait for the branch's CI (\`colab ci-wait --sha <sha> --branch <branch>\`) and
7706
+ \`colab ship --branch <branch>\`. Ship computes the TUNING-ONLY class from the diff — it is never
7707
+ asserted — and, like docs-only (#345), it opens the autonomy gate on a repo without auto-trunk.
7708
+ Every other precondition still applies.
7709
+
7710
+ Never on this path (they grant authority or change what deploys): ${configSet.AUTHORITY_KEYS.join(', ')}.
7711
+
7712
+ --evidence <text> the measurement behind the number (required)
7713
+ --no-push create the branch locally only
7714
+ --dry print the edit and the verdict; create nothing`;
7715
+
7716
+ function cmdConfigSetDescriptor(argv) {
7717
+ const opts = parseArgs(argv, {
7718
+ values: { '--repo': 'repo', '--evidence': 'evidence' },
7719
+ flags: { '--no-push': 'noPush', '--dry': 'dry', '-h': 'help', '--help': 'help' },
7720
+ });
7721
+ if (opts.help) return print(HELP_CONFIG_SET_DESCRIPTOR);
7722
+ const [key, value] = opts._ || [];
7723
+ if (!key || value === undefined) throw new UserError('config set needs <tuning-key> <value> — see: colab config set ship-batch --help');
7724
+ const kp = configSet.parseKeyPath(key);
7725
+ if (kp.problem) throw new UserError(kp.problem);
7726
+ if (!opts.dry && !String(opts.evidence || '').trim()) {
7727
+ throw new UserError('--evidence "<why>" is required — the measurement behind the number goes in the commit body (#561); re-run with --evidence "<what you measured>"');
7728
+ }
7729
+ const repoAbs = resolveRepo(opts);
7730
+ const trunk = resolveTrunk(repoAbs, projectDoc(repoAbs));
7731
+ if (!trunk) throw new UserError('could not determine trunk — add `trunk:` to .github/project.yml (or run `colab adopt`), then re-run');
7732
+ const remote = git.remoteFor(repoAbs);
7733
+ const f = git.git(['fetch', remote, trunk], repoAbs);
7734
+ if (!f.ok) throw new UserError(`could not fetch ${remote}/${trunk} — nothing created (${f.stderr.split('\n')[0]}); re-run once \`git fetch ${remote} ${trunk}\` succeeds`);
7735
+ const baseRef = `${remote}/${trunk}`;
7736
+ const baseSha = (git.git(['rev-parse', `refs/remotes/${baseRef}`], repoAbs).stdout || '').trim();
7737
+ if (!baseSha) throw new UserError(`${baseRef} does not resolve after the fetch — check \`git ls-remote ${remote} ${trunk}\` and re-run`);
7738
+ const text = configSet.descriptorAt(repoAbs, baseSha);
7739
+ if (text === null) throw new UserError(`could not read ${configSet.DESCRIPTOR} at ${baseRef} — see why with \`git show ${baseRef}:${configSet.DESCRIPTOR}\``);
7740
+ if (text === '') throw new UserError(`${baseRef} has no ${configSet.DESCRIPTOR} — adopt the handbook first: \`colab adopt\``);
7741
+ const edit = configSet.editText(text, kp, value);
7742
+ if (edit.problem) throw new UserError(edit.problem);
7743
+ const name = [kp.top, kp.sub].filter(Boolean).join('.');
7744
+ if (edit.text === text) { print(`${name} is already ${value} on ${baseRef} — nothing to change`); return 0; }
7745
+ // The SAME verdict ship will compute on this diff — so a value ship would refuse is refused here.
7746
+ const verdict = configSet.classify({
7747
+ entries: [{ path: configSet.DESCRIPTOR, oldMode: '100644', newMode: '100644', binary: false }],
7748
+ baseText: text, headText: edit.text,
7749
+ });
7750
+ if (!verdict.tuning) throw new UserError(`refused: ${verdict.reason} — pick a valid value (\`colab config set ${name} --help\`)`);
7751
+ const branch = configSet.branchName(kp);
7752
+ if (git.branchExists(repoAbs, branch, remote)) {
7753
+ throw new UserError(`branch ${branch} already exists — ship it with \`colab ship --branch ${branch}\`, or delete it with \`git push ${remote} --delete ${branch}\` and \`git branch -D ${branch}\``);
7754
+ }
7755
+ const message = configSet.commitMessage(kp, edit.old, value, opts.evidence || '(dry run)');
7756
+ print(`config set ${shortRepo(repoAbs)} · ${name}: ${edit.old === null ? '(unset)' : edit.old} → ${value}`);
7757
+ print(` verdict: ${verdict.reason}`);
7758
+ print(` branch: ${branch} (base ${baseRef} @ ${shortSha(baseSha)})`);
7759
+ if (opts.dry) { print(' [DRY RUN] nothing created.'); return 0; }
7760
+ const c = configSet.commitOnBranch(repoAbs, { baseSha, text: edit.text, message, branch });
7761
+ if (!c.ok) throw new UserError(`could not create the commit: ${c.error} — nothing was created; a human must read the git error above before re-running`);
7762
+ print(` commit: ${shortSha(c.sha)} ${message.split('\n')[0]}`);
7763
+ if (opts.noPush) {
7764
+ print(` not pushed (--no-push). Push it, wait for CI, then: colab ship --branch ${branch}`);
7765
+ return 0;
7766
+ }
7767
+ const p = git.git(['push', remote, `refs/heads/${branch}:refs/heads/${branch}`], repoAbs);
7768
+ if (!p.ok) {
7769
+ warn(`push failed — the branch exists locally only: ${p.stderr.split('\n')[0]}`);
7770
+ return 1;
7771
+ }
7772
+ print(` pushed: ${remote}/${branch}`);
7773
+ print(`Next: colab ci-wait --sha ${c.sha} --branch ${branch} && colab ship --branch ${branch}`);
7774
+ return 0;
7775
+ }
7776
+
7687
7777
  function cmdConfig(argv) {
7688
7778
  const sub = argv[0];
7689
7779
  const cfg = state.loadConfig();
@@ -7741,6 +7831,7 @@ function cmdConfig(argv) {
7741
7831
  print(`notifyUrl = ${urls.length ? urls.join(', ') : '(unset)'}`);
7742
7832
  return 0;
7743
7833
  }
7834
+ if (sub === 'set' && argv[1] && configSet.isDescriptorKey(argv[1])) return cmdConfigSetDescriptor(argv.slice(1)); // #561
7744
7835
  if (sub === 'set') {
7745
7836
  const [k, v] = [argv[1], argv[2]];
7746
7837
  if (!k || v === undefined) throw new UserError('set needs <key> <value>');
@@ -10122,6 +10213,7 @@ promotes is an integration event of the same weight as a promotion, and stays hu
10122
10213
 
10123
10214
  Sequence (each step gated; any failure aborts before the push — the target is never half-shipped):
10124
10215
  a. autonomy gate repo must grant auto-trunk (no --force override) — or the diff is docs-only (#345)
10216
+ or tuning-only (#561)
10125
10217
  — or a person runs ship through the human door (#525): a confirmed interactive
10126
10218
  terminal, or COLAB_HUMAN=1 + --answered-by <name>. An agent shell is no terminal.
10127
10219
  b. preconditions target CI alive+green (UNLESS the branch proves the CURE RULE, #281 — no
@@ -10298,6 +10390,14 @@ auto-trunk). The row reads "docs-only (N files) — autonomy exception", and --d
10298
10390
  \`autonomyGate: { via, docsOnly }\`. After B0 sync the diff is measured again before the squash.
10299
10391
  Every other precondition is unchanged. No flag, env var or project.yml field widens the list.
10300
10392
 
10393
+ TUNING-ONLY — the second computed exception (#561). Ship also proceeds without the grant when the
10394
+ diff changes .github/project.yml ALONE, every changed line inside a tuning key (ship-batch,
10395
+ ship-batch-wait, ci-wait-factor, thresholds) and every moved value valid; never with an authority
10396
+ key (autonomy, promotion, migration-grant, ci-grant, trust-humans, exposure, tier, trunk, deploy,
10397
+ release, production). It needs no issue. \`colab config set <key> <value> --evidence "<why>"\`
10398
+ writes such a branch. The row reads "tuning-only (<keys>) — autonomy exception (#561)"; --dry --json
10399
+ adds \`autonomyGate.tuning\`. Re-measured after B0 sync like docs-only.
10400
+
10301
10401
  TRUNK-DIRECT — \`colab ship --direct\` (#302). A unit committed straight to trunk has no branch and
10302
10402
  no worktree, so neither door above can find it, and evidence-close's own detection cannot fire
10303
10403
  (\`landed\` is \`unknown\` when base === branch). --direct is its close path: the claims are this
@@ -11775,7 +11875,8 @@ function cmdShipDryJson(opts) {
11775
11875
 
11776
11876
  // ---- (a) AUTONOMY GATE — does NOT short-circuit here; an unattended caller wants the whole table ----
11777
11877
  const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
11778
- humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
11878
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy), // #525
11879
+ () => configSet.branchTuning(git, repoAbs, target, shipRefFor(repoAbs, sess.branch))); // #561
11779
11880
  autonomyGatePayloadVal = autonomyGatePayload(autonomyGate);
11780
11881
  checks.push({ name: 'autonomy granted', ok: autonomyGate.ok, class: autonomyGate.ok ? null : HUMAN_GATED, detail: autonomyGate.detail });
11781
11882
 
@@ -12656,23 +12757,33 @@ function shipOpenCorePr(repoAbs, cr, { target, branch, title, body }) {
12656
12757
  * caller asserts nothing. `readDocsOnly` is a thunk, so an auto-trunk repo never pays for the
12657
12758
  * diff read. Every other precondition is untouched — this relaxes the autonomy gate, not the checks.
12658
12759
  *
12659
- * Returns `{ ok, via: 'auto-trunk'|'docs-only'|null, declared, docsOnly: verdict|null, detail }`.
12760
+ * #561 adds the TUNING-ONLY class beside it: a diff `lib/config-set.js` classifies as one or more
12761
+ * tuning keys of .github/project.yml with valid values, and nothing else. `readTuning` is a thunk
12762
+ * too, consulted only when the change is not docs-only; a branchless (trunk-direct) door passes none.
12763
+ *
12764
+ * Returns `{ ok, via: 'auto-trunk'|'docs-only'|'tuning'|'human'|null, declared, docsOnly: verdict|null,
12765
+ * tuning: verdict|null, detail }`.
12660
12766
  */
12661
- function shipAutonomyGate(doc, readDocsOnly, door = null) {
12767
+ function shipAutonomyGate(doc, readDocsOnly, door = null, readTuning = null) {
12662
12768
  const declared = doc.autonomy ? String(doc.autonomy) : 'absent';
12663
- if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, human: null, detail: 'auto-trunk' };
12769
+ if (declared === 'auto-trunk') return { ok: true, via: 'auto-trunk', declared, docsOnly: null, tuning: null, human: null, detail: 'auto-trunk' };
12664
12770
  const verdict = readDocsOnly();
12665
12771
  if (verdict.docsOnly) {
12666
- return { ok: true, via: 'docs-only', declared, docsOnly: verdict, human: null, detail: `${verdict.reason} — autonomy exception` };
12772
+ return { ok: true, via: 'docs-only', declared, docsOnly: verdict, tuning: null, human: null, detail: `${verdict.reason} — autonomy exception` };
12773
+ }
12774
+ const tuning = readTuning ? readTuning() : null;
12775
+ if (tuning && tuning.tuning) {
12776
+ return { ok: true, via: 'tuning', declared, docsOnly: verdict, tuning, human: null, detail: `${tuning.reason} — autonomy exception (#561)` };
12667
12777
  }
12668
12778
  // #525: the human door — the person running ship IS the go (ruling on #525, option 1). Checked
12669
- // after docs-only, so a docs-only change keeps its own (agent-usable) door and record.
12779
+ // after docs-only and tuning, so either keeps its own (agent-usable) door and record.
12670
12780
  if (door && door.open) {
12671
- return { ok: true, via: 'human', declared, docsOnly: verdict, human: door,
12781
+ return { ok: true, via: 'human', declared, docsOnly: verdict, tuning, human: door,
12672
12782
  detail: `human door (#525): ${door.why} — project.yml autonomy: ${declared}` };
12673
12783
  }
12674
- return { ok: false, via: null, declared, docsOnly: verdict, human: door,
12675
- detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason}; human door closed: ${door ? door.why : 'not offered'})` };
12784
+ return { ok: false, via: null, declared, docsOnly: verdict, tuning, human: door,
12785
+ detail: `project.yml autonomy: ${declared} — a human must trigger Phase B (not docs-only: ${verdict.reason}; ` +
12786
+ `${tuning ? `not tuning-only: ${tuning.reason}; ` : ''}human door closed: ${door ? door.why : 'not offered'})` };
12676
12787
  }
12677
12788
 
12678
12789
  /** #525: the human-door refusal lines — what a person runs, never just "a human must". */
@@ -12731,8 +12842,10 @@ function shipHumanDoorGo(gate, opts, what) {
12731
12842
  function autonomyGatePayload(gate) {
12732
12843
  // #525: `human` is additive and present only when the human door was consulted, so an
12733
12844
  // auto-trunk / docs-only payload stays byte-identical to before.
12734
- return gate.human ? { via: gate.via, docsOnly: gate.docsOnly, human: { open: gate.human.open, how: gate.human.how, why: gate.human.why } }
12735
- : { via: gate.via, docsOnly: gate.docsOnly };
12845
+ // #561: `tuning` likewise — present only when the tuning class was consulted.
12846
+ const base = { via: gate.via, docsOnly: gate.docsOnly };
12847
+ if (gate.tuning) base.tuning = gate.tuning;
12848
+ return gate.human ? { ...base, human: { open: gate.human.open, how: gate.human.how, why: gate.human.why } } : base;
12736
12849
  }
12737
12850
 
12738
12851
  /** The sha a branch name resolves to, local first, else origin's copy (#324's remote-only shape). */
@@ -12819,11 +12932,13 @@ function cmdShip(argv) {
12819
12932
  // ---- (a) AUTONOMY GATE — granted by the repo file, never by the caller ----
12820
12933
  // #345: …or the branch's diff is documentation only, computed here from git — never asserted.
12821
12934
  const autonomyGate = shipAutonomyGate(doc, () => docsOnly.branchChanges(git, repoAbs, target, shipRefFor(repoAbs, sess.branch)),
12822
- humanDoor.humanDoorFromProcess(process, opts.answeredBy)); // #525
12935
+ humanDoor.humanDoorFromProcess(process, opts.answeredBy), // #525
12936
+ () => configSet.branchTuning(git, repoAbs, target, shipRefFor(repoAbs, sess.branch))); // #561
12823
12937
  if (!autonomyGate.ok) {
12824
12938
  process.stderr.write(`✗ ${shortRepo(repoAbs)} does not grant auto-trunk (project.yml autonomy: ${autonomyGate.declared}).\n`);
12825
12939
  process.stderr.write(' A human must trigger Phase B. (Autonomy is granted by the repo, not by a flag — --force cannot override.)\n');
12826
12940
  process.stderr.write(` The docs-only exception (#345) does not apply either: ${autonomyGate.docsOnly.reason}.\n`);
12941
+ if (autonomyGate.tuning) process.stderr.write(` Nor the tuning-only class (#561): ${autonomyGate.tuning.reason}.\n`);
12827
12942
  process.stderr.write(shipHumanDoorRefusal(autonomyGate, shipSelector(opts, sess)));
12828
12943
  return 1;
12829
12944
  }
@@ -13316,6 +13431,14 @@ function cmdShip(argv) {
13316
13431
  return 1;
13317
13432
  }
13318
13433
  }
13434
+ if (autonomyGate.via === 'tuning') {
13435
+ const again = configSet.branchTuning(git, repoAbs, mergeRef, sess.branch);
13436
+ if (!again.tuning) {
13437
+ cleanupEphemeral();
13438
+ process.stderr.write(`✗ B1: the tuning-only class (#561) no longer holds after B0 sync — ${again.reason}. A human must trigger Phase B. Nothing pushed.\n`);
13439
+ return 1;
13440
+ }
13441
+ }
13319
13442
 
13320
13443
  // #350: B0 may have brought in paths (a pre-ship hook's regenerated files). The approval covered
13321
13444
  // the core paths the table listed; a core path it did not list was never reviewed.
@@ -0,0 +1,319 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/config-set.js — a TUNING change to `.github/project.yml`, made and shipped cheaply (#561).
4
+ *
5
+ * Before this module, changing one repo-owned value (`ship-batch: 2`, a threshold) cost an issue, a
6
+ * code session, a wrap and a ship — the same ceremony as a feature. Repos that pay that much per
7
+ * tuning step do not tune. The descriptor stays committed (CI templates read it from the commit,
8
+ * worktrees are cut from git, and authority-granting fields need their review trail), so the cost is
9
+ * cut on two sides instead:
10
+ *
11
+ * 1. `colab config set <key> <value>` writes ONE tuning key, validated by the same parser every
12
+ * reader of that key uses, and commits it on a short branch — no checkout is touched.
13
+ * 2. `colab ship` computes a TUNING-ONLY class from the diff, modelled on the docs-only door
14
+ * (tools/lib/docs-only.js): no issue, no `Closes #N`, the evidence in the commit body, every
15
+ * other precondition unchanged.
16
+ *
17
+ * The allowlist and the authority list below are constants, so widening either is a handbook change
18
+ * reviewed in a commit — never a project.yml field, a flag or an env var. Every doubt resolves to
19
+ * "not tuning": a second file, a comment line, an authority key, a malformed value, a git read that
20
+ * failed. A false "no" costs a human click; a false "yes" lands an unreviewed change.
21
+ */
22
+
23
+ const yaml = require('./yaml');
24
+ const shipBatch = require('./ship-batch');
25
+ const ciProfile = require('./ci-profile');
26
+ const thresholds = require('./thresholds');
27
+
28
+ const DESCRIPTOR = '.github/project.yml';
29
+
30
+ /**
31
+ * The tuning allowlist: key → the one validator every reader of that key already uses. Each returns
32
+ * a problem sentence, or null when the parsed descriptor's value is valid (absent counts as valid —
33
+ * removing a tuning key restores the documented default).
34
+ */
35
+ const TUNING = Object.freeze({
36
+ 'ship-batch': (doc) => { const r = shipBatch.parseShipBatch(doc); return r.valid ? null : r.reason; },
37
+ 'ship-batch-wait': (doc) => { const r = shipBatch.parseShipBatchWait(doc); return r.valid ? null : r.reason; },
38
+ 'ci-wait-factor': (doc) => { const r = ciProfile.parseFactor(doc); return r.valid ? null : r.reason; },
39
+ [thresholds.KEY]: (doc) => { const r = thresholds.parseThresholds(doc); return r.problems.length ? r.problems.join('; ') : null; },
40
+ });
41
+ const TUNING_KEYS = Object.freeze(Object.keys(TUNING));
42
+
43
+ /**
44
+ * Never on this path: these grant authority or change what deploys (#561 §4). Listed so `config set`
45
+ * can say WHY it refuses them; any key outside TUNING is refused all the same.
46
+ */
47
+ const AUTHORITY_KEYS = Object.freeze([
48
+ 'autonomy', 'promotion', 'migration-grant', 'ci-grant', 'trust-humans',
49
+ 'exposure', 'tier', 'trunk', 'deploy', 'release', 'production',
50
+ ]);
51
+
52
+ /** A value is a plain YAML scalar — every tuning value is one (`2`, `6m`, `1.5`). */
53
+ const VALUE_RE = /^[A-Za-z0-9._-]+$/;
54
+
55
+ /**
56
+ * `ship-batch` → `{ top: 'ship-batch', sub: null }`; `thresholds.hot-file-count` → `{ top:
57
+ * 'thresholds', sub: 'hot-file-count' }`. Returns `{ problem }` for anything outside the allowlist.
58
+ */
59
+ function parseKeyPath(arg) {
60
+ const s = String(arg || '').trim();
61
+ const dot = s.indexOf('.');
62
+ const top = dot < 0 ? s : s.slice(0, dot);
63
+ const sub = dot < 0 ? null : s.slice(dot + 1);
64
+ if (AUTHORITY_KEYS.includes(top)) {
65
+ return { problem: `${top} grants authority or changes what deploys — it is never a tuning change; edit it on a branch with an issue and ship it the full way (#561)` };
66
+ }
67
+ if (!TUNING[top]) return { problem: `${s} is not a tuning key (tuning keys: ${TUNING_KEYS.join(', ')}, thresholds.<name>)` };
68
+ if (top === thresholds.KEY) {
69
+ if (!sub) return { problem: `${top} is a map — set one entry: ${top}.<name> (names: ${Object.keys(thresholds.SPEC).join(', ')})` };
70
+ if (!thresholds.SPEC[sub]) return { problem: `${top}.${sub} is not a known threshold (known: ${Object.keys(thresholds.SPEC).join(', ')})` };
71
+ } else if (sub !== null) {
72
+ return { problem: `${top} is a scalar — set it as ${top}, not ${s}` };
73
+ }
74
+ return { top, sub };
75
+ }
76
+
77
+ const isTopKeyLine = (line) => /^[^\s#][^:]*:/.test(line);
78
+ const topKeyOf = (line) => (isTopKeyLine(line) ? line.slice(0, line.indexOf(':')).trim() : null);
79
+
80
+ /** Replace a `key: value # comment` line's value, keeping the indent and the trailing comment. */
81
+ function replaceValue(line, value) {
82
+ const m = /^(\s*[^:#]+:)([ \t]*)([^#]*?)([ \t]*#.*)?$/.exec(line);
83
+ if (!m) return null;
84
+ return `${m[1]} ${value}${m[4] || ''}`;
85
+ }
86
+
87
+ /**
88
+ * Edit ONE tuning key in the descriptor's text, leaving every other byte alone. Returns `{ text,
89
+ * old }` (`old` is the previous raw value, or null when the key was absent), or `{ problem }`.
90
+ */
91
+ function editText(text, keyPath, value) {
92
+ if (!VALUE_RE.test(String(value))) return { problem: `value ${JSON.stringify(value)} is not a plain scalar (letters, digits, . _ -)` };
93
+ const src = String(text);
94
+ const eol = src.endsWith('\n') ? '' : '\n';
95
+ const lines = src.split('\n');
96
+ if (lines[lines.length - 1] === '') lines.pop();
97
+ const topIdx = lines.findIndex((l) => topKeyOf(l) === keyPath.top);
98
+ const blockEnd = (start) => { let j = start + 1; while (j < lines.length && !isTopKeyLine(lines[j]) && !/^#/.test(lines[j])) j++; return j; };
99
+ const restOf = (l) => l.slice(l.indexOf(':') + 1).replace(/[ \t]#.*$/, '').trim();
100
+
101
+ if (!keyPath.sub) {
102
+ if (topIdx < 0) return { text: `${src}${eol}${keyPath.top}: ${value}\n`, old: null };
103
+ const rest = restOf(lines[topIdx]);
104
+ if (rest === '' && blockEnd(topIdx) > topIdx + 1 && lines.slice(topIdx + 1, blockEnd(topIdx)).some((l) => l.trim() && !l.trim().startsWith('#'))) {
105
+ return { problem: `${keyPath.top} is written as a block in ${DESCRIPTOR} — edit it by hand` };
106
+ }
107
+ lines[topIdx] = replaceValue(lines[topIdx], value);
108
+ return { text: lines.join('\n') + '\n', old: rest === '' ? null : rest };
109
+ }
110
+
111
+ if (topIdx < 0) return { text: `${src}${eol}${keyPath.top}:\n ${keyPath.sub}: ${value}\n`, old: null };
112
+ if (restOf(lines[topIdx]) !== '') return { problem: `${keyPath.top} is written inline in ${DESCRIPTOR} — edit it by hand` };
113
+ const end = blockEnd(topIdx);
114
+ let lastChild = topIdx, indent = ' ';
115
+ for (let j = topIdx + 1; j < end; j++) {
116
+ const l = lines[j];
117
+ if (!l.trim() || l.trim().startsWith('#')) continue;
118
+ const m = /^(\s+)([^:#]+):/.exec(l);
119
+ if (!m) return { problem: `${keyPath.top} has a line this command cannot read (${JSON.stringify(l)}) — edit it by hand` };
120
+ lastChild = j; indent = m[1];
121
+ if (m[2].trim() === keyPath.sub) {
122
+ const old = restOf(l);
123
+ lines[j] = replaceValue(l, value);
124
+ return { text: lines.join('\n') + '\n', old: old === '' ? null : old };
125
+ }
126
+ }
127
+ lines.splice(lastChild + 1, 0, `${indent}${keyPath.sub}: ${value}`);
128
+ return { text: lines.join('\n') + '\n', old: null };
129
+ }
130
+
131
+ /** The value a key path resolves to in a parsed doc (undefined when absent). */
132
+ function valueAt(doc, keyPath) {
133
+ const top = doc ? doc[keyPath.top] : undefined;
134
+ if (!keyPath.sub) return top;
135
+ return top && typeof top === 'object' ? top[keyPath.sub] : undefined;
136
+ }
137
+
138
+ /**
139
+ * Line diff → the 0-based indices of changed lines on each side. A plain LCS: a descriptor is a few
140
+ * hundred lines at most, and a dependency-free diff keeps this module pure and testable.
141
+ */
142
+ function changedLines(aText, bText) {
143
+ const a = String(aText).split('\n'), b = String(bText).split('\n');
144
+ const n = a.length, m = b.length;
145
+ const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
146
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) {
147
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
148
+ }
149
+ const del = [], add = [];
150
+ let i = 0, j = 0;
151
+ while (i < n && j < m) {
152
+ if (a[i] === b[j]) { i++; j++; } else if (dp[i + 1][j] >= dp[i][j + 1]) del.push(i++); else add.push(j++);
153
+ }
154
+ while (i < n) del.push(i++);
155
+ while (j < m) add.push(j++);
156
+ return { a, b, del, add };
157
+ }
158
+
159
+ /**
160
+ * The top-level key whose block holds line `idx`, or null for a top-level comment / a line before
161
+ * any key. A blank line is reported as `''` (harmless wherever it sits).
162
+ */
163
+ function ownerOf(lines, idx) {
164
+ const l = lines[idx];
165
+ if (!l.trim()) return '';
166
+ if (/^#/.test(l)) return null;
167
+ for (let k = idx; k >= 0; k--) {
168
+ if (/^#/.test(lines[k])) return null; // a top-level comment ends the block above it
169
+ const key = topKeyOf(lines[k]);
170
+ if (key !== null) return key;
171
+ }
172
+ return null;
173
+ }
174
+
175
+ /**
176
+ * Is the change from `baseText` to `headText` (both the descriptor's full text) TUNING ONLY?
177
+ * `paths` are the changed entries for the whole diff — `[{ path, oldMode, newMode, binary }]`, the
178
+ * shape docs-only.js reads — so a second file anywhere refuses the class.
179
+ *
180
+ * Tuning only means: exactly one file changed, the descriptor, as a regular text file; every changed
181
+ * non-blank line sits inside a tuning key's block; every other key parses identical on both sides;
182
+ * and every tuning key that moved holds a valid value (or is absent) at head.
183
+ *
184
+ * Returns `{ tuning, keys, reason }` — `reason` is one line for a human, set on both outcomes.
185
+ */
186
+ function classify({ entries, baseText, headText }) {
187
+ const no = (reason, keys = []) => ({ tuning: false, keys, reason });
188
+ const files = [...new Set((entries || []).map((e) => e.path))];
189
+ if (!files.length) return no('empty diff — nothing to call tuning');
190
+ if (files.length !== 1 || files[0] !== DESCRIPTOR) {
191
+ const other = files.filter((f) => f !== DESCRIPTOR);
192
+ return no(`changes ${other.length ? other.slice(0, 3).join(', ') + (other.length > 3 ? ` +${other.length - 3} more` : '') : files.join(', ')} — a tuning change touches ${DESCRIPTOR} alone`);
193
+ }
194
+ for (const e of entries) {
195
+ if (e.binary) return no(`${DESCRIPTOR} reads as binary`);
196
+ if ((e.oldMode && e.oldMode !== '100644' && e.oldMode !== '000000') || (e.newMode && e.newMode !== '100644')) {
197
+ return no(`${DESCRIPTOR} mode change (${e.oldMode} → ${e.newMode})`);
198
+ }
199
+ }
200
+ if (typeof baseText !== 'string' || typeof headText !== 'string') return no(`could not read ${DESCRIPTOR} on both sides`);
201
+
202
+ const d = changedLines(baseText, headText);
203
+ const owners = new Set();
204
+ for (const [lines, idxs] of [[d.a, d.del], [d.b, d.add]]) {
205
+ for (const idx of idxs) {
206
+ const o = ownerOf(lines, idx);
207
+ if (o === '') continue;
208
+ if (o === null) return no(`line ${JSON.stringify(lines[idx].slice(0, 60))} is a top-level comment or sits outside any key`);
209
+ owners.add(o);
210
+ }
211
+ }
212
+ if (!owners.size) return no('only blank lines changed — nothing to call tuning');
213
+ const offending = [...owners].filter((k) => !TUNING[k]);
214
+ if (offending.length) {
215
+ const auth = offending.filter((k) => AUTHORITY_KEYS.includes(k));
216
+ return no(`${offending.join(', ')} ${offending.length > 1 ? 'are' : 'is'} not a tuning key${auth.length ? ` (${auth.join(', ')} grant${auth.length > 1 ? '' : 's'} authority)` : ''}`, [...owners]);
217
+ }
218
+
219
+ let base, head;
220
+ try { base = yaml.parse(baseText) || {}; head = yaml.parse(headText) || {}; } catch (e) { return no(`${DESCRIPTOR} does not parse: ${e.message}`); }
221
+ const keys = [...new Set([...Object.keys(base), ...Object.keys(head)])];
222
+ const moved = keys.filter((k) => JSON.stringify(base[k]) !== JSON.stringify(head[k]));
223
+ const nonTuning = moved.filter((k) => !TUNING[k]);
224
+ if (nonTuning.length) return no(`${nonTuning.join(', ')} changed value — not a tuning key`, moved);
225
+ if (!moved.length) return no('no value changed — formatting alone is not a tuning change');
226
+ const bad = moved.map((k) => TUNING[k](head)).filter(Boolean);
227
+ if (bad.length) return no(`malformed tuning value: ${bad.join('; ')}`, moved);
228
+ return { tuning: true, keys: moved, reason: `tuning-only (${moved.join(', ')})` };
229
+ }
230
+
231
+ /**
232
+ * The branch shape, with I/O: what `branch` changes relative to its merge base with `base` — the
233
+ * same three-dot diff the squash would land, read through docs-only.js's entry reader so both doors
234
+ * judge one diff. `git` is tools/lib/git.js (or a fake with its `git()` shape).
235
+ */
236
+ function branchTuning(git, repo, base, branch) {
237
+ const docsOnly = require('./docs-only');
238
+ const entries = docsOnly.readEntries(git, repo, 'diff', [`${base}...${branch}`, '--']);
239
+ if (!entries) return { tuning: false, keys: [], reason: `could not read the diff ${base}...${branch}` };
240
+ const mb = git.git(['merge-base', base, branch], repo);
241
+ if (!mb.ok) return { tuning: false, keys: [], reason: `no merge base between ${base} and ${branch}` };
242
+ const show = (ref) => { const r = git.git(['show', `${ref}:${DESCRIPTOR}`], repo); return r.ok ? r.stdout : (/does not exist|exists on disk, but not in/.test(r.stderr || '') ? '' : null); };
243
+ return classify({ entries, baseText: show(mb.stdout.trim()), headText: show(branch) });
244
+ }
245
+
246
+ /**
247
+ * Commit `text` as the descriptor on top of `baseSha`, as branch `branch`, WITHOUT touching any
248
+ * working tree or the repo's own index: a scratch index (GIT_INDEX_FILE) holds the tree. The main
249
+ * checkout stays on trunk at rest, which a `git checkout -b` here would break (CONVENTIONS.md §4).
250
+ * The ref is created only if absent (`update-ref <ref> <sha> ""`), so a concurrent run cannot
251
+ * overwrite a branch someone else just made. Returns `{ ok, sha, error }`.
252
+ */
253
+ function commitOnBranch(repo, { baseSha, text, message, branch }) {
254
+ const { spawnSync } = require('child_process');
255
+ const fs = require('fs');
256
+ const os = require('os');
257
+ const path = require('path');
258
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'colab-config-set-'));
259
+ const env = { ...process.env, GIT_INDEX_FILE: path.join(tmp, 'index') };
260
+ const run = (args, input) => {
261
+ const r = spawnSync('git', args, { cwd: repo, env, encoding: 'utf8', ...(input !== undefined ? { input } : {}) });
262
+ return { ok: r.status === 0, out: String(r.stdout || '').trim(), err: String(r.stderr || '').trim() };
263
+ };
264
+ try {
265
+ const rt = run(['read-tree', baseSha]);
266
+ if (!rt.ok) return { ok: false, error: `read-tree ${baseSha}: ${rt.err}` };
267
+ const blob = run(['hash-object', '-w', '--stdin'], text);
268
+ if (!blob.ok) return { ok: false, error: `hash-object: ${blob.err}` };
269
+ const up = run(['update-index', '--add', '--cacheinfo', `100644,${blob.out},${DESCRIPTOR}`]);
270
+ if (!up.ok) return { ok: false, error: `update-index: ${up.err}` };
271
+ const tree = run(['write-tree']);
272
+ if (!tree.ok) return { ok: false, error: `write-tree: ${tree.err}` };
273
+ const commit = run(['commit-tree', tree.out, '-p', baseSha, '-F', '-'], message);
274
+ if (!commit.ok) return { ok: false, error: `commit-tree: ${commit.err}` };
275
+ const ref = run(['update-ref', `refs/heads/${branch}`, commit.out, '']);
276
+ if (!ref.ok) return { ok: false, error: `update-ref refs/heads/${branch}: ${ref.err}` };
277
+ return { ok: true, sha: commit.out };
278
+ } finally {
279
+ fs.rmSync(tmp, { recursive: true, force: true });
280
+ }
281
+ }
282
+
283
+ /** The descriptor's exact text at `ref` (no trimming — it becomes a blob), '' when absent, null on a git error. */
284
+ function descriptorAt(repo, ref) {
285
+ const { spawnSync } = require('child_process');
286
+ const r = spawnSync('git', ['show', `${ref}:${DESCRIPTOR}`], { cwd: repo, encoding: 'utf8' });
287
+ if (r.status === 0) return String(r.stdout);
288
+ return /does not exist|exists on disk, but not in/.test(String(r.stderr || '')) ? '' : null;
289
+ }
290
+
291
+ /**
292
+ * Does `colab config set <key>` mean THIS repo's descriptor (#561) rather than the machine-local
293
+ * config? Machine keys are camelCase (`claimTTLHours`); descriptor keys are kebab-case. An authority
294
+ * key routes here too, so its refusal names the reason instead of "unknown config key".
295
+ */
296
+ function isDescriptorKey(arg) {
297
+ const s = String(arg || '');
298
+ const top = s.split('.')[0];
299
+ return !!TUNING[top] || AUTHORITY_KEYS.includes(top) || /[-.]/.test(s);
300
+ }
301
+
302
+ /** `chore/tune-<key>` — never ending in a digit group, which `colab ship` would read as an issue number. */
303
+ function branchName(keyPath) {
304
+ const slug = [keyPath.top, keyPath.sub].filter(Boolean).join('-').toLowerCase().replace(/[^a-z0-9-]+/g, '-');
305
+ return `chore/tune-${slug}`;
306
+ }
307
+
308
+ /** The commit message: a conventional subject, the evidence in the body (#561). */
309
+ function commitMessage(keyPath, oldValue, value, evidence) {
310
+ const name = [keyPath.top, keyPath.sub].filter(Boolean).join('.');
311
+ return `chore(project): ${name} ${oldValue === null || oldValue === undefined ? '(unset)' : oldValue} → ${value}\n\n` +
312
+ `Tuning-only change to ${DESCRIPTOR}, written by \`colab config set\` (#561).\n\n` +
313
+ `Evidence: ${String(evidence).trim()}\n`;
314
+ }
315
+
316
+ module.exports = {
317
+ DESCRIPTOR, TUNING, TUNING_KEYS, AUTHORITY_KEYS,
318
+ parseKeyPath, editText, valueAt, changedLines, ownerOf, classify, branchTuning, commitOnBranch, descriptorAt, isDescriptorKey, branchName, commitMessage,
319
+ };
@@ -166,5 +166,5 @@ function directChanges(git, repo, trunk, since) {
166
166
 
167
167
  module.exports = {
168
168
  DOC_EXTENSIONS, DOCS_DIR, NEVER_BASENAMES, NEVER_DIRS, NEVER_SUBDIRS,
169
- pathReason, classify, parseRaw, parseBinary, branchChanges, directChanges,
169
+ pathReason, classify, parseRaw, parseBinary, readEntries, branchChanges, directChanges,
170
170
  };