create-agent-rig 0.8.0 → 0.9.1

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 (58) hide show
  1. package/CHANGELOG.md +152 -1
  2. package/README.md +99 -4
  3. package/package.json +4 -3
  4. package/packages/cli/dist/commands/init.js +43 -7
  5. package/packages/cli/dist/commands/memory.js +182 -0
  6. package/packages/cli/dist/commands/setup.js +45 -0
  7. package/packages/cli/dist/commands/upgrade.js +22 -4
  8. package/packages/cli/dist/index.js +110 -3
  9. package/packages/cli/dist/lib/manifest.js +23 -5
  10. package/packages/cli/dist/lib/subsystems.js +269 -0
  11. package/packages/cli/dist/lib/version.js +15 -0
  12. package/packages/cli/dist/policy/benchmark/corpus.js +165 -0
  13. package/packages/cli/dist/policy/core/coverage.js +253 -0
  14. package/packages/cli/dist/policy/core/decision-record.js +130 -44
  15. package/packages/cli/dist/policy/core/declaration.js +58 -17
  16. package/packages/cli/dist/policy/core/evidence-matrix.js +94 -0
  17. package/packages/cli/dist/policy/core/probe.js +442 -0
  18. package/packages/cli/dist/policy/core/validation.js +194 -1
  19. package/packages/cli/dist/policy/core/vocabulary.js +70 -3
  20. package/packages/cli/dist/policy/harness/claude.js +9 -1
  21. package/packages/cli/dist/policy/harness/codex.js +48 -1
  22. package/packages/cli/dist/policy/harness/shared-hooks.js +18 -0
  23. package/packages/cli/dist/policy/index.js +9 -2
  24. package/templates/agent-os/stack/aws-cdk/.claude/agents/cdk-diff-reviewer.md +2 -0
  25. package/templates/agent-os/stack/aws-cdk/.codex/agents/cdk-diff-reviewer.toml +2 -0
  26. package/templates/agent-os/subagent-routing.json +32 -0
  27. package/templates/agent-os/universal/.agents/skills/loop/SKILL.md +41 -4
  28. package/templates/agent-os/universal/.claude/agents/code-reviewer.md +2 -0
  29. package/templates/agent-os/universal/.claude/agents/prose-reviewer.md +2 -0
  30. package/templates/agent-os/universal/.claude/agents/security-scanner.md +2 -0
  31. package/templates/agent-os/universal/.claude/agents/test-writer.md +2 -0
  32. package/templates/agent-os/universal/.claude/hooks/guard-subagent-model.mjs +234 -0
  33. package/templates/agent-os/universal/.claude/hooks/lib/edit-input.mjs +75 -32
  34. package/templates/agent-os/universal/.claude/hooks/warn-subagent-routing.mjs +120 -0
  35. package/templates/agent-os/universal/.claude/rules/workflow.md +5 -0
  36. package/templates/agent-os/universal/.claude/scripts/preflight.mjs +27 -3
  37. package/templates/agent-os/universal/.claude/scripts/queue/core.mjs +43 -0
  38. package/templates/agent-os/universal/.claude/scripts/queue/gate-rounds.mjs +70 -2
  39. package/templates/agent-os/universal/.claude/scripts/queue/index.mjs +12 -4
  40. package/templates/agent-os/universal/.claude/scripts/queue/jira.mjs +18 -1
  41. package/templates/agent-os/universal/.claude/scripts/reconcile-external-prs.mjs +269 -32
  42. package/templates/agent-os/universal/.claude/scripts/unattended-flag.mjs +64 -1
  43. package/templates/agent-os/universal/.claude/settings.json +16 -0
  44. package/templates/agent-os/universal/.claude/skills/loop/SKILL.md +41 -4
  45. package/templates/agent-os/universal/.codex/agents/code-reviewer.toml +2 -0
  46. package/templates/agent-os/universal/.codex/agents/prose-reviewer.toml +2 -0
  47. package/templates/agent-os/universal/.codex/agents/security-scanner.toml +2 -0
  48. package/templates/agent-os/universal/.codex/agents/test-writer.toml +2 -0
  49. package/templates/agent-os/universal/.codex/config.toml +3 -0
  50. package/templates/agent-os/universal/docs/decisions/codex-adapter.md +31 -5
  51. package/templates/agent-os/universal/docs/decisions/subagent-routing.md +142 -0
  52. package/templates/agent-os/universal/layers.json +4 -0
  53. package/templates/hash-history.json +71 -22
  54. package/templates/release-ledger.json +3 -1
  55. package/templates/skeleton/node-service/services/api/test/artifact.test.ts +3 -4
  56. package/templates/skeleton/node-service/services/api/test/package-manager.test.ts +40 -0
  57. package/templates/skeleton/node-service/services/api/test/package-manager.ts +51 -0
  58. package/templates/skeleton/node-service/services/api/test/static-dir.test.ts +9 -8
@@ -26,6 +26,9 @@ import { dirname, join } from 'node:path';
26
26
  // so this sweep sees exactly what the gate sweep sees — including the paths a
27
27
  // stack layer contributes for its own shape.
28
28
  import { elevatedPathsIn, laneOf, readDeclaredPaths } from './detect-missed-gate.mjs';
29
+ // The one credential vocabulary (`guard-secret-file`, the commit sweep and this
30
+ // diagnostic all read it): a second list of token shapes here would drift.
31
+ import { SECRET_VALUE_PATTERNS } from './lib/secrets.mjs';
29
32
 
