@jjanczur/tyran 0.1.0 → 0.1.4

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,9 +63,10 @@
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
- import { basename, dirname, join, resolve as resolvePath } from 'node:path';
68
+ import { homedir, tmpdir } from 'node:os';
69
+ import { basename, dirname, join, resolve as resolvePath, sep } from 'node:path';
69
70
  import { fileURLToPath } from 'node:url';
70
71
 
71
72
  import { PASS, field, main, runGate } from './hook-io.mjs';
@@ -314,6 +315,83 @@ export class PolicyFailure extends Error {
314
315
  }
315
316
  }
316
317
 
318
+ // ------------------------------------------------------------- git worktrees
319
+
320
+ /**
321
+ * A linked worktree's main checkout, or null when this IS the main checkout.
322
+ *
323
+ * Two field reports on 0.1.2 described opposite failures with one cause: this
324
+ * gate treated "the repository" as "this directory tree", and a git worktree is
325
+ * neither inside it nor a different repository.
326
+ *
327
+ * - a session running IN a worktree found no `.tyran/` there — the directory
328
+ * is committed data, but `git worktree add` gives you a fresh checkout and
329
+ * the tree only travels if it was committed — so `loadPolicy` returned null
330
+ * and the gate went SILENT. Measured: four worktrees, four implementers with
331
+ * no autonomy class and no path classes, and `git push origin main` passing;
332
+ * - a session running in the main checkout and writing into a sibling worktree
333
+ * got `normalizePath` -> null -> unconditional KERNEL, so every `Edit` was
334
+ * refused as "outside this repository". Five agents hit it in one initiative
335
+ * and all converged on `python3` heredocs through `Bash`, which this gate
336
+ * does not class at all. A refusal that reroutes work into a less visible
337
+ * channel is worse than no refusal.
338
+ *
339
+ * Both are fixed by asking the same question — *which repository is this path
340
+ * in* — instead of *is this path under my root*.
341
+ *
342
+ * Detection is pure filesystem, deliberately. `.git` is a DIRECTORY in a main
343
+ * checkout and a FILE in a linked worktree, holding `gitdir: <path>`. Reading
344
+ * it costs a stat and a small read; asking git would cost a subprocess on the
345
+ * write path, which today does none at all and is measured at ~50 ms.
346
+ */
347
+ export function mainWorktreeOf(root) {
348
+ const dotGit = join(root, '.git');
349
+ let text;
350
+ try {
351
+ if (statSync(dotGit).isDirectory()) return null;
352
+ text = readFileSync(dotGit, 'utf8');
353
+ } catch {
354
+ return null;
355
+ }
356
+ if (text.length > MAX_GITFILE_BYTES) return null;
357
+ const match = /^gitdir:\s*(.+)$/m.exec(text);
358
+ if (match === null) return null;
359
+ // `<main>/.git/worktrees/<name>` — the main checkout is what precedes it.
360
+ const gitdir = resolvePath(root, match[1].trim()).replace(/\\/g, '/');
361
+ const marker = '/.git/worktrees/';
362
+ const at = gitdir.indexOf(marker);
363
+ return at === -1 ? null : gitdir.slice(0, at);
364
+ }
365
+
366
+ /** A `.git` file is one short line. Anything larger is not one (ADR-22 c1 D). */
367
+ export const MAX_GITFILE_BYTES = 4096;
368
+
369
+ /** How far up from a path to look for the checkout containing it. */
370
+ const MAX_WORKTREE_WALK = 64;
371
+
372
+ /**
373
+ * The checkout root containing `path`, and the repository it belongs to.
374
+ *
375
+ * Returns `{ checkout, repository }` where `repository` is the main worktree —
376
+ * the identity two sibling worktrees share — or null when no checkout is found.
377
+ */
378
+ export function checkoutOf(path) {
379
+ let cursor = resolvePath(path);
380
+ for (let i = 0; i < MAX_WORKTREE_WALK; i++) {
381
+ let exists = false;
382
+ try {
383
+ exists = statSync(join(cursor, '.git')) !== null;
384
+ } catch {
385
+ exists = false;
386
+ }
387
+ if (exists) return { checkout: cursor, repository: mainWorktreeOf(cursor) ?? cursor };
388
+ const parent = dirname(cursor);
389
+ if (parent === cursor) return null;
390
+ cursor = parent;
391
+ }
392
+ return null;
393
+ }
394
+
317
395
  /** The repository this call is about. Explicit, never defaulted per call site. */
