rungate 0.4.0 → 0.5.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 (65) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/ac-quality.ts +119 -0
  11. package/lib/cli-commands.ts +7 -1
  12. package/lib/config-loader.ts +129 -5
  13. package/lib/conformity.ts +1122 -31
  14. package/lib/context-docs.ts +182 -0
  15. package/lib/create-brief.ts +22 -17
  16. package/lib/create-sc.ts +35 -8
  17. package/lib/doc-scan-targets.ts +435 -0
  18. package/lib/gate-check-audit.ts +9 -9
  19. package/lib/github.ts +195 -0
  20. package/lib/js-top-level-code.ts +27 -2
  21. package/lib/organize.ts +129 -40
  22. package/lib/package-closure.ts +387 -0
  23. package/lib/project-aliases.ts +100 -0
  24. package/lib/release-preflight.ts +352 -48
  25. package/lib/rungate-schema.ts +23 -1
  26. package/lib/sc-cover.ts +92 -1
  27. package/lib/sc-ids.ts +151 -0
  28. package/lib/scaffold/defaults.ts +40 -0
  29. package/lib/scaffold/managed-workflow.ts +125 -27
  30. package/lib/scaffold/owned-files.ts +6 -0
  31. package/lib/scaffold/profiles.ts +94 -0
  32. package/lib/scaffold/rehearsal.ts +355 -0
  33. package/lib/scaffold/steps.ts +787 -105
  34. package/lib/scaffold/write-steps.ts +208 -0
  35. package/lib/scratch-cleanup.ts +198 -0
  36. package/lib/scratch-roots.ts +94 -0
  37. package/lib/source-anchor.ts +144 -0
  38. package/lib/success-doc.ts +779 -0
  39. package/lib/suite-run-reading.ts +194 -0
  40. package/lib/test-census.ts +199 -0
  41. package/lib/trajectory.ts +377 -0
  42. package/lib/validators/spec-validators.ts +52 -35
  43. package/lib/workflow-security.ts +152 -7
  44. package/lib/workflow-test-harness.ts +349 -0
  45. package/lib/worktree-cleanup.ts +123 -7
  46. package/lib/worktree-repo.ts +165 -0
  47. package/package.json +10 -1
  48. package/scripts/audit-specs.ts +134 -37
  49. package/scripts/audit-transcript.ts +259 -0
  50. package/scripts/create-sc.ts +15 -1
  51. package/scripts/create-success.ts +162 -0
  52. package/scripts/detect-sc-drift.ts +200 -0
  53. package/scripts/extract-constraints.ts +16 -36
  54. package/scripts/scaffold-project.ts +51 -137
  55. package/scripts/split-spec.ts +315 -0
  56. package/scripts/sync-sc-status.ts +751 -0
  57. package/specs/SPEC-TEMPLATE.md +200 -0
  58. package/templates/SUCCESS-TEMPLATE.md +72 -0
  59. package/templates/agent-briefs/_shared.md +9 -0
  60. package/templates/agent-briefs/aditi.md +46 -0
  61. package/templates/agent-briefs/discovery.md +37 -0
  62. package/templates/agent-briefs/marcus.md +39 -0
  63. package/templates/agent-briefs/quinn.md +67 -0
  64. package/templates/agent-briefs/rook.md +40 -0
  65. package/templates/agent-briefs/serena.md +39 -0
@@ -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
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { readFileSync, writeFileSync, existsSync } from "fs";
8
+ import { writeRoleConfig } from "./config-loader";
8
9
  import type { AgentMeta } from "./generators/types";
9
10
 
