rungate 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/lib/agents-md-sections.ts +144 -0
  2. package/lib/branch-diff.ts +139 -0
  3. package/lib/bun-version.ts +268 -0
  4. package/lib/ci-checkout.ts +1 -1
  5. package/lib/compliance.ts +13 -11
  6. package/lib/config-loader.ts +12 -0
  7. package/lib/conformity.ts +184 -88
  8. package/lib/context-docs.ts +143 -28
  9. package/lib/create-brief.ts +2 -1
  10. package/lib/create-sc.ts +90 -4
  11. package/lib/doc-scan-targets.ts +9 -0
  12. package/lib/evidence-command-transport.ts +160 -0
  13. package/lib/evidence-prevalidator.ts +22 -0
  14. package/lib/fallow-availability.ts +129 -0
  15. package/lib/gate-refusal-currency.ts +112 -0
  16. package/lib/gate-timeouts.ts +82 -0
  17. package/lib/generators/agent-briefs.ts +4 -1
  18. package/lib/generators/agents-md.ts +71 -23
  19. package/lib/generators/code-map.ts +2 -1
  20. package/lib/generators/types.ts +8 -0
  21. package/lib/git-dates.ts +55 -0
  22. package/lib/junit-checks.ts +484 -0
  23. package/lib/local-calendar-day.ts +78 -0
  24. package/lib/project-state-shape.ts +59 -0
  25. package/lib/promote-outputs.ts +6 -2
  26. package/lib/report-provenance.ts +156 -0
  27. package/lib/sc-claim-forms.ts +75 -0
  28. package/lib/sc-id-cross-tree.ts +311 -0
  29. package/lib/scaffold/ai-review-step.ts +180 -0
  30. package/lib/scaffold/owned-files.ts +42 -2
  31. package/lib/scaffold/rehearsal.ts +205 -71
  32. package/lib/scaffold/steps.ts +128 -73
  33. package/lib/scaffold/write-steps.ts +6 -4
  34. package/lib/scanner.ts +38 -12
  35. package/lib/spec-listing.ts +148 -0
  36. package/lib/spec-requirements.ts +209 -0
  37. package/lib/suite-run-reading.ts +170 -0
  38. package/lib/test-command.ts +133 -0
  39. package/lib/test-suite-lock.ts +166 -10
  40. package/lib/tool-probe.ts +120 -0
  41. package/lib/tracked-vs-ignored.ts +234 -0
  42. package/lib/validators/spec-validators.ts +3 -2
  43. package/package.json +1 -1
  44. package/scripts/audit-specs.ts +247 -12
  45. package/scripts/audit-transcript.ts +2 -1
  46. package/scripts/convert-spec.ts +2 -1
  47. package/scripts/create-sc.ts +17 -7
  48. package/scripts/create-spec.ts +2 -1
  49. package/scripts/create-success.ts +2 -1
  50. package/scripts/extract-constraints.ts +90 -19
  51. package/scripts/generate-code-map.ts +53 -12
  52. package/scripts/scaffold-project.ts +4 -1
  53. package/scripts/split-spec.ts +2 -1
  54. package/scripts/sync-sc-status.ts +57 -5
  55. package/scripts/sync-spec-tests.ts +2 -1
package/lib/conformity.ts CHANGED
@@ -9,6 +9,14 @@ import { describe, test, expect } from "bun:test";
9
9
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
10
10
  import type { Dirent } from "fs";
11
11
  import { collectSpecFiles } from "./spec-files";
12
+ import {
13
+ ambiguousSpecNames,
14
+ readSpecRequirements,
15
+ requirementViolations,
16
+ specIsReferenced,
17
+ testableViolations,
18
+ } from "./spec-requirements";
19
+ import { lastCommitDates } from "./git-dates";
12
20
  import { spawnSync } from "child_process";
13
21
  import { join, dirname, sep } from "path";
14
22
  import { fileURLToPath } from "url";
@@ -18,6 +26,7 @@ import { tryLoadRungateConfig } from "./config-loader";
18
26
  import { stripJsComments } from "./strip-js-comments";
19
27
  import { parseScDeclarations } from "./sc-ids";
20
28
  import { isHarnessItself } from "./harness-identity";
29
+ import { fallowAvailable } from "./fallow-availability";
21
30
  import { tsconfigVerdict, TS_SOURCE_DIRS } from "./typescript-project";
22
31
  import { readSuccessDoc, readSuccessTemplate, successViolations } from "./success-doc";
23
32
 
@@ -1526,7 +1535,11 @@ export function runSpecDrift(
1526
1535
  }
1527
1536
  }
1528
1537
 
