master-orchestrator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/package.json +56 -4
  5. package/src/adapters/agy.ts +285 -0
  6. package/src/adapters/claude.ts +317 -0
  7. package/src/adapters/codex.ts +162 -0
  8. package/src/adapters/common.ts +211 -0
  9. package/src/adapters/dsh.ts +356 -0
  10. package/src/adapters/fake-agent.mjs +50 -0
  11. package/src/adapters/fake.ts +88 -0
  12. package/src/adapters/gemini.ts +239 -0
  13. package/src/adapters/grok.ts +328 -0
  14. package/src/adapters/omp.ts +119 -0
  15. package/src/adapters/opencode.ts +228 -0
  16. package/src/adapters/pi.ts +284 -0
  17. package/src/adapters/registry.ts +27 -0
  18. package/src/adapters/types.ts +201 -0
  19. package/src/config/load.ts +290 -0
  20. package/src/config/profiles.ts +64 -0
  21. package/src/config/schema.ts +158 -0
  22. package/src/config/write.ts +83 -0
  23. package/src/engine/artifacts.ts +145 -0
  24. package/src/engine/baseline.ts +132 -0
  25. package/src/engine/execute.ts +437 -0
  26. package/src/engine/git.ts +32 -0
  27. package/src/engine/hostenv.ts +54 -0
  28. package/src/engine/registry.ts +280 -0
  29. package/src/engine/runner.ts +249 -0
  30. package/src/engine/types.ts +55 -0
  31. package/src/engine/verify.ts +100 -0
  32. package/src/index.ts +602 -0
  33. package/src/prompts/envelope.ts +29 -0
  34. package/src/prompts/templates.ts +389 -0
  35. package/src/ui/configure.ts +174 -0
  36. package/src/ui/dialogs.ts +88 -0
  37. package/src/ui/doctor.ts +120 -0
  38. package/src/ui/format.ts +94 -0
  39. package/src/ui/host.ts +100 -0
  40. package/src/ui/render.ts +86 -0
  41. package/src/ui/widget.ts +70 -0
  42. package/src/workflows/budget.ts +66 -0
  43. package/src/workflows/common.ts +100 -0
  44. package/src/workflows/debate.ts +488 -0
  45. package/src/workflows/host.ts +78 -0
  46. package/src/workflows/plan-exec.ts +807 -0
  47. package/src/workflows/plan.ts +407 -0
  48. package/src/workflows/planfile.ts +380 -0
  49. package/src/workflows/planstate.ts +229 -0
  50. package/src/workflows/verdict.ts +74 -0
