@lingjingai/scriptctl 0.9.7 → 0.9.8
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/dist/usecases/direct.js +553 -680
- package/dist/usecases/direct.js.map +1 -1
- package/package.json +1 -1
package/dist/usecases/direct.js
CHANGED
|
@@ -626,12 +626,6 @@ async function pMapWithConcurrency(items, concurrency, worker) {
|
|
|
626
626
|
// command_init
|
|
627
627
|
// ---------------------------------------------------------------------------
|
|
628
628
|
export async function commandInit(opts) {
|
|
629
|
-
const ctx = makeInitCtx(validateInitOpts(opts));
|
|
630
|
-
fs.mkdirSync(ctx.dd, { recursive: true });
|
|
631
|
-
ctx.previousState = readRunState(ctx.workspace);
|
|
632
|
-
return runInitPipeline(INIT_STEPS, ctx);
|
|
633
|
-
}
|
|
634
|
-
function validateInitOpts(opts) {
|
|
635
629
|
const sourcePathArg = strOf(opts["source_path"]);
|
|
636
630
|
const source = sourcePathArg.startsWith("~")
|
|
637
631
|
? path.join(process.env.HOME ?? "", sourcePathArg.slice(1))
|
|
@@ -721,698 +715,577 @@ function validateInitOpts(opts) {
|
|
|
721
715
|
nextSteps: ["Use a supported source file and rerun init."],
|
|
722
716
|
});
|
|
723
717
|
}
|
|
724
|
-
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
batchResults: [],
|
|
748
|
-
completedBatches: 0,
|
|
749
|
-
script: {},
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
async function runInitPipeline(steps, ctx) {
|
|
753
|
-
for (const step of steps) {
|
|
754
|
-
if (step.enter) {
|
|
755
|
-
const updates = step.enter(ctx);
|
|
756
|
-
if (updates)
|
|
757
|
-
updateRunState(ctx.workspace, updates);
|
|
758
|
-
}
|
|
759
|
-
let result;
|
|
760
|
-
try {
|
|
761
|
-
result = await step.run(ctx);
|
|
762
|
-
}
|
|
763
|
-
catch (exc) {
|
|
764
|
-
if (step.onError)
|
|
765
|
-
step.onError(ctx, exc);
|
|
718
|
+
const dd = directDir(workspace);
|
|
719
|
+
fs.mkdirSync(dd, { recursive: true });
|
|
720
|
+
const previousStateBeforeInit = readRunState(workspace);
|
|
721
|
+
updateRunState(workspace, {
|
|
722
|
+
status: "init_running",
|
|
723
|
+
command: "direct init",
|
|
724
|
+
init_stage: "source_prepare",
|
|
725
|
+
provider: providerName,
|
|
726
|
+
model,
|
|
727
|
+
concurrency,
|
|
728
|
+
source_path: path.resolve(source),
|
|
729
|
+
});
|
|
730
|
+
let info;
|
|
731
|
+
try {
|
|
732
|
+
info = await prepareSource(source, workspace);
|
|
733
|
+
}
|
|
734
|
+
catch (exc) {
|
|
735
|
+
if (exc instanceof CliError) {
|
|
736
|
+
updateRunState(workspace, {
|
|
737
|
+
status: "init_failed",
|
|
738
|
+
init_stage: "source_prepare",
|
|
739
|
+
last_error: { title: exc.title, received: exc.received, failed_at: checkpointTimestamp() },
|
|
740
|
+
});
|
|
766
741
|
throw exc;
|
|
767
742
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
throw new Error("init pipeline ended without halting");
|
|
773
|
-
}
|
|
774
|
-
function groupResultsByEpisode(batchResults) {
|
|
775
|
-
const byEpisode = new Map();
|
|
776
|
-
for (const result of batchResults) {
|
|
777
|
-
const ep = Number(result["episode"] ?? 0);
|
|
778
|
-
if (!byEpisode.has(ep))
|
|
779
|
-
byEpisode.set(ep, []);
|
|
780
|
-
byEpisode.get(ep).push(result);
|
|
781
|
-
}
|
|
782
|
-
return byEpisode;
|
|
783
|
-
}
|
|
784
|
-
// Merge one episode's batch results, validate, and persist its episode_results
|
|
785
|
-
// file + index metadata. Shared by the success path (episode_merge) and the
|
|
786
|
-
// failure path's partial merge so the two stay in lockstep.
|
|
787
|
-
function mergeEpisodeAndPersist(sourceText, episodeResultsDir, episode, batchResultsForEpisode, providerName, model) {
|
|
788
|
-
const result = mergeBatchResultsForEpisode(episode, batchResultsForEpisode);
|
|
789
|
-
validateEpisodeExtractionQuality(sourceText, episode, result);
|
|
790
|
-
writeJson(episodeResultPath(episodeResultsDir, episode), compactEpisodeResult(result));
|
|
791
|
-
updateEpisodeResultMetadata(episodeResultsDir, episode, providerName, model);
|
|
792
|
-
return result;
|
|
793
|
-
}
|
|
794
|
-
const INIT_STEPS = [
|
|
795
|
-
{
|
|
796
|
-
stage: "source_prepare",
|
|
797
|
-
enter: (ctx) => ({
|
|
798
|
-
status: "init_running",
|
|
799
|
-
command: "direct init",
|
|
743
|
+
const e = exc;
|
|
744
|
+
const receivedError = `${source}: ${e?.name ?? "Error"}${e?.message ? `: ${e.message}` : ""}`;
|
|
745
|
+
updateRunState(workspace, {
|
|
746
|
+
status: "init_failed",
|
|
800
747
|
init_stage: "source_prepare",
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
ctx.manifest = makeSourceManifest(ctx.source, sourceTextPath, info);
|
|
840
|
-
return { kind: "continue" };
|
|
841
|
-
},
|
|
842
|
-
},
|
|
843
|
-
{
|
|
844
|
-
stage: "episode_plan",
|
|
845
|
-
enter: () => ({ status: "init_running", init_stage: "episode_plan" }),
|
|
846
|
-
run: (ctx) => {
|
|
847
|
-
ctx.plan = buildEpisodePlan(ctx.sourceText);
|
|
848
|
-
return { kind: "continue" };
|
|
849
|
-
},
|
|
850
|
-
onError: (ctx, exc) => {
|
|
851
|
-
const e = exc;
|
|
852
|
-
throw initFailedReport(ctx.workspace, {
|
|
853
|
-
title: "INIT FAILED: Episode planning failed",
|
|
854
|
-
stage: "episode_plan",
|
|
855
|
-
required: ["source.txt that can be split into episodes"],
|
|
856
|
-
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
857
|
-
nextSteps: ["Inspect workspace/source.txt, fix the source file, and rerun init."],
|
|
748
|
+
last_error: { title: "INIT BLOCKED: Source preparation failed", received: [receivedError], failed_at: checkpointTimestamp() },
|
|
749
|
+
});
|
|
750
|
+
throw new CliError("INIT BLOCKED: Source preparation failed", "Source preparation failed.", {
|
|
751
|
+
exitCode: EXIT_INPUT,
|
|
752
|
+
required: ["readable source file that can be converted to source.txt"],
|
|
753
|
+
received: [receivedError],
|
|
754
|
+
nextSteps: ["Fix or re-export the source file, then rerun init."],
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
const sourceTextPath = strOf(info["sourceTextPath"]);
|
|
758
|
+
const sourceText = readText(sourceTextPath);
|
|
759
|
+
const manifest = makeSourceManifest(source, sourceTextPath, info);
|
|
760
|
+
updateRunState(workspace, { status: "init_running", init_stage: "episode_plan" });
|
|
761
|
+
let plan;
|
|
762
|
+
try {
|
|
763
|
+
plan = buildEpisodePlan(sourceText);
|
|
764
|
+
}
|
|
765
|
+
catch (exc) {
|
|
766
|
+
const e = exc;
|
|
767
|
+
throw initFailedReport(workspace, {
|
|
768
|
+
title: "INIT FAILED: Episode planning failed",
|
|
769
|
+
stage: "episode_plan",
|
|
770
|
+
required: ["source.txt that can be split into episodes"],
|
|
771
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
772
|
+
nextSteps: ["Inspect workspace/source.txt, fix the source file, and rerun init."],
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
updateRunState(workspace, { status: "init_running", init_stage: "provider" });
|
|
776
|
+
let provider;
|
|
777
|
+
try {
|
|
778
|
+
provider = makeProvider(providerName, model);
|
|
779
|
+
}
|
|
780
|
+
catch (exc) {
|
|
781
|
+
if (exc instanceof CliError) {
|
|
782
|
+
updateRunState(workspace, {
|
|
783
|
+
status: "init_failed",
|
|
784
|
+
init_stage: "provider",
|
|
785
|
+
last_error: { title: exc.title, received: exc.received, failed_at: checkpointTimestamp() },
|
|
858
786
|
});
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
catch (exc) {
|
|
871
|
-
if (exc instanceof CliError) {
|
|
872
|
-
updateRunState(ctx.workspace, {
|
|
873
|
-
status: "init_failed",
|
|
874
|
-
init_stage: "provider",
|
|
875
|
-
last_error: { title: exc.title, received: exc.received, failed_at: checkpointTimestamp() },
|
|
876
|
-
});
|
|
877
|
-
}
|
|
878
|
-
throw exc;
|
|
879
|
-
}
|
|
880
|
-
return { kind: "continue" };
|
|
881
|
-
},
|
|
882
|
-
},
|
|
883
|
-
{
|
|
884
|
-
stage: "episode_titles",
|
|
885
|
-
enter: () => ({ status: "init_running", init_stage: "episode_titles" }),
|
|
886
|
-
run: async (ctx) => {
|
|
887
|
-
ctx.plan = await enrichEpisodePlanTitles(ctx.sourceText, ctx.plan, ctx.provider);
|
|
888
|
-
return { kind: "continue" };
|
|
889
|
-
},
|
|
890
|
-
onError: (ctx, exc) => {
|
|
891
|
-
if (exc instanceof CliError) {
|
|
892
|
-
throw initFailedReport(ctx.workspace, {
|
|
893
|
-
title: exc.title,
|
|
894
|
-
stage: "episode_titles",
|
|
895
|
-
exitCode: exc.exitCode,
|
|
896
|
-
required: exc.required.length > 0 ? exc.required : ["episode titles generated from source text"],
|
|
897
|
-
received: exc.received.length > 0 ? exc.received : [String(exc.message).slice(0, 160)],
|
|
898
|
-
nextSteps: exc.nextSteps.length > 0 ? exc.nextSteps : ["Rerun init after checking source episode headers."],
|
|
899
|
-
});
|
|
900
|
-
}
|
|
901
|
-
const e = exc;
|
|
902
|
-
throw initFailedReport(ctx.workspace, {
|
|
903
|
-
title: "INIT FAILED: Episode title planning failed",
|
|
787
|
+
}
|
|
788
|
+
throw exc;
|
|
789
|
+
}
|
|
790
|
+
updateRunState(workspace, { status: "init_running", init_stage: "episode_titles" });
|
|
791
|
+
try {
|
|
792
|
+
plan = await enrichEpisodePlanTitles(sourceText, plan, provider);
|
|
793
|
+
}
|
|
794
|
+
catch (exc) {
|
|
795
|
+
if (exc instanceof CliError) {
|
|
796
|
+
throw initFailedReport(workspace, {
|
|
797
|
+
title: exc.title,
|
|
904
798
|
stage: "episode_titles",
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
},
|
|
910
|
-
},
|
|
911
|
-
{
|
|
912
|
-
stage: "batch_plan",
|
|
913
|
-
run: (ctx) => {
|
|
914
|
-
ctx.batchPlan = buildBatchPlan(ctx.sourceText, ctx.plan, {
|
|
915
|
-
targetLines: ctx.batchTargetLines,
|
|
916
|
-
maxChars: ctx.batchMaxChars,
|
|
917
|
-
minLines: ctx.batchMinLines,
|
|
918
|
-
mode: ctx.batchMode,
|
|
919
|
-
});
|
|
920
|
-
return { kind: "continue" };
|
|
921
|
-
},
|
|
922
|
-
onError: (ctx, exc) => {
|
|
923
|
-
const e = exc;
|
|
924
|
-
throw initFailedReport(ctx.workspace, {
|
|
925
|
-
title: "INIT FAILED: Batch planning failed",
|
|
926
|
-
stage: "batch_plan",
|
|
927
|
-
required: ["episode_plan.json that can be split into natural paragraph batches"],
|
|
928
|
-
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
929
|
-
nextSteps: ["Inspect workspace/source.txt and episode_plan.json, then rerun init."],
|
|
930
|
-
});
|
|
931
|
-
},
|
|
932
|
-
},
|
|
933
|
-
{
|
|
934
|
-
stage: "checkpoint_setup",
|
|
935
|
-
run: (ctx) => {
|
|
936
|
-
const checkpoint = initCheckpoint(ctx.sourceText, ctx.plan);
|
|
937
|
-
const batchCheckpoint = initBatchCheckpoint(ctx.sourceText, ctx.batchPlan);
|
|
938
|
-
const previousState = ctx.previousState;
|
|
939
|
-
const previousCheckpoint = isDict(previousState["checkpoint"]) ? previousState["checkpoint"] : {};
|
|
940
|
-
const previousBatchCheckpoint = isDict(previousState["batch_checkpoint"]) ? previousState["batch_checkpoint"] : {};
|
|
941
|
-
const checkpointReused = checkpointSourceMatches(previousCheckpoint, checkpoint);
|
|
942
|
-
const batchCheckpointReused = checkpointReused && batchCheckpointMatches(previousBatchCheckpoint, batchCheckpoint);
|
|
943
|
-
if (!checkpointReused)
|
|
944
|
-
resetInitOutputs(ctx.dd);
|
|
945
|
-
else if (!batchCheckpointReused)
|
|
946
|
-
resetBatchOutputs(ctx.dd);
|
|
947
|
-
writeJson(path.join(ctx.dd, "source_manifest.json"), ctx.manifest);
|
|
948
|
-
writeJson(path.join(ctx.dd, "episode_plan.json"), ctx.plan);
|
|
949
|
-
writeJson(path.join(ctx.dd, "batch_plan.json"), ctx.batchPlan);
|
|
950
|
-
const episodeResultsDir = path.join(ctx.dd, "episode_results");
|
|
951
|
-
const batchResultsDir = path.join(ctx.dd, "batch_results");
|
|
952
|
-
fs.mkdirSync(episodeResultsDir, { recursive: true });
|
|
953
|
-
fs.mkdirSync(batchResultsDir, { recursive: true });
|
|
954
|
-
ctx.checkpoint = checkpoint;
|
|
955
|
-
ctx.batchCheckpoint = batchCheckpoint;
|
|
956
|
-
ctx.checkpointReused = checkpointReused;
|
|
957
|
-
ctx.batchCheckpointReused = batchCheckpointReused;
|
|
958
|
-
ctx.episodeResultsDir = episodeResultsDir;
|
|
959
|
-
ctx.batchResultsDir = batchResultsDir;
|
|
960
|
-
updateRunState(ctx.workspace, {
|
|
961
|
-
status: "init_running",
|
|
962
|
-
init_stage: "batch_extract",
|
|
963
|
-
checkpoint,
|
|
964
|
-
batch_checkpoint: batchCheckpoint,
|
|
965
|
-
checkpoint_reused: checkpointReused,
|
|
966
|
-
batch_checkpoint_reused: batchCheckpointReused,
|
|
967
|
-
batch_mode: ctx.batchMode,
|
|
968
|
-
batch_target_lines: ctx.batchTargetLines,
|
|
969
|
-
batch_max_chars: ctx.batchMaxChars,
|
|
970
|
-
batch_min_lines: ctx.batchMinLines,
|
|
971
|
-
episode_total: asList(ctx.plan["episodes"]).length,
|
|
972
|
-
batch_total: asList(ctx.batchPlan["batches"]).length,
|
|
973
|
-
});
|
|
974
|
-
return { kind: "continue" };
|
|
975
|
-
},
|
|
976
|
-
},
|
|
977
|
-
{
|
|
978
|
-
stage: "extract_episodes",
|
|
979
|
-
run: async (ctx) => {
|
|
980
|
-
const pendingBatches = [];
|
|
981
|
-
const batchesByEpisode = new Map();
|
|
982
|
-
for (const batch of asList(ctx.batchPlan["batches"])) {
|
|
983
|
-
const epNum = Number(batch["episode"]);
|
|
984
|
-
if (!batchesByEpisode.has(epNum))
|
|
985
|
-
batchesByEpisode.set(epNum, []);
|
|
986
|
-
batchesByEpisode.get(epNum).push(batch);
|
|
987
|
-
}
|
|
988
|
-
const previousProvider = strOf(ctx.previousState["provider"]).trim() || null;
|
|
989
|
-
for (const episode of asList(ctx.plan["episodes"])) {
|
|
990
|
-
const cached = ctx.checkpointReused
|
|
991
|
-
? loadCheckpointedEpisode(ctx.sourceText, ctx.episodeResultsDir, episode, ctx.providerName, ctx.model, previousProvider)
|
|
992
|
-
: null;
|
|
993
|
-
if (cached !== null) {
|
|
994
|
-
ctx.results.push(cached);
|
|
995
|
-
ctx.skipped.push(Number(episode["episode"]));
|
|
996
|
-
const cachedBatches = batchesByEpisode.get(Number(episode["episode"])) ?? [];
|
|
997
|
-
ctx.skippedEpisodeBatchCount += cachedBatches.length;
|
|
998
|
-
for (const cachedBatch of cachedBatches) {
|
|
999
|
-
if (!exists(batchResultPath(ctx.batchResultsDir, cachedBatch))) {
|
|
1000
|
-
const backfilled = recoverBatchFromSource(ctx.sourceText, cachedBatch);
|
|
1001
|
-
persistBatchResult(ctx.batchResultsDir, cachedBatch, backfilled);
|
|
1002
|
-
updateBatchResultMetadata(ctx.batchResultsDir, cachedBatch, ctx.providerName, ctx.model);
|
|
1003
|
-
}
|
|
1004
|
-
const errorPath = batchErrorPath(ctx.batchResultsDir, cachedBatch);
|
|
1005
|
-
if (exists(errorPath))
|
|
1006
|
-
deletePath(errorPath);
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
else {
|
|
1010
|
-
pendingBatches.push(...(batchesByEpisode.get(Number(episode["episode"])) ?? []));
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
const pending = [];
|
|
1014
|
-
for (const batch of pendingBatches) {
|
|
1015
|
-
const cachedBatch = ctx.batchCheckpointReused
|
|
1016
|
-
? loadCheckpointedBatch(ctx.sourceText, ctx.batchResultsDir, batch, ctx.providerName, ctx.model, previousProvider)
|
|
1017
|
-
: null;
|
|
1018
|
-
if (cachedBatch !== null) {
|
|
1019
|
-
cachedBatch["_batch_id"] = batchResultKey(batch);
|
|
1020
|
-
cachedBatch["_batch_part"] = Number(batch["part"]);
|
|
1021
|
-
cachedBatch["_starts_inside_scene"] = Boolean(batch["starts_inside_scene"]);
|
|
1022
|
-
ctx.batchResults.push(cachedBatch);
|
|
1023
|
-
ctx.skippedBatches.push(batchResultKey(batch));
|
|
1024
|
-
}
|
|
1025
|
-
else {
|
|
1026
|
-
pending.push(batch);
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
const failures = [];
|
|
1030
|
-
const outcomes = await pMapWithConcurrency(pending, ctx.concurrency, async (batch) => {
|
|
1031
|
-
return await extractBatchWithRecovery(ctx.provider, ctx.sourceText, batch);
|
|
799
|
+
exitCode: exc.exitCode,
|
|
800
|
+
required: exc.required.length > 0 ? exc.required : ["episode titles generated from source text"],
|
|
801
|
+
received: exc.received.length > 0 ? exc.received : [String(exc.message).slice(0, 160)],
|
|
802
|
+
nextSteps: exc.nextSteps.length > 0 ? exc.nextSteps : ["Rerun init after checking source episode headers."],
|
|
1032
803
|
});
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
804
|
+
}
|
|
805
|
+
const e = exc;
|
|
806
|
+
throw initFailedReport(workspace, {
|
|
807
|
+
title: "INIT FAILED: Episode title planning failed",
|
|
808
|
+
stage: "episode_titles",
|
|
809
|
+
required: ["episode titles generated from source text"],
|
|
810
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
811
|
+
nextSteps: ["Inspect workspace/source.txt and episode_plan.json, then rerun init."],
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
let batchPlan;
|
|
815
|
+
try {
|
|
816
|
+
batchPlan = buildBatchPlan(sourceText, plan, {
|
|
817
|
+
targetLines: batchTargetLines,
|
|
818
|
+
maxChars: batchMaxChars,
|
|
819
|
+
minLines: batchMinLines,
|
|
820
|
+
mode: batchMode,
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
catch (exc) {
|
|
824
|
+
const e = exc;
|
|
825
|
+
throw initFailedReport(workspace, {
|
|
826
|
+
title: "INIT FAILED: Batch planning failed",
|
|
827
|
+
stage: "batch_plan",
|
|
828
|
+
required: ["episode_plan.json that can be split into natural paragraph batches"],
|
|
829
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
830
|
+
nextSteps: ["Inspect workspace/source.txt and episode_plan.json, then rerun init."],
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
const checkpoint = initCheckpoint(sourceText, plan);
|
|
834
|
+
const batchCheckpoint = initBatchCheckpoint(sourceText, batchPlan);
|
|
835
|
+
const previousState = previousStateBeforeInit;
|
|
836
|
+
const previousCheckpoint = isDict(previousState["checkpoint"]) ? previousState["checkpoint"] : {};
|
|
837
|
+
const previousBatchCheckpoint = isDict(previousState["batch_checkpoint"]) ? previousState["batch_checkpoint"] : {};
|
|
838
|
+
const checkpointReused = checkpointSourceMatches(previousCheckpoint, checkpoint);
|
|
839
|
+
const batchCheckpointReused = checkpointReused && batchCheckpointMatches(previousBatchCheckpoint, batchCheckpoint);
|
|
840
|
+
if (!checkpointReused)
|
|
841
|
+
resetInitOutputs(dd);
|
|
842
|
+
else if (!batchCheckpointReused)
|
|
843
|
+
resetBatchOutputs(dd);
|
|
844
|
+
writeJson(path.join(dd, "source_manifest.json"), manifest);
|
|
845
|
+
writeJson(path.join(dd, "episode_plan.json"), plan);
|
|
846
|
+
writeJson(path.join(dd, "batch_plan.json"), batchPlan);
|
|
847
|
+
const episodeResultsDir = path.join(dd, "episode_results");
|
|
848
|
+
const batchResultsDir = path.join(dd, "batch_results");
|
|
849
|
+
fs.mkdirSync(episodeResultsDir, { recursive: true });
|
|
850
|
+
fs.mkdirSync(batchResultsDir, { recursive: true });
|
|
851
|
+
updateRunState(workspace, {
|
|
852
|
+
status: "init_running",
|
|
853
|
+
init_stage: "batch_extract",
|
|
854
|
+
checkpoint,
|
|
855
|
+
batch_checkpoint: batchCheckpoint,
|
|
856
|
+
checkpoint_reused: checkpointReused,
|
|
857
|
+
batch_checkpoint_reused: batchCheckpointReused,
|
|
858
|
+
batch_mode: batchMode,
|
|
859
|
+
batch_target_lines: batchTargetLines,
|
|
860
|
+
batch_max_chars: batchMaxChars,
|
|
861
|
+
batch_min_lines: batchMinLines,
|
|
862
|
+
episode_total: asList(plan["episodes"]).length,
|
|
863
|
+
batch_total: asList(batchPlan["batches"]).length,
|
|
864
|
+
});
|
|
865
|
+
const results = [];
|
|
866
|
+
const skipped = [];
|
|
867
|
+
let skippedEpisodeBatchCount = 0;
|
|
868
|
+
const pendingBatches = [];
|
|
869
|
+
const batchesByEpisode = new Map();
|
|
870
|
+
for (const batch of asList(batchPlan["batches"])) {
|
|
871
|
+
const epNum = Number(batch["episode"]);
|
|
872
|
+
if (!batchesByEpisode.has(epNum))
|
|
873
|
+
batchesByEpisode.set(epNum, []);
|
|
874
|
+
batchesByEpisode.get(epNum).push(batch);
|
|
875
|
+
}
|
|
876
|
+
const previousProvider = strOf(previousState["provider"]).trim() || null;
|
|
877
|
+
for (const episode of asList(plan["episodes"])) {
|
|
878
|
+
const cached = checkpointReused
|
|
879
|
+
? loadCheckpointedEpisode(sourceText, episodeResultsDir, episode, providerName, model, previousProvider)
|
|
880
|
+
: null;
|
|
881
|
+
if (cached !== null) {
|
|
882
|
+
results.push(cached);
|
|
883
|
+
skipped.push(Number(episode["episode"]));
|
|
884
|
+
const cachedBatches = batchesByEpisode.get(Number(episode["episode"])) ?? [];
|
|
885
|
+
skippedEpisodeBatchCount += cachedBatches.length;
|
|
886
|
+
for (const cachedBatch of cachedBatches) {
|
|
887
|
+
if (!exists(batchResultPath(batchResultsDir, cachedBatch))) {
|
|
888
|
+
const backfilled = recoverBatchFromSource(sourceText, cachedBatch);
|
|
889
|
+
persistBatchResult(batchResultsDir, cachedBatch, backfilled);
|
|
890
|
+
updateBatchResultMetadata(batchResultsDir, cachedBatch, providerName, model);
|
|
1050
891
|
}
|
|
892
|
+
const errorPath = batchErrorPath(batchResultsDir, cachedBatch);
|
|
893
|
+
if (exists(errorPath))
|
|
894
|
+
deletePath(errorPath);
|
|
1051
895
|
}
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
896
|
+
}
|
|
897
|
+
else {
|
|
898
|
+
pendingBatches.push(...(batchesByEpisode.get(Number(episode["episode"])) ?? []));
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const batchResults = [];
|
|
902
|
+
const skippedBatches = [];
|
|
903
|
+
const pending = [];
|
|
904
|
+
for (const batch of pendingBatches) {
|
|
905
|
+
const cachedBatch = batchCheckpointReused
|
|
906
|
+
? loadCheckpointedBatch(sourceText, batchResultsDir, batch, providerName, model, previousProvider)
|
|
907
|
+
: null;
|
|
908
|
+
if (cachedBatch !== null) {
|
|
909
|
+
cachedBatch["_batch_id"] = batchResultKey(batch);
|
|
910
|
+
cachedBatch["_batch_part"] = Number(batch["part"]);
|
|
911
|
+
cachedBatch["_starts_inside_scene"] = Boolean(batch["starts_inside_scene"]);
|
|
912
|
+
batchResults.push(cachedBatch);
|
|
913
|
+
skippedBatches.push(batchResultKey(batch));
|
|
914
|
+
}
|
|
915
|
+
else {
|
|
916
|
+
pending.push(batch);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
const failures = [];
|
|
920
|
+
const outcomes = await pMapWithConcurrency(pending, concurrency, async (batch) => {
|
|
921
|
+
return await extractBatchWithRecovery(provider, sourceText, batch);
|
|
922
|
+
});
|
|
923
|
+
for (let i = 0; i < outcomes.length; i++) {
|
|
924
|
+
const outcome = outcomes[i];
|
|
925
|
+
const batch = pending[i];
|
|
926
|
+
const errorPath = batchErrorPath(batchResultsDir, batch);
|
|
927
|
+
if (outcome.ok) {
|
|
928
|
+
const result = outcome.value;
|
|
929
|
+
result["_batch_id"] = batchResultKey(batch);
|
|
930
|
+
result["_batch_part"] = Number(batch["part"]);
|
|
931
|
+
result["_starts_inside_scene"] = Boolean(batch["starts_inside_scene"]);
|
|
932
|
+
batchResults.push(result);
|
|
933
|
+
persistBatchResult(batchResultsDir, batch, result);
|
|
934
|
+
updateBatchResultMetadata(batchResultsDir, batch, providerName, model);
|
|
935
|
+
if (exists(errorPath))
|
|
936
|
+
deletePath(errorPath);
|
|
937
|
+
}
|
|
938
|
+
else {
|
|
939
|
+
failures.push(writeBatchFailure(batchResultsDir, batch, outcome.error));
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
results.sort((a, b) => Number(a["episode"] ?? 0) - Number(b["episode"] ?? 0));
|
|
943
|
+
batchResults.sort((a, b) => {
|
|
944
|
+
const ea = Number(a["episode"] ?? 0);
|
|
945
|
+
const eb = Number(b["episode"] ?? 0);
|
|
946
|
+
if (ea !== eb)
|
|
947
|
+
return ea - eb;
|
|
948
|
+
return Number(a["_batch_part"] ?? 0) - Number(b["_batch_part"] ?? 0);
|
|
949
|
+
});
|
|
950
|
+
failures.sort((a, b) => {
|
|
951
|
+
const ea = Number(a["episode"] ?? 0);
|
|
952
|
+
const eb = Number(b["episode"] ?? 0);
|
|
953
|
+
if (ea !== eb)
|
|
954
|
+
return ea - eb;
|
|
955
|
+
return Number(a["part"] ?? 0) - Number(b["part"] ?? 0);
|
|
956
|
+
});
|
|
957
|
+
const completedBatches = skippedEpisodeBatchCount + batchResults.length;
|
|
958
|
+
if (failures.length > 0) {
|
|
959
|
+
const failedEpisodes = [...new Set(failures.map((it) => Number(it["episode"])))].sort((a, b) => a - b);
|
|
960
|
+
const failedBatches = failures.map((it) => strOf(it["batch_id"]));
|
|
961
|
+
const currentFailureSignature = failureSignature(failedBatches);
|
|
962
|
+
const previousFailureSignature = failureSignature(previousState["failed_batches"]);
|
|
963
|
+
const sameFailuresRepeated = checkpointReused &&
|
|
964
|
+
batchCheckpointReused &&
|
|
965
|
+
currentFailureSignature.length > 0 &&
|
|
966
|
+
currentFailureSignature.length === previousFailureSignature.length &&
|
|
967
|
+
currentFailureSignature.every((v, idx) => v === previousFailureSignature[idx]) &&
|
|
968
|
+
["init_incomplete", "init_stalled"].includes(strOf(previousState["status"]));
|
|
969
|
+
const previousFailureStreak = normalizeInt(previousState["failure_streak"], 0);
|
|
970
|
+
const failureStreak = sameFailuresRepeated ? previousFailureStreak + 1 : 1;
|
|
971
|
+
const failureTitle = sameFailuresRepeated
|
|
972
|
+
? "INIT STALLED: Same batches keep failing"
|
|
973
|
+
: "INIT INCOMPLETE: Batch extraction failed";
|
|
974
|
+
const nextSteps = sameFailuresRepeated
|
|
975
|
+
? [
|
|
976
|
+
"Run direct inspect --target issue to read failed batch details.",
|
|
977
|
+
"Do not rerun the same init command again until source, batch options, provider, or failed content has changed.",
|
|
978
|
+
]
|
|
979
|
+
: [
|
|
980
|
+
"Run direct inspect --target issue to review failed batches.",
|
|
981
|
+
"Rerun the same init once if failures look transient; completed checkpoints will be reused.",
|
|
982
|
+
];
|
|
983
|
+
const failedEpisodeSet = new Set(failedEpisodes);
|
|
984
|
+
const skippedSet = new Set(skipped);
|
|
985
|
+
const batchResultsByEpisode = new Map();
|
|
986
|
+
for (const result of batchResults) {
|
|
987
|
+
const ep = Number(result["episode"] ?? 0);
|
|
988
|
+
if (!batchResultsByEpisode.has(ep))
|
|
989
|
+
batchResultsByEpisode.set(ep, []);
|
|
990
|
+
batchResultsByEpisode.get(ep).push(result);
|
|
991
|
+
}
|
|
992
|
+
for (const episode of asList(plan["episodes"])) {
|
|
993
|
+
const episodeNum = Number(episode["episode"]);
|
|
994
|
+
if (skippedSet.has(episodeNum) || failedEpisodeSet.has(episodeNum))
|
|
995
|
+
continue;
|
|
996
|
+
const expectedBatches = (batchesByEpisode.get(episodeNum) ?? []).length;
|
|
997
|
+
if (expectedBatches && (batchResultsByEpisode.get(episodeNum) ?? []).length === expectedBatches) {
|
|
998
|
+
const result = mergeBatchResultsForEpisode(episode, batchResultsByEpisode.get(episodeNum) ?? []);
|
|
999
|
+
validateEpisodeExtractionQuality(sourceText, episode, result);
|
|
1000
|
+
results.push(result);
|
|
1001
|
+
writeJson(episodeResultPath(episodeResultsDir, episode), compactEpisodeResult(result));
|
|
1002
|
+
updateEpisodeResultMetadata(episodeResultsDir, episode, providerName, model);
|
|
1150
1003
|
}
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1004
|
+
}
|
|
1005
|
+
updateRunState(workspace, {
|
|
1006
|
+
status: sameFailuresRepeated ? "init_stalled" : "init_incomplete",
|
|
1007
|
+
init_stage: "batch_extract",
|
|
1008
|
+
checkpoint,
|
|
1009
|
+
batch_checkpoint: batchCheckpoint,
|
|
1010
|
+
episode_total: asList(plan["episodes"]).length,
|
|
1011
|
+
episode_completed: results.length,
|
|
1012
|
+
episode_reused: skipped.length,
|
|
1013
|
+
episode_failed: failedEpisodes.length,
|
|
1014
|
+
failed_episodes: failedEpisodes,
|
|
1015
|
+
batch_total: asList(batchPlan["batches"]).length,
|
|
1016
|
+
batch_completed: completedBatches,
|
|
1017
|
+
batch_reused: skippedEpisodeBatchCount + skippedBatches.length,
|
|
1018
|
+
batch_failed: failures.length,
|
|
1019
|
+
failed_batches: failedBatches,
|
|
1020
|
+
failure_signature: currentFailureSignature,
|
|
1021
|
+
failure_streak: failureStreak,
|
|
1022
|
+
last_error: { title: failureTitle, failed_at: checkpointTimestamp() },
|
|
1023
|
+
exportable: false,
|
|
1024
|
+
});
|
|
1025
|
+
const issues = failures.slice(0, 5).map((it) => `${it["batch_id"]} episode ${it["episode"]} part ${it["part"]}: ${it["error_type"]} - ${it["message"]}`);
|
|
1026
|
+
const report = {
|
|
1027
|
+
title: failureTitle,
|
|
1028
|
+
result: [
|
|
1029
|
+
`episodes total: ${asList(plan["episodes"]).length}`,
|
|
1030
|
+
`completed: ${results.length}`,
|
|
1031
|
+
`reused: ${skipped.length}`,
|
|
1032
|
+
`failed episodes: ${failedEpisodes.length}`,
|
|
1033
|
+
`batches: ${completedBatches}/${asList(batchPlan["batches"]).length} completed, ${failures.length} failed`,
|
|
1034
|
+
`provider: ${providerName}`,
|
|
1035
|
+
],
|
|
1036
|
+
artifacts: [
|
|
1037
|
+
path.join(workspace, "source.txt"),
|
|
1038
|
+
path.join(dd, "source_manifest.json"),
|
|
1039
|
+
path.join(dd, "episode_plan.json"),
|
|
1040
|
+
path.join(dd, "batch_plan.json"),
|
|
1041
|
+
batchResultsDir,
|
|
1042
|
+
episodeResultsDir,
|
|
1043
|
+
path.join(dd, "run_state.json"),
|
|
1044
|
+
],
|
|
1045
|
+
issues,
|
|
1046
|
+
next: nextSteps,
|
|
1047
|
+
};
|
|
1048
|
+
return [report, EXIT_RUNTIME];
|
|
1049
|
+
}
|
|
1050
|
+
updateRunState(workspace, {
|
|
1051
|
+
status: "init_running",
|
|
1052
|
+
init_stage: "episode_merge",
|
|
1053
|
+
checkpoint,
|
|
1054
|
+
batch_checkpoint: batchCheckpoint,
|
|
1055
|
+
episode_total: asList(plan["episodes"]).length,
|
|
1056
|
+
episode_completed: results.length,
|
|
1057
|
+
episode_reused: skipped.length,
|
|
1058
|
+
episode_failed: 0,
|
|
1059
|
+
failed_episodes: [],
|
|
1060
|
+
batch_total: asList(batchPlan["batches"]).length,
|
|
1061
|
+
batch_completed: completedBatches,
|
|
1062
|
+
batch_reused: skippedEpisodeBatchCount + skippedBatches.length,
|
|
1063
|
+
batch_failed: 0,
|
|
1064
|
+
failed_batches: [],
|
|
1065
|
+
failure_signature: [],
|
|
1066
|
+
failure_streak: 0,
|
|
1067
|
+
last_error: null,
|
|
1068
|
+
});
|
|
1069
|
+
for (const dir of [batchResultsDir, episodeResultsDir]) {
|
|
1070
|
+
if (!exists(dir))
|
|
1071
|
+
continue;
|
|
1072
|
+
for (const name of fs.readdirSync(dir)) {
|
|
1073
|
+
if (name.endsWith(".error.json")) {
|
|
1182
1074
|
try {
|
|
1183
|
-
|
|
1075
|
+
deletePath(path.join(dir, name));
|
|
1184
1076
|
}
|
|
1185
1077
|
catch {
|
|
1186
|
-
|
|
1187
|
-
}
|
|
1188
|
-
for (const name of names) {
|
|
1189
|
-
if (name.endsWith(".error.json")) {
|
|
1190
|
-
try {
|
|
1191
|
-
deletePath(path.join(dir, name));
|
|
1192
|
-
}
|
|
1193
|
-
catch {
|
|
1194
|
-
// ignore
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1078
|
+
// ignore
|
|
1197
1079
|
}
|
|
1198
1080
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
const
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
updates: { checkpoint: ctx.checkpoint, batch_checkpoint: ctx.batchCheckpoint, episode_completed: ctx.results.length },
|
|
1263
|
-
});
|
|
1264
|
-
}
|
|
1265
|
-
const e = exc;
|
|
1266
|
-
throw initFailedReport(ctx.workspace, {
|
|
1267
|
-
title: "INIT FAILED: Asset curation failed",
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
try {
|
|
1084
|
+
const batchResultsByEpisode = new Map();
|
|
1085
|
+
for (const result of batchResults) {
|
|
1086
|
+
const ep = Number(result["episode"] ?? 0);
|
|
1087
|
+
if (!batchResultsByEpisode.has(ep))
|
|
1088
|
+
batchResultsByEpisode.set(ep, []);
|
|
1089
|
+
batchResultsByEpisode.get(ep).push(result);
|
|
1090
|
+
}
|
|
1091
|
+
const skippedSet = new Set(skipped);
|
|
1092
|
+
for (const episode of asList(plan["episodes"])) {
|
|
1093
|
+
const episodeNum = Number(episode["episode"]);
|
|
1094
|
+
if (skippedSet.has(episodeNum))
|
|
1095
|
+
continue;
|
|
1096
|
+
const result = mergeBatchResultsForEpisode(episode, batchResultsByEpisode.get(episodeNum) ?? []);
|
|
1097
|
+
validateEpisodeExtractionQuality(sourceText, episode, result);
|
|
1098
|
+
results.push(result);
|
|
1099
|
+
writeJson(episodeResultPath(episodeResultsDir, episode), compactEpisodeResult(result));
|
|
1100
|
+
updateEpisodeResultMetadata(episodeResultsDir, episode, providerName, model);
|
|
1101
|
+
const errorPath = episodeErrorPath(episodeResultsDir, episode);
|
|
1102
|
+
if (exists(errorPath))
|
|
1103
|
+
deletePath(errorPath);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
catch (exc) {
|
|
1107
|
+
const e = exc;
|
|
1108
|
+
throw initFailedReport(workspace, {
|
|
1109
|
+
title: "INIT FAILED: Episode merge failed",
|
|
1110
|
+
stage: "episode_merge",
|
|
1111
|
+
required: ["complete batch_results/*.json that can merge into episode_results/*.json"],
|
|
1112
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
1113
|
+
nextSteps: ["Rerun init; completed batch checkpoints will be reused and episode merge will retry."],
|
|
1114
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, batch_completed: completedBatches },
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
results.sort((a, b) => Number(a["episode"] ?? 0) - Number(b["episode"] ?? 0));
|
|
1118
|
+
let script;
|
|
1119
|
+
try {
|
|
1120
|
+
updateRunState(workspace, { status: "init_running", init_stage: "script_merge", checkpoint, batch_checkpoint: batchCheckpoint });
|
|
1121
|
+
script = mergeEpisodeResults(results, strOf(info["projectName"]) || path.basename(source, path.extname(source)));
|
|
1122
|
+
}
|
|
1123
|
+
catch (exc) {
|
|
1124
|
+
const e = exc;
|
|
1125
|
+
throw initFailedReport(workspace, {
|
|
1126
|
+
title: "INIT FAILED: Merge failed",
|
|
1127
|
+
stage: "script_merge",
|
|
1128
|
+
required: ["complete episode_results/*.json"],
|
|
1129
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
1130
|
+
nextSteps: ["Rerun init; completed episode extraction checkpoints will be reused and merge will retry."],
|
|
1131
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, episode_completed: results.length },
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
try {
|
|
1135
|
+
updateRunState(workspace, { status: "init_running", init_stage: "asset_curation", checkpoint, batch_checkpoint: batchCheckpoint });
|
|
1136
|
+
const rawCuration = await providerExtractAssetCurationLocal(provider, sourceText, script);
|
|
1137
|
+
const curation = curateScriptAssets(script, rawCuration);
|
|
1138
|
+
writeJson(path.join(dd, "asset_curation.json"), curation);
|
|
1139
|
+
}
|
|
1140
|
+
catch (exc) {
|
|
1141
|
+
if (exc instanceof CliError) {
|
|
1142
|
+
throw initFailedReport(workspace, {
|
|
1143
|
+
title: exc.title,
|
|
1268
1144
|
stage: "asset_curation",
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1145
|
+
exitCode: exc.exitCode,
|
|
1146
|
+
required: exc.required.length > 0 ? exc.required : ["asset curation JSON matching final script contract"],
|
|
1147
|
+
received: exc.received.length > 0 ? exc.received : [String(exc.message).slice(0, 160)],
|
|
1148
|
+
nextSteps: exc.nextSteps.length > 0 ? exc.nextSteps : ["Rerun init; extraction checkpoints will be reused and asset curation will retry."],
|
|
1149
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, episode_completed: results.length },
|
|
1273
1150
|
});
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
});
|
|
1298
|
-
}
|
|
1299
|
-
const e = exc;
|
|
1300
|
-
throw initFailedReport(ctx.workspace, {
|
|
1301
|
-
title: "INIT FAILED: Metadata extraction failed",
|
|
1151
|
+
}
|
|
1152
|
+
const e = exc;
|
|
1153
|
+
throw initFailedReport(workspace, {
|
|
1154
|
+
title: "INIT FAILED: Asset curation failed",
|
|
1155
|
+
stage: "asset_curation",
|
|
1156
|
+
required: ["provider location merge decisions and deterministic asset reuse curation"],
|
|
1157
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
1158
|
+
nextSteps: ["Rerun init; extraction checkpoints will be reused and asset curation will retry."],
|
|
1159
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, episode_completed: results.length },
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
try {
|
|
1163
|
+
updateRunState(workspace, { status: "init_running", init_stage: "metadata_extract", checkpoint, batch_checkpoint: batchCheckpoint });
|
|
1164
|
+
let metadata = provider.extractMetadata ? await provider.extractMetadata(sourceText, script) : {};
|
|
1165
|
+
if (!isDict(metadata))
|
|
1166
|
+
metadata = {};
|
|
1167
|
+
writeJson(path.join(dd, "asset_metadata.json"), metadata);
|
|
1168
|
+
applyMetadataToScript(script, metadata);
|
|
1169
|
+
}
|
|
1170
|
+
catch (exc) {
|
|
1171
|
+
if (exc instanceof CliError) {
|
|
1172
|
+
throw initFailedReport(workspace, {
|
|
1173
|
+
title: exc.title,
|
|
1302
1174
|
stage: "metadata_extract",
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1175
|
+
exitCode: exc.exitCode,
|
|
1176
|
+
required: exc.required.length > 0 ? exc.required : ["metadata JSON matching final script contract"],
|
|
1177
|
+
received: exc.received.length > 0 ? exc.received : [String(exc.message).slice(0, 160)],
|
|
1178
|
+
nextSteps: exc.nextSteps.length > 0 ? exc.nextSteps : ["Rerun init; extraction checkpoints will be reused and metadata will retry."],
|
|
1179
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, episode_completed: results.length },
|
|
1307
1180
|
});
|
|
1308
|
-
}
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1181
|
+
}
|
|
1182
|
+
const e = exc;
|
|
1183
|
+
throw initFailedReport(workspace, {
|
|
1184
|
+
title: "INIT FAILED: Metadata extraction failed",
|
|
1185
|
+
stage: "metadata_extract",
|
|
1186
|
+
required: ["provider metadata for worldview, role_type, and asset descriptions"],
|
|
1187
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
1188
|
+
nextSteps: ["Rerun init; extraction checkpoints will be reused and metadata will retry."],
|
|
1189
|
+
updates: { checkpoint, batch_checkpoint: batchCheckpoint, episode_completed: results.length },
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
const scriptPath = path.join(dd, "script.initial.json");
|
|
1193
|
+
writeJson(scriptPath, script);
|
|
1194
|
+
updateRunState(workspace, { status: "init_running", init_stage: "validate", checkpoint, batch_checkpoint: batchCheckpoint });
|
|
1195
|
+
let validation;
|
|
1196
|
+
try {
|
|
1197
|
+
validation = validateScript(workspace, scriptPath);
|
|
1198
|
+
}
|
|
1199
|
+
catch (exc) {
|
|
1200
|
+
const e = exc;
|
|
1201
|
+
throw initFailedReport(workspace, {
|
|
1202
|
+
title: "INIT FAILED: Validation failed",
|
|
1203
|
+
stage: "validate",
|
|
1204
|
+
required: ["script.initial.json that can be validated"],
|
|
1205
|
+
received: [`${e?.name ?? "Error"}: ${(e?.message ?? "").slice(0, 160)}`],
|
|
1206
|
+
nextSteps: ["Rerun init to retry validation, or inspect script.initial.json if the failure persists."],
|
|
1207
|
+
updates: { checkpoint, script_path: scriptPath },
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
const passed = Boolean(validation["passed"]);
|
|
1211
|
+
const status = passed ? "ready_for_agent" : "needs_agent_repair";
|
|
1212
|
+
updateRunState(workspace, {
|
|
1213
|
+
status,
|
|
1214
|
+
command: "direct init",
|
|
1215
|
+
init_stage: "complete",
|
|
1216
|
+
checkpoint,
|
|
1217
|
+
batch_checkpoint: batchCheckpoint,
|
|
1218
|
+
checkpoint_reused: checkpointReused,
|
|
1219
|
+
batch_checkpoint_reused: batchCheckpointReused,
|
|
1220
|
+
provider: providerName,
|
|
1221
|
+
model,
|
|
1222
|
+
concurrency,
|
|
1223
|
+
batch_mode: batchMode,
|
|
1224
|
+
batch_target_lines: batchTargetLines,
|
|
1225
|
+
batch_max_chars: batchMaxChars,
|
|
1226
|
+
batch_min_lines: batchMinLines,
|
|
1227
|
+
source_path: path.resolve(source),
|
|
1228
|
+
script_path: scriptPath,
|
|
1229
|
+
validation_path: path.join(dd, "validation.json"),
|
|
1230
|
+
episode_total: asList(plan["episodes"]).length,
|
|
1231
|
+
episode_completed: results.length,
|
|
1232
|
+
episode_reused: skipped.length,
|
|
1233
|
+
episode_failed: 0,
|
|
1234
|
+
failed_episodes: [],
|
|
1235
|
+
batch_total: asList(batchPlan["batches"]).length,
|
|
1236
|
+
batch_completed: completedBatches,
|
|
1237
|
+
batch_reused: skippedEpisodeBatchCount + skippedBatches.length,
|
|
1238
|
+
batch_failed: 0,
|
|
1239
|
+
failed_batches: [],
|
|
1240
|
+
failure_signature: [],
|
|
1241
|
+
failure_streak: 0,
|
|
1242
|
+
last_error: null,
|
|
1243
|
+
review_status: "pending",
|
|
1244
|
+
review_missing: [...REVIEW_TARGETS],
|
|
1245
|
+
inspected_targets: [],
|
|
1246
|
+
patch_count: 0,
|
|
1247
|
+
exportable: providerName !== "mock",
|
|
1248
|
+
});
|
|
1249
|
+
const title = passed
|
|
1250
|
+
? "INIT COMPLETE: Initial script ready"
|
|
1251
|
+
: "INIT NEEDS AGENT: Initial script written with repair issues";
|
|
1252
|
+
const stats = validation["stats"] ?? {};
|
|
1253
|
+
const report = {
|
|
1254
|
+
title,
|
|
1255
|
+
result: [
|
|
1256
|
+
`episodes: ${stats["episodes"] ?? 0}`,
|
|
1257
|
+
`scenes: ${stats["scenes"] ?? 0}`,
|
|
1258
|
+
`actions: ${stats["actions"] ?? 0}`,
|
|
1259
|
+
`validation: ${passed ? "passed" : "needs repair"}`,
|
|
1260
|
+
`provider: ${providerName}`,
|
|
1261
|
+
`episode checkpoint reused: ${skipped.length}`,
|
|
1262
|
+
`batches: ${completedBatches}/${asList(batchPlan["batches"]).length} completed`,
|
|
1263
|
+
`batch checkpoint reused: ${skippedEpisodeBatchCount + skippedBatches.length}`,
|
|
1264
|
+
"agent_review: pending",
|
|
1265
|
+
],
|
|
1266
|
+
artifacts: [
|
|
1267
|
+
path.join(workspace, "source.txt"),
|
|
1268
|
+
path.join(dd, "source_manifest.json"),
|
|
1269
|
+
path.join(dd, "episode_plan.json"),
|
|
1270
|
+
path.join(dd, "batch_plan.json"),
|
|
1271
|
+
batchResultsDir,
|
|
1272
|
+
episodeResultsDir,
|
|
1273
|
+
path.join(dd, "asset_curation.json"),
|
|
1274
|
+
path.join(dd, "asset_metadata.json"),
|
|
1275
|
+
scriptPath,
|
|
1276
|
+
path.join(dd, "validation.json"),
|
|
1277
|
+
path.join(dd, "run_state.json"),
|
|
1278
|
+
],
|
|
1279
|
+
issues: summarizeIssues(asList(validation["issues"])),
|
|
1280
|
+
next: providerName === "mock"
|
|
1281
|
+
? [
|
|
1282
|
+
"Run inspect for issue, episode, and asset; apply patches if needed; then validate/export.",
|
|
1283
|
+
"Do not export mock-provider results for delivery.",
|
|
1284
|
+
]
|
|
1285
|
+
: ["Run inspect for issue, episode, and asset; apply patches if needed; then validate/export."],
|
|
1286
|
+
};
|
|
1287
|
+
return [report, passed ? EXIT_OK : EXIT_NEEDS_AGENT];
|
|
1288
|
+
}
|
|
1416
1289
|
export function summarizeIssues(issues) {
|
|
1417
1290
|
if (issues.length === 0)
|
|
1418
1291
|
return [];
|