@tiangong-lca/foundry 0.1.10 → 0.1.12

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.
Files changed (44) hide show
  1. package/README.md +6 -6
  2. package/docs/architecture.md +6 -6
  3. package/docs/foundry-task-contracts.md +11 -3
  4. package/docs/package-distribution-contract.md +6 -4
  5. package/docs/public-runtime-contract.md +21 -5
  6. package/docs/runtime-context-contract.md +7 -3
  7. package/docs/task-authorization-contract.md +5 -3
  8. package/package-dist/assets/foundry-package-descriptor.json +120 -64
  9. package/package-dist/scripts/foundry-facade.d.ts +1 -0
  10. package/package-dist/scripts/foundry-facade.js +261 -36
  11. package/package-dist/scripts/foundry-runtime.d.ts +2 -1
  12. package/package-dist/scripts/foundry-runtime.js +2 -2
  13. package/package-dist/scripts/lib/foundry-interaction-input.d.ts +19 -0
  14. package/package-dist/scripts/lib/foundry-interaction-input.js +327 -0
  15. package/package-dist/scripts/lib/foundry-interaction-projection.d.ts +22 -0
  16. package/package-dist/scripts/lib/foundry-interaction-projection.js +81 -0
  17. package/package-dist/scripts/lib/foundry-interaction-types.d.ts +17 -0
  18. package/package-dist/scripts/lib/foundry-interaction-types.js +4 -0
  19. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -2
  20. package/package-dist/scripts/lib/foundry-package-contract.d.ts +3 -3
  21. package/package-dist/scripts/lib/foundry-package-contract.js +3 -1
  22. package/package-dist/scripts/lib/foundry-semantic-input.d.ts +2 -0
  23. package/package-dist/scripts/lib/foundry-semantic-input.js +29 -2
  24. package/package-dist/scripts/lib/foundry-semantic-interaction.d.ts +12 -0
  25. package/package-dist/scripts/lib/foundry-semantic-interaction.js +38 -0
  26. package/package-dist/scripts/lib/foundry-task-start-spec.d.ts +11 -0
  27. package/package-dist/scripts/lib/foundry-task-start-spec.js +36 -0
  28. package/package-dist/scripts/lib/foundry-task-store.d.ts +1 -1
  29. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +7 -1
  30. package/package-dist/scripts/lib/foundry-workflow-assessment.js +301 -8
  31. package/package-dist/scripts/lib/foundry-workflow-finalize.js +7 -4
  32. package/package-dist/scripts/lib/foundry-workflow-interaction.d.ts +4 -0
  33. package/package-dist/scripts/lib/foundry-workflow-interaction.js +63 -0
  34. package/package-dist/scripts/lib/foundry-workflow-semantic.js +21 -1
  35. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +9 -1
  36. package/package-dist/scripts/lib/foundry-workflow-state.js +173 -21
  37. package/package-dist/scripts/public-api.d.ts +2 -0
  38. package/package-dist/scripts/public-api.js +1 -0
  39. package/package-dist/scripts/runtime-entry.js +9 -1
  40. package/package.json +2 -1
  41. package/specs/schemas/foundry-interaction-input.schema.json +173 -0
  42. package/specs/schemas/foundry-package-descriptor.schema.json +2 -1
  43. package/specs/schemas/foundry-semantic-input.schema.json +12 -1
  44. package/specs/schemas/foundry-task-start.schema.json +75 -0
@@ -23,6 +23,8 @@ import { completedOwnerScopes, prepareFoundryOwnerExecution, } from "./lib/found
23
23
  import { executeFoundryOwnerScope } from "./lib/foundry-workflow-execution.js";
24
24
  import { inspectFoundryReferences, verifyFoundryReferences, } from "./lib/foundry-workflow-reference-verify.js";
25
25
  import { selectFoundrySemanticInput } from "./lib/foundry-semantic-input.js";
26
+ import { currentFoundryInteractionState, currentFoundryQuestions, currentFoundryDecisions, currentFoundryInvestigations, currentFoundryAssumptions, selectFoundryInteractionInput, } from "./lib/foundry-interaction-input.js";
27
+ import { recordFoundryInteractionInput } from "./lib/foundry-workflow-interaction.js";
26
28
  import { runFoundryWorkflowIdentity } from "./lib/foundry-workflow-identity.js";
27
29
  import { finalizeFoundryWorkflow } from "./lib/foundry-workflow-finalize.js";
28
30
  import { prepareFoundryRepair, readFoundryRepairPreparation, } from "./lib/foundry-workflow-repair.js";
@@ -32,6 +34,7 @@ import { authorizeFoundryWorkflow } from "./lib/foundry-workflow-authorization.j
32
34
  import { continueFoundryPreparedApproval } from "./lib/foundry-workflow-approval-continuation.js";
