@jjanczur/tyran 0.1.13 → 0.1.17

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.
@@ -1025,8 +1025,11 @@ const READ_REMEDY =
1025
1025
  // calls: `cat >> .tyran/policies/autonomy.yaml`, then the same read, allowed.
1026
1026
  // The shell route is closed now, so the claim is nearly true — and "nearly"
1027
1027
  // is exactly the word a guarantee may not leave out.
1028
- 'That file is class KERNEL, and a shell command that NAMES it is refused too, so the exemption ' +
1029
- 'is not one an agent can write for itself in the ordinary way. It is not a proof: a path this ' +
1028
+ // Narrowed in 0.1.16 from "a shell command that NAMES it": a read-only shell
1029
+ // command on that path passes now, exactly as `Read` always did. What closes
1030
+ // the route is the WRITE half, which is the half `cat >>` used.
1031
+ 'That file is class KERNEL, and a shell command that WRITES to it is refused too, so the ' +
1032
+ 'exemption is not one an agent can write for itself in the ordinary way. It is not a proof: a path this ' +
1030
1033
  'gate never sees as a word — assembled from a variable, or from a program it launches — is in ' +
1031
1034
  'the declared floor in docs/policy-gate.md. Writing that exemption yourself is working around ' +
1032
1035
  'the gate, which is the one move that makes a boundary worse than no boundary.';
@@ -1225,8 +1228,8 @@ function escapeRoute(cls, unsupervised) {
1225
1228
  'edit in the main session, where the permission prompt is the approval. Do not look for a ' +
1226
1229
  'path around this gate: writing the same bytes through `Bash` is outside what this gate ' +
1227
1230
  'checks for CLASSES — though it does refuse a shell command that names a credential file or ' +
1228
- 'a built-in protected path — and doing it deliberately is the one thing that turns a ' +
1229
- 'boundary into a decoration.'
1231
+ 'writes to a built-in protected path — and doing it deliberately is the one thing that ' +
1232
+ 'turns a boundary into a decoration.'
1230
1233
  );
1231
1234
  }