1529
- const orphaned = testable.filter(s => !allContent.includes(s));
1538
+ // Not `allContent.includes(s)`. A bare basename credits a spec for a
1539
+ // test that names a DIFFERENT file — see `lib/spec-requirements.ts`,
1540
+ // where the collision and its one instance on this tree are measured.
1541
+ const ambiguous = ambiguousSpecNames(root, collectSpecFiles(specsDir));
1542
+ const orphaned = testable.filter(s => !specIsReferenced(allContent, s, ambiguous));
1530
1543
 
1531
1544
  // Was `expect(true).toBe(true)` after a console.warn, so the mechanical
1532
1545
  // enforcement of CLAUDE.md's "SCs without tests are wishes" could never
@@ -1612,6 +1625,23 @@ export function runSpecDrift(
1612
1625
  `exemption a deliberate recorded decision rather than a diff.`,
1613
1626
  ).toEqual([]);
1614
1627
  });
1628
+
1629
+ test("DRIFT-4: Every spec states criteria, or declares that it states none", () => {
1630
+ if (!existsSync(specsDir)) return checkSkipped("DRIFT-4", "no specs/ directory");
1631
+ const specs = collectSpecFiles(specsDir);
1632
+ if (specs.length === 0) return checkSkipped("DRIFT-4", "no spec files");
1633
+
1634
+ // Unlike DRIFT-2 this has no ratchet and does not need one. The
1635
+ // exemption is a line in the document's own frontmatter, so a consumer
1636
+ // on upgrade can clear a violation by declaring it where the reader it
1637
+ // affects will see it — no list to adopt, nothing inherited from
1638
+ // rungate's backlog, and nothing DRIFT-3 has to police.
1639
+ const violations = requirementViolations(specs.map(s => readSpecRequirements(specsDir, s)));
1640
+ expect(violations, violations.join("\n")).toEqual([]);
1641
+
1642
+ const badFlags = testableViolations(specsDir, specs);
1643
+ expect(badFlags, badFlags.join("\n")).toEqual([]);
1644
+ });
1615
1645
  });
1616
1646
  }
1617
1647
 
