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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +312 -3
  3. package/README.vi.md +281 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13806 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +278 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify-endpoint.js +170 -0
  63. package/tools/lib/notify.js +188 -0
  64. package/tools/lib/npm-publish-guard.js +242 -0
  65. package/tools/lib/orphan-worktree.js +127 -0
  66. package/tools/lib/owner-branch.js +182 -0
  67. package/tools/lib/place.js +782 -0
  68. package/tools/lib/ports.js +167 -0
  69. package/tools/lib/procs.js +185 -0
  70. package/tools/lib/readiness.js +240 -0
  71. package/tools/lib/records.js +185 -0
  72. package/tools/lib/refs-brake.js +95 -0
  73. package/tools/lib/release-channel.js +99 -0
  74. package/tools/lib/release-cut.js +822 -0
  75. package/tools/lib/release-finalize.js +521 -0
  76. package/tools/lib/release-policy.js +358 -0
  77. package/tools/lib/release-tag.js +225 -0
  78. package/tools/lib/ship-batch.js +277 -0
  79. package/tools/lib/ship-roles.js +71 -0
  80. package/tools/lib/ship-target-sync.js +181 -0
  81. package/tools/lib/shipguard.js +317 -0
  82. package/tools/lib/shipped-branch.js +56 -0
  83. package/tools/lib/solo.js +213 -0
  84. package/tools/lib/squash.js +515 -0
  85. package/tools/lib/stale-base.js +70 -0
  86. package/tools/lib/stamp.js +740 -0
  87. package/tools/lib/state.js +262 -0
  88. package/tools/lib/teardown.js +83 -0
  89. package/tools/lib/trust-humans.js +104 -0
  90. package/tools/lib/util.js +98 -0
  91. package/tools/lib/wake.js +188 -0
  92. package/tools/lib/workflow-triggers.js +273 -0
  93. package/tools/lib/writes-authority.js +237 -0
  94. package/tools/lib/yaml.js +101 -0
  95. package/bin/cli.js +0 -3
