emd-agents 0.0.0-stage → 0.14.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 (77) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +121 -2
  4. package/dist/adapters/expo/index.d.ts +3 -0
  5. package/dist/adapters/expo/index.js +55 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +11 -0
  8. package/dist/cli/main.d.ts +1 -0
  9. package/dist/cli/main.js +265 -0
  10. package/dist/core/adapter.d.ts +32 -0
  11. package/dist/core/adapter.js +3 -0
  12. package/dist/core/check.d.ts +20 -0
  13. package/dist/core/check.js +214 -0
  14. package/dist/core/checkrecord.d.ts +22 -0
  15. package/dist/core/checkrecord.js +34 -0
  16. package/dist/core/detect.d.ts +2 -0
  17. package/dist/core/detect.js +27 -0
  18. package/dist/core/device/axe.d.ts +10 -0
  19. package/dist/core/device/axe.js +66 -0
  20. package/dist/core/device/backend.d.ts +43 -0
  21. package/dist/core/device/backend.js +72 -0
  22. package/dist/core/device/maestro.d.ts +4 -0
  23. package/dist/core/device/maestro.js +86 -0
  24. package/dist/core/device/screen.d.ts +9 -0
  25. package/dist/core/device/screen.js +7 -0
  26. package/dist/core/doctor.d.ts +12 -0
  27. package/dist/core/doctor.js +70 -0
  28. package/dist/core/evidence.d.ts +9 -0
  29. package/dist/core/evidence.js +107 -0
  30. package/dist/core/gc.d.ts +22 -0
  31. package/dist/core/gc.js +172 -0
  32. package/dist/core/index.d.ts +17 -0
  33. package/dist/core/index.js +16 -0
  34. package/dist/core/input.d.ts +15 -0
  35. package/dist/core/input.js +59 -0
  36. package/dist/core/isolate.d.ts +4 -0
  37. package/dist/core/isolate.js +43 -0
  38. package/dist/core/jobs.d.ts +21 -0
  39. package/dist/core/jobs.js +114 -0
  40. package/dist/core/jobstore.d.ts +21 -0
  41. package/dist/core/jobstore.js +45 -0
  42. package/dist/core/launch.d.ts +8 -0
  43. package/dist/core/launch.js +273 -0
  44. package/dist/core/log.d.ts +5 -0
  45. package/dist/core/log.js +54 -0
  46. package/dist/core/logs.d.ts +19 -0
  47. package/dist/core/logs.js +122 -0
  48. package/dist/core/owned.d.ts +19 -0
  49. package/dist/core/owned.js +91 -0
  50. package/dist/core/probe.d.ts +2 -0
  51. package/dist/core/probe.js +14 -0
  52. package/dist/core/process.d.ts +10 -0
  53. package/dist/core/process.js +32 -0
  54. package/dist/core/project.d.ts +6 -0
  55. package/dist/core/project.js +76 -0
  56. package/dist/core/registry.d.ts +3 -0
  57. package/dist/core/registry.js +13 -0
  58. package/dist/core/result.d.ts +248 -0
  59. package/dist/core/result.js +147 -0
  60. package/dist/core/run.d.ts +15 -0
  61. package/dist/core/run.js +22 -0
  62. package/dist/core/setup.d.ts +29 -0
  63. package/dist/core/setup.js +202 -0
  64. package/dist/core/simulator.d.ts +21 -0
  65. package/dist/core/simulator.js +107 -0
  66. package/dist/core/state.d.ts +2 -0
  67. package/dist/core/state.js +9 -0
  68. package/dist/core/tool.d.ts +5 -0
  69. package/dist/core/tool.js +54 -0
  70. package/dist/core/version.d.ts +1 -0
  71. package/dist/core/version.js +5 -0
  72. package/dist/core/workspace.d.ts +1 -0
  73. package/dist/core/workspace.js +109 -0
  74. package/dist/mcp/server.d.ts +1 -0
  75. package/dist/mcp/server.js +188 -0
  76. package/package.json +58 -4
  77. package/skills/emd/SKILL.md +35 -0
