@tea-agent/loop-agent 0.52.0 → 0.53.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -5
- package/dist/build-stamp.json +3 -3
- package/dist/executors/dag-pi/plan/finalize-tools.js +13 -0
- package/dist/executors/dag-pi/plan/record-tools.js +37 -11
- package/dist/executors/dag-pi/sessions/plan-batches.js +1 -1
- package/dist/executors/dag-pi/sessions/segmented-plan.js +28 -20
- package/dist/executors/dag-pi/tools/plan-decision-tools.js +2 -1
- package/dist/executors/dag-pi-executor.js +50 -5
- package/dist/executors/pi-executor.js +12 -0
- package/dist/executors/pi-sdk-executor.js +2 -2
- package/dist/shared/frontend-execution-policy.js +28 -2
- package/dist/task/config-types.js +2 -2
- package/dist/task/source-prepare/prepare.js +1 -1
- package/dist/task/source-prepare/semantic-intake.js +2 -2
- package/dist/task/source-prepare/source-fidelity-pi.js +2 -1
- package/dist/workflows/dag/checkpoint.js +6 -1
- package/dist/workflows/dag/frontend-committed-facts.js +38 -5
- package/dist/workflows/dag/frontend-design-policy.js +22 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +39 -12
- package/dist/workflows/dag/frontend-imported-run-artifacts.js +126 -0
- package/dist/workflows/dag/frontend-recovery-run.js +7 -110
- package/dist/workflows/dag/frontend-test-framework-adapters.js +14 -0
- package/dist/workflows/dag/frontend-verification-trace.js +20 -8
- package/dist/workflows/dag/frontend-writer-reuse.js +104 -0
- package/dist/workflows/dag/frontend-writer-status.js +0 -4
- package/dist/workflows/dag/hybrid/templates/frontend.js +15 -8
- package/dist/workflows/dag/init-hybrid.js +1 -1
- package/dist/workflows/dag/reconcile-run.js +11 -1
- package/dist/workflows/dag/recovery-lease.js +23 -0
- package/dist/workflows/dag/rerun-feedback.js +4 -2
- package/dist/workflows/dag/rerun-run.js +40 -0
- package/dist/workflows/dag/runner.js +11 -0
- package/dist/workflows/dag/terminal-status.js +2 -1
- package/package.json +3 -3
|
@@ -404,8 +404,8 @@ const taskConfigObjectSchema = z.object({
|
|
|
404
404
|
* default; raise to 2-3 for more tolerance of transient verify failures). */
|
|
405
405
|
frontendRecovery: z
|
|
406
406
|
.object({
|
|
407
|
-
/**
|
|
408
|
-
maxProviderRequests: z.number().int().positive().optional(),
|
|
407
|
+
/** Task-lifetime request quota; null explicitly disables admission, omitted defaults to 1024. */
|
|
408
|
+
maxProviderRequests: z.number().int().positive().nullable().optional(),
|
|
409
409
|
maxContinuations: z
|
|
410
410
|
.number()
|
|
411
411
|
.int()
|
|
@@ -781,7 +781,7 @@ async function prepareTaskSourceInExecution(input) {
|
|
|
781
781
|
// A previously ordinary intake may only become frontend after deterministic
|
|
782
782
|
// source classification. Admit its observed requests before further work;
|
|
783
783
|
// dry-run must remain read-only.
|
|
784
|
-
if (input.mode === "apply") {
|
|
784
|
+
if (input.mode === "apply" && existingTaskConfig?.frontendRecovery?.maxProviderRequests !== null) {
|
|
785
785
|
await openTaskSourceProviderBudget({ repoRoot, taskId, maxProviderRequests: existingTaskConfig?.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
786
786
|
}
|
|
787
787
|
// An imported PRD is materialized under sourceIntegrity rather than copied
|
|
@@ -601,7 +601,7 @@ export async function runSemanticIntake(input) {
|
|
|
601
601
|
const result = await observeSourceExecution({ repoRoot: input.repoRoot, taskId: input.taskId, taskKind: input.flags.taskKind ?? input.taskKind, phase: "semantic-intake", inputIdentity: { documents: input.documents, flags: input.flags, title: input.title } }, () => runSemanticIntakeInExecution(input));
|
|
602
602
|
// Classification happens after the request. Admit only complete observed
|
|
603
603
|
// usage, after its source execution has closed, if the result selects frontend.
|
|
604
|
-
if (result.ok && result.draft.taskKind === "frontend-implementation" && input.fixtureAssistantText === undefined) {
|
|
604
|
+
if (result.ok && result.draft.taskKind === "frontend-implementation" && input.fixtureAssistantText === undefined && config.frontendRecovery?.maxProviderRequests !== null) {
|
|
605
605
|
await openTaskSourceProviderBudget({ ...input, maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
606
606
|
}
|
|
607
607
|
return result;
|
|
@@ -681,7 +681,7 @@ async function runSemanticIntakeInExecution(input) {
|
|
|
681
681
|
}
|
|
682
682
|
const config = await loadTaskConfig(input.repoRoot, input.taskId);
|
|
683
683
|
const taskKind = input.flags.taskKind ?? input.taskKind ?? config.taskKind;
|
|
684
|
-
const reserveProviderRequest = taskKind === "frontend-implementation" ? await openTaskSourceProviderBudget({
|
|
684
|
+
const reserveProviderRequest = taskKind === "frontend-implementation" && config.frontendRecovery?.maxProviderRequests !== null ? await openTaskSourceProviderBudget({
|
|
685
685
|
repoRoot: input.repoRoot, taskId: input.taskId,
|
|
686
686
|
maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024,
|
|
687
687
|
}) : undefined;
|
|
@@ -435,6 +435,7 @@ export async function resolveProductionSourceFidelityPi(input) {
|
|
|
435
435
|
if (effectiveTaskKind !== SOURCE_FIDELITY_TASK_KIND)
|
|
436
436
|
return undefined;
|
|
437
437
|
const config = await loadTaskConfig(input.repoRoot, input.taskId);
|
|
438
|
-
const reserveProviderRequest =
|
|
438
|
+
const reserveProviderRequest = config.frontendRecovery?.maxProviderRequests === null ? undefined
|
|
439
|
+
: await openTaskSourceProviderBudget({ ...input, maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
439
440
|
return createProductionSourceFidelityPi({ repoRoot: input.repoRoot, taskId: input.taskId, reserveProviderRequest });
|
|
440
441
|
}
|
|
@@ -347,7 +347,7 @@ export async function executeDagCheckpoint(input) {
|
|
|
347
347
|
}
|
|
348
348
|
},
|
|
349
349
|
runDir,
|
|
350
|
-
abortSignal
|
|
350
|
+
abortSignal,
|
|
351
351
|
createExecuteNodeForRank: (rankWriterNodeIds) => buildRankAwareExecuteNode({
|
|
352
352
|
baseExecuteNode,
|
|
353
353
|
customExecuteNode: input.executeNode,
|
|
@@ -445,6 +445,11 @@ export async function executeDagCheckpoint(input) {
|
|
|
445
445
|
// makes run-dag exit non-zero after every node already finished.
|
|
446
446
|
clearInterval(heartbeatTimer);
|
|
447
447
|
await stateWriteQueue;
|
|
448
|
+
// Cancellation owns the run outcome even when the in-flight node was
|
|
449
|
+
// the last node or an earlier node already recorded another failure.
|
|
450
|
+
// Preserve individual node outcomes, but never start recovery after abort.
|
|
451
|
+
if (abortSignal?.aborted)
|
|
452
|
+
state.failureCategory = "controller-interrupted";
|
|
448
453
|
state.finishedAt = new Date().toISOString();
|
|
449
454
|
const runDirBeforeTransfer = runDir;
|
|
450
455
|
await writeBudgetLedgerArtifacts(runDir, state.budgetLedger);
|
|
@@ -124,13 +124,26 @@ export function assemblePlanPatchFromCommittedFacts(records, contractRequirement
|
|
|
124
124
|
const stateFlows = facts.filter((fact) => fact.kind === "state-flow");
|
|
125
125
|
const stateByName = new Map();
|
|
126
126
|
const unnamedStates = [];
|
|
127
|
+
// A shared interaction has one contribution per requirement. A later
|
|
128
|
+
// non-goal batch must not replace the positive behavior from another batch.
|
|
129
|
+
// Corrections replace only their scope; an unscoped correction is global.
|
|
127
130
|
const interactionByName = new Map();
|
|
128
131
|
const unnamedInteractions = [];
|
|
129
132
|
for (const flow of stateFlows) {
|
|
130
133
|
for (const name of asStringArray(flow.removeUiStateNames))
|
|
131
134
|
stateByName.delete(name);
|
|
132
|
-
|
|
133
|
-
|
|
135
|
+
const scope = asStringArray(flow.scopeRequirementIds);
|
|
136
|
+
for (const name of asStringArray(flow.removeInteractionNames)) {
|
|
137
|
+
if (scope.length === 0)
|
|
138
|
+
interactionByName.delete(name);
|
|
139
|
+
else {
|
|
140
|
+
const contributions = interactionByName.get(name);
|
|
141
|
+
for (const owner of scope)
|
|
142
|
+
contributions?.delete(owner);
|
|
143
|
+
if (contributions?.size === 0)
|
|
144
|
+
interactionByName.delete(name);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
134
147
|
for (const state of Array.isArray(flow.uiStates) ? flow.uiStates : []) {
|
|
135
148
|
if (!isRecord(state))
|
|
136
149
|
continue;
|
|
@@ -144,20 +157,40 @@ export function assemblePlanPatchFromCommittedFacts(records, contractRequirement
|
|
|
144
157
|
if (!isRecord(interaction))
|
|
145
158
|
continue;
|
|
146
159
|
const name = asString(interaction.name);
|
|
147
|
-
if (name)
|
|
148
|
-
|
|
160
|
+
if (name) {
|
|
161
|
+
const contributions = scope.length === 0
|
|
162
|
+
? new Map()
|
|
163
|
+
: interactionByName.get(name) ?? new Map();
|
|
164
|
+
for (const owner of scope.length ? scope : [""])
|
|
165
|
+
contributions.set(owner, interaction);
|
|
166
|
+
interactionByName.set(name, contributions);
|
|
167
|
+
}
|
|
149
168
|
else
|
|
150
169
|
unnamedInteractions.push(interaction);
|
|
151
170
|
}
|
|
152
171
|
}
|
|
153
172
|
if (stateFlows.length > 0) {
|
|
154
173
|
patch.uiStates = [...stateByName.values(), ...unnamedStates];
|
|
155
|
-
patch.interactions = [...interactionByName.values()
|
|
174
|
+
patch.interactions = [...interactionByName.values()].map(contributions => {
|
|
175
|
+
const entries = [...new Set(contributions.values())];
|
|
176
|
+
const merged = { ...entries.at(-1) };
|
|
177
|
+
for (const field of ["trigger", "expectedBehavior"]) {
|
|
178
|
+
merged[field] = [...new Set(entries.map(entry => asString(entry[field])).filter(Boolean))].join("\n");
|
|
179
|
+
}
|
|
180
|
+
for (const field of ["implementationTargets", "verificationTargetIds"]) {
|
|
181
|
+
merged[field] = [...new Set(entries.flatMap(entry => asStringArray(entry[field])))];
|
|
182
|
+
}
|
|
183
|
+
return merged;
|
|
184
|
+
}).concat(unnamedInteractions);
|
|
156
185
|
}
|
|
157
186
|
const mockApi = lastByKind("mock-api");
|
|
158
187
|
if (!mockApi && facts.some(f => f.kind === "mock-endpoint" && f.removed !== true))
|
|
159
188
|
throw Error("MOCK_POLICY_MISSING: endpoint has no policy");
|
|
160
189
|
if (mockApi && isRecord(mockApi.mockApi)) {
|
|
190
|
+
if (typeof mockApi.realIntegrationGap === "string" && mockApi.realIntegrationGap.trim())
|
|
191
|
+
patch.realIntegrationGap = mockApi.realIntegrationGap;
|
|
192
|
+
if (Array.isArray(mockApi.residualRisks))
|
|
193
|
+
patch.residualRisks = asStringArray(mockApi.residualRisks);
|
|
161
194
|
const endpoints = new Map();
|
|
162
195
|
for (const endpoint of Array.isArray(mockApi.mockApi.endpoints) ? mockApi.mockApi.endpoints : []) {
|
|
163
196
|
if (isRecord(endpoint))
|
|
@@ -396,6 +396,27 @@ export function checkDesignApproval(designApproval) {
|
|
|
396
396
|
}
|
|
397
397
|
return [];
|
|
398
398
|
}
|
|
399
|
+
/** A component keeps one creation/reuse decision across Plan scopes. */
|
|
400
|
+
export function checkComponentChoiceConsistency(contract) {
|
|
401
|
+
const groups = new Map();
|
|
402
|
+
for (const choice of contract.uiComponentChoices ?? []) {
|
|
403
|
+
const name = choice.component.trim();
|
|
404
|
+
const group = groups.get(name) ?? [];
|
|
405
|
+
group.push(choice);
|
|
406
|
+
groups.set(name, group);
|
|
407
|
+
}
|
|
408
|
+
return [...groups].flatMap(([component, choices]) => {
|
|
409
|
+
const decisions = new Set(choices.map(choice => choice.decision));
|
|
410
|
+
// specified identifies a specification, not whether the component exists.
|
|
411
|
+
if (!decisions.has("new") || !decisions.has("reuse-existing"))
|
|
412
|
+
return [];
|
|
413
|
+
return [{
|
|
414
|
+
code: "component-choice-inconsistent",
|
|
415
|
+
path: component,
|
|
416
|
+
message: `Component "${component}" has conflicting decisions: ${choices.map(choice => `${choice.purpose}=${choice.decision}`).join(", ")}. Inspect the baseline and replace each conflicting record_component_choice using its original purpose, keeping all covers and supporting evidence. Keep creation/reuse consistent across scopes; do not remove requirement coverage.`,
|
|
417
|
+
}];
|
|
418
|
+
});
|
|
419
|
+
}
|
|
399
420
|
/**
|
|
400
421
|
* UX vocabulary collisions (item ③, dogfood dag-1788504923861-0f7b17a9):
|
|
401
422
|
* prioritize-planner-task / prioritizePlannerTask / prioritize-planner-tasks
|
|
@@ -734,6 +755,7 @@ export function evaluateFrontendDesignPolicy(input) {
|
|
|
734
755
|
...checkDependencies(input.contract, input.allowedDependencies),
|
|
735
756
|
...checkUiStateAttribution(input.contract),
|
|
736
757
|
...checkUxNameCollisions(input.contract),
|
|
758
|
+
...checkComponentChoiceConsistency(input.contract),
|
|
737
759
|
...checkRequiredDeliverables(input.contract),
|
|
738
760
|
...checkImplementationSlices(input.contract, input.writeSetPatterns),
|
|
739
761
|
...checkDesignInputBindings(input.contract, input.sourceFreshness),
|
|
@@ -18,7 +18,7 @@ export { extractRequiredDeliverablePaths } from "./frontend-contract-facts.js";
|
|
|
18
18
|
// Cycle-safe value imports: the check functions are hoisted declarations used
|
|
19
19
|
// only at call time, so the contract module and the policy module can depend
|
|
20
20
|
// on each other without module-init ordering issues.
|
|
21
|
-
import { checkDependencies, checkImplementationSlices, checkDesignInputBindings, checkTargetPaths, checkUiDesignCoverage, checkUiStateAttribution, checkRequiredDeliverables, checkUxNameCollisions, } from "./frontend-design-policy.js";
|
|
21
|
+
import { checkDependencies, checkImplementationSlices, checkDesignInputBindings, checkTargetPaths, checkUiDesignCoverage, checkUiStateAttribution, checkRequiredDeliverables, checkUxNameCollisions, checkComponentChoiceConsistency, } from "./frontend-design-policy.js";
|
|
22
22
|
import { isDagSourceBindingV2 } from "./types.js";
|
|
23
23
|
import { canonicalContractRel, classifyStructuredContractFailure, formatStructuredArtifactPointer, persistRuntimeSkeleton, } from "./structured-output-repair.js";
|
|
24
24
|
import { renderFrontendPlanMarkdown } from "./frontend-plan-render.js";
|
|
@@ -553,32 +553,48 @@ export async function deriveFrontendInteractionIdsFromRun(runDir) {
|
|
|
553
553
|
try {
|
|
554
554
|
raw = await readFile(specPath, "utf8");
|
|
555
555
|
}
|
|
556
|
-
catch {
|
|
557
|
-
|
|
556
|
+
catch (error) {
|
|
557
|
+
if (error.code === "ENOENT")
|
|
558
|
+
return [];
|
|
559
|
+
throw error;
|
|
558
560
|
}
|
|
561
|
+
const invalid = () => new Error("FRONTEND_INTERACTION_AUTHORITY_INVALID: frozen run interaction vocabulary is malformed or inconsistent");
|
|
559
562
|
let spec;
|
|
560
563
|
try {
|
|
561
564
|
spec = JSON.parse(raw);
|
|
562
565
|
}
|
|
563
566
|
catch {
|
|
564
|
-
|
|
567
|
+
throw invalid();
|
|
565
568
|
}
|
|
569
|
+
if (!spec || typeof spec !== "object" || (spec.tasks !== undefined && !Array.isArray(spec.tasks)))
|
|
570
|
+
throw invalid();
|
|
571
|
+
let declared;
|
|
566
572
|
for (const task of spec.tasks ?? []) {
|
|
567
|
-
const ids = task
|
|
568
|
-
if (ids
|
|
569
|
-
|
|
573
|
+
const ids = task?.shell?.frontendDesignPolicy?.interactionIds;
|
|
574
|
+
if (ids === undefined)
|
|
575
|
+
continue;
|
|
576
|
+
if (!Array.isArray(ids) || ids.some(id => typeof id !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)))
|
|
577
|
+
throw invalid();
|
|
578
|
+
const normalized = [...new Set(ids)].sort();
|
|
579
|
+
if (declared && JSON.stringify(declared) !== JSON.stringify(normalized))
|
|
580
|
+
throw invalid();
|
|
581
|
+
declared = normalized;
|
|
570
582
|
}
|
|
571
|
-
return [];
|
|
583
|
+
return declared ?? [];
|
|
584
|
+
}
|
|
585
|
+
/** Empty vocabulary retains the existing unrestricted task semantics. */
|
|
586
|
+
export function undeclaredFrontendInteractionIds(names, declared) {
|
|
587
|
+
return declared.length ? [...new Set(names.filter(name => !declared.includes(name)))] : [];
|
|
572
588
|
}
|
|
573
589
|
function checkInteractionIdVocabulary(canonical, declaredIds) {
|
|
574
590
|
const findings = [];
|
|
575
591
|
if (declaredIds.length === 0)
|
|
576
592
|
return findings;
|
|
577
593
|
for (const interaction of canonical.interactions ?? []) {
|
|
578
|
-
if (
|
|
594
|
+
if (undeclaredFrontendInteractionIds([interaction.name], declaredIds).length) {
|
|
579
595
|
findings.push({
|
|
580
596
|
code: "interaction-name-not-declared",
|
|
581
|
-
message: `interaction "${interaction.name}" is not in the frozen interaction id vocabulary; allowed: [${declaredIds.join(", ")}]
|
|
597
|
+
message: `interaction "${interaction.name}" is not in the frozen interaction id vocabulary; allowed: [${declaredIds.join(", ")}]; correct the owning interaction fact using the active Plan protocol, preserving its requirements and verification coverage`,
|
|
582
598
|
path: "interactions",
|
|
583
599
|
});
|
|
584
600
|
}
|
|
@@ -1345,13 +1361,23 @@ export const frontendImplementationContractSchema = z
|
|
|
1345
1361
|
message: "requirement needs targets or evidenceGap",
|
|
1346
1362
|
path: ["requirements"],
|
|
1347
1363
|
});
|
|
1348
|
-
for (const targetId of requirement.verificationTargetIds)
|
|
1349
|
-
|
|
1364
|
+
for (const targetId of requirement.verificationTargetIds) {
|
|
1365
|
+
const target = value.verificationTargets.find((item) => item.id === targetId);
|
|
1366
|
+
if (!target) {
|
|
1350
1367
|
ctx.addIssue({
|
|
1351
1368
|
code: "custom",
|
|
1352
1369
|
message: `unknown verification target ${targetId}`,
|
|
1353
1370
|
path: ["requirements"],
|
|
1354
1371
|
});
|
|
1372
|
+
}
|
|
1373
|
+
else if (!target.requirementIds.includes(requirement.id)) {
|
|
1374
|
+
ctx.addIssue({
|
|
1375
|
+
code: "custom",
|
|
1376
|
+
message: `verification target ${targetId} does not cover requirement ${requirement.id}; correct the requirement/target association before finalizing the plan`,
|
|
1377
|
+
path: ["requirements"],
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1355
1381
|
// Interactions bind to VTs too: an interaction whose behavior
|
|
1356
1382
|
// verification points at an unmaterialized VT is untraceable —
|
|
1357
1383
|
// r20 review finding (dangling *-BEHAVIOR references sailed
|
|
@@ -3579,6 +3605,7 @@ export async function analyzeFrontendPlanPatchCandidate(input) {
|
|
|
3579
3605
|
...checkUiStateAttribution(analysis.canonical),
|
|
3580
3606
|
...checkRequiredDeliverables(analysis.canonical),
|
|
3581
3607
|
...checkUxNameCollisions(analysis.canonical),
|
|
3608
|
+
...checkComponentChoiceConsistency(analysis.canonical),
|
|
3582
3609
|
...checkDependencies(analysis.canonical, await deriveAllowedDependenciesFromRun(input.runDir)),
|
|
3583
3610
|
...checkTargetPaths(analysis.canonical, await deriveWriteSetFromRun(input.runDir), await collectExistingFrontendVerificationPaths(workspaceRootFromDagRunDir(input.runDir), analysis.canonical)),
|
|
3584
3611
|
// F1: front-load slice containment/coverage/acyclicity so the plan
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { writeFrontendContractReviewArtifacts } from "./frontend-implementation-contract.js";
|
|
6
|
+
import { FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT } from "./frontend-writer-admission.js";
|
|
7
|
+
const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
8
|
+
/** Imported nodes never execute again. Carry their run-owned outputs as well
|
|
9
|
+
* as their node records, and derive the bounded reader index from verified
|
|
10
|
+
* canonical bytes. Both automatic repair and explicit node reruns use this. */
|
|
11
|
+
async function collectFrontendRunArtifacts(input) {
|
|
12
|
+
const imported = new Set(input.importedNodeIds);
|
|
13
|
+
const nodeArtifacts = [];
|
|
14
|
+
const importedRunArtifacts = [];
|
|
15
|
+
const copy = async (nodeId, relativePath, required = true) => {
|
|
16
|
+
const normalized = relativePath.replace(/\\/g, "/");
|
|
17
|
+
if (path.posix.isAbsolute(normalized) || normalized.split("/").includes("..")) {
|
|
18
|
+
throw new Error(`imported frontend artifact must stay within the run: ${relativePath}`);
|
|
19
|
+
}
|
|
20
|
+
const sourcePath = path.join(input.parentRunDir, normalized);
|
|
21
|
+
try {
|
|
22
|
+
if (!(await stat(sourcePath)).isFile())
|
|
23
|
+
throw new Error(`imported frontend artifact is not a file: ${normalized}`);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code !== "ENOENT")
|
|
27
|
+
throw error;
|
|
28
|
+
if (!required)
|
|
29
|
+
return undefined;
|
|
30
|
+
throw new Error(`missing imported artifact: ${normalized}`);
|
|
31
|
+
}
|
|
32
|
+
const sourceRoot = await realpath(input.parentRunDir);
|
|
33
|
+
if (!(await realpath(sourcePath)).startsWith(`${sourceRoot}${path.sep}`)) {
|
|
34
|
+
throw new Error(`imported frontend artifact resolves outside parent run: ${normalized}`);
|
|
35
|
+
}
|
|
36
|
+
const sourceBytes = await readFile(sourcePath);
|
|
37
|
+
const expected = sha256Hex(sourceBytes);
|
|
38
|
+
// All selected inputs are JSON facts. Reject corrupt input while still
|
|
39
|
+
// preparing outside the active lifecycle and before acquiring a lease.
|
|
40
|
+
JSON.parse(sourceBytes.toString("utf8"));
|
|
41
|
+
const destinationPath = path.join(input.newRunDir, normalized);
|
|
42
|
+
await mkdir(path.dirname(destinationPath), { recursive: true });
|
|
43
|
+
await writeFile(destinationPath, sourceBytes);
|
|
44
|
+
const actual = sha256Hex(await readFile(destinationPath));
|
|
45
|
+
if (actual !== expected)
|
|
46
|
+
throw new Error(`copy hash mismatch for artifact: ${normalized}`);
|
|
47
|
+
const artifact = { destinationRelativePath: normalized, sha256: actual };
|
|
48
|
+
nodeArtifacts.push({ nodeId, sourceRelativePath: normalized, ...artifact });
|
|
49
|
+
return artifact;
|
|
50
|
+
};
|
|
51
|
+
// The micro contract-import node only checks source freshness. Canonical
|
|
52
|
+
// outputs belong to design-policy and must be regenerated when it resets.
|
|
53
|
+
const policyNodeId = imported.has("frontend-design-policy-shell") ? "frontend-design-policy-shell" : undefined;
|
|
54
|
+
let canonicalContract;
|
|
55
|
+
if (policyNodeId) {
|
|
56
|
+
const policy = input.spec.tasks.find(task => task.shell?.frontendDesignPolicy)?.shell?.frontendDesignPolicy;
|
|
57
|
+
const relativePath = policy
|
|
58
|
+
? path.posix.join(policy.outputDir, policy.artifactName)
|
|
59
|
+
: "contracts/frontend-implementation-contract.json";
|
|
60
|
+
canonicalContract = await copy(policyNodeId, relativePath);
|
|
61
|
+
const canonicalPath = path.join(input.newRunDir, relativePath);
|
|
62
|
+
const bytes = await readFile(canonicalPath);
|
|
63
|
+
await writeFrontendContractReviewArtifacts({
|
|
64
|
+
runDir: input.newRunDir,
|
|
65
|
+
outputDir: path.posix.dirname(relativePath),
|
|
66
|
+
artifactName: path.posix.basename(relativePath),
|
|
67
|
+
canonical: JSON.parse(bytes.toString("utf8")),
|
|
68
|
+
canonicalArtifact: { path: canonicalPath, sha256: canonicalContract.sha256, bytes: bytes.length },
|
|
69
|
+
});
|
|
70
|
+
// A reset admission node reads this result before capturing its baseline.
|
|
71
|
+
const policyResult = await copy(policyNodeId, "contracts/frontend-design-policy-result.json", !imported.has("frontend-writer-admission-shell"));
|
|
72
|
+
if (policyResult)
|
|
73
|
+
importedRunArtifacts.push({ sourceRelativePath: policyResult.destinationRelativePath, ...policyResult });
|
|
74
|
+
}
|
|
75
|
+
let writerAdmissionResult;
|
|
76
|
+
if (imported.has("frontend-writer-admission-shell")) {
|
|
77
|
+
writerAdmissionResult = await copy("frontend-writer-admission-shell", FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT);
|
|
78
|
+
for (const [relativePath, required] of [
|
|
79
|
+
["contracts/frontend-worktree-baseline.json", true],
|
|
80
|
+
["contracts/frontend-lint-baseline.json", false],
|
|
81
|
+
]) {
|
|
82
|
+
const artifact = await copy("frontend-writer-admission-shell", relativePath, required);
|
|
83
|
+
if (artifact)
|
|
84
|
+
importedRunArtifacts.push({ sourceRelativePath: relativePath, ...artifact });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { canonicalContract, writerAdmissionResult, importedRunArtifacts, nodeArtifacts };
|
|
88
|
+
}
|
|
89
|
+
/** Validate and freeze source bytes and the generated reader surface before
|
|
90
|
+
* reserving a recovery lease or creating an active child. No parent mutation. */
|
|
91
|
+
export async function prepareFrontendRunArtifacts(input) {
|
|
92
|
+
const temporary = await mkdtemp(path.join(os.tmpdir(), "frontend-run-import-"));
|
|
93
|
+
try {
|
|
94
|
+
const manifest = await collectFrontendRunArtifacts({ ...input, newRunDir: temporary });
|
|
95
|
+
const files = [];
|
|
96
|
+
const collect = async (relative = "") => {
|
|
97
|
+
for (const entry of await readdir(path.join(temporary, relative), { withFileTypes: true })) {
|
|
98
|
+
const relativePath = path.posix.join(relative, entry.name);
|
|
99
|
+
if (entry.isDirectory())
|
|
100
|
+
await collect(relativePath);
|
|
101
|
+
else {
|
|
102
|
+
const bytes = await readFile(path.join(temporary, relativePath));
|
|
103
|
+
files.push(Object.freeze({ relativePath, base64: bytes.toString("base64"), sha256: sha256Hex(bytes) }));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
await collect();
|
|
108
|
+
return Object.freeze({ manifest, files: Object.freeze(files) });
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await rm(temporary, { recursive: true, force: true });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function importFrontendRunArtifacts(input) {
|
|
115
|
+
const prepared = input.prepared ?? await prepareFrontendRunArtifacts(input);
|
|
116
|
+
for (const file of prepared.files) {
|
|
117
|
+
const bytes = Buffer.from(file.base64, "base64");
|
|
118
|
+
const destination = path.join(input.newRunDir, file.relativePath);
|
|
119
|
+
await mkdir(path.dirname(destination), { recursive: true });
|
|
120
|
+
await writeFile(destination, bytes);
|
|
121
|
+
if (sha256Hex(await readFile(destination)) !== file.sha256) {
|
|
122
|
+
throw new Error(`copy hash mismatch for artifact: ${file.relativePath}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return prepared.manifest;
|
|
126
|
+
}
|
|
@@ -2,50 +2,16 @@ import { copyFile, mkdir, readdir, readFile, rm, access } from "node:fs/promises
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { sha256OfCanonicalJson } from "../../task/contract/hash.js";
|
|
4
4
|
import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
|
|
5
|
-
import { sha256Hex
|
|
5
|
+
import { sha256Hex } from "./frontend-implementation-contract.js";
|
|
6
|
+
import { importFrontendRunArtifacts } from "./frontend-imported-run-artifacts.js";
|
|
6
7
|
import { FRONTEND_RECOVERY_IMPORT_MANIFEST_REL_PATH, FRONTEND_RECOVERY_INTENT_REL_DIR, FRONTEND_RECOVERY_STAGING_PREFIX, computeFrontendRecoveryPlan, computeFrontendRecoveryPlanForSource, } from "./frontend-recovery-plan.js";
|
|
7
8
|
import { dagRunDirExists, getDagRunDir, locateDagRun, readDagRunSpec, readDagRunState, transferDagRunDir, writeDagRunState, } from "./lifecycle.js";
|
|
8
9
|
import { buildDagRunId } from "./runner.js";
|
|
9
10
|
import { buildFrontendTopologyBinding } from "./frontend-shape.js";
|
|
10
11
|
import { FRONTEND_SHAPE_BOUNDARIES, isCanonicalFrontendShapeDag, } from "./frontend-shape-facts.js";
|
|
11
12
|
import { prepareRunDir, writeNodeRecord } from "./run-store.js";
|
|
12
|
-
import {
|
|
13
|
+
import { readFrontendWriterAdmissionResult, } from "./scheduler.js";
|
|
13
14
|
import { topoSortToRanks } from "./topo.js";
|
|
14
|
-
/**
|
|
15
|
-
* Candidate-continuation child creation kernel (phase 3b).
|
|
16
|
-
*
|
|
17
|
-
* Parent terminal convergence (phase 3a) has already persisted a recovery
|
|
18
|
-
* intent on `DagRunState.frontendRecoveryState`. This module is the single
|
|
19
|
-
* writer that stages and commits one reserved child run per requestId, with a
|
|
20
|
-
* commit-point handoff: CAS-reserve childRunId → stage files (hash-verified) →
|
|
21
|
-
* rename into active/ → activation marker → three-way consistency check → CAS
|
|
22
|
-
* phase=child-running. Scheduling/execution of the child is phase 3c and out
|
|
23
|
-
* of scope here.
|
|
24
|
-
*/
|
|
25
|
-
/** Canonical contract artifact default location; overridden by the design
|
|
26
|
-
* policy shell's configured outputDir/artifactName when present. */
|
|
27
|
-
const FRONTEND_CANONICAL_CONTRACT_DEFAULT_REL_PATH = "contracts/frontend-implementation-contract.json";
|
|
28
|
-
/**
|
|
29
|
-
* Run-owned artifacts a frontend node writes *outside* its own node directory.
|
|
30
|
-
*
|
|
31
|
-
* An imported node keeps its parent FINISHED record in the child run, so the
|
|
32
|
-
* child never executes the body that produced these files. Any downstream node
|
|
33
|
-
* that reads them must still find them in the child run directory: smoke r31
|
|
34
|
-
* saw a review-triggered recovery die at `frontend-review-context-shell` with
|
|
35
|
-
* `ENOENT contracts/frontend-worktree-baseline.json`, because
|
|
36
|
-
* `frontend-writer-admission-shell` is imported (its baseline capture is a side
|
|
37
|
-
* effect of the node body) while the review context requires that file.
|
|
38
|
-
*
|
|
39
|
-
* Entries listed as required fail the staging closed when the parent lacks
|
|
40
|
-
* them; optional entries (for example the lint baseline, which only exists when
|
|
41
|
-
* lint is configured) are copied when present.
|
|
42
|
-
*/
|
|
43
|
-
const FRONTEND_IMPORTED_NODE_RUN_ARTIFACTS = {
|
|
44
|
-
"frontend-writer-admission-shell": {
|
|
45
|
-
required: ["contracts/frontend-worktree-baseline.json"],
|
|
46
|
-
optional: ["contracts/frontend-lint-baseline.json"],
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
15
|
function resolveDeps(deps) {
|
|
50
16
|
return {
|
|
51
17
|
readParentState: deps?.readParentState ?? readDagRunState,
|
|
@@ -116,15 +82,6 @@ function classifyFrontendFactKind(nodeId) {
|
|
|
116
82
|
return "plan";
|
|
117
83
|
return "plan";
|
|
118
84
|
}
|
|
119
|
-
function resolveCanonicalContractRelPath(spec) {
|
|
120
|
-
for (const task of spec.tasks) {
|
|
121
|
-
const policy = task.shell?.frontendDesignPolicy;
|
|
122
|
-
if (policy) {
|
|
123
|
-
return path.posix.join(policy.outputDir, policy.artifactName);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
return FRONTEND_CANONICAL_CONTRACT_DEFAULT_REL_PATH;
|
|
127
|
-
}
|
|
128
85
|
function normalizeRunRelativePath(relPath) {
|
|
129
86
|
return relPath.replace(/\\/g, "/");
|
|
130
87
|
}
|
|
@@ -410,72 +367,12 @@ async function materializeChildStaging(input) {
|
|
|
410
367
|
throw new Error(`node ${task.id} missing from frontend recovery plan partition`);
|
|
411
368
|
}
|
|
412
369
|
}
|
|
413
|
-
|
|
414
|
-
// the per-node facts so reset nodes can re-read them (AC-4).
|
|
415
|
-
const canonicalContract = plan.importedNodeIds.some(id => ["frontend-design-policy-shell", "frontend-contract-import-shell"].includes(id)) ? await copyArtifactVerified({
|
|
416
|
-
parentRunDir,
|
|
417
|
-
newRunDir: stagingDir,
|
|
418
|
-
relativePath: resolveCanonicalContractRelPath(childSpec),
|
|
419
|
-
}) : undefined;
|
|
420
|
-
if (canonicalContract) {
|
|
421
|
-
// Imported policy nodes do not execute in the child. Recreate their
|
|
422
|
-
// read surface from the verified canonical bytes before activating it;
|
|
423
|
-
// otherwise an indexed-reader writer cannot start a repair round.
|
|
424
|
-
const relativePath = canonicalContract.destinationRelativePath;
|
|
425
|
-
const canonicalPath = path.join(stagingDir, ...relativePath.split("/"));
|
|
426
|
-
const bytes = await readFile(canonicalPath);
|
|
427
|
-
await writeFrontendContractReviewArtifacts({
|
|
428
|
-
runDir: stagingDir,
|
|
429
|
-
outputDir: path.posix.dirname(relativePath),
|
|
430
|
-
artifactName: path.posix.basename(relativePath),
|
|
431
|
-
canonical: JSON.parse(bytes.toString("utf8")),
|
|
432
|
-
canonicalArtifact: {
|
|
433
|
-
path: canonicalPath,
|
|
434
|
-
sha256: canonicalContract.sha256,
|
|
435
|
-
bytes: bytes.length,
|
|
436
|
-
},
|
|
437
|
-
});
|
|
438
|
-
}
|
|
439
|
-
const writerAdmissionResult = plan.importedNodeIds.includes("frontend-writer-admission-shell") ? await copyArtifactVerified({
|
|
370
|
+
const { canonicalContract, writerAdmissionResult, importedRunArtifacts } = await importFrontendRunArtifacts({
|
|
440
371
|
parentRunDir,
|
|
441
372
|
newRunDir: stagingDir,
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
// their bodies wrote outside the node directory travel with them (smoke r31:
|
|
446
|
-
// a review-triggered recovery reached review-context with no worktree
|
|
447
|
-
// baseline and hard-failed on ENOENT).
|
|
448
|
-
const importedRunArtifacts = [];
|
|
449
|
-
for (const nodeId of plan.importedNodeIds) {
|
|
450
|
-
const artifactSpec = FRONTEND_IMPORTED_NODE_RUN_ARTIFACTS[nodeId];
|
|
451
|
-
if (!artifactSpec)
|
|
452
|
-
continue;
|
|
453
|
-
for (const relativePath of artifactSpec.required) {
|
|
454
|
-
const copied = await copyArtifactVerified({
|
|
455
|
-
parentRunDir,
|
|
456
|
-
newRunDir: stagingDir,
|
|
457
|
-
relativePath,
|
|
458
|
-
});
|
|
459
|
-
importedRunArtifacts.push({
|
|
460
|
-
sourceRelativePath: relativePath,
|
|
461
|
-
...copied,
|
|
462
|
-
});
|
|
463
|
-
}
|
|
464
|
-
for (const relativePath of artifactSpec.optional) {
|
|
465
|
-
const sourcePath = path.join(parentRunDir, ...relativePath.split("/"));
|
|
466
|
-
if (!(await fileExists(sourcePath)))
|
|
467
|
-
continue;
|
|
468
|
-
const copied = await copyArtifactVerified({
|
|
469
|
-
parentRunDir,
|
|
470
|
-
newRunDir: stagingDir,
|
|
471
|
-
relativePath,
|
|
472
|
-
});
|
|
473
|
-
importedRunArtifacts.push({
|
|
474
|
-
sourceRelativePath: relativePath,
|
|
475
|
-
...copied,
|
|
476
|
-
});
|
|
477
|
-
}
|
|
478
|
-
}
|
|
373
|
+
spec: childSpec,
|
|
374
|
+
importedNodeIds: plan.importedNodeIds,
|
|
375
|
+
});
|
|
479
376
|
// The scheduler gates every shape boundary by its committed fact once the
|
|
480
377
|
// boundary's source node is FINISHED. Imported nodes stay FINISHED in the
|
|
481
378
|
// child, so their boundaries must inherit the parent's committed facts or
|
|
@@ -81,6 +81,20 @@ export function resolveRunnerArgv(argv) {
|
|
|
81
81
|
words.shift();
|
|
82
82
|
}
|
|
83
83
|
const head = words[0];
|
|
84
|
+
// Recognize the project-local Jest entrypoint without rewriting the actual
|
|
85
|
+
// command. Only unwrap understood Node flags: eval/loaders/preloads can
|
|
86
|
+
// change execution semantics and must not be guessed away.
|
|
87
|
+
if (head === "node" || head === "node.exe") {
|
|
88
|
+
let entry = 1;
|
|
89
|
+
while (words[entry] === "--experimental-vm-modules")
|
|
90
|
+
entry++;
|
|
91
|
+
if (words[entry] === "--")
|
|
92
|
+
entry++;
|
|
93
|
+
const script = words[entry]?.replace(/\\/g, "/");
|
|
94
|
+
if (script && /^(?:\.\/)?node_modules\/jest\/bin\/jest\.js$/.test(script)) {
|
|
95
|
+
return ["jest", ...words.slice(entry + 1)];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
84
98
|
if (head === "npx" || head === "pnpx" || head === "bunx") {
|
|
85
99
|
words.shift();
|
|
86
100
|
// `npx --no-install vitest run` / `npx -y vitest run`
|
|
@@ -246,22 +246,34 @@ function frozenCheckFailureCategory(mode) {
|
|
|
246
246
|
}
|
|
247
247
|
/**
|
|
248
248
|
* Normalize a failed frozen check into a bounded, model-independent detail.
|
|
249
|
-
*
|
|
250
|
-
*
|
|
249
|
+
* Prefer diagnostic lines over reporter footers. This is advisory output,
|
|
250
|
+
* never authority for changing a command, write boundary or verdict.
|
|
251
251
|
*/
|
|
252
|
-
function describeFrozenCheckFailure(result) {
|
|
252
|
+
export function describeFrozenCheckFailure(result) {
|
|
253
253
|
const status = result.command.trim().length === 0
|
|
254
254
|
? "has no frozen command text (nothing was run)"
|
|
255
255
|
: result.exitCode === null
|
|
256
256
|
? `did not complete (${result.failureCategory})`
|
|
257
257
|
: `exited ${result.exitCode}`;
|
|
258
|
-
const
|
|
258
|
+
const lines = `${result.stdout}\n${result.stderr}`
|
|
259
259
|
.split("\n")
|
|
260
260
|
.map((line) => line.trim())
|
|
261
|
-
.filter(Boolean)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
261
|
+
.filter(Boolean);
|
|
262
|
+
const anchors = lines.flatMap((line, index) => /^(?:●|FAIL\b|AssertionError\b|Error:)|\berror TS\d+:/.test(line) ? [index] : []).slice(0, 8);
|
|
263
|
+
const selected = new Set();
|
|
264
|
+
for (const index of anchors) {
|
|
265
|
+
// Keep each headline even if a previous diagnostic has a long source dump.
|
|
266
|
+
selected.add(index);
|
|
267
|
+
}
|
|
268
|
+
for (const index of anchors) {
|
|
269
|
+
for (let offset = 1; offset < 12 && index + offset < lines.length; offset++)
|
|
270
|
+
selected.add(index + offset);
|
|
271
|
+
}
|
|
272
|
+
const detail = (anchors.length
|
|
273
|
+
? [...selected].map((index) => (lines[index] ?? "").slice(0, 240))
|
|
274
|
+
: [...lines.slice(0, 3), ...lines.slice(-3)])
|
|
275
|
+
.join(" | ").slice(0, 2400);
|
|
276
|
+
return `frozen check ${result.commandId} ${status}${detail ? `: ${detail}` : ""}`;
|
|
265
277
|
}
|
|
266
278
|
/**
|
|
267
279
|
* Writer-boundary check. It validates declared file existence AND, when the
|