10
11
  /**
@@ -83,22 +84,9 @@ export function writeBriefTemplate(templatesDir: string, roleName: string, descr
83
84
  return filePath;
84
85
  }
85
86
 
86
- /**
87
- * Add a new role to the project's rungate.json config.
88
- * Adds brief path, isolation: worktree, and a standardTask.
89
- */
90
- export function addRoleToConfig(configPath: string, roleName: string, description: string): void {
91
- if (!existsSync(configPath)) {
92
- throw new Error(`Config file not found: ${configPath}`);
93
- }
94
- const config = JSON.parse(readFileSync(configPath, "utf-8"));
95
- if (!config.roles) {
96
- config.roles = {};
97
- }
98
- if (config.roles[roleName]) {
99
- throw new Error(`Role '${roleName}' already exists in ${configPath}`);
100
- }
101
- config.roles[roleName] = {
87
+ /** The entry a newly created role gets: brief path, isolation, standardTask. */
88
+ export function buildRoleEntry(roleName: string, description: string) {
89
+ return {
102
90
  brief: `.claude/agents/${roleName}.md`,
103
91
  isolation: "worktree",
104
92
  standardTask: `Perform ${description.toLowerCase()} tasks as assigned`,
@@ -106,7 +94,24 @@ export function addRoleToConfig(configPath: string, roleName: string, descriptio
106
94
  tools: "[Bash, Read]",
107
95
  model: "sonnet",
108
96
  };
109
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
97
+ }
98
+
99
+ /**
100
+ * Register a new role in the project's config, whichever layout it is on.
101
+ *
102
+ * This file decides what a role ENTRY looks like; `writeRoleConfig` decides
103
+ * which file it belongs in. Keeping the second half in the loader is #415:
104
+ * the predecessor took a `configPath` from its caller, and every caller built
105
+ * `.claude/rungate.json` by hand.
106
+ *
107
+ * Returns the file the role was written to.
108
+ */
109
+ export function registerRole(
110
+ projectRoot: string,
111
+ roleName: string,
112
+ description: string,
113
+ ): string {
114
+ return writeRoleConfig(projectRoot, roleName, buildRoleEntry(roleName, description));
110
115
  }
111
116
 
112
117
  export const DEFAULT_AGENT_META: Record<string, AgentMeta> = {
package/lib/create-sc.ts CHANGED
@@ -9,6 +9,7 @@ import { join, dirname } from "path";
9
9
  import { fileURLToPath } from "url";
10
10
 
11
11
  import type { ScRegistry } from "./sc-ids";
12
+ import { isFixtureScId } from "./sc-ids";
12
13
  import { tryLoadRungateConfig } from "./config-loader";
13
14
 
14
15
  // ── Types ─────────────────────────────────────────────────────
@@ -243,18 +244,44 @@ export function listPatterns(): string {
243
244
  * that has no registry to hand; silently changing that would be a different
244
245
  * bug. It is the wrong answer in a shared namespace, which is why
245
246
  * `scripts/create-sc.ts` passes one.
247
+ *
248
+ * ## The namespace has a second half, and #392 only fixed the first
249
+ *
250
+ * Consulting the registry stopped two specs minting the same number. It did
251
+ * nothing about test fixtures, which spell SC ids inside the SAME namespace
252
+ * and appear in no registry: `test/sync-sc-status.test.ts:61` is literally
253
+ * `- [ ] SC-9441: AGENTS.md exists`, a checkbox declaration in a string
254
+ * literal. Allocating 900 would mint a criterion out of a scratch number and
255
+ * hand a live claim to a fixture — the shape #392 closed, arriving from the
256
+ * side nothing looks at.
257
+ *
258
+ * So `spelledInSource` is the other half — and only there is the reserved
259
+ * range ignored. The 9000s exist to be safe for fixtures, so counting a
260
+ * FIXTURE at 9450 as taken would push every future criterion past 9000 and
261
+ * destroy the reservation it was built on. That is the one case where a
262
+ * higher number is the wrong answer.
263
+ *
264
+ * A SPEC declaration is authoritative at any number, reserved or not. If a
265
+ * spec has already claimed 9150 then 9150 is claimed, whatever the
266
+ * convention says it should have been, and allocating it again is the
267
+ * collision this function exists to prevent. The reservation is enforced
268
+ * against specs by SC-1524, not by making the allocator pretend.
246
269
  */
247
- export function nextSCNumber(specContent: string, reg?: ScRegistry): number {
270
+ export function nextSCNumber(
271
+ specContent: string,
272
+ reg?: ScRegistry,
273
+ spelledInSource?: Iterable<string>,
274
+ ): number {
248
275
  const ids: number[] = [];
276
+ const take = (raw: string): void => {
277
+ const n = Number(raw.replace(/^SC-[A-Z]?/, ""));
278
+ if (Number.isFinite(n)) ids.push(n);
279
+ };
249
280
  const pattern = /SC-(\d+)/g;
250
281
  let match;
251
- while ((match = pattern.exec(specContent)) !== null) {
252
- ids.push(parseInt(match[1]));
253
- }
254
- for (const id of reg?.declaredById.keys() ?? []) {
255
- const n = Number(id.replace(/^SC-[A-Z]?/, ""));
256
- if (Number.isFinite(n)) ids.push(n);
257
- }
282
+ while ((match = pattern.exec(specContent)) !== null) take(match[0]);
283
+ for (const id of reg?.declaredById.keys() ?? []) take(id);
284
+ for (const id of spelledInSource ?? []) if (!isFixtureScId(id)) take(id);
258
285
  if (ids.length === 0) return 1;
259
286
  return Math.max(...ids) + 1;
260
287
  }