Skip to content

Commit f7a1063

Browse files
authored
✨ Run the packaged Plan in xmd repl, under one immutable profile (#864)
`xmd repl` took a location and nothing else, so an Agent had no way to reach a REPL entry and `<Plan>` had no way to run in one. It now reads the same five Agent options `xmd run` reads, as a first-class Plugin command of its own — selected Plugins are told `repl`, and the bundled Git Plugin declares for it, because a REPL entry is a document run under the ordinary profile — one declaration, so the two commands cannot come to mean different things by the same spelling — and settles them in a fixed order: the line, then the Agent configuration, then one profile, then the terminal. Everything a wrong invocation can be refused for is refused before a per-user directory is formed, a history file exists or the terminal's modes are touched. What a REPL execution runs under is one immutable `ReplExecutionProfile`, assembled once in the command's own scope: the selected Plugins, the Agent identity components, the real packaged `<Plan>` declaration and the ordinary evaluation ceiling, with the settled permission mode beside them. The program takes that one value and nothing else, so what an entry may resolve, what ceiling a generated fragment runs under and how a permission request is answered are facts about the command a person invoked rather than about the entry they typed. It carries data and installations and never authority: no stack, provider, Plan writer, live request or scope reaches the model, the route or the Journal through it. The REPL installs no readline permission handling, no foreground launcher and no browser form — a question is answered in the drawer in front of the person, and `<Session.Launch>` refuses through the established missing-launcher contract because this command is using the terminal it would be given. A returned Plan is a generated fragment, and a fragment that may write may now also ask: canonical `<Elicit>` joins the ordinary write table at core's own origin, key and revision, paired only, as a *pinned capability* rather than a name the fragment resolves. Preflight selects it where it finds an occurrence under a `write` selection, and the body it selects is core's own `<Elicit>`, closed over before any document code runs — exactly as the body behind `<File>` is. Nothing resolves the name: not before the root import, not at invocation, and middleware answering a generated import with a body of its own is refused, because only canonical execution answers one. So a same-name repository, registered, declared, middleware or separately loaded `Elicit` receives no grant and never runs, including the workflow host's own suspension replacement, which goes on answering the *authored* element in a run exactly as it did. An execution whose fragment never writes the element resolves nothing at all, which is why admitting the entry cannot break a document that only writes a `<File>`. `allow={["read"]}` still refuses it, because a read selection promises nobody will be interrupted. What stays contextual is the interaction and only the interaction: the pinned body asks through the Elicitation Api lexically in scope, so the REPL drawer answers a generated question and an enclosing `<Answers>` region answers it without anybody being asked. Its answer is retained by the ordinary `elicit` operation, and replay restores it without asking anyone. The `generated_xmd` record keeps the identity and the form and nothing about the answer. One defect the journey found is fixed here. The model owned nothing the packaged Plan did: an import's retained selection says where its scope's source came from, and for a component the host *declared* that is the retained origin and the retained bytes rather than a path, which the reader did not know. Every turn and question inside `Plan.md` therefore belonged to nothing, so a live screen quietly kept its last good model and a cold one refused the whole history. Both are read from the Journal — no declaration lookup, no file read, no fallback owner — and a source this prefix never admitted, or admitted twice, is still refused rather than attached to a guess. The program a Plan returns has no file at all, so a position gains a second source it can name. `SourcePosition` takes an optional `generatedSource`: the id the fragment was admitted under, which whole-fragment preflight stamps on every executable position in the candidate text it scans, before the fragment performs anything. A position names one source — a path, that id, or neither for dynamic text — and both together is malformed wherever a reader parses one. The member travels by value through the scanner, expansion snapshots and element sites, the durable source description, component-resolution copies and Workflow history. That identity is what owns the work inside a fragment. The effect names its fragment; journal order and coroutine ancestry only say whether the admission it names could be its — one that happened afterwards, or on work the effect is not part of, owns nothing however recently it ran, and ancestry is by coroutine segment, so `root.1` encloses `root.1.0` and has nothing to do with `root.10`. Two sequential fragments are sibling scopes even though their effects collide in name, line and column; a fragment's spawned descendants belong to it; concurrent siblings are independent of which settled first; and every way a history names no one fragment — never admitted, admitted only afterwards, admitted twice, admitted elsewhere, refused, unreadable, or naming no source at all — refuses whole, with no partial model. Evidence is `packages/cli/tests/repl-agent-journey.test.ts`, which drives `runReplProgram()` over a real Journal, a mounted Freedom tree, the real renderer and a terminal the suite writes bytes to. J1 walks the published Story: the real packaged Plan, its review in the REPL's own drawer, a refused revision that appends no answer and starts no turn, feedback resuming the same conversation, and an approval that admits the returned source byte for byte — then the generated program's two questions, the preview it showed, the one README it wrote after confirmation and the decline path that writes nothing. J2 runs three `<Spawn>` conversations and holds them complete, streaming and queued in one frame. J3 reruns that whole journey and reopens it in a fresh command scope — the Plan's scope, the program it returned, both retained turns, both reviews, both of the program's own questions, the README result and the same History positions — with zero provider calls and a byte-identical history, and restores a failed and a cancelled turn with the text each had. C1 is the command line, and X1 is EOF, a lost renderer, a lost terminal and a cancelled scope — each joining what it owned, appending nothing after, and giving the modes back once. One measured limit is reported rather than papered over: while a turn is still queued it has no provider conversation key yet, so the Sessions surface offers fewer selectors than there are children until it starts.
1 parent 4af3009 commit f7a1063

42 files changed

Lines changed: 4407 additions & 288 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎architecture.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5640,6 +5640,60 @@ that leaves no record for anything else to observe.
56405640
directory, identifier and filesystem operations; nothing under `repl/` names a
56415641
runtime.
56425642

5643+
### What one REPL command settles before it draws
5644+
5645+
The command line is read, the Agent configuration is settled, and then one
5646+
immutable profile is assembled in the command's own scope: the selected Plugins,
5647+
the Agent identity components, the packaged `<Plan>` declaration and the ordinary
5648+
evaluation ceiling, with the settled permission mode beside them. The program
5649+
takes that one profile and nothing else, so what an entry may resolve, what
5650+
ceiling a generated fragment runs under and how a permission request is answered
5651+
are facts about the command a person invoked rather than about the entry they
5652+
typed. The profile carries data and installations, never authority: no stack,
5653+
provider, Plan writer, live request or scope reaches the application model, the
5654+
route or the Journal through it.
5655+
5656+
The `<Plan>` the REPL declares is the packaged Component `xmd plan` runs, and the
5657+
ceiling around a returned program is the shared ordinary profile — whose write
5658+
table holds paired canonical `<Elicit>` beside `<File>` and `<File.Delete>`, so a
5659+
generated program may ask before it writes. That entry is a pinned capability
5660+
rather than a name the fragment resolves: preflight selects it where an
5661+
`<Elicit>` occurrence appears under a `write` selection, and the body it selects
5662+
is core's own `<Elicit>`, closed over before any document code runs. No component
5663+
name is resolved for it, so a same-name repository, registered, declared,
5664+
middleware or separately loaded definition inherits no grant and never runs, and
5665+
an execution that never writes the element resolves nothing. Only the interaction
5666+
is contextual: the pinned body asks through the Elicitation Api lexically in
5667+
scope, which is what lets the REPL drawer answer a generated question and an
5668+
`<Answers>` region answer it without anybody being asked.
5669+
5670+
Permission composes outermost-first: Core's own audit observer, then this
5671+
session's authoritative policy, then whatever the document and provider
5672+
installed, then the base denial. One private ledger per inherited Prompt scope
5673+
holds what was granted, and a retained audit is read rather than answered. The
5674+
live overlay, the application and the terminal have one owner each — the session,
5675+
the root transition boundary and the screen — and every ending cancels and joins
5676+
that owner rather than appending on its way out.
5677+
5678+
Ownership in the model is read from the Journal and from nothing else. An
5679+
import's retained selection says where its scope's source came from — a path for
5680+
a component read from somewhere, the retained origin for one the host declared —
5681+
and that origin is the path the effects inside it are recorded against. A
5682+
generated fragment has no file, so the work inside it names the admission it was
5683+
decided under, and the scope that admission created is what owns it: the
5684+
identity chooses the candidate, and journal order and coroutine ancestry only
5685+
say whether that candidate could be its owner — an admission that happened afterwards,
5686+
or on work the effect is not part of, owns nothing however recently it ran. Two
5687+
sequential fragments are therefore sibling scopes, work in a fragment's spawned
5688+
descendants belongs to that fragment, and concurrent siblings are independent of
5689+
which finished first. A record naming a source this prefix never admitted, one it
5690+
admitted twice, or two sources at once is refused rather than attached to a
5691+
guessed owner.
5692+
5693+
This command installs no foreground launcher, no browser elicitation and no
5694+
readline permission handling, reads no runtime global, and adds no durable record
5695+
family of its own: what it retains is the ordinary events any other run writes.
5696+
56435697
## Changing these rules
56445698

56455699
Spec, tests, and mechanics move together, in the same PR. If a workaround

‎packages/cli/src/agent-stack.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,19 @@ export function hostAcpDependencies(stack: PlanWriterStack): AcpxProviderDepende
163163
*
164164
* Nothing here starts an agent. The provider validates availability on first
165165
* use, and an embedded adapter reaches the disk at that same point.
166+
*
167+
* `acp` is the seam `planAgentContext` already takes, for the same reason and on
168+
* the same terms: production states none and gets what this host carries, while
169+
* a journey states a scriptable runtime so it can drive this exact provider
170+
* stack rather than a copy of it. It reaches the subprocess boundary and nothing
171+
* above it — the provider, the components, the policy and the record are the
172+
* product's own.
166173
*/
167-
export function* installAgentProviderStack(stack: AgentStack): Operation<void> {
168-
const acpx = createAcpxProvider(hostAcpDependencies(stack));
174+
export function* installAgentProviderStack(
175+
stack: AgentStack,
176+
acp?: AcpxProviderDependencies,
177+
): Operation<void> {
178+
const acpx = createAcpxProvider(acp ?? hostAcpDependencies(stack));
169179
yield* registerAgentProvider("acpx", acpx);
170180

171181
// The trusted host selects its own root provider by name. Document-level

‎packages/cli/src/cli.ts‎

Lines changed: 115 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ import {
107107
resolvePlanWriterStack,
108108
} from "./agent-stack.ts";
109109
import { planComponentDeclaration } from "./plan-component.ts";
110+
import { assembleReplProfile } from "./repl-profile.ts";
110111
import { planAgentContext } from "./plan-writer-profile.ts";
111112
import { useVerboseComponent } from "./verbose-component.ts";
112113
import type { AgentStack } from "./agent-stack.ts";
@@ -208,6 +209,41 @@ const SECRET_DETECTION_FIELD = {
208209
* a journal, a permission mode, an exec deadline or a presentation option would
209210
* each configure work this command never performs.
210211
*/
212+
/**
213+
* The Agent configuration two commands share.
214+
*
215+
* Declared once and spread into both, because `xmd run` and `xmd repl` configure
216+
* the same thing: which provider answers, which agent a `<Session>` means by
217+
* default, and how a permission request is decided. A second table would be two
218+
* descriptions of one option, free to drift in wording, default or precedence —
219+
* and a person reading either `--help` would have no way to tell which was true.
220+
*
221+
* `xmd test` refuses all five, because its agents are the deterministic
222+
* `<TestAgent>` stack, and `xmd plan` accepts only the two that say who writes.
223+
*/
224+
const agentFields = {
225+
agentProvider: {
226+
description: "agent provider for agent components",
227+
...field(z.string(), field.default("acpx")),
228+
},
229+
defaultAgent: {
230+
description: "default agent name (overrides DEFAULT_AGENT_NAME)",
231+
...field(z.string().optional()),
232+
},
233+
approveAll: {
234+
description: "approve every agent permission request",
235+
...field(z.boolean(), field.default(false)),
236+
},
237+
approveReads: {
238+
description: "approve read and search agent permissions, ask for the rest (default)",
239+
...field(z.boolean(), field.default(false)),
240+
},
241+
denyAll: {
242+
description: "deny every agent permission request",
243+
...field(z.boolean(), field.default(false)),
244+
},
245+
};
246+
211247
const executionFields = {
212248
include: {
213249
description: "component search directory",
@@ -227,14 +263,7 @@ const executionFields = {
227263
description: "output raw markdown without normalization or terminal formatting",
228264
...field(z.boolean(), field.default(false)),
229265
},
230-
agentProvider: {
231-
description: "agent provider for agent components",
232-
...field(z.string(), field.default("acpx")),
233-
},
234-
defaultAgent: {
235-
description: "default agent name (overrides DEFAULT_AGENT_NAME)",
236-
...field(z.string().optional()),
237-
},
266+
...agentFields,
238267
timeout: {
239268
description: "deadline for the whole run, as a duration (500ms, 30s, 5min)",
240269
...field(z.string().optional()),
@@ -247,18 +276,6 @@ const executionFields = {
247276
description: "default timeout for each fetch, as a duration (500ms, 30s, 5min)",
248277
...field(z.string().optional()),
249278
},
250-
approveAll: {
251-
description: "approve every agent permission request",
252-
...field(z.boolean(), field.default(false)),
253-
},
254-
approveReads: {
255-
description: "approve read and search agent permissions, ask for the rest (default)",
256-
...field(z.boolean(), field.default(false)),
257-
},
258-
denyAll: {
259-
description: "deny every agent permission request",
260-
...field(z.boolean(), field.default(false)),
261-
},
262279
secretDetection: SECRET_DETECTION_FIELD,
263280
};
264281

@@ -290,10 +307,12 @@ const REPL_DESCRIPTION = "Run and reconstruct one XMD entry in an interactive te
290307
* the command reopens exactly that retained history and selects exactly what the
291308
* location names; with none, it starts a fresh execution with an empty draft.
292309
*
293-
* No option a run configures appears here. This command renders no file, takes
294-
* no document reference and spends no model turn beyond what the one entry a
295-
* person types asks for, so a permission mode, an exec deadline, a props file
296-
* and a journal each configure work this command never performs.
310+
* The entry a person types may run Agent work, so this command configures the
311+
* Agent the same way `xmd run` does: the five shared fields, with the same
312+
* descriptions, defaults and environment precedence. Everything else a run
313+
* configures is absent — this command renders no file, takes no document
314+
* reference and writes no journal of its own, so an exec deadline, a props file
315+
* and a trace each configure work it never performs.
297316
*/
298317
const replConfig = object({
299318
location: {
@@ -302,6 +321,7 @@ const replConfig = object({
302321
"that retained history and the exact view it names",
303322
...field(z.string().optional(), cli.argument()),
304323
},
324+
...agentFields,
305325
});
306326

307327
/** What `xmd --help` says the plan command is for. */
@@ -588,21 +608,60 @@ export type ReplHostInstaller = () => Operation<void>;
588608
* ignored — a caller who wrote `--json` asked for something, and silence would
589609
* let them believe they got it.
590610
*/
611+
/** The two REPL options that carry a value, by the spelling a caller writes. */
612+
const REPL_VALUES: readonly string[] = ["--agent-provider", "--default-agent"];
613+
614+
/** The three REPL switches, which carry none. */
615+
const REPL_SWITCHES: readonly string[] = ["--approve-all", "--approve-reads", "--deny-all"];
616+
591617
export function replGrammarError(
592618
args: readonly string[],
593619
location: string | undefined,
594620
): string | undefined {
595621
// The command's own name is the first token, as it is for every command that
596622
// reads its line directly.
597623
const rest = args.slice(1);
598-
const option = rest.find((token) => token.startsWith("-") && token !== "-");
599-
if (option !== undefined) {
624+
const positional: string[] = [];
625+
for (let at = 0; at < rest.length; at += 1) {
626+
const token = rest[at] ?? "";
627+
if (!token.startsWith("-") || token === "-") {
628+
positional.push(token);
629+
continue;
630+
}
631+
// `--name=value` and `--name value` are both the parser's forms, so the scan
632+
// reads the name the same way the parser will.
633+
const split = token.indexOf("=");
634+
const name = split === -1 ? token : token.slice(0, split);
635+
const written = split === -1 ? undefined : token.slice(split + 1);
636+
if (REPL_SWITCHES.includes(name)) {
637+
if (written !== undefined) {
638+
return `xmd repl: ${name} is a switch and takes no value`;
639+
}
640+
continue;
641+
}
642+
if (REPL_VALUES.includes(name)) {
643+
if (written !== undefined) {
644+
if (written.length === 0) {
645+
return `xmd repl: ${name} requires a value`;
646+
}
647+
continue;
648+
}
649+
// The next token is this option's value, not a location: a scan that
650+
// counted it as one would refuse `--default-agent claude` for naming two
651+
// things.
652+
const value = rest[at + 1];
653+
if (value === undefined || value.startsWith("-")) {
654+
return `xmd repl: ${name} requires a value`;
655+
}
656+
at += 1;
657+
continue;
658+
}
600659
return (
601-
`unrecognized option for xmd repl: ${option} — xmd repl takes one optional location ` +
602-
"and no options"
660+
`unrecognized option for xmd repl: ${name} — xmd repl takes one optional location and ` +
661+
"the agent options --agent-provider, --default-agent, --approve-all, --approve-reads " +
662+
"and --deny-all"
603663
);
604664
}
605-
const positional = rest.filter((token) => !token.startsWith("-"));
606665
if (positional.length > 1) {
607666
return (
608667
"xmd repl takes at most one location. This REPL admits one entry per execution, so " +
@@ -2835,17 +2894,41 @@ function* dispatch(
28352894
yield* exit(1);
28362895
break;
28372896
}
2897+
// The Agent configuration, settled before a terminal exists: mutual
2898+
// exclusion, an unknown provider and `DEFAULT_AGENT_NAME` precedence are
2899+
// all decided here, so an invocation nobody could run refuses without
2900+
// having taken the screen, made a directory or materialized an adapter.
2901+
const replStack = yield* settleAgentStack(
2902+
{
2903+
agentProvider: command.config.agentProvider,
2904+
defaultAgent: command.config.defaultAgent,
2905+
approveAll: command.config.approveAll,
2906+
approveReads: command.config.approveReads,
2907+
denyAll: command.config.denyAll,
2908+
},
2909+
sessions,
2910+
);
2911+
if (replStack === undefined) {
2912+
break;
2913+
}
28382914
if (installRepl === undefined) {
28392915
console.error(
28402916
"xmd repl: this host assembles no interactive terminal, so there is nothing to open.",
28412917
);
28422918
yield* exit(1);
28432919
break;
28442920
}
2921+
// One profile for the whole command, assembled once in this scope: the
2922+
// packaged `<Plan>` Component, the selected Plugins, the Agent identity
2923+
// vocabulary and the ceiling a generated fragment runs under. Nothing is
2924+
// assembled again per entry, so two entries of one session cannot run
2925+
// under different rules.
2926+
const profile = yield* assembleReplProfile(replStack, plugins);
28452927
yield* installRepl();
2846-
const ran = yield* runReplProgram(
2847-
command.config.location === undefined ? {} : { location: command.config.location },
2848-
);
2928+
const ran = yield* runReplProgram({
2929+
profile,
2930+
...(command.config.location === undefined ? {} : { location: command.config.location }),
2931+
});
28492932
if (!ran.ok) {
28502933
console.error(`xmd repl: ${ran.error.message}`);
28512934
yield* exit(1);

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,16 @@
99
* ## The two tables
1010
*
1111
* `read` is core's self-closing `<File />`, its self-closing `<Glob />` and
12-
* canonical `<Syntax />`. `write` is core's paired `<File>…</File>` and
13-
* self-closing `<File.Delete />`. A fragment run by `xmd run` therefore reaches
14-
* the caller's own filesystem through the Files provider this command
15-
* installed, and reaches nothing else at all: no network read, no process, no
16-
* repository, no Git, no credential and no agent.
12+
* canonical `<Syntax />`. `write` is core's paired `<File>…</File>`, its
13+
* self-closing `<File.Delete />` and paired canonical `<Elicit>`: a fragment
14+
* that may change something may also ask the person first, which is what makes
15+
* "preview this, then confirm it" a program an Agent can write. A `read`
16+
* selection admits no question — it promises nobody will be interrupted.
17+
*
18+
* A fragment run by `xmd run` therefore reaches the caller's own filesystem
19+
* through the Files provider this command installed, and the person through the
20+
* Elicitation provider the run already has. It reaches nothing else at all: no
21+
* network read, no process, no repository, no Git, no credential and no agent.
1722
*
1823
* Reading and writing stay separate spellings of one name. A selection of
1924
* `read` admits `<File />` and not `<File>…</File>`, so a fragment that asks to
@@ -40,6 +45,7 @@
4045
*/
4146

4247
import {
48+
elicitWriteEntry,
4349
fileDeleteEntry,
4450
fileReadEntry,
4551
fileWriteEntry,
@@ -92,7 +98,7 @@ function ordinaryFiles(): FragmentFileAccess {
9298
export function ordinaryEvaluationProfile(): FragmentEvaluationInput {
9399
return {
94100
read: [fileReadEntry(), globReadEntry(), syntaxReadEntry()],
95-
write: [fileWriteEntry(), fileDeleteEntry()],
101+
write: [fileWriteEntry(), fileDeleteEntry(), elicitWriteEntry()],
96102
files: ordinaryFiles(),
97103
};
98104
}

‎packages/cli/src/plugin-selection.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ const COMMANDS: ReadonlySet<string> = new Set([
2525
"syntax",
2626
"upgrade",
2727
"workflow",
28+
// `repl` runs a document, so a Plugin has to be told it is the command that
29+
// did. Left out, a REPL invocation normalizes to `run` and its own name
30+
// arrives as a positional — which tells every Plugin that something it was
31+
// written for is happening when it is not, and tells none of them that the
32+
// REPL is.
33+
"repl",
2834
]);
2935

3036
/**

0 commit comments

Comments
 (0)