@@ -0,0 +1,172 @@
1
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
2
+ import { join, relative, sep } from "node:path";
3
+ import { diskMB } from "./isolate.js";
4
+ import { firstLine } from "./log.js";
5
+ import { listLedgers, removeLedger } from "./owned.js";
6
+ import { listSimulators, removeSimulator, } from "./simulator.js";
7
+ import { homeDir } from "./state.js";
8
+ import { runTool } from "./tool.js";
9
+ // True when the folder is gone. Any other error means unknown, which is never
10
+ // taken for gone (decision 0006).
11
+ function rootGone(root) {
12
+ try {
13
+ statSync(root);
14
+ return false;
15
+ }
16
+ catch (error) {
17
+ const code = error.code;
18
+ if (code === "ENOENT" || code === "ENOTDIR")
19
+ return true;
20
+ throw error;
21
+ }
22
+ }
23
+ // `derived/<key>` may hold only the chain down to the ledger's DerivedData
24
+ // folder (Developer/Xcode/DerivedData/<app>), and nothing beside it.
25
+ function holdsOnly(dir, chain) {
26
+ if (!existsSync(dir))
27
+ return true;
28
+ let current = dir;
29
+ for (const part of chain) {
30
+ const names = readdirSync(current);
31
+ if (names.length !== 1 || names[0] !== part)
32
+ return false;
33
+ current = join(current, part);
34
+ }
35
+ return chain.length > 0 || readdirSync(dir).length === 0;
36
+ }
37
+ // Why this entry must not be removed, or undefined.
38
+ function problem(ledger, simulator) {
39
+ const { key } = ledger;
40
+ if (simulator && simulator.name !== `emd-${key}`) {
41
+ return `simulator ${simulator.id} is named "${simulator.name}", not emd-${key}`;
42
+ }
43
+ const dir = join(homeDir(), "derived", key);
44
+ const derived = ledger.resources.find((r) => r.kind === "derivedData")?.id;
45
+ const chain = derived ? relative(dir, derived).split(sep) : [];
46
+ if (chain[0] === ".." || !holdsOnly(dir, chain)) {
47
+ return `${dir} holds more than the ledger's DerivedData folder`;
48
+ }
49
+ }
50
+ // Free disk in MB at `path`, by `df`.
51
+ async function freeMB(path) {
52
+ const { stdout } = await runTool("df", "df", ["-k", path], 60);
53
+ return Number(stdout.trim().split("\n")[1]?.split(/\s+/)[3]) / 1024;
54
+ }
55
+ // CLI only, no MCP tool: it deletes things, so a person runs it on purpose.
56
+ // Removes what EMD made for worktrees that no longer exist (decision 0006).
57
+ // Without `apply` it only reports. The ledger file goes last, and only when
58
+ // every step before it worked, so a failure is retried on the next run.
59
+ export async function gc(options = {}) {
60
+ const result = (rest) => ({
61
+ verdict: options.apply ? "applied" : "dry-run",
62
+ entries: [],
63
+ unreferencedSimulators: [],
64
+ totalMB: 0,
65
+ ...rest,
66
+ });
67
+ let ledgers;
68
+ let simulators;
69
+ try {
70
+ ledgers = listLedgers();
71
+ simulators = await listSimulators().catch((error) => {
72
+ // No simctl is fine when there is nothing to remove.
73
+ if (ledgers.length === 0)
74
+ return [];
75
+ throw error;
76
+ });
77
+ }
78
+ catch (error) {
79
+ return result({ verdict: "failed", reason: firstLine(error) });
80
+ }
81
+ const mentioned = new Set(ledgers.flatMap((l) => [
82
+ `emd-${l.key}`,
83
+ ...l.resources.filter((r) => r.kind === "simulator").map((r) => r.id),
84
+ ]));
85
+ const unreferencedSimulators = simulators
86
+ .filter((s) => s.name.startsWith("emd-"))
87
+ .filter((s) => !mentioned.has(s.id) && !mentioned.has(s.name))
88
+ .map(({ id, name }) => ({ id, name }));
89
+ const entries = [];
90
+ for (const ledger of ledgers) {
91
+ const base = { key: ledger.key, root: ledger.root };
92
+ try {
93
+ if (!rootGone(ledger.root))
94
+ continue;
95
+ }
96
+ catch (error) {
97
+ entries.push({
98
+ entry: {
99
+ ...base,
100
+ mb: 0,
101
+ status: "skipped",
102
+ reason: `cannot tell if the root exists: ${firstLine(error)}`,
103
+ },
104
+ ledger,
105
+ });
106
+ continue;
107
+ }
108
+ const wanted = ledger.resources.find((r) => r.kind === "simulator")?.id;
109
+ const sim = simulators.find((s) => s.id === wanted || s.name === wanted);
110
+ const derivedData = ledger.resources.find((r) => r.kind === "derivedData")?.id;
111
+ const reason = problem(ledger, sim);
112
+ entries.push({
113
+ entry: {
114
+ ...base,
115
+ ...(sim && { simulator: sim.id }),
116
+ ...(derivedData && { derivedData }),
117
+ mb: (await diskMB(join(homeDir(), "derived", ledger.key))) +
118
+ (await diskMB(join(homeDir(), "bin", ledger.key))),
119
+ status: reason ? "skipped" : "stale",
120
+ ...(reason && { reason }),
121
+ },
122
+ ledger,
123
+ sim,
124
+ });
125
+ }
126
+ const totalMB = entries.reduce((sum, e) => sum + e.entry.mb, 0);
127
+ const done = () => entries.map((e) => e.entry);
128
+ if (!options.apply) {
129
+ return result({
130
+ entries: done(),
131
+ unreferencedSimulators,
132
+ totalMB,
133
+ });
134
+ }
135
+ if (!entries.some((e) => e.entry.status === "stale")) {
136
+ return result({ entries: done(), unreferencedSimulators, totalMB });
137
+ }
138
+ const before = await freeMB(homeDir()).catch(() => undefined);
139
+ for (const { entry, ledger, sim } of entries) {
140
+ if (entry.status !== "stale")
141
+ continue;
142
+ try {
143
+ if (sim)
144
+ await removeSimulator(sim);
145
+ rmSync(join(homeDir(), "derived", ledger.key), {
146
+ recursive: true,
147
+ force: true,
148
+ });
149
+ rmSync(join(homeDir(), "bin", ledger.key), {
150
+ recursive: true,
151
+ force: true,
152
+ });
153
+ // The failed-check count is keyed like the ledger; a new worktree at the
154
+ // same path must not inherit a used-up retry budget.
155
+ rmSync(join(homeDir(), "checks", `${ledger.key}.json`), { force: true });
156
+ removeLedger(ledger.key);
157
+ entry.status = "removed";
158
+ }
159
+ catch (error) {
160
+ entry.status = "failed";
161
+ entry.reason = firstLine(error);
162
+ }
163
+ }
164
+ const after = await freeMB(homeDir()).catch(() => undefined);
165
+ return result({
166
+ entries: done(),
167
+ unreferencedSimulators,
168
+ totalMB,
169
+ ...(before !== undefined &&
170
+ after !== undefined && { freedMB: Math.round(after - before) }),
171
+ });
172
+ }
@@ -0,0 +1,17 @@
1
+ export type { LaunchPlan, PackageManager, Platform, ProjectInfo, StackAdapter, StackDetection, StackId, } from "./adapter.js";
2
+ export { check } from "./check.js";
3
+ export { resetChecks } from "./checkrecord.js";
4
+ export { detect } from "./detect.js";
5
+ export { directions } from "./device/backend.js";
6
+ export { type DoctorResult, doctor } from "./doctor.js";
7
+ export { evidence } from "./evidence.js";
8
+ export { type GcResult, gc } from "./gc.js";
9
+ export { swipe, tap, typeText } from "./input.js";
10
+ export { jobStatus, runJob, startJob } from "./jobs.js";
11
+ export { launch } from "./launch.js";
12
+ export { logs } from "./logs.js";
13
+ export { loadedAdapters } from "./registry.js";
14
+ export { type CheckResult, checkResultSchema, type DetectResult, detectResultSchema, type EvidenceResult, evidenceResultSchema, type InputResult, inputResultSchema, type JobView, jobViewSchema, type LaunchResult, type LogsResult, launchResultSchema, logsResultSchema, } from "./result.js";
15
+ export { type SetupResult, setup } from "./setup.js";
16
+ export { runTool } from "./tool.js";
17
+ export { version } from "./version.js";
@@ -0,0 +1,16 @@
1
+ export { check } from "./check.js";
2
+ export { resetChecks } from "./checkrecord.js";
3
+ export { detect } from "./detect.js";
4
+ export { directions } from "./device/backend.js";
5
+ export { doctor } from "./doctor.js";
6
+ export { evidence } from "./evidence.js";
7
+ export { gc } from "./gc.js";
8
+ export { swipe, tap, typeText } from "./input.js";
9
+ export { jobStatus, runJob, startJob } from "./jobs.js";
10
+ export { launch } from "./launch.js";
11
+ export { logs } from "./logs.js";
12
+ export { loadedAdapters } from "./registry.js";
13
+ export { checkResultSchema, detectResultSchema, evidenceResultSchema, inputResultSchema, jobViewSchema, launchResultSchema, logsResultSchema, } from "./result.js";
14
+ export { setup } from "./setup.js";
15
+ export { runTool } from "./tool.js";
16
+ export { version } from "./version.js";
@@ -0,0 +1,15 @@
1
+ import type { InputResult } from "./result.js";
2
+ import { type RunRef } from "./run.js";
3
+ export type TapOptions = RunRef & {
4
+ id?: string;
5
+ text?: string;
6
+ x?: number;
7
+ y?: number;
8
+ };
9
+ export declare function tap(options: TapOptions): Promise<InputResult>;
10
+ export declare function typeText(options: RunRef & {
11
+ text: string;
12
+ }): Promise<InputResult>;
13
+ export declare function swipe(options: RunRef & {
14
+ direction: string;
15
+ }): Promise<InputResult>;
@@ -0,0 +1,59 @@
1
+ import { axeBackend } from "./device/axe.js";
2
+ import { detectEnvironment, directions, firstWorking, } from "./device/backend.js";
3
+ import { maestroBackend } from "./device/maestro.js";
4
+ import { firstLine } from "./log.js";
5
+ import { resolveRun } from "./run.js";
6
+ // Taps, typing and swipes on a launched app (decision 0009). Each acts once
7
+ // and says which backend did it; whether the app reacted is for `check`.
8
+ async function act(what, { jobId }, gesture) {
9
+ const resolved = resolveRun({ jobId });
10
+ if ("reason" in resolved)
11
+ return { verdict: "failed", reason: resolved.reason };
12
+ const where = { device: resolved.run.device, appId: resolved.run.appId };
13
+ try {
14
+ const { backend, fellBack } = await firstWorking(what, await detectEnvironment(), [axeBackend, maestroBackend], (b, bin) => gesture(b, where, bin));
15
+ return { verdict: "ok", backend, ...(fellBack ? { fellBack } : {}) };
16
+ }
17
+ catch (error) {
18
+ return { verdict: "failed", reason: firstLine(error) };
19
+ }
20
+ }
21
+ // One target: an id, a text, or a point (x and y together).
22
+ function targetOf({ id, text, x, y }) {
23
+ const given = [id, text, x, y].filter((v) => v !== undefined).length;
24
+ if (id !== undefined && given === 1)
25
+ return { id };
26
+ if (text !== undefined && given === 1)
27
+ return { text };
28
+ if (x !== undefined && y !== undefined && given === 2)
29
+ return { x, y };
30
+ return undefined;
31
+ }
32
+ export function tap(options) {
33
+ const target = targetOf(options);
34
+ if (!target) {
35
+ return Promise.resolve({
36
+ verdict: "failed",
37
+ reason: "Give one target: id, text, or both x and y.",
38
+ });
39
+ }
40
+ return act("tap", options, (b, where, bin) => b.tap(where, bin, target));
41
+ }
42
+ export function typeText(options) {
43
+ const { text } = options;
44
+ if (text.length === 0) {
45
+ return Promise.resolve({ verdict: "failed", reason: "Give text to type." });
46
+ }
47
+ return act("type", options, (b, where, bin) => b.type(where, bin, text));
48
+ }
49
+ const isDirection = (value) => directions.includes(value);
50
+ export function swipe(options) {
51
+ const { direction } = options;
52
+ if (!isDirection(direction)) {
53
+ return Promise.resolve({
54
+ verdict: "failed",
55
+ reason: `Give a direction: ${directions.join(", ")}.`,
56
+ });
57
+ }
58
+ return act("swipe", options, (b, where, bin) => b.swipe(where, bin, direction));
59
+ }
@@ -0,0 +1,4 @@
1
+ export declare function pickPort(taken: Set<string>): Promise<string>;
2
+ export declare const derivedDataPath: (root: string) => string;
3
+ export declare function xcodebuildShim(root: string, derivedData: string): string;
4
+ export declare function diskMB(path: string): Promise<number>;
@@ -0,0 +1,43 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { createServer } from "node:net";
3
+ import { basename, join } from "node:path";
4
+ import { worktreeKey } from "./owned.js";
5
+ import { homeDir } from "./state.js";
6
+ import { runTool } from "./tool.js";
7
+ const firstPort = 8081;
8
+ const free = (port) => new Promise((resolve) => {
9
+ const server = createServer();
10
+ server.once("error", () => resolve(false));
11
+ server.listen(port, () => server.close(() => resolve(true)));
12
+ });
13
+ // The first port from 8081 that no worktree holds and nothing listens on.
14
+ export async function pickPort(taken) {
15
+ for (let port = firstPort; port < firstPort + 1000; port++) {
16
+ if (!taken.has(String(port)) && (await free(port)))
17
+ return String(port);
18
+ }
19
+ throw new Error("No free Metro port.");
20
+ }
21
+ // The component after DerivedData is there because Expo finds the built app by
22
+ // matching `/Developer/Xcode/DerivedData/<name>/Build/Products/`.
23
+ export const derivedDataPath = (root) => join(homeDir(), "derived", worktreeKey(root), "Developer/Xcode/DerivedData", basename(root));
24
+ // Expo's build has no DerivedData option, so a directory placed first on PATH
25
+ // holds an xcodebuild that adds it. Returns that directory.
26
+ export function xcodebuildShim(root, derivedData) {
27
+ const dir = join(homeDir(), "bin", worktreeKey(root));
28
+ mkdirSync(dir, { recursive: true });
29
+ const path = join(dir, "xcodebuild");
30
+ const quoted = `'${derivedData.replaceAll("'", "'\\''")}'`;
31
+ writeFileSync(path, `#!/bin/sh\nexec /usr/bin/xcodebuild -derivedDataPath ${quoted} "$@"\n`, { mode: 0o755 });
32
+ return dir;
33
+ }
34
+ // Disk use of a folder in MB; absent counts as 0.
35
+ export async function diskMB(path) {
36
+ try {
37
+ const { stdout } = await runTool("du", "du", ["-sk", path], 60);
38
+ return Math.round(Number(stdout.split("\t")[0]) / 1024);
39
+ }
40
+ catch {
41
+ return 0;
42
+ }
43
+ }
@@ -0,0 +1,21 @@
1
+ import { type CheckOptions } from "./check.js";
2
+ import { type Job, type JobKind } from "./jobstore.js";
3
+ import { type LaunchOptions } from "./launch.js";
4
+ import type { CheckResult, JobView, LaunchResult } from "./result.js";
5
+ export type { JobKind } from "./jobstore.js";
6
+ type Inputs = {
7
+ launch: LaunchOptions;
8
+ check: CheckOptions;
9
+ };
10
+ type Results = {
11
+ launch: LaunchResult;
12
+ check: CheckResult;
13
+ };
14
+ type Report = (step: string) => void;
15
+ export type Handlers = {
16
+ [K in JobKind]: (input: Inputs[K], report: Report) => Promise<Results[K]>;
17
+ };
18
+ export declare function createJob<K extends JobKind>(kind: K, input: Inputs[K]): Job;
19
+ export declare function startJob<K extends JobKind>(kind: K, input: Inputs[K], worker?: string): JobView;
20
+ export declare function runJob(id: string, run?: Handlers): Promise<void>;
21
+ export declare function jobStatus(id: string): JobView | undefined;
@@ -0,0 +1,114 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { check } from "./check.js";
6
+ import { now, readJob, update, write, } from "./jobstore.js";
7
+ import { launch } from "./launch.js";
8
+ import { firstLine } from "./log.js";
9
+ const handlers = { launch, check };
10
+ const workerGraceMs = 30_000;
11
+ const defaultWorker = fileURLToPath(new URL("../bin.js", import.meta.url));
12
+ function fail(id, reason) {
13
+ const job = readJob(id);
14
+ if (!job)
15
+ return;
16
+ write({
17
+ ...job,
18
+ status: "failed",
19
+ step: undefined,
20
+ finishedAt: now(),
21
+ result: job.kind === "launch"
22
+ ? {
23
+ verdict: "failed",
24
+ root: resolve(job.input.dir ?? "."),
25
+ reason,
26
+ }
27
+ : { verdict: "error", reason },
28
+ });
29
+ }
30
+ const alive = (pid) => {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ }
35
+ catch (error) {
36
+ return error.code === "EPERM";
37
+ }
38
+ };
39
+ function view(job) {
40
+ const from = Date.parse(job.startedAt ?? job.createdAt);
41
+ const to = job.finishedAt ? Date.parse(job.finishedAt) : Date.now();
42
+ return {
43
+ jobId: job.id,
44
+ kind: job.kind,
45
+ status: job.status,
46
+ ...(job.step ? { step: job.step } : {}),
47
+ seconds: Math.round((to - from) / 100) / 10,
48
+ ...(job.result ? { result: job.result } : {}),
49
+ };
50
+ }
51
+ // Records a queued job. Nothing runs it yet.
52
+ export function createJob(kind, input) {
53
+ const job = {
54
+ id: randomBytes(4).toString("hex"),
55
+ kind,
56
+ input,
57
+ status: "queued",
58
+ createdAt: now(),
59
+ };
60
+ write(job);
61
+ return job;
62
+ }
63
+ // Records the job and starts its worker. Returns at once; the job stays queued
64
+ // until the worker picks it up.
65
+ export function startJob(kind, input, worker = defaultWorker) {
66
+ const job = createJob(kind, input);
67
+ const child = spawn(process.execPath, [worker, "job", "run", job.id], {
68
+ detached: true,
69
+ stdio: "ignore",
70
+ });
71
+ child.on("error", (error) => fail(job.id, `The worker did not start: ${error.message}`));
72
+ child.unref();
73
+ return view(job);
74
+ }
75
+ const execute = (job, run, report) => job.kind === "launch"
76
+ ? run.launch(job.input, report)
77
+ : run.check(job.input, report);
78
+ // What the worker process runs.
79
+ export async function runJob(id, run = handlers) {
80
+ const job = readJob(id);
81
+ if (job?.status !== "queued")
82
+ return;
83
+ update(id, { status: "running", pid: process.pid, startedAt: now() });
84
+ try {
85
+ const result = await execute(job, run, (step) => update(id, { step }));
86
+ update(id, {
87
+ status: result.verdict === "launched" || result.verdict === "passed"
88
+ ? "succeeded"
89
+ : "failed",
90
+ step: undefined,
91
+ finishedAt: now(),
92
+ result,
93
+ });
94
+ }
95
+ catch (error) {
96
+ fail(id, firstLine(error) || "The job failed.");
97
+ }
98
+ }
99
+ // A worker that died or never started would leave a job running forever, so
100
+ // reading a job also settles it.
101
+ export function jobStatus(id) {
102
+ const job = readJob(id);
103
+ if (!job)
104
+ return undefined;
105
+ if (job.status === "running" && job.pid && !alive(job.pid)) {
106
+ fail(id, "The worker process died.");
107
+ }
108
+ else if (job.status === "queued" &&
109
+ Date.now() - Date.parse(job.createdAt) > workerGraceMs) {
110
+ fail(id, "The worker did not start.");
111
+ }
112
+ const current = readJob(id);
113
+ return current && view(current);
114
+ }
@@ -0,0 +1,21 @@
1
+ import type { CheckOptions } from "./check.js";
2
+ import type { LaunchOptions } from "./launch.js";
3
+ import type { CheckResult, JobView, LaunchResult } from "./result.js";
4
+ export type JobKind = "launch" | "check";
5
+ export type Job = {
6
+ id: string;
7
+ kind: JobKind;
8
+ input: LaunchOptions | CheckOptions;
9
+ status: JobView["status"];
10
+ step?: string;
11
+ createdAt: string;
12
+ startedAt?: string;
13
+ finishedAt?: string;
14
+ pid?: number;
15
+ result?: LaunchResult | CheckResult;
16
+ };
17
+ export declare const now: () => string;
18
+ export declare function write(job: Job): void;
19
+ export declare function readJob(id: string): Job | undefined;
20
+ export declare const launchesIn: (root: string) => LaunchResult[];
21
+ export declare function update(id: string, patch: Partial<Job>): void;
@@ -0,0 +1,45 @@
1
+ import { mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { stateDir } from "./state.js";
4
+ // The id comes from callers, so it is checked before it touches a path.
5
+ const idPattern = /^[0-9a-f]{8}$/;
6
+ const jobsDir = () => join(stateDir(), "jobs");
7
+ const fileOf = (id) => join(jobsDir(), `${id}.json`);
8
+ export const now = () => new Date().toISOString();
9
+ export function write(job) {
10
+ mkdirSync(jobsDir(), { recursive: true });
11
+ const temp = `${fileOf(job.id)}.${process.pid}.tmp`;
12
+ writeFileSync(temp, JSON.stringify(job));
13
+ renameSync(temp, fileOf(job.id));
14
+ }
15
+ export function readJob(id) {
16
+ if (!idPattern.test(id))
17
+ return undefined;
18
+ try {
19
+ return JSON.parse(readFileSync(fileOf(id), "utf8"));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ function readJobs() {
26
+ try {
27
+ return readdirSync(jobsDir())
28
+ .filter((name) => name.endsWith(".json"))
29
+ .map((name) => readJob(name.slice(0, -".json".length)))
30
+ .filter((job) => job !== undefined);
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ }
36
+ // The results of the launch jobs that finished in this worktree.
37
+ export const launchesIn = (root) => readJobs().flatMap((job) => {
38
+ const result = job.kind === "launch" ? job.result : undefined;
39
+ return result?.root === root ? [result] : [];
40
+ });
41
+ export function update(id, patch) {
42
+ const job = readJob(id);
43
+ if (job)
44
+ write({ ...job, ...patch });
45
+ }
@@ -0,0 +1,8 @@
1
+ import type { LaunchResult } from "./result.js";
2
+ export type LaunchOptions = {
3
+ dir?: string;
4
+ device?: string;
5
+ timeoutSeconds?: number;
6
+ };
7
+ export declare function stopEarlierServer(root: string, port: number): Promise<void>;
8
+ export declare function launch(options?: LaunchOptions, report?: (step: string) => void): Promise<LaunchResult>;