@@ -0,0 +1,882 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/adopt.js — the core of `colab adopt` (#199, commit 1 of 2).
4
+ *
5
+ * This unit is DETECT / DERIVE / REPORT only. It never asks a human a question, never gates on
6
+ * `COLAB_HUMAN`, and never writes `.github/project.yml` — see the plan on #199 for why asking and
7
+ * writing are a separate commit ("the seam"). What lives here is the part that is useful on its
8
+ * own: read whatever a repo has already declared, detect what its working tree already states,
9
+ * derive what §9's checklist says follows from those answers, and hand back a structured report.
10
+ *
11
+ * Pure and injected-`io`, on purpose — every function here is unit-testable with a scripted `io`,
12
+ * no real git/filesystem required (`tools/lib/adopt.test.js`); the real CLI wiring
13
+ * (`tools/colab`'s `cmdAdopt`) is the only place that touches `fs`/`git` for real.
14
+ *
15
+ * `io` matches the local shape of `makeSource()` in `audit/audit.mjs` (~:538-590) — deliberately
16
+ * narrow, three functions:
17
+ * readFile(relPath) -> string | null file contents, or null if unreadable/absent
18
+ * listDir(relPath) -> string[] non-recursive listing, [] if unreadable/absent
19
+ * tags() -> string[] | null every git tag, or null if undeterminable
20
+ *
21
+ * Git facts that are NOT plain file reads (trunk, `core.hooksPath`) are passed in separately via
22
+ * `extra`, rather than folded into `io` — `detectTrunk()` already lives in `tools/lib/git.js` and
23
+ * belongs to the CLI layer, not duplicated here.
24
+ *
25
+ * `.github/project.yml`'s FIVE rows are exactly §9's shared question set (CONVENTIONS.md §9):
26
+ * tier, room, exposure, writes, channels. `trunk`/`stack`/`ports` are DETECTED, never asked, and
27
+ * are reported alongside the rows without being rows themselves.
28
+ */
29
+
30
+ const axisAuthority = require('./axis-authority.js');
31
+ const writesAuthority = require('./writes-authority.js');
32
+ const yaml = require('./yaml.js');
33
+ const { consumerEvidence, describeEvidence } = require('./consumer-evidence.js');
34
+ const { evaluateExposure } = require('./exposure-shape.js');
35
+ const { UserError } = require('./util.js');
36
+
37
+ const ROW_NAMES = ['tier', 'room', 'exposure', 'writes', 'channels'];
38
+
39
+ // ---------------------------------------------------------------------- descriptor read
40
+
41
+ /** Parsed `.github/project.yml`, or {} when absent/unparseable — never throws. */
42
+ function readDescriptor(io) {
43
+ const text = io.readFile('.github/project.yml');
44
+ if (text === null) return {};
45
+ try {
46
+ return yaml.parse(text) || {};
47
+ } catch (_) {
48
+ return {};
49
+ }
50
+ }
51
+
52
+ // ---------------------------------------------------------------------- detect (never ask)
53
+
54
+ /**
55
+ * Stack candidates from manifest PRESENCE only — never a version, never a claim about which one
56
+ * is authoritative when more than one manifest exists (a repo can genuinely be polyglot). Each
57
+ * entry names the manifest found, so a human reads WHY a candidate was proposed.
58
+ */
59
+ function detectStack(io) {
60
+ const candidates = [];
61
+ if (io.readFile('package.json') !== null) candidates.push('node (package.json)');
62
+ if (io.readFile('composer.json') !== null) candidates.push('php (composer.json)');
63
+ if (io.readFile('pyproject.toml') !== null) candidates.push('python (pyproject.toml)');
64
+ if (io.readFile('.python-version') !== null) candidates.push('python (.python-version)');
65
+ return candidates;
66
+ }
67
+
68
+ /**
69
+ * Channel candidates (CONVENTIONS.md §2, "Channels") — evidence only, never an assertion that a
70
+ * channel is real, mirroring the exposure-raising asymmetry: an agent may PROPOSE, never declare
71
+ * absence. Reuses `consumerEvidence()` (#137, extracted #199) for the `workflow`/`artifact`
72
+ * evidence it already gathers, and adds the one kind that function does not cover: a hooks dir or
73
+ * a non-default `core.hooksPath`, evidence for `hook`.
74
+ */
75
+ function detectChannelCandidates(io, workflows, extra) {
76
+ const evidence = consumerEvidence(io, workflows);
77
+ const candidates = [];
78
+ if (evidence.deployPaths.some((p) => p.startsWith('.github/workflows/'))) candidates.push('workflow');
79
+ if (evidence.versionTags.length) candidates.push('artifact');
80
+ const hooksDirFiles = (extra && extra.hooksDirFiles) || [];
81
+ const hooksPath = (extra && extra.hooksPath) || null;
82
+ // A REPO-RELATIVE hooksPath (e.g. ".githooks") is a committed fact about the repo — real
83
+ // evidence. An ABSOLUTE hooksPath is exactly the per-host mechanism CONVENTIONS.md §2
84
+ // ("Channels — names the KIND, never the machine") says never belongs in the descriptor: test
85
+ // fixtures and CI runners routinely point core.hooksPath at a scratch directory OUTSIDE the
86
+ // repo to neutralise a developer's real hooks (CONVENTIONS.md §7, "Test fixtures"), and that
87
+ // machine-local override must never read as the repo declaring a hook channel.
88
+ if (hooksDirFiles.length > 0 || (hooksPath && !hooksPath.startsWith('/'))) candidates.push('hook');
89
+ return { candidates, evidence, evidenceLine: describeEvidence(evidence) };
90
+ }
91
+
92
+ // ---------------------------------------------------------------------- derive (never ask)
93
+
94
+ /**
95
+ * The legacy tier LETTER, as a pure function of `(production, deploy)` — never of `exposure`.
96
+ * `tier` is a function of these two fields; the plan on #199 is emphatic about this direction
97
+ * only, and explains why: `exposure` is what tier is now DERIVED FROM when declared, so deriving
98
+ * exposure from a tier this function just invented would be circular.
99
+ *
100
+ * production: null/absent -> "B" (no production, the tier-B contract)
101
+ * production set + deploy push-main -> "C" (the promotion itself is the deploy)
102
+ * production set + deploy tag|manual -> "A" (a deliberate release artifact gates production)
103
+ * production set + deploy none/other -> null (a shape §2/schema.md has no letter for — a
104
+ * descriptor contradiction to REPORT, never guess past)
105
+ */
106
+ function deriveTier(production, deploy) {
107
+ const hasProduction = production !== null && production !== undefined && production !== '';
108
+ if (!hasProduction) return 'B';
109
+ if (deploy === 'push-main') return 'C';
110
+ if (deploy === 'tag' || deploy === 'manual') return 'A';
111
+ return null;
112
+ }
113
+
114
+ const RECOVERY_OBLIGATION = Object.freeze({
115
+ none: "amend or `git reset` the trunk-direct commit — nothing outside the repo saw it",
116
+ self: 'rebuild the checkout from a known-good ref and redeploy — the deploy gate, where the repo has one, is the recovery point',
117
+ live: 'revert the commit, then promote the revert — the revert is a deploy in its own right, not a formality before one',
118
+ released: 'cut a new version and publish an advisory — a release, once tagged, cannot be un-tagged',
119
+ });
120
+
121
+ /**
122
+ * Everything §9/§7's "derived, never asked" list follows from `writes`/`exposure`/`room` alone —
123
+ * CONVENTIONS.md §2 ("CI", "Recovery", "Ceremony", "Writes"). Every value here is null when the
124
+ * axis it depends on is undeclared: this function derives, it never guesses a default beyond the
125
+ * one the schema itself states.
126
+ *
127
+ * #237 (⚖ Decision on #233): `writes` stopped selecting a write-conflict prevention METHOD and
128
+ * became a two-state VETO — `trunkDirectVetoed` (tools/lib/writes-authority.js), computed from
129
+ * the RAW value, is the only reading anything downstream may act on now.
130
+ *
131
+ * #283 (structural fix for #282, replacing the `writesMethod`/`resolveWrites` reading): this
132
+ * function now reads `writesAuthority.writesMode(writes)` — a TOTAL function onto exactly
133
+ * `free` / `direct` / `isolated` — instead of `resolveWrites`, so `writesResolved` and
134
+ * `trunkDirect` (still computed from the raw value via `trunkDirectVetoed`, unchanged since
135
+ * #237) are derived from the SAME underlying fact and can never disagree in the same --json
136
+ * blob. That disagreement was #282's whole complaint: `resolveWrites(raw).value` reads
137
+ * 'isolated' for BOTH an explicit declaration and plain absence, so a `writesResolved` sourced
138
+ * from it could say "isolated" while `trunkDirect` (sourced from `trunkDirectVetoed(raw)`) said
139
+ * "permitted", in the same returned object. `writesMethod` — the retired 3-way parse whose only
140
+ * job was that now-wrong reading — is dropped from the returned object entirely; nothing
141
+ * downstream may read it as a method choice (#282's own suggested fix).
142
+ *
143
+ * `direct` is declared, stored, and honestly reported here — but its runtime is DEFERRED (#283,
144
+ * Approach §2): `trunkDirect`/`ciRole`/`branchMandatory` each name that explicitly ("declared,
145
+ * not yet enforced") rather than silently reusing `free`'s text, so a `direct` repo's report
146
+ * never claims a guarantee this diff does not implement.
147
+ */
148
+ function deriveConsequences({ exposure, writes, room }) {
149
+ const { mode: writesResolved, source: modeSource } = writesAuthority.writesMode(writes);
150
+ const writesSource = writes === null || writes === undefined ? null : modeSource;
151
+ const vetoed = writesAuthority.trunkDirectVetoed(writes); // the ONE reading that decides anything now (#237) — unchanged, raw value, direct never vetoes
152
+
153
+ const gateCount = exposure && Object.prototype.hasOwnProperty.call(axisAuthority.GATE_COUNT, exposure)
154
+ ? axisAuthority.GATE_COUNT[exposure]
155
+ : null;
156
+
157
+ const DIRECT_DEFERRED_POINTER = 'declared, not yet enforced — see CONVENTIONS.md §2, '
158
+ + '"writes: direct — declared today, runtime deferred (#283)"';
159
+
160
+ // #237: absence and every non-veto value now permit trunk-direct to an ATTENDED session
161
+ // (COLAB_HUMAN=1) — a session-identity fact this function cannot see from the descriptor
162
+ // alone, so `trunkDirect` names both branches rather than resolving to one. `direct` gets its
163
+ // own branch (#283): it never over-claims a guarantee `free` does not already give — see
164
+ // writes-authority.js's `WRITES_CURRENT` comment on the fail-safe direction this rests on.
165
+ const trunkDirect = vetoed
166
+ ? 'vetoed — writes: isolated forbids trunk-direct for every session, human or not (CONVENTIONS.md §2, Writes)'
167
+ : writesResolved === 'direct'
168
+ ? `${DIRECT_DEFERRED_POINTER} — an attended session may take trunk-direct today exactly as under free (COLAB_HUMAN=1, CONVENTIONS.md §5, The human flag)`
169
+ : 'permitted to an attended human session only — COLAB_HUMAN=1, set on a human\'s explicit instruction (CONVENTIONS.md §5, The human flag)';
170
+
171
+ // #283, Approach §3 (Q2 — decided and shipped): under `direct` there is no merge event, so CI
172
+ // can never gate a merge that never happens — `ciRole` is alarm, always. This is cheap to
173
+ // decide because `ciRole` is derived prose here, not enforcement.
174
+ const ciRole = vetoed
175
+ ? 'gate — isolated writers always branch, so CI runs before the merge lands (CONVENTIONS.md §7)'
176
+ : writesResolved === 'direct'
177
+ ? `alarm, always — ${DIRECT_DEFERRED_POINTER}`
178
+ : 'gate for a worktree session, alarm for an attended trunk-direct one — what CI is follows '
179
+ + 'whether the unit has a branch, a fact about the session rather than a declared value (CONVENTIONS.md §7)';
180
+
181
+ const ciDepth = (exposure === 'live' || exposure === 'released')
182
+ ? 'thorough — answers to a consumer with no way to ask a clarifying question (CONVENTIONS.md §7)'
183
+ : (exposure === 'none' || exposure === 'self')
184
+ ? 'answers only to the room (CONVENTIONS.md §7)'
185
+ : null;
186
+
187
+ const ceremonyWeight = room === 'solo'
188
+ ? 'light narration is coherent — the trail has exactly one reader (CONVENTIONS.md §2, Ceremony)'
189
+ : (room === 'team' || room === 'public')
190
+ ? 'standard narration — more than one reader could ever comb the trail'
191
+ : null;
192
+
193
+ const branchMandatory = vetoed
194
+ ? 'mandatory — isolated writers always use a worktree + branch'
195
+ : writesResolved === 'direct'
196
+ ? `${DIRECT_DEFERRED_POINTER} — the same two conditions as free decide it today`
197
+ : 'mandatory for every session except an attended trunk-direct one, which needs a branch only '
198
+ + 'when more than one unit is already in flight, or a gate must inspect a unit before it '
199
+ + 'lands (CONVENTIONS.md §2, Writes)';
200
+
201
+ const recoveryObligation = exposure && Object.prototype.hasOwnProperty.call(RECOVERY_OBLIGATION, exposure)
202
+ ? RECOVERY_OBLIGATION[exposure]
203
+ : null;
204
+
205
+ return {
206
+ writesResolved, writesSource, trunkDirect, gateCount, ciRole, ciDepth,
207
+ ceremonyWeight, branchMandatory, recoveryObligation,
208
+ };
209
+ }
210
+
211
+ // ---------------------------------------------------------------------- §9 remainder checklist
212
+
213
+ /**
214
+ * §9's steps 3-9, unconditionally — this commit never performs any of them (Boundary, #199's
215
+ * plan: "adopt writes the descriptor and nothing else"), so the remainder is the same regardless
216
+ * of what the descriptor already states. Handed back as data, not prose, so a caller (a report
217
+ * printer, or a future `handbook-sync` call site) does not grow its own paraphrase of these steps.
218
+ */
219
+ function remainingSteps() {
220
+ return [
221
+ { n: 3, text: 'Create the full label set (13 names) — `colab labels --ensure`, CONVENTIONS.md §9 step 3 (#206)' },
222
+ { n: 4, text: 'Add the tier topic to the GitHub repo — `gh repo edit --add-topic tier-<b|c|a>`, step 4' },
223
+ { n: 5, text: 'Make CLAUDE.md the thin shell — `@AGENTS.md` plus templates/repo-CLAUDE-block.md, repo prose in AGENTS.md (adopt writes both on a new repo, #417), step 5' },
224
+ { n: 6, text: "Make sure CI meets §7's outcome — `colab template <name>`, step 6" },
225
+ { n: 7, text: 'Register the repo — `colab register`, step 7' },
226
+ { n: 8, text: 'Leave existing branches alone — nothing to do, step 8' },
227
+ { n: 9, text: 'Do not create `dev` unless genuinely Tier A or Tier C — nothing to do, step 9' },
228
+ ];
229
+ }
230
+
231
+ // ---------------------------------------------------------------------- row state
232
+
233
+ /** One of the five §9 rows: { state: 'answered'|'missing'|'detected'|'legacy read', value, source }. */
234
+ function rowFromDeclared(cfg, key) {
235
+ const has = Object.prototype.hasOwnProperty.call(cfg, key) && cfg[key] !== null && cfg[key] !== undefined;
236
+ return has
237
+ ? { state: 'answered', value: cfg[key], source: 'declared in .github/project.yml' }
238
+ : { state: 'missing', value: null, source: null };
239
+ }
240
+
241
+ function rowExposure(cfg, axis) {
242
+ if (axis.source === 'exposure') {
243
+ return { state: 'answered', value: axis.exposure, source: 'declared in .github/project.yml' };
244
+ }
245
+ if (axis.source === 'tier-legacy') {
246
+ return {
247
+ state: 'legacy read',
248
+ value: axis.exposure, // may be null (tier: B carries no derivable opinion)
249
+ source: `derived from tier: ${axis.tier} (tools/lib/axis-authority.js)`,
250
+ };
251
+ }
252
+ return { state: 'missing', value: null, source: null };
253
+ }
254
+
255
+ function rowChannels(cfg, channelInfo) {
256
+ const has = Object.prototype.hasOwnProperty.call(cfg, 'channels') && cfg.channels !== null && cfg.channels !== undefined;
257
+ if (has) return { state: 'answered', value: cfg.channels, source: 'declared in .github/project.yml' };
258
+ if (channelInfo.candidates.length > 0) {
259
+ return {
260
+ state: 'detected',
261
+ value: channelInfo.candidates,
262
+ source: channelInfo.evidenceLine || 'working-tree evidence',
263
+ };
264
+ }
265
+ return { state: 'missing', value: null, source: null };
266
+ }
267
+
268
+ function rowTier(cfg, legacyTierLetter) {
269
+ const has = Object.prototype.hasOwnProperty.call(cfg, 'tier') && cfg.tier !== null && cfg.tier !== undefined;
270
+ if (has) return { state: 'answered', value: cfg.tier, source: 'declared in .github/project.yml' };
271
+ if (legacyTierLetter !== null) {
272
+ return {
273
+ state: 'detected',
274
+ value: legacyTierLetter,
275
+ source: 'derived from production + deploy (tools/lib/adopt.js:deriveTier)',
276
+ };
277
+ }
278
+ return { state: 'missing', value: null, source: null };
279
+ }
280
+
281
+ // ---------------------------------------------------------------------- detect (top-level)
282
+
283
+ /**
284
+ * The whole report. `io` — see the module header. `extra` — everything the CLI already knows
285
+ * that is not a plain file read: `{ trunk, hooksPath, hooksDirFiles }`, all optional.
286
+ *
287
+ * Never asks, never writes. Returns a plain object — the CLI decides how to render it (text or
288
+ * `--json`), and both paths read the same structure so they cannot drift apart from each other.
289
+ */
290
+ function detect(io, extra = {}) {
291
+ const cfg = readDescriptor(io);
292
+ const axis = axisAuthority.axisOfRecord(cfg);
293
+
294
+ const workflows = io.listDir('.github/workflows').filter((f) => /\.ya?ml$/.test(f));
295
+ const channelInfo = detectChannelCandidates(io, workflows, extra);
296
+ const stackCandidates = detectStack(io);
297
+
298
+ const production = Object.prototype.hasOwnProperty.call(cfg, 'production') ? cfg.production : null;
299
+ const deploy = Object.prototype.hasOwnProperty.call(cfg, 'deploy') ? cfg.deploy : null;
300
+ const legacyTierLetter = deriveTier(production, deploy);
301
+
302
+ const rows = {
303
+ tier: rowTier(cfg, legacyTierLetter),
304
+ room: rowFromDeclared(cfg, 'room'),
305
+ exposure: rowExposure(cfg, axis),
306
+ writes: rowFromDeclared(cfg, 'writes'),
307
+ channels: rowChannels(cfg, channelInfo),
308
+ };
309
+
310
+ const consequences = deriveConsequences({
311
+ exposure: axis.exposure,
312
+ writes: cfg.writes || null,
313
+ room: cfg.room || null,
314
+ });
315
+
316
+ const declaredTrunk = Object.prototype.hasOwnProperty.call(cfg, 'trunk') ? cfg.trunk : null;
317
+ const detectedTrunk = (extra && extra.trunk) || null;
318
+ // 'origin-head' (the ordinary case) | 'current-branch-fallback' (no origin remote at all —
319
+ // exactly first-time adoption's own shape: `git init`, adopt, add a remote later) | null
320
+ // (nothing could be determined). Surfaced so a human sees a fallback was INFERRED, not read
321
+ // from a remote's HEAD — tools/colab's adoptGitExtras() is the only place that computes it.
322
+ const trunkSource = (extra && extra.trunkSource) || null;
323
+
324
+ return {
325
+ descriptorExists: io.readFile('.github/project.yml') !== null,
326
+ cfg,
327
+ axis,
328
+ rows,
329
+ detected: {
330
+ trunk: { declared: declaredTrunk, detected: detectedTrunk, source: trunkSource, agree: declaredTrunk === null || detectedTrunk === null ? null : declaredTrunk === detectedTrunk },
331
+ stackCandidates,
332
+ ports: Object.prototype.hasOwnProperty.call(cfg, 'ports') ? cfg.ports : null,
333
+ channelCandidates: channelInfo.candidates,
334
+ channelEvidenceLine: channelInfo.evidenceLine,
335
+ },
336
+ legacyTierLetter,
337
+ consequences,
338
+ remaining: remainingSteps(),
339
+ };
340
+ }
341
+
342
+ // =========================================================================================
343
+ // commit 2 of #199 — asking, the human gate, and the write.
344
+ //
345
+ // Everything above this line is commit 1 (detect / derive / report; never asks, never
346
+ // writes). Everything below is new: which of the five §9 rows still needs a human answer,
347
+ // whether a PROPOSED answer is one this repo's own shape can support (EXPOSURE_SHAPE), whether
348
+ // the answer needs authorization before it may be written (gateVerdict), and how to append it
349
+ // to `.github/project.yml` without disturbing a single byte that was already there
350
+ // (renderDescriptor). tools/colab's cmdAdopt is the only place that reads env/tty/argv and
351
+ // calls fs.writeFileSync — every function here stays pure and unit-testable.
352
+ // =========================================================================================
353
+
354
+ const VALID_ROOM = new Set(['solo', 'team', 'public']);
355
+ // #283: `colab adopt --writes` accepts the CURRENT 3-way vocabulary (free/direct/isolated) AND
356
+ // every pre-#283 spelling (isolated/serial-direct/serial-gated, plus the `serial` alias) — an
357
+ // existing script or muscle-memory invocation keeps working, exactly like the audit's own
358
+ // read-side acceptance (tools/lib/writes-authority.js's WRITES_ACCEPTED_SET is the ONE set both
359
+ // share). `--writes direct` is legal here but subject to `writesGateVerdict` below before a
360
+ // write may proceed.
361
+ const VALID_WRITES = writesAuthority.WRITES_ACCEPTED_SET;
362
+ const VALID_EXPOSURE = new Set(['none', 'self', 'live', 'released']);
363
+ const VALID_CHANNELS = new Set(['workflow', 'hook', 'procedure', 'checkout', 'artifact', 'data', 'none']);
364
+ const VALID_DEPLOY = new Set(['tag', 'manual', 'push-main', 'none']);
365
+
366
+ /** `--channels` / the wizard's shared validator (#283: moved here from tools/colab so
367
+ * `resolveChoice` below can share it with `adoptAnswersFromFlags`'s flag-driven path without a
368
+ * second copy): non-empty, every member in VALID_CHANNELS, no duplicate member, and "none" must
369
+ * stand alone. Throws UserError — the CLI's flag path lets that surface directly; `resolveChoice`
370
+ * below catches it and turns it into an `{ ok: false, message }`. */
371
+ function adoptValidateChannels(list) {
372
+ if (!Array.isArray(list) || list.length === 0) {
373
+ throw new UserError('--channels must be a non-empty comma-separated list — use "none" if nothing runs this code anywhere');
374
+ }
375
+ const unknown = list.filter((c) => !VALID_CHANNELS.has(c));
376
+ if (unknown.length) throw new UserError(`--channels contains ${JSON.stringify(unknown)}, expected members of: ${[...VALID_CHANNELS].join(', ')}`);
377
+ const deduped = [...new Set(list)];
378
+ if (deduped.length !== list.length) throw new UserError(`--channels contains a duplicate member — declare each channel once: ${JSON.stringify(deduped)}`);
379
+ if (list.includes('none') && list.length > 1) throw new UserError('--channels combines "none" with another value — "none" must stand alone');
380
+ return list;
381
+ }
382
+
383
+ // ---------------------------------------------------------------------- §9 question set
384
+
385
+ /**
386
+ * The five §9 rows, phrased exactly as CONVENTIONS.md §9 phrases them to a human — never
387
+ * restated with different wording (this handbook has paid for a duplicated checklist drifting
388
+ * from its source twice in one day; see skills/handbook-sync/SKILL.md's own note on the same
389
+ * failure). `axis: 'tier'` writes `production` + `deploy`, never `tier` itself — question 1 is
390
+ * the MECHANISM question ("does a deploy target exist today, and how is it reached?"), and
391
+ * `tier` is a function of those two answers, never a row a human answers directly
392
+ * (tools/lib/adopt.js:deriveTier). The `axis` name matches `ROW_NAMES` on purpose: it is the
393
+ * same five names the report table already uses, so `--axis` and the report agree on vocabulary.
394
+ *
395
+ * #283: every entry below now carries a `choices` array — the wizard's forced multiple-choice
396
+ * menu, rendered by `renderMenu(axis)` and resolved by `resolveChoice(axis, raw)` (both below).
397
+ * `tier`'s `choices` are the `deploy` menu's four options — `production` is a URL, not an enum
398
+ * member, so it is asked as its own two-option gate ("does a deploy target exist today?")
399
+ * directly in `tools/colab`'s `adoptAskInteractive`, never through this generic mechanism; a URL
400
+ * cannot honestly be a menu choice without pretending it belongs to a closed set. `channels` is
401
+ * the one `multi: true` entry — "one or more numbers or names, comma-separated" — and its
402
+ * resolution still runs through `adoptValidateChannels` unchanged (dedupe, "none" stands alone).
403
+ * `exposure` is the one entry with a `skip` — see the "blank = skip" rule below its prompt.
404
+ */
405
+ const QUESTIONS = Object.freeze([
406
+ {
407
+ axis: 'tier',
408
+ keys: ['production', 'deploy'],
409
+ prompt: 'Does a deploy target exist today (a URL), and how is it reached — a tag gates '
410
+ + 'production, the promotion itself deploys (push-main), a human runs a runbook '
411
+ + '(manual), or nothing is live yet (none)?',
412
+ choices: [
413
+ { value: 'push-main', label: 'the promotion itself deploys' },
414
+ { value: 'tag', label: 'a version tag gates production' },
415
+ { value: 'manual', label: 'a human runs a documented runbook' },
416
+ { value: 'none', label: 'nothing is live yet' },
417
+ ],
418
+ },
419
+ {
420
+ axis: 'room',
421
+ keys: ['room'],
422
+ prompt: 'Who else works here? (solo / team / public)',
423
+ choices: [
424
+ { value: 'solo', label: 'nobody else could ever read what a session writes here' },
425
+ { value: 'team', label: 'colleagues could read the record' },
426
+ { value: 'public', label: 'anyone could read the record' },
427
+ ],
428
+ },
429
+ {
430
+ axis: 'exposure',
431
+ keys: ['exposure'],
432
+ prompt: 'What would break if you merged something wrong here? (none / self / live / released)',
433
+ choices: [
434
+ { value: 'none', label: 'nothing outside this room consumes a merge' },
435
+ { value: 'self', label: 'only parties already in the room' },
436
+ { value: 'live', label: 'the promotion into trunk is itself the deploy' },
437
+ { value: 'released', label: 'a deliberate artifact (a tag, a runbook) deploys' },
438
+ ],
439
+ // #283: the ONE row that keeps a decline path — CONVENTIONS.md §9's own fallback (derive
440
+ // `tier` from production+deploy instead) is a real fallback that consumes the absence. The
441
+ // other four rows have no such fallback, so a skip there would just re-create #282's "leave
442
+ // unanswered" shape under a different name.
443
+ skip: { label: 'skip — derive tier from production + deploy instead' },
444
+ },
445
+ {
446
+ axis: 'writes',
447
+ keys: ['writes'],
448
+ // #283: `free` IS the former blank. The old prompt told a human to "leave unanswered" for
449
+ // coexistence because there was no spelling for it; now `free` names it directly, so this
450
+ // prompt no longer offers (or needs) a decline — a later reader must not "restore" the
451
+ // decline path here as a regression fix, it is deliberately gone (§5 of the plan on #283).
452
+ prompt: 'Should a human ever be allowed to commit straight to this repo\'s trunk checkout, '
453
+ + 'alongside worktree sessions? free allows it with no runtime restriction; direct allows '
454
+ + 'it and additionally declares intent for a stronger guarantee later (declared today, not '
455
+ + 'yet enforced — CONVENTIONS.md §2); isolated vetoes it outright, human or not.',
456
+ choices: [
457
+ { value: 'free', label: 'no restriction beyond the ordinary worktree flow (the default)' },
458
+ { value: 'direct', label: 'declares intent for a future guarantee; declared today, not yet enforced' },
459
+ { value: 'isolated', label: 'vetoes trunk-direct outright, human or not' },
460
+ ],
461
+ },
462
+ {
463
+ axis: 'channels',
464
+ keys: ['channels'],
465
+ prompt: 'By what path does a commit reach something that runs it? (a list — several may '
466
+ + 'apply: workflow / hook / procedure / checkout / artifact / data / none)',
467
+ multi: true,
468
+ choices: [
469
+ { value: 'workflow', label: 'merge → CI → a deploy workflow' },
470
+ { value: 'hook', label: 'a git hook fires on a git act' },
471
+ { value: 'procedure', label: 'a human builds/installs/restarts by a documented procedure' },
472
+ { value: 'checkout', label: 'a per-machine service serves the working tree directly' },
473
+ { value: 'artifact', label: 'a tag or package that adopters/others consume' },
474
+ { value: 'data', label: 'the effect lands in another system\'s production data' },
475
+ { value: 'none', label: 'nothing runs this code anywhere' },
476
+ ],
477
+ },
478
+ ]);
479
+
480
+ // ---------------------------------------------------------------------- the wizard (#283) — pure menu logic
481
+
482
+ /**
483
+ * The numbered menu block for `axis` — one line per choice ("N) value — label"), plus a
484
+ * trailing skip line when the axis declares one (`exposure` only, today). Pure string building;
485
+ * `tools/colab`'s `adoptAskInteractive` prints the question's `prompt` separately, then this.
486
+ */
487
+ function renderMenu(axis) {
488
+ const q = QUESTIONS.find((x) => x.axis === axis);
489
+ if (!q || !q.choices) return '';
490
+ const lines = q.choices.map((c, i) => ` ${i + 1}) ${c.value} — ${c.label}`);
491
+ if (q.skip) lines.push(` ${q.choices.length + 1}) ${q.skip.label}`);
492
+ return lines.join('\n');
493
+ }
494
+
495
+ /**
496
+ * Resolve a raw typed answer for `axis` against its menu (#283). Accepts EITHER the option
497
+ * NUMBER or the literal VALUE — muscle memory and scriptability read the same validating set:
498
+ * `resolveChoice('room', '2')` and `resolveChoice('room', 'team')` both succeed identically.
499
+ *
500
+ * Returns one of:
501
+ * { ok: true, value } — an ordinary choice, resolved to its declared value.
502
+ * { ok: true, skip: true } — the skip option, only for an axis that declares one (`exposure`).
503
+ * { ok: false, message } — anything else; `message` names the valid options so a reprompt
504
+ * (or a scripted caller) knows exactly what would have worked.
505
+ *
506
+ * `channels` is the one `multi: true` axis: `raw` is a comma-separated list of numbers/names,
507
+ * each resolved independently against the same menu, then the whole resulting list is run
508
+ * through `adoptValidateChannels` UNCHANGED (dedupe, "none" stands alone) — a thrown UserError
509
+ * from that call becomes this function's ordinary `{ ok: false, message }` shape, never a throw.
510
+ */
511
+ function resolveChoice(axis, raw) {
512
+ const q = QUESTIONS.find((x) => x.axis === axis);
513
+ const trimmed = (raw === null || raw === undefined ? '' : String(raw)).trim();
514
+ if (!q || !q.choices) return { ok: false, message: `no menu defined for axis "${axis}"` };
515
+
516
+ const findOne = (part) => {
517
+ if (/^\d+$/.test(part)) {
518
+ const byNumber = q.choices[Number(part) - 1];
519
+ if (byNumber) return byNumber;
520
+ }
521
+ return q.choices.find((c) => c.value === part) || null;
522
+ };
523
+ const optionsText = () => {
524
+ const base = q.choices.map((c, i) => `${i + 1}) ${c.value}`).join(', ');
525
+ return q.skip ? `${base}, ${q.choices.length + 1}) ${q.skip.label}` : base;
526
+ };
527
+
528
+ if (q.multi) {
529
+ if (trimmed === '') {
530
+ return { ok: false, message: `choose one or more of: ${q.choices.map((c) => c.value).join(', ')} (numbers or names, comma-separated)` };
531
+ }
532
+ const parts = trimmed.split(',').map((s) => s.trim()).filter(Boolean);
533
+ const values = [];
534
+ for (const part of parts) {
535
+ const choice = findOne(part);
536
+ if (!choice) return { ok: false, message: `"${part}" is not one of: ${optionsText()}` };
537
+ values.push(choice.value);
538
+ }
539
+ try {
540
+ return { ok: true, value: adoptValidateChannels(values) };
541
+ } catch (e) {
542
+ return { ok: false, message: e.message };
543
+ }
544
+ }
545
+
546
+ if (q.skip && trimmed === String(q.choices.length + 1)) return { ok: true, skip: true };
547
+ if (trimmed === '') return { ok: false, message: `choose one of: ${optionsText()}` };
548
+
549
+ const choice = findOne(trimmed);
550
+ if (!choice) return { ok: false, message: `"${trimmed}" is not one of: ${optionsText()}` };
551
+ return { ok: true, value: choice.value };
552
+ }
553
+
554
+ /**
555
+ * Is `axis` (one of `ROW_NAMES`) still unanswered in `cfg`? This is deliberately NOT the same
556
+ * question `detect()`'s `rows` answer — `rows.tier` reads `detected` the moment `production`
557
+ * defaults to "no production" (a genuine derivation), and `rows.exposure` reads `legacy read`
558
+ * off a declared `tier` (a genuine, useful fallback for REPORTING). Neither counts as "answered"
559
+ * here: asking is about what a human has explicitly put on record, not what this tool could
560
+ * infer on their behalf. A legacy `tier: C` reading as `exposure: live` must still be ASKED —
561
+ * that explicit declaration is the entire point of phase 3 of the epic this unit closes.
562
+ */
563
+ function axisMissing(cfg, axis) {
564
+ const c = cfg || {};
565
+ switch (axis) {
566
+ case 'tier':
567
+ return !('production' in c) || !('deploy' in c);
568
+ case 'room':
569
+ return !('room' in c) || c.room === null || c.room === undefined;
570
+ case 'exposure':
571
+ return axisAuthority.axisOfRecord(c).source !== 'exposure';
572
+ case 'writes':
573
+ return !('writes' in c) || c.writes === null || c.writes === undefined;
574
+ case 'channels':
575
+ return !('channels' in c) || c.channels === null || c.channels === undefined;
576
+ default:
577
+ return false;
578
+ }
579
+ }
580
+
581
+ // ---------------------------------------------------------------------- EXPOSURE_SHAPE — the constructor
582
+
583
+ /**
584
+ * exposureShapeVerdict — the CONSTRUCTOR half of #144's exposure contract, where
585
+ * `audit/audit.mjs`'s exposure block is the VALIDATOR half. Given the shape a repo is actually
586
+ * IN right now — `{ trunk, hasProduction, deploy, hasDeployWorkflow, hasRunbook }` (`hasRunbook`:
587
+ * a `runbook:` key is declared AND the file it names exists — only `released` with
588
+ * `deploy: manual`, or `deploy: tag` with no committed workflow, ever reads it) — does it
589
+ * support DECLARING a given exposure value?
590
+ *
591
+ * Both this and the audit's block now read ONE shared rule table, `tools/lib/exposure-shape.js`
592
+ * (#207) — this function's whole job is picking the FIRST violation `evaluateExposure` reports
593
+ * (the audit reports every one; a constructor only needs one reason to refuse) and resolving the
594
+ * one entry kind ('runbook') whose verdict depends on which caller is asking: the audit can read
595
+ * the repo and tell "missing" from "unreadable"; this constructor only has `ctx.hasRunbook`.
596
+ * `EXPOSURE_SHAPE` (the old per-exposure closure table, and the module-level export of the same
597
+ * name) is retired along with `tools/lib/adopt-audit-agreement.test.js` — see that file's
598
+ * replacement, `tools/lib/exposure-shape.test.js`, for what now guards this.
599
+ */
600
+ function exposureShapeVerdict(exposure, ctx) {
601
+ for (const entry of evaluateExposure(exposure, ctx || {})) {
602
+ if (entry.kind === 'runbook') {
603
+ if (!(ctx && ctx.hasRunbook)) return { ok: false, reason: entry.message };
604
+ continue; // runbook requirement met — this entry does not block the write
605
+ }
606
+ return { ok: false, reason: entry.message };
607
+ }
608
+ return { ok: true };
609
+ }
610
+
611
+ // ---------------------------------------------------------------------- the human gate (#199's plan)
612
+
613
+ const EXPOSURE_RANK = Object.freeze({ none: 0, self: 1, live: 2, released: 3 });
614
+
615
+ const GATE_CLASS = Object.freeze({
616
+ HUMAN_GATED: 'human-gated',
617
+ EVIDENCE_CONTRADICTS: 'evidence-contradicts',
618
+ REPO_SHAPE: 'repo-shape',
619
+ });
620
+
621
+ const EXIT_CODE = Object.freeze({
622
+ ok: 0,
623
+ [GATE_CLASS.HUMAN_GATED]: 3,
624
+ [GATE_CLASS.EVIDENCE_CONTRADICTS]: 4,
625
+ [GATE_CLASS.REPO_SHAPE]: 5,
626
+ });
627
+
628
+ /**
629
+ * THE HONEST LIMIT (#199's plan is emphatic this be stated in code, not only in a comment
630
+ * somewhere it can be missed): `COLAB_HUMAN=1` is an env var the gated party can set — #150 is
631
+ * the parked epic that would make it mean something stronger, and until that lands this gate is
632
+ * exactly as strong as `colab ship`'s identical bar, and no stronger. An interactive TTY is a
633
+ * better DEFAULT (an agent must take an unusual act — allocate a pty — to defeat it, where
634
+ * setting an env var is an entirely ordinary one), but a TTY is not identity either. The
635
+ * provenance comment this module writes beside every answered key does not prevent a false
636
+ * claim; it makes one require DELIBERATELY writing a lie into a committed file, which is
637
+ * auditable after the fact. None of this becomes a real access-control boundary until #150's
638
+ * identity work exists — this module does not pretend otherwise.
639
+ *
640
+ * The bar applies ONLY to the LOWERING direction (`EXPOSURE_RANK`: released > live > self >
641
+ * none) plus first declarations of `none`/`self` — raising, or a FIRST declaration of
642
+ * `live`/`released`, needs nothing beyond falsifier/shape clearance, because an agent may
643
+ * PROPOSE those from committed evidence (CONVENTIONS.md §2's asymmetry) while only a human may
644
+ * conclude "nothing" or "only the room" consumes a merge here.
645
+ *
646
+ * Pure — every fact this needs is passed in. `tools/colab`'s cmdAdopt is the only place that
647
+ * reads `process.env.COLAB_HUMAN` / `process.stdin.isTTY` and passes the booleans through.
648
+ */
649
+ function gateVerdict({ exposure, currentExposure, shapeCtx, evidence, isTTY, colabHuman, answeredBy, reason }) {
650
+ const shape = exposureShapeVerdict(exposure, shapeCtx);
651
+ if (!shape.ok) {
652
+ return { ok: false, class: GATE_CLASS.REPO_SHAPE, exitCode: EXIT_CODE[GATE_CLASS.REPO_SHAPE], message: `exposure: ${exposure} — ${shape.reason}` };
653
+ }
654
+
655
+ // Falsifier (#137, mirrored): only ever fires on `none` — `self` gets no falsifier at all, on
656
+ // the audit's own precedent (its consumer set is a subset of the room's, which nothing here
657
+ // can confirm or deny from repo-local evidence). Direction-independent: this is evidence about
658
+ // the CLAIM, not about who is authorized to make it.
659
+ if (exposure === 'none' && evidence) {
660
+ const line = describeEvidence(evidence);
661
+ if (line && !reason) {
662
+ return {
663
+ ok: false,
664
+ class: GATE_CLASS.EVIDENCE_CONTRADICTS,
665
+ exitCode: EXIT_CODE[GATE_CLASS.EVIDENCE_CONTRADICTS],
666
+ message: `exposure: none is contradicted by repo evidence — ${line}. Choose again, or `
667
+ + 'override with --reason "<text>", written into the file',
668
+ };
669
+ }
670
+ }
671
+
672
+ const isFirst = currentExposure === null || currentExposure === undefined;
673
+ const isLowering = !isFirst && EXPOSURE_RANK[exposure] < EXPOSURE_RANK[currentExposure];
674
+ const isRaisingOrFirstHigh = (exposure === 'live' || exposure === 'released') && !isLowering;
675
+ if (isRaisingOrFirstHigh) return { ok: true };
676
+
677
+ const authorized = isTTY || (colabHuman && answeredBy);
678
+ if (!authorized) {
679
+ return {
680
+ ok: false,
681
+ class: GATE_CLASS.HUMAN_GATED,
682
+ exitCode: EXIT_CODE[GATE_CLASS.HUMAN_GATED],
683
+ message: isLowering
684
+ ? `lowering exposure from ${JSON.stringify(currentExposure)} to ${JSON.stringify(exposure)} requires `
685
+ + 'a human: answer at an interactive terminal, or re-run with COLAB_HUMAN=1 and --answered-by "<name>"'
686
+ : `declaring exposure: ${exposure} requires a human: answer at an interactive terminal, `
687
+ + 'or re-run with COLAB_HUMAN=1 and --answered-by "<name>"',
688
+ };
689
+ }
690
+ if (isLowering && !reason) {
691
+ return {
692
+ ok: false,
693
+ class: GATE_CLASS.HUMAN_GATED,
694
+ exitCode: EXIT_CODE[GATE_CLASS.HUMAN_GATED],
695
+ message: `lowering exposure from ${JSON.stringify(currentExposure)} to ${JSON.stringify(exposure)} also `
696
+ + 'requires --reason "<text>", written into the file',
697
+ };
698
+ }
699
+ return { ok: true };
700
+ }
701
+
702
+ /**
703
+ * #283, Approach §6: the declaration-time gate for `writes: direct` — a SIBLING of `gateVerdict`
704
+ * above, never an overload of it, so neither function's existing tests get entangled with the
705
+ * other's. `direct` is the only `writes` value that EXPANDS permission relative to `free`
706
+ * (`free`/`isolated` never do), so it is the only one gated:
707
+ *
708
+ * 1. Human bar — the same bar as lowering exposure: an interactive TTY, or `COLAB_HUMAN=1`
709
+ * together with `--answered-by <name>`. `GATE_CLASS.HUMAN_GATED`, exit 3.
710
+ * 2. Exposure refusal, BOTH directions — refused when the EFFECTIVE exposure (this run's
711
+ * exposure answer, else the descriptor's own axis of record) is `live` or `released`.
712
+ * `GATE_CLASS.REPO_SHAPE`, exit 5. The symmetric case matters: declaring `writes: direct`
713
+ * when exposure is already live/released is refused, and so is answering
714
+ * `--exposure live|released` against an already-declared `writes: direct` (or one answered
715
+ * in the SAME run) — the caller (`tools/colab`'s `cmdAdopt`) is what computes `effExposure`
716
+ * to cover both orders; this function only ever sees the resolved value.
717
+ *
718
+ * No `--force`, no override flag — consistent with `HELP_ADOPT`'s "There is no --force." A
719
+ * `writes` value other than `direct` always clears this gate; it exists for `direct` alone.
720
+ */
721
+ function writesGateVerdict({ writes, effExposure, isTTY, colabHuman, answeredBy }) {
722
+ if (writes !== 'direct') return { ok: true };
723
+
724
+ if (effExposure === 'live' || effExposure === 'released') {
725
+ return {
726
+ ok: false,
727
+ class: GATE_CLASS.REPO_SHAPE,
728
+ exitCode: EXIT_CODE[GATE_CLASS.REPO_SHAPE],
729
+ message: `writes: direct is refused when exposure is ${JSON.stringify(effExposure)} — a `
730
+ + 'repo where a merge reaches users or adopters directly is exactly the shape this '
731
+ + 'declaration-time gate exists to stop before direct\'s runtime lands (CONVENTIONS.md '
732
+ + '§2, "writes: direct — declared today, runtime deferred (#283)")',
733
+ };
734
+ }
735
+
736
+ const authorized = isTTY || (colabHuman && answeredBy);
737
+ if (!authorized) {
738
+ return {
739
+ ok: false,
740
+ class: GATE_CLASS.HUMAN_GATED,
741
+ exitCode: EXIT_CODE[GATE_CLASS.HUMAN_GATED],
742
+ message: 'declaring writes: direct requires a human: answer at an interactive terminal, or '
743
+ + 're-run with COLAB_HUMAN=1 and --answered-by "<name>" — direct is the one writes value '
744
+ + 'that EXPANDS permission',
745
+ };
746
+ }
747
+ return { ok: true };
748
+ }
749
+
750
+ // ---------------------------------------------------------------------- provenance + the append-only write
751
+
752
+ /** The comment placed beside a written key — never trusted as identity (see gateVerdict's
753
+ * header note), only as an audit trail a false claim would have to be written deliberately into. */
754
+ function provenanceComment(key, meta) {
755
+ if (meta.mode === 'interactive') {
756
+ // #369: `host` is null where the destination may not name it — the comment keeps the date.
757
+ return `# ${key}: answered interactively (${meta.host ? `${meta.host}, ` : ''}${meta.date})`;
758
+ }
759
+ const bits = [`supplied by ${meta.flags.join(', ')}`];
760
+ if (meta.colabHuman) bits.push('COLAB_HUMAN=1');
761
+ if (meta.answeredBy) bits.push(`--answered-by ${JSON.stringify(meta.answeredBy)}`);
762
+ return `# ${key}: ${bits.join(', ')} (${meta.date})`;
763
+ }
764
+
765
+ function yamlScalar(v) {
766
+ if (v === null || v === undefined) return 'null';
767
+ if (typeof v === 'boolean' || typeof v === 'number') return String(v);
768
+ const s = String(v);
769
+ if (s === '') return '""';
770
+ if (/^(null|true|false|yes|no|~)$/i.test(s) || /[:#]/.test(s) || /^\s|\s$/.test(s) || /^['"]/.test(s)) {
771
+ return JSON.stringify(s);
772
+ }
773
+ return s;
774
+ }
775
+
776
+ function isBlockMap(v) {
777
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
778
+ }
779
+
780
+ function yamlFlowSeq(arr) {
781
+ return `[${arr.map((v) => yamlScalar(v)).join(', ')}]`;
782
+ }
783
+
784
+ /**
785
+ * Append-only. `entries` — `[{ key, value, comment? }]` — are rendered in order and added to the
786
+ * END of `rawText` (which may be `null`/`''`/absent for a repo adopting for the first time).
787
+ * A plain-object `value` renders as a one-level block map of scalars (#405's `owner:` block).
788
+ * Never re-parses, never re-serialises, never touches a byte already present: this repo's own
789
+ * descriptor is ~60 lines of comment over 9 keys, and a parse-and-reserialise pass would destroy
790
+ * every one of them. `tools/lib/adopt-cli.test.js` asserts `git diff` shows only appended lines.
791
+ */
792
+ function renderDescriptor(rawText, entries) {
793
+ const base = rawText === null || rawText === undefined ? '' : rawText;
794
+ const lines = [];
795
+ for (const e of entries) {
796
+ if (isBlockMap(e.value)) {
797
+ // A one-level block map (#405: `owner:` / ` branch: master`). The comment sits right after
798
+ // `key:`, indented like the sub-keys — after them it would read as describing only the last.
799
+ lines.push(`${e.key}:`);
800
+ if (e.comment) lines.push(` ${e.comment}`);
801
+ for (const [k, v] of Object.entries(e.value)) lines.push(` ${k}: ${Array.isArray(v) ? yamlFlowSeq(v) : yamlScalar(v)}`);
802
+ continue;
803
+ }
804
+ const valueStr = Array.isArray(e.value) ? yamlFlowSeq(e.value) : yamlScalar(e.value);
805
+ lines.push(`${e.key}: ${valueStr}`);
806
+ if (e.comment) lines.push(e.comment);
807
+ }
808
+ const block = `${lines.join('\n')}\n`;
809
+ if (base === '') return block;
810
+ const needsNewline = !base.endsWith('\n');
811
+ return base + (needsNewline ? '\n' : '') + block;
812
+ }
813
+
814
+ // ---------------------------------------------------------------------- the CLAUDE.md shell (#417)
815
+
816
+ /**
817
+ * The thin-shell CLAUDE.md `colab adopt` writes on a new repo: an `@AGENTS.md` import on the
818
+ * first line, then the Conventions block from templates/repo-CLAUDE-block.md with its
819
+ * placeholders filled. The block stays in CLAUDE.md on purpose — the audit, handbook-sync and
820
+ * `colab update` find it there by name (tools/lib/stamp.js); repo prose belongs in AGENTS.md.
821
+ *
822
+ * `tier` may be null (a shape with no legacy letter): the placeholder is then left for a human,
823
+ * never guessed — the same rule deriveTier itself follows.
824
+ */
825
+ function renderClaudeShell(blockTemplate, { version, trunk, tier }) {
826
+ let block = String(blockTemplate).replace(/^\s*<!--[\s\S]*?-->\s*/, ''); // the paste note
827
+ block = block.replace('<!-- colab-handbook @ <version> -->', `<!-- colab-handbook @ ${version} -->`);
828
+ if (trunk) {
829
+ block = block.replace('`<dev|main>`', `\`${trunk}\``);
830
+ block = block.replace(/^[ \t]*<!-- Tier A and C both use[^\n]*-->[ \t]*\n/m, '');
831
+ }
832
+ if (tier) {
833
+ block = block.replace('`<A|B|C>`', `\`${tier}\``);
834
+ // `<A = … · C = … · B = …>` → the one gloss that applies.
835
+ block = block.replace(/<A = ([^·>]+?) · C = ([^·>]+?) · B = ([^>]+?)>/, (m, a, c, b) => ({ A: a, B: b, C: c })[tier] || m);
836
+ }
837
+ return `@AGENTS.md\n\n${block.replace(/\s*$/, '\n')}`;
838
+ }
839
+
840
+ /** The AGENTS.md stub written beside a new shell, only when no AGENTS.md exists. */
841
+ function renderAgentsStub() {
842
+ return [
843
+ '# AGENTS.md',
844
+ '',
845
+ "This repo's instructions for coding agents: what it is, how to run and test it, and pointers",
846
+ 'into `docs/` for anything deeper. It is the file you edit — CLAUDE.md only imports it',
847
+ '(`@AGENTS.md`) and holds the tool-managed blocks that tools look up there by name.',
848
+ '',
849
+ ].join('\n');
850
+ }
851
+
852
+ module.exports = {
853
+ renderClaudeShell,
854
+ renderAgentsStub,
855
+ ROW_NAMES,
856
+ readDescriptor,
857
+ detectStack,
858
+ detectChannelCandidates,
859
+ deriveTier,
860
+ deriveConsequences,
861
+ remainingSteps,
862
+ detect,
863
+ // commit 2
864
+ VALID_ROOM,
865
+ VALID_WRITES,
866
+ VALID_EXPOSURE,
867
+ VALID_CHANNELS,
868
+ VALID_DEPLOY,
869
+ adoptValidateChannels,
870
+ QUESTIONS,
871
+ renderMenu,
872
+ resolveChoice,
873
+ axisMissing,
874
+ EXPOSURE_RANK,
875
+ GATE_CLASS,
876
+ EXIT_CODE,
877
+ exposureShapeVerdict,
878
+ gateVerdict,
879
+ writesGateVerdict,
880
+ provenanceComment,
881
+ renderDescriptor,
882
+ };