1232
1235
  return (
@@ -1318,6 +1321,13 @@ export function stripMessageArguments(command) {
1318
1321
  * the thing that stops an operator running the validator. The two built-in
1319
1322
  * globs need no configuration and cannot be edited away.
1320
1323
  *
1324
+ * The second family is a WRITE rule, and since 0.1.16 it says so: a command
1325
+ * that can only read passes on `SHELL_READABLE_GLOBS`, because the `Read` tool
1326
+ * passes on those paths and a shell refusal on top of an allowed `Read`
1327
+ * protects nothing. See `SHELL_READABLE_GLOBS` for the measurement. The first
1328
+ * family is untouched — for a credential the `Read` tool refuses too, and that
1329
+ * symmetry is the entire rule.
1330
+ *
1321
1331
  * ## The declared floor
1322
1332
  *
1323
1333
  * `SHELL_DECLARED_MISSES` names what still gets through. A path assembled at
@@ -1362,6 +1372,313 @@ export function shellProtectedGlobFor(normalized) {
1362
1372
  return null;
1363
1373
  }
1364
1374
 
1375
+ // ------------------------------------------- the read-only shell exemption
1376
+
1377
+ /**
1378
+ * The protected globs on which a READ-ONLY shell command is allowed.
1379
+ *
1380
+ * ## The measurement
1381
+ *
1382
+ * On 0.1.15, for any path under `hooks/**` or `.tyran/policies/**`: the `Read`
1383
+ * tool PASSES, and every read-shaped shell command on the SAME file is
1384
+ * refused — `cat FILE`, `grep -n X FILE`, `wc -l FILE`, `node --check FILE`,
1385
+ * all deny. The bytes are one `Read` call away, so the refusal protected
1386
+ * nothing and cost a tool call every time somebody inspected the gate they
1387
+ * were working on. The rule was not even consistent with itself:
1388
+ * `git log --oneline -- hooks/` passes, because a bare directory token names
1389
+ * no file to classify, while `wc -l` on a file inside it does not.
1390
+ *
1391
+ * ## The distinction this encodes
1392
+ *
1393
+ * **The shell must not become a second route to something the `Read` tool
1394
+ * already refuses.** For a secret that symmetry is load-bearing and stays
1395
+ * exactly as it was: `Read .env` denies AND `grep .env` denies, because the
1396
+ * measured incident is a refused `Read` followed by `Bash: grep` in the very
1397
+ * next tool call. Where `Read` is allowed, refusing the shell buys nothing —
1398
+ * it only teaches the reader that the gate is an obstacle rather than a
1399
+ * boundary, which is the failure mode ADR-19 is about.
1400
+ *
1401
+ * ## Why this list is not `SHELL_PROTECTED_GLOBS`
1402
+ *
1403
+ * `.claude/settings.json` and `.claude/settings.local.json` are deliberately
1404
+ * NOT here, and that is a narrowing beyond what the argument above strictly
1405
+ * requires — `Read` passes on them too, so by the principle alone they would
1406
+ * qualify. They are the hook registry, the one place inside a repository from
1407
+ * which every gate is switched off at once, and this change is scoped to the
1408
+ * friction that was actually measured. Direction of error stays REFUSE.
1409
+ */
1410
+ export const SHELL_READABLE_GLOBS = Object.freeze([...MANDATORY_KERNEL_PATHS]);
1411
+
1412
+ /**
1413
+ * Characters that put a WRITE — or a program this gate cannot see — into a
1414
+ * command line. One of them anywhere in the raw text disqualifies the whole
1415
+ * line from the exemption, whatever the programs are.
1416
+ *
1417
+ * `>` and `<` are every redirection spelling at once (`>`, `>>`, `2>`, `&>`,
1418
+ * `<`, `<<`, `<<<`, `<(…)`); `` ` `` and `$` are command substitution and
1419
+ * parameter expansion, whose result this gate never sees; `(`, `)`, `{`, `}`
1420
+ * are subshells and groups; `&` is both background and `&&`, and telling those
1421
+ * apart needs a parser this repository is not getting a second of (ADR-21).
1422
+ *
1423
+ * Tested on the RAW command rather than on the lexer's tokens, and that is
1424
+ * forced rather than chosen: `splitSegments` CONSUMES these as separators
1425
+ * (`SEPARATORS` in secrets-gate.mjs), so by the time a token exists the `>`
1426
+ * that made the line a write is already gone. Quoting is not honoured, so
1427
+ * `grep ">" FILE` is a false refusal — the direction this gate errs in.
1428
+ *
1429
+ * `|`, `;` and newline are absent on purpose: they compose commands without
1430
+ * writing, and every composed segment still has to be an allowed read-only
1431
+ * program, so a pipe into a writer is refused by the program check.
1432
+ */
1433
+ export const SHELL_READ_DISQUALIFIERS = '<>$`(){}&';
1434
+
1435
+ /**
1436
+ * Programs that read, and the flags under which they only read.
1437
+ *
1438
+ * ## Program AND flags, because read-shaped programs have write-shaped modes
1439
+ *
1440
+ * This is the honest risk of the whole exemption, so it is matched rather than
1441
+ * asserted: `sed -n` versus `sed -i`, `node --check FILE` versus
1442
+ * `node FILE`, and `git log` versus `git log --output=FILE` — the last a real
1443
+ * hole found in an earlier review of this gate. Every token beginning with `-`
1444
+ * must appear in the entry for its program; an unrecognised flag REFUSES, so
1445
+ * the enumeration's incompleteness costs a false refusal and never a pass.
1446
+ *
1447
+ * Fields, all optional except `short`/`long`:
1448
+ * - `short` — the single letters a short cluster may contain (`-rn` is `r`
1449
+ * and `n`, checked one letter at a time);
1450
+ * - `long` — the long options, matched on the name before any `=`, so
1451
+ * `--output=/tmp/x` is tested as `--output` and refused;
1452
+ * - `numeric` — the program takes a bare count (`head -20`, `git log -5`)
1453
+ * and an attached one (`head -n20`);
1454
+ * - `subcommands` — the word that MUST follow the program immediately. `git`
1455
+ * is the only entry with one, and requiring it in the very next slot is
1456
+ * what refuses `git -c core.pager=… log`: a global `-c` can name a program
1457
+ * for git to run, and `planCommand`'s alias check only covers `alias.`;
1458
+ * - `require` — at least one of these must be present. `node` alone RUNS a
1459
+ * file, so `--check` is not merely permitted, it is mandatory.
1460
+ *
1461
+ * Null-prototype on purpose: a plain object literal answers `constructor`
1462
+ * with a function, which would make `constructor FILE` an allowed program.
1463
+ */
1464
+ export const READ_ONLY_PROGRAMS = Object.freeze(Object.assign(Object.create(null), {
1465
+ cat: {
1466
+ short: 'AbeEnstTuv',
1467
+ long: ['--show-all', '--number-nonblank', '--show-ends', '--number', '--squeeze-blank',
1468
+ '--show-tabs', '--show-nonprinting'],
1469
+ },
1470
+ head: {
1471
+ short: 'cnqvz',
1472
+ numeric: true,
1473
+ long: ['--bytes', '--lines', '--quiet', '--silent', '--verbose', '--zero-terminated'],
1474
+ },
1475
+ // Identical to `head` minus `-f`/`-F`/`--follow`/`--retry`/`--pid`, which do
1476
+ // not write but never return either: a gate that hands the session a command
1477
+ // it can only recover from by killing the tool call has not helped anyone.
1478
+ tail: {
1479
+ short: 'cnqvz',
1480
+ numeric: true,
1481
+ long: ['--bytes', '--lines', '--quiet', '--silent', '--verbose', '--zero-terminated'],
1482
+ },
1483
+ wc: {
1484
+ short: 'clLmw',
1485
+ long: ['--bytes', '--chars', '--lines', '--max-line-length', '--words'],
1486
+ },
1487
+ grep: {
1488
+ short: 'ABCDEFGHILPRTUVZabcdefhilmnoqrsuvwxyz',
1489
+ long: ['--extended-regexp', '--fixed-strings', '--basic-regexp', '--perl-regexp', '--regexp',
1490
+ '--file', '--ignore-case', '--no-ignore-case', '--invert-match', '--word-regexp',
1491
+ '--line-regexp', '--count', '--files-without-match', '--files-with-matches', '--max-count',
1492
+ '--only-matching', '--quiet', '--silent', '--no-messages', '--byte-offset', '--with-filename',
1493
+ '--no-filename', '--label', '--line-number', '--initial-tab', '--null', '--null-data',
1494
+ '--after-context', '--before-context', '--context', '--group-separator',
1495
+ '--no-group-separator', '--color', '--colour', '--binary-files', '--text', '--directories',
1496
+ '--devices', '--recursive', '--dereference-recursive', '--include', '--exclude',
1497
+ '--exclude-from', '--exclude-dir', '--line-buffered', '--binary', '--version', '--help'],
1498
+ },
1499
+ // ripgrep is the entry that most needs its flags read rather than its name:
1500
+ // `--pre` and `--hostname-bin` name a program for rg to execute per file,
1501
+ // which is arbitrary code from a command line that otherwise looks like a
1502
+ // search. Neither is listed, so both refuse.
1503
+ rg: {
1504
+ short: 'ABCFHILMNPSTUVcefghijlmnopqrstuvwxz0',
1505
+ long: ['--after-context', '--before-context', '--context', '--count', '--count-matches',
1506
+ '--regexp', '--fixed-strings', '--file', '--glob', '--iglob', '--with-filename',
1507
+ '--no-filename', '--ignore-case', '--smart-case', '--case-sensitive', '--follow',
1508
+ '--files-with-matches', '--files-without-match', '--files', '--max-columns', '--max-count',
1509
+ '--max-depth', '--max-filesize', '--no-line-number', '--line-number', '--column',
1510
+ '--only-matching', '--pcre2', '--pretty', '--quiet', '--replace', '--type', '--type-not',
1511
+ '--multiline', '--multiline-dotall', '--unrestricted', '--version', '--invert-match',
1512
+ '--word-regexp', '--line-regexp', '--search-zip', '--threads', '--null', '--heading',
1513
+ '--no-heading', '--hidden', '--no-ignore', '--no-config', '--color', '--colors', '--json',
1514
+ '--vimgrep', '--sort', '--sortr', '--stats', '--trim', '--text', '--binary', '--engine',
1515
+ '--help'],
1516
+ },
1517
+ diff: {
1518
+ short: 'BCEHNSTUWZabcdinpqrstuwxy',
1519
+ long: ['--unified', '--context', '--side-by-side', '--brief', '--report-identical-files',
1520
+ '--recursive', '--new-file', '--ignore-space-change', '--ignore-all-space',
1521
+ '--ignore-blank-lines', '--ignore-case', '--ignore-tab-expansion', '--ignore-trailing-space',
1522
+ '--ignore-matching-lines', '--text', '--expand-tabs', '--initial-tab', '--minimal',
1523
+ '--speed-large-files', '--color', '--width', '--suppress-common-lines',
1524
+ '--strip-trailing-cr', '--show-c-function', '--label', '--exclude', '--exclude-from',
1525
+ '--starting-file', '--no-dereference', '--version', '--help'],
1526
+ },
1527
+ // `node FILE` executes FILE. `--check` only parses it, and is REQUIRED here
1528
+ // rather than merely allowed, which is what separates the two.
1529
+ node: {
1530
+ short: 'c',
1531
+ long: ['--check'],
1532
+ require: { short: 'c', long: ['--check'] },
1533
+ },
1534
+ git: {
1535
+ subcommands: ['log', 'show', 'diff'],
1536
+ short: 'MSUbnpsuw',
1537
+ numeric: true,
1538
+ long: ['--oneline', '--graph', '--decorate', '--no-decorate', '--abbrev-commit',
1539
+ '--no-abbrev-commit', '--pretty', '--format', '--date', '--stat', '--numstat',
1540
+ '--shortstat', '--dirstat', '--name-only', '--name-status', '--raw', '--patch',
1541
+ '--no-patch', '--unified', '--word-diff', '--color', '--no-color', '--reverse', '--all',
1542
+ '--branches', '--tags', '--remotes', '--author', '--committer', '--grep', '--since',
1543
+ '--until', '--before', '--after', '--max-count', '--skip', '--follow', '--first-parent',
1544
+ '--merges', '--no-merges', '--cached', '--staged', '--summary', '--find-renames',
1545
+ '--find-copies', '--full-history', '--topo-order', '--date-order', '--author-date-order',
1546
+ '--relative', '--no-prefix', '--src-prefix', '--dst-prefix', '--diff-filter', '--text',
1547
+ '--binary', '--numbered', '--no-renames'],
1548
+ },
1549
+ }));
1550
+
1551
+ /** True when one `-…` token is a flag its program only reads under. */
1552
+ export function readOnlyFlag(spec, token) {
1553
+ if (token.startsWith('--')) return (spec.long ?? []).includes(token.split('=')[0]);
1554
+ const body = token.slice(1);
1555
+ // `head -20`, `git log -5`: the whole body is the count.
1556
+ if (/^[0-9]+$/.test(body)) return spec.numeric === true;
1557
+ // `head -n20`: an attached count on the last letter of the cluster.
1558
+ const letters = spec.numeric === true ? body.replace(/[0-9]+$/, '') : body;
1559
+ if (letters === '') return false;
1560
+ for (const ch of letters) if (!(spec.short ?? '').includes(ch)) return false;
1561
+ return true;
1562
+ }
1563
+
1564
+ /** True when one segment is a read-only program used in a read-only way. */
1565
+ export function readOnlySegment(tokens) {
1566
+ if (tokens.length === 0) return false;
1567
+ // `basename` for the same reason the lexer uses it: `/usr/bin/cat` and `cat`
1568
+ // are one program. Case-folded because a case-insensitive filesystem will
1569
+ // launch `CAT` from the same inode. What that costs is the last entry of
1570
+ // SHELL_DECLARED_MISSES: a repo-writable `src/cat` is an allowed reader by
1571
+ // name. Stated there rather than narrowed here — see the entry for why a
1572
+ // narrowing would close nothing.
1573
+ const spec = READ_ONLY_PROGRAMS[basename(tokens[0]).toLowerCase()];
1574
+ if (spec === undefined) return false;
1575
+ let rest = tokens.slice(1);
1576
+ if (spec.subcommands !== undefined) {
1577
+ if (rest.length === 0 || !spec.subcommands.includes(rest[0])) return false;
1578
+ rest = rest.slice(1);
1579
+ }
1580
+ // `-` is stdin and `--` ends the options; neither is a flag.
1581
+ const flags = rest.filter((t) => t.startsWith('-') && t !== '-' && t !== '--');
1582
+ for (const flag of flags) if (!readOnlyFlag(spec, flag)) return false;
1583
+ if (spec.require === undefined) return true;
1584
+ return flags.some((t) =>
1585
+ t.startsWith('--')
1586
+ ? spec.require.long.includes(t.split('=')[0])
1587
+ : [...t.slice(1)].some((ch) => spec.require.short.includes(ch)));
1588
+ }
1589
+
1590
+ /**
1591
+ * True when this whole command line can only read.
1592
+ *
1593
+ * Two gates, and both have to hold: no character that can redirect, substitute
1594
+ * or group (checked on the raw text, see `SHELL_READ_DISQUALIFIERS`), and
1595
+ * every segment the shared lexer produces is an allowed program under allowed
1596
+ * flags. Segmentation comes from `splitSegments` — this repository has one
1597
+ * lexer and is not getting a second (ADR-21).
1598
+ */
1599
+ export function isReadOnlyCommand(command) {
1600
+ const text = String(command);
1601
+ for (const ch of SHELL_READ_DISQUALIFIERS) if (text.includes(ch)) return false;
1602
+ const segments = splitSegments(text);
1603
+ if (segments.length === 0) return false;
1604
+ for (const segment of segments) if (!readOnlySegment(tokensOf(segment))) return false;
1605
+ return true;
1606
+ }
1607
+
1608
+ /**
1609
+ * Credential-shaped words of the RAW command text, as `{token, detail}`.
1610
+ *
1611
+ * ## Why the finding list is not enough to decide the exemption
1612
+ *
1613
+ * `shellPathFindings` reads `commandTokens`, and `commandTokens` runs
1614
+ * `stripMessageArguments` FIRST — which removes a message-bearing flag together
1615
+ * with its argument. `-t` is in `MESSAGE_FLAGS` (git's `--template`) and is also
1616
+ * a legal flag of `diff` and `cat`, so `diff -t SECRET READABLE` produced a
1617
+ * finding list naming only the readable path, `isReadOnlyCommand` agreed on the
1618
+ * raw text, and the line was EXEMPTED. Measured deny-on-0.1.15 -> pass, in four
1619
+ * shapes: `diff -t S R`, `grep --file=S R`, `grep -m S R`, and `diff ~/S R` —
1620
+ * the last for a second reason, that `~` makes the token fail `isLiteralPath`
1621
+ * and `commandTokens` drops it entirely.
1622
+ *
1623
+ * That is a broken INVARIANT rather than a new capability: `diff -t S src/app.js`
1624
+ * publishes the same bytes and always did, because it names no protected path
1625
+ * at all. But the exemption's stated claim is that it widens what may be done
1626
+ * to paths `Read` already hands over and NOTHING else, and a line that dumps a
1627
+ * credential is not that.
1628
+ *
1629
+ * ## What this reads
1630
+ *
1631
+ * The raw text, with none of the three filters that lost the word: no message
1632
+ * stripping, no `isLiteralPath`, and the right-hand side of an attached `=`
1633
+ * tested as well as the whole word, so `--file=.env` cannot hide behind its own
1634
+ * flag. The RULES are `secretReadRules` — the same matcher the credential
1635
+ * findings use, asked a second question rather than spelled a second time
1636
+ * (ADR-21).
1637
+ *
1638
+ * One false refusal is declared with it, and it is the direction this gate errs
1639
+ * in: a credential-SHAPED word that is not a path loses the exemption, so
1640
+ * `git log --grep=.env -- hooks/x.mjs` is refused for a word in a search
1641
+ * pattern and costs one `Read` call. A commit message cannot reach here at all
1642
+ * — `git commit -m "fix .env loading"` names no protected path, so there is no
1643
+ * finding to exempt and this function is never called.
1644
+ */
1645
+ export function rawCredentialWords(command) {
1646
+ const out = [];
1647
+ for (const segment of splitSegments(String(command))) {
1648
+ for (const token of tokensOf(segment)) {
1649
+ const at = token.indexOf('=');
1650
+ for (const word of at === -1 ? [token] : [token, token.slice(at + 1)]) {
1651
+ if (word === '') continue;
1652
+ const ids = secretReadRules(word);
1653
+ if (ids.length > 0) {
1654
+ out.push({ token, detail: ids.join(', ') });
1655
+ break;
1656
+ }
1657
+ }
1658
+ }
1659
+ }
1660
+ return out;
1661
+ }
1662
+
1663
+ /**
1664
+ * True when the path refusal may be lifted for this command.
1665
+ *
1666
+ * Every finding must be in the readable class — one credential-shaped path, or
1667
+ * one `.claude/settings.json`, and the whole line is refused however read-only
1668
+ * the rest of it is. That ordering is the point: the exemption widens what may
1669
+ * be done to paths the `Read` tool already hands over, and nothing else.
1670
+ *
1671
+ * The last clause is checked on the RAW text and not only on the findings,
1672
+ * because the findings are computed from a STRIPPED copy of the command and a
1673
+ * credential can be invisible in it. See `rawCredentialWords`.
1674
+ */
1675
+ export function shellReadExempt(findings, command) {
1676
+ if (findings.length === 0) return false;
1677
+ if (!findings.every((f) => f.kind === 'kernel' && SHELL_READABLE_GLOBS.includes(f.detail))) return false;
1678
+ if (rawCredentialWords(command).length > 0) return false;
1679
+ return isReadOnlyCommand(command);
1680
+ }
1681
+
1365
1682
  export const SHELL_DECLARED_MISSES = Object.freeze([
1366
1683
  'a path assembled at runtime — from a variable, a command substitution, a glob, or a file ' +
1367
1684
  'already on disk. The gate never expands anything, so it never sees the result',
@@ -1371,6 +1688,20 @@ export const SHELL_DECLARED_MISSES = Object.freeze([
1371
1688
  'anything a script writes once it is running — this reads the COMMAND, never its effect',
1372
1689
  'a KERNEL path declared by the POLICY rather than built in; only SHELL_PROTECTED_GLOBS is ' +
1373
1690
  'checked here, so that a broken policy cannot stop the operator repairing it',
1691
+ // The floor of the read-only exemption, stated in the same list rather than
1692
+ // in a second one: what an allowed program does is decided partly OUTSIDE
1693
+ // the command text this gate reads, and no flag table can see that half.
1694
+ 'a program an allowed reader is CONFIGURED to launch — a `diff.external` driver or a pager ' +
1695
+ 'in git config, a `NODE_OPTIONS` carrying `--require`, a shell function shadowing `cat`. ' +
1696
+ 'READ_ONLY_PROGRAMS matches the command TEXT, and the environment is not in it',
1697
+ // The same miss one step earlier: not what the reader launches, but which
1698
+ // reader the name picks out. Split from the entry above because that one ends
1699
+ // "the environment is not in it" and this program IS in the command text —
1700
+ // the gate reads the word and still gets the wrong program.
1701
+ 'a DIFFERENT program with an allowed one\'s name. The table is keyed on the BASENAME, so ' +
1702
+ '`/bin/cat` and `cat` are one entry — and so is a repo-writable `src/cat`, or a bare `cat` ' +
1703
+ 'resolved from a PATH entry the repository owns. Closing it would close nothing: a script ' +
1704
+ 'with the path already inside it needs no allowed name at all, which is miss 3',
1374
1705
  ]);
1375
1706
 
1376
1707
  /** Every literal token of a command, with message-flag arguments skipped. */
@@ -1404,19 +1735,34 @@ export function shellPathFindings(command, startDir, root) {
1404
1735
  }
1405
1736
 
1406
1737
  /** The refusal for a protected path named in a shell command. */
1407
- function refuseShellPaths(findings) {
1738
+ function refuseShellPaths(findings, command = '') {
1408
1739
  const credentials = findings.filter((f) => f.kind === 'credential');
1409
1740
  const kernel = findings.filter((f) => f.kind === 'kernel');
1741
+ // The credential the finding list never saw, because it sat where a message
1742
+ // flag's argument would be or behind a `~`. Computed only when no credential
1743
+ // finding already names one, so the same path is not billed twice — and named
1744
+ // out loud, because otherwise this refusal would offer the "rewrite it as a
1745
+ // read-only command" way forward for a line whose problem is the secret in it.
1746
+ // A refusal that states the wrong reason is worse than one that states none.
1747
+ const hidden = credentials.length === 0 ? rawCredentialWords(command) : [];
1748
+ // True when the PATHS were all in the readable class, so the command itself
1749
+ // is the only reason this is a refusal. Worth saying: the reader is one
1750
+ // rewrite away from an allowed call, and a refusal with no reachable way
1751
+ // forward produces an agent that looks for a way around (ADR-19).
1752
+ const commandWasTheProblem =
1753
+ credentials.length === 0 &&
1754
+ hidden.length === 0 &&
1755
+ kernel.every((f) => SHELL_READABLE_GLOBS.includes(f.detail));
1410
1756
  const lines = [
1411
1757
  'tyran policy-gate: refused. This command names a path this gate protects.',
1412
- ...credentials.map(
1758
+ ...[...credentials, ...hidden].map(
1413
1759
  (f) => ` - ${JSON.stringify(shortPath(f.token))} is credential-shaped (${safePolicyText(f.detail)})`,
1414
1760
  ),
1415
1761
  ...kernel.map(
1416
1762
  (f) => ` - ${JSON.stringify(shortPath(f.token))} is under the protected path \`${safePolicyText(f.detail)}\``,
1417
1763
  ),
1418
1764
  ];
1419
- if (credentials.length > 0) {
1765
+ if (credentials.length + hidden.length > 0) {
1420
1766
  lines.push(
1421
1767
  '',
1422
1768
  'A shell command that names a credential file publishes its bytes whatever the program is: ' +
@@ -1433,6 +1779,23 @@ function refuseShellPaths(findings) {
1433
1779
  'refused for them.',
1434
1780
  );
1435
1781
  }
1782
+ if (commandWasTheProblem) {
1783
+ lines.push(
1784
+ '',
1785
+ `These paths are READABLE from a shell — ${SHELL_READABLE_GLOBS.join(' and ')} both are — ` +
1786
+ 'so what was refused is this COMMAND, not the file. A read-only line passes: the allowed ' +
1787
+ 'programs are cat, head, tail, wc, grep, rg, diff, `node --check` and `git log`/`show`/' +
1788
+ '`diff`, each only under flags that cannot write, and the line may contain no redirection ' +
1789
+ '(`>`, `>>`, `2>`, `<`), no command substitution (`$(…)`, backticks), no `&`, and no ' +
1790
+ 'segment whose program is not on that list — a pipe into a writer is a writer.',
1791
+ 'Residual floor, stated because a flag table cannot see past the command text: an allowed ' +
1792
+ 'reader can still be made to run something else by configuration this gate never reads — ' +
1793
+ 'a `diff.external` driver or pager in git config, a NODE_OPTIONS carrying `--require`, a ' +
1794
+ 'shell function shadowing `cat`. The exemption is that these paths are no harder to READ ' +
1795
+ 'from a shell than with the Read tool, which already passes on them; it is not a claim ' +
1796
+ 'that an allowed program can only ever read.',
1797
+ );
1798
+ }
1436
1799
  lines.push(
1437
1800
  '',
1438
1801
  // The same sentence write-guard settled on, for the same measured reason:
@@ -1468,7 +1831,10 @@ async function decideBash({ input, toolInput, root, runner, budget }) {
1468
1831
  // check that only runs once a policy loads is a check an unconfigured repo
1469
1832
  // does not have.
1470
1833
  const findings = shellPathFindings(command, startDir, root);
1471
- if (findings.length > 0) return refuseShellPaths(findings);
1834
+ // The exemption SKIPS this refusal; it does not return PASS. A `git log` that
1835
+ // names a protected path still travels the deployment class and every other
1836
+ // check below, exactly as `git log` on any other path does.
1837
+ if (findings.length > 0 && !shellReadExempt(findings, command)) return refuseShellPaths(findings, command);
1472
1838
 
1473
1839
  const plan = planCommand(command, startDir);
1474
1840
  const pushes = plan.targets.filter((t) => t.scanPush === true && Array.isArray(t.pushArgv));
@@ -17,13 +17,14 @@
17
17
  * worse bug than the missing summary.
18
18
  */
19
19
  import { execFileSync } from 'node:child_process';
20
- import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
20
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
21
21
  import { cpus, totalmem } from 'node:os';
22
22
  import { dirname, isAbsolute, join, resolve } from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
 
25
25
  import { checkHooks } from '../../scripts/hooks-check.mjs';
26
26
  import { readJournal } from '../../scripts/journal.mjs';
27
+ import { SESSION_ID_RE } from '../../scripts/overnight.mjs';
27
28
  import { fold, inlinePlain, progressLine } from '../../scripts/project.mjs';
28
29
  import { field, main, runProbe } from './hook-io.mjs';
29
30
 
@@ -206,7 +207,19 @@ export function renderContext({ repoRoot, initiatives, doctor, hardware, nowIso,
206
207
  const openGates = state.openGates ?? [];
207
208
  if (openGates.length > 0) {
208
209
  lines.push(`- Open gates (${openGates.length}):`);
209
- lines.push(...rows(openGates, (g) => ` - ${inlinePlain(g.kind)}: ${inlinePlain(g.result ?? 'open')} (${inlinePlain(g.ts)})`));
210
+ // The QUESTION, not only the gate's name: an ask is a gate whose kind is
211
+ // its id, and `Q-7: WAITING_ON_OPERATOR` tells a resumed conductor that
212
+ // it is waiting without telling it what it asked — which is a
213
+ // re-litigation after every compaction.
214
+ lines.push(
215
+ ...rows(
216
+ openGates,
217
+ (g) =>
218
+ ` - ${inlinePlain(g.kind)}: ${inlinePlain(g.result ?? 'open')}` +
219
+ (g.question ? ` — ${inlinePlain(g.question)}` : '') +
220
+ ` (${inlinePlain(g.ts)})`,
221
+ ),
222
+ );
210
223
  }
211
224
 
212
225
  const leases = [...(state.leases?.values() ?? [])];
@@ -335,6 +348,59 @@ export function renderPauseNotice(marker, nowIso) {
335
348
  );
336
349
  }
337
350
 
351
+ /** Where the resumable session id is recorded, relative to `.tyran`. */
352
+ export const CONDUCTOR_RELPATH = join('state', 'conductor.json');
353
+
354
+ /**
355
+ * Record this session so `answer.mjs apply --resume` can put the swarm back on
356
+ * it. Until this existed a resumable session id was written ONLY by a
357
+ * usage-limit pause or by the operator-installed statusline, so a repo with
358
+ * neither had no way to be resumed at all.
359
+ *
360
+ * THE CONTRACT, because a reader will otherwise infer more than this process
361
+ * can vouch for. The file carries exactly three fields:
362
+ *
363
+ * - `session_id` — shape-checked against SESSION_ID_RE before it is written,
364
+ * because it becomes an argument of a `claude --resume` command and this
365
+ * file is the only thing vouching for it;
366
+ * - `started_at` — the moment of THIS `SessionStart`, which fires on
367
+ * `startup`, `resume` and `compact` (hooks.json's matcher), so it is the
368
+ * last time the session announced itself, not the time it began;
369
+ * - `cwd` — the repo root this probe resolved.
370
+ *
371
+ * There is deliberately NO liveness signal, and no pid. The only pid a hook
372
+ * can observe is its OWN: this process is spawned per event and exits within
373
+ * a second, so a recorded pid is dead before anyone reads it and, once the OS
374
+ * recycles the number, names a stranger. A consumer treating it as "the
375
+ * conductor is alive" is wrong in both directions — never true while the
376
+ * session runs, sometimes true after it is gone. Nothing else in a
377
+ * `SessionStart` payload has been MEASURED to track the session's lifetime
378
+ * (see hooks/HOOK-CONTRACT-MEASURED.md), so this file says only that the
379
+ * session id existed at `started_at`, and a consumer may conclude only that.
380
+ *
381
+ * Best-effort, and inside its own try/catch: `SessionStart` has no way to
382
+ * refuse anything (ADR-22), so a probe that threw here would cost the user
383
+ * their session to report that a convenience file could not be written.
384
+ * `.tyran/state/**` is the AUTO policy class already, so no policy moves.
385
+ */
386
+ export function recordConductor(stateDir, input, { now = new Date(), cwd = null } = {}) {
387
+ try {
388
+ const sessionId = field(input, 'session_id');
389
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
390
+ const target = join(stateDir, CONDUCTOR_RELPATH);
391
+ mkdirSync(dirname(target), { recursive: true });
392
+ const doc = { session_id: sessionId, started_at: now.toISOString(), cwd: cwd ?? dirname(stateDir) };
393
+ // The pid names the TEMP file only — two hook processes writing at once
394
+ // must not collide on one name. It is never part of the record.
395
+ const temp = join(dirname(target), `.conductor-${process.pid}.tmp`);
396
+ writeFileSync(temp, JSON.stringify(doc, null, 2) + '\n');
397
+ renameSync(temp, target);
398
+ return true;
399
+ } catch {
400
+ return false; // a probe never fails a session over a courtesy file
401
+ }
402
+ }
403
+
338
404
  /** The pause marker, if one is active. Garbage reads as absent. */
339
405
  export function readPauseMarker(stateDir) {
340
406
  try {
@@ -357,6 +423,7 @@ export async function buildContext({ input, now = new Date(), env = process.env,
357
423
  if (repoRoot === null) return fitBudget(warning);
358
424
  const stateDir = join(repoRoot, '.tyran');
359
425
  if (!existsSync(stateDir)) return fitBudget(warning); // not a Tyran repo — but a dead gate still counts
426
+ recordConductor(stateDir, input, { now, cwd: repoRoot });
360
427
  const nowIso = now.toISOString();
361
428
  return fitBudget(
362
429
  warning +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.13",
3
+ "version": "0.1.17",
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": {