From cd1f097450e293bb90334f69a32bbe95f010ca72 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Tue, 17 Nov 2026 15:04:20 -0500 Subject: [PATCH] Capture failure journals in local artifact and fixture tests Replay the reviewed #1362 patch onto current main. --- .../repl-bench/tests/publish-evidence.test.ts | 139 ++++++--- packages/cli/tests/repl-forms.test.ts | 284 +++++++++--------- packages/cli/tests/run-composition.test.ts | 9 +- .../tests/document-target-execution.test.ts | 59 ++-- .../core/tests/evaluate-loaded-copy.test.ts | 159 ++++++---- .../core/tests/expansion-identity.test.ts | 34 ++- .../core/tests/file-delete-component.test.ts | 83 +++-- .../tests/generated-owner-metadata.test.ts | 16 +- .../core/tests/generated-selection.test.ts | 158 +++++----- packages/core/tests/named-slots.test.ts | 24 +- packages/core/tests/syntax-api.test.ts | 121 +++++--- .../core/tests/syntax-loaded-copy.test.ts | 227 ++++++++------ .../workspace-effect-loaded-copy.test.ts | 11 +- 13 files changed, 792 insertions(+), 532 deletions(-) diff --git a/examples/repl-bench/tests/publish-evidence.test.ts b/examples/repl-bench/tests/publish-evidence.test.ts index 7b8ecd2b7..e69aa9855 100644 --- a/examples/repl-bench/tests/publish-evidence.test.ts +++ b/examples/repl-bench/tests/publish-evidence.test.ts @@ -4,7 +4,8 @@ import { Stdio } from "@effectionx/process"; import { collect, execute, fileSource, useNormalizedOutput } from "@executablemd/core"; import { InMemoryStream } from "@executablemd/durable-streams"; import { API, useHostFiles } from "@executablemd/runtime"; -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 { useComponentModuleLoader } from "@executablemd/test-support/host"; import { cliRuntime } from "@executablemd/test-support/launch"; @@ -39,6 +40,13 @@ import { WARMUP, WORKLOADS, } from "../lib/typing-latency-report.ts"; +import { + journalBeforeEach, + useJournalStream, + captureTestJournal, +} from "@executablemd/test-support/failure-journal"; + +const OWNER = "examples/repl-bench/tests/publish-evidence.test.ts"; const document = fileURLToPath(new URL("../publish-evidence.md", import.meta.url)); const components = fileURLToPath(new URL("../components", import.meta.url)); @@ -381,6 +389,7 @@ function run( host: ReturnType, mode: "dry-run" | "publish" = "publish", setup?: { directory: string; install: () => Operation; beforeEdit: () => Operation }, + stream = new InMemoryStream(), ) { return scoped(function* () { yield* API.Env.around({ @@ -400,7 +409,7 @@ function run( ...fileSource(document), includes: [components], props: { mode, receipt: fixture.path }, - stream: new InMemoryStream(), + stream, }), ), ); @@ -417,57 +426,89 @@ function* preview(fixture: Fixture) { } describe("REPL UI evidence publication", () => { - it("reproduces the local preview with the actual entry and only preflights the CLI", function* () { - const input = yield* useFixture(); - const host = modeledHost(() => snapshot(input)); - yield* writeTextFile(join(input.directory, "preview.md"), afterProse); - const one = yield* run(input, host, "dry-run"); - const two = yield* run(input, host, "dry-run"); - expect(two).toEqual(one); - expect(one.visualSignOff).toBe("pending"); - const legacyIdentity = sha256( - JSON.stringify({ - version: 1, - ...input.pins, - acceptance: input.receipt.acceptance.map(({ name, kind, status, revision }) => ({ - name, - kind, - status, - revision, - })), - checkpoints: input.receipt.checkpoints, - slots: input.receipt.captures.map(({ checkpoint, role, revision, sha256 }) => ({ - id: `${checkpoint}-${role}`, - revision, - sha256, - })), - timingDigest: sha256(JSON.stringify(input.timing)), - }), - ); - expect(one.identity).toBe(legacyIdentity); - expect(one.markdown).toContain(``); - expect(one.markdown?.endsWith(afterProse)).toBe(true); - expect(one.markdown).toContain("| Checkpoint | Fixture | Viewport | Action | Before | After |"); - expect(one.markdown).toContain("synthetic | composer"); - expect(one.markdown).toContain("| small | 30 |"); - expect(one.markdown).not.toContain(input.directory); - expect(one.images).toEqual(input.paths); - expect(host.events).toEqual(["help", "help"]); + beforeEach(journalBeforeEach(OWNER)); + const previewCase = + "reproduces the local preview with the actual entry and only preflights the CLI"; + it(previewCase, function* () { + yield* captureTestJournal({ owner: OWNER, name: previewCase }, document, function* (stream) { + const input = yield* useFixture(); + const host = modeledHost(() => snapshot(input)); + yield* writeTextFile(join(input.directory, "preview.md"), afterProse); + const one = yield* run(input, host, "dry-run", undefined, stream); + yield* captureTestJournal( + { owner: OWNER, name: previewCase }, + document, + function* (secondStream) { + const two = yield* run(input, host, "dry-run", undefined, secondStream); + expect(two).toEqual(one); + expect(one.visualSignOff).toBe("pending"); + const legacyIdentity = sha256( + JSON.stringify({ + version: 1, + ...input.pins, + acceptance: input.receipt.acceptance.map(({ name, kind, status, revision }) => ({ + name, + kind, + status, + revision, + })), + checkpoints: input.receipt.checkpoints, + slots: input.receipt.captures.map(({ checkpoint, role, revision, sha256 }) => ({ + id: `${checkpoint}-${role}`, + revision, + sha256, + })), + timingDigest: sha256(JSON.stringify(input.timing)), + }), + ); + expect(one.identity).toBe(legacyIdentity); + expect(one.markdown).toContain(``); + expect(one.markdown?.endsWith(afterProse)).toBe(true); + expect(one.markdown).toContain( + "| Checkpoint | Fixture | Viewport | Action | Before | After |", + ); + expect(one.markdown).toContain("synthetic | composer"); + expect(one.markdown).toContain("| small | 30 |"); + expect(one.markdown).not.toContain(input.directory); + expect(one.images).toEqual(input.paths); + expect(host.events).toEqual(["help", "help"]); + }, + ); + }); }); - it("rejects a generated description over the body limit in preview and numbered publish", function* () { - const input = yield* useFixture(); - const host = modeledHost(() => snapshot(input, oversizedProse)); - yield* writeTextFile(join(input.directory, "preview.md"), oversizedProse); - const diagnostic = "The proposed draft description exceeds the GitHub body limit."; - expect(String(yield* raised(run(input, host, "dry-run")))).toContain(diagnostic); - expect(host.events).toEqual(["help"]); - host.events.length = 0; - expect(String(yield* raised(run(input, host)))).toContain(diagnostic); - expect(host.events).toEqual(["help", "read"]); + const descriptionLimit = + "rejects a generated description over the body limit in preview and numbered publish"; + it(descriptionLimit, function* () { + yield* captureTestJournal( + { owner: OWNER, name: descriptionLimit }, + document, + function* (stream) { + const input = yield* useFixture(); + const host = modeledHost(() => snapshot(input, oversizedProse)); + yield* writeTextFile(join(input.directory, "preview.md"), oversizedProse); + const diagnostic = "The proposed draft description exceeds the GitHub body limit."; + expect(String(yield* raised(run(input, host, "dry-run", undefined, stream)))).toContain( + diagnostic, + ); + expect(host.events).toEqual(["help"]); + host.events.length = 0; + yield* captureTestJournal( + { owner: OWNER, name: descriptionLimit }, + document, + function* (secondStream) { + expect( + String(yield* raised(run(input, host, undefined, undefined, secondStream))), + ).toContain(diagnostic); + expect(host.events).toEqual(["help", "read"]); + }, + ); + }, + ); }); it("publishes a PNG with final IDAT padding without changing its approved bytes", function* () { + const stream = yield* useJournalStream(document); const input = yield* useFixture(); const padded = Uint8Array.from( atob( @@ -485,7 +526,7 @@ describe("REPL UI evidence publication", () => { }), ); const host = modeledHost(() => snapshot(input)); - const result = yield* run(input, host); + const result = yield* run(input, host, undefined, undefined, stream); expect(result.status).toBe("complete"); expect(host.edits[0].images[0].sha256).toBe(digest); expect(host.bytes.get(urls[0])).toEqual(padded); diff --git a/packages/cli/tests/repl-forms.test.ts b/packages/cli/tests/repl-forms.test.ts index 32d16da8e..a431597df 100644 --- a/packages/cli/tests/repl-forms.test.ts +++ b/packages/cli/tests/repl-forms.test.ts @@ -19,7 +19,7 @@ import { useTempFileCompiler, validateParsed, } from "@executablemd/core"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import { captureReplEntry } from "./fixtures/repl/failure-journal.ts"; import type { Json } from "@executablemd/core"; import { readQuestionForm, useReplElicitation } from "../src/repl/elicitation.ts"; @@ -1160,141 +1160,148 @@ describe("F3 — focus returns to the invocation, not to where the drawer came f // this test. beforeAll(() => useTempFileCompiler()); - it("F3: focus lands on the record this answer caused, once it appends", function* () { - // One real session over one real journal, asking three questions in a row. - // The record focus has to reach does not exist when the answer is taken — - // it appends when the invocation settles — so this drives the whole - // interval rather than a frame that already has everything in it. - const holder = execution(); - const session = granted( - yield* submitReplEntry({ - execution: holder, - installations: [], - generated: ordinaryGeneratedSelection(), - source: THREE_QUESTIONS, - }), - ); - // Chained after the session's own observer, so a signal arrives with the - // session already reprojected — and so the session does not replace it. - const appended = elicitAppends(holder); - - // An answer this test did not cause, carrying the same value the one under - // test will carry. What excludes it is that it was already retained, not - // that it looks different. - const first = yield* waiting(session, "the first question"); - expect(first.message).toContain("First"); - expect(first.submit({ decision: "Approve" }).kind).toBe("answered"); - yield* appended(1); - expect(answers(session.model)).toHaveLength(1); - - // The question under test, in the mounted drawer. - const second = yield* waiting(session, "the question under test", first); - expect(second.message).toContain("Second"); - const held = liveReading(session); - const open = withScope(opened(held), ENTRY_SCOPE); - const tree = yield* useReplTree(); - yield* applied(tree, reading(open, held, session.model)); - const inside = keyed(tree); - expect(inside?.startsWith("drawer:")).toBe(true); - - // Answered by activating the option control the drawer mounted: Enter on - // it is one keystroke, and what it produces is the ordinary action. - yield* tree.dispatch({ kind: "key", key: "Alt+ArrowUp" }); - yield* tree.dispatch({ kind: "key", key: "Alt+ArrowUp" }); - expect(keyed(tree)).toBe("drawer:choice:decision:Approve"); - const dispatched = yield* tree.dispatch({ kind: "key", key: "Enter" }); - if (!dispatched.ok || dispatched.value.outcome !== "action") { - throw new Error("the mounted option control produced no action"); - } - const transition = reduceRepl( - open, - dispatched.value.action, - session.model, - held, - yield* admissionOf(open, held, session.model), - ); - expect(transition.intent.kind).toBe("answer"); - if (transition.intent.kind !== "answer") { - throw new Error("activating an option offers the whole object"); - } - // The boundary the program performs it at, on the question this process is - // actually holding. - const outcome = session.overlay.question?.submit(transition.intent.values); - if (outcome?.kind !== "answered") { - throw new Error("the live question did not take its answer"); - } - // Nothing has appended yet: this is the interval the claim has to survive. - expect(answers(session.model)).toHaveLength(1); - let state = answered(transition.state, session.model, outcome.answer); - expect(state.restore?.kind).toBe("answered"); - - // A frame drawn in that interval claims nothing, because the row it would - // name is not there — and spends nothing either. - let view = reading(state, liveReading(session), session.model, NARROW, inside); - expect(focusClaim(view)).toBe(undefined); - yield* applied(tree, view); - const between = keyed(tree); - expect(between?.startsWith("elicit:")).toBe(false); - state = focusSettled(view, between); - expect(state.restore?.kind).toBe("answered"); - - // A third answer, with a different value, so the record under test is no - // longer the newest one by the time any frame can draw it. - const third = yield* waiting(session, "the third question", second); - expect(third.message).toContain("Third"); - expect(third.submit({ decision: "Stop" }).kind).toBe("answered"); - yield* appended(3); - - const retained = answers(session.model); - expect(retained).toHaveLength(3); - const caused = retained[1]; - const before = retained[0]; - const newest = retained[2]; - if (caused === undefined || before === undefined || newest === undefined) { - throw new Error("the entry retained three answers"); - } - // The one it did not cause has the same answer; the newest one is somebody - // else's. Identity here is both, or neither would be enough. - expect(before.answer).toEqual({ decision: "Approve" }); - expect(caused.answer).toEqual({ decision: "Approve" }); - expect(newest.answer).toEqual({ decision: "Stop" }); - - // Wide, where there is an inspection region: focus lands on the record this - // answer caused, and on neither of the two it did not. - view = reading(state, liveReading(session), session.model, WIDE, between); - expect(focusClaim(view)).toBe(`elicit:${caused.marker}`); - yield* applied(tree, view); - expect(keyed(tree)).toBe(`elicit:${caused.marker}`); - expect(keyed(tree)).not.toBe(`elicit:${before.marker}`); - expect(keyed(tree)).not.toBe(`elicit:${newest.marker}`); - - // Narrow, where there is not. The record's own row is not a row this screen - // offers, so the claim names the entry that owns the record — the visible - // control — and focus lands there rather than on a node drawing nothing. - const owner = `entry:${session.model.entries[0]?.key}`; - view = reading(state, liveReading(session), session.model, NARROW, between); - expect(focusClaim(view)).toBe(owner); - yield* applied(tree, view); - const landed = keyed(tree); - expect(landed).toBe(owner); - // And no recorded-answer row is mounted at this size at all, so none of the - // three could have been what focus found. - expect( - tree - .mounted() - .map((node) => tree.keyOf(node)) - .filter((key) => key !== undefined && key.startsWith("elicit:")), - ).toEqual([]); - - // Spent by the commit that satisfied it, so traversal from here is the - // person's: Tab moves, and the next frame leaves it where they moved it. - state = focusSettled(view, landed); - expect(state.restore).toBe(undefined); - const moved = yield* tabbed(tree); - expect(moved).not.toBe(landed); - yield* applied(tree, reading(state, liveReading(session), session.model, NARROW, moved)); - expect(keyed(tree)).toBe(moved); - }); + const retainedFocus = "F3: focus lands on the record this answer caused, once it appends"; + it(retainedFocus, () => + captureReplEntry( + { owner: "packages/cli/tests/repl-forms.test.ts", name: retainedFocus }, + "elicit-forms", + "", + function* (holder) { + // One real session over one real journal, asking three questions in a row. + // The record focus has to reach does not exist when the answer is taken — + // it appends when the invocation settles — so this drives the whole + // interval rather than a frame that already has everything in it. + const session = granted( + yield* submitReplEntry({ + execution: holder, + installations: [], + generated: ordinaryGeneratedSelection(), + source: THREE_QUESTIONS, + }), + ); + // Chained after the session's own observer, so a signal arrives with the + // session already reprojected — and so the session does not replace it. + const appended = elicitAppends(holder); + + // An answer this test did not cause, carrying the same value the one under + // test will carry. What excludes it is that it was already retained, not + // that it looks different. + const first = yield* waiting(session, "the first question"); + expect(first.message).toContain("First"); + expect(first.submit({ decision: "Approve" }).kind).toBe("answered"); + yield* appended(1); + expect(answers(session.model)).toHaveLength(1); + + // The question under test, in the mounted drawer. + const second = yield* waiting(session, "the question under test", first); + expect(second.message).toContain("Second"); + const held = liveReading(session); + const open = withScope(opened(held), ENTRY_SCOPE); + const tree = yield* useReplTree(); + yield* applied(tree, reading(open, held, session.model)); + const inside = keyed(tree); + expect(inside?.startsWith("drawer:")).toBe(true); + + // Answered by activating the option control the drawer mounted: Enter on + // it is one keystroke, and what it produces is the ordinary action. + yield* tree.dispatch({ kind: "key", key: "Alt+ArrowUp" }); + yield* tree.dispatch({ kind: "key", key: "Alt+ArrowUp" }); + expect(keyed(tree)).toBe("drawer:choice:decision:Approve"); + const dispatched = yield* tree.dispatch({ kind: "key", key: "Enter" }); + if (!dispatched.ok || dispatched.value.outcome !== "action") { + throw new Error("the mounted option control produced no action"); + } + const transition = reduceRepl( + open, + dispatched.value.action, + session.model, + held, + yield* admissionOf(open, held, session.model), + ); + expect(transition.intent.kind).toBe("answer"); + if (transition.intent.kind !== "answer") { + throw new Error("activating an option offers the whole object"); + } + // The boundary the program performs it at, on the question this process is + // actually holding. + const outcome = session.overlay.question?.submit(transition.intent.values); + if (outcome?.kind !== "answered") { + throw new Error("the live question did not take its answer"); + } + // Nothing has appended yet: this is the interval the claim has to survive. + expect(answers(session.model)).toHaveLength(1); + let state = answered(transition.state, session.model, outcome.answer); + expect(state.restore?.kind).toBe("answered"); + + // A frame drawn in that interval claims nothing, because the row it would + // name is not there — and spends nothing either. + let view = reading(state, liveReading(session), session.model, NARROW, inside); + expect(focusClaim(view)).toBe(undefined); + yield* applied(tree, view); + const between = keyed(tree); + expect(between?.startsWith("elicit:")).toBe(false); + state = focusSettled(view, between); + expect(state.restore?.kind).toBe("answered"); + + // A third answer, with a different value, so the record under test is no + // longer the newest one by the time any frame can draw it. + const third = yield* waiting(session, "the third question", second); + expect(third.message).toContain("Third"); + expect(third.submit({ decision: "Stop" }).kind).toBe("answered"); + yield* appended(3); + + const retained = answers(session.model); + expect(retained).toHaveLength(3); + const caused = retained[1]; + const before = retained[0]; + const newest = retained[2]; + if (caused === undefined || before === undefined || newest === undefined) { + throw new Error("the entry retained three answers"); + } + // The one it did not cause has the same answer; the newest one is somebody + // else's. Identity here is both, or neither would be enough. + expect(before.answer).toEqual({ decision: "Approve" }); + expect(caused.answer).toEqual({ decision: "Approve" }); + expect(newest.answer).toEqual({ decision: "Stop" }); + + // Wide, where there is an inspection region: focus lands on the record this + // answer caused, and on neither of the two it did not. + view = reading(state, liveReading(session), session.model, WIDE, between); + expect(focusClaim(view)).toBe(`elicit:${caused.marker}`); + yield* applied(tree, view); + expect(keyed(tree)).toBe(`elicit:${caused.marker}`); + expect(keyed(tree)).not.toBe(`elicit:${before.marker}`); + expect(keyed(tree)).not.toBe(`elicit:${newest.marker}`); + + // Narrow, where there is not. The record's own row is not a row this screen + // offers, so the claim names the entry that owns the record — the visible + // control — and focus lands there rather than on a node drawing nothing. + const owner = `entry:${session.model.entries[0]?.key}`; + view = reading(state, liveReading(session), session.model, NARROW, between); + expect(focusClaim(view)).toBe(owner); + yield* applied(tree, view); + const landed = keyed(tree); + expect(landed).toBe(owner); + // And no recorded-answer row is mounted at this size at all, so none of the + // three could have been what focus found. + expect( + tree + .mounted() + .map((node) => tree.keyOf(node)) + .filter((key) => key !== undefined && key.startsWith("elicit:")), + ).toEqual([]); + + // Spent by the commit that satisfied it, so traversal from here is the + // person's: Tab moves, and the next frame leaves it where they moved it. + state = focusSettled(view, landed); + expect(state.restore).toBe(undefined); + const moved = yield* tabbed(tree); + expect(moved).not.toBe(landed); + yield* applied(tree, reading(state, liveReading(session), session.model, NARROW, moved)); + expect(keyed(tree)).toBe(moved); + }, + ), + ); it("F3: closing without answering moves focus to the invocation still asking", function* () { const recorded = yield* retained(); @@ -1430,11 +1437,6 @@ const THREE_QUESTIONS = [ "{before.decision} {under.decision} {after.decision}", ].join("\n"); -/** One execution with an empty journal of its own. */ -function execution(): ReplExecution { - return { id: "elicit-forms", stream: new InMemoryStream([]) }; -} - /** The session, or the refusal that means there is nothing to drive. */ function granted(result: Result): ReplSession { if (!result.ok) { diff --git a/packages/cli/tests/run-composition.test.ts b/packages/cli/tests/run-composition.test.ts index 586e82b89..9b76dc960 100644 --- a/packages/cli/tests/run-composition.test.ts +++ b/packages/cli/tests/run-composition.test.ts @@ -21,7 +21,6 @@ import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { scoped, suspend, type Operation } from "effection"; -import { InMemoryStream } from "@executablemd/durable-streams"; import { collect, execute, inlineSource, registerComponents } from "@executablemd/core"; import { API, Service, useHostFiles } from "@executablemd/runtime"; import type { RuntimeFetchResponse } from "@executablemd/runtime"; @@ -98,6 +97,7 @@ const COMPOSITION_NAMES = [ */ function ordinaryWithoutProvider(source: string, cwd: string): Operation { return scoped(function* () { + const stream = yield* useJournalStream(""); yield* API.Env.around( { // deno-lint-ignore require-yield @@ -109,9 +109,7 @@ function ordinaryWithoutProvider(source: string, cwd: string): Operation { }); describe("ORC2 — one language, described everywhere and operated somewhere", () => { + beforeEach(journalBeforeEach("packages/cli/tests/run-composition.test.ts")); it("registers the same sixteen declarations the syntax catalog describes", function* () { // The array itself, rather than a second list: the Plugin's own // registration and the catalog both consume this one, so there is nothing @@ -255,6 +254,7 @@ describe("ORC2 — one language, described everywhere and operated somewhere", ( }); describe("ORC2 — Dir is operational where the repository provider is not", () => { + beforeEach(journalBeforeEach("packages/cli/tests/run-composition.test.ts")); // The one composition element that needs no repository provider. Every other // name here reports an absent provider on this runtime; `` reaches the // host `API.Files` provider instead, which all four entrypoints install — so @@ -299,6 +299,7 @@ describe("ORC2 — Dir is operational where the repository provider is not", () }); describe("ORC2 — where the managed root is", () => { + beforeEach(journalBeforeEach("packages/cli/tests/run-composition.test.ts")); it("names ~/.xmd/repositories and nothing a document can influence", function* () { expect(DEFAULT_REPOSITORY_ROOT.endsWith("/.xmd/repositories")).toBe(true); // Describing the vocabulary and refusing an operation both leave it exactly diff --git a/packages/core/tests/document-target-execution.test.ts b/packages/core/tests/document-target-execution.test.ts index e464b6d45..a687dff7a 100644 --- a/packages/core/tests/document-target-execution.test.ts +++ b/packages/core/tests/document-target-execution.test.ts @@ -91,13 +91,17 @@ function* useProbes(seen: Probes): Operation { ]); } -/** A directory the contextual cwd points at, removed when the test ends. */ -function* useWorkspace(files: Record): Operation { +/** A fixture directory removed when its owning scope ends. */ +function* createWorkspace(files: Record): Operation { const root = yield* until(mkdtemp(join(tmpdir(), "xmd-targets-"))); yield* ensure(() => rm(root, { recursive: true, force: true })); for (const [name, content] of Object.entries(files)) { yield* writeTextFile(join(root, name), content); } + return root; +} + +function* useWorkspaceHost(root: string): Operation { yield* API.Env.around( { *cwd() { @@ -107,6 +111,11 @@ function* useWorkspace(files: Record): Operation { { at: "min" }, ); yield* useHostFiles(); +} + +function* useWorkspace(files: Record): Operation { + const root = yield* createWorkspace(files); + yield* useWorkspaceHost(root); return root; } @@ -256,29 +265,29 @@ describe("Tier TX — targeted execution", () => { 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); - }, - ); - }); + const secondStream = yield* useJournalStream(""); + const workspace = yield* createWorkspace({ "doc.md": SECTIONS }); + yield* captureTestJournal( + { owner: OWNER, name: tx6Name }, + formatDocumentReference(join(workspace, "doc.md"), "Beta"), + function* (firstStream) { + yield* useWorkspaceHost(workspace); + 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* () { diff --git a/packages/core/tests/evaluate-loaded-copy.test.ts b/packages/core/tests/evaluate-loaded-copy.test.ts index cfd5eb039..4dd616be4 100644 --- a/packages/core/tests/evaluate-loaded-copy.test.ts +++ b/packages/core/tests/evaluate-loaded-copy.test.ts @@ -19,9 +19,10 @@ * canonical core owns and a registration for it is refused outright (FE27b). */ -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 { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import type { DurableEvent, Json } from "@executablemd/durable-streams"; import { Ok, scoped } from "effection"; import type { Operation, Result } from "effection"; @@ -36,6 +37,13 @@ import { registerComponents } from "../src/components/registration.ts"; import { retainedSource } from "../src/root-source.ts"; import { recordedFiles, useRecordedFiles } from "./support/fragment-files.ts"; import type { RecordedFiles } from "./support/fragment-files.ts"; +import { + journalBeforeEach, + useJournalStream, + captureTestJournal, +} from "@executablemd/test-support/failure-journal"; + +const OWNER = "packages/core/tests/evaluate-loaded-copy.test.ts"; const ROOT_PATH = "evaluate.md"; const NOTE = "the retained note\n"; @@ -66,7 +74,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( @@ -94,6 +102,7 @@ const READS = `\\n'} as="answer" />\n\n` + `\n`; describe("Tier FE — nothing replaces the protected implementation", () => { + beforeEach(journalBeforeEach(OWNER)); it("FE24: the name cannot be registered at all", function* () { const reached: string[] = []; const failed = yield* refusal( @@ -121,54 +130,65 @@ describe("Tier FE — nothing replaces the protected implementation", () => { }); it("FE24: a live registration of the name does not exist to be selected", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The positive half of the row above: with the claim refused, an ordinary // document still resolves `` to canonical core's implementation // and the fragment runs. const files = recordedFiles({ "notes.md": NOTE }); - const output = yield* run(READS, [reading(files)]); + const output = yield* run(READS, [reading(files)], stream); expect(String(output)).toContain("the retained note"); expect(files.performed).toEqual(["read notes.md"]); }); - it("FE24: a middleware answer is refused, and honest delegation is not", function* () { - const files = recordedFiles({ "notes.md": NOTE }); - const substituted = yield* refusal( - scoped(function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - if (name !== "Evaluate" || definition.kind !== "function") { - return definition; - } - // A wrapper that forwards everything and changes nothing. Refused - // anyway: only canonical execution answers a protected import. - return { ...definition }; - }, - }); - return yield* run(READS, [reading(files)]); - }), - ); - expect(substituted).toContain("canonical core owns"); - expect(files.performed).toEqual([]); + const comparison = "FE24: a middleware answer is refused, and honest delegation is not"; + it(comparison, function* () { + yield* captureTestJournal({ owner: OWNER, name: comparison }, ROOT_PATH, function* (stream) { + const files = recordedFiles({ "notes.md": NOTE }); + const substituted = yield* refusal( + scoped(function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + if (name !== "Evaluate" || definition.kind !== "function") { + return definition; + } + // A wrapper that forwards everything and changes nothing. Refused + // anyway: only canonical execution answers a protected import. + return { ...definition }; + }, + }); + return yield* run(READS, [reading(files)], stream); + }), + ); + expect(substituted).toContain("canonical core owns"); + expect(files.performed).toEqual([]); - // The same handler, delegating honestly, is still supported. - const observed: string[] = []; - const clean = recordedFiles({ "notes.md": NOTE }); - const output = yield* scoped(function* () { - yield* Component.around({ - *importComponent([name], next) { - const definition = yield* next(name); - observed.push(name); - return definition; + // The same handler, delegating honestly, is still supported. + const observed: string[] = []; + const clean = recordedFiles({ "notes.md": NOTE }); + yield* captureTestJournal( + { owner: OWNER, name: comparison }, + ROOT_PATH, + function* (secondStream) { + const output = yield* scoped(function* () { + yield* Component.around({ + *importComponent([name], next) { + const definition = yield* next(name); + observed.push(name); + return definition; + }, + }); + return yield* run(READS, [reading(clean)], secondStream); + }); + expect(observed).toContain("Evaluate"); + expect(String(output)).toContain("the retained note"); }, - }); - return yield* run(READS, [reading(clean)]); + ); }); - expect(observed).toContain("Evaluate"); - expect(String(output)).toContain("the retained note"); }); it("FE24: a deliberate middleware refusal stays a refusal", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); const failed = yield* refusal( scoped(function* () { @@ -180,7 +200,7 @@ describe("Tier FE — nothing replaces the protected implementation", () => { return yield* next(name); }, }); - return yield* run(READS, [reading(files)]); + return yield* run(READS, [reading(files)], stream); }), ); @@ -190,6 +210,7 @@ describe("Tier FE — nothing replaces the protected implementation", () => { }); it("FE25: a replacement written to ignore `allow` is never invoked", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The replacement's body would write through the widest ambient permission // it can reach, under a read-only selection. It never runs, and canonical // `` refuses the write before any provider call. @@ -235,6 +256,7 @@ describe("Tier FE — nothing replaces the protected implementation", () => { return yield* run( `x\\n'} allow={["write"]} />\n`, [reading(files)], + stream, ); }), ); @@ -250,32 +272,48 @@ describe("Tier FE — nothing replaces the protected implementation", () => { }); describe("Tier FE — ownership is not permission", () => { - it("FE26: owning the name adds no class and no identity", function* () { - const files = recordedFiles(); - // A host offering only reads. Canonical `` cannot add a write - // table, and no spelling of `allow` conjures one. - expect( - yield* refusal( - run(`x\\n'} allow={["write"]} />\n`, [ - reading(files), - ]), - ), - ).toContain("installed no write table"); + beforeEach(journalBeforeEach(OWNER)); + const comparison = "FE26: owning the name adds no class and no identity"; + it(comparison, function* () { + yield* captureTestJournal({ owner: OWNER, name: comparison }, ROOT_PATH, function* (stream) { + const files = recordedFiles(); + // A host offering only reads. Canonical `` cannot add a write + // table, and no spelling of `allow` conjures one. + expect( + yield* refusal( + run( + `x\\n'} allow={["write"]} />\n`, + [reading(files)], + stream, + ), + ), + ).toContain("installed no write table"); - // And with a write table, the read table is still not part of `write`: - // selecting a class reaches that class's own entries and no others. - const mixed = recordedFiles({ "notes.md": NOTE }); - expect( - yield* refusal( - run(`\\n'} allow={["write"]} />\n`, [both(mixed)]), - ), - ).toContain("admitted only in its paired form"); - expect(mixed.performed).toEqual([]); + // And with a write table, the read table is still not part of `write`: + // selecting a class reaches that class's own entries and no others. + const mixed = recordedFiles({ "notes.md": NOTE }); + yield* captureTestJournal( + { owner: OWNER, name: comparison }, + ROOT_PATH, + function* (secondStream) { + expect( + yield* refusal( + run( + `\\n'} allow={["write"]} />\n`, + [both(mixed)], + secondStream, + ), + ), + ).toContain("admitted only in its paired form"); + expect(mixed.performed).toEqual([]); + }, + ); + }); }); it("FE27: a replaceable ordinary component still wins at an authored site", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); - const stream = new InMemoryStream(); const reached: string[] = []; const output = yield* scoped(function* () { // `` is an ordinary registration, so a repository or host component @@ -316,6 +354,7 @@ describe("Tier FE — ownership is not permission", () => { }); it("FE27b: an admitted name canonical core owns cannot be registered at all", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const files = recordedFiles({ "notes.md": NOTE }); // Where this used to prove that a *live* registration for `` could @@ -345,7 +384,7 @@ describe("Tier FE — ownership is not permission", () => { expect(failed).toContain("canonical core owns that name"); const output = yield* scoped(function* () { - return yield* run(READS, [reading(files)]); + return yield* run(READS, [reading(files)], stream); }); expect(String(output)).toContain("the retained note"); expect(files.performed).toEqual(["read notes.md"]); diff --git a/packages/core/tests/expansion-identity.test.ts b/packages/core/tests/expansion-identity.test.ts index f11e10ee4..eae248b85 100644 --- a/packages/core/tests/expansion-identity.test.ts +++ b/packages/core/tests/expansion-identity.test.ts @@ -20,6 +20,7 @@ import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { InMemoryStream } from "@executablemd/durable-streams"; +import { captureTestJournal } from "@executablemd/test-support/failure-journal"; import type { DurableEvent } from "@executablemd/durable-streams"; import { Component, content } from "../src/component-api.ts"; import { collect } from "../src/collect.ts"; @@ -131,7 +132,7 @@ function* useDocuments(names: string[], body: string): Operation { } /** Execute one document, collecting the identifiers `` saw. */ -function* executed(path: string, stream = new InMemoryStream()): Operation { +function* executed(path: string, stream: InMemoryStream): Operation { const seen: string[] = []; yield* scoped(function* () { yield* registerComponents([ @@ -217,6 +218,8 @@ function* expandedBody(bodySegments: Segment[]): Operation { return seen; } +const OWNER = "packages/core/tests/expansion-identity.test.ts"; + describe("Tier XP — expansion identity", () => { it("XP1: two elements written at different offsets get different identifiers", function* () { const seen = yield* identifiers("\n\n\n"); @@ -735,19 +738,30 @@ describe("Tier XP — expansion identity", () => { expect(yield* expandedBody([element("Probe"), outputRegion()])).toEqual(first); }); - it("XP19: the same element structure under two root documents differs", function* () { + const distinctRoots = "XP19: the same element structure under two root documents differs"; + it(distinctRoots, function* () { const [here, there] = yield* useDocuments(["a.md", "b.md"], "\n"); - const first = yield* executed(here!); - const second = yield* executed(there!); - - expect(first).toHaveLength(1); - expect(first[0]).not.toBe(second[0]); + const label = { owner: OWNER, name: distinctRoots }; + yield* captureTestJournal(label, here!, function* (stream) { + const first = yield* executed(here!, stream); + yield* captureTestJournal(label, there!, function* (secondStream) { + const second = yield* executed(there!, secondStream); + + expect(first).toHaveLength(1); + expect(first[0]).not.toBe(second[0]); + }); + }); }); - it("XP20: one root document reproduces its identifiers", function* () { + const repeatedRoot = "XP20: one root document reproduces its identifiers"; + it(repeatedRoot, function* () { const [only] = yield* useDocuments(["a.md"], "\n\n\n"); - - expect(yield* executed(only!)).toEqual(yield* executed(only!)); + const label = { owner: OWNER, name: repeatedRoot }; + yield* captureTestJournal(label, only!, function* (stream) { + yield* captureTestJournal(label, only!, function* (secondStream) { + expect(yield* executed(only!, stream)).toEqual(yield* executed(only!, secondStream)); + }); + }); }); // `` is consumed by its `` and never reaches expansion's diff --git a/packages/core/tests/file-delete-component.test.ts b/packages/core/tests/file-delete-component.test.ts index 3badc7eaa..5450963cd 100644 --- a/packages/core/tests/file-delete-component.test.ts +++ b/packages/core/tests/file-delete-component.test.ts @@ -18,7 +18,12 @@ * symlinks rather than following them. */ -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, Err, resource, scoped, until } from "effection"; import type { Operation, Result } from "effection"; @@ -94,16 +99,22 @@ function* useWorkspaceCwd(fixture: Fixture): Operation { * `execute()`, which is what lets a test wrap `API.Env` or `API.Files` and * count what the component actually reached for. */ -function run(fixture: Fixture, source: string, install?: () => Operation): Operation { +function run( + fixture: Fixture, + source: string, + install?: () => Operation, + suppliedStream?: InMemoryStream, +): Operation { return scoped(function* () { const path = join(fixture.workspace, "doc.md"); yield* writeTextFile(path, source); + const stream = suppliedStream ?? (yield* useJournalStream(path)); yield* useWorkspaceCwd(fixture); if (install) { yield* install(); } const output: Json = yield* collect( - yield* execute({ path, stream: new InMemoryStream(), includes: [fixture.workspace] }), + yield* execute({ path, stream, includes: [fixture.workspace] }), ); return String(output); }); @@ -186,11 +197,15 @@ function* useLyingContent(script: readonly boolean[], answered: boolean[]): Oper }); } +const OWNER = "packages/core/tests/file-delete-component.test.ts"; + describe("Tier FD — File.Delete", () => { + beforeEach(journalBeforeEach(OWNER)); // FD1: the ordinary case, and the whole of what a success looks like from the // document: the file is gone, and nothing is rendered or bound in its place. it("FD1: removes one regular file, rendering nothing and binding the empty string", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "obsolete.md"), "stale"); yield* writeTextFile(join(fixture.workspace, "kept.md"), "kept"); @@ -203,6 +218,8 @@ describe("Tier FD — File.Delete", () => { "", "[{gone}]", ].join("\n"), + undefined, + stream, ); // `as` captures the empty string the component returns, exactly as it does @@ -217,12 +234,14 @@ describe("Tier FD — File.Delete", () => { // is not sure it created. it("FD2: deleting a path that names nothing succeeds, twice", function* () { const fixture = yield* useFixture(); - + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const output = yield* run( fixture, ['', "", '', "", "done"].join( "\n", ), + undefined, + stream, ); expect(output).toContain("done"); @@ -234,8 +253,10 @@ describe("Tier FD — File.Delete", () => { // FD3: the shape of the invocation decides its one form, and paired-*empty* // is the case that says so — there is no rendered content to blame, so a // component that branched on rendered length would accept it. - it("FD3: paired content is refused before Env.cwd or the provider is reached", function* () { + const pairedDelete = "FD3: paired content is refused before Env.cwd or the provider is reached"; + it(pairedDelete, function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "kept.md"), "kept"); const reached: string[] = []; @@ -254,7 +275,7 @@ describe("Tier FD — File.Delete", () => { }); } - const output = yield* run(fixture, '', watch); + const output = yield* run(fixture, '', watch, stream); expect(output).toContain(" is self-closing"); expect(reached).toEqual([]); @@ -262,9 +283,15 @@ describe("Tier FD — File.Delete", () => { // The same watchers, on the form that is accepted. Without this the empty // list above would also be what a spy that never fired reports. - yield* run(fixture, '', watch); - expect(reached).toEqual(["cwd", "deleteFile"]); - expect(yield* exists(join(fixture.workspace, "kept.md"))).toBe(false); + yield* captureTestJournal( + { owner: OWNER, name: pairedDelete }, + join(fixture.workspace, "doc.md"), + function* (secondStream) { + yield* run(fixture, '', watch, secondStream); + expect(reached).toEqual(["cwd", "deleteFile"]); + expect(yield* exists(join(fixture.workspace, "kept.md"))).toBe(false); + }, + ); }); // FD4: a relative path means what the contextual directory says it means, and @@ -273,6 +300,7 @@ describe("Tier FD — File.Delete", () => { // stays, and the element after the region reaches the outer directory. it("FD4: Env.cwd selects the target, and lexical restoration is whole", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); const nested = join(fixture.workspace, "nested"); yield* ensureDir(nested); yield* writeTextFile(join(nested, "target.md"), "inner"); @@ -289,6 +317,7 @@ describe("Tier FD — File.Delete", () => { '', ].join("\n"), () => useNested(nested), + stream, ); expect(yield* exists(join(nested, "target.md"))).toBe(false); @@ -318,6 +347,7 @@ describe("Tier FD — File.Delete", () => { for (const [what, script] of DENYING) { it(`FD3b: a paired File.Delete removes nothing under ${what}`, function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "kept.md"), "kept"); yield* writeTextFile(join(fixture.workspace, "kept-empty.md"), "also kept"); yield* writeTextFile(join(fixture.workspace, "gone.md"), "removed"); @@ -352,6 +382,7 @@ describe("Tier FD — File.Delete", () => { }, }); }, + stream, ); // The handler is live, and the lie is visible on a component that does @@ -445,7 +476,8 @@ describe("Tier FD — File.Delete", () => { // they share — a printed error names the path the document wrote and nothing // the filesystem knows. The provider is the real host one, so what is under // test is the whole path from an authored string to a printed sentence. - it("FD5: each refusal names the authored path and no absolute one", function* () { + const pathRefusals = "FD5: each refusal names the authored path and no absolute one"; + it(pathRefusals, function* () { const fixture = yield* useFixture(); yield* writeTextFile(join(fixture.outside, "secret.txt"), "SECRET"); yield* ensureDir(join(fixture.workspace, "held")); @@ -484,15 +516,26 @@ describe("Tier FD — File.Delete", () => { // a removal that did not happen rather than a spy that never fired. const removed: string[] = []; yield* writeTextFile(join(fixture.workspace, "ordinary.txt"), "gone soon"); - yield* run(fixture, '', function* () { - yield* API.Fs.around({ - *remove([path, options], next) { - removed.push(path); - return yield* next(path, options); - }, - }); - }); - expect(removed).toEqual([join(fixture.workspace, "ordinary.txt")]); + yield* captureTestJournal( + { owner: OWNER, name: pathRefusals }, + join(fixture.workspace, "doc.md"), + function* (stream) { + yield* run( + fixture, + '', + function* () { + yield* API.Fs.around({ + *remove([path, options], next) { + removed.push(path); + return yield* next(path, options); + }, + }); + }, + stream, + ); + expect(removed).toEqual([join(fixture.workspace, "ordinary.txt")]); + }, + ); }); // FD6: an ordinary structural refusal from a provider is this component's own @@ -501,6 +544,7 @@ describe("Tier FD — File.Delete", () => { // nothing the provider chose. it("FD6: a structural provider refusal is printed, and changes nothing", function* () { const fixture = yield* useFixture(); + const stream = yield* useJournalStream(join(fixture.workspace, "doc.md")); yield* writeTextFile(join(fixture.workspace, "kept.md"), "kept"); const output = yield* run( @@ -516,6 +560,7 @@ describe("Tier FD — File.Delete", () => { }, }); }, + stream, ); expect(output).toContain('cannot delete "kept.md": permission denied.'); diff --git a/packages/core/tests/generated-owner-metadata.test.ts b/packages/core/tests/generated-owner-metadata.test.ts index e71f116d2..8e4f75b20 100644 --- a/packages/core/tests/generated-owner-metadata.test.ts +++ b/packages/core/tests/generated-owner-metadata.test.ts @@ -27,9 +27,10 @@ * takes its first copy of. */ -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 { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { scoped } from "effection"; import type { Operation } from "effection"; @@ -56,6 +57,7 @@ import { SYNTAX_PROTECTED } from "../src/components/Syntax.ts"; import { EVALUATE_PROTECTED } from "../src/components/Evaluate.ts"; import { pinnedJson } from "../src/generated-xmd.ts"; import type { ComponentRegistry, FunctionComponentDefinition, Json } from "../src/types.ts"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; /** The registry visible in the current scope. */ function currentRegistry(): Operation { @@ -506,6 +508,8 @@ describe("Tier GOM — a shared definition's metadata cannot be edited", () => { * a run that admitted the wrong URL and happened to fail later. */ describe("Tier GOM — a declared component's offer survives capture", () => { + const OWNER = "packages/core/tests/generated-owner-metadata.test.ts"; + beforeEach(journalBeforeEach(OWNER)); const ROOT_PATH = "owner.md"; /** A document naming the declared component in the spelling it offers. */ const NAMING_PROBE = `\\n'} />\n`; @@ -631,7 +635,7 @@ describe("Tier GOM — a declared component's offer survives capture", () => { }; it("GOM4: a host's factory declaration runs the spelling it offered", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(ROOT_PATH); const published: FunctionComponentDefinition[] = []; const output = yield* run([host(declaredProbe(READ_PROBE), published)], stream); @@ -644,6 +648,7 @@ describe("Tier GOM — a declared component's offer survives capture", () => { }); it("GOM4: capture reads the offer once, and construction uses that reading", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // The check/use gap at the installation boundary, where the host also gets // to run code in between: the accessor answers the accepted URL the first // time and a substituted one afterwards, so a construction that read the @@ -657,7 +662,6 @@ describe("Tier GOM — a declared component's offer survives capture", () => { return reads.length === 1 ? READ_PROBE : SUBSTITUTE; }, }; - const stream = new InMemoryStream(); const published: FunctionComponentDefinition[] = []; const output = yield* run([host(component, published)], stream); @@ -673,6 +677,7 @@ describe("Tier GOM — a declared component's offer survives capture", () => { }); it("GOM4: an offer replaced from inside install() has replaced nothing", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // A host's installation callback runs before the declared components are // built, so this is the window a live reference would be read through. const offers: { generated: GeneratedForms } = { generated: READ_PROBE }; @@ -682,7 +687,6 @@ describe("Tier GOM — a declared component's offer survives capture", () => { return offers.generated; }, }; - const stream = new InMemoryStream(); const published: FunctionComponentDefinition[] = []; const output = yield* run( @@ -702,7 +706,7 @@ describe("Tier GOM — a declared component's offer survives capture", () => { }); it("GOM4: an unusable offer refuses the execution, having run nothing", function* () { - const stream = new InMemoryStream(); + const stream = yield* useJournalStream(ROOT_PATH); const published: FunctionComponentDefinition[] = []; const unusable = { "self-closing": { identity: "not-a-url", effect: "read" as const } }; diff --git a/packages/core/tests/generated-selection.test.ts b/packages/core/tests/generated-selection.test.ts index a88902cf3..b6d28a654 100644 --- a/packages/core/tests/generated-selection.test.ts +++ b/packages/core/tests/generated-selection.test.ts @@ -301,23 +301,28 @@ describe("Tier GS — a selection core cannot capture refuses setup", () => { for (const [what, offered, diagnostic] of MALFORMED) { it(`U5-1: ${what} refuses before policy, the root import and any effect`, 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, - 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, + files, + *around(): Operation { + yield* useProducer(produced); + yield* Execution.around({ + *execute([request], next) { + policy.push("execute"); + yield* next(request); + }, + }); + }, }, - }); + stream, + ); expect([what, attempt.failure ?? ""]).toEqual([what, expect.stringContaining(diagnostic)]); // Nothing after setup happened: no public execution policy, no root @@ -820,32 +825,38 @@ describe("Tier GS — what a selected name resolves to", () => { }); it("U5-3: an unsupported answer refuses", function* () { + const stream = yield* useJournalStream(ROOT_PATH); // A repository Markdown component is a legitimate answer for an authored // import and is not something a generated fragment can be given: there is // no implementation to invoke and no declaration to read an identity off. - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Markdowny: ["self-closing"] }); - yield* Component.around({ - *importComponent([name, position], next) { - if (name !== "Markdowny") { - return yield* next(name, position); - } - return markdownAnswer(); - }, - }); + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Markdowny: ["self-closing"] }); + yield* Component.around({ + *importComponent([name, position], next) { + if (name !== "Markdowny") { + return yield* next(name, position); + } + return markdownAnswer(); + }, + }); + }, }, - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toBeDefined(); expect(attempt.failure).not.toContain("rendered"); }); it("U5-3: a definition edited after publication cannot be rebaselined", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const ran: string[] = []; const definition: FunctionComponentDefinition = { kind: "function", @@ -865,41 +876,45 @@ describe("Tier GS — what a selected name resolves to", () => { }, }; - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Edited: ["self-closing"] }); - }, - componentAnswers: [ - { - origin: "test://edited", - *install(registrar): Operation { - yield* registrar.around(function* (request, next) { - if (request.name !== "Edited") { - return yield* next(); - } - const published = request.answer(definition); - // Published, and then edited in place. What the execution - // retained is the copy taken at publication, so this reaches - // nothing — and the answer the chain is now holding no longer - // describes what was published, which refuses. - Object.assign(definition, { - generated: { - "self-closing": { - identity: "https://executable.md/components/edited/write", - effect: "write", + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Edited: ["self-closing"] }); + }, + componentAnswers: [ + { + origin: "test://edited", + *install(registrar): Operation { + yield* registrar.around(function* (request, next) { + if (request.name !== "Edited") { + return yield* next(); + } + const published = request.answer(definition); + // Published, and then edited in place. What the execution + // retained is the copy taken at publication, so this reaches + // nothing — and the answer the chain is now holding no longer + // describes what was published, which refuses. + Object.assign(definition, { + generated: { + "self-closing": { + identity: "https://executable.md/components/edited/write", + effect: "write", + }, }, - }, + }); + return published; }); - return published; - }); + }, }, - }, - ], - }, - ], - }); + ], + }, + ], + }, + stream, + ); expect(attempt.failure).toBeDefined(); expect(ran).toEqual([]); @@ -907,6 +922,7 @@ describe("Tier GS — what a selected name resolves to", () => { }); it("U5-3: accessor-backed metadata is refused before it can answer twice", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const readings: string[] = []; // A declaration whose metadata would answer one thing while it is validated // and another when it is read again. The reading that was validated is the @@ -939,16 +955,20 @@ describe("Tier GS — what a selected name resolves to", () => { }, }; - const attempt = yield* run(evaluating("\n"), { - installations: [ - { - *install(): Operation { - yield* useSelection({ Shifty: ["self-closing"] }); + const attempt = yield* run( + evaluating("\n"), + { + installations: [ + { + *install(): Operation { + yield* useSelection({ Shifty: ["self-closing"] }); + }, + componentAnswers: [answerProvider("Shifty", definition)], }, - componentAnswers: [answerProvider("Shifty", definition)], - }, - ], - }); + ], + }, + stream, + ); expect(attempt.failure).toBeDefined(); expect(attempt.output ?? "").not.toContain("the shifty answer ran"); diff --git a/packages/core/tests/named-slots.test.ts b/packages/core/tests/named-slots.test.ts index 8b399b9c0..9cb73e139 100644 --- a/packages/core/tests/named-slots.test.ts +++ b/packages/core/tests/named-slots.test.ts @@ -6,7 +6,8 @@ * boundary scanner confirmation, and nested projection points. */ -import { describe, it, beforeAll } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it, beforeAll } from "@executablemd/test-support/bdd"; + import { useTempFileCompiler } from "../src/temp-file-compiler.ts"; import { expect } from "@executablemd/test-support/expect"; import { scoped } from "effection"; @@ -26,6 +27,8 @@ import type { Segment, ComponentDefinition, Json, CodeBlockResult } from "../src import { ensureDir, readTextFile, writeTextFile } from "@effectionx/fs"; import { useTempDirectory } from "@executablemd/test-support/temp"; import * as path from "node:path"; +import { join } from "node:path"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; function makeComponent( name: string, @@ -667,10 +670,14 @@ describe("Tier NS-D — slot prop reservation", () => { }); }); +const OWNER = "packages/core/tests/named-slots.test.ts"; + describe("Tier NS-E — renderChildren interaction", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("NS-E1: renderChildren includes all slots", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); const sampleMd = yield* readTextFile( path.join(process.cwd(), "packages/core/components/Sample.md"), ); @@ -688,7 +695,6 @@ describe("Tier NS-E — renderChildren interaction", () => { "", ].join("\n"), }); - const stream = new InMemoryStream(); const output = yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), @@ -703,6 +709,7 @@ describe("Tier NS-E — renderChildren interaction", () => { it("NS-E2: Sample component with slotted content — all content captured", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); const sampleMd = yield* readTextFile( path.join(process.cwd(), "packages/core/components/Sample.md"), ); @@ -722,7 +729,6 @@ describe("Tier NS-E — renderChildren interaction", () => { "", ].join("\n"), }); - const stream = new InMemoryStream(); const output = yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), @@ -737,6 +743,7 @@ describe("Tier NS-E — renderChildren interaction", () => { it("NS-E3: renderChildren preserves order", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); const sampleMd = yield* readTextFile( path.join(process.cwd(), "packages/core/components/Sample.md"), ); @@ -757,7 +764,6 @@ describe("Tier NS-E — renderChildren interaction", () => { "", ].join("\n"), }); - const stream = new InMemoryStream(); const output = yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), @@ -772,6 +778,7 @@ describe("Tier NS-E — renderChildren interaction", () => { }); describe("Tier NS-F — Edge cases", () => { + beforeEach(journalBeforeEach(OWNER)); it("NS-F1: slot on self-closing component", function* () { const layout = makeComponent("Layout", '\n'); const badge = makeComponent("Badge", "BADGE"); @@ -866,6 +873,7 @@ describe("Tier NS-F — Edge cases", () => { it("NS-F7: journal shape unchanged", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); yield* writeFiles(tmpDir, { "components/Layout.md": [ "---", @@ -878,7 +886,6 @@ describe("Tier NS-F — Edge cases", () => { "---\nprops: { type: object, properties: {}, additionalProperties: false }\n---\nHEADER", "doc.md": '\n
\nbody\n', }); - const stream = new InMemoryStream(); yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), @@ -972,6 +979,7 @@ describe("Tier NS-G — Boundary scanner", () => { }); describe("Tier NS-H — Nested projection points", () => { + beforeEach(journalBeforeEach(OWNER)); it("NS-H1: inside another component invocation", function* () { const echo = makeComponent("Echo", "ECHO()"); const host = makeComponent("Host", "prefix suffix"); @@ -1031,6 +1039,7 @@ describe("Tier NS-H — Nested projection points", () => { it("NS-H7: nested inside a structural construct", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); yield* writeFiles(tmpDir, { "components/HostCap.md": [ "---", @@ -1044,7 +1053,7 @@ describe("Tier NS-H — Nested projection points", () => { const output = yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [path.join(tmpDir, "components"), tmpDir], }), ); @@ -1053,6 +1062,7 @@ describe("Tier NS-H — Nested projection points", () => { it("NS-H8: nested inside an iterating construct", function* () { const tmpDir = yield* useTempDirectory("named-slots-test-"); + const stream = yield* useJournalStream(join(tmpDir, "doc.md")); yield* writeFiles(tmpDir, { "components/EachHost.md": [ "---", @@ -1067,7 +1077,7 @@ describe("Tier NS-H — Nested projection points", () => { const output = yield* collect( yield* execute({ path: path.join(tmpDir, "doc.md"), - stream: new InMemoryStream(), + stream, includes: [path.join(tmpDir, "components"), tmpDir], }), ); diff --git a/packages/core/tests/syntax-api.test.ts b/packages/core/tests/syntax-api.test.ts index 4693e5958..41b4de7a9 100644 --- a/packages/core/tests/syntax-api.test.ts +++ b/packages/core/tests/syntax-api.test.ts @@ -1,4 +1,5 @@ -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 { type Api, createApi } from "@effectionx/context-api"; import { call, ensure, scoped, until } from "effection"; @@ -25,6 +26,11 @@ import { executeInstalled, useSyntax, Structural } from "../host.ts"; import { inspectSyntax } from "../src/inspect.ts"; import { syntaxReference } from "../src/syntax-reference.ts"; import { selecting } from "./support/generated-selection.ts"; +import { + journalBeforeEach, + useJournalStream, + captureTestJournal, +} from "@executablemd/test-support/failure-journal"; function symbolsOf(...names: string[]): SyntaxSymbols { return { @@ -65,7 +71,9 @@ function without(symbols: SyntaxSymbols, name: string): SyntaxSymbols { }; } -function* run(text: string, stream = new InMemoryStream()): Operation { +const OWNER = "packages/core/tests/syntax-api.test.ts"; + +function* run(text: string, stream: InMemoryStream): Operation { return String( yield* collect( yield* executeInstalled({ ...inlineSource(text), stream, includes: [] }, [ @@ -139,6 +147,7 @@ describe("1178 reference specialization", () => { }); describe("Tier SA — contextual Syntax", () => { + beforeEach(journalBeforeEach(OWNER)); it("SA: structural availability compares complete installed identity and keeps enclosing references", function* () { const declaration = Structural({ name: "Banner", @@ -263,6 +272,7 @@ describe("Tier SA — contextual Syntax", () => { }); it("SA4: moving named occurrences resolve one basis each and record the final transformed answer", function* () { + const stream = yield* useJournalStream(""); let reads = 0; let symbols = 0; yield* useSyntax(function* () { @@ -277,7 +287,6 @@ describe("Tier SA — contextual Syntax", () => { return `${yield* next(names)}\nFINAL NAMED`; }, }); - const stream = new InMemoryStream(); const source = '\n\n'; const output = yield* run(source, stream); expect(output).toContain("Marker1"); @@ -340,29 +349,48 @@ describe("Tier SA — contextual Syntax", () => { expect(yield* run(source, partial)).toBe(first); }); - it("SA6: generated descriptions retain host-only metadata and never grant execution", function* () { - let reads = 0; - yield* useSyntax(function* () { - reads += 1; - return symbolsOf("HostOnly"); - }); - const output = yield* run( - "'} />\n\n", - ); - expect(output).toContain("### ``"); - expect(output).toContain("**Available in this evaluation:** no"); - expect(reads).toBe(2); - yield* Syntax.around({ - *symbols() { - return symbolsOf("HostOnly"); + const generatedSyntax = + "SA6: generated descriptions retain host-only metadata and never grant execution"; + it(generatedSyntax, function* () { + yield* captureTestJournal( + { owner: OWNER, name: generatedSyntax }, + "", + function* (stream) { + let reads = 0; + yield* useSyntax(function* () { + reads += 1; + return symbolsOf("HostOnly"); + }); + const output = yield* run( + "'} />\n\n", + stream, + ); + expect(output).toContain("### ``"); + expect(output).toContain("**Available in this evaluation:** no"); + expect(reads).toBe(2); + yield* Syntax.around({ + *symbols() { + return symbolsOf("HostOnly"); + }, + }); + yield* captureTestJournal( + { owner: OWNER, name: generatedSyntax }, + "", + function* (refusedStream) { + const refused = yield* run( + "'} />\n", + refusedStream, + ); + expect(refused).toContain("a component this host did not admit"); + expect(refused).not.toContain("No long-form documentation"); + }, + ); }, - }); - const refused = yield* run("'} />\n"); - expect(refused).toContain("a component this host did not admit"); - expect(refused).not.toContain("No long-form documentation"); + ); }); it("SA7: a descriptive filter cannot disable an admitted generated component", function* () { + const stream = yield* useJournalStream(""); yield* Syntax.around({ *symbols() { return symbolsOf(); @@ -373,35 +401,42 @@ describe("Tier SA — contextual Syntax", () => { return "ADMITTED SYNTAX RAN"; }, }); - expect(yield* run("'} />\n")).toContain("ADMITTED SYNTAX RAN"); + expect(yield* run("'} />\n", stream)).toContain( + "ADMITTED SYNTAX RAN", + ); }); - it("SA8: canonical unknown names are safe records; provider-thrown UnknownComponentError is terminal", function* () { - const stream = new InMemoryStream(); - yield* useSyntax(function* () { - return symbolsOf("HostOnly"); - }); - yield* run('\n', stream); - const record = stream - .snapshot() - .find((event) => event.type === "yield" && event.description.type === "syntax_symbols"); - expect(record?.type === "yield" ? record.result.status : "absent").toBe("ok"); - expect(JSON.stringify(record)).toContain('"refused"'); - yield* scoped(function* () { - yield* useSyntax(function* (): Operation { - throw new UnknownComponentError("provider failure"); + const unknownNames = + "SA8: canonical unknown names are safe records; provider-thrown UnknownComponentError is terminal"; + it(unknownNames, function* () { + yield* captureTestJournal({ owner: OWNER, name: unknownNames }, "", function* (stream) { + yield* useSyntax(function* () { + return symbolsOf("HostOnly"); }); - const failed = new InMemoryStream(); - yield* run('\n', failed); - const retained = failed + yield* run('\n', stream); + const record = stream .snapshot() .find((event) => event.type === "yield" && event.description.type === "syntax_symbols"); - expect(retained?.type === "yield" ? retained.result.status : "absent").toBe("err"); - expect(JSON.stringify(retained)).toContain("provider failure"); + expect(record?.type === "yield" ? record.result.status : "absent").toBe("ok"); + expect(JSON.stringify(record)).toContain('"refused"'); + yield* captureTestJournal({ owner: OWNER, name: unknownNames }, "", function* (failed) { + yield* scoped(function* () { + yield* useSyntax(function* (): Operation { + throw new UnknownComponentError("provider failure"); + }); + yield* run('\n', failed); + const retained = failed + .snapshot() + .find((event) => event.type === "yield" && event.description.type === "syntax_symbols"); + expect(retained?.type === "yield" ? retained.result.status : "absent").toBe("err"); + expect(JSON.stringify(retained)).toContain("provider failure"); + }); + }); }); }); it("SA9: independently constructed same-name descriptors share ordinary middleware", function* () { + const stream = yield* useJournalStream(""); const other: Api = createApi("executablemd.core.syntax", { symbols: call(function* (): Operation { throw new Error("foreign default must not run"); @@ -418,6 +453,6 @@ describe("Tier SA — contextual Syntax", () => { return "OTHER DESCRIPTOR"; }, }); - expect(yield* run("\n")).toContain("OTHER DESCRIPTOR"); + expect(yield* run("\n", stream)).toContain("OTHER DESCRIPTOR"); }); }); diff --git a/packages/core/tests/syntax-loaded-copy.test.ts b/packages/core/tests/syntax-loaded-copy.test.ts index 4d529ab70..f95243da7 100644 --- a/packages/core/tests/syntax-loaded-copy.test.ts +++ b/packages/core/tests/syntax-loaded-copy.test.ts @@ -41,7 +41,8 @@ * the only one a locally rebuilt definition cannot stand in for. */ -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"; @@ -49,7 +50,7 @@ import { useSelection } from "./support/generated-selection.ts"; import { rm, writeTextFile } from "@effectionx/fs"; import { exec } from "@effectionx/process"; import { API, Files, useHostFiles } from "@executablemd/runtime"; -import { InMemoryStream } from "@executablemd/durable-streams"; +import type { InMemoryStream } from "@executablemd/durable-streams"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -66,6 +67,11 @@ import { fixedFilesystemDefinition } from "../src/components/fixed-filesystem.ts import { form as fileForm, props as fileProps } from "../src/components/File.ts"; import { parseJsonObject } from "../src/json.ts"; import type { FunctionComponentDefinition } from "../src/types.ts"; +import { + journalBeforeEach, + useJournalStream, + captureTestJournal, +} from "@executablemd/test-support/failure-journal"; const PROTECTION_MODULE = fileURLToPath(new URL("../src/invocation-identity.ts", import.meta.url)); const REPOSITORY = fileURLToPath(new URL("../../../", import.meta.url)); @@ -256,7 +262,12 @@ function answering(definition: unknown): ExecutionInstallation { }; } +const OWNER = "packages/core/tests/syntax-loaded-copy.test.ts"; + +const ROOT_PATH = "documents/root.md"; + function runRoot( + stream: InMemoryStream, installations: readonly ExecutionInstallation[], source = "\n", ): Operation { @@ -264,8 +275,8 @@ function runRoot( return yield* collect( yield* executeInstalled( { - ...retainedSource("documents/root.md", source), - stream: new InMemoryStream(), + ...retainedSource(ROOT_PATH, source), + stream, includes: [], }, [...installations], @@ -284,107 +295,128 @@ function* refusal(operation: Operation): Operation { } describe("Tier SYN — a separately loaded protected implementation", () => { - it("SYN26: an implementation another copy built answers for nothing here", function* () { - const copy = yield* useSeparateCopy(); - - // An installation the other copy performed: it minted the domain, built the - // implementation and kept the body in its own table. Nothing here is a fake - // — this is that copy's real protected-component path. - const installed = copy.installIdentities( - [], - [], - [ - { - name: SYNTAX_COMPONENT, - origin: "@executablemd/core", - props: syntaxProps, - forms: ["self-closing"], - // deno-lint-ignore require-yield - build: () => - // deno-lint-ignore require-yield - function* (): Operation { - return "a foreign catalog"; - }, - }, - ], - ); - yield* ensure(() => installed.identities.revoke()); - installed.activate(); - const foreign = installed.protected.get(SYNTAX_COMPONENT); - if (foreign === undefined) { - throw new Error("the bundled copy built no protected implementation"); - } - // The premise, stated as a fact rather than assumed: that copy holds a body - // for its own implementation. - expect(installed.componentRouting.body(foreign.fn)).toBeDefined(); - - const refused = yield* refusal(runRoot([answering(foreign)])); - expect(refused).toContain("canonical core owns"); - - // The positive control, in the same shape: a handler that delegates and - // answers with what came back runs the canonical component. - const output = yield* runRoot([ - { - *install() { - yield* Component.around( + const protectedSyntax = "SYN26: an implementation another copy built answers for nothing here"; + it(protectedSyntax, function* () { + yield* captureTestJournal( + { owner: OWNER, name: protectedSyntax }, + ROOT_PATH, + function* (stream) { + const copy = yield* useSeparateCopy(); + + // An installation the other copy performed: it minted the domain, built the + // implementation and kept the body in its own table. Nothing here is a fake + // — this is that copy's real protected-component path. + const installed = copy.installIdentities( + [], + [], + [ { - *importComponent([name, position], next) { - return yield* next(name, position); - }, + name: SYNTAX_COMPONENT, + origin: "@executablemd/core", + props: syntaxProps, + forms: ["self-closing"], + // deno-lint-ignore require-yield + build: () => + // deno-lint-ignore require-yield + function* (): Operation { + return "a foreign catalog"; + }, }, - { at: "max" }, - ); - }, - }, - ]); - expect(String(output)).toContain("### ``"); - expect(String(output)).not.toContain("a foreign catalog"); - - const forged = function* (): Operation { - return "foreign projection"; - }; - const projected: unknown[] = []; - const observed: string[] = []; - const profile: ExecutionInstallation = { - *install(): Operation { - yield* useSelection({ Syntax: ["self-closing"] }); - }, - componentAnswers: [ - { - origin: "test://delegate", - *install(registrar) { - yield* registrar.around(function* (request, next) { - const answer = yield* next(); - if (request.name === "Syntax" && answer.kind === "function") { - observed.push(request.name); - projected.push(installed.componentRouting.project(answer.fn, forged)); - } - // Delegated unchanged, so canonical core's own publication of the - // protected answer travels with it. A separately loaded copy may - // answer an import it was handed; what it cannot do is route a - // body of its own into the one the fragment reaches. - return answer; - }); + ], + ); + yield* ensure(() => installed.identities.revoke()); + installed.activate(); + const foreign = installed.protected.get(SYNTAX_COMPONENT); + if (foreign === undefined) { + throw new Error("the bundled copy built no protected implementation"); + } + // The premise, stated as a fact rather than assumed: that copy holds a body + // for its own implementation. + expect(installed.componentRouting.body(foreign.fn)).toBeDefined(); + + const refused = yield* refusal(runRoot(stream, [answering(foreign)])); + expect(refused).toContain("canonical core owns"); + + // The positive control, in the same shape: a handler that delegates and + // answers with what came back runs the canonical component. + yield* captureTestJournal( + { owner: OWNER, name: protectedSyntax }, + ROOT_PATH, + function* (secondStream) { + const output = yield* runRoot(secondStream, [ + { + *install() { + yield* Component.around( + { + *importComponent([name, position], next) { + return yield* next(name, position); + }, + }, + { at: "max" }, + ); + }, + }, + ]); + expect(String(output)).toContain("### ``"); + expect(String(output)).not.toContain("a foreign catalog"); + + const forged = function* (): Operation { + return "foreign projection"; + }; + const projected: unknown[] = []; + const observed: string[] = []; + const profile: ExecutionInstallation = { + *install(): Operation { + yield* useSelection({ Syntax: ["self-closing"] }); + }, + componentAnswers: [ + { + origin: "test://delegate", + *install(registrar) { + yield* registrar.around(function* (request, next) { + const answer = yield* next(); + if (request.name === "Syntax" && answer.kind === "function") { + observed.push(request.name); + projected.push(installed.componentRouting.project(answer.fn, forged)); + } + // Delegated unchanged, so canonical core's own publication of the + // protected answer travels with it. A separately loaded copy may + // answer an import it was handed; what it cannot do is route a + // body of its own into the one the fragment reaches. + return answer; + }); + }, + }, + ], + }; + yield* captureTestJournal( + { owner: OWNER, name: protectedSyntax }, + ROOT_PATH, + function* (thirdStream) { + const generated = yield* runRoot( + thirdStream, + [profile], + `'} as="answer" />\n`, + ); + expect(String(generated)).toContain("### ``"); + expect(String(generated)).not.toContain("foreign projection"); + expect(observed).toEqual(["Syntax", "Syntax"]); + expect(projected).toEqual([undefined, undefined]); + expect(installed.componentRouting.body(forged)).toBeUndefined(); + }, + ); }, - }, - ], - }; - const generated = yield* runRoot( - [profile], - `'} as="answer" />\n`, + ); + }, ); - expect(String(generated)).toContain("### ``"); - expect(String(generated)).not.toContain("foreign projection"); - expect(observed).toEqual(["Syntax", "Syntax"]); - expect(projected).toEqual([undefined, undefined]); - expect(installed.componentRouting.body(forged)).toBeUndefined(); }); }); describe("Tier FE14 — a separately loaded provider publishes its own answer", () => { + beforeEach(journalBeforeEach(OWNER)); it("FE14/U4-7: loaded provider code publishes through the handed request, and the fragment runs it", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const loaded = yield* useLoadedProvider(); - const stream = new InMemoryStream(); // The selection states the name and the spelling; what offering it grants // comes from the loaded module's own declaration. @@ -399,7 +431,7 @@ describe("Tier FE14 — a separately loaded provider publishes its own answer", return yield* collect( yield* executeInstalled( { - ...retainedSource("documents/root.md", `\\n'} />\n`), + ...retainedSource(ROOT_PATH, `\\n'} />\n`), stream, includes: [], }, @@ -429,7 +461,9 @@ describe("Tier FE14 — a separately loaded provider publishes its own answer", }); describe("Tier FX — a fixed definition from a separately loaded copy", () => { + beforeEach(journalBeforeEach(OWNER)); it("FX3g: another copy's File dispatcher answers for nothing, and reaches no I/O", function* () { + const stream = yield* useJournalStream(ROOT_PATH); const copy = yield* useSeparateCopy(); // The other shape in the protected tier. `` is answered with an @@ -467,6 +501,7 @@ describe("Tier FX — a fixed definition from a separately loaded copy", () => { const refused = yield* refusal( runRoot( + stream, [ { *install() { diff --git a/packages/workflow/tests/workspace-effect-loaded-copy.test.ts b/packages/workflow/tests/workspace-effect-loaded-copy.test.ts index acd80ca1f..5365ca4f9 100644 --- a/packages/workflow/tests/workspace-effect-loaded-copy.test.ts +++ b/packages/workflow/tests/workspace-effect-loaded-copy.test.ts @@ -1,4 +1,5 @@ -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 { ensureDir, readTextFile, rm, writeTextFile } from "@effectionx/fs"; import { createApi } from "@effectionx/context-api"; @@ -55,6 +56,7 @@ import type { GitHostCompletion, GitHostObservation, } from "@executablemd/git/api"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; /** * The admissions the Git Plugin contributes, as a host installing it receives @@ -418,10 +420,13 @@ describe("Tier DLC — physical Workspace package composition", () => { * copy buys a place in the middleware chain and nothing else: no credential, no * capability, no answer, and no route to the invocation's own terminal. */ +const OWNER = "packages/workflow/tests/workspace-effect-loaded-copy.test.ts"; + describe("Tier DLG — physical Git-host package composition", () => { + beforeEach(journalBeforeEach(OWNER)); it("DLG1: one copy's provider serves the other copy's reconciliation", function* () { + const stream = yield* useJournalStream(""); const copy = yield* physicalGitHostCopy(); - const stream = new InMemoryStream(); const observed: unknown[] = []; const captured: unknown[] = []; const refused: unknown[] = []; @@ -502,8 +507,8 @@ describe("Tier DLG — physical Git-host package composition", () => { }); it("DLG2: the other copy's reconciliation runs under this copy's provider", function* () { + const stream = yield* useJournalStream(""); const copy = yield* physicalGitHostCopy(); - const stream = new InMemoryStream(); const observed: unknown[] = []; const seen = gitHostAttempt();