Skip to content

Commit 67faff9

Browse files
committed
✨ Run and resume one REPL execution
Slice B of #848: the execution kernel. An injected host can create or open one retained execution, submit the reference entry, run it with the ordinary core runtime, watch immutable Journal-derived models beside explicit live overlays, pause and continue expansion, answer one question, and cold-reopen the same history through ordinary replay. There is no component tree, no terminal and no command; this is the layer between the Journal and whatever draws it. `journal.ts` is the storage design in full: one append-only NDJSON file of `serializeDurableEvent` records and nothing else — no manifest, no projected model, no cache, no checkpoint index, no sidecar. Reading is hostile: every line goes through `parseDurableEvent`, a file whose last record has no terminating newline is a write that did not finish, a target that is not a regular file is refused before it is read, and no refusal quotes what the file held. Creation is exclusive, because a name already taken is somebody else's history and appending to it would join two executions into one. Writing stays single-writer, which is the `DurableStream` contract rather than a claim this feature strengthens. Nothing in the kernel chooses a runtime. Reading, existence, kind and directory creation are `@effectionx/fs` operations; the two this repository's portable layer does not offer — creating a name exclusively and appending to it — cross the contextual host boundary instead, and the storage root arrives as an argument rather than being found in a home directory or an environment. `session.ts` runs both directions through one path. A fresh session validates the submitted document against the environment the run would use, so an entry that cannot run leaves the history empty and the draft editable rather than admitting an entry whose only history is its own failure. A cold session parses, projects and replays in a scope the caller can drop, and hands back nothing until admission — the execution settling, the first new record reaching the file, or the first question reaching this process. Before that point a divergence, a stale answer or a malformed record is a refusal with no append and no provider call; after it, a failure is an outcome the transcript shows. The append observer has the session's lifetime. Its removal is registered before the callback is published and clears only the callback this session installed, because the stream outlives the session watching it — a repository hands the same one to whoever opens the execution next — and a callback left behind would reproject into, and signal, a session whose scope is gone. Live output is consumed as it arrives inside that same scope: an overlay that filled in at close would be showing what the document rendered, but never *so far*. `expansion.ts` pauses XMD expansion without cancelling anything, over ordinary middleware and with no new core primitive. Three operations bracket a walk today and a fourth is published for a host that declares structural syntax; eight steps inside a walk are gates, `DocumentOutput.output` among them, which is what covers prose. A walk is satisfied when it holds a continuation or all of its active children are satisfied, and expansion is paused when every active walk is. A hold is a suspended `action()`, so teardown unwinds through it and releases nothing, and Continue resolves each current hold once and re-runs nothing. The boundary partition is three declared lists per wrapped Api — walks, gates, and the members deliberately neither — so a member core adds later belongs to no list and the inventory says so. `elicitation.ts` presents one question shape and refuses anything else as an `ElicitationProviderError` before a value is yielded. A choice the form does not offer is an incomplete interaction, not a rejected answer: the request stays open and nothing appends. A value the schema rejects is the other case, and core records it as a durable `err`. The reference entry now displays its generated source before the fragment is admitted, which is what makes that order observable rather than inferred. X2 counts the work a run performs where performing it happens — the component source read and the eval compilation, not the durable records that replay restores — with a positive control so a counter that never moves cannot read as proof of replay. Four review corrections. Everything a session owns — its append observer, its execution task, its output consumer and its question watcher — now lives in one provisional scope built as a child of the caller's. An accepted session is torn down with its owner; a refused reconstruction is torn down *before* the refusal is returned, because a refused cold open that left a live observer behind would keep reprojecting into a session nobody was ever given. The Continue capability is exposed only by the process that owns holds. `session.expansion` stays readable everywhere, because any surface may show that expansion is paused; `session.controller` is absent — not a controller whose Continue does nothing — for a settled history replay restored whole, an execution with no entry, and a run that has finished. P1 now exercises the distinction the mode name rests on: a question is work that has already started, so a pause requested while one is pending cannot take effect until it settles. Its record reaches the Journal while the request is outstanding, and only then does expansion report paused and stop moving. The corrupt-history control counts provider entry rather than assuming it, with a positive control for every counter the negatives rely on — a count that could never increment would otherwise read as proof of replay.
1 parent 970bc0d commit 67faff9

8 files changed

Lines changed: 2135 additions & 2 deletions

