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.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
refactor(cli): clarify build progress and runtime ownership
kashorin930b092b67e7
diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.tsindex 555c174a..b57f9b48 100644--- a/packages/cli/src/arguments.ts+++ b/packages/cli/src/arguments.ts@@ -48,7 +48,20 @@ const commonOptions = ["--json", "--color", "--no-color", "--verbose", "--debug"export function parseCommand(argv: readonly string[]): CliCommand {const [command, ...tail] = argv;switch (command) {- case "check":+ case "check": {+ const [source, rest] = requiredPositional(tail, "check requires one Source");+ const options = commandOptions(command, rest,+ "--package-root", "--workspace", "--asset-root", "--limit");+ return {+ command,+ source,+ presentation: options.presentation,+ assetRoots: options.assetRoots,+ limit: options.limit,+ ...optionalProject(options),+ ...optionalPackageRoot(options),+ };+ }case "plan": {const [source, rest] = requiredPositional(tail, `${command} requires one Source`);const options = commandOptions(command, rest,diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.tsindex 59cd3ae3..283b7777 100644--- a/packages/cli/src/command.ts+++ b/packages/cli/src/command.ts@@ -12,7 +12,7 @@ export type ProjectOption = {readonly workspaceRoot?: string;};-type AuthorOptions = ProjectOption & RuntimeOption & {+type SourceOptions = ProjectOption & {readonly source: string;readonly assetRoots: readonly string[];readonly packageRoot?: string;@@ -20,9 +20,9 @@ type AuthorOptions = ProjectOption & RuntimeOption & {};export type AuthorCommand =- | (CommandBase & AuthorOptions & { readonly command: "check" })- | (CommandBase & AuthorOptions & { readonly command: "plan" })- | (CommandBase & AuthorOptions & {+ | (CommandBase & SourceOptions & { readonly command: "check" })+ | (CommandBase & SourceOptions & RuntimeOption & { readonly command: "plan" })+ | (CommandBase & SourceOptions & RuntimeOption & {readonly command: "build";readonly follow: boolean;readonly maxWaitMs?: number;diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.tsindex ccb44066..6de5ceec 100644--- a/packages/cli/src/commands/environment.ts+++ b/packages/cli/src/commands/environment.ts@@ -38,6 +38,7 @@ export async function runEnvironmentCommand(input: {const reportProgramProgress = args.presentation.json? undefined: (event: { readonly id: string; readonly phase: "checking" | "installing" | "starting" | "waiting" | "ready" }): void => {+ if (!args.presentation.verbose && event.phase !== "installing" && event.phase !== "starting") return;const verb = {checking: "Checking",installing: "Installing",@@ -149,6 +150,11 @@ export async function runEnvironmentCommand(input: {const desiredState = args.action === "down" ? !result.programs.some((item) => item.state.state === "ready") : ready;const lifecycleOk = args.action === "status" || desiredState;const shownPrograms = result.programs.filter((item) => item.state.state !== "ready").slice(0, args.limit);+ const title = args.action === "up"+ ? desiredState ? "External programs ready" : "External programs need attention"+ : args.action === "down"+ ? desiredState ? "External programs stopped" : "Some external programs are still running"+ : "External program status";write({format: "hypit.cli-programs@2",action: args.action,@@ -159,10 +165,12 @@ export async function runEnvironmentCommand(input: {...(args.presentation.verbose && item.action !== undefined ? { action: item.action } : {}),})),...(result.programs.length <= args.limit ? {} : { omittedPrograms: result.programs.length - args.limit }),- }, `External programs ${args.action}`,+ }, title,args.action === "status" ? ready ? "success" : "info" : lifecycleOk ? "success" : "warning", [- ["Programs", String(result.programs.length)],- ["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)],+ ...(!args.presentation.verbose && lifecycleOk && args.action !== "status" ? [] : [+ ["Programs", String(result.programs.length)] as const,+ ["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)] as const,+ ]),], shownPrograms.map((item) => `${item.id}: ${item.state.state}`));if (!lifecycleOk) io.setExitCode?.(1);return;@@ -198,10 +206,12 @@ export async function runEnvironmentCommand(input: {total: external.programs.length,ready: external.programs.filter((item) => item.state.state === "ready").length,},- }, "Runtime is up", ok ? "success" : "warning", [- ["Machine packages", String(prepared.length)],- ["Worker", processState.state],- ["External programs", String(external.programs.length)],+ }, ok ? "Runtime deployment ready" : "Runtime deployment needs attention", ok ? "success" : "warning", [+ ...(!args.presentation.verbose && ok ? [] : [+ ["Machine packages", String(prepared.length)] as const,+ ["Worker", processState.state] as const,+ ["External programs", `${external.programs.filter((item) => item.state.state === "ready").length}/${external.programs.length} ready`] as const,+ ]),]);if (!ok) io.setExitCode?.(1);return;@@ -243,10 +253,10 @@ export async function runEnvironmentCommand(input: {runtime = selectedRuntime;const activity = await runtime.activity();const counts = Object.fromEntries([- ["starting", activity.builds.filter((item) => item.activity === "submitting" || item.activity === "ready").length],- ["active", activity.builds.filter((item) => item.activity === "running").length],- ["waiting", activity.builds.filter((item) => item.activity === "waiting").length],- ["decided", activity.builds.filter((item) => item.activity === "saving-result").length],+ ["submitting", activity.builds.filter((item) => item.activity === "submitting").length],+ ["working", activity.builds.filter((item) =>+ item.activity === "ready" || item.activity === "running" || item.activity === "waiting").length],+ ["savingResult", activity.builds.filter((item) => item.activity === "saving-result").length],]);const lanes = summarizeQueueLanes(activity.capacity);const ready = worker.state === "running"@@ -273,14 +283,19 @@ export async function runEnvironmentCommand(input: {...(args.presentation.verbose ? { lanes: lanes.slice(0, args.limit) } : {}),},};- write(machine, "Runtime status", attention ? "warning" : ready ? "success" : "info", [+ write(machine, attention+ ? "Runtime deployment needs attention"+ : ready ? "Runtime deployment ready" : "Runtime Worker stopped",+ attention ? "warning" : ready ? "success" : "info", [["Worker", worker.state],- ["Starting", String(counts.starting ?? 0)],- ["Active", String(counts.active ?? 0)],- ["Waiting", String(counts.waiting ?? 0)],- ["Decided", String(counts.decided ?? 0)],+ ["Active Builds", String(activity.builds.length)],["Programs", `${external.programs.length - unavailable.length}/${external.programs.length} ready`],- ...(args.presentation.verbose ? [["Active requests", String(activity.capacity.length)] as const] : []),+ ...(args.presentation.verbose ? [+ ["Submitting", String(counts.submitting ?? 0)] as const,+ ["Working", String(counts.working ?? 0)] as const,+ ["Saving Result", String(counts.savingResult ?? 0)] as const,+ ["Capacity in use", String(activity.capacity.length)] as const,+ ] : []),], [...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),...(args.presentation.verbose ? queueLaneLines(lanes.slice(0, args.limit)) : []),diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.tsindex b8e98972..07f5dc2f 100644--- a/packages/cli/src/commands/execution.ts+++ b/packages/cli/src/commands/execution.ts@@ -2,7 +2,7 @@ import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-reimport type { NodeRuntimeHost } from "@hypit/runtime-host-node";import type { CliCommand, ExecutionCommand } from "../command.js";-import { buildObservationKey } from "../observation.js";+import { activityObservationKey, buildProgressLines, observeBuildView } from "../observation.js";import type { CliIo } from "../output.js";import type { CliRuntimeController } from "../runtime-port.js";import { formatOperationProgress, queueLaneLines, summarizeQueueLanes } from "../runtime-view.js";@@ -43,18 +43,23 @@ export async function runExecutionCommand(input: {}const finished = result?.outcome !== undefined;const build = result === undefined ? null : buildStatusView({ id: result.id, result });+ const outcome = result?.outcome;write({ format: "hypit.cli-status@3", build }, result === undefined? "Build Result not found"- : finished ? "Build Result is finished" : "Build Result is unfinished",- result === undefined || !finished ? "warning" : "info", [+ : outcome === "complete" ? "Build complete"+ : outcome === "failed" ? "Build failed"+ : outcome === "cancelled" ? "Build cancelled" : "Build Result is open",+ result === undefined || !finished ? "warning"+ : outcome === "failed" ? "error"+ : outcome === "cancelled" ? "warning" : "success", [["Build", args.build],- ["Work", build?.work.state ?? "unknown"],- ...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),- ["Result", build?.result.state ?? "missing"],+ ...(build?.title === undefined ? [] : [["Title", build.title] as const]),+ ...(outcome === undefined ? [] : [["Outcome", outcome] as const]),+ ...(!finished && result !== undefined ? [["Result", "open"] as const] : []),...(build?.result.outputCount === undefined ? [] : [["Outputs", String(build.result.outputCount)] as const]),- ], result === undefined ? [] : [- "Result and Runtime are independent facts; select the Runtime to inspect active execution.",- ]);+ ], !finished && result !== undefined+ ? ["Select the Runtime to inspect active work."]+ : []);if (result === undefined || !finished) io.setExitCode?.(1);return;}@@ -98,12 +103,7 @@ export async function runExecutionCommand(input: {};});const lanes = args.presentation.verbose ? summarizeQueueLanes(activity.capacity).slice(0, args.limit) : undefined;- const currentView = JSON.stringify({- worker: worker.state,- builds,- activeRequests: activity.capacity.length,- ...(lanes === undefined ? {} : { lanes }),- });+ const currentView = activityObservationKey(worker.state, activity.builds);if (args.watch && currentView === previous) return;previous = currentView;const value = {@@ -115,10 +115,15 @@ export async function runExecutionCommand(input: {activeRequests: activity.capacity.length,...(lanes === undefined ? {} : { lanes }),};- const buildLines = activity.builds.slice(0, args.limit).map((item) =>- `${item.id}: ${buildStatusView({ id: item.id, runtime: item }).work.state}`+ const buildLines = activity.builds.slice(0, args.limit).map((item) => {+ const requestProgress = item.requests === undefined || item.requests.total === 0+ ? ""+ : ` · ${item.requests.completed}/${item.requests.total} steps`;+ return `${item.id}: ${buildStatusView({ id: item.id, runtime: item }).work.state}`+ + requestProgress+ `${item.cancellationRequested ? " · cancelling" : ""}`- + `${item.issue === undefined ? "" : ` · ${item.issue.message}`}`);+ + `${item.issue === undefined ? "" : ` · ${item.issue.message}`}`;+ });const activeOperations = activity.builds.flatMap((item) => item.operations).filter((item) => item.status === "pending");const operationLines = args.presentation.verbose@@ -153,30 +158,19 @@ export async function runExecutionCommand(input: {try {openedResults = await openProjectResults();if (args.watch && view !== undefined && view.issue === undefined) {- const startedAt = Date.now();- let delayMs = 100;- let previous: string | undefined;const controller = await runtimeController(runtimeProfile);- while (view !== undefined && view.issue === undefined) {- const encoded = buildObservationKey(view);- if (encoded !== previous && !args.presentation.json) {- previous = encoded;- io.write(` · ${view.id}: ${view.activity}`- + `${view.operations.length === 0 ? "" : ` · ${view.operations.length} operation(s)`}\n`);- delayMs = 100;- } else {- delayMs = Math.min(1_000, delayMs * 2);- }- const remaining = args.maxWaitMs === undefined- ? undefined- : args.maxWaitMs - (Date.now() - startedAt);- if (remaining !== undefined && remaining <= 0) break;- const worker = await controller.worker.status();- if (worker.state !== "running") break;- await new Promise((resolveWait) => setTimeout(resolveWait,- remaining === undefined ? delayMs : Math.min(delayMs, remaining)));- view = await runtime.inspect(args.build);- }+ view = await observeBuildView(runtime, args.build, view, {+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ controller,+ ...(args.presentation.json ? {} : {+ onProgress: (progress) => {+ for (const line of buildProgressLines(progress, {+ verbose: args.presentation.verbose,+ limit: args.limit,+ })) io.write(`${line}\n`);+ },+ }),+ });}result = await openedResults.repository.read(args.build);} catch (error) {@@ -186,7 +180,9 @@ export async function runExecutionCommand(input: {}const found = view !== undefined || result !== undefined;const activity = view?.activity;- const outcome = result?.outcome ?? view?.outcome;+ const resultOutcome = result?.outcome;+ const outcome = resultOutcome ?? view?.outcome;+ const savingResult = activity === "saving-result" && resultOutcome === undefined;const issue = view?.issue;const build = !found ? null : buildStatusView({id: view?.id ?? result!.id,@@ -196,34 +192,54 @@ export async function runExecutionCommand(input: {verbose: args.presentation.verbose,operationLimit: args.limit,});- write({ format: "hypit.cli-status@3", build }, !found+ const attention = build?.attention;+ const humanTitle = !found? "Build not found"- : issue !== undefined+ : attention !== undefined? "Build needs attention"- : args.watch- ? activity === undefined ? "Build finished" : "Build still active"- : "Build status",+ : savingResult+ ? "Saving Build Result"+ : resultOutcome === "complete"+ ? "Build complete"+ : resultOutcome === "failed"+ ? "Build failed"+ : resultOutcome === "cancelled"+ ? "Build cancelled"+ : args.watch && activity === undefined ? "Build finished" : "Build active";+ write({ format: "hypit.cli-status@3", build }, !found+ ? "Build not found" : humanTitle,!found? "warning"- : issue !== undefined || resultReadError !== undefined+ : attention !== undefined? "error": outcome === "failed"? "error"- : args.watch && activity !== undefined ? "warning" : "info", [+ : outcome === "cancelled"+ ? "warning"+ : resultOutcome === "complete"+ ? "success"+ : args.watch && activity !== undefined ? "warning" : "info", [["Build", args.build],...(build?.title === undefined ? [] : [["Title", build.title] as const]),- ["Work", build?.work.state ?? "unknown"],- ...(build?.work.outcome === undefined ? [] : [["Decision", build.work.outcome] as const]),- ["Result", build?.result.state ?? "missing"],- ...(build?.result.outputCount === undefined ? [] : [["Outputs", String(build.result.outputCount)] as const]),+ ...(attention !== undefined ? [+ ["Execution", build?.work.outcome ?? build?.work.state ?? "unknown"] as const,+ ["Result", build?.result.state ?? "missing"] as const,+ ] : savingResult ? [+ ["Execution", view?.outcome ?? "complete"] as const,+ ["Result", "saving"] as const,+ ] : resultOutcome !== undefined ? [+ ["Outcome", resultOutcome] as const,+ ...(build?.result.outputCount === undefined+ ? [] : [["Outputs", String(build.result.outputCount)] as const]),+ ] : [["State", build?.work.state ?? "unknown"] as const]),], (build?.operations ?? []).map((operation) => operation.failure !== undefined? `${operation.endpoint}: ${operation.failure.code} — ${operation.failure.message}`: operation.progress === undefined? `${operation.endpoint}: ${operation.state}`: `${operation.endpoint}: ${formatOperationProgress(operation.progress)}`)- .concat(build?.attention === undefined ? [] : [- `Attention ${build.attention.message}`,- ...(build.attention.action === undefined ? [] : [`Action ${build.attention.action}`]),+ .concat(attention === undefined ? [] : [+ `Attention ${attention.message}`,+ ...(attention.action === undefined ? [] : [`Action ${attention.action}`]),]));if (!found || issue !== undefined || resultReadError !== undefined || outcome === "failed") io.setExitCode?.(1);return;diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.tsindex 8de22f34..25d584e3 100644--- a/packages/cli/src/commands/results.ts+++ b/packages/cli/src/commands/results.ts@@ -87,7 +87,8 @@ export async function runProjectResultCommand(input: {["Builds", String(entries.length)],], entries.map((item) => {const label = item.title === undefined ? item.build : `${item.title} · ${item.build}`;- return `${label}: ${item.outcome} · ${item.output.kind} · ${item.output.type} · ${item.createdAt}`;+ return `${label}: ${item.outcome} · ${new Date(item.createdAt).toLocaleString()}`+ + (args.presentation.verbose ? ` · ${item.output.kind} · ${item.output.type}` : "");}).concat(page.next === undefined ? [] : [`Older hypit history ${args.outputName} --before ${page.next}`]));return;}@@ -100,23 +101,37 @@ export async function runProjectResultCommand(input: {...(args.outputName === undefined ? {} : { output: args.outputName }),limit: args.limit,});+ const focusedOutputs = args.outputName === undefined+ ? build.outputs.filter((item) => item.target || item.highlighted)+ : build.outputs;+ const visibleOutputs = args.presentation.verbose ? build.outputs : focusedOutputs;+ const outputCount = build.outputs.length + (build.omittedOutputs ?? 0);+ const hiddenOutputCount = args.outputName === undefined ? outputCount - focusedOutputs.length : 0;write({ format: "hypit.cli-inspect@4", build }, "Build Result",- manifest.outcome === "failed" ? "error" : "info", [+ manifest.outcome === "failed" ? "error"+ : manifest.outcome === "cancelled" ? "warning"+ : manifest.outcome === "complete" ? "success" : "info", [["Build", build.id],["Created", new Date(build.createdAt).toLocaleString()],...(build.title === undefined ? [] : [["Title", build.title] as const]),["Outcome", build.outcome],- ["Targets", String(build.targetCount)],- ["Outputs", String(build.outputs.length + (build.omittedOutputs ?? 0))],+ ...(args.outputName === undefined ? [+ ["Targets", String(build.targetCount)] as const,+ ["Outputs", String(outputCount)] as const,+ ] : []),], [...(build.failure === undefined ? [] : [`Reason ${build.failure}`]),...(build.note === undefined ? [] : [`Note ${build.note}`]),- ...build.outputs.map((item) => `${item.highlighted ? "★" : item.target ? "Target" : "Output"} ${item.name} · ${item.type} · ${item.kind}`- + `${item.mediaType === undefined ? "" : ` · ${item.mediaType}`}`- + `${item.size === undefined ? "" : ` · ${item.size} bytes`}`),- ...(build.omittedOutputs === undefined ? [] : [+ ...visibleOutputs.map((item) => `${item.highlighted ? "★" : item.target ? "Target" : "Output"} ${item.name}`+ + (!args.presentation.verbose ? "" : ` · ${item.type} · ${item.kind}`+ + `${item.mediaType === undefined ? "" : ` · ${item.mediaType}`}`+ + `${item.size === undefined ? "" : ` · ${item.size} bytes`}`)),+ ...(!args.presentation.verbose && hiddenOutputCount > 0 ? [+ `${hiddenOutputCount} other Output${hiddenOutputCount === 1 ? "" : "s"} · use --verbose or --output <name>`,+ ] : []),+ ...(args.presentation.verbose && build.omittedOutputs !== undefined ? [`${build.omittedOutputs} more Outputs · use --limit <count> or --output <name>`,- ]),+ ] : []),]);return;}@@ -157,11 +172,12 @@ export async function runProjectResultCommand(input: {kind: exported.kind,path: exported.path,};- write(machine, "Build Output exported", "success", [- ["Build", exported.build],- ["Output", exported.output],- ["Type", machine.type],- ["Kind", exported.kind],- ["Path", exported.path],- ]);+ const path = projectPath(exported.path, projectRoot);+ write(machine, `Exported ${exported.output} → ${path}`, "success",+ args.presentation.verbose ? [+ ["Build", exported.build],+ ["Type", machine.type],+ ["Kind", exported.kind],+ ["Path", exported.path],+ ] : []);}diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex c5a440dc..7efa102f 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -1,5 +1,5 @@import { randomBytes } from "node:crypto";-import { dirname, isAbsolute, relative, resolve, sep } from "node:path";+import { resolve } from "node:path";import type { NodeRuntimeHost } from "@hypit/runtime-host-node";import { orderedBuildId } from "@hypit/protocol";@@ -18,12 +18,12 @@ import type { CliIo, CliMachineView } from "./output.js";import { parseCommand } from "./arguments.js";import type { CliCommand, RuntimeOption } from "./command.js";import { assertPreflight, createCatalogDescriptor, preflightPlan } from "./build-planning.js";-import { observeBuild } from "./observation.js";+import { buildProgressLines, observeBuild } from "./observation.js";import { isProjectResultCommand, runProjectResultCommand } from "./commands/results.js";import { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";import { isExecutionCommand, runExecutionCommand } from "./commands/execution.js";import { inlineValuePreview } from "./runtime-view.js";-import { resolvePackageRoot } from "./project-context.js";+import { resolvePackageRoot, resolveProjectRoot } from "./project-context.js";import { loadDiscoveredSourcePackages } from "./source-packages.js";import {clearRuntimeProfile,@@ -67,14 +67,17 @@ export async function runCli(return;}const args = parseCommand(argv);- let selectedRuntimeProjectRoot: string | undefined;- const commandProjectRoot = (): string => commandWorkspaceRoot(args)- ?? selectedRuntimeProjectRoot- ?? ((args.command === "check" || args.command === "plan" || args.command === "build")- ? dirname(resolve(args.source))- : process.cwd());- const packageRootForProject = async (projectRoot = commandProjectRoot()): Promise<string> =>- commandPackageRoot(args) ?? await resolvePackageRoot(projectRoot);+ let resolvedProject: Promise<string> | undefined;+ const commandProjectRoot = async (): Promise<string> => {+ const workspaceRoot = commandWorkspaceRoot(args);+ resolvedProject ??= resolveProjectRoot({+ ...(workspaceRoot === undefined ? {} : { workspaceRoot }),+ cwd: process.cwd(),+ });+ return await resolvedProject;+ };+ const packageRootForProject = async (projectRoot?: string): Promise<string> =>+ commandPackageRoot(args) ?? await resolvePackageRoot(projectRoot ?? await commandProjectRoot());const writeOperational = (machine: CliMachineView,title: string,@@ -101,7 +104,8 @@ export async function runCli(}return await opened;};- const projectResults = async (projectRoot = commandProjectRoot()) => {+ const projectResults = async (requestedProjectRoot?: string) => {+ const projectRoot = requestedProjectRoot ?? await commandProjectRoot();const packageRoot = await packageRootForProject(projectRoot);return await distribution.openProjectResults(projectRoot, {packageRoot,@@ -117,7 +121,7 @@ export async function runCli(}if (args.command === "runtime" && args.action === "use") {const profile = resolve(args.profile);- const selected = await selectRuntimeProfile(args.workspaceRoot ?? process.cwd(), profile);+ const selected = await selectRuntimeProfile(await commandProjectRoot(), profile);writeOperational({format: "hypit.cli-runtime-selection@2",selected: true,@@ -130,7 +134,7 @@ export async function runCli(return;}if (args.command === "runtime" && args.action === "unset") {- const cleared = await clearRuntimeProfile(args.workspaceRoot ?? process.cwd());+ const cleared = await clearRuntimeProfile(await commandProjectRoot());writeOperational({format: "hypit.cli-runtime-selection@2",selected: false,@@ -147,23 +151,14 @@ export async function runCli(const runtimeWasExplicit = runtimeProfile !== undefined;let runtimeNeedsHint = runtimeWasExplicit;if (acceptsRuntimeContext(args) && runtimeProfile === undefined) {- const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build";- const start = commandWorkspaceRoot(args)- ?? (sourceScoped ? dirname(resolve(args.source)) : process.cwd());- const selected = await findRuntimeProfile(start);+ const selected = await findRuntimeProfile(await commandProjectRoot());if (selected !== undefined) {runtimeProfile = selected.profile;- selectedRuntimeProjectRoot = selected.projectRoot;- const cwdFromProject = relative(selected.projectRoot, resolve(process.cwd()));- runtimeNeedsHint = cwdFromProject === ".." || cwdFromProject.startsWith(`..${sep}`)- || isAbsolute(cwdFromProject);+ runtimeNeedsHint = false;}}- const runtimeController = async (profile: string, source?: string): Promise<CliRuntimeController> => {- const workspaceRoot = commandWorkspaceRoot(args)- ?? selectedRuntimeProjectRoot- ?? (source === undefined ? process.cwd() : dirname(resolve(source)));- const packageRoot = await packageRootForProject(workspaceRoot);+ const runtimeController = async (profile: string): Promise<CliRuntimeController> => {+ const packageRoot = await packageRootForProject();return await (await runtimeHost(profile, packageRoot)).controller({packageRoot,});@@ -174,7 +169,7 @@ export async function runCli(runtimeProfile,io,distribution,- projectRoot: args.command === "paths" ? selectedRuntimeProjectRoot ?? process.cwd() : commandProjectRoot(),+ projectRoot: await commandProjectRoot(),packageRootForProject,runtimeHost,runtimeController,@@ -187,7 +182,7 @@ export async function runCli(try {await runProjectResultCommand({args,- projectRoot: commandProjectRoot(),+ projectRoot: await commandProjectRoot(),repository: results.repository,write: writeOperational,});@@ -208,16 +203,9 @@ export async function runCli(});return;}- const runtimePaths = runtimeProfile === undefined- ? undefined- : await (await runtimeHost(runtimeProfile)).resolvePaths();- const effectivePackageRoot = args.packageRoot ?? runtimePaths?.packageRoot;- const effectiveWorkspaceRoot = args.workspaceRoot- ?? selectedRuntimeProjectRoot- ?? dirname(resolve(args.source));+ const effectiveWorkspaceRoot = await commandProjectRoot();const projectResultsRoot = effectiveWorkspaceRoot;- const sourcePackageRoot = effectivePackageRoot- ?? await resolvePackageRoot(effectiveWorkspaceRoot);+ const sourcePackageRoot = args.packageRoot ?? await resolvePackageRoot(effectiveWorkspaceRoot);const loadedPackageSet = distribution.discoverSourcePackages === undefined? undefined: await loadDiscoveredSourcePackages(distribution, {@@ -346,6 +334,8 @@ export async function runCli(throw error;}})();+ const runSelections = result.selections.filter((selection) =>+ loadedRun.run.satisfactionNames[selection.output] !== undefined);let runtime: CliRuntime | undefined;try {const catalog = createCatalogDescriptor({@@ -392,6 +382,31 @@ export async function runCli(}runtime = await loadRuntime(await runtimeHost(runtimeProfile));let built = await runtime.build(request);+ const externalRequestCount = result.definition.plan.steps.reduce(+ (total, step) => total + Object.keys(step.needs).length,+ 0,+ );+ const suppliedOutputCount = runSelections.length;+ const workSummary = [+ `${externalRequestCount} external ${externalRequestCount === 1 ? "request" : "requests"}`,+ ...(suppliedOutputCount === 0 ? [] : [+ `${suppliedOutputCount} ${suppliedOutputCount === 1 ? "Output" : "Outputs"} supplied by Run`,+ ]),+ ].join(" · ");+ if (args.follow && "view" in built && !args.presentation.json) {+ const acceptedView = buildStatusView({ id: built.id, runtime: built.view });+ const targets = built.view.targets.slice(0, args.limit);+ writeOperational({+ format: "hypit.cli-build@3",+ build: args.title === undefined ? acceptedView : { ...acceptedView, title: args.title },+ }, "Build submitted", "success", [+ ["Build", built.id],+ ...(args.title === undefined ? [] : [["Title", args.title] as const]),+ [built.view.targets.length === 1 ? "Target" : "Targets", targets.join(", ")+ + (built.view.targets.length > targets.length ? ` (+${built.view.targets.length - targets.length})` : "")],+ ["Work", workSummary],+ ], ["Following accepted work. Ctrl-C stops watching; the Build continues."]);+ }if (args.follow && runtime !== undefined) {built = await observeBuild(runtime, built, {...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),@@ -399,14 +414,10 @@ export async function runCli(readResult: async () => await buildResults.repository.read(built.id),...(args.presentation.json ? {} : {onProgress: (progress) => {- const operations = Object.entries(progress.operations)- .map(([status, count]) => `${count} ${status}`)- .join(", ");- io.write(` · ${progress.phase}`- + `${operations.length === 0 ? "" : ` · ${operations}`}\n`);- if (args.presentation.verbose) {- for (const line of progress.activity.slice(0, args.limit)) io.write(` ${line}\n`);- }+ for (const line of buildProgressLines(progress, {+ verbose: args.presentation.verbose,+ limit: args.limit,+ })) io.write(`${line}\n`);},}),});@@ -479,16 +490,29 @@ export async function runCli(.slice(0, args.limit).map((item) => `Result ${item.published.name} = ${item.inline}`)),];- writeOperational(machine, args.follow- ? finished ? "Build finished" : issue !== undefined ? "Result needs attention" : "Build still active"- : "Build submitted",+ const humanTitle = issue !== undefined+ ? "Result needs attention"+ : finished+ ? buildOutcome === "complete"+ ? "Build complete"+ : buildOutcome === "failed"+ ? "Build failed"+ : buildOutcome === "cancelled" ? "Build cancelled" : "Build finished"+ : args.follow ? "Build still active" : "Build submitted";+ writeOperational(machine, humanTitle,buildOutcome === "failed" || issue !== undefined ? "error": buildOutcome === "cancelled" || (args.follow && !finished) ? "warning" : "success", [["Build", built.id],- ["Work", machine.build.work.state],- ...(machine.build.work.outcome === undefined ? [] : [["Decision", machine.build.work.outcome] as const]),- ["Result", machine.build.result.state],- ["Targets", String(finishedResult?.targets.length ?? targetPublishedOutputs.length)],+ ...(args.title === undefined ? [] : [["Title", args.title] as const]),+ ...(!args.follow && !finished ? [+ [targetPublishedOutputs.length === 1 ? "Target" : "Targets",+ targetPublishedOutputs.map((item) => item.name).join(", ")] as const,+ ["Work", workSummary] as const,+ ] : []),+ ...(issue === undefined ? [] : [+ ["Execution", buildOutcome ?? machine.build.work.state] as const,+ ["Result", "needs attention"] as const,+ ]),], finished ? finishedLines : issue !== undefined ? [`Result ${issue.scope}: ${issue.message}`,`Finish hypit result finish ${built.id}${runtimeHint}`,diff --git a/packages/cli/src/observation.ts b/packages/cli/src/observation.tsindex aea5231f..e99239a6 100644--- a/packages/cli/src/observation.ts+++ b/packages/cli/src/observation.ts@@ -3,29 +3,167 @@ import type { BuildResultManifest } from "@hypit/build-result";import type { CliBuildSubmission, CliBuildView, CliRuntimeControl, CliRuntimeController } from "./runtime-port.js";import { formatOperationProgress } from "./runtime-view.js";+const FIRST_HEARTBEAT_MS = 30_000;+const LATER_HEARTBEAT_MS = 60_000;+const MIN_PROGRESS_INTERVAL_MS = 1_000;+export type BuildProgressView = {readonly build: string;- readonly phase: string;- readonly operations: Readonly<Record<string, number>>;- readonly activity: readonly string[];+ readonly state: "submitting" | "working" | "saving-result";+ readonly requests?: { readonly total: number; readonly completed: number };+ readonly phases: Readonly<Record<string, number>>;+ readonly elapsedMs: number;+ readonly details: readonly string[];};-function operationCounts(view: CliBuildView): Readonly<Record<string, number>> {- return Object.fromEntries([...new Set(view.operations.map((item) => item.status))]- .sort().map((state) => [state, view.operations.filter((item) => item.status === state).length]));+function progressPhases(view: CliBuildView): Readonly<Record<string, number>> {+ const phases = new Map<string, number>();+ for (const operation of view.operations.filter((item) => item.status === "pending")) {+ const phase = operation.progress?.phase ?? "in progress";+ phases.set(phase, (phases.get(phase) ?? 0) + 1);+ }+ return Object.fromEntries([...phases].sort(([left], [right]) => left.localeCompare(right)));+}++function progressState(view: CliBuildView): BuildProgressView["state"] {+ if (view.activity === "submitting") return "submitting";+ if (view.activity === "saving-result") return "saving-result";+ // `ready`, `running` and `waiting` describe short Worker scheduling turns, not three stages of a+ // video. They deliberately collapse into one stable product state.+ return "working";+}++export function buildProgressView(view: CliBuildView, now = Date.now()): BuildProgressView {+ return {+ build: view.id,+ state: progressState(view),+ ...(view.requests === undefined ? {} : { requests: view.requests }),+ phases: progressPhases(view),+ elapsedMs: Math.max(0, now - view.createdAt),+ details: view.operations+ .filter((item) => item.status === "pending")+ .map((item) => `${item.endpoint}: ${item.progress === undefined+ ? item.status+ : formatOperationProgress(item.progress)}`),+ };}/** Stable product-state projection for watch output and polling backoff. */export function buildObservationKey(view: CliBuildView): string {return JSON.stringify({- phase: view.activity,+ state: progressState(view),outcome: view.outcome,issue: view.issue,cancellationRequested: view.cancellationRequested,- operations: operationCounts(view),+ requests: view.requests,+ phases: progressPhases(view),+ });+}++/**+ * Stable Runtime activity projection. Capacity reservations are intentionally absent: they are+ * short implementation leases and can appear and disappear while no Build makes progress.+ */+export function activityObservationKey(+ worker: string,+ builds: readonly CliBuildView[],+): string {+ return JSON.stringify({+ worker,+ builds: [...builds]+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((view) => [view.id, buildObservationKey(view)]),});}+export function buildProgressLines(+ progress: BuildProgressView,+ options: { readonly verbose: boolean; readonly limit: number },+): readonly string[] {+ const state = {+ submitting: "Submitting",+ working: "Working",+ "saving-result": "Saving Result",+ }[progress.state];+ const requestProgress = progress.requests === undefined || progress.requests.total === 0+ ? []+ : [`${progress.requests.completed}/${progress.requests.total} steps complete`];+ const phases = Object.entries(progress.phases).map(([phase, count]) => `${count} ${phase}`);+ const seconds = Math.floor(progress.elapsedMs / 1_000);+ const elapsed = seconds < 60+ ? `${seconds}s`+ : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`;+ return [+ ` · ${[state, ...requestProgress, ...phases, elapsed].join(" · ")}`,+ ...(options.verbose ? progress.details.slice(0, options.limit).map((line) => ` ${line}`) : []),+ ];+}++/**+ * Follow one accepted active Build until it finishes, needs attention or reaches the caller's wait+ * bound. Runtime polling stays responsive; progress callbacks observe only the stable product view.+ */+export async function observeBuildView(+ runtime: Pick<CliRuntimeControl, "inspect">,+ build: string,+ initial: CliBuildView,+ options: {+ readonly maxWaitMs?: number;+ readonly controller?: CliRuntimeController;+ readonly onProgress?: (value: BuildProgressView) => void;+ } = {},+): Promise<CliBuildView | undefined> {+ let view: CliBuildView | undefined = initial;+ let observedProgress: string | undefined;+ let pendingProgress = false;+ let lastProgressAt: number | undefined;+ let pollDelayMs = 100;+ let observed = false;+ const startedAt = Date.now();+ let nextHeartbeatAt = startedAt + FIRST_HEARTBEAT_MS;+ while (view !== undefined && view.issue === undefined) {+ const nextProgress = buildObservationKey(view);+ const now = Date.now();+ if (nextProgress !== observedProgress) {+ observedProgress = nextProgress;+ pendingProgress = true;+ pollDelayMs = 100;+ } else {+ pollDelayMs = Math.min(1_000, pollDelayMs * 2);+ }+ const heartbeatDue = now >= nextHeartbeatAt;+ const progressDue = pendingProgress+ && (lastProgressAt === undefined || now - lastProgressAt >= MIN_PROGRESS_INTERVAL_MS);+ if (progressDue || heartbeatDue) {+ options.onProgress?.(buildProgressView(view, now));+ lastProgressAt = now;+ nextHeartbeatAt = now + (pendingProgress ? FIRST_HEARTBEAT_MS : LATER_HEARTBEAT_MS);+ pendingProgress = false;+ }+ const elapsedMs = Date.now() - startedAt;+ const remainingMs = options.maxWaitMs === undefined ? undefined : options.maxWaitMs - elapsedMs;+ if (remainingMs !== undefined && remainingMs <= 0) break;+ if (options.controller !== undefined) {+ const worker = await options.controller.worker.status();+ if (worker.state !== "running") {+ throw new Error(+ `Runtime Worker is ${worker.state}; Build ${build} remains durable. `+ + `Run hypit runtime up, then run hypit status ${build} --watch again`,+ );+ }+ }+ await new Promise((resolveWait) => setTimeout(resolveWait,+ remainingMs === undefined ? pollDelayMs : Math.min(pollDelayMs, remainingMs)));+ view = await runtime.inspect(build);+ observed = true;+ }+ if (observed && view !== undefined && options.maxWaitMs !== undefined+ && Date.now() - startedAt >= options.maxWaitMs) {+ view = await runtime.inspect(build);+ }+ return view;+}+/** Observe one submitted Build. This reads accepted state only and never performs execution work. */export async function observeBuild(runtime: Pick<CliRuntimeControl, "inspect">,@@ -37,68 +175,24 @@ export async function observeBuild(readonly onProgress?: (value: BuildProgressView) => void;},): Promise<CliBuildSubmission> {- let current = initial;- let lastProgress: string | undefined;- let pollDelayMs = 100;- let observedActivity = false;- const startedAt = Date.now();const finishFromResult = async (): Promise<CliBuildSubmission> => {const result = await options.readResult();if (result?.outcome === undefined) {- throw new Error(`Build ${current.id} left active Runtime state without a finished Result`);+ throw new Error(`Build ${initial.id} left active Runtime state without a finished Result`);}return {- id: current.id,- state: current.state,+ id: initial.id,+ state: initial.state,completion: {- build: current.id,+ build: initial.id,outcome: result.outcome,...(result.failure === undefined ? {} : { reason: result.failure }),},};};- while ("view" in current && current.view.issue === undefined) {- const elapsedMs = Date.now() - startedAt;- const remainingMs = options.maxWaitMs === undefined ? undefined : options.maxWaitMs - elapsedMs;- if (remainingMs !== undefined && remainingMs <= 0) break;- const waitMs = remainingMs === undefined ? pollDelayMs : Math.min(pollDelayMs, remainingMs);- await new Promise((resolveWait) => setTimeout(resolveWait, waitMs));- const view = await runtime.inspect(current.id);- observedActivity = true;- if (view === undefined) {- current = await finishFromResult();- break;- }- current = { id: current.id, state: current.state, view };- if (current.view.issue === undefined && options.controller !== undefined) {- const worker = await options.controller.worker.status();- if (worker.state !== "running") {- throw new Error(- `Runtime Worker is ${worker.state}; Build ${current.id} remains durable. `- + `Run hypit runtime up, then run hypit status ${current.id} --watch again`,- );- }- }- const operations = operationCounts(view);- const activity = view.operations- .filter((item) => item.status === "pending")- .map((item) => `${item.endpoint}: ${item.progress === undefined- ? item.status- : formatOperationProgress(item.progress)}`);- // Default observation reacts to product state, not every raw Provider progress detail.- const nextProgress = buildObservationKey(view);- if (nextProgress !== lastProgress) {- lastProgress = nextProgress;- pollDelayMs = 100;- options.onProgress?.({ build: current.id, phase: view.activity, operations, activity });- } else {- pollDelayMs = Math.min(1_000, pollDelayMs * 2);- }- }- if (observedActivity && "view" in current) {- const view = await runtime.inspect(current.id);- if (view === undefined) return await finishFromResult();- current = { id: current.id, state: current.state, view };- }- return current;+ if (!("view" in initial)) return initial;+ const view = await observeBuildView(runtime, initial.id, initial.view, options);+ return view === undefined+ ? await finishFromResult()+ : { id: initial.id, state: initial.state, view };}diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex 8f9574ae..6932ec4e 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -232,15 +232,17 @@ function renderAuthorCheck(const readable = view.machine.outputs;lines.push(...facts([["Source", shortPath(view.machine.source)],- ["Frontend", view.machine.frontend],- ["Modules", String(view.machine.modules)],- ["Units", String(view.machine.units)],["Outputs", String(view.machine.outputCount)],- ...(verbose && view.machine.details !== undefined- ? [["Values", String(view.machine.details.values.length)] as const] : []),- ["Assets", String(view.machine.assets)],+ ...(verbose ? [+ ["Frontend", view.machine.frontend] as const,+ ["Modules", String(view.machine.modules)] as const,+ ["Units", String(view.machine.units)] as const,+ ["Assets", String(view.machine.assets)] as const,+ ...(view.machine.details === undefined+ ? [] : [["Values", String(view.machine.details.values.length)] as const]),+ ] : []),], colors));- if (readable.length > 0) {+ if (verbose && readable.length > 0) {lines.push("", colors.strong("Outputs"));const ordered = [...readable].sort((left, right) => left.name.localeCompare(right.name));const width = Math.max(...ordered.map((item) => item.name.length));@@ -264,54 +266,80 @@ function renderRunCheck(view: Extract<CliPresentation, { kind: "check-run" }>,io: CliIo,colors: Palette,+ verbose: boolean,): string {const lines = [heading("success", "Run source is valid", io, colors), ""];+ const reuse = (view.machine.unresolvedHistoricalOutputs?.length ?? 0)+ + (view.machine.omittedHistoricalOutputs ?? 0);+ const targetSummary = view.machine.targets.length === 0+ ? String(view.machine.targetCount)+ : view.machine.targets.join(", ")+ + (view.machine.targets.length < view.machine.targetCount+ ? ` (+${view.machine.targetCount - view.machine.targets.length})`+ : "");lines.push(...facts([["Run", shortPath(view.machine.run)],- ["Author", shortPath(view.machine.author)],- ["Frontend", view.machine.frontend],- ["Targets", String(view.machine.targetCount)],- ["Candidates", String(view.machine.candidates)],- ["Satisfactions", String(view.machine.satisfactions)],- ...(view.machine.steps === undefined ? [] : [["Steps", String(view.machine.steps)] as const]),+ ["Targets", targetSummary],+ ...(reuse === 0 ? [] : [["Reuse", `${reuse} historical Output${reuse === 1 ? "" : "s"}`] as const]),+ ...(verbose ? [+ ["Author", shortPath(view.machine.author)] as const,+ ["Frontend", view.machine.frontend] as const,+ ["Candidates", String(view.machine.candidates)] as const,+ ["Satisfactions", String(view.machine.satisfactions)] as const,+ ...(view.machine.steps === undefined ? [] : [["Steps", String(view.machine.steps)] as const]),+ ] : []),], colors));const unresolved = view.machine.unresolvedHistoricalOutputs ?? [];- if (unresolved.length > 0) {- lines.push("", heading("warning", `${unresolved.length} historical Candidate${unresolved.length === 1 ? "" : "s"} unresolved`, io, colors));+ if (verbose && unresolved.length > 0) {+ lines.push("", colors.strong("Historical reuse"));for (const item of unresolved) lines.push(` ${item.candidate} ← ${item.build}/${item.output}`);if ((view.machine.omittedHistoricalOutputs ?? 0) > 0) {lines.push(` ${colors.dim(`${view.machine.omittedHistoricalOutputs} more · use --limit <count>`)}`);}- lines.push(` ${colors.dim("The Run source is valid. plan/build will resolve these Result values.")}`);}return `${lines.join("\n")}\n`;}+function operationLabel(operation: string): string {+ const name = operation.split("/").at(-1) ?? operation;+ return name.replace(/^request-/u, "").replaceAll("-", " ");+}+function renderPlan(view: Extract<CliPresentation, { kind: "plan" }>,io: CliIo,colors: Palette,+ verbose: boolean,): string {- const lines = [heading("success", "Build plan is valid", io, colors), ""];+ const lines = [heading(view.machine.ok ? "success" : "error",+ view.machine.ok ? "Build plan is valid" : "Build plan needs attention", io, colors), ""];+ const targetSummary = view.machine.targets.length === 0+ ? String(view.machine.targetCount)+ : view.machine.targets.join(", ")+ + (view.machine.targets.length < view.machine.targetCount+ ? ` (+${view.machine.targetCount - view.machine.targets.length})`+ : "");lines.push(...facts([["Run", shortPath(view.machine.run)],- ["Targets", String(view.machine.targetCount)],- ["Steps", String(view.machine.steps)],+ ["Targets", targetSummary],["External requests", String(view.machine.externalRequestCount)],+ ...(view.machine.preflight === undefined ? [] : [[+ "Preflight", view.machine.preflight.ok ? "ready" : "needs attention",+ ] as const]),+ ...(verbose ? [["Steps", String(view.machine.steps)] as const] : []),], colors));if (view.machine.externalRequests.length > 0) {lines.push("", colors.strong("External requests"));const countWidth = Math.max(...view.machine.externalRequests.map((item) => String(item.count).length));for (const item of view.machine.externalRequests) {- lines.push(` ${colors.warning(String(item.count).padStart(countWidth))} ${item.operation}`);+ lines.push(` ${colors.warning(String(item.count).padStart(countWidth))} ${verbose ? item.operation : operationLabel(item.operation)}`);}if ((view.machine.omittedExternalRequests ?? 0) > 0) {lines.push(` ${colors.dim(`${view.machine.omittedExternalRequests} more Operations · use --limit <count>`)}`);}- lines.push(` ${colors.dim("These Needs may reach the Endpoints selected by the Runtime Profile during build.")}`);}const unreached = view.machine.unreached ?? [];- if (unreached.length > 0) {+ if (verbose && unreached.length > 0) {lines.push("", colors.strong("Declared but not reached"));const width = Math.max(...unreached.map((item) => item.output.length));for (const item of unreached) {@@ -320,16 +348,16 @@ function renderPlan(if ((view.machine.omittedUnreached ?? 0) > 0) {lines.push(` ${colors.dim(`${view.machine.omittedUnreached} more · use --limit <count>`)}`);}- lines.push(` ${colors.dim("These Outputs are outside the selected target graph.")}`);}if (view.machine.preflight !== undefined- && (view.machine.preflight.capabilities.length > 0 || view.machine.preflight.diagnostics.length > 0)) {+ && (view.machine.preflight.diagnostics.length > 0+ || (verbose && view.machine.preflight.capabilities.length > 0))) {lines.push("", colors.strong("Runtime preflight"));- for (const capability of view.machine.preflight.capabilities) lines.push(` ${colors.accent(capability)}`);- if ((view.machine.preflight.omittedCapabilities ?? 0) > 0) {+ if (verbose) for (const capability of view.machine.preflight.capabilities) lines.push(` ${colors.accent(capability)}`);+ if (verbose && (view.machine.preflight.omittedCapabilities ?? 0) > 0) {lines.push(` ${colors.dim(`${view.machine.preflight.omittedCapabilities} more capabilities · use --limit <count>`)}`);}- if (view.machine.preflight.diagnostics.length === 0) {+ if (verbose && view.machine.preflight.diagnostics.length === 0) {lines.push(` ${colors.success(glyph(io, "✓", "+"))} required deployment slice is ready`);} else {for (const item of view.machine.preflight.diagnostics) {@@ -337,8 +365,10 @@ function renderPlan(lines.push(` ${mark} ${item.code}: ${item.message}`);}}- const capabilityCount = view.machine.preflight.capabilityCount;- lines.push(` ${colors.dim(`Runtime base checked; ${capabilityCount} demanded Endpoint ${capabilityCount === 1 ? "capability" : "capabilities"} checked.`)}`);+ if (verbose) {+ const capabilityCount = view.machine.preflight.capabilityCount;+ lines.push(` ${colors.dim(`${capabilityCount} demanded Endpoint ${capabilityCount === 1 ? "capability" : "capabilities"} checked.`)}`);+ }}if (view.machine.choices.length > 0) {lines.push("", colors.strong("Run choices"));@@ -379,9 +409,9 @@ export function writeCliOutput(: presentation.kind === "check-author"? renderAuthorCheck(presentation, io, colors, options.verbose): presentation.kind === "check-run"- ? renderRunCheck(presentation, io, colors)+ ? renderRunCheck(presentation, io, colors, options.verbose): presentation.kind === "plan"- ? renderPlan(presentation, io, colors)+ ? renderPlan(presentation, io, colors, options.verbose): renderOperational(presentation, io, colors);io.write(output);}@@ -401,7 +431,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("hypit check")),colors.dim("Validate one self-described Author Source or Run Source without executing it."),"",- " hypit check <source> [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>]",+ " hypit check <source> [--workspace <workspace>] [--asset-root <directory>]",],doctor: [colors.accent(colors.strong("hypit doctor")),@@ -423,7 +453,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("hypit build")),colors.dim("Submit one durable Build and ensure its selected Runtime Worker is available."),"",- " hypit build <run-source> [--title <text>] [--runtime <profile>] [--asset-root <directory>] [--follow]",+ " hypit build <run-source> [--title <text>] [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>] [--follow]",""," --title <text> give this Result a human-facing title"," --follow observe the Build; the Worker still owns execution",@@ -439,6 +469,9 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi" hypit runtime status [<profile>] inspect Worker, active Builds and declared programs"," hypit runtime logs [<profile>] [--lines <count>]"," hypit runtime down [<profile>] stop the Worker; external programs keep running",+ "",+ "The project is resolved first. Selection is read only from that project's .hypit/runtime.",+ "No Profile filename discovery or parent-project inheritance is performed.",],packages: [colors.accent(colors.strong("hypit packages")),diff --git a/packages/cli/src/project-context.ts b/packages/cli/src/project-context.tsindex 7fd2b2c7..51b553e7 100644--- a/packages/cli/src/project-context.ts+++ b/packages/cli/src/project-context.ts@@ -16,7 +16,23 @@ async function nearestProjectPackageRoot(start: string): Promise<string | undefi}}-/** Resolve package discovery independently from project-owned Result storage. */-export async function resolvePackageRoot(projectStart: string): Promise<string> {- return await nearestProjectPackageRoot(projectStart) ?? resolve(projectStart);+/**+ * Resolve the project before any Runtime selection is considered.+ *+ * An explicit Workspace is already the boundary. Otherwise the nearest+ * package.json declares the boundary; when none exists, cwd itself is the+ * explicit shell context. Source paths and Runtime state never choose it.+ */+export async function resolveProjectRoot(options: {+ readonly workspaceRoot?: string;+ readonly cwd?: string;+} = {}): Promise<string> {+ const start = resolve(options.workspaceRoot ?? options.cwd ?? process.cwd());+ if (options.workspaceRoot !== undefined) return start;+ return await nearestProjectPackageRoot(start) ?? start;+}++/** Project package discovery cannot escape an already resolved project. */+export async function resolvePackageRoot(projectRoot: string): Promise<string> {+ return resolve(projectRoot);}diff --git a/packages/cli/src/runtime-selection.ts b/packages/cli/src/runtime-selection.tsindex f837b39f..54b7e27e 100644--- a/packages/cli/src/runtime-selection.ts+++ b/packages/cli/src/runtime-selection.ts@@ -1,5 +1,5 @@import { mkdir, readFile, realpath, unlink, writeFile } from "node:fs/promises";-import { dirname, relative, resolve } from "node:path";+import { relative, resolve } from "node:path";const stateDirectoryName = ".hypit";const selectionFileName = "runtime";@@ -16,26 +16,22 @@ function errorCode(error: unknown): string | undefined {: undefined;}-async function readSelectionFile(start: string): Promise<{+async function readSelectionFile(projectRoot: string): Promise<{readonly projectRoot: string;readonly selectionFile: string;readonly value: string;} | undefined> {- let directory = resolve(start);- while (true) {- const selectionFile = resolve(directory, stateDirectoryName, selectionFileName);- try {- return {- projectRoot: directory,- selectionFile,- value: (await readFile(selectionFile, "utf8")).trim(),- };- } catch (error) {- if (errorCode(error) !== "ENOENT") throw error;- }- const parent = dirname(directory);- if (parent === directory) return undefined;- directory = parent;+ const root = resolve(projectRoot);+ const selectionFile = resolve(root, stateDirectoryName, selectionFileName);+ try {+ return {+ projectRoot: root,+ selectionFile,+ value: (await readFile(selectionFile, "utf8")).trim(),+ };+ } catch (error) {+ if (errorCode(error) === "ENOENT") return undefined;+ throw error;}}@@ -59,19 +55,19 @@ export async function selectRuntimeProfile(projectRoot: string, profile: string)return { profile: selectedProfile, projectRoot: root, selectionFile };}-/** Find the nearest project-local Runtime selection, starting at a file's directory or cwd. */-export async function findRuntimeProfile(start: string): Promise<RuntimeProfileSelection | undefined> {- const selected = await readSelectionFile(start);+/** Read only the explicitly resolved project's Runtime selection. */+export async function findRuntimeProfile(projectRoot: string): Promise<RuntimeProfileSelection | undefined> {+ const selected = await readSelectionFile(projectRoot);if (selected === undefined) return undefined;if (selected.value.length === 0) {throw new Error(`Runtime selection is empty: ${selected.selectionFile}; run hypit runtime use <profile>`);}- const projectRoot = await realpath(selected.projectRoot);- const candidate = resolve(projectRoot, selected.value);+ const root = selected.projectRoot;+ const candidate = resolve(root, selected.value);try {return {profile: await realpath(candidate),- projectRoot,+ projectRoot: root,selectionFile: selected.selectionFile,};} catch (error) {@@ -85,8 +81,8 @@ export async function findRuntimeProfile(start: string): Promise<RuntimeProfileS}/** Remove only the local pointer. Runtime state, Programs and Builds are untouched. */-export async function clearRuntimeProfile(start: string): Promise<RuntimeProfileSelection | undefined> {- const selected = await readSelectionFile(start);+export async function clearRuntimeProfile(projectRoot: string): Promise<RuntimeProfileSelection | undefined> {+ const selected = await readSelectionFile(projectRoot);if (selected === undefined) return undefined;const profile = resolve(selected.projectRoot, selected.value);await unlink(selected.selectionFile);diff --git a/packages/cli/src/view.ts b/packages/cli/src/view.tsindex 2f89da39..0ae57ad1 100644--- a/packages/cli/src/view.ts+++ b/packages/cli/src/view.ts@@ -54,9 +54,10 @@ export type CliBuildStatusView = {readonly id: string;readonly title?: string;readonly work: {- readonly state: "unknown" | "starting" | "active" | "waiting" | "done";+ readonly state: "unknown" | "submitting" | "working" | "done";readonly outcome?: "complete" | "failed" | "cancelled";readonly cancellationRequested?: boolean;+ readonly requests?: { readonly total: number; readonly completed: number };};readonly result: {readonly state: "missing" | "open" | "complete" | "failed" | "cancelled" | "unavailable";@@ -129,9 +130,8 @@ function orderedOutputNames(manifest: BuildResultManifest): readonly string[] {function workState(view: BuildView | undefined, result: BuildResultManifest | undefined): CliBuildStatusView["work"]["state"] {if (view === undefined) return result?.outcome === undefined ? "unknown" : "done";- if (view.activity === "submitting" || view.activity === "ready") return "starting";- if (view.activity === "running") return "active";- if (view.activity === "waiting") return "waiting";+ if (view.activity === "submitting") return "submitting";+ if (view.activity === "ready" || view.activity === "running" || view.activity === "waiting") return "working";return "done";}@@ -156,6 +156,7 @@ export function buildStatusView(options: {? {}: { outcome: options.runtime?.outcome ?? options.result!.outcome }),...(options.runtime?.cancellationRequested === true ? { cancellationRequested: true } : {}),+ ...(options.runtime?.requests === undefined ? {} : { requests: options.runtime.requests }),},result: {state: resultState,diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.tsindex 22a1eb28..f373eb38 100644--- a/packages/cli/test/build-programs.test.ts+++ b/packages/cli/test/build-programs.test.ts@@ -21,6 +21,8 @@ const io = { write: () => {} };function distribution(calls: string[],diagnostics: readonly RuntimeDoctorDiagnostic[],+ authorSource = "./main.svml",+ execution?: object,): CliDistribution {return {bootstrapPackages: [{@@ -29,10 +31,10 @@ function distribution(format: "hypit.node-package@1",hostFacets: [createRunFrontendHostFacet({id: "@hypit/run-markup@1",- discover: () => ({ author: { source: "./main.svml" }, imports: [] }),+ discover: () => ({ author: { source: authorSource }, imports: [] }),decode: () => ({ document: {format: "hypit.run-document@1",- author: { source: "./main.svml" },+ author: { source: authorSource },imports: [],targets: [{ output: "result" }],candidates: [],@@ -121,7 +123,10 @@ function distribution(}),preflight: async () => ({ dataRoot: "/tmp", diagnostics }),doctor: async () => ({ dataRoot: "/tmp", diagnostics: [] }),- createRuntime: async () => { throw new Error("createRuntime is unavailable"); },+ createRuntime: async () => {+ if (execution !== undefined) return execution;+ throw new Error("createRuntime is unavailable");+ },openControl: async () => ({ inspect: async () => undefined }),}),} as unknown as CliDistribution;@@ -168,6 +173,52 @@ test("Build accepts a Result title and never provisions programs after a clean passert.deepEqual(calls, []);});+test("Build confirms durable submission before following stable work progress", async () => {+ const calls: string[] = [];+ const source = await runSource();+ const execution = {+ async build(request: { readonly id: string }) {+ calls.push("build");+ return {+ id: request.id,+ state: {+ targets: [{ output: "result" }],+ plan: { outputBindings: [] },+ records: [],+ },+ view: {+ id: request.id,+ createdAt: Date.now(),+ activity: "ready",+ cancellationRequested: false,+ targets: ["result"],+ requests: { total: 0, completed: 0 },+ acceptedRecords: 0,+ outstandingCommands: 0,+ operations: [],+ },+ };+ },+ async close() {},+ };+ let output = "";++ await runCli(+ ["build", source, "--runtime", "/p/hypit.runtime.json", "--follow", "--max-wait-ms", "0"],+ { write(text) { output += text; } },+ distribution(calls, [], "./main.svml", execution),+ );++ assert.deepEqual(calls, ["build"]);+ const submitted = output.indexOf("Build submitted");+ const working = output.indexOf("· Working");+ const active = output.indexOf("Build still active");+ assert.ok(submitted >= 0 && working > submitted && active > working);+ assert.match(output, /Target\s+result/u);+ assert.match(output, /Work\s+0 external requests/u);+ assert.match(output, /Ctrl-C stops watching; the Build continues\./u);+});+test("plan preserves the selected work summary but exits non-zero when cheap preflight fails", async () => {const source = await runSource();let output = "";diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.tsindex fa01e854..ec666374 100644--- a/packages/cli/test/build-results.test.ts+++ b/packages/cli/test/build-results.test.ts@@ -71,6 +71,14 @@ async function jsonCommand(args: readonly string[], root: string): Promise<unknoreturn JSON.parse(output);}+async function humanCommand(args: readonly string[], root: string): Promise<string> {+ let output = "";+ await runCli([...args, "--workspace", root], {+ write(text) { output += text; },+ }, resultDistribution());+ return output;+}+test("builds, history, inspect and get read project Build Results without opening a Runtime", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-cli-results-"));try {@@ -105,6 +113,14 @@ test("builds, history, inspect and get read project Build Results without openinassert.equal(inspected.build.id, "bld_20260902T110000000Z_0000000001");assert.equal(inspected.build.title, "episode-stage");+ const humanHistory = await humanCommand(["history", "stage.value"], root);+ assert.match(humanHistory, /episode-stage/u);+ assert.doesNotMatch(humanHistory, /example\.result|scalar/u);++ const humanInspect = await humanCommand(["inspect", "bld_20260902T110000000Z_0000000001"], root);+ assert.match(humanInspect, /Target\s+stage\.value/u);+ assert.doesNotMatch(humanInspect, /example\.result|scalar/u);+const destination = join(root, "exported.json");const exported = await jsonCommand(["get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--to", destination,@@ -118,6 +134,13 @@ test("builds, history, inspect and get read project Build Results without openinpath: destination,});assert.equal(await readFile(destination, "utf8"), "\"ready\"\n");++ const humanDestination = join(root, "human-exported.json");+ const humanGet = await humanCommand([+ "get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--to", humanDestination,+ ], root);+ assert.match(humanGet, /Exported stage\.value → human-exported\.json/u);+ assert.doesNotMatch(humanGet, /\b(?:Type|Kind|Build)\b|example\.result|scalar/u);await assert.rejects(jsonCommand(["get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--to", destination], root),/Export destination .* already exists/u,diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.tsindex 65f3630a..2fcd55c5 100644--- a/packages/cli/test/control-commands.test.ts+++ b/packages/cli/test/control-commands.test.ts@@ -163,6 +163,70 @@ test("status reads a finished project Result without a Runtime", async () => {assert.deepEqual(calls, ["result.read:build-finished", "result.close"]);});+test("finished status defaults to the Result outcome without repeating internal layers", async () => {+ const distribution = {+ openProjectResults: async () => ({+ repository: {+ async read() {+ return {+ format: "hypit.build-result@2",+ id: "build-finished",+ source: { path: "main.svml" },+ targets: ["final.video"],+ finishedAt: 2,+ outcome: "complete",+ outputs: { "final.video": {} },+ };+ },+ },+ async close() {},+ }),+ } as unknown as CliDistribution;+ let output = "";++ await runCli(["status", "build-finished"], {+ write(text) { output += text; },+ }, distribution);++ assert.match(output, /Build complete/u);+ assert.match(output, /Outcome\s+complete/u);+ assert.doesNotMatch(output, /\bWork\b|\bDecision\b|\bResult\s+complete/u);+});++test("status separates execution from Result only while the Result is being saved", async () => {+ const view = {+ id: "build-saving",+ createdAt: 1,+ activity: "saving-result" as const,+ outcome: "complete" as const,+ cancellationRequested: false,+ targets: ["final.video"],+ acceptedRecords: 1,+ outstandingCommands: 0,+ operations: [],+ };+ const distribution = {+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openControl: async () => ({ async inspect() { return view; }, async close() {} }),+ }),+ openProjectResults: async () => ({+ repository: { async read() { return undefined; } },+ async close() {},+ }),+ } as unknown as CliDistribution;+ let output = "";++ await runCli(["status", view.id, "--runtime", "/tmp/runtime.json"], {+ write(text) { output += text; },+ }, distribution);++ assert.match(output, /Saving Build Result/u);+ assert.match(output, /Execution\s+complete/u);+ assert.match(output, /Result\s+saving/u);+ assert.doesNotMatch(output, /Build complete|Outcome\s+complete/u);+});+test("status preserves Runtime decision and attention when its Result Store is unavailable", async () => {const view = {id: "build-result-unavailable",diff --git a/packages/cli/test/observation.test.ts b/packages/cli/test/observation.test.tsnew file mode 100644index 00000000..ef4383c0--- /dev/null+++ b/packages/cli/test/observation.test.ts@@ -0,0 +1,96 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ activityObservationKey,+ buildObservationKey,+ buildProgressLines,+ buildProgressView,+ observeBuildView,+} from "../src/observation.js";+import type { BuildProgressView } from "../src/observation.js";+import type { CliBuildView, CliRuntimeControl } from "../src/runtime-port.js";++function view(+ activity: CliBuildView["activity"],+ pending: number,+ completed: number,+): CliBuildView {+ return {+ id: "bld_20260903T000000000Z_0000000000",+ createdAt: Date.now(),+ activity,+ cancellationRequested: false,+ targets: ["final.video"],+ requests: { total: pending + completed, completed },+ acceptedRecords: 0,+ outstandingCommands: pending,+ operations: [+ ...Array.from({ length: pending }, () => ({+ endpoint: "kie.default",+ status: "pending" as const,+ progress: { phase: "generating" },+ })),+ ...Array.from({ length: completed }, () => ({ endpoint: "kie.default", status: "completed" as const })),+ ],+ };+}++test("Build observation ignores Worker turn churn and coalesces rapid real progress", async () => {+ const running = view("running", 7, 0);+ const waiting = view("waiting", 7, 0);+ const ready = view("ready", 7, 0);+ const advanced = view("running", 6, 1);+ assert.equal(buildObservationKey(running), buildObservationKey(waiting));+ assert.equal(buildObservationKey(waiting), buildObservationKey(ready));+ assert.notEqual(buildObservationKey(ready), buildObservationKey(advanced));++ const snapshots: Array<CliBuildView | undefined> = [waiting, ready, advanced, undefined];+ const progress: BuildProgressView[] = [];+ const runtime = {+ async inspect() { return snapshots.shift(); },+ } as Pick<CliRuntimeControl, "inspect">;++ const finished = await observeBuildView(runtime, running.id, running, {+ onProgress: (item) => progress.push(item),+ });++ assert.equal(finished, undefined);+ assert.deepEqual(progress.map((item) => item.requests), [+ { total: 7, completed: 0 },+ ]);+ assert.deepEqual(progress.map((item) => item.phases), [+ { generating: 7 },+ ]);+ assert.deepEqual(buildProgressLines(+ buildProgressView({ ...running, createdAt: 1_000 }, 32_000),+ { verbose: false, limit: 20 },+ ), [+ " · Working · 0/7 steps complete · 7 generating · 31s",+ ]);+});++test("Runtime activity ignores capacity leases but observes Build progress", () => {+ const running = view("running", 7, 0);+ const waiting = view("waiting", 7, 0);+ const ready = view("ready", 7, 0);+ const advanced = view("running", 6, 1);+ const other = { ...advanced, id: "bld_20260903T000000001Z_0000000000" };++ assert.equal(+ activityObservationKey("running", [running]),+ activityObservationKey("running", [waiting]),+ );+ assert.equal(+ activityObservationKey("running", [waiting]),+ activityObservationKey("running", [ready]),+ );+ assert.notEqual(+ activityObservationKey("running", [waiting]),+ activityObservationKey("running", [advanced]),+ );+ assert.equal(+ activityObservationKey("running", [running, other]),+ activityObservationKey("running", [other, running]),+ );+});diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex 11eb8b85..8cc715d3 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -14,8 +14,8 @@ function capture(const human = { json: false, color: "auto", verbose: false } as const;-test("author check exposes author-facing Outputs, not graph or resource identities", () => {- const output = capture(human, {+test("author check keeps the default summary compact and reserves Output types for verbose", () => {+ const presentation = {kind: "check-author",machine: {format: "hypit.cli-check@2",@@ -29,10 +29,14 @@ test("author check exposes author-facing Outputs, not graph or resource identitioutputCount: 1,outputs: [{ name: "story", type: "@hypit/narrative@1/Narrative" }],},- });+ } as const;+ const output = capture(human, presentation);assert.match(output, /✓ Source is valid/u);- assert.match(output, /story\s+@hypit\/narrative@1\/Narrative/u);+ assert.doesNotMatch(output, /story|@hypit\/narrative/u);assert.doesNotMatch(output, /resource|logical-output|res_/u);++ const verbose = capture({ ...human, verbose: true }, presentation);+ assert.match(verbose, /story\s+@hypit\/narrative@1\/Narrative/u);});test("JSON mode writes exactly the stable command view", () => {@@ -49,8 +53,8 @@ test("JSON mode writes exactly the stable command view", () => {assert.doesNotMatch(output, /Hypit Doctor|\u001b\[/u);});-test("plan presents named choices and bounded external request summaries", () => {- const output = capture(human, {+test("plan presents useful choices and readable requests without default graph internals", () => {+ const presentation = {kind: "plan",machine: {format: "hypit.cli-plan@2",@@ -61,13 +65,50 @@ test("plan presents named choices and bounded external request summaries", () =>steps: 2,externalRequestCount: 1,externalRequests: [{ operation: "@hypit/media@1/inspect", count: 1 }],+ preflight: {+ ok: true,+ capabilityCount: 1,+ capabilities: ["@hypit/media@1/inspect"],+ diagnosticCount: 0,+ diagnostics: [],+ },choiceCount: 1,choices: [{ output: "take.video", candidate: "preview" }],+ unreached: [{ output: "unused.image", operation: "@hypit/gpt-image@1/request-gpt-image-2" }],},- });+ } as const;+ const output = capture(human, presentation);assert.match(output, /take\.video\s+← preview/u);- assert.match(output, /1\s+@hypit\/media@1\/inspect/u);- assert.doesNotMatch(output, /logical:|record:|step-/u);+ assert.match(output, /1\s+inspect/u);+ assert.match(output, /Preflight\s+ready/u);+ assert.doesNotMatch(output, /Runtime\s+ready/u);+ assert.doesNotMatch(output, /@hypit\/media|unused\.image|Declared but not reached|logical:|record:|step-/u);++ const verbose = capture({ ...human, verbose: true }, presentation);+ assert.match(verbose, /1\s+@hypit\/media@1\/inspect/u);+ assert.match(verbose, /unused\.image/u);+});++test("run check treats historical reuse as a normal summary", () => {+ const output = capture(human, {+ kind: "check-run",+ machine: {+ format: "hypit.cli-check@2",+ sourceKind: "run",+ ok: true,+ run: "/project/build.svrun",+ author: "/project/main.svml",+ frontend: "@hypit/run-markup@1",+ targetCount: 1,+ targets: ["final.video"],+ candidates: 1,+ satisfactions: 1,+ unresolvedHistoricalOutputs: [{ candidate: "previous", build: "bld_previous", output: "take.video" }],+ },+ });+ assert.match(output, /Targets\s+final\.video/u);+ assert.match(output, /Reuse\s+1 historical Output/u);+ assert.doesNotMatch(output, /unresolved|bld_previous|Candidate/u);});test("help is concise and describes stable rather than complete output", () => {diff --git a/packages/cli/test/programs-command.test.ts b/packages/cli/test/programs-command.test.tsindex 17608235..18fdab94 100644--- a/packages/cli/test/programs-command.test.ts+++ b/packages/cli/test/programs-command.test.ts@@ -89,6 +89,37 @@ test("program status may report down without failing the observation", async ()assert.match(output, /speech-evidence\.local: down/u);});+test("program startup reports actions, not no-op checks", async () => {+ let output = "";+ const selected = {+ bootstrapPackages: [],+ openRuntimeHost: async (path: string) => ({+ profile: path,+ prepare: async () => [],+ controller: async () => ({+ worker: {},+ programs: {+ async up(options: { readonly onProgress?: (event: { readonly id: string; readonly phase: "checking" | "starting" | "waiting" | "ready" }) => void }) {+ options.onProgress?.({ id: "example", phase: "checking" });+ options.onProgress?.({ id: "example", phase: "starting" });+ options.onProgress?.({ id: "example", phase: "waiting" });+ options.onProgress?.({ id: "example", phase: "ready" });+ return { dataRoot: "/tmp", programs: [{ id: "example", instances: [], state: { state: "ready" } }] };+ },+ },+ }),+ }),+ } as unknown as CliDistribution;++ await runCli(["programs", "up", "/project/hypit.runtime.json"], {+ write(text) { output += text; },+ }, selected);++ assert.match(output, /· Starting example/u);+ assert.match(output, /External programs ready/u);+ assert.doesNotMatch(output, /· (?:Checking|Waiting for|Ready) example/u);+});+test("runtime up validates the Runtime before it starts Programs", async () => {const calls: string[] = [];const base = distribution(calls);@@ -107,3 +138,32 @@ test("runtime up validates the Runtime before it starts Programs", async () => {);assert.deepEqual(calls, []);});++test("runtime status keeps scheduling phases out of the default view", async () => {+ let output = "";+ const selected = {+ bootstrapPackages: [],+ openRuntimeHost: async (path: string) => ({+ profile: path,+ controller: async () => ({+ worker: { status: async () => ({ state: "running", profile: path, logPath: "/tmp/worker.log" }) },+ programs: { report: async () => ({+ dataRoot: "/tmp",+ programs: [{ id: "renderer", instances: [], state: { state: "ready" } }],+ }) },+ }),+ openControl: async () => ({+ activity: async () => ({ builds: [], capacity: [] }),+ close: async () => {},+ }),+ }),+ } as unknown as CliDistribution;++ await runCli(["runtime", "status", "/project/hypit.runtime.json"], {+ write(text) { output += text; },+ }, selected);++ assert.match(output, /Runtime deployment ready/u);+ assert.match(output, /Active Builds\s+0/u);+ assert.doesNotMatch(output, /\bStarting\b|\bWaiting\b|\bDecided\b|Running turn|Capacity in use/u);+});diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.tsindex 83c470b5..2981b5a4 100644--- a/packages/cli/test/runtime-selection.test.ts+++ b/packages/cli/test/runtime-selection.test.ts@@ -5,24 +5,37 @@ import { join, resolve } from "node:path";import test from "node:test";import type { CliDistribution } from "../src/distribution.js";+import { parseCommand } from "../src/arguments.js";import { runCli } from "../src/main.js";+import { resolveProjectRoot } from "../src/project-context.js";import type { CliRuntimeControl } from "../src/runtime-port.js";import { findRuntimeProfile, selectRuntimeProfile } from "../src/runtime-selection.js";-test("project Runtime selection is a relative local pointer discovered from nested sources", async () => {+test("check has no Runtime context", () => {+ assert.throws(+ () => parseCommand(["check", "main.svml", "--runtime", "runtime.json"]),+ /--runtime does not apply to check/u,+ );+});++test("project resolution precedes exact project Runtime selection", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-runtime-selection-"));try {const nested = join(root, "sources", "chapter");const profile = join(root, "runtime", "local.json");await mkdir(nested, { recursive: true });await mkdir(join(root, "runtime"), { recursive: true });+ await writeFile(join(root, "package.json"), "{}\n", "utf8");await writeFile(profile, "{}\n", "utf8");const selected = await selectRuntimeProfile(root, profile);assert.equal(selected.profile, await realpath(profile));assert.equal((await readFile(join(root, ".hypit", "runtime"), "utf8")).trim(), join("runtime", "local.json"));- const found = await findRuntimeProfile(nested);+ assert.equal(await findRuntimeProfile(nested), undefined);+ const project = await resolveProjectRoot({ cwd: nested });+ assert.equal(project, resolve(root));+ const found = await findRuntimeProfile(project);assert.equal(found?.profile, selected.profile);assert.equal(await realpath(found!.projectRoot), selected.projectRoot);} finally {@@ -30,6 +43,24 @@ test("project Runtime selection is a relative local pointer discovered from nest}});+test("a parent Runtime selection never becomes a child project's selection", async () => {+ const parent = await mkdtemp(join(tmpdir(), "hypit-runtime-parent-"));+ try {+ const child = join(parent, "child");+ const profile = join(parent, "runtime.json");+ await mkdir(child, { recursive: true });+ await writeFile(join(child, "package.json"), "{}\n", "utf8");+ await writeFile(profile, "{}\n", "utf8");+ await selectRuntimeProfile(parent, profile);++ const project = await resolveProjectRoot({ cwd: child });+ assert.equal(project, resolve(child));+ assert.equal(await findRuntimeProfile(project), undefined);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("runtime use lets later CLI commands reuse the selected Profile", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-runtime-cli-"));const previous = process.cwd();diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.tsindex 5d5e8bfd..5ac5e9bd 100644--- a/packages/runtime-host-node/src/index.ts+++ b/packages/runtime-host-node/src/index.ts@@ -51,6 +51,8 @@ export type BuildView = {readonly source?: { readonly path: string };readonly run?: { readonly path: string };readonly targets: readonly string[];+ /** External Needs in the frozen Build Plan and the subset already accepted by Core. */+ readonly requests?: { readonly total: number; readonly completed: number };readonly acceptedRecords: number;readonly outstandingCommands: number;readonly operations: readonly BuildOperationView[];diff --git a/packages/runtime-local/src/control.ts b/packages/runtime-local/src/control.tsindex 0057d8b5..baf43b27 100644--- a/packages/runtime-local/src/control.ts+++ b/packages/runtime-local/src/control.ts@@ -34,6 +34,13 @@ function buildView(input: {if (name === undefined) throw new Error(`Build ${input.build} target ${target.output} has no published Output name`);return name;}) ?? [];+ const requests = input.snapshot === undefined ? undefined : {+ total: input.snapshot.definition.plan.steps.reduce(+ (total, step) => total + Object.keys(step.needs).length,+ 0,+ ),+ completed: input.snapshot.facts.filter((fact) => fact.kind === "need-applied").length,+ };return {id: input.build,createdAt,@@ -46,6 +53,7 @@ function buildView(input: {...(input.catalog?.source === undefined ? {} : { source: input.catalog.source }),...(input.catalog?.run === undefined ? {} : { run: input.catalog.run }),targets,+ ...(requests === undefined ? {} : { requests }),acceptedRecords: input.snapshot?.state.records.length ?? 0,outstandingCommands: input.snapshot?.state.outstanding.length ?? 0,operations: input.operations.map((operation) => ({diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.tsindex 5a8dd04c..badc322b 100644--- a/packages/runtime-local/test/local.test.ts+++ b/packages/runtime-local/test/local.test.ts@@ -117,6 +117,7 @@ test("a Worker that lost Runtime ownership cannot claim a ready Build", async ()await assert.rejects(runtime.workOnce(), /no longer owns this Runtime/u);const status = await runtime.inspect("bld_20260902T120000000Z_0000000001");assert.equal(status?.activity, "ready");+ assert.deepEqual(status?.requests, { total: 1, completed: 0 });await runtime.close();} finally {await rm(directory, { recursive: true, force: true });