@re-cinq/floor-studio 0.12.0 → 0.13.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 (82) hide show
  1. package/README.md +46 -9
  2. package/dist/backend/collection-view.js +2 -2
  3. package/dist/backend/floor-answers.d.ts +14 -0
  4. package/dist/backend/floor-answers.js +39 -0
  5. package/dist/backend/floor-blob-routes.d.ts +9 -0
  6. package/dist/backend/floor-blob-routes.js +30 -0
  7. package/dist/backend/floor-brief-route.d.ts +26 -0
  8. package/dist/backend/floor-brief-route.js +21 -0
  9. package/dist/backend/floor-connection-request.d.ts +6 -0
  10. package/dist/backend/floor-connection-request.js +9 -0
  11. package/dist/backend/floor-credentials.d.ts +16 -0
  12. package/dist/backend/floor-credentials.js +14 -0
  13. package/dist/backend/floor-event-routes.d.ts +14 -0
  14. package/dist/backend/floor-event-routes.js +80 -0
  15. package/dist/backend/floor-records-route.d.ts +3 -0
  16. package/dist/backend/floor-records-route.js +22 -0
  17. package/dist/backend/floor-request-body.d.ts +9 -0
  18. package/dist/backend/floor-request-body.js +30 -0
  19. package/dist/backend/floor-route.d.ts +12 -0
  20. package/dist/backend/floor-route.js +41 -0
  21. package/dist/backend/floor-start-route.d.ts +4 -0
  22. package/dist/backend/floor-start-route.js +21 -0
  23. package/dist/backend/floor-visits.d.ts +10 -0
  24. package/dist/backend/floor-visits.js +29 -0
  25. package/dist/backend/guard.d.ts +1 -0
  26. package/dist/backend/guard.js +1 -1
  27. package/dist/backend/parse-json-text.d.ts +1 -0
  28. package/dist/backend/parse-json-text.js +10 -0
  29. package/dist/backend/past-test-run-state.js +22 -4
  30. package/dist/backend/past-test-runs.js +2 -9
  31. package/dist/backend/requests.d.ts +10 -1
  32. package/dist/backend/requests.js +2 -1
  33. package/dist/backend/start-studio.d.ts +17 -0
  34. package/dist/backend/start-studio.js +45 -15
  35. package/dist/backend/test-floor-server.d.ts +27 -0
  36. package/dist/backend/test-floor-server.js +30 -0
  37. package/dist/backend/test-floor-token.d.ts +1 -0
  38. package/dist/backend/test-floor-token.js +19 -0
  39. package/dist/backend/test-run-folder.js +8 -5
  40. package/dist/backend/test-run-session.d.ts +3 -0
  41. package/dist/backend/test-run-session.js +56 -10
  42. package/dist/protocol.d.ts +13 -1
  43. package/dist/protocol.js +2 -1
  44. package/dist/shell/arguments.d.ts +2 -0
  45. package/dist/shell/arguments.js +12 -7
  46. package/dist/shell/loopback-server.d.ts +6 -0
  47. package/dist/shell/loopback-server.js +13 -0
  48. package/dist/shell/static-files.js +3 -6
  49. package/dist/shell/studio-command.d.ts +1 -1
  50. package/dist/shell/studio-command.js +24 -7
  51. package/dist/test-floor/blob-store.d.ts +10 -0
  52. package/dist/test-floor/blob-store.js +29 -0
  53. package/dist/test-floor/dispatch-queue.d.ts +19 -0
  54. package/dist/test-floor/dispatch-queue.js +90 -0
  55. package/dist/test-floor/visit-brief.d.ts +12 -0
  56. package/dist/test-floor/visit-brief.js +57 -0
  57. package/dist/test-floor/visit-tokens.d.ts +5 -0
  58. package/dist/test-floor/visit-tokens.js +12 -0
  59. package/dist/test-floor/worker-answer.d.ts +8 -0
  60. package/dist/test-floor/worker-answer.js +14 -0
  61. package/dist/test-run/event-answer.js +2 -1
  62. package/dist/test-run/outcome-fields.d.ts +2 -0
  63. package/dist/test-run/outcome-fields.js +3 -1
  64. package/dist/test-run/past-state.d.ts +7 -1
  65. package/dist/test-run/past-state.js +6 -2
  66. package/dist/test-run/stand-in-actions.d.ts +1 -0
  67. package/dist/test-run/stand-in-actions.js +6 -3
  68. package/dist/test-run/stand-in-report.js +3 -6
  69. package/dist/test-run/test-run-state.d.ts +5 -1
  70. package/dist/test-run/test-visit.d.ts +6 -0
  71. package/dist/test-run/timeline.d.ts +2 -1
  72. package/dist/test-run/visit-kind.d.ts +2 -1
  73. package/dist/test-run/visit-kind.js +6 -2
  74. package/dist/test-run/visit-record.d.ts +1 -0
  75. package/dist/test-run/visit-record.js +3 -3
  76. package/dist/view.d.ts +1 -0
  77. package/dist/web/assets/index-C8uog-4Z.css +1 -0
  78. package/dist/web/assets/index-CfJcNJKZ.js +195 -0
  79. package/dist/web/index.html +2 -2
  80. package/package.json +6 -5
  81. package/dist/web/assets/index-BYtywrMW.css +0 -1
  82. package/dist/web/assets/index-DrObCntU.js +0 -195
