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,280 @@
1
+ import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import type { Mode } from "../adapters/types.ts";
5
+
6
+ export interface ActiveRun {
7
+ runId: string;
8
+ profile: string;
9
+ agent: string;
10
+ model?: string;
11
+ mode: Mode;
12
+ workspace: string;
13
+ /** Phase or step shown in the widget, e.g. "round 1/2" or "step 2.1". */
14
+ label?: string;
15
+ workflowId?: string;
16
+ startedAt: number;
17
+ lastActivity?: string;
18
+ controller: AbortController;
19
+ /** Runs in the same workspace whose lifetime overlapped this one. */
20
+ overlaps: Set<string>;
21
+ }
22
+
23
+ export interface WorkflowEntry {
24
+ id: string;
25
+ kind: "debate" | "plan";
26
+ header: string;
27
+ controller: AbortController;
28
+ /** Set by `/plan abort` before aborting: the plan ends as aborted instead of paused. */
29
+ stopIntent?: "abort";
30
+ }
31
+
32
+ /** Active runs and workflows of one extension instance. They die with it by design. */
33
+ export class RunRegistry {
34
+ private readonly runs = new Map<string, ActiveRun>();
35
+ private readonly workflows = new Map<string, WorkflowEntry>();
36
+ private readonly listeners = new Set<() => void>();
37
+ private analyzeActive = 0;
38
+ private readonly waiters: Array<() => void> = [];
39
+
40
+ private readonly maxParallel: () => number;
41
+
42
+ constructor(maxParallel: () => number) {
43
+ this.maxParallel = maxParallel;
44
+ }
45
+
46
+ onChange(listener: () => void): () => void {
47
+ this.listeners.add(listener);
48
+ return () => this.listeners.delete(listener);
49
+ }
50
+
51
+ private emit(): void {
52
+ for (const listener of this.listeners) {
53
+ try {
54
+ listener();
55
+ } catch {
56
+ // UI listeners must not break the engine.
57
+ }
58
+ }
59
+ }
60
+
61
+ add(run: ActiveRun): void {
62
+ for (const other of this.runs.values()) {
63
+ if (other.workspace !== run.workspace) continue;
64
+ other.overlaps.add(run.runId);
65
+ run.overlaps.add(other.runId);
66
+ }
67
+ this.runs.set(run.runId, run);
68
+ this.emit();
69
+ }
70
+
71
+ update(runId: string, patch: Partial<Pick<ActiveRun, "lastActivity" | "label">>): void {
72
+ const run = this.runs.get(runId);
73
+ if (!run) return;
74
+ Object.assign(run, patch);
75
+ this.emit();
76
+ }
77
+
78
+ remove(runId: string): void {
79
+ if (this.runs.delete(runId)) this.emit();
80
+ }
81
+
82
+ get(runId: string): ActiveRun | undefined {
83
+ return this.runs.get(runId);
84
+ }
85
+
86
+ list(): ActiveRun[] {
87
+ return [...this.runs.values()];
88
+ }
89
+
90
+ /** Cancels a run, a workflow, or everything. Returns what was cancelled. */
91
+ cancel(target: string): string[] {
92
+ const cancelled: string[] = [];
93
+ if (target === "all") {
94
+ for (const workflow of this.workflows.values()) {
95
+ workflow.controller.abort();
96
+ cancelled.push(workflow.id);
97
+ }
98
+ for (const run of this.runs.values()) {
99
+ run.controller.abort();
100
+ cancelled.push(run.runId);
101
+ }
102
+ return cancelled;
103
+ }
104
+ const workflow = this.workflows.get(target);
105
+ if (workflow) {
106
+ workflow.controller.abort();
107
+ cancelled.push(workflow.id);
108
+ }
109
+ const run = this.runs.get(target);
110
+ if (run) {
111
+ run.controller.abort();
112
+ cancelled.push(run.runId);
113
+ }
114
+ return cancelled;
115
+ }
116
+
117
+ addWorkflow(entry: WorkflowEntry): void {
118
+ this.workflows.set(entry.id, entry);
119
+ this.emit();
120
+ }
121
+
122
+ setWorkflowHeader(id: string, header: string): void {
123
+ const entry = this.workflows.get(id);
124
+ if (!entry) return;
125
+ entry.header = header;
126
+ this.emit();
127
+ }
128
+
129
+ removeWorkflow(id: string): void {
130
+ if (this.workflows.delete(id)) this.emit();
131
+ }
132
+
133
+ listWorkflows(): WorkflowEntry[] {
134
+ return [...this.workflows.values()];
135
+ }
136
+
137
+ /** Waits for a free analyze slot (bounded by `defaults.maxParallel`). */
138
+ async acquireAnalyzeSlot(signal?: AbortSignal): Promise<() => void> {
139
+ while (this.analyzeActive >= this.maxParallel()) {
140
+ if (signal?.aborted) throw new Error("cancelled while waiting for a free slot");
141
+ await new Promise<void>((resolve) => {
142
+ const onAbort = () => resolve();
143
+ signal?.addEventListener("abort", onAbort, { once: true });
144
+ this.waiters.push(() => {
145
+ signal?.removeEventListener("abort", onAbort);
146
+ resolve();
147
+ });
148
+ });
149
+ }
150
+ if (signal?.aborted) throw new Error("cancelled while waiting for a free slot");
151
+ this.analyzeActive += 1;
152
+ let released = false;
153
+ return () => {
154
+ if (released) return;
155
+ released = true;
156
+ this.analyzeActive -= 1;
157
+ this.waiters.shift()?.();
158
+ };
159
+ }
160
+
161
+ /** Aborts every workflow and run (session shutdown). */
162
+ shutdown(): void {
163
+ this.cancel("all");
164
+ }
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------------------------------------------------
168
+ // Workspace write lock: one implement run (or executing plan) per workspace, across pi processes.
169
+
170
+ export interface LockHolder {
171
+ pid: number;
172
+ /** Identifies the extension instance inside the process; a torn-down instance's lock is stale. */
173
+ instanceId: string;
174
+ sessionId?: string;
175
+ owner: string; // "run:<id>" or "plan:<id>"
176
+ workspace: string;
177
+ startedAt: string;
178
+ }
179
+
180
+ export interface LockHandle {
181
+ path: string;
182
+ holder: LockHolder;
183
+ release(): void;
184
+ }
185
+
186
+ export class WriteLockHeldError extends Error {
187
+ readonly holder: LockHolder;
188
+ constructor(holder: LockHolder) {
189
+ super(
190
+ `The workspace write lock is held by ${holder.owner} (pid ${holder.pid}` +
191
+ `${holder.sessionId ? `, pi session ${holder.sessionId}` : ""}, since ${holder.startedAt}). ` +
192
+ "Only one implement run or executing plan per workspace is allowed.",
193
+ );
194
+ this.name = "WriteLockHeldError";
195
+ this.holder = holder;
196
+ }
197
+ }
198
+
199
+ const LIVE_INSTANCES = Symbol.for("master-orchestrator.live-instances");
200
+
201
+ /** Ids of the extension instances alive in this process (shared across module reloads). */
202
+ export function liveInstances(): Set<string> {
203
+ const store = globalThis as unknown as Record<symbol, Set<string> | undefined>;
204
+ store[LIVE_INSTANCES] ??= new Set<string>();
205
+ return store[LIVE_INSTANCES];
206
+ }
207
+
208
+ function processAlive(pid: number): boolean {
209
+ try {
210
+ process.kill(pid, 0);
211
+ return true;
212
+ } catch (error) {
213
+ return (error as NodeJS.ErrnoException).code === "EPERM";
214
+ }
215
+ }
216
+
217
+ function readHolder(path: string): LockHolder | undefined {
218
+ try {
219
+ return JSON.parse(readFileSync(path, "utf8")) as LockHolder;
220
+ } catch {
221
+ return undefined;
222
+ }
223
+ }
224
+
225
+ function isStale(holder: LockHolder | undefined): boolean {
226
+ if (!holder || typeof holder.pid !== "number") return true;
227
+ if (!processAlive(holder.pid)) return true;
228
+ return holder.pid === process.pid && !liveInstances().has(holder.instanceId);
229
+ }
230
+
231
+ /** Takes the lock atomically, taking over a stale one. Throws `WriteLockHeldError` when a live holder has it. */
232
+ export async function acquireWriteLock(path: string, holder: Omit<LockHolder, "pid" | "startedAt">): Promise<LockHandle> {
233
+ await mkdir(dirname(path), { recursive: true });
234
+ const record: LockHolder = { ...holder, pid: process.pid, startedAt: new Date().toISOString() };
235
+ for (let attempt = 0; attempt < 3; attempt++) {
236
+ try {
237
+ const fd = openSync(path, "wx");
238
+ try {
239
+ writeSync(fd, JSON.stringify(record, null, 2));
240
+ } finally {
241
+ closeSync(fd);
242
+ }
243
+ let released = false;
244
+ return {
245
+ path,
246
+ holder: record,
247
+ release() {
248
+ if (released) return;
249
+ released = true;
250
+ const current = readHolder(path);
251
+ if (current && current.pid === record.pid && current.instanceId === record.instanceId && current.owner === record.owner) {
252
+ try {
253
+ unlinkSync(path);
254
+ } catch {
255
+ // Already removed.
256
+ }
257
+ }
258
+ },
259
+ };
260
+ } catch (error) {
261
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
262
+ const current = readHolder(path);
263
+ if (!isStale(current)) throw new WriteLockHeldError(current as LockHolder);
264
+ try {
265
+ unlinkSync(path);
266
+ } catch {
267
+ // Another process took it over first; try again.
268
+ }
269
+ }
270
+ }
271
+ const current = readHolder(path);
272
+ if (current) throw new WriteLockHeldError(current);
273
+ throw new Error(`Could not take the workspace write lock at ${path}`);
274
+ }
275
+
276
+ /** Reads the current holder of a lock, ignoring stale ones. */
277
+ export function readLiveHolder(path: string): LockHolder | undefined {
278
+ const holder = readHolder(path);
279
+ return holder && !isStale(holder) ? holder : undefined;
280
+ }
@@ -0,0 +1,249 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { createWriteStream } from "node:fs";
3
+
4
+ export interface ProcessSpec {
5
+ command: string;
6
+ args: string[];
7
+ cwd: string;
8
+ env: Record<string, string>;
9
+ /** Written to stdin, then stdin is closed. Undefined means stdin is /dev/null. */
10
+ stdin?: string;
11
+ timeoutMs: number;
12
+ stopSignal: "SIGINT" | "SIGTERM";
13
+ /** Delay between escalation steps of the stop sequence. */
14
+ graceMs?: number;
15
+ signal?: AbortSignal;
16
+ eventsPath: string;
17
+ stderrPath: string;
18
+ onLine: (line: string) => void;
19
+ /** Called with the stderr tail after each chunk. */
20
+ onStderr?: (tail: string) => void;
21
+ }
22
+
23
+ export interface ProcessOutcome {
24
+ exitCode: number | null;
25
+ signal: string | null;
26
+ stderrTail: string;
27
+ timedOut: boolean;
28
+ cancelled: boolean;
29
+ spawnError?: string;
30
+ durationMs: number;
31
+ }
32
+
33
+ const STDERR_TAIL_BYTES = 64 * 1024;
34
+ const DEFAULT_GRACE_MS = 10_000;
35
+ /** How long to wait for stdio to close after the child exited and its group was killed. */
36
+ const CLOSE_WAIT_MS = 3_000;
37
+
38
+ /**
39
+ * Runs one child in its own process group, never on a TTY. Stdout is split into lines (a partial last line is
40
+ * buffered and flushed at the end) and copied verbatim to `eventsPath`; stderr goes to `stderrPath`.
41
+ *
42
+ * Stop sequence (timeout or abort): `stopSignal` to the group, SIGTERM after `graceMs` when the first signal was not
43
+ * SIGTERM, SIGKILL after a further `graceMs`. Whatever is left in the group after the child exits is killed. The stop
44
+ * sequence also reaches descendants that moved to a group of their own (Gemini CLI runs its shell tool under setsid):
45
+ * they are listed before each signal, because once the child is gone they are reparented and cannot be traced to it.
46
+ */
47
+ export function runProcess(spec: ProcessSpec): Promise<ProcessOutcome> {
48
+ const startedAt = Date.now();
49
+ const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
50
+
51
+ if (spec.signal?.aborted) {
52
+ return Promise.resolve({
53
+ exitCode: null,
54
+ signal: null,
55
+ stderrTail: "",
56
+ timedOut: false,
57
+ cancelled: true,
58
+ durationMs: 0,
59
+ });
60
+ }
61
+
62
+ return new Promise<ProcessOutcome>((resolve) => {
63
+ const events = createWriteStream(spec.eventsPath, { flags: "a" });
64
+ const stderrFile = createWriteStream(spec.stderrPath, { flags: "a" });
65
+ let stderrTail = "";
66
+ let pending = "";
67
+ let timedOut = false;
68
+ let cancelled = false;
69
+ let stopping = false;
70
+ let exited = false;
71
+ let settled = false;
72
+ let exitCode: number | null = null;
73
+ let exitSignal: string | null = null;
74
+ let spawnError: string | undefined;
75
+ const timers: NodeJS.Timeout[] = [];
76
+
77
+ const child = spawn(spec.command, spec.args, {
78
+ cwd: spec.cwd,
79
+ env: spec.env,
80
+ detached: true,
81
+ stdio: [spec.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
82
+ });
83
+
84
+ // Groups of descendants that left the child's group, collected while stopping.
85
+ const foreignGroups = new Set<number>();
86
+ const killGroup = (signal: NodeJS.Signals) => {
87
+ if (child.pid === undefined) return;
88
+ if (stopping && !exited) for (const group of descendantGroups(child.pid)) foreignGroups.add(group);
89
+ for (const group of [child.pid, ...foreignGroups]) {
90
+ try {
91
+ process.kill(-group, signal);
92
+ } catch {
93
+ // ESRCH: the group is already gone.
94
+ }
95
+ }
96
+ };
97
+
98
+ const stop = (why: "timeout" | "cancel") => {
99
+ if (stopping || exited) return;
100
+ stopping = true;
101
+ if (why === "timeout") timedOut = true;
102
+ else cancelled = true;
103
+ killGroup(spec.stopSignal);
104
+ if (spec.stopSignal === "SIGTERM") {
105
+ timers.push(setTimeout(() => killGroup("SIGKILL"), graceMs));
106
+ } else {
107
+ timers.push(setTimeout(() => killGroup("SIGTERM"), graceMs));
108
+ timers.push(setTimeout(() => killGroup("SIGKILL"), graceMs * 2));
109
+ }
110
+ };
111
+
112
+ const emitLine = (line: string) => {
113
+ const clean = line.endsWith("\r") ? line.slice(0, -1) : line;
114
+ try {
115
+ spec.onLine(clean);
116
+ } catch {
117
+ // A parser error must not kill the run; the adapter's state stays as it was.
118
+ }
119
+ };
120
+
121
+ const finish = () => {
122
+ if (settled) return;
123
+ settled = true;
124
+ for (const timer of timers) clearTimeout(timer);
125
+ spec.signal?.removeEventListener("abort", onAbort);
126
+ if (pending) {
127
+ emitLine(pending);
128
+ pending = "";
129
+ }
130
+ const done = () =>
131
+ resolve({
132
+ exitCode,
133
+ signal: exitSignal,
134
+ stderrTail,
135
+ timedOut,
136
+ cancelled,
137
+ spawnError,
138
+ durationMs: Date.now() - startedAt,
139
+ });
140
+ let open = 2;
141
+ const closed = () => {
142
+ open -= 1;
143
+ if (open === 0) done();
144
+ };
145
+ events.end(closed);
146
+ stderrFile.end(closed);
147
+ };
148
+
149
+ const onAbort = () => stop("cancel");
150
+ spec.signal?.addEventListener("abort", onAbort, { once: true });
151
+ timers.push(setTimeout(() => stop("timeout"), spec.timeoutMs));
152
+
153
+ child.on("error", (error: NodeJS.ErrnoException) => {
154
+ if (child.pid === undefined) {
155
+ spawnError = error.code ? `spawn ${spec.command} ${error.code}` : error.message;
156
+ exited = true;
157
+ finish();
158
+ }
159
+ });
160
+
161
+ child.stdout?.on("data", (chunk: Buffer) => {
162
+ events.write(chunk);
163
+ pending += chunk.toString("utf8");
164
+ let index = pending.indexOf("\n");
165
+ while (index !== -1) {
166
+ emitLine(pending.slice(0, index));
167
+ pending = pending.slice(index + 1);
168
+ index = pending.indexOf("\n");
169
+ }
170
+ });
171
+
172
+ child.stderr?.on("data", (chunk: Buffer) => {
173
+ stderrFile.write(chunk);
174
+ stderrTail += chunk.toString("utf8");
175
+ if (stderrTail.length > STDERR_TAIL_BYTES) stderrTail = stderrTail.slice(-STDERR_TAIL_BYTES);
176
+ try {
177
+ spec.onStderr?.(stderrTail);
178
+ } catch {
179
+ // A watcher error must not kill the run.
180
+ }
181
+ });
182
+
183
+ if (child.stdin) {
184
+ child.stdin.on("error", () => {
185
+ // EPIPE: the child exited or closed stdin before reading everything.
186
+ });
187
+ child.stdin.end(spec.stdin);
188
+ }
189
+
190
+ child.on("exit", (code, signal) => {
191
+ exited = true;
192
+ exitCode = code;
193
+ exitSignal = signal;
194
+ // Leftovers in the group (shell children, servers) die with the run.
195
+ killGroup("SIGTERM");
196
+ setTimeout(() => killGroup("SIGKILL"), 1_000).unref();
197
+ timers.push(
198
+ setTimeout(() => {
199
+ child.stdout?.destroy();
200
+ child.stderr?.destroy();
201
+ finish();
202
+ }, CLOSE_WAIT_MS),
203
+ );
204
+ });
205
+
206
+ child.on("close", () => {
207
+ if (exited) finish();
208
+ });
209
+ });
210
+ }
211
+
212
+ /**
213
+ * Process groups of `root`'s descendants other than `root`'s own group, read from `ps`. Our own group and init's are
214
+ * never returned. Empty when `ps` is unavailable.
215
+ */
216
+ export function descendantGroups(root: number): number[] {
217
+ let table: string;
218
+ try {
219
+ table = execFileSync("ps", ["-A", "-o", "pid=,ppid=,pgid="], { encoding: "utf8", timeout: 5_000 });
220
+ } catch {
221
+ return [];
222
+ }
223
+ const children = new Map<number, number[]>();
224
+ const groupOf = new Map<number, number>();
225
+ for (const line of table.split("\n")) {
226
+ const [pid, ppid, pgid] = line.trim().split(/\s+/).map(Number);
227
+ if (!pid || ppid === undefined || pgid === undefined || Number.isNaN(ppid) || Number.isNaN(pgid)) continue;
228
+ groupOf.set(pid, pgid);
229
+ const siblings = children.get(ppid);
230
+ if (siblings) siblings.push(pid);
231
+ else children.set(ppid, [pid]);
232
+ }
233
+ const excluded = new Set([root, 0, 1, groupOf.get(process.pid) ?? process.pid]);
234
+ const groups = new Set<number>();
235
+ const queue = [...(children.get(root) ?? [])];
236
+ const seen = new Set<number>(queue);
237
+ while (queue.length > 0) {
238
+ const pid = queue.shift() as number;
239
+ const group = groupOf.get(pid);
240
+ if (group !== undefined && !excluded.has(group)) groups.add(group);
241
+ for (const next of children.get(pid) ?? []) {
242
+ if (!seen.has(next)) {
243
+ seen.add(next);
244
+ queue.push(next);
245
+ }
246
+ }
247
+ }
248
+ return [...groups];
249
+ }
@@ -0,0 +1,55 @@
1
+ import type { AdapterOutcome, Mode, NormalizedEvent, RunStatus } from "../adapters/types.ts";
2
+ import type { LockHandle } from "./registry.ts";
3
+
4
+ export interface RunAttempt {
5
+ profile: string;
6
+ agent: string;
7
+ status: RunStatus;
8
+ reason?: string;
9
+ runId?: string;
10
+ }
11
+
12
+ export interface RunResult extends AdapterOutcome {
13
+ runId: string;
14
+ profile: string;
15
+ agent: string;
16
+ model?: string;
17
+ mode: Mode;
18
+ durationMs: number;
19
+ changedFiles: string[];
20
+ unexpectedChanges: string[]; // analyze runs
21
+ outOfScopeChanges: string[]; // implement runs with a scope
22
+ gitPolicyDepartures: string[];
23
+ artifactsDir: string;
24
+ /** Earlier profiles of the fallback chain that ended unavailable, auth_required or quota. */
25
+ attempts: RunAttempt[];
26
+ warnings: string[];
27
+ /** Runs that overlapped in the same workspace; changes are attributed to the group. */
28
+ overlappingRuns: string[];
29
+ /** What the change report covers, or why there is none. */
30
+ changeNote: string;
31
+ /** Whether a follow-up can continue this run's session. */
32
+ resumable: boolean;
33
+ }
34
+
35
+ export interface Assignment {
36
+ task: string;
37
+ mode: Mode;
38
+ scope?: string[];
39
+ workspace: string;
40
+ /** Candidate profiles in fallback order. A follow-up has exactly one. */
41
+ profiles: string[];
42
+ followUp?: { sessionId: string };
43
+ outputSchema?: object;
44
+ /** Phase or step shown in the widget. */
45
+ label?: string;
46
+ workflowId?: string;
47
+ signal?: AbortSignal;
48
+ /** The write lock is already held by the caller (an executing plan). */
49
+ lock?: LockHandle;
50
+ onEvent?: (runId: string, event: NormalizedEvent) => void;
51
+ }
52
+
53
+ export interface Executor {
54
+ run(assignment: Assignment): Promise<RunResult>;
55
+ }
@@ -0,0 +1,100 @@
1
+ import { posix } from "node:path";
2
+ import type { Mode } from "../adapters/types.ts";
3
+
4
+ export interface ScopeResult {
5
+ scope: string[];
6
+ errors: string[];
7
+ }
8
+
9
+ /**
10
+ * Normalizes scope entries: paths or globs relative to the workspace. Absolute entries and entries that leave the
11
+ * workspace are rejected.
12
+ */
13
+ export function normalizeScope(entries: readonly string[]): ScopeResult {
14
+ const scope: string[] = [];
15
+ const errors: string[] = [];
16
+ for (const raw of entries) {
17
+ const entry = raw.trim().replace(/\\/g, "/").replace(/^@/, "");
18
+ if (!entry) continue;
19
+ if (entry.startsWith("/") || /^[A-Za-z]:\//.test(entry)) {
20
+ errors.push(`scope entry "${raw}" is absolute; use a path relative to the workspace`);
21
+ continue;
22
+ }
23
+ let normalized = posix.normalize(entry);
24
+ if (normalized === ".." || normalized.startsWith("../")) {
25
+ errors.push(`scope entry "${raw}" leaves the workspace`);
26
+ continue;
27
+ }
28
+ if (normalized.startsWith("./")) normalized = normalized.slice(2);
29
+ if (normalized.length > 1 && normalized.endsWith("/")) normalized = normalized.slice(0, -1);
30
+ if (normalized === "") normalized = ".";
31
+ if (!scope.includes(normalized)) scope.push(normalized);
32
+ }
33
+ return { scope, errors };
34
+ }
35
+
36
+ const GLOB_CHARS = /[*?[{]/;
37
+
38
+ /** Converts a workspace-relative glob to a regular expression (supports `**`, `*`, `?`, `[...]`, `{a,b}`). */
39
+ export function globToRegExp(glob: string): RegExp {
40
+ let pattern = "";
41
+ for (let i = 0; i < glob.length; i++) {
42
+ const char = glob[i];
43
+ if (char === "*") {
44
+ if (glob[i + 1] === "*") {
45
+ const slash = glob[i + 2] === "/";
46
+ pattern += slash ? "(?:.*/)?" : ".*";
47
+ i += slash ? 2 : 1;
48
+ } else {
49
+ pattern += "[^/]*";
50
+ }
51
+ } else if (char === "?") {
52
+ pattern += "[^/]";
53
+ } else if (char === "[") {
54
+ const end = glob.indexOf("]", i + 1);
55
+ if (end === -1) pattern += "\\[";
56
+ else {
57
+ pattern += `[${glob.slice(i + 1, end).replace(/^!/, "^").replace(/\\/g, "\\\\")}]`;
58
+ i = end;
59
+ }
60
+ } else if (char === "{") {
61
+ const end = glob.indexOf("}", i + 1);
62
+ if (end === -1) pattern += "\\{";
63
+ else {
64
+ const options = glob.slice(i + 1, end).split(",").map((option) => globToRegExp(option).source.slice(1, -1));
65
+ pattern += `(?:${options.join("|")})`;
66
+ i = end;
67
+ }
68
+ } else {
69
+ pattern += char.replace(/[.+^$()|\\]/g, "\\$&");
70
+ }
71
+ }
72
+ return new RegExp(`^${pattern}$`);
73
+ }
74
+
75
+ /** Whether a workspace-relative path is inside the scope. A plain entry covers itself and everything below it. */
76
+ export function inScope(path: string, scope: readonly string[]): boolean {
77
+ const target = posix.normalize(path.replace(/\\/g, "/")).replace(/^\.\//, "");
78
+ return scope.some((entry) => {
79
+ if (entry === ".") return true;
80
+ if (GLOB_CHARS.test(entry)) {
81
+ const regex = globToRegExp(entry);
82
+ if (regex.test(target)) return true;
83
+ // A glob naming a directory covers what is below it.
84
+ return target.split("/").some((_, index, parts) => regex.test(parts.slice(0, index + 1).join("/")));
85
+ }
86
+ return target === entry || target.startsWith(`${entry}/`);
87
+ });
88
+ }
89
+
90
+ export interface ChangeClassification {
91
+ unexpectedChanges: string[];
92
+ outOfScopeChanges: string[];
93
+ }
94
+
95
+ /** Mechanical check of a run's changes against its mode and scope. A report, never a failure. */
96
+ export function classifyChanges(mode: Mode, changed: readonly string[], scope?: readonly string[]): ChangeClassification {
97
+ if (mode === "analyze") return { unexpectedChanges: [...changed], outOfScopeChanges: [] };
98
+ if (!scope || scope.length === 0) return { unexpectedChanges: [], outOfScopeChanges: [] };
99
+ return { unexpectedChanges: [], outOfScopeChanges: changed.filter((path) => !inScope(path, scope)) };
100
+ }