@@ -1622,67 +1652,11 @@ export function runSpecDrift(
1622
1652
  * `runDocHygiene(ROOT, findings)`.
1623
1653
  */
1624
1654
  /**
1625
- * Every path's most recent commit date, from ONE git subprocess (#323).
1626
- *
1627
- * Exported so the regression test can run it against the repository and
1628
- * compare it to the per-file calls it replaced — a single site to mutate, and
1629
- * the only way to prove the parser still agrees with git rather than merely
1630
- * being faster. A detector that got quicker by finding less would pass every
1631
- * timing test and none of the ones that matter.
1632
- *
1633
- * Walks newest-first, so the first time a path appears is its latest commit
1634
- * and later entries are ignored. Paths deleted or renamed earlier in history
1635
- * also appear; they are never looked up, which is cheaper than filtering them.
1636
- *
1637
- * `pathspecs` must be the SET OF PATHS THE CALLER WILL LOOK UP, not the
1638
- * directories they mostly live in. The first version of this took the six doc
1639
- * directories, which is where the staleness scan finds most of its files — but
1640
- * the scan also walks root-level markdown, and `git log -- specs docs` cannot
1641
- * report a commit for `AGENTS.md`. Six files silently dropped out of the
1642
- * lookup and `if (!dateStr) continue` read that as "newly added, so not
1643
- * stale". A detector narrower than what it detects, shipped inside the fix for
1644
- * a different instance of the same thing. Passing the lookup set makes the
1645
- * pathspec and the keys the same list by construction, so they cannot drift.
1646
- *
1647
- * Fails CLOSED. `spawnSync` does not throw when git exits non-zero, so a
1648
- * broken invocation would otherwise return an empty map and every file would
1649
- * read as newly added — total blindness that looks exactly like a clean run.
1655
+ * Re-exported from `lib/git-dates.ts` (#508). The body moved to a leaf so a
1656
+ * CLI outside the test runner can call it; this stays the name SC-842 and
1657
+ * every existing caller use.
1650
1658
  */
1651
- export function lastCommitDates(root: string, pathspecs: string[]): Map<string, string> {
1652
- const lastCommit = new Map<string, string>();
1653
- // Not a git repository: nothing is tracked, so no path has a commit date.
1654
- // That is a real answer, not a failure, and scaffolded projects hit it.
1655
- if (!existsSync(join(root, ".git"))) return lastCommit;
1656
- if (pathspecs.length === 0) return lastCommit;
1657
- {
1658
- const log = spawnSync(
1659
- "git",
1660
- ["-C", root, "log", "--format=%H %ci", "--name-only", "--", ...pathspecs],
1661
- { timeout: 60_000, maxBuffer: 64 * 1024 * 1024 },
1662
- );
1663
- if (log.error) {
1664
- throw new Error(`lastCommitDates: git log could not run in ${root}: ${log.error.message}`);
1665
- }
1666
- if (log.status !== 0) {
1667
- throw new Error(
1668
- `lastCommitDates: git log exited ${log.status} in ${root}: ` +
1669
- `${log.stderr?.toString().trim() || "(no stderr)"}`,
1670
- );
1671
- }
1672
- let currentDate = "";
1673
- for (const line of log.stdout.toString().split("\n")) {
1674
- const header = /^[0-9a-f]{7,40} (\d{4}-\d{2}-\d{2})/.exec(line);
1675
- if (header) {
1676
- currentDate = header[1];
1677
- continue;
1678
- }
1679
- const path = line.trim();
1680
- if (!path || !currentDate) continue;
1681
- if (!lastCommit.has(path)) lastCommit.set(path, currentDate);
1682
- }
1683
- }
1684
- return lastCommit;
1685
- }
1659
+ export { lastCommitDates };
1686
1660
 
1687
1661
  export function runDocHygiene(
1688
1662
  root: string,
@@ -2003,7 +1977,28 @@ export function runDocHygiene(
2003
1977
  );
2004
1978
  }
2005
1979
 
2006
- expect(true).toBe(true);
1980
+ // The leniency above is about the BACKLOG. It was never meant to be
1981
+ // leniency about whether the scan happened, and `expect(true).toBe(true)`
1982
+ // made it both: with no assertion on the reading, the only red this
1983
+ // check could produce was a timeout — which is exactly the red it
1984
+ // produced, four times, until #508 made the staleness scan one git
1985
+ // call instead of ninety-two.
1986
+ //
1987
+ // So the reading is asserted and the backlog still is not. `0
1988
+ // candidates` over 91 documents and `0 candidates` over 4 are the same
1989
+ // line of output, and nothing here could previously tell them apart.
1990
+ console.log(
1991
+ `HYGIENE-6 coverage: read ${result.coverage.read} of ${result.coverage.planned} planned documents ` +
1992
+ `from ${result.scan.roots.length} directories (${result.scan.source})`,
1993
+ );
1994
+ expect(
1995
+ result.coverage.planned,
1996
+ "the documentation scan planned no files, so this check measured nothing",
1997
+ ).toBeGreaterThan(0);
1998
+ expect(
1999
+ result.coverage.unread,
2000
+ "planned documents could not be read, so the candidate list above is partial",
2001
+ ).toEqual([]);
2007
2002
  });
2008
2003
 
