rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The containment reading: are there harness-pattern files left in the
3
+ * locations this harness was moved OUT of (#921).
4
+ *
5
+ * ## Why this is a module and not three lines in a test
6
+ *
7
+ * `test/structure.test.ts` ST-2b used to compose the old harness root from
8
+ * `process.env.HOME` and `readdirSync` it, then assert the listing was empty.
9
+ * Two separate defects, and the second is the worse one:
10
+ *
11
+ * - `if (!existsSync(dir)) return` made ABSENCE a pass. A machine with no
12
+ * old `gates/` directory ran the case to completion having measured
13
+ * nothing, which is indistinguishable from a clean directory —
14
+ * `.claude/rules/checks-must-be-able-to-fail.md`, first shape.
15
+ * - The verdict of the suite that gates THIS repository was set by whatever
16
+ * the developer happened to have installed in their home directory. Two
17
+ * unrelated scripts belonging to another running process made every full
18
+ * local suite 1-fail, while CI — where the home directory is empty — was
19
+ * green on the same commit. **The CI green was the vacuous case and the
20
+ * local red was the only real measurement**, which is the exact shape that
21
+ * gets read as flake and suppressed.
22
+ *
23
+ * Containment is still a property worth watching: harness code moved out of
24
+ * the old locations, and a copy left behind is a second source of truth. What
25
+ * is wrong is reading it off a directory this repository does not own, inside
26
+ * the suite that gates this repository's changes.
27
+ *
28
+ * So the reading is separated from where it is pointed. The suite points it
29
+ * at fixture trees it builds itself and asserts the three states it can
30
+ * return. `scripts/check-containment.ts` points it at the real old root for
31
+ * whoever can actually act on a stray — and that script's exit code, not the
32
+ * repo suite's verdict, is where a machine-local stray shows up.
33
+ *
34
+ * ## Three states, not two
35
+ *
36
+ * `0 strays`, `directory absent` and `could not read the directory` are three
37
+ * different facts and only the first is a pass. Same vocabulary as
38
+ * `scripts/check-unit-suite.sh` (exit 2 = nothing was measured) and the secret
39
+ * scan in `gates.yml` (capture first, so a git failure fails closed).
40
+ */
41
+
42
+ import { existsSync, readdirSync, statSync } from "fs";
43
+ import { join } from "path";
44
+
45
+ import { remedyMessage } from "./check-remedy";
46
+
47
+ /** What a reading of one watched location can say. */
48
+ export type ContainmentState = "CLEAN" | "STRAY" | "UNMEASURED";
49
+
50
+ /**
51
+ * What a location that could not be looked at reports.
52
+ *
53
+ * One declaration, so there is exactly one site to flip in a mutation
54
+ * battery and no second decider can hold a case up while this one is dead.
55
+ * Flipping it to `"CLEAN"` is the pre-#921 behaviour — `if (!existsSync(dir))
56
+ * return` — and is the mutation `test/containment-home-independence.test.ts`
57
+ * applies.
58
+ */
59
+ export const ABSENT_STATE: ContainmentState = "UNMEASURED";
60
+
61
+ /** A directory that must hold no file with the given extension. */
62
+ export interface WatchedDir {
63
+ /** Relative to the old harness root. */
64
+ dir: string;
65
+ /** The extension that makes a file there a harness-pattern file. */
66
+ ext: string;
67
+ }
68
+
69
+ /**
70
+ * The directories the harness was moved out of, and the extension that marks
71
+ * a harness file in each.
72
+ *
73
+ * Spelled here rather than derived from `reference/migration-manifest.json`,
74
+ * and the reason is a correctness one rather than convenience: the manifest
75
+ * also lists `skills/`, `PAI/` and `scripts/*.sh` sources, which were NOT
76
+ * migrated away from the old root and still legitimately live there. A watch
77
+ * list derived from every manifest source would report that legitimate tree
78
+ * as strays, and a report that is wrong by construction gets ignored, which
79
+ * costs more than the hand-maintained list of three.
80
+ */
81
+ export const WATCHED_DIRS: readonly WatchedDir[] = [
82
+ { dir: "workflows", ext: ".js" },
83
+ { dir: "gates", ext: ".ts" },
84
+ { dir: "lib", ext: ".ts" },
85
+ ];
86
+
87
+ /**
88
+ * Individual files whose old directory still holds unrelated files, so the
89
+ * whole directory cannot be scanned by extension.
90
+ *
91
+ * `scripts/` in the old root is shared with scripts that never moved, so only
92
+ * the named two are strays there. This is a narrowing of what counts as a
93
+ * stray in a shared directory, not an exemption for a stray that was found.
94
+ */
95
+ export const WATCHED_FILES: readonly string[] = [
96
+ "scripts/sync-spec-tests.ts",
97
+ "scripts/scaffold-rungate-config.ts",
98
+ ];
99
+
100
+ /** What one watched location says, and why. */
101
+ export interface ContainmentReading {
102
+ /** Human-readable subject, e.g. `workflows/*.js`. */
103
+ subject: string;
104
+ /** The absolute path that was examined. */
105
+ path: string;
106
+ state: ContainmentState;
107
+ /** Absolute paths of the harness-pattern files found. Empty unless STRAY. */
108
+ strays: string[];
109
+ /** Why the state is what it is — the sentence a reader needs. */
110
+ note: string;
111
+ }
112
+
113
+ function dirReading(oldRoot: string, { dir, ext }: WatchedDir): ContainmentReading {
114
+ const path = join(oldRoot, dir);
115
+ const subject = `${dir}/*${ext}`;
116
+ if (!existsSync(path)) {
117
+ return {
118
+ subject,
119
+ path,
120
+ state: ABSENT_STATE,
121
+ strays: [],
122
+ note: `${path} does not exist, so nothing was looked at. Absent is not clean.`,
123
+ };
124
+ }
125
+ let entries: string[];
126
+ try {
127
+ entries = readdirSync(path).map(String);
128
+ } catch (err) {
129
+ // Fails CLOSED. A catch that returned an empty listing here would turn
130
+ // an unreadable directory into a pass, which is the fail-open shape this
131
+ // whole module exists to refuse.
132
+ return {
133
+ subject,
134
+ path,
135
+ state: ABSENT_STATE,
136
+ strays: [],
137
+ note: `${path} could not be read (${(err as Error).message}), so nothing was looked at.`,
138
+ };
139
+ }
140
+ const strays = entries.filter(f => f.endsWith(ext)).map(f => join(path, f));
141
+ return {
142
+ subject,
143
+ path,
144
+ state: strays.length > 0 ? "STRAY" : "CLEAN",
145
+ strays,
146
+ note:
147
+ strays.length > 0
148
+ ? `${strays.length} harness-pattern file(s) in ${path}`
149
+ : `${entries.length} entr(ies) read in ${path}, none ending ${ext}`,
150
+ };
151
+ }
152
+
153
+ function fileReading(oldRoot: string, rel: string): ContainmentReading {
154
+ const path = join(oldRoot, rel);
155
+ const parent = join(oldRoot, rel.split("/").slice(0, -1).join("/"));
156
+ if (!existsSync(parent)) {
157
+ return {
158
+ subject: rel,
159
+ path,
160
+ state: ABSENT_STATE,
161
+ strays: [],
162
+ note: `${parent} does not exist, so ${rel} was never looked for. Absent is not clean.`,
163
+ };
164
+ }
165
+ let present = false;
166
+ try {
167
+ present = statSync(path).isFile();
168
+ } catch {
169
+ present = false;
170
+ }
171
+ return {
172
+ subject: rel,
173
+ path,
174
+ state: present ? "STRAY" : "CLEAN",
175
+ strays: present ? [path] : [],
176
+ note: present ? `${path} is still in the old location` : `${path} is not present`,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Read every watched location under `oldRoot`.
182
+ *
183
+ * `oldRoot` is a parameter and has no default on purpose: a default would put
184
+ * the home directory back inside every caller that forgot to think about it,
185
+ * and the whole point of #921 is that the repo suite must name a root it owns.
186
+ */
187
+ export function readContainment(oldRoot: string): ContainmentReading[] {
188
+ return [
189
+ ...WATCHED_DIRS.map(w => dirReading(oldRoot, w)),
190
+ ...WATCHED_FILES.map(f => fileReading(oldRoot, f)),
191
+ ];
192
+ }
193
+
194
+ /**
195
+ * The verdict over a set of readings.
196
+ *
197
+ * STRAY outranks UNMEASURED because a found file is actionable now; both are
198
+ * non-zero, so neither can be mistaken for clean. A reading set that is empty
199
+ * is UNMEASURED — zero locations examined is not zero strays found.
200
+ */
201
+ export function containmentVerdict(readings: ContainmentReading[]): ContainmentState {
202
+ if (readings.length === 0) return "UNMEASURED";
203
+ if (readings.some(r => r.state === "STRAY")) return "STRAY";
204
+ if (readings.some(r => r.state === "UNMEASURED")) return "UNMEASURED";
205
+ return "CLEAN";
206
+ }
207
+
208
+ /** 0 clean, 1 a stray was found, 2 nothing was measured. */
209
+ export function containmentExitCode(state: ContainmentState): 0 | 1 | 2 {
210
+ if (state === "CLEAN") return 0;
211
+ return state === "STRAY" ? 1 : 2;
212
+ }
213
+
214
+ /**
215
+ * The message a refusal carries: every file, the directory it is in, and the
216
+ * action — routed through `remedyMessage` so it also names the family of
217
+ * repository-level checks when the project carries that document.
218
+ */
219
+ export function containmentRemedy(root: string, readings: ContainmentReading[]): string {
220
+ const strays = readings.filter(r => r.state === "STRAY").flatMap(r => r.strays);
221
+ const unmeasured = readings.filter(r => r.state === "UNMEASURED");
222
+ const unmeasuredNote = unmeasured.length
223
+ ? ` ${unmeasured.length} location(s) reported UNMEASURED and are NOT clean: ` +
224
+ `${unmeasured.map(r => r.note).join("; ")}.`
225
+ : "";
226
+ return remedyMessage({
227
+ root,
228
+ check: "ST-2b containment",
229
+ violations: strays,
230
+ fix:
231
+ `each file above is a second copy of the harness in a directory it was moved out of. ` +
232
+ `Read it, find who owns it, and move or delete it there — do NOT delete a file you ` +
233
+ `did not put there, and do NOT add its name to a list of accepted ones, which only ` +
234
+ `dates the problem. The repo suite asserts this reading against a fixture tree it ` +
235
+ `owns and never a home directory; \`bun scripts/check-containment.ts\` is what takes ` +
236
+ `it against the real old root.${unmeasuredNote}`,
237
+ });
238
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The content hash a constraint candidate is identified by — ONE binding.
3
+ *
4
+ * A LEAF module, moved here from `scripts/extract-constraints.ts` and
5
+ * re-exported from it under the name every existing caller knows. That is the
6
+ * arrangement `lib/git-dates.ts` has with `lib/conformity.ts` (#508) and
7
+ * `lib/harness-identity.ts` has with `isHarnessItself` (#380): one binding,
8
+ * two names.
9
+ *
10
+ * It moved for a reason worth stating rather than for tidiness. The permanent
11
+ * veto in `reference/rejected-constraints.md` (SC-137) is a table of these
12
+ * hashes, and `loadRejectedHashes` matches a candidate against it by string
13
+ * equality. A second implementation of "the hash of a candidate" — even a
14
+ * correct one — would make the veto silently stop applying to whichever
15
+ * producer used the other copy, and no behavioural test could tell the two
16
+ * apart while they agreed. `lib/failure-intake.ts` is that second producer,
17
+ * so this is the collapse done before the pair exists rather than after
18
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
19
+ */
20
+ import { createHash } from "crypto";
21
+
22
+ export function contentHash(text: string): string {
23
+ return createHash("sha256").update(text.trim().toLowerCase()).digest("hex").slice(0, 12);
24
+ }
@@ -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 `---