@re-cinq/floor-studio 0.8.0 → 0.11.1

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 (122) hide show
  1. package/README.md +46 -4
  2. package/dist/backend/agent-run.d.ts +13 -0
  3. package/dist/backend/agent-run.js +32 -0
  4. package/dist/backend/collection-view.d.ts +2 -0
  5. package/dist/backend/collection-view.js +18 -8
  6. package/dist/backend/in-order.d.ts +1 -0
  7. package/dist/backend/in-order.js +10 -0
  8. package/dist/backend/last-tests.d.ts +10 -0
  9. package/dist/backend/last-tests.js +40 -0
  10. package/dist/backend/past-test-run-state.d.ts +2 -0
  11. package/dist/backend/past-test-run-state.js +19 -0
  12. package/dist/backend/past-test-runs.d.ts +2 -0
  13. package/dist/backend/past-test-runs.js +31 -0
  14. package/dist/backend/read-collection-view.d.ts +4 -0
  15. package/dist/backend/read-collection-view.js +19 -0
  16. package/dist/backend/read-test-line.d.ts +2 -0
  17. package/dist/backend/read-test-line.js +10 -0
  18. package/dist/backend/requests.d.ts +11 -1
  19. package/dist/backend/requests.js +4 -1
  20. package/dist/backend/run-cancel-request.d.ts +2 -1
  21. package/dist/backend/run-cancel-request.js +6 -3
  22. package/dist/backend/run-preview-request.d.ts +3 -2
  23. package/dist/backend/run-preview-request.js +6 -4
  24. package/dist/backend/run-start-request.js +2 -27
  25. package/dist/backend/start-studio.d.ts +4 -0
  26. package/dist/backend/start-studio.js +7 -13
  27. package/dist/backend/test-last-requests.d.ts +6 -0
  28. package/dist/backend/test-last-requests.js +6 -0
  29. package/dist/backend/test-list-requests.d.ts +9 -0
  30. package/dist/backend/test-list-requests.js +15 -0
  31. package/dist/backend/test-run-agent-visit.d.ts +13 -0
  32. package/dist/backend/test-run-agent-visit.js +73 -0
  33. package/dist/backend/test-run-folder.d.ts +5 -0
  34. package/dist/backend/test-run-folder.js +25 -0
  35. package/dist/backend/test-run-requests.d.ts +34 -0
  36. package/dist/backend/test-run-requests.js +112 -0
  37. package/dist/backend/test-run-session.d.ts +23 -0
  38. package/dist/backend/test-run-session.js +218 -0
  39. package/dist/backend/test-run-snapshot.d.ts +3 -0
  40. package/dist/backend/test-run-snapshot.js +25 -0
  41. package/dist/backend/test-run-supplied-files.d.ts +5 -0
  42. package/dist/backend/test-run-supplied-files.js +35 -0
  43. package/dist/backend/test-run-timeline.d.ts +6 -0
  44. package/dist/backend/test-run-timeline.js +13 -0
  45. package/dist/backend/test-run-visit-files.d.ts +8 -0
  46. package/dist/backend/test-run-visit-files.js +28 -0
  47. package/dist/cli.js +2 -2
  48. package/dist/folder-listing.d.ts +6 -0
  49. package/dist/folder-listing.js +2 -0
  50. package/dist/protocol.d.ts +179 -4
  51. package/dist/protocol.js +30 -4
  52. package/dist/run/result-line.d.ts +6 -0
  53. package/dist/run/result-line.js +18 -0
  54. package/dist/run/run-cost.d.ts +6 -0
  55. package/dist/run/run-cost.js +17 -0
  56. package/dist/run/run-outcome.d.ts +2 -0
  57. package/dist/run/run-outcome.js +4 -20
  58. package/dist/run/run-preview.d.ts +2 -0
  59. package/dist/run/run-preview.js +15 -6
  60. package/dist/run/run-process.d.ts +5 -3
  61. package/dist/run/run-process.js +13 -2
  62. package/dist/run/run-produces.d.ts +4 -0
  63. package/dist/run/run-produces.js +6 -1
  64. package/dist/run/run-records.d.ts +11 -0
  65. package/dist/run/run-result.js +15 -3
  66. package/dist/run/station-fixtures.d.ts +2 -1
  67. package/dist/run/station-fixtures.js +11 -0
  68. package/dist/shell/open-browser.d.ts +3 -3
  69. package/dist/shell/open-browser.js +7 -7
  70. package/dist/test-run/agent-report.d.ts +3 -0
  71. package/dist/test-run/agent-report.js +21 -0
  72. package/dist/test-run/brief.d.ts +6 -0
  73. package/dist/test-run/brief.js +25 -0
  74. package/dist/test-run/entered-value.d.ts +1 -0
  75. package/dist/test-run/entered-value.js +6 -0
  76. package/dist/test-run/event-answer.d.ts +13 -0
  77. package/dist/test-run/event-answer.js +13 -0
  78. package/dist/test-run/folder-names.d.ts +2 -0
  79. package/dist/test-run/folder-names.js +18 -0
  80. package/dist/test-run/next-transition.d.ts +3 -0
  81. package/dist/test-run/next-transition.js +10 -0
  82. package/dist/test-run/outcome-fields.d.ts +10 -0
  83. package/dist/test-run/outcome-fields.js +40 -0
  84. package/dist/test-run/past-listing.d.ts +3 -0
  85. package/dist/test-run/past-listing.js +5 -0
  86. package/dist/test-run/past-state.d.ts +5 -0
  87. package/dist/test-run/past-state.js +26 -0
  88. package/dist/test-run/run-bag.d.ts +5 -0
  89. package/dist/test-run/run-bag.js +12 -0
  90. package/dist/test-run/run-summary.d.ts +13 -0
  91. package/dist/test-run/run-summary.js +23 -0
  92. package/dist/test-run/stand-in-actions.d.ts +17 -0
  93. package/dist/test-run/stand-in-actions.js +26 -0
  94. package/dist/test-run/stand-in-report.d.ts +13 -0
  95. package/dist/test-run/stand-in-report.js +34 -0
  96. package/dist/test-run/start-blockers.d.ts +3 -0
  97. package/dist/test-run/start-blockers.js +21 -0
  98. package/dist/test-run/start-items.d.ts +12 -0
  99. package/dist/test-run/start-items.js +18 -0
  100. package/dist/test-run/test-line.d.ts +16 -0
  101. package/dist/test-run/test-line.js +24 -0
  102. package/dist/test-run/test-preview.d.ts +11 -0
  103. package/dist/test-run/test-preview.js +7 -0
  104. package/dist/test-run/test-run-state.d.ts +30 -0
  105. package/dist/test-run/test-run-state.js +2 -0
  106. package/dist/test-run/test-visit.d.ts +24 -0
  107. package/dist/test-run/test-visit.js +2 -0
  108. package/dist/test-run/timeline.d.ts +32 -0
  109. package/dist/test-run/timeline.js +4 -0
  110. package/dist/test-run/totals.d.ts +20 -0
  111. package/dist/test-run/totals.js +26 -0
  112. package/dist/test-run/visit-kind.d.ts +3 -0
  113. package/dist/test-run/visit-kind.js +10 -0
  114. package/dist/test-run/visit-record.d.ts +22 -0
  115. package/dist/test-run/visit-record.js +27 -0
  116. package/dist/view.d.ts +2 -0
  117. package/dist/web/assets/index-C5eUTmhR.css +1 -0
  118. package/dist/web/assets/index-mRcd501r.js +195 -0
  119. package/dist/web/index.html +2 -2
  120. package/package.json +5 -5
  121. package/dist/web/assets/index-ChyDvQtL.css +0 -1
  122. package/dist/web/assets/index-In7XfxsK.js +0 -195
