diff --git a/packages/cli/tests/fixtures/repl/failure-journal.ts b/packages/cli/tests/fixtures/repl/failure-journal.ts new file mode 100644 index 000000000..85e1937ce --- /dev/null +++ b/packages/cli/tests/fixtures/repl/failure-journal.ts @@ -0,0 +1,30 @@ +import type { Operation } from "effection"; +import process from "node:process"; +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; +import type { JournalCase } from "../../../src/test-diagnostics.ts"; +import type { DeliverySink } from "../../../src/stdout-delivery.ts"; +import { partitionEntrySegments } from "../../../src/repl/entries.ts"; +import type { ReplExecution } from "../../../src/repl/journal.ts"; + +/** Capture the admission owned by a synthetic, single-entry REPL fixture. */ +export function captureReplEntry( + testCase: JournalCase, + id: string, + source: string, + body: (holder: ReplExecution) => Operation, + sink: DeliverySink = process.stderr, +): Operation { + return captureTestJournal(testCase, source, (stream) => body({ id, stream }), { + sink, + selectEvents(events) { + const partition = partitionEntrySegments(events); + if (!partition.ok) { + throw partition.error; + } + if (partition.value.length > 1) { + throw new Error("fixture execution holds more than one admitted entry"); + } + return partition.value[0]?.events ?? []; + }, + }); +} diff --git a/packages/cli/tests/repl-execution.test.ts b/packages/cli/tests/repl-execution.test.ts index a38170d42..9ed52d166 100644 --- a/packages/cli/tests/repl-execution.test.ts +++ b/packages/cli/tests/repl-execution.test.ts @@ -29,7 +29,7 @@ import { join } from "node:path"; import process from "node:process"; import { Writable } from "node:stream"; import { partitionEntrySegments, ROOT_IMPORT } from "../src/repl/entries.ts"; -import { captureTestJournal } from "@executablemd/test-support/failure-journal"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import type { DeliverySink } from "../src/stdout-delivery.ts"; import { useTempDirectory } from "@executablemd/test-support/temp"; @@ -255,24 +255,7 @@ function captureEntry( body: (holder: ReplExecution) => Operation, sink: DeliverySink = process.stderr, ): Operation { - return captureTestJournal( - { owner: OWNER, suite, name }, - source, - (stream) => body({ id: "kf39sla2", stream }), - { - sink, - selectEvents(events) { - const partition = partitionEntrySegments(events); - if (!partition.ok) { - throw partition.error; - } - if (partition.value.length > 1) { - throw new Error("fixture execution holds more than one admitted entry"); - } - return partition.value[0]?.events ?? []; - }, - }, - ); + return captureReplEntry({ owner: OWNER, suite, name }, "kf39sla2", source, body, sink); } function admitReferenceEntry( diff --git a/packages/cli/tests/repl-history.test.ts b/packages/cli/tests/repl-history.test.ts index ee813094d..272504236 100644 --- a/packages/cli/tests/repl-history.test.ts +++ b/packages/cli/tests/repl-history.test.ts @@ -23,9 +23,10 @@ import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, sleep } from "effection"; import type { Operation, Result } from "effection"; -import { useTempFileCompiler } from "@executablemd/core"; +import { INLINE_SOURCE_PATH, useTempFileCompiler } from "@executablemd/core"; import { InMemoryStream } from "@executablemd/durable-streams"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import { openReplSession } from "../src/repl/session.ts"; import type { ReplSession } from "../src/repl/session.ts"; import type { ReplExecution } from "../src/repl/journal.ts"; @@ -366,57 +367,79 @@ describe("H3 — the head is derived from retained facts and owned work", () => }); }); -describe("H3 — the head a real session publishes", () => { - beforeAll(() => useTempFileCompiler()); - - it("is empty before an entry, live while one runs, settled once it has", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - // Nothing retained and nothing owned. - expect(session.navigation.head).toBe("empty"); - expect(session.navigation.checkpoints).toEqual([]); +const HEAD_SUITE = "H3 — the head a real session publishes"; - accepted(yield* session.submit('\n')); - // Owned work, from before its first record exists. - expect(session.navigation.head).toBe("live"); - - yield* session.join(); - yield* sleep(0); - // The outcome is retained and nothing of the entry is still standing. - expect(session.navigation.head).toBe("settled"); - expect(session.navigation.checkpoints.map((one) => one.kind)).toContain("entry"); - expect(session.navigation.checkpoints.map((one) => one.kind)).toContain("terminal"); - }); +describe(HEAD_SUITE, () => { + beforeAll(() => useTempFileCompiler()); - it("is SETTLING while the outcome is retained and the entry is still coming down", function* () { - // The window a reader watching a run end is actually in: the root closed, - // and this process still owns what the entry acquired. A head taken from - // the root Close alone would call this finished. - let duringRelease: string | undefined; - let held: ReplSession | undefined; - const session = opened( - yield* openReplSession({ - execution: execution(), - installations: [ - { - *install(): Operation { - yield* ensure(() => { - duringRelease = held?.navigation.head; - }); - }, - }, - ], - }), - ); - held = session; - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); - // Read at the moment this entry's own installation was released, which - // is after its outcome was recorded and before its work was finished. - expect(duringRelease).toBe("settling"); - // And neutral once it is down, however it went. - expect(session.navigation.head).toBe("settled"); - }); + it("is empty before an entry, live while one runs, settled once it has", () => + captureReplEntry( + { + owner: "packages/cli/tests/repl-history.test.ts", + suite: HEAD_SUITE, + name: "is empty before an entry, live while one runs, settled once it has", + }, + "history", + INLINE_SOURCE_PATH, + function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + // Nothing retained and nothing owned. + expect(session.navigation.head).toBe("empty"); + expect(session.navigation.checkpoints).toEqual([]); + + accepted(yield* session.submit('\n')); + // Owned work, from before its first record exists. + expect(session.navigation.head).toBe("live"); + + yield* session.join(); + yield* sleep(0); + // The outcome is retained and nothing of the entry is still standing. + expect(session.navigation.head).toBe("settled"); + expect(session.navigation.checkpoints.map((one) => one.kind)).toContain("entry"); + expect(session.navigation.checkpoints.map((one) => one.kind)).toContain("terminal"); + }, + )); + + it("is SETTLING while the outcome is retained and the entry is still coming down", () => + captureReplEntry( + { + owner: "packages/cli/tests/repl-history.test.ts", + suite: HEAD_SUITE, + name: "is SETTLING while the outcome is retained and the entry is still coming down", + }, + "history", + INLINE_SOURCE_PATH, + function* (holder) { + // The window a reader watching a run end is actually in: the root closed, + // and this process still owns what the entry acquired. A head taken from + // the root Close alone would call this finished. + let duringRelease: string | undefined; + let held: ReplSession | undefined; + const session = opened( + yield* openReplSession({ + execution: holder, + installations: [ + { + *install(): Operation { + yield* ensure(() => { + duringRelease = held?.navigation.head; + }); + }, + }, + ], + }), + ); + held = session; + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); + // Read at the moment this entry's own installation was released, which + // is after its outcome was recorded and before its work was finished. + expect(duringRelease).toBe("settling"); + // And neutral once it is down, however it went. + expect(session.navigation.head).toBe("settled"); + }, + )); it("carries no payload from the entry it is describing", function* () { const session = opened(yield* openReplSession({ execution: execution() })); diff --git a/packages/cli/tests/repl-lifecycle.test.ts b/packages/cli/tests/repl-lifecycle.test.ts index fbf059549..6d0d0724c 100644 --- a/packages/cli/tests/repl-lifecycle.test.ts +++ b/packages/cli/tests/repl-lifecycle.test.ts @@ -10,19 +10,30 @@ import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; -import { Component, useTempFileCompiler } from "@executablemd/core"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import { Component, INLINE_SOURCE_PATH, useTempFileCompiler } from "@executablemd/core"; import { each, ensure, scoped, sleep, spawn, withResolvers } from "effection"; import type { Operation, Result } from "effection"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import { openReplSession } from "../src/repl/session.ts"; import type { ReplSession } from "../src/repl/session.ts"; import type { ReplExecution } from "../src/repl/journal.ts"; import type { ReplQuestion } from "../src/repl/elicitation.ts"; import type { ReplLifecycleReading, ReplOccurrence } from "../src/repl/lifecycle.ts"; -function execution(): ReplExecution { - return { id: "lifecycle", stream: new InMemoryStream([]) }; +const OWNER = "packages/cli/tests/repl-lifecycle.test.ts"; +const SUITE = "Tier L — the reading one entry leaves behind"; + +function captureEntry( + name: string, + body: (holder: ReplExecution) => Operation, +): Operation { + return captureReplEntry( + { owner: OWNER, suite: SUITE, name }, + "lifecycle", + INLINE_SOURCE_PATH, + body, + ); } function opened(result: Result): ReplSession { @@ -92,222 +103,260 @@ function watching(session: ReplSession): Operation { }; } -describe("Tier L — the reading one entry leaves behind", () => { +describe(SUITE, () => { beforeAll(() => useTempFileCompiler()); - it("L1: a repeated element is two calls, never one overwritten by the other", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - const watched = yield* watching(session); - accepted(yield* session.submit('\n\n\n')); - yield* session.join(); - yield* sleep(0); + it("L1: a repeated element is two calls, never one overwritten by the other", () => + captureEntry( + "L1: a repeated element is two calls, never one overwritten by the other", + function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + const watched = yield* watching(session); + accepted(yield* session.submit('\n\n\n')); + yield* session.join(); + yield* sleep(0); - const seen = watched.calls("Json"); - expect(seen.length).toBe(2); - expect(new Set(seen.map((one) => one.key)).size).toBe(2); - // Both reached a terminal observation of their own. - expect(seen.map((one) => one.phase).sort()).toEqual(["settled", "settled"]); - }); + const seen = watched.calls("Json"); + expect(seen.length).toBe(2); + expect(new Set(seen.map((one) => one.key)).size).toBe(2); + // Both reached a terminal observation of their own. + expect(seen.map((one) => one.phase).sort()).toEqual(["settled", "settled"]); + }, + )); - it("L1: a nested element is a child of the call that reached it", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - const watched = yield* watching(session); - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); + it("L1: a nested element is a child of the call that reached it", () => + captureEntry("L1: a nested element is a child of the call that reached it", function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + const watched = yield* watching(session); + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); - const outer = watched.calls("Each"); - const inner = watched.calls("Json"); - expect(outer.length).toBe(1); - expect(inner.length).toBe(2); - // Each iteration's element names the call it was reached through, and - // the two iterations are separate calls rather than one id twice. - for (const one of inner) { - expect(one.parent).toBe(outer[0].key); - } - expect(new Set(inner.map((one) => one.key)).size).toBe(2); - }); + const outer = watched.calls("Each"); + const inner = watched.calls("Json"); + expect(outer.length).toBe(1); + expect(inner.length).toBe(2); + // Each iteration's element names the call it was reached through, and + // the two iterations are separate calls rather than one id twice. + for (const one of inner) { + expect(one.parent).toBe(outer[0].key); + } + expect(new Set(inner.map((one) => one.key)).size).toBe(2); + })); - it("L2: an element waiting on a question says so, and stops when it is answered", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - accepted( - yield* session.submit( - 'Answer this.\n', - ), - ); - const question = yield* nextQuestion(session); + it("L2: an element waiting on a question says so, and stops when it is answered", () => + captureEntry( + "L2: an element waiting on a question says so, and stops when it is answered", + function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + accepted( + yield* session.submit( + 'Answer this.\n', + ), + ); + const question = yield* nextQuestion(session); - const waiting = session.lifecycle.occurrences.filter((one) => one.waiting.length > 0); - // The element that is waiting, what it is waiting on, and that it is - // the only one: a session-wide "busy" would name every element here. - expect( - session.lifecycle.occurrences.map((one) => `${one.name}:${one.phase}:${one.waiting.join()}`), - ).toEqual(["Elicit:active:question"]); - expect(waiting.map((one) => one.name)).toEqual(["Elicit"]); + const waiting = session.lifecycle.occurrences.filter((one) => one.waiting.length > 0); + // The element that is waiting, what it is waiting on, and that it is + // the only one: a session-wide "busy" would name every element here. + expect( + session.lifecycle.occurrences.map( + (one) => `${one.name}:${one.phase}:${one.waiting.join()}`, + ), + ).toEqual(["Elicit:active:question"]); + expect(waiting.map((one) => one.name)).toEqual(["Elicit"]); - question.submit({ note: "answered" }); - yield* session.join(); - yield* sleep(0); - // The entry closed, so its reading went with it. - expect(session.lifecycle.occurrences).toEqual([]); - expect(session.live).toBe(false); - }); + question.submit({ note: "answered" }); + yield* session.join(); + yield* sleep(0); + // The entry closed, so its reading went with it. + expect(session.lifecycle.occurrences).toEqual([]); + expect(session.live).toBe(false); + }, + )); - it("L2: an entered import has no question wait until it asks", function* () { - const arrived = withResolvers(); - const release = withResolvers(); - const session = opened( - yield* openReplSession({ - execution: execution(), - installations: [ - { - *install(): Operation { - yield* Component.around({ - *importComponent([name], next) { - if (name === "Elicit") { - arrived.resolve(); - yield* release.operation; - } - return yield* next(name); - }, - }); + it("L2: an entered import has no question wait until it asks", () => + captureEntry("L2: an entered import has no question wait until it asks", function* (holder) { + const arrived = withResolvers(); + const release = withResolvers(); + const session = opened( + yield* openReplSession({ + execution: holder, + installations: [ + { + *install(): Operation { + yield* Component.around({ + *importComponent([name], next) { + if (name === "Elicit") { + arrived.resolve(); + yield* release.operation; + } + return yield* next(name); + }, + }); + }, }, - }, - ], - }), - ); - accepted( - yield* session.submit( - 'Answer this.\n', - ), - ); - yield* arrived.operation; - expect(session.elicitation.pending).toBe(undefined); - expect( - session.lifecycle.occurrences.map((one) => `${one.name}:${one.phase}:${one.waiting.join()}`), - ).toEqual(["Elicit:enter:"]); + ], + }), + ); + accepted( + yield* session.submit( + 'Answer this.\n', + ), + ); + yield* arrived.operation; + expect(session.elicitation.pending).toBe(undefined); + expect( + session.lifecycle.occurrences.map( + (one) => `${one.name}:${one.phase}:${one.waiting.join()}`, + ), + ).toEqual(["Elicit:enter:"]); - const asking = yield* spawn(() => nextQuestion(session)); - release.resolve(); - const question = yield* asking; - const waiting = session.lifecycle.occurrences.filter((one) => one.waiting.length > 0); - expect( - session.lifecycle.occurrences.map((one) => `${one.name}:${one.phase}:${one.waiting.join()}`), - ).toEqual(["Elicit:active:question"]); - expect(waiting.map((one) => one.name)).toEqual(["Elicit"]); + const asking = yield* spawn(() => nextQuestion(session)); + release.resolve(); + const question = yield* asking; + const waiting = session.lifecycle.occurrences.filter((one) => one.waiting.length > 0); + expect( + session.lifecycle.occurrences.map( + (one) => `${one.name}:${one.phase}:${one.waiting.join()}`, + ), + ).toEqual(["Elicit:active:question"]); + expect(waiting.map((one) => one.name)).toEqual(["Elicit"]); - question.submit({ note: "answered" }); - yield* session.join(); - expect(session.lifecycle.occurrences).toEqual([]); - expect(session.live).toBe(false); - }); + question.submit({ note: "answered" }); + yield* session.join(); + expect(session.lifecycle.occurrences).toEqual([]); + expect(session.live).toBe(false); + })); - it("L2: ordinary work is not a wait", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - const watched = yield* watching(session); - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); + it("L2: ordinary work is not a wait", () => + captureEntry("L2: ordinary work is not a wait", function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + const watched = yield* watching(session); + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); - const waited = watched.readings.flatMap((reading) => - reading.occurrences.filter((one) => one.waiting.length > 0), - ); - expect(waited).toEqual([]); - }); + const waited = watched.readings.flatMap((reading) => + reading.occurrences.filter((one) => one.waiting.length > 0), + ); + expect(waited).toEqual([]); + })); - it("L3: an entry that closes takes its reading, and says it is no longer live", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); + it("L3: an entry that closes takes its reading, and says it is no longer live", () => + captureEntry( + "L3: an entry that closes takes its reading, and says it is no longer live", + function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); - expect(session.lifecycle.entry).toBe(undefined); - expect(session.lifecycle.occurrences).toEqual([]); - expect(session.live).toBe(false); - // The entry really ran: the reading going is the reading going, not the - // work never having happened. - expect(session.model.entries.length).toBe(1); - expect(session.model.entries[0]?.terminal?.status).toBe("ok"); - }); + expect(session.lifecycle.entry).toBe(undefined); + expect(session.lifecycle.occurrences).toEqual([]); + expect(session.live).toBe(false); + // The entry really ran: the reading going is the reading going, not the + // work never having happened. + expect(session.model.entries.length).toBe(1); + expect(session.model.entries[0]?.terminal?.status).toBe("ok"); + }, + )); - it("L3: everything this entry held is released before the session says it is not live", function* () { - // The frozen ordering, observed rather than read off the comment that - // states it. An installation of this entry's own records, at the moment it - // is released, what the session was still saying about itself. If the - // liveness finalizer had been registered after the things this entry - // acquires, it would run before them and this would read `false` — and a - // reader woken then would be told the entry was over while its provider, - // its middleware and its Agent attachment were still standing. - let liveWhenReleased: boolean | undefined; - let released = false; - const session = opened( - yield* openReplSession({ - execution: execution(), - installations: [ - { - *install(): Operation { - yield* ensure(() => { - released = true; - liveWhenReleased = session.live; - }); - }, - }, - ], - }), - ); - const watched = yield* watching(session); - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); - - // The installation really was released, so this is an ordering rather - // than an assertion about something that never ran. - expect(released).toBe(true); - expect(liveWhenReleased).toBe(true); - // And by now the session says what it is. - expect(session.live).toBe(false); - // The wake arrived with no input: nothing was typed, nothing activated, - // and a reader waiting for the entry to end was still told. - expect(watched.readings.length).toBeGreaterThan(0); - expect(watched.readings[watched.readings.length - 1].occurrences).toEqual([]); - expect(watched.readings[watched.readings.length - 1].entry).toBe(undefined); - }); + it("L3: everything this entry held is released before the session says it is not live", () => + captureEntry( + "L3: everything this entry held is released before the session says it is not live", + function* (holder) { + // The frozen ordering, observed rather than read off the comment that + // states it. An installation of this entry's own records, at the moment it + // is released, what the session was still saying about itself. If the + // liveness finalizer had been registered after the things this entry + // acquires, it would run before them and this would read `false` — and a + // reader woken then would be told the entry was over while its provider, + // its middleware and its Agent attachment were still standing. + let liveWhenReleased: boolean | undefined; + let released = false; + const session = opened( + yield* openReplSession({ + execution: holder, + installations: [ + { + *install(): Operation { + yield* ensure(() => { + released = true; + liveWhenReleased = session.live; + }); + }, + }, + ], + }), + ); + const watched = yield* watching(session); + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); - it("L3: a late producer update cannot revive a reading the entry took with it", function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - accepted(yield* session.submit('\n')); - yield* session.join(); - yield* sleep(0); - expect(session.lifecycle.occurrences).toEqual([]); + // The installation really was released, so this is an ordering rather + // than an assertion about something that never ran. + expect(released).toBe(true); + expect(liveWhenReleased).toBe(true); + // And by now the session says what it is. + expect(session.live).toBe(false); + // The wake arrived with no input: nothing was typed, nothing activated, + // and a reader waiting for the entry to end was still told. + expect(watched.readings.length).toBeGreaterThan(0); + expect(watched.readings[watched.readings.length - 1].occurrences).toEqual([]); + expect(watched.readings[watched.readings.length - 1].entry).toBe(undefined); + }, + )); - // Whatever is still draining from the entry that closed — a terminal - // phase published as its dispatch unwound — arrives after the generation - // it belonged to is gone, and is refused by generation rather than - // appended to nothing. - for (let turn = 0; turn < 5; turn += 1) { - yield* sleep(0); - } - expect(session.lifecycle.occurrences).toEqual([]); - expect(session.lifecycle.entry).toBe(undefined); - }); + it("L3: a late producer update cannot revive a reading the entry took with it", () => + captureEntry( + "L3: a late producer update cannot revive a reading the entry took with it", + function* (holder) { + const session = opened(yield* openReplSession({ execution: holder })); + accepted(yield* session.submit('\n')); + yield* session.join(); + yield* sleep(0); + expect(session.lifecycle.occurrences).toEqual([]); - it("L3: observing changes neither the outcome nor what the document rendered", function* () { - const source = '\n'; - const rendered: string[] = []; - for (const collect of [true, false]) { - yield* scoped(function* () { - const session = opened(yield* openReplSession({ execution: execution() })); - if (collect) { - yield* watching(session); + // Whatever is still draining from the entry that closed — a terminal + // phase published as its dispatch unwound — arrives after the generation + // it belonged to is gone, and is refused by generation rather than + // appended to nothing. + for (let turn = 0; turn < 5; turn += 1) { + yield* sleep(0); } - accepted(yield* session.submit(source)); - yield* session.join(); - rendered.push(session.model.entries[0]?.terminal?.output ?? ""); - }); - } - expect(rendered[0]).toBe(rendered[1]); - expect(rendered[0]).not.toBe(""); - }); + expect(session.lifecycle.occurrences).toEqual([]); + expect(session.lifecycle.entry).toBe(undefined); + }, + )); + + { + const name = "L3: observing changes neither the outcome nor what the document rendered"; + it(name, () => + captureEntry(name, function* (watched) { + yield* captureEntry(name, function* (unwatched) { + const source = '\n'; + const rendered: string[] = []; + for (const collect of [true, false]) { + yield* scoped(function* () { + const session = opened( + yield* openReplSession({ execution: collect ? watched : unwatched }), + ); + if (collect) { + yield* watching(session); + } + accepted(yield* session.submit(source)); + yield* session.join(); + rendered.push(session.model.entries[0]?.terminal?.output ?? ""); + }); + } + expect(rendered[0]).toBe(rendered[1]); + expect(rendered[0]).not.toBe(""); + }); + }), + ); + } }); diff --git a/packages/core/tests/contextual-cwd.test.ts b/packages/core/tests/contextual-cwd.test.ts index a62e32bea..8ef0a775f 100644 --- a/packages/core/tests/contextual-cwd.test.ts +++ b/packages/core/tests/contextual-cwd.test.ts @@ -14,12 +14,12 @@ import { useComponentModuleLoader } from "@executablemd/test-support/host"; * will rest on. */ -import { describe, it, beforeAll } from "@executablemd/test-support/bdd"; +import { describe, it, beforeAll, beforeEach } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, resource, scoped, until } from "effection"; import type { Operation } from "effection"; import { exists, readTextFile, rm, writeTextFile } from "@effectionx/fs"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { Stdio } from "@effectionx/process"; import type { Json } from "@executablemd/durable-streams"; import { execute } from "../src/execute.ts"; @@ -31,6 +31,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; /** * The boundary under test: a component that installs a directory as the @@ -104,7 +105,7 @@ function writeDocument(fixture: Fixture, source: string): Operation { * document (#441), so what these cases inspect — the directory a command * reported — is collected from the display. */ -function run(fixture: Fixture): Operation { +function run(fixture: Fixture, stream: InMemoryStream): Operation { return scoped(function* () { let displayed = ""; yield* useComponentModuleLoader(); @@ -117,7 +118,7 @@ function run(fixture: Fixture): Operation { yield* collect( yield* execute({ path: join(fixture.root, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [fixture.root], }), ); @@ -132,28 +133,32 @@ function lines(output: Json): string[] { .filter((line) => line.length > 0); } +const OWNER = "packages/core/tests/contextual-cwd.test.ts"; const PWD = "```sh exec\npwd\n```"; describe("Tier CW — Contextual working directory", () => { beforeAll(() => useTempFileCompiler()); + beforeEach(journalBeforeEach(OWNER)); // CW1: the contract a component rebinding `Env.cwd` depends on. it("CW1: an exec block inside the boundary runs in the contextual directory", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); yield* writeDocument(fixture, `\n${PWD}\n`); - expect(lines(yield* run(fixture))).toEqual([fixture.target]); + expect(lines(yield* run(fixture, stream))).toEqual([fixture.target]); }); // CW2: the boundary ends where the element does. it("CW2: an exec block after the boundary runs in the original directory", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); yield* writeDocument( fixture, `\n${PWD}\n\n\n${PWD}`, ); - const reported = lines(yield* run(fixture)); + const reported = lines(yield* run(fixture, stream)); expect(reported[0]).toBe(fixture.target); expect(reported[1]).toBe(yield* until(realpath(process.cwd()))); }); @@ -163,6 +168,7 @@ describe("Tier CW — Contextual working directory", () => { // observes teardown at the process API boundary. it("CW3: a daemon starts in the contextual directory and is stopped afterwards", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); const marker = join(fixture.root, "daemon.txt"); const timeline = yield* useDaemonTimeline(); yield* writeDocument( @@ -182,7 +188,7 @@ describe("Tier CW — Contextual working directory", () => { ].join("\n"), ); - yield* run(fixture); + yield* run(fixture, stream); const reported = (yield* readTextFile(marker)).trim(); expect(reported).toBe(fixture.target); @@ -193,6 +199,7 @@ describe("Tier CW — Contextual working directory", () => { // they always did. it("CW5: without an override both exec and daemon use the process directory", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); const marker = join(fixture.root, "plain.txt"); yield* writeDocument( fixture, @@ -208,7 +215,7 @@ describe("Tier CW — Contextual working directory", () => { ); const here = yield* until(realpath(process.cwd())); - expect(lines(yield* run(fixture))[0]).toBe(here); + expect(lines(yield* run(fixture, stream))[0]).toBe(here); expect((yield* readTextFile(marker)).trim()).toBe(here); // The fixture's own directories were never involved. expect(yield* exists(fixture.target)).toBe(true); @@ -216,8 +223,10 @@ describe("Tier CW — Contextual working directory", () => { }); describe("1113: Cwd reports the performing scope", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: reads and captures launch cwd without filesystem permission or a newline", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); yield* useComponentModuleLoader(); yield* API.Env.around( { @@ -229,15 +238,14 @@ describe("1113: Cwd reports the performing scope", () => { ); yield* Permissions.around({ files: () => false }); yield* writeDocument(fixture, '[{directory}]'); - const output = yield* collect( - yield* execute({ path: join(fixture.root, "doc.md"), stream: new InMemoryStream() }), - ); + const output = yield* collect(yield* execute({ path: join(fixture.root, "doc.md"), stream })); expect(output).toBe(`[${fixture.target}]${fixture.target}`); expect(yield* cwd()).toBe(fixture.target); }); it("1113: wrapper Content observes projection cwd and a sibling restores the launch directory", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); yield* useComponentModuleLoader(); yield* API.Env.around( { @@ -256,7 +264,7 @@ describe("1113: Cwd reports the performing scope", () => { yield* execute({ path: join(fixture.root, "doc.md"), includes: [fixture.root], - stream: new InMemoryStream(), + stream, }), ), ).toBe(`${fixture.target}|${fixture.root}`); @@ -265,8 +273,10 @@ describe("1113: Cwd reports the performing scope", () => { }); describe("1113: source location does not set execution cwd", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: Cwd and the supported shell report P when the source is elsewhere", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.root, "doc.md")); yield* useTempFileCompiler(); yield* useComponentModuleLoader(); yield* API.Env.around( @@ -287,9 +297,7 @@ describe("1113: source location does not set execution cwd", () => { "", ].join("\n"), ); - const output = yield* collect( - yield* execute({ path: join(fixture.root, "doc.md"), stream: new InMemoryStream() }), - ); + const output = yield* collect(yield* execute({ path: join(fixture.root, "doc.md"), stream })); expect(JSON.parse(String(output))).toEqual({ directory: fixture.target, stdout: fixture.target + "\n", diff --git a/packages/core/tests/document-validation.test.ts b/packages/core/tests/document-validation.test.ts index 28e264b6c..2968f1057 100644 --- a/packages/core/tests/document-validation.test.ts +++ b/packages/core/tests/document-validation.test.ts @@ -15,11 +15,16 @@ * run rather than pass unnoticed. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { scoped } from "effection"; import type { Operation } from "effection"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { API } from "@executablemd/runtime"; import type { DirectoryEntry, LinkStatResult, StatResult } from "@executablemd/runtime"; @@ -1281,7 +1286,13 @@ describe("Tier DV: one parser, one rule catalog", () => { * its error into the output; a root that fails outright reports it instead, so * both are folded into one string. */ -function expansionPrints(source: string, scenario: Scenario = {}): Operation { +const OWNER = "packages/core/tests/document-validation.test.ts"; + +function expansionPrints( + stream: InMemoryStream, + source: string, + scenario: Scenario = {}, +): Operation { return scoped(function* () { const seen = probe(); yield* useEnvironment(scenario.tree ?? {}, seen); @@ -1290,7 +1301,7 @@ function expansionPrints(source: string, scenario: Scenario = {}): Operation { - it("DV14: an ordinary component's `as` binding name is decided once", function* () { - // A registration reaches expansion through the function-component path... - const registered = yield* bothCallersAgree('\n', "capture-invalid"); - expect(registered).toBe( - 'Prop "as" on must be a valid JavaScript identifier. Got: "1bad"', - ); - - // ...and a Markdown component through the other one. Both ask this module. - const markdown = yield* bothCallersAgree( - '\n', - "capture-invalid", - { - tree: { "components/Widget.md": WIDGET }, - }, - ); - expect(markdown).toContain('Prop "as" on '); - }); + beforeEach(journalBeforeEach(OWNER)); + { + const name = "DV14: an ordinary component's `as` binding name is decided once"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + // A registration reaches expansion through the function-component path... + const registered = yield* bothCallersAgree( + stream, + '\n', + "capture-invalid", + ); + expect(registered).toBe( + 'Prop "as" on must be a valid JavaScript identifier. Got: "1bad"', + ); + + // ...and a Markdown component through the other one. Both ask this module. + const markdown = yield* bothCallersAgree( + stream2, + '\n', + "capture-invalid", + { + tree: { "components/Widget.md": WIDGET }, + }, + ); + expect(markdown).toContain('Prop "as" on '); + }); + }); + } it("DV14: `as` written as an expression is refused by one rule", function* () { - const message = yield* bothCallersAgree("\n", "capture-invalid"); + const stream = yield* useJournalStream(""); + const message = yield* bothCallersAgree(stream, "\n", "capture-invalid"); expect(message).toBe('Prop "as" on must be a string literal.'); }); it("DV14: a value component invoked without `as` is refused by one rule", function* () { + const stream = yield* useJournalStream(""); const message = yield* bothCallersAgree( + stream, '\n', "return-usage-invalid", ); @@ -1355,47 +1382,69 @@ describe("Tier DV: one decision, both callers", () => { ); }); - it("DV14: props and body shape are decided once", function* () { - const prop = yield* bothCallersAgree( - "body\n", - "structural-usage-invalid", - ); - expect(prop).toBe(' does not accept a "wrong" prop (allowed: delegate).'); - - const delegate = yield* bothCallersAgree( - 'body\n', - "structural-usage-invalid", - ); - expect(delegate).toBe( - ' delegate must be a boolean — write delegate={true}, not delegate="yes".', - ); - - const body = yield* bothCallersAgree( - '\n', - "structural-usage-invalid", - ); - expect(body).toContain(" has no body to answer for."); - }); - - it("DV14: props, template form and required value are decided once", function* () { - const prop = yield* bothCallersAgree( - "\n\nbody\n\n", - "structural-usage-invalid", - ); - expect(prop).toBe(' does not accept a "bogus" prop (allowed: template, value).'); - - const template = yield* bothCallersAgree( - "\n\nbody\n\n", - "structural-usage-invalid", - ); - expect(template).toContain(" template must be a literal string prop"); + { + const name = "DV14: props and body shape are decided once"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream3) { + const prop = yield* bothCallersAgree( + stream, + "body\n", + "structural-usage-invalid", + ); + expect(prop).toBe(' does not accept a "wrong" prop (allowed: delegate).'); + + const delegate = yield* bothCallersAgree( + stream2, + 'body\n', + "structural-usage-invalid", + ); + expect(delegate).toBe( + ' delegate must be a boolean — write delegate={true}, not delegate="yes".', + ); + + const body = yield* bothCallersAgree( + stream3, + '\n', + "structural-usage-invalid", + ); + expect(body).toContain(" has no body to answer for."); + }); + }); + }); + } - const value = yield* bothCallersAgree( - '\n\nbody\n\n', - "structural-usage-invalid", - ); - expect(value).toBe(' requires a "value" prop.'); - }); + { + const name = "DV14: props, template form and required value are decided once"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream3) { + const prop = yield* bothCallersAgree( + stream, + "\n\nbody\n\n", + "structural-usage-invalid", + ); + expect(prop).toBe(' does not accept a "bogus" prop (allowed: template, value).'); + + const template = yield* bothCallersAgree( + stream2, + "\n\nbody\n\n", + "structural-usage-invalid", + ); + expect(template).toContain(" template must be a literal string prop"); + + const value = yield* bothCallersAgree( + stream3, + '\n\nbody\n\n', + "structural-usage-invalid", + ); + expect(value).toBe(' requires a "value" prop.'); + }); + }); + }); + } }); describe("Tier DV: the no-execution boundary", () => { diff --git a/packages/core/tests/eval-bindings.test.ts b/packages/core/tests/eval-bindings.test.ts index 0c78999b6..bf1946b93 100644 --- a/packages/core/tests/eval-bindings.test.ts +++ b/packages/core/tests/eval-bindings.test.ts @@ -17,7 +17,11 @@ import { asText, completion, failureMessage } from "./helpers.ts"; import type { Json } from "../src/types.ts"; import type { DurableEvent } from "@executablemd/durable-streams"; import type { Operation } from "effection"; -import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; const OWNER = "packages/core/tests/eval-bindings.test.ts"; @@ -189,11 +193,11 @@ function malformed(value: unknown): ExecutionInitialization { /** What one run of a document under `initialBindings` did. */ function* inheriting( + stream: InMemoryStream, source: string, initialBindings: Readonly>, installations: readonly ExecutionInstallation[] = [], ): Operation<{ output: string; events: DurableEvent[] }> { - const stream = new InMemoryStream(); const output = asText( yield* collect( yield* executeInstalled({ ...inlineSource(source), stream }, [...installations], { @@ -205,9 +209,11 @@ function* inheriting( } describe("Tier T5 — initial root bindings a trusted host supplies", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("EB1: copies a nested record before installations run, and document code reads it", function* () { + const stream = yield* useJournalStream(""); // The caller's own graph, which the second installation rewrites while the // run is in flight. const held = { plan: { title: "Ship the REPL", steps: 2 }, flags: ["draft", "ready"] }; @@ -219,6 +225,7 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { }; const { output } = yield* inheriting( + stream, [ "```js eval", "const read = `${plan.title}/${plan.steps}/${flags[1]}`;", @@ -254,6 +261,7 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { }); it("EB1: the execution may mutate its own copy, and the caller's graph never moves", function* () { + const stream = yield* useJournalStream(""); // A durable eval value is ordinary mutable data: an entry that inherits a // list and appends to it is doing what any block does to any binding. What // isolation has to mean is that the *caller's* graph is unreachable from @@ -261,6 +269,7 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { const held = { items: ["first"], counts: { runs: 1 } }; const { output } = yield* inheriting( + stream, [ "```js eval", 'items.push("second");', @@ -340,7 +349,9 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { }); it("EB1: an authored export replaces an initial value through the ordinary rules", function* () { + const stream = yield* useJournalStream(""); const { output } = yield* inheriting( + stream, [ "```js eval", "const inherited = 'authored';", @@ -393,6 +404,7 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { }); it("EB1: a retained `__proto__` binding is installed as an ordinary name", function* () { + const stream = yield* useJournalStream(""); // Its own enumerable member, which is what `JSON.parse` produces and // therefore what a journal read back from a file can hold. Nothing here sets // a prototype: an object literal would have, which is why this is defined. @@ -407,6 +419,7 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { expect(Object.getPrototypeOf(record)).toBe(Object.prototype); const { output } = yield* inheriting( + stream, ["```js eval", "const copied = `${__proto__}`;", "```", "", "Read: {copied}", ""].join("\n"), record, ); @@ -416,17 +429,22 @@ describe("Tier T5 — initial root bindings a trusted host supplies", () => { expect(output).toContain("Read: retained"); }); - it("EB1: ordinary execute() inherits nothing, so the same document fails", function* () { - const stream = new InMemoryStream(); - const source = "```js eval\nconst read = inherited;\n```\n"; + { + const name = "EB1: ordinary execute() inherits nothing, so the same document fails"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + const source = "```js eval\nconst read = inherited;\n```\n"; - // The same bytes succeed through the host entrypoint. - const { output } = yield* inheriting(source, { inherited: "retained" }); - expect(output).not.toContain("ERROR"); + // The same bytes succeed through the host entrypoint. + const { output } = yield* inheriting(stream2, source, { inherited: "retained" }); + expect(output).not.toContain("ERROR"); - const result = yield* completion({ ...inlineSource(source), stream }); + const result = yield* completion({ ...inlineSource(source), stream }); - expect(result.ok).toBe(false); - expect(failureMessage(result)).toContain("inherited"); - }); + expect(result.ok).toBe(false); + expect(failureMessage(result)).toContain("inherited"); + }); + }); + } }); diff --git a/packages/core/tests/execution-init.test.ts b/packages/core/tests/execution-init.test.ts index 20d4df1fb..dd1b40505 100644 --- a/packages/core/tests/execution-init.test.ts +++ b/packages/core/tests/execution-init.test.ts @@ -1,8 +1,13 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { createContext, ensure, scoped, spawn, suspend, withResolvers } from "effection"; import type { Operation } from "effection"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { Execution } from "../api.ts"; import { parseFilesFatal } from "@executablemd/runtime"; import { fatalCause } from "../src/errors.ts"; @@ -13,14 +18,12 @@ import { useSelection } from "./support/generated-selection.ts"; import { Documentation } from "../src/documentation-api.ts"; import { recordedFiles, useRecordedFiles } from "./support/fragment-files.ts"; +const OWNER = "packages/core/tests/execution-init.test.ts"; + const State = createContext<{ id: number } | undefined>("executablemd.test.init.state", undefined); -function* run(text = "hello\n"): Operation { - return String( - yield* collect( - yield* execute({ ...inlineSource(text), stream: new InMemoryStream(), includes: [] }), - ), - ); +function* run(stream: InMemoryStream, text = "hello\n"): Operation { + return String(yield* collect(yield* execute({ ...inlineSource(text), stream, includes: [] }))); } function* failure(operation: Operation): Operation { @@ -33,33 +36,42 @@ function* failure(operation: Operation): Operation { } describe("Tier EI — execution-owned initialization", () => { - it("EI1: the public descriptors agree, default init is no-op and each fresh owner dispatches once", function* () { - expect(Execution).toBe(RootExecution); - yield* Execution.operations.init(); - expect(yield* State.get()).toBe(undefined); - let calls = 0; - yield* Execution.around({ - *init(_args, next) { - calls += 1; - yield* State.set({ id: calls }); - yield* next(); - }, - }); - const execution = yield* execute({ - ...inlineSource("hello\n"), - stream: new InMemoryStream(), - includes: [], + beforeEach(journalBeforeEach(OWNER)); + { + const name = + "EI1: the public descriptors agree, default init is no-op and each fresh owner dispatches once"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + expect(Execution).toBe(RootExecution); + yield* Execution.operations.init(); + expect(yield* State.get()).toBe(undefined); + let calls = 0; + yield* Execution.around({ + *init(_args, next) { + calls += 1; + yield* State.set({ id: calls }); + yield* next(); + }, + }); + const execution = yield* execute({ + ...inlineSource("hello\n"), + stream, + includes: [], + }); + expect(String(yield* collect(execution))).toContain("hello"); + const completed = yield* execution; + expect(yield* execution).toBe(completed); + expect(calls).toBe(1); + yield* run(stream2); + expect(calls).toBe(2); + expect(yield* State.get()).toBe(undefined); + }); }); - expect(String(yield* collect(execution))).toContain("hello"); - const completed = yield* execution; - expect(yield* execution).toBe(completed); - expect(calls).toBe(1); - yield* run(); - expect(calls).toBe(2); - expect(yield* State.get()).toBe(undefined); - }); + } it("EI2: initialization precedes assembly, captured documentation and execution/document policy", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; yield* Execution.around({ *init(_args, next) { @@ -86,7 +98,7 @@ describe("Tier EI — execution-owned initialization", () => { }, }); const execution = yield* executeInstalled( - { ...inlineSource("\n"), includes: [], stream: new InMemoryStream() }, + { ...inlineSource("\n"), includes: [], stream }, [ { *install() { @@ -111,6 +123,7 @@ describe("Tier EI — execution-owned initialization", () => { * protected at. That half is `generated-selection` U5-2's. */ it("EI3: init cannot rewrite captured admissions or declarations", function* () { + const stream = yield* useJournalStream(""); const admitted: string[] = []; const admissions: JournalAdmission[] = [ function* () { @@ -119,7 +132,12 @@ describe("Tier EI — execution-owned initialization", () => { ]; const source = "CAPTURED DECLARATION\n"; const declarations = [ - Markdown({ name: "Kept", origin: "test://init/kept", source, digest: sourceDigest(source) }), + Markdown({ + name: "Kept", + origin: "test://init/kept", + source, + digest: sourceDigest(source), + }), ]; const files = recordedFiles({ "note.md": "CAPTURED PROFILE" }); yield* Execution.around({ @@ -134,10 +152,9 @@ describe("Tier EI — execution-owned initialization", () => { }, }); const text = "\n'} />\n"; - const execution = yield* executeInstalled( - { ...inlineSource(text), includes: [], stream: new InMemoryStream() }, - [{ admissions, declarations }], - ); + const execution = yield* executeInstalled({ ...inlineSource(text), includes: [], stream }, [ + { admissions, declarations }, + ]); const output = String(yield* collect(execution)); expect(admitted).toEqual(["original"]); expect(output).toContain("CAPTURED DECLARATION"); @@ -146,11 +163,11 @@ describe("Tier EI — execution-owned initialization", () => { }); it("EI4: initializer failure settles only after acquired teardown and reaches no policy or root", function* () { + const stream = yield* useJournalStream(""); const entered = withResolvers(); const release = withResolvers(); const cleanup = withResolvers(); const phases: string[] = []; - const stream = new InMemoryStream(); yield* Execution.around({ *init() { yield* ensure(function* () { @@ -184,11 +201,11 @@ describe("Tier EI — execution-owned initialization", () => { }); it("EI5: deterministic cancellation during init joins cleanup before halt returns", function* () { + const stream = yield* useJournalStream(""); const entered = withResolvers(); const cleaning = withResolvers(); const release = withResolvers(); const phases: string[] = []; - const stream = new InMemoryStream(); yield* Execution.around({ *init() { yield* ensure(function* () { @@ -221,58 +238,77 @@ describe("Tier EI — execution-owned initialization", () => { expect(phases).toEqual(["released"]); }); - it("EI6: concurrent owners get independent state inherited by ordinary descendants", function* () { - let counter = 0; - const both = withResolvers(); - const release = withResolvers(); - const seen: number[] = []; - yield* Execution.around({ - *init(_args, next) { - yield* State.set({ id: ++counter }); - yield* next(); - }, - *execute([request], next) { - seen.push((yield* State.expect())?.id ?? 0); - if (seen.length === 2) { - both.resolve(); - } - yield* release.operation; - const parent = yield* State.get(); - expect(yield* scoped(() => State.get())).toBe(parent); - yield* next(request); - }, + { + const name = "EI6: concurrent owners get independent state inherited by ordinary descendants"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + let counter = 0; + const both = withResolvers(); + const release = withResolvers(); + const seen: number[] = []; + yield* Execution.around({ + *init(_args, next) { + yield* State.set({ id: ++counter }); + yield* next(); + }, + *execute([request], next) { + seen.push((yield* State.expect())?.id ?? 0); + if (seen.length === 2) { + both.resolve(); + } + yield* release.operation; + const parent = yield* State.get(); + expect(yield* scoped(() => State.get())).toBe(parent); + yield* next(request); + }, + }); + const first = yield* spawn(() => run(stream)); + const second = yield* spawn(() => run(stream2)); + yield* both.operation; + expect([...seen].sort((a, b) => a - b)).toEqual([1, 2]); + expect(yield* State.get()).toBe(undefined); + release.resolve(); + yield* first; + yield* second; + expect(yield* scoped(() => State.get())).toBe(undefined); + }); }); - const first = yield* spawn(() => run()); - const second = yield* spawn(() => run()); - yield* both.operation; - expect([...seen].sort((a, b) => a - b)).toEqual([1, 2]); - expect(yield* State.get()).toBe(undefined); - release.resolve(); - yield* first; - yield* second; - expect(yield* scoped(() => State.get())).toBe(undefined); - }); + } - it("EI7: a no-op initializer invents no Files provider; explicit initialization supplies one", function* () { - expect(parseFilesFatal(fatalCause(yield* failure(run(''))))).toEqual({ - type: "executablemd.runtime.files-fatal/v1", - kind: "provider-unavailable", - }); - const files = recordedFiles({ "note.md": "INSTALLED BY INIT" }); - const output = yield* scoped(function* () { - yield* Execution.around({ - *init(_args, next) { - yield* useRecordedFiles(files); - yield* next(); - }, + { + const name = + "EI7: a no-op initializer invents no Files provider; explicit initialization supplies one"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, "", function* (stream3) { + expect( + parseFilesFatal(fatalCause(yield* failure(run(stream, '')))), + ).toEqual({ + type: "executablemd.runtime.files-fatal/v1", + kind: "provider-unavailable", + }); + const files = recordedFiles({ "note.md": "INSTALLED BY INIT" }); + const output = yield* scoped(function* () { + yield* Execution.around({ + *init(_args, next) { + yield* useRecordedFiles(files); + yield* next(); + }, + }); + return yield* run(stream2, ''); + }); + expect(output).toContain("INSTALLED BY INIT"); + expect(files.performed).toEqual(["read note.md"]); + expect( + parseFilesFatal(fatalCause(yield* failure(run(stream3, '')))), + ).toEqual({ + type: "executablemd.runtime.files-fatal/v1", + kind: "provider-unavailable", + }); + }); }); - return yield* run(''); }); - expect(output).toContain("INSTALLED BY INIT"); - expect(files.performed).toEqual(["read note.md"]); - expect(parseFilesFatal(fatalCause(yield* failure(run(''))))).toEqual({ - type: "executablemd.runtime.files-fatal/v1", - kind: "provider-unavailable", - }); - }); + } }); diff --git a/packages/core/tests/fail-component.test.ts b/packages/core/tests/fail-component.test.ts index 941e960e9..6bfa6a931 100644 --- a/packages/core/tests/fail-component.test.ts +++ b/packages/core/tests/fail-component.test.ts @@ -15,9 +15,8 @@ * sentinel message being nowhere in the failure. */ -import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; - import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, resource, scoped, until } from "effection"; import type { Operation, Result } from "effection"; @@ -228,6 +227,7 @@ describe("Tier FAIL — stopping a document deliberately", () => { it("FAIL3: does nothing beneath an unselected , and the root returns", function* () { const dir = yield* useDir(); + const stream = yield* useJournalStream(join(dir, "doc.md")); const result = yield* run( dir, [ @@ -239,6 +239,7 @@ describe("Tier FAIL — stopping a document deliberately", () => { '', "", ].join("\n"), + { stream }, ); expect(result.outcome).toEqual({ ok: true, value: "approved" }); @@ -375,7 +376,8 @@ describe("Tier FAIL — invocations that never raise the authored message", () = for (const [title, source, expected] of refusals) { it(title, function* () { const dir = yield* useDir(); - const result = yield* run(dir, source); + const stream = yield* useJournalStream(join(dir, "doc.md")); + const result = yield* run(dir, source, { stream }); expect(failureOf(result).message).toContain(expected); // The refusal happened first: nothing anywhere carries the message a @@ -444,7 +446,9 @@ describe("Tier FAIL — position, durability and precedence", () => { it("FAIL10: a repository Fail.md is chosen ahead of core's", function* () { const dir = yield* useDir(); + const stream = yield* useJournalStream(join(dir, "doc.md")); const result = yield* run(dir, `\n`, { + stream, files: { "Fail.md": [ "---", diff --git a/packages/core/tests/failure-printing.test.ts b/packages/core/tests/failure-printing.test.ts index d7482084e..87b08daa5 100644 --- a/packages/core/tests/failure-printing.test.ts +++ b/packages/core/tests/failure-printing.test.ts @@ -10,12 +10,12 @@ * survived, rather than searching a rendered message. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Err, Ok, resource, scoped, spawn, suspend, until, withResolvers } from "effection"; import type { Operation, Result } from "effection"; import { rm, writeTextFile } from "@effectionx/fs"; -import { InMemoryStream, StaleInputError } from "@executablemd/durable-streams"; +import { StaleInputError } from "@executablemd/durable-streams"; import { mkdtemp, realpath } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -38,6 +38,7 @@ import type { Json, Segment, } from "../src/types.ts"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; const NO_PROPS = { type: "object", properties: {}, additionalProperties: false }; @@ -211,7 +212,10 @@ function reachableFrom(error: unknown, seen = new Set()): unknown[] { return [error, ...nestedCauses(error).flatMap((cause) => reachableFrom(cause, seen))]; } +const OWNER = "packages/core/tests/failure-printing.test.ts"; + describe("Tier CF — failing is the default", () => { + beforeEach(journalBeforeEach(OWNER)); it("CF1: an unmarked component's failure fails the operation, and nothing follows", function* () { const boom = new Error("boom"); const result = yield* run("\n\nAFTER\n", { Boom: throwing("Boom", boom) }); @@ -223,9 +227,11 @@ describe("Tier CF — failing is the default", () => { }); it("CF1b: a registered default fails by default, with nothing after it", function* () { - const boom = new Error("registered boom"); const dir = yield* useFixture(); - yield* writeTextFile(join(dir, "doc.md"), "\n\nAFTER\n"); + const path = join(dir, "doc.md"); + const stream = yield* useJournalStream(path); + const boom = new Error("registered boom"); + yield* writeTextFile(path, "\n\nAFTER\n"); const registration: ComponentRegistration = { name: "Widget", @@ -247,8 +253,8 @@ describe("Tier CF — failing is the default", () => { }); yield* registerComponents([registration]); const execution = yield* execute({ - path: join(dir, "doc.md"), - stream: new InMemoryStream(), + path, + stream, includes: [dir], }); const subscription = yield* execution.output; diff --git a/packages/core/tests/journal-source-position.test.ts b/packages/core/tests/journal-source-position.test.ts index 5f4efeb7a..4ea1df85f 100644 --- a/packages/core/tests/journal-source-position.test.ts +++ b/packages/core/tests/journal-source-position.test.ts @@ -1,3 +1,4 @@ +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; /** * Tier JSP — where an authored durable operation says it was written. * @@ -16,7 +17,7 @@ import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, resource, until } from "effection"; import type { Operation } from "effection"; @@ -95,69 +96,78 @@ function sourceOf(events: DurableEvent[], type: string, name?: string): unknown return found.description[SOURCE_POSITION_FIELD]; } +const OWNER = "packages/core/tests/journal-source-position.test.ts"; + describe("Tier JSP — authored source in the journal", () => { // The document holds an eval block, and a root that cannot compile one now // settles that failure rather than printing it. beforeAll(() => useTempFileCompiler()); - - it("JSP1: component imports, commands and eval blocks retain where they were written", function* () { - const path = yield* useDocument(); - const stream = new InMemoryStream(); - yield* useMark(); - yield* collect(yield* execute({ path, stream })); - - const events = yield* stream.readAll(); - for (const event of events) { - if ( - event.type === "yield" && - ["eval", "import_component"].includes(event.description.type) && - event.description.name !== "__root__" - ) { - expect(event.description["executablemd.source-owner"]).toEqual({ - coroutineId: "root", - index: 0, - }); + beforeEach(journalBeforeEach(OWNER)); + + { + const name = "JSP1: component imports, commands and eval blocks retain where they were written"; + it(name, function* () { + const path = yield* useDocument(); + const stream = yield* useJournalStream(path); + yield* useMark(); + yield* collect(yield* execute({ path, stream })); + + const events = yield* stream.readAll(); + for (const event of events) { + if ( + event.type === "yield" && + ["eval", "import_component"].includes(event.description.type) && + event.description.name !== "__root__" + ) { + expect(event.description["executablemd.source-owner"]).toEqual({ + coroutineId: "root", + index: 0, + }); + } } - } - expect(sourceOf(events, "import_component", "Mark")).toEqual({ - path, - offset: DOCUMENT.indexOf(""), - line: lineOf(""), - column: 1, - }); - expect(sourceOf(events, "exec")).toEqual({ - path, - offset: DOCUMENT.indexOf("```bash exec"), - line: lineOf("```bash exec"), - column: 1, + expect(sourceOf(events, "import_component", "Mark")).toEqual({ + path, + offset: DOCUMENT.indexOf(""), + line: lineOf(""), + column: 1, + }); + expect(sourceOf(events, "exec")).toEqual({ + path, + offset: DOCUMENT.indexOf("```bash exec"), + line: lineOf("```bash exec"), + column: 1, + }); + expect(sourceOf(events, "eval")).toEqual({ + path, + offset: DOCUMENT.indexOf("```js eval"), + line: lineOf("```js eval"), + column: 1, + }); }); - expect(sourceOf(events, "eval")).toEqual({ - path, - offset: DOCUMENT.indexOf("```js eval"), - line: lineOf("```js eval"), - column: 1, - }); - }); + } - it("JSP2: the root import and the root Close carry no authored source", function* () { - const path = yield* useDocument(); - const stream = new InMemoryStream(); - yield* useMark(); - yield* collect(yield* execute({ path, stream })); + { + const name = "JSP2: the root import and the root Close carry no authored source"; + it(name, function* () { + const path = yield* useDocument(); + const stream = yield* useJournalStream(path); + yield* useMark(); + yield* collect(yield* execute({ path, stream })); - const events = yield* stream.readAll(); + const events = yield* stream.readAll(); - // The root is the run's own entry rather than an element somebody wrote. - expect(sourceOf(events, "import_component", "__root__")).toBeUndefined(); + // The root is the run's own entry rather than an element somebody wrote. + expect(sourceOf(events, "import_component", "__root__")).toBeUndefined(); - const close = events.find((event) => event.type === "close" && event.coroutineId === "root"); - expect(close).toBeDefined(); - expect(close && "description" in close).toBe(false); - }); + const close = events.find((event) => event.type === "close" && event.coroutineId === "root"); + expect(close).toBeDefined(); + expect(close && "description" in close).toBe(false); + }); + } it("JSP3: an inline document's position names the inline document", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); yield* useMark(); const root = inlineSource("\n"); yield* collect(yield* execute({ ...root, stream })); diff --git a/packages/core/tests/query-component.test.ts b/packages/core/tests/query-component.test.ts index 0a9dfde95..6334f86c0 100644 --- a/packages/core/tests/query-component.test.ts +++ b/packages/core/tests/query-component.test.ts @@ -12,7 +12,7 @@ * the component a document resolves. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, resource, scoped, until } from "effection"; import type { Operation } from "effection"; @@ -22,7 +22,6 @@ import { join } from "node:path"; import process from "node:process"; import { exists, readTextFile, rm, writeTextFile } from "@effectionx/fs"; import { API, env, Files, useHostFiles } from "@executablemd/runtime"; -import { InMemoryStream } from "@executablemd/durable-streams"; import { Component } from "../src/component-api.ts"; import { collect } from "../src/collect.ts"; import { execute } from "../src/execute.ts"; @@ -37,6 +36,7 @@ import type { FunctionComponentDefinition, Json, } from "../src/types.ts"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; /** Core's own registered definition, so what runs is what a document resolves. */ function core(name: string): FunctionComponentDefinition { @@ -117,6 +117,8 @@ function useFixture(): Operation { }); } +const OWNER = "packages/core/tests/query-component.test.ts"; + describe("Tier QRY — the two ordinary modes", () => { const DATA: Record = { name: "widget", @@ -413,6 +415,7 @@ describe("Tier QRY — what the engine can reach", () => { }); describe("Tier QRY — two producers, each run once, over the page they supplied", () => { + beforeEach(journalBeforeEach(OWNER)); const FIXTURE = JSON.stringify( { records: [ @@ -447,9 +450,11 @@ describe("Tier QRY — two producers, each run once, over the page they supplied it("Q4: a file read once and a glob listed once answer several queries", function* () { const dir = yield* useFixture(); + const path = join(dir, "doc.md"); + const stream = yield* useJournalStream(path); yield* writeTextFile(join(dir, "input.json"), FIXTURE); yield* writeTextFile( - join(dir, "doc.md"), + path, [ '', ``, @@ -464,7 +469,6 @@ describe("Tier QRY — two producers, each run once, over the page they supplied ); const calls: Calls = { reads: [], globs: [] }; - const stream = new InMemoryStream(); const output = yield* scoped(function* () { // The document's own working directory, installed explicitly the way an // entrypoint does: `` and `` resolve against `Env.cwd` @@ -480,7 +484,7 @@ describe("Tier QRY — two producers, each run once, over the page they supplied ); yield* useHostFiles(); yield* watched(calls); - return yield* collect(yield* execute({ path: join(dir, "doc.md"), stream, includes: [dir] })); + return yield* collect(yield* execute({ path, stream, includes: [dir] })); }); const rendered = String(output); diff --git a/packages/core/tests/slice-component.test.ts b/packages/core/tests/slice-component.test.ts index bbf049594..6aac81ab3 100644 --- a/packages/core/tests/slice-component.test.ts +++ b/packages/core/tests/slice-component.test.ts @@ -1,3 +1,8 @@ +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; /** * Tier SL1 — `` (spec §6.21). * @@ -26,7 +31,7 @@ * anything. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, spawn, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -34,7 +39,7 @@ import { forEach } from "@effectionx/stream-helpers"; import { readTextFile } from "@effectionx/fs"; import { fileURLToPath } from "node:url"; import { useStubFs } from "@executablemd/runtime/test"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { execute } from "../src/execute.ts"; import { registerComponents } from "../src/components/registration.ts"; import type { ComponentRegistration } from "../src/components/registration.ts"; @@ -162,7 +167,10 @@ function controlled(): Harness { } /** Run `source` as the document, with `values` reachable through ``. */ +const OWNER = "packages/core/tests/slice-component.test.ts"; + function run( + stream: InMemoryStream, source: string, values: Record = {}, harness?: Harness, @@ -183,7 +191,7 @@ function run( ), ); - const execution = yield* execute({ path: "doc.md", stream: new InMemoryStream() }); + const execution = yield* execute({ path: "doc.md", stream }); const output = yield* forEach(function* () {}, execution.output); const outcome = yield* execution; return { @@ -206,13 +214,14 @@ function excerpt(start: number, end: number, total: number, payload: string): st } /** One `` over a ``, with nothing else in the document. */ -function* over(value: string, attributes = ""): Operation { - return yield* run(``, { v: value }); +function* over(stream: InMemoryStream, value: string, attributes = ""): Operation { + return yield* run(stream, ``, { v: value }); } /** The exact string `as` bound, at the capture boundary. */ -function* captured(value: string, attributes = ""): Operation { +function* captured(stream: InMemoryStream, value: string, attributes = ""): Operation { const result = yield* run( + stream, ``, { v: value }, ); @@ -235,106 +244,164 @@ const SEVEN = "A\u{1F600}BCDEF"; const BOUNDARY = `${"a".repeat(4095)}\u{1F600}z`; describe("Tier SL1 — S1: windows, defaults, clamping and the exact note", () => { - it("S1: the omitted window is [0, 4096) and counts code points, not UTF-16 units", function* () { - expect(Array.from(BOUNDARY).length).toBe(4097); - expect(BOUNDARY.length).toBe(4098); - - const result = yield* over(BOUNDARY); - const expected = excerpt(0, 4096, 4097, `${"a".repeat(4095)}\u{1F600}`); - - expect(result.failure).toBe(""); - expect(result.output).toBe(expected); - expect(yield* captured(BOUNDARY)).toBe(expected); - // Stated separately: the window holds the emoji whole, so no half of a - // surrogate pair reached the document. - expect(Array.from(result.output.slice(note(0, 4096, 4097).length + 1)).length).toBe(4096); - expect(result.output.endsWith("\u{1F600}")).toBe(true); - }); - - it("S1: a middle window, an end window, and a start before the beginning", function* () { - expect(yield* over(SEVEN, " offset={1} length={3}")).toMatchObject({ - failure: "", - output: excerpt(1, 4, 7, "\u{1F600}BC"), + beforeEach(journalBeforeEach(OWNER)); + { + const name = "S1: the omitted window is [0, 4096) and counts code points, not UTF-16 units"; + it(name, function* () { + const stream = yield* useJournalStream("doc.md"); + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream2) { + expect(Array.from(BOUNDARY).length).toBe(4097); + expect(BOUNDARY.length).toBe(4098); + + const result = yield* over(stream, BOUNDARY); + const expected = excerpt(0, 4096, 4097, `${"a".repeat(4095)}\u{1F600}`); + + expect(result.failure).toBe(""); + expect(result.output).toBe(expected); + expect(yield* captured(stream2, BOUNDARY)).toBe(expected); + // Stated separately: the window holds the emoji whole, so no half of a + // surrogate pair reached the document. + expect(Array.from(result.output.slice(note(0, 4096, 4097).length + 1)).length).toBe(4096); + expect(result.output.endsWith("\u{1F600}")).toBe(true); + }); }); - expect(yield* captured(SEVEN, " offset={1} length={3}")).toBe(excerpt(1, 4, 7, "\u{1F600}BC")); - - expect((yield* over(SEVEN, " offset={-3} length={4096}")).output).toBe(excerpt(4, 7, 7, "DEF")); - - // Clamped to zero rather than wrapping or refusing, and the whole input is - // then covered — so the body comes back with no note at all. - expect((yield* over(SEVEN, " offset={-99} length={4096}")).output).toBe(SEVEN); - expect((yield* over(SEVEN, " offset={-99} length={2}")).output).toBe( - excerpt(0, 2, 7, "A\u{1F600}"), - ); - }); - - it("S1: a start at or beyond the end is an empty window that still says so", function* () { - for (const offset of [7, 8, 400]) { - const result = yield* over(SEVEN, ` offset={${offset}} length={4}`); - - expect(result.failure).toBe(""); - expect(result.output).toBe(`${note(7, 7, 7)}\n`); - } - }); + } - it("S1: empty content is the empty string, in both authored spellings", function* () { - expect(yield* run("")).toMatchObject({ failure: "", output: "" }); - expect(yield* run("")).toMatchObject({ failure: "", output: "" }); - expect(yield* captured("", " length={4}")).toBe(""); - }); + { + const name = "S1: a middle window, an end window, and a start before the beginning"; + it(name, function* () { + const stream = yield* useJournalStream("doc.md"); + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream3) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream4) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream5) { + expect(yield* over(stream, SEVEN, " offset={1} length={3}")).toMatchObject({ + failure: "", + output: excerpt(1, 4, 7, "\u{1F600}BC"), + }); + expect(yield* captured(stream2, SEVEN, " offset={1} length={3}")).toBe( + excerpt(1, 4, 7, "\u{1F600}BC"), + ); + + expect((yield* over(stream3, SEVEN, " offset={-3} length={4096}")).output).toBe( + excerpt(4, 7, 7, "DEF"), + ); + + // Clamped to zero rather than wrapping or refusing, and the whole input is + // then covered — so the body comes back with no note at all. + expect((yield* over(stream4, SEVEN, " offset={-99} length={4096}")).output).toBe( + SEVEN, + ); + expect((yield* over(stream5, SEVEN, " offset={-99} length={2}")).output).toBe( + excerpt(0, 2, 7, "A\u{1F600}"), + ); + }); + }); + }); + }); + }); + } - it("S1: a positive integer length has no maximum, so 10000 is not capped at 4096", function* () { - const long = "b".repeat(5000); - const result = yield* over(long, " length={10000}"); + { + const name = "S1: a start at or beyond the end is an empty window that still says so"; + it(name, function* () { + for (const offset of [7, 8, 400]) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* () { + const stream = yield* useJournalStream("doc.md"); + const result = yield* over(stream, SEVEN, ` offset={${offset}} length={4}`); + + expect(result.failure).toBe(""); + expect(result.output).toBe(`${note(7, 7, 7)}\n`); + }); + } + }); + } - expect(result.failure).toBe(""); - // The complete original, with no note: a 4096 cap would have reported - // `[0, 4096) of 5000` here. - expect(result.output).toBe(long); - expect(result.output).not.toContain("Text excerpt"); - expect(yield* captured(long, " length={10000}")).toBe(long); - }); + { + const name = "S1: empty content is the empty string, in both authored spellings"; + it(name, function* () { + const stream = yield* useJournalStream("doc.md"); + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream3) { + expect(yield* run(stream, "")).toMatchObject({ failure: "", output: "" }); + expect(yield* run(stream2, "")).toMatchObject({ failure: "", output: "" }); + expect(yield* captured(stream3, "", " length={4}")).toBe(""); + }); + }); + }); + } - it("S1: authored whitespace counts, and is neither trimmed nor normalized", function* () { - const padded = yield* run(" padded body "); - expect(padded.failure).toBe(""); - expect(padded.output).toBe(" padded body "); + { + const name = "S1: a positive integer length has no maximum, so 10000 is not capped at 4096"; + it(name, function* () { + const stream = yield* useJournalStream("doc.md"); + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream2) { + const long = "b".repeat(5000); + const result = yield* over(stream, long, " length={10000}"); + + expect(result.failure).toBe(""); + // The complete original, with no note: a 4096 cap would have reported + // `[0, 4096) of 5000` here. + expect(result.output).toBe(long); + expect(result.output).not.toContain("Text excerpt"); + expect(yield* captured(stream2, long, " length={10000}")).toBe(long); + }); + }); + } - // The same authored content, partially: the total counts every space, and - // the payload keeps the two it begins with. - const cut = yield* run(" padded body "); - expect(cut.output).toBe(excerpt(0, 9, 16, " padded ")); - }); + { + const name = "S1: authored whitespace counts, and is neither trimmed nor normalized"; + it(name, function* () { + const stream = yield* useJournalStream("doc.md"); + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream2) { + const padded = yield* run(stream, " padded body "); + expect(padded.failure).toBe(""); + expect(padded.output).toBe(" padded body "); + + // The same authored content, partially: the total counts every space, and + // the payload keeps the two it begins with. + const cut = yield* run(stream2, " padded body "); + expect(cut.output).toBe(excerpt(0, 9, 16, " padded ")); + }); + }); + } }); describe("Tier SL1 — S2: an invalid window runs no body", () => { - it("S2: every refused argument is ordinary prop validation, and nothing expands", function* () { - const refused = [ - " offset={1.5}", - ' offset="x"', - " offset={true}", - " length={0}", - " length={-1}", - " length={2.5}", - ' length="x"', - " window={1}", - ]; - - for (const attributes of refused) { - const result = yield* run(``); - - expect(reported(result)).toContain("Prop validation failed for "); - // Decided before the body: the content never expanded, so there is no - // completed work for a window to have been taken from. - expect(result.tripped).toBe(0); - expect(result.output).not.toContain("TRIPPED"); - expect(result.output).not.toContain("Text excerpt"); - } - }); + { + const name = "S2: every refused argument is ordinary prop validation, and nothing expands"; + it(name, function* () { + const refused = [ + " offset={1.5}", + ' offset="x"', + " offset={true}", + " length={0}", + " length={-1}", + " length={2.5}", + ' length="x"', + " window={1}", + ]; + + for (const attributes of refused) { + yield* captureTestJournal({ owner: OWNER, name }, "doc.md", function* (stream) { + const result = yield* run(stream, ``); + + expect(reported(result)).toContain("Prop validation failed for "); + // Decided before the body: the content never expanded, so there is no + // completed work for a window to have been taken from. + expect(result.tripped).toBe(0); + expect(result.output).not.toContain("TRIPPED"); + expect(result.output).not.toContain("Text excerpt"); + }); + } + }); + } }); describe("Tier SL1 — S3: one completion, and captures that stay complete", () => { + beforeEach(journalBeforeEach(OWNER)); it("S3: the window waits for the producer, and cuts nothing it captured", function* () { + const stream = yield* useJournalStream("doc.md"); const harness = controlled(); const source = 'X' + @@ -342,7 +409,7 @@ describe("Tier SL1 — S3: one completion, and captures that stay complete", () const result = yield* scoped(function* (): Operation { try { - const running = yield* spawn(() => run(source, { after: "AFTER" }, harness)); + const running = yield* spawn(() => run(stream, source, { after: "AFTER" }, harness)); yield* harness.entered; // Held: the producer has started and has not returned, so the window @@ -382,10 +449,16 @@ describe("Tier SL1 — S3: one completion, and captures that stay complete", () }); describe("Tier SL1 — S4: one window over the combined rendering", () => { + beforeEach(journalBeforeEach(OWNER)); it("S4: enclosed renderings share one window, and siblings outside are untouched", function* () { - const result = yield* run('HEADABEFTAIL', { - piece: "CD", - }); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + stream, + 'HEADABEFTAIL', + { + piece: "CD", + }, + ); expect(result.failure).toBe(""); // One window over `ABCDEF`, not one per child and not one over the whole @@ -399,13 +472,16 @@ describe("Tier SL1 — S4: one window over the combined rendering", () => { }); describe("Tier SL1 — S5: nesting is ordinary inside-out text", () => { + beforeEach(journalBeforeEach(OWNER)); it("S5: the outer window counts the inner note and may cut it", function* () { + const stream = yield* useJournalStream("doc.md"); const inner = excerpt(1, 4, 7, "\u{1F600}BC"); // The inner rendering is seventy code points: a sixty-six point note, its // line feed, and the three points it selected. expect(Array.from(inner).length).toBe(70); const result = yield* run( + stream, ``, { v: SEVEN }, ); @@ -419,8 +495,11 @@ describe("Tier SL1 — S5: nesting is ordinary inside-out text", () => { }); describe("Tier SL1 — S6: failed work is not an empty successful excerpt", () => { + beforeEach(journalBeforeEach(OWNER)); it("S6: a content failure settles the root and publishes no window", function* () { + const stream = yield* useJournalStream("doc.md"); const result = yield* run( + stream, 'PREFIX' + '', { after: "AFTER" }, @@ -439,7 +518,9 @@ describe("Tier SL1 — S6: failed work is not an empty successful excerpt", () = }); describe("Tier SL1 — S7: cancellation owns the teardown", () => { + beforeEach(journalBeforeEach(OWNER)); it("S7: halting the owner joins the producer's cleanup and publishes nothing", function* () { + const stream = yield* useJournalStream("doc.md"); const harness = controlled(); const source = 'X' + @@ -447,7 +528,7 @@ describe("Tier SL1 — S7: cancellation owns the teardown", () => { yield* scoped(function* () { try { - const running = yield* spawn(() => run(source, { after: "AFTER" }, harness)); + const running = yield* spawn(() => run(stream, source, { after: "AFTER" }, harness)); yield* harness.entered; expect(harness.producer.starts).toBe(1); @@ -482,8 +563,13 @@ describe("Tier SL1 — S7: cancellation owns the teardown", () => { }); describe("993 selected Slice input", () => { + beforeEach(journalBeforeEach(OWNER)); it("W6: returns the ordinary excerpt without publishing the original selected string", function* () { - const result = yield* run("documentationABCDtail"); + const stream = yield* useJournalStream("doc.md"); + const result = yield* run( + stream, + "documentationABCDtail", + ); expect(result.failure).toBe(""); expect(result.output).toBe(excerpt(0, 2, 4, "AB")); expect(result.output).not.toContain("ABCD"); diff --git a/packages/git/tests/git-host-owned.test.ts b/packages/git/tests/git-host-owned.test.ts index ff36be210..71f9664fb 100644 --- a/packages/git/tests/git-host-owned.test.ts +++ b/packages/git/tests/git-host-owned.test.ts @@ -17,7 +17,12 @@ * fence, and E8's joined teardown before publication. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { Err, @@ -75,6 +80,8 @@ import type { GitHostProvider, } from "@executablemd/git/api"; +const JOURNAL_OWNER = "packages/git/tests/git-host-owned.test.ts"; + const OWNER = '["executablemd.repl.issue-owner",1,"execution-7","entry-2"]'; const SITE = "site-9f2c"; @@ -320,8 +327,9 @@ function refusingGitHostAppends(inner: InMemoryStream): DurableStream { } describe("Tier OW — owner-specified external Git-host reconciliation", () => { + beforeEach(journalBeforeEach(JOURNAL_OWNER)); it("OW1: reconciles under exactly the stated owner and site, with no workflow run", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const host = recordingProvider(answering(Ok(ABSENT)), answering(Ok(PERFORMED))); const seen = yield* runOwned({ stream, provider: host.provider }); @@ -362,6 +370,7 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { }); it("OW2: another owner, another site and a second occurrence are separate work", function* () { + const stream = yield* useJournalStream(""); const identity = (owner: string, site: string) => ({ runId: owner, expansionId: site }); const complete = (owner: string, site: string): CompleteGitHostEffectRequest => ({ identity: identity(owner, site), @@ -379,7 +388,6 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { // They are two occurrences at two positions, which is allowed: telling them // apart is the engine's positional matching, and nothing deduplicates by // name. - const stream = new InMemoryStream(); const host = recordingProvider(answering(Ok(ABSENT)), answering(Ok(PERFORMED))); const seen = yield* runOwned({ stream, provider: host.provider, calls: 2 }); @@ -420,7 +428,7 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { }); it("OW4: a completion the caller cannot account for is fatal and publishes nothing", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const host = recordingProvider(answering(Ok(ABSENT)), answering(Ok(PERFORMED))); const refusal = new Error("this completion names a push this invocation did not describe"); @@ -487,7 +495,7 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { }); it("OW6: attempt resources survive both phases, and a held cleanup holds publication", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const order: string[] = []; stream.onAppend = (event) => { if (event.type === "yield" && event.description.type === GIT_HOST_EFFECT) { @@ -569,45 +577,49 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { ]); }); - it("OW7: a cleanup failure publishes neither a success nor an authored refusal", function* () { - const broken = new Error("the attempt's own scratch directory could not be removed"); - - // A successful reconciliation whose teardown then fails. - const succeeded = new InMemoryStream(); - const host = recordingProvider(answering(Ok(ABSENT)), answering(Ok(PERFORMED))); - const success = yield* runOwned({ - stream: succeeded, - provider: host.provider, - *resource(): Operation { - yield* ensure(function* () { - throw broken; + { + const name = "OW7: a cleanup failure publishes neither a success nor an authored refusal"; + it(name, function* () { + const succeeded = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (refused) { + const broken = new Error("the attempt's own scratch directory could not be removed"); + + // A successful reconciliation whose teardown then fails. + const host = recordingProvider(answering(Ok(ABSENT)), answering(Ok(PERFORMED))); + const success = yield* runOwned({ + stream: succeeded, + provider: host.provider, + *resource(): Operation { + yield* ensure(function* () { + throw broken; + }); + }, }); - }, - }); - expect(success.records).toEqual([]); - expect(host.performed).toHaveLength(1); - // The outcome object survived unwinding, and surviving is not enough: the - // attempt is no longer holding what it authored, so nothing is published. - expect(gitHostYields(succeeded.snapshot())).toEqual([]); - - // And an ordinary conflict the worker authored, on the same terms. - const refused = new InMemoryStream(); - const conflicted = recordingProvider(answering(Ok(CONFLICT))); - const second = yield* runOwned({ - stream: refused, - provider: conflicted.provider, - *resource(): Operation { - yield* ensure(function* () { - throw broken; + expect(success.records).toEqual([]); + expect(host.performed).toHaveLength(1); + // The outcome object survived unwinding, and surviving is not enough: the + // attempt is no longer holding what it authored, so nothing is published. + expect(gitHostYields(succeeded.snapshot())).toEqual([]); + + // And an ordinary conflict the worker authored, on the same terms. + const conflicted = recordingProvider(answering(Ok(CONFLICT))); + const second = yield* runOwned({ + stream: refused, + provider: conflicted.provider, + *resource(): Operation { + yield* ensure(function* () { + throw broken; + }); + }, }); - }, - }); - expect(second.records).toEqual([]); - expect(second.failures[0]).not.toBeInstanceOf(GitHostConflictError); - expect(gitHostYields(refused.snapshot())).toEqual([]); - }); + expect(second.records).toEqual([]); + expect(second.failures[0]).not.toBeInstanceOf(GitHostConflictError); + expect(gitHostYields(refused.snapshot())).toEqual([]); + }); + }); + } it("OW8: a refused append is the first failure, and nothing is published after it", function* () { const backing = new InMemoryStream(); @@ -626,46 +638,50 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { expect(gitHostYields(backing.snapshot())).toEqual([]); }); - it("OW9: the stated identity and request are read once, before anything suspends", function* () { - const stream = new InMemoryStream(); - const host = recordingProvider(answering(Ok(COMPATIBLE))); - - // A request object the caller keeps and edits while the attempt runs. What - // was reconciled is the reading taken before the first suspension. - const mutable: { kind: string; inputs: Json; naturalKey: Json } = { - kind: PUSH.kind, - inputs: { remote: "origin", branch: "review/push", commit: "9fceb02" }, - naturalKey: { ref: "refs/heads/review/push" }, - }; - const seen = yield* runOwned({ - stream, - request: mutable, - provider: host.provider, - validate: () => { - mutable.kind = "git-pull-request"; - mutable.inputs = { remote: "elsewhere" }; - }, - }); + { + const name = "OW9: the stated identity and request are read once, before anything suspends"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (empty) { + const host = recordingProvider(answering(Ok(COMPATIBLE))); + + // A request object the caller keeps and edits while the attempt runs. What + // was reconciled is the reading taken before the first suspension. + const mutable: { kind: string; inputs: Json; naturalKey: Json } = { + kind: PUSH.kind, + inputs: { remote: "origin", branch: "review/push", commit: "9fceb02" }, + naturalKey: { ref: "refs/heads/review/push" }, + }; + const seen = yield* runOwned({ + stream, + request: mutable, + provider: host.provider, + validate: () => { + mutable.kind = "git-pull-request"; + mutable.inputs = { remote: "elsewhere" }; + }, + }); - expect(seen.failures).toEqual([]); - expect(recordOf(seen).request.kind).toBe(PUSH.kind); - expect(recordOf(seen).request.inputs).toEqual({ - remote: "origin", - branch: "review/push", - commit: "9fceb02", - }); + expect(seen.failures).toEqual([]); + expect(recordOf(seen).request.kind).toBe(PUSH.kind); + expect(recordOf(seen).request.inputs).toEqual({ + remote: "origin", + branch: "review/push", + commit: "9fceb02", + }); - // And an identity member that names no history refuses before any of it. - const empty = new InMemoryStream(); - const refused = yield* runOwned({ - stream: empty, - owner: "", - provider: forbiddenProvider(), + // And an identity member that names no history refuses before any of it. + const refused = yield* runOwned({ + stream: empty, + owner: "", + provider: forbiddenProvider(), + }); + expect(refused.failures).toHaveLength(1); + expect(refused.constructions).toBe(0); + expect(gitHostYields(empty.snapshot())).toEqual([]); + }); }); - expect(refused.failures).toHaveLength(1); - expect(refused.constructions).toBe(0); - expect(gitHostYields(empty.snapshot())).toEqual([]); - }); + } it("OW10: an unauthored throw inside the attempt withholds what it raised", function* () { const stream = new InMemoryStream(); @@ -687,7 +703,7 @@ describe("Tier OW — owner-specified external Git-host reconciliation", () => { }); it("OW11: a provider the attempt cannot construct publishes nothing", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const unavailable = new Error("this host lends no transport for that locator"); const seen = yield* runOwned({ diff --git a/packages/git/tests/git-observations.test.ts b/packages/git/tests/git-observations.test.ts index ede443923..13c136025 100644 --- a/packages/git/tests/git-observations.test.ts +++ b/packages/git/tests/git-observations.test.ts @@ -9,11 +9,12 @@ * repository can answer. */ +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; -import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import type { Json } from "@executablemd/durable-streams"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { scoped, until } from "effection"; import { join } from "node:path"; import { utimes } from "node:fs/promises"; @@ -202,6 +203,8 @@ function propertiesOf(schema: Json): Record { } /** The four reads, with the smallest invocation each one accepts. */ +const JOURNAL_OWNER = "packages/git/tests/git-observations.test.ts"; + const FOUR_ELEMENTS: readonly { readonly name: string; readonly source: string }[] = [ { name: "Git.Files", source: '' }, { name: "Git.Changes", source: '' }, @@ -239,7 +242,11 @@ interface NeutralOptions { * adds is exactly what it is about: a Repository that answers and no reads, or * reads supplied through the same contextual Api a native host answers. */ -function runNeutralDocument(source: string, options: NeutralOptions = {}): Operation { +function runNeutralDocument( + source: string, + options: NeutralOptions, + stream: InMemoryStream, +): Operation { return scoped(function* () { yield* useCompositionComponents(); if (options.components !== undefined) { @@ -260,9 +267,7 @@ function runNeutralDocument(source: string, options: NeutralOptions = {}): Opera if (asked !== undefined) { yield* GitQuery.around(suppliedReads(asked), { at: "min" }); } - return yield* collect( - yield* execute({ ...inlineSource(source), stream: new InMemoryStream() }), - ); + return yield* collect(yield* execute({ ...inlineSource(source), stream })); }); } @@ -722,54 +727,68 @@ describe("GO4 — the patch a comparison produces", () => { }); describe("GO5 — pages are bounded, complete, and about one observation", () => { - beforeEach(journalBeforeEach("packages/git/tests/git-observations.test.ts")); - it("defaults to 100 records, follows every page once, and honors a larger limit", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useGeneratedFixture(1002); - const seen: Json[] = []; - - yield* runOrdinaryDocument( - ['', "", "", ""].join("\n"), - { root, cwd: fixture.root, components: [capturingProbe(seen)] }, - ); - expect(paths(seen[0])).toHaveLength(100); - expect(object(seen[0]).next).not.toBe(null); - - // Every page, followed through the ordinary Api with the cursor the - // previous page supplied, until it says there is no more. - const followed: string[] = []; - yield* runOrdinaryDocument("\n", { - root, - cwd: fixture.root, - components: [ - followingProbe("Follows", function* (place) { - let cursor: string | null = null; - for (;;) { - const page: GitFilesResult = yield* GitQuery.operations.files({ - ...place, - request: { kind: "files", prefix: null, limit: 100, cursor }, - }); - followed.push(...page.paths); - if (page.next === null) { - break; - } - cursor = page.next.cursor; - } - }), - ], + beforeEach(journalBeforeEach(JOURNAL_OWNER)); + { + const name = "defaults to 100 records, follows every page once, and honors a larger limit"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream2) { + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream3) { + const root = yield* useManagedRoot(); + const fixture = yield* useGeneratedFixture(1002); + const seen: Json[] = []; + + yield* runOrdinaryDocument( + ['', "", "", ""].join("\n"), + { root, cwd: fixture.root, components: [capturingProbe(seen)] }, + stream, + ); + expect(paths(seen[0])).toHaveLength(100); + expect(object(seen[0]).next).not.toBe(null); + + // Every page, followed through the ordinary Api with the cursor the + // previous page supplied, until it says there is no more. + const followed: string[] = []; + yield* runOrdinaryDocument( + "\n", + { + root, + cwd: fixture.root, + components: [ + followingProbe("Follows", function* (place) { + let cursor: string | null = null; + for (;;) { + const page: GitFilesResult = yield* GitQuery.operations.files({ + ...place, + request: { kind: "files", prefix: null, limit: 100, cursor }, + }); + followed.push(...page.paths); + if (page.next === null) { + break; + } + cursor = page.next.cursor; + } + }), + ], + }, + stream2, + ); + expect(followed).toEqual([...fixture.paths]); + expect(new Set(followed).size).toBe(followed.length); + + // One read for all of them, which is the claim that there is no hidden cap. + const whole: Json[] = []; + yield* runOrdinaryDocument( + ['', "", "", ""].join("\n"), + { root, cwd: fixture.root, components: [capturingProbe(whole)] }, + stream3, + ); + expect(paths(whole[0])).toEqual([...fixture.paths]); + expect(object(whole[0]).next).toBe(null); + }); + }); }); - expect(followed).toEqual([...fixture.paths]); - expect(new Set(followed).size).toBe(followed.length); - - // One read for all of them, which is the claim that there is no hidden cap. - const whole: Json[] = []; - yield* runOrdinaryDocument( - ['', "", "", ""].join("\n"), - { root, cwd: fixture.root, components: [capturingProbe(whole)] }, - ); - expect(paths(whole[0])).toEqual([...fixture.paths]); - expect(object(whole[0]).next).toBe(null); - }); + } it("pages changes at a limit of one and at the default", function* () { const runFresh = yield* useOrdinaryDocumentRunner(); @@ -807,64 +826,75 @@ describe("GO5 — pages are bounded, complete, and about one observation", () => }); }); - it("windows a patch at the default, above 65536, and reassembles the whole text", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useGeneratedFixture(1002); - for (const path of fixture.paths) { - yield* writeFixtureFile(fixture.root, path, "changed\n"); - } - const seen: Json[] = []; - const windows: string[] = []; - let whole = ""; - - yield* runOrdinaryDocument( - ['', "", "", ""].join( - "\n", - ), - { root, cwd: fixture.root, components: [capturingProbe(seen)] }, - ); - const first = object(seen[0]); - expect([...String(first.text)]).toHaveLength(4096); - expect(first.offset).toBe(0); - expect(first.next).not.toBe(null); - - yield* runOrdinaryDocument("\n", { - root, - cwd: fixture.root, - components: [ - followingProbe("Follows", function* (place) { - let offset = 0; - let cursor: string | null = null; - for (;;) { - const page: GitDiffResult = yield* GitQuery.operations.diff({ - ...place, - request: { - kind: "diff", - comparison: { compare: "unstaged" }, - paths: null, - offset, - limit: 70000, - cursor, - }, - }); - windows.push(page.text); - if (page.next === null) { - whole = windows.join(""); - expect(page.length).toBe([...whole].length); - break; - } - offset = page.next.offset; - cursor = page.next.cursor; - } - }), - ], + { + const name = "windows a patch at the default, above 65536, and reassembles the whole text"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream2) { + const root = yield* useManagedRoot(); + const fixture = yield* useGeneratedFixture(1002); + for (const path of fixture.paths) { + yield* writeFixtureFile(fixture.root, path, "changed\n"); + } + const seen: Json[] = []; + const windows: string[] = []; + let whole = ""; + + yield* runOrdinaryDocument( + ['', "", "", ""].join( + "\n", + ), + { root, cwd: fixture.root, components: [capturingProbe(seen)] }, + stream, + ); + const first = object(seen[0]); + expect([...String(first.text)]).toHaveLength(4096); + expect(first.offset).toBe(0); + expect(first.next).not.toBe(null); + + yield* runOrdinaryDocument( + "\n", + { + root, + cwd: fixture.root, + components: [ + followingProbe("Follows", function* (place) { + let offset = 0; + let cursor: string | null = null; + for (;;) { + const page: GitDiffResult = yield* GitQuery.operations.diff({ + ...place, + request: { + kind: "diff", + comparison: { compare: "unstaged" }, + paths: null, + offset, + limit: 70000, + cursor, + }, + }); + windows.push(page.text); + if (page.next === null) { + whole = windows.join(""); + expect(page.length).toBe([...whole].length); + break; + } + offset = page.next.offset; + cursor = page.next.cursor; + } + }), + ], + }, + stream2, + ); + + // A limit above the old proposed cap is honored, and the windows are the + // whole patch rather than a prefix of it. + expect([...(windows[0] ?? "")]).toHaveLength(70000); + expect(whole).toBe(fixture.output("diff", "--no-ext-diff", "--no-textconv", "--no-color")); + }); }); - - // A limit above the old proposed cap is honored, and the windows are the - // whole patch rather than a prefix of it. - expect([...(windows[0] ?? "")]).toHaveLength(70000); - expect(whole).toBe(fixture.output("diff", "--no-ext-diff", "--no-textconv", "--no-color")); - }); + } it("keeps generated fixture commits free of automatic maintenance", function* () { const fixture = yield* useGeneratedFixture(1002); @@ -1116,75 +1146,86 @@ describe("GO6 — a changed observation cannot be paged over", () => { }); describe("GO7 — a file is read as one commit holds it", () => { - beforeEach(journalBeforeEach("packages/git/tests/git-observations.test.ts")); - it("windows the committed text, stays on its commit, and reassembles it", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useFileFixture(); - const seen: Json[] = []; - const windows: string[] = []; - - yield* runOrdinaryDocument( - [ - '', - "", - "", - "", - ].join("\n"), - { root, cwd: fixture.root, components: [capturingProbe(seen)] }, - ); - - const first = object(seen[0]); - expect(first.commit).toBe(fixture.f1); - expect(first.path).toBe("big.txt"); - expect(first.offset).toBe(0); - expect(first.length).toBe([...LONG_BLOB].length); - // The default window, counted in code points: the astral character is the - // last one in it and arrives whole. - expect([...String(first.text)]).toHaveLength(4096); - expect(String(first.text).endsWith(ASTRAL)).toBe(true); - expect(first.next).toEqual({ - commit: fixture.f1, - path: "big.txt", - offset: 4096, - limit: 4096, - }); - windows.push(String(first.text)); - - // The branch and the working copy both move before the continuation is - // followed, so a read that resolved `HEAD~1` again would read another file. - fixture.run("commit", "--allow-empty", "-m", "third"); - yield* writeFixtureFile(fixture.root, "big.txt", "working copy\n"); + beforeEach(journalBeforeEach(JOURNAL_OWNER)); + { + const name = "windows the committed text, stays on its commit, and reassembles it"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream2) { + const root = yield* useManagedRoot(); + const fixture = yield* useFileFixture(); + const seen: Json[] = []; + const windows: string[] = []; + + yield* runOrdinaryDocument( + [ + '', + "", + "", + "", + ].join("\n"), + { root, cwd: fixture.root, components: [capturingProbe(seen)] }, + stream, + ); + + const first = object(seen[0]); + expect(first.commit).toBe(fixture.f1); + expect(first.path).toBe("big.txt"); + expect(first.offset).toBe(0); + expect(first.length).toBe([...LONG_BLOB].length); + // The default window, counted in code points: the astral character is the + // last one in it and arrives whole. + expect([...String(first.text)]).toHaveLength(4096); + expect(String(first.text).endsWith(ASTRAL)).toBe(true); + expect(first.next).toEqual({ + commit: fixture.f1, + path: "big.txt", + offset: 4096, + limit: 4096, + }); + windows.push(String(first.text)); + + // The branch and the working copy both move before the continuation is + // followed, so a read that resolved `HEAD~1` again would read another file. + fixture.run("commit", "--allow-empty", "-m", "third"); + yield* writeFixtureFile(fixture.root, "big.txt", "working copy\n"); + + yield* runOrdinaryDocument( + "\n", + { + root, + cwd: fixture.root, + components: [ + followingProbe("Follows", function* (place) { + let offset = 4096; + for (;;) { + const page: GitFileResult = yield* GitQuery.operations.file({ + ...place, + request: { + kind: "file", + commit: fixture.f1, + path: "big.txt", + offset, + limit: 70000, + }, + }); + expect(page.commit).toBe(fixture.f1); + windows.push(page.text); + if (page.next === null) { + break; + } + offset = page.next.offset; + } + }), + ], + }, + stream2, + ); - yield* runOrdinaryDocument("\n", { - root, - cwd: fixture.root, - components: [ - followingProbe("Follows", function* (place) { - let offset = 4096; - for (;;) { - const page: GitFileResult = yield* GitQuery.operations.file({ - ...place, - request: { - kind: "file", - commit: fixture.f1, - path: "big.txt", - offset, - limit: 70000, - }, - }); - expect(page.commit).toBe(fixture.f1); - windows.push(page.text); - if (page.next === null) { - break; - } - offset = page.next.offset; - } - }), - ], + expect(windows.join("")).toBe(LONG_BLOB); + }); }); - - expect(windows.join("")).toBe(LONG_BLOB); - }); + } it("answers a middle window, an empty window past the end, and an empty file", function* () { const runFresh = yield* useOrdinaryDocumentRunner(); @@ -1237,67 +1278,73 @@ describe("GO7 — a file is read as one commit holds it", () => { expect(empty.next).toBe(null); }); - it("refuses an unusable revision, an absent path, a tree, a gitlink and a nontext blob", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useFileFixture(); - const main = yield* useObservationFixture(); - - const refusals: { source: string; cwd: string; reason: string }[] = [ - { - source: ``, - cwd: fixture.root, - reason: "invalid-revision", - }, - { - source: ``, - cwd: fixture.root, - reason: "absent-path", - }, - { - source: ``, - cwd: fixture.root, - reason: "nontext-blob", - }, - // Both spellings of the same directory. The argument Git receives is a - // pathspec rather than a lookup, so `dir/` matches the *contents* of the - // directory — and a read that took the first record would answer this - // with the blob at `dir/inside.txt` under a path claiming to be `dir/`. - { - source: ``, - cwd: fixture.root, - reason: "nontext-blob", - }, - // A file is not a directory either way round: a trailing slash on one - // matches nothing at all, which is an absent path rather than that file. - { - source: ``, - cwd: fixture.root, - reason: "absent-path", - }, - { - source: ``, - cwd: main.root, - reason: "nontext-blob", - }, - { - source: ``, - cwd: fixture.root, - reason: "nontext-blob", - }, - { - source: ``, - cwd: fixture.root, - reason: "nontext-blob", - }, - ]; + { + const name = + "refuses an unusable revision, an absent path, a tree, a gitlink and a nontext blob"; + it(name, function* () { + const root = yield* useManagedRoot(); + const fixture = yield* useFileFixture(); + const main = yield* useObservationFixture(); - for (const entry of refusals) { - const raised_ = yield* raised( - runOrdinaryDocument(`${entry.source}\n`, { root, cwd: entry.cwd }), - ); - expect(`${entry.source}: ${reasonOf(raised_)}`).toBe(`${entry.source}: ${entry.reason}`); - } - }); + const refusals: { source: string; cwd: string; reason: string }[] = [ + { + source: ``, + cwd: fixture.root, + reason: "invalid-revision", + }, + { + source: ``, + cwd: fixture.root, + reason: "absent-path", + }, + { + source: ``, + cwd: fixture.root, + reason: "nontext-blob", + }, + // Both spellings of the same directory. The argument Git receives is a + // pathspec rather than a lookup, so `dir/` matches the *contents* of the + // directory — and a read that took the first record would answer this + // with the blob at `dir/inside.txt` under a path claiming to be `dir/`. + { + source: ``, + cwd: fixture.root, + reason: "nontext-blob", + }, + // A file is not a directory either way round: a trailing slash on one + // matches nothing at all, which is an absent path rather than that file. + { + source: ``, + cwd: fixture.root, + reason: "absent-path", + }, + { + source: ``, + cwd: main.root, + reason: "nontext-blob", + }, + { + source: ``, + cwd: fixture.root, + reason: "nontext-blob", + }, + { + source: ``, + cwd: fixture.root, + reason: "nontext-blob", + }, + ]; + + for (const entry of refusals) { + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream) { + const raised_ = yield* raised( + runOrdinaryDocument(`${entry.source}\n`, { root, cwd: entry.cwd }, stream), + ); + expect(`${entry.source}: ${reasonOf(raised_)}`).toBe(`${entry.source}: ${entry.reason}`); + }); + } + }); + } it("still reads a directory's own child by its exact path", function* () { const runFresh = yield* useOrdinaryDocumentRunner(); @@ -1438,28 +1485,41 @@ describe("GO8 — a read runs no repository-defined program and changes nothing" }); describe("GO9 — which checkout answers, and what cannot choose one", () => { - it("distinguishes two sibling checkouts of one repository by their content", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useObservationFixture(); - const linked = yield* useLinkedWorktree(fixture); - yield* writeFixtureFile(linked.root, "only-linked.txt", "linked\n"); - linked.run("add", "--", "only-linked.txt"); - linked.run("commit", "-m", "linked only"); - const seen: Json[] = []; - - yield* runOrdinaryDocument( - ['', "", "", ""].join("\n"), - { root, cwd: linked.root, components: [capturingProbe(seen)] }, - ); - expect(paths(seen[0])).toContain("only-linked.txt"); - - const primary: Json[] = []; - yield* runOrdinaryDocument( - ['', "", "", ""].join("\n"), - { root, cwd: fixture.root, components: [capturingProbe(primary)] }, - ); - expect(paths(primary[0])).not.toContain("only-linked.txt"); - }); + beforeEach(journalBeforeEach(JOURNAL_OWNER)); + { + const name = "distinguishes two sibling checkouts of one repository by their content"; + it(name, function* () { + const stream = yield* useJournalStream(""); + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream2) { + const root = yield* useManagedRoot(); + const fixture = yield* useObservationFixture(); + const linked = yield* useLinkedWorktree(fixture); + yield* writeFixtureFile(linked.root, "only-linked.txt", "linked\n"); + linked.run("add", "--", "only-linked.txt"); + linked.run("commit", "-m", "linked only"); + const seen: Json[] = []; + + yield* runOrdinaryDocument( + ['', "", "", ""].join( + "\n", + ), + { root, cwd: linked.root, components: [capturingProbe(seen)] }, + stream, + ); + expect(paths(seen[0])).toContain("only-linked.txt"); + + const primary: Json[] = []; + yield* runOrdinaryDocument( + ['', "", "", ""].join( + "\n", + ), + { root, cwd: fixture.root, components: [capturingProbe(primary)] }, + stream2, + ); + expect(paths(primary[0])).not.toContain("only-linked.txt"); + }); + }); + } it("refuses a foreign selection and an edited one before reaching a host", function* () { const root = yield* useManagedRoot(); @@ -1556,46 +1616,59 @@ describe("GO10 — the comparison sees an edit the index's own times would hide" }); describe("GO11 — the authored contract, before a provider is reached", () => { - it("refuses a missing binding, a paired form, an extra prop and a mismatched comparison", function* () { - const root = yield* useManagedRoot(); - const fixture = yield* useObservationFixture(); - const counted = countingOrdinaryHost(); - - const refused: { source: string; reason: string }[] = [ - { source: "", reason: "refused" }, - { source: 'content', reason: "unexpected-content" }, - { source: '', reason: "refused" }, - { source: '', reason: "refused" }, - { - source: '', - reason: "invalid-invocation", - }, - { - source: '', - reason: "invalid-invocation", - }, - { source: '', reason: "refused" }, - { source: '', reason: "refused" }, - { - source: '', - reason: "invalid-invocation", - }, - { - source: '', - reason: "invalid-invocation", - }, - ]; - - for (const entry of refused) { - const raised_ = yield* raised( - runOrdinaryDocument(`${entry.source}\n`, { root, cwd: fixture.root, host: counted.host }), - ); - expect(`${entry.source}: ${refusalKind(raised_)}`).toBe(`${entry.source}: ${entry.reason}`); - } + { + const name = + "refuses a missing binding, a paired form, an extra prop and a mismatched comparison"; + it(name, function* () { + const root = yield* useManagedRoot(); + const fixture = yield* useObservationFixture(); + const counted = countingOrdinaryHost(); + + const refused: { source: string; reason: string }[] = [ + { source: "", reason: "refused" }, + { source: 'content', reason: "unexpected-content" }, + { source: '', reason: "refused" }, + { source: '', reason: "refused" }, + { + source: '', + reason: "invalid-invocation", + }, + { + source: '', + reason: "invalid-invocation", + }, + { source: '', reason: "refused" }, + { source: '', reason: "refused" }, + { + source: '', + reason: "invalid-invocation", + }, + { + source: '', + reason: "invalid-invocation", + }, + ]; + + for (const entry of refused) { + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream) { + const raised_ = yield* raised( + runOrdinaryDocument( + `${entry.source}\n`, + { root, cwd: fixture.root, host: counted.host }, + stream, + ), + ); + expect(`${entry.source}: ${refusalKind(raised_)}`).toBe( + `${entry.source}: ${entry.reason}`, + ); + expect(subcommands(counted.counters)).toEqual([]); + }); + } - // Not one of them reached a repository: no read ran, and no `git` for one. - expect(subcommands(counted.counters)).toEqual([]); - }); + // Not one of them reached a repository: no read ran, and no `git` for one. + expect(subcommands(counted.counters)).toEqual([]); + }); + } it("declares exactly the four names, forms, props, results and defaults", function* () { const registered = COMPOSITION_REGISTRATIONS.filter((entry) => @@ -1671,30 +1744,42 @@ describe("GO11 — the authored contract, before a provider is reached", () => { }); describe("GO12 — availability is the installed provider's, with no fallback", () => { - it("refuses all four on a host that installs nothing for them", function* () { - for (const element of FOUR_ELEMENTS) { - const raised_ = yield* raised(runNeutralDocument(`${element.source}\n`)); - // A neutral host has no Repository provider either, so the refusal is - // the first absent one — and nothing falls back to the caller's own - // filesystem on the way. - expect(`${element.name}: ${raised_ === undefined ? "answered" : "refused"}`).toBe( - `${element.name}: refused`, - ); - } - }); + beforeEach(journalBeforeEach(JOURNAL_OWNER)); + { + const name = "refuses all four on a host that installs nothing for them"; + it(name, function* () { + for (const element of FOUR_ELEMENTS) { + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream) { + const raised_ = yield* raised(runNeutralDocument(`${element.source}\n`, {}, stream)); + // A neutral host has no Repository provider either, so the refusal is + // the first absent one — and nothing falls back to the caller's own + // filesystem on the way. + expect(`${element.name}: ${raised_ === undefined ? "answered" : "refused"}`).toBe( + `${element.name}: refused`, + ); + }); + } + }); + } - it("reaches the reads' own absent-provider refusal once a repository is selected", function* () { - for (const element of FOUR_ELEMENTS) { - const raised_ = yield* raised( - runNeutralDocument(`${element.source}\n`, { repository: true }), - ); - expect(`${element.name}: ${raised_ instanceof GitObservationProviderError}`).toBe( - `${element.name}: true`, - ); - } - }); + { + const name = "reaches the reads' own absent-provider refusal once a repository is selected"; + it(name, function* () { + for (const element of FOUR_ELEMENTS) { + yield* captureTestJournal({ owner: JOURNAL_OWNER, name }, "", function* (stream) { + const raised_ = yield* raised( + runNeutralDocument(`${element.source}\n`, { repository: true }, stream), + ); + expect(`${element.name}: ${raised_ instanceof GitObservationProviderError}`).toBe( + `${element.name}: true`, + ); + }); + } + }); + } it("answers through the same Api when a host supplies the four methods", function* () { + const stream = yield* useJournalStream(""); const asked: string[] = []; const seen: Json[] = []; @@ -1718,6 +1803,7 @@ describe("GO12 — availability is the installed provider's, with no fallback", "", ].join("\n"), { repository: true, reads: asked, components: [capturingProbe(seen)] }, + stream, ); // The request each component composed, in the order they ran. diff --git a/packages/testing/tests/testing-activation.test.ts b/packages/testing/tests/testing-activation.test.ts index 91c7fc58d..cba555e5d 100644 --- a/packages/testing/tests/testing-activation.test.ts +++ b/packages/testing/tests/testing-activation.test.ts @@ -9,8 +9,7 @@ * and "no results" is the vacuous failure mode rather than the evidence. */ -import { captureTestJournal } from "@executablemd/test-support/failure-journal"; -import { describe, it, beforeAll } from "@executablemd/test-support/bdd"; +import { describe, it, beforeAll, beforeEach } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { scoped } from "effection"; import type { Operation, Result } from "effection"; @@ -21,6 +20,7 @@ import { useStubFs } from "@executablemd/runtime/test"; import { Component, execute, registerComponents, useTempFileCompiler } from "@executablemd/core"; import type { Operation as CoreOperation } from "effection"; import type { Json } from "@executablemd/core"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; import { installTestingComponents } from "../src/components.ts"; import { useTesting } from "../src/use-testing.ts"; import type { TestResult } from "../src/test-api.ts"; @@ -168,6 +168,7 @@ const REFUSAL = "complete testing activation"; describe("complete testing activation", () => { beforeAll(() => useTempFileCompiler()); + beforeEach(journalBeforeEach(OWNER)); // Both body shapes, because a passing body and a failing one take different // paths through classification and reporting — and neither may start. @@ -177,9 +178,11 @@ describe("complete testing activation", () => { ]; for (const shape of shapes) { it(`refuses ${shape.label} before it expands`, function* () { + const stream = yield* useJournalStream("README.md"); const attempt = yield* runComposed( `${shape.assertion}\n`, incompleteActivation(), + stream, ); expect(attempt.sentinels).toEqual([]); expect(errorOf(attempt)?.message).toContain(REFUSAL); @@ -308,6 +311,7 @@ describe("complete testing activation", () => { // decline it: recognizing the refusal takes core's own private mark, and a // package composed against a second loaded copy of core could not see it. it("keeps a refused decision away from every failure handler", function* () { + const stream = yield* useJournalStream("README.md"); const handled: string[] = []; const attempt = yield* runComposed( '\n', @@ -320,6 +324,7 @@ describe("complete testing activation", () => { }); yield* incompleteActivation(); })(), + stream, ); expect(handled).toEqual([]); expect(attempt.sentinels).toEqual([]); @@ -337,6 +342,7 @@ describe("complete testing activation", () => { // never ran, so the refusal is still a configuration failure: what marks it is // where it was raised, not what it is. it("refuses when a handler throws its own error from the decision chain", function* () { + const stream = yield* useJournalStream("README.md"); const attempt = yield* runComposed( '\n', (function* () { @@ -349,6 +355,7 @@ describe("complete testing activation", () => { }); yield* incompleteActivation(); })(), + stream, ); expect(attempt.sentinels).toEqual([]); expect(attempt.completion.ok).toBe(false); @@ -375,6 +382,7 @@ describe("complete testing activation", () => { ]; for (const composition of blockedCompositions) { it(`refuses a blocked activation decision under ${composition.label}`, function* () { + const stream = yield* useJournalStream("README.md"); const attempt = yield* runComposed( '\n', (function* () { @@ -383,6 +391,7 @@ describe("complete testing activation", () => { yield* seam.around({ *require() {} }); yield* composition.compose(); })(), + stream, ); expect(attempt.sentinels).toEqual([]); expect(attempt.completion.ok).toBe(false); @@ -400,6 +409,7 @@ describe("complete testing activation", () => { // and before this chain is dispatched, so a handler that answers for what a // test does cannot answer for whether it may run. it("survives a TestBehavior handler that never delegates", function* () { + const stream = yield* useJournalStream("README.md"); const behavior = loadedCopyBehaviorApi(); const attempt = yield* runComposed( '\n', @@ -414,6 +424,7 @@ describe("complete testing activation", () => { }); yield* incompleteActivation(); })(), + stream, ); expect(attempt.sentinels).toEqual([]); expect(errorOf(attempt)?.message).toContain(REFUSAL); @@ -423,112 +434,89 @@ describe("complete testing activation", () => { // The control, in the identical middleware order: a handler that delegates // observes the behavior and changes nothing about it. it("leaves an ordinary TestBehavior handler composing under a complete session", function* () { - yield* captureTestJournal( - { - owner: OWNER, - name: "leaves an ordinary TestBehavior handler composing under a complete session", - }, - "README.md", - function* (stream) { - const behavior = loadedCopyBehaviorApi(); - const observed: string[] = []; - const attempt = yield* runComposed( - '\n', - (function* () { - yield* behavior.around({ - *test([props], next) { - observed.push(String(props.name)); - return yield* next(props); - }, - }); - yield* useTesting(); - })(), - stream, - ); - expect(observed).toEqual(["t"]); - expect(attempt.sentinels).toEqual(["body"]); - expect(attempt.completion.ok).toBe(true); - expect(attempt.results.map((result) => [result.name, result.status])).toEqual([ - ["t", "pass"], - ]); - expect(testResultEvents(attempt.events)).toHaveLength(1); - }, + const stream = yield* useJournalStream("README.md"); + const behavior = loadedCopyBehaviorApi(); + const observed: string[] = []; + const attempt = yield* runComposed( + '\n', + (function* () { + yield* behavior.around({ + *test([props], next) { + observed.push(String(props.name)); + return yield* next(props); + }, + }); + yield* useTesting(); + })(), + stream, ); + expect(observed).toEqual(["t"]); + expect(attempt.sentinels).toEqual(["body"]); + expect(attempt.completion.ok).toBe(true); + expect(attempt.results.map((result) => [result.name, result.status])).toEqual([ + ["t", "pass"], // The discovered test is the only result. + ]); + expect(testResultEvents(attempt.events)).toHaveLength(1); }); // The other direction: under a real session the same public surface keeps // working, and observes results in discovery order. it("leaves loaded-copy policy and recording composition working", function* () { - yield* captureTestJournal( - { owner: OWNER, name: "leaves loaded-copy policy and recording composition working" }, - "README.md", - function* (stream) { - const attempt = yield* runComposed( - [ - '', - '', - "", - ].join("\n"), - useTesting(), - stream, - ); - expect(attempt.completion.ok).toBe(true); - expect(attempt.sentinels).toEqual(["first", "second"]); - expect(attempt.results.map((result) => [result.name, result.status])).toEqual([ - ["first", "pass"], - ["second", "pass"], - ]); - expect(testResultEvents(attempt.events)).toHaveLength(2); - }, + const stream = yield* useJournalStream("README.md"); + const attempt = yield* runComposed( + [ + '', + '', + "", + ].join("\n"), + useTesting(), + stream, ); + expect(attempt.completion.ok).toBe(true); + expect(attempt.sentinels).toEqual(["first", "second"]); + expect(attempt.results.map((result) => [result.name, result.status])).toEqual([ + ["first", "pass"], + ["second", "pass"], + ]); + expect(testResultEvents(attempt.events)).toHaveLength(2); }); // Narrowing is what the public boolean is for, and it still works: a policy // that answers `false` leaves the test inactive rather than refused. it("lets public policy narrow testing to false under a complete session", function* () { - yield* captureTestJournal( - { owner: OWNER, name: "lets public policy narrow testing to false under a complete session" }, - "README.md", - function* (stream) { - const attempt = yield* runComposed( - '\n', - (function* () { - yield* useTesting(); - const policy = loadedCopyTestApi(); - yield* policy.around({ testing: () => false }); - })(), - stream, - ); - expect(attempt.sentinels).toEqual([]); - expect(attempt.results).toEqual([]); - // No tests were discovered, which is the session's own outcome — not the - // activation refusal. - expect(errorOf(attempt)?.message).toContain("no tests were discovered"); - }, + const stream = yield* useJournalStream("README.md"); + const attempt = yield* runComposed( + '\n', + (function* () { + yield* useTesting(); + const policy = loadedCopyTestApi(); + yield* policy.around({ testing: () => false }); + })(), + stream, ); + expect(attempt.sentinels).toEqual([]); + expect(attempt.results).toEqual([]); + // No tests were discovered, which is the session's own outcome — not the + // activation refusal. + expect(errorOf(attempt)?.message).toContain("no tests were discovered"); }); // An ended boundary's credential is retired, so a `` written after it // is refused exactly as one written before it. it("expires with the boundary that established it", function* () { - yield* captureTestJournal( - { owner: OWNER, name: "expires with the boundary that established it" }, - "README.md", - function* (stream) { - const attempt = yield* runComposed( - [ - "", - '', - "", - '', - "", - ].join("\n"), - incompleteActivation(), - stream, - ); - expect(attempt.sentinels).toEqual(["inside"]); - expect(errorOf(attempt)?.message).toContain(REFUSAL); - }, + const stream = yield* useJournalStream("README.md"); + const attempt = yield* runComposed( + [ + "", + '', + "", + '', + "", + ].join("\n"), + incompleteActivation(), + stream, ); + expect(attempt.sentinels).toEqual(["inside"]); + expect(errorOf(attempt)?.message).toContain(REFUSAL); }); }); diff --git a/packages/workflow/tests/generated-observations.test.ts b/packages/workflow/tests/generated-observations.test.ts index 5176b4df3..e8a0d35fd 100644 --- a/packages/workflow/tests/generated-observations.test.ts +++ b/packages/workflow/tests/generated-observations.test.ts @@ -26,7 +26,11 @@ import type { DurableEvent, Json } from "@executablemd/durable-streams"; import { retainedSource, SOURCE_POSITION_FIELD } from "@executablemd/core"; import { executeInstalled } from "@executablemd/core/host"; import { collect } from "@executablemd/core"; -import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; import { useWorkflowGenerated, workflowGeneratedSelection, @@ -389,86 +393,88 @@ describe("Tier WGX — what an admitted request may reach is live", () => { expect(transport.performed).toHaveLength(0); }); - it("WGX9: a bound this host stated cannot be moved by editing what it was given", function* () { - const transport = yield* useTransport(); - const bound = { url: URL_ONE, headers: { "x-bound": "stated" } }; - - yield* scoped(function* () { - // One installed policy for the whole row. The edit below happens while - // this is still the thing deciding requests, which is the only place an - // in-place edit could have moved anything. - yield* useWorkflowGenerated({ requests: [bound] }); - - const stated = yield* once(fetching(URL_ONE, { "x-bound": "stated" })); - expect(stated.failure).toBe(undefined); - expect(transport.performed).toHaveLength(1); - - // The host still holds the object it passed, and edits it here. - bound.url = URL_TWO; - bound.headers["x-bound"] = "changed"; - - // What it stated is still admitted: the policy compares against the copy - // it captured, not against the object it was handed. - const again = yield* once(fetching(URL_ONE, { "x-bound": "stated" })); - expect(again.failure).toBe(undefined); - expect(transport.performed).toHaveLength(2); - - // And what the edit tried to admit was never bounded. Both halves of it - // are refused — the destination and the header value. - const moved = yield* once(fetching(URL_TWO, { "x-bound": "changed" })); - expect(moved.failure).toContain("not permitted in this scope"); - const changed = yield* once(fetching(URL_ONE, { "x-bound": "changed" })); - expect(changed.failure).toContain("not permitted in this scope"); - expect(transport.performed).toHaveLength(2); + { + const name = "WGX9: a bound this host stated cannot be moved by editing what it was given"; + it(name, function* () { + const stream = yield* useJournalStream(ROOT_PATH); + yield* captureTestJournal({ owner: OWNER, name }, ROOT_PATH, function* (stream2) { + yield* captureTestJournal({ owner: OWNER, name }, ROOT_PATH, function* (stream3) { + yield* captureTestJournal({ owner: OWNER, name }, ROOT_PATH, function* (stream4) { + const transport = yield* useTransport(); + const bound = { url: URL_ONE, headers: { "x-bound": "stated" } }; + + yield* scoped(function* () { + // One installed policy for the whole row. The edit below happens while + // this is still the thing deciding requests, which is the only place an + // in-place edit could have moved anything. + yield* useWorkflowGenerated({ requests: [bound] }); + + const stated = yield* once(fetching(URL_ONE, { "x-bound": "stated" }), {}, stream); + expect(stated.failure).toBe(undefined); + expect(transport.performed).toHaveLength(1); + + bound.url = URL_TWO; + bound.headers["x-bound"] = "changed"; + + const again = yield* once(fetching(URL_ONE, { "x-bound": "stated" }), {}, stream2); + expect(again.failure).toBe(undefined); + expect(transport.performed).toHaveLength(2); + + const moved = yield* once(fetching(URL_TWO, { "x-bound": "changed" }), {}, stream3); + expect(moved.failure).toContain("not permitted in this scope"); + const changed = yield* once(fetching(URL_ONE, { "x-bound": "changed" }), {}, stream4); + expect(changed.failure).toContain("not permitted in this scope"); + expect(transport.performed).toHaveLength(2); + }); + }); + }); + }); }); - }); - - it("WGX13: a header a transformation added is compared as the transport will send it", function* () { - // The real terminal and a real server, because this row is about the - // difference between the request a policy read and the request that goes - // out. Nothing substitutes `API.Fetch`: the terminal asks `Permissions` - // itself, after every transformation and immediately before transport. - const server = yield* useLoopback(); - const url = `${server.origin}/bounded`; + } - // Positive control: the request the host bounded, unchanged, reaches the - // server carrying exactly the header that was stated. - const allowed = yield* run(fetching(url, { "x-bound": "admitted" }), { - generated: { requests: [{ url, headers: { "x-bound": "admitted" } }] }, - }); - expect(allowed.failure).toBe(undefined); - expect(server.received).toEqual(["admitted"]); - expect(fetches(allowed.events)).toHaveLength(1); - - // The same bound, with middleware that adds a differently cased spelling of - // the bounded name. A transport joins the two into one sent header, so the - // value that would go out is neither the bounded one nor anything this host - // stated — and the request is refused before transport starts. - const transformed = yield* scoped(function* () { - yield* API.Fetch.around({ - *fetch([input, init], next) { - return yield* next(input, { - ...init, - headers: { "X-Bound": "EXTRA", ...(init?.headers ?? {}) }, + { + const name = "WGX13: a header a transformation added is compared as the transport will send it"; + it(name, function* () { + const stream = yield* useJournalStream(ROOT_PATH); + yield* captureTestJournal({ owner: OWNER, name }, ROOT_PATH, function* (stream2) { + const server = yield* useLoopback(); + const url = `${server.origin}/bounded`; + + const allowed = yield* run( + fetching(url, { "x-bound": "admitted" }), + { + generated: { requests: [{ url, headers: { "x-bound": "admitted" } }] }, + }, + stream, + ); + expect(allowed.failure).toBe(undefined); + expect(server.received).toEqual(["admitted"]); + expect(fetches(allowed.events)).toHaveLength(1); + + const transformed = yield* scoped(function* () { + yield* API.Fetch.around({ + *fetch([input, init], next) { + return yield* next(input, { + ...init, + headers: { "X-Bound": "EXTRA", ...(init?.headers ?? {}) }, + }); + }, }); - }, - }); - return yield* run(fetching(url, { "x-bound": "admitted" }), { - generated: { requests: [{ url, headers: { "x-bound": "admitted" } }] }, + return yield* run( + fetching(url, { "x-bound": "admitted" }), + { + generated: { requests: [{ url, headers: { "x-bound": "admitted" } }] }, + }, + stream2, + ); + }); + + expect(server.received).toEqual(["admitted"]); + expect(transformed.failure).toContain("not permitted in this scope"); + expect(statuses(fetches(transformed.events))).toEqual(["err"]); }); }); - - // Asked first, because it is the whole question: the server was asked once - // in this row, by the control, and the transformed request reached it not - // at all. A comparator that read a collapsed copy of the headers would let - // this one through carrying `EXTRA, admitted`. - expect(server.received).toEqual(["admitted"]); - expect(transformed.failure).toContain("not permitted in this scope"); - // What it retained is the refusal, not an observation: the request was - // refused where it would have been sent, so there is no response here to - // restore from. - expect(statuses(fetches(transformed.events))).toEqual(["err"]); - }); + } it("WGX14: a bound naming one header twice is refused where it is stated", function* () { const transport = yield* useTransport();