Skip to content

Commit 1e44987

Browse files
committed
✨ Capture the problems with <Json as>, and claim the directory before making it (#260)
Rebased onto `<Json as>` (#667), which supplies what the single-child `<Let>` wrapper was standing in for. Both wrappers in the packaged prompt command document are gone; `<Json value={check.diagnostics} as="problems" />` binds the serialized text directly, and the bytes reaching `<CodeBlock>` are the same bytes — the repair turn and the review presentation still carry the complete structured problems, now proven by parsing the fence back rather than by matching a substring of it. The default session's directory is now a scope-owned resource rather than a directory with an ensure attached afterwards. The release is registered before the `mkdir` that could create it, so there is no window in which a leaf exists that nothing is responsible for: a failure between making it and using it hands it back like every other ending. What the release knows is whether the directory was ever handed over, and that decides which question it is answering. Once established, the exit has exactly two outcomes and no third. Still the empty directory it was given, and the leaf is removed, non-recursively. Anything else — content that appeared, or a directory that vanished — is preserved as found and fails the command terminally. A leaf that disappears under a live conversation was silently accepted before, which was wrong twice over: nothing here is allowed to remove it, so its absence is interference, and treating interference as a clean exit would let admission, the save and the execution proceed on a conversation something else had already reached into. A directory establishment never handed over is a different question, already answered by what establishment reported. The release leaves that report and the directory's contents alone, while still handing back an empty leaf it did create. Explicitly named directories are untouched by any of this: they stay, because the next `--session` derives the same ACPX session identity from where they are. Claude-Session: https://claude.ai/code/session_015HcqB9kJM9KFnMNToAuZF6
1 parent 6348b73 commit 1e44987

7 files changed

Lines changed: 206 additions & 41 deletions

File tree

‎architecture.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Existing documents and code get aligned to this section retroactively.
3636
| Prompt | a person's original request, in ordinary natural language. `xmd prompt` takes exactly one |
3737
| Plan | the executable program produced from a Prompt: an Executable Markdown document combining readable prose that expresses the Prompt's intent with the components that carry it out, each placed beside the prose describing what it does. A Plan is what `xmd prompt` approves, optionally saves and runs; it is not a synonym for a workflow, a policy document or any executable Markdown file |
3838
| prompt command document | the one exact checked-in first-party Markdown value root `xmd prompt` executes to convert a Prompt into a Plan. It implements that conversion and its review workflow — the request wording, the draft and repair loops, the check branches, human review, revision, approval, abort and exhaustion — and returns the exact approved Plan source. It is not itself a Plan. Internal: no command-line option selects another one, and no repository component search can answer for it |
39-
| prompt profile | the trusted-host assembly used only for the prompt command document: its fixed inputs, a constrained Agent provider, Elicitation, the fixed first-party components and the host-declared draft validator. It uses no repository component search and exposes no custom root, and the ceiling it establishes is not readable from the command line. Its working directory is one host-owned directory dedicated to the logical prompt session, keyed by the digest of that name, created empty and required to be empty on the way in. An explicitly named session's directory is durable, because continuation derives the same session identity from it; an invocation-unique default session's is scope-owned, and exactly one cleanup is attempted after profile teardown and before admission on every ending — the leaf removed non-recursively when still empty, and preserved whole with the command failing terminally when it is not. Where those directories live is a host dependency no caller or document selects |
39+
| prompt profile | the trusted-host assembly used only for the prompt command document: its fixed inputs, a constrained Agent provider, Elicitation, the fixed first-party components and the host-declared draft validator. It uses no repository component search and exposes no custom root, and the ceiling it establishes is not readable from the command line. Its working directory is one host-owned directory dedicated to the logical prompt session, keyed by the digest of that name, created empty and required to be empty on the way in. An explicitly named session's directory is durable, because continuation derives the same session identity from it; an invocation-unique default session's is scope-owned, claimed before it is created, and exactly one cleanup is attempted after profile teardown and before admission on every ending — the leaf removed non-recursively when it is still the empty directory that was handed over, and left as found with the command failing terminally when it has gained content or vanished. Where those directories live is a host dependency no caller or document selects |
4040
| expansion | one logical evaluation of an authored executable element within a document execution |
4141
| expansion ID | a deterministic identifier for one logical expansion; restoring or retrying that expansion preserves the ID, while a distinct evaluation requested by the document receives another |
4242
| Git capability | the contextual interface through which workflow infrastructure queries the Git repository associated with the current working directory |

‎packages/cli/src/documents/prompt-command.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ found. A change you ask for produces a new draft, so it gets its own three.
8686
<Prompt as="draft">
8787
That document has problems. These are the exact ones:
8888

89-
<Let as="problems"><Json value={check.diagnostics} /></Let>
89+
<Json value={check.diagnostics} as="problems" />
9090
<CodeBlock value={problems} language="json" />
9191

9292
Send one complete replacement document that resolves every problem above. Keep
@@ -129,7 +129,7 @@ This document was written for: {props.request}
129129
<If condition={!check.valid}>
130130
Three attempts to fix it did not clear everything. These problems remain:
131131

132-
<Let as="problems"><Json value={check.diagnostics} /></Let>
132+
<Json value={check.diagnostics} as="problems" />
133133
<CodeBlock value={problems} language="json" />
134134
</If>
135135
</Elicit>

‎packages/cli/src/prompt-profile.ts‎

Lines changed: 57 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -144,22 +144,16 @@ export function* runPromptCommandDocument(profile: PromptProfile): Operation<Res
144144
}
145145

146146
return yield* scoped(function* (): Operation<Result<string>> {
147-
// First, and before anything is built: this session's directory is
147+
// First, and before anything is built: this session's directory is claimed,
148148
// established and proven empty, or the command stops here. Nothing has been
149-
// installed yet, so a refusal reaches no provider, no session and no turn.
150-
const established = yield* establishDirectory(profile.root, profile.session);
149+
// installed yet, so a refusal reaches no provider, no session and no turn —
150+
// and because the claim is taken before the directory is made, an ending of
151+
// any kind, including a cancellation, still hands it back.
152+
const established = yield* useSessionDirectory(profile);
151153
if (!established.ok) {
152154
return established;
153155
}
154156
const workdir = established.value;
155-
if (!profile.explicitSession) {
156-
// Registered before every other resource, so it runs after all of them:
157-
// the provider, the Prompt tasks and the Elicitation provider are already
158-
// gone when this hands the directory back. Being an `ensure` is what makes
159-
// an abort, a failed turn and a cancellation clean up the same way a
160-
// success does.
161-
yield* ensure(() => removeEmptyDirectory(workdir));
162-
}
163157

164158
yield* refuseDocumentCapabilities();
165159
yield* profile.installElicitation();
@@ -323,6 +317,37 @@ export function profileDirectoryFor(root: string, session: string): string {
323317
return join(root, createHash("sha256").update(session).digest("hex"));
324318
}
325319

320+
/**
321+
* This conversation's directory, for as long as the conversation lasts.
322+
*
323+
* An explicitly named session's directory is durable — a later `--session` finds
324+
* the same location and therefore the same ACPX session — so nothing is
325+
* registered against it and nothing removes it.
326+
*
327+
* An invocation-unique one belongs to this scope, and the release is registered
328+
* *before* the first filesystem call that could create it. A leaf this call
329+
* made and then failed on is still a leaf this call made; registering after the
330+
* `mkdir` would leave one behind exactly in the case nobody is watching. Being
331+
* the first thing registered in the scope is also what puts it last in teardown,
332+
* after every provider, Prompt task and Elicitation resource has gone.
333+
*/
334+
function* useSessionDirectory(profile: PromptProfile): Operation<Result<string>> {
335+
const directory = profileDirectoryFor(profile.root, profile.session);
336+
if (profile.explicitSession) {
337+
return yield* establishDirectory(directory);
338+
}
339+
const claim: DirectoryClaim = { established: false };
340+
yield* ensure(() => releaseSessionDirectory(directory, claim));
341+
const established = yield* establishDirectory(directory);
342+
claim.established = established.ok;
343+
return established;
344+
}
345+
346+
/** Whether the directory was ever handed to this conversation to use. */
347+
interface DirectoryClaim {
348+
established: boolean;
349+
}
350+
326351
/**
327352
* Establish this session's directory, or refuse.
328353
*
@@ -331,8 +356,7 @@ export function profileDirectoryFor(root: string, session: string): string {
331356
* a stranger's files to get on with the work is the opposite of what a ceiling
332357
* is for. So the command says what it found and where, and stops.
333358
*/
334-
function* establishDirectory(root: string, session: string): Operation<Result<string>> {
335-
const directory = profileDirectoryFor(root, session);
359+
function* establishDirectory(directory: string): Operation<Result<string>> {
336360
try {
337361
yield* until(mkdir(directory, { recursive: true }));
338362
const entries = yield* until(readdir(directory));
@@ -359,23 +383,34 @@ function* establishDirectory(root: string, session: string): Operation<Result<st
359383
/**
360384
* Give an invocation-unique conversation's directory back when it is over.
361385
*
362-
* Only an explicitly named session needs its directory afterwards: its identity
363-
* is what a later `--session` derives the same ACPX session from. A generated
364-
* name names nothing anybody can ask for again, so its directory is this scope's
365-
* and goes away with it — before the approved Plan is validated, saved or run.
386+
* One attempt, non-recursive, always. A directory this conversation was given
387+
* empty and is handing back empty is removed; anything else is reported and
388+
* nothing is deleted, because a leaf that changed underneath a conversation
389+
* nobody authorized to write there is interference, not a tidying job. The
390+
* failure raises out of the profile's scope, so no final validation, save or
391+
* execution follows it.
366392
*
367-
* Non-recursive, always. If something is in there, this host did not authorize
368-
* whatever put it there, and the honest answer is to say so rather than to
369-
* delete it: the same refusal an occupied directory earns on the way in.
393+
* A directory the conversation never got — establishment refused it, or never
394+
* made it — is a different question, and one already answered: whatever
395+
* establishment reported is the honest account, and this leaves both it and the
396+
* directory's contents alone. An empty leaf this call did create is still handed
397+
* back, which is the whole reason the release is registered before the `mkdir`.
370398
*/
371-
function* removeEmptyDirectory(directory: string): Operation<void> {
399+
function* releaseSessionDirectory(directory: string, claim: DirectoryClaim): Operation<void> {
372400
try {
373401
yield* until(rmdir(directory));
374402
} catch (error) {
375403
const code = error instanceof Error && "code" in error ? error.code : undefined;
376-
if (code === "ENOENT") {
404+
if (!claim.established) {
377405
return;
378406
}
407+
if (code === "ENOENT") {
408+
throw new Error(
409+
`${directory} was made for this conversation and is already gone. Something removed ` +
410+
"it while the conversation was still running, which nothing here is allowed to do; " +
411+
"nothing was saved or run",
412+
);
413+
}
379414
if (code === "ENOTEMPTY" || code === "EEXIST") {
380415
throw new Error(
381416
`${directory} was empty when this conversation started and is not now. It belongs to ` +

‎packages/cli/tests/packaged-document.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ describe("packaged documents", () => {
4848
"places each component\nimmediately after the sentences describing the action",
4949
);
5050
expect(source).toContain("ordinary reader-facing prose");
51+
// It captures the serialized problems with `<Json as>` directly. The
52+
// single-child `<Let>` wrapper existed only because the component refused a
53+
// literal `as`, and main supplies that now.
54+
expect(source).toContain('<Json value={check.diagnostics} as="problems" />');
55+
expect(source).not.toContain('<Let as="problems">');
5156
});
5257

5358
it("says which build is missing a document rather than behaving differently", function* () {

‎packages/cli/tests/prompt.test.ts‎

Lines changed: 114 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,30 @@ function* exists(path: string): Operation<boolean> {
177177
return (yield* stat(path)).exists;
178178
}
179179

180+
/** What one message's `json` fence holds, parsed back. */
181+
interface FencedDiagnostics {
182+
validation?: {
183+
version?: number;
184+
outcome?: string;
185+
diagnostics?: { code?: string }[];
186+
};
187+
}
188+
189+
/**
190+
* The complete JSON a message carried, read out of its fence.
191+
*
192+
* Parsed rather than string-matched: what matters is that `<Json>`'s serialized
193+
* text reached `<CodeBlock>` whole, and a structure that parses back to the same
194+
* shape is what says so.
195+
*/
196+
function fencedJson(message: string): FencedDiagnostics {
197+
const fence = /```json\n([\s\S]*?)\n```/.exec(message);
198+
if (fence === null) {
199+
throw new Error(`no json fence in: ${message}`);
200+
}
201+
return JSON.parse(fence[1]);
202+
}
203+
180204
/** How many times one exact string appears. */
181205
function occurrences(haystack: string, needle: string): number {
182206
return haystack.split(needle).length - 1;
@@ -404,6 +428,79 @@ describe(
404428
expect(yield* until(readdir(profileRoot))).toEqual([]);
405429
});
406430

431+
// A failure between making the leaf and using it still hands it back. The
432+
// claim is taken before the `mkdir`, so there is no window in which a
433+
// directory exists that nothing is responsible for.
434+
yield* useWorkingDirectory(function* (dir, profileRoot) {
435+
const harness = createPromptHarness({ profileRoot });
436+
harness.fake.script({ reply: VALID });
437+
// deno-lint-ignore require-yield
438+
harness.deps.installElicitation = function* () {
439+
throw new Error("this host could not install a review provider");
440+
};
441+
442+
const { value, lines } = yield* reported(() =>
443+
runPrompt(command(dir, [REQUEST]), harness.deps),
444+
);
445+
446+
expect(value).toBe(1);
447+
expect(lines.join("\n")).toContain("could not install a review provider");
448+
// Nothing was built after it, and no empty leaf was left behind.
449+
expect(harness.fake.created).toHaveLength(0);
450+
expect(harness.executions).toHaveLength(0);
451+
expect(yield* until(readdir(profileRoot))).toEqual([]);
452+
});
453+
454+
// Establishment failing for a reason of its own leaves nothing behind and
455+
// says what it found. The claim is already taken here, so the release runs
456+
// and finds no directory it was ever given — which is the one case where
457+
// an absent directory is the ordinary answer rather than interference.
458+
yield* useWorkingDirectory(function* (dir, profileRoot) {
459+
const blocked = join(profileRoot, "not-a-directory");
460+
yield* writeTextFile(blocked, "in the way\n");
461+
462+
const harness = createPromptHarness({ profileRoot: blocked });
463+
harness.fake.script({ reply: VALID });
464+
465+
const { value, lines } = yield* reported(() =>
466+
runPrompt(command(dir, [REQUEST]), harness.deps),
467+
);
468+
469+
expect(value).toBe(1);
470+
expect(lines).toHaveLength(1);
471+
expect(lines[0]).toContain("could not establish");
472+
// What was in the way is untouched, and no phase after it began.
473+
expect(yield* readTextFile(blocked)).toBe("in the way\n");
474+
expect(harness.fake.created).toHaveLength(0);
475+
expect(harness.executions).toHaveLength(0);
476+
});
477+
478+
// A leaf that disappears under a live conversation is interference, not a
479+
// tidy exit. The command fails terminally rather than shrugging at an
480+
// absent directory, and nothing it would have done next happens.
481+
yield* useWorkingDirectory(function* (dir, profileRoot) {
482+
const harness = createPromptHarness({ profileRoot });
483+
harness.fake.script({ reply: VALID });
484+
harness.deps.installElicitation = watching(harness, function* (workdir) {
485+
yield* rm(workdir, { recursive: true, force: true });
486+
});
487+
488+
const { value, lines } = yield* reported(() =>
489+
runPrompt({ ...command(dir, [REQUEST]), save: "out.md" }, harness.deps),
490+
);
491+
492+
expect(value).toBe(1);
493+
expect(lines).toHaveLength(1);
494+
expect(lines[0]).toContain("was made for this conversation and is already gone");
495+
expect(lines[0]).not.toContain("does not validate");
496+
// The Plan was approved and still reached nothing: no admission that
497+
// could have saved it, no save, no execution and so no journal.
498+
expect(harness.reviews).toHaveLength(1);
499+
expect(yield* exists(join(dir, "out.md"))).toBe(false);
500+
expect(yield* until(readdir(dir))).toEqual([]);
501+
expect(harness.executions).toHaveLength(0);
502+
});
503+
407504
// The other outcome of the one attempt. A directory this invocation was
408505
// given empty and did not leave empty is preserved and the command fails:
409506
// something wrote there while the conversation ran, and this host
@@ -659,6 +756,16 @@ describe(
659756
expect(code).toBe(0);
660757
expect(harness.fake.prompts).toHaveLength(2);
661758
expect(harness.fake.prompts[1]).toContain("That document has problems");
759+
// `<Json as>` captured the whole serialized value, and the fence it went
760+
// into holds every byte of it: the wrapper's removal changed where the
761+
// text is bound, not what it says. Parsed back rather than matched, so
762+
// what is proven is that the complete structure survived the trip.
763+
const repaired = fencedJson(harness.fake.prompts[1]);
764+
expect(repaired.validation?.version).toBe(1);
765+
expect(repaired.validation?.outcome).toBe("invalid");
766+
expect(
767+
repaired.validation?.diagnostics?.some((entry) => entry.code === "source-invalid"),
768+
).toBe(true);
662769
expect(harness.fake.prompts[1]).toContain("source-invalid");
663770
// The whole versioned value, as data the program serialized.
664771
expect(harness.fake.prompts[1]).toContain('"version": 1');
@@ -782,7 +889,13 @@ describe(
782889
expect(harness.reviews[0].message).toContain(
783890
"Three attempts to fix it did not clear everything",
784891
);
785-
expect(harness.reviews[0].message).toContain("component-unresolved");
892+
// The presentation carries the same complete captured JSON the repair
893+
// turns did, through the same `<Json as>` binding.
894+
const shown = fencedJson(harness.reviews[0].message);
895+
expect(shown.validation?.version).toBe(1);
896+
expect(
897+
shown.validation?.diagnostics?.some((entry) => entry.code === "component-unresolved"),
898+
).toBe(true);
786899
expect(harness.executions).toHaveLength(0);
787900
});
788901

‎specs/acp-client-spec.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -578,10 +578,12 @@ write there.
578578

579579
An explicitly named session keeps its directory afterwards, because that is what
580580
the next invocation derives the same session identity from, and no cleanup
581-
applies to it. An invocation-unique default keeps nothing: once the profile has
582-
torn down, on every ending, exactly one cleanup is attempted — the leaf is
583-
removed non-recursively if it is still empty, and if it is not, it is preserved
584-
whole and the command fails terminally. Which applies is a trusted host value —
581+
applies to it. An invocation-unique default keeps nothing: its release is
582+
registered before the directory is created, and once the profile has torn down,
583+
on every ending, exactly one cleanup is attempted — the leaf is removed
584+
non-recursively if it is still the empty directory that was handed over, and if
585+
it has gained content or disappeared it is left as found and the command fails
586+
terminally. Which applies is a trusted host value —
585587
whether `--session` was written — and where the directories live is a host
586588
dependency no caller or document can select.
587589

0 commit comments

Comments
 (0)