diff --git a/examples/repl-bench/tests/mounted-typing.test.ts b/examples/repl-bench/tests/mounted-typing.test.ts index 9a6b73d13..6d51c53f3 100644 --- a/examples/repl-bench/tests/mounted-typing.test.ts +++ b/examples/repl-bench/tests/mounted-typing.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import type { Operation } from "effection"; import { useReplPage } from "../../../packages/cli/tests/support/repl-page.ts"; @@ -11,6 +12,8 @@ import { generateTypingHistory } from "../../../packages/cli/tests/support/typin import { EDITS, VIEWPORT, WARMUP, WORKLOADS } from "../lib/typing-latency-report.ts"; import type { TypingSample } from "../lib/typing-latency-report.ts"; +const OWNER = "examples/repl-bench/tests/mounted-typing.test.ts"; + const MARKER = "XMD:"; const CHARACTERS = "abcdefghijklmnopqrstuvwxyz".repeat(2).slice(0, EDITS); const revision = Deno.env.get("XMD_TYPING_BENCH_REVISION"); @@ -62,6 +65,7 @@ function* sampleTyping(page: ReplPage): Operation { if (revision !== undefined) { describe("mounted REPL typing latency", () => { + beforeEach(journalBeforeEach(OWNER)); for (const workload of WORKLOADS) { it(workload.name, function* () { const page = yield* useReplPage({ size: VIEWPORT }); diff --git a/packages/cli/src/test-diagnostics.ts b/packages/cli/src/test-diagnostics.ts index acf72adbe..280ab68fc 100644 --- a/packages/cli/src/test-diagnostics.ts +++ b/packages/cli/src/test-diagnostics.ts @@ -32,7 +32,7 @@ import type { DurableEvent } from "@executablemd/durable-streams"; import { Test, testing } from "@executablemd/testing"; import type { FailureJournalHost, TestResult } from "@executablemd/testing"; import { randomUUID } from "node:crypto"; -import { isAbsolute, join, relative, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { deliverWhole } from "./stdout-delivery.ts"; import type { DeliverySink } from "./stdout-delivery.ts"; @@ -79,6 +79,20 @@ export interface ExecutionDiagnostics { observe(): Operation; /** Saves this execution's journal when `failed` says its outcome failed. */ journal(failed: (value: T) => boolean): FailureJournalHost; + /** + * Saves journal files a host wrote for this execution, as the UTF-8 text + * they held, beneath one directory named like this execution's journal. + * + * `path` is each file's place beneath the storage root, so two files of one + * root keep the names that tell them apart. + */ + saveFiles(files: readonly SavedJournalFile[]): Operation; +} + +/** One journal file as its host wrote it. */ +export interface SavedJournalFile { + readonly path: string; + readonly text: string; } /** @@ -167,6 +181,22 @@ function testDiagnosticsAt( const displayedSource = shown(source); const named = `${kind} ${ordinal} ${displayedSource}${profile === undefined ? "" : ` (${profile})`}`; const context = kind === "root" ? "" : `${named}: `; + function* identify(files?: readonly string[]): Operation { + yield* ensureDir(directory); + if (attribution !== undefined) { + yield* writeTextFile( + `${stem}.case.json`, + JSON.stringify({ + ...attribution, + kind, + ordinal, + source: displayedSource, + profile, + files, + }) + "\n", + ); + } + } return { observe: () => observe( @@ -186,19 +216,7 @@ function testDiagnosticsAt( journal: (failed: (value: T) => boolean): FailureJournalHost => ({ failed, *save(events: readonly DurableEvent[]) { - yield* ensureDir(directory); - if (attribution !== undefined) { - yield* writeTextFile( - `${stem}.case.json`, - JSON.stringify({ - ...attribution, - kind, - ordinal, - source: displayedSource, - profile, - }) + "\n", - ); - } + yield* identify(); yield* writeTextFile(file, events.map(serializeDurableEvent).join("")); emit(`journal saved: ${file} (${named})`); }, @@ -207,6 +225,15 @@ function testDiagnosticsAt( emit(`journal not saved for ${named}: ${error.message}`); }, }), + *saveFiles(files: readonly SavedJournalFile[]) { + yield* identify(files.map(({ path }) => path)); + for (const { path, text } of files) { + const target = join(stem, path); + yield* ensureDir(dirname(target)); + yield* writeTextFile(target, text); + } + emit(`journal saved: ${stem} (${named})`); + }, }; }, delivery: () => delivery, diff --git a/packages/cli/tests/fixtures/mounted-failure-journal.ts b/packages/cli/tests/fixtures/mounted-failure-journal.ts new file mode 100644 index 000000000..1ebddbef7 --- /dev/null +++ b/packages/cli/tests/fixtures/mounted-failure-journal.ts @@ -0,0 +1,406 @@ +/** + * Synthetic mounted cases for `mounted-failure-journal.test.ts`, run as a child + * test file under the parent's own runtime. + * + * Each case drives the real mounted REPL over real file storage and copies the + * histories that storage held to `XMD_MOUNTED_WITNESS`, outside the directory + * its host removes, so the parent can compare a saved failure journal with what + * the command actually wrote. Each case also records, from its own teardown + * after every mounted scope has unwound, which data roots it mounted and + * whether each still exists. + */ + +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { expect } from "@executablemd/test-support/expect"; +import { journalBeforeEach, useJournalStream } from "@executablemd/test-support/failure-journal"; +import { exists, readTextFile, writeTextFile, ensureDir } from "@effectionx/fs"; +import { API, env } from "@executablemd/runtime"; +import { createContext, ensure, race, scoped, sleep, spawn, withResolvers } from "effection"; +import type { Operation } from "effection"; +import { dirname, join } from "node:path"; + +import { useReplPage } from "../support/repl-page.ts"; +import type { ReplPage } from "../support/repl-page.ts"; +import { appendGate, awaited, mountedExecution, useMountedHost } from "../support/mounted-repl.ts"; +import { asked, intoDraft, sendMessage, tab, typed } from "../support/screen-journeys.ts"; +import { pairedLocation, SIDEKICK_FILE } from "../../src/repl/sidekick/history.ts"; +import { executionPath } from "../../src/repl/journal.ts"; +import { useTemporary } from "./repl/issue-883/sidekick-harness.ts"; + +const OWNER = "packages/cli/tests/fixtures/mounted-failure-journal.ts"; + +const WIDE = { columns: 160, rows: 36 }; + +/** How long the deadline case waits for a reply its turn never sends. */ +const CASE_DEADLINE_MS = 500; + +/** + * How long the held append stays held once its case has failed, so the host's + * teardown is demonstrably waiting on it rather than merely not yet reached. + */ +const HELD_MS = 300; + +/** + * How long the rescue in the held-message case watches a failed case's hold + * before letting it go itself. Its own owner releases it as the failure leaves, + * so a rescue that finds it still held is evidence the owner never did. + */ +const RESCUE_MS = 500; + +/** A session another run left beside this one, under an identifier that is not hex. */ +const SECOND_SESSION = "Second_session-1"; + +/** A direct legacy history beside the paired ones. */ +const LEGACY_SESSION = "Legacy-Run_2"; + +/** + * Non-ASCII text, and a final record a write left unfinished: no newline, and + * ending in a multi-byte character that is still whole. + */ +const LEGACY_TEXT = + '{"type":"close","coroutineId":"root","result":{"status":"ok","value":"é☃"}}\n' + + '{"type":"yield","coroutineId":"root","partial":"naïve ☃'; + +/** One case's witness directory, and the roots it mounted, in mount order. */ +interface Witness { + readonly directory: string; + readonly roots: string[]; +} + +const Witnessed = createContext("mounted-failure-journal/witness"); + +/** + * This case's witness, its own artifact directory, and the record its teardown + * leaves once every mounted scope it opened has unwound. + */ +function witnessCase(name: string): () => Operation { + return function* () { + const artifacts = yield* env("XMD_TEST_ARTIFACTS"); + const witnesses = yield* env("XMD_MOUNTED_WITNESS"); + if (!artifacts || !witnesses) { + throw new Error("The mounted journal witness needs an artifact and a witness directory."); + } + yield* API.Env.around({ + *env([variable], next) { + return variable === "XMD_TEST_ARTIFACTS" ? join(artifacts, name) : yield* next(variable); + }, + }); + const witness: Witness = { directory: join(witnesses, name), roots: [] }; + yield* Witnessed.set(witness); + // Acquired before the case body, so it runs after everything the body + // acquired: what it records is the state that teardown actually left. + yield* ensure(function* () { + const roots: { root: string; exists: boolean }[] = []; + for (const root of witness.roots) { + roots.push({ root, exists: yield* exists(root) }); + } + yield* writeWitness(witness, "teardown.json", JSON.stringify({ roots }) + "\n"); + }); + }; +} + +function* writeWitness(witness: Witness, path: string, text: string): Operation { + const target = join(witness.directory, path); + yield* ensureDir(dirname(target)); + yield* writeTextFile(target, text); +} + +/** Copy this root's paired histories of `execution`, as the command left them. */ +function* copyPair(ordinal: number, root: string, execution: string): Operation { + const witness = yield* Witnessed.expect(); + const location = pairedLocation(root, execution); + for (const [name, path] of [ + ["entries.jsonl", location.entries], + ["sidekick.jsonl", location.sidekick], + ]) { + yield* writeWitness( + witness, + join(`root-${ordinal}`, "v1", execution, name), + yield* readTextFile(path), + ); + } +} + +/** Mount the real command and remember the root it stores its histories in. */ +function* mounted( + options: Parameters[0] = {}, +): Operation<{ page: ReplPage; ordinal: number }> { + const witness = yield* Witnessed.expect(); + const page = yield* useReplPage({ size: WIDE, ...options }); + witness.roots.push(page.repl.root); + return { page, ordinal: witness.roots.length }; +} + +/** + * One Sidekick exchange and one entry of a person's own, both settled. + * + * The message spells `word` in lower case so that only the reply draws it. + */ +function* exchange(page: ReplPage, word: string): Operation { + page.repl.fake.script({ reply: `${word}\n` }); + yield* asked(page, `reply ${word.toLowerCase()}`, word); + yield* intoDraft(page); + yield* typed(page, `entry ${word}`); + // Enter in the Round editor breaks the line; the Round's own Send runs it. + yield* tab(page); + yield* page.key("Enter"); + yield* page.until("the entry settling", (one) => one.shows("1 ✓")); +} + +/** Leave the command and wait for it to return. */ +function* exit(page: ReplPage): Operation { + yield* page.press("[exit]"); + yield* awaited("Exit joined", () => page.repl.outcome() !== undefined); + expect(page.repl.outcome()?.ok).toBe(true); +} + +/** Write a synthetic file beneath a mounted root. */ +function* plant(root: string, path: string, text: string): Operation { + yield* ensureDir(dirname(join(root, path))); + yield* writeTextFile(join(root, path), text); +} + +describe("mounted journal passing page", () => { + beforeEach(witnessCase("passing page")); + beforeEach(journalBeforeEach(OWNER)); + + it("passing page", function* () { + const { page, ordinal } = yield* mounted(); + yield* exchange(page, "PASSING"); + yield* exit(page); + yield* copyPair(ordinal, page.repl.root, yield* mountedExecution(page.repl)); + }); +}); + +describe("mounted journal late assertion", () => { + beforeEach(witnessCase("late assertion")); + beforeEach(journalBeforeEach(OWNER)); + + it("late assertion", function* () { + const { page, ordinal } = yield* mounted(); + yield* exchange(page, "ASSERTED"); + yield* exit(page); + const execution = yield* mountedExecution(page.repl); + yield* copyPair(ordinal, page.repl.root, execution); + // An execution's own authored inputs, named like journals, which are not history. + yield* plant(page.repl.root, join("v1", execution, "assets", "authored.jsonl"), "{}\n"); + yield* plant(page.repl.root, join("v1", execution, "components", "authored.jsonl"), "{}\n"); + expect("the mounted command returned").toBe("deliberate mounted late assertion"); + }); +}); + +describe("mounted journal deadline", () => { + beforeEach(witnessCase("deadline")); + beforeEach(journalBeforeEach(OWNER)); + + it("deadline", function* () { + // A root this case supplies, so the copy can be taken at the latest moment + // before removal: after the host's own retention and before the directory goes. + const dataRoot = yield* useTemporary("xmd-mounted-witness-"); + let root: string | undefined; + yield* ensure(function* () { + if (root !== undefined) { + yield* copyPair(1, root, yield* mountedExecution(page.repl)); + } + }); + const { page } = yield* mounted({ dataRoot }); + root = page.repl.root; + yield* exchange(page, "STARTED"); + page.repl.fake.script({ manual: true }); + yield* sendMessage(page, "never answered"); + yield* page.repl.fake.startedTurns(2); + yield* race([ + page.until("a reply its turn never sends", (one) => one.shows("NEVER SENT")), + (function* (): Operation { + yield* sleep(CASE_DEADLINE_MS); + throw new Error(`deliberate mounted deadline after ${CASE_DEADLINE_MS}ms`); + })(), + ]); + }); +}); + +describe("mounted journal held append", () => { + beforeEach(witnessCase("held append")); + beforeEach(journalBeforeEach(OWNER)); + + it("held append", function* () { + const witness = yield* Witnessed.expect(); + const gate = appendGate(); + let record: string | undefined; + const held = gate.holdNext((path, appended) => { + if (!path.endsWith(SIDEKICK_FILE) || !appended.includes('"kind":"response"')) { + return false; + } + record = appended; + return true; + }); + const failing = withResolvers(); + let root = ""; + let closed = false; + // Owned by the case rather than the host, so the release comes from outside + // the scope whose teardown is waiting for it. A failure before the hold was + // reached has nothing to observe, and a halted controller still lets go. + const controller = yield* spawn(function* () { + try { + yield* failing.operation; + if (!held.inFlight) { + return undefined; + } + yield* sleep(HELD_MS); + return { rootWhileHeld: yield* exists(root), closedWhileHeld: closed }; + } finally { + held.release(); + } + }); + let failure: unknown; + try { + yield* scoped(function* () { + // Every way out of this body tells the controller, so an interaction + // that fails early cannot leave the host draining a hold nobody releases. + try { + const host = yield* useMountedHost({ gate }); + const { page } = yield* mounted({ host }); + root = page.repl.root; + yield* exchange(page, "BEFORE"); + page.repl.fake.script({ reply: "HELD\n" }); + yield* sendMessage(page, "reply held"); + yield* held.started(); + throw new Error("deliberate held append cancellation"); + } finally { + failing.resolve(); + } + }); + } catch (error) { + failure = error; + } + closed = true; + const observed = yield* controller; + yield* writeWitness( + witness, + "held.json", + JSON.stringify({ + ...observed, + record, + reached: gate.reached.filter((path) => path.endsWith(SIDEKICK_FILE)).length, + rootAfterClose: yield* exists(root), + }) + "\n", + ); + throw failure; + }); +}); + +describe("mounted journal held message", () => { + beforeEach(witnessCase("held message")); + beforeEach(journalBeforeEach(OWNER)); + + it("held message", function* () { + const witness = yield* Witnessed.expect(); + const gate = appendGate(); + let record: string | undefined; + // This case's own message, not the one the exchange before it sends. + const saving = gate.holdNext((path, appended) => { + if ( + !path.endsWith(SIDEKICK_FILE) || + !appended.includes('"kind":"message"') || + !appended.includes("ask held") + ) { + return false; + } + record = appended; + return true; + }); + let root = ""; + // Owned by the case rather than the host. It lets the hold go only if the + // hold's own owner has not, so the host's teardown stays joinable either way. + const rescue = yield* spawn(function* () { + try { + yield* saving.started(); + yield* sleep(RESCUE_MS); + return { rescueNeeded: !saving.released, rootAtRescue: yield* exists(root) }; + } finally { + saving.release(); + } + }); + let failure: unknown; + try { + yield* scoped(function* () { + const host = yield* useMountedHost({ gate }); + const { page } = yield* mounted({ host }); + root = page.repl.root; + yield* exchange(page, "BEFORE"); + page.repl.fake.script({ reply: "HELD\n" }); + try { + yield* sendMessage(page, "ask held"); + yield* saving.started(); + expect("the held message").toBe("deliberate held message failure"); + saving.release(); + yield* page.until("the held reply", (one) => one.shows("HELD")); + } finally { + saving.release(); + } + }); + } catch (error) { + failure = error; + } + // Joined either way: a hold the case never reached has nothing to rescue. + let rescued: { rescueNeeded: boolean; rootAtRescue: boolean } | undefined; + if (saving.inFlight) { + rescued = yield* rescue; + } else { + yield* rescue.halt(); + } + yield* writeWitness( + witness, + "held-message.json", + JSON.stringify({ ...rescued, record, rootAfterClose: yield* exists(root) }) + "\n", + ); + throw failure; + }); +}); + +describe("mounted journal multiple roots", () => { + beforeEach(witnessCase("multiple roots")); + beforeEach(journalBeforeEach(OWNER)); + + describe("nested setup", () => { + beforeEach(journalBeforeEach(OWNER)); + + it("multiple roots", function* () { + const witness = yield* Witnessed.expect(); + const stream = yield* useJournalStream("synthetic/in-memory.md"); + yield* stream.append({ + type: "close", + coroutineId: "root", + result: { status: "ok", value: null }, + }); + yield* scoped(function* () { + const { page, ordinal } = yield* mounted(); + yield* exchange(page, "NESTED"); + yield* exit(page); + yield* copyPair(ordinal, page.repl.root, yield* mountedExecution(page.repl)); + }); + expect(yield* exists(witness.roots[0])).toBe(false); + + // A root this case supplies and removes itself, holding a second session + // and a direct legacy history beside the command's own. + const dataRoot = yield* useTemporary("xmd-mounted-supplied-"); + const { page, ordinal } = yield* mounted({ dataRoot }); + yield* exchange(page, "OUTER"); + yield* exit(page); + const root = page.repl.root; + const execution = yield* mountedExecution(page.repl); + yield* copyPair(ordinal, root, execution); + const second = pairedLocation(root, SECOND_SESSION); + for (const [path, text] of [ + [second.entries, '{"synthetic":"entries ü"}\n'], + [second.sidekick, '{"synthetic":"sidekick ü"}\n'], + [executionPath(root, LEGACY_SESSION), LEGACY_TEXT], + ]) { + const inside = path.slice(root.length + 1); + yield* plant(root, inside, text); + yield* writeWitness(witness, join(`root-${ordinal}`, inside), text); + } + expect("both mounted roots returned").toBe("deliberate multiple-root assertion"); + }); + }); +}); diff --git a/packages/cli/tests/mounted-failure-journal.test.ts b/packages/cli/tests/mounted-failure-journal.test.ts new file mode 100644 index 000000000..3c3df26e1 --- /dev/null +++ b/packages/cli/tests/mounted-failure-journal.test.ts @@ -0,0 +1,334 @@ +/** + * A mounted REPL case that fails keeps the histories its host wrote. + * + * The mounted host stores its paired entry and Sidekick histories as real files + * in a directory it removes when the case's scope ends. These rows run the + * synthetic cases in `fixtures/mounted-failure-journal.ts` as a child test file + * under this runtime, join it, and compare each saved journal with the copy the + * child took of what the command actually wrote: a passing case uploads + * nothing; an assertion after a successful run keeps its pair and none of the + * execution's authored files; a case deadline that cancels a turn in flight + * keeps what that turn wrote; an append still held when its case fails is + * written before the histories are read and the root is removed; a message + * append held when an assertion fails is released by its own owner, so the + * failure surfaces and the record is saved without anything else letting it + * go; and a case + * with a nested and a supplied root under nested attribution keeps each root + * apart, with every session and legacy history the supplied root held. + */ + +import { describe, it } from "@executablemd/test-support/bdd"; +import { expect } from "@executablemd/test-support/expect"; +import { cliRuntime, runShell, shellQuote } from "@executablemd/test-support/launch"; +import { useTempDirectory } from "@executablemd/test-support/temp"; +import { exists, readdir, readTextFile, walk } from "@effectionx/fs"; +import { parseDurableEvent } from "@executablemd/durable-streams"; +import { each } from "effection"; +import type { Operation } from "effection"; +import { join, relative } from "node:path"; +import { execPath } from "node:process"; +import { fileURLToPath } from "node:url"; + +const OWNER = "packages/cli/tests/fixtures/mounted-failure-journal.ts"; + +/** Every file beneath a directory, by its path inside it, with its text. */ +function* contents(directory: string): Operation> { + const found: Record = {}; + for (const entry of yield* each(walk(directory, { includeDirs: false }))) { + found[relative(directory, entry.path)] = yield* readTextFile(entry.path); + yield* each.next(); + } + return found; +} + +function* readJson(path: string): Operation { + return JSON.parse(yield* readTextFile(path)); +} + +/** What the child recorded once a case's whole teardown had run. */ +function* teardown(witness: string): Operation<{ root: string; exists: boolean }[]> { + const recorded = yield* readJson(join(witness, "teardown.json")); + if ( + recorded === null || + typeof recorded !== "object" || + !("roots" in recorded) || + !Array.isArray(recorded.roots) + ) { + throw new Error(`The child recorded no teardown: ${JSON.stringify(recorded)}`); + } + return recorded.roots.map((one: unknown) => { + if ( + one === null || + typeof one !== "object" || + !("root" in one) || + typeof one.root !== "string" || + !("exists" in one) || + typeof one.exists !== "boolean" + ) { + throw new Error(`The child recorded an unreadable root: ${JSON.stringify(one)}`); + } + return { root: one.root, exists: one.exists }; + }); +} + +/** The one invocation directory a failed case saved into. */ +function* invocation(artifacts: string, name: string): Operation { + const invocations = yield* readdir(join(artifacts, name)); + expect(invocations).toHaveLength(1); + return join(artifacts, name, invocations[0]); +} + +/** The paired entry and Sidekick paths among a saved root's files. */ +function pairs(files: readonly string[]): { entries: string; sidekick: string }[] { + return files + .filter((path) => /^v1\/[0-9a-f]+\/entries\.jsonl$/.test(path)) + .map((entries) => ({ + entries, + sidekick: entries.replace(/entries\.jsonl$/, "sidekick.jsonl"), + })); +} + +/** + * One saved mounted root: its files equal the child's witness copy, its + * metadata names this case and the root, and the run reported the save. + */ +function* savedRoot( + directory: string, + ordinal: number, + witness: string, + copy: number, + identity: { name: string; suite: string; source: string }, + output: string, +): Operation> { + const saved = yield* contents(join(directory, `root-${ordinal}`)); + expect(saved).toEqual(yield* contents(join(witness, `root-${copy}`))); + expect(yield* readJson(join(directory, `root-${ordinal}.case.json`))).toEqual({ + owner: OWNER, + ...identity, + kind: "root", + ordinal, + files: Object.keys(saved).sort(), + }); + expect(output).toContain( + `journal saved: ${join(directory, `root-${ordinal}`)} (root ${ordinal} ${identity.source})`, + ); + return saved; +} + +describe("mounted REPL failure journals", () => { + it("keeps each failed case's actual paired histories after its roots are removed", function* () { + const artifacts = yield* useTempDirectory("xmd-mounted-journal-artifacts-"); + const witnesses = yield* useTempDirectory("xmd-mounted-journal-witness-"); + const cwd = fileURLToPath(new URL("../../../", import.meta.url)); + const runtime = cliRuntime(); + const flags = { + deno: ["test", "--allow-all", "--frozen"], + node: ["--import", "tsx", "--test", "--test-reporter=spec", "--test-concurrency=1"], + bun: ["test", "--timeout=120000"], + }[runtime]; + const command = [execPath, ...flags, "./" + OWNER].map(shellQuote).join(" "); + const result = yield* runShell("exec " + command, { + cwd, + timeout: 240_000, + env: { + XMD_TEST_ARTIFACTS: artifacts, + XMD_MOUNTED_WITNESS: witnesses, + TSX_TSCONFIG_PATH: join(cwd, "tsconfig.node.json"), + NO_COLOR: "1", + }, + }).join(); + const output = result.stdout + result.stderr; + if (result.code !== 1) { + throw new Error(`Expected the fixture to exit with 1, received ${result.code}.\n${output}`); + } + expect(output).toMatch(/(?:✔|\(pass\)).*passing page|passing page \.\.\. ok/); + expect(output).toContain('Expected: "deliberate mounted late assertion"'); + expect(output).toContain("deliberate mounted deadline after 500ms"); + expect(output).toContain("deliberate held append cancellation"); + expect(output).toContain('Expected: "deliberate held message failure"'); + expect(output).toContain('Expected: "deliberate multiple-root assertion"'); + + // A passing case unwound the same way and created nothing to upload. + expect(yield* exists(join(artifacts, "passing page"))).toBe(false); + expect((yield* teardown(join(witnesses, "passing page"))).map((one) => one.exists)).toEqual([ + false, + ]); + + for (const [name, word] of [ + ["late assertion", "ASSERTED"], + ["deadline", "STARTED"], + ] as const) { + const witness = join(witnesses, name); + const [root] = yield* teardown(witness); + expect(root.exists).toBe(false); + const directory = yield* invocation(artifacts, name); + expect((yield* readdir(directory)).sort()).toEqual(["root-1", "root-1.case.json"]); + const saved = yield* savedRoot( + directory, + 1, + witness, + 1, + { name, suite: "mounted journal " + name, source: root.root }, + output, + ); + // Only the pair: an execution's authored assets and components stay behind. + const [pair] = pairs(Object.keys(saved)); + expect(Object.keys(saved).sort()).toEqual([pair.entries, pair.sidekick]); + expect(saved[pair.entries]).toContain(`entry ${word}`); + expect(saved[pair.sidekick]).toContain(`reply ${word.toLowerCase()}`); + } + + // The held append was still waiting when its case failed: the host's + // teardown waited for it, then read the histories, then removed the root. + { + const name = "held append"; + const witness = join(witnesses, name); + const [root] = yield* teardown(witness); + expect(root.exists).toBe(false); + const held = yield* readJson(join(witness, "held.json")); + expect(held).toMatchObject({ + rootWhileHeld: true, + closedWhileHeld: false, + rootAfterClose: false, + }); + if ( + held === null || + typeof held !== "object" || + !("record" in held) || + typeof held.record !== "string" + ) { + throw new Error(`The child recorded no held record: ${JSON.stringify(held)}`); + } + const directory = yield* invocation(artifacts, name); + expect((yield* readdir(directory)).sort()).toEqual(["root-1", "root-1.case.json"]); + const saved = yield* contents(join(directory, "root-1")); + const [pair] = pairs(Object.keys(saved)); + expect(Object.keys(saved).sort()).toEqual([pair.entries, pair.sidekick]); + expect(saved[pair.entries]).toContain("entry BEFORE"); + expect(saved[pair.sidekick]).toContain("reply before"); + expect(saved[pair.sidekick].endsWith(held.record)).toBe(true); + expect(yield* readJson(join(directory, "root-1.case.json"))).toEqual({ + owner: OWNER, + name, + suite: "mounted journal " + name, + kind: "root", + ordinal: 1, + source: root.root, + files: [pair.entries, pair.sidekick], + }); + } + + // The message append its own owner held was let go by that owner as the + // assertion failed: the rescue watching it found nothing left to release, + // and the record was written before the histories were read and removed. + { + const name = "held message"; + const witness = join(witnesses, name); + const [root] = yield* teardown(witness); + expect(root.exists).toBe(false); + const held = yield* readJson(join(witness, "held-message.json")); + expect(held).toMatchObject({ + rescueNeeded: false, + rootAtRescue: false, + rootAfterClose: false, + }); + if ( + held === null || + typeof held !== "object" || + !("record" in held) || + typeof held.record !== "string" + ) { + throw new Error(`The child recorded no held message: ${JSON.stringify(held)}`); + } + expect(held.record).toContain('"kind":"message"'); + const directory = yield* invocation(artifacts, name); + expect((yield* readdir(directory)).sort()).toEqual(["root-1", "root-1.case.json"]); + const saved = yield* contents(join(directory, "root-1")); + const [pair] = pairs(Object.keys(saved)); + expect(Object.keys(saved).sort()).toEqual([pair.entries, pair.sidekick]); + expect(saved[pair.entries]).toContain("entry BEFORE"); + expect(saved[pair.sidekick]).toContain(held.record); + expect(yield* readJson(join(directory, "root-1.case.json"))).toEqual({ + owner: OWNER, + name, + suite: "mounted journal " + name, + kind: "root", + ordinal: 1, + source: root.root, + files: [pair.entries, pair.sidekick], + }); + } + + // An in-memory root, a nested mounted root released before the assertion + // and a supplied root, each saved apart under the case that opened them. + { + const name = "multiple roots"; + const suite = "mounted journal multiple roots > nested setup"; + const witness = join(witnesses, name); + const roots = yield* teardown(witness); + expect(roots.map((one) => one.exists)).toEqual([false, false]); + const directory = yield* invocation(artifacts, name); + expect((yield* readdir(directory)).sort()).toEqual([ + "root-1.case.json", + "root-1.jsonl", + "root-2", + "root-2.case.json", + "root-3", + "root-3.case.json", + ]); + expect(yield* readJson(join(directory, "root-1.case.json"))).toEqual({ + owner: OWNER, + name, + suite, + kind: "root", + ordinal: 1, + source: "synthetic/in-memory.md", + }); + expect( + parseDurableEvent((yield* readTextFile(join(directory, "root-1.jsonl"))).trimEnd()), + ).toMatchObject({ ok: true, value: { type: "close", coroutineId: "root" } }); + + const nested = yield* savedRoot( + directory, + 2, + witness, + 1, + { name, suite, source: roots[0].root }, + output, + ); + const [nestedPair] = pairs(Object.keys(nested)); + expect(Object.keys(nested).sort()).toEqual([nestedPair.entries, nestedPair.sidekick]); + expect(nested[nestedPair.entries]).toContain("entry NESTED"); + + const supplied = yield* savedRoot( + directory, + 3, + witness, + 2, + { name, suite, source: roots[1].root }, + output, + ); + const [outerPair] = pairs(Object.keys(supplied)); + expect(Object.keys(supplied).sort()).toEqual( + [ + "Legacy-Run_2.jsonl", + outerPair.entries, + outerPair.sidekick, + "v1/Second_session-1/entries.jsonl", + "v1/Second_session-1/sidekick.jsonl", + ].sort(), + ); + expect(supplied[outerPair.entries]).toContain("entry OUTER"); + expect(nestedPair.entries).not.toBe(outerPair.entries); + // Non-ASCII text and an unfinished final record, kept as the UTF-8 they were. + const legacy = supplied["Legacy-Run_2.jsonl"]; + expect(legacy).toContain("é☃"); + expect(legacy.endsWith('"partial":"naïve ☃')).toBe(true); + expect(new TextEncoder().encode(legacy)).toEqual( + new TextEncoder().encode( + yield* readTextFile(join(witness, "root-2", "Legacy-Run_2.jsonl")), + ), + ); + } + }); +}); diff --git a/packages/cli/tests/plugin-modules.test.ts b/packages/cli/tests/plugin-modules.test.ts index e3e8b3514..6ec367515 100644 --- a/packages/cli/tests/plugin-modules.test.ts +++ b/packages/cli/tests/plugin-modules.test.ts @@ -15,10 +15,13 @@ import { usePluginProgram } from "./support/plugin-program.ts"; * it from any host — which is the whole point, because no shard runs the CLI on * Windows. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { classifyPluginSpecifier, resolvePluginSpecifier } from "../src/host-plugin-modules.ts"; +const OWNER = "packages/cli/tests/plugin-modules.test.ts"; + describe("PM1 — a Windows path is a path, on every host", () => { // deno-lint-ignore require-yield it("reads a drive prefix as a filesystem path rather than a scheme", function* () { @@ -127,6 +130,7 @@ describe("PM3 — resolution follows the classification", () => { }); describe("REPL Plugin author API", () => { + beforeEach(journalBeforeEach(OWNER)); it("R8: imports the public API and executes the selected author example", function* () { const { Repl } = yield* until(import("@executablemd/cli/api")); expect(Repl.operations.initialize).toBeDefined(); diff --git a/packages/cli/tests/repl-agent-interface.test.ts b/packages/cli/tests/repl-agent-interface.test.ts index 267353421..706041ded 100644 --- a/packages/cli/tests/repl-agent-interface.test.ts +++ b/packages/cli/tests/repl-agent-interface.test.ts @@ -13,7 +13,8 @@ * session, a screenshot for a frame, or a bare `` for a conversation. */ -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { race, scoped, sleep, until as untilResolved, useScope, withResolvers } from "effection"; import type { Operation, Result, Stream } from "effection"; @@ -114,6 +115,8 @@ import { } from "./support/screen-journeys.ts"; import { readScreen } from "./support/terminal-screen.ts"; +const OWNER = "packages/cli/tests/repl-agent-interface.test.ts"; + /** The widest accepted frame, stated here because layout keeps it private. */ const WIDE = { columns: 160, rows: 36 }; const MEDIUM = { columns: 120, rows: 30 }; @@ -1996,6 +1999,7 @@ describe("U3 — what each accepted frame mounts, and nothing else", () => { const TURN_FACT_SUFFIXES = [":whose", ":text", ":stop", ":failed"]; describe("U2 — the program performs a permission, end to end", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("U2: choosing through the running program settles the request and closes its drawer", function* () { @@ -2113,6 +2117,7 @@ describe("U2 — the program performs a permission, end to end", () => { }); describe("U4 — the loop wakes for Agent work", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("U4: queued, streaming and a waiting request each repaint on their own", function* () { @@ -3775,6 +3780,7 @@ function* admittedSources(hostRoot: string): Operation { * region with every control on the screen. */ describe("U2 — a draft outlives a permission and is still editable", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); for (const size of [{ columns: 160, rows: 36 }, NARROW]) { diff --git a/packages/cli/tests/repl-agent-journey.test.ts b/packages/cli/tests/repl-agent-journey.test.ts index 87ddd6eb0..1ffd80db9 100644 --- a/packages/cli/tests/repl-agent-journey.test.ts +++ b/packages/cli/tests/repl-agent-journey.test.ts @@ -1,5 +1,6 @@ import { installTodoSource } from "../src/node-todo-source.ts"; -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { scoped, sleep, spawn, suspend, until as untilResolved, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -66,6 +67,8 @@ import { projectRepl } from "../src/repl/model.ts"; import { REPL_DIRECTORY } from "../src/repl/storage.ts"; import { pairedReplRepository } from "../src/repl/sidekick/repository.ts"; +const OWNER = "packages/cli/tests/repl-agent-journey.test.ts"; + const STORY = [ '', " ", @@ -166,6 +169,7 @@ const WIDE: ReplTerminalSize = { columns: 200, rows: 140 }; const TALL: ReplTerminalSize = { columns: 200, rows: 60 }; describe("J1 — the Story, from one entry to one README", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("J1: the packaged Plan is reviewed in the drawer, and its program asks, previews and writes", function* () { @@ -334,6 +338,7 @@ describe("J1 — the Story, from one entry to one README", () => { }); describe("C1 — the command line this REPL runs under", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("C1: the five options settle into one immutable profile", function* () { @@ -528,6 +533,7 @@ function* selectedProfile( } describe("A2–A5 — the selected REPL component environment", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("A2/A5: one detached ordered selection describes vocabulary, protected names and environment", function* () { @@ -731,6 +737,7 @@ describe("A2–A5 — the selected REPL component environment", () => { }); describe("J3 — durable truth, and a cold process over it", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("J3: a fresh command scope reconstructs the whole Story from the Journal alone", function* () { @@ -1061,6 +1068,7 @@ describe("J3 — durable truth, and a cold process over it", () => { }); describe("J2 — three conversations at once, through the terminal", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("J2: complete, streaming and queued are one frame, and filtering changes only Sessions", function* () { @@ -1158,6 +1166,7 @@ describe("J2 — three conversations at once, through the terminal", () => { }); describe("J2 — a filter and a draft across a resize (#875 R1)", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); const TYPED = "and then this one"; @@ -1286,6 +1295,7 @@ function* failing(body: () => Operation): Operation { } describe("X1 — how this command ends, with work still in flight", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); function* inFlight(fake: FakeAcp, hostRoot: string, waitingFor: string): Operation { diff --git a/packages/cli/tests/repl-asset-import.test.ts b/packages/cli/tests/repl-asset-import.test.ts index b4a2c1b65..d35b18640 100644 --- a/packages/cli/tests/repl-asset-import.test.ts +++ b/packages/cli/tests/repl-asset-import.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { copyFile, @@ -27,6 +28,8 @@ import { records, useHarness, useTemporary } from "./fixtures/repl/issue-883/sid import type { Harness } from "./fixtures/repl/issue-883/sidekick-harness.ts"; import type { ReplElicitations, ReplQuestion } from "../src/repl/elicitation.ts"; +const OWNER = "packages/cli/tests/repl-asset-import.test.ts"; + const BINARY = new Uint8Array([0, 255, 128, 195, 40, 13, 10, 65]); function nativeGate() { @@ -407,6 +410,7 @@ import { } from "./support/screen-journeys.ts"; describe("mounted asset import", () => { + beforeEach(journalBeforeEach(OWNER)); it("A1/A2/A4: the form begins empty, closes unanswered, and approves the actual workspace", function* () { const { source, bytes } = yield* fixture(new TextEncoder().encode("mounted ü text")); const io = yield* instrument(); @@ -715,6 +719,7 @@ import { API, hostFilesHandler, useHostFiles } from "@executablemd/runtime"; import { useNormalizedOutput } from "@executablemd/core"; describe("asset import acknowledgement and independent owners", () => { + beforeEach(journalBeforeEach(OWNER)); it("A8: a failed import outcome append supplies no success or passive retry", function* () { const { source } = yield* fixture(); const held = yield* useHarness(); diff --git a/packages/cli/tests/repl-exec-output.test.ts b/packages/cli/tests/repl-exec-output.test.ts index 14284558e..d172cd55a 100644 --- a/packages/cli/tests/repl-exec-output.test.ts +++ b/packages/cli/tests/repl-exec-output.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { useTempDirectory } from "@executablemd/test-support/temp"; import { exists, writeTextFile } from "@effectionx/fs"; @@ -17,7 +18,10 @@ import type { ReplPage } from "./support/repl-page.ts"; import { awaitedFact, mountedReading } from "./support/mounted-repl.ts"; import { intoComposer, intoDraft, pasteDraft, sidekickIdle } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-exec-output.test.ts"; + describe("E3 retained command output", () => { + beforeEach(journalBeforeEach(OWNER)); it("retains captured control bytes in output, bindings, and command records", function* () { const received = "PROBE\x1b[2JTAIL\rEND"; yield* API.Process.around({ @@ -65,6 +69,7 @@ function* submit(page: ReplPage, source: string, order = 1): Operation { } describe("REPL foreground command presentation E1", () => { + beforeEach(journalBeforeEach(OWNER)); it("E1: contains both real child streams in the producing entry before exit", function* () { const directory = yield* useTempDirectory("repl-output-"); const release = join(directory, "release"); @@ -134,6 +139,7 @@ describe("REPL foreground command presentation E1", () => { }); describe("REPL command routing, containment and history E2–E5", () => { + beforeEach(journalBeforeEach(OWNER)); it("E2: retains bound, captured, and silent command results", function* () { const page = yield* useReplPage({ size: { columns: 160, rows: 52 } }); yield* submit( diff --git a/packages/cli/tests/repl-focus-regions.test.ts b/packages/cli/tests/repl-focus-regions.test.ts index 9fab2e9a3..3e600b3a5 100644 --- a/packages/cli/tests/repl-focus-regions.test.ts +++ b/packages/cli/tests/repl-focus-regions.test.ts @@ -1,5 +1,6 @@ import type { ScreenReading } from "./support/repl-page.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { REPL_PALETTE } from "../src/repl/presentation-style.ts"; import { sleep } from "effection"; @@ -30,6 +31,8 @@ import type { PageKey, ReplPage } from "./support/repl-page.ts"; import { DRAFT_VALUE, intoDraft } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-focus-regions.test.ts"; + const WIDE = { columns: 160, rows: 36 }; const MEDIUM = { columns: 120, rows: 30 }; const NARROW = { columns: 72, rows: 20 }; @@ -53,6 +56,7 @@ function* draftFocus(page: ReplPage): Operation { } describe("REPL focus regions: the normal screen", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of [WIDE, MEDIUM]) { it(`R1/R2: fixed region entries deliver Draft and Message input at ${size.columns}x${size.rows}`, function* () { const page = yield* useReplPage({ size }); @@ -135,6 +139,7 @@ describe("REPL focus regions: the normal screen", () => { }); describe("REPL focus regions: Unicode caret editing", () => { + beforeEach(journalBeforeEach(OWNER)); it("reveals both ends of a source line longer than the terminal", function* () { const page = yield* useReplPage({ size: MEDIUM }); yield* draftFocus(page); @@ -192,6 +197,7 @@ describe("REPL focus regions: Unicode caret editing", () => { }); describe("REPL focus regions: reading and narrow recovery", () => { + beforeEach(journalBeforeEach(OWNER)); it("PV5: the selected reading reaches both boundaries without activating or editing", function* () { const page = yield* useReplPage({ size: MEDIUM }); yield* draftFocus(page); @@ -265,6 +271,7 @@ describe("REPL focus regions: reading and narrow recovery", () => { }); describe("REPL focus regions: the catalog drawer at the narrow size", () => { + beforeEach(journalBeforeEach(OWNER)); it("R5: nested arrows reveal hidden entries, fixed Content entry and modal close restore", function* () { const page = yield* useReplPage({ size: NARROW, includes: [REFERENCE_DIRECTORY] }); for (let order = 1; order <= 6; order += 1) { @@ -631,6 +638,7 @@ describe("REPL focus regions: logical drawer reveal", () => { }); describe("REPL focus regions: background input ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("PV7: a reply and question leave a middle Message caret and Draft untouched", function* () { const page = yield* useReplPage({ size: MEDIUM }); yield* draftFocus(page); @@ -665,6 +673,7 @@ describe("REPL focus regions: background input ownership", () => { }); describe("REPL focus regions: Sidekick reading keys", () => { + beforeEach(journalBeforeEach(OWNER)); it("PV5: Home/End and pages preserve an unsent Message while output arrives", function* () { const page = yield* useReplPage({ size: MEDIUM }); yield* draftFocus(page); diff --git a/packages/cli/tests/repl-headless-attach.test.ts b/packages/cli/tests/repl-headless-attach.test.ts index 3b4f7a97d..d1dc9612e 100644 --- a/packages/cli/tests/repl-headless-attach.test.ts +++ b/packages/cli/tests/repl-headless-attach.test.ts @@ -1,5 +1,6 @@ import { readTextFile } from "@effectionx/fs"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { createSignal, ensure, race, scoped, sleep, spawn } from "effection"; import type { Operation, Scope } from "effection"; @@ -20,9 +21,12 @@ import { XmdResponse } from "@executablemd/acp"; import { childAddressPath } from "../src/headless/host.ts"; import { pairedLocation, readSidekickRecords } from "../src/repl/sidekick/history.ts"; +const OWNER = "packages/cli/tests/repl-headless-attach.test.ts"; + type AppliedFrames = WeakMap Operation>; describe("987 — fresh child recovery reference", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps host readiness pending while an applied acknowledgement is held", function* () { const held = yield* useHeadlessFixture(); const gate = held.input.holdNextAcknowledgement(); @@ -368,6 +372,7 @@ function locateInBindings(terminal: Terminal, label: string): { row: number; col } describe("headless renderer lifetime", () => { + beforeEach(journalBeforeEach(OWNER)); it("releases every detached renderer scope while the exact child remains live", function* () { const live = new Set(); const parents = new WeakMap(); @@ -456,6 +461,7 @@ describe("headless renderer lifetime", () => { }); describe("headless live UI", () => { + beforeEach(journalBeforeEach(OWNER)); it("C3: Control-C typed while the attached first frame is still being written detaches", function* () { const held = yield* useHeadlessFixture(); const prompts = held.host.fake.prompts.length; @@ -1059,6 +1065,7 @@ describe("headless live UI", () => { }); describe("numbered attached frames", () => { + beforeEach(journalBeforeEach(OWNER)); it("H4: applies numbered frames only at matching dimensions and releases an outstanding frame on loss", function* () { const held = yield* useHeadlessFixture(); yield* scoped(function* () { @@ -1221,6 +1228,7 @@ describe("numbered attached frames", () => { }); describe("protected input through capable ACP pipes", () => { + beforeEach(journalBeforeEach(OWNER)); it("preserves the marker in the embedded callback and returns only a safe child result", function* () { let marked = false; const held = yield* useHeadlessFixture((input) => { @@ -1264,6 +1272,7 @@ describe("protected input through capable ACP pipes", () => { }); describe("marked ACP absence", () => { + beforeEach(journalBeforeEach(OWNER)); it("withdraws a marked question through the current no-form branch without opening a parent form", function* () { let callbacks = 0; const held = yield* useHeadlessFixture( diff --git a/packages/cli/tests/repl-headless-clients.test.ts b/packages/cli/tests/repl-headless-clients.test.ts index d4e7334db..893084725 100644 --- a/packages/cli/tests/repl-headless-clients.test.ts +++ b/packages/cli/tests/repl-headless-clients.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, race, scoped, sleep, spawn, suspend, useScope, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -22,6 +23,8 @@ import { Elicitation } from "@executablemd/core"; import type { Scope } from "effection"; import type { AgentPromptEvent } from "@executablemd/agent/api"; +const OWNER = "packages/cli/tests/repl-headless-clients.test.ts"; + const conditional = { type: "object", additionalProperties: false, @@ -39,6 +42,7 @@ function entryResponse(source: string): string { } describe("headless presentation lifetime", () => { + beforeEach(journalBeforeEach(OWNER)); it("releases more than 64 UI-resolved presentations after callbacks join and preserves an in-flight stale response", function* () { const held = yield* useHeadlessFixture(); const questions = yield* useReplElicitation(); @@ -189,6 +193,7 @@ describe("headless presentation lifetime", () => { }); describe("headless child ACP clients", () => { + beforeEach(journalBeforeEach(OWNER)); it("H5: every closed response variant closes only its correlated presentation and retirement proves no answer", function* () { const issue = { instancePath: "/reason", diff --git a/packages/cli/tests/repl-headless-submit-process.test.ts b/packages/cli/tests/repl-headless-submit-process.test.ts index fc3e3a28e..58fa89d09 100644 --- a/packages/cli/tests/repl-headless-submit-process.test.ts +++ b/packages/cli/tests/repl-headless-submit-process.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { cliCommand } from "@executablemd/test-support/launch"; import { ensure, race, sleep, withResolvers } from "effection"; @@ -14,6 +15,8 @@ import { platformDataRoot } from "../src/repl-assembly.ts"; import { ReplEntryHost } from "../src/repl-entry-installation.ts"; import { SubmitRecord } from "../src/sidekick-acp/protocol.ts"; +const OWNER = "packages/cli/tests/repl-headless-submit-process.test.ts"; + function within(operation: Operation, evidence: () => unknown): Operation { return race([ operation, @@ -135,6 +138,7 @@ const QUESTION = 'Continue?'; describe("first SIGINT at the submit host boundary", () => { + beforeEach(journalBeforeEach(OWNER)); it("G: joins a blocked stdin read on the first SIGINT while its writer stays open", function* () { const home = yield* useTemporary("xmd-submit-process-home-"); const fixture = yield* useHeadlessFixture( diff --git a/packages/cli/tests/repl-headless-submit.test.ts b/packages/cli/tests/repl-headless-submit.test.ts index fc6c6e4c7..4a18839a8 100644 --- a/packages/cli/tests/repl-headless-submit.test.ts +++ b/packages/cli/tests/repl-headless-submit.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { Err, Ok, ensure, race, scoped, sleep, spawn, suspend, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -26,6 +27,8 @@ import { recordingTerminal } from "./support/mounted-repl.ts"; import type { Terminal } from "./support/mounted-repl.ts"; import { attachChildUi } from "../src/headless/ui.ts"; +const OWNER = "packages/cli/tests/repl-headless-submit.test.ts"; + type Fixture = ReturnType extends Operation ? T : never; function gate() { const entered = withResolvers(); @@ -122,6 +125,7 @@ const HOLD = '---\nreturns: {type: object}\n---\n\n'; describe("direct headless submission", () => { + beforeEach(journalBeforeEach(OWNER)); it("A: transfers a complete large UTF-8 program once, with consumption credit, values and project placement", function* () { const directory = yield* useTemporary("xmd-direct-project-"); yield* API.Env.around( diff --git a/packages/cli/tests/repl-headless.test.ts b/packages/cli/tests/repl-headless.test.ts index eb00623ba..f238ba669 100644 --- a/packages/cli/tests/repl-headless.test.ts +++ b/packages/cli/tests/repl-headless.test.ts @@ -3,7 +3,8 @@ import type { ReplPluginInstallation } from "../api.ts"; import { useSidekickAttachment } from "../src/sidekick-acp/server.ts"; import { attachChildUi } from "../src/headless/ui.ts"; import { sidekickAssembly } from "../src/repl/sidekick/assembly.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Err, race, scoped, sleep, spawn, suspend, until, withResolvers } from "effection"; import { API } from "@executablemd/runtime"; @@ -29,7 +30,10 @@ import { join } from "node:path"; import { makeRegistry, makeStore } from "./support/fake-acp.ts"; import { chmod, mkdtemp, realpath } from "node:fs/promises"; +const OWNER = "packages/cli/tests/repl-headless.test.ts"; + describe("parent-owned headless REPL", () => { + beforeEach(journalBeforeEach(OWNER)); it("H3: disconnect after accepted work reconnects exactly without resubmitting its effect", function* () { const held = yield* useHeadlessFixture(); const source = '{once}'; @@ -841,6 +845,7 @@ function* useManagedRecoveryChild(publicationFailure: { armed: boolean }) { } describe("987 — owned reference disposition", () => { + beforeEach(journalBeforeEach(OWNER)); for (const cut of ["publication", "active-unwind"]) { it(`keeps authoritative selection and reference lifetime at ${cut}`, function* () { const publication = { armed: false }; @@ -918,6 +923,7 @@ describe("987 — owned reference disposition", () => { }); describe("987 — original child input ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps an entry question through inspection, UI detach and same-original recovery", function* () { const held = yield* useManagedRecoveryChild({ armed: false }); held.host.fake.script({ reply: "" }); @@ -999,6 +1005,7 @@ describe("987 — original child input ownership", () => { }); describe("REPL Plugin session ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("R2: parent and child initialize once; UI and history reads initialize nothing", function* () { const workspaces: string[] = []; const stopped: string[] = []; diff --git a/packages/cli/tests/repl-journey.test.ts b/packages/cli/tests/repl-journey.test.ts index 44a745eb8..56a646dce 100644 --- a/packages/cli/tests/repl-journey.test.ts +++ b/packages/cli/tests/repl-journey.test.ts @@ -1,6 +1,7 @@ /** The mounted REPL journey, driven by terminal input and visible outcomes. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ReplClock } from "../src/repl/frame.ts"; import { ReplHost } from "../src/repl/host.ts"; @@ -52,10 +53,13 @@ import { pasteDraft, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-journey.test.ts"; + const WIDE = { columns: 160, rows: 36 }; const NARROW = { columns: 72, rows: 20 }; describe("REPL journey: a person drives the running command", () => { + beforeEach(journalBeforeEach(OWNER)); it("submits a Draft through the terminal and sees its settled History mark", function* () { const page = yield* useReplPage({ size: WIDE }); yield* pasteDraft(page, 'output("one done");'); @@ -164,6 +168,7 @@ const SECOND_COLD = '```js eval\nconst carried = `${token}-again`;\n```\n\nTwo: {carried}\n\n\n'; describe("REPL retained readings across every terminal size", () => { + beforeEach(journalBeforeEach(OWNER)); it("TL10: every size and a refusal keep the nested reading, and a cold open restores it", function* () { const dataRoot = yield* useTemporary("xmd-tl10-"); let path = ""; @@ -282,6 +287,7 @@ describe("REPL retained readings across every terminal size", () => { }); describe("REPL startup below the minimum terminal size", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: a terminal below the minimum refuses, and recovers when it grows", function* () { const terminal = yield* scoped(function* () { const page = yield* useReplPage({ size: { columns: 40, rows: 10 } }); @@ -365,6 +371,7 @@ function released(terminal: MountedRepl["terminal"]): void { } describe("REPL original admission and terminal exit claims", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: pasting the reference entry puts all of it in the draft and the location", function* () { const page = yield* referencePage(); const source = yield* referenceSource(); @@ -567,6 +574,7 @@ function* leaveRefusal(page: ReplPage) { } describe("REPL original refusals before replay and terminal ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: Control-C leaves a refusal, and it is still a refusal", function* () { const { page } = yield* corruptPage(); expect(page.screen().shows("cannot read")).toBe(true); @@ -739,6 +747,7 @@ function* missingEntryRefusal() { } describe("REPL original retained readings and navigation", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: a second process reconstructs the view from the URL and the journal alone", function* () { const dataRoot = yield* useTemporary("xmd-binding-cold-"); let path = ""; @@ -906,6 +915,7 @@ function* interactionCost( } describe("REPL original interaction costs and visible exit routes", () => { + beforeEach(journalBeforeEach(OWNER)); for (const lines of [12, 222]) { it(`RS3: typing and traversing beside a ${lines}-line entry read the size a fixed number of times`, function* () { const page = yield* referencePage(); @@ -1128,6 +1138,7 @@ function* resumeOnce( } describe("REPL original pause-before-admission boundaries", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of [WIDE, { columns: 120, rows: 30 }, NARROW]) { it(`PPA2/PPA5: Pause is offered, requested and applied to the exact entry at ${size.columns}x${size.rows}`, function* () { const host = yield* useMountedHost({ includes: [REFERENCE_DIRECTORY] }); @@ -1478,6 +1489,7 @@ function* answerGo(page: ReplPage): Operation { } describe("REPL original live output and entry lifecycle", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: text the Journal has not settled is drawn while the run is held", function* () { const host = yield* useMountedHost(); const release = withResolvers(); @@ -1643,6 +1655,7 @@ function directions(one: ScreenReading): string { } describe("REPL original first-use paths and question ownership", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of [WIDE, NARROW]) { it( size.columns === 72 @@ -1811,6 +1824,7 @@ describe("REPL original first-use paths and question ownership", () => { }); describe("REPL original completed-screen lifecycle", () => { + beforeEach(journalBeforeEach(OWNER)); it("reads typing, diffs and every profile off completed presentations", function* () { yield* ReplHost.around( { @@ -2042,6 +2056,7 @@ function* fourEntries(page: ReplPage): Operation { } describe("REPL original complete History and cold catalog", () => { + beforeEach(journalBeforeEach(OWNER)); it("H5: the drawer reaches them all, and four resizes keep the reading", function* () { const page = yield* referencePage(); yield* fourEntries(page); @@ -2297,6 +2312,7 @@ function referencePageFor(dataRoot: string): Operation { } describe("REPL original visible guidance and controlled typing", () => { + beforeEach(journalBeforeEach(OWNER)); it("UI1: the visible History controls remain navigable at both sizes", function* () { for (const size of [WIDE, NARROW]) { yield* scoped(function* () { @@ -2393,6 +2409,7 @@ describe("REPL original visible guidance and controlled typing", () => { }); describe("REPL original held reading and canonical startup", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: run, hold at a gate, inspect a prefix, return live, continue, answer, settle", function* () { const host = yield* useMountedHost({ includes: [REFERENCE_DIRECTORY] }); const gate = preparationGate(); @@ -2453,6 +2470,7 @@ describe("REPL original held reading and canonical startup", () => { }); describe("REPL original presentation acknowledgement", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: a frame is not acknowledged until it has been presented", function* () { const host = yield* useMountedHost({ includes: [REFERENCE_DIRECTORY] }); const pending: Array<() => void> = []; @@ -2547,6 +2565,7 @@ function* retainedAnswerLines(page: ReplPage): Operation<{ first: string[]; seen } describe("REPL original retained schema and generated evidence", () => { + beforeEach(journalBeforeEach(OWNER)); it("J1: a recorded question reopens its whole schema and answer without work", function* () { const dataRoot = yield* useTemporary("xmd-recorded-answer-cold-"); const kept = yield* scoped(function* () { @@ -2655,6 +2674,7 @@ describe("REPL original retained schema and generated evidence", () => { }); describe("REPL original question arrival on another reading", () => { + beforeEach(journalBeforeEach(OWNER)); it("UI3: a question on Sessions moves nothing, and is reached by activating it", function* () { for (const size of [WIDE, NARROW]) { yield* scoped(function* () { @@ -2700,6 +2720,7 @@ describe("REPL original question arrival on another reading", () => { }); describe("REPL original surface and entry selection marks", () => { + beforeEach(journalBeforeEach(OWNER)); it("UI1: the active surface and the selected entry are marked in the frame", function* () { for (const size of [WIDE, NARROW]) { yield* scoped(function* () { diff --git a/packages/cli/tests/repl-layout-admission.test.ts b/packages/cli/tests/repl-layout-admission.test.ts index 4de94dbdb..2756fb82c 100644 --- a/packages/cli/tests/repl-layout-admission.test.ts +++ b/packages/cli/tests/repl-layout-admission.test.ts @@ -18,7 +18,8 @@ import { parseTodo } from "../src/repl/todo/document.ts"; * told and from nothing else. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { Elicitation, collect, inlineSource, useTempFileCompiler } from "@executablemd/core"; import { executeInstalled } from "@executablemd/core/host"; @@ -68,6 +69,8 @@ import { useReplPage } from "./support/repl-page.ts"; import type { ReplPage } from "./support/repl-page.ts"; import { entrySettles, intoDraft, pasteDraft } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-layout-admission.test.ts"; + /** * The two cells in front of a control's label that its focus marker draws in. * @@ -588,6 +591,7 @@ describe("REPL layout: what an action row admits", () => { }); describe("REPL layout: what a shrinking reading leaves behind", () => { + beforeEach(journalBeforeEach(OWNER)); /** One journal whose whole reading is the long one, and one that is short. */ function* readings(): Operation<{ long: ReplModel; short: ReplModel }> { return { @@ -1615,6 +1619,7 @@ describe("Owned narrow guidance and pane navigation routes", () => { }); describe("Owned footer, History and single-field inventory", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps the full execution refusal readable from the narrow identity header", function* () { // The long search path ends row five with a supplementary letter. const cutoff = "\u{10400}"; @@ -1826,6 +1831,7 @@ describe("Owned Transcript control geometry", () => { }); describe("accepted rendered scrolling guidance", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of [MEDIUM, NARROW]) { it(`Content and reading help fit whole at ${size.columns}x${size.rows}`, function* () { const page = yield* useReplPage({ size }); diff --git a/packages/cli/tests/repl-page.test.ts b/packages/cli/tests/repl-page.test.ts index 853cfe1d7..d9ad04224 100644 --- a/packages/cli/tests/repl-page.test.ts +++ b/packages/cli/tests/repl-page.test.ts @@ -12,7 +12,8 @@ * actually draws; nothing here asks the command where it put something. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import type { Operation } from "effection"; @@ -21,6 +22,8 @@ import type { ReplPage, ScreenCell, ScreenScope } from "./support/repl-page.ts"; import { awaited } from "./support/mounted-repl.ts"; import { draftShows, intoDraft } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-page.test.ts"; + const WIDE = { columns: 160, rows: 36 }; const NARROW = { columns: 72, rows: 20 }; const BELOW = { columns: 60, rows: 15 }; @@ -69,6 +72,7 @@ function* typed(page: ReplPage, text: string): Operation { } describe("REPL page — Send and its visible scope", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps one outlined editor and its caret while narrow Send hides the heading", function* () { const page = yield* useReplPage({ size: NARROW }); yield* intoDraft(page); @@ -145,6 +149,7 @@ describe("REPL page — Send and its visible scope", () => { }); describe("REPL page — resize, a modal, and writes that never land", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps the draft across every size and refuses a pane the size removed", function* () { const page = yield* useReplPage({ size: WIDE }); yield* intoDraft(page); @@ -197,6 +202,7 @@ describe("REPL page — resize, a modal, and writes that never land", () => { }); describe("REPL page — a column is a terminal cell, not a string offset", () => { + beforeEach(journalBeforeEach(OWNER)); it("locates a label after a wide glyph at the cell it is really drawn in", function* () { const page = yield* useReplPage({ size: WIDE }); yield* intoDraft(page); @@ -287,6 +293,7 @@ function* asked(page: ReplPage, text: string, shown: string): Operation { } describe("REPL page — reaching a field the claim names, by keyboard", () => { + beforeEach(journalBeforeEach(OWNER)); it("puts a person's own entry in the Draft after a Sidekick exchange", function* () { const page = yield* useReplPage({ size: WIDE }); page.repl.fake.script({ reply: "AUTHORED\n" }); diff --git a/packages/cli/tests/repl-paged-history.test.ts b/packages/cli/tests/repl-paged-history.test.ts index b34ae754e..a68e23ab7 100644 --- a/packages/cli/tests/repl-paged-history.test.ts +++ b/packages/cli/tests/repl-paged-history.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { useTempDirectory } from "@executablemd/test-support/temp"; import { Elicitation, INLINE_SOURCE_PATH } from "@executablemd/core"; @@ -29,6 +30,8 @@ import { awaited, useMountedHost } from "./support/mounted-repl.ts"; import { useReplPage } from "./support/repl-page.ts"; import { pasteDraft, SIDEKICK_PANE } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-paged-history.test.ts"; + function admission(content: string): DurableEvent { return { type: "yield", @@ -77,6 +80,7 @@ function* useWriter(): Operation { } describe("Paged REPL history", () => { + beforeEach(journalBeforeEach(OWNER)); it("matches the whole projection at each position and finds older binding publishers", function* () { const path = join(yield* useTempDirectory("xmd-pages-"), "entries.jsonl"); const records: DurableEvent[] = [ diff --git a/packages/cli/tests/repl-plugin.test.ts b/packages/cli/tests/repl-plugin.test.ts index d9a80832b..0f263c1e1 100644 --- a/packages/cli/tests/repl-plugin.test.ts +++ b/packages/cli/tests/repl-plugin.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { createContext, ensure, scoped, sleep, spawn, suspend, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -13,6 +14,8 @@ import { useReplLiveScreen } from "../src/repl/live-screen.ts"; import { usePluginProgram } from "./support/plugin-program.ts"; import { useMountedHost } from "./support/mounted-repl.ts"; +const OWNER = "packages/cli/tests/repl-plugin.test.ts"; + const Session = createContext<{ workspace: string; calls: number }>("test.repl-plugin.session"); const props = { type: "object", properties: {}, additionalProperties: false }; function fixture(name: string, events: string[], counts: { factories: number }) { @@ -75,6 +78,7 @@ function fixture(name: string, events: string[], counts: { factories: number }) } describe("Selected REPL Plugin contributions", () => { + beforeEach(journalBeforeEach(OWNER)); it("R1/R5: collection and descriptions start no service; ordered setup shares session state", function* () { const events: string[] = []; const counts = { factories: 0 }; diff --git a/packages/cli/tests/repl-presentation-style.test.ts b/packages/cli/tests/repl-presentation-style.test.ts index 8967d1437..12af8341a 100644 --- a/packages/cli/tests/repl-presentation-style.test.ts +++ b/packages/cli/tests/repl-presentation-style.test.ts @@ -21,7 +21,8 @@ import { parseTodo } from "../src/repl/todo/document.ts"; * chose. */ -import { beforeAll, describe, it } from "@executablemd/test-support/bdd"; +import { beforeAll, beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { close, fit, open, text } from "../generated/tty/mod.js"; import { @@ -153,6 +154,8 @@ import { submitReplEntry } from "../src/repl/session.ts"; import type { ReplSession } from "../src/repl/session.ts"; import type { CellStyle, Observed, Presenter, TerminalGrid } from "./fixtures/repl/presentation.ts"; +const OWNER = "packages/cli/tests/repl-presentation-style.test.ts"; + const WIDE: ReplTerminalSize = { columns: 160, rows: 36 }; const MEDIUM: ReplTerminalSize = { columns: 120, rows: 30 }; /** The large frame the History rows drive, where the drawer sits lower. */ @@ -5223,6 +5226,7 @@ function stagedView(model: ReplModel, size: ReplTerminalSize): ReplView { * to keep; the archive's own inks are the appearance rows above. */ describe("Checkpoint #971 — the workspace screen at 160x36", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("C1/C2: every surface is placed whole, wraps inside its region and keeps its styles", function* () { @@ -5751,6 +5755,7 @@ describe("Checkpoint #971 — the workspace screen at 160x36", () => { }); describe("Checkpoint #971 A2 — the workspace at the two smaller sizes", () => { + beforeEach(journalBeforeEach(OWNER)); beforeAll(() => useTempFileCompiler()); it("A2: every size places whole controls inside the frame and keeps its routes", function* () { @@ -5986,6 +5991,7 @@ describe("Checkpoint #971 A2 — the workspace at the two smaller sizes", () => * Whether it looks right is the image review's answer, not a test's. */ describe("Checkpoint #971 A4 — current outcomes, work and the waiting question", () => { + beforeEach(journalBeforeEach(OWNER)); it("A4: every outcome, work identity and the waiting question read from the current screen", function* () { const page = yield* reachOutcomes(WIDE); const { model } = yield* settledReading(page.repl); @@ -6086,6 +6092,7 @@ describe("Checkpoint #971 A4 — current outcomes, work and the waiting question * */ describe("Checkpoint #971 R2 — current chat windows and outcomes", () => { + beforeEach(journalBeforeEach(OWNER)); it("R2: current chat traversal reads every outcome and keeps its composer", function* () { const page = yield* reachOutcomes(WIDE); // The size whose conversation still holds more than it shows. @@ -6123,6 +6130,7 @@ describe("Checkpoint #971 R2 — current chat windows and outcomes", () => { }); describe("REPL presentation: the screen says what is placed", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps the shell and its readable surfaces at the supported sizes", function* () { const page = yield* useReplPage({ size: WIDE }); yield* intoDraft(page); diff --git a/packages/cli/tests/repl-project-files.test.ts b/packages/cli/tests/repl-project-files.test.ts index 295802e34..b1517bce7 100644 --- a/packages/cli/tests/repl-project-files.test.ts +++ b/packages/cli/tests/repl-project-files.test.ts @@ -8,7 +8,8 @@ import { InMemoryStream } from "@executablemd/durable-streams"; import { collect, inlineSource, registerComponents } from "@executablemd/core"; import { executeInstalled } from "@executablemd/core/host"; import { replRepositoryInstallation } from "../src/repl/repositories/deno/provider.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensureDir, readTextFile, writeTextFile, exists } from "@effectionx/fs"; import { @@ -42,11 +43,14 @@ import type { ReplPage, ScreenReading } from "./support/repl-page.ts"; import { settledReading } from "./support/mounted-history.ts"; import { pairedLocation } from "../src/repl/sidekick/history.ts"; +const OWNER = "packages/cli/tests/repl-project-files.test.ts"; + function submit(source: string): string { return `{code}`; } describe("1113: project files through the mounted Sidekick", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: submitted work starts in P, scopes session source and assets, and restores sibling cwd", function* () { const project = yield* useTemporary("1113-project-"); const host = yield* useMountedHost({ projectCwd: project, hostFiles: true }); @@ -288,6 +292,7 @@ describe("1113: transformed Files requests", () => { }); describe("1113: executable capture teaching", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: runs the complete shipped passive-source response and reads the exact entry output", function* () { const project = yield* useTemporary("1113-capture-"); const page = yield* useReplPage({ projectCwd: project, hostFiles: true }); @@ -323,6 +328,7 @@ describe("1113: executable capture teaching", () => { }); describe("1113: session scopes retain their restrictions", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113 M1: outer Content keeps AssetDir write denial after middleware redirects into P", function* () { const project = yield* useTemporary("1113-asset-redirect-project-"); const redirects: { @@ -615,6 +621,7 @@ function* reportPagingFailure( } describe("1113: receipt-directed exact output paging", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: follows the receipt's entry and each returned next argument until exact output is complete", function* () { const project = yield* useTemporary("1113-output-"); const page = yield* useReplPage({ projectCwd: project, hostFiles: true }); @@ -783,6 +790,7 @@ describe("1113: receipt-directed exact output paging", () => { }); describe("1113: project selection belongs to the actual entry", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: a fresh response and both entry origins observe P while storage is elsewhere", function* () { const project = yield* useTemporary("1113-owner-project-"); const page = yield* useReplPage({ projectCwd: project, hostFiles: true }); diff --git a/packages/cli/tests/repl-project-recovery.test.ts b/packages/cli/tests/repl-project-recovery.test.ts index 37568cce7..6ec1c5c85 100644 --- a/packages/cli/tests/repl-project-recovery.test.ts +++ b/packages/cli/tests/repl-project-recovery.test.ts @@ -11,7 +11,8 @@ import { runXmd } from "../src/cli.ts"; import { Elicitation } from "@executablemd/core"; import { Plugin } from "@executablemd/core/api"; import { unsupportedWorkflowHost } from "../src/workflow.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { readTextFile, writeTextFile, exists, rm, ensureDir } from "@effectionx/fs"; import { API, cwd, Permissions } from "@executablemd/runtime"; @@ -35,6 +36,8 @@ import { import { useReplPage } from "./support/repl-page.ts"; import { pasteDraft, sendMessage } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-project-recovery.test.ts"; + function columnOf(cells: readonly string[], label: string): number { const offset = cells.join("").indexOf(label); let text = 0; @@ -105,6 +108,7 @@ function* saved(sidekick = false) { } describe("1113: project placement before live recovery", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: records the strict pair and needs no answer at the original root or an alias", function* () { const held = yield* saved(); const reopened = yield* held.host.repository.open(held.id); @@ -543,6 +547,7 @@ describe("1113: project placement before live recovery", () => { }); describe("1113: unavailable access and conflicting placement", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: diagnoses an access refusal without offering another path", function* () { const directory = yield* useTemporary("1113-inaccessible-"); let accessed = ""; diff --git a/packages/cli/tests/repl-restore-progress.test.ts b/packages/cli/tests/repl-restore-progress.test.ts index d1a0982ee..bab2a0789 100644 --- a/packages/cli/tests/repl-restore-progress.test.ts +++ b/packages/cli/tests/repl-restore-progress.test.ts @@ -2,7 +2,8 @@ import process from "node:process"; import { readTextFile, writeTextFile } from "@effectionx/fs"; import { Agent, AgentProviders } from "@executablemd/agent/api"; import { API } from "@executablemd/runtime"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { createContext, ensure, race, scoped, sleep, spawn, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -18,6 +19,8 @@ import type { Terminal } from "./support/mounted-repl.ts"; import { invalidRestoreEntries, savedRestoreFixture } from "./support/restore-progress.ts"; import type { RetainedRestoreFixture } from "./support/restore-progress.ts"; +const OWNER = "packages/cli/tests/repl-restore-progress.test.ts"; + const WIDE = { columns: 160, rows: 36 }; const MEDIUM = { columns: 120, rows: 30 }; const NARROW = { columns: 72, rows: 20 }; @@ -221,6 +224,7 @@ function settled( } describe("#1037 cold restore progress", () => { + beforeEach(journalBeforeEach(OWNER)); it("draws projected rounds, resizes, then waits for Sidekick before opening the original view", function* () { const held = yield* savedRestoreFixture(yield* useMountedHost(), 155); const rounds = gate(); diff --git a/packages/cli/tests/repl-sidekick-acp.test.ts b/packages/cli/tests/repl-sidekick-acp.test.ts index 609865f24..5515005cc 100644 --- a/packages/cli/tests/repl-sidekick-acp.test.ts +++ b/packages/cli/tests/repl-sidekick-acp.test.ts @@ -6,7 +6,8 @@ import { sidekickCeilingInstallation, } from "../src/repl/sidekick/profile.ts"; import { runSidekickCommand } from "../src/sidekick-acp/command.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { cliCommand, cliShellCommand, shellQuote } from "@executablemd/test-support/launch"; import { readTextFile, writeTextFile } from "@effectionx/fs"; @@ -100,6 +101,8 @@ import { journalReplyBound, } from "../src/sidekick-acp/protocol.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-acp.test.ts"; + const ROOT = fileURLToPath(new URL("../../../", import.meta.url)); const attachResult = z.object({ attachment: z.string() }).strict(); const message = z @@ -2500,6 +2503,7 @@ describe("A5: a peer the listener accepts after teardown begins", () => { }); describe("ACP startup bootstrap", () => { + beforeEach(journalBeforeEach(OWNER)); it("creates a real initial message without UI input and joins the first external prompt", function* () { yield* usePosixSidekickTransport(process.platform); const home = yield* until(realpath(yield* useTemporary("xmd-acp-startup-"))); @@ -3653,6 +3657,7 @@ describe("ACP82: the file this publication keeps open", () => { }); describe("resume presentation in mounted Sidekick chat", () => { + beforeEach(journalBeforeEach(OWNER)); const actionable = "Release first."; const credential = ["ghp", "_", "abcdefghijklmnopqrstuvwxyz0123456789"].join(""); const remedy = "could not be resumed"; @@ -3794,6 +3799,7 @@ describe("resume presentation in mounted Sidekick chat", () => { }); describe("Follow: joined mixed-origin queue handoff", () => { + beforeEach(journalBeforeEach(OWNER)); it("Follow: mounted UI and delivered ACP stay FIFO behind entry and generated-control cleanup", function* () { yield* usePosixSidekickTransport(process.platform); const home = yield* publishingHome("xmd-follow-queue-"); diff --git a/packages/cli/tests/repl-sidekick-configuration.test.ts b/packages/cli/tests/repl-sidekick-configuration.test.ts index b22218673..7417b8f8e 100644 --- a/packages/cli/tests/repl-sidekick-configuration.test.ts +++ b/packages/cli/tests/repl-sidekick-configuration.test.ts @@ -19,7 +19,8 @@ * association rather than a conversation's agent. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Ok, scoped, sleep, spawn } from "effection"; import type { Operation, Result, Task } from "effection"; @@ -156,6 +157,8 @@ import { createRepositoryRoot, runPhase } from "./fixtures/repl/issue-883/host.t import { AGENT, useHarness, useTemporary } from "./fixtures/repl/issue-883/sidekick-harness.ts"; import type { Harness } from "./fixtures/repl/issue-883/sidekick-harness.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-configuration.test.ts"; + /** A second agent, named explicitly rather than defaulted to. */ const OTHER = "other-sidekick"; @@ -905,6 +908,7 @@ function outside(page: ReplPage): string[] { } describe("Tier CFG — Configure in the Sidekick's pane", () => { + beforeEach(journalBeforeEach(OWNER)); /** What this agent offers, and what each of its models offers for effort. */ const ADVERTISED = { model: { @@ -1283,31 +1287,35 @@ describe("Tier CFG — Configure in the Sidekick's pane", () => { const closing = gate.holdNext( (path, record) => path.endsWith("entries.jsonl") && record.includes('"type":"close"'), ); - yield* sendMessage(page, "run it"); - yield* closing.started(); - yield* page.until("the entry's output", (one) => one.shows("the entry ran")); - const asking = repl.fake.configCalls.length; - - if (changing) { - // Applied while the entry is held. A preference is a record, so this asks - // the agent for nothing and stops nothing. - yield* openConfigure(page); - yield* offeredChoice(page, NAMED["fast"]); - yield* chooseNamed(page, "fast"); - yield* applyConfigure(page); - yield* drawerGone(page); - expect(yield* savedPreference(repl)).toMatchObject({ model: "fast" }); - // Nothing of the agent's was touched by saving, and the entry is still - // held: the save coexists with the work rather than interrupting it. - expect(repl.fake.configCalls).toHaveLength(asking); - expect(closing.released).toBe(false); + try { + yield* sendMessage(page, "run it"); + yield* closing.started(); + yield* page.until("the entry's output", (one) => one.shows("the entry ran")); + const asking = repl.fake.configCalls.length; + + if (changing) { + // Applied while the entry is held. A preference is a record, so this asks + // the agent for nothing and stops nothing. + yield* openConfigure(page); + yield* offeredChoice(page, NAMED["fast"]); + yield* chooseNamed(page, "fast"); + yield* applyConfigure(page); + yield* drawerGone(page); + expect(yield* savedPreference(repl)).toMatchObject({ model: "fast" }); + // Nothing of the agent's was touched by saving, and the entry is still + // held: the save coexists with the work rather than interrupting it. + expect(repl.fake.configCalls).toHaveLength(asking); + expect(closing.released).toBe(false); + } + + // Released: the entry settles, the Submit it was waiting for answers, and + // the automatic turn that reports it runs. + closing.release(); + yield* page.until("the turn that follows the entry", (one) => one.shows("Both done.")); + return repl.fake.configCalls.slice(asking); + } finally { + closing.release(); } - - // Released: the entry settles, the Submit it was waiting for answers, and - // the automatic turn that reports it runs. - closing.release(); - yield* page.until("the turn that follows the entry", (one) => one.shows("Both done.")); - return repl.fake.configCalls.slice(asking); } it("CFG3: a preference saved while an entry is held is used by the turn after it", function* () { @@ -1507,6 +1515,7 @@ describe("Tier CFG — Configure in the Sidekick's pane", () => { * agent's choices goes with the replacement. */ describe("Tier CFG — replacing the Sidekick's agent", () => { + beforeEach(journalBeforeEach(OWNER)); const ADVERTISED = { model: { selected: "balanced", @@ -1735,35 +1744,39 @@ describe("Tier CFG — replacing the Sidekick's agent", () => { const closing = gate.holdNext( (path, record) => path.endsWith("entries.jsonl") && record.includes('"type":"close"'), ); - yield* sendMessage(page, "run it"); - yield* closing.started(); - yield* page.until("the entry's output", (one) => one.shows("the entry ran")); + try { + yield* sendMessage(page, "run it"); + yield* closing.started(); + yield* page.until("the entry's output", (one) => one.shows("the entry ran")); - yield* openConfigure(page); - yield* replaceAgent(page, OTHER_MOUNTED_AGENT); - yield* page.until("the control saying it stops first", (one) => - applyReads(one, "[stop and start new conversation"), - ); - yield* applyConfigure(page); - yield* page.until("the new agent after the join", (one) => - headerNames(one, OTHER_MOUNTED_AGENT), - ); - // The entry was not cancelled with the conversation that asked for it: it - // is the document's work, and it is still waiting to close. - expect(closing.released).toBe(false); - - closing.release(); - // It finishes on its own, and its record is in this execution's entries. - // The gate records the whole path it let through, so this asks whether an - // entries file was written rather than naming one. - yield* awaited("the entry closing", () => - gate.reached.some((one) => one.endsWith("entries.jsonl")), - ); - yield* entrySettles(page, 1, "ok"); - expect(page.screen().shows("the entry ran")).toBe(true); - // And the new conversation is the one a message now goes to. - yield* page.until("the Sidekick at rest", sidekickIdle); - yield* conversed(page, "and you?", "Second agent."); + yield* openConfigure(page); + yield* replaceAgent(page, OTHER_MOUNTED_AGENT); + yield* page.until("the control saying it stops first", (one) => + applyReads(one, "[stop and start new conversation"), + ); + yield* applyConfigure(page); + yield* page.until("the new agent after the join", (one) => + headerNames(one, OTHER_MOUNTED_AGENT), + ); + // The entry was not cancelled with the conversation that asked for it: it + // is the document's work, and it is still waiting to close. + expect(closing.released).toBe(false); + + closing.release(); + // It finishes on its own, and its record is in this execution's entries. + // The gate records the whole path it let through, so this asks whether an + // entries file was written rather than naming one. + yield* awaited("the entry closing", () => + gate.reached.some((one) => one.endsWith("entries.jsonl")), + ); + yield* entrySettles(page, 1, "ok"); + expect(page.screen().shows("the entry ran")).toBe(true); + // And the new conversation is the one a message now goes to. + yield* page.until("the Sidekick at rest", sidekickIdle); + yield* conversed(page, "and you?", "Second agent."); + } finally { + closing.release(); + } }); it("CFG4: an unreachable agent keeps the old association and says why", function* () { @@ -1872,6 +1885,7 @@ describe("Tier CFG — replacing the Sidekick's agent", () => { * explicit job does to another. */ describe("Tier CFG — one order for everything this conversation writes", () => { + beforeEach(journalBeforeEach(OWNER)); const ADVERTISED = { model: { selected: "balanced", @@ -1902,37 +1916,41 @@ describe("Tier CFG — one order for everything this conversation writes", () => const writing = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"kind":"response"'), ); - repl.fake.script({ reply: "And this one.\n" }); - yield* sendMessage(page, "again"); - yield* writing.started(); + try { + repl.fake.script({ reply: "And this one.\n" }); + yield* sendMessage(page, "again"); + yield* writing.started(); - // A preference applied while that write is in flight. It is admitted — - // a save is a record of this history rather than work the conversation - // does — and it waits for the writer rather than overtaking it. - yield* openConfigure(page); - yield* offeredChoice(page, NAMED["fast"]); - yield* chooseNamed(page, "fast"); - yield* applyConfigure(page); - yield* lingering(); - // Nothing of it reached the file while the other append was inside the - // host, and the held write is still held. - expect(yield* savedPreference(repl)).toBe(undefined); - expect(writing.released).toBe(false); + // A preference applied while that write is in flight. It is admitted — + // a save is a record of this history rather than work the conversation + // does — and it waits for the writer rather than overtaking it. + yield* openConfigure(page); + yield* offeredChoice(page, NAMED["fast"]); + yield* chooseNamed(page, "fast"); + yield* applyConfigure(page); + yield* lingering(); + // Nothing of it reached the file while the other append was inside the + // host, and the held write is still held. + expect(yield* savedPreference(repl)).toBe(undefined); + expect(writing.released).toBe(false); - writing.release(); - yield* page.until("the reply that was being written", (one) => one.shows("And this one.")); - yield* awaitedFact("the preference landing", function* (): Operation { - return (yield* savedPreference(repl)) !== undefined; - }); + writing.release(); + yield* page.until("the reply that was being written", (one) => one.shows("And this one.")); + yield* awaitedFact("the preference landing", function* (): Operation { + return (yield* savedPreference(repl)) !== undefined; + }); - // One order, on disk: the response that was being written, and then the - // preference that waited for it. Read back through the projection, so this - // is the history as everything else reads it. - const read = yield* settledReading(repl); - const kinds = read.chat.map((record) => record.kind); - expect(kinds.indexOf("preferences")).toBeGreaterThan(kinds.lastIndexOf("response")); - expect(yield* savedPreference(repl)).toMatchObject({ model: "fast" }); - expect(read.chat.filter((record) => record.kind === "response")).toHaveLength(2); + // One order, on disk: the response that was being written, and then the + // preference that waited for it. Read back through the projection, so this + // is the history as everything else reads it. + const read = yield* settledReading(repl); + const kinds = read.chat.map((record) => record.kind); + expect(kinds.indexOf("preferences")).toBeGreaterThan(kinds.lastIndexOf("response")); + expect(yield* savedPreference(repl)).toMatchObject({ model: "fast" }); + expect(read.chat.filter((record) => record.kind === "response")).toHaveLength(2); + } finally { + writing.release(); + } }); it("CFG8: a replacement owns the drawer while it runs, and rebinds what Apply saves", function* () { @@ -2036,6 +2054,7 @@ describe("Tier CFG — one order for everything this conversation writes", () => }); describe("Tier CFG — Retry for a request whose turn failed", () => { + beforeEach(journalBeforeEach(OWNER)); it("CFG5: Retry sends the saved request again, not whatever is in the box", function* () { const page = yield* useReplPage(); const repl = page.repl; @@ -2223,6 +2242,7 @@ describe("Tier CFG — Retry for a request whose turn failed", () => { * exercising every flag and the interactive screen at once is not this row. */ describe("Tier TE — the two configured agents each do their own work", () => { + beforeEach(journalBeforeEach(OWNER)); /** One entry asking one Agent, naming no agent: the default is the subject. */ const ASKING = ['', '', ""].join("\n"); @@ -2300,6 +2320,7 @@ describe("Tier TE — the two configured agents each do their own work", () => { * field, so these rows drive the width of a notice the way a person does. */ describe("Configure notice fitting", () => { + beforeEach(journalBeforeEach(OWNER)); /** What the agent in these rows advertises, so the drawer has choices to draw. */ const ADVERTISED = { model: { diff --git a/packages/cli/tests/repl-sidekick-dispatch.test.ts b/packages/cli/tests/repl-sidekick-dispatch.test.ts index 0475a73b8..09e9ba77e 100644 --- a/packages/cli/tests/repl-sidekick-dispatch.test.ts +++ b/packages/cli/tests/repl-sidekick-dispatch.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Ok, scoped, spawn, suspend, withResolvers } from "effection"; import type { Operation, Result } from "effection"; @@ -34,6 +35,8 @@ import { sidekickIdle, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-dispatch.test.ts"; + function service( held: Harness, admission = createSidekickAdmission(), @@ -78,6 +81,7 @@ function fills(source: string): string { } describe("shared Sidekick dispatch", () => { + beforeEach(journalBeforeEach(OWNER)); for (const busy of [false, true]) { it(`keeps one pasted Message at its caret while ${busy ? "busy" : "idle"}`, function* () { const page = yield* useReplPage(); diff --git a/packages/cli/tests/repl-sidekick-journey.test.ts b/packages/cli/tests/repl-sidekick-journey.test.ts index bb99a434c..6d1495439 100644 --- a/packages/cli/tests/repl-sidekick-journey.test.ts +++ b/packages/cli/tests/repl-sidekick-journey.test.ts @@ -36,7 +36,8 @@ import { pairedLocation } from "../src/repl/sidekick/history.ts"; import { encodeLocation } from "../src/repl/route.ts"; import { initialState } from "../src/repl/application.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { allSettled, @@ -121,6 +122,8 @@ import { unwrapped, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-journey.test.ts"; + /** * The orientation an older build left on a conversation it completed a turn of. * @@ -1217,6 +1220,7 @@ function* composedChat(repl: MountedRepl): Operation { * item then becomes the evaluated reply. */ describe("Tier PV — a response in flight, shown as it arrives", () => { + beforeEach(journalBeforeEach(OWNER)); /** * A reply whose text arrives in pieces, with candidate controls in it. * @@ -1299,53 +1303,61 @@ describe("Tier PV — a response in flight, shown as it arrives", () => { const closing = gate.holdNext( (path, record) => path.endsWith("entries.jsonl") && record.includes('"type":"close"'), ); - repl.fake.releaseDeltas(); - // The update, with nothing else going on and still nothing pressed: the - // sentence is finished by the piece that just arrived. - yield* page.until("the finished sentence", (one) => - one.shows(`${MOUNTED_AGENT} (preview): Half a thought.`), - ); - expect(repl.terminal.fed).toBe(fed); + try { + repl.fake.releaseDeltas(); + // The update, with nothing else going on and still nothing pressed: the + // sentence is finished by the piece that just arrived. + yield* page.until("the finished sentence", (one) => + one.shows(`${MOUNTED_AGENT} (preview): Half a thought.`), + ); + expect(repl.terminal.fed).toBe(fed); - // The whole candidate has now arrived — the EntryInput and the Submit came - // with that second piece — and the provider has not finished. None of it - // has run: no control pair, no fill, no entry. This is the boundary the - // claim is about, because source nobody completed is not a program. - yield* repl.fake.streamingTurns(1); - const complete = yield* settledReading(repl); - expect(complete.chat.filter((record) => record.kind === "control")).toEqual([]); - expect(complete.chat.filter((record) => record.kind === "response")).toEqual([]); - expect(complete.model.entries).toEqual([]); - expect(draftHolds(page.screen(), "mine")).toBe(true); - expect(page.screen().shows("HEAD · EMPTY")).toBe(true); - expect(repl.terminal.fed).toBe(fed); + // The whole candidate has now arrived — the EntryInput and the Submit came + // with that second piece — and the provider has not finished. None of it + // has run: no control pair, no fill, no entry. This is the boundary the + // claim is about, because source nobody completed is not a program. + yield* repl.fake.streamingTurns(1); + const complete = yield* settledReading(repl); + expect(complete.chat.filter((record) => record.kind === "control")).toEqual([]); + expect(complete.chat.filter((record) => record.kind === "response")).toEqual([]); + expect(complete.model.entries).toEqual([]); + expect(draftHolds(page.screen(), "mine")).toBe(true); + expect(page.screen().shows("HEAD · EMPTY")).toBe(true); + expect(repl.terminal.fed).toBe(fed); - repl.fake.releaseDeltas(); - yield* closing.started(); - // Still a preview while its controls run: nothing has been evaluated into - // a reply. - expect(page.screen().shows(`${MOUNTED_AGENT} (preview): Half a thought.`)).toBe(true); - const running = yield* settledReading(repl); - expect(running.chat.filter((record) => record.kind === "response")).toEqual([]); - - // Released: the entry settles, the response is evaluated, and the same item - // becomes the reply — the preview is gone, not joined by an answer. - closing.release(); - yield* page.until("the evaluated reply", (one) => saidBySidekick(one, "Half a thought.")); - yield* page.until("the Sidekick at rest", sidekickIdle); - expect(page.screen().shows("(preview)")).toBe(false); - const after = yield* settledReading(repl); - // One response record for the turn that was being previewed, and exactly - // one: the item a person watched arrive is the item they are reading. - const answered = after.chat.filter((record) => record.kind === "response" && record.turn === 1); - expect(answered).toHaveLength(1); - expect(answered[0]).toMatchObject({ output: "Half a thought.", hasOutput: true }); - // The entry really ran, and its feedback went back as the next turn's - // request rather than as chat. - expect(after.model.entries.map((entry) => entry.key)).toEqual(["entry-1"]); - yield* page.until("the turn that was told what it did", (one) => one.shows("And the receipt.")); - expect(repl.fake.prompts[1] ?? "").toContain("## REPL.Submit"); - expect(page.screen().shows("REPL.Submit")).toBe(false); + repl.fake.releaseDeltas(); + yield* closing.started(); + // Still a preview while its controls run: nothing has been evaluated into + // a reply. + expect(page.screen().shows(`${MOUNTED_AGENT} (preview): Half a thought.`)).toBe(true); + const running = yield* settledReading(repl); + expect(running.chat.filter((record) => record.kind === "response")).toEqual([]); + + // Released: the entry settles, the response is evaluated, and the same item + // becomes the reply — the preview is gone, not joined by an answer. + closing.release(); + yield* page.until("the evaluated reply", (one) => saidBySidekick(one, "Half a thought.")); + yield* page.until("the Sidekick at rest", sidekickIdle); + expect(page.screen().shows("(preview)")).toBe(false); + const after = yield* settledReading(repl); + // One response record for the turn that was being previewed, and exactly + // one: the item a person watched arrive is the item they are reading. + const answered = after.chat.filter( + (record) => record.kind === "response" && record.turn === 1, + ); + expect(answered).toHaveLength(1); + expect(answered[0]).toMatchObject({ output: "Half a thought.", hasOutput: true }); + // The entry really ran, and its feedback went back as the next turn's + // request rather than as chat. + expect(after.model.entries.map((entry) => entry.key)).toEqual(["entry-1"]); + yield* page.until("the turn that was told what it did", (one) => + one.shows("And the receipt."), + ); + expect(repl.fake.prompts[1] ?? "").toContain("## REPL.Submit"); + expect(page.screen().shows("REPL.Submit")).toBe(false); + } finally { + closing.release(); + } }); it("PV2: what the screen shows a prefix saying is what the pure reader says", function* () { const page = yield* useReplPage(); @@ -1709,6 +1721,7 @@ const GATED_ENTRY_REPLY = [ ].join("\n"); describe("Tier R5 — a mounted message prepares and submits a real entry", () => { + beforeEach(journalBeforeEach(OWNER)); it("M3: the message a person sends runs its entry, and is answered about it", function* () { const page = yield* useReplPage(); const repl = page.repl; @@ -2050,6 +2063,7 @@ describe("Tier R5 — a mounted message prepares and submits a real entry", () = * both arms identically. */ describe("Tier TE — a published binding becomes real greetings, and then a real table", () => { + beforeEach(journalBeforeEach(OWNER)); /** What the first arm publishes. */ const FIRST = ["Ada", "Grace", "Linus"]; /** The same arm with one name replaced, and nothing else changed. */ @@ -2303,6 +2317,7 @@ describe("Tier TE — a published binding becomes real greetings, and then a rea * authors becomes a second real entry while the first stays exactly as it failed. */ describe("Tier TE — a failed entry is corrected as a new entry", () => { + beforeEach(journalBeforeEach(OWNER)); it("TE2: the failure goes back to its owner, which submits a corrected entry", function* () { const page = yield* useReplPage(); const repl = page.repl; @@ -3412,6 +3427,7 @@ describe("Tier EI — four reads make a saved failure diagnosable", () => { }); describe("975 — the shipped session component journey", () => { + beforeEach(journalBeforeEach(OWNER)); it("creates, discovers and invokes a component, then reopens without work", function* () { yield* Permissions.around( { files: ([operation], next) => (operation === "absolute" ? true : next(operation)) }, @@ -3659,6 +3675,7 @@ describe("975 — entry cwd ends with its actual owner", () => { }); describe("975 — configured-first lookup and unchanged permissions", () => { + beforeEach(journalBeforeEach(OWNER)); function submitSource(source: string): string { return ( '\n```xmd\n' + @@ -3998,6 +4015,7 @@ function followSubmission(source: string): string { } describe("Follow: submitted rounds in the running command", () => { + beforeEach(journalBeforeEach(OWNER)); it("Follow: one mounted Send carries completed, failed and Entry Stop output from exact joined entries", function* () { const asking = withResolvers(); yield* Elicitation.around({ @@ -4566,6 +4584,7 @@ Session body ${version}.`, }); describe("993 mounted nested Output journeys", () => { + beforeEach(journalBeforeEach(OWNER)); for (const ready of [true, false]) { it(`W1: an actual Draft entry selects branch ${ready} and only that marker`, function* () { const workspace = yield* useTemporary("nested-repl-"); @@ -4767,6 +4786,7 @@ describe("993 mounted nested Output journeys", () => { }); describe("Contributed Sidekick controls", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps contributed entry-only Cwd authored while omitting generated selection and vocabulary", function* () { let calls = 0; const plugin = Plugin({ @@ -5158,6 +5178,7 @@ describe("protected Sidekick question feedback", () => { }); describe("1183 — a follow-up sent during live automatic feedback", () => { + beforeEach(journalBeforeEach(OWNER)); it("A1/A2: queues visibly behind the held feedback and starts once on the same conversation", function* () { const page = yield* useReplPage(); const FOLLOW_UP = "When that finishes, explain the changes."; @@ -5225,6 +5246,7 @@ describe("1183 — a follow-up sent during live automatic feedback", () => { * entry's Output all keep the punctuation around it. */ describe("1342 — written Markdown in the chat and in entry Output", () => { + beforeEach(journalBeforeEach(OWNER)); const WIDE_SIZE = { columns: 160, rows: 36 }; const NARROW_SIZE = { columns: 72, rows: 20 }; const ENTRY_MARKDOWN = [ diff --git a/packages/cli/tests/repl-sidekick-lifecycle.test.ts b/packages/cli/tests/repl-sidekick-lifecycle.test.ts index 3205dbd83..7896aed07 100644 --- a/packages/cli/tests/repl-sidekick-lifecycle.test.ts +++ b/packages/cli/tests/repl-sidekick-lifecycle.test.ts @@ -25,7 +25,8 @@ import type { Contributions } from "./fixtures/repl/contributed-plugin.ts"; * owner, an answer and a withdrawal whether or not anything is drawing it. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import type { SidekickOperation } from "../src/repl/sidekick/model.ts"; import { ensure, Ok, sleep, spawn, suspend, until, withResolvers } from "effection"; @@ -101,6 +102,8 @@ import { join } from "node:path"; import { readFile } from "node:fs/promises"; import type { SidekickRecord } from "../src/repl/sidekick/history.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-lifecycle.test.ts"; + /** * Real time for an assertion that something did not happen. * @@ -932,6 +935,7 @@ describe("Tier R6 — a reply asks, and the Sidekick owns the answer", () => { * said as one, and only as much of one as was actually saved. */ describe("Tier PV — generation that ended without a reply", () => { + beforeEach(journalBeforeEach(OWNER)); /** A candidate that says something and then asks for work to be done. */ const CANDIDATE = [ "As far as I got.\n", @@ -1025,60 +1029,70 @@ describe("Tier PV — generation that ended without a reply", () => { const closing = gate.holdNext( (path, record) => path.endsWith("entries.jsonl") && record.includes('"type":"close"'), ); - yield* pasteDraft(page, OWN_ENTRY); - yield* page.key("Tab"); - yield* page.until("Round Send focused", (one) => one.shows("> Send")); - yield* page.key("Enter"); - yield* closing.started(); - - yield* sendMessage(page, "try it"); - yield* repl.fake.streamingTurns(1); - yield* page.until("the preview", (one) => one.shows(`${MOUNTED_AGENT} (preview): As far as I`)); + try { + yield* pasteDraft(page, OWN_ENTRY); + yield* page.key("Tab"); + yield* page.until("Round Send focused", (one) => one.shows("> Send")); + yield* page.key("Enter"); + yield* closing.started(); + + yield* sendMessage(page, "try it"); + yield* repl.fake.streamingTurns(1); + yield* page.until("the preview", (one) => + one.shows(`${MOUNTED_AGENT} (preview): As far as I`), + ); - // Stopped, with the provider's own cancellation held: this is what says - // Stop joined what it asked for rather than returning over the top of it. - expect(page.screen().shows("[x] Follow")).toBe(true); - const cancelling = repl.fake.holdCancellation(); - // The Sidekick's own Stop. This person's entry is running, so the draft is - // wearing a Stop too — and it is the leftmost, so a press that went looking - // for `[stop]` on the screen would stop the document's work and never reach - // the generation this row is about. - yield* stopSidekick(page); - yield* cancelling.reached; - expect(repl.outcome()).toBe(undefined); - cancelling.release(); + // Stopped, with the provider's own cancellation held: this is what says + // Stop joined what it asked for rather than returning over the top of it. + expect(page.screen().shows("[x] Follow")).toBe(true); + const cancelling = repl.fake.holdCancellation(); + try { + // The Sidekick's own Stop. This person's entry is running, so the draft is + // wearing a Stop too — and it is the leftmost, so a press that went looking + // for `[stop]` on the screen would stop the document's work and never reach + // the generation this row is about. + yield* stopSidekick(page); + yield* cancelling.reached; + expect(repl.outcome()).toBe(undefined); + cancelling.release(); + } finally { + cancelling.release(); + } - // What the agent said stays, as the attempt it is — and it claims nothing: - // no turn, no response, no acceptance, no recorded failure. - yield* page.until("the attempt Stop left", (one) => - one.shows(`${MOUNTED_AGENT} (unfinished): As far as I`), - ); - expect(page.screen().shows("[x] Follow")).toBe(true); - const read = yield* settledReading(repl); - expect(read.chat.filter((record) => record.kind === "response")).toEqual([]); - expect(read.chat.filter((record) => record.kind === "control")).toEqual([]); - expect(page.screen().shows("[retry]")).toBe(false); - // None of the candidate's controls ran, and no successor turn started. - expect(repl.fake.prompts).toHaveLength(1); + // What the agent said stays, as the attempt it is — and it claims nothing: + // no turn, no response, no acceptance, no recorded failure. + yield* page.until("the attempt Stop left", (one) => + one.shows(`${MOUNTED_AGENT} (unfinished): As far as I`), + ); + expect(page.screen().shows("[x] Follow")).toBe(true); + const read = yield* settledReading(repl); + expect(read.chat.filter((record) => record.kind === "response")).toEqual([]); + expect(read.chat.filter((record) => record.kind === "control")).toEqual([]); + expect(page.screen().shows("[retry]")).toBe(false); + // None of the candidate's controls ran, and no successor turn started. + expect(repl.fake.prompts).toHaveLength(1); - // The entry is untouched by any of it: still open, and still the - // document's own work to finish. - expect(closing.released).toBe(false); - closing.release(); - yield* page.until("the entry finishing on its own", (one) => one.shows("my own entry")); + // The entry is untouched by any of it: still open, and still the + // document's own work to finish. + expect(closing.released).toBe(false); + closing.release(); + yield* page.until("the entry finishing on its own", (one) => one.shows("my own entry")); - // And nothing of that attempt was persisted to preserve a screen: a cold - // reopen of this same history has no account of it. - const execution = yield* mountedExecution(repl); - yield* page.press("[exit]"); - yield* awaited("the command returning", () => repl.outcome() !== undefined); - const againPage = yield* useReplPage({ - host, - location: `xmd://repl/${execution}/entries`, - }); - yield* againPage.until("the reopened chat", (one) => saidByPerson(one, "try it")); - expect(againPage.screen().shows("(unfinished)")).toBe(false); - expect(againPage.screen().shows("As far as I")).toBe(false); + // And nothing of that attempt was persisted to preserve a screen: a cold + // reopen of this same history has no account of it. + const execution = yield* mountedExecution(repl); + yield* page.press("[exit]"); + yield* awaited("the command returning", () => repl.outcome() !== undefined); + const againPage = yield* useReplPage({ + host, + location: `xmd://repl/${execution}/entries`, + }); + yield* againPage.until("the reopened chat", (one) => saidByPerson(one, "try it")); + expect(againPage.screen().shows("(unfinished)")).toBe(false); + expect(againPage.screen().shows("As far as I")).toBe(false); + } finally { + closing.release(); + } }); /** @@ -1206,6 +1220,7 @@ describe("Tier PV — generation that ended without a reply", () => { }); describe("Tier R6 — leaving, with Sidekick work in flight", () => { + beforeEach(journalBeforeEach(OWNER)); /** An entry that publishes nothing and stays open until it is torn down. */ const SUSPENDS = ["```js eval", "yield* suspend();", "```", ""].join("\n"); @@ -1323,6 +1338,7 @@ describe("Tier R6 — leaving, with Sidekick work in flight", () => { * terminal sends are text there, and only a plain Enter sends. */ describe("Control-C and newlines in the message box", () => { + beforeEach(journalBeforeEach(OWNER)); function* composing(text: string): Operation { const page = yield* useReplPage(); yield* intoComposer(page); @@ -1522,6 +1538,7 @@ describe("Control-C and newlines in the message box", () => { * tree, with only the terminal and the transport replaced. */ describe("Tier MQ — a Sidekick question, filled in and answered on the screen", () => { + beforeEach(journalBeforeEach(OWNER)); /** A choice, and a reason long enough that a short one is a real refusal. */ const REVIEW = { type: "object", @@ -1693,6 +1710,7 @@ describe("Tier MQ — a Sidekick question, filled in and answered on the screen" * answers, and a Stop that withdraws one without inventing an answer to either. */ describe("Tier MQ — two questions, two answers, and Stop", () => { + beforeEach(journalBeforeEach(OWNER)); /** Overlapping field names, so an answer reaching the wrong form would show. */ const SIDEKICK_ASKS = { type: "object", @@ -1866,6 +1884,7 @@ describe("Tier MQ — two questions, two answers, and Stop", () => { * leaves a readable account of what it was in the middle of. */ describe("Tier MQ — leaving with questions pending, and the cold reopen after", () => { + beforeEach(journalBeforeEach(OWNER)); const ASKS = { type: "object", properties: { choice: { type: "string", enum: ["yes", "no"] } }, @@ -1999,6 +2018,7 @@ describe("Tier MQ — leaving with questions pending, and the cold reopen after" * written nothing publishes nothing. */ describe("Tier CFG — a preference being written when the command leaves", () => { + beforeEach(journalBeforeEach(OWNER)); const ADVERTISED = { model: { selected: "balanced", @@ -2041,36 +2061,40 @@ describe("Tier CFG — a preference being written when the command leaves", () = // their way and this writer's memory of them is not there yet, which is the // one window the ordering is about. const saving = gate.holdNext((_path, record) => record.includes('"kind":"preferences"')); - yield* page.press("[apply]"); - yield* saving.started(); + try { + yield* page.press("[apply]"); + yield* saving.started(); - // Leave while it is in flight. - yield* page.press("[exit]"); - yield* lingering(); + // Leave while it is in flight. + yield* page.press("[exit]"); + yield* lingering(); - // The command has not returned: it is waiting for the record it admitted. - expect(repl.outcome()).toBe(undefined); - expect(repl.terminal.resets).toBe(0); + // The command has not returned: it is waiting for the record it admitted. + expect(repl.outcome()).toBe(undefined); + expect(repl.terminal.resets).toBe(0); - saving.release(); - yield* awaited("the command returning", () => repl.outcome() !== undefined); + saving.release(); + yield* awaited("the command returning", () => repl.outcome() !== undefined); - // Once, and with everything released. - expect(repl.outcome()?.ok).toBe(true); - expect(repl.terminal.resets).toBe(1); - expect(repl.terminal.readers).toBe(0); - expect(repl.terminal.listeners).toBe(0); + // Once, and with everything released. + expect(repl.outcome()?.ok).toBe(true); + expect(repl.terminal.resets).toBe(1); + expect(repl.terminal.readers).toBe(0); + expect(repl.terminal.listeners).toBe(0); - // And the record is on disk: a save that had been let go of halfway would - // have left the file holding something nothing acknowledged, or nothing at - // all after the drawer said it had saved. - const execution = yield* mountedExecution(repl); - const written = yield* readSidekickRecords( - join(repl.root, PAIRED_DIRECTORY, execution, SIDEKICK_FILE), - ); - const saved = written.filter((record) => record.kind === "preferences"); - expect(saved).toHaveLength(1); - expect(saved[0]).toMatchObject({ model: "fast" }); + // And the record is on disk: a save that had been let go of halfway would + // have left the file holding something nothing acknowledged, or nothing at + // all after the drawer said it had saved. + const execution = yield* mountedExecution(repl); + const written = yield* readSidekickRecords( + join(repl.root, PAIRED_DIRECTORY, execution, SIDEKICK_FILE), + ); + const saved = written.filter((record) => record.kind === "preferences"); + expect(saved).toHaveLength(1); + expect(saved[0]).toMatchObject({ model: "fast" }); + } finally { + saving.release(); + } }); it("CFG9: a save still waiting for the writer is cancelled, and appends nothing", function* () { @@ -2094,32 +2118,36 @@ describe("Tier CFG — a preference being written when the command leaves", () = // Somebody else's record held inside the host, so the writer is occupied // by an append that is not this save's. const writing = gate.holdNext((_path, record) => record.includes('"kind":"response"')); - yield* sendMessage(page, "again"); - yield* writing.started(); - - // And now the save, which is admitted and then *waits*: it is behind that - // append in the one order this history has. - yield* configure(page); - yield* chooseOffer(page, "Fast"); - yield* page.until("the model being chosen", (one) => one.shows("(x) Fast")); - yield* page.press("[apply]"); - yield* lingering(); - const before = yield* readSidekickRecords(savedAt(repl, yield* mountedExecution(repl))); - expect(before.filter((record) => record.kind === "preferences")).toEqual([]); - - // Control-C while it is still waiting. A waiter is not a write: it has - // nothing in flight to join, so leaving cancels it. - repl.terminal.feed("\x03"); - writing.release(); - yield* awaited("the command returning", () => repl.outcome() !== undefined); - expect(repl.outcome()?.ok).toBe(true); - expect(repl.terminal.resets).toBe(1); - - // Nothing of it reached the file, then or later: a cancelled waiter writes - // no record, and no record arrives after the command has gone. - yield* lingering(); - const written = yield* readSidekickRecords(savedAt(repl, yield* mountedExecution(repl))); - expect(written.filter((record) => record.kind === "preferences")).toEqual([]); + try { + yield* sendMessage(page, "again"); + yield* writing.started(); + + // And now the save, which is admitted and then *waits*: it is behind that + // append in the one order this history has. + yield* configure(page); + yield* chooseOffer(page, "Fast"); + yield* page.until("the model being chosen", (one) => one.shows("(x) Fast")); + yield* page.press("[apply]"); + yield* lingering(); + const before = yield* readSidekickRecords(savedAt(repl, yield* mountedExecution(repl))); + expect(before.filter((record) => record.kind === "preferences")).toEqual([]); + + // Control-C while it is still waiting. A waiter is not a write: it has + // nothing in flight to join, so leaving cancels it. + repl.terminal.feed("\x03"); + writing.release(); + yield* awaited("the command returning", () => repl.outcome() !== undefined); + expect(repl.outcome()?.ok).toBe(true); + expect(repl.terminal.resets).toBe(1); + + // Nothing of it reached the file, then or later: a cancelled waiter writes + // no record, and no record arrives after the command has gone. + yield* lingering(); + const written = yield* readSidekickRecords(savedAt(repl, yield* mountedExecution(repl))); + expect(written.filter((record) => record.kind === "preferences")).toEqual([]); + } finally { + writing.release(); + } }); it("CFG9: an inspection in flight is cancelled, and its result reaches nothing", function* () { @@ -2191,6 +2219,7 @@ describe("Tier CFG — a preference being written when the command leaves", () = }); describe("Follow: mounted Stop owns continuation", () => { + beforeEach(journalBeforeEach(OWNER)); /** The Round bar's own Stop, counted only while that one bar is drawn. */ const roundStops = (one: ScreenReading): number => one.occurrences("+ New Round") === 1 ? one.found("Stop", { onRow: "+ New Round" }) : -1; @@ -2267,6 +2296,7 @@ describe("Follow: mounted Stop owns continuation", () => { }); describe("Contributed control acknowledgement and teardown", () => { + beforeEach(journalBeforeEach(OWNER)); it("R4f: intent acknowledgement and joined cleanup precede outcome and feedback", function* () { const counts: Contributions = { initialized: 0, conversations: 0, closed: 0, calls: [] }; const gate = appendGate(); @@ -2275,36 +2305,44 @@ describe("Contributed control acknowledgement and teardown", () => { record.includes('"kind":"control"') && record.includes('"component":"Contributed"'), ); const outcome = gate.holdNext((_path, record) => record.includes('"kind":"control-outcome"')); - const cleaning = withResolvers(); const release = withResolvers(); - counts.cleanup = function* () { - cleaning.resolve(); - yield* release.operation; - }; - const held = yield* usePluginProgram({ plugins: [contributedPlugin(counts)], gate }); - held.host.fake.script({ reply: '' }); - held.host.fake.script({ reply: "joined" }); - const sending = yield* spawn(() => held.root.owner.message("Read the contributed value")); - yield* intent.started(); - expect(counts.calls).toEqual([]); - expect(held.host.fake.prompts).toHaveLength(1); - intent.release(); - yield* cleaning.operation; - expect(counts.calls).toEqual(["read"]); - expect(held.host.fake.prompts).toHaveLength(1); - const execution = yield* held.host.repository.open(held.root.execution); - expect((yield* records(execution)).filter((one) => one.kind === "control-outcome")).toEqual([]); - release.resolve(); - yield* outcome.started(); - expect(held.host.fake.prompts).toHaveLength(1); - outcome.release(); - expect((yield* sending).ok).toBe(true); - expect(held.host.fake.prompts[1]).toContain('"count": 1'); - expect( - (yield* records(yield* held.host.repository.open(held.root.execution))).filter( - (one) => one.kind === "control-outcome", - ), - ).toHaveLength(1); + try { + const cleaning = withResolvers(); + counts.cleanup = function* () { + cleaning.resolve(); + yield* release.operation; + }; + const held = yield* usePluginProgram({ plugins: [contributedPlugin(counts)], gate }); + held.host.fake.script({ reply: '' }); + held.host.fake.script({ reply: "joined" }); + const sending = yield* spawn(() => held.root.owner.message("Read the contributed value")); + yield* intent.started(); + expect(counts.calls).toEqual([]); + expect(held.host.fake.prompts).toHaveLength(1); + intent.release(); + yield* cleaning.operation; + expect(counts.calls).toEqual(["read"]); + expect(held.host.fake.prompts).toHaveLength(1); + const execution = yield* held.host.repository.open(held.root.execution); + expect((yield* records(execution)).filter((one) => one.kind === "control-outcome")).toEqual( + [], + ); + release.resolve(); + yield* outcome.started(); + expect(held.host.fake.prompts).toHaveLength(1); + outcome.release(); + expect((yield* sending).ok).toBe(true); + expect(held.host.fake.prompts[1]).toContain('"count": 1'); + expect( + (yield* records(yield* held.host.repository.open(held.root.execution))).filter( + (one) => one.kind === "control-outcome", + ), + ).toHaveLength(1); + } finally { + intent.release(); + release.resolve(); + outcome.release(); + } }); it("R4g: actual cancellation leaves only acknowledged intent after joined cleanup", function* () { diff --git a/packages/cli/tests/repl-sidekick-presentation.test.ts b/packages/cli/tests/repl-sidekick-presentation.test.ts index c9b00bbc9..84f66d28f 100644 --- a/packages/cli/tests/repl-sidekick-presentation.test.ts +++ b/packages/cli/tests/repl-sidekick-presentation.test.ts @@ -33,7 +33,8 @@ import type { SidekickRecord } from "../src/repl/sidekick/history.ts"; import { awaitedFact } from "./support/mounted-repl.ts"; import { settledReading } from "./support/mounted-history.ts"; import type { ReplPage, ScreenReading } from "./support/repl-page.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import type { Operation } from "effection"; import { expect } from "@executablemd/test-support/expect"; @@ -71,6 +72,8 @@ import { typed, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-presentation.test.ts"; + const WIDE = { columns: 160, rows: 36 }; const NARROW = { columns: 72, rows: 20 }; @@ -143,6 +146,7 @@ function* focusMessage(page: ReplPage): Operation { } describe("987 — mounted original recovery", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of [WIDE, { columns: 120, rows: 30 }, NARROW]) { it(`reads actual saved multiline entry feedback by keyboard at ${size.columns} columns`, function* () { const page = yield* useReplPage({ size: WIDE }); @@ -299,6 +303,7 @@ describe("987 — mounted original recovery", () => { }); describe("Sidekick presentation: visible work owns its controls", () => { + beforeEach(journalBeforeEach(OWNER)); it("sends one message through the Sidekick pane and reads the reply", function* () { const page = yield* useReplPage({ size: WIDE }); page.repl.fake.script({ reply: "Noted.\n" }); @@ -383,6 +388,7 @@ function* exchange(page: ReplPage, text: string, answer: string): Operation { + beforeEach(journalBeforeEach(OWNER)); it("CF1: a message with its own lines keeps every one of them when the next arrives", function* () { const page = yield* useReplPage({ size: WIDE }); const wide = "a-very-long-line-that-cannot-fit-this-pane-and-must-be-cut-across-rows"; @@ -531,6 +537,7 @@ function sendComposed(page: ReplPage): Operation { } describe("Sidekick acquisition, durable handoff and acknowledgements", () => { + beforeEach(journalBeforeEach(OWNER)); it("M1: a fresh command shows its Sidekick, asks the agent nothing, and focuses Message", function* () { const page = yield* useReplPage({ size: WIDE }); const first = page.screen(); @@ -596,63 +603,72 @@ describe("Sidekick acquisition, durable handoff and acknowledgements", () => { { at: "max" }, ); const finishing = gate.holdNext((path, record) => path === pair.sidekick && record === "\n"); - const page = yield* useReplPage({ host, location: `xmd://repl/${execution}/entries` }); - const running = gate.holdNext((path) => path === legacy && gate.reaching(legacy) >= 1); - yield* pasteDraft(page, TWO_STEP_ENTRY); - yield* page.key("Tab"); - yield* page.until("Round Send focused", (one) => one.shows("> Send")); - yield* page.key("Enter"); - yield* running.started(); - yield* page.until("the admitted source leaving the draft", (one) => !draftOpen(one)); - yield* compose(page, "explain"); - yield* sendComposed(page); - yield* sleep(100); - expect(host.fake.ensured).toEqual([]); - expect(host.fake.prompts).toEqual([]); - expect(running.released).toBe(false); - expect(yield* publishedPairs(host.root)).toEqual([]); - yield* compose(page, "!"); - expect(composerHolds(page.screen(), "!")).toBe(true); - yield* draftText(page, "next"); - running.release(); - yield* page.until("the reply arriving", (one) => one.shows("Noted.")); - yield* finishing.started(); - expect(sidekickIdle(page.screen())).toBe(false); - let refusal: unknown; try { - yield* readSidekickRecords(pair.sidekick); - } catch (caught) { - refusal = caught; + const page = yield* useReplPage({ host, location: `xmd://repl/${execution}/entries` }); + const running = gate.holdNext((path) => path === legacy && gate.reaching(legacy) >= 1); + try { + yield* pasteDraft(page, TWO_STEP_ENTRY); + yield* page.key("Tab"); + yield* page.until("Round Send focused", (one) => one.shows("> Send")); + yield* page.key("Enter"); + yield* running.started(); + yield* page.until("the admitted source leaving the draft", (one) => !draftOpen(one)); + yield* compose(page, "explain"); + yield* sendComposed(page); + yield* sleep(100); + expect(host.fake.ensured).toEqual([]); + expect(host.fake.prompts).toEqual([]); + expect(running.released).toBe(false); + expect(yield* publishedPairs(host.root)).toEqual([]); + yield* compose(page, "!"); + expect(composerHolds(page.screen(), "!")).toBe(true); + yield* draftText(page, "next"); + running.release(); + yield* page.until("the reply arriving", (one) => one.shows("Noted.")); + yield* finishing.started(); + expect(sidekickIdle(page.screen())).toBe(false); + let refusal: unknown; + try { + yield* readSidekickRecords(pair.sidekick); + } catch (caught) { + refusal = caught; + } + expect(refusal).toBeInstanceOf(SidekickHistoryError); + expect(refusal).toMatchObject({ + message: + "this execution's chat history ends in a record that was never finished writing.", + }); + finishing.release(); + yield* page.until("the Sidekick finishing its saved reply", sidekickIdle); + yield* entrySettles(page, 1, "ok"); + expect(yield* publishedPairs(host.root)).toEqual([execution]); + const retained = yield* readTextFile(legacy); + const records = retained.split("\n").filter((line) => line.length > 0); + expect(records.length).toBeGreaterThan(1); + expect((yield* readTextFile(pair.entries)).startsWith(retained)).toBe(true); + expect((yield* host.repository.open(execution)).chat.form).toBe("paired"); + expect((yield* readSidekickRecords(pair.sidekick))[0]).toMatchObject({ + kind: "owner", + execution, + origin: { bytes: new TextEncoder().encode(retained).length, records: records.length }, + }); + expect(host.fake.prompts).toHaveLength(1); + expect(host.fake.ensured).toHaveLength(1); + expect(host.fake.prompts[0]).toContain("explain"); + expect(host.fake.prompts[0]).not.toContain("explain!"); + expect(personMessages(yield* readSidekickRecords(pair.sidekick))).toEqual(["explain"]); + expect(page.screen().shows("[U] explain")).toBe(true); + const reachedLegacy = gate.reaching(legacy); + yield* awaited("the next record reaching the pair", () => gate.reaching(pair.entries) > 0); + expect(gate.reaching(legacy)).toBe(reachedLegacy); + expect(yield* readTextFile(legacy)).toBe(retained); + expect(yield* finishDraft(page)).toBe("next"); + } finally { + running.release(); + } + } finally { + finishing.release(); } - expect(refusal).toBeInstanceOf(SidekickHistoryError); - expect(refusal).toMatchObject({ - message: "this execution's chat history ends in a record that was never finished writing.", - }); - finishing.release(); - yield* page.until("the Sidekick finishing its saved reply", sidekickIdle); - yield* entrySettles(page, 1, "ok"); - expect(yield* publishedPairs(host.root)).toEqual([execution]); - const retained = yield* readTextFile(legacy); - const records = retained.split("\n").filter((line) => line.length > 0); - expect(records.length).toBeGreaterThan(1); - expect((yield* readTextFile(pair.entries)).startsWith(retained)).toBe(true); - expect((yield* host.repository.open(execution)).chat.form).toBe("paired"); - expect((yield* readSidekickRecords(pair.sidekick))[0]).toMatchObject({ - kind: "owner", - execution, - origin: { bytes: new TextEncoder().encode(retained).length, records: records.length }, - }); - expect(host.fake.prompts).toHaveLength(1); - expect(host.fake.ensured).toHaveLength(1); - expect(host.fake.prompts[0]).toContain("explain"); - expect(host.fake.prompts[0]).not.toContain("explain!"); - expect(personMessages(yield* readSidekickRecords(pair.sidekick))).toEqual(["explain"]); - expect(page.screen().shows("[U] explain")).toBe(true); - const reachedLegacy = gate.reaching(legacy); - yield* awaited("the next record reaching the pair", () => gate.reaching(pair.entries) > 0); - expect(gate.reaching(legacy)).toBe(reachedLegacy); - expect(yield* readTextFile(legacy)).toBe(retained); - expect(yield* finishDraft(page)).toBe("next"); }); it("M4: acceptance clears Message while delayed saved acknowledgement preserves newer edits", function* () { @@ -664,20 +680,24 @@ describe("Sidekick acquisition, durable handoff and acknowledgements", () => { const saving = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"kind":"message"'), ); - yield* compose(page, "ask"); - yield* sendComposed(page); - yield* saving.started(); - yield* compose(page, "!"); - yield* draftText(page, "X"); - saving.release(); - yield* page.until("the reply arriving", (one) => one.shows("Understood.")); - expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual(["ask"]); - expect(page.repl.fake.prompts[0]).toContain("ask"); - expect(page.repl.fake.prompts[0]).not.toContain("ask!"); - expect(composerHolds(page.screen(), "!")).toBe(true); - expect(draftHolds(page.screen(), "mineX")).toBe(true); - expect(page.repl.fake.prompts[1] ?? "").toContain("taken the shared draft over"); - expect(yield* finishDraft(page)).toBe("mineX"); + try { + yield* compose(page, "ask"); + yield* sendComposed(page); + yield* saving.started(); + yield* compose(page, "!"); + yield* draftText(page, "X"); + saving.release(); + yield* page.until("the reply arriving", (one) => one.shows("Understood.")); + expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual(["ask"]); + expect(page.repl.fake.prompts[0]).toContain("ask"); + expect(page.repl.fake.prompts[0]).not.toContain("ask!"); + expect(composerHolds(page.screen(), "!")).toBe(true); + expect(draftHolds(page.screen(), "mineX")).toBe(true); + expect(page.repl.fake.prompts[1] ?? "").toContain("taken the shared draft over"); + expect(yield* finishDraft(page)).toBe("mineX"); + } finally { + saving.release(); + } }); it("M4: control — with nothing typed after it, the same message clears the box", function* () { @@ -689,15 +709,19 @@ describe("Sidekick acquisition, durable handoff and acknowledgements", () => { const saving = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"kind":"message"'), ); - yield* compose(page, "ask"); - yield* sendComposed(page); - yield* saving.started(); - saving.release(); - yield* page.until("the reply arriving", (one) => one.shows("Understood.")); - expect(composerHolds(page.screen(), "ask")).toBe(false); - expect(page.repl.fake.prompts[1] ?? "").toContain("Entry input updated."); - expect(page.repl.fake.prompts[1] ?? "").not.toContain("taken the shared draft over"); - expect(page.screen().found("Replaced by the reply.", DRAFT_VALUE)).toBe(1); + try { + yield* compose(page, "ask"); + yield* sendComposed(page); + yield* saving.started(); + saving.release(); + yield* page.until("the reply arriving", (one) => one.shows("Understood.")); + expect(composerHolds(page.screen(), "ask")).toBe(false); + expect(page.repl.fake.prompts[1] ?? "").toContain("Entry input updated."); + expect(page.repl.fake.prompts[1] ?? "").not.toContain("taken the shared draft over"); + expect(page.screen().found("Replaced by the reply.", DRAFT_VALUE)).toBe(1); + } finally { + saving.release(); + } }); it("M5: while generation is held, Send remains beside Stop without starting unrequested work", function* () { @@ -771,6 +795,7 @@ function entryTrail(reading: ScreenReading): string { } describe("Sidekick texts and reading across every profile", () => { + beforeEach(journalBeforeEach(OWNER)); it("M7: all three profiles keep both texts, the footer and one body", function* () { const page = yield* useReplPage(); yield* draftText(page, "note"); @@ -938,6 +963,7 @@ function* submittedUnderEdit( } describe("Sidekick submission held to the current Draft", () => { + beforeEach(journalBeforeEach(OWNER)); it("M-P2: a Draft edit during preflight admits no stale entry, and the edit survives", function* () { const result = yield* submittedUnderEdit(true); expect(result.entries).toEqual([]); @@ -1021,6 +1047,7 @@ function* filledQuestion(): Operation { } describe("Sidekick question announcement and modal ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("MQ1: the notice arrives with nothing pressed, and only opening shows the form", function* () { const gate = appendGate(); const page = yield* useReplPage({ gate }); @@ -1029,44 +1056,48 @@ describe("Sidekick question announcement and modal ownership", () => { const filing = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"component":"Elicit"'), ); - yield* pasteDraft(page, TWO_STEP_ENTRY); - yield* page.key("Tab"); - yield* page.until("Round Send focused", (one) => one.shows("> Send")); - yield* page.key("Enter"); - yield* entrySettles(page, 1, "ok"); - yield* chooseEntry(page, "entry-1"); - yield* sendMessage(page, "review it"); - yield* filing.started(); - yield* selectPane(page, "bindings"); - yield* draftText(page, "mine"); - const fed = page.repl.terminal.fed; - filing.release(); - yield* page.until("the question announcing without input", (one) => - one.shows("SIDEKICK (question)"), - ); - expect(page.repl.terminal.fed).toBe(fed); - expect(page.screen().shows(COMPOSER)).toBe(false); - expect(page.screen().shows("[submit]")).toBe(false); - yield* page.type("-still-draft"); - yield* page.until( - "the original input still receiving text", - (one) => one.found("mine-still-draft", DRAFT_VALUE) === 1, - ); - yield* page.key("Ctrl+G"); - yield* page.type("3"); - yield* page.until("the selected entry", (one) => entryTrail(one).includes("Entry 1")); - expect(entryTrail(page.screen())).toContain("Entry 1"); - yield* intoDraft(page); - expect(draftShows(page.screen(), "mine-still-draft")).toBe(true); - yield* selectPane(page, "sidekick"); - yield* page.until("the notice in its pane", (one) => one.shows("[answer sidekick]")); - expect(page.screen().shows("[submit]")).toBe(false); - expect(composerHolds(page.screen(), "review it")).toBe(false); - yield* openedQuestion(page); - expect(page.screen().shows("Approve the plan?")).toBe(true); - expect(page.screen().shows("approve")).toBe(true); - expect(page.screen().shows("reject")).toBe(true); - expect(yield* finishDraft(page)).toBe("mine-still-draft"); + try { + yield* pasteDraft(page, TWO_STEP_ENTRY); + yield* page.key("Tab"); + yield* page.until("Round Send focused", (one) => one.shows("> Send")); + yield* page.key("Enter"); + yield* entrySettles(page, 1, "ok"); + yield* chooseEntry(page, "entry-1"); + yield* sendMessage(page, "review it"); + yield* filing.started(); + yield* selectPane(page, "bindings"); + yield* draftText(page, "mine"); + const fed = page.repl.terminal.fed; + filing.release(); + yield* page.until("the question announcing without input", (one) => + one.shows("SIDEKICK (question)"), + ); + expect(page.repl.terminal.fed).toBe(fed); + expect(page.screen().shows(COMPOSER)).toBe(false); + expect(page.screen().shows("[submit]")).toBe(false); + yield* page.type("-still-draft"); + yield* page.until( + "the original input still receiving text", + (one) => one.found("mine-still-draft", DRAFT_VALUE) === 1, + ); + yield* page.key("Ctrl+G"); + yield* page.type("3"); + yield* page.until("the selected entry", (one) => entryTrail(one).includes("Entry 1")); + expect(entryTrail(page.screen())).toContain("Entry 1"); + yield* intoDraft(page); + expect(draftShows(page.screen(), "mine-still-draft")).toBe(true); + yield* selectPane(page, "sidekick"); + yield* page.until("the notice in its pane", (one) => one.shows("[answer sidekick]")); + expect(page.screen().shows("[submit]")).toBe(false); + expect(composerHolds(page.screen(), "review it")).toBe(false); + yield* openedQuestion(page); + expect(page.screen().shows("Approve the plan?")).toBe(true); + expect(page.screen().shows("approve")).toBe(true); + expect(page.screen().shows("reject")).toBe(true); + expect(yield* finishDraft(page)).toBe("mine-still-draft"); + } finally { + filing.release(); + } }); it("MQ1: control — an ordinary entry's question announces itself the same way", function* () { @@ -1110,6 +1141,7 @@ function* configured(page: ReplPage): Operation { } describe("PV3/PV4: question and Configure editing", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps each value's middle caret across close and a held History drawer", function* () { const page = yield* useReplPage(); page.repl.fake.configuration(ADVERTISED); @@ -1170,6 +1202,7 @@ describe("PV3/PV4: question and Configure editing", () => { }); describe("Configure keyboard, retained values and window ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("CFG6: local arrows reach Configure choices, and Close or Escape return to its opener", function* () { const page = yield* useReplPage(); page.repl.fake.configuration(ADVERTISED); @@ -1403,6 +1436,7 @@ function* backToCurrent(page: ReplPage, reply = "Newer answer."): Operation { + beforeEach(journalBeforeEach(OWNER)); it("SS1: both sections hold their own work, settled in the order each finishes", function* () { const page = yield* useReplPage(); page.repl.fake.script({ held: true, reply: "ENTRY-DONE" }); @@ -1674,6 +1708,7 @@ function* questionThroughKeyboard(explicit: boolean): Operation { } describe("Sidekick resize ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("Q-P1: a form hidden by a resize does not consume Draft typing", function* () { const page = yield* questionThroughKeyboard(false); const narrow = yield* page.resize(NARROW); @@ -1763,6 +1798,7 @@ function atSize(page: ReplPage, size: { columns: number; rows: number }): Operat } describe("Sidekick drawers across every supported size", () => { + beforeEach(journalBeforeEach(OWNER)); it("MQ4: the form stays inside its own pane at every size, and survives a refusal", function* () { const page = yield* useReplPage(); yield* draftText(page, "mine"); @@ -1907,6 +1943,7 @@ function* refusedLocation(host: MountedHost, location: string): Operation { + beforeEach(journalBeforeEach(OWNER)); it("SS2: a current failure read beside an older chat leaves its items alone", function* () { const page = yield* useReplPage(); yield* twoChats(page, true); @@ -2240,6 +2277,7 @@ function* appendBoundary(stopped: boolean): Operation { } describe("Sidekick original provider membership and cancelled append", () => { + beforeEach(journalBeforeEach(OWNER)); it("SS3: Stop before the canonical append leaves the key local and nothing saved", function* () { yield* appendBoundary(true); }); @@ -2290,21 +2328,25 @@ describe("Sidekick original provider membership and cancelled append", () => { const hold = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes("agent_prompt"), ); - yield* compose(page, "say it"); - yield* sendComposed(page); - yield* hold.started(); - const choices = yield* conversationChoices(page); - expect(choices).toHaveLength(1); - yield* filterChoice(page, choices[0]); - const standing = selectedFilter(page.screen()); - expect(standing).toBeDefined(); - expect(transcriptHas(page.screen(), "say it")).toBe(true); - expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual(["say it"]); - hold.release(); - yield* stopSidekick(page); - yield* page.until("idle after the saved append", sidekickIdle); - expect(selectedFilter(page.screen())).toBe(standing); - expect(page.screen().shows("xmd:v1:")).toBe(true); + try { + yield* compose(page, "say it"); + yield* sendComposed(page); + yield* hold.started(); + const choices = yield* conversationChoices(page); + expect(choices).toHaveLength(1); + yield* filterChoice(page, choices[0]); + const standing = selectedFilter(page.screen()); + expect(standing).toBeDefined(); + expect(transcriptHas(page.screen(), "say it")).toBe(true); + expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual(["say it"]); + hold.release(); + yield* stopSidekick(page); + yield* page.until("idle after the saved append", sidekickIdle); + expect(selectedFilter(page.screen())).toBe(standing); + expect(page.screen().shows("xmd:v1:")).toBe(true); + } finally { + hold.release(); + } }); it("SS3: a Sidekick key is selectable at an entry checkpoint that precedes it", function* () { @@ -2400,6 +2442,7 @@ function* populateChat(page: ReplPage, count: number, prefix = "SAID"): Operatio } describe("Sidekick original multiline composer ownership", () => { + beforeEach(journalBeforeEach(OWNER)); it("MC5: the value wraps into rows of its own, and the chat gives them room", function* () { const page = yield* useReplPage(); yield* populateChat(page, 10); @@ -2443,24 +2486,28 @@ describe("Sidekick original multiline composer ownership", () => { const hold = gate.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"kind":"message"'), ); - yield* sendComposed(page); - yield* hold.started(); - yield* composerPaste(page, "NEWER-1\nNEWER-2\nNEWER-3"); - const newer = composerRows( - page.screen(), - page.screen().shows("NEWER-3") ? "NEWER-3" : "while busy", - ); - expect(newer.length).toBeGreaterThan(1); - hold.release(); - yield* page.until("the acknowledged multiline message", (one) => chatHas(one, "Understood.")); - expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual([text]); - expect(page.repl.fake.prompts).toHaveLength(1); - expect(page.repl.fake.prompts[0]).toContain("LINE-1"); - expect(page.repl.fake.prompts[0]).toContain("LINE-9"); - expect(page.repl.fake.prompts[0]).not.toContain("NEWER-1"); - expect( - composerRows(page.screen(), page.screen().shows("NEWER-3") ? "NEWER-3" : "while busy"), - ).toEqual(newer); + try { + yield* sendComposed(page); + yield* hold.started(); + yield* composerPaste(page, "NEWER-1\nNEWER-2\nNEWER-3"); + const newer = composerRows( + page.screen(), + page.screen().shows("NEWER-3") ? "NEWER-3" : "while busy", + ); + expect(newer.length).toBeGreaterThan(1); + hold.release(); + yield* page.until("the acknowledged multiline message", (one) => chatHas(one, "Understood.")); + expect(personMessages((yield* settledReading(page.repl)).chat)).toEqual([text]); + expect(page.repl.fake.prompts).toHaveLength(1); + expect(page.repl.fake.prompts[0]).toContain("LINE-1"); + expect(page.repl.fake.prompts[0]).toContain("LINE-9"); + expect(page.repl.fake.prompts[0]).not.toContain("NEWER-1"); + expect( + composerRows(page.screen(), page.screen().shows("NEWER-3") ? "NEWER-3" : "while busy"), + ).toEqual(newer); + } finally { + hold.release(); + } }); it("MC6: control — an acknowledged Send leaves three blank value rows", function* () { @@ -2629,6 +2676,7 @@ function* historicalSubmit(historical: boolean, failed: boolean): Operation { + beforeEach(journalBeforeEach(OWNER)); for (const arm of [ { name: "opened at the first entry", historical: true }, { name: "control: opened at the head", historical: false }, @@ -2648,35 +2696,41 @@ describe("Sidekick original acknowledged history submission identity", () => { const hold = gate.holdNext( (path, record) => path.endsWith(ENTRIES_FILE) && record.includes('"type":"close"'), ); - page.repl.fake.script({ reply: submitting(HI_FAILING) }); - page.repl.fake.script({ reply: "Noted.\n" }); - yield* compose(page, "run one that fails"); - yield* sendComposed(page); - yield* hold.started(); - yield* freezeFirst(page); - yield* closeDrawer(page); - hold.release(); - yield* page.until("the failure's followup", (one) => sidekickShows(one, "Noted.")); - expect(page.screen().shows("[live]")).toBe(true); - const read = yield* settledReading(page.repl); - expect(read.model.entries.map((one) => one.key)).toEqual(["entry-1", "entry-2", "entry-3"]); - expect(read.model.entries[2]?.terminal?.status).toBe("err"); - expect(submitIntent(read.chat).entry).toBe("entry-3"); - const feedback = read.chat - .flatMap((one) => (one.kind === "feedback" ? [one.text] : [])) - .join("\n"); - expect(feedback).toContain("Entry entry-3 failed."); - expect(feedback).toContain("Inspect its saved evidence with ."); - expect(feedback).not.toContain("entry={1}"); - expect(feedback).not.toContain("entry={2}"); - expect( - renderReceipt({ - entry: "entry-3", - status: "failed", - failure: "the third entry failed", - read: { entry: "entry-3" }, - }), - ).toContain("Inspect its saved evidence with ."); + try { + page.repl.fake.script({ reply: submitting(HI_FAILING) }); + page.repl.fake.script({ reply: "Noted.\n" }); + yield* compose(page, "run one that fails"); + yield* sendComposed(page); + yield* hold.started(); + yield* freezeFirst(page); + yield* closeDrawer(page); + hold.release(); + yield* page.until("the failure's followup", (one) => sidekickShows(one, "Noted.")); + expect(page.screen().shows("[live]")).toBe(true); + const read = yield* settledReading(page.repl); + expect(read.model.entries.map((one) => one.key)).toEqual(["entry-1", "entry-2", "entry-3"]); + expect(read.model.entries[2]?.terminal?.status).toBe("err"); + expect(submitIntent(read.chat).entry).toBe("entry-3"); + const feedback = read.chat + .flatMap((one) => (one.kind === "feedback" ? [one.text] : [])) + .join("\n"); + expect(feedback).toContain("Entry entry-3 failed."); + expect(feedback).toContain( + "Inspect its saved evidence with .", + ); + expect(feedback).not.toContain("entry={1}"); + expect(feedback).not.toContain("entry={2}"); + expect( + renderReceipt({ + entry: "entry-3", + status: "failed", + failure: "the third entry failed", + read: { entry: "entry-3" }, + }), + ).toContain("Inspect its saved evidence with ."); + } finally { + hold.release(); + } }); it("HI3: frozen, Run establishes nothing; live, it admits the next entry", function* () { const dataRoot = yield* useTemporary("xmd-hi-person-"); @@ -2787,6 +2841,7 @@ function* twoOverflowingChats(page: ReplPage): Operation { } describe("Sidekick original independent readings and streaming rows", () => { + beforeEach(journalBeforeEach(OWNER)); it("CF-P1: scrolling an older chat leaves the current chat's own reading alone", function* () { const page = yield* useReplPage(); yield* twoOverflowingChats(page); @@ -2903,6 +2958,7 @@ describe("Sidekick original independent readings and streaming rows", () => { }); describe("Sidekick original interrupted identities and native input routes", () => { + beforeEach(journalBeforeEach(OWNER)); it("SS6: an interrupted first message leaves every later row its own identity", function* () { const host = yield* useMountedHost(); const first = yield* useReplPage({ host }); @@ -2949,14 +3005,16 @@ describe("Sidekick original interrupted identities and native input routes", () it("SS6: a real automatic turn nobody answered opens as its own inert anchor", function* () { const dataRoot = yield* useTemporary("xmd-ss6-inert-"); - const gate = appendGate(); + // Held as an operation, so closing the host takes the response back rather + // than leaving a write for the host's teardown to wait on. + const operations = operationGate(); const execution = yield* scoped(function* () { - const host = yield* useMountedHost({ dataRoot, gate }); + const host = yield* useMountedHost({ dataRoot, operations }); const page = yield* useReplPage({ host }); page.repl.fake.script({ reply: "First answer.\n\n" }); page.repl.fake.script({ reply: "\n" }); let seen = 0; - const held = gate.holdNext( + const held = operations.holdNext( (path, record) => path.endsWith(SIDEKICK_FILE) && record.includes('"kind":"response"') && ++seen === 2, ); @@ -3116,6 +3174,7 @@ function* readSilentAndSpoken(page: ReplPage): Operation { } describe("Sidekick original reveal and cold decision coverage", () => { + beforeEach(journalBeforeEach(OWNER)); it("SS4: a turn past the chat's window is revealed, and this screen keeps its own", function* () { const page = yield* useReplPage(); page.repl.fake.configuration(ADVERTISED); @@ -3236,6 +3295,7 @@ describe("Sidekick original reveal and cold decision coverage", () => { }); describe("Sidekick original populated chat profiles", () => { + beforeEach(journalBeforeEach(OWNER)); it("SS7: three profiles keep a populated older reading, its window and the way home", function* () { const page = yield* useReplPage(); page.repl.fake.configuration(ADVERTISED); @@ -3300,6 +3360,7 @@ describe("Sidekick original populated chat profiles", () => { }); describe("Sidekick original independent body controls", () => { + beforeEach(journalBeforeEach(OWNER)); it("BP3: both bodies stay usable through their own controls across resize", function* () { const page = yield* useReplPage(); page.repl.fake.script({ reply: "ENTRY-REPLY" }); @@ -3347,6 +3408,7 @@ describe("Sidekick original independent body controls", () => { }); describe("Follow: the running command owns the mounted control", () => { + beforeEach(journalBeforeEach(OWNER)); for (const size of PROFILES) { it(`Follow: keyboard and pointer at ${size.columns}x${size.rows} retain the live setting`, function* () { const page = yield* useReplPage(); @@ -3410,6 +3472,7 @@ describe("Follow: the running command owns the mounted control", () => { }); describe("1137 — recovery stays among the fixed conversation controls", () => { + beforeEach(journalBeforeEach(OWNER)); const LONG = Array.from( { length: 60 }, (_, at) => `LONG${String(at + 1).padStart(2, "0")} retained reply row`, @@ -3518,6 +3581,7 @@ describe("1137 — recovery stays among the fixed conversation controls", () => }); describe("Retained Sidekick token usage", () => { + beforeEach(journalBeforeEach(OWNER)); const USAGE_OFF = "[ ] Show token usage"; const USAGE_ON = "[x] Show token usage"; diff --git a/packages/cli/tests/repl-sidekick-recovery.test.ts b/packages/cli/tests/repl-sidekick-recovery.test.ts index d714df5b8..bebafc172 100644 --- a/packages/cli/tests/repl-sidekick-recovery.test.ts +++ b/packages/cli/tests/repl-sidekick-recovery.test.ts @@ -39,7 +39,8 @@ import { pairedLocation } from "../src/repl/sidekick/history.ts"; import { useHarness } from "./fixtures/repl/issue-883/sidekick-harness.ts"; import { useTemporary } from "./fixtures/repl/issue-883/sidekick-harness.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -142,6 +143,8 @@ import { initialState } from "../src/repl/application.ts"; import { projectRepl } from "../src/repl/model.ts"; import type { ReplEntry } from "../src/repl/model.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-recovery.test.ts"; + const CHAT = "chat-1"; const AGENT = "scribe"; @@ -2693,6 +2696,7 @@ describe("Tier SS — what a saved Sidekick turn establishes about itself", () = * with a list this file chose. */ describe("Tier HI — a reopening reconciles against the acknowledged history", () => { + beforeEach(journalBeforeEach(OWNER)); const FIRST = "First prior.\n"; const SECOND = "Second prior.\n"; /** What the next ordinary entry says, distinct from the reserved source. */ @@ -3219,6 +3223,7 @@ describe("Tier IN5 — a saved EntryOutput result keeps its own renderer", () => }); describe("975 — placement survives cold Submit reconciliation", () => { + beforeEach(journalBeforeEach(OWNER)); for (const marked of [true, false]) { it(`975: ${marked ? "legacy workspace-marked" : "project-placed"} entry resumes in its owned directory`, function* () { const project = yield* useTemporary("xmd-placement-project-"); @@ -3810,6 +3815,7 @@ describe("987 — joined recovery before canonical feedback publication", () => }); describe("987 — actual child reference recording faults", () => { + beforeEach(journalBeforeEach(OWNER)); for (const cut of ["offered", "acknowledged", "activation", "activation-uncertain"]) { it(`sends nothing and retains fatal recording precedence at ${cut}`, function* () { const failure = new Error(`Reference recording failure: ${cut}`); @@ -4065,6 +4071,7 @@ describe("987 — exact missing original and deliberate fallback", () => { }); describe("987 — root whole-set reconciliation", () => { + beforeEach(journalBeforeEach(OWNER)); for (const interrupted of [false, true]) { it(`reconciles the acknowledged head while inspecting older History${interrupted ? " across the first outcome cut" : ""}`, function* () { const host = yield* useMountedHost(); @@ -4923,6 +4930,7 @@ describe("1183 — the exact live feedback request is the only exception", () => }); describe("resume retention and mounted retained recovery corrections", () => { + beforeEach(journalBeforeEach(OWNER)); const savedText = "Continue the exact saved instruction."; const oldText = "Original chat remains readable."; const entryText = "An established entry remains readable."; @@ -5208,6 +5216,7 @@ describe("resume retention and mounted retained recovery corrections", () => { }); describe("1311 — a completed reply that secret detection withholds", () => { + beforeEach(journalBeforeEach(OWNER)); const refused = 'authorization: "Use a separate approval for this example issue #34"'; function showsWithheldReply(screen: ScreenReading): boolean { diff --git a/packages/cli/tests/repl-sidekick-testing.test.ts b/packages/cli/tests/repl-sidekick-testing.test.ts index e9b1bfb34..2815cc240 100644 --- a/packages/cli/tests/repl-sidekick-testing.test.ts +++ b/packages/cli/tests/repl-sidekick-testing.test.ts @@ -4,7 +4,8 @@ import { planComponentDescription } from "../src/plan-component.ts"; import { BUNDLED_PLUGIN } from "../src/run-profile.ts"; import { DurablePersistenceError } from "@executablemd/durable-streams"; import { submitForSidekick } from "../src/repl/sidekick/admission.ts"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { useComponentModuleLoader } from "@executablemd/test-support/host"; import { ensureDir, exists, readTextFile, rm, writeTextFile } from "@effectionx/fs"; @@ -61,6 +62,8 @@ import { stopSidekick, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-testing.test.ts"; + const reportSchema = z .object({ path: z.string(), @@ -149,6 +152,7 @@ function passing(name = "real assertion", expected = "yes"): string { } describe("REPL.Test accepted journeys", () => { + beforeEach(journalBeforeEach(OWNER)); it("R1: authors, fails, fixes and reuses ordinary Markdown without executing its creation", function* () { const { page, repl, workspace } = yield* mounted(); const chapter = yield* readGuideChapter("Entries"); @@ -322,6 +326,7 @@ describe("REPL.Test accepted journeys", () => { }); describe("REPL.Test selection, display and isolation", () => { + beforeEach(journalBeforeEach(OWNER)); it("R4: preserves configured selection, immutable declarations, document isolation and explicit display", function* () { const configured = yield* useTemporary("xmd-testing-includes-"); yield* writeTextFile(join(configured, "Greeting.md"), "configured greeting"); @@ -465,6 +470,7 @@ function* holdModule( } describe("REPL.Test admission and joined lifetime", () => { + beforeEach(journalBeforeEach(OWNER)); it("R5: refuses both submitters and a second test throughout response cancellation and gated cleanup", function* () { yield* useHostFiles(); yield* useComponentModuleLoader(); @@ -669,6 +675,7 @@ describe("REPL.Test admission and joined lifetime", () => { }); describe("REPL.Test retained and fatal outcomes", () => { + beforeEach(journalBeforeEach(OWNER)); it("R6: reopen inspection keeps completed reports inert and unmatched work unknown until a new explicit request", function* () { yield* useComponentModuleLoader(); const gate = appendGate(); @@ -890,6 +897,7 @@ describe("REPL.Test retained and fatal outcomes", () => { }); describe("1113: session tests use bounded fixtures", () => { + beforeEach(journalBeforeEach(OWNER)); it("1113: keeps test cwd at S and permits components fixtures while refusing private session bytes", function* () { yield* useComponentModuleLoader(); const host = yield* useMountedHost({ diff --git a/packages/cli/tests/repl-sidekick-typing.test.ts b/packages/cli/tests/repl-sidekick-typing.test.ts index f36947baa..a47d7735b 100644 --- a/packages/cli/tests/repl-sidekick-typing.test.ts +++ b/packages/cli/tests/repl-sidekick-typing.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { scoped } from "effection"; import type { Operation } from "effection"; @@ -41,9 +42,12 @@ import { settledReading } from "./support/mounted-history.ts"; import { useReplPage } from "./support/repl-page.ts"; import { generateTypingHistory, typingView } from "./support/typing-history.ts"; +const OWNER = "packages/cli/tests/repl-sidekick-typing.test.ts"; + const WIDE = { columns: 160, rows: 36 }; describe("1048 — prepare only admitted chat descriptions", () => { + beforeEach(journalBeforeEach(OWNER)); it("constructs the admitted range over all passes independently of off-screen history", function* () { const counts: number[] = []; for (const rounds of [2, 12]) { @@ -115,6 +119,7 @@ describe("1048 — prepare only admitted chat descriptions", () => { }); describe("1048 — selected chat preparation", () => { + beforeEach(journalBeforeEach(OWNER)); it("matches fresh preparation after changed source facts and keeps one geometry", function* () { const page = yield* useReplPage({ size: WIDE }); const read = yield* generateTypingHistory(page, 2, 32); @@ -266,6 +271,7 @@ describe("1048 — selected chat preparation", () => { }); describe("1048 — generated retained output", () => { + beforeEach(journalBeforeEach(OWNER)); it("reads early, middle and tail output after resizing without consuming either draft", function* () { const page = yield* useReplPage({ size: WIDE }); const read = yield* generateTypingHistory(page, 2, 32, true); @@ -380,6 +386,7 @@ describe("1048 — generated retained output", () => { }); describe("1048 — reuse Transcript facts", () => { + beforeEach(journalBeforeEach(OWNER)); it("invalidates consumed source facts while retaining only the current sequence", function* () { const page = yield* useReplPage({ size: WIDE }); const read = yield* generateTypingHistory(page, 2, 32); @@ -639,6 +646,7 @@ describe("1048 — reuse Transcript facts", () => { * again — which a count of renders or a warm machine could not show. */ describe("1342 — formatted bodies are kept for the frames that ask again", () => { + beforeEach(journalBeforeEach(OWNER)); function spied() { const real = createMarkdownStore(); const answers: { readonly source: string; readonly lines: readonly ReplMarkdownLine[] }[] = []; diff --git a/packages/cli/tests/repl-task-tabs.test.ts b/packages/cli/tests/repl-task-tabs.test.ts index eddf4b6f5..82c430520 100644 --- a/packages/cli/tests/repl-task-tabs.test.ts +++ b/packages/cli/tests/repl-task-tabs.test.ts @@ -1,5 +1,6 @@ import { sleep } from "effection"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { writeTextFile } from "@effectionx/fs"; import { useReplPage } from "./support/repl-page.ts"; @@ -16,6 +17,8 @@ import { awaitedFact } from "./support/mounted-repl.ts"; import { pairedLocation } from "../src/repl/sidekick/history.ts"; import { REPL_PALETTE } from "../src/repl/presentation-style.ts"; +const OWNER = "packages/cli/tests/repl-task-tabs.test.ts"; + function capture(page: ReplPage, name: string): void { const screen = page.repl.terminal.screen; if (screen === undefined) { @@ -39,6 +42,7 @@ for (const size of [ { columns: 72, rows: 20 }, ]) { describe(`Sidekick and TODO tabs at ${size.columns}x${size.rows}`, () => { + beforeEach(journalBeforeEach(OWNER)); it("switches only on human selection and retains drafts, item controls and held queue work", function* () { const page = yield* useReplPage({ size }); yield* draftText(page, "kept entry"); diff --git a/packages/cli/tests/repl-terminal.test.ts b/packages/cli/tests/repl-terminal.test.ts index f61a671fc..b4d6ef050 100644 --- a/packages/cli/tests/repl-terminal.test.ts +++ b/packages/cli/tests/repl-terminal.test.ts @@ -13,7 +13,8 @@ * is Slice E's turn. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { useTempFileCompiler } from "@executablemd/core"; import { @@ -87,6 +88,8 @@ import { railMark, } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-terminal.test.ts"; + const WIDE: ReplTerminalSize = { columns: 160, rows: 36 }; const MEDIUM: ReplTerminalSize = { columns: 120, rows: 30 }; const NARROW: ReplTerminalSize = { columns: 72, rows: 20 }; @@ -1995,6 +1998,7 @@ function framed(text: string): Uint8Array { } describe("REPL bracketed paste", () => { + beforeEach(journalBeforeEach(OWNER)); const payload = "first\n\n\t é界🙂\nlast\n"; for (const separator of ["\r", "\n", "\r\n"]) { it(`keeps framed ${JSON.stringify(separator)} as text only`, function* () { @@ -2107,6 +2111,7 @@ describe("REPL newline keys, from recorded terminal bytes", () => { }); describe("REPL terminal: what the host normalizes, and what it refuses to guess", () => { + beforeEach(journalBeforeEach(OWNER)); it("I1: a key becomes a normalized event and a mouse press becomes a position", function* () { const terminal = recordingTerminal(); yield* terminal.install(); @@ -2597,6 +2602,7 @@ describe("REPL terminal: what the host normalizes, and what it refuses to guess" }); describe("REPL terminal: what a drawer covers, and what it cannot reach", () => { + beforeEach(journalBeforeEach(OWNER)); it("TL6: a drawer is visible with its way out while the footer remains readable", function* () { const page = yield* useReplPage({ size: WIDE }); yield* page.press("[history]"); @@ -3039,6 +3045,7 @@ function* submitPast(page: ReplPage, order: number): Operation { } describe("REPL terminal: History past the row-full point (#1017)", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps every action reachable and preserves results, selection and the draft", function* () { const page = yield* useReplPage({ size: WIDE }); yield* intoDraft(page); diff --git a/packages/cli/tests/repl-todo-journey.test.ts b/packages/cli/tests/repl-todo-journey.test.ts index 4fadcb85a..171277ab2 100644 --- a/packages/cli/tests/repl-todo-journey.test.ts +++ b/packages/cli/tests/repl-todo-journey.test.ts @@ -1,6 +1,7 @@ import { sleep } from "effection"; import type { Operation } from "effection"; -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { readTextFile, writeTextFile } from "@effectionx/fs"; import { API } from "@executablemd/runtime"; @@ -12,6 +13,8 @@ import { pairedLocation } from "../src/repl/sidekick/history.ts"; import type { ReplPage, ScreenReading } from "./support/repl-page.ts"; import { TODO_WAKE } from "../src/repl/todo/wake.ts"; +const OWNER = "packages/cli/tests/repl-todo-journey.test.ts"; + /** * Whether the inert last task is the focused one, by its own row and rows. * @@ -173,6 +176,7 @@ for (const size of [ { columns: 72, rows: 20 }, ]) { describe(`Shared TODO terminal at ${size.columns}x${size.rows}`, () => { + beforeEach(journalBeforeEach(OWNER)); it("creates a shared task and keeps it when switching tabs", function* () { const page = yield* useReplPage({ size }); if (size.columns < 120) { @@ -464,6 +468,7 @@ for (const size of [ } describe("TODO human semantic actions", () => { + beforeEach(journalBeforeEach(OWNER)); it("adds, renames, completes, reopens, reorders and removes through mounted controls", function* () { const page = yield* useReplPage(); let inputCount = 0; @@ -647,6 +652,7 @@ describe("TODO human semantic actions", () => { }); describe("TODO background task focus", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps the surviving target and its local actions after an external prepend", function* () { const page = yield* useReplPage(); yield* intoComposer(page); diff --git a/packages/cli/tests/repl-todo-recovery.test.ts b/packages/cli/tests/repl-todo-recovery.test.ts index a29672876..87e2471ec 100644 --- a/packages/cli/tests/repl-todo-recovery.test.ts +++ b/packages/cli/tests/repl-todo-recovery.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { ensure, scoped, spawn, suspend, withResolvers } from "effection"; import { readTextFile, writeTextFile } from "@effectionx/fs"; @@ -10,7 +11,10 @@ import { settledReading } from "./support/mounted-history.ts"; import { pairedLocation } from "../src/repl/sidekick/history.ts"; import { todoWakeEligible } from "../src/repl/todo/wake.ts"; +const OWNER = "packages/cli/tests/repl-todo-recovery.test.ts"; + describe("TODO logical runtime recovery", () => { + beforeEach(journalBeforeEach(OWNER)); it("restores only file state and initializes once per open logical runtime", function* () { let initialized = 0; let cleaned = 0; diff --git a/packages/cli/tests/repl-unfinished-entry.test.ts b/packages/cli/tests/repl-unfinished-entry.test.ts index 418231609..a976f68a8 100644 --- a/packages/cli/tests/repl-unfinished-entry.test.ts +++ b/packages/cli/tests/repl-unfinished-entry.test.ts @@ -1,5 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; -import { captureTestJournal } from "@executablemd/test-support/failure-journal"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { captureTestJournal, journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { cliCommand, cliRuntime } from "@executablemd/test-support/launch"; import { expect } from "@executablemd/test-support/expect"; import { @@ -513,6 +513,7 @@ function* delegatedRepositoryWitness() { } describe(REPOSITORY_SUITE, () => { + beforeEach(journalBeforeEach(OWNER)); it(REPOSITORY_TEST, function* () { if (cliRuntime() === "deno") { // E3's real subdirectory control and the fatal witness own separate roots. @@ -526,6 +527,7 @@ describe(REPOSITORY_SUITE, () => { }); describe("joined entry diagnostics", () => { + beforeEach(journalBeforeEach(OWNER)); it("E3/E4/E5: exact earlier outcomes coexist with a live idle entry and joined Stop cleanup", function* () { const cleanup = gate(); yield* ensure(cleanup.release); diff --git a/packages/cli/tests/repl-wheel-burst.test.ts b/packages/cli/tests/repl-wheel-burst.test.ts index edbe9cfa7..58d84e100 100644 --- a/packages/cli/tests/repl-wheel-burst.test.ts +++ b/packages/cli/tests/repl-wheel-burst.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { scoped, sleep } from "effection"; import type { Operation } from "effection"; @@ -7,6 +8,8 @@ import type { ReplPage, ScreenCell, ScreenReading } from "./support/repl-page.ts import { draftHolds, intoComposer, intoDraft, paneLines } from "./support/screen-journeys.ts"; import { generateTypingHistory } from "./support/typing-history.ts"; +const OWNER = "packages/cli/tests/repl-wheel-burst.test.ts"; + const SIZE = { columns: 160, rows: 36 }; function report(direction: "up" | "down", at: ScreenCell): string { @@ -82,6 +85,7 @@ function* typed(page: ReplPage, text: string): Operation { } describe("wheel bursts in one input chunk", () => { + beforeEach(journalBeforeEach(OWNER)); it("Sidekick chat reaches the sequential endpoint and keeps follow", function* () { const page = yield* useReplPage({ size: SIZE }); yield* intoComposer(page); diff --git a/packages/cli/tests/repl-wheel-migration.test.ts b/packages/cli/tests/repl-wheel-migration.test.ts index 7553b880e..d6f56d7ba 100644 --- a/packages/cli/tests/repl-wheel-migration.test.ts +++ b/packages/cli/tests/repl-wheel-migration.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { sleep } from "effection"; import type { Operation } from "effection"; @@ -16,6 +17,8 @@ import { import { awaitedFact, OTHER_MOUNTED_AGENT } from "./support/mounted-repl.ts"; import { REFERENCE_DIRECTORY } from "./fixtures/repl/reference.ts"; +const OWNER = "packages/cli/tests/repl-wheel-migration.test.ts"; + function* key(page: ReplPage, name: PageKey): Operation { const before = page.screen().index; yield* page.key(name); @@ -97,6 +100,7 @@ function absentButtons(page: ReplPage): void { } describe("wheel remaining migration journeys", () => { + beforeEach(journalBeforeEach(OWNER)); it("keeps permission focus through scrolling and acknowledges a held presentation", function* () { const page = yield* useReplPage({ size: { columns: 120, rows: 30 } }); const explanation = Array.from( diff --git a/packages/cli/tests/repl-wheel-scroll.test.ts b/packages/cli/tests/repl-wheel-scroll.test.ts index ee8aabc7b..8f833c2f0 100644 --- a/packages/cli/tests/repl-wheel-scroll.test.ts +++ b/packages/cli/tests/repl-wheel-scroll.test.ts @@ -1,4 +1,5 @@ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { sleep, spawn, withResolvers } from "effection"; import type { Operation } from "effection"; @@ -7,6 +8,8 @@ import { useReplPage } from "./support/repl-page.ts"; import type { PageKey, ReplPage, ScreenCell } from "./support/repl-page.ts"; import { draftText, intoComposer, intoDraft, SIDEKICK_PANE } from "./support/screen-journeys.ts"; +const OWNER = "packages/cli/tests/repl-wheel-scroll.test.ts"; + function* key(page: ReplPage, name: PageKey): Operation { const before = page.screen().index; yield* page.key(name); @@ -75,6 +78,7 @@ function* transcriptThrough(page: ReplPage, last: number): Operation { } describe("wheel real consumers", () => { + beforeEach(journalBeforeEach(OWNER)); it("permission explanation is readable in both directions without deciding", function* () { const page = yield* useReplPage({ size: { columns: 120, rows: 30 } }); const explanation = [ diff --git a/packages/cli/tests/retained-repository-local.test.ts b/packages/cli/tests/retained-repository-local.test.ts index b73a86d85..652e3bfb3 100644 --- a/packages/cli/tests/retained-repository-local.test.ts +++ b/packages/cli/tests/retained-repository-local.test.ts @@ -17,7 +17,8 @@ * them assert is what a *second* open of one history does. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { allSettled, @@ -86,6 +87,8 @@ import { useReplFileRecorder } from "../src/repl/repositories/deno/files.ts"; import { workspaceMountInstallation } from "../src/repl/workspace-mount-installation.ts"; import type { ReplLocalValue } from "../src/repl/repositories/records.ts"; +const OWNER = "packages/cli/tests/retained-repository-local.test.ts"; + interface Fixture { readonly root: string; readonly checkout: string; @@ -1297,6 +1300,7 @@ describe("one entry's local file work", () => { }); describe("975 — native Git keeps project selection and refuses an outside cwd", () => { + beforeEach(journalBeforeEach(OWNER)); it("reads the launch project and refuses native Git outside its selected checkout", function* () { yield* Permissions.around( { files: ([operation], next) => (operation === "absolute" ? true : next(operation)) }, diff --git a/packages/cli/tests/retained-repository-selection.test.ts b/packages/cli/tests/retained-repository-selection.test.ts index 7a3cac74e..0d9d3523d 100644 --- a/packages/cli/tests/retained-repository-selection.test.ts +++ b/packages/cli/tests/retained-repository-selection.test.ts @@ -19,7 +19,8 @@ * because what most of them assert is what a *second* open of one history does. */ -import { describe, it } from "@executablemd/test-support/bdd"; +import { beforeEach, describe, it } from "@executablemd/test-support/bdd"; +import { journalBeforeEach } from "@executablemd/test-support/failure-journal"; import { expect } from "@executablemd/test-support/expect"; import { cliCommand } from "@executablemd/test-support/launch"; import { @@ -81,6 +82,8 @@ import type { ReplPlacementRecord } from "../src/repl/repositories/placement-rec import { REPL_REPOSITORY_LOCAL } from "../src/repl/repositories/records.ts"; import { repositorySlot, worktreeSlot } from "@executablemd/git/deno"; +const OWNER = "packages/cli/tests/retained-repository-selection.test.ts"; + interface Fixture { /** The scenario's own directory: source repository, managed root and HOME. */ readonly root: string; @@ -1191,6 +1194,7 @@ function* slotBytes(path: string): Operation { } describe("1113: repositories use the selected project and configured managed root", () => { + beforeEach(journalBeforeEach(OWNER)); it("acquires, reads, reopens and reuses saved source with different repository inputs", function* () { const fixture = yield* useFixture(); const chapter = yield* readGuideChapter("Entries"); diff --git a/packages/cli/tests/support/mounted-repl.ts b/packages/cli/tests/support/mounted-repl.ts index 946505545..2089c793c 100644 --- a/packages/cli/tests/support/mounted-repl.ts +++ b/packages/cli/tests/support/mounted-repl.ts @@ -15,8 +15,9 @@ import { installTodoSource } from "../../src/node-todo-source.ts"; import { action, ensure, resource, sleep, spawn, until, withResolvers } from "effection"; import type { Operation, Result, Stream, Subscription } from "effection"; import { appendFile, open as openFile, readdir } from "node:fs/promises"; -import { join } from "node:path"; +import { join, relative } from "node:path"; import { randomBytes } from "node:crypto"; +import { exists, FsApi, readTextFile } from "@effectionx/fs"; import { installReplHost } from "../../src/repl-assembly.ts"; import { ReplHost } from "../../src/repl/host.ts"; @@ -31,7 +32,10 @@ import { resolveAgentStack } from "../../src/agent-stack.ts"; import { NO_PLUGINS, installPlugins } from "../../src/plugin-host.ts"; import { todoPlugin, todoPluginDeclaresFor } from "../../src/repl/todo/plugin.ts"; import { pairedReplRepository } from "../../src/repl/sidekick/repository.ts"; -import { PAIRED_DIRECTORY } from "../../src/repl/sidekick/history.ts"; +import { PAIRED_DIRECTORY, pairedLocation } from "../../src/repl/sidekick/history.ts"; +import { executionPath } from "../../src/repl/journal.ts"; +import { isOpaqueExecution } from "../../src/repl/route.ts"; +import type { SavedJournalFile } from "../../src/test-diagnostics.ts"; import type { SidekickRecord } from "../../src/repl/sidekick/history.ts"; import { projectRepl } from "../../src/repl/model.ts"; import type { ReplModel } from "../../src/repl/model.ts"; @@ -44,6 +48,7 @@ import type { AcpxProviderDependencies } from "@executablemd/acp"; import { useTempFileCompiler, useNormalizedOutput } from "@executablemd/core"; import { createFakeAcp, makeRegistry, makeStore } from "./fake-acp.ts"; import type { FakeAcp } from "./fake-acp.ts"; +import { retainJournalFiles } from "@executablemd/test-support/failure-journal"; import { useTemporary } from "../fixtures/repl/issue-883/sidekick-harness.ts"; import { useTerminalScreen } from "./terminal-screen.ts"; import type { TerminalScreen } from "./terminal-screen.ts"; @@ -634,6 +639,77 @@ export function operationGate(): OperationGate { }; } +/** + * The histories a mounted command writes beneath `root`, as UTF-8 text: each + * paired execution's entries and Sidekick files, and each direct legacy file. + * + * Named files only, because an execution's directory also holds its authored + * assets and components, which are inputs rather than history. + */ +function* mountedJournals(root: string): Operation { + if (!(yield* exists(root))) { + return []; + } + const paths: string[] = []; + for (const entry of yield* FsApi.operations.readdirDirents(root)) { + const execution = entry.name.slice(0, -".jsonl".length); + if (entry.isFile() && entry.name.endsWith(".jsonl") && isOpaqueExecution(execution)) { + paths.push(executionPath(root, execution)); + } + } + const paired = join(root, PAIRED_DIRECTORY); + if (yield* exists(paired)) { + for (const entry of yield* FsApi.operations.readdirDirents(paired)) { + if (entry.isDirectory() && isOpaqueExecution(entry.name)) { + const location = pairedLocation(root, entry.name); + paths.push(location.entries, location.sidekick); + } + } + } + const files: SavedJournalFile[] = []; + for (const path of paths.sort()) { + if ((yield* exists(path)) && (yield* FsApi.operations.stat(path)).isFile()) { + files.push({ path: relative(root, path), text: yield* readTextFile(path) }); + } + } + return files; +} + +/** The appends a mounted host has handed out and not yet seen settle. */ +interface OutstandingAppends { + /** Hold `append` until it settles, and hand it back unchanged. */ + track(append: Promise): Promise; +} + +/** + * Keep the host's appends inside the host's lifetime. + * + * Halting the task that asked for an append abandons its wait but not the + * write, which is already scheduled. Teardown waits for every outstanding one + * to settle — written or refused, without retrying or reporting it — so nothing + * acquired earlier, such as reading or removing the storage, races a write. + */ +function useOutstandingAppends(): Operation { + return resource(function* (provide) { + const outstanding = new Set>(); + yield* ensure(function* () { + while (outstanding.size > 0) { + yield* until(Promise.all(outstanding)); + } + }); + yield* provide({ + track(append) { + const settled: Promise = append.then( + () => outstanding.delete(settled), + () => outstanding.delete(settled), + ); + outstanding.add(settled); + return append; + }, + }); + }); +} + /** One mounted command, and everything a case needs to drive and read it. */ export interface MountedRepl { @@ -763,6 +839,14 @@ export function* useMountedHost( // harness without it would run entries that fail for a reason no row is about. yield* useTempFileCompiler(); const dataRoot = options.dataRoot ?? (yield* useTemporary("xmd-repl-mounted-")); + // The directory the command itself resolves, so a case that writes a file for + // the command to find writes it where the command actually looks. + const root = join(dataRoot, ...REPL_DIRECTORY); + // Before anything that writes there, so this case's command has unwound and + // its appends have settled when its histories are read, and they are read + // before the root is removed. + yield* retainJournalFiles(root, mountedJournals(root)); + const appends = yield* useOutstandingAppends(); yield* useNodeReplProjectAccess(); yield* installTodoSource(); yield* installReplHost({ @@ -776,11 +860,13 @@ export function* useMountedHost( appendRecord: (path, record) => { const held = gate?.around(path, record); const written = (held ?? Promise.resolve()).then(() => appendFile(path, record)); - return gate === undefined - ? written - : written.then(() => { - gate.reached.push(path); - }); + return appends.track( + gate === undefined + ? written + : written.then(() => { + gate.reached.push(path); + }), + ); }, }); // Over the installed implementation, at the instrumentation band, so the @@ -837,9 +923,6 @@ export function* useMountedHost( planWriterRoot: yield* useTemporary("xmd-repl-mounted-plan-"), }, ); - // The directory the command itself resolves, so a case that writes a file for - // the command to find writes it where the command actually looks. - const root = join(dataRoot, ...REPL_DIRECTORY); return { root, fake, diff --git a/packages/test-support/failure-journal.ts b/packages/test-support/failure-journal.ts index 8bddc323a..07f41f4e8 100644 --- a/packages/test-support/failure-journal.ts +++ b/packages/test-support/failure-journal.ts @@ -1,24 +1,42 @@ -import { createContext, resource, scoped } from "effection"; -import type { Operation } from "effection"; +import { createContext, ensure, Err, Ok, resource, scoped } from "effection"; +import type { Operation, Result } from "effection"; import { InMemoryStream } from "@executablemd/durable-streams"; import type { DurableEvent } from "@executablemd/durable-streams"; import { withFailureJournal } from "@executablemd/testing"; import process from "node:process"; import { prepareTestDiagnostics, useTestDiagnostics } from "../cli/src/test-diagnostics.ts"; -import type { JournalCase, TestDiagnostics } from "../cli/src/test-diagnostics.ts"; +import type { + JournalCase, + SavedJournalFile, + TestDiagnostics, +} from "../cli/src/test-diagnostics.ts"; import type { DeliverySink } from "../cli/src/stdout-delivery.ts"; import { CaseOutcome } from "./case-outcome.ts"; import type { CaseSetup } from "./case-outcome.ts"; -const CaseJournals = createContext<(source: string) => InMemoryStream>( - "@executablemd/test-support/case-journals", -); +/** A case's file-backed journals, read before the fixture that owns them deletes them. */ +interface RetainedFiles { + read?: Result; +} + +type CaseRoot = + | { readonly source: string; readonly stream: InMemoryStream } + | { readonly source: string; readonly files: RetainedFiles }; + +interface CaseRoots { + stream(source: string): InMemoryStream; + files(source: string): RetainedFiles; +} + +const CaseJournals = createContext("@executablemd/test-support/case-journals"); /** * Give ordinary cases fresh attributed roots with one suite setup. For example, * the held-host witness registers `beforeEach(journalBeforeEach(OWNER))`. Its * fixture selects `request.stream ?? (yield* useJournalStream(document.path))`. - * Keep explicit replay and private inputs at the fixture that owns them. + * A fixture whose host writes journal files registers how to read them with + * {@link retainJournalFiles}. Keep explicit replay and private inputs at the + * fixture that owns them. */ export function journalBeforeEach(owner: string): CaseSetup { return { @@ -30,7 +48,7 @@ export function journalBeforeEach(owner: string): CaseSetup { }; } -function useCaseJournals(owner: string): Operation<(source: string) => InMemoryStream> { +function useCaseJournals(owner: string): Operation { return resource(function* (provide) { const outcome = yield* CaseOutcome.expect(); const openDiagnostics = yield* prepareTestDiagnostics(process.stderr, { @@ -38,12 +56,19 @@ function useCaseJournals(owner: string): Operation<(source: string) => InMemoryS name: outcome.name, suite: outcome.suite, }); - const roots: Array<{ source: string; stream: InMemoryStream }> = []; + const roots: CaseRoot[] = []; try { - yield* provide((source) => { - const stream = new InMemoryStream(); - roots.push({ source, stream }); - return stream; + yield* provide({ + stream(source) { + const stream = new InMemoryStream(); + roots.push({ source, stream }); + return stream; + }, + files(source) { + const files: RetainedFiles = {}; + roots.push({ source, files }); + return files; + }, }); } finally { // The adapter can reject after destroying the entire case scope. @@ -56,17 +81,30 @@ function useCaseJournals(owner: string): Operation<(source: string) => InMemoryS function* saveCaseJournals( openDiagnostics: () => Operation, - roots: readonly { source: string; stream: InMemoryStream }[], + roots: readonly CaseRoot[], ): Operation { const diagnostics = yield* openDiagnostics(); - for (const { source, stream } of roots) { - const host = diagnostics.execution("root", source).journal(() => false); - const events = yield* stream.readAll(); - if (events.length === 0) { - continue; - } + for (const root of roots) { + const execution = diagnostics.execution("root", root.source); + const host = execution.journal(() => false); try { - yield* host.save(events); + if ("stream" in root) { + const events = yield* root.stream.readAll(); + if (events.length > 0) { + yield* host.save(events); + } + continue; + } + const read = root.files.read; + if (read === undefined) { + throw new Error("its files were never read before their owner ended"); + } + if (!read.ok) { + throw read.error; + } + if (read.value.length > 0) { + yield* execution.saveFiles(read.value); + } } catch (error) { yield* host.reportSaveFailure(error instanceof Error ? error : new Error(String(error))); } @@ -75,8 +113,42 @@ function* saveCaseJournals( /** Open a fresh journal at the actual source of an independent execution. */ export function* useJournalStream(source: string): Operation { - const open = yield* CaseJournals.get(); - return open === undefined ? new InMemoryStream() : open(source); + const roots = yield* CaseJournals.get(); + return roots === undefined ? new InMemoryStream() : roots.stream(source); +} + +/** + * Keep the journal files a fixture's host writes for this case's failure save. + * + * `snapshot` is the owner's own operation for reading them, because only the + * owner knows which of its files are journals. Acquire this once the fixture + * owns the storage and before the work that writes there begins: `snapshot` + * runs when this resource is torn down, after everything the calling scope + * acquired later and before anything it acquired earlier — such as the + * storage's own removal. A passing case discards what was read, and a failed + * case saves each file beneath the registration's own execution name, keeping + * its `path`. Outside an attributed case `snapshot` never runs. + */ +export function retainJournalFiles( + source: string, + snapshot: Operation, +): Operation { + return resource(function* (provide) { + const roots = yield* CaseJournals.get(); + if (roots === undefined) { + yield* provide(); + return; + } + const retained = roots.files(source); + yield* ensure(function* () { + try { + retained.read = Ok(yield* snapshot); + } catch (error) { + retained.read = Err(error instanceof Error ? error : new Error(String(error))); + } + }); + yield* provide(); + }); } /**