@futurelastic/colab-handbook 1.14.0-rc.7 → 1.14.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/audit/audit.mjs CHANGED
@@ -1422,11 +1422,11 @@ function auditRepoInner(target, ctx) {
1422
1422
  {
1423
1423
  const pol = migrationGrant.parseGrantPolicy(cfg);
1424
1424
  info.migrationGrant = pol.policy;
1425
- // #596: an undeclared key is no longer "human, full stop" — the owner-level value (a tracker
1426
- // record, `colab owner-policy show`) may apply, and this offline audit cannot read it. So the
1425
+ // #598: an undeclared key is not "human, full stop" — the machine-level value (the gating
1426
+ // machine's colab config) may apply, and this audit cannot know which machine gates. So the
1427
1427
  // source is reported: `repo` (declared here, final) or `undeclared` (repo-local default human,
1428
- // owner level unread). The round-trip warning below stays on a DECLARED reviewer only: for an
1429
- // owner-level reviewer the mint itself refuses without the job, which is where it surfaces.
1428
+ // machine level unread). The round-trip warning below stays on a DECLARED reviewer only: for a
1429
+ // machine-level reviewer the mint itself refuses without the job, which is where it surfaces.
1430
1430
  info.migrationGrantSource = pol.declared ? "repo" : "undeclared";
1431
1431
  if (!pol.valid) fail(pol.reason);
1432
1432
  // #494: R needs a live `Migration round-trip…` job. Without one every reviewer grant fails R
@@ -1485,6 +1485,18 @@ function auditRepoInner(target, ctx) {
1485
1485
  if (!tr.valid) fail(tr.reason);
1486
1486
  }
1487
1487
 
1488
+ // ---- instruction-files (#602) ---------------------------------------------
1489
+ // `instruction-files: upstream` — a fork whose CLAUDE.md/AGENTS.md belong to the upstream it
1490
+ // tracks; the instruction-file shape is then not judged (checkInstructionFileShape below, and
1491
+ // the shared gate the hook and the CI workflow run). tools/lib/instruction-file.js
1492
+ // parseInstructionFiles is the one reading. An invalid value fails: it reads as absent (judged —
1493
+ // the stricter direction), so the declaration silently does nothing.
1494
+ {
1495
+ const ifl = instructionFile.parseInstructionFiles(cfg);
1496
+ info.instructionFiles = ifl.declared ? ifl.value : null;
1497
+ if (!ifl.valid) fail(ifl.reason);
1498
+ }
1499
+
1488
1500
  // ---- ci-docs-skip (#570) ----------------------------------------------------
1489
1501
  // Opts the CI templates' guard into docs-only mode: a change whose every path is documentation
1490
1502
  // (tools/lib/docs-only.js, the rule colab ship applies), from a green base, skips the suite.
@@ -1816,7 +1828,7 @@ function auditRepoInner(target, ctx) {
1816
1828
  checkInstructionFileBlocks(src, warn, { self: isSelf });
1817
1829
  // #419: and prose left in CLAUDE.md / no AGENTS.md at all — same posture, same reason.
1818
1830
  // #588: and the same finding FAILS where the instruction-file ratchet trips (local repos only).
1819
- checkInstructionFileShape(src, warn, fail, { base: ctx.base, trunk: cfg?.trunk ?? null });
1831
+ checkInstructionFileShape(src, warn, fail, { base: ctx.base, trunk: cfg?.trunk ?? null, upstreamOwned: instructionFile.parseInstructionFiles(cfg).exempt });
1820
1832
  // #599: a caller of the reusable instruction-files workflow narrowed off session branches, or not
1821
1833
  // dispatchable, defeats the ratchet's point (fail on the branch) and the cure rule's way out.
1822
1834
  checkInstructionFilesCaller(src, workflows, cfg?.trunk ?? null, warn);
@@ -2734,7 +2746,12 @@ function instructionRatchet(src, opts) {
2734
2746
  return r;
2735
2747
  }
2736
2748
 
2749
+ //
2750
+ // #602: a fork declaring `instruction-files: upstream` is not judged at all — neither the ratchet's
2751
+ // failure nor the two warnings: its CLAUDE.md/AGENTS.md are the upstream's (CONVENTIONS.md §9, *A
2752
+ // fork of an upstream*), and the --json `instructionFiles` field says why nothing was reported.
2737
2753
  function checkInstructionFileShape(src, warn, fail = warn, opts = {}) {
2754
+ if (opts.upstreamOwned) return;
2738
2755
  const ratchet = instructionRatchet(src, opts);
2739
2756
  if (ratchet && !ratchet.ok) warn(`instruction-file ratchet not evaluated: ${ratchet.error} (#588)`);
2740
2757
  if (ratchet && ratchet.ok && ratchet.fail) {
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.14.0-rc.7"
36
+ "version": "1.14.0-rc.9"
37
37
  }
package/tools/colab CHANGED
@@ -44,6 +44,7 @@ const blockedBy = require('./lib/blocked-by');
44
44
  const ciGrant = require('./lib/ci-grant');
45
45
  const trustHumans = require('./lib/trust-humans');
46
46
  const ownerPolicy = require('./lib/owner-policy');
47
+ const grantPolicy = require('./lib/grant-policy');
47
48
  const ciCure = require('./lib/ci-cure');
48
49
  const ciVerdict = require('./lib/ci-verdict');
49
50
  const baseCiVerdict = require('./lib/base-ci-verdict');
@@ -86,6 +87,7 @@ const localAdopt = require('./lib/local-adopt'); // #393
86
87
  const ownerBranch = require('./lib/owner-branch'); // #394
87
88
  const humanDoor = require('./lib/ship-human-door'); // #525
88
89
  const instructionGate = require('./lib/instruction-gate'); // #588
90
+ const instructionFile = require('./lib/instruction-file'); // #602
89
91
  const {
90
92
  HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
91
93
  parseArgs, table, shortRepo,
@@ -3851,8 +3853,8 @@ It is minted only when ALL of these hold, checked before any network call:
3851
3853
  - the record is well-formed AND passing (approve · checklist pass · escalation clear · CI pass) —
3852
3854
  a grant carrying a failing review is a contradiction, so it is refused, not recorded;
3853
3855
  - the branch is pushed, and --head (if given) equals origin's tip — the grant binds that tip;
3854
- - the policy resolves to \`reviewer\` (#596): this checkout's project.yml \`migration-grant:\` when
3855
- declared (#398), else the owner-level value (\`colab owner-policy\`), else human;
3856
+ - the policy resolves to \`reviewer\` (#598): this checkout's project.yml \`migration-grant:\` when
3857
+ declared (#398), else this machine's value (\`colab config set migration-grant\`), else human;
3856
3858
  - checklist-items, when given, is <passed>/${migrationGrant.REVIEW_CHECKLIST_ITEMS} and, with checklist pass, every item
3857
3859
  passed (#457) — the record counts against the checklist the migration-review skill walks today.
3858
3860
  Then, read from CI after the tracker read and before anything is written (#457):
@@ -3861,7 +3863,7 @@ Then, read from CI after the tracker read and before anything is written (#457):
3861
3863
  head and carries the job. A repo whose CI has no such job cannot mint a reviewer grant at all.
3862
3864
  COLAB_HUMAN=1 is still required for every role. The reviewer identity is DECLARED, not attested.
3863
3865
  \`colab ship\` honours a reviewer grant only when ALL of (#401): P the policy at the target resolves to
3864
- reviewer (its project.yml key, else the owner-level value, else human — #596) · M this record is live, trusted and passing · HEAD its head is the
3866
+ reviewer (its project.yml key, else this machine's value, else human — #598) · M this record is live, trusted and passing · HEAD its head is the
3865
3867
  branch's exact remote head, or its \`migrations\` id equals the id at that head · R the live
3866
3868
  "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job passed on the SHIPPED head (re-read by ship, never
3867
3869
  taken from the record). Any condition failing → a human runs Phase B.
@@ -3966,17 +3968,15 @@ function migrationGrantReviewRecord(repoAbs, opts) {
3966
3968
 
3967
3969
  // Policy first: under the default (human) a reviewer grant would do nothing and mislead. Read from
3968
3970
  // THIS checkout (trunk at rest), never the branch — a branch must not raise its own grant policy.
3969
- // #596: three levels — this checkout's key > the owner-level value > human. The owner record is
3970
- // read only when the repo key is absent or `human` (the opt-out case needs it to say so).
3971
- const mintDoc = projectDoc(repoAbs);
3972
- const pol = migrationGrantPolicyFor(repoAbs, mintDoc, trustHumans.parseTrustHumans(mintDoc));
3971
+ // #598: three levels — this checkout's key > this machine's value > human (grant-policy.js).
3972
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
3973
3973
  if (!pol.valid) throw new UserError(`${pol.reason} — fix project.yml before minting a reviewer grant`);
3974
3974
  if (pol.policy !== 'reviewer') {
3975
3975
  if (pol.optedOut) {
3976
3976
  throw new UserError(`${pol.reason} — no reviewer grant is minted here. A human grant still works: \`COLAB_HUMAN=1 colab migration-grant <N> --branch <branch>\``);
3977
3977
  }
3978
- if (pol.ownerNote) {
3979
- throw new UserError(`this repo's migration-grant policy is "${pol.policy}" (absent = human), and ${pol.ownerNote} — re-run once \`colab owner-policy show\` reads it`);
3978
+ if (pol.machineNote) {
3979
+ throw new UserError(`this repo's migration-grant policy is "${pol.policy}" (absent = human), and ${pol.machineNote} — re-set it with \`COLAB_HUMAN=1 colab config set migration-grant <human|reviewer>\``);
3980
3980
  }
3981
3981
  throw new UserError(`this repo's migration-grant policy is "${pol.policy}"${pol.declared ? '' : ' (absent = human)'} — a reviewer grant is minted only where project.yml declares migration-grant: reviewer`);
3982
3982
  }
@@ -4111,7 +4111,7 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
4111
4111
  print(' Bound to that HEAD: any new commit voids it. It expires the moment the issue closes.');
4112
4112
  }
4113
4113
  print(` colab ship honours it only while the "${migrationGrant.ROUNDTRIP_JOB_PREFIX}" CI job has passed on that HEAD and the policy still says reviewer.`);
4114
- if (opts.policyResolved && opts.policyResolved.source === 'owner') print(` Policy source: ${opts.policyResolved.reason}.`);
4114
+ if (opts.policyResolved && opts.policyResolved.source === 'machine') print(` Policy source: ${opts.policyResolved.reason}.`);
4115
4115
  print(` Revoke any time: colab migration-grant ${num} --revoke`);
4116
4116
  return 0;
4117
4117
  }
@@ -4184,16 +4184,15 @@ function cmdMigrationGrantList(opts) {
4184
4184
  grants.push(row);
4185
4185
  }
4186
4186
 
4187
- // #596: the policy these grants are judged under, with its source (repo | owner | default).
4188
- const listDoc = projectDoc(repoAbs);
4189
- const pol = migrationGrantPolicyFor(repoAbs, listDoc, trustHumans.parseTrustHumans(listDoc));
4187
+ // #598: the policy these grants are judged under, with its source (repo | machine | default).
4188
+ const pol = migrationGrantPolicyFor(projectDoc(repoAbs));
4190
4189
  const policy = { value: pol.policy, source: pol.source, optedOut: pol.optedOut,
4191
- ...(pol.source === 'owner' ? { owner: pol.owner, by: pol.ownerBy, at: pol.ownerAt } : {}) };
4190
+ ...(pol.source === 'machine' ? { by: pol.machineBy, at: pol.machineAt, host: pol.machineHost } : {}) };
4192
4191
  if (opts.json) {
4193
4192
  return print(JSON.stringify({ repo: shortRepo(repoAbs), label: labels.MIGRATION_GRANT_LABEL, policy, grants, stale }, null, 2));
4194
4193
  }
