Skip to content

Commit d0e6a57

Browse files
authored
Merge pull request #281 from taras/feat/retire-expand-hook
✨ Move <Answers> and <WhenPrompt> off the expansion hook (#202, part A of two)
2 parents 3fe0120 + 478d43f commit d0e6a57

19 files changed

Lines changed: 1564 additions & 790 deletions

‎packages/core/src/answers.ts‎

Lines changed: 20 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,17 @@
2525
*
2626
* ## Why these are structural rather than registered
2727
*
28-
* A registered function component sees `content()` — rendered text. Matchers
29-
* are structure: `value` is an expression prop, `template` is a prop-or-children
30-
* pair, and each needs its own position for diagnostics. Only the expansion hook
31-
* hands over the element itself, which is why `<Test>` and `<WhenPrompt>` are
32-
* claimed the same way. Being claimed means being reserved: a repository file
33-
* named `Answers.md` never stands in, and it could not implement matcher
34-
* semantics if it did.
28+
* A function component sees `content()` — rendered text. Matchers are
29+
* structure: `value` is an expression prop, `template` is a prop-or-children
30+
* pair, and each needs its own position for diagnostics, and only the element
31+
* itself carries those. That is why these are structural rather than
32+
* components: being reserved means a repository file named `Answers.md` never
33+
* stands in, and it could not implement matcher semantics if it did.
3534
*
36-
* Partitioning before expanding is what the hook buys. Matchers are collected
37-
* from the whole child list first, so where an `<Answer>` is written does not
38-
* decide what it can answer; and "an `<Answers>` with no body" is a structural
39-
* fact rather than a guess from empty rendered text.
35+
* Partitioning before expanding is what the structural dispatch buys. Matchers
36+
* are collected from the whole child list first, so where an `<Answer>` is
37+
* written does not decide what it can answer; and "an `<Answers>` with no body"
38+
* is a structural fact rather than a guess from empty rendered text.
4039
*
4140
* ## Selection
4241
*
@@ -65,15 +64,15 @@
6564
import { scoped } from "effection";
6665
import type { Operation } from "effection";
6766

68-
import { Component, env, expandSegments, raise } from "./component-api.ts";
67+
import { env, expandSegments, raise } from "./component-api.ts";
6968
import { renderSegments } from "./render.ts";
7069
import { evaluateExpression } from "./expand.ts";
7170
import { Elicitation } from "./elicitation-api.ts";
7271
import type { ElicitationRequest } from "./elicitation-api.ts";
7372
import { JsonParseError, parseJson } from "./json.ts";
7473
import { matchPrompt, parseTemplate } from "./template.ts";
7574
import type { ParsedTemplate } from "./template.ts";
76-
import type { ComponentElement, ComponentHandling, ErrorSegment, Json, Segment } from "./types.ts";
75+
import type { ComponentElement, ErrorSegment, Json, Segment } from "./types.ts";
7776

7877
const ANSWERS = "Answers";
7978
const ANSWER = "Answer";
@@ -106,44 +105,17 @@ function isBlankText(segment: Segment): boolean {
106105
return segment.type === "text" && segment.content.trim() === "";
107106
}
108107

109-
/**
110-
* Install the handler for both constructs.
111-
*
112-
* Offered every element, it claims only these two names and delegates the rest,
113-
* so it composes with any other expansion support a host has installed.
114-
*/
115-
export function installAnswers(): Operation<void> {
116-
return Component.around(
117-
{
118-
*expand([element], next) {
119-
if (element.name === ANSWERS) {
120-
return { segments: yield* expandAnswers(element) };
121-
}
122-
if (element.name === ANSWER) {
123-
// Reaching here means no enclosing `<Answers>` consumed it: a
124-
// well-placed matcher is partitioned out and never expanded on its
125-
// own. Same shape as `<Else>` outside `<If>`.
126-
return {
127-
segments: [
128-
yield* raise(
129-
configError(
130-
ANSWER,
131-
"must be a direct child of <Answers>. It is reserved: it never resolves a " +
132-
"component, and only the <Answers> it belongs to can read it.",
133-
element,
134-
),
135-
),
136-
],
137-
};
138-
}
139-
return yield* next(element);
140-
},
141-
},
142-
{ at: "min" },
108+
/** A `<Answer>` written outside the `<Answers>` that would have read it. */
109+
export function strayAnswerError(element: ComponentElement): ErrorSegment {
110+
return configError(
111+
ANSWER,
112+
"must be a direct child of <Answers>. It is reserved: it never resolves a " +
113+
"component, and only the <Answers> it belongs to can read it.",
114+
element,
143115
);
144116
}
145117

146-
function* expandAnswers(element: ComponentElement): Operation<Segment[]> {
118+
export function* expandAnswers(element: ComponentElement): Operation<Segment[]> {
147119
for (const name of Object.keys({ ...element.props, ...element.expressions })) {
148120
if (name !== "delegate") {
149121
return [

‎packages/core/src/execute.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import {
2222
import { exec, readTextFile, cwd } from "@executablemd/runtime";
2323
import { cwd as processCwd } from "@effectionx/fs";
2424
import type { Workflow, Json } from "@executablemd/durable-streams";
25-
import { installAnswers } from "./answers.ts";
2625
import { createReplayStream } from "./replay-stream.ts";
2726
import type {
2827
ComponentDefinition,
@@ -539,12 +538,6 @@ function* executeDocument(options: ExecuteOptions): Operation<DocumentExecution>
539538
{ at: "min" },
540539
);
541540

542-
// `<Answers>`/`<Answer>` are structural, and a structural construct that
543-
// needs its children as elements is claimed through this hook rather than
544-
// handled in the expansion switch. Installed after the providers above so
545-
// it sits nearest the expansion it claims for.
546-
yield* installAnswers();
547-
548541
const { output, value } = yield* durableRun(() => Execution.operations.document(props), {
549542
stream,
550543
});

‎packages/core/src/expand.ts‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import { SchemaValidationError, validateProps, validateReturnValue } from "./val
6767
import { parseJson } from "./json.ts";
6868
import { healSegment } from "./heal.ts";
6969
import { scanSegments } from "./scanner.ts";
70+
import { expandAnswers, strayAnswerError } from "./answers.ts";
7071
import { RESERVED_STRUCTURAL } from "./structural.ts";
7172
import { renderSegments } from "./render.ts";
7273
import { remark } from "remark";
@@ -149,25 +150,45 @@ function* rejectRetain(): Operation<never> {
149150
* interpolation inputs, hide set, and block counter — bound for exactly the
150151
* length of the offer. A claiming handler reaches it through
151152
* `Component.expandSegments`; a nested claim replaces the binding for its own
152-
* offer and restores this one. Nothing else in expansion sees a frame, so a
153-
* code block or modifier running between elements finds none active.
153+
* offer and restores this one.
154154
*/
155-
function* offerElement(
155+
function offerElement(
156156
element: ComponentElement,
157157
parentMeta: Record<string, unknown>,
158158
parentProps: Record<string, Json>,
159159
hideSet: Set<string>,
160160
counter: BlockCounter,
161161
): Operation<ComponentHandling | undefined> {
162+
return withExpansionFrame(parentMeta, parentProps, hideSet, counter, () =>
163+
Component.operations.expand(element),
164+
);
165+
}
166+
167+
/**
168+
* Bind this expansion's recursion for the length of `body`.
169+
*
170+
* Two callers need it. An offer publishes it for a claiming handler, and a
171+
* structural construct that renders segments of its own — `<Answers>` — reaches
172+
* them through the Api form of `expandSegments` rather than this module's
173+
* function. Nothing else in expansion binds one, so a code block or modifier
174+
* running between elements finds none active.
175+
*/
176+
function* withExpansionFrame<T>(
177+
parentMeta: Record<string, unknown>,
178+
parentProps: Record<string, Json>,
179+
hideSet: Set<string>,
180+
counter: BlockCounter,
181+
body: () => Operation<T>,
182+
): Operation<T> {
162183
const scope = yield* useScope();
163-
const enclosingFrame = scope.get(ExpansionFrame);
184+
const enclosing = scope.get(ExpansionFrame);
164185
scope.set(ExpansionFrame, (inner: Segment[]) =>
165186
expandSegments(inner, parentMeta, parentProps, hideSet, counter),
166187
);
167188
try {
168-
return yield* Component.operations.expand(element);
189+
return yield* body();
169190
} finally {
170-
scope.set(ExpansionFrame, enclosingFrame);
191+
scope.set(ExpansionFrame, enclosing);
171192
}
172193
}
173194

@@ -624,6 +645,28 @@ export function* expandSegments(
624645
break;
625646
}
626647

648+
if (segment.name === "Answers") {
649+
// No raise() here, like the branches above: expandAnswers reports the
650+
// errors it creates, and the selected answer settled its own (§6.9).
651+
// It renders the answer it chose through the Api form of
652+
// `expandSegments`, so it needs this frame — the same one the
653+
// retired claim hook used to publish for a handler.
654+
result.push(
655+
...(yield* withExpansionFrame(parentMeta, parentProps, hideSet, counter, () =>
656+
expandAnswers(segment),
657+
)),
658+
);
659+
break;
660+
}
661+
662+
if (segment.name === "Answer") {
663+
// A well-placed <Answer> is partitioned out by its <Answers> and never
664+
// expanded on its own. Reaching here means it sits outside one, so it
665+
// names no component — the same shape as a stray <Else>.
666+
result.push(yield* raise(strayAnswerError(segment)));
667+
break;
668+
}
669+
627670
if (segment.name === "Break") {
628671
result.push(...(yield* expandBreak(segment, loop)));
629672
break;

‎packages/core/tests/agent-stack.test.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { randomUUID } from "node:crypto";
1616
import * as path from "node:path";
1717
import * as os from "node:os";
1818
import { execute } from "../src/execute.ts";
19-
import { Component } from "../src/component-api.ts";
19+
import { registerComponents } from "../src/components/registration.ts";
2020
import { Agent } from "../src/agent/agent-api.ts";
2121
import type { PermissionOutcome, PermissionRequest } from "../src/agent/agent-api.ts";
2222
import { AgentProviders, registerAgentProvider } from "../src/agent/provider-api.ts";
@@ -108,16 +108,22 @@ function* decide(kind?: string): Operation<PermissionOutcome> {
108108
* outside a component body.
109109
*/
110110
function* installAskComponent(outcomes: string[]): Operation<void> {
111-
yield* Component.around({
112-
*expand([element], next) {
113-
if (element.name === "Ask") {
111+
// Registered, not an importComponent stub: execute() installs its own
112+
// terminal importComponent provider at { at: "min" } that does not delegate,
113+
// so an outer stub never sees the name. The middleware seam is only for tests
114+
// driving expandSegments directly.
115+
yield* registerComponents([
116+
{
117+
name: "Ask",
118+
origin: "test",
119+
props: { type: "object", properties: {}, additionalProperties: false },
120+
*fn() {
114121
const outcome = yield* decide();
115122
outcomes.push(outcome.outcome === "selected" ? outcome.optionId : "cancelled");
116-
return { segments: [] };
117-
}
118-
return yield* next(element);
123+
return "";
124+
},
119125
},
120-
});
126+
]);
121127
}
122128

123129
describe("Tier AG — provider registry and permission policies", () => {

‎packages/core/tests/answers-component.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { collect } from "../src/collect.ts";
2929
import { Elicitation } from "../src/elicitation-api.ts";
3030
import type { ElicitationRequest } from "../src/elicitation-api.ts";
3131
import { execute } from "../src/execute.ts";
32+
import { ComponentRegistrationError, registerComponents } from "../src/components/registration.ts";
3233
import { useTempFileCompiler } from "../src/temp-file-compiler.ts";
3334

3435
const SCHEMA =
@@ -838,6 +839,96 @@ describe("Answers: configuration diagnostics", () => {
838839
});
839840
});
840841

842+
describe("Answers: reservation", () => {
843+
/**
844+
* Repository files named after both constructs, in the directory `run()`
845+
* searches — so the only thing keeping them out of the document is the names
846+
* being reserved (§5.3).
847+
*
848+
* Each body renders a marker and answers nothing. That makes standing in
849+
* observable from two directions at once: the marker reaches the output, and
850+
* the elicitation the region was supposed to answer goes unanswered.
851+
*/
852+
function* writeStandIns(workspace: string): Operation<void> {
853+
yield* ensureDir(workspace);
854+
yield* writeTextFile(join(workspace, "Answers.md"), "REPOSITORY_ANSWERS\n");
855+
yield* writeTextFile(join(workspace, "Answer.md"), "REPOSITORY_ANSWER\n");
856+
}
857+
858+
it("does not let a repository Answers.md stand in for the construct", function* () {
859+
const workspace = yield* useWorkspace();
860+
yield* writeStandIns(workspace);
861+
862+
const result = yield* run(
863+
workspace,
864+
SCHEMA_BLOCK +
865+
[
866+
"<Answers>",
867+
'<Answer template="Approve?" value={{ decision: "supplied" }} />',
868+
"",
869+
elicits("v", "Approve?"),
870+
"",
871+
"Got: {v.decision}",
872+
"</Answers>",
873+
"",
874+
].join("\n"),
875+
);
876+
877+
expect(result.failure).toBe(undefined);
878+
expect(result.output).toContain("Got: supplied");
879+
expect(result.output).not.toContain("REPOSITORY_ANSWERS");
880+
expect(result.output).not.toContain("REPOSITORY_ANSWER");
881+
});
882+
883+
/**
884+
* Membership in the reserved set, which nothing above reaches.
885+
*
886+
* Keeping a repository file out is the expansion loop's doing — it dispatches
887+
* both names before resolution runs, and would go on doing so if they were
888+
* dropped from the set. What the set uniquely decides is that a *registration*
889+
* cannot claim either name, so this is the assertion that fails if they are.
890+
*/
891+
it("refuses a registration for either name", function* () {
892+
for (const name of ["Answers", "Answer"]) {
893+
let thrown: unknown;
894+
try {
895+
yield* scoped(() =>
896+
registerComponents([
897+
{
898+
name,
899+
origin: "a-host",
900+
// deno-lint-ignore require-yield
901+
*fn() {
902+
return "";
903+
},
904+
props: { type: "object", properties: {}, additionalProperties: false },
905+
},
906+
]),
907+
);
908+
} catch (error) {
909+
thrown = error;
910+
}
911+
expect(thrown).toBeInstanceOf(ComponentRegistrationError);
912+
expect(thrown instanceof Error ? thrown.message : "").toContain("structural syntax");
913+
}
914+
});
915+
916+
it("does not let a repository Answer.md rescue a stray matcher", function* () {
917+
const workspace = yield* useWorkspace();
918+
yield* writeStandIns(workspace);
919+
920+
const result = yield* run(
921+
workspace,
922+
'<Answer template="Approve?" value={{ decision: "a" }} />\n',
923+
);
924+
925+
// A reserved name resolves to nothing else wherever it is written, so the
926+
// misplacement is still a diagnostic rather than a component that renders.
927+
expect(diagnostics(result)).toContain("<Answer> must be a direct child of <Answers>");
928+
expect(result.output).not.toContain("REPOSITORY_ANSWER");
929+
});
930+
});
931+
841932
describe("Answers: durability", () => {
842933
/**
843934
* A replayed elicitation never reaches a provider, so matchers see nothing.

0 commit comments

Comments
 (0)