File tree

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/**
2+
* How this REPL asks the person sitting in front of it.
3+
*
4+
* A provider and nothing more. The document says what it is asking and what
5+
* shape the answer must have; this decides where the asking happens, publishes
6+
* the request so the application can draw it, and waits. Core normalized the
7+
* schema, core validates what comes back, and core alone appends the answer —
8+
* so a question this provider could not present never becomes a half-answered
9+
* record.
10+
*
11+
* ## One form, stated as a refusal
12+
*
13+
* This slice presents exactly one shape: a closed object with one required
14+
* string property whose values are an enum. Anything else is refused as an
15+
* `ElicitationProviderError` *before* a value is yielded, because a provider
16+
* that quietly rendered a schema it does not understand would collect an answer
17+
* to a question nobody was shown. Refusing names the shape it can present, so
18+
* the limit is legible rather than mysterious — and it is a limit rather than a
19+
* general JSON Schema form toolkit, deliberately.
20+
*
21+
* ## Nothing here is durable
22+
*
23+
* No provider state, form state, focus or presentation reaches the Journal. A
24+
* pending request lives exactly as long as the suspended `action()` holding it:
25+
* if the run is halted the request disappears with it and no answer is
26+
* manufactured. Closing the drawer is a presentation decision and leaves the
27+
* request waiting; only submitting a value answers it.
28+
*/
29+
30+
import { action, createSignal } from "effection";
31+
import type { Operation, Stream } from "effection";
32+
import { Elicitation, ElicitationProviderError } from "@executablemd/core";
33+
import type { ElicitationRequest } from "@executablemd/core";
34+
import type { Json } from "@executablemd/durable-streams";
35+
36+
/** The one question shape this REPL presents: one field, one list of choices. */
37+
export interface ReplQuestionForm {
38+
readonly field: string;
39+
readonly choices: readonly string[];
40+
}
41+
42+
/** One question waiting for an answer in this process. */
43+
export interface ReplQuestion {
44+
readonly message: string;
45+
readonly schema: Json;
46+
readonly form: ReplQuestionForm;
47+
/**
48+
* Submit one of the offered choices.
49+
*
50+
* A choice the form does not offer is not an answer: the request stays open
51+
* and nothing is appended, which is what keeps a stray keystroke from binding
52+
* a value the schema would then reject.
53+
*/
54+
answer(choice: string): boolean;
55+
}
56+
57+
/** What the application reads to draw the question, and to know there is one. */
58+
export interface ReplElicitations {
59+
/** The question waiting right now, or none. */
60+
readonly pending: ReplQuestion | undefined;
61+
/** Every change to what is pending, as it changes. */
62+
readonly changes: Stream<ReplQuestion | undefined, never>;
63+
/** How many questions this provider has been asked. */
64+
readonly asked: number;
65+
}
66+
67+
/**
68+
* The form one normalized schema describes, or none when this REPL cannot
69+
* present it.
70+
*
71+
* Read from the normalized schema core compiled rather than from the source
72+
* that produced it: what the person is shown has to be what the answer will be
73+
* judged against.
74+
*/
75+
export function readQuestionForm(schema: Json): ReplQuestionForm | undefined {
76+
if (!isObject(schema) || schema["type"] !== "object") {
77+
return undefined;
78+
}
79+
if (schema["additionalProperties"] !== false) {
80+
return undefined;
81+
}
82+
const properties = schema["properties"];
83+
const required = schema["required"];
84+
if (!isObject(properties) || !Array.isArray(required) || required.length !== 1) {
85+
return undefined;
86+
}
87+
const names = Object.keys(properties);
88+
const field = required[0];
89+
if (names.length !== 1 || typeof field !== "string" || names[0] !== field) {
90+
return undefined;
91+
}
92+
const property = properties[field];
93+
if (!isObject(property) || property["type"] !== "string") {
94+
return undefined;
95+
}
96+
const choices = property["enum"];
97+
if (!Array.isArray(choices) || choices.length === 0) {
98+
return undefined;
99+
}
100+
const offered: string[] = [];
101+
for (const choice of choices) {
102+
if (typeof choice !== "string") {
103+
return undefined;
104+
}
105+
offered.push(choice);
106+
}
107+
return { field, choices: Object.freeze(offered) };
108+
}
109+
110+
/**
111+
* Install this REPL's provider on the calling scope.
112+
*
113+
* At `{ at: "min" }`: middleware installed at the default position runs
114+
* outermost, so an outer provider would answer ahead of this one — the opposite
115+
* of what a provider is.
116+
*/
117+
export function* useReplElicitation(): Operation<ReplElicitations> {
118+
const changes = createSignal<ReplQuestion | undefined, never>();
119+
let pending: ReplQuestion | undefined;
120+
let asked = 0;
121+
122+
function publish(question: ReplQuestion | undefined): void {
123+
pending = question;
124+
changes.send(question);
125+
}
126+
127+
yield* Elicitation.around(
128+
{
129+
*elicit([request]: [ElicitationRequest]) {
130+
const form = readQuestionForm(request.schema);
131+
if (form === undefined) {
132+
throw new ElicitationProviderError(
133+
"this REPL presents one question shape: an object with one required string " +
134+
"property whose values are an enum, and no other properties. The document asked " +
135+
"for something else, so nobody was asked.",
136+
);
137+
}
138+
asked++;
139+
return yield* action<Json>(function (resolve) {
140+
const question: ReplQuestion = {
141+
message: request.message,
142+
schema: request.schema,
143+
form,
144+
answer(choice: string): boolean {
145+
if (!form.choices.includes(choice)) {
146+
return false;
147+
}
148+
resolve({ [form.field]: choice });
149+
return true;
150+
},
151+
};
152+
publish(question);
153+
// Whatever ends this — an answer, a halt, a failure upstream — the
154+
// request stops being pending exactly when it stops existing.
155+
return () => publish(undefined);
156+
});
157+
},
158+
},
159+
{ at: "min" },
160+
);
161+
162+
return {
163+
get pending() {
164+
return pending;
165+
},
166+
changes,
167+
get asked() {
168+
return asked;
169+
},
170+
};
171+
}
172+
173+
function isObject(value: Json | undefined): value is { [key: string]: Json } {
174+
return value !== null && typeof value === "object" && !Array.isArray(value);
175+
}

0 commit comments

Comments
 (0)