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.
- package/lib/ac-quality.ts +119 -0
- package/lib/config-loader.ts +129 -5
- package/lib/conformity.ts +157 -1
- package/lib/context-docs.ts +182 -0
- package/lib/create-brief.ts +22 -17
- package/lib/create-sc.ts +35 -8
- package/lib/doc-scan-targets.ts +435 -0
- package/lib/gate-check-audit.ts +9 -9
- package/lib/organize.ts +129 -40
- package/lib/package-closure.ts +111 -0
- package/lib/project-aliases.ts +100 -0
- package/lib/release-preflight.ts +156 -48
- package/lib/rungate-schema.ts +23 -1
- package/lib/sc-cover.ts +92 -1
- package/lib/sc-ids.ts +151 -0
- package/lib/scaffold/rehearsal.ts +330 -0
- package/lib/scaffold/steps.ts +133 -21
- package/lib/scaffold/write-steps.ts +167 -0
- package/lib/scratch-cleanup.ts +198 -0
- package/lib/scratch-roots.ts +94 -0
- package/lib/validators/spec-validators.ts +23 -34
- package/lib/workflow-security.ts +51 -7
- package/lib/worktree-cleanup.ts +123 -7
- package/lib/worktree-repo.ts +165 -0
- package/package.json +5 -1
- package/scripts/audit-specs.ts +134 -37
- package/scripts/audit-transcript.ts +259 -0
- package/scripts/create-sc.ts +15 -1
- package/scripts/detect-sc-drift.ts +200 -0
- package/scripts/extract-constraints.ts +16 -36
- package/scripts/scaffold-project.ts +26 -136
- package/scripts/split-spec.ts +315 -0
- package/scripts/sync-sc-status.ts +751 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every step that writes, as one callable body (#398).
|
|
3
|
+
*
|
|
4
|
+
* This used to be the inside of `if (fix) { … }` in
|
|
5
|
+
* `scripts/scaffold-project.ts`, with a four-`existsSync` `else` standing in
|
|
6
|
+
* for it during an audit. Those two branches shared no code, so they could
|
|
7
|
+
* only agree by somebody keeping them in step, and the measured disagreement
|
|
8
|
+
* was 28 paths to 0.
|
|
9
|
+
*
|
|
10
|
+
* Pulling the body out here is what lets audit RUN it against a clone instead
|
|
11
|
+
* of predicting it — see `lib/scaffold/rehearsal.ts`. Nothing about the
|
|
12
|
+
* ordering changed in the move, including the two comments that explain why
|
|
13
|
+
* particular steps sit where they do (#72, #123); they are load-bearing and
|
|
14
|
+
* are carried verbatim.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync, writeFileSync } from "fs";
|
|
18
|
+
import { join } from "path";
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
safeDir,
|
|
22
|
+
safeWrite,
|
|
23
|
+
regenerateOwned,
|
|
24
|
+
generateAgentsMdContent,
|
|
25
|
+
refreshScopedRulesStep,
|
|
26
|
+
refreshAgentsMd,
|
|
27
|
+
updateSpecsTable,
|
|
28
|
+
injectEnvironmentSection,
|
|
29
|
+
generateConformityTest,
|
|
30
|
+
generateAgentBriefsStep,
|
|
31
|
+
generateOrAuditProjectHarness,
|
|
32
|
+
generateCodeMapStep,
|
|
33
|
+
copySpecTemplateIfEmpty,
|
|
34
|
+
createGitignore,
|
|
35
|
+
createTsconfig,
|
|
36
|
+
generateProjectState,
|
|
37
|
+
createClaudeMdBridge,
|
|
38
|
+
createCiWorkflows,
|
|
39
|
+
createGitHooks,
|
|
40
|
+
deployHooksToConsumers,
|
|
41
|
+
addPaiHarnessDevDep,
|
|
42
|
+
reportExternalAdoptionStep,
|
|
43
|
+
runAuditSpecsFix,
|
|
44
|
+
postScaffoldCommit,
|
|
45
|
+
} from "./steps";
|
|
46
|
+
import {
|
|
47
|
+
addFrontmatterToSpecs, addFrontmatterToAdrs, detectOversizedSpecs,
|
|
48
|
+
checkGovernsAlignment, detectMisplacedSpecs, detectUnconvertedSpecs,
|
|
49
|
+
} from "../validators/spec-validators";
|
|
50
|
+
import type { ProjectType } from "../generators/types";
|
|
51
|
+
|
|
52
|
+
export interface WriteStepOptions {
|
|
53
|
+
force?: boolean;
|
|
54
|
+
commit?: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* True when running against a disposable clone. The two steps that reach
|
|
57
|
+
* outside the tree are skipped — see `STEPS_NOT_REHEARSED` in
|
|
58
|
+
* `./rehearsal.ts`, which carries the reason for each.
|
|
59
|
+
*/
|
|
60
|
+
rehearsing?: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function runScaffoldWriteSteps(
|
|
64
|
+
projectPath: string,
|
|
65
|
+
projectType: ProjectType,
|
|
66
|
+
actions: string[],
|
|
67
|
+
opts: WriteStepOptions = {},
|
|
68
|
+
): void {
|
|
69
|
+
const { force = false, commit = false, rehearsing = false } = opts;
|
|
70
|
+
|
|
71
|
+
// Phase 0: Security and directory setup
|
|
72
|
+
createGitignore(projectPath, actions);
|
|
73
|
+
safeDir(join(projectPath, "specs"), "specs", actions);
|
|
74
|
+
safeDir(join(projectPath, "reference"), "reference", actions);
|
|
75
|
+
safeDir(join(projectPath, ".github"), ".github", actions);
|
|
76
|
+
safeDir(join(projectPath, ".github", "workflows"), ".github/workflows", actions);
|
|
77
|
+
safeDir(join(projectPath, "scripts"), "scripts", actions);
|
|
78
|
+
safeDir(join(projectPath, "docs"), "docs", actions);
|
|
79
|
+
safeDir(join(projectPath, "docs", "adr"), "docs/adr", actions);
|
|
80
|
+
|
|
81
|
+
const testDirName = existsSync(join(projectPath, "test")) ? "test" : "tests";
|
|
82
|
+
safeDir(join(projectPath, testDirName), testDirName, actions);
|
|
83
|
+
|
|
84
|
+
// Before Phase 0.5 and before createCiWorkflows on purpose (#72): both decide
|
|
85
|
+
// whether to emit a type check by looking for tsconfig.json on disk.
|
|
86
|
+
createTsconfig(projectPath, actions);
|
|
87
|
+
|
|
88
|
+
// Phase 0.5: Generate AGENTS.md
|
|
89
|
+
const agentsMd = generateAgentsMdContent(projectPath, projectType, actions);
|
|
90
|
+
writeFileSync(join(projectPath, "AGENTS.md"), agentsMd);
|
|
91
|
+
actions.push("REGENERATED: AGENTS.md");
|
|
92
|
+
refreshAgentsMd(projectPath, projectType, actions);
|
|
93
|
+
updateSpecsTable(join(projectPath, "AGENTS.md"), actions);
|
|
94
|
+
|
|
95
|
+
// Phase 0.6: Create copilot instructions
|
|
96
|
+
const copilotInstructions = `# Copilot Instructions\n\nRead [AGENTS.md](../AGENTS.md) for project context, key files, specs, and workflow.\n\nAll project knowledge lives in AGENTS.md. Start there.\n`;
|
|
97
|
+
safeWrite(join(projectPath, ".github", "copilot-instructions.md"), copilotInstructions, ".github/copilot-instructions.md", actions);
|
|
98
|
+
|
|
99
|
+
// Phase 0.7: regenerate the conformity test. Strategy passed, not looked up — the label carries the project's own test dir, which may not be `test/` (#208).
|
|
100
|
+
regenerateOwned(join(projectPath, testDirName, "scaffold-conformity.test.ts"), generateConformityTest(projectPath), `${testDirName}/scaffold-conformity.test.ts`, actions, "regenerate");
|
|
101
|
+
|
|
102
|
+
// Validators. These used to run outside the `if (fix)` block with a `{ fix }`
|
|
103
|
+
// flag, which is why `addFrontmatterToSpecs` is the one step audit ever
|
|
104
|
+
// reported anything from.
|
|
105
|
+
addFrontmatterToSpecs(join(projectPath, "specs"), actions);
|
|
106
|
+
addFrontmatterToAdrs(join(projectPath, "docs", "adr"), actions);
|
|
107
|
+
detectOversizedSpecs(join(projectPath, "specs"), actions);
|
|
108
|
+
checkGovernsAlignment(join(projectPath, "specs"), actions);
|
|
109
|
+
detectMisplacedSpecs(projectPath, actions);
|
|
110
|
+
detectUnconvertedSpecs(join(projectPath, "specs"), actions);
|
|
111
|
+
|
|
112
|
+
// Phase 0.8: Workflow project setup
|
|
113
|
+
if (projectType === "workflow") {
|
|
114
|
+
const workflowDef = `---
|
|
115
|
+
doc-type: spec
|
|
116
|
+
testable: no
|
|
117
|
+
governs: workflow-definition
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
# Workflow Definition
|
|
121
|
+
|
|
122
|
+
## Trigger
|
|
123
|
+
|
|
124
|
+
When should this workflow run?
|
|
125
|
+
|
|
126
|
+
## Inputs
|
|
127
|
+
|
|
128
|
+
What inputs does this workflow require?
|
|
129
|
+
|
|
130
|
+
## Process
|
|
131
|
+
|
|
132
|
+
What steps does this workflow perform?
|
|
133
|
+
|
|
134
|
+
## Output
|
|
135
|
+
|
|
136
|
+
What does this workflow produce?
|
|
137
|
+
`;
|
|
138
|
+
safeWrite(join(projectPath, "specs", "WORKFLOW-DEFINITION.md"), workflowDef, "specs/WORKFLOW-DEFINITION.md", actions);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Phase 1.5: Harness config + briefs for ALL project types
|
|
142
|
+
generateOrAuditProjectHarness(projectPath, actions);
|
|
143
|
+
injectEnvironmentSection(projectPath, actions);
|
|
144
|
+
generateAgentBriefsStep(projectPath, actions);
|
|
145
|
+
|
|
146
|
+
// Phase 3: Final setup
|
|
147
|
+
copySpecTemplateIfEmpty(join(projectPath, "specs"), actions);
|
|
148
|
+
generateProjectState(projectPath, actions);
|
|
149
|
+
runAuditSpecsFix(projectPath, actions);
|
|
150
|
+
addPaiHarnessDevDep(projectPath, actions);
|
|
151
|
+
createClaudeMdBridge(projectPath, actions);
|
|
152
|
+
createCiWorkflows(projectPath, actions, { force });
|
|
153
|
+
createGitHooks(projectPath, actions);
|
|
154
|
+
|
|
155
|
+
// Leaves the tree. See STEPS_NOT_REHEARSED.
|
|
156
|
+
if (!rehearsing) deployHooksToConsumers(projectPath, actions);
|
|
157
|
+
|
|
158
|
+
// Phase 3.5: steps that DESCRIBE the project run last, so they describe the tree this run left (#123).
|
|
159
|
+
reportExternalAdoptionStep(projectPath, actions);
|
|
160
|
+
refreshScopedRulesStep(projectPath, projectType, actions);
|
|
161
|
+
if (projectType === "code") {
|
|
162
|
+
generateCodeMapStep(projectPath, actions);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Leaves the tree. See STEPS_NOT_REHEARSED.
|
|
166
|
+
if (!rehearsing) postScaffoldCommit(projectPath, actions, { commit });
|
|
167
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sweep scratch directories the test suite leaked into the repo root (#437).
|
|
3
|
+
*
|
|
4
|
+
* `test/tree-under-test.test.ts` and four others plant their fixtures with
|
|
5
|
+
* `mkdtempSync(join(REPO_ROOT, "<prefix>"))`. They all have correct `afterAll`
|
|
6
|
+
* cleanup; that is the point. The directory is created when bun *imports* the
|
|
7
|
+
* file, before any lifecycle hook can run and before any hook is guaranteed to
|
|
8
|
+
* run at all, so a suite that is interrupted, killed, or that throws during
|
|
9
|
+
* collection leaves one behind. 34 of them had accumulated when Jason noticed,
|
|
10
|
+
* all but one 0 bytes — created at import, never populated, never cleaned.
|
|
11
|
+
*
|
|
12
|
+
* #437 moves creation into `beforeAll`, which stops new ones appearing. This
|
|
13
|
+
* is the other half: the ones already there, and the ones a kill during
|
|
14
|
+
* `beforeAll` can still produce.
|
|
15
|
+
*
|
|
16
|
+
* Same family as #68 (39 stale worktrees) and #436 (a worktree git had pruned
|
|
17
|
+
* out from under): a resource created by tooling that only gets cleaned on the
|
|
18
|
+
* happy path.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readdirSync, statSync, rmSync } from "fs";
|
|
22
|
+
import { join } from "path";
|
|
23
|
+
import { readFileSync } from "fs";
|
|
24
|
+
import { uniqueScratchPrefixes } from "./scratch-roots";
|
|
25
|
+
|
|
26
|
+
export interface ScratchCleanupResult {
|
|
27
|
+
/** Directories removed, named relative to the repo root. */
|
|
28
|
+
removed: string[];
|
|
29
|
+
/** Matched a prefix but was too young to be certain it is not in use. */
|
|
30
|
+
kept: string[];
|
|
31
|
+
/** Did not match any derived prefix — the overwhelming majority. */
|
|
32
|
+
refused: string[];
|
|
33
|
+
errors: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ScratchCleanupOptions {
|
|
37
|
+
repoRoot: string;
|
|
38
|
+
/**
|
|
39
|
+
* How old a scratch directory must be before it is swept. Default one hour.
|
|
40
|
+
*
|
|
41
|
+
* NOT belt-and-braces. This runs at SessionStart, and another session may be
|
|
42
|
+
* three minutes into a suite whose scratch directory is live. The suite that
|
|
43
|
+
* created it cannot defend it — the directory is anonymous and holds no lock
|
|
44
|
+
* — so age is the only signal available, and the direction to be wrong in is
|
|
45
|
+
* leaving litter rather than deleting a running suite's fixtures.
|
|
46
|
+
*/
|
|
47
|
+
maxAgeMs?: number;
|
|
48
|
+
/** Report what would go without removing anything. */
|
|
49
|
+
dryRun?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ONE_HOUR_MS = 60 * 60 * 1000;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The file whose "prefixes" are test fixtures rather than real scratch roots.
|
|
56
|
+
*
|
|
57
|
+
* `test/scratch-paths-unique.test.ts` carries `mkdtempSync(join(ROOT, ".x-"))`
|
|
58
|
+
* as a STRING LITERAL, because that is the only way to prove its detector
|
|
59
|
+
* still fires. Stripping comments does not remove it. Deriving from it would
|
|
60
|
+
* put `.x-` into a deletion allowlist on the strength of a test fixture, which
|
|
61
|
+
* is the self-reference trap with a recursive delete on the end of it.
|
|
62
|
+
*/
|
|
63
|
+
const FIXTURE_FILE = "scratch-paths-unique.test.ts";
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Every prefix any suite in `test/` plants under the repo root.
|
|
67
|
+
*
|
|
68
|
+
* Derived, never listed. A hand-maintained list is a second place to forget,
|
|
69
|
+
* and forgetting there means a new suite's leak accumulates silently — which
|
|
70
|
+
* is the defect this module exists for, one level up.
|
|
71
|
+
*/
|
|
72
|
+
export function scratchPrefixes(repoRoot: string): string[] {
|
|
73
|
+
const testDir = join(repoRoot, "test");
|
|
74
|
+
const out: string[] = [];
|
|
75
|
+
let entries: string[];
|
|
76
|
+
try {
|
|
77
|
+
entries = readdirSync(testDir);
|
|
78
|
+
} catch {
|
|
79
|
+
return out; // no test directory — nothing plants anything
|
|
80
|
+
}
|
|
81
|
+
for (const f of entries) {
|
|
82
|
+
if (!f.endsWith(".ts")) continue;
|
|
83
|
+
if (f === FIXTURE_FILE) continue;
|
|
84
|
+
let src: string;
|
|
85
|
+
try {
|
|
86
|
+
src = readFileSync(join(testDir, f), "utf-8");
|
|
87
|
+
} catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
for (const p of uniqueScratchPrefixes(src)) if (!out.includes(p)) out.push(p);
|
|
91
|
+
}
|
|
92
|
+
return out.sort();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Exactly what `mkdtempSync` appends: six characters from this alphabet.
|
|
97
|
+
*
|
|
98
|
+
* Measured over 200 calls rather than read off the documentation — the
|
|
99
|
+
* lengths set came back `[6]` and the alphabet came back `[A-Za-z0-9]`.
|
|
100
|
+
*/
|
|
101
|
+
const MKDTEMP_SUFFIX = "[A-Za-z0-9]{6}";
|
|
102
|
+
|
|
103
|
+
/** A prefix is data; it reaches a RegExp, so it is escaped rather than trusted. */
|
|
104
|
+
function escapeRegex(s: string): string {
|
|
105
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Whether `entry` is a name `mkdtempSync` could have produced from `prefixes`.
|
|
110
|
+
*
|
|
111
|
+
* The prefix list is a deletion allowlist, so this is written as one, and the
|
|
112
|
+
* first version was written as a weaker one. It asked only that the entry
|
|
113
|
+
* start with a prefix and be longer — and since the prefixes are DERIVED from
|
|
114
|
+
* `test/*.ts`, a suite writing `mkdtempSync(join(REPO_ROOT, ".c"))` would have
|
|
115
|
+
* armed a SessionStart hook to recursively delete `.claude/`.
|
|
116
|
+
* `isScratchEntry(".claude", [".c"])` returned true; it was found by a
|
|
117
|
+
* security review of the first push and confirmed by running it (BUG-437-A).
|
|
118
|
+
*
|
|
119
|
+
* The paths were never the hole — the sweeper builds those itself. The
|
|
120
|
+
* ALLOWLIST was, and an allowlist derived from file content is content
|
|
121
|
+
* steering a recursive delete just as surely as a path would be.
|
|
122
|
+
*
|
|
123
|
+
* So the test is the full shape, not a prefix test: the entry must be a
|
|
124
|
+
* prefix followed by EXACTLY the suffix `mkdtempSync` produces. A bare prefix
|
|
125
|
+
* with nothing after it is a directory someone made deliberately, and
|
|
126
|
+
* anything else is not a name this repo's tooling can have written.
|
|
127
|
+
*
|
|
128
|
+
* ONE anchored match, not a `startsWith` beside a slice at `p.length`. Those
|
|
129
|
+
* two are behaviourally identical on every input — relaxing `startsWith` to
|
|
130
|
+
* `includes` measured **0 of 24**, because the fixed offset refuses whatever
|
|
131
|
+
* the substring match would have let through. Two deciders that agree, with
|
|
132
|
+
* the delete still on the end of them. See
|
|
133
|
+
* `.claude/rules/checks-must-be-able-to-fail.md`.
|
|
134
|
+
*/
|
|
135
|
+
export function isScratchEntry(entry: string, prefixes: string[]): boolean {
|
|
136
|
+
return prefixes.some(p =>
|
|
137
|
+
p.length > 1 && new RegExp(`^${escapeRegex(p)}${MKDTEMP_SUFFIX}$`).test(entry));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Remove leaked scratch directories from the repo root.
|
|
142
|
+
*
|
|
143
|
+
* Every path this deletes is one THIS function built, from
|
|
144
|
+
* `join(opts.repoRoot, entry)` where `entry` came from reading that same
|
|
145
|
+
* directory. No absolute path from any other source — not a config, not a
|
|
146
|
+
* prefix, not a `.git` file — can reach the `rmSync`. #436 learned that one
|
|
147
|
+
* the expensive way: content must never steer a recursive delete.
|
|
148
|
+
*/
|
|
149
|
+
export function cleanupScratchDirs(opts: ScratchCleanupOptions): ScratchCleanupResult {
|
|
150
|
+
const result: ScratchCleanupResult = { removed: [], kept: [], refused: [], errors: [] };
|
|
151
|
+
const maxAgeMs = opts.maxAgeMs ?? ONE_HOUR_MS;
|
|
152
|
+
const prefixes = scratchPrefixes(opts.repoRoot);
|
|
153
|
+
|
|
154
|
+
let entries: string[];
|
|
155
|
+
try {
|
|
156
|
+
entries = readdirSync(opts.repoRoot);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
result.errors.push(`Failed to read ${opts.repoRoot}: ${err}`);
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
for (const entry of entries) {
|
|
163
|
+
if (!isScratchEntry(entry, prefixes)) {
|
|
164
|
+
result.refused.push(entry);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const path = join(opts.repoRoot, entry);
|
|
168
|
+
let age: number;
|
|
169
|
+
try {
|
|
170
|
+
const stat = statSync(path);
|
|
171
|
+
if (!stat.isDirectory()) {
|
|
172
|
+
result.refused.push(entry);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
age = Date.now() - stat.mtimeMs;
|
|
176
|
+
} catch (err) {
|
|
177
|
+
result.errors.push(`Failed to stat ${entry}: ${err}`);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (age < maxAgeMs) {
|
|
182
|
+
result.kept.push(`${entry} (${Math.round(age / 1000)}s old — a suite may still be using it)`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (opts.dryRun) {
|
|
186
|
+
result.removed.push(`${entry} (dry run)`);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
rmSync(path, { recursive: true, force: true });
|
|
191
|
+
result.removed.push(entry);
|
|
192
|
+
} catch (err) {
|
|
193
|
+
result.errors.push(`Failed to remove ${entry}: ${err}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single owner of "what does a scratch root in this repo look like" (#437).
|
|
3
|
+
*
|
|
4
|
+
* Two questions are asked about the same source text, and they are asked from
|
|
5
|
+
* two different places:
|
|
6
|
+
*
|
|
7
|
+
* - `test/scratch-paths-unique.test.ts` asks which scratch roots are FIXED,
|
|
8
|
+
* because a fixed path under the shared checkout is a shared mutable
|
|
9
|
+
* resource (#323 SC-6).
|
|
10
|
+
* - `lib/scratch-cleanup.ts` asks which PREFIXES the unique ones use,
|
|
11
|
+
* because a sweeper needs to know what it is allowed to delete.
|
|
12
|
+
*
|
|
13
|
+
* They are the same parse. Two copies of it would be two deciders that agree —
|
|
14
|
+
* the fourth shape in `.claude/rules/checks-must-be-able-to-fail.md` — and
|
|
15
|
+
* worse than usual here, because the second decider's output is a deletion
|
|
16
|
+
* allowlist. A parser that quietly stopped seeing a prefix would not go red;
|
|
17
|
+
* it would stop sweeping, which is indistinguishable from nothing having
|
|
18
|
+
* leaked.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { stripJsComments } from "./strip-js-comments";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Identifiers bound to the repository root, per file.
|
|
25
|
+
*
|
|
26
|
+
* `join(tmpDir, ".claude")` is a fixed name under an ALREADY-UNIQUE root —
|
|
27
|
+
* the suffix is on the parent, which is just as good. Only a path rooted at
|
|
28
|
+
* the shared checkout can collide, so the root is the thing to look at.
|
|
29
|
+
*/
|
|
30
|
+
export function repoRootIdents(src: string): Set<string> {
|
|
31
|
+
const idents = new Set<string>();
|
|
32
|
+
for (const m of src.matchAll(/(?:const|let|var)?\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^;\n]+)/g)) {
|
|
33
|
+
if (/import\.meta\.dir|process\.cwd\(\)/.test(m[2]!)) idents.add(m[1]!);
|
|
34
|
+
}
|
|
35
|
+
return idents;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The declaration forms a scratch root can arrive in.
|
|
40
|
+
*
|
|
41
|
+
* `const` is matched optionally, and that is #437's doing rather than
|
|
42
|
+
* tidiness. Moving creation out of module scope means writing
|
|
43
|
+
* `let SCRATCH = ""` at the top and `SCRATCH = mkdtempSync(...)` inside
|
|
44
|
+
* `beforeAll`, and a `const`-only pattern stops seeing both forms at once —
|
|
45
|
+
* so the fix for the leak would have opened a hole in the guard against
|
|
46
|
+
* fixed paths. Measured: it is 3 red without the relaxation.
|
|
47
|
+
*/
|
|
48
|
+
const DECL = /(?:const|let|var\s+)?\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(mkdtempSync\s*\(\s*)?join\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*,\s*"(\.[^"]*)"/g;
|
|
49
|
+
|
|
50
|
+
/** Navigation, not a scratch name. */
|
|
51
|
+
function isNavigation(literal: string): boolean {
|
|
52
|
+
return literal === "." || literal === ".." || literal.startsWith("../");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Scratch roots declared at a fixed path under the shared checkout. */
|
|
56
|
+
export function fixedScratchRoots(source: string): string[] {
|
|
57
|
+
const src = stripJsComments(source);
|
|
58
|
+
const roots = repoRootIdents(src);
|
|
59
|
+
const out: string[] = [];
|
|
60
|
+
for (const m of src.matchAll(new RegExp(DECL.source, "g"))) {
|
|
61
|
+
const [, name, wrapped, rootIdent, literal] = m;
|
|
62
|
+
if (wrapped) continue; // mkdtempSync — unique per run, which is the fix
|
|
63
|
+
if (!roots.has(rootIdent!)) continue; // already under a unique root
|
|
64
|
+
if (isNavigation(literal!)) continue;
|
|
65
|
+
// Only a directory this suite CREATES or DELETES is scratch. One it merely
|
|
66
|
+
// reads is configuration, and renaming it per run would break the read.
|
|
67
|
+
const mutates = new RegExp(`(?:mkdirSync|rmSync)\\(\\s*(?:join\\(\\s*)?${name}\\b`);
|
|
68
|
+
if (mutates.test(src)) out.push(`${name} = ${literal}`);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The `mkdtempSync` prefixes a file plants under the repo root.
|
|
75
|
+
*
|
|
76
|
+
* This is the other half of the same parse, and it is what the sweeper's
|
|
77
|
+
* allowlist is built from. It deliberately returns the prefix EXACTLY as
|
|
78
|
+
* written — including the trailing `-` that `mkdtempSync` appends its random
|
|
79
|
+
* suffix to — because a prefix widened by even one character is a wider
|
|
80
|
+
* deletion allowlist.
|
|
81
|
+
*/
|
|
82
|
+
export function uniqueScratchPrefixes(source: string): string[] {
|
|
83
|
+
const src = stripJsComments(source);
|
|
84
|
+
const roots = repoRootIdents(src);
|
|
85
|
+
const out: string[] = [];
|
|
86
|
+
for (const m of src.matchAll(new RegExp(DECL.source, "g"))) {
|
|
87
|
+
const [, , wrapped, rootIdent, literal] = m;
|
|
88
|
+
if (!wrapped) continue; // a fixed path is the other function's subject
|
|
89
|
+
if (!roots.has(rootIdent!)) continue;
|
|
90
|
+
if (isNavigation(literal!)) continue;
|
|
91
|
+
if (!out.includes(literal!)) out.push(literal!);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
@@ -44,12 +44,16 @@ export function checkGovernsAlignment(specsDir: string, actions: string[]): void
|
|
|
44
44
|
/**
|
|
45
45
|
* Add or complete frontmatter on spec files.
|
|
46
46
|
* Injects doc-type, testable, governs fields if missing.
|
|
47
|
-
*
|
|
47
|
+
*
|
|
48
|
+
* Always writes. The `opts.fix` parameter and its gap-reporting branch were
|
|
49
|
+
* removed in #398: audit no longer predicts what this would do, it runs this
|
|
50
|
+
* against a throwaway clone, so a second non-writing code path has nothing
|
|
51
|
+
* left to serve. Unreachable from the only caller for its whole life, and an
|
|
52
|
+
* unreachable branch reporting gaps is a report nothing can contradict.
|
|
48
53
|
*/
|
|
49
|
-
export function addFrontmatterToSpecs(specsDir: string, actions: string[]
|
|
54
|
+
export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void {
|
|
50
55
|
if (!existsSync(specsDir)) return;
|
|
51
56
|
|
|
52
|
-
const fixMode = opts?.fix ?? true;
|
|
53
57
|
const today = new Date().toISOString().split("T")[0];
|
|
54
58
|
|
|
55
59
|
for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
|
|
@@ -57,13 +61,9 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?
|
|
|
57
61
|
const content = readFileSync(filePath, "utf-8");
|
|
58
62
|
|
|
59
63
|
if (!content.startsWith("---\n")) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
actions.push(`UPDATED: specs/${file} (added frontmatter)`);
|
|
64
|
-
} else {
|
|
65
|
-
actions.push(`GAP: specs/${file} missing frontmatter — run with --fix to add`);
|
|
66
|
-
}
|
|
64
|
+
const frontmatter = `---\ndoc-type: spec\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\ngoverns: TODO — describe what this spec governs\ntestable: false\n---\n\n`;
|
|
65
|
+
writeFileSync(filePath, frontmatter + content);
|
|
66
|
+
actions.push(`UPDATED: specs/${file} (added frontmatter)`);
|
|
67
67
|
} else {
|
|
68
68
|
// Validate existing frontmatter has required fields
|
|
69
69
|
const fmEnd = content.indexOf("\n---", 4);
|
|
@@ -74,13 +74,9 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?
|
|
|
74
74
|
if (!fm.includes("created:")) missing.push(`created: ${today}`);
|
|
75
75
|
if (!fm.includes("governs:")) missing.push(`governs: TODO`);
|
|
76
76
|
if (missing.length > 0) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
|
|
81
|
-
} else {
|
|
82
|
-
actions.push(`GAP: specs/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
|
|
83
|
-
}
|
|
77
|
+
const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
|
|
78
|
+
writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
|
|
79
|
+
actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
|
|
84
80
|
}
|
|
85
81
|
// SC-269: WARN for specs with missing or TODO governs
|
|
86
82
|
const governsMatch = fm.match(/governs:\s*(.+)/);
|
|
@@ -130,12 +126,13 @@ export function detectUnconvertedSpecs(specsDir: string, actions: string[]): voi
|
|
|
130
126
|
/**
|
|
131
127
|
* Add or complete frontmatter on ADR files.
|
|
132
128
|
* Injects doc-type, created fields if missing.
|
|
133
|
-
*
|
|
129
|
+
*
|
|
130
|
+
* Always writes — see `addFrontmatterToSpecs` for why the non-fix branch is
|
|
131
|
+
* gone (#398).
|
|
134
132
|
*/
|
|
135
|
-
export function addFrontmatterToAdrs(adrDir: string, actions: string[]
|
|
133
|
+
export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
|
|
136
134
|
if (!existsSync(adrDir)) return;
|
|
137
135
|
|
|
138
|
-
const fixMode = opts?.fix ?? true;
|
|
139
136
|
const today = new Date().toISOString().split("T")[0];
|
|
140
137
|
|
|
141
138
|
for (const file of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
|
|
@@ -143,13 +140,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: {
|
|
|
143
140
|
const content = readFileSync(filePath, "utf-8");
|
|
144
141
|
|
|
145
142
|
if (!content.startsWith("---\n")) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
|
|
150
|
-
} else {
|
|
151
|
-
actions.push(`GAP: docs/adr/${file} missing frontmatter — run with --fix to add`);
|
|
152
|
-
}
|
|
143
|
+
const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
|
|
144
|
+
writeFileSync(filePath, frontmatter + content);
|
|
145
|
+
actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
|
|
153
146
|
} else {
|
|
154
147
|
const fmEnd = content.indexOf("\n---", 4);
|
|
155
148
|
if (fmEnd === -1) continue;
|
|
@@ -158,13 +151,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: {
|
|
|
158
151
|
if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
|
|
159
152
|
if (!fm.includes("created:")) missing.push(`created: ${today}`);
|
|
160
153
|
if (missing.length > 0) {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
|
|
165
|
-
} else {
|
|
166
|
-
actions.push(`GAP: docs/adr/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
|
|
167
|
-
}
|
|
154
|
+
const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
|
|
155
|
+
writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
|
|
156
|
+
actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
|
|
168
157
|
}
|
|
169
158
|
}
|
|
170
159
|
}
|
package/lib/workflow-security.ts
CHANGED
|
@@ -4,6 +4,56 @@ const SHELL_METACHARACTERS = /[;&|$`\n\r"'\\(){}[\]<>!~*?#]/;
|
|
|
4
4
|
const PATH_TRAVERSAL = /\.\.($|[/\\])/;
|
|
5
5
|
const NULL_BYTE = /\x00/;
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Why a path may not be contributed by an agent, or `null` if it may.
|
|
9
|
+
*
|
|
10
|
+
* ONE table, ONE decider (#400). Before this there were two: a regex set here,
|
|
11
|
+
* checked at staging time, and a segment walk in `workflows/ship.js`'s
|
|
12
|
+
* `escapesWorktree`, checked at collection time. They agreed on traversal and
|
|
13
|
+
* on nothing else, so the audit accepted a reported path carrying a shell
|
|
14
|
+
* metacharacter, a null byte or 500+ characters, declared the run clean, and
|
|
15
|
+
* staging refused it two phases later with a different message.
|
|
16
|
+
*
|
|
17
|
+
* `boundary` separates the two reasons a path can be refused, because they are
|
|
18
|
+
* different things to tell an operator:
|
|
19
|
+
*
|
|
20
|
+
* true — the path does not name a location inside the worktree at all.
|
|
21
|
+
* false — it does, and still cannot be handled safely.
|
|
22
|
+
*
|
|
23
|
+
* "not inside its own worktree" is a wrong sentence to print about
|
|
24
|
+
* `lib/a;rm.ts`, and an operator who reads it goes looking for a path that is
|
|
25
|
+
* not there.
|
|
26
|
+
*
|
|
27
|
+
* The order is the order the reasons are reported in. Absoluteness first
|
|
28
|
+
* because it is the least ambiguous, then the segment walk, then the regexes.
|
|
29
|
+
*
|
|
30
|
+
* The two traversal rules are deliberately both present and deliberately
|
|
31
|
+
* separate. `p.split("/").includes("..")` is the real boundary question; the
|
|
32
|
+
* regex also matches a segment merely ENDING in `..` (`lib/foo..`), which is a
|
|
33
|
+
* legal filename that staging has always refused. Folding it into the boundary
|
|
34
|
+
* rule would label a legal file an escape; dropping it would make the audit
|
|
35
|
+
* permit something staging rejects, which is the whole defect.
|
|
36
|
+
*/
|
|
37
|
+
const CONTRIBUTABLE_PATH_RULES: ReadonlyArray<
|
|
38
|
+
readonly [rule: string, boundary: boolean, fails: (p: string) => boolean]
|
|
39
|
+
> = [
|
|
40
|
+
["an absolute path", true, (p) => p.startsWith("/")],
|
|
41
|
+
["a `..` segment", true, (p) => p.split("/").includes("..")],
|
|
42
|
+
["a segment ending in `..`", false, (p) => PATH_TRAVERSAL.test(p)],
|
|
43
|
+
["a shell metacharacter", false, (p) => SHELL_METACHARACTERS.test(p)],
|
|
44
|
+
["a null byte", false, (p) => NULL_BYTE.test(p)],
|
|
45
|
+
["over 500 characters", false, (p) => p.length > 500],
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
export function pathRefusal(
|
|
49
|
+
p: string,
|
|
50
|
+
): { rule: string; boundary: boolean } | null {
|
|
51
|
+
for (const [rule, boundary, fails] of CONTRIBUTABLE_PATH_RULES) {
|
|
52
|
+
if (fails(p)) return { rule, boundary };
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
7
57
|
export function buildSafeGitAdd(filesChanged: string[]): string {
|
|
8
58
|
const validated = validateFilePaths(filesChanged);
|
|
9
59
|
if (validated.rejected.length > 0) {
|
|
@@ -21,13 +71,7 @@ export function validateFilePaths(
|
|
|
21
71
|
const valid: string[] = [];
|
|
22
72
|
const rejected: string[] = [];
|
|
23
73
|
for (const p of paths) {
|
|
24
|
-
if (
|
|
25
|
-
SHELL_METACHARACTERS.test(p) ||
|
|
26
|
-
PATH_TRAVERSAL.test(p) ||
|
|
27
|
-
NULL_BYTE.test(p) ||
|
|
28
|
-
p.startsWith("/") ||
|
|
29
|
-
p.length > 500
|
|
30
|
-
) {
|
|
74
|
+
if (pathRefusal(p)) {
|
|
31
75
|
rejected.push(p);
|
|
32
76
|
} else {
|
|
33
77
|
valid.push(p);
|