@@ -0,0 +1,158 @@
1
+ import { Type, type Static } from "typebox";
2
+
3
+ const Int = (minimum: number, maximum: number, description: string) => Type.Integer({ minimum, maximum, description });
4
+ const NonEmpty = (description: string) => Type.String({ minLength: 1, description });
5
+ const Choice = <T extends string>(values: readonly T[], description: string) =>
6
+ Type.Union(
7
+ values.map((value) => Type.Literal(value)),
8
+ { description },
9
+ );
10
+
11
+ export const ROLE_NAMES = ["planner", "critic", "implementer", "reviewer", "debater"] as const;
12
+ export type RoleName = (typeof ROLE_NAMES)[number];
13
+
14
+ /** Roles whose listed profiles all take part; the others are ordered fallback chains. */
15
+ export const MULTI_ROLES: readonly RoleName[] = ["critic", "debater"];
16
+
17
+ export const AgentSettingsSchema = Type.Object(
18
+ {
19
+ enabled: Type.Optional(Type.Boolean({ description: "Default: true when the agent is detected" })),
20
+ bin: Type.Optional(NonEmpty("Executable name or absolute path")),
21
+ env: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Environment additions for every run" })),
22
+ extraArgs: Type.Optional(Type.Array(Type.String(), { description: "Arguments appended to every invocation" })),
23
+ allowUntestedVersion: Type.Optional(Type.Boolean({ description: "Run with a warning outside testedVersions" })),
24
+ persistTrust: Type.Optional(Type.Boolean({ description: "grok only: pass --trust, which persists the grant" })),
25
+ },
26
+ { additionalProperties: false },
27
+ );
28
+
29
+ export const ProfileSchema = Type.Object(
30
+ {
31
+ agent: NonEmpty("Agent id (codex, claude, opencode, pi, agy, grok, dsh, gemini, omp)"),
32
+ model: Type.Optional(NonEmpty("Model id passed verbatim to the agent")),
33
+ effort: Type.Optional(NonEmpty("Effort or thinking level, validated against the adapter's levels")),
34
+ timeoutMinutes: Type.Optional(Int(1, 720, "Run timeout")),
35
+ options: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Adapter-specific options" })),
36
+ description: Type.Optional(Type.String()),
37
+ },
38
+ { additionalProperties: false },
39
+ );
40
+
41
+ const RoleList = Type.Array(NonEmpty("Profile name or agent id"), { minItems: 1 });
42
+
43
+ export const ConfigFileSchema = Type.Object(
44
+ {
45
+ $schema: Type.Optional(Type.String()),
46
+ agents: Type.Optional(Type.Record(Type.String(), AgentSettingsSchema)),
47
+ profiles: Type.Optional(Type.Record(Type.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9._-]*$" }), ProfileSchema)),
48
+ roles: Type.Optional(
49
+ Type.Object(
50
+ {
51
+ planner: Type.Optional(RoleList),
52
+ critic: Type.Optional(RoleList),
53
+ implementer: Type.Optional(RoleList),
54
+ reviewer: Type.Optional(RoleList),
55
+ debater: Type.Optional(RoleList),
56
+ },
57
+ { additionalProperties: false },
58
+ ),
59
+ ),
60
+ defaults: Type.Optional(
61
+ Type.Object(
62
+ {
63
+ timeoutMinutes: Type.Optional(Int(1, 720, "Default run timeout")),
64
+ maxParallel: Type.Optional(Int(1, 16, "Parallel analyze runs")),
65
+ artifactRetentionDays: Type.Optional(Int(1, 365, "Days run artifacts are kept")),
66
+ },
67
+ { additionalProperties: false },
68
+ ),
69
+ ),
70
+ approval: Type.Optional(
71
+ Type.Object(
72
+ {
73
+ implementFromTool: Type.Optional(Choice(["auto", "ask"], "Model-initiated implement runs")),
74
+ workflowStart: Type.Optional(Choice(["ask", "auto"], "Cost gate before a debate or plan")),
75
+ },
76
+ { additionalProperties: false },
77
+ ),
78
+ ),
79
+ debate: Type.Optional(
80
+ Type.Object(
81
+ {
82
+ maxRounds: Type.Optional(Int(0, 5, "Rebuttal rounds after the opening")),
83
+ anonymize: Type.Optional(Type.Boolean()),
84
+ minParticipants: Type.Optional(Int(2, 9, "Minimum debaters")),
85
+ },
86
+ { additionalProperties: false },
87
+ ),
88
+ ),
89
+ planning: Type.Optional(
90
+ Type.Object(
91
+ {
92
+ maxRevisions: Type.Optional(Int(0, 3, "Revision loops after critique")),
93
+ execution: Type.Optional(
94
+ Type.Object(
95
+ {
96
+ mode: Type.Optional(Choice(["auto", "block"], "auto: stop on failure; block: confirm each block")),
97
+ maxFixAttempts: Type.Optional(Int(0, 5, "Fix cycles per block")),
98
+ review: Type.Optional(Choice(["per-block", "none"], "Independent review")),
99
+ commit: Type.Optional(Choice(["none", "per-block"], "Commit accepted blocks")),
100
+ requireCleanTree: Type.Optional(Type.Boolean()),
101
+ },
102
+ { additionalProperties: false },
103
+ ),
104
+ ),
105
+ },
106
+ { additionalProperties: false },
107
+ ),
108
+ ),
109
+ prompts: Type.Optional(
110
+ Type.Object(
111
+ { dir: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "Template override directory" })) },
112
+ { additionalProperties: false },
113
+ ),
114
+ ),
115
+ },
116
+ { additionalProperties: false },
117
+ );
118
+
119
+ export type ConfigFile = Static<typeof ConfigFileSchema>;
120
+ export type AgentSettings = Static<typeof AgentSettingsSchema>;
121
+ export type ProfileSettings = Static<typeof ProfileSchema>;
122
+
123
+ export interface OrchestratorConfig {
124
+ agents: Record<string, AgentSettings>;
125
+ profiles: Record<string, ProfileSettings>;
126
+ roles: Partial<Record<RoleName, string[]>>;
127
+ defaults: { timeoutMinutes: number; maxParallel: number; artifactRetentionDays: number };
128
+ approval: { implementFromTool: "auto" | "ask"; workflowStart: "ask" | "auto" };
129
+ debate: { maxRounds: number; anonymize: boolean; minParticipants: number };
130
+ planning: {
131
+ maxRevisions: number;
132
+ execution: {
133
+ mode: "auto" | "block";
134
+ maxFixAttempts: number;
135
+ review: "per-block" | "none";
136
+ commit: "none" | "per-block";
137
+ requireCleanTree: boolean;
138
+ };
139
+ };
140
+ /** Absolute directory of template overrides, or null. */
141
+ prompts: { dir: string | null };
142
+ }
143
+
144
+ export function defaultConfig(): OrchestratorConfig {
145
+ return {
146
+ agents: {},
147
+ profiles: {},
148
+ roles: {},
149
+ defaults: { timeoutMinutes: 30, maxParallel: 4, artifactRetentionDays: 14 },
150
+ approval: { implementFromTool: "auto", workflowStart: "ask" },
151
+ debate: { maxRounds: 2, anonymize: true, minParticipants: 2 },
152
+ planning: {
153
+ maxRevisions: 1,
154
+ execution: { mode: "auto", maxFixAttempts: 2, review: "per-block", commit: "none", requireCleanTree: true },
155
+ },
156
+ prompts: { dir: null },
157
+ };
158
+ }
@@ -0,0 +1,83 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import type { AgentAdapter } from "../adapters/types.ts";
4
+ import { crossValidate, mergeConfig, stripJsonComments, userConfigPath, validateConfigFile, type ConfigError } from "./load.ts";
5
+ import { defaultConfig, type ConfigFile, type RoleName } from "./schema.ts";
6
+
7
+ export interface UserConfigFile {
8
+ path: string;
9
+ present: boolean;
10
+ value: ConfigFile;
11
+ /** Rewriting the file drops its comments. */
12
+ hasComments: boolean;
13
+ error?: string;
14
+ }
15
+
16
+ export async function readUserConfig(agentDir: string): Promise<UserConfigFile> {
17
+ const path = userConfigPath(agentDir);
18
+ let text: string;
19
+ try {
20
+ text = await readFile(path, "utf8");
21
+ } catch (error) {
22
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path, present: false, value: {}, hasComments: false };
23
+ return { path, present: true, value: {}, hasComments: false, error: `cannot read: ${(error as Error).message}` };
24
+ }
25
+ const stripped = stripJsonComments(text);
26
+ try {
27
+ return { path, present: true, value: JSON.parse(stripped) as ConfigFile, hasComments: stripped !== text };
28
+ } catch (error) {
29
+ return { path, present: true, value: {}, hasComments: false, error: `invalid JSON: ${(error as Error).message}` };
30
+ }
31
+ }
32
+
33
+ /** Schema and cross-reference errors of a user file on its own (the project file is not involved). */
34
+ export function checkUserConfig(value: unknown, path: string, adapters: ReadonlyMap<string, AgentAdapter>): ConfigError[] {
35
+ const schemaErrors = validateConfigFile(value, path);
36
+ if (schemaErrors.length > 0) return schemaErrors;
37
+ const { $schema: _ignored, ...rest } = value as ConfigFile;
38
+ return crossValidate(mergeConfig(defaultConfig(), rest), adapters, path);
39
+ }
40
+
41
+ /** Writes the user file atomically after validating it. Throws with the errors when it does not validate. */
42
+ export async function writeUserConfig(agentDir: string, value: ConfigFile, adapters: ReadonlyMap<string, AgentAdapter>): Promise<string> {
43
+ const path = userConfigPath(agentDir);
44
+ const errors = checkUserConfig(value, path, adapters);
45
+ if (errors.length > 0) throw new Error(errors.map((error) => `${error.pointer}: ${error.message}`).join("\n"));
46
+ await mkdir(dirname(path), { recursive: true });
47
+ const temp = `${path}.${process.pid}.tmp`;
48
+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`);
49
+ await rename(temp, path);
50
+ return path;
51
+ }
52
+
53
+ export function withRole(value: ConfigFile, role: RoleName, profiles: string[]): ConfigFile {
54
+ return { ...value, roles: { ...(value.roles ?? {}), [role]: profiles } };
55
+ }
56
+
57
+ /**
58
+ * A starter file from the detected agents: each agent enabled, and roles filled from them in the order given so the
59
+ * user has something to review. The implicit profiles (one per agent) need no entry.
60
+ */
61
+ export function starterConfig(detected: readonly string[]): ConfigFile {
62
+ const agents: Record<string, { enabled: boolean; persistTrust?: boolean }> = {};
63
+ for (const id of detected) agents[id] = id === "grok" ? { enabled: true, persistTrust: false } : { enabled: true };
64
+ const [first, second, third] = detected;
65
+ const roles: Partial<Record<RoleName, string[]>> = {};
66
+ if (first) {
67
+ roles.planner = second ? [first, second] : [first];
68
+ roles.implementer = second ? [first, second] : [first];
69
+ roles.reviewer = [second ?? first];
70
+ roles.critic = [second ?? first];
71
+ if (second) roles.debater = third ? [first, second, third] : [first, second];
72
+ }
73
+ const defaults = defaultConfig();
74
+ return {
75
+ agents,
76
+ profiles: {},
77
+ roles,
78
+ defaults: defaults.defaults,
79
+ approval: defaults.approval,
80
+ debate: defaults.debate,
81
+ planning: defaults.planning,
82
+ } as unknown as ConfigFile;
83
+ }
@@ -0,0 +1,145 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { realpathSync } from "node:fs";
3
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+
6
+ export function orchestratorDir(agentDir: string): string {
7
+ return join(agentDir, "master-orchestrator");
8
+ }
9
+
10
+ export function realWorkspace(workspace: string): string {
11
+ try {
12
+ return realpathSync(workspace);
13
+ } catch {
14
+ return workspace;
15
+ }
16
+ }
17
+
18
+ /** Stable key of a workspace, derived from its real path. */
19
+ export function workspaceHash(workspace: string): string {
20
+ return createHash("sha256").update(realWorkspace(workspace)).digest("hex").slice(0, 16);
21
+ }
22
+
23
+ export function lockPath(agentDir: string, workspace: string): string {
24
+ return join(orchestratorDir(agentDir), "locks", `${workspaceHash(workspace)}.lock`);
25
+ }
26
+
27
+ function timestamp(date = new Date()): string {
28
+ const pad = (value: number) => String(value).padStart(2, "0");
29
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
30
+ }
31
+
32
+ export function newRunId(agent: string): string {
33
+ return `${timestamp()}-${agent.replace(/[^a-z0-9-]/gi, "")}-${randomBytes(2).toString("hex")}`;
34
+ }
35
+
36
+ export function newWorkflowId(kind: string): string {
37
+ return `${timestamp()}-${kind}-${randomBytes(2).toString("hex")}`;
38
+ }
39
+
40
+ export function runsRoot(agentDir: string, workspace: string): string {
41
+ return join(orchestratorDir(agentDir), "runs", workspaceHash(workspace));
42
+ }
43
+
44
+ /** Creates `<agentDir>/master-orchestrator/runs/<workspace-hash>/<runId>/` with a `scratch/` directory. */
45
+ export async function createRunDir(agentDir: string, workspace: string, runId: string): Promise<string> {
46
+ const dir = join(runsRoot(agentDir, workspace), runId);
47
+ await mkdir(join(dir, "scratch"), { recursive: true });
48
+ return dir;
49
+ }
50
+
51
+ export async function createWorkflowDir(agentDir: string, workspace: string, id: string): Promise<string> {
52
+ const dir = join(orchestratorDir(agentDir), "workflows", workspaceHash(workspace), id);
53
+ await mkdir(dir, { recursive: true });
54
+ return dir;
55
+ }
56
+
57
+ export interface RunMeta {
58
+ runId: string;
59
+ profile: string;
60
+ agent: string;
61
+ model?: string;
62
+ effort?: string;
63
+ mode: "analyze" | "implement";
64
+ workspace: string;
65
+ startedAt: string;
66
+ endedAt?: string;
67
+ status?: string;
68
+ reason?: string;
69
+ sessionId?: string;
70
+ pid?: number;
71
+ /** How the process ended: `null` when it was killed by a signal or never started. */
72
+ exitCode?: number | null;
73
+ signal?: string | null;
74
+ args?: string[];
75
+ workflowId?: string;
76
+ label?: string;
77
+ }
78
+
79
+ export async function writeMeta(runDir: string, meta: RunMeta): Promise<void> {
80
+ await writeFile(join(runDir, "meta.json"), `${JSON.stringify(meta, null, 2)}\n`);
81
+ }
82
+
83
+ export async function readMeta(runDir: string): Promise<RunMeta | undefined> {
84
+ try {
85
+ return JSON.parse(await readFile(join(runDir, "meta.json"), "utf8")) as RunMeta;
86
+ } catch {
87
+ return undefined;
88
+ }
89
+ }
90
+
91
+ /** Recent runs of a workspace, newest first. */
92
+ export async function listRecentRuns(agentDir: string, workspace: string, limit = 20): Promise<Array<RunMeta & { dir: string }>> {
93
+ const root = runsRoot(agentDir, workspace);
94
+ let names: string[];
95
+ try {
96
+ names = await readdir(root);
97
+ } catch {
98
+ return [];
99
+ }
100
+ const result: Array<RunMeta & { dir: string }> = [];
101
+ for (const name of names.sort().reverse().slice(0, limit)) {
102
+ const dir = join(root, name);
103
+ const meta = await readMeta(dir);
104
+ if (meta) result.push({ ...meta, dir });
105
+ }
106
+ return result;
107
+ }
108
+
109
+ /** Removes run and workflow directories older than the retention period. Returns how many were removed. */
110
+ export async function pruneArtifacts(agentDir: string, retentionDays: number, keep: ReadonlySet<string> = new Set()): Promise<number> {
111
+ const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
112
+ let removed = 0;
113
+ for (const kind of ["runs", "workflows"]) {
114
+ const root = join(orchestratorDir(agentDir), kind);
115
+ let workspaces: string[];
116
+ try {
117
+ workspaces = await readdir(root);
118
+ } catch {
119
+ continue;
120
+ }
121
+ for (const workspace of workspaces) {
122
+ const workspaceDir = join(root, workspace);
123
+ let entries: string[];
124
+ try {
125
+ entries = await readdir(workspaceDir);
126
+ } catch {
127
+ continue;
128
+ }
129
+ for (const entry of entries) {
130
+ if (keep.has(entry)) continue;
131
+ const dir = join(workspaceDir, entry);
132
+ try {
133
+ const info = await stat(dir);
134
+ if (info.isDirectory() && info.mtimeMs < cutoff) {
135
+ await rm(dir, { recursive: true, force: true });
136
+ removed++;
137
+ }
138
+ } catch {
139
+ // Removed concurrently.
140
+ }
141
+ }
142
+ }
143
+ }
144
+ return removed;
145
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, readFile, readlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { git, gitOk } from "./git.ts";
5
+
6
+ /**
7
+ * Snapshot of a workspace before a run. Serializable and free of absolute paths, so it can live in a versioned plan
8
+ * state file. `entries` maps every modified, staged or untracked path (relative to the workspace) to its porcelain
9
+ * status and a content hash.
10
+ */
11
+ export interface Baseline {
12
+ git: boolean;
13
+ /** Why the workspace has no baseline (not a Git work tree, git missing). */
14
+ reason?: string;
15
+ branch?: string | null;
16
+ head?: string | null;
17
+ stash?: string | null;
18
+ entries: Record<string, string>;
19
+ takenAt: string;
20
+ }
21
+
22
+ export interface ChangeReport {
23
+ git: boolean;
24
+ /** Paths (relative to the workspace) whose state differs from the baseline. */
25
+ changed: string[];
26
+ /** New commits, branch changes, stash changes. */
27
+ departures: string[];
28
+ /** Always set: what the report does not cover. */
29
+ note: string;
30
+ head?: string | null;
31
+ }
32
+
33
+ const COVERAGE_NOTE = "Ignored files and anything outside the workspace are not covered.";
34
+ const LARGE_FILE_BYTES = 4 * 1024 * 1024;
35
+
36
+ export async function takeBaseline(workspace: string): Promise<Baseline> {
37
+ const takenAt = new Date().toISOString();
38
+ const inside = await gitOk(workspace, ["rev-parse", "--is-inside-work-tree"]);
39
+ if (inside !== "true") return { git: false, reason: "not a Git work tree", entries: {}, takenAt };
40
+
41
+ const [prefix, branch, head, stash, status] = await Promise.all([
42
+ gitOk(workspace, ["rev-parse", "--show-prefix"]),
43
+ gitOk(workspace, ["symbolic-ref", "-q", "--short", "HEAD"]),
44
+ gitOk(workspace, ["rev-parse", "-q", "--verify", "HEAD"]),
45
+ gitOk(workspace, ["rev-parse", "-q", "--verify", "refs/stash"]),
46
+ git(workspace, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignore-submodules=dirty", "--", "."]),
47
+ ]);
48
+ if (status.code !== 0) return { git: false, reason: `git status failed: ${status.stderr.trim()}`, entries: {}, takenAt };
49
+
50
+ const entries: Record<string, string> = {};
51
+ for (const { xy, path } of parsePorcelain(status.stdout, prefix ?? "")) {
52
+ entries[path] = `${xy}:${await hashPath(join(workspace, path))}`;
53
+ }
54
+ return { git: true, branch: branch ?? null, head: head ?? null, stash: stash ?? null, entries, takenAt };
55
+ }
56
+
57
+ /** Compares the workspace now (or a later baseline) with `before`. */
58
+ export async function diffBaseline(workspace: string, before: Baseline, after?: Baseline): Promise<ChangeReport> {
59
+ if (!before.git) {
60
+ return { git: false, changed: [], departures: [], note: `Changes cannot be computed: ${before.reason ?? "no Git baseline"}.` };
61
+ }
62
+ const now = after ?? (await takeBaseline(workspace));
63
+ if (!now.git) return { git: false, changed: [], departures: [], note: `Changes cannot be computed: ${now.reason}.` };
64
+
65
+ const changed = new Set<string>();
66
+ for (const path of new Set([...Object.keys(before.entries), ...Object.keys(now.entries)])) {
67
+ if (before.entries[path] !== now.entries[path]) changed.add(path);
68
+ }
69
+
70
+ const departures: string[] = [];
71
+ if (before.head !== now.head) {
72
+ if (before.head && now.head) {
73
+ const count = await gitOk(workspace, ["rev-list", "--count", `${before.head}..${now.head}`]);
74
+ departures.push(
75
+ count && count !== "0"
76
+ ? `HEAD moved from ${short(before.head)} to ${short(now.head)} (${count} new commit${count === "1" ? "" : "s"})`
77
+ : `HEAD moved from ${short(before.head)} to ${short(now.head)}`,
78
+ );
79
+ const diff = await git(workspace, ["diff", "--name-only", "--relative", "-z", before.head, now.head, "--", "."]);
80
+ if (diff.code === 0) for (const path of diff.stdout.split("\0").filter(Boolean)) changed.add(path);
81
+ } else {
82
+ departures.push(`HEAD changed from ${before.head ? short(before.head) : "no commit"} to ${now.head ? short(now.head) : "no commit"}`);
83
+ }
84
+ }
85
+ if (before.branch !== now.branch) departures.push(`branch changed from ${before.branch ?? "detached"} to ${now.branch ?? "detached"}`);
86
+ if (before.stash !== now.stash) departures.push("the stash changed");
87
+
88
+ return { git: true, changed: [...changed].sort(), departures, note: COVERAGE_NOTE, head: now.head };
89
+ }
90
+
91
+ /** Parses `git status --porcelain=v1 -z` and returns paths relative to the workspace (`prefix` is stripped). */
92
+ export function parsePorcelain(output: string, prefix: string): Array<{ xy: string; path: string }> {
93
+ const tokens = output.split("\0");
94
+ const result: Array<{ xy: string; path: string }> = [];
95
+ for (let i = 0; i < tokens.length; i++) {
96
+ const token = tokens[i];
97
+ if (token.length < 4) continue;
98
+ const xy = token.slice(0, 2);
99
+ const path = token.slice(3);
100
+ result.push({ xy, path });
101
+ // Renames and copies carry the original path in the next token.
102
+ if (xy.includes("R") || xy.includes("C")) {
103
+ const original = tokens[i + 1];
104
+ if (original) result.push({ xy: "D?", path: original });
105
+ i++;
106
+ }
107
+ }
108
+ return result
109
+ .filter((entry) => !prefix || entry.path.startsWith(prefix))
110
+ .map((entry) => ({ xy: entry.xy, path: prefix ? entry.path.slice(prefix.length) : entry.path }));
111
+ }
112
+
113
+ async function hashPath(absolute: string): Promise<string> {
114
+ try {
115
+ const info = await lstat(absolute);
116
+ if (info.isSymbolicLink()) return `link:${await readlink(absolute)}`;
117
+ if (info.isDirectory()) return "dir";
118
+ if (info.size > LARGE_FILE_BYTES) return `size:${info.size}:${Math.trunc(info.mtimeMs)}`;
119
+ return createHash("sha1").update(await readFile(absolute)).digest("hex");
120
+ } catch {
121
+ return "missing";
122
+ }
123
+ }
124
+
125
+ /** Content hash of a workspace-relative path, as stored in baselines. */
126
+ export function hashWorkspaceFile(workspace: string, path: string): Promise<string> {
127
+ return hashPath(join(workspace, path));
128
+ }
129
+
130
+ function short(sha: string): string {
131
+ return sha.slice(0, 10);
132
+ }