318
396
  export function repoRootOf(input, env = process.env) {
319
397
  const fromEnv = env.CLAUDE_PROJECT_DIR;
@@ -364,13 +442,32 @@ async function readBounded(path, what) {
364
442
  * that lets writes through is the defect this whole epic is about.
365
443
  */
366
444
  export async function loadPolicy(root) {
367
- const text = await readBounded(join(root, POLICY_PATH), 'the autonomy policy');
445
+ // A linked worktree inherits its repository's policy. Without this a
446
+ // worktree with no `.tyran/` of its own reads as "this repo never adopted
447
+ // Tyran" and the gate goes silent — measured in the field as four worktrees
448
+ // running four implementers with no autonomy class at all. Tried in order,
449
+ // so a `.tyran/` that DID travel with the worktree still wins.
450
+ const roots = [root, mainWorktreeOf(root)].filter((r) => r !== null);
451
+ let text = null;
452
+ let from = root;
453
+ for (const candidate of roots) {
454
+ text = await readBounded(join(candidate, POLICY_PATH), 'the autonomy policy');
455
+ if (text !== null) {
456
+ from = candidate;
457
+ break;
458
+ }
459
+ }
368
460
  if (text === null) {
369
461
  let adopted = false;
370
- try {
371
- adopted = (await stat(join(root, TYRAN_DIR))).isDirectory();
372
- } catch {
373
- adopted = false;
462
+ for (const candidate of roots) {
463
+ try {
464
+ if ((await stat(join(candidate, TYRAN_DIR))).isDirectory()) {
465
+ adopted = true;
466
+ break;
467
+ }
468
+ } catch {
469
+ /* keep looking */
470
+ }
374
471
  }
375
472
  if (!adopted) return null;
376
473
  throw new PolicyFailure(
@@ -403,7 +500,14 @@ export async function loadPolicy(root) {
403
500
 
404
501
  /** Load the deployment class from config.yaml, or refuse. `null` = no config. */
405
502
  export async function loadDeployClass(root) {
406
- const text = await readBounded(join(root, CONFIG_PATH), 'the Tyran config');
503
+ // Same inheritance as the policy, and for the sharper reason: without it a
504
+ // `git push origin main` from inside a worktree found no config, concluded
505
+ // the repo had not adopted Tyran, and PASSED at every deployment class.
506
+ let text = null;
507
+ for (const candidate of [root, mainWorktreeOf(root)].filter((r) => r !== null)) {
508
+ text = await readBounded(join(candidate, CONFIG_PATH), 'the Tyran config');
509
+ if (text !== null) break;
510
+ }
407
511
  if (text === null) return null;
408
512
  let doc;
409
513
  try {
@@ -577,6 +681,80 @@ function canonicalDeepest(raw) {
577
681
  return resolvePath(raw);
578
682
  }
579
683
 
684
+ /**
685
+ * The path segments below `base`, canonicalized on BOTH sides, or null when
686
+ * `target` is not under `base`. `canonicalDeepest` on the base too, so `/tmp`
687
+ * and `/private/tmp` — one directory in two spellings on macOS — do not read as
688
+ * two, the same symlink hazard `repoRelative` documents.
689
+ */
690
+ function segmentsUnder(canonTarget, base) {
691
+ let root;
692
+ try {
693
+ root = canonicalDeepest(base);
694
+ } catch {
695
+ return null;
696
+ }
697
+ if (canonTarget === root) return [];
698
+ const prefix = root.endsWith(sep) ? root : root + sep;
699
+ if (!canonTarget.startsWith(prefix)) return null;
700
+ return canonTarget.slice(prefix.length).split(sep).filter(Boolean);
701
+ }
702
+
703
+ /**
704
+ * Claude Code's own two working directories, which belong to no repository:
705
+ * the persistent memory store under the config dir, and the per-session
706
+ * scratchpad under the system temp dir. `repoRelative` returns null for both —
707
+ * they are genuinely outside every repo — so the write matrix answered them
708
+ * with KERNEL, and adopting Tyran in a repo then refused the harness's OWN
709
+ * memory writes: `Write` to `~/.claude/projects/<slug>/memory/*.md` failed with
710
+ * "outside this repository", so the assistant could no longer persist what it
711
+ * learned while working in a Tyran repo. A boundary that blocks the tool's own
712
+ * bookkeeping is one its user turns off.
713
+ *
714
+ * The exemption is narrow on two axes, and both carry weight:
715
+ * - PATH — only the memory store <config>/projects/<slug>/memory and the
716
+ * scratchpad <tmp>/claude-<id>. The rest of the config dir is untouched,
717
+ * so `.claude/settings.json`, which registers these very hooks, stays
718
+ * KERNEL and out of reach. An allowlist of two shapes, never "anything
719
+ * under home".
720
+ * - ACTOR — `main` only, enforced at the call site. A subagent has no
721
+ * business writing outside its worktree; `actorOf` returns `subagent` for
722
+ * it and it still falls through to KERNEL. So the blast radius is an
723
+ * interactive thread writing advisory notes and temp files, not a
724
+ * fanned-out loop reaching across the filesystem.
725
+ *
726
+ * Bash never needed this: an out-of-repo token yields no finding in
727
+ * `shellPathFindings`, so `echo > scratch` was already allowed. The refusal
728
+ * lived only on the file-writing tools, which is the asymmetry a user meets.
729
+ */
730
+ export function harnessWritable(rawPath, env = process.env) {
731
+ let canon;
732
+ try {
733
+ canon = canonicalDeepest(rawPath);
734
+ } catch {
735
+ return false;
736
+ }
737
+ const configDir =
738
+ typeof env.CLAUDE_CONFIG_DIR === 'string' && env.CLAUDE_CONFIG_DIR.trim() !== ''
739
+ ? env.CLAUDE_CONFIG_DIR
740
+ : join(homedir(), '.claude');
741
+ const underConfig = segmentsUnder(canon, configDir);
742
+ // The memory store's exact shape: <config>/projects/<slug>/memory/**.
743
+ if (underConfig !== null && underConfig[0] === 'projects' && underConfig[2] === 'memory') {
744
+ return true;
745
+ }
746
+ // The scratchpad: <tmp>/claude-*/**, under whichever temp root the platform
747
+ // used. `/tmp` is included explicitly because `os.tmpdir()` is `/var/...` on
748
+ // macOS while the scratchpad lives under `/private/tmp`.
749
+ for (const tempRoot of new Set([tmpdir(), '/tmp'])) {
750
+ const underTemp = segmentsUnder(canon, tempRoot);
751
+ if (underTemp !== null && underTemp.length >= 1 && /^claude-/.test(underTemp[0])) {
752
+ return true;
753
+ }
754
+ }
755
+ return false;
756
+ }
757
+
580
758
  /**
581
759
  * The repo-relative path, resolved through symlinks on BOTH sides.
582
760
  *
@@ -595,7 +773,25 @@ function canonicalDeepest(raw) {
595
773
  * outside. Two spellings of one location must not resolve to two classes.
596
774
  */
597
775
  export function repoRelative(raw, root) {
598
- return normalizePath(canonicalDeepest(raw), canonicalDeepest(root));
776
+ const direct = normalizePath(canonicalDeepest(raw), canonicalDeepest(root));
777
+ if (direct !== null) return direct;
778
+ // Not under this root — but a git worktree of the SAME repository is not
779
+ // "outside the repository", and calling it that refused every Edit an
780
+ // implementer made in the worktree rule 7 tells the conductor to give it.
781
+ // Five agents hit this in one initiative and all rerouted their writes
782
+ // through `Bash` heredocs, which this gate does not class at all.
783
+ //
784
+ // The test is repository IDENTITY, never proximity: both sides resolve to a
785
+ // main checkout and those must be the same path. A path in a DIFFERENT
786
+ // repository still normalizes to null and is still KERNEL, which is the
787
+ // property that keeps this from being a hole.
788
+ const target = checkoutOf(canonicalDeepest(raw));
789
+ if (target === null) return null;
790
+ const session = checkoutOf(canonicalDeepest(root));
791
+ if (session === null || target.repository !== session.repository) return null;
792
+ // Classified against the worktree it lives in, so `.tyran/knowledge/x.yaml`
793
+ // in a worktree is the same class as in the main checkout.
794
+ return normalizePath(canonicalDeepest(raw), target.checkout);
599
795
  }
600
796
 
601
797
  /** Every path this tool call names. Prototype-safe, deduplicated, order-stable. */
@@ -875,6 +1071,13 @@ export async function decide({ input, runner = runChild, startedAt = Date.now(),
875
1071
  // and the two would agree in every test that happened to run in the repo
876
1072
  // root. Normalization is idempotent, so the resolver's own call is a no-op.
877
1073
  const normalized = repoRelative(target, root);
1074
+ // Claude Code's own memory store and per-session scratchpad are outside
1075
+ // every repository, so `normalized` is null and the matrix below answers
1076
+ // KERNEL — which made adopting Tyran refuse the harness's own memory
1077
+ // writes. `harnessWritable` exempts exactly those two locations, and only
1078
+ // for the main thread; a subagent still falls through to KERNEL. See its
1079
+ // definition for the full argument.
1080
+ if (normalized === null && actor === 'main' && harnessWritable(target, env)) continue;
878
1081
  // The one branch this cannot delegate: a path outside the repository makes
879
1082
  // `normalizePath` return null, which `classifyPath` answers with KERNEL.
880
1083
  // Restated in one line rather than reached by passing a null through, and
@@ -1205,10 +1408,17 @@ async function decideBash({ input, toolInput, root, runner, budget }) {
1205
1408
  // config in an ADOPTED repo refuses, exactly as a missing policy does.
1206
1409
  // Only a repo with no `.tyran/` at all is silent.
1207
1410
  let adopted = false;
1208
- try {
1209
- adopted = (await stat(join(root, TYRAN_DIR))).isDirectory();
1210
- } catch {
1211
- adopted = false;
1411
+ // The worktree's repository, not just the worktree: a push from a linked
1412
+ // checkout must not read as "Tyran does not run here" (see loadPolicy).
1413
+ for (const candidate of [root, mainWorktreeOf(root)].filter((r) => r !== null)) {
1414
+ try {
1415
+ if ((await stat(join(candidate, TYRAN_DIR))).isDirectory()) {
1416
+ adopted = true;
1417
+ break;
1418
+ }
1419
+ } catch {
1420
+ /* keep looking */
1421
+ }
1212
1422
  }
1213
1423
  if (!adopted) return PASS;
1214
1424
  throw new PolicyFailure(
@@ -1342,8 +1552,11 @@ const DEPLOY_REMEDY = Object.freeze(Object.assign(Object.create(null), {
1342
1552
  'recoverable from this session, which is the whole reason they are outside every autonomy class.',
1343
1553
  production:
1344
1554
  '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 ' +
1555
+ `\`${CONFIG_PATH}\`, and it is your own policy that decides whether an agent may edit that ` +
1556
+ 'file — the shipped template classifies it AUTO — so keeping the class where the operator put ' +
1557
+ 'it is by CONVENTION, not by mechanism. No class is named here on purpose: this text would ' +
1558
+ 'otherwise go stale the moment a repo reclassified the file, and a refusal that states the ' +
1559
+ 'wrong reason is worse than one that states none. Measured in review, an agent in an ' +
1347
1560
  'unattended main loop edited P1 to P3 with no refusal. Treat raising it yourself as the thing ' +
1348
1561
  'you were asked not to do, and say in your report that you wanted to.',
1349
1562
  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.4",
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
  }