2009
2004
  test("HYGIENE-11: Stale unreferenced files warn with archival suggestion", () => {
@@ -2464,21 +2459,13 @@ interface FallowResult {
2464
2459
  // fail as timeouts instead of skipping, which blocks the pre-push conformity
2465
2460
  // gate on a tool nobody installed.
2466
2461
  //
2467
- // Resolve it locally instead, with no network path. Memoised PER ROOT —
2468
- // runFallowCheck is exported and consumer projects call it with their own
2469
- // root, so a single process can ask about several. A root-independent cache
2470
- // would answer for the wrong directory.
2471
- const FALLOW_AVAILABLE = new Map<string, boolean>();
2472
-
2473
- function fallowAvailable(root: string): boolean {
2474
- const cached = FALLOW_AVAILABLE.get(root);
2475
- if (cached !== undefined) return cached;
2476
- const available =
2477
- existsSync(join(root, "node_modules", ".bin", "fallow")) ||
2478
- Bun.which("fallow") !== null;
2479
- FALLOW_AVAILABLE.set(root, available);
2480
- return available;
2481
- }
2462
+ // Resolve it locally instead, with no network path. The predicate moved to
2463
+ // `lib/fallow-availability.ts` in #581 and is re-exported here rather than
2464
+ // copied: this module imports `bun:test` at module scope, so a CLI cannot
2465
+ // import it, and `scripts/generate-code-map.ts` is a CLI that needed the
2466
+ // same answer. It had a second answer — a bare `npx fallow` — for four
2467
+ // months, which is the defect #581 is about.
2468
+ export { fallowAvailable };
2482
2469
 
2483
2470
  /** Shared skip notice — a skipped check must say so, not read as a pass. */
2484
2471
  function fallowSkipped(check: string): void {
@@ -2976,7 +2963,19 @@ function walkSources(dir: string, rel: string, out: Array<{ path: string; text:
2976
2963
  walkSources(abs, relPath, out);
2977
2964
  continue;
2978
2965
  }
2979
- if (!/\.(ts|js)$/.test(e.name) || /\.test\.ts$/.test(e.name)) continue;
2966
+ // `SOURCE_EXTENSIONS`, not `/\.(ts|js)$/`. The evidence walk counts
2967
+ // `.tsx .jsx .mjs .cjs .mts .cts` as source and this scan could not read
2968
+ // any of them, so the invariant stated above — the walk must not claim
2969
+ // source the scan would never read — was violated for six extensions
2970
+ // (#506).
2971
+ //
2972
+ // Measured: a project whose only code is `lib/app.tsx` holding a live
2973
+ // direct config read scans ZERO files, and CONFIG-1 refuses with *"This
2974
+ // project DOES contain source — lib/app.tsx — none of it in the
2975
+ // directories this check reads"*. `lib/` is the first directory this
2976
+ // check reads. The sentence is false, the refusal is unclearable, and
2977
+ // the read goes uncaught — three failures from one missing extension.
2978
+ if (!SOURCE_EXTENSIONS.test(e.name) || /\.test\.ts$/.test(e.name)) continue;
2980
2979
  out.push({ path: relPath, text: readFileSync(abs, "utf-8") });
2981
2980
  }
2982
2981
  }
@@ -3029,19 +3028,58 @@ export function scanConfigAccess(root: string): ConfigAccessScan {
3029
3028
  * through both scans and asserts they disagree, so the collapse cannot be made
3030
3029
  * quietly in the name of consistency.
3031
3030
  */
3031
+ /**
3032
+ * Every module in `workflows/`, in any language this project writes them in.
3033
+ *
3034
+ * It was `.js` only, non-recursively, because rungate's own workflows are
3035
+ * flat `.js` — they cannot import (#69). A consumer keeping TypeScript
3036
+ * workflows got CONFIG-2 reading zero files over a directory full of code,
3037
+ * which the empty-scan refusal then reported as `the scan read NO files`,
3038
+ * unsatisfiable without converting the workflows to `.js` (#501).
3039
+ *
3040
+ * `.d.ts` is excluded for the same reason the CONFIG-1 walk excludes it:
3041
+ * declarations contain no calls.
3042
+ */
3043
+ const WORKFLOW_MODULE = /\.(js|mjs|cjs|ts|mts|cts)$/;
3044
+
3045
+ function workflowModules(dir: string, rel: string, out: string[]): void {
3046
+ let entries;
3047
+ try {
3048
+ entries = readdirSync(dir, { withFileTypes: true });
3049
+ } catch {
3050
+ return;
3051
+ }
3052
+ for (const e of entries) {
3053
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
3054
+ // RECURSIVE, and that is load-bearing rather than tidy. CONFIG-1
3055
+ // declines `workflows/` entirely on the grounds that CONFIG-2 owns it,
3056
+ // so a depth CONFIG-2 does not reach is a depth NEITHER check reads —
3057
+ // a blind spot the hand-off would create rather than one it inherits.
3058
+ if (e.isDirectory()) {
3059
+ if (e.name === "node_modules") continue;
3060
+ workflowModules(join(dir, e.name), childRel, out);
3061
+ continue;
3062
+ }
3063
+ if (!e.isFile()) continue;
3064
+ if (!WORKFLOW_MODULE.test(e.name) || e.name.endsWith(".d.ts")) continue;
3065
+ out.push(childRel);
3066
+ }
3067
+ }
3068
+
3032
3069
  export function scanPromptConfigAccess(root: string): ConfigAccessScan {
3033
3070
  const dir = join(root, "workflows");
3034
3071
  const counts: Record<string, number> = {};
3035
3072
  let filesScanned = 0;
3036
3073
  let bytesScanned = 0;
3037
- let entries: string[];
3038
- try {
3039
- entries = readdirSync(dir).filter(f => f.endsWith(".js"));
3040
- } catch {
3041
- return { counts, filesScanned: 0, bytesScanned: 0 };
3042
- }
3043
- for (const f of entries) {
3044
- const text = readFileSync(join(dir, f), "utf-8");
3074
+ const entries: string[] = [];
3075
+ workflowModules(dir, "", entries);
3076
+ for (const f of entries.sort()) {
3077
+ let text: string;
3078
+ try {
3079
+ text = readFileSync(join(dir, f), "utf-8");
3080
+ } catch {
3081
+ continue;
3082
+ }
3045
3083
  filesScanned++;
3046
3084
  bytesScanned += text.length;
3047
3085
  const n = (stripJsComments(text).match(configAccessPattern()) || []).length;
@@ -3290,7 +3328,7 @@ export function configAccessViolationRecords(
3290
3328
  * refusal had never been reachable.
3291
3329
  */
3292
3330
  /** Anything that can carry code. Deliberately WIDER than any scanner's filter. */
3293
- const SOURCE_EXTENSIONS = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
3331
+ export const SOURCE_EXTENSIONS = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
3294
3332
 
3295
3333
  /** Directories that hold code nobody wrote, or output nobody edits. */
3296
3334
  const SOURCE_SKIP_DIRS = new Set([
@@ -3461,9 +3499,47 @@ const NEVER_PROJECT_SOURCE = new Set([".git", "node_modules"]);
3461
3499
  * dangling-symlink note further down already rules out for the same reason.
3462
3500
  * A link that resolves to nothing is not somewhere a reader can go looking,
3463
3501
  * which is the only thing the trailing slash claims.
3502
+ *
3503
+ * ## The dirent is authoritative for everything that is not a symlink (#543)
3504
+ *
3505
+ * `if (!e.isSymbolicLink()) return false` is a COST guard, not a correctness
3506
+ * one — `statSync` on a regular file answers the same thing the dirent
3507
+ * already did, so removing it changes no label on any real tree and was
3508
+ * **0 red of 92**. What it changes is syscalls. Before #518 an entry named
3509
+ * `.git`, `node_modules`, `dist`, `build`, `coverage`, `.next`, `.output`,
3510
+ * `vendor` or any dot-name cost zero; this function made it cost one, and
3511
+ * those are exactly the names people symlink onto network paths — a shared
3512
+ * `node_modules`, a pnpm store, `dist` on a build mount. `statSync` on a
3513
+ * stale NFS or autofs target blocks uninterruptibly and there is no timeout
3514
+ * to give it.
3515
+ *
3516
+ * A cost is not observable from a test, so the guard is pinned by the one
3517
+ * thing that is: a dirent that DISAGREES with the filesystem. Hand this
3518
+ * function "not a directory, not a symlink" together with a path that is a
3519
+ * directory, and today it answers `false`; without the guard the stat runs
3520
+ * and it answers `true`. That is the syscall, made visible.
3521
+ *
3522
+ * **Two residuals, stated rather than silently carried:**
3523
+ *
3524
+ * - A declined SYMLINK still costs one `statSync`, and that is the stale-
3525
+ * mount exposure. It is kept deliberately: dropping it writes a symlinked
3526
+ * `node_modules` down as a file, which is the commonest real instance of
3527
+ * the thing #518 fixed. `readlinkSync` would resolve the name without
3528
+ * touching the target, but a monorepo's `node_modules -> ../../node_modules`
3529
+ * is outside the project and still a directory, so the cheap answer is
3530
+ * wrong for the case that motivates the stat.
3531
+ * - That stat crosses the project boundary without consulting
3532
+ * `insideProject`. The walk does not follow the link — all three branches
3533
+ * `continue` — so containment holds, verified over a 64-shape matrix; the
3534
+ * residual is that the waiver message asserts one bit about a path
3535
+ * outside the project, reachable only by someone who could already plant
3536
+ * a symlink inside it.
3464
3537
  */
3465
- function declinedIsDir(e: Dirent, abs: string): boolean {
3538
+ export function declinedIsDir(e: Dirent, abs: string): boolean {
3466
3539
  if (e.isDirectory()) return true;
3540
+ // Not a correctness branch — see the note above. A dirent that says
3541
+ // "regular file" is the answer; going to the filesystem to ask again is a
3542
+ // syscall on a path that may be a stale mount.
3467
3543
  if (!e.isSymbolicLink()) return false;
3468
3544
  try {
3469
3545
  return statSync(abs).isDirectory();
@@ -3693,6 +3769,26 @@ export function projectSourceEvidence(root: string): SourceEvidence {
3693
3769
  // the scan does not walk either — `index.ts` is an ordinary shape
3694
3770
  // and leaving it out would be the same blind spot one level up.
3695
3771
  const top = childRel.includes("/") ? childRel.slice(0, childRel.indexOf("/")) : ".";
3772
+ // Source another CHECK measures is not evidence that this one is
3773
+ // blind (#501). `workflows/w.ts` set `found`, so a project whose
3774
+ // only code is a workflow was told CONFIG-1 "DOES contain source …
3775
+ // none of it in the directories this check reads" — true, and
3776
+ // unsatisfiable, because CONFIG-1 declines that directory precisely
3777
+ // so CONFIG-2 can own it. Two red checks, neither fixable without
3778
+ // rewriting the project in another language.
3779
+ //
3780
+ // `CONFIG_1_DECLINES` and NOT `measuredElsewhere`, and the gap
3781
+ // between the two is deliberate: `test/` is excluded by ADR-002 D4
3782
+ // with nobody measuring it, so a project whose only source is a test
3783
+ // directory must still refuse — that is #500's own case, and
3784
+ // collapsing the two predicates would waive it.
3785
+ //
3786
+ // Recorded rather than skipped silently, so the UNMEASURED sentence
3787
+ // names the hand-off instead of implying the tree is empty.
3788
+ if (CONFIG_1_DECLINES.has(top)) {
3789
+ skipped.push(`${childRel} (measured by CONFIG-2, which reads ${top}/)`);
3790
+ continue;
3791
+ }
3696
3792
  if (!CONFIG_SCAN_DIRS.includes(top) && !measuredElsewhere(top)) {
3697
3793
  unscannedDirs.add(top);
3698
3794
  unscannedSourceCount++;
@@ -18,27 +18,50 @@
18
18
  *
19
19
  * This module owns (1) and (3)'s successor; the loader owns (2).
20
20
  *
21
- * ## The decision about paths outside the project root
22
- *
23
- * They are ALLOWED, and the brief says so.
24
- *
25
- * The filter's instinct was right — an unvalidated path from config into an
26
- * agent brief is worth thinking about — but the thing being protected is not
27
- * what it looked like. A brief NAMES files; it does not read them. The config
28
- * is written by the operator whose session the agent runs in, so a path they
29
- * declared is not an escalation of anything: they could have put the file in
30
- * the repo, or pointed the agent at it in a sentence.
31
- *
32
- * What is worth protecting is a reader's ability to SEE that a brief reaches
33
- * outside the repository. So an external doc is included and labelled
34
- * `(external to this project)`, and a missing one is included and labelled
35
- * rather than dropped. Nothing declared disappears without a line saying what
36
- * happened to it — which is the property the old filter did not have and the
37
- * only one this file is really about.
21
+ * ## The decision about paths outside the project root (#439, revised by #497)
22
+ *
23
+ * #439 allowed them, on two premises:
24
+ *
25
+ * > A brief NAMES files; it does not read them. The config is written by the
26
+ * > operator whose session the agent runs in, so a path they declared is not
27
+ * > an escalation of anything.
28
+ *
29
+ * The first is true of the brief and beside the point: the brief exists to be
30
+ * obeyed by an agent holding a Read tool, so "named" and "read" are one step
31
+ * apart and the step is the document's purpose. The second is true when the
32
+ * operator scaffolded the project. Rungate is a harness pointed at a
33
+ * `projectRoot`, and the config lives INSIDE that tree — so for any repo the
34
+ * operator cloned rather than authored, `contextDocs: ["/Users/<them>/.ssh/id_rsa"]`
35
+ * is a line in a checked-in file that puts an arbitrary host path into an
36
+ * agent instruction.
37
+ *
38
+ * That is a true sentence derived from the cases that were measured —
39
+ * operator-authored config — and then applied to a population it does not
40
+ * cover. `.claude/rules/checks-must-be-able-to-fail.md` has the shape under
41
+ * *"This cannot be checked" is a claim, and it is checkable*.
42
+ *
43
+ * So an external path is now REJECTED rather than included, unless its root
44
+ * is trusted — and the trust comes from `RUNGATE_TRUSTED_DOC_ROOTS` in the
45
+ * environment, never from the repository under test. **An allowlist inside
46
+ * the config it is allowing is not one**, which is the whole reason this is a
47
+ * revision rather than a revert.
48
+ *
49
+ * #439's real property is untouched and is still the thing this file is
50
+ * about: nothing declared disappears without a line saying what happened to
51
+ * it. A rejected external path is named in the notes with its reason, exactly
52
+ * as a missing or malformed one is. The old filter dropped it in silence; the
53
+ * difference between that and this is the only difference that matters.
54
+ *
55
+ * ## Symlinks
56
+ *
57
+ * The comparison is on the REAL path. `relative(resolve(root), resolved)` is
58
+ * symlink-blind: a link inside the repo pointing at `/Users/<them>/.ssh`
59
+ * resolves to a path under the root and reads as internal, which makes the
60
+ * control satisfiable by the cheapest possible bypass.
38
61
  */
39
62
 
40
- import { existsSync } from "fs";
41
- import { isAbsolute, relative, resolve } from "path";
63
+ import { existsSync, realpathSync } from "fs";
64
+ import { dirname, isAbsolute, join, relative, resolve } from "path";
42
65
 
43
66
  /**
44
67
  * Characters a path must not carry into a brief (BUG-439-A).
@@ -65,6 +88,61 @@ export function hasBriefUnsafeChars(value: string): boolean {
65
88
  return BRIEF_UNSAFE.test(value);
66
89
  }
67
90
 
91
+ /**
92
+ * The environment variable that names roots outside a project whose docs may
93
+ * still be reached.
94
+ *
95
+ * Deliberately NOT a config key. The threat is a `contextDocs` line in a
96
+ * repository the operator cloned rather than wrote; an allowlist read from
97
+ * that same repository would be authored by whoever authored the entry it is
98
+ * supposed to authorise. It is also deliberately not a rungate config read,
99
+ * so `.claude/rules/config-access.md` does not apply — this is not project
100
+ * config, and routing it through the loader would put it back inside the tree
101
+ * it exists to be outside of.
102
+ */
103
+ export const TRUSTED_ROOTS_ENV = "RUNGATE_TRUSTED_DOC_ROOTS";
104
+
105
+ /**
106
+ * The trusted roots, absolute and real. `PATH`-style separator, because an
107
+ * operator setting this is already thinking in terms of a path list.
108
+ */
109
+ export function trustedDocRoots(env: NodeJS.ProcessEnv = process.env): string[] {
110
+ const raw = env[TRUSTED_ROOTS_ENV];
111
+ if (typeof raw !== "string" || raw.trim() === "") return [];
112
+ return raw
113
+ .split(":")
114
+ .map(p => p.trim())
115
+ .filter(p => p !== "" && isAbsolute(p))
116
+ .map(p => realPathish(p));
117
+ }
118
+
119
+ /**
120
+ * `realpathSync` where it can answer, and the real path of the nearest
121
+ * existing ancestor with the remainder appended where it cannot.
122
+ *
123
+ * A declared doc need not exist — `missing` is a first-class verdict here —
124
+ * and a plain `resolve()` fallback would make a path through a symlinked
125
+ * directory to a file that is not there yet read as internal. The ancestor
126
+ * walk is what keeps the missing case and the symlink case from being
127
+ * mutually exclusive.
128
+ */
129
+ export function realPathish(p: string): string {
130
+ let head = resolve(p);
131
+ const tail: string[] = [];
132
+ for (;;) {
133
+ try {
134
+ return tail.length === 0 ? realpathSync(head) : join(realpathSync(head), ...tail);
135
+ } catch {
136
+ const parent = dirname(head);
137
+ // `/` is its own parent: nothing below it existed, so there is nothing
138
+ // to resolve and the lexical answer is the honest one.
139
+ if (parent === head) return resolve(p);
140
+ tail.unshift(head.slice(parent.length === 1 ? 1 : parent.length + 1));
141
+ head = parent;
142
+ }
143
+ }
144
+ }
145
+
68
146
  export type ContextDocVerdict =
69
147
  | {
70
148
  kind: "included";
@@ -72,8 +150,10 @@ export type ContextDocVerdict =
72
150
  declared: string;
73
151
  /** Absolute, after resolving against the project root. */
74
152
  resolved: string;
75
- /** Outside the project root — reported, not refused. */
153
+ /** Outside the project root. Only reachable here when a trusted root allows it. */
76
154
  external: boolean;
155
+ /** The trusted root that allowed an external path, or null. */
156
+ trustedBy: string | null;
77
157
  /** Declared but not on disk when the brief was assembled. */
78
158
  missing: boolean;
79
159
  }
@@ -83,7 +163,11 @@ export type ContextDocVerdict =
83
163
  * Classify ONE declared entry. The single binding, so there is one thing to
84
164
  * mutate and each arm is separately observable in the assembled brief.
85
165
  */
86
- export function classifyContextDoc(projectRoot: string, declared: unknown): ContextDocVerdict {
166
+ export function classifyContextDoc(
167
+ projectRoot: string,
168
+ declared: unknown,
169
+ env: NodeJS.ProcessEnv = process.env,
170
+ ): ContextDocVerdict {
87
171
  if (typeof declared !== "string") {
88
172
  return { kind: "rejected", declared: JSON.stringify(declared) ?? String(declared), reason: "not a string" };
89
173
  }
@@ -99,14 +183,39 @@ export function classifyContextDoc(projectRoot: string, declared: unknown): Cont
99
183
  };
100
184
  }
101
185
 
102
- const resolved = isAbsolute(trimmed) ? resolve(trimmed) : resolve(projectRoot, trimmed);
186
+ // The REAL path, on both sides. A link inside the repo pointing outside it
187
+ // resolves under the root lexically, and comparing the lexical answers is a
188
+ // control anyone can walk past with `ln -s`.
189
+ const resolved = realPathish(isAbsolute(trimmed) ? trimmed : join(projectRoot, trimmed));
103
190
  // `relative` rather than `startsWith`: `/repo-backup` starts with `/repo`
104
191
  // and is a different directory. One comparison, computed the way the
105
192
  // filesystem means it.
106
- const rel = relative(resolve(projectRoot), resolved);
193
+ const rel = relative(realPathish(projectRoot), resolved);
107
194
  const external = rel === "" || rel.startsWith("..") || isAbsolute(rel);
108
195
 
109
- return { kind: "included", declared: trimmed, resolved, external, missing: !existsSync(resolved) };
196
+ const trustedBy = external ? (trustedDocRoots(env).find(root => isWithin(root, resolved)) ?? null) : null;
197
+ if (external && trustedBy === null) {
198
+ return {
199
+ kind: "rejected",
200
+ declared: trimmed,
201
+ reason: `resolves to ${resolved}, outside this project; add its root to ${TRUSTED_ROOTS_ENV} in the environment to allow it`,
202
+ };
203
+ }
204
+
205
+ return {
206
+ kind: "included",
207
+ declared: trimmed,
208
+ resolved,
209
+ external,
210
+ trustedBy,
211
+ missing: !existsSync(resolved),
212
+ };
213
+ }
214
+
215
+ /** Is `path` the root itself or under it? Same `relative` comparison, one place. */
216
+ function isWithin(root: string, path: string): boolean {
217
+ const rel = relative(root, path);
218
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
110
219
  }
111
220
 
112
221
  /**
@@ -116,7 +225,11 @@ export function classifyContextDoc(projectRoot: string, declared: unknown): Cont
116
225
  * rejection rather than silence, because a config that declares the key and
117
226
  * gets nothing is exactly the case this issue is about.
118
227
  */
119
- export function classifyContextDocs(projectRoot: string, raw: unknown): ContextDocVerdict[] {
228
+ export function classifyContextDocs(
229
+ projectRoot: string,
230
+ raw: unknown,
231
+ env: NodeJS.ProcessEnv = process.env,
232
+ ): ContextDocVerdict[] {
120
233
  if (raw === undefined || raw === null) return [];
121
234
  const entries: unknown[] = Array.isArray(raw)
122
235
  ? raw
@@ -130,7 +243,7 @@ export function classifyContextDocs(projectRoot: string, raw: unknown): ContextD
130
243
  reason: `contextDocs must be an array or an object, got ${typeof raw}`,
131
244
  }];
132
245
  }
133
- return entries.map(e => classifyContextDoc(projectRoot, e));
246
+ return entries.map(e => classifyContextDoc(projectRoot, e, env));
134
247
  }
135
248
 
136
249
  /** The numbered brief lines, one per included doc, labelled where it matters. */
@@ -140,7 +253,7 @@ export function contextDocLines(verdicts: ContextDocVerdict[], startIndex: numbe
140
253
  for (const v of verdicts) {
141
254
  if (v.kind !== "included") continue;
142
255
  const notes = [
143
- v.external ? "external to this project" : null,
256
+ v.external ? `external to this project, allowed by ${TRUSTED_ROOTS_ENV}` : null,
144
257
  v.missing ? "declared in contextDocs but not present at assembly time" : null,
145
258
  ].filter(Boolean);
146
259
  lines.push(`${idx}. ${v.resolved}${notes.length ? ` (${notes.join("; ")})` : ""}`);
@@ -176,7 +289,9 @@ export function contextDocNotes(verdicts: ContextDocVerdict[]): string[] {
176
289
  if (v.kind === "included") notes.push(`> - MISSING ${v.declared}: nothing at ${v.resolved}`);
177
290
  }
178
291
  for (const v of external) {
179
- if (v.kind === "included") notes.push(`> - EXTERNAL ${v.declared}: resolves to ${v.resolved}, outside this project`);
292
+ if (v.kind === "included") {
293
+ notes.push(`> - EXTERNAL ${v.declared}: resolves to ${v.resolved}, outside this project, trusted via ${v.trustedBy}`);
294
+ }
180
295
  }
181
296
  return notes;
182
297
  }
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { readFileSync, writeFileSync, existsSync } from "fs";
8
8
  import { writeRoleConfig } from "./config-loader";
9
+ import { localCalendarDay } from "./local-calendar-day";
9
10
  import type { AgentMeta } from "./generators/types";
10
11
 
11
12
  /**
@@ -16,7 +17,7 @@ export function generateBriefTemplate(
16
17
  description: string,
17
18
  forbiddenCommands?: string[],
18
19
  ): string {
19
- const today = new Date().toISOString().split("T")[0];
20
+ const today = localCalendarDay();
20
21
  const displayName = roleName.charAt(0).toUpperCase() + roleName.slice(1);
21
22
 
22
23
  return `---