@@ -0,0 +1,6 @@
1
+ import { readLastTest } from "./last-tests.js";
2
+ export const testLastHandler = {
3
+ type: "test.last",
4
+ handle: async (context, { line }) => readLastTest(context.collectionDir, line),
5
+ };
6
+ //# sourceMappingURL=test-last-requests.js.map
@@ -0,0 +1,9 @@
1
+ import type { Request } from "../protocol.js";
2
+ import type { TestRunListing } from "../test-run/test-run-state.js";
3
+ import type { Handler } from "./requests.js";
4
+ import type { TestRunSession } from "./test-run-session.js";
5
+ export type TestListRequest = Extract<Request, {
6
+ type: "test.list";
7
+ }>;
8
+ export declare function listingOf({ id, startedAt, state }: TestRunSession): TestRunListing;
9
+ export declare const testListHandler: Handler<TestListRequest>;
@@ -0,0 +1,15 @@
1
+ import { pastTestRuns } from "./past-test-runs.js";
2
+ export function listingOf({ id, startedAt, state }) {
3
+ const { lineId, folder, status, ending } = state();
4
+ return { run: id, line: lineId, folder, status, startedAt, ...(ending && { ending }) };
5
+ }
6
+ export const testListHandler = {
7
+ type: "test.list",
8
+ handle: async (context) => {
9
+ const live = [...context.testRuns.values()].map(listingOf);
10
+ const liveFolders = new Set(live.map(({ folder }) => folder));
11
+ const past = (await pastTestRuns(context.collectionDir)).filter(({ folder }) => !liveFolders.has(folder));
12
+ return [...live, ...past].sort((first, second) => second.startedAt.localeCompare(first.startedAt));
13
+ },
14
+ };
15
+ //# sourceMappingURL=test-list-requests.js.map
@@ -0,0 +1,13 @@
1
+ import type { Report } from "@re-cinq/floor-contracts";
2
+ import type { VisitState } from "../test-run/test-visit.js";
3
+ import type { CollectionView } from "../view.js";
4
+ import type { StudioContext } from "./requests.js";
5
+ export interface AgentVisitSetup {
6
+ context: StudioContext;
7
+ view: CollectionView;
8
+ folder: string;
9
+ lineId: string;
10
+ permission: "acceptEdits" | "bypass";
11
+ onRun: (run: string) => void;
12
+ }
13
+ export declare function runAgentVisit(setup: AgentVisitSetup, visit: VisitState): Promise<Report>;
@@ -0,0 +1,73 @@
1
+ // An agent's visit in a local test run: previews the prompt, runs the agent in the visit folder and keeps what it wrote and said.
2
+ import { copyFile, lstat, mkdir, realpath } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { agentReportOf } from "../test-run/agent-report.js";
5
+ import { blockerReasonOf } from "../run/run-preview.js";
6
+ import { startAgentRun } from "./agent-run.js";
7
+ import { previewOf } from "./run-preview-request.js";
8
+ import { outputsFolderOf, visitFolderOf, writeVisitPrompt, writeVisitTranscript } from "./test-run-visit-files.js";
9
+ export async function runAgentVisit(setup, visit) {
10
+ const { view, folder, lineId, permission } = setup;
11
+ const workFolder = join(visitFolderOf(folder, visit.id), "work");
12
+ const previewed = await previewOf(view, { line: lineId, node: visit.nodeId, fixture: visit.needs, folder: workFolder, permission });
13
+ const { preview } = previewed;
14
+ await writeVisitPrompt(folder, visit.id, preview.prompt);
15
+ if (preview.blockers.length > 0) {
16
+ visit.report = { outcome: "failed", error: blockerReasonOf(preview) };
17
+ return visit.report;
18
+ }
19
+ return runStartedAgent(setup, visit, previewed, workFolder);
20
+ }
21
+ async function runStartedAgent({ context, folder, onRun }, visit, previewed, workFolder) {
22
+ const { run, ended } = await startAgentRun(context, previewed, { node: visit.nodeId, folder: workFolder });
23
+ onRun(run);
24
+ const ending = await ended;
25
+ const { runs } = context;
26
+ await writeVisitTranscript(folder, visit.id, runs.get(run)?.lines ?? []);
27
+ const report = await reportOfOutputs(previewed.station, ending, { workFolder, outputsFolder: outputsFolderOf(folder, visit.id) });
28
+ keepOnVisit(visit, report, ending);
29
+ return report;
30
+ }
31
+ function keepOnVisit(visit, report, { costUsd, durationMs }) {
32
+ visit.report = report;
33
+ if (costUsd !== undefined)
34
+ visit.costUsd = costUsd;
35
+ if (durationMs !== undefined)
36
+ visit.agentDurationMs = durationMs;
37
+ }
38
+ async function reportOfOutputs(station, ending, folders) {
39
+ const outputs = foundOutputsOf(station, ending);
40
+ const reasons = await linkReasonsOf(outputs, folders.workFolder);
41
+ if (reasons.length > 0)
42
+ return { outcome: "failed", error: reasons.join("; ") };
43
+ return agentReportOf(ending, await saveOutputs(outputs, folders));
44
+ }
45
+ function foundOutputsOf(station, { produced = [] }) {
46
+ const foundNames = new Set(produced.filter(({ found }) => found).map(({ name }) => name));
47
+ return station.produces.filter((output) => foundNames.has(output.name) && output.path !== undefined);
48
+ }
49
+ async function linkReasonsOf(outputs, workFolder) {
50
+ const reasons = await Promise.all(outputs.map((output) => linkReasonOf(output, workFolder)));
51
+ return reasons.filter((reason) => reason !== undefined);
52
+ }
53
+ async function linkReasonOf({ name, path }, workFolder) {
54
+ const stat = await lstat(join(workFolder, path));
55
+ if (stat.isSymbolicLink())
56
+ return linkReason(name, path, "is a link");
57
+ const [actualParent, plainParent] = await Promise.all([realpath(dirname(join(workFolder, path))), realpath(workFolder)]);
58
+ if (actualParent !== join(plainParent, dirname(path)))
59
+ return linkReason(name, path, "leads through a link");
60
+ }
61
+ function linkReason(name, path, finding) {
62
+ return `${name}: ${path} ${finding}, and an output must be a file the agent wrote`;
63
+ }
64
+ async function saveOutputs(outputs, { workFolder, outputsFolder }) {
65
+ const saved = await Promise.all(outputs.map(async ({ name, path }) => {
66
+ const target = join(outputsFolder, path);
67
+ await mkdir(dirname(target), { recursive: true });
68
+ await copyFile(join(workFolder, path), target);
69
+ return [name, target];
70
+ }));
71
+ return Object.fromEntries(saved);
72
+ }
73
+ //# sourceMappingURL=test-run-agent-visit.js.map
@@ -0,0 +1,5 @@
1
+ export declare function createRunFolder(workspace: string, name: string): Promise<string>;
2
+ /** The text of a JSON file in a run folder: indented, one trailing newline. */
3
+ export declare function jsonFileText(value: unknown): string;
4
+ export declare function enforceAbsolute(path: string, folderName: string): void;
5
+ export declare function isFolder(path: string): Promise<boolean>;
@@ -0,0 +1,25 @@
1
+ // The fresh folder a local test run lives in, made inside the workspace the person picked, and how the JSON files in it are written.
2
+ import { mkdir, stat } from "node:fs/promises";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { enforce } from "@re-cinq/floor-assembly-lines";
5
+ export async function createRunFolder(workspace, name) {
6
+ enforceAbsolute(workspace, "the workspace folder");
7
+ enforce(await isFolder(workspace), `the workspace folder ${workspace} is not a folder on disk`);
8
+ const runFolder = join(workspace, name);
9
+ await mkdir(runFolder).catch((error) => {
10
+ enforce(error.code !== "EEXIST", `${runFolder} already exists, and a test run never reuses a folder`);
11
+ throw error;
12
+ });
13
+ return runFolder;
14
+ }
15
+ /** The text of a JSON file in a run folder: indented, one trailing newline. */
16
+ export function jsonFileText(value) {
17
+ return `${JSON.stringify(value, null, 2)}\n`;
18
+ }
19
+ export function enforceAbsolute(path, folderName) {
20
+ enforce(isAbsolute(path), `${folderName} must be an absolute path, and ${JSON.stringify(path)} is not`);
21
+ }
22
+ export function isFolder(path) {
23
+ return stat(path).then((found) => found.isDirectory(), () => false);
24
+ }
25
+ //# sourceMappingURL=test-run-folder.js.map
@@ -0,0 +1,34 @@
1
+ import type { Request } from "../protocol.js";
2
+ import type { Handler } from "./requests.js";
3
+ export type TestStartRequest = Extract<Request, {
4
+ type: "test.start";
5
+ }>;
6
+ export type TestReportRequest = Extract<Request, {
7
+ type: "test.report";
8
+ }>;
9
+ export type TestCancelRequest = Extract<Request, {
10
+ type: "test.cancel";
11
+ }>;
12
+ export type TestReadRequest = Extract<Request, {
13
+ type: "test.read";
14
+ }>;
15
+ export type TestPreviewRequest = Extract<Request, {
16
+ type: "test.preview";
17
+ }>;
18
+ export type FolderOpenRequest = Extract<Request, {
19
+ type: "folder.open";
20
+ }>;
21
+ export type FolderListRequest = Extract<Request, {
22
+ type: "folder.list";
23
+ }>;
24
+ export type TestEventRequest = Extract<Request, {
25
+ type: "test.event";
26
+ }>;
27
+ export declare const testStartHandler: Handler<TestStartRequest>;
28
+ export declare const testReportHandler: Handler<TestReportRequest>;
29
+ export declare const testCancelHandler: Handler<TestCancelRequest>;
30
+ export declare const testPreviewHandler: Handler<TestPreviewRequest>;
31
+ export declare const testReadHandler: Handler<TestReadRequest>;
32
+ export declare const testEventHandler: Handler<TestEventRequest>;
33
+ export declare const folderOpenHandler: Handler<FolderOpenRequest>;
34
+ export declare const folderListHandler: Handler<FolderListRequest>;
@@ -0,0 +1,112 @@
1
+ // The requests that start, answer for, cancel and read a local test run of a whole line; its `test.changed` frames come from the session.
2
+ import { readdir, realpath } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { enforce } from "@re-cinq/floor-assembly-lines";
6
+ import { testPreviewOf } from "../test-run/test-preview.js";
7
+ import { pastTestRuns } from "./past-test-runs.js";
8
+ import { readPastRun } from "./past-test-run-state.js";
9
+ import { rememberLastTest } from "./last-tests.js";
10
+ import { enforceAbsolute, isFolder } from "./test-run-folder.js";
11
+ import { readTestLine } from "./read-test-line.js";
12
+ import { snapshotPathsIn } from "./test-run-snapshot.js";
13
+ import { startTestRun } from "./test-run-session.js";
14
+ export const testStartHandler = {
15
+ type: "test.start",
16
+ handle: async (context, { line, workspace, entered, permission }) => {
17
+ const session = await startTestRun(context, { collectionDir: context.collectionDir, lineId: line, workspace, entered, permission });
18
+ context.testRuns.set(session.id, session);
19
+ // Remembering is a convenience, the run has started.
20
+ await rememberLastTest(context.collectionDir, line, { workspace, entered }).catch(() => undefined);
21
+ return { run: session.id, folder: session.state().folder };
22
+ },
23
+ };
24
+ export const testReportHandler = {
25
+ type: "test.report",
26
+ handle: async (context, { run, visit, outcome, produced, files }) => {
27
+ await sessionOf(context, run).report(visit, { outcome, produced, ...(files && { files }) });
28
+ return { reported: visit };
29
+ },
30
+ };
31
+ export const testCancelHandler = {
32
+ type: "test.cancel",
33
+ handle: async (context, { run }) => {
34
+ await sessionOf(context, run).cancel();
35
+ return { cancelled: run };
36
+ },
37
+ };
38
+ export const testPreviewHandler = {
39
+ type: "test.preview",
40
+ handle: async (context, { line, entered }) => {
41
+ const [testLine, definitions] = await Promise.all([readTestLine(context.collectionDir, line), snapshotPathsIn(context.collectionDir)]);
42
+ return testPreviewOf(testLine, entered, definitions);
43
+ },
44
+ };
45
+ export const testReadHandler = {
46
+ type: "test.read",
47
+ handle: async (context, { run }) => {
48
+ const session = context.testRuns.get(run);
49
+ return session ? session.state() : await pastRunOf(context, run);
50
+ },
51
+ };
52
+ export const testEventHandler = {
53
+ type: "test.event",
54
+ handle: async (context, { run, event, payload }) => sessionOf(context, run).event({ name: event, payload }),
55
+ };
56
+ async function pastRunOf(context, run) {
57
+ const past = await readPastRun(context.collectionDir, run);
58
+ enforce(past, `there is no test run ${run}`);
59
+ return past;
60
+ }
61
+ function sessionOf(context, run) {
62
+ const session = context.testRuns.get(run);
63
+ enforce(session, `there is no test run ${run}`);
64
+ return session;
65
+ }
66
+ export const folderOpenHandler = {
67
+ type: "folder.open",
68
+ handle: async (context, { path }) => {
69
+ const runFolder = await runFolderOf(context, path);
70
+ enforce(runFolder, `${path} is not inside a test run's folder`);
71
+ await enforceRealFolderInside(runFolder, path);
72
+ context.openFolder(path);
73
+ return { opened: path };
74
+ },
75
+ };
76
+ async function runFolderOf({ testRuns, collectionDir }, path) {
77
+ const liveFolders = [...testRuns.values()].map((session) => session.state().folder);
78
+ const pastFolders = (await pastTestRuns(collectionDir)).map(({ folder }) => folder);
79
+ return [...liveFolders, ...pastFolders].find((folder) => isInside(folder, path));
80
+ }
81
+ async function enforceRealFolderInside(runFolder, path) {
82
+ const realPath = await realpath(path).catch(() => undefined);
83
+ enforce(realPath, `${path} is not a folder`);
84
+ enforce(isInside(await realpath(runFolder), realPath), `${path} is not inside a test run's folder`);
85
+ enforce(await isFolder(realPath), `${path} is not a folder`);
86
+ }
87
+ function isInside(folder, path) {
88
+ const inside = relative(folder, resolve(path));
89
+ return inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside);
90
+ }
91
+ export const folderListHandler = {
92
+ type: "folder.list",
93
+ handle: async (context, { path = homedir() }) => {
94
+ enforceAbsolute(path, "the folder to list");
95
+ enforce(await isFolder(path), `${path} is not a folder on disk`);
96
+ return listFolder(path);
97
+ },
98
+ };
99
+ async function listFolder(path) {
100
+ const entries = await readdir(path, { withFileTypes: true });
101
+ const parent = dirname(path);
102
+ return {
103
+ path,
104
+ parent: parent === path ? null : parent,
105
+ folders: namesOf(entries.filter((entry) => entry.isDirectory())),
106
+ files: namesOf(entries.filter((entry) => !entry.isDirectory())),
107
+ };
108
+ }
109
+ function namesOf(entries) {
110
+ return entries.map(({ name }) => name).sort();
111
+ }
112
+ //# sourceMappingURL=test-run-requests.js.map
@@ -0,0 +1,23 @@
1
+ import { type SentEvent } from "../test-run/event-answer.js";
2
+ import { type StandInAnswer } from "../test-run/stand-in-report.js";
3
+ import type { TestRunState } from "../test-run/test-run-state.js";
4
+ import type { StudioContext } from "./requests.js";
5
+ export interface TestRunStart {
6
+ collectionDir: string;
7
+ lineId: string;
8
+ workspace: string;
9
+ entered: Readonly<Record<string, string>>;
10
+ permission: "acceptEdits" | "bypass";
11
+ }
12
+ export interface TestRunSession {
13
+ id: string;
14
+ startedAt: string;
15
+ state(): TestRunState;
16
+ idle(): Promise<void>;
17
+ cancel(): Promise<void>;
18
+ report(visitId: string, answer: StandInAnswer): Promise<void>;
19
+ event(sent: SentEvent): Promise<{
20
+ answered: string[];
21
+ }>;
22
+ }
23
+ export declare function startTestRun(context: StudioContext, start: TestRunStart, clock?: () => Date): Promise<TestRunSession>;
@@ -0,0 +1,218 @@
1
+ // A local test run in flight: its folder, its snapshot of the collection and the visits the line's walk has opened so far.
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { endsRun, enforce } from "@re-cinq/floor-assembly-lines";
5
+ import { answeredVisitsOf } from "../test-run/event-answer.js";
6
+ import { briefOf } from "../test-run/brief.js";
7
+ import { runFolderName, visitFolderName } from "../test-run/folder-names.js";
8
+ import { nextTransitionOf } from "../test-run/next-transition.js";
9
+ import { enforceStartable } from "../test-run/start-blockers.js";
10
+ import { runSummaryOf } from "../test-run/run-summary.js";
11
+ import { startItemsOf } from "../test-run/start-items.js";
12
+ import { standInReport } from "../test-run/stand-in-report.js";
13
+ import { bagEntriesOf } from "../test-run/run-bag.js";
14
+ import { waitingActionsOf } from "../test-run/stand-in-actions.js";
15
+ import { nodeAt, stationAt } from "../test-run/test-line.js";
16
+ import { modeOf } from "../test-run/timeline.js";
17
+ import { visitRecordOf } from "../test-run/visit-record.js";
18
+ import { visitKindOf } from "../test-run/visit-kind.js";
19
+ import { inOrder } from "./in-order.js";
20
+ import { readCollectionView } from "./read-collection-view.js";
21
+ import { readTestLine } from "./read-test-line.js";
22
+ import { cancelRun } from "./run-cancel-request.js";
23
+ import { runAgentVisit } from "./test-run-agent-visit.js";
24
+ import { createRunFolder } from "./test-run-folder.js";
25
+ import { SNAPSHOT_FOLDER, snapshotCollection } from "./test-run-snapshot.js";
26
+ import { enforcePickedFilesOnDisk, suppliedTargets, writeSuppliedFiles } from "./test-run-supplied-files.js";
27
+ import { appendTimeline, writeRunSummary } from "./test-run-timeline.js";
28
+ import { outputsFolderOf, writeVisitInputs, writeVisitRecord } from "./test-run-visit-files.js";
29
+ export async function startTestRun(context, start, clock = () => new Date()) {
30
+ const { collectionDir, lineId, workspace, entered } = start;
31
+ const liveLine = await readTestLine(collectionDir, lineId);
32
+ const { items: startItems, missing } = startItemsOf(liveLine, entered);
33
+ enforceStartable(lineId, liveLine, missing);
34
+ const startedAt = clock();
35
+ const folder = await createRunFolder(workspace, runFolderName(lineId, startedAt));
36
+ const snapshotDir = join(folder, SNAPSHOT_FOLDER);
37
+ await snapshotCollection(collectionDir, folder);
38
+ const [line, view] = await Promise.all([readTestLine(snapshotDir, lineId), readCollectionView(snapshotDir, [])]);
39
+ const state = { folder, lineId, status: "running", visits: [] };
40
+ const run = { line, startItems, visits: state.visits };
41
+ const work = { id: randomUUID(), context, start, view, run, state, clock, startedAt: startedAt.toISOString(), cancelled: false, stepping: Promise.resolve(), timelineWrites: inOrder() };
42
+ await noteInTimeline(work, { "at": startedAt.toISOString(), type: "run_started", line: lineId });
43
+ void trackStep(work, stepRun(work));
44
+ return sessionOf(work);
45
+ }
46
+ function sessionOf(work) {
47
+ return {
48
+ id: work.id,
49
+ startedAt: work.startedAt,
50
+ state: () => stateOf(work),
51
+ idle: () => work.stepping,
52
+ cancel: () => cancelWork(work),
53
+ report: (visitId, answer) => reportAnswer(work, visitId, answer),
54
+ event: (sent) => answerEvent(work, sent),
55
+ };
56
+ }
57
+ function stateOf({ state, run }) {
58
+ return { ...state, actions: waitingActionsOf(run.line, state.visits), bag: bagEntriesOf(run) };
59
+ }
60
+ function cancelWork(work) {
61
+ const { status } = work.state;
62
+ if (status === "settled")
63
+ return work.stepping;
64
+ work.cancelled = true;
65
+ if (status === "waiting")
66
+ return trackStep(work, settleRun(work, { outcome: "cancelled" }));
67
+ if (work.agentRun !== undefined)
68
+ cancelRun(work.context.runs, work.agentRun);
69
+ return work.stepping;
70
+ }
71
+ async function reportAnswer(work, visitId, answer) {
72
+ const accepted = acceptReport(work, visitId, answer);
73
+ const written = writeSuppliedFiles(accepted.targets, answer.files ?? {}).catch((cause) => refuseReport(work, accepted, cause));
74
+ const stepped = written.then(() => trackStep(work, noteThenStep(work, [accepted])));
75
+ work.stepping = stepped.catch(() => undefined);
76
+ return stepped;
77
+ }
78
+ function refuseReport({ state }, { visit }, cause) {
79
+ visit.report = null;
80
+ state.status = "waiting";
81
+ throw cause;
82
+ }
83
+ async function answerEvent(work, sent) {
84
+ const { answered, settled } = receiveEvent(work, sent);
85
+ await (answered.length > 0 ? trackStep(work, settled) : settled);
86
+ return { answered };
87
+ }
88
+ function receiveEvent(work, sent) {
89
+ const { state, run } = work;
90
+ enforceTakesAnswers(state);
91
+ const answers = answeredVisitsOf(run.line, state.visits, sent);
92
+ const answered = answers.map(({ visit }) => visit.id);
93
+ const reported = answers.map(({ visit, outcome }) => ({ visit, report: { outcome } }));
94
+ for (const { visit, report } of reported)
95
+ visit.report = report;
96
+ if (answers.length > 0)
97
+ state.status = "running";
98
+ const received = noteInTimeline(work, { "at": work.clock().toISOString(), type: "event_received", event: sent.name, payload: sent.payload, answered });
99
+ if (answers.length === 0)
100
+ return { answered, settled: received };
101
+ return { answered, settled: received.then(() => noteThenStep(work, reported)) };
102
+ }
103
+ function enforceTakesAnswers(state) {
104
+ enforce(state.status !== "settled", "the run is settled, and a settled run takes no answers");
105
+ }
106
+ function acceptReport({ run, state }, visitId, answer) {
107
+ const visit = state.visits.find(({ id }) => id === visitId);
108
+ enforce(visit, `the run has no visit ${visitId}`);
109
+ enforce(visit.kind === "stand-in", `visit ${visitId} was run by an agent, and a person cannot answer for it`);
110
+ enforce(visit.report === null, `visit ${visitId} has already reported ${visit.report?.outcome}`);
111
+ enforceTakesAnswers(state);
112
+ enforcePickedFilesOnDisk(answer.files ?? {});
113
+ const report = standInReport(run.line, visit.nodeId, answer);
114
+ const outputsFolder = outputsFolderOf(state.folder, visitId);
115
+ const targets = suppliedTargets(stationAt(run.line, visit.nodeId).station, answer.files ?? {}, outputsFolder);
116
+ const produced = { ...report.produced, ...targets };
117
+ const accepted = Object.keys(produced).length === 0 ? report : { ...report, produced };
118
+ visit.report = accepted;
119
+ state.status = "running";
120
+ return { visit, report: accepted, targets };
121
+ }
122
+ function trackStep(work, step) {
123
+ work.stepping = step.catch((cause) => settleFailedRun(work, cause));
124
+ return work.stepping;
125
+ }
126
+ async function settleFailedRun(work, cause) {
127
+ const reason = cause instanceof Error ? cause.message : String(cause);
128
+ try {
129
+ await settleRun(work, { outcome: "error", reason });
130
+ }
131
+ catch {
132
+ work.context.broadcast({ type: "test.changed", run: work.id, state: stateOf(work) });
133
+ }
134
+ }
135
+ async function noteThenStep(work, reported) {
136
+ for (const { visit, report } of reported)
137
+ await noteReported(work, visit, report);
138
+ return stepRun(work);
139
+ }
140
+ async function stepRun(work) {
141
+ if (work.cancelled)
142
+ return settleRun(work, { outcome: "cancelled" });
143
+ const transition = nextTransitionOf(work.run);
144
+ if (endsRun(transition))
145
+ return settleRun(work, endingOf(transition));
146
+ if (transition.kind !== "launch")
147
+ return;
148
+ const visit = openVisit(work, transition);
149
+ const { state } = work;
150
+ state.visits.push(visit);
151
+ if (visit.kind !== "agent")
152
+ state.status = "waiting";
153
+ await noteOpened(work, visit);
154
+ if (visit.kind !== "agent")
155
+ return;
156
+ await runAgentStep(work, visit);
157
+ return stepRun(work);
158
+ }
159
+ async function runAgentStep(work, visit) {
160
+ const { context, view, start, state } = work;
161
+ const onRun = (run) => {
162
+ work.agentRun = run;
163
+ // A cancel can arrive before the agent's run id is known; stop it as soon as it starts.
164
+ if (work.cancelled)
165
+ cancelRun(context.runs, run);
166
+ };
167
+ const report = await runAgentVisit({ context, view, folder: state.folder, lineId: state.lineId, permission: start.permission, onRun }, visit);
168
+ await noteReported(work, visit, report);
169
+ }
170
+ async function settleRun(work, ending) {
171
+ const { state } = work;
172
+ state.status = "settled";
173
+ state.ending = ending;
174
+ await noteInTimeline(work, { "at": work.clock().toISOString(), type: "run_settled", outcome: ending.outcome });
175
+ }
176
+ function endingOf(transition) {
177
+ if (transition.kind === "finish")
178
+ return { outcome: "finished" };
179
+ return { outcome: transition.outcome, reason: transition.reason };
180
+ }
181
+ function noteInTimeline(work, entry) {
182
+ const { state, run, startedAt } = work;
183
+ // Calls come from the run loop and from outside requests at once, and plain writes of one file may overlap: queue them so entries, summaries and frames keep call order.
184
+ return work.timelineWrites(async () => {
185
+ await appendTimeline(state.folder, entry);
186
+ await writeRunSummary(state.folder, runSummaryOf(startedAt, run.startItems, state));
187
+ work.context.broadcast({ type: "test.changed", run: work.id, state: stateOf(work) });
188
+ });
189
+ }
190
+ function noteOpened(work, { id, nodeId, iteration, kind, needs, openedAt }) {
191
+ return Promise.all([
192
+ noteInTimeline(work, { "at": openedAt, type: "visit_opened", visit: id, node: nodeId, iteration, mode: modeOf(kind) }),
193
+ writeVisitInputs(work.state.folder, id, needs),
194
+ ]).then(() => undefined);
195
+ }
196
+ function openVisit({ run, state, clock }, { nodeId, iteration }) {
197
+ const { line } = run;
198
+ return {
199
+ id: visitFolderName(state.visits.length + 1, nodeId, iteration),
200
+ nodeId,
201
+ iteration,
202
+ station: nodeAt(line, nodeId).station ?? null,
203
+ kind: visitKindOf(line, nodeId),
204
+ needs: briefOf(run, nodeId).needs,
205
+ report: null,
206
+ openedAt: clock().toISOString(),
207
+ };
208
+ }
209
+ async function noteReported(work, visit, report) {
210
+ const { state, run } = work;
211
+ const reportedAt = work.clock().toISOString();
212
+ visit.reportedAt = reportedAt;
213
+ await Promise.all([
214
+ noteInTimeline(work, { "at": reportedAt, type: "visit_reported", visit: visit.id, outcome: report.outcome }),
215
+ writeVisitRecord(state.folder, visitRecordOf(run.line, visit, report)),
216
+ ]);
217
+ }
218
+ //# sourceMappingURL=test-run-session.js.map
@@ -0,0 +1,3 @@
1
+ export declare const SNAPSHOT_FOLDER = "definitions";
2
+ export declare function snapshotCollection(collectionDir: string, runFolder: string): Promise<string[]>;
3
+ export declare function snapshotPathsIn(collectionDir: string): Promise<string[]>;
@@ -0,0 +1,25 @@
1
+ // The copy of a collection's definitions a local test run keeps, so later edits never reach a run in flight.
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { COLLECTION_SETTINGS_FILE, collectionFilesIn } from "@re-cinq/floor-pipeline";
5
+ export const SNAPSHOT_FOLDER = "definitions";
6
+ export async function snapshotCollection(collectionDir, runFolder) {
7
+ const files = await snapshotFilesIn(collectionDir);
8
+ await Promise.all(files.map(({ path, text }) => writeSnapshotFile(join(runFolder, SNAPSHOT_FOLDER, path), text)));
9
+ return files.map(({ path }) => path);
10
+ }
11
+ export async function snapshotPathsIn(collectionDir) {
12
+ return (await snapshotFilesIn(collectionDir)).map(({ path }) => path);
13
+ }
14
+ async function snapshotFilesIn(collectionDir) {
15
+ const files = [...(await collectionFilesIn(collectionDir)), ...(await settingsFileIn(collectionDir))];
16
+ return files.sort((first, second) => (first.path < second.path ? -1 : first.path > second.path ? 1 : 0));
17
+ }
18
+ async function writeSnapshotFile(target, text) {
19
+ await mkdir(dirname(target), { recursive: true });
20
+ await writeFile(target, text);
21
+ }
22
+ function settingsFileIn(collectionDir) {
23
+ return readFile(join(collectionDir, COLLECTION_SETTINGS_FILE), "utf8").then((text) => [{ path: COLLECTION_SETTINGS_FILE, text }], () => []);
24
+ }
25
+ //# sourceMappingURL=test-run-snapshot.js.map
@@ -0,0 +1,5 @@
1
+ import type { StationBody } from "@re-cinq/floor-contracts";
2
+ import type { SuppliedFile } from "../test-run/stand-in-report.js";
3
+ export declare function enforcePickedFilesOnDisk(files: Readonly<Record<string, SuppliedFile>>): void;
4
+ export declare function suppliedTargets(station: StationBody, files: Readonly<Record<string, SuppliedFile>>, outputsFolder: string): Record<string, string>;
5
+ export declare function writeSuppliedFiles(targets: Readonly<Record<string, string>>, files: Readonly<Record<string, SuppliedFile>>): Promise<void>;
@@ -0,0 +1,35 @@
1
+ // The files a person supplies for a stand-in visit: picked ones must exist on disk before the report is accepted.
2
+ import { statSync } from "node:fs";
3
+ import { copyFile, mkdir, writeFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { enforce } from "@re-cinq/floor-assembly-lines";
6
+ import { enforceAbsolute } from "./test-run-folder.js";
7
+ import { leavesFolder } from "../run/run-preview.js";
8
+ export function enforcePickedFilesOnDisk(files) {
9
+ for (const [name, file] of Object.entries(files)) {
10
+ if (!("picked" in file))
11
+ continue;
12
+ const { picked } = file;
13
+ enforceAbsolute(picked, `${name}: the picked file`);
14
+ const stats = statSync(picked, { throwIfNoEntry: false });
15
+ enforce(stats !== undefined, `${name}: the picked file ${picked} is not on disk`);
16
+ enforce(stats.isFile(), `${name}: the picked file ${picked} is not a file`);
17
+ }
18
+ }
19
+ export function suppliedTargets(station, files, outputsFolder) {
20
+ const { produces } = station;
21
+ const targets = Object.keys(files).map((name) => {
22
+ const path = produces.find((output) => output.name === name)?.path ?? name;
23
+ enforce(!leavesFolder(outputsFolder, path), `"${name}": ${path} leaves the visit's outputs folder`);
24
+ return [name, join(outputsFolder, path)];
25
+ });
26
+ return Object.fromEntries(targets);
27
+ }
28
+ export async function writeSuppliedFiles(targets, files) {
29
+ await Promise.all(Object.entries(targets).map(async ([name, target]) => {
30
+ const file = files[name];
31
+ await mkdir(dirname(target), { recursive: true });
32
+ await ("picked" in file ? copyFile(file.picked, target) : writeFile(target, file.pasted));
33
+ }));
34
+ }
35
+ //# sourceMappingURL=test-run-supplied-files.js.map
@@ -0,0 +1,6 @@
1
+ import type { RunSummary } from "../test-run/run-summary.js";
2
+ import type { TimelineEntry } from "../test-run/timeline.js";
3
+ export declare const TIMELINE_FILE = "timeline.jsonl";
4
+ export declare const RUN_FILE = "run.json";
5
+ export declare function appendTimeline(runFolder: string, entry: TimelineEntry): Promise<void>;
6
+ export declare function writeRunSummary(runFolder: string, summary: RunSummary): Promise<void>;
@@ -0,0 +1,13 @@
1
+ // The timeline file of a local test run: one JSON entry per line, only ever appended to.
2
+ import { appendFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { jsonFileText } from "./test-run-folder.js";
5
+ export const TIMELINE_FILE = "timeline.jsonl";
6
+ export const RUN_FILE = "run.json";
7
+ export function appendTimeline(runFolder, entry) {
8
+ return appendFile(join(runFolder, TIMELINE_FILE), `${JSON.stringify(entry)}\n`);
9
+ }
10
+ export function writeRunSummary(runFolder, summary) {
11
+ return writeFile(join(runFolder, RUN_FILE), jsonFileText(summary));
12
+ }
13
+ //# sourceMappingURL=test-run-timeline.js.map
@@ -0,0 +1,8 @@
1
+ import type { RunLine } from "../run/run-process.js";
2
+ import type { VisitRecord } from "../test-run/visit-record.js";
3
+ export declare function visitFolderOf(runFolder: string, visitId: string): string;
4
+ export declare function outputsFolderOf(runFolder: string, visitId: string): string;
5
+ export declare function writeVisitRecord(runFolder: string, record: VisitRecord): Promise<void>;
6
+ export declare function writeVisitInputs(runFolder: string, visitId: string, needs: Readonly<Record<string, string>>): Promise<void>;
7
+ export declare function writeVisitPrompt(runFolder: string, visitId: string, prompt: string): Promise<void>;
8
+ export declare function writeVisitTranscript(runFolder: string, visitId: string, lines: readonly RunLine[]): Promise<void>;