@jjanczur/tyran 0.1.0 → 0.1.3

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.
@@ -63,7 +63,7 @@
63
63
  * read rule, which needs no configuration and is what the incident above
64
64
  * actually called for.
65
65
  */
66
- import { realpathSync } from 'node:fs';
66
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
67
67
  import { readFile, stat } from 'node:fs/promises';
68
68
  import { basename, dirname, join, resolve as resolvePath } from 'node:path';
69
69
  import { fileURLToPath } from 'node:url';
@@ -314,6 +314,83 @@ export class PolicyFailure extends Error {
314
314
  }
315
315
  }
316
316
 
317
+ // ------------------------------------------------------------- git worktrees
318
+
319
+ /**
320
+ * A linked worktree's main checkout, or null when this IS the main checkout.
321
+ *
322
+ * Two field reports on 0.1.2 described opposite failures with one cause: this
323
+ * gate treated "the repository" as "this directory tree", and a git worktree is
324
+ * neither inside it nor a different repository.
325
+ *
326
+ * - a session running IN a worktree found no `.tyran/` there — the directory
327
+ * is committed data, but `git worktree add` gives you a fresh checkout and
328
+ * the tree only travels if it was committed — so `loadPolicy` returned null
329
+ * and the gate went SILENT. Measured: four worktrees, four implementers with
330
+ * no autonomy class and no path classes, and `git push origin main` passing;
331
+ * - a session running in the main checkout and writing into a sibling worktree
332
+ * got `normalizePath` -> null -> unconditional KERNEL, so every `Edit` was
333
+ * refused as "outside this repository". Five agents hit it in one initiative
334
+ * and all converged on `python3` heredocs through `Bash`, which this gate
335
+ * does not class at all. A refusal that reroutes work into a less visible
336
+ * channel is worse than no refusal.
337
+ *
338
+ * Both are fixed by asking the same question — *which repository is this path
339
+ * in* — instead of *is this path under my root*.
340
+ *
341
+ * Detection is pure filesystem, deliberately. `.git` is a DIRECTORY in a main
342
+ * checkout and a FILE in a linked worktree, holding `gitdir: <path>`. Reading
343
+ * it costs a stat and a small read; asking git would cost a subprocess on the
344
+ * write path, which today does none at all and is measured at ~50 ms.
345
+ */
346
+ export function mainWorktreeOf(root) {
347
+ const dotGit = join(root, '.git');
348
+ let text;
349
+ try {
350
+ if (statSync(dotGit).isDirectory()) return null;
351
+ text = readFileSync(dotGit, 'utf8');
352
+ } catch {
353
+ return null;
354
+ }
355
+ if (text.length > MAX_GITFILE_BYTES) return null;
356
+ const match = /^gitdir:\s*(.+)$/m.exec(text);
357
+ if (match === null) return null;
358
+ // `<main>/.git/worktrees/<name>` — the main checkout is what precedes it.
359
+ const gitdir = resolvePath(root, match[1].trim()).replace(/\\/g, '/');
360
+ const marker = '/.git/worktrees/';
361
+ const at = gitdir.indexOf(marker);
362
+ return at === -1 ? null : gitdir.slice(0, at);
363
+ }
364
+
365
+ /** A `.git` file is one short line. Anything larger is not one (ADR-22 c1 D). */
366
+ export const MAX_GITFILE_BYTES = 4096;
367
+
368
+ /** How far up from a path to look for the checkout containing it. */
369
+ const MAX_WORKTREE_WALK = 64;
370
+
371
+ /**
372
+ * The checkout root containing `path`, and the repository it belongs to.
373
+ *
374
+ * Returns `{ checkout, repository }` where `repository` is the main worktree —
375
+ * the identity two sibling worktrees share — or null when no checkout is found.
376
+ */
377
+ export function checkoutOf(path) {
378
+ let cursor = resolvePath(path);
379
+ for (let i = 0; i < MAX_WORKTREE_WALK; i++) {
380
+ let exists = false;
381
+ try {
382
+ exists = statSync(join(cursor, '.git')) !== null;
383
+ } catch {
384
+ exists = false;
385
+ }
386
+ if (exists) return { checkout: cursor, repository: mainWorktreeOf(cursor) ?? cursor };
387
+ const parent = dirname(cursor);
388
+ if (parent === cursor) return null;
389
+ cursor = parent;
390
+ }
391
+ return null;
392
+ }
393
+
317
394
  /** The repository this call is about. Explicit, never defaulted per call site. */