@@ -127,6 +127,10 @@ export declare const testListRequest: z.ZodObject<{
127
127
  id: z.ZodString;
128
128
  type: z.ZodLiteral<"test.list">;
129
129
  }, z.core.$strict>;
130
+ export declare const floorConnectionRequest: z.ZodObject<{
131
+ id: z.ZodString;
132
+ type: z.ZodLiteral<"floor.connection">;
133
+ }, z.core.$strict>;
130
134
  export declare const folderOpenRequest: z.ZodObject<{
131
135
  id: z.ZodString;
132
136
  type: z.ZodLiteral<"folder.open">;
@@ -261,6 +265,9 @@ export declare const requestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
261
265
  }, z.core.$strict>, z.ZodObject<{
262
266
  id: z.ZodString;
263
267
  type: z.ZodLiteral<"test.list">;
268
+ }, z.core.$strict>, z.ZodObject<{
269
+ id: z.ZodString;
270
+ type: z.ZodLiteral<"floor.connection">;
264
271
  }, z.core.$strict>], "type">;
265
272
  export type Request = z.infer<typeof requestSchema>;
266
273
  export type RequestKind = Request["type"];
@@ -329,7 +336,12 @@ export type ResultOf<Asked extends Request> = Asked extends {
329
336
  entered: Record<string, string>;
330
337
  } | null : Asked extends {
331
338
  type: "test.list";
332
- } ? TestRunListing[] : never;
339
+ } ? TestRunListing[] : Asked extends {
340
+ type: "floor.connection";
341
+ } ? {
342
+ url: string;
343
+ token: string;
344
+ } : never;
333
345
  export declare const collectionViewSchema: z.ZodType<CollectionView>;
