rungate 0.2.1 → 0.3.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.
- package/bin/rungate.ts +70 -0
- package/lib/aes-calculator.ts +66 -0
- package/lib/agent-audit.ts +139 -0
- package/lib/agent-brief-validation.ts +359 -0
- package/lib/agents-md-refs.ts +90 -0
- package/lib/bash-file-read.ts +197 -0
- package/lib/behavioral-cache.ts +78 -0
- package/lib/branch-cleanup.ts +234 -0
- package/lib/brief-context-parser.ts +35 -0
- package/lib/canary.ts +117 -0
- package/lib/check-registry.ts +226 -0
- package/lib/ci-checkout.ts +400 -0
- package/lib/cli-commands.ts +137 -0
- package/lib/compliance-backfill.ts +220 -0
- package/lib/compliance-report.ts +504 -0
- package/lib/compliance.ts +361 -0
- package/lib/config-loader.ts +255 -0
- package/lib/conformity.ts +1818 -131
- package/lib/container-provenance.ts +230 -0
- package/lib/create-brief.ts +150 -0
- package/lib/create-sc.ts +272 -0
- package/lib/deep-merge.ts +69 -0
- package/lib/dev-liveness.ts +214 -0
- package/lib/directive-extractor.ts +210 -0
- package/lib/distribution-standing.ts +113 -0
- package/lib/doc-hygiene.ts +238 -0
- package/lib/eval-criteria.ts +6 -0
- package/lib/evidence-portability.ts +123 -0
- package/lib/evidence-prevalidator.ts +390 -0
- package/lib/evidence-required.ts +150 -0
- package/lib/evidence-satisfiability.ts +288 -0
- package/lib/frontmatter.ts +163 -0
- package/lib/gap-scanner.ts +348 -0
- package/lib/gate-enforcement.ts +366 -0
- package/lib/generators/agent-briefs.ts +136 -0
- package/lib/generators/agents-md.ts +506 -0
- package/lib/generators/code-map.ts +60 -0
- package/lib/generators/types.ts +184 -0
- package/lib/git-ref-normalizer.ts +107 -0
- package/lib/github.ts +539 -0
- package/lib/harness-identity.ts +63 -0
- package/lib/hill-climb.ts +164 -0
- package/lib/instruction-effectiveness.ts +131 -0
- package/lib/issue-closure-audit.ts +225 -0
- package/lib/issue-create-override.ts +343 -0
- package/lib/js-top-level-code.ts +250 -0
- package/lib/liveness-contradiction.ts +149 -0
- package/lib/organize.ts +505 -0
- package/lib/paths.ts +197 -6
- package/lib/post-fix-verify.ts +157 -0
- package/lib/prior-branch.ts +489 -0
- package/lib/project-state-shape.ts +166 -0
- package/lib/promote-outputs.ts +156 -0
- package/lib/prove-label-gate.ts +35 -0
- package/lib/reachability.ts +302 -0
- package/lib/release-preflight.ts +186 -0
- package/lib/rule-health-pipeline.ts +264 -0
- package/lib/rule-health-trend.ts +161 -0
- package/lib/rule-provenance.ts +149 -0
- package/lib/rule-registry.ts +128 -0
- package/lib/rungate-schema.ts +114 -4
- package/lib/sc-claim-forms.ts +179 -0
- package/lib/sc-cover.ts +150 -0
- package/lib/sc-guard.ts +157 -0
- package/lib/sc-ids.ts +344 -0
- package/lib/scaffold/defaults.ts +165 -0
- package/lib/scaffold/managed-workflow.ts +370 -0
- package/lib/scaffold/owned-files.ts +265 -0
- package/lib/scaffold/steps.ts +2680 -0
- package/lib/scanner.ts +701 -0
- package/lib/screenshot-upload.ts +73 -0
- package/lib/secret-patterns.ts +112 -0
- package/lib/security-verdict.ts +616 -0
- package/lib/signal-phrases.ts +1 -0
- package/lib/spec-change-conformity.ts +80 -0
- package/lib/spec-files.ts +62 -0
- package/lib/spec-registry.ts +133 -0
- package/lib/spec-updater.ts +96 -0
- package/lib/stale-cleanup.ts +224 -0
- package/lib/stale-issue-scanner.ts +36 -0
- package/lib/strip-js-comments.ts +269 -0
- package/lib/suite-measurement.ts +228 -0
- package/lib/task-completion-checks.ts +177 -0
- package/lib/test-suite-lock.ts +1136 -0
- package/lib/transcript-checker.ts +1140 -0
- package/lib/validators/spec-validators.ts +171 -0
- package/lib/verdict-capture.ts +73 -0
- package/lib/verified-push.ts +358 -0
- package/lib/workflow-security.ts +174 -0
- package/lib/worktree-cleanup.ts +250 -0
- package/lib/worktree-collect.ts +283 -0
- package/lib/worktree-isolation.ts +82 -0
- package/package.json +24 -2
- package/prompts/ac-adversary.md +14 -2
- package/prompts/aditi.md +5 -0
- package/prompts/blast-radius.md +5 -0
- package/prompts/container-verify.md +5 -0
- package/prompts/discovery.md +4 -0
- package/prompts/environment.md +5 -0
- package/prompts/evidence-hierarchy.md +5 -0
- package/prompts/evidence-validator.md +11 -0
- package/prompts/marcus.md +5 -0
- package/prompts/prevention.md +5 -0
- package/prompts/prove-reproducer.md +12 -0
- package/prompts/quinn-decision-tree.md +5 -0
- package/prompts/quinn-ui-brief.md +5 -0
- package/prompts/quinn.md +5 -0
- package/prompts/rca.md +5 -0
- package/prompts/read-before-write.md +4 -0
- package/prompts/regression.md +5 -0
- package/prompts/serena.md +5 -0
- package/scripts/audit-specs.ts +464 -0
- package/scripts/convert-spec.ts +293 -0
- package/scripts/create-sc.ts +92 -0
- package/scripts/create-spec.ts +166 -0
- package/scripts/extract-constraints.ts +4 -3
- package/scripts/generate-code-map.ts +1 -1
- package/scripts/scaffold-project.ts +138 -1426
- package/scripts/sync-spec-tests.ts +211 -126
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* spec-validators.ts — Spec validation functions extracted from scaffold-project.ts
|
|
3
|
+
*
|
|
4
|
+
* Handles frontmatter injection, oversized spec detection, and governs alignment checks.
|
|
5
|
+
* All functions take a directory path and an actions array for reporting.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* SC-278: Detect specs that exceed 500 lines and suggest splitting.
|
|
12
|
+
*/
|
|
13
|
+
export function detectOversizedSpecs(specsDir: string, actions: string[]): void {
|
|
14
|
+
if (!existsSync(specsDir)) return;
|
|
15
|
+
for (const file of new Bun.Glob("**/*.md").scanSync({ cwd: specsDir, absolute: false })) {
|
|
16
|
+
const content = readFileSync(join(specsDir, file), "utf-8");
|
|
17
|
+
const lineCount = content.split("\n").length;
|
|
18
|
+
if (lineCount > 500) {
|
|
19
|
+
actions.push(`WARN: specs/${file} is ${lineCount} lines (>500) — consider splitting with \`bun scripts/split-spec.ts specs/${file}\``);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* SC-279: Check that spec content aligns with its governs field.
|
|
26
|
+
* Warns when a spec has too many H2 sections relative to its governs scope.
|
|
27
|
+
*/
|
|
28
|
+
export function checkGovernsAlignment(specsDir: string, actions: string[]): void {
|
|
29
|
+
if (!existsSync(specsDir)) return;
|
|
30
|
+
for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
|
|
31
|
+
const content = readFileSync(join(specsDir, file), "utf-8");
|
|
32
|
+
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
|
33
|
+
if (!fmMatch) continue;
|
|
34
|
+
const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
|
|
35
|
+
if (!gMatch || gMatch[1].trim().startsWith("TODO")) continue;
|
|
36
|
+
// Check if the file has multiple unrelated H2 sections that don't match governs
|
|
37
|
+
const h2s = content.match(/^## .+/gm) || [];
|
|
38
|
+
if (h2s.length > 8) {
|
|
39
|
+
actions.push(`WARN: specs/${file} has ${h2s.length} sections — may cover more than its governs ("${gMatch[1].trim().slice(0, 60)}"). Consider splitting.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Add or complete frontmatter on spec files.
|
|
46
|
+
* Injects doc-type, testable, governs fields if missing.
|
|
47
|
+
* When opts.fix is false, reports gaps without modifying files.
|
|
48
|
+
*/
|
|
49
|
+
export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?: { fix?: boolean }): void {
|
|
50
|
+
if (!existsSync(specsDir)) return;
|
|
51
|
+
|
|
52
|
+
const fixMode = opts?.fix ?? true;
|
|
53
|
+
const today = new Date().toISOString().split("T")[0];
|
|
54
|
+
|
|
55
|
+
for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
|
|
56
|
+
const filePath = join(specsDir, file);
|
|
57
|
+
const content = readFileSync(filePath, "utf-8");
|
|
58
|
+
|
|
59
|
+
if (!content.startsWith("---\n")) {
|
|
60
|
+
if (fixMode) {
|
|
61
|
+
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`;
|
|
62
|
+
writeFileSync(filePath, frontmatter + content);
|
|
63
|
+
actions.push(`UPDATED: specs/${file} (added frontmatter)`);
|
|
64
|
+
} else {
|
|
65
|
+
actions.push(`GAP: specs/${file} missing frontmatter — run with --fix to add`);
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
// Validate existing frontmatter has required fields
|
|
69
|
+
const fmEnd = content.indexOf("\n---", 4);
|
|
70
|
+
if (fmEnd === -1) continue;
|
|
71
|
+
const fm = content.substring(4, fmEnd);
|
|
72
|
+
const missing: string[] = [];
|
|
73
|
+
if (!fm.includes("testable:")) missing.push(`testable: false`);
|
|
74
|
+
if (!fm.includes("created:")) missing.push(`created: ${today}`);
|
|
75
|
+
if (!fm.includes("governs:")) missing.push(`governs: TODO`);
|
|
76
|
+
if (missing.length > 0) {
|
|
77
|
+
if (fixMode) {
|
|
78
|
+
const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
|
|
79
|
+
writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
|
|
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
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// SC-269: WARN for specs with missing or TODO governs
|
|
86
|
+
const governsMatch = fm.match(/governs:\s*(.+)/);
|
|
87
|
+
if (!governsMatch || governsMatch[1].trim() === "TODO" || governsMatch[1].trim().startsWith("TODO")) {
|
|
88
|
+
actions.push(`WARN: specs/${file} has no governs: field (or governs: TODO) — add a one-line description of what this spec governs`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Issue #41: Detect spec files in docs/specs/ and suggest migration to specs/.
|
|
96
|
+
* Takes a project root (not specs dir) since it needs to check docs/specs/.
|
|
97
|
+
*/
|
|
98
|
+
export function detectMisplacedSpecs(projectRoot: string, actions: string[]): void {
|
|
99
|
+
const docsSpecsDir = join(projectRoot, "docs", "specs");
|
|
100
|
+
if (!existsSync(docsSpecsDir)) return;
|
|
101
|
+
const specFiles = readdirSync(docsSpecsDir).filter(f => f.endsWith(".md"));
|
|
102
|
+
if (specFiles.length === 0) return;
|
|
103
|
+
for (const file of specFiles) {
|
|
104
|
+
actions.push(
|
|
105
|
+
`WARN: docs/specs/${file} should be in specs/ — run \`bun scripts/migrate-specs.ts .\` to migrate`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Issue #41: Detect specs in specs/ that lack SC checkbox lines and suggest conversion.
|
|
112
|
+
*/
|
|
113
|
+
export function detectUnconvertedSpecs(specsDir: string, actions: string[]): void {
|
|
114
|
+
if (!existsSync(specsDir)) return;
|
|
115
|
+
for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md")) {
|
|
116
|
+
const content = readFileSync(join(specsDir, file), "utf-8");
|
|
117
|
+
// Check if this spec has frontmatter with testable field
|
|
118
|
+
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
|
119
|
+
if (!fmMatch) continue;
|
|
120
|
+
// Check if file has any SC checkbox lines
|
|
121
|
+
const hasSCLines = /^- \[[ x]\] SC-\d+:/m.test(content);
|
|
122
|
+
if (!hasSCLines) {
|
|
123
|
+
actions.push(
|
|
124
|
+
`WARN: specs/${file} has no SC checkboxes — run \`bun scripts/convert-spec.ts specs/${file}\` to convert`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Add or complete frontmatter on ADR files.
|
|
132
|
+
* Injects doc-type, created fields if missing.
|
|
133
|
+
* When opts.fix is false, reports gaps without modifying files.
|
|
134
|
+
*/
|
|
135
|
+
export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: { fix?: boolean }): void {
|
|
136
|
+
if (!existsSync(adrDir)) return;
|
|
137
|
+
|
|
138
|
+
const fixMode = opts?.fix ?? true;
|
|
139
|
+
const today = new Date().toISOString().split("T")[0];
|
|
140
|
+
|
|
141
|
+
for (const file of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
|
|
142
|
+
const filePath = join(adrDir, file);
|
|
143
|
+
const content = readFileSync(filePath, "utf-8");
|
|
144
|
+
|
|
145
|
+
if (!content.startsWith("---\n")) {
|
|
146
|
+
if (fixMode) {
|
|
147
|
+
const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
|
|
148
|
+
writeFileSync(filePath, frontmatter + content);
|
|
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
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
const fmEnd = content.indexOf("\n---", 4);
|
|
155
|
+
if (fmEnd === -1) continue;
|
|
156
|
+
const fm = content.substring(4, fmEnd);
|
|
157
|
+
const missing: string[] = [];
|
|
158
|
+
if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
|
|
159
|
+
if (!fm.includes("created:")) missing.push(`created: ${today}`);
|
|
160
|
+
if (missing.length > 0) {
|
|
161
|
+
if (fixMode) {
|
|
162
|
+
const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
|
|
163
|
+
writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
|
|
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
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verdict capture logic — extracted from AgentVerdictCapture.hook.ts
|
|
3
|
+
*
|
|
4
|
+
* Deep module: contains workflow discovery and verdict parsing.
|
|
5
|
+
* The hook file is a thin trigger that delegates here.
|
|
6
|
+
*
|
|
7
|
+
* Issue: #544
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
|
|
11
|
+
import { join } from 'path';
|
|
12
|
+
|
|
13
|
+
export interface ActiveWorkflow {
|
|
14
|
+
path: string;
|
|
15
|
+
data: any;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Find the most recently modified active workflow-state.json.
|
|
20
|
+
* Scans 1 and 2 levels deep under workDir for BUILD/VERIFY/SHIP phases.
|
|
21
|
+
*/
|
|
22
|
+
export function findActiveWorkflow(workDir: string): ActiveWorkflow | null {
|
|
23
|
+
if (!existsSync(workDir)) return null;
|
|
24
|
+
let best: { path: string; data: any; mtime: number } | null = null;
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
for (const entry of readdirSync(workDir, { withFileTypes: true })) {
|
|
28
|
+
if (!entry.isDirectory()) continue;
|
|
29
|
+
// Level 1
|
|
30
|
+
const wfPath = join(workDir, entry.name, 'workflow-state.json');
|
|
31
|
+
if (existsSync(wfPath)) {
|
|
32
|
+
try {
|
|
33
|
+
const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
|
|
34
|
+
if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
|
|
35
|
+
const mtime = statSync(wfPath).mtimeMs;
|
|
36
|
+
if (!best || mtime > best.mtime) best = { path: wfPath, data, mtime };
|
|
37
|
+
}
|
|
38
|
+
} catch {}
|
|
39
|
+
}
|
|
40
|
+
// Level 2
|
|
41
|
+
try {
|
|
42
|
+
for (const sub of readdirSync(join(workDir, entry.name), { withFileTypes: true })) {
|
|
43
|
+
if (!sub.isDirectory()) continue;
|
|
44
|
+
const nestedWf = join(workDir, entry.name, sub.name, 'workflow-state.json');
|
|
45
|
+
if (!existsSync(nestedWf)) continue;
|
|
46
|
+
try {
|
|
47
|
+
const data = JSON.parse(readFileSync(nestedWf, 'utf-8'));
|
|
48
|
+
if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
|
|
49
|
+
const mtime = statSync(nestedWf).mtimeMs;
|
|
50
|
+
if (!best || mtime > best.mtime) best = { path: nestedWf, data, mtime };
|
|
51
|
+
}
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
} catch {}
|
|
55
|
+
}
|
|
56
|
+
} catch {}
|
|
57
|
+
|
|
58
|
+
return best ? { path: best.path, data: best.data } : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Extract a structured verdict block from agent output text.
|
|
63
|
+
* Looks for "## Verdict\n{...}" pattern.
|
|
64
|
+
*/
|
|
65
|
+
export function extractVerdict(text: string): any | null {
|
|
66
|
+
const match = text.match(/## Verdict\n(\{[\s\S]*?\n\})/);
|
|
67
|
+
if (!match) return null;
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(match[1]);
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #213 — the ship gate's auto-push, with every failure mode named.
|
|
3
|
+
*
|
|
4
|
+
* The code this replaces was five statements wrapped in `try { … } catch {}`.
|
|
5
|
+
* It ran at the very end of `generateShipEvidence`, which `runGate` calls only
|
|
6
|
+
* once the ship gate has already decided PASS — so nothing downstream looks at
|
|
7
|
+
* it, and four distinct ways for it to leave the work on the local machine all
|
|
8
|
+
* produced the same observable outcome as success:
|
|
9
|
+
*
|
|
10
|
+
* - the push was rejected (non-fast-forward, a pre-receive hook, no network);
|
|
11
|
+
* - the branch had no upstream, so `rev-list @{upstream}..HEAD` exited
|
|
12
|
+
* non-zero and the catch swallowed it before the push was even attempted;
|
|
13
|
+
* - `rev-list` printed something non-numeric, and `parseInt(x) > 0` is false
|
|
14
|
+
* for NaN, so the push was skipped as if there were nothing to push;
|
|
15
|
+
* - the push "succeeded" against a remote that did not end up carrying the
|
|
16
|
+
* commit, with `stdio: "pipe"` discarding whatever git said about it.
|
|
17
|
+
*
|
|
18
|
+
* This is not the same reading `unpushedViolations` in gates/workflow.test.ts
|
|
19
|
+
* takes for the `code-pushed` check, and it does not make that one redundant.
|
|
20
|
+
* That one runs during the gate and compares HEAD against `@{upstream}`, a
|
|
21
|
+
* LOCAL remote-tracking ref that only fetch and push update. This one runs
|
|
22
|
+
* after the gate's verdict and asks the remote directly, with `ls-remote`,
|
|
23
|
+
* because the question here is "did the commit leave the machine" and a local
|
|
24
|
+
* ref cannot answer it.
|
|
25
|
+
*
|
|
26
|
+
* ## Shape
|
|
27
|
+
*
|
|
28
|
+
* `classifyPush` is pure and total: it takes the readings and returns exactly
|
|
29
|
+
* one outcome. The git invocations live in `verifiedPush`, so every branch —
|
|
30
|
+
* including the ones a healthy repo never reaches — is reachable in a test
|
|
31
|
+
* without a network, and the interesting ones are additionally driven against
|
|
32
|
+
* a real temp repo with a real rejecting remote in test/gate-auto-push.test.ts.
|
|
33
|
+
*
|
|
34
|
+
* Nothing here throws. The caller is a post-verdict bookkeeping step and must
|
|
35
|
+
* not be able to crash a run that has already passed; the point of the change
|
|
36
|
+
* is that the failure is now RECORDED rather than that it is now fatal.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { execFileSync } from "child_process";
|
|
40
|
+
|
|
41
|
+
/** One git invocation's result. `ok` is "exited zero", never "looks sensible". */
|
|
42
|
+
export interface Reading {
|
|
43
|
+
ok: boolean;
|
|
44
|
+
output: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Everything `classifyPush` is allowed to look at.
|
|
49
|
+
*
|
|
50
|
+
* `push` and `remote` are nullable because they describe steps that may never
|
|
51
|
+
* have been attempted — and "not attempted" has to be distinguishable from
|
|
52
|
+
* "attempted and came back empty", which is the distinction the empty catch
|
|
53
|
+
* destroyed.
|
|
54
|
+
*/
|
|
55
|
+
export interface PushReadings {
|
|
56
|
+
/** `git symbolic-ref --short HEAD`, or a failed reading on a detached HEAD. */
|
|
57
|
+
branch: Reading;
|
|
58
|
+
/** `git config --get branch.<b>.remote` — absent means no upstream is configured. */
|
|
59
|
+
remoteName: Reading;
|
|
60
|
+
/** `git config --get branch.<b>.merge` — the full ref name on the remote. */
|
|
61
|
+
remoteRef: Reading;
|
|
62
|
+
/** `git rev-list --count @{upstream}..HEAD`. */
|
|
63
|
+
ahead: Reading;
|
|
64
|
+
/** `git rev-parse HEAD`. */
|
|
65
|
+
localSha: Reading;
|
|
66
|
+
/** The push itself, or null when it was never attempted. */
|
|
67
|
+
push: Reading | null;
|
|
68
|
+
/** `git ls-remote <remote> <ref>`, or null when it was never attempted. */
|
|
69
|
+
remote: Reading | null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type PushOutcome =
|
|
73
|
+
/** The remote was read back and carries the local HEAD. The only success. */
|
|
74
|
+
| { kind: "pushed"; sha: string; remote: string; detail: string }
|
|
75
|
+
/** The upstream already had HEAD. Nothing was pushed and nothing is missing. */
|
|
76
|
+
| { kind: "nothing-to-push"; sha: string; detail: string }
|
|
77
|
+
/** No upstream is configured, so nothing on this branch has been pushed. */
|
|
78
|
+
| { kind: "no-upstream"; detail: string }
|
|
79
|
+
/** A git read failed or printed something that is not a count. UNMEASURED. */
|
|
80
|
+
| { kind: "unmeasured"; detail: string }
|
|
81
|
+
/** Commits are ahead and no push was attempted. */
|
|
82
|
+
| { kind: "not-attempted"; sha: string; ahead: number; detail: string }
|
|
83
|
+
/** The push ran and exited non-zero. */
|
|
84
|
+
| { kind: "rejected"; detail: string }
|
|
85
|
+
/** The push exited zero and the remote does not carry HEAD. */
|
|
86
|
+
| { kind: "unconfirmed"; sha: string; remoteSha: string | null; detail: string };
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The outcomes that mean a commit this run reported on may not be on the
|
|
90
|
+
* remote. Exported so the caller states the rule once rather than spelling out
|
|
91
|
+
* a list of string literals that drifts the first time a kind is added.
|
|
92
|
+
*/
|
|
93
|
+
export const OUTCOMES_LEAVING_WORK_LOCAL: ReadonlySet<PushOutcome["kind"]> = new Set([
|
|
94
|
+
"no-upstream",
|
|
95
|
+
"unmeasured",
|
|
96
|
+
"not-attempted",
|
|
97
|
+
"rejected",
|
|
98
|
+
"unconfirmed",
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
export function leftWorkLocal(outcome: PushOutcome): boolean {
|
|
102
|
+
return OUTCOMES_LEAVING_WORK_LOCAL.has(outcome.kind);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The sha `ls-remote` reports for a ref, or null if its output names none. */
|
|
106
|
+
export function parseLsRemoteSha(output: string, ref: string): string | null {
|
|
107
|
+
for (const line of output.split("\n")) {
|
|
108
|
+
const [sha, name] = line.split("\t");
|
|
109
|
+
if (!sha || !name) continue;
|
|
110
|
+
if (name.trim() === ref) return sha.trim();
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Turn the readings into exactly one outcome.
|
|
117
|
+
*
|
|
118
|
+
* Order matters and is the opposite of the original's: the cheap reads that
|
|
119
|
+
* can invalidate everything downstream are checked first, so a missing
|
|
120
|
+
* upstream is reported as a missing upstream rather than surfacing later as a
|
|
121
|
+
* confusing push failure.
|
|
122
|
+
*/
|
|
123
|
+
export function classifyPush(raw: PushReadings): PushOutcome {
|
|
124
|
+
// Every `detail` below interpolates git's own output, and every `detail`
|
|
125
|
+
// ends up in ship-evidence.json. Redacting once here rather than at each
|
|
126
|
+
// interpolation means a `detail` added later cannot forget to do it — and
|
|
127
|
+
// it holds for callers that build readings by hand, not only for the ones
|
|
128
|
+
// that came through `runner`.
|
|
129
|
+
const r = redactReadings(raw);
|
|
130
|
+
|
|
131
|
+
if (!r.localSha.ok || !/^[0-9a-f]{7,64}$/i.test(r.localSha.output.trim())) {
|
|
132
|
+
return {
|
|
133
|
+
kind: "unmeasured",
|
|
134
|
+
detail: `HEAD could not be read (${r.localSha.output.trim() || "no output"}), so there is ` +
|
|
135
|
+
`nothing to compare the remote against. UNMEASURED is not PASS.`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const sha = r.localSha.output.trim();
|
|
139
|
+
|
|
140
|
+
if (!r.branch.ok || r.branch.output.trim() === "") {
|
|
141
|
+
return {
|
|
142
|
+
kind: "no-upstream",
|
|
143
|
+
detail: "HEAD is detached, so there is no branch to push and nothing on it has been " +
|
|
144
|
+
"pushed. This is the worst case for this check, not an exemption from it.",
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const branch = r.branch.output.trim();
|
|
148
|
+
|
|
149
|
+
if (!r.remoteName.ok || r.remoteName.output.trim() === "" ||
|
|
150
|
+
!r.remoteRef.ok || r.remoteRef.output.trim() === "") {
|
|
151
|
+
return {
|
|
152
|
+
kind: "no-upstream",
|
|
153
|
+
detail: `branch ${branch} has no upstream configured, so nothing on it has been pushed. ` +
|
|
154
|
+
`A remediation re-push uses \`git push origin HEAD:<branch>\`, which does not set ` +
|
|
155
|
+
`upstream, so this is reachable on any run that needed one (#174).`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const remoteName = r.remoteName.output.trim();
|
|
159
|
+
const remoteRef = r.remoteRef.output.trim();
|
|
160
|
+
const upstream = `${remoteName} ${remoteRef}`;
|
|
161
|
+
|
|
162
|
+
if (!r.ahead.ok) {
|
|
163
|
+
return {
|
|
164
|
+
kind: "unmeasured",
|
|
165
|
+
detail: `branch ${branch} tracks ${upstream} but the ahead-count could not be read ` +
|
|
166
|
+
`(${r.ahead.output.trim() || "no output"}). A git invocation that fails for an unknown ` +
|
|
167
|
+
`reason says nothing about whether work is unpushed.`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
// `parseInt("") === NaN` and `NaN > 0 === false`, so the original read an
|
|
171
|
+
// empty or garbled count as "nothing to push" and skipped the push entirely.
|
|
172
|
+
// An exact-digits test is the whole fix for that path.
|
|
173
|
+
const aheadRaw = r.ahead.output.trim();
|
|
174
|
+
if (!/^\d+$/.test(aheadRaw)) {
|
|
175
|
+
return {
|
|
176
|
+
kind: "unmeasured",
|
|
177
|
+
detail: `the ahead-count against ${upstream} is not a number (${JSON.stringify(aheadRaw)}). ` +
|
|
178
|
+
`The previous code ran this through parseInt and compared NaN > 0, which is false, so ` +
|
|
179
|
+
`an unreadable count was indistinguishable from nothing to push.`,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (aheadRaw === "0") {
|
|
184
|
+
return {
|
|
185
|
+
kind: "nothing-to-push",
|
|
186
|
+
sha,
|
|
187
|
+
detail: `HEAD (${sha}) is not ahead of ${upstream}; nothing to push.`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (r.push === null) {
|
|
192
|
+
return {
|
|
193
|
+
kind: "not-attempted",
|
|
194
|
+
sha,
|
|
195
|
+
ahead: Number(aheadRaw),
|
|
196
|
+
detail: `${aheadRaw} commit(s) are ahead of ${upstream} and no push was attempted.`,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (!r.push.ok) {
|
|
201
|
+
return {
|
|
202
|
+
kind: "rejected",
|
|
203
|
+
detail: `git push to ${upstream} was rejected: ${r.push.output.trim() || "no output"}`,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// The push exited zero. That is a claim by git, not a reading of the remote,
|
|
208
|
+
// and this issue exists because the two were treated as the same thing.
|
|
209
|
+
if (r.remote === null || !r.remote.ok) {
|
|
210
|
+
return {
|
|
211
|
+
kind: "unconfirmed",
|
|
212
|
+
sha,
|
|
213
|
+
remoteSha: null,
|
|
214
|
+
detail: `git push to ${upstream} exited 0 and the remote could not be read back ` +
|
|
215
|
+
`(${r.remote ? r.remote.output.trim() || "no output" : "not attempted"}). An unconfirmed ` +
|
|
216
|
+
`push is not a successful push.`,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const remoteSha = parseLsRemoteSha(r.remote.output, remoteRef);
|
|
221
|
+
if (remoteSha !== sha) {
|
|
222
|
+
return {
|
|
223
|
+
kind: "unconfirmed",
|
|
224
|
+
sha,
|
|
225
|
+
remoteSha,
|
|
226
|
+
detail: `git push to ${upstream} exited 0 but ${remoteName} ${remoteRef} is at ` +
|
|
227
|
+
`${remoteSha ?? "no such ref"}, not the local HEAD ${sha}. The commit this run reported ` +
|
|
228
|
+
`on is not on the remote.`,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
kind: "pushed",
|
|
234
|
+
sha,
|
|
235
|
+
remote: upstream,
|
|
236
|
+
detail: `pushed ${aheadRaw} commit(s); ${upstream} confirmed at ${sha}.`,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Strip credentials out of anything git says before it is recorded.
|
|
242
|
+
*
|
|
243
|
+
* The push outcome's `detail` is written into ship-evidence.json, which is a
|
|
244
|
+
* durable artefact, and printed. git's failure output quotes the remote URL —
|
|
245
|
+
* `fatal: Authentication failed for 'https://user:ghp_…@github.com/o/r.git'`
|
|
246
|
+
* — so a push that fails to authenticate against an HTTPS remote with an
|
|
247
|
+
* embedded token would write that token into the artefact. The remote name
|
|
248
|
+
* read from `branch.<b>.remote` can be a URL for the same reason.
|
|
249
|
+
*
|
|
250
|
+
* Two independent rules rather than one, because they fail differently: the
|
|
251
|
+
* userinfo rule catches the structured case and the token rule catches a bare
|
|
252
|
+
* token that reached the output some other way.
|
|
253
|
+
*/
|
|
254
|
+
export function redactSecrets(text: string): string {
|
|
255
|
+
return text
|
|
256
|
+
// scheme://user:secret@host — the password is what matters, but the
|
|
257
|
+
// username is dropped too: a PAT is often supplied AS the username.
|
|
258
|
+
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi, "$1<redacted>@")
|
|
259
|
+
// Bare GitHub token forms, in case one arrives outside a URL.
|
|
260
|
+
.replace(/\b(gh[pousr]|github_pat)_[A-Za-z0-9_]{10,}/g, "<redacted-token>");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const redactReading = (x: Reading | null): Reading | null =>
|
|
264
|
+
x === null ? null : { ok: x.ok, output: redactSecrets(x.output) };
|
|
265
|
+
|
|
266
|
+
function redactReadings(r: PushReadings): PushReadings {
|
|
267
|
+
return {
|
|
268
|
+
branch: redactReading(r.branch)!,
|
|
269
|
+
remoteName: redactReading(r.remoteName)!,
|
|
270
|
+
remoteRef: redactReading(r.remoteRef)!,
|
|
271
|
+
ahead: redactReading(r.ahead)!,
|
|
272
|
+
localSha: redactReading(r.localSha)!,
|
|
273
|
+
push: redactReading(r.push),
|
|
274
|
+
remote: redactReading(r.remote),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function runner(cwd: string, env: NodeJS.ProcessEnv) {
|
|
279
|
+
return (args: string[], timeout: number): Reading => {
|
|
280
|
+
try {
|
|
281
|
+
const output = execFileSync("git", args, {
|
|
282
|
+
cwd,
|
|
283
|
+
env,
|
|
284
|
+
encoding: "utf-8",
|
|
285
|
+
timeout,
|
|
286
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
287
|
+
});
|
|
288
|
+
return { ok: true, output: redactSecrets(output ?? "") };
|
|
289
|
+
} catch (e: any) {
|
|
290
|
+
// stderr is where git explains a rejection, and the original threw it
|
|
291
|
+
// away. Both streams are kept because which one carries the reason
|
|
292
|
+
// depends on the subcommand.
|
|
293
|
+
const parts = [e?.stdout, e?.stderr, e?.message].filter(Boolean).map(String);
|
|
294
|
+
return { ok: false, output: redactSecrets(parts.join("\n").trim()) };
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Push, then read the remote back, then say what happened.
|
|
301
|
+
*
|
|
302
|
+
* `env` is injectable so a test can place a `git` shim ahead of the real one
|
|
303
|
+
* on PATH. That is how test/gate-auto-push.test.ts performs the mutation this
|
|
304
|
+
* change has to survive — a `git push` that exits 0 without doing anything —
|
|
305
|
+
* as a measurement on every run rather than a sentence in a PR body.
|
|
306
|
+
*
|
|
307
|
+
* It resolves the `git` binary, so it is worth saying what it is not: it is
|
|
308
|
+
* not a widening of trust. The only production caller passes `process.env`
|
|
309
|
+
* plus one flag, and anyone who can set `process.env` already controls PATH
|
|
310
|
+
* for the whole process. The shape of that call site is asserted in
|
|
311
|
+
* test/gate-auto-push.test.ts, so a later caller that funnels a value from a
|
|
312
|
+
* state file or an issue body into `env` is caught rather than assumed away.
|
|
313
|
+
*
|
|
314
|
+
* It does not throw. Every git invocation's failure becomes a `Reading` with
|
|
315
|
+
* `ok: false`, and `classifyPush` is total, so the worst case is an outcome of
|
|
316
|
+
* `unmeasured` — which `leftWorkLocal` counts as "work may be local". There is
|
|
317
|
+
* no input for which this reports success without having read the remote.
|
|
318
|
+
*/
|
|
319
|
+
export function verifiedPush(
|
|
320
|
+
cwd: string,
|
|
321
|
+
opts: { env?: NodeJS.ProcessEnv } = {},
|
|
322
|
+
): PushOutcome {
|
|
323
|
+
const env = opts.env ?? process.env;
|
|
324
|
+
const git = runner(cwd, env);
|
|
325
|
+
|
|
326
|
+
const localSha = git(["rev-parse", "HEAD"], 5000);
|
|
327
|
+
const branch = git(["symbolic-ref", "--short", "HEAD"], 5000);
|
|
328
|
+
const b = branch.output.trim();
|
|
329
|
+
const remoteName = b
|
|
330
|
+
? git(["config", "--get", `branch.${b}.remote`], 5000)
|
|
331
|
+
: { ok: false, output: "" };
|
|
332
|
+
const remoteRef = b
|
|
333
|
+
? git(["config", "--get", `branch.${b}.merge`], 5000)
|
|
334
|
+
: { ok: false, output: "" };
|
|
335
|
+
const ahead = git(["rev-list", "--count", "@{upstream}..HEAD"], 5000);
|
|
336
|
+
|
|
337
|
+
const base: PushReadings = {
|
|
338
|
+
branch, remoteName, remoteRef, ahead, localSha, push: null, remote: null,
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// Classify once with no push attempted. Everything that rules the push out —
|
|
342
|
+
// a detached HEAD, no upstream, an unreadable count, nothing to push — is
|
|
343
|
+
// already decided here, and re-deriving those conditions below is how two
|
|
344
|
+
// copies of the same rule drift apart. `not-attempted` is the one outcome
|
|
345
|
+
// this call cannot be sure of, because it is the one a push would change.
|
|
346
|
+
const before = classifyPush(base);
|
|
347
|
+
if (before.kind !== "not-attempted") return before;
|
|
348
|
+
|
|
349
|
+
const push = git(
|
|
350
|
+
["push", "--", remoteName.output.trim(), `HEAD:${remoteRef.output.trim()}`],
|
|
351
|
+
30_000,
|
|
352
|
+
);
|
|
353
|
+
const remote = push.ok
|
|
354
|
+
? git(["ls-remote", "--", remoteName.output.trim(), remoteRef.output.trim()], 20_000)
|
|
355
|
+
: null;
|
|
356
|
+
|
|
357
|
+
return classifyPush({ ...base, push, remote });
|
|
358
|
+
}
|