rungate 0.4.0 → 0.4.1

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.
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The two AC-quality readings `gates/workflow.test.ts` used to compute inline
3
+ * and then `console.warn` about (#423).
4
+ *
5
+ * #183 audited the ported check list and found four checks that warn without
6
+ * asserting. Two were documented decisions. These two were not: they were
7
+ * `tsc-pass`'s shape — a name promising a verdict over a body that cannot
8
+ * produce one — and they sat in `WARN_TIER_CHECKS` with a reason reading
9
+ * "reported, not fixed".
10
+ *
11
+ * #423 settles them in opposite directions, and the reason they go different
12
+ * ways is the whole point of separating the READING from the VERDICT:
13
+ *
14
+ * - `outcomeEvidenceViolations` now **refuses**. An OUTCOME AC records that a
15
+ * user-visible outcome was observed; a bare number cannot establish one, and
16
+ * `0`, `{}`, `null` and `SKIP` being indistinguishable from success is the
17
+ * *Silent Default Substitution* anti-pattern this repo already names in
18
+ * `.claude/rules/config-access.md`. Its sibling two tests above it,
19
+ * `outcome-acs-no-skip`, has always asserted.
20
+ *
21
+ * - `goalKeywordCoverage` stays a **warning**, and that is now a measured
22
+ * decision rather than a deferral. Measured over the 153 `workflow-state.json`
23
+ * files under `~/.rungate` carrying a goal: **71% of real runs** fall under
24
+ * the 50% threshold, median coverage 38%. Restricting to states whose ACs
25
+ * carry real statements (>80 chars) gives 66% of 131, median 41%; >300 chars
26
+ * gives 73% of 101. The number does not move. A check that would refuse two
27
+ * runs in three is not a gate, it is an outage, and a stopword-filtered
28
+ * substring match over prose is the same basis #409 Decision #9 already
29
+ * rejected for `spec-decision-compliance`.
30
+ *
31
+ * Both are here rather than inline in the gate suite for the reason
32
+ * `.claude/rules/checks-must-be-able-to-fail.md` gives: one exported binding
33
+ * per reading, so there is exactly one thing to mutate and the test can drive
34
+ * both sides of it without a workflow run.
35
+ */
36
+
37
+ /** An AC as the gate suite sees it — untyped on the wire, so read defensively. */
38
+ interface LooseAc {
39
+ id?: unknown;
40
+ type?: unknown;
41
+ verdict?: unknown;
42
+ statement?: unknown;
43
+ evidence?: { content?: unknown } | null;
44
+ }
45
+
46
+ function asAcs(acs: unknown): LooseAc[] {
47
+ return Array.isArray(acs) ? (acs as LooseAc[]) : [];
48
+ }
49
+
50
+ /**
51
+ * Evidence that is a bare measurement — a number and nothing a reader could
52
+ * check.
53
+ *
54
+ * Deliberately wider than the `/^\d+$/` the inline body used. That form read
55
+ * `3` as numeric-only and `3/3`, `12%`, `0.0` and `-1` as behavioural, which
56
+ * is the second shape in `.claude/rules/checks-must-be-able-to-fail.md`: a
57
+ * detector narrower than what it detects, where a reformat of the same
58
+ * non-answer walks straight through. The question is whether the evidence
59
+ * contains a WORD, so that is what is asked.
60
+ */
61
+ export function isBareMeasurement(content: unknown): boolean {
62
+ if (typeof content !== "string") return false;
63
+ const trimmed = content.trim();
64
+ if (trimmed === "") return false; // absence is a different check's question
65
+ return !/[a-z]/i.test(trimmed);
66
+ }
67
+
68
+ /**
69
+ * OUTCOME ACs marked PASS whose evidence is a bare measurement.
70
+ *
71
+ * **Absent evidence is deliberately out of scope.** `all-acs-have-evidence`
72
+ * exempts OUTCOME ACs from mechanical evidence at ship time by design — they
73
+ * are verified live at prove — so reporting absence here would duplicate a
74
+ * decision another check already owns, and two deciders answering one question
75
+ * are behaviourally one (the fourth shape, #420). This one answers: when there
76
+ * IS evidence, does it say anything.
77
+ */
78
+ export function outcomeEvidenceViolations(acs: unknown): string[] {
79
+ return asAcs(acs)
80
+ .filter(ac => ac.type === "OUTCOME" && ac.verdict === "PASS")
81
+ .filter(ac => isBareMeasurement(ac.evidence?.content))
82
+ .map(ac => `${String(ac.id ?? "?")}: evidence is ${JSON.stringify(String(ac.evidence?.content ?? "")).slice(0, 40)}`);
83
+ }
84
+
85
+ /** The words in a goal worth asking about: long enough to mean something. */
86
+ const STOPWORDS = new Set([
87
+ "the", "and", "for", "that", "this", "with", "from", "have", "been",
88
+ "will", "must", "when", "into", "also", "each", "than",
89
+ ]);
90
+
91
+ /** ADR-009 C4's threshold, warned under — never refused. See the file docblock. */
92
+ export const GOAL_COVERAGE_WARN_BELOW = 0.5;
93
+
94
+ export interface GoalCoverage {
95
+ keywords: string[];
96
+ covered: string[];
97
+ coverage: number;
98
+ }
99
+
100
+ /**
101
+ * How much of the issue goal's vocabulary the ACs repeat (ADR-009 C4).
102
+ *
103
+ * `null` when there is nothing to ask — no goal, or a goal of nothing but
104
+ * short words. A caller must not read that as full coverage; it is the
105
+ * difference between measuring zero and not measuring, which is the
106
+ * distinction `.claude/rules/config-access.md` calls out by name.
107
+ */
108
+ export function goalKeywordCoverage(goal: unknown, acs: unknown): GoalCoverage | null {
109
+ if (typeof goal !== "string" || goal.trim() === "") return null;
110
+ const keywords = goal
111
+ .toLowerCase()
112
+ .replace(/[^a-z0-9\s]/g, " ")
113
+ .split(/\s+/)
114
+ .filter(w => w.length > 4 && !STOPWORDS.has(w));
115
+ if (keywords.length === 0) return null;
116
+ const acText = asAcs(acs).map(ac => String(ac.statement ?? "").toLowerCase()).join(" ");
117
+ const covered = keywords.filter(kw => acText.includes(kw));
118
+ return { keywords, covered, coverage: covered.length / keywords.length };
119
+ }
@@ -1,11 +1,20 @@
1
1
  /**
2
- * config-loader.ts — Central config loader for rungate
2
+ * config-loader.ts — the one module that knows where rungate config LIVES
3
3
  *
4
4
  * Reads config from .claude/rungate/ directory (preferred) or
5
5
  * .claude/rungate.json (fallback). Merges directory files into
6
6
  * the same shape as the monolith for backward compatibility.
7
+ *
8
+ * It owns the WRITE side too (#415). ADR-002 D1 is usually quoted as "only
9
+ * this module may read the config", but the thing being centralised is the
10
+ * knowledge of which file a project's config is in, and a writer that answers
11
+ * that question for itself is a second answer to drift from. `create-brief`
12
+ * was the live instance: it built `.claude/rungate.json`, handed it to a
13
+ * writer, and on a project that had followed the documented migration printed
14
+ * "not found — role not registered", naming a file the project is documented
15
+ * not to have. The brief was written and the role was registered nowhere.
7
16
  */
8
- import { existsSync, readFileSync } from "fs";
17
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
9
18
  import { join } from "path";
10
19
  import { z } from "zod";
11
20
  import {
@@ -39,6 +48,14 @@ export interface ComplianceConfig {
39
48
  fileTypes: string[];
40
49
  artifactClassification: Record<string, string>;
41
50
  externalSources: OrganizeExternalSource[];
51
+ /**
52
+ * Names a cross-project document may call this project by (#442).
53
+ *
54
+ * Optional: the directory name and the GitHub slug are derived from the
55
+ * tree, so this is only for what a human knows — the abbreviation, the
56
+ * product name, the thing the team says out loud.
57
+ */
58
+ aliases?: string[];
42
59
  };
43
60
  }
44
61
 
@@ -98,7 +115,13 @@ export const DEFAULT_TEST_TIMEOUT = 120000;
98
115
  * Malformed JSON and orphaned fragments THROW, per ADR-001 D2. Unchanged.
99
116
  */
100
117
  export type ConfigResolution =
101
- | { status: "resolved"; config: ResolvedConfig; source: "directory" | "monolith" }
118
+ | {
119
+ status: "resolved";
120
+ config: ResolvedConfig;
121
+ source: "directory" | "monolith";
122
+ /** The directory or file the config was read from (#415). */
123
+ path: string;
124
+ }
102
125
  | { status: "absent" };
103
126
 
104
127
  const DIRECTORY_CONFIG_FILES = ["config.json", "roles.json", "hooks.json", "compliance.json"];
@@ -143,11 +166,21 @@ export function resolveConfig(projectRoot: string): ConfigResolution {
143
166
  // and silently drop issueRepo/ci/test — ADR-001 Step E keeps the monolith
144
167
  // in place during migration, so that state is on the normal upgrade path.
145
168
  if (existsSync(join(dirPath, "config.json"))) {
146
- return { status: "resolved", config: loadFromDirectory(dirPath), source: "directory" };
169
+ return {
170
+ status: "resolved",
171
+ config: loadFromDirectory(dirPath),
172
+ source: "directory",
173
+ path: dirPath,
174
+ };
147
175
  }
148
176
 
149
177
  if (existsSync(monolithPath)) {
150
- return { status: "resolved", config: loadFromMonolith(monolithPath), source: "monolith" };
178
+ return {
179
+ status: "resolved",
180
+ config: loadFromMonolith(monolithPath),
181
+ source: "monolith",
182
+ path: monolithPath,
183
+ };
151
184
  }
152
185
 
153
186
  // Fragments with no config.json and no monolith is a broken directory
@@ -209,6 +242,97 @@ function readJson(path: string): any {
209
242
  return JSON.parse(readFileSync(path, "utf-8"));
210
243
  }
211
244
 
245
+ /**
246
+ * Register a role in whichever layout the project is actually on (#415).
247
+ *
248
+ * The counterpart to `loadRoleConfig`, and deliberately in the same module:
249
+ * the writer has to make the same choice between the two layouts that the
250
+ * reader makes, and a second place making it is how `create-brief` came to
251
+ * write a monolith a migrated consumer does not have.
252
+ *
253
+ * Throws on an unscaffolded project. There is no third branch that invents a
254
+ * layout — a tool that creates `.claude/rungate.json` beside an existing
255
+ * `.claude/rungate/` gives the project two role sets and lets whichever the
256
+ * reader prefers decide what the project is, which is #70 one layer up.
257
+ *
258
+ * Returns the file written, so a caller can say where the role went rather
259
+ * than naming a path it guessed.
260
+ */
261
+ export function writeRoleConfig(
262
+ projectRoot: string,
263
+ roleName: string,
264
+ role: unknown,
265
+ ): string {
266
+ const resolution = resolveConfig(projectRoot);
267
+ if (resolution.status === "absent") {
268
+ throw new Error(
269
+ `No rungate config found under ${join(projectRoot, ".claude")} — ` +
270
+ `scaffold the project before registering a role`,
271
+ );
272
+ }
273
+
274
+ const target =
275
+ resolution.source === "directory"
276
+ ? join(resolution.path, "roles.json")
277
+ : resolution.path;
278
+
279
+ const existing = existsSync(target) ? readJson(target) : {};
280
+ const roles = resolution.source === "directory" ? existing : (existing.roles ??= {});
281
+
282
+ if (roles[roleName]) {
283
+ throw new Error(`Role '${roleName}' already exists in ${target}`);
284
+ }
285
+ roles[roleName] = role;
286
+
287
+ writeFileSync(target, JSON.stringify(existing, null, 2) + "\n");
288
+ return target;
289
+ }
290
+
291
+ /** Whether a scaffold wrote, or stepped aside because something was there. */
292
+ export type ScaffoldWriteResult =
293
+ | { status: "created"; path: string }
294
+ | { status: "exists"; path: string };
295
+
296
+ /**
297
+ * Create a project's config in the DIRECTORY layout (#415).
298
+ *
299
+ * `scripts/scaffold-rungate-config.ts` built these four paths itself, which
300
+ * put two modules in the business of knowing the layout — and left the
301
+ * scaffolder banked in the config-access ratchet at a number no migration
302
+ * could ever lower, because there was no read to migrate.
303
+ *
304
+ * **The "already there" decision lives here and only here.** The script used
305
+ * to make it as well, which made this one unreachable: a mutation that
306
+ * deleted it left the caller's copy still refusing, so the guard measured as
307
+ * load-bearing while nothing depended on it. Two deciders that agree are
308
+ * behaviourally one.
309
+ *
310
+ * Returns rather than throwing, so the caller reports the outcome without
311
+ * having to sniff an exception message for a prefix.
312
+ */
313
+ export function writeScaffoldedConfig(
314
+ projectRoot: string,
315
+ parts: { config: unknown; roles: unknown; hooks: unknown; compliance: unknown },
316
+ ): ScaffoldWriteResult {
317
+ const resolution = resolveConfig(projectRoot);
318
+ if (resolution.status === "resolved") {
319
+ return { status: "exists", path: resolution.path };
320
+ }
321
+
322
+ const dirPath = join(projectRoot, ".claude", "rungate");
323
+ mkdirSync(dirPath, { recursive: true });
324
+ const files: Array<[string, unknown]> = [
325
+ ["config.json", parts.config],
326
+ ["roles.json", parts.roles],
327
+ ["hooks.json", parts.hooks],
328
+ ["compliance.json", parts.compliance],
329
+ ];
330
+ for (const [name, body] of files) {
331
+ writeFileSync(join(dirPath, name), JSON.stringify(body, null, 2) + "\n");
332
+ }
333
+ return { status: "created", path: dirPath };
334
+ }
335
+
212
336
  export function loadComplianceConfig(projectRoot: string): ComplianceConfig | null {
213
337
  const dirPath = join(projectRoot, ".claude", "rungate", "compliance.json");
214
338
  if (existsSync(dirPath)) {
package/lib/conformity.ts CHANGED
@@ -2722,6 +2722,153 @@ function configAccessPattern(): RegExp {
2722
2722
  );
2723
2723
  }
2724
2724
 
2725
+ /**
2726
+ * Calls whose arguments are FILESYSTEM PATHS (#415).
2727
+ *
2728
+ * The positive list IS the definition, not a heuristic: a config path that
2729
+ * reaches the disk is either built by a path API or handed straight to an fs
2730
+ * one. Everything a `node:path` call touches is a path by construction.
2731
+ */
2732
+ const FS_PATH_CALLS = new Set([
2733
+ "existsSync", "readFileSync", "writeFileSync", "appendFileSync", "readdirSync",
2734
+ "mkdirSync", "rmSync", "rmdirSync", "unlinkSync", "statSync", "lstatSync",
2735
+ "copyFileSync", "cpSync", "renameSync", "realpathSync", "readlinkSync", "openSync",
2736
+ ]);
2737
+
2738
+ /**
2739
+ * `node:path` builders. Receiver-checked, unlike the fs names above, because
2740
+ * `Array.prototype.join` shares one of them and `["a", "b"].join(", ")` is
2741
+ * text. A bare `join` is the named import this repo uses; `path.join` is the
2742
+ * namespace form.
2743
+ */
2744
+ const PATH_BUILDERS = new Set(["join", "resolve", "relative", "normalize"]);
2745
+
2746
+ /**
2747
+ * Handing a shell a command that names the config is a read, and the literal
2748
+ * carrying it has spaces in it by construction — `cat <root>/…json` would
2749
+ * otherwise read as prose and go uncounted, which is the one fail-open the
2750
+ * prose rule could have opened on its own.
2751
+ */
2752
+ const SHELL_CALLS = new Set(["execSync", "exec", "execFileSync", "spawnSync", "spawn"]);
2753
+
2754
+ function isPathCall(callee: string | null): boolean {
2755
+ if (!callee) return false;
2756
+ const bare = callee.slice(callee.lastIndexOf(".") + 1);
2757
+ if (FS_PATH_CALLS.has(bare) || SHELL_CALLS.has(bare)) return true;
2758
+ return PATH_BUILDERS.has(bare) && (callee === bare || callee === `path.${bare}`);
2759
+ }
2760
+
2761
+ /**
2762
+ * Calls that take TEXT. Both are universal JS idioms rather than names out of
2763
+ * this repo — `x.push(…)` into a list of messages, and `console.*` — and both
2764
+ * are needed because a documentation entry can carry a path-SHAPED literal:
2765
+ * `keyFiles.push({ file: "…/" })` is a row in a generated table, not a read.
2766
+ */
2767
+ function isTextCall(callee: string | null): boolean {
2768
+ if (!callee) return false;
2769
+ return callee.endsWith(".push") || callee.startsWith("console.");
2770
+ }
2771
+
2772
+ /** The dotted name immediately left of an open paren, or `""` for a group. */
2773
+ function calleeBefore(text: string, parenIndex: number): string {
2774
+ let j = parenIndex - 1;
2775
+ while (j >= 0 && /\s/.test(text[j]!)) j--;
2776
+ const end = j + 1;
2777
+ while (j >= 0 && /[A-Za-z0-9_$.]/.test(text[j]!)) j--;
2778
+ return text.slice(j + 1, end);
2779
+ }
2780
+
2781
+ /** What a config-path match turned out to be. */
2782
+ export type ConfigSiteKind = "use" | "mention";
2783
+
2784
+ export interface ConfigSite {
2785
+ /** Offset in the comment-stripped source. */
2786
+ index: number;
2787
+ kind: ConfigSiteKind;
2788
+ /** Innermost enclosing call, or null at statement level. */
2789
+ callee: string | null;
2790
+ /** The literal run the match sits in, or null if it is not in one. */
2791
+ literal: string | null;
2792
+ }
2793
+
2794
+ /**
2795
+ * Is this path being BUILT, or merely NAMED? (#415)
2796
+ *
2797
+ * The one place that decides, so the mutation harness has one site to
2798
+ * collapse (`.claude/rules/checks-must-be-able-to-fail.md`). Collapsing it
2799
+ * either way moves a banked number and the both-ways ratchet refuses, which
2800
+ * is the property `test/config-access-mentions.test.ts` SC-1553 pins down.
2801
+ *
2802
+ * ## How the two views are read
2803
+ *
2804
+ * There is NO second lexer here. `stripJsComments` already scans code,
2805
+ * strings, templates (with `${}` to any depth) and regex literals, offset
2806
+ * preserving, and `blankLiterals` gives a view in which every literal's
2807
+ * CONTENTS are spaces and its delimiters are not. Over that view a naive
2808
+ * paren counter is exact — no quote, paren or brace inside a string or a
2809
+ * regex can reach it — and the literal a match sits in is simply the maximal
2810
+ * run of blanked offsets around it. A second scanner answering the same
2811
+ * question is a second scanner to drift.
2812
+ *
2813
+ * ## The decision, and which way each branch is allowed to be wrong
2814
+ *
2815
+ * 1. an fs, shell or `node:path` call
2816
+ * around it → USE, whatever the text says
2817
+ * 2. otherwise, prose around the path → MENTION
2818
+ * 3. otherwise, a path-shaped literal into a
2819
+ * message list or the console → MENTION
2820
+ * 4. otherwise → USE
2821
+ *
2822
+ * Rule 4 is the fail-closed default and it is the reason an unrecognised
2823
+ * helper, a bare `const p = "…"` or a path built by concatenation still
2824
+ * counts: a path-shaped literal is a path until something shows otherwise.
2825
+ *
2826
+ * STATED LIMIT, in the tradition of ADR-001's: a literal containing
2827
+ * whitespace, passed to a call this cannot recognise, reads as prose. Both
2828
+ * halves have to be true at once, which is why the remaining blind spot is a
2829
+ * sentence that is also a path.
2830
+ */
2831
+ export function classifyConfigSites(source: string): ConfigSite[] {
2832
+ const code = stripJsComments(source);
2833
+ const bare = stripJsComments(source, { blankLiterals: true });
2834
+
2835
+ const sites: ConfigSite[] = [];
2836
+ const pattern = configAccessPattern();
2837
+ let match: RegExpExecArray | null;
2838
+ while ((match = pattern.exec(code)) !== null) {
2839
+ const at = match.index;
2840
+
2841
+ let depthCallee: string | null = null;
2842
+ const stack: string[] = [];
2843
+ for (let i = 0; i < at; i++) {
2844
+ const c = bare[i];
2845
+ if (c === "(") stack.push(calleeBefore(bare, i));
2846
+ else if (c === ")") stack.pop();
2847
+ }
2848
+ depthCallee = stack.length > 0 ? stack[stack.length - 1]! : null;
2849
+
2850
+ let literal: string | null = null;
2851
+ if (bare[at] === " " && code[at] !== " ") {
2852
+ let lo = at;
2853
+ let hi = at;
2854
+ while (lo > 0 && bare[lo - 1] === " ") lo--;
2855
+ while (hi + 1 < bare.length && bare[hi + 1] === " ") hi++;
2856
+ literal = code.slice(lo, hi + 1);
2857
+ }
2858
+
2859
+ const kind: ConfigSiteKind = isPathCall(depthCallee)
2860
+ ? "use"
2861
+ : literal !== null && /\s/.test(literal)
2862
+ ? "mention"
2863
+ : isTextCall(depthCallee)
2864
+ ? "mention"
2865
+ : "use";
2866
+
2867
+ sites.push({ index: at, kind, callee: depthCallee, literal });
2868
+ }
2869
+ return sites;
2870
+ }
2871
+
2725
2872
  /** Directories CHECK-1 walks. Tests and `test/` are excluded by ADR-002 D4. */
2726
2873
  const CONFIG_SCAN_DIRS = ["lib", "gates", "scripts", "hooks", "generators"];
2727
2874
 
@@ -2774,7 +2921,7 @@ export function scanConfigAccess(root: string): ConfigAccessScan {
2774
2921
  for (const f of files) {
2775
2922
  bytesScanned += f.text.length;
2776
2923
  if (f.path === CONFIG_LOADER) continue;
2777
- const n = (stripJsComments(f.text).match(configAccessPattern()) || []).length;
2924
+ const n = classifyConfigSites(f.text).filter(site => site.kind === "use").length;
2778
2925
  if (n > 0) counts[f.path] = n;
2779
2926
  }
2780
2927
  return { counts, filesScanned: files.length, bytesScanned };
@@ -2786,6 +2933,15 @@ export function scanConfigAccess(root: string): ConfigAccessScan {
2786
2933
  * Comments are stripped and literals are NOT, which is the whole point —
2787
2934
  * `ship.js` is mostly prompt text, and the eleven sites ADR-001's check could
2788
2935
  * not see all live inside template literals handed to agents.
2936
+ *
2937
+ * **It does NOT use `classifyConfigSites`, and must not** (#415). CHECK-1's
2938
+ * subject is a path being built in code, so a sentence naming the file is
2939
+ * noise. CHECK-2's subject is the sentence: "Read ${PROJECT_ROOT}/…" IS the
2940
+ * violation, and it is prose by construction. Pointing the classifier at this
2941
+ * scan would silently empty the check — every one of its sites would reclassify
2942
+ * as a mention. `test/config-access-mentions.test.ts` SC-1552 runs one sentence
2943
+ * through both scans and asserts they disagree, so the collapse cannot be made
2944
+ * quietly in the name of consistency.
2789
2945
  */
2790
2946
  export function scanPromptConfigAccess(root: string): ConfigAccessScan {
2791
2947
  const dir = join(root, "workflows");
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `contextDocs` — the one binding that decides what a declared doc becomes (#439).
3
+ *
4
+ * Reported from a consumer project's session as "a dead config key". It is
5
+ * not dead: `gates/brief-assembler.ts` consumes it. What was wrong is worse
6
+ * than inert, because the key looked like it worked — three defects stacked in
7
+ * one twenty-line region:
8
+ *
9
+ * 1. Every entry starting with `/` or containing `..` was filtered out with
10
+ * no warning and no difference in the brief. The use case that prompted
11
+ * the report was declaring docs in another project, which is an absolute
12
+ * path. Refusing was indistinguishable from there being nothing to
13
+ * refuse — `.claude/rules/config-access.md`'s *Silent Default
14
+ * Substitution*.
15
+ * 2. The config was read straight from `.claude/rungate.json`, so a project
16
+ * on the directory layout got nothing regardless of the filter.
17
+ * 3. A `catch { return null }` turned a trailing comma into "no docs".
18
+ *
19
+ * This module owns (1) and (3)'s successor; the loader owns (2).
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.
38
+ */
39
+
40
+ import { existsSync } from "fs";
41
+ import { isAbsolute, relative, resolve } from "path";
42
+
43
+ /**
44
+ * Characters a path must not carry into a brief (BUG-439-A).
45
+ *
46
+ * A brief is an agent instruction and a path is rendered into it inline, so
47
+ * an entry containing a newline writes whatever follows as its own line, in a
48
+ * document whose whole purpose is to be obeyed. The old filter did not stop
49
+ * this: a relative path with no leading `/` and no `..` passed it and could
50
+ * still contain `\n`. This is not a control #439 removed — it is one neither
51
+ * version had, found by security review of the first push.
52
+ *
53
+ * `\u2028` and `\u2029` are in the class because they are line terminators
54
+ * that `\n`-shaped thinking misses.
55
+ */
56
+ const BRIEF_UNSAFE = /[\u0000-\u001f\u007f\u2028\u2029]/;
57
+
58
+ /**
59
+ * One predicate, two callers: `contextDocs` here and the AC `contextFiles`
60
+ * rendered by `gates/brief-assembler.ts`. `contextFiles` had no filtering of
61
+ * any kind, which is also why the old `contextDocs` filter was never a path
62
+ * control — it covered one of two doors.
63
+ */
64
+ export function hasBriefUnsafeChars(value: string): boolean {
65
+ return BRIEF_UNSAFE.test(value);
66
+ }
67
+
68
+ export type ContextDocVerdict =
69
+ | {
70
+ kind: "included";
71
+ /** Exactly as written in the config, for error messages that can be traced back. */
72
+ declared: string;
73
+ /** Absolute, after resolving against the project root. */
74
+ resolved: string;
75
+ /** Outside the project root — reported, not refused. */
76
+ external: boolean;
77
+ /** Declared but not on disk when the brief was assembled. */
78
+ missing: boolean;
79
+ }
80
+ | { kind: "rejected"; declared: string; reason: string };
81
+
82
+ /**
83
+ * Classify ONE declared entry. The single binding, so there is one thing to
84
+ * mutate and each arm is separately observable in the assembled brief.
85
+ */
86
+ export function classifyContextDoc(projectRoot: string, declared: unknown): ContextDocVerdict {
87
+ if (typeof declared !== "string") {
88
+ return { kind: "rejected", declared: JSON.stringify(declared) ?? String(declared), reason: "not a string" };
89
+ }
90
+ const trimmed = declared.trim();
91
+ if (trimmed === "") {
92
+ return { kind: "rejected", declared, reason: "empty" };
93
+ }
94
+ if (hasBriefUnsafeChars(trimmed)) {
95
+ return {
96
+ kind: "rejected",
97
+ declared: JSON.stringify(trimmed),
98
+ reason: "contains a newline or control character, which would write its own lines into the brief",
99
+ };
100
+ }
101
+
102
+ const resolved = isAbsolute(trimmed) ? resolve(trimmed) : resolve(projectRoot, trimmed);
103
+ // `relative` rather than `startsWith`: `/repo-backup` starts with `/repo`
104
+ // and is a different directory. One comparison, computed the way the
105
+ // filesystem means it.
106
+ const rel = relative(resolve(projectRoot), resolved);
107
+ const external = rel === "" || rel.startsWith("..") || isAbsolute(rel);
108
+
109
+ return { kind: "included", declared: trimmed, resolved, external, missing: !existsSync(resolved) };
110
+ }
111
+
112
+ /**
113
+ * Both authored shapes: an array of paths, or an object whose values are paths.
114
+ *
115
+ * A present-but-unusable `contextDocs` — a string, a number, `null` — is ONE
116
+ * rejection rather than silence, because a config that declares the key and
117
+ * gets nothing is exactly the case this issue is about.
118
+ */
119
+ export function classifyContextDocs(projectRoot: string, raw: unknown): ContextDocVerdict[] {
120
+ if (raw === undefined || raw === null) return [];
121
+ const entries: unknown[] = Array.isArray(raw)
122
+ ? raw
123
+ : typeof raw === "object"
124
+ ? Object.values(raw as Record<string, unknown>)
125
+ : [{ __unusable: raw }];
126
+ if (entries.length === 1 && typeof entries[0] === "object" && entries[0] !== null && "__unusable" in (entries[0] as object)) {
127
+ return [{
128
+ kind: "rejected",
129
+ declared: JSON.stringify(raw),
130
+ reason: `contextDocs must be an array or an object, got ${typeof raw}`,
131
+ }];
132
+ }
133
+ return entries.map(e => classifyContextDoc(projectRoot, e));
134
+ }
135
+
136
+ /** The numbered brief lines, one per included doc, labelled where it matters. */
137
+ export function contextDocLines(verdicts: ContextDocVerdict[], startIndex: number): string[] {
138
+ const lines: string[] = [];
139
+ let idx = startIndex;
140
+ for (const v of verdicts) {
141
+ if (v.kind !== "included") continue;
142
+ const notes = [
143
+ v.external ? "external to this project" : null,
144
+ v.missing ? "declared in contextDocs but not present at assembly time" : null,
145
+ ].filter(Boolean);
146
+ lines.push(`${idx}. ${v.resolved}${notes.length ? ` (${notes.join("; ")})` : ""}`);
147
+ idx++;
148
+ }
149
+ return lines;
150
+ }
151
+
152
+ /**
153
+ * The report. Empty when nothing was declared, which is the one case that may
154
+ * be silent — and NOT empty when entries were declared and could not be used,
155
+ * which is the case the old filter made indistinguishable from it.
156
+ */
157
+ export function contextDocNotes(verdicts: ContextDocVerdict[]): string[] {
158
+ // There is no `if (verdicts.length === 0) return []` here, and the absence
159
+ // is deliberate. It was in the first draft, and it was a second decider
160
+ // agreeing with the guard below: an empty list has no rejected, missing or
161
+ // external entries either, so both returned `[]` on exactly the same
162
+ // inputs. Mutating the guard below measured 1 of 54 against a predicted 4
163
+ // because the early return was quietly holding three of the cases up. See
164
+ // `.claude/rules/checks-must-be-able-to-fail.md`, fourth shape.
165
+ const rejected = verdicts.filter(v => v.kind === "rejected");
166
+ const included = verdicts.filter(v => v.kind === "included");
167
+ const missing = included.filter(v => v.kind === "included" && v.missing);
168
+ const external = included.filter(v => v.kind === "included" && v.external);
169
+ if (rejected.length === 0 && missing.length === 0 && external.length === 0) return [];
170
+
171
+ const notes = [`> contextDocs: ${verdicts.length} declared, ${included.length} usable.`];
172
+ for (const v of rejected) {
173
+ if (v.kind === "rejected") notes.push(`> - REJECTED ${v.declared}: ${v.reason}`);
174
+ }
175
+ for (const v of missing) {
176
+ if (v.kind === "included") notes.push(`> - MISSING ${v.declared}: nothing at ${v.resolved}`);
177
+ }
178
+ for (const v of external) {
179
+ if (v.kind === "included") notes.push(`> - EXTERNAL ${v.declared}: resolves to ${v.resolved}, outside this project`);
180
+ }
181
+ return notes;
182
+ }