334
346
  export declare const helloFrame: z.ZodObject<{
335
347
  type: z.ZodLiteral<"hello">;
package/dist/protocol.js CHANGED
@@ -20,11 +20,12 @@ export const testReadRequest = z.strictObject({ id: requestId, type: z.literal("
20
20
  export const testPreviewRequest = z.strictObject({ id: requestId, type: z.literal("test.preview"), line: z.string(), entered: z.record(z.string(), z.string()) });
21
21
  export const testLastRequest = z.strictObject({ id: requestId, type: z.literal("test.last"), line: z.string() });
22
22
  export const testListRequest = z.strictObject({ id: requestId, type: z.literal("test.list") });
23
+ export const floorConnectionRequest = z.strictObject({ id: requestId, type: z.literal("floor.connection") });
23
24
  export const folderOpenRequest = z.strictObject({ id: requestId, type: z.literal("folder.open"), path: z.string() });
24
25
  export const folderListRequest = z.strictObject({ id: requestId, type: z.literal("folder.list"), path: z.string().optional() });
25
26
  export const testEventRequest = z.strictObject({ id: requestId, type: z.literal("test.event"), run: z.string(), event: z.string(), payload: z.record(z.string(), z.unknown()) });
26
27
  /** A new request type is one schema here and one handler in the backend's table. */
27
- export const requestSchema = z.discriminatedUnion("type", [collectionReadRequest, agentWriteRequest, extraWriteRequest, fixtureWriteRequest, fixtureReadRequest, runPreviewRequest, runStartRequest, runCancelRequest, runReadRequest, testStartRequest, testReportRequest, testCancelRequest, testReadRequest, testPreviewRequest, folderOpenRequest, folderListRequest, testEventRequest, testLastRequest, testListRequest]);
28
+ export const requestSchema = z.discriminatedUnion("type", [collectionReadRequest, agentWriteRequest, extraWriteRequest, fixtureWriteRequest, fixtureReadRequest, runPreviewRequest, runStartRequest, runCancelRequest, runReadRequest, testStartRequest, testReportRequest, testCancelRequest, testReadRequest, testPreviewRequest, folderOpenRequest, folderListRequest, testEventRequest, testLastRequest, testListRequest, floorConnectionRequest]);
28
29
  export const REQUEST_TYPES = requestSchema.options.map(({ shape }) => shape.type.value);
29
30
  // Strict down to a node's agent; events, placeholders, needs, produces, edges, args, start and kind come from other packages and are only checked to be objects where required.
30
31
  const presentObject = () => z.custom((value) => typeof value === "object" && value !== null);
@@ -3,6 +3,8 @@ export interface RunArguments {
3
3
  dir: string;
4
4
  /** The backend's socket port; 0 picks a free one. */
5
5
  port: number;
6
+ /** The local test floor's socket port; 0 picks a free one. */
7
+ floorPort: number;
6
8
  hostKeys: string[];
7
9
  open: boolean;
8
10
  }
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  const MAX_PORT = 65535;
3
- const OPTIONS = { port: { type: "string" }, "host-key": { type: "string", multiple: true }, "no-open": { type: "boolean" }, help: { type: "boolean" } };
3
+ const PORT_OPTIONS = ["port", "floor-port"];
4
+ const OPTIONS = { port: { type: "string" }, "floor-port": { type: "string" }, "host-key": { type: "string", multiple: true }, "no-open": { type: "boolean" }, help: { type: "boolean" } };
4
5
  export function parseStudioArguments(argv) {
5
6
  try {
6
7
  return interpreted(parsed(argv));
@@ -18,13 +19,17 @@ function interpreted(parsedOptions) {
18
19
  return { kind: "help" };
19
20
  if (positionals.length > 1)
20
21
  return { kind: "bad", reason: `one directory at most: got ${positionals.join(", ")}` };
21
- const port = Number(values.port ?? 0);
22
- if (!isPort(port))
23
- return { kind: "bad", reason: `--port needs a whole number from 0 to ${MAX_PORT}` };
24
- return runOf(parsedOptions, port);
22
+ const ports = portsOf(values);
23
+ const refusedPort = PORT_OPTIONS.find((name) => !isPort(ports[name]));
24
+ if (refusedPort)
25
+ return { kind: "bad", reason: `--${refusedPort} needs a whole number from 0 to ${MAX_PORT}` };
26
+ return { kind: "run", dir: positionals[0] ?? ".", port: ports.port, floorPort: ports["floor-port"], hostKeys: values["host-key"] ?? [], open: !values["no-open"] };
25
27
  }
26
- function runOf({ values, positionals }, port) {
27
- return { kind: "run", dir: positionals[0] ?? ".", port, hostKeys: values["host-key"] ?? [], open: !values["no-open"] };
28
+ function portsOf(values) {
29
+ return { port: portOf(values.port), "floor-port": portOf(values["floor-port"]) };
30
+ }
31
+ function portOf(text = "0") {
32
+ return /^\d+$/.test(text) ? Number(text) : Number.NaN;
28
33
  }
29
34
  function isPort(port) {
30
35
  return Number.isInteger(port) && port >= 0 && port <= MAX_PORT;
@@ -0,0 +1,6 @@
1
+ import type { Server } from "node:http";
2
+ export declare const LOOPBACK = "127.0.0.1";
3
+ /** Listens on the loopback address and resolves with the port bound; 0 picks a free one. A listen error rejects as it came. */
4
+ export declare function listenOnLoopback(server: Server, port: number): Promise<number>;
5
+ /** Drops the open connections, then stops listening. */
6
+ export declare function closeServer(server: Server): Promise<void>;
@@ -0,0 +1,13 @@
1
+ export const LOOPBACK = "127.0.0.1";
2
+ /** Listens on the loopback address and resolves with the port bound; 0 picks a free one. A listen error rejects as it came. */
3
+ export function listenOnLoopback(server, port) {
4
+ return new Promise((listening, refused) => {
5
+ server.once("error", refused);
6
+ server.listen(port, LOOPBACK, () => listening(server.address().port));
7
+ });
8
+ }
9
+ /** Drops the open connections, then stops listening. */
10
+ export function closeServer(server) {
11
+ return new Promise((closed) => (server.closeAllConnections(), server.close(() => closed())));
12
+ }
13
+ //# sourceMappingURL=loopback-server.js.map
@@ -2,7 +2,7 @@
2
2
  import { readFile, realpath, stat } from "node:fs/promises";
3
3
  import { createServer } from "node:http";
4
4
  import { extname, resolve, sep } from "node:path";
5
- const LOOPBACK = "127.0.0.1";
5
+ import { closeServer, listenOnLoopback, LOOPBACK } from "./loopback-server.js";
6
6
  const SUCCESS = 200;
7
7
  const BAD_REQUEST = 400;
8
8
  const NOT_FOUND = 404;
@@ -29,11 +29,8 @@ export function contentTypeOf(path) {
29
29
  }
30
30
  export async function startPageServer(root) {
31
31
  const server = createServer((request, response) => void respond(root, request, response));
32
- await new Promise((listening) => server.listen(0, LOOPBACK, listening));
33
- return {
34
- origin: `http://${LOOPBACK}:${server.address().port}`,
35
- close: () => new Promise((closed) => (server.closeAllConnections(), server.close(() => closed()))),
36
- };
32
+ const port = await listenOnLoopback(server, 0);
33
+ return { origin: `http://${LOOPBACK}:${port}`, close: () => closeServer(server) };
37
34
  }
38
35
  async function respond(root, request, response) {
39
36
  const answer = await pageAnswer(root, request);
@@ -1,4 +1,4 @@
1
- export declare const USAGE = "floor-studio [dir] [--port <n>] [--host-key <name>]... [--no-open]\n\n dir the collection: one folder a line, with its assembly-line.yaml and agents/. Default: the current directory\n --port <n> the port of the backend's socket on 127.0.0.1. Default: a free one\n --host-key <name> a frontmatter key the host owns, accepted in an agent file; as often as needed\n --no-open print the url and do not open a browser. Without it a browser opens after 3 seconds, unless a page\n (such as a tab left open from before a restart) has connected by then\n --help this text";
1
+ export declare const USAGE = "floor-studio [dir] [--port <n>] [--floor-port <n>] [--host-key <name>]... [--no-open]\n\n dir the collection: one folder a line, with its assembly-line.yaml and agents/. Default: the current directory\n --port <n> the port of the backend's socket on 127.0.0.1. Default: a free one\n --floor-port <n> the port of the test floor custom-station workers connect to, on 127.0.0.1. Default: a free one\n --host-key <name> a frontmatter key the host owns, accepted in an agent file; as often as needed\n --no-open print the url and do not open a browser. Without it a browser opens after 3 seconds, unless a page\n (such as a tab left open from before a restart) has connected by then\n --help this text";
2
2
  export interface Shell {
3
3
  out(line: string): void;
4
4
  err(line: string): void;
@@ -1,13 +1,21 @@
1
1
  // The `floor-studio` command without the process around it: arguments in, an exit code or a running studio out.
2
+ import { randomBytes } from "node:crypto";
2
3
  import { resolve } from "node:path";
4
+ import { createBlobStore } from "../test-floor/blob-store.js";
5
+ import { createVisitTokens } from "../test-floor/visit-tokens.js";
3
6
  import { startStudio } from "../backend/start-studio.js";
7
+ import { startTestFloor } from "../backend/test-floor-server.js";
8
+ import { storeFolderIn } from "../backend/store-folder.js";
9
+ import { testFloorToken } from "../backend/test-floor-token.js";
4
10
  import { parseStudioArguments } from "./arguments.js";
5
11
  import { pageUrl } from "./page-url.js";
6
12
  import { startPageServer } from "./static-files.js";
7
- export const USAGE = `floor-studio [dir] [--port <n>] [--host-key <name>]... [--no-open]
13
+ const TOKEN_BYTES = 32;
14
+ export const USAGE = `floor-studio [dir] [--port <n>] [--floor-port <n>] [--host-key <name>]... [--no-open]
8
15
 
9
16
  dir the collection: one folder a line, with its assembly-line.yaml and agents/. Default: the current directory
10
17
  --port <n> the port of the backend's socket on 127.0.0.1. Default: a free one
18
+ --floor-port <n> the port of the test floor custom-station workers connect to, on 127.0.0.1. Default: a free one
11
19
  --host-key <name> a frontmatter key the host owns, accepted in an agent file; as often as needed
12
20
  --no-open print the url and do not open a browser. Without it a browser opens after 3 seconds, unless a page
13
21
  (such as a tab left open from before a restart) has connected by then
@@ -31,18 +39,27 @@ function refused(shell, exitCode, ...lines) {
31
39
  return { exitCode };
32
40
  }
33
41
  async function started(given, shell) {
42
+ const dir = resolve(given.dir);
34
43
  const page = await startPageServer(shell.pageDir);
35
44
  // Only the page's own origin may use the socket, whether the browser shows it as 127.0.0.1 or localhost.
36
- const studio = await startStudio({ dir: resolve(given.dir), port: given.port, hostKeys: given.hostKeys, origins: [page.origin, page.origin.replace("127.0.0.1", "localhost")] }).catch(async (cause) => {
37
- await page.close();
38
- throw cause;
39
- });
45
+ const studio = await startStudio({ dir, port: given.port, hostKeys: given.hostKeys, origins: [page.origin, page.origin.replace("127.0.0.1", "localhost")] }).catch(closing(page));
46
+ const floorToken = await testFloorToken(dir).catch(closing(page, studio));
47
+ const blobs = createBlobStore(await storeFolderIn(dir, "blobs").catch(closing(page, studio)));
48
+ const tokens = createVisitTokens(() => randomBytes(TOKEN_BYTES).toString("hex"));
49
+ const floor = await startTestFloor({ port: given.floorPort, token: floorToken, queue: studio.testFloor, visits: studio.floorVisits, tokens, blobs, dispatchChanged: studio.dispatchChanged, reportFromWorker: studio.reportFromWorker, startFromVisit: studio.startFromVisit }).catch(closing(page, studio));
50
+ studio.serveFloor({ url: floor.url, token: floorToken });
40
51
  const url = pageUrl({ origin: page.origin, socket: studio.url, token: studio.token });
41
- shell.out(`floor-studio: ${url}`);
52
+ [`floor-studio: ${url}`, "floor-studio: test floor for custom stations:", ` export FLOOR_API_URL=${floor.url}`, ` export FLOOR_SERVICE_TOKEN=${floorToken}`].forEach((line) => shell.out(line));
42
53
  const opening = given.open ? setTimeout(() => studio.pageCount() === 0 && shell.openBrowser(url), shell.pageWaitMs) : undefined;
43
54
  return { running: { pageUrl: url, close: async () => {
44
55
  clearTimeout(opening);
45
- await Promise.all([studio.close(), page.close()]);
56
+ await Promise.all([studio.close(), page.close(), floor.close()]);
46
57
  } } };
47
58
  }
59
+ function closing(...servers) {
60
+ return async (cause) => {
61
+ await Promise.all(servers.map((server) => server.close()));
62
+ throw cause;
63
+ };
64
+ }
48
65
  //# sourceMappingURL=studio-command.js.map
@@ -0,0 +1,10 @@
1
+ import type { BlobRef } from "@re-cinq/floor-contracts";
2
+ export interface BlobStore {
3
+ store(bytes: Buffer, contentType: string): Promise<BlobRef>;
4
+ storedPathOf(hash: string): string | undefined;
5
+ read(hash: string): Promise<{
6
+ bytes: Buffer;
7
+ contentType: string;
8
+ } | undefined>;
9
+ }
10
+ export declare function createBlobStore(folder: string, maxBytes?: number): BlobStore;
@@ -0,0 +1,29 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { MAX_BLOB_BYTES, blobHashOf, enforce } from "@re-cinq/floor-assembly-lines";
5
+ const BLOB_HASH_PATTERN = /^sha256-[0-9a-f]{64}$/;
6
+ export function createBlobStore(folder, maxBytes = MAX_BLOB_BYTES) {
7
+ const bytesPath = (hash) => join(folder, hash);
8
+ const storedPathOf = (hash) => (BLOB_HASH_PATTERN.test(hash) && existsSync(bytesPath(hash)) ? bytesPath(hash) : undefined);
9
+ const typePath = (hash) => join(folder, `${hash}.type`);
10
+ return {
11
+ storedPathOf,
12
+ async store(bytes, contentType) {
13
+ enforce(bytes.length <= maxBytes, `blob of ${bytes.length} bytes exceeds the ${maxBytes}-byte cap`);
14
+ const hash = blobHashOf(bytes);
15
+ if (!existsSync(bytesPath(hash))) {
16
+ await writeFile(typePath(hash), contentType);
17
+ await writeFile(bytesPath(hash), bytes);
18
+ }
19
+ return { hash, size: bytes.length };
20
+ },
21
+ async read(hash) {
22
+ const storedPath = storedPathOf(hash);
23
+ if (!storedPath)
24
+ return undefined;
25
+ return { bytes: await readFile(storedPath), contentType: await readFile(typePath(hash), "utf8") };
26
+ },
27
+ };
28
+ }
29
+ //# sourceMappingURL=blob-store.js.map
@@ -0,0 +1,19 @@
1
+ import type { ClaimedEvent } from "@re-cinq/floor-contracts";
2
+ export interface DispatchStatus {
3
+ tag: string;
4
+ claimedBy?: string;
5
+ claimedAt?: string;
6
+ gaveUp?: string;
7
+ }
8
+ export interface DispatchQueue {
9
+ dispatchOf(floorVisitId: string): DispatchStatus | undefined;
10
+ open(visitId: string, tag: string): void;
11
+ end(visitId: string): void;
12
+ claim(tags: string[], limit: number, claimedBy?: string): ClaimedEvent[];
13
+ ack(id: string): void;
14
+ fail(id: string, failure: {
15
+ permanent: boolean;
16
+ error: string;
17
+ }): string | undefined;
18
+ }
19
+ export declare const createDispatchQueue: (clock: () => Date) => DispatchQueue;
@@ -0,0 +1,90 @@
1
+ // In-memory twin of the floor's event queue: a worker claims the events whose tags it serves.
2
+ import { randomUUID } from "node:crypto";
3
+ import { MAX_EVENT_ATTEMPTS, backoffMs } from "@re-cinq/floor-assembly-lines";
4
+ const isServedBy = (askedTags) => ({ event }) => event.tags.every((tag) => askedTags.includes(tag));
5
+ const isAvailable = (now) => (queued) => !queued.claimed && !queued.dead && !queued.acked && now >= queued.heldUntil;
6
+ const newQueued = (event) => ({
7
+ event,
8
+ claimed: false,
9
+ dead: false,
10
+ acked: false,
11
+ heldUntil: 0,
12
+ });
13
+ const newVisitEvent = (name, visitId, tags) => ({
14
+ id: randomUUID(),
15
+ name,
16
+ tags,
17
+ attempts: 0,
18
+ payload: { visitId },
19
+ });
20
+ const isEventOf = (name, visitId) => ({ event }) => event.name === name && "visitId" in event.payload && event.payload.visitId === visitId;
21
+ const liveDispatchOf = (queue, visitId) => {
22
+ const dispatch = queue.find(isEventOf("station_run.dispatch", visitId));
23
+ const isAborted = queue.some(isEventOf("station_run.abort", visitId));
24
+ return isAborted ? undefined : dispatch;
25
+ };
26
+ const abortDispatchOf = (queue, visitId) => {
27
+ const dispatch = liveDispatchOf(queue, visitId);
28
+ if (!dispatch)
29
+ return;
30
+ dispatch.dead = true;
31
+ queue.push(newQueued(newVisitEvent("station_run.abort", visitId, dispatch.event.tags)));
32
+ };
33
+ const dispatchStatusOf = (queue, visitId) => {
34
+ const dispatch = liveDispatchOf(queue, visitId);
35
+ if (!dispatch)
36
+ return undefined;
37
+ const [tag] = dispatch.event.tags;
38
+ return dispatch.gaveUp === undefined ? { tag, ...dispatch.claim } : { tag, gaveUp: dispatch.gaveUp };
39
+ };
40
+ const recordFailure = (queued, now, { permanent, error }) => {
41
+ queued.heldUntil = now + backoffMs(queued.event.attempts);
42
+ queued.event = { ...queued.event, attempts: queued.event.attempts + 1 };
43
+ queued.claimed = false;
44
+ queued.claim = undefined;
45
+ queued.dead ||= permanent || queued.event.attempts >= MAX_EVENT_ATTEMPTS;
46
+ if (queued.dead)
47
+ queued.gaveUp = error;
48
+ };
49
+ const markClaimed = (queued, now, claimedBy) => {
50
+ queued.claimed = true;
51
+ queued.claim = { claimedAt: now.toISOString(), ...(claimedBy === undefined ? {} : { claimedBy }) };
52
+ };
53
+ const forEvent = (queue, id, update) => {
54
+ queue.filter(({ event }) => event.id === id).forEach(update);
55
+ };
56
+ const failDispatchOf = (queue, id, now, failure) => {
57
+ forEvent(queue, id, (queued) => recordFailure(queued, now, failure));
58
+ const failed = queue.find(({ event }) => event.id === id)?.event;
59
+ return failed?.name === "station_run.dispatch" ? failed.payload.visitId : undefined;
60
+ };
61
+ export const createDispatchQueue = (clock) => {
62
+ const queue = [];
63
+ return {
64
+ dispatchOf: (floorVisitId) => dispatchStatusOf(queue, floorVisitId),
65
+ open: (visitId, tag) => {
66
+ queue.push(newQueued(newVisitEvent("station_run.dispatch", visitId, [tag])));
67
+ },
68
+ end: (visitId) => abortDispatchOf(queue, visitId),
69
+ claim: (tags, limit, claimedBy) => {
70
+ const now = clock();
71
+ const handedOut = queue
72
+ .filter(isAvailable(now.getTime()))
73
+ .filter(isServedBy(tags))
74
+ .slice(0, limit);
75
+ handedOut.forEach((queued) => {
76
+ markClaimed(queued, now, claimedBy);
77
+ });
78
+ return handedOut.map(({ event }) => event);
79
+ },
80
+ ack: (id) => {
81
+ forEvent(queue, id, (queued) => {
82
+ queued.acked = true;
83
+ });
84
+ },
85
+ fail: (id, failure) => {
86
+ return failDispatchOf(queue, id, clock().getTime(), failure);
87
+ },
88
+ };
89
+ };
90
+ //# sourceMappingURL=dispatch-queue.js.map
@@ -0,0 +1,12 @@
1
+ import type { VisitBrief } from "@re-cinq/floor-contracts";
2
+ import type { TestRun, VisitState } from "../test-run/test-visit.js";
3
+ import type { BlobStore } from "./blob-store.js";
4
+ export interface VisitBriefSource {
5
+ run: TestRun;
6
+ runId: string;
7
+ visit: VisitState;
8
+ floorUrl: string;
9
+ mintToken(): string;
10
+ blobs: BlobStore;
11
+ }
12
+ export declare function visitBriefOf({ run, runId, visit, floorUrl, mintToken, blobs }: VisitBriefSource): Promise<VisitBrief>;
@@ -0,0 +1,57 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { enforce, needPathOf } from "@re-cinq/floor-assembly-lines";
5
+ import { stationAt } from "../test-run/test-line.js";
6
+ const FLOOR_DEADLINE_MINUTES = 60;
7
+ export async function visitBriefOf({ run, runId, visit, floorUrl, mintToken, blobs }) {
8
+ const { produces, needs } = stationAt(run.line, visit.nodeId).station;
9
+ enforce(visit.floorVisitId !== undefined, `visit ${visit.id} has no dispatch on the test floor`);
10
+ const context = { blobs, floorUrl };
11
+ const bag = new Map(Object.entries(visit.needs));
12
+ const placedNeeds = needs.filter(isPlaced).flatMap((spec) => placedNeedOf(spec, bag));
13
+ const placedNames = new Set(placedNeeds.map(({ spec }) => spec.name));
14
+ const valueEntries = Object.entries(visit.needs).filter(([name]) => !placedNames.has(name));
15
+ const briefNeeds = await Promise.all([
16
+ ...valueEntries.map((entry) => needBriefOf(entry, undefined, context)),
17
+ ...placedNeeds.map(({ spec, entry }) => needBriefOf(entry, spec, context)),
18
+ ]);
19
+ return {
20
+ visitId: visit.floorVisitId,
21
+ runId,
22
+ lineId: run.line.id,
23
+ nodeId: visit.nodeId,
24
+ iteration: visit.iteration,
25
+ floorBaseUrl: floorUrl,
26
+ token: mintToken(),
27
+ deadlineMinutes: FLOOR_DEADLINE_MINUTES,
28
+ settings: null,
29
+ needs: briefNeeds,
30
+ produces,
31
+ conversation: { mode: "new", save: false },
32
+ };
33
+ }
34
+ function placedNeedOf(spec, bag) {
35
+ const value = bag.get(spec.name);
36
+ return value === undefined ? [] : [{ spec, entry: [spec.name, value] }];
37
+ }
38
+ function isPlaced(spec) {
39
+ return spec.kind === "git" || spec.kind === "file";
40
+ }
41
+ async function needBriefOf([name, value], spec, context) {
42
+ if (spec?.kind === "git")
43
+ return gitNeedBrief(name, value, spec);
44
+ if (spec?.kind === "file")
45
+ return fileNeedBrief(name, value, spec, context);
46
+ return { name, kind: "value", value };
47
+ }
48
+ function gitNeedBrief(name, checkout, spec) {
49
+ enforce(existsSync(join(checkout, ".git")), `the checkout of need ${name} is not a git repository: ${checkout}`);
50
+ return { name, kind: "git", path: needPathOf(spec), repoUrl: checkout, ref: "HEAD", access: spec.access ?? "read" };
51
+ }
52
+ async function fileNeedBrief(name, file, spec, { blobs, floorUrl }) {
53
+ enforce(existsSync(file), `the file of need ${name} is not on disk: ${file}`);
54
+ const { hash } = await blobs.store(await readFile(file), "application/octet-stream");
55
+ return { name, kind: "file", path: needPathOf(spec), url: `${floorUrl}/blobs/${hash}` };
56
+ }
57
+ //# sourceMappingURL=visit-brief.js.map
@@ -0,0 +1,5 @@
1
+ export interface VisitTokens {
2
+ mint(floorVisitId: string): string;
3
+ visitOf(token: string): string | undefined;
4
+ }
5
+ export declare function createVisitTokens(randomHex: () => string): VisitTokens;
@@ -0,0 +1,12 @@
1
+ export function createVisitTokens(randomHex) {
2
+ const visitsByToken = new Map();
3
+ return {
4
+ mint: (floorVisitId) => {
5
+ const token = randomHex();
6
+ visitsByToken.set(token, floorVisitId);
7
+ return token;
8
+ },
9
+ visitOf: (token) => visitsByToken.get(token),
10
+ };
11
+ }
12
+ //# sourceMappingURL=visit-tokens.js.map
@@ -0,0 +1,8 @@
1
+ import type { StationBody } from "@re-cinq/floor-contracts";
2
+ import type { StandInAnswer } from "../test-run/stand-in-report.js";
3
+ interface WorkerReport {
4
+ outcome: string;
5
+ produced?: Record<string, string>;
6
+ }
7
+ export declare function workerAnswerOf(station: StationBody, { outcome, produced }: WorkerReport, storedPathOf: (hash: string) => string | undefined): StandInAnswer | string;
8
+ export {};
@@ -0,0 +1,14 @@
1
+ export function workerAnswerOf(station, { outcome, produced = {} }, storedPathOf) {
2
+ const { produces } = station;
3
+ const fileNames = new Set(produces.filter(({ kind }) => kind === "file").map(({ name }) => name));
4
+ const entries = Object.entries(produced);
5
+ const files = {};
6
+ for (const [name, hash] of entries.filter(([producedName]) => fileNames.has(producedName))) {
7
+ const picked = storedPathOf(hash);
8
+ if (picked === undefined)
9
+ return `${name}: no blob "${hash}"`;
10
+ files[name] = { picked };
11
+ }
12
+ return { outcome, produced: Object.fromEntries(entries.filter(([name]) => !fileNames.has(name))), files };
13
+ }
14
+ //# sourceMappingURL=worker-answer.js.map
@@ -1,10 +1,11 @@
1
1
  // The outcome an event a person sends gives a waiting node: the floor's kernel decides, never Studio.
2
2
  import { answersOf } from "@re-cinq/floor-assembly-lines";
3
+ import { waitsForAnswer } from "./visit-kind.js";
3
4
  export function eventOutcomeOf(line, nodeId, sent) {
4
5
  return answersOf(line.body, sent.name, sent.payload).find((answer) => answer.nodeId === nodeId)?.outcome;
5
6
  }
6
7
  export function answeredVisitsOf(line, visits, sent) {
7
- const waiting = visits.filter(({ report, kind }) => report === null && kind === "stand-in");
8
+ const waiting = visits.filter(({ report, kind }) => report === null && waitsForAnswer(kind));
8
9
  return waiting.flatMap((visit) => {
9
10
  const outcome = eventOutcomeOf(line, visit.nodeId, sent);
10
11
  return outcome === undefined ? [] : [{ visit, outcome }];
@@ -5,6 +5,8 @@ export interface OutcomeField {
5
5
  kind: "value" | "file";
6
6
  required: boolean;
7
7
  path?: string;
8
+ description?: string;
9
+ enum?: string[];
8
10
  }
9
11
  export declare function outcomeFieldsOf(line: TestLine, nodeId: string, outcome: string): OutcomeField[];
10
12
  export declare function otherOutputsOf(produces: ProduceSpec[], fields: OutcomeField[]): OutcomeField[];
@@ -9,11 +9,13 @@ export function outcomeFieldsOf(line, nodeId, outcome) {
9
9
  const { produces } = stationAt(line, nodeId).station;
10
10
  return produces
11
11
  .filter((produce) => reads.has(produce.name))
12
- .map(({ name, kind, path }) => ({
12
+ .map(({ name, kind, path, description, enum: allowed }) => ({
13
13
  name,
14
14
  kind,
15
15
  required: isRequired(reads.get(name)),
16
16
  ...(path === undefined ? {} : { path }),
17
+ ...(description === undefined ? {} : { description }),
18
+ ...(allowed === undefined ? {} : { enum: allowed }),
17
19
  }));
18
20
  }
19
21
  export function otherOutputsOf(produces, fields) {
@@ -1,5 +1,11 @@
1
1
  import type { RunSummary } from "./run-summary.js";
2
2
  import type { TimelineEntry } from "./timeline.js";
3
3
  import type { TestRunState } from "./test-run-state.js";
4
+ import type { TestLine } from "./test-line.js";
4
5
  import type { VisitRecord } from "./visit-record.js";
5
- export declare function pastStateOf(folder: string, summary: RunSummary, timeline: TimelineEntry[], records: Record<string, VisitRecord>): TestRunState;
6
+ interface PastFiles {
7
+ records: Record<string, VisitRecord>;
8
+ line?: TestLine;
9
+ }
10
+ export declare function pastStateOf(folder: string, summary: RunSummary, timeline: TimelineEntry[], { records, line }: PastFiles): TestRunState;
11
+ export {};
@@ -1,13 +1,17 @@
1
- export function pastStateOf(folder, summary, timeline, records) {
1
+ // Pure: the state of a run an earlier studio left in a workspace, rebuilt from what it wrote to disk.
2
+ import { bagEntriesOf } from "./run-bag.js";
3
+ export function pastStateOf(folder, summary, timeline, { records, line }) {
2
4
  const settled = summary.status === "settled";
3
5
  const opened = timeline.filter((entry) => entry.type === "visit_opened");
6
+ const visits = opened.map((entry) => visitOf(entry, records[entry.visit]));
4
7
  return {
5
8
  folder,
6
9
  lineId: summary.line,
7
10
  status: settled ? summary.status : "stopped",
8
11
  ...(settled && summary.ending && { ending: summary.ending }),
9
- visits: opened.map((entry) => visitOf(entry, records[entry.visit])),
12
+ visits,
10
13
  actions: {},
14
+ ...(line && { bag: bagEntriesOf({ line, startItems: summary.startItems, visits }) }),
11
15
  };
12
16
  }
13
17
  function visitOf({ visit, node, iteration, at: openedAt, mode }, record) {
@@ -5,6 +5,7 @@ import type { VisitState } from "./test-visit.js";
5
5
  export type StandInAction = {
6
6
  kind: "report";
7
7
  outcome: string;
8
+ description?: string;
8
9
  fields: OutcomeField[];
9
10
  others: OutcomeField[];
10
11
  } | {
@@ -1,12 +1,13 @@
1
1
  import { otherOutputsOf, outcomeFieldsOf } from "./outcome-fields.js";
2
2
  import { stationAt } from "./test-line.js";
3
+ import { waitsForAnswer } from "./visit-kind.js";
3
4
  export function standInActionsOf(line, nodeId) {
4
5
  const { node, station } = stationAt(line, nodeId);
5
6
  const reports = node.reports ?? [];
6
7
  return [...eventActionsOf(reports), ...reportActionsOf(line, nodeId, station.outcomes, reports)];
7
8
  }
8
9
  export function waitingActionsOf(line, visits) {
9
- const waiting = visits.filter(({ kind, report }) => kind === "stand-in" && report === null);
10
+ const waiting = visits.filter(({ kind, report }) => waitsForAnswer(kind) && report === null);
10
11
  return Object.fromEntries(waiting.map(({ id, nodeId }) => [id, standInActionsOf(line, nodeId)]));
11
12
  }
12
13
  function eventActionsOf(reports) {
@@ -20,7 +21,9 @@ function reportActionsOf(line, nodeId, outcomes, reports) {
20
21
  }
21
22
  function reportActionOf(line, nodeId, outcome) {
22
23
  const fields = outcomeFieldsOf(line, nodeId, outcome);
23
- const others = otherOutputsOf(stationAt(line, nodeId).station.produces, fields);
24
- return { kind: "report", outcome, fields, others };
24
+ const { produces, outcomeDescriptions } = stationAt(line, nodeId).station;
25
+ const others = otherOutputsOf(produces, fields);
26
+ const description = outcomeDescriptions?.[outcome];
27
+ return { kind: "report", outcome, ...(description === undefined ? {} : { description }), fields, others };
25
28
  }
26
29
  //# sourceMappingURL=stand-in-actions.js.map
@@ -1,19 +1,16 @@
1
- import { enforce } from "@re-cinq/floor-assembly-lines";
1
+ import { checkReport, enforce } from "@re-cinq/floor-assembly-lines";
2
2
  import { enteredValue } from "./entered-value.js";
3
3
  import { outcomeFieldsOf } from "./outcome-fields.js";
4
4
  import { stationAt } from "./test-line.js";
5
5
  export function standInReport(line, nodeId, answer) {
6
6
  const { node, station } = stationAt(line, nodeId);
7
7
  const { outcome } = answer;
8
- enforceStationHasOutcome(node, station, outcome);
8
+ const produced = enteredProduces(station.produces, answer.produced);
9
+ checkReport({ line: line.body, nodeId, stationOf: () => station, report: { outcome, produced } });
9
10
  enforceRequiredFieldsEntered(line, nodeId, answer);
10
11
  enforceSuppliedFilesAreDeclared(node, station, answer);
11
- const produced = enteredProduces(station.produces, answer.produced);
12
12
  return Object.keys(produced).length === 0 ? { outcome } : { outcome, produced };
13
13
  }
14
- function enforceStationHasOutcome(node, station, outcome) {
15
- enforce(station.outcomes.includes(outcome), `${node.id} cannot report ${outcome}: its station ${node.station} has the outcomes ${station.outcomes.join(", ")}`);
16
- }
17
14
  function enforceRequiredFieldsEntered(line, nodeId, answer) {
18
15
  for (const field of outcomeFieldsOf(line, nodeId, answer.outcome)) {
19
16
  enforce(!field.required || isEntered(answer, field.name), `${field.name} is required when ${nodeId} reports ${answer.outcome}`);
@@ -1,4 +1,5 @@
1
1
  import type { Item } from "@re-cinq/floor-contracts";
2
+ import type { DispatchStatus } from "../test-floor/dispatch-queue.js";
2
3
  import type { StandInAction } from "./stand-in-actions.js";
3
4
  import type { VisitState } from "./test-visit.js";
4
5
  export interface TestRunState {
@@ -6,10 +7,13 @@ export interface TestRunState {
6
7
  lineId: string;
7
8
  status: "running" | "waiting" | "settled" | "stopped";
8
9
  ending?: TestRunEnding;
9
- visits: VisitState[];
10
+ visits: DispatchedVisit[];
10
11
  actions: Record<string, StandInAction[]>;
11
12
  bag?: BagEntry[];
12
13
  }
14
+ export type DispatchedVisit = VisitState & {
15
+ dispatch?: DispatchStatus;
16
+ };
13
17
  export interface BagEntry {
14
18
  name: string;
15
19
  kind: Item["kind"];