318
395
  export function repoRootOf(input, env = process.env) {
319
396
  const fromEnv = env.CLAUDE_PROJECT_DIR;
@@ -364,13 +441,32 @@ async function readBounded(path, what) {
364
441
  * that lets writes through is the defect this whole epic is about.
365
442
  */
366
443
  export async function loadPolicy(root) {
367
- const text = await readBounded(join(root, POLICY_PATH), 'the autonomy policy');
444
+ // A linked worktree inherits its repository's policy. Without this a
445
+ // worktree with no `.tyran/` of its own reads as "this repo never adopted
446
+ // Tyran" and the gate goes silent — measured in the field as four worktrees
447
+ // running four implementers with no autonomy class at all. Tried in order,
448
+ // so a `.tyran/` that DID travel with the worktree still wins.
449
+ const roots = [root, mainWorktreeOf(root)].filter((r) => r !== null);
450
+ let text = null;
451
+ let from = root;
452
+ for (const candidate of roots) {
453
+ text = await readBounded(join(candidate, POLICY_PATH), 'the autonomy policy');
454
+ if (text !== null) {
455
+ from = candidate;
456
+ break;
457
+ }
458
+ }
368
459
  if (text === null) {
369
460
  let adopted = false;
370
- try {
371
- adopted = (await stat(join(root, TYRAN_DIR))).isDirectory();
372
- } catch {
373
- adopted = false;
461
+ for (const candidate of roots) {
462
+ try {
463
+ if ((await stat(join(candidate, TYRAN_DIR))).isDirectory()) {
464
+ adopted = true;
465
+ break;
466
+ }
467
+ } catch {
468
+ /* keep looking */
469
+ }
374
470
  }
375
471
  if (!adopted) return null;
376
472
  throw new PolicyFailure(
@@ -403,7 +499,14 @@ export async function loadPolicy(root) {
403
499
 
404
500
  /** Load the deployment class from config.yaml, or refuse. `null` = no config. */
405
501
  export async function loadDeployClass(root) {
406
- const text = await readBounded(join(root, CONFIG_PATH), 'the Tyran config');
502
+ // Same inheritance as the policy, and for the sharper reason: without it a
503
+ // `git push origin main` from inside a worktree found no config, concluded
504
+ // the repo had not adopted Tyran, and PASSED at every deployment class.
505
+ let text = null;
506
+ for (const candidate of [root, mainWorktreeOf(root)].filter((r) => r !== null)) {
507
+ text = await readBounded(join(candidate, CONFIG_PATH), 'the Tyran config');
508
+ if (text !== null) break;
509
+ }
407
510
  if (text === null) return null;
408
511
  let doc;
409
512
  try {
@@ -595,7 +698,25 @@ function canonicalDeepest(raw) {
595
698
  * outside. Two spellings of one location must not resolve to two classes.
596
699
  */
597
700
  export function repoRelative(raw, root) {
598
- return normalizePath(canonicalDeepest(raw), canonicalDeepest(root));
701
+ const direct = normalizePath(canonicalDeepest(raw), canonicalDeepest(root));
702
+ if (direct !== null) return direct;
703
+ // Not under this root — but a git worktree of the SAME repository is not
704
+ // "outside the repository", and calling it that refused every Edit an
705
+ // implementer made in the worktree rule 7 tells the conductor to give it.
706
+ // Five agents hit this in one initiative and all rerouted their writes
707
+ // through `Bash` heredocs, which this gate does not class at all.
708
+ //
709
+ // The test is repository IDENTITY, never proximity: both sides resolve to a
710
+ // main checkout and those must be the same path. A path in a DIFFERENT
711
+ // repository still normalizes to null and is still KERNEL, which is the
712
+ // property that keeps this from being a hole.
713
+ const target = checkoutOf(canonicalDeepest(raw));
714
+ if (target === null) return null;
715
+ const session = checkoutOf(canonicalDeepest(root));
716
+ if (session === null || target.repository !== session.repository) return null;
717
+ // Classified against the worktree it lives in, so `.tyran/knowledge/x.yaml`
718
+ // in a worktree is the same class as in the main checkout.
719
+ return normalizePath(canonicalDeepest(raw), target.checkout);
599
720
  }
600
721
 
601
722
  /** Every path this tool call names. Prototype-safe, deduplicated, order-stable. */
@@ -1205,10 +1326,17 @@ async function decideBash({ input, toolInput, root, runner, budget }) {
1205
1326
  // config in an ADOPTED repo refuses, exactly as a missing policy does.
1206
1327
  // Only a repo with no `.tyran/` at all is silent.
1207
1328
  let adopted = false;
1208
- try {
1209
- adopted = (await stat(join(root, TYRAN_DIR))).isDirectory();
1210
- } catch {
1211
- adopted = false;
1329
+ // The worktree's repository, not just the worktree: a push from a linked
1330
+ // checkout must not read as "Tyran does not run here" (see loadPolicy).
1331
+ for (const candidate of [root, mainWorktreeOf(root)].filter((r) => r !== null)) {
1332
+ try {
1333
+ if ((await stat(join(candidate, TYRAN_DIR))).isDirectory()) {
1334
+ adopted = true;
1335
+ break;
1336
+ }
1337
+ } catch {
1338
+ /* keep looking */
1339
+ }
1212
1340
  }
1213
1341
  if (!adopted) return PASS;
1214
1342
  throw new PolicyFailure(
@@ -1342,8 +1470,11 @@ const DEPLOY_REMEDY = Object.freeze(Object.assign(Object.create(null), {
1342
1470
  'recoverable from this session, which is the whole reason they are outside every autonomy class.',
1343
1471
  production:
1344
1472
  'What to do instead: push to your own branch and open a pull request. The class lives in ' +
1345
- `\`${CONFIG_PATH}\`, which ADR-06 classifies GATED rather than KERNEL, so raising it is an ` +
1346
- 'operator decision by CONVENTION, not by mechanism: measured in review, an agent in an ' +
1473
+ `\`${CONFIG_PATH}\`, and it is your own policy that decides whether an agent may edit that ` +
1474
+ 'file — the shipped template classifies it AUTO — so keeping the class where the operator put ' +
1475
+ 'it is by CONVENTION, not by mechanism. No class is named here on purpose: this text would ' +
1476
+ 'otherwise go stale the moment a repo reclassified the file, and a refusal that states the ' +
1477
+ 'wrong reason is worse than one that states none. Measured in review, an agent in an ' +
1347
1478
  'unattended main loop edited P1 to P3 with no refusal. Treat raising it yourself as the thing ' +
1348
1479
  'you were asked not to do, and say in your report that you wanted to.',
1349
1480
  shared:
@@ -304,6 +304,75 @@ export function isAbbreviationOf(token, longOption, minimum = 4) {
304
304
  return token.length >= minimum && token.length <= longOption.length && longOption.startsWith(token);
305
305
  }
306
306
 
307
+ // ------------------------------------------------------ the subcommand slot
308
+
309
+ /**
310
+ * git's own options, which sit BEFORE the subcommand. These consume the token
311
+ * after them, so a resolver that skipped only tokens starting with `-` would
312
+ * read `git -C push …` as the subcommand `push` when the directory is called
313
+ * `push`, and `git -c alias.x=y stash` as `alias.x=y`.
314
+ */
315
+ export const GIT_GLOBAL_VALUE_FLAGS = Object.freeze([
316
+ '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env', '--super-prefix',
317
+ ]);
318
+
319
+ /**
320
+ * Subcommands that are a NAMESPACE: their own second word is the verb.
321
+ *
322
+ * This is the whole reason `git stash push` was misread as a publish. Keeping
323
+ * the list explicit rather than "anything with two words" means a new git
324
+ * subcommand is read as a plain verb — the conservative direction, because an
325
+ * unknown verb in the first slot is compared against `push`/`commit`/`add`
326
+ * directly and still matches when it is one of them.
327
+ */
328
+ export const GIT_NAMESPACE_SUBCOMMANDS = Object.freeze([
329
+ 'stash', 'subtree', 'worktree', 'remote', 'submodule', 'bundle', 'notes', 'sparse-checkout', 'maintenance',
330
+ ]);
331
+
332
+ /** The next token that is not a flag or a flag's value, from `from`. */
333
+ function nextWord(tokens, from) {
334
+ for (let k = from; k < tokens.length; k++) {
335
+ const token = tokens[k];
336
+ if (GIT_GLOBAL_VALUE_FLAGS.includes(token)) {
337
+ k++;
338
+ continue;
339
+ }
340
+ if (token === '--' || token.startsWith('-')) continue;
341
+ return { name: token, index: k };
342
+ }
343
+ return null;
344
+ }
345
+
346
+ /**
347
+ * What this git command actually DOES, from the subcommand slot.
348
+ *
349
+ * Returns `{ name, index }` where `name` is the verb and `index` is where that
350
+ * verb sits, so a caller slicing "everything after the verb" gets the right
351
+ * tokens. For a namespace subcommand the verb is the second word:
352
+ * `git stash push` answers `push` at the index of the SECOND token — which is
353
+ * why callers must ask `name === 'push'` *and* check the namespace, rather
354
+ * than trusting the name alone.
355
+ *
356
+ * `git subtree push --prefix=x origin main` is the case that stops this being
357
+ * a pure narrowing: it publishes, and its verb is in the second slot. Both
358
+ * spellings therefore resolve to a verb, and the caller distinguishes them by
359
+ * `namespace`.
360
+ */
361
+ export function gitOperation(tokens) {
362
+ const first = nextWord(tokens, 1);
363
+ if (first === null) return null;
364
+ if (!GIT_NAMESPACE_SUBCOMMANDS.includes(first.name)) {
365
+ return { name: first.name, namespace: null, index: first.index };
366
+ }
367
+ const second = nextWord(tokens, first.index + 1);
368
+ if (second === null) return { name: first.name, namespace: first.name, index: first.index };
369
+ // `git subtree push` publishes; `git stash push`, `git worktree add` and
370
+ // `git remote add` do not do the thing their verb names elsewhere. Only
371
+ // `subtree` forwards its verb.
372
+ if (first.name === 'subtree') return { name: second.name, namespace: 'subtree', index: second.index };
373
+ return { name: `${first.name} ${second.name}`, namespace: first.name, index: second.index };
374
+ }
375
+
307
376
  // ----------------------------------------------------------- the classifier
308
377
 
309
378
  export const DENIAL_CODES = Object.freeze({
@@ -482,9 +551,34 @@ export function planCommand(command, startDir) {
482
551
  }
483
552
  }
484
553
 
485
- const gitCommit = hasGit && words.has('commit');
486
- const gitPush = hasGit && words.has('push');
487
- const gitAdd = hasGit && words.has('add');
554
+ // Asked of the SUBCOMMAND SLOT, never of the token bag.
555
+ //
556
+ // These three were `words.has('push')` and friends — true when the word
557
+ // appeared ANYWHERE in the segment. Measured in the field on `tyran@0.1.2`:
558
+ // `git stash push --staged -m "conductor: ..."`, a purely local operation,
559
+ // was classified as a publish, and the remote was then read as the token
560
+ // after the word — `conductor` from the message, or `2` from a `2>&1`. The
561
+ // refusal told the operator to run `git remote set-head conductor -a`, a
562
+ // command that cannot succeed, about a repository whose default branch was
563
+ // recorded all along.
564
+ //
565
+ // The cost was not one bad refusal. `skills/run/SKILL.md` rule 7 REQUIRES
566
+ // addressed stashes to protect other windows' work, so the gate refused the
567
+ // safe half of a workflow the plugin mandates, and pushed agents toward the
568
+ // deprecated positional form that has no `--staged` and no pathspec.
569
+ //
570
+ // `git remote add` and `git worktree add` had the same shape against
571
+ // `gitAdd` — and `worktree add` is the command rule 7 tells every parallel
572
+ // agent to run.
573
+ const op = hasGit ? gitOperation(tokens) : null;
574
+ const gitCommit = op !== null && op.name === 'commit';
575
+ // NOT narrower than the token bag where it counts: `git subtree push`
576
+ // publishes for real and its verb is the second word, so the resolver
577
+ // returns that word rather than stopping at `subtree`. Dropping it would
578
+ // have traded one false positive for a false NEGATIVE on a real push,
579
+ // which is the wrong direction for this gate.
580
+ const gitPush = op !== null && op.name === 'push';
581
+ const gitAdd = op !== null && op.name === 'add';
488
582
  const hasGh = raw.some(isGhProgram);
489
583
  const ghPublishes =
490
584
  hasGh &&
@@ -492,7 +586,7 @@ export function planCommand(command, startDir) {
492
586
  (words.has('pr') || words.has('repo') || words.has('release') || words.has('gist'));
493
587
 
494
588
  if (gitAdd) {
495
- const after = tokens.slice(tokens.indexOf('add') + 1);
589
+ const after = tokens.slice(op.index + 1);
496
590
  const all = after.some((t) => t === '-A' || t === '--all' || t === '.' || t === '-u');
497
591
  const named = [];
498
592
  let widen = false;
@@ -537,7 +631,7 @@ export function planCommand(command, startDir) {
537
631
  // without ever being scanned. Review raised it as a hypothesis; it
538
632
  // reproduced on the first attempt.
539
633
  const after = tokens
540
- .slice(tokens.indexOf('push') + 1)
634
+ .slice(op.index + 1)
541
635
  .filter((t) => !t.startsWith('-'))
542
636
  .map((t) => (t.startsWith('+') ? t.slice(1) : t));
543
637
  const remote = after[0] ?? null;
@@ -563,7 +657,7 @@ export function planCommand(command, startDir) {
563
657
  // would have been the third spelling of one rule in this repository
564
658
  // (ADR-21), and the one that decides whether a push reaches production is
565
659
  // not the place to start diverging.
566
- const pushArgv = tokens.slice(tokens.indexOf('push') + 1);
660
+ const pushArgv = tokens.slice(op.index + 1);
567
661
  note(dir, { scanPush: true, pushRemote: remote, pushRefs: refs, pushArgv, pushReadable: readable });
568
662
  triggers.push('a git push (every commit not already on the target remote is scanned)');
569
663
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -49,6 +49,7 @@ import {
49
49
  STATE_FILE,
50
50
  } from './project.mjs';
51
51
  import { classifyPath, normalizePath, validateFile, MANDATORY_KERNEL_PATHS } from './schema.mjs';
52
+ import { gitRunner } from './scan-repo.mjs';
52
53
 
53
54
  /** Severity order is also the report order. `info` never fails the check. */
54
55
  export const SEVERITIES = Object.freeze(['error', 'warning', 'info']);
@@ -175,7 +176,11 @@ export const SEVERITY_BY_CODE = Object.freeze(
175
176
  'knowledge-invalid': 'error',
176
177
  'knowledge-unreadable': 'error',
177
178
  'knowledge-not-a-directory': 'warning',
178
- 'policy-missing': 'info',
179
+ // Not `info`, which is what it was: with `.tyran/` on disk and no policy
180
+ // under it the gate refuses every write in the repository. A severity that
181
+ // does not fail the check reports a locked-out repo as a note.
182
+ 'tyran-dir-untracked': 'warning',
183
+ 'policy-missing': 'error',
179
184
  'policy-invalid': 'error',
180
185
  'policy-unreadable': 'error',
181
186
  'policies-unreadable': 'error',
@@ -980,7 +985,31 @@ function policyFindings(path, repoRoot) {
980
985
  * Run every state check. Pure with respect to time: `now` is either given
981
986
  * or taken from each journal's last event, never from the clock.
982
987
  */
983
- export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAULT_STALE_HOURS } = {}) {
988
+ /**
989
+ * Is `.tyran/` committed? The one Tyran failure that is completely silent.
990
+ *
991
+ * `git worktree add` carries TRACKED files only, and the policy gate is
992
+ * deliberately silent in a repository with no `.tyran/` directory. Put those
993
+ * two together and an uncommitted `.tyran/` means every worktree the conductor
994
+ * creates runs with no autonomy class and no path classes — nothing fails,
995
+ * nothing is refused, the boundary is simply absent in the one place the most
996
+ * agents run. Measured on a real install: four worktrees, four ungated
997
+ * implementers, and the operator had no way to see it.
998
+ *
999
+ * Returns null when git cannot answer. The distinction matters exactly as it
1000
+ * does in `detectPackageManager`: "this is not a git repository" is not
1001
+ * evidence that a file is untracked, and reporting it as such would fire on
1002
+ * every temp directory and every fresh `git init`.
1003
+ */
1004
+ export function untrackedTyranDir(repoRoot, run) {
1005
+ if (run(['rev-parse', '--is-inside-work-tree']).trim() !== 'true') return null;
1006
+ // `ls-files` over the directory: any tracked file under it means the tree
1007
+ // travels with a worktree, which is the property being checked. Asking about
1008
+ // config.yaml alone would pass a repo that committed only the policy.
1009
+ return run(['ls-files', '--', '.tyran']).trim() === '';
1010
+ }
1011
+
1012
+ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAULT_STALE_HOURS, run = null } = {}) {
984
1013
  const root = resolve(dir);
985
1014
  if (!existsSync(root)) {
986
1015
  return summarize(dir, [finding('no-state-dir', show(dir), 'no Tyran state directory here — nothing to check')], [
@@ -1009,6 +1038,21 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1009
1038
  checked.push('config.yaml: absent');
1010
1039
  }
1011
1040
 
1041
+ const untracked = untrackedTyranDir(repoRoot, run ?? gitRunner(repoRoot));
1042
+ if (untracked === true) {
1043
+ findings.push(
1044
+ finding(
1045
+ 'tyran-dir-untracked',
1046
+ show(dir),
1047
+ 'nothing under .tyran/ is tracked by git — `git worktree add` carries tracked files only, and ' +
1048
+ 'the policy gate is silent in a repo with no .tyran/, so every worktree runs with no autonomy ' +
1049
+ 'class and no path classes. Nothing fails; the boundary is absent where the most agents run',
1050
+ `git add ${sq(dir)} && git commit -m 'chore: adopt Tyran'`,
1051
+ ),
1052
+ );
1053
+ }
1054
+ checked.push(`.tyran/ tracked by git: ${untracked === null ? 'unknown (not a git work tree)' : !untracked}`);
1055
+
1012
1056
  const knowledge = yamlFilesIn(join(dir, 'knowledge'), 'knowledge');
1013
1057
  findings.push(...knowledge.findings);
1014
1058
  for (const file of knowledge.files) findings.push(...checkSchemaFile('knowledge', file).findings);
@@ -1022,8 +1066,11 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1022
1066
  finding(
1023
1067
  'policy-missing',
1024
1068
  show(join(dir, 'policies')),
1025
- 'no autonomy policy — the self-improvement boundary (AUTO / GATED / KERNEL) is undefined for this repo',
1026
- `mkdir -p ${sq(join(dir, 'policies'))} && cp templates/policies/autonomy.yaml ${sq(join(dir, 'policies', 'autonomy.yaml'))}`,
1069
+ 'no autonomy policy, in a repo that HAS a .tyran/ directory — the policy gate fails closed on ' +
1070
+ 'exactly this state, so every write in every session is refused until the file exists. It is not ' +
1071
+ 'a missing nicety; the repository is unusable',
1072
+ `node scripts/scan-repo.mjs --dir ${sq(repoRoot)} --ensure-policy # installs the shipped template; ` +
1073
+ 'never overwrites a policy you wrote',
1027
1074
  ),
1028
1075
  );
1029
1076
  }
@@ -1218,8 +1265,13 @@ function main() {
1218
1265
  if (err instanceof UsageError) {
1219
1266
  console.error(
1220
1267
  'usage: doctor.mjs --state [--dir <.tyran>] [--json] [--now <iso>] [--stale-hours <n>]\n' +
1221
- ' --state is the only mode today; it is required so that adding --env/--config later\n' +
1222
- ' cannot change what a bare invocation means.',
1268
+ ' doctor.mjs --hooks [--plugin-root <dir>] [--json]\n' +
1269
+ '\n' +
1270
+ ' A mode is REQUIRED: `--state` asks whether the record of the work is\n' +
1271
+ ' consistent, `--hooks` whether the gates can fire at all. They answer\n' +
1272
+ ' different questions, and a bare invocation would have to pick one\n' +
1273
+ ' silently. This text said `--state is the only mode today` long after\n' +
1274
+ ' `--hooks` shipped, which sent readers looking for a flag they had.',
1223
1275
  );
1224
1276
  process.exit(2);
1225
1277
  }
@@ -53,8 +53,15 @@ export const EVENT_TYPES = Object.freeze([
53
53
  'error',
54
54
  ]);
55
55
 
56
+ /**
57
+ * Event types whose `data.id` the CLI issues when the caller omits it, and the
58
+ * prefix to issue it under. `ticket.created` is deliberately absent: a ticket
59
+ * id comes from the plan, which numbers its own stories.
60
+ */
61
+ export const ID_ISSUED_FOR = Object.freeze(Object.assign(Object.create(null), { decision: 'D' }));
62
+
56
63
  /** Per-type required keys inside `data` (data may always carry extra keys). */
57
- const DATA_REQUIRED = Object.freeze({
64
+ export const DATA_REQUIRED = Object.freeze({
58
65
  'ticket.created': ['id'],
59
66
  spawn: ['agent', 'role'],
60
67
  report: ['agent', 'verdict'],
@@ -95,7 +102,10 @@ export function validateEvent(event) {
95
102
  errors.push('ts must be an ISO-8601 timestamp string');
96
103
  }
97
104
  if (!EVENT_TYPES.includes(event.ev)) {
98
- errors.push(`ev "${q(event.ev)}" is not in the closed event set`);
105
+ // The set is CLOSED and was not printed, so the only way to recover was to
106
+ // grep the plugin's own source — which is what a field run actually did.
107
+ // A closed set that will not name its members is a riddle, not a contract.
108
+ errors.push(`ev "${q(event.ev)}" is not in the closed event set — valid: ${EVENT_TYPES.join(', ')}`);
99
109
  }
100
110
  if (typeof event.init !== 'string' || event.init.length === 0) {
101
111
  errors.push('init (initiative slug) must be a non-empty string');
@@ -107,8 +117,16 @@ export function validateEvent(event) {
107
117
  errors.push('data must be a JSON object (may be empty)');
108
118
  } else if (DATA_REQUIRED[event.ev]) {
109
119
  for (const key of DATA_REQUIRED[event.ev]) {
110
- if (!(key in event.data)) errors.push(`data.${q(key)} is required for ev "${q(event.ev)}"`);
111
- else if (key === 'id' && typeof event.data.id !== 'string') {
120
+ // Name the WHOLE contract, not just the key that happened to be checked
121
+ // first. Discovering it by rejection cost a field run four round-trips,
122
+ // one failed invocation each, because the agent recovering from the error
123
+ // has no other source of truth — the table is not printed anywhere else.
124
+ if (!(key in event.data)) {
125
+ errors.push(
126
+ `data.${q(key)} is required for ev "${q(event.ev)}" ` +
127
+ `(this event requires: ${DATA_REQUIRED[event.ev].join(', ')})`,
128
+ );
129
+ } else if (key === 'id' && typeof event.data.id !== 'string') {
112
130
  errors.push(`data.id must be a string for ev "${q(event.ev)}" (got ${typeof event.data.id})`);
113
131
  }
114
132
  }
@@ -635,6 +653,20 @@ function main() {
635
653
  const [file, ev, init] = rest;
636
654
  if (!file || !ev || !init) throw new UsageError();
637
655
  const data = flags.data ? JSON.parse(flags.data) : {};
656
+ // An id the caller omitted is ISSUED, not demanded.
657
+ //
658
+ // `skills/run/SKILL.md` is emphatic that IDs never come from memory,
659
+ // because after a compaction memory hands out the same number twice —
660
+ // and then `append` REJECTED a missing `data.id` and left the conductor
661
+ // to remember a separate `next-id` call. Measured in the field: 12
662
+ // decision IDs hand-assigned from memory in one initiative, which is
663
+ // the exact failure the rule names, with nothing objecting.
664
+ //
665
+ // A rule in prose loses to a mechanism that makes the mistake
666
+ // impossible. This is that mechanism, and an explicit id still wins.
667
+ if (ID_ISSUED_FOR[ev] !== undefined && data.id === undefined) {
668
+ data.id = nextId(file, ID_ISSUED_FOR[ev]);
669
+ }
638
670
  const written = append(file, { ev, init, actor: flags.actor ?? 'conductor', data });
639
671
  console.log(emit(written));
640
672
  return;
@@ -695,7 +727,17 @@ function main() {
695
727
  ' journal.mjs query <file> [--ev E] [--init I] [--ticket T] [--limit N]\n' +
696
728
  ' journal.mjs validate <file> · next-id <file> <prefix> · tail <file>\n' +
697
729
  ' journal.mjs open-spawns <file>\n' +
698
- ' journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V] [--actor A]',
730
+ ' journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V] [--actor A]\n' +
731
+ '\n' +
732
+ // The `--data` contract varies per event and lived only in a table no
733
+ // command printed. A field run discovered it by rejection, one failed
734
+ // invocation at a time.
735
+ 'events, and the `--data` keys each one requires:\n' +
736
+ EVENT_TYPES.map((ev) => {
737
+ const required = DATA_REQUIRED[ev];
738
+ const issued = ID_ISSUED_FOR[ev] !== undefined ? ' (id is issued if omitted)' : '';
739
+ return ` ${ev.padEnd(16)}${required === undefined ? '—' : required.join(', ')}${issued}`;
740
+ }).join('\n'),
699
741
  );
700
742
  process.exit(2);
701
743
  }