33
35
  const maxSpecBytes = 1024 * 1024;
34
36
  const maxSeedBytes = 8 * 1024 * 1024;
37
+ const maxQueueBytes = 32 * 1024 * 1024;
35
38
  function readCaptured(fact, maxBytes, code) {
36
39
  if (fact.bytes > maxBytes)
37
40
  throw new FoundryContextError(code, "Selected facade input exceeds its byte limit.");
@@ -366,14 +369,145 @@ function completionProven(context, record, inspected) {
366
369
  }
367
370
  return false;
368
371
  }
372
+ function independentLocalPreparationPending(record, workflow, entries) {
373
+ if (record.spec.repair)
374
+ return false;
375
+ if (record.spec.preparation)
376
+ return !entries.some((entry) => entry.command === "dataset-curation-cleanup");
377
+ return !workflow.rows || workflow.assessmentRemainingTypes.length > 0;
378
+ }
379
+ function currentIndexedQueueBlockers(context, workflow, entries) {
380
+ const blockers = [];
381
+ const actions = [];
382
+ const seenBlockerSha256 = new Set();
383
+ const queueExpected = workflow.rows?.value.sets.some((set) => set.type === "process") ?? false;
384
+ for (const set of workflow.assessment?.value.sets ?? []) {
385
+ if (typeof set.curation_report !== "string")
386
+ continue;
387
+ const curation = entries.find((entry) => entry.command === "dataset-workflow-assessment" &&
388
+ path.join(context.taskRoot, entry.path) === set.curation_report);
389
+ if (!curation)
390
+ continue;
391
+ // Artifact-index paths use '/' on every platform, including Windows.
392
+ const manifest = entries.find((entry) => entry.operation_id === curation.operation_id &&
393
+ entry.path.endsWith("/queue/outputs/curation-queue-manifest.json"));
394
+ if (!manifest) {
395
+ if (queueExpected && ["flow", "process"].includes(String(set.type)))
396
+ throw new FoundryContextError("workflow_queue_invalid", "The registered assessment is missing its curation queue evidence.");
397
+ continue;
398
+ }
399
+ const blockerFile = entries.find((entry) => entry.operation_id === curation.operation_id &&
400
+ entry.path.endsWith("/queue/outputs/curation-queue-blockers.jsonl"));
401
+ if (!blockerFile)
402
+ throw new FoundryContextError("workflow_queue_invalid", "The registered curation queue is missing its complete blocker evidence.");
403
+ const manifestFile = path.join(context.taskRoot, manifest.path);
404
+ const detailsFile = path.join(context.taskRoot, blockerFile.path);
405
+ const report = workflowObject(JSON.parse(readCaptured({ path: manifestFile, bytes: manifest.bytes, sha256: manifest.sha256 }, maxQueueBytes, "workflow_queue_invalid").toString("utf8")));
406
+ if (report.status !== "blocked")
407
+ continue;
408
+ const reportFiles = workflowObject(report.files);
409
+ const reportCounts = workflowObject(report.counts);
410
+ if (report.schema_version !== 1 ||
411
+ reportFiles.manifest !== manifestFile ||
412
+ reportFiles.blockers !== detailsFile ||
413
+ !Array.isArray(report.blockers) ||
414
+ !report.blockers.length ||
415
+ reportCounts.blockers !== report.blockers.length)
416
+ throw new FoundryContextError("workflow_queue_invalid", "The registered curation queue blocker manifest is invalid.");
417
+ const recorded = report.blockers;
418
+ let blockerRows;
419
+ try {
420
+ blockerRows = readCaptured({ path: detailsFile, bytes: blockerFile.bytes, sha256: blockerFile.sha256 }, maxQueueBytes, "workflow_queue_invalid")
421
+ .toString("utf8")
422
+ .split(/\r?\n/u)
423
+ .filter((line) => line.length > 0)
424
+ .map((line) => JSON.parse(line));
425
+ }
426
+ catch {
427
+ throw new FoundryContextError("workflow_queue_invalid", "The registered curation queue blocker file is invalid or changed.");
428
+ }
429
+ if (JSON.stringify(blockerRows) !== JSON.stringify(recorded))
430
+ throw new FoundryContextError("workflow_queue_invalid", "The registered curation queue blocker file does not match its manifest.");
431
+ if (seenBlockerSha256.has(blockerFile.sha256))
432
+ continue;
433
+ seenBlockerSha256.add(blockerFile.sha256);
434
+ const missing = recorded
435
+ .map(workflowObject)
436
+ .filter((item) => item.code === "process_flow_reference_unresolved")
437
+ .reduce((total, item) => {
438
+ const refs = workflowObject(item.details).missing_flow_refs;
439
+ return total + (Array.isArray(refs) ? refs.length : 0);
440
+ }, 0);
441
+ const scope = missing ? "process" : String(set.type);
442
+ const message = missing
443
+ ? `Selected Process data has ${missing} unresolved Flow reference occurrence${missing === 1 ? "" : "s"}: the cited Flow evidence is absent from the selected inputs and has no verified external declaration. Process review is blocked; unrelated records can continue. Provide the cited Flow evidence or verified references, or keep the gap open. Adding selected sources requires a new task revision because this task's inputs are frozen. Full IDs and paths: ${detailsFile}.`
444
+ : `The selected ${scope} dependency queue has ${recorded.length} blocker${recorded.length === 1 ? "" : "s"}. Independent types can continue. Review the exact registered evidence at ${detailsFile} before revising the source or closure.`;
445
+ blockers.push({ code: "curation_queue_blocked", message, scope });
446
+ actions.push(human("review_queue_blockers", message));
447
+ }
448
+ return { blockers, actions };
449
+ }
369
450
  function taskProjection(operation, context, record, inspected, identity) {
370
451
  const artifacts = taskArtifacts(context, inspected);
371
- if (completionProven(context, record, inspected))
452
+ const interaction = currentFoundryInteractionState(context, inspected.artifacts);
453
+ const pendingQuestions = interaction ? currentFoundryQuestions(interaction.state) : [];
454
+ const investigations = interaction ? currentFoundryInvestigations(interaction.state) : [];
455
+ if (record.spec.brief)
456
+ artifacts.push(inlineArtifact("task_brief", record.spec.brief));
457
+ if (interaction)
458
+ artifacts.push(Object.freeze({
459
+ kind: "file",
460
+ role: "current_interaction_state",
461
+ path: path.join(context.taskRoot, interaction.entry.path),
462
+ bytes: interaction.entry.bytes,
463
+ sha256: interaction.entry.sha256,
464
+ }));
465
+ const recap = (completionProven) => {
466
+ const questions = new Map(interaction?.state.events
467
+ .filter((event) => event.kind === "question")
468
+ .map((event) => [String(event.id), event]) ?? []);
469
+ return inlineArtifact("decision_recap", {
470
+ schema: "tiangong-foundry.decision-recap.v1",
471
+ task_id: record.task_id,
472
+ completion_proven: completionProven,
473
+ brief: record.spec.brief ?? null,
474
+ user_decisions: interaction
475
+ ? currentFoundryDecisions(interaction.state).map((answer) => ({
476
+ question_id: answer.question_id,
477
+ dataset_type: questions.get(String(answer.question_id))?.dataset_type ?? null,
478
+ impact: questions.get(String(answer.question_id))?.impact ?? null,
479
+ raw_answer_sha256: createHash("sha256").update(String(answer.raw_answer)).digest("hex"),
480
+ adopted_decision: answer.adopted_decision,
481
+ decision_id: answer.decision_id,
482
+ supersedes_decision_id: answer.supersedes_decision_id,
483
+ evidence_sha256: answer.evidence_sha256,
484
+ }))
485
+ : [],
486
+ ai_assumptions: interaction ? currentFoundryAssumptions(interaction.state) : [],
487
+ unresolved_questions: [...pendingQuestions, ...investigations].map((question) => ({
488
+ id: question.id,
489
+ dataset_type: question.dataset_type,
490
+ missing: question.missing,
491
+ impact: question.impact,
492
+ ask: question.ask,
493
+ choices: question.choices,
494
+ })),
495
+ source_interaction_sha256: interaction?.entry.sha256 ?? null,
496
+ });
497
+ };
498
+ if (record.spec.brief || interaction)
499
+ artifacts.push(recap(false));
500
+ const completedArtifacts = () => record.spec.brief || interaction
501
+ ? [...artifacts.filter((artifact) => artifact.role !== "decision_recap"), recap(true)]
502
+ : artifacts;
503
+ if (completionProven(context, record, inspected) &&
504
+ !pendingQuestions.length &&
505
+ !investigations.length)
372
506
  return createFoundryOperationResult({
373
507
  operation,
374
508
  status: "completed",
375
509
  taskId: record.task_id,
376
- artifacts,
510
+ artifacts: completedArtifacts(),
377
511
  blockers: [],
378
512
  nextActions: [],
379
513
  runtimeIdentity: identity,
@@ -442,6 +576,7 @@ function taskProjection(operation, context, record, inspected, identity) {
442
576
  });
443
577
  }
444
578
  const workflow = currentWorkflowState(context, inspected.artifacts);
579
+ const queueIssues = currentIndexedQueueBlockers(context, workflow, inspected.artifacts);
445
580
  if (record.spec.repair && execution.verified.size) {
446
581
  if (execution.requests.length !== 1 || execution.verified.size !== 1)
447
582
  throw new FoundryContextError("repair_execution_mismatch", "A repair task must retain one exact verified execution scope.");
@@ -460,7 +595,7 @@ function taskProjection(operation, context, record, inspected, identity) {
460
595
  operation,
461
596
  status: "completed",
462
597
  taskId: record.task_id,
463
- artifacts,
598
+ artifacts: completedArtifacts(),
464
599
  blockers: [],
465
600
  nextActions: [],
466
601
  runtimeIdentity: identity,
@@ -477,7 +612,7 @@ function taskProjection(operation, context, record, inspected, identity) {
477
612
  operation,
478
613
  status: noChange ? "completed" : found ? "needs_input" : "ready",
479
614
  taskId: record.task_id,
480
- artifacts,
615
+ artifacts: noChange ? completedArtifacts() : artifacts,
481
616
  blockers: noChange || !found
482
617
  ? []
483
618
  : [
@@ -502,6 +637,36 @@ function taskProjection(operation, context, record, inspected, identity) {
502
637
  : noPermission(),
503
638
  });
504
639
  }
640
+ if (pendingQuestions.length || investigations.length) {
641
+ const describe = (question) => `${String(question.missing)} ${String(question.impact)} ${String(question.recommendation)} ${String(question.ask)}`;
642
+ const askActions = pendingQuestions.map((question) => human("answer_current_question", `${describe(question)}${Array.isArray(question.choices) && question.choices.length ? ` ${question.choices.join(" / ")}` : ""}`));
643
+ const investigationIds = new Set(investigations.map((question) => String(question.id)));
644
+ return createFoundryOperationResult({
645
+ operation,
646
+ status: "needs_input",
647
+ taskId: record.task_id,
648
+ artifacts,
649
+ blockers: [
650
+ ...[...pendingQuestions, ...investigations].map((question) => ({
651
+ code: investigationIds.has(String(question.id))
652
+ ? "interaction_investigation_pending"
653
+ : "interaction_decision_pending",
654
+ message: `${String(question.missing)} ${String(question.impact)}`,
655
+ scope: String(question.dataset_type ?? record.task_id),
656
+ })),
657
+ ...queueIssues.blockers,
658
+ ],
659
+ nextActions: [
660
+ ...askActions,
661
+ ...queueIssues.actions,
662
+ ...(independentLocalPreparationPending(record, workflow, inspected.artifacts)
663
+ ? [resumeCommand(context, record)]
664
+ : []),
665
+ ],
666
+ runtimeIdentity: identity,
667
+ permissions: noPermission(),
668
+ });
669
+ }
505
670
  const references = inspectFoundryReferences(context, inspected.artifacts);
506
671
  const scopeComplete = workflow.rows &&
507
672
  (workflow.rows.value.sets.length > 0 || references.scope) &&
@@ -511,7 +676,7 @@ function taskProjection(operation, context, record, inspected, identity) {
511
676
  operation,
512
677
  status: "completed",
513
678
  taskId: record.task_id,
514
- artifacts,
679
+ artifacts: completedArtifacts(),
515
680
  blockers: [],
516
681
  nextActions: [],
517
682
  runtimeIdentity: identity,
@@ -645,15 +810,15 @@ function taskProjection(operation, context, record, inspected, identity) {
645
810
  });
646
811
  const assessment = workflow.assessment?.entry;
647
812
  if (assessment) {
648
- const report = JSON.parse(readCaptured({ ...assessment, path: path.join(context.taskRoot, assessment.path) }, maxSeedBytes, "workflow_assessment_invalid").toString("utf8"));
649
- if (!report ||
650
- typeof report !== "object" ||
651
- !("schema" in report) ||
652
- report.schema !== "tiangong-foundry.assessment-stage.v1" ||
653
- !("sets" in report) ||
654
- !Array.isArray(report.sets))
813
+ const rawReport = JSON.parse(readCaptured({ ...assessment, path: path.join(context.taskRoot, assessment.path) }, maxSeedBytes, "workflow_assessment_invalid").toString("utf8"));
814
+ if (!rawReport ||
815
+ typeof rawReport !== "object" ||
816
+ !("schema" in rawReport) ||
817
+ rawReport.schema !== "tiangong-foundry.assessment-stage.v1" ||
818
+ !("sets" in rawReport) ||
819
+ !Array.isArray(rawReport.sets))
655
820
  throw new FoundryContextError("workflow_assessment_invalid", "Registered assessment metadata is invalid.");
656
- const pending = report.sets.filter((value) => {
821
+ const pending = workflow.assessment.value.sets.filter((value) => {
657
822
  if (!value ||
658
823
  typeof value !== "object" ||
659
824
  !("curation_counts" in value) ||
@@ -693,15 +858,22 @@ function taskProjection(operation, context, record, inspected, identity) {
693
858
  status: "needs_input",
694
859
  taskId: record.task_id,
695
860
  artifacts,
696
- blockers: pending.map((set) => ({
697
- code: "curation_requires_input",
698
- message: `Resolve the current ${set.type} curation and authoring work before a write handoff.`,
699
- scope: record.task_id,
700
- })),
701
- nextActions: pending.flatMap((set) => [
702
- human("review_semantic_work", `Read the registered curation report ${set.curation_report} and authoring manifest ${set.authoring_manifest}. Use their bound source/context evidence; no write permission is implied.`),
703
- ...(set.decisions ?? []).map((work) => human(`review_${work.kind}_decisions`, `Read registered ${work.kind} task ${work.task} (${work.status}). Complete its bound decision template and submit it with semantic-input kind=${work.kind}.`)),
704
- ]),
861
+ blockers: [
862
+ ...queueIssues.blockers,
863
+ ...pending.map((set) => ({
864
+ code: "curation_requires_input",
865
+ message: `Resolve the current ${set.type} curation and authoring work before a write handoff.`,
866
+ scope: record.task_id,
867
+ })),
868
+ ],
869
+ nextActions: [
870
+ ...queueIssues.actions,
871
+ ...pending.flatMap((set) => [
872
+ human("review_semantic_work", `Read the registered curation report ${set.curation_report} and authoring manifest ${set.authoring_manifest}. Use their bound source/context evidence; no write permission is implied.`),
873
+ ...(set.decisions ?? []).map((work) => human(`review_${work.kind}_decisions`, `Read registered ${work.kind} task ${work.task} (${work.status}). Complete its bound decision template and submit it with semantic-input kind=${work.kind}.`)),
874
+ ]),
875
+ ...(workflow.assessmentRemainingTypes.length ? [resumeCommand(context, record)] : []),
876
+ ],
705
877
  runtimeIdentity: identity,
706
878
  permissions: noPermission(),
707
879
  });
@@ -710,7 +882,7 @@ function taskProjection(operation, context, record, inspected, identity) {
710
882
  ? [
711
883
  human("review_prepared_rows", "Review the current prepared artifacts and continue the returned task workflow."),
712
884
  ]
713
- : record.spec.preparation || !workflow.assessment
885
+ : record.spec.preparation || !workflow.assessmentComplete
714
886
  ? [resumeCommand(context, record)]
715
887
  : [
716
888
  human("review_assessment", "Review the registered curation reports and authoring-task manifests. Resolve their current semantic work before requesting a write handoff; assessment does not grant permission."),
@@ -1037,6 +1209,7 @@ export function createFoundryFacade(options) {
1037
1209
  artifacts: [
1038
1210
  fileArtifact("facade_request_index", requestIndex),
1039
1211
  fileArtifact("foundry_job", path.join(context.taskRoot, "foundry-job.json")),
1212
+ ...result.artifacts,
1040
1213
  ],
1041
1214
  nextActions: result.next_actions,
1042
1215
  runtimeIdentity: result.runtime_identity,
@@ -1082,6 +1255,16 @@ export function createFoundryFacade(options) {
1082
1255
  if (input.referenceInputFile !== undefined &&
1083
1256
  (typeof input.referenceInputFile !== "string" || !input.referenceInputFile.trim()))
1084
1257
  throw new FoundryContextError("reference_input_invalid", "An explicit reference input requires one nonempty file path.");
1258
+ if (input.interactionInputFile !== undefined &&
1259
+ (typeof input.interactionInputFile !== "string" || !input.interactionInputFile.trim()))
1260
+ throw new FoundryContextError("interaction_input_invalid", "An explicit interaction input requires one nonempty file path.");
1261
+ if ([
1262
+ input.semanticInputFile,
1263
+ input.authorizationInputFile,
1264
+ input.referenceInputFile,
1265
+ input.interactionInputFile,
1266
+ ].filter((file) => file !== undefined).length > 1)
1267
+ throw new FoundryContextError("task_input_conflict", "Submit one task input kind at a time.");
1085
1268
  current = base();
1086
1269
  assertFoundryWorkspaceWrite(current);
1087
1270
  const record = loadFoundryFacadeTaskRecord(current, input.taskId, input.actorId);
@@ -1089,18 +1272,23 @@ export function createFoundryFacade(options) {
1089
1272
  const qualified = qualification(context, options.runtimeSelection);
1090
1273
  const runtime = createFoundryRuntime(context, qualified);
1091
1274
  const before = await runtime.inspectTask();
1092
- if (record.spec.repair && (input.semanticInputFile || input.referenceInputFile))
1275
+ if (record.spec.repair &&
1276
+ (input.semanticInputFile || input.referenceInputFile || input.interactionInputFile))
1093
1277
  throw new FoundryContextError("repair_revision_required", "A repair keeps its before, candidate and contract immutable; changed inputs require an explicit revision.");
1094
1278
  assertNotInterrupted(options.signal);
1095
1279
  loadFoundryFacadeTaskRecord(current, record.task_id, record.spec.actor_id);
1096
1280
  const existing = taskProjection("task.resume", context, record, before, runtimeIdentity(context, qualified));
1097
- if (input.referenceInputFile && existing.status === "completed")
1281
+ if ((input.referenceInputFile || input.interactionInputFile) &&
1282
+ existing.status === "completed")
1098
1283
  throw new FoundryContextError("execution_scope_completed", "A completed task cannot replace its reference evidence.");
1099
1284
  if (existing.status === "completed" || existing.status === "blocked")
1100
1285
  return existing;
1101
1286
  const execution = completedOwnerScopes(context, before.artifacts);
1102
1287
  if (execution.pending.length) {
1103
- if (input.authorizationInputFile || input.semanticInputFile || input.referenceInputFile)
1288
+ if (input.authorizationInputFile ||
1289
+ input.semanticInputFile ||
1290
+ input.referenceInputFile ||
1291
+ input.interactionInputFile)
1104
1292
  throw new FoundryContextError("execution_recovery_required", "Recover the consumed request before submitting changes.");
1105
1293
  if (!qualified)
1106
1294
  throw new FoundryContextError("runtime_unqualified", "Owner readback requires qualified runtime owners.");
@@ -1112,6 +1300,25 @@ export function createFoundryFacade(options) {
1112
1300
  await executeFoundryOwnerScope(selected, qualified, before.artifacts, execution.pending[0], options.authentication);
1113
1301
  return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1114
1302
  }
1303
+ if (input.interactionInputFile) {
1304
+ if (execution.consumed.size)
1305
+ throw new FoundryContextError("execution_scope_consumed", "Recover and preserve consumed scope evidence before changing task decisions.");
1306
+ const selected = selectFoundryInteractionInput(context, input.interactionInputFile);
1307
+ const facts = before.artifacts.map((entry) => ({
1308
+ path: path.join(context.taskRoot, entry.path),
1309
+ bytes: entry.bytes,
1310
+ sha256: entry.sha256,
1311
+ }));
1312
+ await recordFoundryInteractionInput(taskContext(options, current, record, facts), before.artifacts, selected, record.spec.target_entities);
1313
+ assertNotInterrupted(options.signal);
1314
+ return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1315
+ }
1316
+ const unresolvedInteraction = currentFoundryInteractionState(context, before.artifacts);
1317
+ const hasUnresolvedInteraction = Boolean(unresolvedInteraction &&
1318
+ (currentFoundryQuestions(unresolvedInteraction.state).length ||
1319
+ currentFoundryInvestigations(unresolvedInteraction.state).length));
1320
+ if (hasUnresolvedInteraction && input.authorizationInputFile)
1321
+ throw new FoundryContextError("interaction_decision_pending", "Resolve the current question or investigation before write approval.");
1115
1322
  if (input.referenceInputFile) {
1116
1323
  if (input.authorizationInputFile || input.semanticInputFile || record.spec.preparation)
1117
1324
  throw new FoundryContextError("reference_input_invalid", "Select reference evidence separately from approval, semantic input or explicit cleanup.");
@@ -1192,6 +1399,10 @@ export function createFoundryFacade(options) {
1192
1399
  }
1193
1400
  const preparation = record.spec.preparation;
1194
1401
  const workflow = currentWorkflowState(context, before.artifacts);
1402
+ if (hasUnresolvedInteraction &&
1403
+ (workflow.authorization ||
1404
+ !independentLocalPreparationPending(record, workflow, before.artifacts)))
1405
+ return existing;
1195
1406
  if (record.spec.repair && !workflow.authorization && !execution.completed.size) {
1196
1407
  if (!qualified)
1197
1408
  throw new FoundryContextError("runtime_qualification_required", "Repair preflight requires the qualified installed owners.");
@@ -1199,7 +1410,11 @@ export function createFoundryFacade(options) {
1199
1410
  return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1200
1411
  }
1201
1412
  const references = inspectFoundryReferences(context, before.artifacts);
1202
- if (!preparation && workflow.finalization && references.scope && !references.verified) {
1413
+ if (!preparation &&
1414
+ workflow.assessmentComplete &&
1415
+ workflow.finalization &&
1416
+ references.scope &&
1417
+ !references.verified) {
1203
1418
  if (!qualified)
1204
1419
  throw new FoundryContextError("runtime_unqualified", "Reference verification requires qualified runtime owners.");
1205
1420
  const selected = taskContext(options, current, record, before.artifacts.map((entry) => ({
@@ -1211,6 +1426,7 @@ export function createFoundryFacade(options) {
1211
1426
  return taskProjection("task.resume", context, record, await runtime.inspectTask(), runtimeIdentity(context, qualified));
1212
1427
  }
1213
1428
  if (!preparation &&
1429
+ (record.spec.repair || workflow.assessmentComplete) &&
1214
1430
  workflow.authorization?.value.status === "sealed" &&
1215
1431
  !execution.completed.has(String(workflow.authorization.value.dataset_type))) {
1216
1432
  if (!qualified)
@@ -1288,13 +1504,11 @@ export function createFoundryFacade(options) {
1288
1504
  await createFoundryRuntime(selected, qualified).materializeRows(facts.map((fact) => fact.path));
1289
1505
  assertNotInterrupted(options.signal);
1290
1506
  }
1291
- else if (!preparation && !workflow.assessment) {
1292
- const selectedArtifacts = before.artifacts.filter((artifact) => [
1293
- "dataset-workflow-rows",
1294
- "dataset-context-pack",
1295
- "dataset-semantic-apply",
1296
- "dataset-workflow-identity",
1297
- ].includes(artifact.command));
1507
+ else if (!preparation &&
1508
+ workflow.rows &&
1509
+ (workflow.assessmentRemainingTypes.length ||
1510
+ (!workflow.assessmentComplete && !workflow.rows.value.sets.length))) {
1511
+ const selectedArtifacts = before.artifacts;
1298
1512
  const facts = selectedArtifacts.map((artifact) => ({
1299
1513
  path: path.join(context.taskRoot, artifact.path),
1300
1514
  bytes: artifact.bytes,
@@ -1309,10 +1523,21 @@ export function createFoundryFacade(options) {
1309
1523
  .filter((fact) => path.basename(fact.path) === "contract-report.json")
1310
1524
  .map((fact) => fact.path);
1311
1525
  const selected = taskContext(options, current, record, facts);
1312
- await createFoundryRuntime(selected, qualified).assessRows(rows.path, contracts, workflow.identity?.value.status === "completed" ? workflow.identity.file : undefined);
1526
+ const identityReport = workflow.identity?.value.status === "completed" ? workflow.identity.file : undefined;
1527
+ if (workflow.assessmentRemainingTypes.length)
1528
+ await createFoundryRuntime(selected, qualified).assessRows(rows.path, contracts, identityReport, {
1529
+ scopeType: workflow.assessmentRemainingTypes[0],
1530
+ previousAssessment: workflow.assessment?.file,
1531
+ interactionSha256: currentFoundryInteractionState(context, before.artifacts)?.entry.sha256 ?? null,
1532
+ });
1533
+ else
1534
+ await createFoundryRuntime(selected, qualified).assessRows(rows.path, contracts, identityReport, {
1535
+ interactionSha256: currentFoundryInteractionState(context, before.artifacts)?.entry.sha256 ?? null,
1536
+ });
1313
1537
  assertNotInterrupted(options.signal);
1314
1538
  }
1315
1539
  else if (!preparation &&
1540
+ workflow.assessmentComplete &&
1316
1541
  (existing.status === "ready" || workflow.identity?.value.status === "blocked") &&
1317
1542
  (!workflow.identity || workflow.identity.value.status === "blocked") &&
1318
1543
  workflow.rows?.value.sets.some((set) => ["flow", "process"].includes(set.type))) {
@@ -1347,7 +1572,7 @@ export function createFoundryFacade(options) {
1347
1572
  }
1348
1573
  if (!preparation &&
1349
1574
  existing.status === "ready" &&
1350
- workflow.assessment &&
1575
+ workflow.assessmentComplete &&
1351
1576
  !workflow.finalization &&
1352
1577
  (workflow.identity?.value.status === "completed" ||
1353
1578
  !workflow.rows?.value.sets.some((set) => ["flow", "process"].includes(set.type)))) {
@@ -4,6 +4,7 @@ import { type FoundryAuthentication, type VerifiedFoundryIdentity } from "./lib/
4
4
  import { type QualifiedFoundryRuntime } from "./lib/foundry-runtime-qualification.ts";
5
5
  import { type PrepareDerivedFoundryTaskAuthorizationOptions, type TaskApprovalEvidence } from "./lib/foundry-task-authorization.ts";
6
6
  import { type CreateFoundryExecutionCapsuleOptions, type FoundryExecutionAdmission, type RehydrateFoundryExecutionAdmissionOptions } from "./lib/foundry-execution-admission.ts";
7
+ import { type FoundryAssessmentOptions } from "./lib/foundry-workflow-assessment.ts";
7
8
  import type { SelectedSemanticInput } from "./lib/foundry-semantic-input.ts";
8
9
  import type { ArtifactEntry } from "./lib/foundry-task-types.ts";
9
10
  export interface FoundryCleanupRequest {
@@ -20,7 +21,7 @@ export declare function createFoundryRuntime(context: FoundryRuntimeContext, qua
20
21
  importPackage: (input: string) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
21
22
  prepareContext: (types: readonly string[]) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
22
23
  materializeRows: (sources: readonly string[]) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
23
- assessRows: (rows: string, contracts: readonly string[], identityReport?: string) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
24
+ assessRows: (rows: string, contracts: readonly string[], identityReport?: string, options?: FoundryAssessmentOptions) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
24
25
  applySemantic: (entries: readonly ArtifactEntry[], submission: SelectedSemanticInput) => Promise<import("./lib/foundry-task-types.ts").JsonRecord>;
25
26
  initializeWorkspace: () => {
26
27
  workspace_id: string;
@@ -15,7 +15,7 @@ import { readRows } from "./lib/import-curation/internal/runtime-io.js";
15
15
  import { importFoundryWorkflowPackage } from "./lib/foundry-workflow-import.js";
16
16
  import { prepareFoundryWorkflowContext } from "./lib/foundry-workflow-context.js";
17
17
  import { materializeFoundryWorkflowRows } from "./lib/foundry-workflow-rows.js";
18
- import { assessFoundryWorkflowRows } from "./lib/foundry-workflow-assessment.js";
18
+ import { assessFoundryWorkflowRows, } from "./lib/foundry-workflow-assessment.js";
19
19
  import { applyFoundrySemanticInput } from "./lib/foundry-workflow-semantic.js";
20
20
  /** Application boundary for user workspaces. Repository maintenance stays outside it. */
21
21
  export function createFoundryRuntime(context, qualification) {
@@ -34,7 +34,7 @@ export function createFoundryRuntime(context, qualification) {
34
34
  importPackage: (input) => importFoundryWorkflowPackage(context, requireQualification(), resolveFoundryInputPath(context, input)),
35
35
  prepareContext: (types) => prepareFoundryWorkflowContext(context, requireQualification(), types),
36
36
  materializeRows: (sources) => materializeFoundryWorkflowRows(context, sources),
37
- assessRows: (rows, contracts, identityReport) => assessFoundryWorkflowRows(context, requireQualification(), rows, contracts, identityReport),
37
+ assessRows: (rows, contracts, identityReport, options) => assessFoundryWorkflowRows(context, requireQualification(), rows, contracts, identityReport, options),
38
38
  applySemantic: (entries, submission) => applyFoundrySemanticInput(context, requireQualification(), entries, submission),
39
39
  initializeWorkspace: () => initializeFoundryWorkspace(context),
40
40
  startTask: (options = {}) => {
@@ -0,0 +1,19 @@
1
+ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ import { type FoundryInteractionInput, type FoundryInteractionState } from "./foundry-interaction-types.ts";
4
+ export { FOUNDRY_INTERACTION_INPUT_SCHEMA, FOUNDRY_INTERACTION_STATE_SCHEMA, FOUNDRY_INTERACTION_COMMAND, FOUNDRY_INTERACTION_REPORT, } from "./foundry-interaction-types.ts";
5
+ export type { FoundryInteractionInput, FoundryInteractionState, } from "./foundry-interaction-types.ts";
6
+ export interface SelectedFoundryInteractionInput {
7
+ readonly spec: FoundryInteractionInput;
8
+ readonly descriptor: FoundryInputFact;
9
+ }
10
+ export declare function parseFoundryInteractionInput(value: unknown): FoundryInteractionInput;
11
+ export declare function advanceFoundryInteractionState(previous: FoundryInteractionState | null, input: FoundryInteractionInput, currentSha256: string | null, availableEvidence: ReadonlySet<string>, allowedTypes: ReadonlySet<string>): FoundryInteractionState;
12
+ export declare function readSelectedFoundryInteractionBytes(fact: FoundryInputFact): Buffer;
13
+ export declare function selectFoundryInteractionInput(context: FoundryRuntimeContext, file: string): SelectedFoundryInteractionInput;
14
+ export declare function assertSelectedFoundryInteractionInput(input: SelectedFoundryInteractionInput): void;
15
+ export declare function currentFoundryInteractionState(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): {
16
+ entry: ArtifactEntry;
17
+ state: FoundryInteractionState;
18
+ } | null;
19
+ export { applicableFoundryInteractionDigest, applicableFoundryInteractionProjection, currentFoundryAssumptions, currentFoundryAssumptionsForType, currentFoundryDecisions, currentFoundryDecisionsForType, currentFoundryInvestigations, currentFoundryQuestions, } from "./foundry-interaction-projection.ts";