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-agent-journey.test.ts b/packages/cli/tests/repl-agent-journey.test.ts index 1a9efd465..509eec215 100644 --- a/packages/cli/tests/repl-agent-journey.test.ts +++ b/packages/cli/tests/repl-agent-journey.test.ts @@ -3,7 +3,8 @@ import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { scoped, sleep, spawn, suspend, until as untilResolved, withResolvers } from "effection"; import type { Operation } from "effection"; -import { useTempFileCompiler } from "@executablemd/core"; +import { INLINE_SOURCE_PATH, useTempFileCompiler } from "@executablemd/core"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import { ensureDir, writeTextFile } from "@effectionx/fs"; import { useTempDirectory } from "@executablemd/test-support/temp"; import { InMemoryStream } from "@executablemd/durable-streams"; @@ -609,48 +610,55 @@ describe("A2–A5 — the selected REPL component environment", () => { expect(reached).toEqual([]); }); - it("A3: preflight and execution select the same collision in either directory order", function* () { + const collision = + "A3: preflight and execution select the same collision in either directory order"; + it(collision, function* () { const fixture = yield* includeWorkspace(); for (const which of ["First", "Second"] satisfies readonly ("First" | "Second")[]) { - yield* scoped(function* () { - const relativeFirst = relative(yield* cwd(), fixture.first); - const includes = - which === "First" ? [relativeFirst, fixture.second] : [fixture.second, relativeFirst]; - const fake = createFakeAcp(); - const profile = yield* selectedProfile(includes, fixture.root, fake); - const stream = new InMemoryStream(); - const options = { - execution: { id: `include-${which}`, stream }, - includes: profile.includes, - installations: profile.installations, - generated: profile.generated, - }; - const wrong = which === "First" ? "Second" : "First"; - const refused = yield* submitReplEntry({ - ...options, - source: ``, - }); - expect(refused.ok).toBe(false); - expect(yield* stream.readAll()).toEqual([]); - const accepted = yield* submitReplEntry({ - ...options, - source: ``, - }); - if (!accepted.ok) { - throw accepted.error; - } - const session = accepted.value; - const result = yield* session.join(); - expect(result.ok).toBe(true); - expect(session.model.terminal?.output).toContain(`${which} greeting rendered.`); - const selectedPath = join( - which === "First" ? fixture.first : fixture.second, - "Greeting.md", - ); - expect(JSON.stringify(yield* stream.readAll())).toContain(selectedPath); - expect(yield* profile.vocabulary.documentation(["Greeting"])).toContain(selectedPath); - expect(fake.prompts).toEqual([]); - }); + yield* captureReplEntry( + { owner: "packages/cli/tests/repl-agent-journey.test.ts", name: collision }, + `include-${which}`, + INLINE_SOURCE_PATH, + function* (execution) { + const relativeFirst = relative(yield* cwd(), fixture.first); + const includes = + which === "First" ? [relativeFirst, fixture.second] : [fixture.second, relativeFirst]; + const fake = createFakeAcp(); + const profile = yield* selectedProfile(includes, fixture.root, fake); + const stream = execution.stream; + const options = { + execution, + includes: profile.includes, + installations: profile.installations, + generated: profile.generated, + }; + const wrong = which === "First" ? "Second" : "First"; + const refused = yield* submitReplEntry({ + ...options, + source: ``, + }); + expect(refused.ok).toBe(false); + expect(yield* stream.readAll()).toEqual([]); + const accepted = yield* submitReplEntry({ + ...options, + source: ``, + }); + if (!accepted.ok) { + throw accepted.error; + } + const session = accepted.value; + const result = yield* session.join(); + expect(result.ok).toBe(true); + expect(session.model.terminal?.output).toContain(`${which} greeting rendered.`); + const selectedPath = join( + which === "First" ? fixture.first : fixture.second, + "Greeting.md", + ); + expect(JSON.stringify(yield* stream.readAll())).toContain(selectedPath); + expect(yield* profile.vocabulary.documentation(["Greeting"])).toContain(selectedPath); + expect(fake.prompts).toEqual([]); + }, + ); } }); diff --git a/packages/cli/tests/repl-entries.test.ts b/packages/cli/tests/repl-entries.test.ts index 9d3c93853..9e2cf4fd2 100644 --- a/packages/cli/tests/repl-entries.test.ts +++ b/packages/cli/tests/repl-entries.test.ts @@ -21,6 +21,7 @@ import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import { collect, Execution, @@ -114,6 +115,8 @@ import { useReplTree } from "../src/repl/reconcile.ts"; import type { ReplTree } from "../src/repl/reconcile.ts"; /** One entry that publishes two root values and renders one of them. */ +const OWNER = "packages/cli/tests/repl-entries.test.ts"; + const FIRST = [ "```js eval", 'const token = "alpha";', @@ -1252,43 +1255,57 @@ function* countPerformed(): Operation { describe("REPL entries: one session, one entry task, in turn", () => { beforeAll(() => useTempFileCompiler()); - it("EL1: the first entry starts exactly one task", function* () { - const holder = replExecution(); - yield* scoped(function* () { - const session = opened(yield* submitReplEntry({ execution: holder, source: FIRST })); - yield* session.join(); + const firstTask = "EL1: the first entry starts exactly one task"; + it(firstTask, () => + captureReplEntry( + { owner: OWNER, name: firstTask }, + "entries", + INLINE_SOURCE_PATH, + function* (holder) { + yield* scoped(function* () { + const session = opened(yield* submitReplEntry({ execution: holder, source: FIRST })); + yield* session.join(); - expect(session.model.entries.map((entry) => entry.key)).toEqual(["entry-1"]); - expect(session.model.settled).toBe(true); - expect(session.live).toBe(false); - }); - expect(started(yield* holder.stream.readAll())).toBe(1); - }); + expect(session.model.entries.map((entry) => entry.key)).toEqual(["entry-1"]); + expect(session.model.settled).toBe(true); + expect(session.live).toBe(false); + }); + expect(started(yield* holder.stream.readAll())).toBe(1); + }, + ), + ); - it("EL1: a submission while an entry is running refuses and starts nothing", function* () { - const holder = replExecution(); - yield* scoped(function* () { - const session = opened(yield* submitReplEntry({ execution: holder, source: ASKS })); - const question = yield* asking(session); - const held = yield* holder.stream.readAll(); + const busySubmission = "EL1: a submission while an entry is running refuses and starts nothing"; + it(busySubmission, () => + captureReplEntry( + { owner: OWNER, name: busySubmission }, + "entries", + INLINE_SOURCE_PATH, + function* (holder) { + yield* scoped(function* () { + const session = opened(yield* submitReplEntry({ execution: holder, source: ASKS })); + const question = yield* asking(session); + const held = yield* holder.stream.readAll(); - const error = refusedSubmission(yield* session.submit(PLAIN)); - // Named for the entry in the way, rather than for which of the two - // conditions fired: what this row claims is that a submission arriving - // while an entry runs refuses and starts nothing. - expect(error.name).toBe("ReplLifecycleError"); - expect(error.message).toContain("entry-1"); - // Nothing started: the file has not moved, no second root was admitted, and - // the question this entry is waiting on is the one it was waiting on. - expect(yield* holder.stream.readAll()).toEqual(held); - expect(started(held)).toBe(1); - expect(session.overlay.question).toBe(question); + const error = refusedSubmission(yield* session.submit(PLAIN)); + // Named for the entry in the way, rather than for which of the two + // conditions fired: what this row claims is that a submission arriving + // while an entry runs refuses and starts nothing. + expect(error.name).toBe("ReplLifecycleError"); + expect(error.message).toContain("entry-1"); + // Nothing started: the file has not moved, no second root was admitted, and + // the question this entry is waiting on is the one it was waiting on. + expect(yield* holder.stream.readAll()).toEqual(held); + expect(started(held)).toBe(1); + expect(session.overlay.question).toBe(question); - question.submit({ decision: "go" }); - yield* session.join(); - }); - expect(started(yield* holder.stream.readAll())).toBe(1); - }); + question.submit({ decision: "go" }); + yield* session.join(); + }); + expect(started(yield* holder.stream.readAll())).toBe(1); + }, + ), + ); it("EL1: terminal and unjoined still refuses; the join lets the next one start", function* () { const holder = replExecution(); @@ -1487,50 +1504,57 @@ describe("REPL entries: one session, one entry task, in turn", () => { }); }); - it("EL1: teardown racing a submission starts no task and joins the one running", function* () { - const holder = replExecution(); - const entered = gate(); - const release = gate(); - // A child of this row's own scope, so the session it holds runs under the - // same compiler and host the rest of the suite does. Teardown is then this - // row's to begin, which is the whole point. - const [scope, dispose] = createScope(yield* useScope()); - const held = withResolvers(); - try { - scope.run(function* () { - const session = opened( - yield* submitReplEntry({ - execution: holder, - source: ASKS, - installations: [holdingTeardown(entered, release)], - }), - ); - held.resolve(session); - yield* suspend(); - }); - const session = yield* held.operation; - yield* asking(session); - const before = yield* holder.stream.readAll(); + const teardownRace = "EL1: teardown racing a submission starts no task and joins the one running"; + it(teardownRace, () => + captureReplEntry( + { owner: OWNER, name: teardownRace }, + "entries", + INLINE_SOURCE_PATH, + function* (holder) { + const entered = gate(); + const release = gate(); + // A child of this row's own scope, so the session it holds runs under the + // same compiler and host the rest of the suite does. Teardown is then this + // row's to begin, which is the whole point. + const [scope, dispose] = createScope(yield* useScope()); + const held = withResolvers(); + try { + scope.run(function* () { + const session = opened( + yield* submitReplEntry({ + execution: holder, + source: ASKS, + installations: [holdingTeardown(entered, release)], + }), + ); + held.resolve(session); + yield* suspend(); + }); + const session = yield* held.operation; + yield* asking(session); + const before = yield* holder.stream.readAll(); - const tearing = dispose(); - // Teardown has reached the running entry's own finalizers, which is as far - // in as anything gets before the task is joined. - yield* awaiting("this session reaching its teardown", entered.opened); + const tearing = dispose(); + // Teardown has reached the running entry's own finalizers, which is as far + // in as anything gets before the task is joined. + yield* awaiting("this session reaching its teardown", entered.opened); - const error = refusedSubmission(yield* session.submit(PLAIN)); - expect(error.name).toBe("ReplLifecycleError"); - expect(yield* holder.stream.readAll()).toEqual(before); + const error = refusedSubmission(yield* session.submit(PLAIN)); + expect(error.name).toBe("ReplLifecycleError"); + expect(yield* holder.stream.readAll()).toEqual(before); - release.open(); - // And the active task is joined, rather than abandoned: observing the - // teardown is what says so. - yield* until(tearing); - expect(started(yield* holder.stream.readAll())).toBe(1); - expect(holder.stream.onAppend).toBe(null); - } finally { - release.open(); - } - }); + release.open(); + // And the active task is joined, rather than abandoned: observing the + // teardown is what says so. + yield* until(tearing); + expect(started(yield* holder.stream.readAll())).toBe(1); + expect(holder.stream.onAppend).toBe(null); + } finally { + release.open(); + } + }, + ), + ); it("EL1: an append the journal refuses opens no successor and mounts no task", function* () { const stream = new InMemoryStream(); 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/cli/tests/repl-todo.test.ts b/packages/cli/tests/repl-todo.test.ts index 38453420f..7329f127d 100644 --- a/packages/cli/tests/repl-todo.test.ts +++ b/packages/cli/tests/repl-todo.test.ts @@ -1,4 +1,6 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +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 { scoped, spawn, suspend, until, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -17,6 +19,8 @@ import type { ComponentInvocationHooks } from "@executablemd/core/host"; import { InMemoryStream } from "@executablemd/durable-streams"; import { forEach } from "@effectionx/stream-helpers"; +const OWNER = "packages/cli/tests/repl-todo.test.ts"; + function entry( source: string, history = new InMemoryStream(), @@ -333,6 +337,7 @@ describe("TODO exact source grammar and patches", () => { }); describe("TODO typed component and historical result", () => { + beforeEach(journalBeforeEach(OWNER)); it("requires as before effects, shares entry state, and replays an edit without repeating it", function* () { const root = yield* fixture(); const todo = yield* useTodo(root); @@ -365,6 +370,7 @@ describe("TODO typed component and historical result", () => { }); it("returns its own committed items while result delivery is held across a newer mutation", function* () { + const stream = yield* useJournalStream("todo-entry.md"); const root = yield* fixture(); const todo = yield* useTodo(root); const delivering = withResolvers(); @@ -384,7 +390,7 @@ describe("TODO typed component and historical result", () => { const running = yield* spawn(() => entry( '\n```diff\n@@ -0,0 +1 @@\n+- [ ] earlier\n```\n\n', - new InMemoryStream(), + stream, observing, ), ); @@ -401,13 +407,14 @@ describe("TODO typed component and historical result", () => { }); it("admits both forms from one captured definition and refuses writes under read-only admission", function* () { + const stream = yield* useJournalStream("todo-host.md"); const root = yield* fixture(); const todo = yield* useTodo(root); const ready = withResolvers(); const execution = yield* executeInstalled( { ...retainedSource("todo-host.md", ""), - stream: new InMemoryStream(), + stream, }, [ { diff --git a/packages/cli/tests/repl-unfinished-entry.test.ts b/packages/cli/tests/repl-unfinished-entry.test.ts index 66c9bf118..418231609 100644 --- a/packages/cli/tests/repl-unfinished-entry.test.ts +++ b/packages/cli/tests/repl-unfinished-entry.test.ts @@ -1,4 +1,5 @@ import { describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; import { cliCommand, cliRuntime } from "@executablemd/test-support/launch"; import { expect } from "@executablemd/test-support/expect"; import { @@ -26,6 +27,7 @@ import { API, Permissions } from "@executablemd/runtime"; import { Elicitation, isJsonObject, registerComponents, retainedSource } from "@executablemd/core"; import { executeInstalled } from "@executablemd/core/host"; import { InMemoryStream, StaleInputError } from "@executablemd/durable-streams"; + import { sidekickRequests } from "../src/repl/sidekick/requests.ts"; import { sidekickCeilingInstallation, @@ -284,7 +286,10 @@ function* history(f: Fixture) { return { path, bytes: yield* readTextFile(path) }; } -function control(root: Root, source: string) { +const OWNER = "packages/cli/tests/repl-unfinished-entry.test.ts"; +const OBSERVATION_SOURCE = "observation-host"; + +function control(root: Root, source: string, stream = new InMemoryStream()) { return scoped(function* () { const observations: unknown[] = []; const journal: ControlJournal = { @@ -303,8 +308,8 @@ function control(root: Root, source: string) { const released = withResolvers(); const host = yield* executeInstalled( { - ...retainedSource("observation-host", ""), - stream: new InMemoryStream(), + ...retainedSource(OBSERVATION_SOURCE, ""), + stream, }, [ sidekickCeilingInstallation(ceiling), @@ -698,22 +703,32 @@ describe("joined entry diagnostics", () => { }); it("E8: Guide.Recovery teaches the supported disposition through the real normalized control", function* () { - const f = yield* fixture(); - const rendered = yield* control( - f.root, - '{guide}', + yield* captureTestJournal( + { + owner: OWNER, + name: "E8: Guide.Recovery teaches the supported disposition through the real normalized control", + }, + OBSERVATION_SOURCE, + function* (stream) { + const f = yield* fixture(); + const rendered = yield* control( + f.root, + '{guide}', + stream, + ); + const text = rendered.response.output; + expect(text).toContain(""); + expect(text).toContain('outcome: "failed"'); + expect(text).toContain("Entry Stop refuses because no task remains"); + expect(text).toContain("unfinished segment permits"); + expect(text).toContain("it can run unrecorded work"); + expect(text).toContain("Passive Sidekick conversation reconstruction sends no turn"); + expect(text).toContain("all three execution members are"); + expect(text).toContain("Do not blindly resend or reopen"); + expect(f.host.fake.prompts).toHaveLength(0); + console.log("RECOVERY_GUIDE_RENDER_BEGIN\n" + text + "\nRECOVERY_GUIDE_RENDER_END"); + }, ); - const text = rendered.response.output; - expect(text).toContain(""); - expect(text).toContain('outcome: "failed"'); - expect(text).toContain("Entry Stop refuses because no task remains"); - expect(text).toContain("unfinished segment permits"); - expect(text).toContain("it can run unrecorded work"); - expect(text).toContain("Passive Sidekick conversation reconstruction sends no turn"); - expect(text).toContain("all three execution members are"); - expect(text).toContain("Do not blindly resend or reopen"); - expect(f.host.fake.prompts).toHaveLength(0); - console.log("RECOVERY_GUIDE_RENDER_BEGIN\n" + text + "\nRECOVERY_GUIDE_RENDER_END"); }); for (const composed of [false, true]) { diff --git a/packages/cli/tests/run-composition-deno.test.ts b/packages/cli/tests/run-composition-deno.test.ts index 1fde4023e..555972a16 100644 --- a/packages/cli/tests/run-composition-deno.test.ts +++ b/packages/cli/tests/run-composition-deno.test.ts @@ -14,7 +14,9 @@ import { Permissions } from "@executablemd/runtime"; * `run-composition-nested.test.ts`. */ -import { describe, it } from "@executablemd/test-support/bdd"; +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 { type Operation, scoped, until } from "effection"; import { realpath } from "node:fs/promises"; @@ -89,6 +91,8 @@ function* useAmbient( return { checkout, root: join(managed, "repositories"), home }; } +const OWNER = "packages/cli/tests/run-composition-deno.test.ts"; + /** * Run one document under the ordinary provider, on a stream a caller chose. * @@ -103,6 +107,7 @@ function runOrdinary( root: string; cwd: string; journal?: string; + stream?: InMemoryStream; /** Installed after the components, where a provider's own middleware goes. */ agent?: () => Operation; }, @@ -134,13 +139,17 @@ function runOrdinary( // `--journal` is exactly this: the file-backed stream instead of the // in-memory one, created by the command before the run begins. const stream = - options.journal === undefined ? new InMemoryStream() : new FileStream(options.journal); + options.journal === undefined + ? (options.stream ?? new InMemoryStream()) + : new FileStream(options.journal); return yield* collect(yield* execute({ ...inlineSource(source), stream })); }); } describe("ORC7 — a Session launched in a managed Worktree", () => { + beforeEach(journalBeforeEach(OWNER)); it("hands the launch that worktree's own root and a session key of its own", function* () { + const stream = yield* useJournalStream(""); yield* Permissions.around( { files: ([operation], next) => (operation === "absolute" ? true : next(operation)) }, { at: "min" }, @@ -242,7 +251,7 @@ describe("ORC7 — a Session launched in a managed Worktree", () => { "", "{w}", ].join("\n"), - { root: ambient.root, cwd: ambient.checkout, agent: capture }, + { root: ambient.root, cwd: ambient.checkout, agent: capture, stream }, ); const worktree = String(bound).trim().split("\n").at(-1) ?? ""; expect(yield* exists(worktree)).toBe(true); @@ -275,7 +284,9 @@ describe("ORC7 — a Session launched in a managed Worktree", () => { }); describe("ORC18 — the journal is diagnostic", () => { + beforeEach(journalBeforeEach(OWNER)); it("performs the same live work with and without a trace, once each", function* () { + const stream = yield* useJournalStream(""); yield* Permissions.around( { files: ([operation], next) => (operation === "absolute" ? true : next(operation)) }, { at: "min" }, @@ -293,7 +304,7 @@ describe("ORC18 — the journal is diagnostic", () => { "", ].join("\n"); - yield* runOrdinary(document, { root: first.root, cwd: first.checkout }); + yield* runOrdinary(document, { root: first.root, cwd: first.checkout, stream }); yield* runOrdinary(document, { root: second.root, cwd: second.checkout, diff --git a/packages/cli/tests/service-document.test.ts b/packages/cli/tests/service-document.test.ts index 86bc3720b..b786b3627 100644 --- a/packages/cli/tests/service-document.test.ts +++ b/packages/cli/tests/service-document.test.ts @@ -1,4 +1,6 @@ import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { when } from "@effectionx/converge"; import { once } from "@effectionx/node/events"; @@ -12,6 +14,8 @@ import { SERVICE_HOSTNAME, ServiceUnexpectedExitError } from "@executablemd/runt import { useStubFs } from "@executablemd/runtime/test"; import { inheritedEnvironment, installHostService } from "../src/service-host.ts"; +const OWNER = "packages/cli/tests/service-document.test.ts"; + const fixture = new URL("./fixtures/attached-service.mjs", import.meta.url).pathname; function command(mode: string, nonce: string): string { @@ -366,23 +370,30 @@ yield* Sample.around({ }); it("supervises an attached service that exits during projected content without restarting it", function* () { - const stderr: string[] = []; - let tokenCalls = 0; - yield* scoped(function* () { - yield* installHostService({ - token() { - tokenCalls += 1; - return tokenCalls.toString(16).padStart(64, "0"); - }, - environment: () => inheritedEnvironment(process.env), - stdout() {}, - stderr(bytes) { - stderr.push(new TextDecoder().decode(bytes)); - }, - }); - yield* useStubFs({ - "doc.md": "\n", - "components/Provider.md": `--- + yield* captureTestJournal( + { + owner: OWNER, + name: "supervises an attached service that exits during projected content without restarting it", + }, + "doc.md", + function* (stream) { + const stderr: string[] = []; + let tokenCalls = 0; + yield* scoped(function* () { + yield* installHostService({ + token() { + tokenCalls += 1; + return tokenCalls.toString(16).padStart(64, "0"); + }, + environment: () => inheritedEnvironment(process.env), + stdout() {}, + stderr(bytes) { + stderr.push(new TextDecoder().decode(bytes)); + }, + }); + yield* useStubFs({ + "doc.md": "\n", + "components/Provider.md": `--- meta: componentName: Provider --- @@ -405,41 +416,50 @@ yield* Sample.around({ `, - "components/Sample.md": SAMPLE, - }); - - let failure: unknown; - try { - yield* runDocument(new InMemoryStream()); - } catch (error) { - failure = error; - } - - expect(stderr.join("")).toContain("service request:projected-exit"); - expect(hasUnexpectedExit(failure)).toBe(true); - expect(tokenCalls).toBe(1); - }); - yield* expectGone(fixturePids(stderr)); + "components/Sample.md": SAMPLE, + }); + + let failure: unknown; + try { + yield* runDocument(stream); + } catch (error) { + failure = error; + } + + expect(stderr.join("")).toContain("service request:projected-exit"); + expect(hasUnexpectedExit(failure)).toBe(true); + expect(tokenCalls).toBe(1); + }); + yield* expectGone(fixturePids(stderr)); + }, + ); }); it("fails projected content promptly, tears down retained service attachments, and does not restart", function* () { - const stderr: string[] = []; - let tokenCalls = 0; - yield* scoped(function* () { - yield* installHostService({ - token() { - tokenCalls += 1; - return tokenCalls.toString(16).padStart(64, "0"); - }, - environment: () => inheritedEnvironment(process.env), - stdout() {}, - stderr(bytes) { - stderr.push(new TextDecoder().decode(bytes)); - }, - }); - yield* useStubFs({ - "doc.md": "\n", - "components/Provider.md": `--- + yield* captureTestJournal( + { + owner: OWNER, + name: "fails projected content promptly, tears down retained service attachments, and does not restart", + }, + "doc.md", + function* (stream) { + const stderr: string[] = []; + let tokenCalls = 0; + yield* scoped(function* () { + yield* installHostService({ + token() { + tokenCalls += 1; + return tokenCalls.toString(16).padStart(64, "0"); + }, + environment: () => inheritedEnvironment(process.env), + stdout() {}, + stderr(bytes) { + stderr.push(new TextDecoder().decode(bytes)); + }, + }); + yield* useStubFs({ + "doc.md": "\n", + "components/Provider.md": `--- meta: componentName: Provider --- @@ -454,7 +474,7 @@ ${command("normal", "second-retained")} `, - "components/Broken.md": `--- + "components/Broken.md": `--- meta: componentName: Broken --- @@ -463,51 +483,60 @@ meta: throw new Error("projected content failure"); \`\`\` `, - }); - - const outcome = yield* timebox(2_000, function* () { - try { - yield* runDocument(new InMemoryStream()); - } catch (error) { - return error; - } - return undefined; - }); - expect(outcome.timeout).toBe(false); - if (outcome.timeout) { - throw new Error("document failure did not complete promptly"); - } - expect(String(outcome.value)).toContain("projected content failure"); - expect(tokenCalls).toBe(2); - yield* sleep(50); - expect(tokenCalls).toBe(2); - }); - - const pids = fixturePids(stderr); - expect(pids).toHaveLength(2); - expect(stderr.join("")).toContain("service stopping:first-retained"); - expect(stderr.join("")).toContain("service stopping:second-retained"); - yield* expectGone(pids); + }); + + const outcome = yield* timebox(2_000, function* () { + try { + yield* runDocument(stream); + } catch (error) { + return error; + } + return undefined; + }); + expect(outcome.timeout).toBe(false); + if (outcome.timeout) { + throw new Error("document failure did not complete promptly"); + } + expect(String(outcome.value)).toContain("projected content failure"); + expect(tokenCalls).toBe(2); + yield* sleep(50); + expect(tokenCalls).toBe(2); + }); + + const pids = fixturePids(stderr); + expect(pids).toHaveLength(2); + expect(stderr.join("")).toContain("service stopping:first-retained"); + expect(stderr.join("")).toContain("service stopping:second-retained"); + yield* expectGone(pids); + }, + ); }); it("tears down nested service attachments from inner lifetime to outer lifetime", function* () { - const stderr: string[] = []; - let tokenCalls = 0; - yield* scoped(function* () { - yield* installHostService({ - token() { - tokenCalls += 1; - return tokenCalls.toString(16).padStart(64, "0"); - }, - environment: () => inheritedEnvironment(process.env), - stdout() {}, - stderr(bytes) { - stderr.push(new TextDecoder().decode(bytes)); - }, - }); - yield* useStubFs({ - "doc.md": "nested content\n", - "components/Outer.md": `--- + yield* captureTestJournal( + { + owner: OWNER, + name: "tears down nested service attachments from inner lifetime to outer lifetime", + }, + "doc.md", + function* (stream) { + const stderr: string[] = []; + let tokenCalls = 0; + yield* scoped(function* () { + yield* installHostService({ + token() { + tokenCalls += 1; + return tokenCalls.toString(16).padStart(64, "0"); + }, + environment: () => inheritedEnvironment(process.env), + stdout() {}, + stderr(bytes) { + stderr.push(new TextDecoder().decode(bytes)); + }, + }); + yield* useStubFs({ + "doc.md": "nested content\n", + "components/Outer.md": `--- meta: componentName: Outer --- @@ -518,7 +547,7 @@ ${command("normal", "outer")} `, - "components/Inner.md": `--- + "components/Inner.md": `--- meta: componentName: Inner --- @@ -529,18 +558,20 @@ ${command("normal", "inner")} `, - }); - - const output = yield* runDocument(new InMemoryStream()); - expect(output).toContain("nested content"); - expect(tokenCalls).toBe(2); - }); - - const log = stderr.join(""); - expect(log.indexOf("service stopping:inner")).toBeGreaterThan(-1); - expect(log.indexOf("service stopping:outer")).toBeGreaterThan( - log.indexOf("service stopping:inner"), + }); + + const output = yield* runDocument(stream); + expect(output).toContain("nested content"); + expect(tokenCalls).toBe(2); + }); + + const log = stderr.join(""); + expect(log.indexOf("service stopping:inner")).toBeGreaterThan(-1); + expect(log.indexOf("service stopping:outer")).toBeGreaterThan( + log.indexOf("service stopping:inner"), + ); + yield* expectGone(fixturePids(stderr)); + }, ); - yield* expectGone(fixturePids(stderr)); }); }); diff --git a/packages/cli/tests/ticket-checkout-deno.test.ts b/packages/cli/tests/ticket-checkout-deno.test.ts index d1b2c1316..9c68f367c 100644 --- a/packages/cli/tests/ticket-checkout-deno.test.ts +++ b/packages/cli/tests/ticket-checkout-deno.test.ts @@ -12,7 +12,13 @@ * cancelled read is not reported until its sibling's cleanup has finished. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { useTempDirectory } from "@executablemd/test-support/temp"; import { ensure, race, scoped, sleep, spawn, suspend, until, withResolvers } from "effection"; @@ -25,7 +31,7 @@ import { writeTextFile } from "@effectionx/fs"; import { collect, execute, inlineSource, registerComponents } from "@executablemd/core"; import type { ComponentRegistration } from "@executablemd/core"; import { API, Permissions, useHostFiles } from "@executablemd/runtime"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import type { Json } from "@executablemd/durable-streams"; import { useCompositionComponents } from "@executablemd/git"; import { useRunComposition } from "@executablemd/git/deno"; @@ -34,6 +40,8 @@ import type { GitChangesInvocation, GitChangesResult } from "@executablemd/git/a import { git } from "../../git/tests/support/git-remotes.ts"; import { actionProbe, capturingProbe } from "../../git/tests/support/observations.ts"; +const OWNER = "packages/cli/tests/ticket-checkout-deno.test.ts"; + const COMPONENTS = fileURLToPath( new URL("../../../examples/adversarial-implementation/components", import.meta.url), ); @@ -71,7 +79,12 @@ interface RunOptions { readonly around?: () => Operation; } -function runChecked(source: string, checkout: Checkout, options: RunOptions = {}): Operation { +function runChecked( + stream: InMemoryStream, + source: string, + checkout: Checkout, + options: RunOptions = {}, +): Operation { return scoped(function* () { yield* API.Env.around( { @@ -106,7 +119,7 @@ function runChecked(source: string, checkout: Checkout, options: RunOptions = {} return yield* collect( yield* execute({ ...inlineSource(source), - stream: new InMemoryStream(), + stream, includes: [COMPONENTS], }), ); @@ -118,9 +131,14 @@ function checkoutOf(repository: string, as = "checkout"): string { } /** Run `` once against this checkout and answer its bound value. */ -function* readCheckout(checkout: Checkout, options: RunOptions = {}): Operation { +function* readCheckout( + stream: InMemoryStream, + checkout: Checkout, + options: RunOptions = {}, +): Operation { const seen: Json[] = []; yield* runChecked( + stream, [checkoutOf(checkout.root), "", "", ""].join("\n"), checkout, { @@ -150,11 +168,13 @@ function requested(invocation: GitChangesInvocation): string { } describe("Ticket.Checkout — staged and unstaged reads", () => { + beforeEach(journalBeforeEach(OWNER)); it("starts both reads before either answers", function* () { + const stream = yield* useJournalStream(""); const checkout = yield* useCheckout("xmd-checkout-barrier"); const entered: string[] = []; const both = withResolvers(); - const value = yield* readCheckout(checkout, { + const value = yield* readCheckout(stream, checkout, { *around() { yield* GitQuery.around({ *changes(args, next): Operation { @@ -182,13 +202,17 @@ describe("Ticket.Checkout — staged and unstaged reads", () => { expect(value).toEqual(expected(checkout.run("rev-parse", "HEAD"), [], [])); }); - it("answers exact HEAD and tracked changes, fresh each time, leaving the index alone", function* () { + const statesCase = + "answers exact HEAD and tracked changes, fresh each time, leaving the index alone"; + it(statesCase, function* () { const checkout = yield* useCheckout("xmd-checkout-states"); const observe = function* (staged: Json[], unstaged: Json[]): Operation { - const index = yield* checkout.index(); - const value = yield* readCheckout(checkout); - expect(value).toEqual(expected(checkout.run("rev-parse", "HEAD"), staged, unstaged)); - expect(yield* checkout.index()).toBe(index); + yield* captureTestJournal({ owner: OWNER, name: statesCase }, "", function* (stream) { + const index = yield* checkout.index(); + const value = yield* readCheckout(stream, checkout); + expect(value).toEqual(expected(checkout.run("rev-parse", "HEAD"), staged, unstaged)); + expect(yield* checkout.index()).toBe(index); + }); }; yield* observe([], []); @@ -221,10 +245,12 @@ describe("Ticket.Checkout — staged and unstaged reads", () => { }); it("reads again after HEAD and the working tree move within one execution", function* () { + const stream = yield* useJournalStream(""); const checkout = yield* useCheckout("xmd-checkout-fresh"); const before = checkout.run("rev-parse", "HEAD"); const seen: Json[] = []; yield* runChecked( + stream, [ checkoutOf(checkout.root, "first"), "", @@ -258,11 +284,12 @@ describe("Ticket.Checkout — staged and unstaged reads", () => { }); it("refuses a checkout the ambient repository does not select", function* () { + const stream = yield* useJournalStream(""); const checkout = yield* useCheckout("xmd-checkout-ambient"); const foreign = yield* useCheckout("xmd-checkout-foreign"); let refusal: unknown; try { - yield* runChecked(checkoutOf(foreign.root), checkout); + yield* runChecked(stream, checkoutOf(foreign.root), checkout); } catch (error) { refusal = error; } @@ -276,14 +303,16 @@ describe("Ticket.Checkout — staged and unstaged reads", () => { }); describe("Ticket.Checkout — one owner for both reads", () => { + beforeEach(journalBeforeEach(OWNER)); it("reports a failed read only after its sibling's cleanup has finished", function* () { + const stream = yield* useJournalStream(""); const checkout = yield* useCheckout("xmd-checkout-failure"); const held = withResolvers(); const gate = withResolvers(); const order: string[] = []; const task = yield* spawn(function* () { try { - yield* readCheckout(checkout, { + yield* readCheckout(stream, checkout, { *around() { yield* GitQuery.around({ *changes(args, _next): Operation { @@ -319,13 +348,14 @@ describe("Ticket.Checkout — one owner for both reads", () => { }); it("does not finish halting until every held read has cleaned up", function* () { + const stream = yield* useJournalStream(""); const checkout = yield* useCheckout("xmd-checkout-cancel"); const entered: string[] = []; const both = withResolvers(); const gate = withResolvers(); const order: string[] = []; const task = yield* spawn(function* () { - yield* readCheckout(checkout, { + yield* readCheckout(stream, checkout, { *around() { yield* GitQuery.around({ *changes(args, _next): Operation { 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-target-execution.test.ts b/packages/core/tests/document-target-execution.test.ts index d30f000a4..e464b6d45 100644 --- a/packages/core/tests/document-target-execution.test.ts +++ b/packages/core/tests/document-target-execution.test.ts @@ -12,7 +12,13 @@ * not a position that merely looks unchanged. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, until } from "effection"; import type { Operation } from "effection"; @@ -55,6 +61,8 @@ import type { Json } from "../src/types.ts"; import { asText } from "./helpers.ts"; /** What every `` in a run reported, in the order it expanded. */ +const OWNER = "packages/core/tests/document-target-execution.test.ts"; + interface Probes { names: string[]; ids: string[]; @@ -166,13 +174,11 @@ const SECTIONS = [ ].join("\n"); describe("Tier TX — targeted execution", () => { + beforeEach(journalBeforeEach(OWNER)); it("TX1: only the preamble, the ancestors, and the subtree expand", function* () { + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; - const text = yield* run( - inlineSource(SECTIONS, { target: "Alpha/Inner" }), - new InMemoryStream(), - seen, - ); + const text = yield* run(inlineSource(SECTIONS, { target: "Alpha/Inner" }), stream, seen); expect(seen.names).toEqual(["pre", "title", "alpha", "inner"]); expect(text).toContain("# Title"); @@ -182,6 +188,7 @@ describe("Tier TX — targeted execution", () => { }); it("TX2: a skipped sibling's components and code blocks never run", function* () { + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; yield* scoped(function* () { yield* API.Process.around({ @@ -189,27 +196,37 @@ describe("Tier TX — targeted execution", () => { throw new Error(`a skipped code block ran: ${JSON.stringify(options.command)}`); }, }); - yield* run(inlineSource(SECTIONS, { target: "Alpha" }), new InMemoryStream(), seen); + yield* run(inlineSource(SECTIONS, { target: "Alpha" }), stream, seen); }); expect(seen.names).toEqual(["pre", "title", "alpha", "inner"]); }); it("TX3: selecting a non-leaf expands every descendant", function* () { + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; - yield* run(inlineSource(SECTIONS, { target: "Alpha" }), new InMemoryStream(), seen); + yield* run(inlineSource(SECTIONS, { target: "Alpha" }), stream, seen); expect(seen.names).toContain("inner"); }); - it("TX4: a retained element keeps the expansion ID it has in a full run", function* () { - const whole: Probes = { names: [], ids: [] }; - const targeted: Probes = { names: [], ids: [] }; - yield* run(inlineSource(SECTIONS), new InMemoryStream(), whole); - yield* run(inlineSource(SECTIONS, { target: "Beta" }), new InMemoryStream(), targeted); - - const idOf = (probes: Probes, name: string) => probes.ids[probes.names.indexOf(name)]; - expect(targeted.names).toEqual(["pre", "title", "beta"]); - expect(idOf(targeted, "beta")).toBe(idOf(whole, "beta")); - expect(idOf(targeted, "pre")).toBe(idOf(whole, "pre")); + const tx4Name = "TX4: a retained element keeps the expansion ID it has in a full run"; + it(tx4Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: tx4Name }, "", function* (firstStream) { + yield* captureTestJournal( + { owner: OWNER, name: tx4Name }, + "", + function* (secondStream) { + const whole: Probes = { names: [], ids: [] }; + const targeted: Probes = { names: [], ids: [] }; + yield* run(inlineSource(SECTIONS), firstStream, whole); + yield* run(inlineSource(SECTIONS, { target: "Beta" }), secondStream, targeted); + + const idOf = (probes: Probes, name: string) => probes.ids[probes.names.indexOf(name)]; + expect(targeted.names).toEqual(["pre", "title", "beta"]); + expect(idOf(targeted, "beta")).toBe(idOf(whole, "beta")); + expect(idOf(targeted, "pre")).toBe(idOf(whole, "pre")); + }, + ); + }); }); /** @@ -218,33 +235,54 @@ describe("Tier TX — targeted execution", () => { * full run — and seeding identity with the target string would break all * three at once. */ - it("TX5: two different targets agree on a shared retained element", function* () { - const alpha: Probes = { names: [], ids: [] }; - const beta: Probes = { names: [], ids: [] }; - yield* run(inlineSource(SECTIONS, { target: "Alpha" }), new InMemoryStream(), alpha); - yield* run(inlineSource(SECTIONS, { target: "Beta" }), new InMemoryStream(), beta); - expect(beta.ids[beta.names.indexOf("title")]).toBe(alpha.ids[alpha.names.indexOf("title")]); + const tx5Name = "TX5: two different targets agree on a shared retained element"; + it(tx5Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: tx5Name }, "", function* (firstStream) { + yield* captureTestJournal( + { owner: OWNER, name: tx5Name }, + "", + function* (secondStream) { + const alpha: Probes = { names: [], ids: [] }; + const beta: Probes = { names: [], ids: [] }; + yield* run(inlineSource(SECTIONS, { target: "Alpha" }), firstStream, alpha); + yield* run(inlineSource(SECTIONS, { target: "Beta" }), secondStream, beta); + expect(beta.ids[beta.names.indexOf("title")]).toBe( + alpha.ids[alpha.names.indexOf("title")], + ); + }, + ); + }); }); - it("TX6: a file root and an inline root behave identically", function* () { - const workspace = yield* useWorkspace({ "doc.md": SECTIONS }); - const fromFile: Probes = { names: [], ids: [] }; - const fromText: Probes = { names: [], ids: [] }; - const fileText = yield* run( - fileSource(formatDocumentReference(join(workspace, "doc.md"), "Beta")), - new InMemoryStream(), - fromFile, - ); - const inlineText = yield* run( - inlineSource(SECTIONS, { target: "Beta" }), - new InMemoryStream(), - fromText, - ); - expect(fromFile.names).toEqual(fromText.names); - expect(fileText).toBe(inlineText); + const tx6Name = "TX6: a file root and an inline root behave identically"; + it(tx6Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: tx6Name }, "", function* (secondStream) { + const workspace = yield* useWorkspace({ "doc.md": SECTIONS }); + yield* captureTestJournal( + { owner: OWNER, name: tx6Name }, + formatDocumentReference(join(workspace, "doc.md"), "Beta"), + function* (firstStream) { + const fromFile: Probes = { names: [], ids: [] }; + const fromText: Probes = { names: [], ids: [] }; + const fileText = yield* run( + fileSource(formatDocumentReference(join(workspace, "doc.md"), "Beta")), + firstStream, + fromFile, + ); + const inlineText = yield* run( + inlineSource(SECTIONS, { target: "Beta" }), + secondStream, + fromText, + ); + expect(fromFile.names).toEqual(fromText.names); + expect(fileText).toBe(inlineText); + }, + ); + }); }); it("TX7: root props and frontmatter apply to the projected body", function* () { + const stream = yield* useJournalStream(""); const body = [ "---", "title: Doc", @@ -267,7 +305,7 @@ describe("Tier TX — targeted execution", () => { const text = yield* scoped(function* () { const execution = yield* execute({ ...inlineSource(body, { target: "Greeting" }), - stream: new InMemoryStream(), + stream, props: { who: "world" }, }); return asText(yield* collect(execution)); @@ -278,6 +316,7 @@ describe("Tier TX — targeted execution", () => { }); it("TX8: a value root returns from the projected body", function* () { + const stream = yield* useJournalStream(""); const body = [ "---", "returns:", @@ -297,13 +336,14 @@ describe("Tier TX — targeted execution", () => { const value = yield* collect( yield* execute({ ...inlineSource(body, { target: "Kept" }), - stream: new InMemoryStream(), + stream, }), ); expect(value).toEqual({ picked: "kept" }); }); it("TX9: `` in the projected body selects what is emitted", function* () { + const stream = yield* useJournalStream(""); const body = [ "# Title", "", @@ -322,7 +362,7 @@ describe("Tier TX — targeted execution", () => { yield* collect( yield* execute({ ...inlineSource(body, { target: "Kept" }), - stream: new InMemoryStream(), + stream, }), ), ); @@ -334,6 +374,7 @@ describe("Tier TX — targeted execution", () => { * caller did not select is not a violation of what runs. */ it("TX10: an invalid structure in a skipped sibling is irrelevant", function* () { + const stream = yield* useJournalStream(""); const body = [ "# Title", "", @@ -347,13 +388,14 @@ describe("Tier TX — targeted execution", () => { "", ].join("\n"); const seen: Probes = { names: [], ids: [] }; - const text = yield* run(inlineSource(body, { target: "Kept" }), new InMemoryStream(), seen); + const text = yield* run(inlineSource(body, { target: "Kept" }), stream, seen); expect(seen.names).toEqual(["kept"]); expect(text).toContain("kept body"); expect(text).not.toContain(" requires"); }); it("TX11: an invalid structure in the retained range fails before any effect", function* () { + const stream = yield* useJournalStream(""); const body = [ "# Title", "", @@ -365,11 +407,7 @@ describe("Tier TX — targeted execution", () => { "", ].join("\n"); const seen: Probes = { names: [], ids: [] }; - const error = yield* failure( - inlineSource(body, { target: "Kept" }), - new InMemoryStream(), - seen, - ); + const error = yield* failure(inlineSource(body, { target: "Kept" }), stream, seen); expect(seen.names).toEqual([]); expect(error instanceof Error ? error.message : String(error)).toContain(" requires"); }); @@ -382,7 +420,7 @@ describe("Tier TX — targeted execution", () => { * inspection is where a host resolves a selector before running anything. */ it("TX12: a target that resolves to nothing runs no authored effect", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; const error = yield* failure(inlineSource(SECTIONS, { target: "Missing" }), stream, seen); expect(isDocumentTargetError(error)).toBe(true); @@ -399,7 +437,7 @@ describe("Tier TX — targeted execution", () => { }); it("TX13: an ambiguous target runs no authored effect", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; const error = yield* failure(inlineSource(SECTIONS, { target: "**" }), stream, seen); expect(asDocumentTargetError(error)?.data.kind).toBe("multiple-matches"); @@ -419,8 +457,9 @@ describe("Tier TX — targeted execution", () => { }); describe("Tier TX — targeted replay", () => { + beforeEach(journalBeforeEach(OWNER)); it("TX15: the journal records the exact target, never the glob", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; yield* run(inlineSource(SECTIONS, { target: "**/I*" }), stream, seen); @@ -432,7 +471,7 @@ describe("Tier TX — targeted replay", () => { }); it("TX16: an untargeted run records no target member at all", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); yield* run(inlineSource(SECTIONS), stream, { names: [], ids: [] }); const recorded = rootImports(stream)[0]; expect(recorded?.result.status).toBe("ok"); @@ -1153,6 +1192,7 @@ describe("Tier TX — one read across check and replay", () => { * its own invocation proves the section did not execute. */ describe("Tier TX — preamble boundary", () => { + beforeEach(journalBeforeEach(OWNER)); const OPENS_DEEP = [ "## Before", "", @@ -1169,20 +1209,18 @@ describe("Tier TX — preamble boundary", () => { ].join("\n"); it("TX44: selecting the later section never executes the earlier one", function* () { + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; - const text = yield* run( - inlineSource(OPENS_DEEP, { target: "After" }), - new InMemoryStream(), - seen, - ); + const text = yield* run(inlineSource(OPENS_DEEP, { target: "After" }), stream, seen); expect(seen.names).toEqual(["title", "after"]); expect(text).not.toContain("## Before"); expect(text).not.toContain("before body"); }); it("TX45: the earlier section still runs when it is the target", function* () { + const stream = yield* useJournalStream(""); const seen: Probes = { names: [], ids: [] }; - yield* run(inlineSource(OPENS_DEEP, { target: "Before" }), new InMemoryStream(), seen); + yield* run(inlineSource(OPENS_DEEP, { target: "Before" }), stream, seen); expect(seen.names).toEqual(["before"]); }); }); @@ -1572,6 +1610,7 @@ describe("Tier TX — detached values stay mutable", () => { * same whether a host inspects, runs, or resumes. */ describe("Tier TX — target resolution precedes schema compilation", () => { + beforeEach(journalBeforeEach(OWNER)); const BROKEN_SCHEMA = [ "---", "props:", @@ -1637,13 +1676,14 @@ describe("Tier TX — target resolution precedes schema compilation", () => { }); it("TX67: the control — a resolvable target and a valid schema run", function* () { + const stream = yield* useJournalStream(""); const info = yield* inspectDocument(inlineSource(GOOD_SCHEMA, { target: "Kept" })); expect(info.target).toBe("Kept"); const text = asText( yield* collect( yield* execute({ ...inlineSource(GOOD_SCHEMA, { target: "Kept" }), - stream: new InMemoryStream(), + stream, }), ), ); @@ -2079,6 +2119,7 @@ describe("Tier TX — guards observe a copy, not the retained history", () => { * is being measured is what reaches live coordination after every wrapper. */ describe("Tier TX — journal provenance across the admission gate", () => { + beforeEach(journalBeforeEach(OWNER)); /** What a live durable operation's coordinator was handed. */ interface Coordinated { witnesses: (JournalProvenance | undefined)[]; @@ -2151,7 +2192,7 @@ describe("Tier TX — journal provenance across the admission gate", () => { } it("TX78: an untargeted run delivers the selected journal's exact witness", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const witness = establishJournalProvenance(stream); const seen = yield* observing(stream, inlineSource(LIVE)); expect(seen.witnesses.length).toBeGreaterThan(0); @@ -2161,7 +2202,7 @@ describe("Tier TX — journal provenance across the admission gate", () => { }); it("TX79: a targeted run delivers the same exact witness", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const witness = establishJournalProvenance(stream); const seen = yield* observing(stream, inlineSource(LIVE, { target: "Alpha" })); expect(seen.witnesses.length).toBeGreaterThan(0); @@ -2183,7 +2224,7 @@ describe("Tier TX — journal provenance across the admission gate", () => { }); it("TX81: an unproven journal stays unproven through both wrappers", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const seen = yield* observing(stream, inlineSource(LIVE, { target: "Alpha" })); expect(seen.witnesses.length).toBeGreaterThan(0); for (const observed of seen.witnesses) { 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/execution-protocol.test.ts b/packages/core/tests/execution-protocol.test.ts index 9857d2c34..e74e82ff3 100644 --- a/packages/core/tests/execution-protocol.test.ts +++ b/packages/core/tests/execution-protocol.test.ts @@ -13,7 +13,13 @@ * in name only. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { createContext, @@ -60,6 +66,8 @@ import { executeObserved } from "../src/execute.ts"; import type { InvocationObservers } from "../src/execute.ts"; import type { DurablePreparation, ExecutionInstallation, JournalAdmission } from "../host.ts"; +const OWNER = "packages/core/tests/execution-protocol.test.ts"; + const DOC = "# Hello\n"; /** A document that fails on its own terms, under error mode. */ @@ -148,21 +156,24 @@ const PROPS_DOC = [ ].join("\n"); describe("Tier EP — the execution protocol", () => { + beforeEach(journalBeforeEach(OWNER)); it("EP1: an ordinary execute() with nothing installed still runs the document", function* () { + const stream = yield* useJournalStream(""); const output = yield* scoped(function* () { - return yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(String(output)).toContain("Hello"); }); it("EP2: an option transformation reaches the document", function* () { + const stream = yield* useJournalStream(""); const output = yield* scoped(function* () { yield* Execution.around({ *execute([request], next) { yield* next(request.withOptions({ ...request.options, ...inlineSource("# Replaced\n") })); }, }); - return yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(String(output)).toContain("Replaced"); expect(String(output)).not.toContain("Hello"); @@ -191,6 +202,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP4: a substitute return after delegating is ignored", function* () { + const stream = yield* useJournalStream(""); // Typed as returning something, which the canonical surface no longer // permits — so this is written the only way it can still happen: through a // same-named descriptor whose own types allow it. @@ -212,7 +224,7 @@ describe("Tier EP — the execution protocol", () => { return { output: undefined, [Symbol.iterator]: () => undefined }; }, }); - return yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(String(output)).toContain("Hello"); }); @@ -240,6 +252,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP6: delegating twice fails", function* () { + const stream = yield* useJournalStream(""); const failure = yield* scoped(function* () { yield* Execution.around({ *execute([request], next) { @@ -247,36 +260,45 @@ describe("Tier EP — the execution protocol", () => { yield* next(request); }, }); - return yield* raised(execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* raised(execute({ ...inlineSource(DOC), stream })); }); expect(failure).toBeInstanceOf(ExecutionProtocolError); expect(String(failure)).toContain("more than once"); }); - it("EP7: reusing a request a previous execution consumed fails", function* () { - const captured: ExecutionRequest[] = []; - yield* scoped(function* () { - yield* Execution.around({ - *execute([request], next) { - captured.push(request); - yield* next(request); - }, - }); - yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); - }); + const ep7Name = "EP7: reusing a request a previous execution consumed fails"; + it(ep7Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: ep7Name }, "", function* (firstStream) { + yield* captureTestJournal( + { owner: OWNER, name: ep7Name }, + "", + function* (secondStream) { + const captured: ExecutionRequest[] = []; + yield* scoped(function* () { + yield* Execution.around({ + *execute([request], next) { + captured.push(request); + yield* next(request); + }, + }); + yield* collect(yield* execute({ ...inlineSource(DOC), stream: firstStream })); + }); - const stale = captured[0]; - expect(stale).toBeDefined(); - const failure = yield* scoped(function* () { - yield* Execution.around({ - *execute([,], next) { - // Delegating the *previous* execution's request. - yield* next(stale!); + const stale = captured[0]; + expect(stale).toBeDefined(); + const failure = yield* scoped(function* () { + yield* Execution.around({ + *execute([,], next) { + // Delegating the *previous* execution's request. + yield* next(stale!); + }, + }); + return yield* raised(execute({ ...inlineSource(DOC), stream: secondStream })); + }); + expect(failure).toBeInstanceOf(ExecutionProtocolError); }, - }); - return yield* raised(execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + ); }); - expect(failure).toBeInstanceOf(ExecutionProtocolError); }); it("EP8: delegating a reconstructed look-alike fails", function* () { @@ -303,6 +325,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP9: delegating a request a later withOptions() superseded fails", function* () { + const stream = yield* useJournalStream(""); const failure = yield* scoped(function* () { yield* Execution.around({ *execute([request], next) { @@ -311,13 +334,14 @@ describe("Tier EP — the execution protocol", () => { yield* next(request); }, }); - return yield* raised(execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* raised(execute({ ...inlineSource(DOC), stream })); }); expect(failure).toBeInstanceOf(ExecutionProtocolError); expect(String(failure)).toContain("superseded"); }); it("EP10: middleware from another loaded copy inspects, transforms and delegates", function* () { + const stream = yield* useJournalStream(""); const seen: string[] = []; // A descriptor of the same stable name, built here rather than imported — // which is what a separately loaded copy of core is. @@ -335,7 +359,7 @@ describe("Tier EP — the execution protocol", () => { yield* next(request.withOptions({ ...request.options, ...inlineSource("# Foreign\n") })); }, }); - return yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(seen).toEqual(["object"]); @@ -441,6 +465,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP21: the exported default refuses and consumes nothing", function* () { + const stream = yield* useJournalStream(""); const captured: ExecutionRequest[] = []; const output = yield* scoped(function* () { let reentered = false; @@ -463,7 +488,7 @@ describe("Tier EP — the execution protocol", () => { yield* next(request); }, }); - return yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(String(output)).toContain("Hello"); @@ -506,37 +531,46 @@ describe("Tier EP — the execution protocol", () => { // EP23: contextual behavior an installation establishes is the invocation's. // It has to reach document teardown, stay out of a concurrent invocation, and // be gone from the next ordinary execution in the same host scope. - it("EP23: invocation-installed context reaches teardown and leaks nowhere", function* () { - const Marker = createContext("tier-ep.marker", undefined); - const seen: string[] = []; + const ep23Name = "EP23: invocation-installed context reaches teardown and leaks nowhere"; + it(ep23Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: ep23Name }, "", function* (firstStream) { + yield* captureTestJournal( + { owner: OWNER, name: ep23Name }, + "", + function* (secondStream) { + const Marker = createContext("tier-ep.marker", undefined); + const seen: string[] = []; + + yield* scoped(function* () { + yield* Execution.around({ + *document([props], next) { + seen.push(`document:${(yield* Marker.get()) ?? "absent"}`); + try { + return yield* next(props); + } finally { + seen.push("teardown"); + } + }, + }); - yield* scoped(function* () { - yield* Execution.around({ - *document([props], next) { - seen.push(`document:${(yield* Marker.get()) ?? "absent"}`); - try { - return yield* next(props); - } finally { - seen.push("teardown"); - } - }, - }); + yield* collect( + yield* executeInstalled({ ...inlineSource(DOC), stream: firstStream }, [ + { + *install(): Operation { + yield* Marker.set("installed"); + }, + }, + ]), + ); - yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ - { - *install(): Operation { - yield* Marker.set("installed"); - }, - }, - ]), - ); + // A later ordinary execution in the same host scope must not inherit it. + yield* collect(yield* execute({ ...inlineSource(DOC), stream: secondStream })); + }); - // A later ordinary execution in the same host scope must not inherit it. - yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); + expect(seen).toEqual(["document:installed", "teardown", "document:absent", "teardown"]); + }, + ); }); - - expect(seen).toEqual(["document:installed", "teardown", "document:absent", "teardown"]); }); // EP24: settlement owns the invocation scope. A caller that continues on the @@ -615,21 +649,19 @@ describe("Tier EP — the execution protocol", () => { }); it("EP24c: a completed handle can be re-observed without refinalizing", function* () { + const stream = yield* useJournalStream(""); const finalized: string[] = []; const results = yield* scoped(function* () { - const execution = yield* executeInstalled( - { ...inlineSource(DOC), stream: new InMemoryStream() }, - [ - { - *install(): Operation { - yield* ensure(() => { - finalized.push("cleanup"); - }); - }, + const execution = yield* executeInstalled({ ...inlineSource(DOC), stream }, [ + { + *install(): Operation { + yield* ensure(() => { + finalized.push("cleanup"); + }); }, - ], - ); + }, + ]); const first = yield* execution; const second = yield* execution; // Late subscription still replays the whole output. @@ -646,6 +678,7 @@ describe("Tier EP — the execution protocol", () => { // the task that is halted never started the execution — nothing but the handle // connects them. it("EP25: halting a consumer of a returned handle cancels the invocation", function* () { + const stream = yield* useJournalStream(""); const finalized: string[] = []; const halted: string[] = []; const reached = withResolvers(); @@ -666,7 +699,7 @@ describe("Tier EP — the execution protocol", () => { const observing = withResolvers(); const execution = yield* executeObserved( - { ...inlineSource(DOC), stream: new InMemoryStream() }, + { ...inlineSource(DOC), stream }, [ { *install(): Operation { @@ -1260,7 +1293,7 @@ describe("Tier EP — the execution protocol", () => { * gave, and asking again adds neither output nor terminal. */ it("EP30: a host Stop reaches a running document, joins its cleanup and retains one cancelled close", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(""); const reached = withResolvers(); const waiting = withResolvers(); const releaseCleanup = withResolvers(); @@ -1565,6 +1598,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP11: admissions are copied before install() runs", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; const late: JournalAdmission[] = []; const installation: ExecutionInstallation = { @@ -1580,17 +1614,14 @@ describe("Tier EP — the execution protocol", () => { }; yield* scoped(function* () { - yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ - installation, - ]), - ); + yield* collect(yield* executeInstalled({ ...inlineSource(DOC), stream }, [installation])); }); expect(order).toEqual(["install"]); }); it("EP12: every captured admission runs, in order, on the retained history", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; const seen: number[] = []; const admission = (name: string): JournalAdmission => @@ -1602,7 +1633,7 @@ describe("Tier EP — the execution protocol", () => { yield* scoped(function* () { yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ + yield* executeInstalled({ ...inlineSource(DOC), stream }, [ { admissions: [admission("first")] }, { admissions: [admission("second")] }, ]), @@ -1713,6 +1744,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP15: a completion policy cannot replace an existing failure", function* () { + const stream = yield* useJournalStream(""); const asked: string[] = []; const result = yield* scoped(function* () { yield* Execution.around({ @@ -1728,7 +1760,7 @@ describe("Tier EP — the execution protocol", () => { // its own terms. return yield* yield* execute({ ...inlineSource("---\nreturns:\n type: object\n---\n\nbody\n"), - stream: new InMemoryStream(), + stream, }); }); @@ -1740,6 +1772,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP16: an additive failure still converts a success", function* () { + const stream = yield* useJournalStream(""); const result = yield* scoped(function* () { yield* Execution.around({ *execute([request], next) { @@ -1747,7 +1780,7 @@ describe("Tier EP — the execution protocol", () => { yield* next(request); }, }); - return yield* yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }); + return yield* yield* execute({ ...inlineSource(DOC), stream }); }); expect(result.ok).toBe(false); @@ -1755,6 +1788,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP17: the first policy to fail wins, and later ones do not replace it", function* () { + const stream = yield* useJournalStream(""); const asked: string[] = []; const result = yield* scoped(function* () { yield* Execution.around({ @@ -1770,7 +1804,7 @@ describe("Tier EP — the execution protocol", () => { yield* next(request); }, }); - return yield* yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }); + return yield* yield* execute({ ...inlineSource(DOC), stream }); }); expect(result.ok).toBe(false); @@ -1782,6 +1816,7 @@ describe("Tier EP — the execution protocol", () => { }); it("EP14: the obsolete ambient admission channel does not exist", function* () { + const stream = yield* useJournalStream(""); const ran: string[] = []; // The exact channel a previous revision used, rebuilt by name and cleared — // before the invocation and again from inside the middleware chain. There @@ -1797,7 +1832,7 @@ describe("Tier EP — the execution protocol", () => { }, }); yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ + yield* executeInstalled({ ...inlineSource(DOC), stream }, [ { admissions: [ // deno-lint-ignore require-yield @@ -1906,8 +1941,9 @@ describe("Tier DP — the document protocol", () => { } describe("lineage", () => { + beforeEach(journalBeforeEach(OWNER)); it("DP1: a handler that answers without delegating is refused, and nothing is authored", function* () { - const journal = new InMemoryStream(); + const journal = yield* useJournalStream(""); const expanded: string[] = []; const failure = yield* scoped(function* () { yield* useMark(expanded); @@ -1930,6 +1966,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP2: a substitute return after delegating is ignored", function* () { + const stream = yield* useJournalStream(""); const output = yield* scoped(function* () { yield* loose().around({ *document([request], next) { @@ -1937,28 +1974,30 @@ describe("Tier DP — the document protocol", () => { return { status: "ok", output: "SUBSTITUTE", value: "SUBSTITUTE" }; }, }); - return yield* collect( - yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }), - ); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(String(output)).toContain("Hello"); expect(String(output)).not.toContain("SUBSTITUTE"); }); it("DP3: props replaced through withProps() are the ones the document runs on", function* () { + const stream = yield* useJournalStream(""); const output = yield* scoped(function* () { yield* useMutate(() => {}); yield* Execution.around({ *document([request], next) { yield* next( - request.withProps({ nested: { value: "replaced-value" }, items: ["replaced-item"] }), + request.withProps({ + nested: { value: "replaced-value" }, + items: ["replaced-item"], + }), ); }, }); return yield* collect( yield* execute({ ...inlineSource(PROPS_DOC), - stream: new InMemoryStream(), + stream, props: { nested: { value: "original" }, items: ["original-item"] }, }), ); @@ -1968,7 +2007,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP4: a second delegation adds no second expansion to the first one's work", function* () { - const journal = new InMemoryStream(); + const journal = yield* useJournalStream(""); const expanded: string[] = []; const result = yield* scoped(function* () { yield* useMark(expanded); @@ -1992,6 +2031,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP5: a request a later withProps() superseded is refused", function* () { + const stream = yield* useJournalStream(""); const failure = yield* scoped(function* () { yield* Execution.around({ *document([request], next) { @@ -1999,9 +2039,7 @@ describe("Tier DP — the document protocol", () => { yield* next(request); }, }); - return yield* raised( - collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })), - ); + return yield* raised(collect(yield* execute({ ...inlineSource(DOC), stream }))); }); expect(failure).toBeInstanceOf(DocumentProtocolError); expect(String(failure)).toContain("superseded"); @@ -2047,35 +2085,45 @@ describe("Tier DP — the document protocol", () => { } }); - it("DP7: a stale request is refused after the expansion it belonged to is over", function* () { - const held = withResolvers(); - yield* scoped(function* () { - yield* Execution.around({ - *document([request], next) { - held.resolve(request); - yield* next(request); - }, - }); - yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })); - }); + const dp7Name = "DP7: a stale request is refused after the expansion it belonged to is over"; + it(dp7Name, function* () { + yield* captureTestJournal({ owner: OWNER, name: dp7Name }, "", function* (firstStream) { + yield* captureTestJournal( + { owner: OWNER, name: dp7Name }, + "", + function* (secondStream) { + const held = withResolvers(); + yield* scoped(function* () { + yield* Execution.around({ + *document([request], next) { + held.resolve(request); + yield* next(request); + }, + }); + yield* collect(yield* execute({ ...inlineSource(DOC), stream: firstStream })); + }); - // The same request, offered to a *later* invocation's terminal. - const stale = yield* held.operation; - const failure = yield* scoped(function* () { - yield* Execution.around({ - *document([,], next) { - yield* next(stale); + // The same request, offered to a *later* invocation's terminal. + const stale = yield* held.operation; + const failure = yield* scoped(function* () { + yield* Execution.around({ + *document([,], next) { + yield* next(stale); + }, + }); + return yield* raised( + collect(yield* execute({ ...inlineSource(DOC), stream: secondStream })), + ); + }); + expect(failure).toBeInstanceOf(DocumentProtocolError); + expect(String(failure)).toContain("another expansion"); }, - }); - return yield* raised( - collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })), ); }); - expect(failure).toBeInstanceOf(DocumentProtocolError); - expect(String(failure)).toContain("another expansion"); }); it("DP8: middleware from another loaded copy composes and delegates", function* () { + const stream = yield* useJournalStream(""); const seen: string[] = []; const foreign: Api<{ document(request: DocumentRequest): Operation }> = createApi( "Execution", @@ -2091,9 +2139,7 @@ describe("Tier DP — the document protocol", () => { yield* next(request); }, }); - return yield* collect( - yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }), - ); + return yield* collect(yield* execute({ ...inlineSource(DOC), stream })); }); expect(seen).toEqual(["object"]); expect(String(output)).toContain("Hello"); @@ -2144,6 +2190,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP10: the exported default refuses a live request and consumes nothing", function* () { + const stream = yield* useJournalStream(""); const captured = withResolvers(); const proceed = withResolvers(); @@ -2158,9 +2205,7 @@ describe("Tier DP — the document protocol", () => { yield* next(request); }, }); - return String( - yield* collect(yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() })), - ); + return String(yield* collect(yield* execute({ ...inlineSource(DOC), stream }))); }); }); @@ -2177,7 +2222,9 @@ describe("Tier DP — the document protocol", () => { }); describe("detached props", () => { + beforeEach(journalBeforeEach(OWNER)); it("DP11: props accepted by the terminal are detached from the caller's containers", function* () { + const stream = yield* useJournalStream(""); const nested = { value: "accepted-value" }; const items = ["accepted-item"]; const edited: string[] = []; @@ -2205,7 +2252,7 @@ describe("Tier DP — the document protocol", () => { yield* collect( yield* execute({ ...inlineSource(PROPS_DOC), - stream: new InMemoryStream(), + stream, props: { nested: { value: "unused" }, items: ["unused"] }, }), ), @@ -2397,6 +2444,7 @@ describe("Tier DP — the document protocol", () => { }); describe("canonical outcome versus later policy", () => { + beforeEach(journalBeforeEach(OWNER)); it("DP15: a canonical outcome and a later policy failure are ranked, not replaced", function* () { const durable = new DurablePersistenceError("yield", new Error("planted-canonical")); const laterDurable = new DurablePersistenceError("close", new Error("planted-policy")); @@ -2513,6 +2561,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP16: cleanup finishes exactly once before a reconciled result is observable", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; const result = yield* scoped(function* () { yield* Execution.around({ @@ -2525,7 +2574,7 @@ describe("Tier DP — the document protocol", () => { throw new Error("POST-DELEGATION-POLICY"); }, }); - const execution = yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }); + const execution = yield* execute({ ...inlineSource(DOC), stream }); const settled = yield* execution; order.push("observed"); return settled; @@ -2536,6 +2585,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP17: cancelling during document policy keeps structured teardown", function* () { + const stream = yield* useJournalStream(""); const entered = withResolvers(); const finalized: string[] = []; @@ -2550,7 +2600,7 @@ describe("Tier DP — the document protocol", () => { }, }); - const execution = yield* execute({ ...inlineSource(DOC), stream: new InMemoryStream() }); + const execution = yield* execute({ ...inlineSource(DOC), stream }); const consumer = yield* spawn(function* () { return yield* execution; }); @@ -2567,6 +2617,7 @@ describe("Tier DP — the document protocol", () => { }); describe("trusted durable preparation", () => { + beforeEach(journalBeforeEach(OWNER)); /** A preparation that records that it ran, and nothing durable. */ function marking(order: string[], name: string): DurablePreparation { // deno-lint-ignore require-yield @@ -2598,6 +2649,7 @@ describe("Tier DP — the document protocol", () => { } it("DP18: prepare is read once, by value, before any install() runs", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; let reads = 0; const installation: ExecutionInstallation = { @@ -2619,11 +2671,7 @@ describe("Tier DP — the document protocol", () => { }); yield* scoped(function* () { - yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ - installation, - ]), - ); + yield* collect(yield* executeInstalled({ ...inlineSource(DOC), stream }, [installation])); }); expect(reads).toEqual(1); @@ -2631,10 +2679,11 @@ describe("Tier DP — the document protocol", () => { }); it("DP19: preparations run in installation order", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; yield* scoped(function* () { yield* collect( - yield* executeInstalled({ ...inlineSource(DOC), stream: new InMemoryStream() }, [ + yield* executeInstalled({ ...inlineSource(DOC), stream }, [ { prepare: marking(order, "first") }, { install: () => marking(order, "installed")() }, { prepare: marking(order, "second") }, @@ -2732,6 +2781,7 @@ describe("Tier DP — the document protocol", () => { }); it("DP21: admission precedes preparation, which precedes policy and the root import", function* () { + const stream = yield* useJournalStream(""); const order: string[] = []; const expanded: string[] = []; yield* scoped(function* () { @@ -2743,7 +2793,7 @@ describe("Tier DP — the document protocol", () => { }, }); yield* collect( - yield* executeInstalled({ ...inlineSource("\n"), stream: new InMemoryStream() }, [ + yield* executeInstalled({ ...inlineSource("\n"), stream }, [ { admissions: [ // deno-lint-ignore require-yield diff --git a/packages/core/tests/expand.test.ts b/packages/core/tests/expand.test.ts index 98712d705..464914278 100644 --- a/packages/core/tests/expand.test.ts +++ b/packages/core/tests/expand.test.ts @@ -5,7 +5,13 @@ import { useTempDirectory } from "@executablemd/test-support/temp"; import { realpath } from "node:fs/promises"; import { join } from "node:path"; import { registerComponents } from "../src/components/registration.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, spawn, until, withResolvers } from "effection"; import type { Subscription } from "effection"; @@ -2168,11 +2174,15 @@ describe("993 nested selection and private renderings", () => { } }); +const OWNER = "packages/core/tests/expand.test.ts"; + describe("993 exported projection helpers with production eval", () => { + beforeEach(journalBeforeEach(OWNER)); for (const helper of ["renderChildren", "useContent", "render"]) { for (const terminal of helper === "renderChildren" ? ["eval", "persist eval"] : ["eval"]) { for (const sameBlock of [true, false]) { it(`${helper} (${terminal}): ${sameBlock ? "same-block control" : "exported helper called in a later block"}`, function* () { + const stream = yield* useJournalStream("root.md"); yield* useTempFileCompiler(); yield* useNormalizedOutput(); const call = helper === "render" ? 'render("sel")' : `${helper}()`; @@ -2197,7 +2207,6 @@ describe("993 exported projection helpers with production eval", () => { : "Documentation.documentationsel", "components/Render.md": body, }); - const stream = new InMemoryStream(); const output = asText(yield* collect(yield* execute({ path: "root.md", stream }))); expect(output.trim()).toBe(helper === "render" ? "" : "[sel]"); const evals = stream @@ -2312,40 +2321,45 @@ ${pwd} } }); - it("C52: each projection captures its own sibling Dir placement", function* () { + const placement = "C52: each projection captures its own sibling Dir placement"; + it(placement, function* () { const root = yield* until(realpath(yield* useTempDirectory("content-dirs-"))); - yield* ensureDir(join(root, "components")); - yield* writeTextFile( - join(root, "components", "Twice.md"), - '\n', - ); - const observed: string[] = []; - yield* API.Env.around( - { - *cwd() { - return root; - }, - }, - { at: "min" }, - ); - yield* useHostFiles(); - yield* registerComponents([ - { - name: "Here", - origin: "test://content-dirs", - props: { type: "object", properties: {} }, - *fn() { - observed.push(yield* cwd()); - return ""; - }, + yield* captureTestJournal( + { owner: OWNER, name: placement }, + join(root, "doc.md"), + function* (stream) { + yield* ensureDir(join(root, "components")); + yield* writeTextFile( + join(root, "components", "Twice.md"), + '\n', + ); + const observed: string[] = []; + yield* API.Env.around( + { + *cwd() { + return root; + }, + }, + { at: "min" }, + ); + yield* useHostFiles(); + yield* registerComponents([ + { + name: "Here", + origin: "test://content-dirs", + props: { type: "object", properties: {} }, + *fn() { + observed.push(yield* cwd()); + return ""; + }, + }, + ]); + const path = join(root, "doc.md"); + yield* writeTextFile(path, "\n"); + yield* collect(yield* execute({ path, includes: [join(root, "components")], stream })); + expect(observed).toEqual([join(root, "first"), join(root, "second"), root]); + expect(yield* cwd()).toBe(root); }, - ]); - const path = join(root, "doc.md"); - yield* writeTextFile(path, "\n"); - yield* collect( - yield* execute({ path, includes: [join(root, "components")], stream: new InMemoryStream() }), ); - expect(observed).toEqual([join(root, "first"), join(root, "second"), root]); - expect(yield* cwd()).toBe(root); }); }); 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/filesystem-placement.test.ts b/packages/core/tests/filesystem-placement.test.ts index 2ff647495..03df34e79 100644 --- a/packages/core/tests/filesystem-placement.test.ts +++ b/packages/core/tests/filesystem-placement.test.ts @@ -1,5 +1,6 @@ import { Permissions } from "@executablemd/runtime"; -import { describe, it } from "@executablemd/test-support/bdd"; +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 { admitDocumentHostPath, authoredOperation } from "../src/filesystem-placement.ts"; import { R1_WIN32 } from "../../test-support/mount-fixture.ts"; @@ -32,11 +33,14 @@ import { Component } from "../src/component-api.ts"; import { executeInstalled } from "../host.ts"; import { workspaceMountInstallation } from "../../cli/src/repl/workspace-mount-installation.ts"; import { mountPolicy } from "../../cli/src/repl/mount-files.ts"; -import { InMemoryStream } from "@executablemd/durable-streams"; + +const OWNER = "packages/core/tests/filesystem-placement.test.ts"; import { ordinaryGeneratedSelection } from "../../cli/src/evaluation-profile.ts"; describe("mapped canonical component expansion", () => { + beforeEach(journalBeforeEach(OWNER)); it("delivers actual cwd to all existing consumers and follows the authored parent", function* () { + const stream = yield* useJournalStream(""); const seen: unknown[] = []; yield* API.Env.around( { @@ -98,10 +102,9 @@ describe("mapped canonical component expansion", () => { '', ].join("\n"); yield* collect( - yield* executeInstalled( - { ...inlineSource(source), includes: [], stream: new InMemoryStream() }, - [workspaceMountInstallation([{ source: "/work/manuals/docs", target: "/reference" }])], - ), + yield* executeInstalled({ ...inlineSource(source), includes: [], stream: stream }, [ + workspaceMountInstallation([{ source: "/work/manuals/docs", target: "/reference" }]), + ]), ); expect(seen).toContainEqual(["ensure", { cwd: "/work/manuals/docs", path: "/" }]); expect(seen).toContainEqual(["read", { cwd: "/", path: "next.md" }]); @@ -121,6 +124,7 @@ describe("mapped canonical component expansion", () => { expect(yield* cwd()).toBe("/host"); }); it("rejects R1-WIN32 before any ensure or child and preserves the ordinary '..' case", function* () { + const stream = yield* useJournalStream(""); const f = R1_WIN32; const policy = mountPolicy([{ source: f.source, target: f.target }], "C:\\host", "win32"); const entered = policy.prepareDirectory( @@ -169,7 +173,7 @@ describe("mapped canonical component expansion", () => { { ...inlineSource(``), includes: [], - stream: new InMemoryStream(), + stream: stream, }, [installation], ), @@ -181,6 +185,7 @@ describe("mapped canonical component expansion", () => { expect(calls).toBe(0); }); it("carries the private frame through generated File forms", function* () { + const stream = yield* useJournalStream(""); const seen: string[] = []; yield* API.Env.around( { @@ -209,10 +214,10 @@ describe("mapped canonical component expansion", () => { }; const source = '\'} />'; const output = yield* collect( - yield* executeInstalled( - { ...inlineSource(source), includes: [], stream: new InMemoryStream() }, - [install, workspaceMountInstallation([{ source: "/external", target: "/reference" }])], - ), + yield* executeInstalled({ ...inlineSource(source), includes: [], stream: stream }, [ + install, + workspaceMountInstallation([{ source: "/external", target: "/reference" }]), + ]), ); expect(output).toContain("generated"); expect(seen).toEqual(["/external"]); @@ -220,7 +225,9 @@ describe("mapped canonical component expansion", () => { }); describe("mapped scope exits", () => { + beforeEach(journalBeforeEach(OWNER)); it("restores both enclosing levels after a nested child failure", function* () { + const stream = yield* useJournalStream(""); const seen: string[] = []; let fail = true; yield* API.Env.around( @@ -260,7 +267,7 @@ describe("mapped scope exits", () => { '', ), includes: [], - stream: new InMemoryStream(), + stream: stream, }, [workspaceMountInstallation([{ source: "/external", target: "/reference" }])], ), @@ -270,6 +277,7 @@ describe("mapped scope exits", () => { expect(yield* cwd()).toBe("/host"); }); it("joins cancelled child work and restores the caller's cwd", function* () { + const stream = yield* useJournalStream(""); const entered = withResolvers(); let released = false; yield* API.Env.around( @@ -309,7 +317,7 @@ describe("mapped scope exits", () => { { ...inlineSource(''), includes: [], - stream: new InMemoryStream(), + stream: stream, }, [workspaceMountInstallation([{ source: "/external", target: "/reference" }])], ); @@ -327,8 +335,10 @@ import { registerComponents } from "../src/components/registration.ts"; import { useNormalizedOutput } from "../src/output/normalize.ts"; describe("993 nested canonical directory projection", () => { + beforeEach(journalBeforeEach(OWNER)); for (const reusable of [false, true]) { it(`W2: selects REPORT inside the canonical frame and reads ROOT after its Dir closes (${reusable})`, function* () { + const stream = yield* useJournalStream(""); yield* Permissions.around( { files: ([operation], next) => (operation === "absolute" ? true : next(operation)) }, { at: "min" }, @@ -345,7 +355,11 @@ describe("993 nested canonical directory projection", () => { { origin: "993", name: "Observe", - props: { type: "object", properties: { value: { type: "string" } }, required: ["value"] }, + props: { + type: "object", + properties: { value: { type: "string" } }, + required: ["value"], + }, *fn(props) { observed.push(props.value); return ""; @@ -362,7 +376,7 @@ describe("993 nested canonical directory projection", () => { { ...inlineSource(reusable ? "" : source), includes: [`${directory}/components`], - stream: new InMemoryStream(), + stream: stream, }, [workspaceMountInstallation([{ source: directory, target: "/document" }])], ), diff --git a/packages/core/tests/generated-composition.test.ts b/packages/core/tests/generated-composition.test.ts index d0a2b1ad8..48541fc8b 100644 --- a/packages/core/tests/generated-composition.test.ts +++ b/packages/core/tests/generated-composition.test.ts @@ -17,9 +17,15 @@ * would have let the read before it through. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import type { Json } from "@executablemd/durable-streams"; import { ensure, scoped } from "effection"; import type { Operation } from "effection"; @@ -35,6 +41,8 @@ import { answerProvider } from "./support/answer-provider.ts"; import { registerComponents } from "../src/components/registration.ts"; import type { FunctionComponentDefinition } from "../src/types.ts"; +const OWNER = "packages/core/tests/generated-composition.test.ts"; + const ROOT_PATH = "workflows/agent.md"; const NOTE = "the retained note\n"; const OTHER = "the other note\n"; @@ -80,7 +88,7 @@ function both(files: RecordedFiles): ExecutionInstallation { function run( source: string, installations: readonly ExecutionInstallation[], - stream: InMemoryStream = new InMemoryStream(), + stream: InMemoryStream, ): Operation { return scoped(function* () { return yield* collect( @@ -105,11 +113,14 @@ function evaluating(fragment: string, allow?: readonly string[]): string { } describe("Tier FE31 — a fragment binds locally and renders what it chose", () => { + beforeEach(journalBeforeEach(OWNER)); it("FE31: bound File output is suppressed and reaches the caller only through Json", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); const output = yield* run( evaluating(`\n\n\n`), [reading(files)], + stream, ); const rendered = String(output); @@ -121,11 +132,12 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () }); it("FE31: the same read without `as` renders itself and builds no object", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The negative control for the row above. An implementation that collected // results implicitly would produce the same object either way, so this is // what says the binding — and only the binding — suppressed the output. const files = recordedFiles({ "notes.md": NOTE }); - const output = yield* run(evaluating(`\n`), [reading(files)]); + const output = yield* run(evaluating(`\n`), [reading(files)], stream); const rendered = String(output); expect(files.performed).toEqual(["read notes.md"]); @@ -135,6 +147,7 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () }); it("FE31: nested literals, arrays and shorthand compose without executing", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE, "other.md": OTHER }); const output = yield* run( evaluating( @@ -143,6 +156,7 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () `\n`, ), [reading(files)], + stream, ); expect(JSON.parse(String(output).trim())).toEqual({ @@ -153,10 +167,12 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () }); it("FE31: `__proto__` stays an ordinary data key and changes no prototype", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); const output = yield* run( evaluating(`\n\n\n`), [reading(files)], + stream, ); // Rendered as a member, which is what proves it was defined rather than @@ -213,46 +229,59 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () for (const [what, element] of EXECUTABLE) { it(`FE31: ${what} refuses before the read written ahead of it`, function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); // The read is written *first*, so a refusal that happened at `` // rather than in whole-fragment preflight would leave it in the recorder. yield* refusal( - run(evaluating(`\n\n${element}\n`), [reading(files)]), + run( + evaluating(`\n\n${element}\n`), + [reading(files)], + stream, + ), ); expect([what, files.performed]).toEqual([what, []]); }); } it("FE31: a directly scanned finite number is the positive control for the non-finite rows", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // `-1` is a JSON number rather than an operator, and the scanner resolves it // to an inert `-1` before an expression exists. Without this row, the // non-finite rows above could be refusing because a scanned numeric literal // never reaches `` at all. const files = recordedFiles({ "notes.md": NOTE }); - const output = yield* run(evaluating(`\n\n\n`), [ - reading(files), - ]); + const output = yield* run( + evaluating(`\n\n\n`), + [reading(files)], + stream, + ); expect(files.performed).toEqual(["read notes.md"]); expect(String(output)).toContain("-1"); }); it("FE31: a scanned finite number composes inside an array and an object", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles(); - const output = yield* run(evaluating(`\n`), [ - reading(files), - ]); + const output = yield* run( + evaluating(`\n`), + [reading(files)], + stream, + ); expect(JSON.parse(String(output).trim())).toEqual({ kept: [-1, 0, 1.5], number: -2 }); }); it("FE31: an admitted read is the positive control for those refusals", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // Every row above shares this fragment's first element. Without this, each // of them could be refusing because the fragment never ran at all. const files = recordedFiles({ "notes.md": NOTE }); const output = yield* run( evaluating(`\n\n\n`), [reading(files)], + stream, ); expect(files.performed).toEqual(["read notes.md"]); @@ -260,16 +289,20 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () }); it("FE31: a binding is unavailable before the element that produces it", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); yield* refusal( - run(evaluating(`\n\n\n`), [ - reading(files), - ]), + run( + evaluating(`\n\n\n`), + [reading(files)], + stream, + ), ); expect(files.performed).toEqual([]); }); it("FE31: a binding made inside content does not leak to a later sibling", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The paired write's children bind in their own scope, exactly as ordinary // expansion's environments do. A preflight that pooled every `as` it met // would admit this and fail only after the write had already run. @@ -282,6 +315,7 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () ["read", "write"], ), [both(files)], + stream, ), ); expect(files.performed).toEqual([]); @@ -289,6 +323,7 @@ describe("Tier FE31 — a fragment binds locally and renders what it chose", () }); describe("Tier FE31 — Json is composition, not an effect", () => { + beforeEach(journalBeforeEach(OWNER)); const SELECTIONS: Array< [string, readonly string[], (files: RecordedFiles) => ExecutionInstallation] > = [ @@ -299,10 +334,12 @@ describe("Tier FE31 — Json is composition, not an effect", () => { for (const [what, allow, profile] of SELECTIONS) { it(`FE31: exact core Json is available under a ${what} selection`, function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); const output = yield* run( evaluating(`\n`, allow), [profile(files)], + stream, ); expect(JSON.parse(String(output).trim())).toEqual({ kept: [1, "two", true] }); @@ -312,6 +349,7 @@ describe("Tier FE31 — Json is composition, not an effect", () => { } it("FE31: Json grants no read permission under a write-only selection", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The negative control for the availability rows: having Json does not make // an unselected class reachable, and the refusal costs the write beside it. const files = recordedFiles({ "notes.md": NOTE }); @@ -323,12 +361,14 @@ describe("Tier FE31 — Json is composition, not an effect", () => { ["write"], ), [writing(files)], + stream, ), ); expect(files.performed).toEqual([]); }); it("FE31: Json grants no write permission under a read-only selection", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); yield* refusal( run( @@ -336,24 +376,30 @@ describe("Tier FE31 — Json is composition, not an effect", () => { "read", ]), [reading(files)], + stream, ), ); expect(files.performed).toEqual([]); }); it("FE31: a host cannot give an effect to a composition name", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // Closed-world conflict detection, at capture rather than at evaluation: // the host never gets to shadow core's own pure component. const files = recordedFiles(); const message = yield* refusal( - run(evaluating(`\n`), [ - { - *install(): Operation { - yield* useSelection({ Json: ["self-closing"] }); - yield* useRecordedFiles(files); + run( + evaluating(`\n`), + [ + { + *install(): Operation { + yield* useSelection({ Json: ["self-closing"] }); + yield* useRecordedFiles(files); + }, }, - }, - ]), + ], + stream, + ), ); expect(message).toContain("Json"); }); @@ -415,11 +461,13 @@ function marking(log: string[]): Operation { } describe("Tier FE33 — the projection settles before its parent continues", () => { + beforeEach(journalBeforeEach(OWNER)); it("FE33: projected teardown completes before later parent work begins", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const log: string[] = []; yield* scoped(function* () { yield* marking(log); - yield* run(evaluating(`\n`) + `\n\n`, [holding(unwinding(log))]); + yield* run(evaluating(`\n`) + `\n\n`, [holding(unwinding(log))], stream); }); // The whole claim is this order. An implementation that let the projection's @@ -431,20 +479,22 @@ describe("Tier FE33 — the projection settles before its parent continues", () }); it("FE33: the parent marker alone is the negative control for that order", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // Without this, the row above could pass because the fragment never ran. const log: string[] = []; yield* scoped(function* () { yield* marking(log); - yield* run(`\n`, []); + yield* run(`\n`, [], stream); }); expect(log).toEqual(["parent after"]); }); }); describe("Tier FE33 — occurrences do not share generated history", () => { + beforeEach(journalBeforeEach(OWNER)); it("FE33: two occurrences each perform their own read", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "one.md": "first\n", "two.md": "second\n" }); - const stream = new InMemoryStream(); const output = yield* run( evaluating(`\n`) + "\n" + evaluating(`\n`), [reading(files)], @@ -466,29 +516,45 @@ describe("Tier FE33 — occurrences do not share generated history", () => { }); describe("Try generated admission", () => { + beforeEach(journalBeforeEach(OWNER)); for (const branch of ["Catch", "Finally"]) { it(`preflights forbidden writes in untaken ${branch} before an allowed read`, function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "note.md": "saved" }); const text = `<${branch}>write`; - const refused = yield* refusal(run(evaluating(text), [reading(files)])); + const refused = yield* refusal(run(evaluating(text), [reading(files)], stream)); expect(refused).toContain("self-closing"); expect(files.performed).toEqual([]); }); } - it("admits literal recovery without exporting Catch locals or admitting property access and calls", function* () { - const files = recordedFiles(); - const capturedRead = ''; - const text = `${capturedRead}literal fallbackfinished`; - const result = yield* run(evaluating(text), [reading(files)]); - expect(String(result)).toContain("literal fallback"); - for (const expression of ["local", "error.message", "error.toString()"]) { - const candidate = - expression === "local" - ? text + `` - : `${capturedRead}`; - const fresh = recordedFiles(); - yield* refusal(run(evaluating(candidate), [reading(fresh)])); - expect(fresh.performed).toEqual([]); - } + const literalRecovery = + "admits literal recovery without exporting Catch locals or admitting property access and calls"; + it(literalRecovery, function* () { + yield* captureTestJournal( + { owner: OWNER, name: literalRecovery }, + ROOT_PATH, + function* (stream) { + const files = recordedFiles(); + const capturedRead = ''; + const text = `${capturedRead}literal fallbackfinished`; + const result = yield* run(evaluating(text), [reading(files)], stream); + expect(String(result)).toContain("literal fallback"); + for (const expression of ["local", "error.message", "error.toString()"]) { + const candidate = + expression === "local" + ? text + `` + : `${capturedRead}`; + yield* captureTestJournal( + { owner: OWNER, name: literalRecovery }, + ROOT_PATH, + function* (refusalStream) { + const fresh = recordedFiles(); + yield* refusal(run(evaluating(candidate), [reading(fresh)], refusalStream)); + expect(fresh.performed).toEqual([]); + }, + ); + } + }, + ); }); }); diff --git a/packages/core/tests/generated-selection.test.ts b/packages/core/tests/generated-selection.test.ts index 040b0559e..a88902cf3 100644 --- a/packages/core/tests/generated-selection.test.ts +++ b/packages/core/tests/generated-selection.test.ts @@ -19,7 +19,13 @@ import { useComponentModuleLoader } from "@executablemd/test-support/host"; * capture must leave no partial allowance anywhere in the execution. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { createApi } from "@effectionx/context-api"; import { ensure, resource, scoped, until, useScope } from "effection"; @@ -45,6 +51,8 @@ import { answerProvider, implementation } from "./support/answer-provider.ts"; import { useSelection } from "./support/generated-selection.ts"; import type { ComponentDefinition, FunctionComponentDefinition } from "../src/types.ts"; +const OWNER = "packages/core/tests/generated-selection.test.ts"; + const ROOT_PATH = "selection.md"; const NOTE = "the retained note\n"; @@ -62,20 +70,21 @@ interface Attempt { * installation, because that is what a host composes: there is no installation * member for it, and core reads the final answer of the chain once. */ +type SelectionRunOptions = { + offered?: unknown; + installations?: readonly ExecutionInstallation[]; + files?: RecordedFiles; + around?: () => Operation; + /** What the *host* supplies, before any policy has seen the request. */ + includes?: readonly string[]; +}; + function run( source: string, - options: { - offered?: unknown; - installations?: readonly ExecutionInstallation[]; - files?: RecordedFiles; - events?: DurableEvent[]; - around?: () => Operation; - /** What the *host* supplies, before any policy has seen the request. */ - includes?: readonly string[]; - } = {}, + options: SelectionRunOptions = {}, + stream = new InMemoryStream(), ): Operation { return scoped(function* () { - const stream = new InMemoryStream(options.events ?? []); yield* useComponentModuleLoader(); if (options.files !== undefined) { yield* useRecordedFiles(options.files); @@ -220,13 +229,15 @@ function rootImports(events: readonly DurableEvent[]): DurableEvent[] { } describe("Tier GS — the property and its default", () => { + beforeEach(journalBeforeEach(OWNER)); it("U5-1: the default is absent, and a document that writes no `` runs", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const read = yield* scoped(function* () { return yield* Component.operations.generated; }); expect(read).toBe(undefined); - const attempt = yield* run("The document wrote no fragment.\n"); + const attempt = yield* run("The document wrote no fragment.\n", {}, stream); expect(attempt.failure).toBe(undefined); expect(attempt.output).toContain("The document wrote no fragment."); expect(admissions(attempt.events)).toHaveLength(0); @@ -244,11 +255,16 @@ describe("Tier GS — the property and its default", () => { }); it("U5-1: an absent selection refuses a paired `` before its producer runs", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const produced: string[] = []; - const attempt = yield* run(producing(`\n`), { - around: () => useProducer(produced), - }); + const attempt = yield* run( + producing(`\n`), + { + around: () => useProducer(produced), + }, + stream, + ); expect(attempt.failure).toContain("no generated components here"); // The producer renders the program, so a refusal that happened after it @@ -259,6 +275,7 @@ describe("Tier GS — the property and its default", () => { }); describe("Tier GS — a selection core cannot capture refuses setup", () => { + beforeEach(journalBeforeEach(OWNER)); /** Every malformed selection a host can offer, and the word it refuses with. */ const MALFORMED: readonly (readonly [string, unknown, string])[] = [ ["an empty selection", {}, "selected no component"], @@ -314,23 +331,28 @@ describe("Tier GS — a selection core cannot capture refuses setup", () => { } it("U5-1: a valid selection is the control every refusal above is measured against", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); const policy: string[] = []; const produced: string[] = []; - const attempt = yield* run(producing(`\n`), { - offered: { File: ["self-closing"] }, - files, - *around(): Operation { - yield* useProducer(produced); - yield* Execution.around({ - *execute([request], next) { - policy.push("execute"); - yield* next(request); - }, - }); + const attempt = yield* run( + producing(`\n`), + { + offered: { File: ["self-closing"] }, + files, + *around(): Operation { + yield* useProducer(produced); + yield* Execution.around({ + *execute([request], next) { + policy.push("execute"); + yield* next(request); + }, + }); + }, }, - }); + stream, + ); expect(attempt.failure).toBe(undefined); expect(attempt.output).toContain("the retained note"); @@ -342,15 +364,20 @@ describe("Tier GS — a selection core cannot capture refuses setup", () => { }); it("U5-1: a mixed valid and invalid selection installs no partial allowance", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); // One name this host could legitimately offer, and one it could not. The // batch is validated whole, so the valid member is not installed on its // own: nothing is filtered, repaired, or kept. - const attempt = yield* run(evaluating(`\n`), { - offered: { File: ["self-closing"], "not a name": ["self-closing"] }, - files, - }); + const attempt = yield* run( + evaluating(`\n`), + { + offered: { File: ["self-closing"], "not a name": ["self-closing"] }, + files, + }, + stream, + ); expect(attempt.failure).toContain("component name"); expect(files.performed).toEqual([]); @@ -359,104 +386,128 @@ describe("Tier GS — a selection core cannot capture refuses setup", () => { }); describe("Tier GS — the selection is read once, before public policy", () => { - it("U5-2: init and the installation callbacks settle the selection before it is read", function* () { - const order: string[] = []; - const files = recordedFiles({ "notes.md": NOTE }); + beforeEach(journalBeforeEach(OWNER)); + const selectionInit = + "U5-2: init and the installation callbacks settle the selection before it is read"; + it(selectionInit, function* () { + yield* captureTestJournal({ owner: OWNER, name: selectionInit }, ROOT_PATH, function* (stream) { + const order: string[] = []; + const files = recordedFiles({ "notes.md": NOTE }); - const attempt = yield* run(evaluating(`\n`), { - installations: [ + const attempt = yield* run( + evaluating(`\n`), { - *install(): Operation { - order.push("install"); - // Offered here, and observed where core reads it: the handler - // records the read so the row can state *when* it happened rather - // than only what it answered. - yield* Component.around({ - generated: (_args, next) => { - order.push("read"); - return next(); + installations: [ + { + *install(): Operation { + order.push("install"); + // Offered here, and observed where core reads it: the handler + // records the read so the row can state *when* it happened rather + // than only what it answered. + yield* Component.around({ + generated: (_args, next) => { + order.push("read"); + return next(); + }, + }); + yield* useSelection({ File: ["self-closing"] }); + }, + }, + ], + files, + *around(): Operation { + yield* Execution.around({ + *init(_args, next) { + order.push("init"); + yield* next(); + }, + *execute([request], next) { + order.push("policy"); + // The selection is already captured. A policy that offers a broader + // one changes nothing: it is composing into a chain core has + // already read its one answer from. + yield* Component.around({ + generated: () => ({ File: ["self-closing", "paired"], Glob: ["self-closing"] }), + }); + yield* next(request); }, }); - yield* useSelection({ File: ["self-closing"] }); }, }, - ], - files, - *around(): Operation { - yield* Execution.around({ - *init(_args, next) { - order.push("init"); - yield* next(); - }, - *execute([request], next) { - order.push("policy"); - // The selection is already captured. A policy that offers a broader - // one changes nothing: it is composing into a chain core has - // already read its one answer from. - yield* Component.around({ - generated: () => ({ File: ["self-closing", "paired"], Glob: ["self-closing"] }), - }); - yield* next(request); - }, - }); - }, - }); + stream, + ); - expect(attempt.failure).toBe(undefined); - // The order is the contract: initialization and the captured installation - // callbacks assemble the host, then core reads the selection once, and only - // then does public execution policy run. A read that happened after the - // policy would be reading a chain the policy had already composed into. - expect(order).toEqual(["init", "install", "read", "policy"]); - // The fragment reached the read it was offered. - expect(files.performed).toEqual(["read notes.md"]); - // And not the vocabulary the policy tried to add: a widened selection after - // capture is a selection nothing reads. - const widened = yield* run(evaluating(`\n`), { - installations: [ - { - *install(): Operation { - yield* useSelection({ File: ["self-closing"] }); - }, + expect(attempt.failure).toBe(undefined); + // The order is the contract: initialization and the captured installation + // callbacks assemble the host, then core reads the selection once, and only + // then does public execution policy run. A read that happened after the + // policy would be reading a chain the policy had already composed into. + expect(order).toEqual(["init", "install", "read", "policy"]); + // The fragment reached the read it was offered. + expect(files.performed).toEqual(["read notes.md"]); + // And not the vocabulary the policy tried to add: a widened selection after + // capture is a selection nothing reads. + yield* captureTestJournal( + { owner: OWNER, name: selectionInit }, + ROOT_PATH, + function* (secondStream) { + const widened = yield* run( + evaluating(`\n`), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ File: ["self-closing"] }); + }, + }, + ], + *around(): Operation { + yield* Execution.around({ + *execute([request], next) { + yield* Component.around({ generated: () => ({ Glob: ["self-closing"] }) }); + yield* next(request); + }, + }); + }, + }, + secondStream, + ); + expect(widened.failure).toContain("did not admit"); }, - ], - *around(): Operation { - yield* Execution.around({ - *execute([request], next) { - yield* Component.around({ generated: () => ({ Glob: ["self-closing"] }) }); - yield* next(request); - }, - }); - }, + ); }); - expect(widened.failure).toContain("did not admit"); }); it("U5-2: one property read and one import per selected name", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const reads: string[] = []; const lookups: string[] = []; const files = recordedFiles({ "notes.md": NOTE }); - const attempt = yield* run(evaluating(`\n\n`), { - files, - installations: [ - { - *install(): Operation { - yield* Component.around({ - generated: (_args, next) => { - reads.push("generated"); - return next(); - }, - *importComponent([name, position], next) { - lookups.push(name); - return yield* next(name, position); - }, - }); - yield* useSelection({ File: ["self-closing", "paired"] }); + const attempt = yield* run( + evaluating(`\n\n`), + { + files, + installations: [ + { + *install(): Operation { + yield* Component.around({ + generated: (_args, next) => { + reads.push("generated"); + return next(); + }, + *importComponent([name, position], next) { + lookups.push(name); + return yield* next(name, position); + }, + }); + yield* useSelection({ File: ["self-closing", "paired"] }); + }, }, - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toBe(undefined); // One read of the property for the whole execution. @@ -475,93 +526,120 @@ describe("Tier GS — the selection is read once, before public policy", () => { expect(files.performed).toEqual(["read notes.md", "read notes.md"]); }); - it("U5-2: a policy's search-path replacement reaches authored imports, not the capture", function* () { - // The one search path a document here can import a component from, and the - // host supplies none of it: everything authored resolves through whatever - // the accepted request names. - const dir = yield* useComponentDirectory(); - const files = recordedFiles({ "notes.md": NOTE }); - - const attempt = yield* run(`\n\n${evaluating(`\n`)}`, { - files, - installations: [ - { - *install(): Operation { - yield* useSelection({ File: ["self-closing"] }); - }, - }, - ], - *around(): Operation { - yield* Execution.around({ - *execute([request], next) { - // A supported policy change, made before delegating. The options - // the terminal accepts are the ones the document is executed - // under, so this is where its authored imports resolve from. - yield* next(request.withOptions({ ...request.options, includes: [dir] })); - }, - }); - }, - }); - - expect(attempt.failure).toBe(undefined); - // The authored import resolved through the replaced path. Without the - // accepted options reaching ordinary resolution there is nowhere for - // `` to come from. - expect(attempt.output).toContain("REPLACED-COMPONENT"); - // And the capture is untouched by it: the fragment wrote the one spelling - // the host selected, resolved before the policy ran. - expect(files.performed).toEqual(["read notes.md"]); - - // The other half: a path a policy added is not a vocabulary a fragment - // gained. `` is importable by the *document* and admitted for - // nothing. - const widened = yield* run(evaluating(`\n`), { - installations: [ - { - *install(): Operation { - yield* useSelection({ File: ["self-closing"] }); + const authoredLookup = + "U5-2: a policy's search-path replacement reaches authored imports, not the capture"; + it(authoredLookup, function* () { + yield* captureTestJournal( + { owner: OWNER, name: authoredLookup }, + ROOT_PATH, + function* (stream) { + // The one search path a document here can import a component from, and the + // host supplies none of it: everything authored resolves through whatever + // the accepted request names. + const dir = yield* useComponentDirectory(); + const files = recordedFiles({ "notes.md": NOTE }); + + const attempt = yield* run( + `\n\n${evaluating(`\n`)}`, + { + files, + installations: [ + { + *install(): Operation { + yield* useSelection({ File: ["self-closing"] }); + }, + }, + ], + *around(): Operation { + yield* Execution.around({ + *execute([request], next) { + // A supported policy change, made before delegating. The options + // the terminal accepts are the ones the document is executed + // under, so this is where its authored imports resolve from. + yield* next(request.withOptions({ ...request.options, includes: [dir] })); + }, + }); + }, }, - }, - ], - *around(): Operation { - yield* Execution.around({ - *execute([request], next) { - yield* next(request.withOptions({ ...request.options, includes: [dir] })); + stream, + ); + + expect(attempt.failure).toBe(undefined); + // The authored import resolved through the replaced path. Without the + // accepted options reaching ordinary resolution there is nowhere for + // `` to come from. + expect(attempt.output).toContain("REPLACED-COMPONENT"); + // And the capture is untouched by it: the fragment wrote the one spelling + // the host selected, resolved before the policy ran. + expect(files.performed).toEqual(["read notes.md"]); + + // The other half: a path a policy added is not a vocabulary a fragment + // gained. `` is importable by the *document* and admitted for + // nothing. + yield* captureTestJournal( + { owner: OWNER, name: authoredLookup }, + ROOT_PATH, + function* (secondStream) { + const widened = yield* run( + evaluating(`\n`), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ File: ["self-closing"] }); + }, + }, + ], + *around(): Operation { + yield* Execution.around({ + *execute([request], next) { + yield* next(request.withOptions({ ...request.options, includes: [dir] })); + }, + }); + }, + }, + secondStream, + ); + expect(widened.failure).toContain("did not admit"); }, - }); + ); }, - }); - expect(widened.failure).toContain("did not admit"); + ); }); it("U5-2: a later ordinary authored registration still behaves contextually", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const told: string[] = []; // The selection is captured; an ordinary registration a document policy // makes afterwards is an ordinary registration, visible to the authored // document exactly as it always was. - const attempt = yield* run("\n", { - offered: { File: ["self-closing"] }, - *around(): Operation { - yield* Execution.around({ - *execute([request], next) { - yield* registerComponents([ - { - name: "Later", - origin: "test://later", - props: { type: "object", properties: {}, additionalProperties: false }, - // deno-lint-ignore require-yield - *fn(): Operation { - told.push("later ran"); - return "the later registration ran"; + const attempt = yield* run( + "\n", + { + offered: { File: ["self-closing"] }, + *around(): Operation { + yield* Execution.around({ + *execute([request], next) { + yield* registerComponents([ + { + name: "Later", + origin: "test://later", + props: { type: "object", properties: {}, additionalProperties: false }, + // deno-lint-ignore require-yield + *fn(): Operation { + told.push("later ran"); + return "the later registration ran"; + }, }, - }, - ]); - yield* next(request); - }, - }); + ]); + yield* next(request); + }, + }); + }, }, - }); + stream, + ); expect(attempt.failure).toBe(undefined); expect(told).toEqual(["later ran"]); @@ -570,21 +648,27 @@ describe("Tier GS — the selection is read once, before public policy", () => { }); describe("Tier GS — what a selected name resolves to", () => { + beforeEach(journalBeforeEach(OWNER)); it("U5-3: a registered function and a published provider answer both run", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const ran: string[] = []; const A = implementation("Open", "the provider's answer ran"); - const attempt = yield* run(evaluating("\n\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Local: ["self-closing"], Open: ["self-closing"] }); - yield* registerComponents([localComponent(ran)]); + const attempt = yield* run( + evaluating("\n\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Local: ["self-closing"], Open: ["self-closing"] }); + yield* registerComponents([localComponent(ran)]); + }, + componentAnswers: [answerProvider("Open", A.definition)], }, - componentAnswers: [answerProvider("Open", A.definition)], - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toBe(undefined); expect(ran).toEqual(["local ran"]); @@ -592,45 +676,68 @@ describe("Tier GS — what a selected name resolves to", () => { expect(attempt.output).toContain("the provider's answer ran"); }); - it("U5-3: a repository component is offered for what it declares, and no more", function* () { - const dir = yield* useRepositoryComponents(); - - // A file on the search path is a declaration like any other: what its - // self-closing form is offered for is on it, so a host that selects the - // name is offered exactly that and the fragment runs that body. - const offered = yield* run(evaluating(`\n`), { - includes: [dir], - installations: [ - { - *install(): Operation { - yield* useSelection({ Offered: ["self-closing"] }); + const repositoryComponent = + "U5-3: a repository component is offered for what it declares, and no more"; + it(repositoryComponent, function* () { + yield* captureTestJournal( + { owner: OWNER, name: repositoryComponent }, + ROOT_PATH, + function* (stream) { + const dir = yield* useRepositoryComponents(); + + // A file on the search path is a declaration like any other: what its + // self-closing form is offered for is on it, so a host that selects the + // name is offered exactly that and the fragment runs that body. + const offered = yield* run( + evaluating(`\n`), + { + includes: [dir], + installations: [ + { + *install(): Operation { + yield* useSelection({ Offered: ["self-closing"] }); + }, + }, + ], }, - }, - ], - }); - - expect(offered.failure).toBe(undefined); - expect(offered.output).toContain("THE REPOSITORY COPY RAN"); + stream, + ); + + expect(offered.failure).toBe(undefined); + expect(offered.output).toContain("THE REPOSITORY COPY RAN"); + + // The same shape, stating nothing: a component that declares no generated + // use is one no selection admits, and the host's statement cannot supply + // what the owner withheld. + yield* captureTestJournal( + { owner: OWNER, name: repositoryComponent }, + ROOT_PATH, + function* (secondStream) { + const silent = yield* run( + evaluating(`\n`), + { + includes: [dir], + installations: [ + { + *install(): Operation { + yield* useSelection({ Silent: ["self-closing"] }); + }, + }, + ], + }, + secondStream, + ); - // The same shape, stating nothing: a component that declares no generated - // use is one no selection admits, and the host's statement cannot supply - // what the owner withheld. - const silent = yield* run(evaluating(`\n`), { - includes: [dir], - installations: [ - { - *install(): Operation { - yield* useSelection({ Silent: ["self-closing"] }); + expect(silent.failure).toContain("offers no generated use"); + expect(silent.output).toBe(undefined); }, - }, - ], - }); - - expect(silent.failure).toContain("offers no generated use"); - expect(silent.output).toBe(undefined); + ); + }, + ); }); it("U5-3: an unpublished replacement refuses", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const ran: string[] = []; const replacement: FunctionComponentDefinition = { kind: "function", @@ -653,51 +760,60 @@ describe("Tier GS — what a selected name resolves to", () => { // Ordinary import middleware answering with its own definition, publishing // nothing. It is a valid ordinary answer and it is not an implementation // this execution may retain for a selected name. - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Local: ["self-closing"] }); - yield* registerComponents([localComponent(ran)]); - yield* Component.around({ - *importComponent([name, position], next) { - return name === "Local" ? replacement : yield* next(name, position); - }, - }); + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Local: ["self-closing"] }); + yield* registerComponents([localComponent(ran)]); + yield* Component.around({ + *importComponent([name, position], next) { + return name === "Local" ? replacement : yield* next(name, position); + }, + }); + }, }, - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toContain("neither canonical resolution's own answer"); expect(ran).toEqual([]); }); it("U5-3: a replacement offering no generated use of the selected spelling refuses", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const ran: string[] = []; - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Open: ["self-closing"] }); + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Open: ["self-closing"] }); + }, + componentAnswers: [ + answerProvider("Open", { + kind: "function", + name: "Open", + props: { type: "object", properties: {}, additionalProperties: false }, + forms: ["self-closing"], + // deno-lint-ignore require-yield + *fn(): Operation { + ran.push("unoffered ran"); + return "the unoffered answer ran"; + }, + }), + ], }, - componentAnswers: [ - answerProvider("Open", { - kind: "function", - name: "Open", - props: { type: "object", properties: {}, additionalProperties: false }, - forms: ["self-closing"], - // deno-lint-ignore require-yield - *fn(): Operation { - ran.push("unoffered ran"); - return "the unoffered answer ran"; - }, - }), - ], - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toContain("offers no generated use of it"); expect(ran).toEqual([]); @@ -844,21 +960,26 @@ describe("Tier GS — what a selected name resolves to", () => { }); it("U5-3: the retained admission holds the identity the owner declared", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const ran: string[] = []; // The positive control for the two refusals above: an ordinary declaration // is retained with the URL its own metadata states, and that is the row the // admission records. - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Local: ["self-closing"] }); - yield* registerComponents([localComponent(ran)]); + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Local: ["self-closing"] }); + yield* registerComponents([localComponent(ran)]); + }, }, - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toBe(undefined); expect(ran).toEqual(["local ran"]); diff --git a/packages/core/tests/inline-root.test.ts b/packages/core/tests/inline-root.test.ts index 2eb7fdf16..d864bf6fc 100644 --- a/packages/core/tests/inline-root.test.ts +++ b/packages/core/tests/inline-root.test.ts @@ -18,7 +18,13 @@ * the identity and the text are recorded — and IR6 marks the boundary. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { + captureTestJournal, + journalBeforeEach, + useJournalStream, +} from "@executablemd/test-support/failure-journal"; + import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, until } from "effection"; import type { Operation } from "effection"; @@ -143,7 +149,10 @@ function importEvents(stream: InMemoryStream) { ); } +const OWNER = "packages/core/tests/inline-root.test.ts"; + describe("Tier IR — inline root documents", () => { + beforeEach(journalBeforeEach(OWNER)); it("IR1: inspection reports the identity and reads nothing", function* () { yield* useNoFs(); @@ -194,8 +203,8 @@ describe("Tier IR — inline root documents", () => { }); it("IR4: the journal holds the supplied identity and text", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); yield* useNoFs(); - const stream = new InMemoryStream(); yield* collect(yield* execute({ ...inlineSource("# Hello\n"), stream })); @@ -271,8 +280,8 @@ describe("Tier IR — inline root documents", () => { }); it("IR7: source positions report past the frontmatter", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); yield* useNoFs(); - const stream = new InMemoryStream(); // Nothing recovers the stray element, so the positioned diagnostic is the // run's own outcome. @@ -286,8 +295,8 @@ describe("Tier IR — inline root documents", () => { }); it("IR8: an inline value root returns its declared value", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); yield* useNoFs(); - const stream = new InMemoryStream(); const value = yield* collect( yield* execute({ @@ -309,12 +318,12 @@ describe("Tier IR — inline root documents", () => { }); it("IR9: repository components resolve from the search path, not the root", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); const trace: FsTrace = { reads: [], stats: [], writes: [] }; // The guard first: `useStubFs` is terminal, so a guard installed after it // would sit below and never see a call. yield* useFsWriteGuard(trace); yield* useStubFs({ "components/Greeting.md": "Hello from a component\n" }); - const stream = new InMemoryStream(); const output = asText( yield* collect(yield* execute({ ...inlineSource("\n"), stream })), @@ -328,8 +337,8 @@ describe("Tier IR — inline root documents", () => { }); it("IR10: a relative path resolves against the contextual cwd", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); yield* useWorkspace({ "notes.md": "notes from the working directory\n" }); - const stream = new InMemoryStream(); const output = asText( yield* collect(yield* execute({ ...inlineSource('\n'), stream })), @@ -338,41 +347,54 @@ describe("Tier IR — inline root documents", () => { expect(output).toContain("notes from the working directory"); }); - it("IR11: props are validated and defaulted for a supplied root", function* () { - yield* useNoFs(); - const source = [ - "---", - "props:", - " name:", - " type: string", - " loud:", - " type: boolean", - " default: false", - "required: [name]", - "---", - "", - "{props.name} {props.loud}", - ].join("\n"); - - const stream = new InMemoryStream(); - const output = asText( - yield* collect(yield* execute({ ...inlineSource(source), props: { name: "Ada" }, stream })), + const rootProps = "IR11: props are validated and defaulted for a supplied root"; + it(rootProps, function* () { + yield* captureTestJournal( + { owner: OWNER, name: rootProps }, + INLINE_SOURCE_PATH, + function* (stream) { + yield* useNoFs(); + const source = [ + "---", + "props:", + " name:", + " type: string", + " loud:", + " type: boolean", + " default: false", + "required: [name]", + "---", + "", + "{props.name} {props.loud}", + ].join("\n"); + + const output = asText( + yield* collect( + yield* execute({ ...inlineSource(source), props: { name: "Ada" }, stream }), + ), + ); + expect(output).toContain("Ada false"); + + yield* captureTestJournal( + { owner: OWNER, name: rootProps }, + INLINE_SOURCE_PATH, + function* (missing) { + const result = yield* execute({ ...inlineSource(source), stream: missing }); + const completion = yield* result; + expect(completion.ok).toBe(false); + }, + ); + }, ); - expect(output).toContain("Ada false"); - - const missing = new InMemoryStream(); - const result = yield* execute({ ...inlineSource(source), stream: missing }); - const completion = yield* result; - expect(completion.ok).toBe(false); }); it("IR12: running a supplied root writes nothing", function* () { + const stream = yield* useJournalStream(INLINE_SOURCE_PATH); const trace: FsTrace = { reads: [], stats: [], writes: [] }; // The guard first: `useStubFs` is terminal, so a guard installed after it // would sit below and never see a call. yield* useFsWriteGuard(trace); yield* useStubFs({ "components/Greeting.md": "Hello from a component\n" }); - const stream = new InMemoryStream(); yield* collect(yield* execute({ ...inlineSource("\n"), stream })); 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/core/tests/state-ownership.test.ts b/packages/core/tests/state-ownership.test.ts index f60e66377..7c70960d6 100644 --- a/packages/core/tests/state-ownership.test.ts +++ b/packages/core/tests/state-ownership.test.ts @@ -12,10 +12,12 @@ */ import { describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; + 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 { useStubFs } from "@executablemd/runtime/test"; import { execute } from "../src/execute.ts"; import { collect } from "../src/collect.ts"; @@ -233,8 +235,14 @@ describe("Tier SO — each run compiles with a compiler of its own", () => { * host changed in between. A validator remembered from the first run would let * the second run accept props its schema no longer allows. */ +const OWNER = "packages/core/tests/state-ownership.test.ts"; + describe("Tier SO — two executions of a registered component", () => { - function run(files: Record, schema: PropsSchema): Operation { + function run( + stream: InMemoryStream, + files: Record, + schema: PropsSchema, + ): Operation { return scoped(function* () { yield* registerComponents([ { @@ -248,33 +256,46 @@ describe("Tier SO — two executions of a registered component", () => { }, ]); yield* useStubFs(files); - return yield* collect(yield* execute({ path: "doc.md", stream: new InMemoryStream() })); + return yield* collect(yield* execute({ path: "doc.md", stream })); }); } - it("SO13: validates the second run against the schema the host now declares", function* () { - const schema: PropsSchema = { - type: "object", - properties: { a: { type: "string" }, b: { type: "string" } }, - required: ["a"], - additionalProperties: false, - }; - - const first = String(yield* run({ "doc.md": '' }, schema)); - expect(first).toContain("widget:one"); - - // The host tightens the contract between runs, on the object it registered. - schema["required"] = ["a", "b"]; - - // The invocation no longer satisfies the schema, and nothing recovers the - // refusal, so the second run reports it instead of rendering a widget. - let second = ""; - try { - second = String(yield* run({ "doc.md": '' }, schema)); - } catch (error) { - second = error instanceof Error ? error.message : String(error); - } - expect(second).toContain("required property"); - expect(second).not.toContain("widget:two"); + const tightenedSchema = "SO13: validates the second run against the schema the host now declares"; + it(tightenedSchema, function* () { + yield* captureTestJournal( + { owner: OWNER, name: tightenedSchema }, + "doc.md", + function* (stream) { + const schema: PropsSchema = { + type: "object", + properties: { a: { type: "string" }, b: { type: "string" } }, + required: ["a"], + additionalProperties: false, + }; + + const first = String(yield* run(stream, { "doc.md": '' }, schema)); + expect(first).toContain("widget:one"); + + // The host tightens the contract between runs, on the object it registered. + schema["required"] = ["a", "b"]; + + // The invocation no longer satisfies the schema, and nothing recovers the + // refusal, so the second run reports it instead of rendering a widget. + yield* captureTestJournal( + { owner: OWNER, name: tightenedSchema }, + "doc.md", + function* (secondStream) { + let second = ""; + try { + second = String(yield* run(secondStream, { "doc.md": '' }, schema)); + } catch (error) { + second = error instanceof Error ? error.message : String(error); + } + expect(second).toContain("required property"); + expect(second).not.toContain("widget:two"); + }, + ); + }, + ); }); }); 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();