4195
- // Prose names the source only where the owner level is in play — otherwise byte-identical.
4196
- if (pol.source === 'owner' || pol.optedOut || pol.ownerNote) print(`migration-grant policy: ${pol.policy} (source: ${ownerPolicy.sourceLabel(pol)}) — ${pol.reason}`);
4194
+ // Prose names the source only where the machine level is in play — otherwise byte-identical.
4195
+ if (pol.source === 'machine' || pol.optedOut || pol.machineNote) print(`migration-grant policy: ${pol.policy} (source: ${grantPolicy.sourceLabel(pol)}) — ${pol.reason}`);
4197
4196
 
4198
4197
  if (grants.length === 0 && stale.length === 0) {
4199
4198
  print(`no outstanding migration grants in ${shortRepo(repoAbs)}`);
@@ -4211,34 +4210,25 @@ function cmdMigrationGrantList(opts) {
4211
4210
  }
4212
4211
 
4213
4212
  // ---------------------------------------------------------------------------
4214
- // owner-policy (#596) — an owner-level `migration-grant` value, set once by a human for every repo
4215
- // the GitHub owner runs. Record + proof rules: tools/lib/owner-policy.js. This section is gh I/O.
4216
- // Precedence everywhere: the repo's own key > the owner value > human.
4213
+ // owner-policy (#596) — RETIRED as a resolution rung by #598. `show` still reads the owner record,
4214
+ // read-only, and says it is not honoured; `set` refuses. The policy resolves repo key > this
4215
+ // machine's value > human (tools/lib/grant-policy.js; `colab config set migration-grant`).
4217
4216
 
4218
4217
  const HELP_OWNER_POLICY = `colab owner-policy [show] [--json] [--repo <path>]
4219
- COLAB_HUMAN=1 colab owner-policy set migration-grant <human|reviewer|unset> [--repo <path>]
4220
4218
 
4221
- The owner-level grant policy (#596): ONE value for every repo the GitHub owner runs, so a new repo
4222
- does not silently start at \`human\` and the owner does not land one project.yml commit per repo.
4219
+ The owner-level grant policy (#596) is RETIRED (#598). No gate reads it. It was a marker comment
4220
+ on the open \`${ownerPolicy.LABEL}\`-labelled issue in <owner>/${ownerPolicy.RECORD_REPO}, accepted from any
4221
+ owner or org MEMBER — and the shared account agent sessions post from is typically a member, so one
4222
+ raw API call (which no COLAB_HUMAN bar can see) switched reviewer grants on for every repo.
4223
4223
 
4224
- Precedence (read by \`colab migration-grant\` when minting and \`colab ship\` when gating):
4224
+ The policy now resolves, everywhere (\`colab migration-grant\` when minting and listing, \`colab ship\`):
4225
4225
  1. the repo's own \`migration-grant:\` in project.yml — \`human\` there opts the repo out
4226
- 2. the owner-level value set here
4226
+ 2. this MACHINE's value: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>
4227
4227
  3. the default, \`human\`
4228
4228
 
4229
- Where it lives: marker comments on the open \`${ownerPolicy.LABEL}\`-labelled issue in the owner's
4230
- \`${ownerPolicy.RECORD_REPO}\` repo (<owner>/${ownerPolicy.RECORD_REPO}). The latest marker per key whose author
4231
- is the owner or an org MEMBER — and, where the judged repo declares trust-humans, a listed login —
4232
- wins. A marker from anyone else is ignored and shown here, never honoured.
4233
-
4234
- show print the owner value, who set it and when, and what THIS repo resolves to
4235
- set K V post a new marker. Human-only: refused without COLAB_HUMAN=1, exit 1. Never
4236
- reachable through \`colab config set\` — migration-grant stays an authority key there.
4237
- \`unset\` withdraws the owner value. The ${ownerPolicy.RECORD_REPO} repo must exist —
4238
- colab never creates a repo; the issue and label are created on the first set.
4239
-
4240
- Only \`migration-grant\` is an owner-level key today. Nothing else about a reviewer grant changes:
4241
- review record, CI round-trip job, HEAD binding and revoke are exactly as before.
4229
+ show print any owner value still standing (marked: not honoured) and what THIS repo resolves
4230
+ to now, with its source (repo | machine | default)
4231
+ set refused, always — set this machine's value instead (above)
4242
4232
  `;
4243
4233
 
4244
4234
  /** The `<owner>/.github` REST paths, with gh's {owner} placeholder — resolved from the repo's remote. */
@@ -4283,14 +4273,13 @@ function ownerPolicyRead(repoAbs, trust, key = 'migration-grant') {
4283
4273
  }
4284
4274
 
4285
4275
  /**
4286
- * #596: the migration-grant policy for a repo, three levels. `doc` is the project.yml that counts
4287
- * (the trunk checkout for a mint, the merge target for ship). The owner record is read only when the
4288
- * repo key is absent or a valid `human` — a declared reviewer needs no lookup.
4276
+ * #598: the migration-grant policy for a repo — repo key > this machine's value > human. `doc` is
4277
+ * the project.yml that counts (the trunk checkout for a mint, the merge target for ship). The SAME
4278
+ * exported function a console imports (grant-policy.js effectiveGrantPolicy), so they cannot differ.
4279
+ * The owner-level record (#596) is not read here: retired as a rung.
4289
4280
  */
4290
- function migrationGrantPolicyFor(repoAbs, doc, trust) {
4291
- const repoPol = migrationGrant.parseGrantPolicy(doc);
4292
- const needOwner = !repoPol.declared || (repoPol.valid && repoPol.policy === 'human');
4293
- return ownerPolicy.resolveGrantPolicy(repoPol, needOwner ? ownerPolicyRead(repoAbs, trust) : null);
4281
+ function migrationGrantPolicyFor(doc) {
4282
+ return grantPolicy.effectiveGrantPolicy(doc);
4294
4283
  }
4295
4284
 
4296
4285
  function cmdOwnerPolicy(argv) {
@@ -4301,19 +4290,10 @@ function cmdOwnerPolicy(argv) {
4301
4290
  if (opts.help) return print(HELP_OWNER_POLICY);
4302
4291
  const sub = opts._[0] || 'show';
4303
4292
  if (sub === 'set') {
4304
- // HUMAN-ONLY, first — before resolveRepo or any gh call. Same bar as minting a grant.
4305
- if (process.env.COLAB_HUMAN !== '1') {
4306
- process.stderr.write('✗ Refusing: setting the owner-level grant policy requires a human.\n');
4307
- process.stderr.write(' Re-run with COLAB_HUMAN=1. (No field, flag or config value can lower this bar.)\n');
4308
- return 1;
4309
- }
4310
- const [, key, value] = opts._;
4311
- if (!ownerPolicy.KEYS.includes(key)) throw new UserError(`owner-policy set: key ${JSON.stringify(key)} — expected one of ${ownerPolicy.KEYS.join(' | ')}`);
4312
- if (!ownerPolicy.isValidValue(key, value)) throw new UserError(`owner-policy set ${key}: value ${JSON.stringify(value)} — expected one of ${[...ownerPolicy.VALUES[key], ownerPolicy.UNSET].join(' | ')}`);
4313
- const repoAbs = resolveRepoOrCwd(opts);
4314
- if (!repoAbs) throw new UserError('not inside a git repo — pass --repo <path>');
4315
- if (!isGhUsable(repoAbs)) throw new UserError(`gh not usable here (${ghUnusableWhy(repoAbs)}) — the owner policy lives on the tracker`);
4316
- return cmdOwnerPolicySet(repoAbs, key, value);
4293
+ // #598: retired. Refused whether or not COLAB_HUMAN is set — nothing is read or posted.
4294
+ process.stderr.write('✗ Refusing: the owner-level grant policy is retired (#598) — no gate reads it, so setting it would do nothing.\n');
4295
+ process.stderr.write(' Set this machine\'s value instead: COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>\n');
4296
+ return 1;
4317
4297
  }
4318
4298
  if (sub !== 'show') throw new UserError(`unknown owner-policy subcommand "${sub}" — expected one of show | set`);
4319
4299
  const repoAbs = resolveRepoOrCwd(opts);
@@ -4322,47 +4302,22 @@ function cmdOwnerPolicy(argv) {
4322
4302
  const doc = projectDoc(repoAbs);
4323
4303
  const trust = trustHumans.parseTrustHumans(doc);
4324
4304
  const owner = ownerPolicyRead(repoAbs, trust);
4325
- const res = ownerPolicy.resolveGrantPolicy(migrationGrant.parseGrantPolicy(doc), owner);
4305
+ const res = migrationGrantPolicyFor(doc);
4326
4306
  const out = {
4327
4307
  repo: shortRepo(repoAbs),
4328
- owner: { read: owner.read, owner: owner.owner || null, issue: owner.issue || null, why: owner.why || null,
4308
+ owner: { retired: true, read: owner.read, owner: owner.owner || null, issue: owner.issue || null, why: owner.why || null,
4329
4309
  'migration-grant': owner.set ? { value: owner.value, by: owner.by, at: owner.at } : null, ignored: owner.ignored || [] },
4330
4310
  resolved: { 'migration-grant': { policy: res.policy, source: res.source, valid: res.valid, optedOut: res.optedOut, reason: res.reason } },
4331
4311
  };
4332
4312
  if (opts.json) return print(JSON.stringify(out, null, 2));
4333
4313
  const where = owner.owner ? `${owner.owner}/${ownerPolicy.RECORD_REPO}#${owner.issue}` : `<owner>/${ownerPolicy.RECORD_REPO}`;
4334
4314
  if (owner.read === 'unread') warn(`could not read the owner record (${owner.why}) — read as unset`);
4335
- print(`owner-level migration-grant: ${owner.set ? `${owner.value} — set by ${owner.by} at ${owner.at} (${where})` : `not set (${owner.why || where})`}`);
4315
+ print(`owner-level migration-grant: ${owner.set ? `${owner.value} — set by ${owner.by} at ${owner.at} (${where})` : `not set (${owner.why || where})`} — retired (#598), not honoured`);
4336
4316
  for (const i of owner.ignored || []) warn(`ignored marker ${i.value} by ${i.login || '(unknown)'} at ${i.at}: ${i.reason}`);
4337
- print(`${shortRepo(repoAbs)} resolves to: ${res.policy} (source: ${ownerPolicy.sourceLabel(res)}) — ${res.reason}`);
4338
- return 0;
4339
- }
4340
-
4341
- function cmdOwnerPolicySet(repoAbs, key, value) {
4342
- let loc = ownerRecordIssue(repoAbs);
4343
- if (loc.read === 'unread') throw new UserError(`could not read the owner record (${loc.why}) — nothing was posted; re-run once \`colab owner-policy show\` reads it`);
4344
- if (loc.read === 'none') {
4345
- // Is the .github repo there at all? colab never creates a repo — that is the owner's call.
4346
- const repoR = git.ghApi(repoAbs, [`repos/{owner}/${ownerPolicy.RECORD_REPO}`, '--jq', '.full_name']);
4347
- if (!repoR.ok) {
4348
- throw new UserError(`the owner has no ${ownerPolicy.RECORD_REPO} repo (${ghFirstLine(repoR.stderr)}) — nothing was posted. colab never creates a repo: the owner must create <owner>/${ownerPolicy.RECORD_REPO} (GitHub's owner-wide defaults repo), then re-run`);
4349
- }
4350
- git.ghApi(repoAbs, ['-X', 'POST', `repos/{owner}/${ownerPolicy.RECORD_REPO}/labels`, '-f', `name=${ownerPolicy.LABEL}`,
4351
- '-f', 'color=5319E7', '-f', 'description=colab owner-level policy record (#596) — human-set markers only']);
4352
- const body = 'The owner-level colab policy record. Each value is a marker comment posted by `COLAB_HUMAN=1 colab owner-policy set`; ' +
4353
- 'the latest one from the owner or an org member wins. Do not close this issue — closing it withdraws every owner value.';
4354
- const created = git.ghApi(repoAbs, ['-X', 'POST', `repos/{owner}/${ownerPolicy.RECORD_REPO}/issues`, '-f', `title=${ownerPolicy.ISSUE_TITLE}`,
4355
- '-f', `body=${body}`, '-f', `labels[]=${ownerPolicy.LABEL}`, '--jq', '.number']);
4356
- if (!created.ok) throw new UserError(`could not create the owner record issue (${ghFirstLine(created.stderr)}) — nothing was posted; check write access with \`gh auth status\`, then re-run`);
4357
- loc = { read: 'ok', issue: Number(created.stdout.trim()), owner: null };
4317
+ print(`${shortRepo(repoAbs)} resolves to: ${res.policy} (source: ${grantPolicy.sourceLabel(res)}) — ${res.reason}`);
4318
+ if (owner.set && owner.value === 'reviewer' && res.source === 'default') {
4319
+ print(' To keep reviewer grants for repos without their own key, set it on this machine: COLAB_HUMAN=1 colab config set migration-grant reviewer');
4358
4320
  }
4359
- const iso = nowISO();
4360
- const c = git.ghApi(repoAbs, ['-X', 'POST', ownerRecordPath(`issues/${loc.issue}/comments`),
4361
- '-f', `body=${ownerPolicy.markerBody(key, value, commentHost(repoAbs), iso)}`]);
4362
- if (!c.ok) throw new UserError(`could not post the owner policy marker (${ghFirstLine(c.stderr)}) — nothing changed; check write access with \`gh auth status\`, then re-run`);
4363
- print(`Recorded owner-level ${key}: ${value} on ${loc.owner ? `${loc.owner}/` : '<owner>/'}${ownerPolicy.RECORD_REPO}#${loc.issue} at ${iso}.`);
4364
- print(` Repos that declare their own ${key}: are unaffected; \`${key}: human\` in a repo opts it out.`);
4365
- print(' Check what a repo resolves to: colab owner-policy show');
4366
4321
  return 0;
4367
4322
  }
4368
4323
 
@@ -7975,6 +7930,11 @@ const HELP_CONFIG = `colab config [show|add-repo <path>|rm-repo <path>|add-reser
7975
7930
  rm-notify-url <url> remove one receiver from notifyUrl; removing the last unsets the key
7976
7931
  set <key> <value> set claimTTLHours | plannerClaimTTLMinutes | portRange | worktreeSubdir | notifyUrl | journal |
7977
7932
  claimIdentity
7933
+ set migration-grant <human|reviewer|unset> [--by <name>]
7934
+ this MACHINE's migration-grant policy (#598) — HUMAN-ONLY, refused without
7935
+ COLAB_HUMAN=1; records who, when, host and machine. Repos that declare
7936
+ their own migration-grant: win; repos without one resolve to this value,
7937
+ else human. Not the repo's key — that stays an authority key (below).
7978
7938
  set <tuning-key> <value> --evidence "<why>"
7979
7939
  a kebab-case key is this REPO's .github/project.yml, not this machine (#561):
7980
7940
  one tuning value, committed on a short branch, shippable with no issue —
@@ -8025,6 +7985,7 @@ asserted — and, like docs-only (#345), it opens the autonomy gate on a repo wi
8025
7985
  Every other precondition still applies.
8026
7986
 
8027
7987
  Never on this path (they grant authority or change what deploys): ${configSet.AUTHORITY_KEYS.join(', ')}.
7988
+ (\`colab config set migration-grant <v>\` is a different command: THIS MACHINE's value, human-only, #598.)
8028
7989
 
8029
7990
  --evidence <text> the measurement behind the number (required)
8030
7991
  --no-push create the branch locally only
@@ -8091,13 +8052,52 @@ function cmdConfigSetDescriptor(argv) {
8091
8052
  return 0;
8092
8053
  }
8093
8054
 
8055
+ /**
8056
+ * #598: `config set migration-grant <human|reviewer|unset>` — THIS MACHINE's migration-grant
8057
+ * policy, stored in config.json `policy["migration-grant"]` (tools/lib/grant-policy.js). Routed here
8058
+ * before the descriptor path: there `migration-grant` is an authority key and is refused, so the
8059
+ * command had no meaning until now. HUMAN-ONLY, checked first — before any argument is parsed.
8060
+ */
8061
+ function cmdConfigSetMachinePolicy(argv) {
8062
+ if (process.env.COLAB_HUMAN !== '1') {
8063
+ process.stderr.write('✗ Refusing: setting the machine-level migration-grant policy requires a human.\n');
8064
+ process.stderr.write(' Re-run with COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>. (No field, flag or project.yml value can lower this bar.)\n');
8065
+ return 1;
8066
+ }
8067
+ const opts = parseArgs(argv, {
8068
+ values: { '--by': 'by', '--repo': 'repo', '--evidence': 'evidence' },
8069
+ flags: { '--dry': 'dry', '--no-push': 'noPush' },
8070
+ });
8071
+ if (opts.repo || opts.evidence || opts.dry || opts.noPush) {
8072
+ throw new UserError('migration-grant here is this MACHINE\'s value — --repo/--evidence/--dry/--no-push do not apply; re-run as `COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset> [--by <name>]`. A repo\'s own migration-grant: is an authority key: edit .github/project.yml on a branch with an issue');
8073
+ }
8074
+ const value = opts._[1]; // opts._[0] is migration-grant — cmdConfig routes here on exactly that key
8075
+ const allowed = [...grantPolicy.VALUES, grantPolicy.UNSET];
8076
+ if (!allowed.includes(value)) throw new UserError(`config set migration-grant: value ${JSON.stringify(value)} — expected one of ${allowed.join(' | ')}`);
8077
+ let by = opts.by;
8078
+ if (!by) { try { by = os.userInfo().username; } catch (_) { by = null; } }
8079
+ const iso = nowISO();
8080
+ const meta = { by: by || null, at: iso, host: os.hostname(), machine: myMachineId() };
8081
+ state.saveConfig(grantPolicy.withValue(state.loadConfig(), value, meta));
8082
+ if (value === grantPolicy.UNSET) {
8083
+ print('migration-grant (machine) = (unset) — repos without their own key fall back to human');
8084
+ } else {
8085
+ print(`migration-grant (machine) = ${value} — set by ${meta.by || '?'} at ${iso} on ${meta.host}`);
8086
+ print(' Repos that declare their own migration-grant: are unaffected; migration-grant: human in a repo opts it out. Check: colab migration-grant --list');
8087
+ }
8088
+ return 0;
8089
+ }
8090
+
8094
8091
  function cmdConfig(argv) {
8095
8092
  const sub = argv[0];
8093
+ if (sub === 'set' && argv[1] === grantPolicy.MACHINE_KEY) return cmdConfigSetMachinePolicy(argv.slice(1)); // #598, human gate first
8096
8094
  const cfg = state.loadConfig();
8097
8095
  if (!sub || sub === 'show') {
8098
8096
  print(`state: ${state.STATE_FILE}`);
8099
8097
  print(`config: ${state.CONFIG_FILE}`);
8100
8098
  print(JSON.stringify(cfg, null, 2));
8099
+ const mp = grantPolicy.readMachinePolicy();
8100
+ print(`migration-grant (machine): ${mp.read === 'ok' ? `${mp.value} — set by ${mp.by || '?'} at ${mp.at || '?'} on ${mp.host || '?'}` : mp.read === 'none' ? 'not set' : `not usable — ${mp.why}`}`);
8101
8101
  const reserved = ports.reservedSet(cfg, knownRepos(cfg));
8102
8102
  print(`reserved ports (${reserved.size}): ${[...reserved.keys()].sort((a, b) => a - b).join(', ') || '—'}`);
8103
8103
  return 0;
@@ -9316,6 +9316,13 @@ async function cmdAdopt(argv) {
9316
9316
  : `detected (the repo's default branch, ${nowDate})`;
9317
9317
  entries.push({ key: 'trunk', value: extra.trunk, comment: `# trunk: ${trunkNote}` });
9318
9318
  }
9319
+ // #602: on a fork, the instruction-file check cannot see the `upstream` remote in CI — so the
9320
+ // fork verdict above (adoptDetectFork, the one fork test) is recorded as the key CI reads.
9321
+ // Detected, never asked, like trunk and stack; never written over an existing declaration.
9322
+ if (extra.fork && !(instructionFile.INSTRUCTION_FILES_KEY in cfg)) {
9323
+ entries.push({ key: instructionFile.INSTRUCTION_FILES_KEY, value: 'upstream',
9324
+ comment: `# instruction-files: detected — a fork (${extra.fork.source === 'flag' ? '--fork' : `remote "${extra.fork.remote}"`}, ${nowDate}); CLAUDE.md/AGENTS.md are the upstream's, so the instruction-file check leaves them unjudged (CONVENTIONS.md §9, #602)` });
9325
+ }
9319
9326
  if (!('stack' in cfg)) {
9320
9327
  if (opts.stack !== undefined) {
9321
9328
  const stackNote = stackAnsweredInteractively
@@ -10375,10 +10382,9 @@ function shipMigrationGate(repoAbs, gh, target, branch, issues) {
10375
10382
  /** P, HEAD and the R thunk for shipMigrationGate. The thunk memoises its one verdict on the ctx
10376
10383
  * (`roundtripResult`) so the payload can report what R saw without a second read. */
10377
10384
  function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10378
- // #596: the target's key > the owner-level value > human. `trust` (the target's trust-humans)
10379
- // also judges who wrote the owner record.
10385
+ // #598: the target's key > this machine's value > human.
10380
10386
  const trust = trustAt(repoAbs, target);
10381
- const pres = migrationGrantPolicyFor(repoAbs, projectDocAt(repoAbs, target), trust);
10387
+ const pres = migrationGrantPolicyFor(projectDocAt(repoAbs, target));
10382
10388
  const policy = pres.policy;
10383
10389
  const remote = git.remoteInfo(repoAbs).name || 'origin';
10384
10390
  const ls = git.git(['ls-remote', remote, `refs/heads/${branch}`], repoAbs);
@@ -10393,8 +10399,8 @@ function shipMigrationCtx(repoAbs, gh, target, branch, migrations) {
10393
10399
  const contentId = headSha ? migrationContentAt(repoAbs, migrations, headSha) : null;
10394
10400
  const ctx = { policy, headSha, contentId, headNote, roundtripResult: null, trust,
10395
10401
  policySource: pres.source, policyRes: pres,
10396
- // Only where the owner level is in play: the default/repo refusal text stays byte-identical.
10397
- policyReason: pres.source === 'owner' || pres.optedOut || pres.ownerNote ? pres.reason : null,
10402
+ // Only where the machine level is in play: the default/repo refusal text stays byte-identical.
10403
+ policyReason: pres.source === 'machine' || pres.optedOut || pres.machineNote ? pres.reason : null,
10398
10404
  labelActors: (n) => git.ghIssueLabelActors(repoAbs, n, labels.MIGRATION_GRANT_LABEL) };
10399
10405
  ctx.roundtrip = () => {
10400
10406
  const d = git.git(['diff', '--name-only', `${target}...${branch}`], repoAbs);
@@ -10427,10 +10433,12 @@ function migDetail(migrations, grants, target, branch, ctx) {
10427
10433
  const payload = {
10428
10434
  branch, files: [...migrations],
10429
10435
  policy: ctx ? ctx.policy : null,
10430
- // #596: where the policy came from — repo | owner | default — and, for owner, who set it when.
10436
+ // #598: where the policy came from — repo | machine | default — and, for machine, who set it when.
10431
10437
  policySource: ctx ? ctx.policySource || null : null,
10432
- policyOwner: ctx && ctx.policyRes && ctx.policyRes.source === 'owner'
10433
- ? { owner: ctx.policyRes.owner, by: ctx.policyRes.ownerBy, at: ctx.policyRes.ownerAt } : null,
10438
+ // #596's field, kept for additive-only consumers: always null now that the owner level is retired.
10439
+ policyOwner: null,
10440
+ policyMachine: ctx && ctx.policyRes && ctx.policyRes.source === 'machine'
10441
+ ? { by: ctx.policyRes.machineBy, at: ctx.policyRes.machineAt, host: ctx.policyRes.machineHost } : null,
10434
10442
  headSha: ctx ? ctx.headSha : null,
10435
10443
  contentId: ctx ? ctx.contentId || null : null,
10436
10444
  // #407: the human list as read from the TARGET — null when undeclared (association class).
@@ -10444,8 +10452,8 @@ function migDetail(migrations, grants, target, branch, ctx) {
10444
10452
  if (grants.ok) {
10445
10453
  const by = grants.granted.map((g) => (g.role === 'reviewer' ? `#${g.issue} (reviewer ${g.reviewer} @ ${String(g.head).slice(0, 7)}${g.via === 'content' ? `, migration content ${String(g.migrations).slice(0, 12)} unchanged since` : ''}, CI round-trip passed)` : '#' + g.issue)).join(' ');
10446
10454
  const roles = [...new Set(grants.granted.map((g) => g.role || 'human'))].join('+');
10447
- const src = ctx && ctx.policySource === 'owner' && grants.granted.some((g) => g.role === 'reviewer')
10448
- ? ` (policy: ${ownerPolicy.sourceLabel(ctx.policyRes)})` : '';
10455
+ const src = ctx && ctx.policySource === 'machine' && grants.granted.some((g) => g.role === 'reviewer')
10456
+ ? ` (policy: ${grantPolicy.sourceLabel(ctx.policyRes)})` : '';
10449
10457
  return { text: `${migrations.length} present, exempted by a ${roles} grant on ${by} for branch "${branch}"${src} — ${files}`, payload };
10450
10458
  }
10451
10459
  // Each missing entry already carries its own specific, actionable reason (evaluateShipSet) —
@@ -16087,6 +16095,10 @@ workflow \`.github/workflows/instruction-files.yml\`.
16087
16095
  --repo <path> repo to run in (default: cwd)
16088
16096
  --json { ok, error?, mode, base, fail, reason, files: [{ path, conforming, message }], changed }
16089
16097
 
16098
+ A fork whose CLAUDE.md/AGENTS.md belong to its upstream declares \`instruction-files: upstream\` in
16099
+ .github/project.yml (read on the judged side — HEAD, the index or the working tree): nothing is judged
16100
+ and the verdict is a pass (\`--json\`: \`exempt: "upstream"\`) — CONVENTIONS.md §9 "A fork of an upstream", #602.
16101
+
16090
16102
  Exit: 0 pass · 1 fail · 2 cannot judge (not a repo, base not fetched — never read as a pass).
16091
16103
  The fix for a failure is always the same: move the prose to AGENTS.md (handbook-sync's graft step
16092
16104
  does the move), keeping CLAUDE.md to \`@AGENTS.md\`, blank lines and tool blocks.
@@ -16753,8 +16765,8 @@ Commands:
16753
16765
  blocked <blocked> --by <blocker> [--clear --reason R [--force]] [--repo P]
16754
16766
  own the blocked_by dependency-edge write (#251)
16755
16767
  migration-grant <issue> --branch B | --revoke | --list [--json] human-only ship migration exemption (#98)
16756
- owner-policy [show [--json]] | set migration-grant <human|reviewer|unset> owner-level grant policy,
16757
- every repo the GitHub owner runs; set is human-only (#596)
16768
+ owner-policy [show [--json]] the retired owner-level grant policy (#596), read-only;
16769
+ set refuses — use config set migration-grant (#598)
16758
16770
  decision <issue> --record --ruled-by N | --reopen --ruled-by N | --list [--json]
16759
16771
  record/reopen a needs-decision answer (#121, #122)
16760
16772
  ci-grant <issue> --branch B | --revoke | --list [--json] ship trunk-CI-green exemption: human, or ci-reviewer under opt-in (#105, #504)
@@ -397,7 +397,7 @@ function remainingSteps(ctx = {}) {
397
397
  { n: 4, text: 'Optional: add the tier topic to the GitHub repo — `gh repo edit --add-topic tier-<b|c|a>`, step 4. Needs repo ADMIN (push access alone gets `HTTP 404 …/topics`); nothing in colab or the audit reads it, so skip it when you are not one (#522)' },
398
398
  );
399
399
  if (ctx.fork) {
400
- steps.push({ n: 5, text: `Fork of an upstream (${ctx.fork.source === 'flag' ? '--fork' : `remote "${ctx.fork.remote}"`}): do NOT make CLAUDE.md the thin shell — append templates/repo-CLAUDE-block.md at the END of the upstream's CLAUDE.md (create it only if upstream has none), record that append as a fork patch, leave AGENTS.md and the upstream prose untouched; CONVENTIONS.md §9 "A fork of an upstream", step 5` });
400
+ steps.push({ n: 5, text: `Fork of an upstream (${ctx.fork.source === 'flag' ? '--fork' : `remote "${ctx.fork.remote}"`}): do NOT make CLAUDE.md the thin shell — append templates/repo-CLAUDE-block.md at the END of the upstream's CLAUDE.md (create it only if upstream has none), record that append as a fork patch, leave AGENTS.md and the upstream prose untouched, and keep \`instruction-files: upstream\` in .github/project.yml (adopt writes it with the descriptor; add it by hand to one that predates #602) so the instruction-file check leaves the upstream's files unjudged; CONVENTIONS.md §9 "A fork of an upstream", step 5` });
401
401
  const agentFiles = ctx.upstreamAgentFiles || [];
402
402
  if (agentFiles.length) {
403
403
  steps.push({ n: 5, text: `Upstream ships its own agent workflow (${listShort(agentFiles)}): leave it in place, and say in the appended block that fork work runs code-start → code-wrap → code-ship, not that workflow — §9 "A fork of an upstream", step 5` });
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+ /**
3
+ * The migration-grant policy's ONE precedence (#598): the repo's explicit `migration-grant:` >
4
+ * this machine's value > `human`. Every reader resolves through here — `colab migration-grant`
5
+ * (mint and --list), `colab ship`, and any console on the same machine that imports this module —
6
+ * so none of them can compute a different answer than the gate does.
7
+ *
8
+ * THE MACHINE VALUE lives in this machine's colab config (`~/.colab/config.json`, or
9
+ * `$COLAB_HOME/config.json`), under `policy["migration-grant"]`:
10
+ * { "value": "human" | "reviewer", "by": "<who>", "at": "<ISO>", "host": "<hostname>", "machine": "<id>|null" }
11
+ * Written only by `COLAB_HUMAN=1 colab config set migration-grant <human|reviewer|unset>` — the
12
+ * human gate is in tools/colab, before anything is parsed. Its reach is ONE machine: a ship run on
13
+ * another machine never sees it and resolves to `human`, which is the safe direction.
14
+ * `machine` binds the record to the machine that wrote it, so a dotfile-synced or copied config
15
+ * does not carry the switch to another box (read: 'foreign'). Where either side has no machine id,
16
+ * the binding is skipped.
17
+ *
18
+ * THE OWNER-LEVEL RECORD (#596) IS NOT A RUNG. It was a tracker comment any org member could post,
19
+ * including the shared account agent sessions post from, and it reached every repo of the owner
20
+ * (#598, docs/adr/539-migration-rationale.md). `colab owner-policy show` still reads it, read-only.
21
+ *
22
+ * A CONSOLE: call `effectiveGrantPolicy(doc)` with the project.yml the gate reads (the trunk
23
+ * checkout for a mint, the merge target for ship). It reads the same config file colab does —
24
+ * pass `{ configFile }` explicitly if the console process does not inherit colab's COLAB_HOME.
25
+ *
26
+ * Everything here is pure except `readMachinePolicy` (and `effectiveGrantPolicy`, which calls it).
27
+ */
28
+ const fs = require('fs');
29
+ const migrationGrant = require('./migration-grant');
30
+
31
+ const MACHINE_KEY = 'migration-grant';
32
+ const CONFIG_SECTION = 'policy';
33
+ const VALUES = ['human', 'reviewer'];
34
+ const UNSET = 'unset';
35
+
36
+ /**
37
+ * The machine record from a parsed config.json object. Pure.
38
+ * Returns { read: 'ok'|'none'|'invalid'|'foreign', set, value, by, at, host, machine, why }.
39
+ * Anything but read 'ok' is unset.
40
+ */
41
+ function machinePolicyFrom(cfg, { machineId = null } = {}) {
42
+ const sec = cfg && typeof cfg === 'object' ? cfg[CONFIG_SECTION] : null;
43
+ const rec = sec && typeof sec === 'object' ? sec[MACHINE_KEY] : undefined;
44
+ const empty = { set: false, value: null, by: null, at: null, host: null, machine: null };
45
+ if (rec === undefined || rec === null) return { read: 'none', ...empty, why: '' };
46
+ if (typeof rec !== 'object' || Array.isArray(rec) || !VALUES.includes(rec.value)) {
47
+ return { read: 'invalid', ...empty, why: `${CONFIG_SECTION}.${MACHINE_KEY} in the machine config is not a human|reviewer record` };
48
+ }
49
+ const bits = { value: rec.value, by: rec.by || null, at: rec.at || null, host: rec.host || null, machine: rec.machine || null };
50
+ if (bits.machine && machineId && bits.machine !== machineId) {
51
+ return { read: 'foreign', ...empty, why: `the machine-level value was written on another machine (${bits.host || bits.machine}) — a copied config does not carry it` };
52
+ }
53
+ return { read: 'ok', set: true, ...bits, why: '' };
54
+ }
55
+
56
+ function defaultConfigFile() { return require('./state').CONFIG_FILE; }
57
+ function defaultMachineId() {
58
+ try { return require('./machine').localMachine().id || null; } catch (_) { return null; }
59
+ }
60
+
61
+ /** The machine record, read from disk. Never throws: an unreadable file reads as unset. */
62
+ function readMachinePolicy({ configFile, machineId } = {}) {
63
+ const file = configFile || defaultConfigFile();
64
+ let raw;
65
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (e) {
66
+ if (e && e.code === 'ENOENT') return machinePolicyFrom({}, {});
67
+ return { read: 'unread', set: false, value: null, why: `${file}: ${e.message}` };
68
+ }
69
+ let cfg;
70
+ try { cfg = JSON.parse(raw); } catch (e) { return { read: 'unread', set: false, value: null, why: `${file} is not valid JSON` }; }
71
+ return machinePolicyFrom(cfg, { machineId: machineId === undefined ? defaultMachineId() : machineId });
72
+ }
73
+
74
+ /**
75
+ * The precedence. `repoPol` = migration-grant.js parseGrantPolicy(doc); `machine` = a
76
+ * machinePolicyFrom/readMachinePolicy result, or null. Returns repoPol's shape plus
77
+ * { source: 'repo'|'machine'|'default', optedOut, machineBy, machineAt, machineHost, machineNote }.
78
+ * `reason` names the source — callers print it on refusal. Pure.
79
+ */
80
+ function resolveGrantPolicy(repoPol, machine) {
81
+ const m = machine || null;
82
+ const set = !!(m && m.read === 'ok' && m.set);
83
+ const bits = set ? { machineBy: m.by || null, machineAt: m.at || null, machineHost: m.host || null }
84
+ : { machineBy: null, machineAt: null, machineHost: null };
85
+ if (repoPol.declared) {
86
+ const optedOut = repoPol.valid && repoPol.policy === 'human' && set && m.value === 'reviewer';
87
+ return { ...repoPol, source: 'repo', optedOut, ...bits, machineNote: '',
88
+ reason: optedOut
89
+ ? `this repo opted out: project.yml declares migration-grant: human, which wins over this machine's reviewer value (set by ${m.by} at ${m.at})`
90
+ : repoPol.reason };
91
+ }
92
+ if (set) {
93
+ return { policy: m.value, declared: false, valid: true, source: 'machine', optedOut: false, ...bits, machineNote: '',
94
+ reason: `machine-level migration-grant: ${m.value} (set by ${m.by || '?'} at ${m.at || '?'} on ${m.host || 'this machine'}; this repo declares no key of its own)` };
95
+ }
96
+ const machineNote = m && (m.read === 'unread' || m.read === 'invalid' || m.read === 'foreign')
97
+ ? `the machine-level value is not usable (${m.why || m.read}) — read as unset` : '';
98
+ return { ...repoPol, source: 'default', optedOut: false, ...bits, machineNote,
99
+ reason: machineNote ? `${repoPol.reason}; ${machineNote}` : repoPol.reason };
100
+ }
101
+
102
+ /** The one call a console makes: the policy for `doc`, against this machine's config. */
103
+ function effectiveGrantPolicy(doc, opts = {}) {
104
+ return resolveGrantPolicy(migrationGrant.parseGrantPolicy(doc), readMachinePolicy(opts));
105
+ }
106
+
107
+ /** One-line source label: `repo`, `machine (<by> at <at>)`, or `default`. */
108
+ function sourceLabel(res) {
109
+ if (!res) return 'default';
110
+ if (res.source === 'machine') return `machine (${res.machineBy || '?'} at ${res.machineAt || '?'})`;
111
+ return res.source;
112
+ }
113
+
114
+ /** The stored record. Pure. */
115
+ function recordFor(value, { by = null, at = null, host = null, machine = null } = {}) {
116
+ if (!VALUES.includes(value)) throw new Error(`grant-policy: ${JSON.stringify(value)} is not one of ${VALUES.join(' | ')}`);
117
+ return { value, by, at, host, machine };
118
+ }
119
+
120
+ /** A new config object with the machine value set (or removed, on `unset`). Every other key kept. Pure. */
121
+ function withValue(cfg, value, meta = {}) {
122
+ const next = { ...(cfg || {}) };
123
+ const sec = { ...(next[CONFIG_SECTION] && typeof next[CONFIG_SECTION] === 'object' ? next[CONFIG_SECTION] : {}) };
124
+ if (value === UNSET) delete sec[MACHINE_KEY];
125
+ else sec[MACHINE_KEY] = recordFor(value, meta);
126
+ if (Object.keys(sec).length) next[CONFIG_SECTION] = sec; else delete next[CONFIG_SECTION];
127
+ return next;
128
+ }
129
+
130
+ module.exports = {
131
+ MACHINE_KEY, CONFIG_SECTION, VALUES, UNSET,
132
+ machinePolicyFrom, readMachinePolicy, resolveGrantPolicy, effectiveGrantPolicy, sourceLabel, recordFor, withValue,
133
+ };
@@ -328,6 +328,30 @@ function ratchetVerdict({ changed = [], head = [], base = null }) {
328
328
  return { fail: false, reason: null, bad };
329
329
  }
330
330
 
331
+ /**
332
+ * #602 — `instruction-files:` in .github/project.yml → `{ declared, exempt, valid, value, reason }`.
333
+ * `upstream` says this repo's CLAUDE.md/AGENTS.md belong to an upstream it tracks (a fork,
334
+ * CONVENTIONS.md §9 *A fork of an upstream*), so the shape is not judged here. Absent = judged.
335
+ * Any other value is invalid and read in the STRICTER direction — judged — while the audit fails
336
+ * the value. The committed record of `colab adopt`'s fork test, which reads a remote CI never has;
337
+ * never a second fork test.
338
+ */
339
+ const INSTRUCTION_FILES_KEY = 'instruction-files';
340
+ function parseInstructionFiles(doc) {
341
+ const has = !!doc && typeof doc === 'object' && Object.prototype.hasOwnProperty.call(doc, INSTRUCTION_FILES_KEY);
342
+ const v = has ? doc[INSTRUCTION_FILES_KEY] : null;
343
+ if (v === null || v === undefined) {
344
+ return { declared: false, exempt: false, valid: true, value: null, reason: 'instruction-files absent — every CLAUDE.md is judged (#588)' };
345
+ }
346
+ if (v === 'upstream') {
347
+ return { declared: true, exempt: true, valid: true, value: 'upstream', reason: 'instruction-files: upstream — CLAUDE.md/AGENTS.md are upstream-owned (a fork), so their shape is not judged here (CONVENTIONS.md §9, #602)' };
348
+ }
349
+ return {
350
+ declared: true, exempt: false, valid: false, value: v,
351
+ reason: `instruction-files is ${JSON.stringify(v)} — the only defined value is "upstream"; read as absent, so every CLAUDE.md is still judged (#602)`,
352
+ };
353
+ }
354
+
331
355
  module.exports = {
332
356
  stripCode,
333
357
  IMPORT_MAX_DEPTH,
@@ -349,4 +373,6 @@ module.exports = {
349
373
  judgeClaudeMd,
350
374
  RULE_FILE_RE,
351
375
  ratchetVerdict,
376
+ INSTRUCTION_FILES_KEY,
377
+ parseInstructionFiles,
352
378
  };
@@ -22,6 +22,7 @@ const fs = require('fs');
22
22
  const path = require('path');
23
23
  const { execFileSync } = require('child_process');
24
24
  const inst = require('./instruction-file.js');
25
+ const yaml = require('./yaml.js');
25
26
 
26
27
  const CLAUDE_RE = /(^|\/)CLAUDE\.md$/;
27
28
 
@@ -84,6 +85,26 @@ function judgeSide(cwd, side) {
84
85
  });
85
86
  }
86
87
 
88
+ /**
89
+ * #602 — the `instruction-files:` declaration on `side`, read from the SAME tree the CLAUDE.md
90
+ * files are judged on (head, index or working tree), never the merge base: a fork's adoption
91
+ * change adds the key, the CI caller and the appended Conventions block together, and the block
92
+ * touches CLAUDE.md — a base-side read would fail exactly the change that declares the exemption.
93
+ * An unreadable or unparseable descriptor reads as absent (judged — the stricter direction).
94
+ */
95
+ function declarationOn(cwd, side) {
96
+ const text = reader(cwd, side)('.github/project.yml');
97
+ if (text === null || text === undefined) return inst.parseInstructionFiles(null);
98
+ let doc = null;
99
+ try { doc = yaml.parse(text); } catch (_) { doc = null; }
100
+ return inst.parseInstructionFiles(doc);
101
+ }
102
+
103
+ /** The neutral verdict of a repo whose instruction files are upstream-owned. */
104
+ function exemptVerdict(mode, base, decl) {
105
+ return { ok: true, mode, base, exempt: decl.value, reason: null, fail: false, files: [], bad: [], changed: [] };
106
+ }
107
+
87
108
  /**
88
109
  * Run the gate. Options:
89
110
  * cwd repo (default process.cwd())
@@ -93,7 +114,10 @@ function judgeSide(cwd, side) {
93
114
  * With neither `staged` nor `base`, every CLAUDE.md at the head is judged with no ratchet:
94
115
  * any non-conforming file fails (`reason: 'strict'`).
95
116
  *
96
- * Returns `{ ok, error?, fail, reason, mode, base, files, bad, changed }`. `ok: false` means the
117
+ * A repo declaring `instruction-files: upstream` on the judged side (#602) is not judged: the
118
+ * verdict is `{ ok: true, exempt: 'upstream', fail: false, files: [] }`, whatever its CLAUDE.md says.
119
+ *
120
+ * Returns `{ ok, error?, exempt?, fail, reason, mode, base, files, bad, changed }`. `ok: false` means the
97
121
  * gate could not answer (not a repo, base unknown, merge base not reachable in a shallow clone)
98
122
  * — callers must refuse rather than read that as a pass.
99
123
  */
@@ -102,6 +126,8 @@ function gate({ cwd = process.cwd(), staged = false, base = null, head = null }
102
126
  const hasHead = git(cwd, ['rev-parse', '--verify', '-q', 'HEAD^{commit}']) !== null;
103
127
 
104
128
  if (staged) {
129
+ const decl = declarationOn(cwd, 'index');
130
+ if (decl.exempt) return exemptVerdict('staged', hasHead ? 'HEAD' : null, decl);
105
131
  const files = judgeSide(cwd, 'index');
106
132
  const changed = (git(cwd, ['diff', '--cached', '--name-only', '-z']) || '').split('\0').filter(Boolean);
107
133
  const baseFiles = hasHead ? judgeSide(cwd, { ref: 'HEAD' }) : [];
@@ -111,6 +137,8 @@ function gate({ cwd = process.cwd(), staged = false, base = null, head = null }
111
137
 
112
138
  const headSide = head === 'worktree' ? 'worktree' : { ref: head || 'HEAD' };
113
139
  if (headSide !== 'worktree' && !hasHead && !head) return { ok: false, error: 'HEAD has no commit yet' };
140
+ const decl = declarationOn(cwd, headSide);
141
+ if (decl.exempt) return exemptVerdict(base ? 'ratchet' : 'strict', null, decl);
114
142
  const files = judgeSide(cwd, headSide);
115
143
  if (files === null) return { ok: false, error: `cannot read ${head || 'HEAD'}` };
116
144
 
@@ -135,6 +163,7 @@ function gate({ cwd = process.cwd(), staged = false, base = null, head = null }
135
163
  /** One human line per verdict, naming the fix. */
136
164
  function describe(r) {
137
165
  if (!r.ok) return [`cannot judge: ${r.error}`];
166
+ if (r.exempt) return [`instruction files not judged: \`instruction-files: ${r.exempt}\` in .github/project.yml — CLAUDE.md/AGENTS.md are upstream-owned on this fork (CONVENTIONS.md §9 "A fork of an upstream", #602)`];
138
167
  if (!r.bad.length) return [`instruction files conform (${r.files.length} CLAUDE.md judged)`];
139
168
  const why = {
140
169
  touched: 'this change touches CLAUDE.md/AGENTS.md, so every CLAUDE.md must conform',
@@ -147,4 +176,4 @@ function describe(r) {
147
176
  return lines;
148
177
  }
149
178
 
150
- module.exports = { CLAUDE_RE, listClaude, reader, judgeSide, gate, describe };
179
+ module.exports = { CLAUDE_RE, listClaude, reader, judgeSide, declarationOn, gate, describe };
@@ -704,8 +704,8 @@ function parseGrantPolicy(doc) {
704
704
  * The reviewer-grant verdict for one issue — P, M and HEAD of the ship rule; evaluateShipSet()
705
705
  * (#401) calls it and adds R. `ctx` = { branch, headSha, contentId, issueNum, labelName, policy } where
706
706
  * `contentId` (#508) is migrationContentId at `headSha` (grantHeadBinding), and
707
- * `policy` is the resolved policy (repo key > owner-level > human, #596) and `policyReason` its
708
- * source sentence when the owner level is in play. Checks, cheapest/most-fundamental first, each with its
707
+ * `policy` is the resolved policy (repo key > machine-level > human, #598) and `policyReason` its
708
+ * source sentence when the machine level is in play. Checks, cheapest/most-fundamental first, each with its
709
709
  * own reason: read failed · not open · no label · policy not `reviewer` · no live reviewer grant ·
710
710
  * branch mismatch · untrusted author · record invalid · record not passing · HEAD binding.
711
711
  * The CI round-trip is checked here only as RECORDED; re-verifying it against live CI for `head`
@@ -720,8 +720,8 @@ function evaluateReviewerGrant(record, ctx) {
720
720
  if (record.state !== 'OPEN') return no(`#${issue} is ${record.state || 'not open'} — a grant expires when its issue closes`);
721
721
  const labelNames = (record.labels || []).map((l) => (l && typeof l === 'object' ? l.name : l));
722
722
  if (!labelNames.includes(c.labelName)) return no(`#${issue} does not carry the \`${c.labelName}\` label`);
723
- // #596: `policyReason` is set only where the owner level is in play (an owner value, a repo opt-out,
724
- // an unreadable owner record) — it names the source. Otherwise the text is the pre-#596 one.
723
+ // #598: `policyReason` is set only where the machine level is in play (a machine value, a repo
724
+ // opt-out, an unusable machine record) — it names the source. Otherwise the text is the pre-#596 one.
725
725
  if (c.policy !== 'reviewer') {
726
726
  return no(c.policyReason
727
727
  ? `${c.policyReason} — a reviewer grant is honoured only where the policy resolves to reviewer`
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
  /**
3
- * Owner-level grant policy (#596): one `migration-grant` value set once, by a human, for every repo
4
- * an owner runs. Precedence: the repo's explicit `migration-grant:` > the owner value > `human`.
3
+ * Owner-level grant policy (#596) — RETIRED as a resolution rung by #598. No gate reads it: the
4
+ * policy resolves repo key > this machine's value > `human` (grant-policy.js). What remains here
5
+ * is the record reader `colab owner-policy show` uses, read-only, so an operator who relied on an
6
+ * owner value can see that it is no longer honoured and why. `owner-policy set` refuses.
7
+ *
8
+ * Why retired: the record is accepted from any OWNER/MEMBER comment, and the shared account agent
9
+ * sessions post from is typically an org member — one raw `gh api` POST, which skips the
10
+ * COLAB_HUMAN bar entirely, switched reviewer grants on for every repo of the owner (#407 class).
11
+ *
12
+ * As it was (#596): one `migration-grant` value set once, by a human, for every repo an owner runs.
5
13
  *
6
14
  * WHERE IT LIVES. Not in a file. A committed file (in the repo, or in the owner's `.github` repo)
7
15
  * is edited by any session that can commit, and nothing in it names who set it. So the value is a
@@ -93,41 +101,10 @@ function ownerValue(comments, key, trust) {
93
101
  return { set: true, value: cur.value, by: cur.by, at: cur.at, ignored };
94
102
  }
95
103
 
96
- /**
97
- * Three-level precedence for `migration-grant`. `repoPol` = migration-grant.js parseGrantPolicy(doc);
98
- * `owner` = { read: 'ok'|'none'|'unread', owner, set, value, by, at, why } from tools/colab's reader,
99
- * or null when the owner record was not consulted (the repo declares its own key, so it is not needed).
100
- * Returns repoPol's shape plus { source: 'repo'|'owner'|'default', optedOut, owner, ownerBy, ownerAt,
101
- * ownerNote }. `reason` is a sentence naming the source — the caller prints it on refusal.
102
- */
103
- function resolveGrantPolicy(repoPol, owner) {
104
- const o = owner || null;
105
- const ownerSet = !!(o && o.read === 'ok' && o.set);
106
- const ownerBits = ownerSet ? { owner: o.owner || null, ownerBy: o.by || null, ownerAt: o.at || null } : { owner: null, ownerBy: null, ownerAt: null };
107
- if (repoPol.declared) {
108
- const optedOut = repoPol.valid && repoPol.policy === 'human' && ownerSet && o.value === 'reviewer';
109
- return { ...repoPol, source: 'repo', optedOut, ...ownerBits, ownerNote: '',
110
- reason: optedOut
111
- ? `this repo opted out: project.yml declares migration-grant: human, which wins over the owner-level reviewer value (set by ${o.by} at ${o.at})`
112
- : repoPol.reason };
113
- }
114
- if (ownerSet) {
115
- return { policy: o.value, declared: false, valid: true, source: 'owner', optedOut: false, ...ownerBits, ownerNote: '',
116
- reason: `owner-level migration-grant: ${o.value} (set on ${o.owner || 'the owner'}/${RECORD_REPO} by ${o.by} at ${o.at}; this repo declares no key of its own)` };
117
- }
118
- const ownerNote = o && o.read === 'unread' ? `the owner-level record could not be read (${o.why || 'unknown error'}) — read as unset` : '';
119
- return { ...repoPol, source: 'default', optedOut: false, ...ownerBits, ownerNote,
120
- reason: ownerNote ? `${repoPol.reason}; ${ownerNote}` : repoPol.reason };
121
- }
122
-
123
- /** One-line source label for a printed policy: `repo`, `owner (<by> at <at>)`, or `default`. */
124
- function sourceLabel(res) {
125
- if (!res) return 'default';
126
- if (res.source === 'owner') return `owner (${res.ownerBy || '?'} at ${res.ownerAt || '?'})`;
127
- return res.source;
128
- }
129
-
130
104
  module.exports = {
131
105
  LABEL, RECORD_REPO, ISSUE_TITLE, KEYS, VALUES, UNSET, OWNER_ASSOCIATIONS, MARK_RE,
132
- isValidValue, markerBody, normComment, ownerValue, resolveGrantPolicy, sourceLabel,
106
+ isValidValue, markerBody, normComment, ownerValue,
107
+ // #598: resolveGrantPolicy / sourceLabel moved to grant-policy.js and are deliberately NOT
108
+ // re-exported: an owner record has the same { read, set, value } shape as a machine record, so a
109
+ // caller still passing one would silently get it honoured as a machine value. Fail loudly instead.
133
110
  };