mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-28 10:54:30 +01:00
Merge origin/main into fix/3360-autopilot-refusal-names-process; v1.91.199.0 stamp (#3377 slot 3)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
commit
c56f4d05a9
87 files changed
+3686
-388
No files matched your search
+75
-2
@@ -115,6 +115,76 @@ export function normalizeChangelog(text: string): string {
|
||||
return [parsed.header.join('\n').replace(/\n+$/, ''), ...sections].join('\n\u0000');
|
||||
}
|
||||
|
||||
/**
|
||||
* A merged-in head's CHANGELOG, however its conflict was resolved: why it is
|
||||
* not main's CHANGELOG with the PR's own entry above it, or null. Main's
|
||||
* header and every main section must follow unchanged and in order, and the
|
||||
* sections above them may hold only lines the PR itself added (`authored`,
|
||||
* the + lines of its pin's CHANGELOG diff), so a hand resolve can drop
|
||||
* damage but never add text the train gate did not carry.
|
||||
*/
|
||||
export function ownEntryAboveMain(head: string, main: string, authored: ReadonlySet<string>): string | null {
|
||||
const h = parseChangelog(head);
|
||||
const m = parseChangelog(main);
|
||||
const trim = (lines: string[]) => { const out = [...lines]; while (out.length && !out[out.length - 1]!.trim()) out.pop(); return out.join('\n'); };
|
||||
if (trim(h.header) !== trim(m.header)) return 'the header differs from main';
|
||||
const own = h.sections.length - m.sections.length;
|
||||
if (own < 0) return `it has ${h.sections.length} sections, main has ${m.sections.length}`;
|
||||
const moved = m.sections.findIndex((s, i) => trim(s.lines) !== trim(h.sections[own + i]!.lines));
|
||||
if (moved >= 0) return `main's ${m.sections[moved]!.heading.trim()} is not carried unchanged below the PR's entry`;
|
||||
const mainKeys = new Set(m.sections.map(s => s.version ?? 'Unreleased'));
|
||||
const clash = h.sections.slice(0, own).find(s => mainKeys.has(s.version ?? 'Unreleased'));
|
||||
if (clash) return `${clash.heading.trim()} is headed twice`;
|
||||
const added = h.sections.slice(0, own).flatMap(s => s.lines.slice(1)).find(l => l.trim() && !authored.has(l));
|
||||
return added === undefined ? null : `the PR's entry holds a line its pin never added: ${JSON.stringify(added.slice(0, 80))}`;
|
||||
}
|
||||
|
||||
const MIN_BLOCK_CHARS = 12;
|
||||
|
||||
/** Paragraph blocks of a section's entry text (heading lines dropped), long enough to identify one entry. */
|
||||
function entryBlocks(s: ChangelogSection): string[] {
|
||||
const blocks: string[] = [];
|
||||
let run: string[] = [];
|
||||
const flush = () => { const text = run.join('\n').trim(); if (text.length >= MIN_BLOCK_CHARS) blocks.push(text); run = []; };
|
||||
for (const line of s.lines.slice(1)) {
|
||||
if (!line.trim() || line.startsWith('#')) flush();
|
||||
else run.push(line);
|
||||
}
|
||||
flush();
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why one side of a CHANGELOG merge damaged released history, or null. A
|
||||
* side damages it when it lacks a released heading the merge base carries
|
||||
* (dropped, or renamed), or when a section only that side carries holds a
|
||||
* paragraph of a released entry the other side carries (a released heading
|
||||
* replaced, so its body reads as part of the section above it; #3345).
|
||||
*/
|
||||
export function changelogDamage(ours: string, theirs: string, base?: string): string | null {
|
||||
const sides = [{ name: 'ours', parsed: parseChangelog(ours) }, { name: 'theirs', parsed: parseChangelog(theirs) }];
|
||||
const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);
|
||||
if (base !== undefined) {
|
||||
const released = parseChangelog(base).sections.filter(s => !s.unreleased).map(key);
|
||||
for (const side of sides) {
|
||||
const has = new Set(side.parsed.sections.map(key));
|
||||
const missing = released.find(v => !has.has(v));
|
||||
if (missing) return `${side.name} drops released heading ${missing} that the merge base carries`;
|
||||
}
|
||||
}
|
||||
for (const [i, side] of sides.entries()) {
|
||||
const other = sides[1 - i]!.parsed.sections;
|
||||
const otherKeys = new Set(other.map(key));
|
||||
const releasedText = new Map<string, string>();
|
||||
for (const s of other.filter(s => !s.unreleased)) for (const b of entryBlocks(s)) releasedText.set(b, s.version!);
|
||||
for (const s of side.parsed.sections.filter(s => !otherKeys.has(key(s)))) {
|
||||
const hit = entryBlocks(s).find(b => releasedText.has(b));
|
||||
if (hit) return `${side.name}'s ${key(s)} section holds released ${releasedText.get(hit)} text (${JSON.stringify(hit.slice(0, 60))}); a released heading was dropped or renamed`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate-ahead merge of two CHANGELOGs that conflict textually but not
|
||||
* semantically: the predecessor's header and sections, with the branch's own
|
||||
@@ -122,9 +192,12 @@ export function normalizeChangelog(text: string): string {
|
||||
* branch's top section carries the same version heading as a predecessor
|
||||
* section with a different body (both took the same tentative stamp), the
|
||||
* branch's entry is kept under `[Unreleased]` so the restamp re-heads it.
|
||||
* Both sides carrying `[Unreleased]` is a real conflict and returns null.
|
||||
* Both sides carrying `[Unreleased]` is a real conflict and returns null, and
|
||||
* so is damage to released history (`changelogDamage`): null means a hand
|
||||
* resolve, never a merge that carries the damage through.
|
||||
*/
|
||||
export function mergeChangelogs(ours: string, theirs: string): string | null {
|
||||
export function mergeChangelogs(ours: string, theirs: string, base?: string): string | null {
|
||||
if (changelogDamage(ours, theirs, base)) return null;
|
||||
const a = parseChangelog(ours);
|
||||
const b = parseChangelog(theirs);
|
||||
const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
*/
|
||||
|
||||
import { spawnSync } from "child_process";
|
||||
import { existsSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { lstatSync, statSync } from "fs";
|
||||
import { dirname, join } from "path";
|
||||
import { mergedStateRoots, resolveStateRoot } from "./state-root";
|
||||
|
||||
export type RepoPolicyTierValue = "deny" | "read-only" | "read-write" | "none";
|
||||
@@ -46,9 +46,36 @@ export function repoPolicyStorePath(env: NodeJS.ProcessEnv = process.env): strin
|
||||
/**
|
||||
* No store on disk = no policy was ever set (the fast path — no subprocess).
|
||||
* The ~/.gstack store counts too: its deny tiers merge into every state root.
|
||||
* Only confirmed absence is "no store": ENOENT whose nearest existing
|
||||
* ancestor resolves (so no dangling symlink cut the walk short). A dangling
|
||||
* symlink at the store or above it, a non-directory component, or a path that
|
||||
* cannot be checked (an unsearchable directory) counts as a store, so the
|
||||
* caller spawns the script and its own fail-closed rules apply.
|
||||
*/
|
||||
export function hasRepoPolicyStore(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return mergedStateRoots(env).some((root) => existsSync(join(root, "gbrain-repo-policy.json")));
|
||||
return mergedStateRoots(env).some((root) => {
|
||||
let path = join(root, "gbrain-repo-policy.json");
|
||||
try {
|
||||
lstatSync(path);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== "ENOENT") return true;
|
||||
}
|
||||
for (let up = dirname(path); up !== path; path = up, up = dirname(up)) {
|
||||
try {
|
||||
lstatSync(up);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
statSync(up);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/** The bash script that owns the store — resolved relative to this file (lib/ → bin/), never cwd. */
|
||||
@@ -94,6 +121,50 @@ export function repoPolicyTier(
|
||||
return { tier: "none", error: "unreadable" }; // unexpected output — a read failure, not a tier
|
||||
}
|
||||
|
||||
export interface MemorableRecallPolicy extends RepoPolicyResult {
|
||||
/**
|
||||
* True only when the tier is `read-only` and the store opts this remote in
|
||||
* to Memorable recall. Never true alongside `error` or any other tier.
|
||||
*/
|
||||
memorableOptIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier plus the per-remote Memorable recall opt-in, via
|
||||
* `gstack-gbrain-repo-policy memorable get <url>` (one spawn). Unlike
|
||||
* repoPolicyTier, the script never quarantines a corrupt store on this path,
|
||||
* so a corrupt store reads as `unreadable` instead of as "no policy".
|
||||
* Fast paths and failure classification match repoPolicyTier; anything but
|
||||
* exactly "<tier>\t<allow|off>" is `unreadable`. POLARITY IS THE CALLER'S.
|
||||
*/
|
||||
export function memorableRecallPolicy(
|
||||
url: string | null,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
timeoutMs: number = 10_000,
|
||||
): MemorableRecallPolicy {
|
||||
if (!hasRepoPolicyStore(env)) return { tier: "none", memorableOptIn: false };
|
||||
if (!url) return { tier: "none", memorableOptIn: false };
|
||||
const [cmd, args]: [string, string[]] =
|
||||
process.platform === "win32"
|
||||
? ["bash", [POLICY_SCRIPT, "memorable", "get", url]]
|
||||
: [POLICY_SCRIPT, ["memorable", "get", url]];
|
||||
const res = spawnSync(cmd, args, {
|
||||
encoding: "utf-8",
|
||||
timeout: Math.max(1, timeoutMs),
|
||||
env: { ...env } as NodeJS.ProcessEnv,
|
||||
});
|
||||
if (res.error) {
|
||||
const code = (res.error as NodeJS.ErrnoException).code;
|
||||
return { tier: "none", memorableOptIn: false, error: code === "ENOENT" ? "spawn-failed" : "unreadable" };
|
||||
}
|
||||
const unreadable: MemorableRecallPolicy = { tier: "none", memorableOptIn: false, error: "unreadable" };
|
||||
if (res.status !== 0) return unreadable;
|
||||
const match = /^(deny|read-only|read-write|unset)\t(allow|off)\n?$/.exec(res.stdout || "");
|
||||
if (!match) return unreadable;
|
||||
const tier = match[1] === "unset" ? "none" : (match[1] as RepoPolicyTierValue);
|
||||
return { tier, memorableOptIn: tier === "read-only" && match[2] === "allow" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk trust-tier lookup via `gstack-gbrain-repo-policy get --batch` — ONE
|
||||
* spawn total for the whole url list (memory-ingest checks every distinct
|
||||
|
||||
@@ -178,7 +178,6 @@ function openaiLifecycle(text: string): ParsedSource {
|
||||
if (!upcoming || !modelTables.length) throw new Error('missing-deprecation-tables');
|
||||
const lifecycle = modelTables.flatMap(table => table.slice(1).flatMap(row => {
|
||||
if (/^(?:Videos API|Assistants API|OpenAI-Beta: |New fine-tuning training on )/.test(row[1]) || row[1].startsWith('`/')) return [];
|
||||
if (!row[1].startsWith('`')) throw new Error('unrecognized-deprecated-model-cell');
|
||||
const floor = row[0].startsWith('at earliest ');
|
||||
const date = lifecycleDate(row[0].replace(/^at earliest /, ''));
|
||||
if (!date) throw new Error('missing-shutdown-date');
|
||||
|
||||
@@ -263,7 +263,8 @@ export function classifyOutsideReview(input: OutsideReviewInput): OutsideReviewC
|
||||
}
|
||||
if (!reviewed) return result(blocking ? 'findings' : 'clean');
|
||||
const unparsed = firstUnparsed(code);
|
||||
const notReady = !findings.highest && verdictNotReady(plainCode);
|
||||
// A last explicit not-ready blocks even when the only parsed severities are advisory.
|
||||
const notReady = verdictNotReady(plainCode);
|
||||
if (blocking || notReady) return { ...result('findings'), ...(unparsed ? { unparsed } : {}) };
|
||||
if (unparsed) return { ...result('unverified', 'unparsed_severity', unparsed), unparsed };
|
||||
if ((input.gate === 'structured' || input.gate === 'review') && !findings.highest && !concludesNoFindings(code)) {
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: s
|
||||
'',
|
||||
renderDecisions(inputs, page).trimEnd(),
|
||||
'',
|
||||
`Full review: ${record}${recordNote}. Answer with \`gstack-autoplan answer --out <dir> --gate-rev ${inputs.gate.gate_rev} --reply "<all | d3b uc1a | all except d3b>" --by human\`.`,
|
||||
`Full review: ${record}${recordNote}. Answer with \`gstack-autoplan answer --out <dir> --gate-rev ${inputs.gate.gate_rev} --reply "<rec | rec except d3b | d3b uc1a | as-is>" --by human\`.`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
+114
-17
@@ -16,9 +16,10 @@ import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { baseInputs, sha256 } from '../context';
|
||||
import { PREGATE_CONFIG_PATH } from '../config';
|
||||
import { isDeviceDart, readRepoFile } from '../import-graph';
|
||||
import { isDeviceDart, listRepoFiles, readRepoFile } from '../import-graph';
|
||||
import { selectLanes, type Selection } from '../lane-selection';
|
||||
import { launchRuntime } from '../runtime';
|
||||
import { cargoModel, type CargoModel } from '../rust';
|
||||
import { adapterFor, readRange, supervise, type Counter, type Supervised } from '../supervise';
|
||||
import { matchesAny } from '../../ship-policy';
|
||||
import type { CheckDef, CheckResult, PregateContext, RemoteObligation } from '../types';
|
||||
@@ -42,21 +43,24 @@ export function detectRunner(ctx: Pick<PregateContext, 'config' | 'repoRoot'>, f
|
||||
/** One runner invocation: `files` relative to `cwd` (repo-relative, `''` for the root). */
|
||||
export interface RunGroup { runner: string; cwd: string; files: string[] }
|
||||
|
||||
/** The nearest directory at or above `file` holding a pubspec.yaml, repo-relative; null outside any Dart package. `seen` memoises per directory. */
|
||||
function dartRoot(repoRoot: string, file: string, seen: Map<string, string | null>): string | null {
|
||||
/** The nearest directory at or above `file` holding `marker`, repo-relative; null when none does. `seen` memoises per directory (one map per marker). */
|
||||
function nearestRoot(repoRoot: string, file: string, marker: string, seen: Map<string, string | null>): string | null {
|
||||
const walked: string[] = [];
|
||||
let found: string | null = null;
|
||||
for (let d = path.posix.dirname(file); ; d = path.posix.dirname(d)) {
|
||||
const rel = d === '.' ? '' : d;
|
||||
if (seen.has(rel)) { found = seen.get(rel)!; break; }
|
||||
walked.push(rel);
|
||||
if (fs.existsSync(path.join(repoRoot, rel, 'pubspec.yaml'))) { found = rel; break; }
|
||||
if (fs.existsSync(path.join(repoRoot, rel, marker))) { found = rel; break; }
|
||||
if (d === '.' || d === '/' || d === '') break;
|
||||
}
|
||||
for (const w of walked) seen.set(w, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The nearest directory at or above `file` holding a pubspec.yaml, repo-relative; null outside any Dart package. */
|
||||
function dartRoot(repoRoot: string, file: string, seen: Map<string, string | null>): string | null { return nearestRoot(repoRoot, file, 'pubspec.yaml', seen); }
|
||||
|
||||
/** An fvm pin (`.fvmrc` or `.fvm/fvm_config.json`) at the package root `root` or any ancestor up to the repo root. */
|
||||
function fvmPinned(repoRoot: string, root: string): boolean {
|
||||
for (let d = root; ; d = path.posix.dirname(d)) {
|
||||
@@ -72,6 +76,9 @@ function fvmPinnedFor(repoRoot: string, files: readonly string[]): boolean {
|
||||
return files.some(f => { const root = f.endsWith('.dart') ? dartRoot(repoRoot, f, seen) : null; return root !== null && fvmPinned(repoRoot, root); });
|
||||
}
|
||||
|
||||
/** Whether `bin` is on the PATH of `env` (the PATH the runner will get). */
|
||||
const onPath = (bin: string, env: NodeJS.ProcessEnv) => !!Bun.which(bin, { PATH: env.PATH ?? '' });
|
||||
|
||||
/**
|
||||
* `flutter test` for a package on the Flutter SDK, else `dart test`; through fvm
|
||||
* when the package or an ancestor up to the repo root pins one and fvm is on PATH. `missing` names the tool when
|
||||
@@ -82,48 +89,129 @@ export function dartRunner(repoRoot: string, root: string, env: NodeJS.ProcessEn
|
||||
const pubspec = readRepoFile(repoRoot, path.posix.join(root, 'pubspec.yaml')) ?? '';
|
||||
// `sdk: flutter` (the key optionally quoted) under any dependency name (flutter, flutter_test, ...), block style or inside a flow mapping a key opens, comments stripped.
|
||||
const tool = /^[ \t]*(['"]?)sdk\1:[ \t]*['"]?flutter\b|^[ \t]*[\w-]+:[ \t]*\{(?:[^\n]*[{,])?[ \t]*(['"]?)sdk\2:[ \t]*['"]?flutter\b/m.test(pubspec.replace(/(^|\s)#.*$/gm, '$1')) ? 'flutter' : 'dart';
|
||||
const onPath = (bin: string) => !!Bun.which(bin, { PATH: env.PATH ?? '' });
|
||||
const fvm = fvmPinned(repoRoot, root) && onPath('fvm');
|
||||
if (!fvm && !onPath(tool)) return { missing: tool };
|
||||
const fvm = fvmPinned(repoRoot, root) && onPath('fvm', env);
|
||||
if (!fvm && !onPath(tool, env)) return { missing: tool };
|
||||
return { runner: `${fvm ? 'fvm ' : ''}${tool} test {files}` };
|
||||
}
|
||||
|
||||
/** The run plan: the groups that can run, the files no runner claims, Dart SDKs missing from PATH, and `.dart` files with no pubspec.yaml above. */
|
||||
/**
|
||||
* `cargo test -p <name>` for a crate (cargo runs a crate's tests, never a file list), or the missing tool when cargo is
|
||||
* not on PATH. The name comes from the repo's Cargo.toml and reaches a shell and the `{files}` expansion: a name outside
|
||||
* Cargo's grammar (letters, digits, `_`, `-`) gets no runner (null), and a valid one is still quoted like every file and cwd.
|
||||
*/
|
||||
function cargoRunner(name: string, env: NodeJS.ProcessEnv): { runner: string } | { missing: string } | null {
|
||||
if (!/^[\p{ID_Continue}-]+$/u.test(name)) return null;
|
||||
return onPath('cargo', env) ? { runner: `cargo test -p ${quote(name)}` } : { missing: 'cargo' };
|
||||
}
|
||||
|
||||
type PackageJson = { packageManager?: string; devDependencies?: Record<string, string>; dependencies?: Record<string, string>; scripts?: Record<string, string> };
|
||||
function readPackageJson(repoRoot: string, dir: string): PackageJson | null {
|
||||
try { return JSON.parse(readRepoFile(repoRoot, path.posix.join(dir, 'package.json')) ?? 'null'); } catch { return null; }
|
||||
}
|
||||
|
||||
const LOCKFILES: Array<[string, string]> = [['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['package-lock.json', 'npm'], ['npm-shrinkwrap.json', 'npm']];
|
||||
const PM_EXEC: Record<string, string> = { pnpm: 'pnpm exec', yarn: 'yarn', bun: 'bun x', npm: 'npx' };
|
||||
|
||||
/** The package manager for a package: the first `packageManager` field or lockfile from its directory up to the repo root; npm when none. */
|
||||
function packageManager(repoRoot: string, dir: string): string {
|
||||
for (let d = dir; ; d = path.posix.dirname(d)) {
|
||||
const rel = d === '.' ? '' : d;
|
||||
const declared = /^(pnpm|yarn|bun|npm)@/.exec(readPackageJson(repoRoot, rel)?.packageManager ?? '')?.[1];
|
||||
if (declared) return declared;
|
||||
const lock = LOCKFILES.find(([f]) => fs.existsSync(path.join(repoRoot, rel, f)));
|
||||
if (lock) return lock[1];
|
||||
if (rel === '') return 'npm';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The runner a nested package (not the repo root) declares for itself: vitest
|
||||
* or jest in its dependencies or its `test` script, through the package manager
|
||||
* its `packageManager` field or nearest lockfile names; null when it declares
|
||||
* neither, so its files stay with the root runner. `missing` names a package
|
||||
* manager that is not on PATH.
|
||||
*/
|
||||
function packageRunner(repoRoot: string, dir: string, env: NodeJS.ProcessEnv): { runner: string } | { missing: string } | null {
|
||||
const pkg = readPackageJson(repoRoot, dir);
|
||||
if (!pkg) return null;
|
||||
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
||||
const script = pkg.scripts?.test ?? '';
|
||||
const tool = deps.vitest || /\bvitest\b/.test(script) ? 'vitest run' : deps.jest || /\bjest\b/.test(script) ? 'jest' : null;
|
||||
if (!tool) return null;
|
||||
const pm = packageManager(repoRoot, dir);
|
||||
const bin = pm === 'npm' ? 'npx' : pm;
|
||||
if (!onPath(bin, env)) return { missing: bin };
|
||||
return { runner: `${PM_EXEC[pm]} ${tool} {files}` };
|
||||
}
|
||||
|
||||
/** The run plan: the groups that can run, the files no runner claims, tools missing from PATH, and `.dart` files with no pubspec.yaml above. */
|
||||
export interface RunPlan { groups: RunGroup[]; unclaimed: string[]; missing: string[]; noPubspec: string[] }
|
||||
|
||||
/**
|
||||
* The invocations that run `files`. A declared runner takes every file. Otherwise
|
||||
* Dart tests run from their own package root (a sub-package's imports resolve
|
||||
* against its own pubspec), and the rest go to the detected runner. Files no
|
||||
* runner claims (a Dart SDK missing from PATH, a `.dart` file outside any
|
||||
* package, no detected runner) are `unclaimed`: the lane is `incomplete`, never a pass.
|
||||
* against its own pubspec); Rust tests run per crate as `cargo test -p <name>`
|
||||
* from the crate's workspace root; JS/TS tests owned by a nested package that
|
||||
* declares vitest or jest run from that package; the rest go to the detected
|
||||
* runner from the repo root. Files no runner claims (a tool missing from PATH,
|
||||
* a `.dart` file outside any package, a `.rs` file outside any crate or in a
|
||||
* crate whose name Cargo would reject, no detected runner) are `unclaimed`: the lane is `incomplete`, never a pass.
|
||||
*/
|
||||
export function planRuns(ctx: PregateContext, files: readonly string[]): RunPlan {
|
||||
if (ctx.config.runner) return { groups: [{ runner: ctx.config.runner, cwd: '', files: [...files] }], unclaimed: [], missing: [], noPubspec: [] };
|
||||
const groups: RunGroup[] = [];
|
||||
const dart = new Map<string, string[]>();
|
||||
const cargo = new Map<string, { name: string; cwd: string; files: string[] }>();
|
||||
const packages = new Map<string, string[]>();
|
||||
const seen = new Map<string, string | null>();
|
||||
const seenPackage = new Map<string, string | null>();
|
||||
let model: CargoModel | null = null;
|
||||
const pkgRunners = new Map<string, ReturnType<typeof packageRunner>>();
|
||||
const rest: string[] = [];
|
||||
const noPubspec: string[] = [];
|
||||
const unclaimed: string[] = [];
|
||||
const missing = new Set<string>();
|
||||
const add = <T>(map: Map<string, T[]>, key: string, value: T) => { let list = map.get(key); if (!list) map.set(key, (list = [])); list.push(value); };
|
||||
const under = (root: string, f: string) => (root ? f.slice(root.length + 1) : f);
|
||||
for (const f of files) {
|
||||
if (f.endsWith('.rs')) {
|
||||
model ??= cargoModel(listRepoFiles(ctx.repoRoot), rel => readRepoFile(ctx.repoRoot, rel));
|
||||
const crate = model.crateOf(f);
|
||||
const cwd = crate?.workspace ?? null;
|
||||
if (!crate || cwd === null) { unclaimed.push(f); continue; }
|
||||
const key = `${cwd}\0${crate.name}`;
|
||||
if (!cargo.has(key)) cargo.set(key, { name: crate.name, cwd, files: [] });
|
||||
cargo.get(key)!.files.push(under(cwd, f));
|
||||
continue;
|
||||
}
|
||||
const pkg = /\.[cm]?[jt]sx?$/.test(f) ? nearestRoot(ctx.repoRoot, f, 'package.json', seenPackage) : null;
|
||||
if (pkg) {
|
||||
if (!pkgRunners.has(pkg)) pkgRunners.set(pkg, packageRunner(ctx.repoRoot, pkg, ctx.env));
|
||||
const r = pkgRunners.get(pkg);
|
||||
if (r && 'missing' in r) { missing.add(r.missing); unclaimed.push(f); continue; }
|
||||
if (r) { add(packages, pkg, under(pkg, f)); continue; }
|
||||
}
|
||||
if (!f.endsWith('.dart')) { rest.push(f); continue; }
|
||||
const root = dartRoot(ctx.repoRoot, f, seen);
|
||||
if (root === null) { noPubspec.push(f); continue; }
|
||||
let list = dart.get(root);
|
||||
if (!list) dart.set(root, (list = []));
|
||||
list.push(root ? f.slice(root.length + 1) : f);
|
||||
add(dart, root, under(root, f));
|
||||
}
|
||||
const unclaimed: string[] = [];
|
||||
const missing = new Set<string>();
|
||||
for (const [root, list] of [...dart].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
const r = dartRunner(ctx.repoRoot, root, ctx.env);
|
||||
if ('missing' in r) { missing.add(r.missing); unclaimed.push(...list.map(f => (root ? `${root}/${f}` : f))); } else groups.push({ runner: r.runner, cwd: root, files: list });
|
||||
}
|
||||
for (const [, c] of [...cargo].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
const r = cargoRunner(c.name, ctx.env);
|
||||
if (r && 'runner' in r) { groups.push({ runner: r.runner, cwd: c.cwd, files: c.files }); continue; }
|
||||
if (r) missing.add(r.missing);
|
||||
unclaimed.push(...c.files.map(f => (c.cwd ? `${c.cwd}/${f}` : f)));
|
||||
}
|
||||
if (rest.length) {
|
||||
const runner = detectRunner(ctx, rest);
|
||||
if (runner) groups.push({ runner, cwd: '', files: rest });
|
||||
else unclaimed.push(...rest);
|
||||
}
|
||||
for (const [root, list] of [...packages].sort(([a], [b]) => a.localeCompare(b))) groups.push({ runner: (pkgRunners.get(root) as { runner: string }).runner, cwd: root, files: list });
|
||||
return { groups, unclaimed: [...unclaimed, ...noPubspec], missing: [...missing].sort(), noPubspec };
|
||||
}
|
||||
|
||||
@@ -153,9 +241,18 @@ function parseDart(output: string): RunnerSummary | null {
|
||||
return d ? { ran: Number(d[1]) + Number(d[2] ?? 0), failed: Number(d[2] ?? 0) } : null;
|
||||
}
|
||||
|
||||
/** The runner's own summary line: bun, node --test, vitest, jest, pytest, bats, dart/flutter test. A bats or dart/flutter runner's summary is tried first; for any other runner those formats are a last resort. `ran: null` when not recognised. Colour codes are dropped and a carriage return ends a line, so a coloured or redrawn verdict still reads. */
|
||||
/** cargo test: one `test result: ok|FAILED. N passed; M failed; …` line per test binary (unit tests, each integration test, doc-tests), summed; ignored and filtered-out tests did not run. */
|
||||
function parseCargo(output: string): RunnerSummary | null {
|
||||
const lines = [...output.matchAll(/^test result: \w+\. (\d+) passed; (\d+) failed;/gm)];
|
||||
if (!lines.length) return null;
|
||||
const failed = lines.reduce((n, m) => n + Number(m[2]), 0);
|
||||
return { ran: lines.reduce((n, m) => n + Number(m[1]), 0) + failed, failed };
|
||||
}
|
||||
|
||||
/** The runner's own summary line: bun, node --test, vitest, jest, pytest, bats, dart/flutter test, cargo test. A bats, dart/flutter or cargo runner's summary is tried first (cargo's only there: its `N passed` lines would misread as another runner's); for any other runner the bats and dart formats are a last resort. `ran: null` when not recognised. Colour codes are dropped and a carriage return ends a line, so a coloured or redrawn verdict still reads. */
|
||||
export function parseSummary(raw: string, runner = ''): RunnerSummary {
|
||||
const output = raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r/g, '\n');
|
||||
if (/(?<![\w-])cargo\s+test(?![\w-])/.test(runner)) return parseCargo(output) ?? { ran: null, failed: null };
|
||||
if (/(?<![\w-])bats(?![\w-])/.test(runner)) { const b = parseBats(output); if (b) return b; }
|
||||
const dartRun = /(?<![\w-])(?:dart|flutter)(?![\w-])/.test(runner);
|
||||
if (dartRun) { const d = parseDart(output); if (d) return d; }
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
* 3. the `bin/<name>` → `test/<name>*.test.*` convention (with and without
|
||||
* the `gstack-` prefix);
|
||||
* 4. explicit `.gstack/pregate.json` `dependencies` declarations;
|
||||
* 5. in a Django project, the files Django loads by name (lib/pregate/django.ts).
|
||||
* 5. in a Django project, the files Django loads by name (lib/pregate/django.ts);
|
||||
* 6. in a Cargo crate, every `.rs` file and the Cargo.toml select the crate's
|
||||
* tests and its dependents' (lib/pregate/rust.ts); in-source
|
||||
* `#[cfg(test)]` files and `<crate>/tests/` files are the tests.
|
||||
* Dart directives (`import`/`export`/`part`, conditional URIs included) resolve
|
||||
* `package:<name>/x` through every tracked pubspec.yaml to `<root>/lib/x`.
|
||||
* Uncertainty selects more tests, never fewer: a dependency on a directory
|
||||
@@ -25,6 +28,7 @@ import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { matchesAny } from '../ship-policy';
|
||||
import { djangoEdges } from './django';
|
||||
import { rustEdges } from './rust';
|
||||
|
||||
export const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|py|rb|sh|bash|go|rs|dart)$/;
|
||||
export const TEST_FILE_RE = /(?:^|\/)(?:test|tests|spec|__tests__)\/.*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]*\.py$|_test\.(?:py|go|rb)$|_spec\.rb$|(?:^|\/)[^/]*\.bats$|(?:^|\/)test\/(?:.*\/)?[^/]*_test\.dart$/;
|
||||
@@ -47,7 +51,7 @@ const scanner = new Bun.Transpiler({ loader: 'tsx' });
|
||||
// that matches more text only gains an edge when it resolves to a repo file.
|
||||
const QUOTED = /['"`]([A-Za-z0-9_@][A-Za-z0-9_./@()[\]+-]*)['"`]/g;
|
||||
const JOIN = /\bjoin\(([^()]*)\)/g;
|
||||
const RESOLVE_EXT = ['', '.ts', '.tsx', '.js', '.mjs', '.cjs', '/index.ts', '/index.js'];
|
||||
const RESOLVE_EXT = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '/index.ts', '/index.tsx', '/index.js', '/index.jsx', '/index.mjs'];
|
||||
// A statement starts a line or follows `;` or a compound statement's `:`. The module spec is
|
||||
// non-empty and starts with a dot or a word character, so no two repetitions can share a dot or a space.
|
||||
const PY_IMPORT = /(?:^|[;:])[ \t\f]*(?:from[ \t]+(\.+(?:\w[\w.]*)?|\w[\w.]*)[ \t]+import[ \t]+(\([^)]*\)|[^\n;]+)|import[ \t]+([^\n;]+))/gm;
|
||||
@@ -465,6 +469,9 @@ export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph {
|
||||
for (const { target, via } of referencesIn(files, dirs, rel, source, config, graph.tests.has(rel) ? unresolved : undefined, packages)) addEdge(graph, target, rel, via);
|
||||
if (unresolved.length) graph.unresolved!.set(rel, unresolved);
|
||||
}
|
||||
const rust = rustEdges(all, rel => readRepoFile(repoRoot, rel, maxBytes));
|
||||
for (const t of rust.tests) graph.tests.add(t);
|
||||
for (const e of rust.edges) addEdge(graph, e.dependency, e.dependent, e.via);
|
||||
const django = djangoEdges({ files: [...files], tests: graph.tests, read: rel => pySources.get(rel) ?? readRepoFile(repoRoot, rel, maxBytes), code: pythonCode, resolveDotted: dotted => pythonPatchTarget(files, dotted) });
|
||||
for (const e of django) addEdge(graph, e.dependency, e.dependent, 'framework');
|
||||
for (const test of graph.tests) {
|
||||
|
||||
@@ -72,13 +72,14 @@ export function draftConfig(repoRoot: string): InitDraft {
|
||||
}
|
||||
|
||||
const groups = new Map<string, string[]>();
|
||||
for (const t of tests) { const lang = t.endsWith('.dart') ? 'dart' : t.endsWith('.py') ? 'python' : /\.[cm]?[jt]sx?$/.test(t) ? 'javascript' : 'other'; groups.set(lang, [...(groups.get(lang) ?? []), t]); }
|
||||
for (const t of tests) { const lang = t.endsWith('.dart') ? 'dart' : t.endsWith('.rs') ? 'rust' : t.endsWith('.py') ? 'python' : /\.[cm]?[jt]sx?$/.test(t) ? 'javascript' : 'other'; groups.set(lang, [...(groups.get(lang) ?? []), t]); }
|
||||
const notes = [...groups].map(([lang, list]) => {
|
||||
if (lang === 'dart') return `${list.length} Dart test file(s) run per package with flutter test or dart test`;
|
||||
if (lang === 'rust') return `${list.length} Rust test file(s) run per crate with cargo test -p`;
|
||||
const runner = detectRunner({ repoRoot, config: DEFAULT_CONFIG }, list);
|
||||
return runner ? `${lang} tests detected at run time: ${runner}` : `no runner detected for ${list.length} ${lang} test file(s); set runner (with {files})`;
|
||||
});
|
||||
const mixed = [...groups.keys()].filter(l => l !== 'dart').length > 1 ? '; a selection mixing these languages needs runner set' : '';
|
||||
const mixed = [...groups.keys()].filter(l => l !== 'dart' && l !== 'rust').length > 1 ? '; a selection mixing these languages needs runner set' : '';
|
||||
const runnerNote = notes.length ? notes.join('; ') + mixed : 'no test files found';
|
||||
|
||||
const selectionTodo = discoverLanes(repoRoot).filter(l => l.runsTests && l.matrixExpression && l.testFiles.length === 0).map(l => l.id);
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* pregate/rust — Cargo crates for the import graph and the `lanes` runner.
|
||||
* A crate is the nearest directory holding a Cargo.toml with a `[package]`
|
||||
* name. Its `.rs` files are tests when they sit under `<crate>/tests/` or hold
|
||||
* a `#[cfg(test)]` (in-source unit tests). Cargo runs tests per crate, never
|
||||
* per file, so the graph maps at crate level: every `.rs` file of a crate,
|
||||
* and its Cargo.toml, select that crate's tests and the tests of every crate
|
||||
* that depends on it, transitively.
|
||||
* Manifests are parsed as TOML (Bun.TOML, as lib/model-policy.ts does), so
|
||||
* dotted keys, `[dependencies.<name>]` tables, target-specific tables and
|
||||
* `{ workspace = true }` inheritance read as Cargo reads them. A dependency
|
||||
* resolves by `path` (relative to the manifest declaring it) to a tracked
|
||||
* crate, else by package name (`package = ` or the key); a name match only
|
||||
* widens. The workspace a crate runs in follows Cargo's membership rules:
|
||||
* `package.workspace`, else the nearest `[workspace]` above it, when that
|
||||
* workspace is the crate's own manifest, lists it in `members` or reaches it
|
||||
* by a path dependency, and does not `exclude` it; otherwise the crate
|
||||
* directory. Nothing here runs cargo: pregate reads files only.
|
||||
*/
|
||||
import * as path from 'node:path';
|
||||
|
||||
/** Reads a repo-relative file's text, or null when it is absent or unreadable. */
|
||||
export type ReadFile = (rel: string) => string | null;
|
||||
|
||||
type Table = Record<string, unknown>;
|
||||
const isTable = (v: unknown): v is Table => typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
|
||||
const DEP_TABLES = ['dependencies', 'dev-dependencies', 'build-dependencies'] as const;
|
||||
|
||||
/** One dependency: the crate directory its `path` names (repo-relative, normalized) and the package name it asks for. */
|
||||
interface DepSpec { path: string | null; name: string }
|
||||
|
||||
export interface Crate {
|
||||
root: string;
|
||||
name: string;
|
||||
/** Where `cargo test -p <name>` runs: the root of the workspace it is a member of, else the crate directory; null when membership is undecided. */
|
||||
workspace: string | null;
|
||||
/** Roots of the tracked crates it depends on. */
|
||||
deps: string[];
|
||||
}
|
||||
|
||||
export interface CargoModel { crates: Map<string, Crate>; crateOf(file: string): Crate | null }
|
||||
|
||||
interface Manifest { dir: string; toml: Table }
|
||||
|
||||
const dirOf = (manifest: string) => (path.posix.dirname(manifest) === '.' ? '' : path.posix.dirname(manifest));
|
||||
/** `dir` joined with a manifest-relative path, normalized; null when it leaves the repository. */
|
||||
function joinRel(dir: string, rel: string): string | null {
|
||||
const joined = path.posix.normalize(path.posix.join(dir || '.', rel.replace(/\\/g, '/'))).replace(/\/+$/, '');
|
||||
if (joined === '..' || joined.startsWith('../') || path.posix.isAbsolute(joined)) return null;
|
||||
return joined === '.' ? '' : joined;
|
||||
}
|
||||
/** One glob component (`*`, `?`, `[...]` with `!`/`^` negation and ranges, else literal) against one path component, by Unicode code point and dynamic programming: O(pattern × name), no regex backtracking. */
|
||||
function componentMatch(glob: string, name: string): boolean {
|
||||
const g = Array.from(glob);
|
||||
const s = Array.from(name);
|
||||
const nextClose = new Array<number>(g.length + 1).fill(-1);
|
||||
for (let i = g.length - 1; i >= 0; i--) nextClose[i] = g[i] === ']' ? i : nextClose[i + 1]!;
|
||||
const tokens: Array<'*' | ((c: string) => boolean)> = [];
|
||||
for (let i = 0; i < g.length; i++) {
|
||||
const ch = g[i]!;
|
||||
const negate = ch === '[' && /[!^]/.test(g[i + 1] ?? '');
|
||||
const close = ch === '[' ? nextClose[i + (negate ? 3 : 2)] ?? -1 : -1;
|
||||
if (ch === '*') tokens.push('*');
|
||||
else if (ch === '?') tokens.push(() => true);
|
||||
else if (close > 0) {
|
||||
const body = g.slice(i + (negate ? 2 : 1), close).map(c => c.codePointAt(0)!);
|
||||
tokens.push(c => {
|
||||
const p = c.codePointAt(0)!;
|
||||
let hit = false;
|
||||
for (let j = 0; j < body.length; j++) {
|
||||
if (body[j + 1] === 0x2d && j + 2 < body.length) { hit ||= p >= body[j]! && p <= body[j + 2]!; j += 2; } else hit ||= p === body[j];
|
||||
}
|
||||
return hit !== negate;
|
||||
});
|
||||
i = close;
|
||||
} else tokens.push(c => c === ch);
|
||||
}
|
||||
let row = s.map(() => false).concat(false);
|
||||
row[0] = true;
|
||||
for (const t of tokens) {
|
||||
const next = row.map(() => false);
|
||||
next[0] = t === '*' && row[0]!;
|
||||
for (let j = 1; j <= s.length; j++) next[j] = t === '*' ? row[j]! || next[j - 1]! : row[j - 1]! && t(s[j - 1]!);
|
||||
row = next;
|
||||
}
|
||||
return row[s.length]!;
|
||||
}
|
||||
/** A Cargo `members` glob against a workspace-relative crate directory, component by component; `**` spans any number of components. */
|
||||
function memberMatch(glob: string, rel: string): boolean {
|
||||
const p = rel.split('/').filter(Boolean);
|
||||
let row = p.map(() => false).concat(false);
|
||||
row[0] = true;
|
||||
for (const part of glob.split('/').filter(Boolean)) {
|
||||
const next = row.map(() => false);
|
||||
next[0] = part === '**' && row[0]!;
|
||||
for (let j = 1; j <= p.length; j++) next[j] = part === '**' ? row[j]! || next[j - 1]! : row[j - 1]! && componentMatch(part, p[j - 1]!);
|
||||
row = next;
|
||||
}
|
||||
return row[p.length]!;
|
||||
}
|
||||
/**
|
||||
* Past this many characters of `members` globs a workspace's membership is undecided: every crate under it counts as a
|
||||
* member for dependency edges (more tests, never fewer), but where its tests run is unknown, so they are unclaimed and the
|
||||
* lane is incomplete (running from the wrong root can test a same-named member instead).
|
||||
*/
|
||||
const MAX_MEMBER_GLOB_CHARS = 4096;
|
||||
const inside = (dir: string, root: string) => root === '' || dir === root || dir.startsWith(`${root}/`);
|
||||
const relTo = (dir: string, root: string) => (root === '' ? dir : dir === root ? '' : dir.slice(root.length + 1));
|
||||
|
||||
/** Every dependency of a manifest: `[*dependencies]` and `[target.<cfg>.*dependencies]`, `{ workspace = true }` read from `ws`'s `[workspace.dependencies]` (its paths relative to the workspace root). */
|
||||
function depSpecs(m: Manifest, ws: Manifest | null): DepSpec[] {
|
||||
const tables: Table[] = [];
|
||||
for (const key of DEP_TABLES) if (isTable(m.toml[key])) tables.push(m.toml[key] as Table);
|
||||
if (isTable(m.toml.target)) for (const cfg of Object.values(m.toml.target)) if (isTable(cfg)) for (const key of DEP_TABLES) if (isTable(cfg[key])) tables.push(cfg[key] as Table);
|
||||
const inherited = ws && isTable(ws.toml.workspace) && isTable(ws.toml.workspace.dependencies) ? ws.toml.workspace.dependencies : {};
|
||||
const out: DepSpec[] = [];
|
||||
for (const table of tables) {
|
||||
for (const [key, raw] of Object.entries(table)) {
|
||||
const fromWorkspace = isTable(raw) && raw.workspace === true;
|
||||
const spec = fromWorkspace ? inherited[key] : raw;
|
||||
const renamed = [spec, raw].find(s => isTable(s) && typeof s.package === 'string') as Table | undefined;
|
||||
const p = isTable(spec) && typeof spec.path === 'string' ? joinRel(fromWorkspace ? ws!.dir : m.dir, spec.path) : null;
|
||||
out.push({ path: p, name: (renamed?.package as string | undefined) ?? key });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The tracked crates among `files` (the paths `git ls-files` reports), what each depends on, and the workspace each runs in. */
|
||||
export function cargoModel(files: readonly string[], read: ReadFile): CargoModel {
|
||||
const manifests = new Map<string, Manifest>();
|
||||
for (const f of files) {
|
||||
if (path.posix.basename(f) !== 'Cargo.toml') continue;
|
||||
const text = read(f);
|
||||
if (text === null) continue;
|
||||
try { const toml = Bun.TOML.parse(text); if (isTable(toml)) manifests.set(dirOf(f), { dir: dirOf(f), toml }); } catch { /* an unparsable manifest names no crate */ }
|
||||
}
|
||||
const nameOf = (dir: string) => { const pkg = manifests.get(dir)?.toml.package; return isTable(pkg) && typeof pkg.name === 'string' ? pkg.name : null; };
|
||||
const roots = [...manifests.keys()].filter(d => nameOf(d) !== null);
|
||||
const workspaces = [...manifests.values()].filter(m => isTable(m.toml.workspace));
|
||||
const byName = new Map<string, string[]>();
|
||||
for (const r of roots) byName.set(nameOf(r)!, [...(byName.get(nameOf(r)!) ?? []), r]);
|
||||
|
||||
// `package.workspace` names the workspace; otherwise Cargo consults only the nearest [workspace] at or above the crate.
|
||||
const candidate = (root: string): Manifest | null => {
|
||||
const pkg = manifests.get(root)!.toml.package as Table;
|
||||
if (typeof pkg.workspace === 'string') { const w = manifests.get(joinRel(root, pkg.workspace) ?? '\0'); return w && isTable(w.toml.workspace) ? w : null; }
|
||||
return workspaces.filter(w => inside(root, w.dir)).sort((a, b) => b.dir.length - a.dir.length)[0] ?? null;
|
||||
};
|
||||
const memberCache = new Map<string, Set<string>>();
|
||||
const undecided = new Set<string>();
|
||||
const membersOf = (ws: Manifest): Set<string> => {
|
||||
const cached = memberCache.get(ws.dir);
|
||||
if (cached) return cached;
|
||||
const conf = ws.toml.workspace as Table;
|
||||
const norm = (g: string) => joinRel('', g) ?? '\0';
|
||||
const globs = strings(conf.members).map(norm);
|
||||
const exclude = strings(conf.exclude).map(norm);
|
||||
const own = new Set(roots.filter(r => candidate(r)?.dir === ws.dir));
|
||||
const excluded = (r: string) => exclude.some(e => { const rel = relTo(r, ws.dir); return rel === e || rel.startsWith(`${e}/`); });
|
||||
// Cargo's rules: the root package and a literally listed member always belong; a glob match or a path dependency of a
|
||||
// member inside the workspace belongs unless `exclude` names it or a directory above it.
|
||||
const literal = (r: string) => globs.some(g => !/[*?[]/.test(g) && relTo(r, ws.dir) === g);
|
||||
const oversized = globs.join('').length > MAX_MEMBER_GLOB_CHARS;
|
||||
const members = new Set([...own].filter(r => r === ws.dir || literal(r) || ((oversized || globs.some(g => memberMatch(g, relTo(r, ws.dir)))) && !excluded(r))));
|
||||
if (oversized) for (const r of members) if (r !== ws.dir && !literal(r)) undecided.add(r);
|
||||
memberCache.set(ws.dir, members);
|
||||
const queue = [...members];
|
||||
while (queue.length) {
|
||||
for (const dep of depSpecs(manifests.get(queue.shift()!)!, ws)) {
|
||||
if (dep.path === null || members.has(dep.path) || !own.has(dep.path) || !inside(dep.path, ws.dir) || excluded(dep.path)) continue;
|
||||
members.add(dep.path);
|
||||
queue.push(dep.path);
|
||||
}
|
||||
}
|
||||
return members;
|
||||
};
|
||||
|
||||
// A path names one crate; without a path (or when it names no tracked crate) every crate of that package name is a candidate.
|
||||
const resolve = (specs: DepSpec[]) => [...new Set(specs.flatMap(s => (s.path !== null && nameOf(s.path) !== null ? [s.path] : byName.get(s.name) ?? [])))];
|
||||
const crates = new Map<string, Crate>();
|
||||
for (const root of roots) {
|
||||
const ws = candidate(root);
|
||||
const member = ws !== null && membersOf(ws).has(root) ? ws : null;
|
||||
crates.set(root, { root, name: nameOf(root)!, workspace: undecided.has(root) ? null : member?.dir ?? root, deps: resolve(depSpecs(manifests.get(root)!, member)).filter(d => d !== root) });
|
||||
}
|
||||
const crateOf = (file: string): Crate | null => {
|
||||
for (let d = path.posix.dirname(file); ; d = path.posix.dirname(d)) {
|
||||
const c = crates.get(d === '.' ? '' : d);
|
||||
if (c) return c;
|
||||
if (d === '.' || d === '/' || d === '') return null;
|
||||
}
|
||||
};
|
||||
return { crates, crateOf };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Rust source declares tests: a `#[test]` or `#[<path>::test]` attribute (a plain test function, `#[tokio::test]`),
|
||||
* or a `#[cfg(...)]` whose predicate names `test` outside a string (`cfg(test)`, `cfg(all(test, unix))`; never
|
||||
* `cfg(feature = "test")`). One forward scan: each attribute is read once to its `]`, and one this scan cannot close
|
||||
* (an unterminated string, no `]` before the end) counts as a test, which selects more, never fewer.
|
||||
*/
|
||||
export function hasCfgTest(source: string): boolean {
|
||||
if (/#\s*\[\s*(?:[A-Za-z_]\w*\s*::\s*)*test\s*[\]()]/.test(source)) return true;
|
||||
const open = /#\s*\[\s*cfg\s*\(/g;
|
||||
for (let m = open.exec(source); m; m = open.exec(source)) {
|
||||
let predicate = '';
|
||||
let i = open.lastIndex;
|
||||
for (; i < source.length && source[i] !== ']'; i++) {
|
||||
if (source[i] !== '"') { predicate += source[i]; continue; }
|
||||
const close = source.indexOf('"', i + 1);
|
||||
if (close < 0) return true;
|
||||
predicate += '""';
|
||||
i = close;
|
||||
}
|
||||
if (i >= source.length) return true;
|
||||
const body = predicate.trimEnd();
|
||||
if (body.endsWith(')') && /\btest\b/.test(body.slice(0, -1))) return true;
|
||||
open.lastIndex = i + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface RustGraph {
|
||||
tests: string[];
|
||||
edges: Array<{ dependency: string; dependent: string; via: 'import' | 'convention' }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Rust part of the reverse graph over the tracked `files`: each crate's
|
||||
* test files, an edge from every `.rs` file of a crate to its Cargo.toml (the
|
||||
* crate's node), and an edge from each Cargo.toml to the tests of its crate
|
||||
* (`convention`) and of every crate depending on it, transitively (`import`).
|
||||
*/
|
||||
export function rustEdges(files: readonly string[], read: ReadFile): RustGraph {
|
||||
const { crates, crateOf } = cargoModel(files, read);
|
||||
const out: RustGraph = { tests: [], edges: [] };
|
||||
if (!crates.size) return out;
|
||||
const testsOf = new Map<string, string[]>([...crates.keys()].map(k => [k, []]));
|
||||
const manifestOf = (root: string) => (root ? `${root}/Cargo.toml` : 'Cargo.toml');
|
||||
for (const f of files) {
|
||||
if (!f.endsWith('.rs')) continue;
|
||||
const crate = crateOf(f);
|
||||
if (!crate) continue;
|
||||
out.edges.push({ dependency: f, dependent: manifestOf(crate.root), via: 'convention' });
|
||||
if (f.startsWith(crate.root ? `${crate.root}/tests/` : 'tests/') || hasCfgTest(read(f) ?? '')) { out.tests.push(f); testsOf.get(crate.root)!.push(f); }
|
||||
}
|
||||
const dependents = new Map<string, Set<string>>();
|
||||
for (const c of crates.values()) for (const d of c.deps) dependents.set(d, (dependents.get(d) ?? new Set()).add(c.root));
|
||||
for (const root of crates.keys()) {
|
||||
const reach = new Set<string>([root]);
|
||||
const queue = [root];
|
||||
while (queue.length) for (const next of dependents.get(queue.shift()!) ?? []) if (!reach.has(next)) { reach.add(next); queue.push(next); }
|
||||
for (const r of reach) for (const t of testsOf.get(r)!) out.edges.push({ dependency: manifestOf(root), dependent: t, via: r === root ? 'convention' : 'import' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+4
-2
@@ -68,7 +68,7 @@ export interface RestampResult {
|
||||
|
||||
function sha256(buf: Buffer | string): string { return createHash('sha256').update(buf).digest('hex'); }
|
||||
function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string; status: number | null } {
|
||||
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, env: env ?? process.env });
|
||||
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, env: env ?? process.env, maxBuffer: 64 * 1024 * 1024 });
|
||||
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
|
||||
}
|
||||
class Refusal extends Error { constructor(public code: ResultCodeName, message: string, public extra: Partial<RestampResult> = {}) { super(message); } }
|
||||
@@ -578,7 +578,9 @@ function gateAhead(o: RestampOptions, plan: Plan, stages: StageRecord[], common:
|
||||
if (resolvable) {
|
||||
for (const c of conflicts) {
|
||||
if (c === plan.policy.changelog) {
|
||||
const merged = mergeChangelogs(git(dir, ['show', `:2:${c}`]).out + '\n', git(dir, ['show', `:3:${c}`]).out + '\n');
|
||||
const stage = (n: number) => git(dir, ['show', `:${n}:${c}`]);
|
||||
const [base, ours, theirs] = [stage(1), stage(2), stage(3)];
|
||||
const merged = ours.ok && theirs.ok ? mergeChangelogs(ours.out + '\n', theirs.out + '\n', base.ok ? base.out + '\n' : undefined) : null;
|
||||
if (merged === null) { unresolved = [c]; break; }
|
||||
fs.writeFileSync(path.join(dir, c), merged);
|
||||
} else git(dir, ['checkout', '--theirs', '--', c]);
|
||||
|
||||
@@ -99,7 +99,8 @@ export function recomputeMergeTree(repoRoot: string, branchHead: string, predece
|
||||
if (!ours || !theirs) return { error: `${file} conflicts beyond a content merge (added or deleted on one side)` };
|
||||
if (file === policy.changelog) {
|
||||
const text = (sha: string) => git(repoRoot, ['cat-file', 'blob', sha]).out + '\n';
|
||||
const merged = mergeChangelogs(text(ours), text(theirs));
|
||||
const base = entry.get(1);
|
||||
const merged = mergeChangelogs(text(ours), text(theirs), base ? text(base) : undefined);
|
||||
if (merged === null) return { error: `${file} conflicts beyond a heading move` };
|
||||
const blob = git(repoRoot, ['hash-object', '-w', '--stdin'], undefined, merged);
|
||||
if (!blob.ok) return { error: `cannot write the merged ${file}: ${blob.err}` };
|
||||
|
||||
@@ -15,7 +15,9 @@ import { trainBisect, trainRebuild, trainVerdict } from './ship-queue-train-verd
|
||||
import { verifyTrain } from './ship-queue-train-verify';
|
||||
import { redactCause } from './ship-queue-train-record';
|
||||
|
||||
export const TRAIN_HELP = ` train build --prs <n>@<sha>[,...] [--urgent | --repair] [--dry-run] [--free-timeout <s>]
|
||||
export const TRAIN_HELP = ` train build --prs <n>@<sha>[,...] [--order <n>,...] [--urgent | --repair] [--dry-run] [--free-timeout <s>]
|
||||
--order: explicit slot order, every PR in --prs once (default: screened
|
||||
first, then READY order)
|
||||
train build --train <nonce> resume a train (push, free tests, dispatch) from its record
|
||||
merge pinned unstamped heads in slot order onto main, free tests on
|
||||
train/<nonce>, then one full gate through eval-bg's nonce
|
||||
@@ -77,8 +79,9 @@ export async function trainMain(ctx: QueueContext, args: string[]): Promise<numb
|
||||
const freeTimeoutSec = positive(flag(rest, '--free-timeout'), 2700);
|
||||
if (Number.isNaN(freeTimeoutSec)) return usage('--free-timeout needs seconds');
|
||||
if (rest.includes('--urgent') && rest.includes('--repair')) return usage('--urgent and --repair are separate one-PR trains; pass one');
|
||||
if (rest.includes('--order') && (nonce || !flag(rest, '--order'))) return usage('--order <n>,... orders a new train from --prs; a resumed train keeps its recorded order');
|
||||
return guarded('train build', () => buildTrain(ctx, {
|
||||
pins: flag(rest, '--prs'), resume: nonce, dryRun, urgent: rest.includes('--urgent'), repair: rest.includes('--repair'), freeTimeoutSec,
|
||||
pins: flag(rest, '--prs'), order: flag(rest, '--order'), resume: nonce, dryRun, urgent: rest.includes('--urgent'), repair: rest.includes('--repair'), freeTimeoutSec,
|
||||
pollMs: Number(process.env.GSTACK_SHIP_QUEUE_POLL_MS) || 30_000,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { DISPATCH_INPUTS, awaitNonceRun, dedupeKey, dispatchWorkflow, findDuplicateRun, listDispatchRuns, makeNonce, type WorkflowDispatch } from '../scripts/eval-bg';
|
||||
import { EXIT } from './headless-artifacts';
|
||||
import { ready, type QueueContext } from './ship-queue';
|
||||
import { classifyTrainHead } from './version-gate-train';
|
||||
import { git } from './ship-queue-gate';
|
||||
import { execFor, repoSlug } from './ship-queue-train-github';
|
||||
import { loadReady, nowIso, persist, readyPath, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record';
|
||||
@@ -100,6 +101,8 @@ export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<Tr
|
||||
}
|
||||
const head = git(ctx.repoRoot, ['rev-parse', 'HEAD']).out;
|
||||
const baseSha = git(ctx.repoRoot, ['rev-parse', `${env.remote}/${ctx.base}`]).out;
|
||||
const kind = classifyTrainHead({ repoRoot: ctx.repoRoot, baseRef: ctx.base, head });
|
||||
if (kind.kind === 'invalid') return outRefused({ code: 'QUEUE_NOT_READY', message: `the Version Gate refuses ${head.slice(0, 12)}: ${kind.reason}` }, base.lines, `fix the head, push, then ${Q} ready --pr ${o.pr} --screen|--no-screen`, 'none');
|
||||
const sel = await screenSelection(env, head, baseSha);
|
||||
const lines = [...base.lines, ...sel.lines];
|
||||
const rec = sel.recommend ?? 'no-screen';
|
||||
@@ -119,7 +122,7 @@ export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<Tr
|
||||
}
|
||||
lines.splice(1, 0, `screen: ${choice.choice}${choice.policy ? ` policy=${choice.policy} nonce=${choice.nonce} run=${choice.run ?? '-'}` : ''}`);
|
||||
const now = nowIso();
|
||||
const readyAt = loadReady(env.repo.key, o.pr, head)?.ready_at ?? now;
|
||||
const readyAt = loadReady(env.repo.keys, o.pr, head)?.ready_at ?? now;
|
||||
const receipt: ReadyReceipt = { schema: 1, kind: 'ready', repo_key: env.repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: readyAt, screen: choice, updated_at: now };
|
||||
if (o.dryRun) return outOk([...lines, 'DRY-RUN: no READY receipt written, nothing dispatched'], `${Q} ready --pr ${o.pr} --${o.screen}${o.broad ? ' --broad' : ''}`, 'none');
|
||||
const p = persist(ctx.repoRoot, [receipt], { remote: env.remote });
|
||||
|
||||
@@ -31,7 +31,7 @@ export interface FreeRun { run: number | null; url: string | null; head_sha: str
|
||||
export interface TrainRecord {
|
||||
schema: 1; kind: 'train'; nonce: string; key: string; repo_key: string; repo: string; base: { ref: string; sha: string }; policy: string;
|
||||
slots: TrainSlot[]; held: string[]; prefixes: TrainPrefix[]; head: string; tree: string; branch: string;
|
||||
urgent: boolean; repair: boolean; state: TrainState; free: FreeRun | null; attempts: string[];
|
||||
urgent: boolean; repair: boolean; explicit_order?: boolean; state: TrainState; free: FreeRun | null; attempts: string[];
|
||||
merged: Array<{ pr: string; sha: string; tree: string; at: string }>; superseded_by: string | null;
|
||||
effects: Array<{ at: string; what: string }>; error: string | null; created_at: string; updated_at: string;
|
||||
}
|
||||
@@ -87,11 +87,34 @@ const bisectPath = (nonce: string) => path.join(trainDir(nonce), 'bisect.json');
|
||||
const freezePath = (repoKey: string) => path.join(queueRoot(), 'freeze', `${repoKey}.json`);
|
||||
export const readyPath = (repoKey: string, pr: string, head: string) => path.join(queueRoot(), 'ready', repoKey, `${pr}-${head}.json`);
|
||||
|
||||
/** The repository's identity: origin's URL, keyed so records of different repositories never mix. */
|
||||
export function repoIdentity(repoRoot: string): { key: string; url: string } {
|
||||
const url = git(repoRoot, ['config', '--get', 'remote.origin.url']).out.trim() || repoRoot;
|
||||
const norm = url.replace(/\.git$/, '').replace(/^git@github\.com:/, 'https://github.com/').replace(/\/+$/, '');
|
||||
return { key: sha256(norm).slice(0, 16), url: norm };
|
||||
/** Hosts that serve GitHub repositories at /<owner>/<repo> (git.capy.ai is Capy's GitHub proxy, set through url.insteadOf). */
|
||||
const GITHUB_HOSTS = ['github.com', 'www.github.com', 'ssh.github.com', 'git.capy.ai'];
|
||||
|
||||
/** Before 1.91.187.0 the key hashed origin's URL with only .git, git@github.com: and trailing slashes normalized. */
|
||||
const legacyNorm = (url: string) => url.replace(/\.git$/, '').replace(/^git@github\.com:/, 'https://github.com/').replace(/\/+$/, '');
|
||||
|
||||
/** A remote URL as https://github.com/<owner>/<repo> when it names a GitHub repository in any form (scp, ssh, http(s), credentials, proxy host); otherwise the legacy form. */
|
||||
export function normalizeRemoteUrl(url: string): string {
|
||||
const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)(?::\d+)?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/*$/i.exec(url.trim());
|
||||
if (m && GITHUB_HOSTS.includes(m[1]!.toLowerCase())) return `https://github.com/${m[2]!.toLowerCase()}/${m[3]!.toLowerCase()}`;
|
||||
return legacyNorm(url.trim().replace(/^([a-z+]+:\/\/)[^@/]+@/i, '$1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository's identity, keyed so records of different repositories
|
||||
* never mix: a hash of origin's URL normalized to owner/repo, so lanes whose
|
||||
* origin names the same GitHub repository in another form share one key.
|
||||
* `keys` adds the keys earlier versions wrote for this URL and for the
|
||||
* repository's common URL forms; readers accept all of them, writers use `key`.
|
||||
*/
|
||||
export function repoIdentity(repoRoot: string): { key: string; url: string; keys: string[] } {
|
||||
const raw = git(repoRoot, ['config', '--get', 'remote.origin.url']).out.trim() || repoRoot;
|
||||
const url = normalizeRemoteUrl(raw);
|
||||
const key = sha256(url).slice(0, 16);
|
||||
const gh = /^https:\/\/github\.com\/(.+)$/.exec(url)?.[1];
|
||||
const forms = gh ? GITHUB_HOSTS.flatMap(h => ['https', 'http', 'ssh://git@'].map(s => `${s.includes('://') ? s : `${s}://`}${h}/${gh}`)) : [];
|
||||
const keys = [...new Set([key, ...[raw, ...forms].map(u => sha256(legacyNorm(u)).slice(0, 16))])];
|
||||
return { key, url, keys };
|
||||
}
|
||||
|
||||
function readJson<T>(file: string, kind: string): T | null {
|
||||
@@ -101,19 +124,25 @@ function readJson<T>(file: string, kind: string): T | null {
|
||||
export const loadTrain = (nonce: string) => (/^[A-Za-z0-9._-]{1,128}$/.test(nonce) ? readJson<TrainRecord>(trainFile(nonce), 'train') : null);
|
||||
export const loadAttempt = (nonce: string, id: string) => (/^[A-Za-z0-9._-]{1,64}$/.test(id) ? readJson<AttemptRecord>(attemptPath(nonce, id), 'train-attempt') : null);
|
||||
export const loadBisect = (nonce: string) => readJson<BisectRecord>(bisectPath(nonce), 'train-bisect');
|
||||
export const loadFreeze = (repoKey: string) => readJson<FreezeRecord>(freezePath(repoKey), 'freeze');
|
||||
export const loadReady = (repoKey: string, pr: string, head: string) => readJson<ReadyReceipt>(readyPath(repoKey, pr, head), 'ready');
|
||||
export const activeFreeze = (repoKey: string): FreezeRecord | null => { const f = loadFreeze(repoKey); return f && !f.cleared_at ? f : null; };
|
||||
/** A reader's repo keys: the current key first, then the legacy keys (repoIdentity().keys). */
|
||||
type RepoKeys = string | readonly string[];
|
||||
const keyList = (k: RepoKeys): readonly string[] => (typeof k === 'string' ? [k] : k);
|
||||
const firstOf = <T>(k: RepoKeys, read: (key: string) => T | null): T | null => { for (const key of keyList(k)) { const r = read(key); if (r) return r; } return null; };
|
||||
|
||||
export const loadFreeze = (repoKeys: RepoKeys) => firstOf(repoKeys, key => readJson<FreezeRecord>(freezePath(key), 'freeze'));
|
||||
export const loadReady = (repoKeys: RepoKeys, pr: string, head: string) => firstOf(repoKeys, key => readJson<ReadyReceipt>(readyPath(key, pr, head), 'ready'));
|
||||
export const activeFreeze = (repoKeys: RepoKeys): FreezeRecord | null => firstOf(repoKeys, key => { const f = readJson<FreezeRecord>(freezePath(key), 'freeze'); return f && !f.cleared_at ? f : null; });
|
||||
|
||||
export function attemptsOf(train: TrainRecord): AttemptRecord[] {
|
||||
return train.attempts.map(id => loadAttempt(train.nonce, id)).filter((a): a is AttemptRecord => !!a);
|
||||
}
|
||||
|
||||
/** Every train of this repository, newest first. */
|
||||
export function listTrains(repoKey: string): TrainRecord[] {
|
||||
export function listTrains(repoKeys: RepoKeys): TrainRecord[] {
|
||||
const dir = path.join(queueRoot(), 'trains');
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir).map(n => loadTrain(n)).filter((t): t is TrainRecord => !!t && t.repo_key === repoKey)
|
||||
const keys = keyList(repoKeys);
|
||||
return fs.readdirSync(dir).map(n => loadTrain(n)).filter((t): t is TrainRecord => !!t && keys.includes(t.repo_key))
|
||||
.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.nonce.localeCompare(a.nonce));
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type AttemptRecord, type BisectRecord, type CasePanel, type GateOutcome, type PrefixResult, type TrainRecord,
|
||||
} from './ship-queue-train-record';
|
||||
import {
|
||||
dispatchAttempt, effect, findTrain, gateDispatch, nextFor, outFailed, outOk, outPending, outRefused, pinList, save, trainEnv,
|
||||
dispatchAttempt, effect, findTrain, gateDispatch, nextFor, outFailed, outOk, outPending, outRefused, prsArgs, save, trainEnv,
|
||||
type TrainEnv, type TrainOut,
|
||||
} from './ship-queue-train';
|
||||
|
||||
@@ -309,7 +309,7 @@ export async function trainRebuild(ctx: QueueContext, o: { train: string; infra:
|
||||
const run = trainFile(t.nonce);
|
||||
const gates = gateAttempts(t);
|
||||
const last = gates.at(-1);
|
||||
const repair = `route ${last?.red_cases.join(',') || 'the red cases'} to a repair lane (GStack Minder); the train is rebuilt only once the repair merges: ${Q} train build --prs ${pinList(t.slots)}`;
|
||||
const repair = `route ${last?.red_cases.join(',') || 'the red cases'} to a repair lane (GStack Minder); the train is rebuilt only once the repair merges: ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
|
||||
const refuse = (reason: string) => outRefused({ code: 'QUEUE_TRAIN_REBUILD_REFUSED', message: `rebuild refused: ${reason}` }, gates.map(attemptLine), repair, run);
|
||||
if (o.infra) {
|
||||
if (!last || last.outcome !== 'INCOMPLETE' || !last.infra_eligible) return refuse(`no INFRA/INCOMPLETE-only record (the last gate is ${last?.outcome ?? 'missing'})`);
|
||||
@@ -321,7 +321,7 @@ export async function trainRebuild(ctx: QueueContext, o: { train: string; infra:
|
||||
if (b.outcome.kind !== 'unattributed' || !b.outcome.all_green) return refuse(`the bisect was not all green (${Object.entries(b.outcome.patterns).map(([c, s]) => `${c}=${s}`).join(' ')})`);
|
||||
}
|
||||
const tip = remoteBranchSha(args => git(ctx.repoRoot, args), env.remote, t.branch);
|
||||
if (tip !== t.head) return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `${t.branch} is at ${tip?.slice(0, 12) ?? 'nothing'}, not the recorded head ${t.head.slice(0, 12)}` }, [], `${Q} train build --prs ${pinList(t.slots)}`, run);
|
||||
if (tip !== t.head) return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `${t.branch} is at ${tip?.slice(0, 12) ?? 'nothing'}, not the recorded head ${t.head.slice(0, 12)}` }, [], `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, run);
|
||||
const slug = repoSlug(ctx);
|
||||
if (!slug) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: 'gh repo view could not name the repository' }, [], `${Q} train rebuild --train ${t.nonce}${o.infra ? ' --infra' : ''}`, run);
|
||||
const a = await dispatchAttempt(env, slug, t, o.infra ? 'infra-redispatch' : 'rebuild', gateDispatch(env, t, `${t.nonce}.${gates.length + 1}`));
|
||||
|
||||
@@ -20,8 +20,9 @@ import { git } from './ship-queue-gate';
|
||||
import { checkRun, execFor, repoSlug } from './ship-queue-train-github';
|
||||
import { activeFreeze, attemptsOf, nowIso, persist, trainFile, type FreezeRecord, type TrainRecord } from './ship-queue-train-record';
|
||||
import {
|
||||
effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, save, trainEnv, type TrainEnv, type TrainOut,
|
||||
effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, prsArgs, save, trainEnv, type TrainEnv, type TrainOut,
|
||||
} from './ship-queue-train';
|
||||
import { ownEntryAboveMain } from './changelog-check';
|
||||
import { buildReceipt } from './tree-receipt';
|
||||
|
||||
const Q = 'gstack-ship-queue';
|
||||
@@ -32,6 +33,37 @@ function sameModuloStamps(env: TrainEnv, gated: string, current: string): { same
|
||||
return { same: r.tree === 'same-modulo-stamps', detail: r.tree === 'same-modulo-stamps' ? `same modulo stamps (${r.files.length} stamp file(s))` : `differs: ${r.residual.slice(0, 8).join(', ')}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* A slot head with main merged in (from slot 2 on the lane merges main into
|
||||
* its pin so GitHub can merge it): it must contain main, and its tree must be
|
||||
* the slot's prefix T<i> modulo stamps. The CHANGELOG is judged against main
|
||||
* instead of T<i>'s mechanical merge, so a hand resolve is accepted when it
|
||||
* is main's CHANGELOG plus the PR's own entry (ownEntryAboveMain); any other
|
||||
* difference is refused.
|
||||
*/
|
||||
function mergedIn(env: TrainEnv, t: TrainRecord, i: number, head: string, main: string): { same: boolean; detail: string } {
|
||||
const after = t.prefixes[i + 1]!;
|
||||
const root = env.ctx.repoRoot;
|
||||
if (!git(root, ['merge-base', '--is-ancestor', main, head]).ok) return { same: false, detail: `does not contain main ${main.slice(0, 12)}` };
|
||||
const r = buildReceipt({ repoRoot: root, gated: after.commit, current: head, policy: env.policy.policy, policyLabel: env.policy.source.label });
|
||||
if ('error' in r) return { same: false, detail: r.error };
|
||||
const stamps = `${r.files.filter(f => f.verdict === 'stamp').length} stamp file(s)`;
|
||||
if (r.tree === 'same-modulo-stamps') return { same: true, detail: `T${after.index} with main merged in, same modulo stamps (${stamps})` };
|
||||
const cl = env.policy.policy.changelog;
|
||||
const beyond = r.residual.filter(f => f !== cl);
|
||||
if (beyond.length || !cl) return { same: false, detail: `differs from T${after.index}: ${r.residual.slice(0, 8).join(', ')}` };
|
||||
const pin = t.slots[i]!.head;
|
||||
const forkPoint = git(root, ['merge-base', pin, t.prefixes[0]!.commit]).out;
|
||||
const diff = git(root, ['diff', '--unified=0', '--no-color', '--no-ext-diff', forkPoint, pin, '--', cl]);
|
||||
const show = (rev: string) => git(root, ['show', `${rev}:${cl}`]);
|
||||
const [headCl, mainCl] = [show(head), show(main)];
|
||||
if (!forkPoint || !diff.ok || !headCl.ok || !mainCl.ok) return { same: false, detail: `cannot read ${cl} at the pin, the head or main` };
|
||||
const authored = new Set(diff.out.split('\n').filter(l => l.startsWith('+') && !l.startsWith('+++')).map(l => l.slice(1)));
|
||||
const why = ownEntryAboveMain(headCl.out, mainCl.out, authored);
|
||||
if (why) return { same: false, detail: `differs from T${after.index} in ${cl}, which is not main's plus #${t.slots[i]!.pr}'s own entry: ${why}` };
|
||||
return { same: true, detail: `T${after.index} with main merged in, same modulo stamps (${stamps}) except ${cl}, resolved as main's ${cl} plus #${t.slots[i]!.pr}'s own entry` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeze the queue: the record goes to local state and the notes ref before
|
||||
* anything remote, then the backstop gate is dispatched on main's sha.
|
||||
@@ -61,8 +93,8 @@ async function freezeQueue(env: TrainEnv, t: TrainRecord, reason: string, mainSh
|
||||
/** Interrupted publication: freeze when earlier slots merged; otherwise a plain refusal (nothing was published). */
|
||||
async function stopped(env: TrainEnv, t: TrainRecord, code: 'QUEUE_TRAIN_TREE_MISMATCH' | 'QUEUE_TRAIN_MOVED', message: string, mainSha: string, lines: string[]): Promise<TrainOut> {
|
||||
const run = trainFile(t.nonce);
|
||||
if (!t.merged.length) return outFailed({ code, message: `${message}; nothing of train ${t.nonce} merged, so the queue is not frozen` }, lines, `${Q} train build --prs ${pinList(t.slots)} (a new train on current main)`, run);
|
||||
const f = activeFreeze(env.repo.key) ?? await freezeQueue(env, t, message, mainSha);
|
||||
if (!t.merged.length) return outFailed({ code, message: `${message}; nothing of train ${t.nonce} merged, so the queue is not frozen` }, lines, `${Q} train build ${prsArgs(t.slots, t.explicit_order)} (a new train on current main)`, run);
|
||||
const f = activeFreeze(env.repo.keys) ?? await freezeQueue(env, t, message, mainSha);
|
||||
return outFailed({ code, message: `${message}; the queue is frozen` }, [...lines, ...frozenLines(f)], `${Q} train build --repair --prs <repair-pr>@<sha>`, run);
|
||||
}
|
||||
|
||||
@@ -84,7 +116,7 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str
|
||||
if (check?.conclusion !== 'success') return outRefused({ code: 'QUEUE_GATE_MISSING', message: `no successful ${env.train.full_gate_check} check run on the train head ${t.head.slice(0, 12)}` }, [], `${Q} train verdict --train ${t.nonce}`, run);
|
||||
if (!fetchTrainBranch(env, t)) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `the train's prefix commits are not here and ${t.branch} could not be fetched` }, [], `${Q} train status --train ${t.nonce}`, run);
|
||||
const main = git(ctx.repoRoot, ['rev-parse', `${env.remote}/${ctx.base}`]).out;
|
||||
const freeze = activeFreeze(env.repo.key);
|
||||
const freeze = activeFreeze(env.repo.keys);
|
||||
if (freeze && freeze.repair?.train !== t.nonce) return outRefused({ code: 'QUEUE_TRAIN_FROZEN', message: `the queue is frozen (${freeze.reason}); only the admitted repair train merges` }, frozenLines(freeze), `${Q} train build --repair --prs <repair-pr>@<sha>`, run);
|
||||
const after = t.prefixes[i + 1]!;
|
||||
const before = t.prefixes[i]!;
|
||||
@@ -98,9 +130,8 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str
|
||||
const headRef = o.noFetch ? '' : (git(ctx.repoRoot, ['fetch', '--no-tags', '-q', env.remote, `+refs/pull/${o.pr}/head:refs/gstack/queue/pr-${o.pr}`]).ok ? `refs/gstack/queue/pr-${o.pr}` : '');
|
||||
const head = headRef ? git(ctx.repoRoot, ['rev-parse', headRef]).out : t.slots[i]!.head;
|
||||
const pinned = head === t.slots[i]!.head ? { same: true, detail: 'the pinned head' } : sameModuloStamps(env, t.slots[i]!.head, head);
|
||||
const asPrefix = pinned.same ? null : sameModuloStamps(env, after.commit, head);
|
||||
const stampOnly = asPrefix?.same ? { same: true, detail: `T${after.index} with main merged in, ${asPrefix.detail}` } : pinned;
|
||||
if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${pinned.detail})`, main, lines);
|
||||
const stampOnly = pinned.same ? pinned : mergedIn(env, t, i, head, main);
|
||||
if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${stampOnly.detail}; against the pin it ${pinned.detail})`, main, lines);
|
||||
return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`,
|
||||
`VERIFY_TRAIN: #${o.pr} may merge as slot ${i + 1} of train ${t.nonce} (green run ${gate.run?.id ?? '-'}, ${env.train.full_gate_check} success)`, `MERGE_CONDITION: sha=${head}`],
|
||||
`merge #${o.pr} with expected head ${head.slice(0, 12)} (gstack-restamp stamps at merge), then ${Q} verify --pr ${o.pr} --train ${t.nonce}`, run);
|
||||
@@ -113,7 +144,7 @@ function confirmMerged(env: TrainEnv, t: TrainRecord, pr: string, main: string,
|
||||
effect(t, `verified #${pr} merged as T${index}`);
|
||||
save(env, t);
|
||||
lines.push(`VERIFY_TRAIN: #${pr} merged; main's tree is T${index} of train ${t.nonce} (${t.merged.length}/${t.slots.length} merged)`);
|
||||
const freeze = activeFreeze(env.repo.key);
|
||||
const freeze = activeFreeze(env.repo.keys);
|
||||
if (freeze && freeze.repair?.train === t.nonce && t.state === 'merged') {
|
||||
freeze.cleared_at = nowIso();
|
||||
freeze.cleared_by = `repair #${pr} via train ${t.nonce}; main ${main.slice(0, 12)} carries a green record`;
|
||||
|
||||
+53
-25
@@ -16,7 +16,7 @@
|
||||
*/
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { DISPATCH_INPUTS, awaitNonceRun, dispatchWorkflow, listDispatchRuns, makeNonce, runForNonce, type WorkflowDispatch } from '../scripts/eval-bg';
|
||||
import { mergeChangelogs, parseChangelog, type ChangelogSection } from './changelog-check';
|
||||
import { changelogDamage, mergeChangelogs, parseChangelog, type ChangelogSection } from './changelog-check';
|
||||
import type { ResultStatus } from './headless-artifacts';
|
||||
import { versionAtRef, versionFiles } from './restamp';
|
||||
import type { LoadedPolicy, ShipPolicy, TrainPolicy } from './ship-policy';
|
||||
@@ -34,7 +34,7 @@ export const outRefused = (failure: QueueFailure, lines: string[], next: string,
|
||||
export const outFailed = (failure: QueueFailure, lines: string[], next: string, run: string): TrainOut => ({ exit: 1, status: 'refused', lines, next, failure, run });
|
||||
export const outPending = (failure: QueueFailure, lines: string[], next: string, run: string): TrainOut => ({ exit: 3, status: 'incomplete', lines, next, failure, run });
|
||||
|
||||
export interface TrainEnv { ctx: QueueContext; policy: LoadedPolicy; train: TrainPolicy; repo: { key: string; url: string }; remote: string }
|
||||
export interface TrainEnv { ctx: QueueContext; policy: LoadedPolicy; train: TrainPolicy; repo: { key: string; url: string; keys: string[] }; remote: string }
|
||||
|
||||
const HEX = /^[0-9a-f]{40,64}$/;
|
||||
const Q = 'gstack-ship-queue';
|
||||
@@ -92,9 +92,20 @@ export function parsePins(spec: string | undefined): Array<{ pr: string; sha: st
|
||||
}
|
||||
|
||||
export const pinList = (slots: Array<{ pr: string; head: string }>) => slots.map(s => `${s.pr}@${s.head}`).join(',');
|
||||
/** `--prs <pins>` for a rebuild of these slots, plus `--order` when the train was built with an explicit order. */
|
||||
export const prsArgs = (slots: Array<{ pr: string; head: string }>, explicit?: boolean) => `--prs ${pinList(slots)}${explicit ? ` --order ${slots.map(s => s.pr).join(',')}` : ''}`;
|
||||
|
||||
/** Slot order: screened PRs first, then unscreened, each in READY order; enough unscreened PRs form their own train. */
|
||||
export function orderSlots(slots: TrainSlot[], max: number): { train: TrainSlot[]; held: TrainSlot[]; split: boolean } {
|
||||
/**
|
||||
* Slot order: screened PRs first, then unscreened, each in READY order;
|
||||
* enough unscreened PRs form their own train. An explicit order (`--order`,
|
||||
* every admitted PR once) replaces that rule: slots follow it, the first
|
||||
* `max` ride and the rest are held.
|
||||
*/
|
||||
export function orderSlots(slots: TrainSlot[], max: number, explicit?: readonly string[]): { train: TrainSlot[]; held: TrainSlot[]; split: boolean } {
|
||||
if (explicit) {
|
||||
const all = explicit.map(pr => slots.find(s => s.pr === pr)!);
|
||||
return { train: all.slice(0, max), held: all.slice(max), split: false };
|
||||
}
|
||||
const byReady = (a: TrainSlot, b: TrainSlot) => a.ready_at.localeCompare(b.ready_at) || Number(a.pr) - Number(b.pr);
|
||||
const screened = slots.filter(s => s.screen.choice === 'screen').sort(byReady);
|
||||
const unscreened = slots.filter(s => s.screen.choice !== 'screen').sort(byReady);
|
||||
@@ -130,7 +141,9 @@ function unionChangelog(ours: string, theirs: string): string {
|
||||
* One train merge, in object storage: the PR head onto the previous prefix.
|
||||
* Version files take the prefix's side; the CHANGELOG merges by section (the
|
||||
* gate-ahead rule, else a union of sections, since each heading is restamped
|
||||
* at merge). Any other conflict is reported with every conflicting path.
|
||||
* at merge), unless a side damaged released history (changelogDamage), which
|
||||
* is a conflict the lane resolves. Any other conflict is reported with every
|
||||
* conflicting path.
|
||||
*/
|
||||
export function mergeStep(repoRoot: string, pred: string, head: string, policy: ShipPolicy): { tree: string } | { conflicts: string[] } {
|
||||
const r = git(repoRoot, ['merge-tree', '--write-tree', head, pred]);
|
||||
@@ -157,6 +170,9 @@ export function mergeStep(repoRoot: string, pred: string, head: string, policy:
|
||||
if (!ours || !theirs) conflicts.push(file);
|
||||
else if (file === policy.changelog) {
|
||||
const text = (sha: string) => git(repoRoot, ['cat-file', 'blob', sha]).out + '\n';
|
||||
const base = entry.get(1);
|
||||
const damage = changelogDamage(text(ours), text(theirs), base ? text(base) : undefined);
|
||||
if (damage) { conflicts.push(`${file} (${damage})`); continue; }
|
||||
const merged = mergeChangelogs(text(ours), text(theirs)) ?? unionChangelog(text(ours), text(theirs));
|
||||
const blob = git(repoRoot, ['hash-object', '-w', '--stdin'], undefined, merged);
|
||||
if (blob.ok) resolved.push({ path: file, blob: blob.out }); else conflicts.push(file);
|
||||
@@ -207,12 +223,12 @@ export function nextFor(t: TrainRecord): string {
|
||||
case 'attributed': {
|
||||
const drop = loadBisect(n)?.outcome?.prs ?? [];
|
||||
const keep = t.slots.filter(s => !drop.includes(s.pr));
|
||||
return keep.length ? `${Q} train build --prs ${pinList(keep)}` : 'none (every PR was dropped)';
|
||||
return keep.length ? `${Q} train build ${prsArgs(keep, t.explicit_order)}` : 'none (every PR was dropped)';
|
||||
}
|
||||
case 'red-on-main': return `fix forward on main first, then ${Q} train build --prs ${pinList(t.slots)}`;
|
||||
case 'red-on-main': return `fix forward on main first, then ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
|
||||
case 'unattributed': return loadBisect(n)?.outcome?.all_green && !attemptsOf(t).some(a => a.purpose === 'rebuild')
|
||||
? `${Q} train rebuild --train ${n}`
|
||||
: `route the red cases to a repair lane (GStack Minder); once the repair merges: ${Q} train build --prs ${pinList(t.slots)}`;
|
||||
: `route the red cases to a repair lane (GStack Minder); once the repair merges: ${Q} train build ${prsArgs(t.slots, t.explicit_order)}`;
|
||||
default: return `${Q} train prune --train ${n}`;
|
||||
}
|
||||
}
|
||||
@@ -249,7 +265,17 @@ export function gateDispatch(env: TrainEnv, train: TrainRecord, nonce: string):
|
||||
return { workflow: env.train.gate_workflow, inputs: { [DISPATCH_INPUTS.evalsAll]: 'true', [DISPATCH_INPUTS.expectedSha]: train.head, [DISPATCH_INPUTS.nonce]: nonce } };
|
||||
}
|
||||
|
||||
export interface BuildOptions { pins?: string; resume?: string; dryRun: boolean; urgent: boolean; repair: boolean; freeTimeoutSec: number; pollMs: number }
|
||||
export interface BuildOptions { pins?: string; order?: string; resume?: string; dryRun: boolean; urgent: boolean; repair: boolean; freeTimeoutSec: number; pollMs: number }
|
||||
|
||||
/** `--order <pr>,<pr>,...`: every pinned PR exactly once (a leading # allowed). */
|
||||
export function parseOrder(spec: string | undefined, pins: Array<{ pr: string }>): string[] | undefined | { error: string } {
|
||||
if (spec === undefined) return undefined;
|
||||
const order = spec.split(',').map(s => s.trim().replace(/^#/, '')).filter(Boolean);
|
||||
const want = pins.map(p => p.pr).sort((a, b) => Number(a) - Number(b));
|
||||
const got = [...order].sort((a, b) => Number(a) - Number(b));
|
||||
if (order.some(pr => !/^\d+$/.test(pr)) || got.join(',') !== want.join(',')) return { error: `--order must list every PR in --prs exactly once (--prs has ${want.map(p => '#' + p).join(',')}; got ${spec})` };
|
||||
return order;
|
||||
}
|
||||
|
||||
/** The slots a new train would carry: trusted, unmoved, READY PRs, in slot order. */
|
||||
function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): { slots: TrainSlot[]; lines: string[] } | TrainOut {
|
||||
@@ -267,7 +293,7 @@ function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): {
|
||||
if (!info.headRefOid.startsWith(p.sha) || fetched !== info.headRefOid) {
|
||||
return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `PR #${p.pr} moved: pinned ${p.sha.slice(0, 12)}, head is now ${info.headRefOid.slice(0, 12)}` }, [], `ask #${p.pr}'s lane for READY on ${info.headRefOid.slice(0, 12)}, then ${Q} train build --prs <pins>`, 'none');
|
||||
}
|
||||
const ready = loadReady(env.repo.key, p.pr, info.headRefOid);
|
||||
const ready = loadReady(env.repo.keys, p.pr, info.headRefOid);
|
||||
if (!ready) return outRefused({ code: 'QUEUE_NOT_READY', message: `no READY receipt for #${p.pr} at ${info.headRefOid.slice(0, 12)} (local state or ${'refs/notes/gstack-trains'})` }, [], `the lane runs ${Q} ready --pr ${p.pr} --screen|--no-screen`, 'none');
|
||||
slots.push({ pr: p.pr, head: info.headRefOid, ready_at: ready.ready_at, screen: ready.screen });
|
||||
}
|
||||
@@ -280,28 +306,30 @@ async function newTrain(env: TrainEnv, o: BuildOptions): Promise<{ t: TrainRecor
|
||||
if (typeof pins === 'string') return outRefused({ code: 'QUEUE_PROOF_MISSING', message: pins }, [], 'none', 'none');
|
||||
if ((o.urgent || o.repair) && pins.length !== 1) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `${o.repair ? '--repair' : '--urgent'} admits exactly one PR` }, [], 'none', 'none');
|
||||
rebuildFromNotes(env.ctx.repoRoot, env.remote);
|
||||
const freeze = activeFreeze(env.repo.key);
|
||||
const freeze = activeFreeze(env.repo.keys);
|
||||
if (freeze && !o.repair) return outRefused({ code: 'QUEUE_TRAIN_FROZEN', message: `the queue is frozen since ${freeze.created_at}: train ${freeze.train} stopped after merging ${freeze.merged.map(p => '#' + p).join(',')} (${freeze.reason})` },
|
||||
frozenLines(freeze), `${Q} train build --repair --prs <repair-pr>@<sha>`, 'none');
|
||||
const explicit = parseOrder(o.order, pins);
|
||||
if (explicit && 'error' in explicit) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: explicit.error }, [], 'none', 'none');
|
||||
const admitted = admitSlots(env, pins);
|
||||
if ('exit' in admitted) return admitted;
|
||||
const order = orderSlots(admitted.slots, o.repair ? 1 : env.train.max_size);
|
||||
const order = orderSlots(admitted.slots, o.repair ? 1 : env.train.max_size, explicit);
|
||||
const lines = [
|
||||
`ORDER: ${order.train.map((s, i) => `${i + 1}:#${s.pr}(${s.screen.choice === 'screen' ? 'screened' : 'unscreened'})`).join(' ')}`,
|
||||
`ORDER: ${order.train.map((s, i) => `${i + 1}:#${s.pr}(${s.screen.choice === 'screen' ? 'screened' : 'unscreened'})`).join(' ')}${explicit ? ' (explicit --order)' : ''}`,
|
||||
...(order.held.length ? [`HELD: ${order.held.map(s => '#' + s.pr).join(',')} (${order.split ? 'unscreened PRs form their own train' : `over the train size ${env.train.max_size}`})`] : []),
|
||||
];
|
||||
const due = fillDue(order.train, env.train, nowIso(), o.urgent || o.repair);
|
||||
if (due && !o.dryRun) return outPending({ code: 'QUEUE_TRAIN_WAITING', message: `${order.train.length} of ${env.train.max_size} PRs; the oldest READY dispatches at ${due}` }, lines, `${Q} train build --prs ${pinList(order.train)} (after ${due}, or with more PRs, or --urgent for one)`, 'none');
|
||||
if (due && !o.dryRun) return outPending({ code: 'QUEUE_TRAIN_WAITING', message: `${order.train.length} of ${env.train.max_size} PRs; the oldest READY dispatches at ${due}` }, lines, `${Q} train build ${prsArgs(order.train, !!explicit)} (after ${due}, or with more PRs, or --urgent for one)`, 'none');
|
||||
const baseSha = git(env.ctx.repoRoot, ['rev-parse', `${env.remote}/${env.ctx.base}`]).out;
|
||||
const key = sha256(JSON.stringify({ base: baseSha, slots: order.train.map(s => `${s.pr}@${s.head}`) }));
|
||||
const live = listTrains(env.repo.key).find(t => t.key === key && !TERMINAL_STATES.includes(t.state) && t.state !== 'red' && t.state !== 'unattributed');
|
||||
const live = listTrains(env.repo.keys).find(t => t.key === key && !TERMINAL_STATES.includes(t.state) && t.state !== 'red' && t.state !== 'unattributed');
|
||||
if (live) return { t: Object.assign(live, { held: order.held.map(s => s.pr) }), lines };
|
||||
const chain = buildChain(env.ctx.repoRoot, baseSha, order.train, env.policy.policy);
|
||||
if ('stoppedAt' in chain) {
|
||||
const without = order.train.filter(s => s.pr !== chain.stoppedAt);
|
||||
return outFailed({ code: 'QUEUE_TRAIN_CONFLICT', message: `#${chain.stoppedAt} conflicts with the prefix before it` }, [...lines,
|
||||
`QUEUE_TRAIN_CONFLICT: train ${key.slice(0, 12)} stopped at #${chain.stoppedAt} (conflicts: ${chain.conflicts.join(', ')}) after merging ${chain.merged.map(p => '#' + p).join(',') || '(none)'}; nothing dispatched, no branch pushed; fix: ${Q} train build --prs ${pinList(without)}`],
|
||||
without.length ? `${Q} train build --prs ${pinList(without)}` : 'none', 'none');
|
||||
`QUEUE_TRAIN_CONFLICT: train ${key.slice(0, 12)} stopped at #${chain.stoppedAt} (conflicts: ${chain.conflicts.join(', ')}) after merging ${chain.merged.map(p => '#' + p).join(',') || '(none)'}; nothing dispatched, no branch pushed; fix: ${Q} train build ${prsArgs(without, !!explicit)}`],
|
||||
without.length ? `${Q} train build ${prsArgs(without, !!explicit)}` : 'none', 'none');
|
||||
}
|
||||
const head = chain.prefixes.at(-1)!;
|
||||
const nonce = makeNonce('gate', head.commit, baseSha, randomBytes(3).toString('hex'), { purpose: 'train' });
|
||||
@@ -309,7 +337,7 @@ async function newTrain(env: TrainEnv, o: BuildOptions): Promise<{ t: TrainRecor
|
||||
return { lines, t: {
|
||||
schema: 1, kind: 'train', nonce, key, repo_key: env.repo.key, repo: env.repo.url, base: { ref: env.ctx.base, sha: baseSha }, policy: env.policy.source.label,
|
||||
slots: order.train, held: order.held.map(s => s.pr), prefixes: chain.prefixes, head: head.commit, tree: head.tree, branch: `train/${nonce}`,
|
||||
urgent: o.urgent, repair: o.repair, state: 'built', free: null, attempts: [], merged: [], superseded_by: null, effects: [], error: null,
|
||||
urgent: o.urgent, repair: o.repair, ...(explicit ? { explicit_order: true } : {}), state: 'built', free: null, attempts: [], merged: [], superseded_by: null, effects: [], error: null,
|
||||
created_at: now, updated_at: now,
|
||||
} };
|
||||
}
|
||||
@@ -342,7 +370,7 @@ async function freePhase(env: TrainEnv, slug: string, t: TrainRecord, o: BuildOp
|
||||
t.state = 'free-red';
|
||||
effect(t, `${env.train.free_workflow} dispatch refused by gh`);
|
||||
save(env, t);
|
||||
return outFailed({ code: 'QUEUE_TRAIN_FREE_RED', message: `gh could not dispatch ${env.train.free_workflow} on ${t.branch}` }, describe(t), `${Q} train build --prs ${pinList(t.slots)}`, run);
|
||||
return outFailed({ code: 'QUEUE_TRAIN_FREE_RED', message: `gh could not dispatch ${env.train.free_workflow} on ${t.branch}` }, describe(t), `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, run);
|
||||
}
|
||||
t.state = 'free-pending';
|
||||
effect(t, `${env.train.free_workflow} dispatched on ${t.branch}`);
|
||||
@@ -422,12 +450,12 @@ export async function buildTrain(ctx: QueueContext, o: BuildOptions): Promise<Tr
|
||||
if (!('kind' in t)) return t;
|
||||
if (o.dryRun) {
|
||||
return outOk([...lines, ...describe(t), `ESTIMATE: one ${env.train.gate_workflow} full gate (evals_all) on T${t.prefixes.length - 1} plus ${env.train.free_workflow}; dollar figure pending the T0 cost replay (lib/gate-cost.ts)`,
|
||||
'DRY-RUN: nothing written, pushed or dispatched'], `${Q} train build --prs ${pinList(t.slots)}`, 'none');
|
||||
'DRY-RUN: nothing written, pushed or dispatched'], `${Q} train build ${prsArgs(t.slots, t.explicit_order)}`, 'none');
|
||||
}
|
||||
if (t.state === 'built' && !t.attempts.length && !loadTrain(t.nonce)) {
|
||||
effect(t, 'train.json written');
|
||||
save(env, t);
|
||||
for (const old of listTrains(env.repo.key)) {
|
||||
for (const old of listTrains(env.repo.keys)) {
|
||||
if (old.nonce === t.nonce || TERMINAL_STATES.includes(old.state) || old.state === 'green' || old.state === 'merging') continue;
|
||||
if (!old.slots.some(s => t.slots.some((n: TrainSlot) => n.pr === s.pr))) continue;
|
||||
old.state = 'superseded';
|
||||
@@ -435,7 +463,7 @@ export async function buildTrain(ctx: QueueContext, o: BuildOptions): Promise<Tr
|
||||
save(env, old);
|
||||
}
|
||||
if (o.repair) {
|
||||
const f = activeFreeze(env.repo.key)!;
|
||||
const f = activeFreeze(env.repo.keys)!;
|
||||
f.repair = { pr: t.slots[0]!.pr, head: t.slots[0]!.head, train: t.nonce };
|
||||
f.updated_at = nowIso();
|
||||
persist(env.ctx.repoRoot, [f], { remote: env.remote });
|
||||
@@ -454,7 +482,7 @@ export function trainStatus(ctx: QueueContext, o: { train?: string }): TrainOut
|
||||
if ('code' in env) return outRefused(env, [], 'none', 'none');
|
||||
const restored = rebuildFromNotes(ctx.repoRoot, env.remote);
|
||||
const lines = [`NOTES: read ${restored.read} record(s), restored ${restored.restored} (${restored.detail})`];
|
||||
const trains = o.train ? [loadTrain(o.train)].filter((t): t is TrainRecord => !!t) : listTrains(env.repo.key).filter(t => !TERMINAL_STATES.includes(t.state));
|
||||
const trains = o.train ? [loadTrain(o.train)].filter((t): t is TrainRecord => !!t) : listTrains(env.repo.keys).filter(t => !TERMINAL_STATES.includes(t.state));
|
||||
if (o.train && !trains.length) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `no train record ${o.train} here or in refs/notes/gstack-trains` }, lines, `${Q} train status`, 'none');
|
||||
const slug = trains.length ? repoSlug(ctx) : null;
|
||||
const exec = execFor(ctx);
|
||||
@@ -482,7 +510,7 @@ export function trainStatus(ctx: QueueContext, o: { train?: string }): TrainOut
|
||||
lines.push(`NEXT(${t.nonce}): ${nextFor(t)}`);
|
||||
}
|
||||
if (!trains.length) lines.push('TRAIN: none live');
|
||||
const freeze = activeFreeze(env.repo.key);
|
||||
const freeze = activeFreeze(env.repo.keys);
|
||||
if (freeze) lines.push(...frozenLines(freeze));
|
||||
const single = trains.length === 1 ? trains[0]! : null;
|
||||
const next = freeze && !freeze.repair ? `${Q} train build --repair --prs <repair-pr>@<sha>` : single ? nextFor(single) : trains.length ? 'see each NEXT(<nonce>) line' : 'none';
|
||||
@@ -496,7 +524,7 @@ export function pruneTrains(ctx: QueueContext, o: { dryRun: boolean; train?: str
|
||||
rebuildFromNotes(ctx.repoRoot, env.remote);
|
||||
const lines: string[] = [];
|
||||
const rgit = (args: string[]) => git(ctx.repoRoot, args);
|
||||
for (const t of listTrains(env.repo.key).filter(x => !o.train || x.nonce === o.train)) {
|
||||
for (const t of listTrains(env.repo.keys).filter(x => !o.train || x.nonce === o.train)) {
|
||||
if (!TERMINAL_STATES.includes(t.state)) { lines.push(`KEEP: ${t.branch} (${t.state})`); continue; }
|
||||
if (!remoteBranchSha(rgit, env.remote, t.branch)) { lines.push(`GONE: ${t.branch} (${t.state})`); continue; }
|
||||
if (o.dryRun) { lines.push(`WOULD-DELETE: ${t.branch} (${t.state})`); continue; }
|
||||
|
||||
@@ -18,7 +18,7 @@ export type TrainHead =
|
||||
| { kind: 'invalid'; reason: string };
|
||||
|
||||
function git(repoRoot: string, args: string[]): string | null {
|
||||
const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 });
|
||||
const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });
|
||||
return r.status === 0 ? r.stdout : null;
|
||||
}
|
||||
|
||||
@@ -50,11 +50,18 @@ export function classifyTrainHead(o: { repoRoot: string; baseRef: string; head:
|
||||
}
|
||||
|
||||
const file = typeof policy.changelog === 'string' ? policy.changelog : 'CHANGELOG.md';
|
||||
const before = parseChangelog(show(mergeBase, file) ?? '');
|
||||
const after = parseChangelog(show(o.head, file) ?? '');
|
||||
const exists = (rev: string) => git(o.repoRoot, ['cat-file', '-e', `${rev}:${file}`]) !== null;
|
||||
const read = (rev: string) => (exists(rev) ? show(rev, file) : '');
|
||||
const [beforeText, afterText] = [read(mergeBase), read(o.head)];
|
||||
if (beforeText === null || afterText === null) return { kind: 'invalid', reason: `cannot read ${file} at ${beforeText === null ? `the merge base ${mergeBase.slice(0, 12)}` : o.head}` };
|
||||
const before = parseChangelog(beforeText);
|
||||
const after = parseChangelog(afterText);
|
||||
const unreleased = after.sections.filter(s => s.unreleased);
|
||||
if (unreleased.length > 1) return { kind: 'invalid', reason: `${file} has ${unreleased.length} [Unreleased] sections` };
|
||||
if (unreleased.length === 1 && after.sections[0] !== unreleased[0]) return { kind: 'invalid', reason: `${file}: [Unreleased] must be the top section` };
|
||||
const kept = new Set(after.sections.filter(s => !s.unreleased).map(s => s.version));
|
||||
const dropped = before.sections.filter(s => !s.unreleased && !kept.has(s.version)).map(s => s.version);
|
||||
if (dropped.length) return { kind: 'invalid', reason: `${file} drops released heading ${dropped.slice(0, 3).join(', ')}${dropped.length > 3 ? ` (+${dropped.length - 3})` : ''}; an unstamped head may only add its [Unreleased] section above the latest release` };
|
||||
const released = (c: typeof after) => [c.header.join('\n'), ...c.sections.filter(s => !s.unreleased).map(s => s.lines.join('\n'))];
|
||||
const was = released(before);
|
||||
const now = released(after);
|
||||
|
||||
Reference in new issue
Block a user