master-orchestrator 0.0.0-stage → 0.1.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 (52) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +174 -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/cursor.ts +242 -0
  10. package/src/adapters/dsh.ts +356 -0
  11. package/src/adapters/fake-agent.mjs +50 -0
  12. package/src/adapters/fake.ts +88 -0
  13. package/src/adapters/gemini.ts +225 -0
  14. package/src/adapters/grok.ts +328 -0
  15. package/src/adapters/muse.ts +281 -0
  16. package/src/adapters/omp.ts +119 -0
  17. package/src/adapters/opencode.ts +228 -0
  18. package/src/adapters/pi.ts +284 -0
  19. package/src/adapters/registry.ts +31 -0
  20. package/src/adapters/types.ts +201 -0
  21. package/src/config/load.ts +290 -0
  22. package/src/config/profiles.ts +64 -0
  23. package/src/config/schema.ts +158 -0
  24. package/src/config/write.ts +83 -0
  25. package/src/engine/artifacts.ts +145 -0
  26. package/src/engine/baseline.ts +132 -0
  27. package/src/engine/execute.ts +437 -0
  28. package/src/engine/git.ts +32 -0
  29. package/src/engine/hostenv.ts +54 -0
  30. package/src/engine/registry.ts +280 -0
  31. package/src/engine/runner.ts +203 -0
  32. package/src/engine/types.ts +55 -0
  33. package/src/engine/verify.ts +100 -0
  34. package/src/index.ts +602 -0
  35. package/src/prompts/envelope.ts +29 -0
  36. package/src/prompts/templates.ts +389 -0
  37. package/src/ui/configure.ts +174 -0
  38. package/src/ui/dialogs.ts +88 -0
  39. package/src/ui/doctor.ts +120 -0
  40. package/src/ui/format.ts +94 -0
  41. package/src/ui/host.ts +100 -0
  42. package/src/ui/render.ts +86 -0
  43. package/src/ui/widget.ts +70 -0
  44. package/src/workflows/budget.ts +66 -0
  45. package/src/workflows/common.ts +100 -0
  46. package/src/workflows/debate.ts +488 -0
  47. package/src/workflows/host.ts +78 -0
  48. package/src/workflows/plan-exec.ts +807 -0
  49. package/src/workflows/plan.ts +407 -0
  50. package/src/workflows/planfile.ts +380 -0
  51. package/src/workflows/planstate.ts +229 -0
  52. package/src/workflows/verdict.ts +74 -0
@@ -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
+ }