Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat(plan): the complete bill of needs before anything is paid for

kashorin95995555b1c5
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 2c5f1b78..fb0d3002 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -11,6 +11,9 @@
"@hypit/build-result": "workspace:*",
"@hypit/build-result-kit": "workspace:*",
"@hypit/compiler-node": "workspace:*",
+ "@hypit/component-kit": "workspace:*",
+ "@hypit/core": "workspace:*",
+ "@hypit/driver-node": "workspace:*",
"@hypit/elaborator": "workspace:*",
"@hypit/package-loader-node": "workspace:*",
"@hypit/protocol": "workspace:*",
@@ -18,6 +21,7 @@
"@hypit/runtime": "workspace:*",
"@hypit/runtime-host-node": "workspace:*",
"@hypit/source": "workspace:*",
+ "@hypit/validation": "workspace:*",
"@hypit/workspace": "workspace:*",
"typescript": "5.9.3"
},
diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.ts
index 2e1c38d4..c4d55bf8 100644
--- a/packages/cli/src/build-planning.ts
+++ b/packages/cli/src/build-planning.ts
@@ -86,3 +86,222 @@ export function assertPreflight(preflight: Awaited<ReturnType<typeof preflightPl
"No Build was submitted and no external capability request was made.",
].join("\n"));
}
+
+// ---------------------------------------------------------------------------------------------------
+// The complete bill of needs: every request the Build will make, with its parameters known before
+// anything is paid for.
+
+import { BuildMachine } from "@hypit/core";
+import { registerProducerFacets, registerTypeValidatorFacets } from "@hypit/component-kit";
+import { EndpointRegistry, MemoryResourceStore, NodeDriver, ProducerRegistry } from "@hypit/driver-node";
+import type { NodePackageContribution } from "@hypit/package-loader-node";
+import type { BuildDefinition, CanonicalValue } from "@hypit/protocol";
+import { TypeValidatorRegistry } from "@hypit/validation";
+
+/** A reading of one request's parameters, taken from the values the request actually carries. */
+export type NeedSummary = {
+ /** Scalar parameters by their own names: numbers, short strings, booleans, and `N words` for prose. */
+ readonly fields: Readonly<Record<string, string | number | boolean>>;
+ /** Referenced media counted by kind (image, video, audio, other). */
+ readonly references: Readonly<Record<string, number>>;
+};
+
+export type PlanNeedView = {
+ readonly step: string;
+ readonly port: string;
+ readonly capability: string;
+ readonly endpoint?: string;
+ /** Present when the request's parameters were computed at plan time. */
+ readonly summary?: NeedSummary;
+ /** Why the parameters are not known yet, when they are not. */
+ readonly unknown?: string;
+};
+
+function mediaKind(mediaType: string): string {
+ const prefix = mediaType.split("/")[0] ?? "";
+ return prefix === "image" || prefix === "video" || prefix === "audio" ? prefix : "other";
+}
+
+function countReferences(value: CanonicalValue, references: Record<string, number>): void {
+ if (value === null || typeof value !== "object") return;
+ if (Array.isArray(value)) {
+ for (const item of value) countReferences(item, references);
+ return;
+ }
+ const record = value as Record<string, CanonicalValue>;
+ if (typeof record.resource === "string" && typeof record.mediaType === "string") {
+ const kind = mediaKind(record.mediaType);
+ references[kind] = (references[kind] ?? 0) + 1;
+ return;
+ }
+ for (const item of Object.values(record)) countReferences(item, references);
+}
+
+function scalarSummary(value: CanonicalValue): string | number | boolean | undefined {
+ if (typeof value === "number" || typeof value === "boolean") return value;
+ if (typeof value === "string") {
+ const words = value.trim().split(/\s+/u).filter((word) => word.length > 0).length;
+ return value.length <= 40 && !value.includes("\n") ? value : `${words} words`;
+ }
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
+ const record = value as Record<string, CanonicalValue>;
+ if (typeof record.text === "string" && Object.keys(record).length <= 2) return scalarSummary(record.text);
+ }
+ return undefined;
+}
+
+/**
+ * Read a request's parameters off the request itself: every scalar it carries under its own name,
+ * every referenced Artifact counted by kind. No model-specific field list lives here; a request
+ * shaped as `{ ports }` (an exact-model generation request) reads each port, anything else reads its
+ * top-level fields.
+ */
+export function summarizeConstraints(constraints: CanonicalValue): NeedSummary {
+ const fields: Record<string, string | number | boolean> = {};
+ const references: Record<string, number> = {};
+ countReferences(constraints, references);
+ if (constraints === null || typeof constraints !== "object" || Array.isArray(constraints)) return { fields, references };
+ const record = constraints as Record<string, CanonicalValue>;
+ const ports = record.ports;
+ const source = ports !== null && typeof ports === "object" && !Array.isArray(ports)
+ ? ports as Record<string, CanonicalValue>
+ : record;
+ for (const [name, value] of Object.entries(source)) {
+ const values = Array.isArray(value) ? value : [value];
+ const scalars = values.map(scalarSummary).filter((item): item is string | number | boolean => item !== undefined);
+ if (scalars.length === 0) continue;
+ fields[name] = scalars.length === 1 ? scalars[0]! : scalars.map(String).join(", ");
+ }
+ return { fields, references };
+}
+
+/**
+ * Run the plan's Producers that need nothing from outside, so every external request exists with
+ * its exact constraints before the Build is submitted. Producers that would need an external result,
+ * or bytes this planning pass does not hold, are left as they are; their requests stay unknown and
+ * say why. Nothing here contacts a Provider or spends anything.
+ */
+export async function evaluatePlanNeeds(
+ definition: BuildDefinition,
+ contributions: readonly NodePackageContribution[],
+): Promise<ReadonlyMap<string, { readonly constraints?: CanonicalValue; readonly unknown?: string }>> {
+ const producers = new ProducerRegistry();
+ const validators = new TypeValidatorRegistry();
+ for (const contribution of contributions) {
+ for (const component of contribution.components ?? []) {
+ registerProducerFacets(producers, component.producers ?? []);
+ registerTypeValidatorFacets(validators, component.validators ?? []);
+ }
+ }
+ const driver = new NodeDriver({ producers, endpoints: new EndpointRegistry(), resources: new MemoryResourceStore(), validators });
+ const machine = new BuildMachine(definition);
+ const failed = new Map<string, string>();
+ let blockedProducers = new Map<string, string>();
+ for (let round = 0; round < 10_000; round += 1) {
+ const prepared = driver.prepare(machine.view());
+ blockedProducers = new Map(prepared.blocked
+ .filter((item) => item.reason === "missing-producer")
+ .map((item) => [item.command, `no Producer for ${item.subject} is loaded at plan time`]));
+ const runnable = prepared.runnable.filter((item) =>
+ item.command.kind === "invoke-producer" && !failed.has(item.command.id));
+ if (runnable.length === 0) break;
+ let advanced = false;
+ for (const descriptor of runnable) {
+ let result: Awaited<ReturnType<NodeDriver["executeCommand"]>>;
+ try {
+ result = await driver.executeCommand(prepared.state, descriptor, { build: "plan" });
+ } catch (error) {
+ failed.set(descriptor.command.id, error instanceof Error ? error.message : String(error));
+ continue;
+ }
+ if (result.status !== "completed" || result.event.kind === "command-failed") {
+ failed.set(descriptor.command.id, result.status === "completed" && result.event.kind === "command-failed"
+ ? result.event.message
+ : "the step did not complete at plan time");
+ continue;
+ }
+ machine.evaluate(result.event);
+ machine.commit();
+ advanced = true;
+ break;
+ }
+ if (!advanced) break;
+ }
+ const state = machine.view();
+ const known = new Map(state.needs.map((need) => [need.id, need]));
+ const stepFailures = new Map<string, string>();
+ for (const [command, message] of [...blockedProducers, ...failed]) {
+ const step = state.plan.steps.find((item) => command.endsWith(item.id))?.id ?? command;
+ stepFailures.set(step, message);
+ }
+ const result = new Map<string, { readonly constraints?: CanonicalValue; readonly unknown?: string }>();
+ for (const planned of plannedNeeds(state)) {
+ const need = known.get(planned.need);
+ if (need !== undefined) {
+ result.set(planned.need, { constraints: need.constraints });
+ continue;
+ }
+ const failure = stepFailures.get(planned.step);
+ const step = state.plan.steps.find((item) => item.id === planned.step);
+ const draft = step === undefined ? undefined : requestDraft(state, step);
+ result.set(planned.need, {
+ ...(draft === undefined ? {} : { constraints: draft }),
+ unknown: failure === undefined
+ ? (draft === undefined ? "depends on an earlier external result" : "references come from an earlier external result")
+ : `its step could not run at plan time: ${failure}`,
+ });
+ }
+ return result;
+}
+
+/**
+ * When a request step cannot run yet because a reference it needs is still to be generated, the
+ * author's own parameters already exist upstream: the request draft the step's inputs were built
+ * from. Walk from the step's missing inputs to the steps that produce them, and read the first
+ * present record shaped as a request (`{ ports }`). The media it would attach is what is pending.
+ */
+function requestDraft(state: BuildState, step: BuildState["plan"]["steps"][number]): CanonicalValue | undefined {
+ const records = new Map(state.records.map((item) => [item.id, item]));
+ const producedBy = new Map(state.plan.steps.flatMap((item) => Object.values(item.outputs).map((id) => [id, item] as const)));
+ const seen = new Set<string>();
+ const queue = [step];
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+ if (seen.has(current.id)) continue;
+ seen.add(current.id);
+ for (const id of Object.values(current.inputs)) {
+ const record = records.get(id);
+ if (record !== undefined) {
+ const value = record.value;
+ if (value.kind === "inline" && value.value !== null && typeof value.value === "object"
+ && !Array.isArray(value.value) && "ports" in value.value) return value.value;
+ continue;
+ }
+ const producer = producedBy.get(id);
+ if (producer !== undefined) queue.push(producer);
+ }
+ }
+ return undefined;
+}
+
+/** Every request in step order, with the Endpoint behind it and its parameters when known. */
+export async function describePlanNeeds(
+ state: BuildState,
+ evaluated: ReadonlyMap<string, { readonly constraints?: CanonicalValue; readonly unknown?: string }>,
+ providers: readonly PlanProviderView[],
+): Promise<readonly PlanNeedView[]> {
+ const endpoints = new Map(providers.map((item) => [item.capability, item.endpoint]));
+ return plannedNeeds(state).map((planned) => {
+ const capability = capabilityName(planned.capability);
+ const endpoint = endpoints.get(capability);
+ const found = evaluated.get(planned.need);
+ return {
+ step: planned.step,
+ port: planned.port,
+ capability,
+ ...(endpoint === undefined ? {} : { endpoint }),
+ ...(found?.constraints === undefined ? {} : { summary: summarizeConstraints(found.constraints) }),
+ ...(found?.unknown === undefined ? {} : { unknown: found.unknown }),
+ };
+ });
+}
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 09d71950..374608a4 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -18,7 +18,7 @@ import { writeCliHelp, writeCliOutput } from "./output.js";
import type { CliIo, CliMachineView } from "./output.js";
import { parseCommand } from "./arguments.js";
import type { CliCommand, RuntimeOption } from "./command.js";
-import { assertPreflight, createCatalogDescriptor, describePlanProviders, preflightPlan } from "./build-planning.js";
+import { assertPreflight, createCatalogDescriptor, describePlanNeeds, describePlanProviders, evaluatePlanNeeds, preflightPlan } from "./build-planning.js";
import { buildProgressLines, observeBuild } from "./observation.js";
import { isProjectResultCommand, runProjectResultCommand } from "./commands/results.js";
import { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";
@@ -571,6 +571,8 @@ export async function runCli(
const planHost = runtimeProfile === undefined ? undefined : await runtimeHost(runtimeProfile);
const preflight = planHost === undefined ? undefined : await preflightPlan(planHost, result.state);
const providers = planHost === undefined ? undefined : await describePlanProviders(planHost, result.state);
+ const evaluated = await evaluatePlanNeeds(result.definition, packageContributions);
+ const needs = await describePlanNeeds(result.state, evaluated, providers ?? []);
const outputNames = Object.fromEntries(result.compilation.author.exports.flatMap((item) =>
item.ref.kind === "logical-output" ? [[item.ref.id, item.name]] : []));
const externalRequests = new Map<string, number>();
@@ -611,6 +613,8 @@ export async function runCli(
providers: providers.slice(0, args.limit),
...(providers.length <= args.limit ? {} : { omittedProviders: providers.length - args.limit }),
}),
+ needs: needs.slice(0, Math.max(args.limit, 50)),
+ ...(needs.length <= Math.max(args.limit, 50) ? {} : { omittedNeeds: needs.length - Math.max(args.limit, 50) }),
...(preflight === undefined ? {} : { preflight: {
ok: preflight.ok,
capabilityCount: preflight.capabilities.length,
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 395c8e8e..bbee03a7 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -123,9 +123,24 @@ export type PlanOutput = {
/** Present only when a Runtime Profile was selected; the Endpoint and price page behind each capability. */
readonly providers?: readonly PlanProvider[];
readonly omittedProviders?: number;
+ /** Every external request the Build will make, in step order, with its parameters when known. */
+ readonly needs?: readonly PlanNeed[];
+ readonly omittedNeeds?: number;
readonly preflight?: PlanPreflight;
};
+export type PlanNeed = {
+ readonly step: string;
+ readonly port: string;
+ readonly capability: string;
+ readonly endpoint?: string;
+ readonly summary?: {
+ readonly fields: Readonly<Record<string, string | number | boolean>>;
+ readonly references: Readonly<Record<string, number>>;
+ };
+ readonly unknown?: string;
+};
+
export type CliMachineView = OperationalMachineView;
export type CliPresentation =
@@ -323,6 +338,64 @@ function capabilityLabel(name: string): string {
return name.replace(/@[^@#]+#/u, "#");
}
+/** The author-facing part of a step id: the component and operation, without the Source path. */
+function stepLabel(step: string): string {
+ let decoded = step;
+ try { decoded = decodeURIComponent(step); } catch { /* keep the raw id */ }
+ const marker = "::component::";
+ const at = decoded.lastIndexOf(marker);
+ return at === -1 ? decoded : decoded.slice(at + marker.length);
+}
+
+const WORDS = /^(\d+) words$/u;
+
+/** Parameters that count words are ranged across a group rather than splitting it. */
+function groupKey(need: PlanNeed): string {
+ if (need.summary === undefined) return need.unknown === undefined ? "?" : `?${need.unknown}`;
+ const fields = Object.entries(need.summary.fields)
+ .filter(([, value]) => !(typeof value === "string" && WORDS.test(value)))
+ .map(([name, value]) => `${name}=${String(value)}`);
+ const references = Object.entries(need.summary.references).map(([kind, count]) => `${kind}=${count}`);
+ return [...fields, "|", ...references, "|", need.unknown ?? ""].join(" ");
+}
+
+function needSummaryText(needs: readonly PlanNeed[]): string {
+ const first = needs[0]!;
+ if (first.summary === undefined) return first.unknown === undefined ? "parameters unknown" : `parameters unknown: ${first.unknown}`;
+ const parts: string[] = [];
+ for (const [name, value] of Object.entries(first.summary.fields)) {
+ if (typeof value === "string" && WORDS.test(value)) {
+ const counts = needs.map((need) => Number(WORDS.exec(String(need.summary?.fields[name] ?? "0 words"))?.[1] ?? 0));
+ const low = Math.min(...counts);
+ const high = Math.max(...counts);
+ parts.push(`${name} ${low === high ? low : `${low}–${high}`} words`);
+ } else if (typeof value === "boolean") {
+ parts.push(value ? name : `no ${name}`);
+ } else {
+ parts.push(`${name} ${value}`);
+ }
+ }
+ const references = Object.entries(first.summary.references).sort(([left], [right]) => left.localeCompare(right))
+ .map(([kind, count]) => `${count} ${kind}`);
+ if (references.length > 0) parts.push(`${references.join(" + ")} reference${references.length === 1 && references[0]!.startsWith("1 ") ? "" : "s"}`);
+ if (first.unknown !== undefined) parts.push(first.unknown);
+ return parts.length === 0 ? "no parameters" : parts.join(" · ");
+}
+
+/** One line per distinct request shape, counted; the step names when only one request has that shape. */
+function groupedNeedLines(needs: readonly PlanNeed[], colors: Palette, verbose: boolean): string[] {
+ const groups = new Map<string, PlanNeed[]>();
+ for (const need of needs) {
+ const key = groupKey(need);
+ groups.set(key, [...(groups.get(key) ?? []), need]);
+ }
+ return [...groups.values()].map((group) => {
+ const who = group.length === 1 || verbose ? colors.dim(group.map((need) => stepLabel(need.step)).join(", ")) : "";
+ const count = `×${group.length}`.padStart(4);
+ return ` ${colors.dim(count)} ${needSummaryText(group)}${who.length === 0 ? "" : ` ${who}`}`;
+ });
+}
+
function renderPlan(
view: Extract<CliPresentation, { kind: "plan" }>,
io: CliIo,
@@ -373,6 +446,7 @@ function renderPlan(
: item.pricing.url;
lines.push(` ${colors.accent(verbose ? item.capability : capabilityLabel(item.capability))}`);
lines.push(` ${where}${price === undefined ? "" : ` · ${price}`}`);
+ lines.push(...groupedNeedLines((view.machine.needs ?? []).filter((need) => need.capability === item.capability), colors, verbose));
}
if ((view.machine.omittedProviders ?? 0) > 0) {
lines.push(` ${colors.dim(`${view.machine.omittedProviders} more capabilities · use --limit <count>`)}`);
diff --git a/packages/cli/test/plan-needs.test.ts b/packages/cli/test/plan-needs.test.ts
new file mode 100644
index 00000000..3f5f0b81
--- /dev/null
+++ b/packages/cli/test/plan-needs.test.ts
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { summarizeConstraints } from "../src/build-planning.js";
+
+test("a request summary reads scalars off the request itself and counts references by kind", () => {
+ const summary = summarizeConstraints({
+ ports: {
+ prompt: ["A woman writes on a whiteboard in a bright room with a pool behind the glass wall and plants."],
+ duration: [10],
+ resolution: ["720p"],
+ generateAudio: [true],
+ referenceImage: [{ artifact: { resource: "sha:1", mediaType: "image/png", size: 10 }, role: "reference" }],
+ referenceAudio: [{ artifact: { resource: "sha:2", mediaType: "audio/wav", size: 10 }, role: "reference" }],
+ },
+ });
+ assert.deepEqual(summary.fields, { prompt: "19 words", duration: 10, resolution: "720p", generateAudio: true });
+ assert.deepEqual(summary.references, { image: 1, audio: 1 });
+});
+
+test("a request that is not a generation request is read from its top-level fields", () => {
+ const summary = summarizeConstraints({
+ audio: { resource: "sha:3", mediaType: "audio/wav", size: 320_000 },
+ sampleFrames: 160_000,
+ sampleRate: 16_000,
+ language: "en",
+ });
+ assert.deepEqual(summary.fields, { sampleFrames: 160_000, sampleRate: 16_000, language: "en" });
+ assert.deepEqual(summary.references, { audio: 1 });
+});
diff --git a/packages/core/src/plan.ts b/packages/core/src/plan.ts
index a0fd686d..de38df39 100644
--- a/packages/core/src/plan.ts
+++ b/packages/core/src/plan.ts
@@ -6,11 +6,13 @@ import type {
CompiledGraph,
GraphValueRef,
LinkedProgram,
+ NeedId,
OperationNode,
ProducerStep,
RecordId,
RunGraph,
Satisfaction,
+ StepId,
TypeRef,
TypedRecord,
} from "@hypit/protocol";
@@ -67,32 +69,37 @@ type ProducedRecord = {
readonly step?: string;
};
+/** One external request the exact finite BuildPlan will make: which step asks, through which port. */
export type PlannedNeed = {
+ readonly step: StepId;
+ readonly port: string;
+ readonly need: NeedId;
+ readonly result: RecordId;
readonly capability: CapabilityRef;
readonly returns: TypeRef;
};
const planStepIndexes = new WeakMap<BuildPlan, ReadonlyMap<string, ProducerStep>>();
-function plannedNeedKey(need: PlannedNeed): string {
- const ref = (value: { readonly module: { readonly name: string; readonly version: string }; readonly name: string }) =>
- `${value.module.name}@${value.module.version}#${value.name}`;
- return `${ref(need.capability)} -> ${ref(need.returns)}`;
-}
-
-/** External requirements declared by the exact finite BuildPlan. */
+/** Every external requirement of the BuildPlan, one entry per request, in step order. */
export function plannedNeeds(state: BuildState): readonly PlannedNeed[] {
- const found = new Map<string, PlannedNeed>();
+ const found: PlannedNeed[] = [];
for (const step of state.plan.steps) {
const producer = resolveProducer(state.program.closure, step.producer);
for (const need of producer.needs) {
- const item = { capability: need.capability, returns: need.returns };
- found.set(plannedNeedKey(item), item);
+ const binding = step.needs[need.name];
+ if (binding === undefined) continue;
+ found.push({
+ step: step.id,
+ port: need.name,
+ need: binding.id,
+ result: binding.result,
+ capability: need.capability,
+ returns: need.returns,
+ });
}
}
- return [...found.entries()]
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([, value]) => structuredClone(value));
+ return structuredClone(found);
}
function planContent(
diff --git a/packages/core/src/reducer.ts b/packages/core/src/reducer.ts
index d4d81dd0..5dbeff46 100644
--- a/packages/core/src/reducer.ts
+++ b/packages/core/src/reducer.ts
@@ -176,26 +176,31 @@ function goalsComplete(state: BuildState, records: ReadonlySet<string>): boolean
return state.plan.goals.every((goal) => records.has(goal.record));
}
+/**
+ * Every command that can run now is outstanding: the ones already issued, plus every Need whose
+ * result is missing and every pending step whose inputs exist. Scheduling is incremental, so a
+ * cheap Producer never waits behind an unrelated external request that happens to share a turn.
+ */
function schedule(state: BuildState): BuildState {
- if (state.status !== "active" || state.outstanding.length > 0) return state;
+ if (state.status !== "active") return state;
const records = new Set(state.records.map((record) => record.id));
if (goalsComplete(state, records)) {
const complete = {
...state,
status: "complete" as const,
+ outstanding: [],
};
return complete;
}
- const commands: CoreCommand[] = [];
+ const issued = new Set(state.outstanding.map((command) => command.id));
+ const commands: CoreCommand[] = [...state.outstanding];
for (const need of state.needs) {
if (records.has(need.result)) continue;
- commands.push({
- kind: "fulfill-need",
- id: commandId("need", need.id),
- need,
- });
+ const id = commandId("need", need.id);
+ if (issued.has(id)) continue;
+ commands.push({ kind: "fulfill-need", id, need });
}
for (const stepState of state.steps) {
@@ -204,9 +209,11 @@ function schedule(state: BuildState): BuildState {
if (!Object.values(step.inputs).every((id) => records.has(id))) {
continue;
}
+ const id = commandId("producer", step.id);
+ if (issued.has(id)) continue;
commands.push({
kind: "invoke-producer",
- id: commandId("producer", step.id),
+ id,
step: step.id,
producer: step.producer,
inputs: step.inputs,
diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.ts
index 3909bce5..9de682bb 100644
--- a/packages/core/test/core.test.ts
+++ b/packages/core/test/core.test.ts
@@ -126,3 +126,21 @@ test("Build Definition plus admitted Facts restores the same next Command", () =
assert.deepEqual(restored.commands(), machine.commands());
assert.equal(restored.commands()[0]?.kind, "fulfill-need");
});
+
+test("scheduling is incremental: a ready Producer runs while an unrelated Need is still outstanding", () => {
+ let current = onlyProducer(createGreetingBuild({ includeSideTarget: true }));
+ let state = reduce(current.state, producerEvent(current.command, { prompt: { kind: "inline", value: "Greet Ada" } }));
+ const request = state.outstanding.find((item): item is InvokeProducerCommand =>
+ item.kind === "invoke-producer" && item.producer.name === "request-text");
+ const side = state.outstanding.find((item): item is InvokeProducerCommand =>
+ item.kind === "invoke-producer" && item.producer.name === "placeholder-text");
+ assert.ok(request);
+ assert.ok(side);
+ // The request step emits its Need; the side chain keeps moving without waiting for it.
+ state = reduce(state, producerEvent(request, {}, { generation: { prompt: "Greet Ada" } }));
+ state = reduce(state, producerEvent(side, { generated: { kind: "inline", value: "Hi, Ada" } }));
+ assert.ok(state.outstanding.some((item) => item.kind === "fulfill-need"), "the Need is still outstanding");
+ const assembleSide = state.outstanding.find((item): item is InvokeProducerCommand =>
+ item.kind === "invoke-producer" && item.producer.name === "assemble");
+ assert.ok(assembleSide, "the side chain's next Producer was scheduled behind the outstanding Need");
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 942d1a32..4cf84f04 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -567,6 +567,15 @@ importers:
'@hypit/compiler-node':
specifier: workspace:*
version: link:../compiler-node
+ '@hypit/component-kit':
+ specifier: workspace:*
+ version: link:../component-kit
+ '@hypit/core':
+ specifier: workspace:*
+ version: link:../core
+ '@hypit/driver-node':
+ specifier: workspace:*
+ version: link:../driver-node
'@hypit/elaborator':
specifier: workspace:*
version: link:../elaborator
@@ -588,6 +597,9 @@ importers:
'@hypit/source':
specifier: workspace:*
version: link:../source
+ '@hypit/validation':
+ specifier: workspace:*
+ version: link:../validation
'@hypit/workspace':
specifier: workspace:*
version: link:../workspace