30
33
  /**
31
34
  * The audit trail for work that already happened: a record born **closed**.
@@ -210,37 +213,261 @@ const parseArgs = (argv) => {
210
213
 
211
214
  const daysAgo = (n) => new Date(Date.now() - n * 86_400_000).toISOString().slice(0, 10);
212
215
 
213
- /** Same rule as the gate sweep: "could not look" must never render as "clean". */
214
- const fetchMergedPrs = (since) => {
215
- try {
216
- return JSON.parse(
217
- execFileSync(
218
- 'gh',
219
- [
220
- 'pr',
221
- 'list',
222
- '--state',
223
- 'merged',
224
- '--limit',
225
- '100',
226
- '--search',
227
- `merged:>=${since}`,
228
- '--json',
229
- 'number,title,body,headRefName,mergedAt,url,files,changedFiles,authorAssociation',
230
- ],
231
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
232
- ),
233
- );
234
- } catch (error) {
235
- process.stderr.write(
236
- 'lane reconciliation: could not list merged PRs the `gh` CLI is missing, ' +
237
- 'unauthenticated, or the API is unreachable. No lane was reconciled; do not ' +
238
- 'record an empty `external lane` block from this run. Use --input <file> to ' +
239
- 'work offline.\n' +
240
- ` ${String(error?.stderr ?? error?.message ?? error).trim().split('\n')[0]}\n`,
216
+ // --- Acquisition (RP-99) --------------------------------------------------------
217
+ //
218
+ // Two calls, not one. `gh pr list --json` does not know `authorAssociation` on
219
+ // every supported `gh` (2.71.2 answers `Unknown JSON field`), so the BASE
220
+ // projection asks only for fields every `gh` has, and the association — the
221
+ // trust signal — is fetched afterwards through one GraphQL query. When that
222
+ // second step fails for any reason the base list is returned WITHOUT the field
223
+ // and `reconcile()` treats those PRs as untrusted, and an answer is kept only
224
+ // when it names the same pull request URL the base list did — see the
225
+ // generator's test/template/reconcile-acquisition.test.ts (absent in a generated rig)
226
+ // › "reconcile() treats a PR that lost authorAssociation to a failed enrichment as untrusted when it crosses an elevated path"
227
+ // and › "drops an association whose answer names a different pull request URL — another host or repository never becomes trust".
228
+
229
+ /** The base projection: fields every supported `gh` serves. */
230
+ const BASE_FIELDS = ['number', 'title', 'body', 'headRefName', 'mergedAt', 'url', 'files', 'changedFiles'];
231
+ /** What GitHub returns for `authorAssociation`: an upper-case enum word. */
232
+ const ASSOCIATION_SHAPE = /^[A-Z_]{1,32}$/;
233
+ const MAX_PRS = 100;
234
+
235
+ /** The default runner: one `gh` child, stdout as text, a thrown error otherwise. */
236
+ const execGh = (file, args) =>
237
+ execFileSync(file, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
238
+
239
+ /** A base record the rest of this script can read: an object with a positive PR number. */
240
+ const isPrRecord = (row) =>
241
+ row !== null &&
242
+ typeof row === 'object' &&
243
+ !Array.isArray(row) &&
244
+ Number.isSafeInteger(row.number) &&
245
+ row.number > 0;
246
+
247
+ /**
248
+ * The merged PRs since `since`, plus the warnings the acquisition produced.
249
+ *
250
+ * Throws only from the BASE list — the caller classifies that with
251
+ * `classifyAcquisitionFailure`. A parsed base list that is not an array is
252
+ * thrown with `notAnArray: true` (JSON.parse succeeded, so a SyntaxError would
253
+ * misdescribe it). Enrichment never throws: it degrades to a warning.
254
+ */
255
+ export const fetchMergedPrs = (since, { exec = execGh } = {}) => {
256
+ const raw = exec('gh', [
257
+ 'pr',
258
+ 'list',
259
+ '--state',
260
+ 'merged',
261
+ '--limit',
262
+ String(MAX_PRS),
263
+ '--search',
264
+ `merged:>=${since}`,
265
+ '--json',
266
+ BASE_FIELDS.join(','),
267
+ ]);
268
+ const parsed = JSON.parse(raw);
269
+ if (!Array.isArray(parsed)) {
270
+ throw Object.assign(new Error('gh pr list answered with something other than a JSON array'), {
271
+ notAnArray: true,
272
+ });
273
+ }
274
+
275
+ const warnings = [];
276
+ const prs = [];
277
+ for (const row of parsed.slice(0, MAX_PRS)) {
278
+ if (!isPrRecord(row)) {
279
+ warnings.push('a merged-PR record without a positive numeric `number` was dropped from the sweep');
280
+ continue;
281
+ }
282
+ // Copy the base fields only; whatever else `gh` returned does not travel.
283
+ const record = {};
284
+ for (const field of BASE_FIELDS) if (row[field] !== undefined) record[field] = row[field];
285
+ prs.push(record);
286
+ }
287
+ if (prs.length === 0) return { prs, warnings };
288
+
289
+ const associations = fetchAuthorAssociations(prs, exec);
290
+ if (associations === null) {
291
+ warnings.push(
292
+ 'author association unavailable for this window — every external merge below is treated as untrusted origin',
241
293
  );
242
- process.exit(1);
294
+ return { prs, warnings };
295
+ }
296
+ for (const pr of prs) {
297
+ const answer = associations.get(pr.number);
298
+ if (answer === undefined) continue;
299
+ // `gh api graphql` asks its own default host, not the remote's: an answer
300
+ // about another pull request must never lend its association to this one.
301
+ if (typeof pr.url !== 'string' || answer.url !== pr.url) {
302
+ warnings.push(`PR #${pr.number}: an author association whose pull request URL does not match the listed one was dropped`);
303
+ continue;
304
+ }
305
+ const value = answer.authorAssociation;
306
+ if (typeof value === 'string' && ASSOCIATION_SHAPE.test(value)) pr.authorAssociation = value;
307
+ else warnings.push(`PR #${pr.number}: an author association of an unexpected shape was dropped`);
243
308
  }
309
+ return { prs, warnings };
310
+ };
311
+
312
+ /**
313
+ * `number → { url, authorAssociation }` for the listed PRs through one GraphQL
314
+ * query, or `null` when the answer cannot be trusted: a failed call, unusable
315
+ * JSON, a repository name of an unexpected shape. Never throws.
316
+ */
317
+ const fetchAuthorAssociations = (prs, exec) => {
318
+ try {
319
+ const repo = JSON.parse(exec('gh', ['repo', 'view', '--json', 'nameWithOwner']));
320
+ const nameWithOwner = typeof repo?.nameWithOwner === 'string' ? repo.nameWithOwner : '';
321
+ const parts = nameWithOwner.split('/');
322
+ if (parts.length !== 2 || !parts.every((part) => /^[A-Za-z0-9_.-]{1,100}$/.test(part))) return null;
323
+ const [owner, name] = parts;
324
+ const fields = prs
325
+ .map((pr) => `pr${pr.number}: pullRequest(number: ${pr.number}) { url authorAssociation }`)
326
+ .join(' ');
327
+ const query = `query { repository(owner: "${owner}", name: "${name}") { ${fields} } }`;
328
+ const answer = JSON.parse(exec('gh', ['api', 'graphql', '-f', `query=${query}`]));
329
+ const repository = answer?.data?.repository;
330
+ if (repository === null || typeof repository !== 'object') return null;
331
+ const out = new Map();
332
+ for (const pr of prs) {
333
+ const node = repository[`pr${pr.number}`];
334
+ if (node === null || typeof node !== 'object' || node.authorAssociation === undefined) continue;
335
+ out.set(pr.number, { url: node.url, authorAssociation: node.authorAssociation });
336
+ }
337
+ return out;
338
+ } catch {
339
+ return null;
340
+ }
341
+ };
342
+
343
+ // --- Failure diagnostics (RP-99) -----------------------------------------------
344
+
345
+ const CAUSES = Object.freeze({
346
+ 'gh-missing': 'the `gh` CLI could not be started (not installed, or not on PATH)',
347
+ 'gh-unauthenticated': 'the `gh` CLI is not authenticated for this host — run `gh auth login`',
348
+ 'api-unreachable': 'the GitHub API could not be reached',
349
+ 'unsupported-projection': 'this `gh` version does not serve a field the sweep asked for',
350
+ 'malformed-response': '`gh` answered, but not with the JSON array the sweep expects',
351
+ unknown: 'the cause is unknown',
352
+ });
353
+ const STDERR_UNAUTHENTICATED = /gh auth login|not logged in|HTTP 401|authentication required/i;
354
+ const STDERR_UNREACHABLE =
355
+ /dial tcp|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|HTTP 5\d\d|could not connect|connection refused/i;
356
+ const STDERR_UNSUPPORTED = /Unknown JSON field/i;
357
+ // ESC-led sequences (CSI, OSC and the single-character escapes); the
358
+ // whitespace controls, which become a space where they sit next to whitespace
359
+ // and a mark where they sit inside a run (so they cannot split a token into
360
+ // pieces too short to match); and every other character a terminal would not
361
+ // print as itself — the remaining C0/C1 controls except the line feed the next
362
+ // step splits on, the invisible format characters (zero-width, bidi,
363
+ // byte-order mark), the line and paragraph separators, and U+E000, the mark
364
+ // they are all replaced with.
365
+ // eslint-disable-next-line no-control-regex -- the pattern exists to remove these very bytes
366
+ const TERMINAL_SEQUENCES = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;
367
+ const WHITESPACE_CONTROLS = /[\t\v\f\r]/g;
368
+ const WHITESPACE_CONTROLS_INSIDE_A_RUN = /(?<=\S)[\t\v\f\r]+(?=\S)/g;
369
+ // eslint-disable-next-line no-control-regex -- likewise
370
+ const HIDDEN_CHARACTERS = /[\x00-\x08\x0E-\x1F\x7F-\x9F\p{Cf}\p{Zl}\p{Zp}\uE000]/gu;
371
+ const MARK = '\uE000';
372
+ // No leading word boundary: a keyword glued to the word before must still be
373
+ // found, and over-redacting prose is the safe way to be wrong here.
374
+ const AUTHORIZATION_VALUE = /(?:Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}|Authorization:\s*[^\s]+(?:\s+[^\s]+)?/gi;
375
+ const DIAGNOSTIC_CAP = 200;
376
+ // Redaction runs on at most this much of the line, and the 200-character cut
377
+ // comes after it: cutting first can shorten a token below what its pattern
378
+ // needs and print the prefix. When the window itself cuts the line, the last
379
+ // whitespace-free run is dropped before redaction, so no token is ever
380
+ // shortened by a cut.
381
+ const REDACTION_WINDOW = 4096;
382
+ // A whitespace-free run that had a hidden character removed from it is masked
383
+ // whole once what is left is at least this long — the shortest value the
384
+ // vocabulary redacts, an authorization value. A removed character can glue a
385
+ // token to the word before it or split it into pieces too short to match, and
386
+ // neither can be told apart from honest text, so such a run is not trusted to
387
+ // the patterns at all.
388
+ const MARKED_RUN_MIN = 8;
389
+ // A masked run that ended in one of these keywords takes the next run with it:
390
+ // the value that followed the keyword can no longer be recognised on its own.
391
+ const AUTHORIZATION_KEYWORD_END = /(?:bearer|basic|token|authorization:)$/i;
392
+
393
+ /** `text` without its trailing whitespace-free run. One backward pass. */
394
+ const dropTrailingRun = (text) => {
395
+ let end = text.length;
396
+ while (end > 0 && !/\s/.test(text[end - 1])) end -= 1;
397
+ return text.slice(0, end);
398
+ };
399
+
400
+ const redactPatterns = (text) => {
401
+ let out = text.replace(AUTHORIZATION_VALUE, '[redacted]');
402
+ for (const { pattern } of SECRET_VALUE_PATTERNS) {
403
+ out = out.replace(new RegExp(pattern.source, `${pattern.flags.replace('g', '')}g`), '[redacted]');
404
+ }
405
+ return out;
406
+ };
407
+
408
+ /**
409
+ * One printable line of a subprocess's stderr: no terminal sequences, control
410
+ * or invisible format characters, the first non-empty line only, every run a
411
+ * hidden character was removed from masked when it is long enough to be a
412
+ * credential, the credential shapes the shared vocabulary knows — plus HTTP
413
+ * authorization values — replaced by `[redacted]`, and then at most 200
414
+ * characters.
415
+ */
416
+ export const sanitizeDiagnostic = (text) => {
417
+ const source = typeof text === 'string' ? text : String(text ?? '');
418
+ const marked = source
419
+ .replace(TERMINAL_SEQUENCES, MARK)
420
+ .replace(HIDDEN_CHARACTERS, MARK)
421
+ .replace(WHITESPACE_CONTROLS_INSIDE_A_RUN, MARK)
422
+ .replace(WHITESPACE_CONTROLS, ' ');
423
+ const line = marked.split('\n').find((candidate) => candidate.replaceAll(MARK, '').trim() !== '') ?? '';
424
+ const windowed = line.length > REDACTION_WINDOW ? dropTrailingRun(line.slice(0, REDACTION_WINDOW)) : line;
425
+ let maskNext = false;
426
+ const masked = windowed
427
+ .split(/(\s+)/)
428
+ .map((run) => {
429
+ if (run.trim() === '') return run;
430
+ const visible = run.replaceAll(MARK, '');
431
+ const hidden = run.includes(MARK) && visible.length >= MARKED_RUN_MIN;
432
+ const mask = hidden || maskNext;
433
+ maskNext = mask && AUTHORIZATION_KEYWORD_END.test(visible);
434
+ return mask ? '[redacted]' : visible;
435
+ })
436
+ .join('');
437
+ return redactPatterns(masked).trim().slice(0, DIAGNOSTIC_CAP);
438
+ };
439
+
440
+ /**
441
+ * The cause the evidence supports, and nothing more. `detail` is the sanitized
442
+ * first non-empty stderr line, whatever the cause, or `null` when there was none. An
443
+ * `unknown` failure with no stderr falls back to the error's own message; the
444
+ * other causes never do, because a parse error's message quotes `gh` output.
445
+ */
446
+ export const classifyAcquisitionFailure = (error) => {
447
+ const stderr = typeof error?.stderr === 'string' ? error.stderr : '';
448
+ const detail = stderr.trim() === '' ? null : sanitizeDiagnostic(stderr);
449
+ if (error?.code === 'ENOENT') return { cause: 'gh-missing', detail };
450
+ if (error instanceof SyntaxError || error?.notAnArray === true) {
451
+ return { cause: 'malformed-response', detail };
452
+ }
453
+ if (STDERR_UNSUPPORTED.test(stderr)) return { cause: 'unsupported-projection', detail };
454
+ if (STDERR_UNAUTHENTICATED.test(stderr)) return { cause: 'gh-unauthenticated', detail };
455
+ if (STDERR_UNREACHABLE.test(stderr)) return { cause: 'api-unreachable', detail };
456
+ if (detail === null && typeof error?.message === 'string' && error.message.trim() !== '') {
457
+ return { cause: 'unknown', detail: sanitizeDiagnostic(error.message) };
458
+ }
459
+ return { cause: 'unknown', detail };
460
+ };
461
+
462
+ /** The message the CLI prints for a failed acquisition: one cause, named. */
463
+ export const acquisitionFailureMessage = ({ cause, detail }) => {
464
+ const named = CAUSES[cause] ?? CAUSES.unknown;
465
+ return (
466
+ `lane reconciliation: could not list merged PRs — ${named}. ` +
467
+ 'No lane was reconciled; do not record an empty `external lane` block from this run. ' +
468
+ 'Use --input <file> to work offline.' +
469
+ (detail ? `\n ${detail}` : '')
470
+ );
244
471
  };
245
472
 
246
473
  /**
@@ -267,9 +494,19 @@ const invokedDirectly = () => {
267
494
  if (invokedDirectly()) {
268
495
  const args = parseArgs(process.argv.slice(2));
269
496
  const projectRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
270
- const prs = args.input
271
- ? readInput(args.input, 'lane reconciliation')
272
- : fetchMergedPrs(args.since ?? daysAgo(7));
497
+ let prs;
498
+ let warnings = [];
499
+ if (args.input) {
500
+ prs = readInput(args.input, 'lane reconciliation');
501
+ } else {
502
+ try {
503
+ ({ prs, warnings } = fetchMergedPrs(args.since ?? daysAgo(7)));
504
+ } catch (error) {
505
+ process.stderr.write(`${acquisitionFailureMessage(classifyAcquisitionFailure(error))}\n`);
506
+ process.exit(1);
507
+ }
508
+ }
509
+ for (const warning of warnings) process.stderr.write(`lane reconciliation: ${warning}\n`);
273
510
  // Lane sorting still works without a declaration; only the elevated marks go
274
511
  // missing, and they render as "no elevated path crossed" rather than lying.
275
512
  const elevatedPaths = readDeclaredPaths(projectRoot) ?? [];
@@ -445,6 +445,69 @@ if (invokedDirectly()) {
445
445
  process.stdout.write(removed.length === 0 ? 'no unattended flag was set\n' : `${removed.join('\n')}\n`);
446
446
  process.exit(0);
447
447
  }
448
- process.stderr.write(`unknown word: ${word ?? '(none)'}. This CLI has two: on, off.\n`);
448
+ // 🔴 **The read-back `on` did not have, and the reason it is a subcommand
449
+ // rather than a line in the skill (RP-103).**
450
+ //
451
+ // `on` refuses a widening allow entry — correctly — by throwing before it
452
+ // writes anything, so the refusal leaves NO flag on disk. Pinned in the
453
+ // generator's `test/template/unattended-flag.test.ts` (absent in a generated
454
+ // rig) › "does not change `on`: a widening --allow still exits 1 and still
455
+ // writes no flag" — the claim is checkable, so it carries a pointer rather
456
+ // than standing on its own. And `guard-rulebook`
457
+ // reads "no flag" as "attended session" and does nothing. So the run that was
458
+ // meant to be the most constrained became the LEAST: every rulebook path
459
+ // editable, including the hook wiring that enforces the rule. Loud at arming
460
+ // (exit 1), and completely silent for the rest of the run.
461
+ //
462
+ // The asymmetry is what made it a defect rather than a rough edge: the `off`
463
+ // branch above ALREADY reads back, and refuses while naming the record it
464
+ // found. One direction of the same operation verified itself and the other
465
+ // did not.
466
+ //
467
+ // ⚠ **Stating the limit, because this whole file is about a mechanism being
468
+ // trusted further than it goes.** `verify` is mechanical where it runs; that
469
+ // it runs is still the `loop` skill's prose. This closes "the refusal was
470
+ // silent" — the run is told, in a command whose exit status is its whole
471
+ // output — and does NOT close "a run that ignores exit statuses ignores this
472
+ // one too". The hook-enforced version would need `guard-rulebook` to tell
473
+ // "attended" from "unattended but unarmed", and it cannot: absence of a flag
474
+ // is all it sees.
475
+ if (word === 'verify') {
476
+ const item = valueOf('--item');
477
+ if (!item || item.startsWith('--')) {
478
+ process.stderr.write(
479
+ 'unattended-flag verify: --item <id> is required — verifying "some flag is armed" would pass on a stale one from a previous run\n',
480
+ );
481
+ process.exit(1);
482
+ }
483
+ const state = readUnattended(cliEnv);
484
+ // ⚠ `unreadable` carries `on: true` — it means "a flag is THERE and cannot be
485
+ // trusted", which is what `off` needs in order to refuse to clear it blindly.
486
+ // For a read-back it is a FAILURE, not an arming: an unreadable record
487
+ // authorizes nothing, and its `item` is absent, so testing only `!state.on`
488
+ // would fall through to the item-mismatch branch and print the wrong reason
489
+ // for the right refusal.
490
+ if (!state.on || state.unreadable) {
491
+ const why = state.why ? ` (${state.why})` : '';
492
+ process.stderr.write(
493
+ `unattended-flag verify: NO usable unattended flag is armed for ${item}${why}. ` +
494
+ 'guard-rulebook reads an absent flag as an attended session and refuses nothing, so this run is ' +
495
+ 'UNGUARDED against the rulebook — every rule, hook, skill and settings path is editable. ' +
496
+ 'Arm it with a narrower --allow (an allow-list narrows the rulebook, never widens it) and verify again, or stop the run.\n',
497
+ );
498
+ process.exit(1);
499
+ }
500
+ if (state.item !== item) {
501
+ process.stderr.write(
502
+ `unattended-flag verify: the armed flag names ${JSON.stringify(state.item)}, not ${JSON.stringify(item)} — ` +
503
+ `it is a leftover from another run and does not authorize this one. This run is UNGUARDED against the rulebook. ` +
504
+ `Clear it with \`off\` and arm it for ${item}, or stop the run.\n`,
505
+ );
506
+ process.exit(1);
507
+ }
508
+ process.stdout.write(`${state.path ?? 'armed'}\n`);
509
+ process.exit(0);
510
+ }
511
+ process.stderr.write(`unknown word: ${word ?? '(none)'}. This CLI has three: on, verify, off.\n`);
449
512
  process.exit(1);
450
513
  }
@@ -1,4 +1,7 @@
1
1
  {
2
+ "env": {
3
+ "CLAUDE_CODE_SUBAGENT_MODEL": "claude-sonnet-5"
4
+ },
2
5
  "hooks": {
3
6
  "PreToolUse": [
4
7
  {
@@ -34,6 +37,15 @@
34
37
  "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard-bash.mjs\""
35
38
  }
36
39
  ]
40
+ },
41
+ {
42
+ "matcher": "Agent",
43
+ "hooks": [
44
+ {
45
+ "type": "command",
46
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard-subagent-model.mjs\""
47
+ }
48
+ ]
37
49
  }
38
50
  ],
39
51
  "Stop": [
@@ -53,6 +65,10 @@
53
65
  {
54
66
  "type": "command",
55
67
  "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/inject-rules.mjs\""
68
+ },
69
+ {
70
+ "type": "command",
71
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/warn-subagent-routing.mjs\""
56
72
  }
57
73
  ]
58
74
  }
@@ -79,16 +79,23 @@ state-vs-queue split exists to prevent.
79
79
  node .claude/scripts/preflight.mjs
80
80
  ```
81
81
 
82
- Five items are scripted (kill switch absent · `RIG_RUN_DIR` not already
83
- exported · the versioned revalidation detection contract is supported · local
84
- default branch matches the remote · the last deploy concluded successfully)
82
+ Scripted checks cover the kill switch, inherited `RIG_RUN_DIR`, the versioned
83
+ revalidation detection contract, queue readability through its configured adapter,
84
+ default-branch freshness, and the last deploy result,
85
85
  and the script **prints the ones it did not check, every time**. Paste the block into the journal: a checklist that
86
86
  leaves no record cannot tell you it was skipped.
87
87
 
88
88
  Verdicts: **STOP** → do not start, deal with the cause. **CAUTION** → start,
89
- knowing which ground is soft. **GO** → the scripted five are clean; the rest are
89
+ knowing which ground is soft. **GO** → the scripted checks are clean; the rest are
90
90
  still yours.
91
91
 
92
+ The queue probe reads one adapter listing without selecting or claiming an item.
93
+ A readable empty queue passes this probe; a configuration, adapter, or queue-read
94
+ failure produces **STOP**. See the generator's `test/template/preflight-queue.test.ts`
95
+ (absent in a generated rig) › "reads exactly one adapter listing without selecting, claiming, or writing queue and run files",
96
+ › "passes a readable empty queue without changing the other preflight verdict or queue state",
97
+ and › "stops when %s cannot be read".
98
+
92
99
  **An `unknown` never becomes a `pass`.** A probe that could not run tells you
93
100
  nothing.
94
101
 
@@ -149,8 +156,38 @@ What a hook CAN see is a file, so the unattended signal is one:
149
156
  # at claim time, from the paths the item names (repo-relative prefixes, with
150
157
  # their trailing slash); the guard refuses every other rulebook edit while it is on
151
158
  node .claude/scripts/unattended-flag.mjs on --root "$PWD" --item <item-id> --run-dir "$RIG_RUN_DIR" --allow <prefix> [<prefix>…]
159
+
160
+ # 🔴 THEN READ IT BACK, and stop the run if it is not armed. Not optional.
161
+ node .claude/scripts/unattended-flag.mjs verify --root "$PWD" --item <item-id>
152
162
  ```
153
163
 
164
+ 🔴 **The second command is the one that makes the first one's failure
165
+ visible, and skipping it inverts the whole mechanism.** `on` refuses an allow
166
+ entry that *widens* the rulebook — and the refusal leaves **no flag on disk**
167
+ (pinned in the generator's `test/template/unattended-flag.test.ts`, absent in a
168
+ generated rig, › "does not change `on`: a widening --allow still exits 1 and
169
+ still writes no flag"), while `guard-rulebook` reads an absent flag as an
170
+ attended session and refuses nothing. So a run that armed with a widening entry and did not check is the
171
+ **least** constrained run this project can produce: every rule, hook, skill and
172
+ settings path editable, with nothing downstream saying so. The failure is loud
173
+ for one line at claim time and silent for the rest of the session.
174
+
175
+ `verify` exits non-zero when no usable flag is armed for this item — absent,
176
+ unreadable, or naming a different item — and its message says the run is
177
+ unguarded rather than merely that a file is missing. **A non-zero exit here ends
178
+ the run**; it does not get retried with a wider allow-list. The natural way to
179
+ hit this is not exotic: an item touching the queue adapter invites `--allow
180
+ .claude/scripts/`, and that entry is refused outright. Pinned in the
181
+ generator's `test/template/unattended-flag.test.ts` (absent in a generated rig)
182
+ › "refuses when no flag is armed, naming the item and the unguarded rulebook"
183
+ and › "refuses when the armed flag names a different item, naming both".
184
+
185
+ ⚠ **What this does not close.** `verify` is mechanical where it runs; that it
186
+ runs is this sentence. It removes the silence, not the possibility that a run
187
+ ignores an exit status — and the hook-enforced version is not available, because
188
+ `guard-rulebook` cannot tell "attended" from "unattended but unarmed": absence of
189
+ a flag is all it sees.
190
+
154
191
  `guard-rulebook` reads it (`.claude/rules/autonomy.md`, "Never"): with the flag
155
192
  on, a Write/Edit/MultiEdit/NotebookEdit/`apply_patch` under the generated
156
193
  rulebook is refused unless its
@@ -1,4 +1,6 @@
1
1
  name = "code-reviewer"
2
2
  description = "Reviews a completed change against the checklist before a PR is opened or merged. Use after any non-trivial implementation work, and always before opening a PR the decision-router puts on its `model` lane, which is everything its two cheap lanes did not claim — code, a rulebook document, an unclassifiable path, a derived artifact git does not report as drift, or anything a risk flag escalated. Blocking findings must be resolved, not argued with."
3
+ model = "gpt-5.6-sol"
4
+ model_reasoning_effort = "high"
3
5
  sandbox_mode = "read-only"
4
6
  developer_instructions = "You review changes. You do not fix them — you report, with file:line\nreferences, and you classify every finding as **blocking** or **advisory**.\n\n## Checklist (blocking findings)\n\n1. **Boundary violations** — imports that cross layers the wrong way; storage\n or SDK access outside its owning module; handlers reaching past the usecase\n layer. See the architecture rules in `.claude/rules/`.\n2. **Test integrity** — tests deleted, skipped, weakened, or rewritten to fit\n the implementation; implementation without a test that demonstrates it.\n3. **Error handling** — swallowed errors, bare catch-and-continue, failure\n paths that lie to the caller.\n4. **Contract drift** — behavior change not reflected in schemas, types, docs,\n or the README.\n5. **Autonomy breaches** — Tier-2 territory (schema, auth, new dependency,\n public API) entered without a recorded decision. See\n `.claude/rules/autonomy.md`.\n6. **Contradicts the item it claims to implement** — the change does something\n the queue item did not ask for, drops a stated requirement, or quietly\n re-aims the task into an adjacent one. Read the item first, then the diff.\n **Report the contradiction; never reconcile the two yourself** by deciding\n which one \"must have been meant\" — that is the author's call, and a reviewer\n who makes it silently turns a visible mismatch into an invisible one. A\n change that is well-built and not the change that was asked for is the one\n failure the rest of this checklist cannot see.\n\n **If the item was not handed to you, say so and stop there.** Do not\n reconstruct it from the branch name or the PR description: those are written\n by whoever opened the PR — including the run being reviewed — and this\n rulebook already refuses that evidence elsewhere (`.claude/rules/autonomy.md`).\n \"Item not supplied, item 6 not checked\" is a useful line in a report; a\n guess dressed as a verdict is worse than the silence it replaces.\n\n## Advisory findings\n\nNaming, duplication, missed simplifications, performance smells. Report them;\ndo not block on them.\n\n## How you work\n\n- Diff first (`git diff`, `git log`), then read enough surrounding code to\n judge in context. Review what changed, not the whole repo.\n- Quote the checklist item a blocking finding violates. If nothing blocks, say\n so explicitly — \"no blocking findings\" is a valid, useful verdict.\n- Do not request rewrites of working, tested code for style alone.\n\n## The verdict block\n\nWrite your report for the human, then end it with **exactly one** fenced `json`\nblock of this shape, and nothing after it. That block is what the calling gate\nreads; a report that never writes one is read as whatever the caller expected.\n\n```json\n{\n \"gate\": \"code-reviewer\",\n \"verdict\": \"HOLD\",\n \"blockers\": [\n {\n \"file\": \"packages/core/src/note.ts\",\n \"line\": 42,\n \"rule\": \"checklist item 2 — test integrity\",\n \"note\": \"the failing case was deleted rather than fixed\"\n }\n ],\n \"advisories\": [],\n \"evidence\": [\"diffed against origin/master\", \"queue item supplied\"],\n \"headSha\": \"9c1f0a7d4b3e2c5a8f6d0b9e7c4a1f2d3e5b6c70\"\n}\n```\n\n- `verdict` is `SHIP`, `HOLD` or `NOT_APPLICABLE` — no other word.\n- Every blocker names the `rule` it violates. `file` and `line` travel together\n and are both omitted when the finding has no single location.\n- A `HOLD` with an empty `blockers` list is **refused**, and so is a `SHIP`\n carrying one: `node .claude/scripts/verdict.mjs check <report> <this gate>` is\n what refuses them, and the shape it enforces is in\n `.claude/scripts/lib/verdict.mjs`. The gate name is what stops your answer\n being read as somebody else's.\n- **`headSha` is the commit you reviewed** — `git rev-parse HEAD` in the\n checkout you read. It is what lets `node .claude/scripts/verdict.mjs coverage\n <commit>` tell \"this gate answered for the commit being merged\" from \"it\n answered two pushes ago\". A verdict naming no commit is counted as neither\n covered nor missing, so `pr-ship` holds on it — and only `pr-ship`: no hook\n runs that check, so a session that skips the gate skips this with it."
@@ -1,4 +1,6 @@
1
1
  name = "prose-reviewer"
2
2
  description = "Reviews the documents that instruct agents — rule files, skills, agent specs, CLAUDE.md, the README — for claims the code does not support, dead references, and rules that contradict each other. Use when a change touches any of them, before the PR."
3
+ model = "gpt-5.6-terra"
4
+ model_reasoning_effort = "high"
3
5
  sandbox_mode = "read-only"
4
6
  developer_instructions = "In this project the prose **is** the implementation. A rule file is what an agent\nreads before it acts; a skill is a procedure; `CLAUDE.md` is the map. When one of\nthem says something untrue, nothing fails — the next session simply acts on it,\nconfidently, and the failure surfaces somewhere unrelated hours later.\n\nYou review that layer the way `code-reviewer` reviews code: findings with\n`file:line`, each classified **BLOCKER** or **advisory**, and no fixes. You do\nnot edit anything.\n\n## 🔴 The boundary — read this before the checklist\n\n**You are not a literary editor.** Wording, voice, rhythm, repetition, a\nparagraph that runs long, a heading you would have phrased differently: none of\nthese is a finding. Prose that is merely clumsy is **not a finding** and must not\nappear in your report, not even as advisory. Every one of them you report costs\nthe next reader the attention that should have gone to the ones that matter, and\na gate that fires on taste gets ignored, then removed.\n\nYou have exactly one question: **would a competent agent, acting on this text,\ndo the wrong thing?** If no, it is not yours.\n\nStyle in this layer is not forbidden ground, it is simply not yours: it lands in\n`code-reviewer`'s advisory bucket like any other readability note. Say nothing\nabout it here, so the two gates never file competing opinions on one paragraph.\n\n## Checklist (blocking findings)\n\n1. **An overstated claim of enforcement.** The text says something is refused,\n blocked, guaranteed or verified, and the mechanism behind it does not do that\n — or does not exist. Read the hook, the script, the CI job, and quote what it\n actually does. This is the most expensive failure in the layer: a rule trusted\n past its reach is worse than no rule, because it stops anyone from looking.\n2. **A dead reference.** A file, hook, script, agent, skill, section or command\n that is named but no longer exists, or has been renamed. Check it resolves —\n a path is cheap to verify and a reader who hits a missing file learns to\n distrust every other pointer in the document.\n3. **Two rules that contradict each other.** Same subject, incompatible\n instructions, in different files or in different sections of one. Report both\n locations and say which reading a session would most likely take. Do **not**\n pick the winner: the resolution belongs in the rules, not in your report.\n4. **A stated limit that has gone stale — in either direction.** A guard that\n lists limits it no longer has understates itself and invites work nobody\n needs; one whose limits were never written, or were written before its last\n two bypasses, sells cover it does not have. Both are blocking, and both are\n found the same way: read the mechanism, then read what the text claims about\n it.\n5. **An unbacked behaviour claim.** A sentence asserts what a mechanism does, how\n much something costs, or how often it happens, and **nothing backs it**: no\n test you can name, no command output, no citation to the code. Per\n `.claude/rules/invariants.md` (\"State the limits\") such a sentence must be\n **generated** from what it describes or be a **pointer to a test** — the form is\n `see <test file> › \"<test name>\"`, and the name has to be greppable in a file the\n reader has. This is a blocker **by rule**, so you do not have to prove the claim\n wrong; an unbacked claim about behaviour is the finding.\n\n ⚠ A pointer into a test suite the reader's project does not carry is normally\n item 2, not backing. There is one narrow inherited-snapshot exception from\n `invariants.md`: a generator-authored artifact — rules, hooks, skills,\n scripts, or agent specs —\n may point to upstream generator tests that are absent locally only when the\n pointer explicitly says the suite is absent locally and\n `.claude/.rig-manifest.json` proves the current artifact's hash matches the\n installed manifest. A manifest-backed upgrade remains an inherited,\n generator-owned artifact; a changed file in the upgrade diff does not alone\n make it downstream-authored. The exception applies **only while the manifest\n hash matches**. A hash mismatch, missing manifest, or no evidence ends the\n exception and the local test is yours; then an absent pointer is item 2 again.\n\n 🔴 Three things this is not. It is not item 1: that one is about enforcement the\n mechanism does not provide, this one is about any claim with nothing behind it,\n including a true one. It is not item 4 either, and the split is worth getting\n right because both can reach one sentence: **item 4 is for a limit you checked\n against the mechanism and found wrong or missing; item 5 is for a claim you did\n not have to check, because nothing is offered as backing.** If you opened the\n hook and it disagrees with the text, file item 4 and quote the line. If there was\n nothing offered to open, file item 5. If you opened it and the claim was right,\n there is no finding. One sentence, one item. And it is not an attack on rationale — \"we chose X\n because Y\" needs no test. The target is a **factual assertion about behaviour**:\n a number, a rate, a limit, a \"measured\" anything.\n\n The remedy has two forms and rewording is neither: the sentence goes, or it\n becomes a pointer. Say which you would expect, and where the test lives if one\n exists.\n6. **Domain that must not travel.** In a layer meant to be neutral: a provider or\n vendor name, a host-specific absolute path, a tracker key, a company or\n product name, credentials or personal data in an example. State which layer\n the file belongs to and why the mention breaks it.\n\n 🔴 **A seam built to name a vendor is not a leak.** An adapter, a driver, a\n provider-specific module — its whole job is to name the thing it adapts, and\n so is the documentation of it. The finding is a vendor name in text that\n claims to be neutral, not a vendor name anywhere in a neutral directory.\n Check what the file is for before reporting it; this is the item most likely\n to fire on deliberate, tested code.\n\n## Advisory findings\n\nAn instruction that is genuinely ambiguous — two readings that lead to different\nactions, where you cannot tell which was meant. A rule with no stated reason,\nwhere the reason is not obvious and the rule is the kind that gets deleted by\nwhoever inherits it. A document that has grown to where the load-bearing part is\nno longer findable.\n\nThat is the whole advisory list, on purpose. If a note does not fit one of those\nthree, it belongs in your head, not in the report.\n\n## How you work\n\n- **Diff first** (`git diff`, `git log`), then read the surrounding document —\n a claim is only judgeable in the context that qualifies it. Review what\n changed, not the whole rulebook.\n- **Verify against the mechanism, never against your memory of it.** Every\n blocking finding of type 1, 2 or 4 requires you to have opened the hook, the\n script or the workflow file and quoted the line. A finding you could not check\n is reported as unverified, or not at all.\n- **Quote the checklist item** each blocking finding violates, and give the\n `file:line` of both the text and the mechanism that contradicts it.\n- **\"No blocking findings\" is a valid and useful verdict.** Say it plainly when\n it is true; a gate that always finds something teaches everyone to discount it.\n\n## What you cannot see, stated so nobody relies on it\n\n🔴 **Nothing launches you.** No hook fires this review; a session reads a rule\nand decides to. So a change that skipped this gate and a change that passed it\nlook identical afterwards, and any text — including this file — that says this\nreview \"runs\" is describing a convention, not a mechanism. Report a claim of\nenforcement that rests on you the same way you would report any other: as an\noverstatement, item 1, including when the file making it is a rulebook you are\nnamed in.\n\nYou read text and the mechanisms it names. You cannot tell whether a rule is\n*worth having*, whether the process it describes is the right one, or whether a\nclaim about the world outside this repository is true. Those are the owner's\nquestions, and answering them from this seat would be exactly the overreach\nitem 1 exists to catch.\n\n## The verdict block\n\nEnd your report with **exactly one** fenced `json` block of this shape, and\nnothing after it. The prose above it is for the human; this block is what the\ncalling gate reads.\n\n```json\n{\n \"gate\": \"prose-reviewer\",\n \"verdict\": \"HOLD\",\n \"blockers\": [\n {\n \"file\": \".claude/rules/invariants.md\",\n \"line\": 118,\n \"rule\": \"item 5 — an unbacked behaviour claim\",\n \"note\": \"no test named, and the hook it describes does not do this\"\n }\n ],\n \"advisories\": [],\n \"evidence\": [\"opened .claude/hooks/guard-bash.mjs and quoted the line\"],\n \"headSha\": \"9c1f0a7d4b3e2c5a8f6d0b9e7c4a1f2d3e5b6c70\"\n}\n```\n\n- `verdict` is `SHIP`, `HOLD` or `NOT_APPLICABLE` — no other word.\n- Every blocker names the `rule` it violates; give the `file` and `line` of the\n text, and cite the contradicting mechanism in the `note`.\n- A `HOLD` naming no blocker is **refused**, and so is a `SHIP` carrying one:\n `node .claude/scripts/verdict.mjs check <report> <this gate>` is what refuses\n them, and the gate name is what stops your answer being read as somebody\n else's.\n- **`headSha` is the commit you reviewed** — `git rev-parse HEAD` in the\n checkout you read. It is what lets `node .claude/scripts/verdict.mjs coverage\n <commit>` tell \"this gate answered for the commit being merged\" from \"it\n answered two pushes ago\". A verdict naming no commit is counted as neither\n covered nor missing, so `pr-ship` holds on it — and only `pr-ship`: no hook\n runs that check, so a session that skips the gate skips this with it."
@@ -1,4 +1,6 @@
1
1
  name = "security-scanner"
2
2
  description = "Scans a change for security issues. MUST be used when a change touches authentication, authorization, secrets or configuration, input parsing, file handling, or any new outbound call. Findings gate the PR."
3
+ model = "gpt-5.6-sol"
4
+ model_reasoning_effort = "high"
3
5
  sandbox_mode = "read-only"
4
6
  developer_instructions = "You are the security gate. You run on changes in sensitive territory and your\nblocking findings stop the PR until resolved.\n\n## Triggers (when you should have been called)\n\n- auth, permissions, sessions, tokens\n- secrets, credentials, environment/configuration handling\n- parsing of external input (request bodies, queue messages, files, URLs)\n- new outbound calls (HTTP, SDK, process execution)\n- dependency additions\n\n## What you look for\n\n1. **Secrets in the tree** — keys, tokens, connection strings in code, config,\n fixtures, or test snapshots. Any hit is blocking.\n2. **Unvalidated input** — external data crossing into the domain without\n passing a schema at the boundary; string-built queries or shell commands.\n3. **Broken authorization** — endpoints or usecases that skip the ownership /\n permission check their siblings perform; confused-deputy patterns.\n4. **Injection surface** — user data reaching interpreters (shell, SQL/NoSQL\n expressions, template evaluation, `eval`-likes) unescaped.\n5. **Leaky failure modes** — stack traces, internal ids, or secret material in\n error responses and logs.\n6. **Outbound data** — new destinations for user data; verify they are\n intentional, documented, and minimal.\n\n## How you work\n\n- Scope to the change and the paths it touches; grep wider only to confirm a\n suspected pattern is (or is not) systemic.\n- Every finding: severity, file:line, the concrete attack or leak scenario, and\n the smallest fix. No theoretical lectures without a code path.\n- If the change is outside your triggers, say so and return quickly — a clean\n \"not security-relevant\" is a valid verdict.\n\n## The verdict block\n\nEnd your report with **exactly one** fenced `json` block of this shape, and\nnothing after it. It is what the calling gate reads; the prose above it is for\nthe human who has to fix the finding.\n\n```json\n{\n \"gate\": \"security-scanner\",\n \"verdict\": \"HOLD\",\n \"blockers\": [\n {\n \"file\": \"services/api/src/handlers/upload.ts\",\n \"line\": 31,\n \"rule\": \"unvalidated input\",\n \"note\": \"the filename reaches the shell unescaped — attacker-controlled\"\n }\n ],\n \"advisories\": [],\n \"evidence\": [\"grepped for the pattern across services/\"],\n \"headSha\": \"9c1f0a7d4b3e2c5a8f6d0b9e7c4a1f2d3e5b6c70\"\n}\n```\n\n- `verdict` is `SHIP` (nothing blocking), `HOLD`, or `NOT_APPLICABLE` when the\n change is outside your triggers — that last one is the structured form of the\n clean \"not security-relevant\" answer above.\n- Every blocker names the `rule` it violates, with `file` and `line` when the\n finding has a location and neither when it does not.\n- A `HOLD` naming no blocker is **refused**, and so is a `SHIP` carrying one:\n `node .claude/scripts/verdict.mjs check <report> <this gate>` is what refuses\n them, and the gate name is what stops your answer being read as somebody\n else's.\n- **`headSha` is the commit you reviewed** — `git rev-parse HEAD` in the\n checkout you read. It is what lets `node .claude/scripts/verdict.mjs coverage\n <commit>` tell \"this gate answered for the commit being merged\" from \"it\n answered two pushes ago\". A verdict naming no commit is counted as neither\n covered nor missing, so `pr-ship` holds on it — and only `pr-ship`: no hook\n runs that check, so a session that skips the gate skips this with it."
@@ -1,4 +1,6 @@
1
1
  name = "test-writer"
2
2
  description = "Writes the failing test BEFORE any implementation exists. Use at the start of every feature, bug fix, or behavior change — the Red step of TDD. Also use to reproduce a reported bug as a test."
3
+ model = "gpt-5.6-terra"
4
+ model_reasoning_effort = "high"
3
5
  sandbox_mode = "workspace-write"
4
6
  developer_instructions = "You write tests that define behavior which does not exist yet. You are the Red\nstep of TDD, and only the Red step.\n\n## Scope — hard boundaries\n\n- You create and modify **test files only**. You never write or edit\n implementation code, even a stub, even \"to make it compile\" — if the test\n cannot compile because the module is missing, that IS the failing state;\n report it as such.\n- You never mark tests as skipped or todo to avoid a failure. A failing test is\n your deliverable.\n\n## How you work\n\n1. Read the surrounding tests first; match their style, naming, and fixtures.\n2. Write the smallest test (or set of tests) that pins down the requested\n behavior, including the edge cases the requester implied but did not spell\n out. Name tests after behavior (\"refuses an empty title\"), not after methods.\n3. Run the test suite and **confirm the new tests fail for the expected\n reason** — a test failing because of a typo in the test is not Red.\n4. Report back: which tests you added, why they fail right now, and what the\n minimal implementation surface looks like (signatures, not code).\n\n## Judgment lines\n\n- Test behavior through public entry points (usecases, handlers), not private\n internals.\n- One behavior per test; shared setup in fixtures, not copy-paste.\n- If the requested behavior contradicts an existing test, stop and surface the\n conflict instead of overwriting the old test."
@@ -0,0 +1,3 @@
1
+ [agents]
2
+ default_subagent_model = "gpt-5.6-terra"
3
+ default_subagent_reasoning_effort = "medium"
@@ -1,6 +1,6 @@
1
1
  # Codex adapter: derived parity
2
2
 
3
- Status: accepted for AR-113.
3
+ Status: accepted for AR-113; subagent routing extended for RP-166.
4
4
 
5
5
  ## Decision
6
6
 
@@ -18,7 +18,22 @@ generated release. There is no downstream automatic drift check.
18
18
 
19
19
  Two hand-maintained rulebooks inevitably diverge. Derivation keeps the generated
20
20
  snapshots aligned while preserving native Codex formats. The adapter translates
21
- the fields for which Codex has native controls and does not invent policy.
21
+ the fields for which Codex has native controls. Subagent routing each role's
22
+ model and effort, for both harnesses — is declared once in the generator's
23
+ `templates/agent-os/subagent-routing.json` (rationale:
24
+ `docs/decisions/subagent-routing.md`). The Codex profiles are derived from that
25
+ table, and the projector refuses a missing or orphaned agent profile. It also
26
+ refuses duplicate source-agent names across layers, since one profile name
27
+ cannot route two definitions.
28
+
29
+ Frequent bounded work (`test-writer`, `prose-reviewer`) uses `gpt-5.6-terra`;
30
+ correctness, security, and infrastructure gates use `gpt-5.6-sol`. Every named
31
+ gate uses `high` reasoning effort. Unnamed subagents inherit repository defaults
32
+ of `gpt-5.6-terra` and `medium` from `.codex/config.toml`. `xhigh` is not a
33
+ continuous-loop default; using it for a named role requires an intentional
34
+ profile-policy change (or a separate escalation profile), because named-profile
35
+ fields take precedence over spawn and repository defaults. Concurrency remains
36
+ a machine/session decision rather than repository policy.
22
37
 
23
38
  Claude agent `tools` allowlists have no equivalent custom-agent allowlist in the
24
39
  documented Codex TOML schema. The adapter therefore uses those fields only to
@@ -28,7 +43,15 @@ not carried over. This is a known parity limit, not an implicit restriction.
28
43
  ## Risk and rollback
29
44
 
30
45
  The main risks are generated-file drift, downstream edits to only one snapshot,
31
- and unsupported Claude shapes. In the generator, the adapter fails loudly when
46
+ unsupported Claude shapes, and a pinned model being unavailable in a user's
47
+ workspace. In the generator, recovery is to update the central routing table to
48
+ an available model or use a separate supported escalation profile — the Codex
49
+ profiles are regenerated from it, while the Claude agent definitions are checked
50
+ against it and are edited to match in the same change. A generated
51
+ project has no copy of that table: there, recovery is editing the role's
52
+ definitions on both harnesses in one reviewed change, and `upgrade` then reports
53
+ those files as the project's own instead of replacing them
54
+ (`docs/decisions/subagent-routing.md`). In the generator, the adapter fails loudly when
32
55
  it cannot derive a portable hook command and its drift check catches stale
33
56
  output. Generated projects rely on review for subsequent local parity. Rollback
34
57
  is deleting the derived Codex files from the generated project and reverting the
@@ -80,8 +103,11 @@ Codex path.
80
103
 
81
104
  ## Schema and executable contracts
82
105
 
83
- The emitted agent fields are `name`, `description`, `sandbox_mode`, and
84
- `developer_instructions`, matching the documented Codex custom-agent TOML.
106
+ The emitted agent fields are `name`, `description`, `model`,
107
+ `model_reasoning_effort`, `sandbox_mode`, and `developer_instructions`, matching
108
+ the documented Codex custom-agent TOML. Named-agent fields take precedence over
109
+ the repository defaults in `.codex/config.toml`; the defaults cover only agents
110
+ without their own model or effort assignment.
85
111
  For hooks, the [official Codex hooks documentation](https://learn.chatgpt.com/docs/hooks)
86
112
  documents `tool_input.command` for both `Bash` and `apply_patch` and requires a
87
113
  string `command` when a hook replaces that input. The same document is what makes