@tiangong-lca/foundry 0.1.17 → 0.1.18

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 (111) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +15 -3
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +45 -13
  5. package/docs/public-runtime-contract.md +73 -5
  6. package/docs/runtime-context-contract.md +20 -4
  7. package/docs/task-authorization-contract.md +15 -3
  8. package/docs/workspace-migration-contract.md +5 -3
  9. package/package-dist/assets/foundry-package-descriptor.json +333 -139
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +258 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  13. package/package-dist/scripts/lib/bundle-sample-utils.d.ts +4 -4
  14. package/package-dist/scripts/lib/bundle-source-context.d.ts +6 -4
  15. package/package-dist/scripts/lib/bundle-source-context.js +10 -8
  16. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +16 -6
  17. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +2 -1
  18. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +28 -1
  19. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  20. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  21. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  22. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  23. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  24. package/package-dist/scripts/lib/foundry-execution-admission.js +4 -1
  25. package/package-dist/scripts/lib/foundry-finalize-owners.js +64 -17
  26. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  27. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  28. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  29. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  30. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  31. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  32. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  33. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  34. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  35. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  36. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  37. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  38. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  39. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  40. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  41. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  42. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  43. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +2 -0
  44. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +25 -3
  45. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  46. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  47. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  48. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  49. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  50. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  51. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  52. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  53. package/package-dist/scripts/lib/foundry-runtime-identity.js +3 -1
  54. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  55. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  56. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  57. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  58. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  59. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  60. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  61. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  62. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  63. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  64. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  65. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  66. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  67. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  68. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  69. package/package-dist/scripts/lib/foundry-workflow-assessment.js +115 -22
  70. package/package-dist/scripts/lib/foundry-workflow-authorization.js +17 -4
  71. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  72. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  73. package/package-dist/scripts/lib/foundry-workflow-context.js +37 -8
  74. package/package-dist/scripts/lib/foundry-workflow-finalize.js +37 -0
  75. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  76. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  77. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  78. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +676 -0
  79. package/package-dist/scripts/lib/foundry-workflow-identity.js +10 -1
  80. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  81. package/package-dist/scripts/lib/foundry-workflow-io.js +76 -11
  82. package/package-dist/scripts/lib/foundry-workflow-semantic.js +27 -13
  83. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  84. package/package-dist/scripts/lib/foundry-workflow-state.js +165 -22
  85. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  86. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  87. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +5 -0
  88. package/package-dist/scripts/lib/identity-preflight-proof.js +73 -1
  89. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  90. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  91. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  92. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  93. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +1 -0
  94. package/package-dist/scripts/lib/import-curation/curation-gate.js +19 -1
  95. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  96. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  97. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  98. package/package-dist/scripts/package-entry.js +2 -3
  99. package/package-dist/scripts/public-api.d.ts +5 -0
  100. package/package-dist/scripts/public-api.js +2 -0
  101. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  102. package/package-dist/scripts/runtime-entry.js +42 -15
  103. package/package.json +6 -2
  104. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  105. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  106. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  107. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  108. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  109. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  110. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  111. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -11,19 +11,28 @@ import { runFoundryTaskOperation, withFoundryTaskMetadata } from "./foundry-task
11
11
  import { registerWorkflowStageFiles } from "./foundry-workflow-io.js";
12
12
  import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
13
13
  import { readRows } from "./import-curation/internal/runtime-io.js";
14
+ import { recoverFoundryWorkflowIdentity } from "./foundry-workflow-identity-recovery.js";
15
+ import { assertNoPendingFoundryIdentityStage } from "./foundry-identity-stage-state.js";
14
16
  /** Run the existing read-only owner first; the local transaction only records its captured evidence. */
15
17
  export async function runFoundryWorkflowIdentity(context, qualified, entries, authentication = { mode: "oauth" }) {
16
18
  assertQualifiedFoundryRuntime(context, qualified);
19
+ assertNoPendingFoundryIdentityStage(context, entries);
17
20
  const state = currentWorkflowState(context, entries), rows = state.rows;
18
- if (!rows || !state.assessment)
21
+ if (!rows || (!state.assessment && !state.retainedAssessment))
19
22
  throw new FoundryContextError("workflow_rows_required", "Assess the current rows before identity preflight.");
20
23
  if (!context.accountIntent)
21
24
  throw new FoundryContextError("needs_auth", "Identity preflight requires a task spec with the intended project and user account.");
22
25
  await withFoundryTaskMetadata(context, (_, index) => {
26
+ assertNoPendingFoundryIdentityStage(context, index);
23
27
  if (currentWorkflowState(context, index).rows?.entry.sha256 !== rows.entry.sha256)
24
28
  throw new FoundryContextError("workflow_identity_rows_changed", "Current rows changed before identity preflight.");
25
29
  });
26
30
  const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
31
+ const recovered = await recoverFoundryWorkflowIdentity(context, qualified, entries, identity.receipt);
32
+ if (recovered)
33
+ return recovered;
34
+ if (!state.assessment)
35
+ throw new FoundryContextError("workflow_rows_required", "Current runtime assessment is required before a new identity query.");
27
36
  const nonce = randomUUID();
28
37
  const output = resolveFoundryOutput(context, `outputs/identity/${nonce}`);
29
38
  const temporary = resolveFoundryOutput(context, `tmp/identity-${nonce}`);
@@ -1,11 +1,17 @@
1
1
  import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
2
  import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ import { WorkflowChildFailure } from "./foundry-workflow-child-failure.ts";
3
4
  import type { FoundryTaskOperation } from "./foundry-task-types.ts";
4
5
  export declare function createWorkflowDirectory(context: FoundryRuntimeContext, prefix: string): string;
5
6
  export declare function createWorkflowStageDirectory(context: FoundryRuntimeContext, operation: FoundryTaskOperation, stage: string): string;
6
- export declare function registerWorkflowStageFiles(context: FoundryRuntimeContext, operation: FoundryTaskOperation, directory: string): string[];
7
+ export declare function registerWorkflowStageFiles(context: FoundryRuntimeContext, operation: FoundryTaskOperation, directory: string | readonly string[]): string[];
8
+ /** Existing owner-selected report paths must belong to this actual call's output generation. */
9
+ export declare function assertWorkflowReportArtifact(context: FoundryRuntimeContext, file: string, selectedDir: string): string;
7
10
  export declare function runWorkflowLocalCli(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, temporary: string, argv: readonly string[]): Record<string, unknown>;
8
11
  export declare function runWorkflowLocalCliResult(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, temporary: string, argv: readonly string[]): {
9
12
  exit: number;
10
13
  report: Record<string, unknown>;
14
+ failure: (rejection?: unknown) => WorkflowChildFailure;
15
+ validate: <T>(check: () => T) => T;
16
+ verifyReportFile: (file: string) => void;
11
17
  };
@@ -6,6 +6,7 @@ import { FoundryContextError, assertFoundryWorkspaceWrite, resolveFoundryOutput,
6
6
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
7
7
  import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
8
8
  import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
9
+ import { bindWorkflowChildExecution, workflowChildFailure, WorkflowChildFailure, } from "./foundry-workflow-child-failure.js";
9
10
  export function createWorkflowDirectory(context, prefix) {
10
11
  assertFoundryWorkspaceWrite(context);
11
12
  const directory = resolveFoundryOutput(context, `${prefix}${randomUUID()}`);
@@ -31,18 +32,35 @@ export function registerWorkflowStageFiles(context, operation, directory) {
31
32
  else {
32
33
  if (files.length >= 9_998)
33
34
  throw new FoundryContextError("workflow_output_limit", "Stage exceeds the task artifact limit.");
34
- operation.writeText(file, fs.readFileSync(file));
35
35
  files.push(file);
36
36
  }
37
37
  }
38
38
  };
39
- visit(directory);
39
+ // Snapshot only the selected roots; one result retains one complete capture roster.
40
+ for (const root of typeof directory === "string" ? [directory] : [...directory])
41
+ visit(root);
42
+ operation.registerExistingFiles(files);
40
43
  return files;
41
44
  }
45
+ /** Existing owner-selected report paths must belong to this actual call's output generation. */
46
+ export function assertWorkflowReportArtifact(context, file, selectedDir) {
47
+ const output = resolveFoundryOutput(context, selectedDir);
48
+ const current = resolveFoundryOutput(context, file);
49
+ const relative = path.relative(output, current);
50
+ if (!relative ||
51
+ relative.startsWith(`..${path.sep}`) ||
52
+ relative === ".." ||
53
+ path.isAbsolute(relative))
54
+ throw new FoundryContextError("workflow_report_invalid", "The child report locator is outside this call's output directory.");
55
+ const stat = fs.lstatSync(current);
56
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8 * 1024 * 1024)
57
+ throw new FoundryContextError("workflow_report_invalid", "The child report must be a bounded regular output artifact.");
58
+ return current;
59
+ }
42
60
  export function runWorkflowLocalCli(context, qualified, temporary, argv) {
43
61
  const result = runWorkflowLocalCliResult(context, qualified, temporary, argv);
44
62
  if (![0, 2].includes(result.exit) || "error" in result.report)
45
- throw new FoundryContextError("workflow_cli_failed", "Local CLI returned an invalid stage report.");
63
+ throw result.failure();
46
64
  return result.report;
47
65
  }
48
66
  export function runWorkflowLocalCliResult(context, qualified, temporary, argv) {
@@ -57,6 +75,7 @@ export function runWorkflowLocalCliResult(context, qualified, temporary, argv) {
57
75
  throw new FoundryContextError("workflow_command_invalid", "This stage admits local validation, QA, queue preparation and patch application only.");
58
76
  assertQualifiedFoundryRuntime(context, qualified);
59
77
  const cli = resolveInstalledTiangongLcaCliPackage();
78
+ const execution = bindWorkflowChildExecution(context, qualified, cli.binPath, argv);
60
79
  const child = spawnSync(process.execPath, [cli.binPath, ...argv], {
61
80
  cwd: context.workspaceRoot,
62
81
  env: createFoundryIsolatedChildEnvironment({ tempRoot: temporary }),
@@ -65,14 +84,60 @@ export function runWorkflowLocalCliResult(context, qualified, temporary, argv) {
65
84
  timeout: 120_000,
66
85
  maxBuffer: 8 * 1024 * 1024,
67
86
  });
68
- if (child.error ||
69
- child.signal ||
70
- ![0, 1, 2].includes(child.status ?? -1) ||
71
- !child.stdout.trim())
72
- throw new FoundryContextError("workflow_cli_failed", `Local CLI ${argv.slice(0, 2).join(" ")} did not return a stage report.`);
73
- const report = JSON.parse(child.stdout);
87
+ const kind = child.error
88
+ ? "spawn_error"
89
+ : child.signal
90
+ ? "signal"
91
+ : ![0, 1, 2].includes(child.status ?? -1)
92
+ ? "exit_code"
93
+ : !child.stdout.trim()
94
+ ? "empty_stdout"
95
+ : null;
96
+ if (kind)
97
+ throw workflowChildFailure(execution, child, kind);
98
+ let report;
99
+ try {
100
+ report = JSON.parse(child.stdout);
101
+ }
102
+ catch {
103
+ throw workflowChildFailure(execution, child, "malformed_json");
104
+ }
74
105
  if (!report || typeof report !== "object" || Array.isArray(report))
75
- throw new FoundryContextError("workflow_cli_failed", "Local CLI returned an invalid stage report.");
106
+ throw workflowChildFailure(execution, child, "invalid_report");
107
+ if ("error" in report ||
108
+ !("status" in report) ||
109
+ typeof report.status !== "string" ||
110
+ !report.status.trim())
111
+ throw workflowChildFailure(execution, child, "stage_rejected", new FoundryContextError("workflow_report_invalid", "Local CLI returned an error or no stage status."));
76
112
  assertQualifiedFoundryRuntime(context, qualified);
77
- return { exit: child.status, report: report };
113
+ const failure = (rejection) => workflowChildFailure(execution, child, "stage_rejected", rejection);
114
+ return {
115
+ exit: child.status,
116
+ report,
117
+ failure,
118
+ verifyReportFile(file) {
119
+ try {
120
+ const selectedDir = argv[argv.indexOf("--out-dir") + 1];
121
+ if (!argv.includes("--out-dir") || typeof selectedDir !== "string")
122
+ throw new FoundryContextError("workflow_report_invalid", "The child report has no bound output directory.");
123
+ const current = assertWorkflowReportArtifact(context, file, selectedDir);
124
+ const recorded = JSON.parse(fs.readFileSync(current, "utf8"));
125
+ if (JSON.stringify(recorded) !== JSON.stringify(report))
126
+ throw new FoundryContextError("workflow_report_invalid", "The child report file differs from its original returned report.");
127
+ }
128
+ catch (error) {
129
+ throw failure(error);
130
+ }
131
+ },
132
+ validate(check) {
133
+ try {
134
+ return check();
135
+ }
136
+ catch (error) {
137
+ if (error instanceof WorkflowChildFailure)
138
+ throw error;
139
+ throw failure(error);
140
+ }
141
+ },
142
+ };
78
143
  }
@@ -1,7 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { registeredAssessmentSetProducerBase } from "./foundry-assessment-producer.js";
3
4
  import { createHash } from "node:crypto";
4
- import { FoundryContextError, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
+ import { FoundryContextError, captureFoundryInput, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
6
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
6
7
  import { assertSelectedSemanticInput, readSelectedSemanticBytes, } from "./foundry-semantic-input.js";
7
8
  import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
@@ -142,6 +143,7 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
142
143
  const decisionWork = [];
143
144
  const work = [];
144
145
  for (const set of assessment.value.sets) {
146
+ const ownerBase = registeredAssessmentSetProducerBase(context, entries, set);
145
147
  const manifestFile = text(set.authoring_manifest, "Authoring manifest");
146
148
  const manifest = workflowObject(JSON.parse(readFoundryInput(context, manifestFile).toString("utf8")));
147
149
  if (!Array.isArray(manifest.tasks))
@@ -149,7 +151,7 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
149
151
  const tasks = [];
150
152
  for (const raw of manifest.tasks) {
151
153
  const task = workflowObject(raw), files = workflowObject(task.files);
152
- const taskFile = path.resolve(assessment.value.owner_base, text(files.task_json, "Authoring task"));
154
+ const taskFile = path.resolve(ownerBase, text(files.task_json, "Authoring task"));
153
155
  const entry = entries.find((candidate) => resolveFoundryOutput(context, candidate.path) === taskFile);
154
156
  if (!entry)
155
157
  fail("semantic_work_unregistered", "Authoring work is not registered in this task.");
@@ -165,7 +167,7 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
165
167
  tasks.push({ task, sha: entry.sha256, fact: chosen.fact });
166
168
  }
167
169
  if (tasks.length)
168
- work.push({ set, manifest, manifestFile, tasks });
170
+ work.push({ set, manifest, manifestFile, ownerBase, tasks });
169
171
  for (const raw of Array.isArray(set.decisions) ? set.decisions : []) {
170
172
  const decision = workflowObject(raw);
171
173
  if (decision.kind !== "classification" &&
@@ -325,7 +327,7 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
325
327
  if (blockers.length !== previousBlockers)
326
328
  continue;
327
329
  const collection = runDatasetAuthoringPatchCollect({
328
- repoRoot: assessment.value.owner_base,
330
+ repoRoot: group.ownerBase,
329
331
  options: {
330
332
  taskManifest: projectedFile,
331
333
  outDir: path.join(output, type, "collect"),
@@ -339,7 +341,7 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
339
341
  continue;
340
342
  }
341
343
  const originalRows = text(group.set.rows, "Assessed rows");
342
- const packageDirectories = new Set(group.tasks.map(({ task }) => path.dirname(path.resolve(assessment.value.owner_base, text(workflowObject(task.files).authoring_package, "Authoring package")))));
344
+ const packageDirectories = new Set(group.tasks.map(({ task }) => path.dirname(path.resolve(group.ownerBase, text(workflowObject(task.files).authoring_package, "Authoring package")))));
343
345
  if (packageDirectories.size !== 1)
344
346
  fail("semantic_work_invalid", "Selected work must share its registered package snapshot directory.");
345
347
  const repaired = path.join(output, type, "repaired.rows.jsonl");
@@ -361,17 +363,29 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
361
363
  "--require-action-item-closure",
362
364
  "--json",
363
365
  ]);
364
- if (applied.exit !== 0 ||
365
- applied.report.status !== "completed" ||
366
- !Array.isArray(applied.report.blockers) ||
367
- applied.report.blockers.length) {
366
+ const original = rows.value.sets.find((set) => set.type === type && set.file === originalRows);
367
+ const completed = applied.validate(() => {
368
+ if (!["completed", "blocked"].includes(String(applied.report.status)) ||
369
+ !Array.isArray(applied.report.blockers))
370
+ fail("semantic_apply_invalid", "Patch application returned no completed or blocked owner report.");
371
+ const reportFile = workflowObject(applied.report.files).report;
372
+ if (typeof reportFile !== "string")
373
+ fail("semantic_apply_invalid", "Patch application returned no report locator.");
374
+ applied.verifyReportFile(reportFile);
375
+ if (applied.exit !== 0 ||
376
+ applied.report.status !== "completed" ||
377
+ applied.report.blockers.length)
378
+ return null;
379
+ if (!original || Number(applied.report.row_count) !== original.count)
380
+ fail("semantic_row_scope_changed", "Patch application changed the assessed row scope.");
381
+ captureFoundryInput(repaired);
382
+ return original;
383
+ });
384
+ if (!completed) {
368
385
  blockers.push({ code: "semantic_apply_blocked", type, report: applied.report });
369
386
  continue;
370
387
  }
371
- const original = rows.value.sets.find((set) => set.type === type && set.file === originalRows);
372
- if (!original || Number(applied.report.row_count) !== original.count)
373
- fail("semantic_row_scope_changed", "Patch application changed the assessed row scope.");
374
- updated.set(type, { ...original, file: repaired });
388
+ updated.set(type, { ...completed, file: repaired });
375
389
  results.push({
376
390
  type,
377
391
  original_rows: originalRows,
@@ -34,7 +34,9 @@ export declare function workflowObject(value: unknown): Record<string, unknown>;
34
34
  export declare function readWorkflowArtifact(context: FoundryRuntimeContext, entry: ArtifactEntry): WorkflowArtifact<Record<string, unknown>>;
35
35
  export declare function currentWorkflowState(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): {
36
36
  rows: WorkflowArtifact<WorkflowRows> | null;
37
+ currentContextReports: string[];
37
38
  assessment: WorkflowArtifact<WorkflowAssessment> | null;
39
+ retainedAssessment: WorkflowArtifact<WorkflowAssessment> | null;
38
40
  assessmentComplete: boolean;
39
41
  assessmentRemainingTypes: string[];
40
42
  interactionSha256: string | null;
@@ -44,4 +46,6 @@ export declare function currentWorkflowState(context: FoundryRuntimeContext, ent
44
46
  preparedApproval: WorkflowArtifact<Record<string, unknown>> | null;
45
47
  referenceInputs: Map<string, WorkflowArtifact<Record<string, unknown>>>;
46
48
  referenceInputsSha256: string | null;
49
+ qualityReview: WorkflowArtifact<Record<string, unknown>> | null;
50
+ qualityReviewSha256: string | null;
47
51
  };
@@ -5,6 +5,12 @@ import { captureFoundryInput, FoundryContextError, resolveFoundryOutput, } from
5
5
  import { readTaskBytes } from "./foundry-task-io.js";
6
6
  import { sha256Json } from "./identity-preflight-proof.js";
7
7
  import { applicableFoundryInteractionDigest } from "./foundry-interaction-projection.js";
8
+ import { qualityReviewInteractionDigest } from "./foundry-quality-review-context.js";
9
+ import { readRows } from "./import-curation/internal/runtime-io.js";
10
+ import { projectFoundryValidationReferences } from "./foundry-validation-reference-context.js";
11
+ import { parseFoundryPreparationCliReport } from "./foundry-preparation-cli-validation.js";
12
+ import { readFoundryTaskRuntimeAdoption, readFoundryTaskRuntimeAdoptionChain, } from "./foundry-task-runtime-adoption.js";
13
+ import { verifyRegisteredAssessmentProducer } from "./foundry-assessment-producer.js";
8
14
  /**
9
15
  * The repair producer's registration of the preparation report. These two values are repeated here
10
16
  * rather than imported so this projection module stays a graph leaf; the public repair suite fails
@@ -58,6 +64,30 @@ export function readWorkflowArtifact(context, entry) {
58
64
  }
59
65
  }
60
66
  export function currentWorkflowState(context, entries) {
67
+ let adoption;
68
+ const runtimeAdoption = () => {
69
+ if (adoption === undefined)
70
+ adoption = readFoundryTaskRuntimeAdoption(context);
71
+ return adoption;
72
+ };
73
+ let retainedRuntimeRoots;
74
+ const assessmentOwner = (value, entry, report) => {
75
+ if (value === context.assetRoot)
76
+ return "current";
77
+ if (retainedRuntimeRoots === undefined) {
78
+ runtimeAdoption();
79
+ retainedRuntimeRoots =
80
+ readFoundryTaskRuntimeAdoptionChain(context)?.retained_runtime_roots ?? [];
81
+ }
82
+ if (typeof value === "string" && retainedRuntimeRoots.includes(value)) {
83
+ verifyRegisteredAssessmentProducer(context, entry, report, entries);
84
+ return "adopted_original";
85
+ }
86
+ if (!runtimeAdoption() &&
87
+ verifyRegisteredAssessmentProducer(context, entry, report, entries) === value)
88
+ return "current";
89
+ throw new FoundryContextError("workflow_assessment_invalid", "Assessment owner is neither the current runtime nor its verified adopted predecessor.");
90
+ };
61
91
  const rowEntry = entries.findLast((entry) => ["dataset-workflow-rows", "dataset-semantic-apply"].includes(entry.command) &&
62
92
  path.basename(entry.path) === "foundry-rows.json");
63
93
  let rows = null;
@@ -123,16 +153,78 @@ export function currentWorkflowState(context, entries) {
123
153
  throw new FoundryContextError("workflow_interaction_invalid", "Registered task decisions are invalid.");
124
154
  const interaction = interactionValue;
125
155
  const contextShaByType = new Map();
156
+ const contextFilesByType = new Map();
157
+ const originalContextFacts = new Map((readFoundryTaskRuntimeAdoptionChain(context)?.prior_context_reports ?? []).map((item) => {
158
+ const fact = workflowObject(item);
159
+ return [fact.path, fact];
160
+ }));
126
161
  for (const entry of entries) {
127
162
  if (entry.command !== "dataset-context-pack" ||
128
163
  path.basename(entry.path) !== "contract-report.json")
129
164
  continue;
130
165
  const report = readWorkflowArtifact(context, entry).value;
131
- if (report.status === "completed" && typeof report.type === "string")
166
+ const original = originalContextFacts.get(entry.path);
167
+ if (original && original.sha256 === entry.sha256 && original.bytes === entry.bytes)
168
+ continue;
169
+ if (report.status === "completed" && typeof report.type === "string") {
132
170
  contextShaByType.set(report.type, entry.sha256);
171
+ contextFilesByType.set(report.type, resolveFoundryOutput(context, entry.path));
172
+ }
173
+ }
174
+ const referenceInputs = new Map();
175
+ for (const entry of entries) {
176
+ if (entry.command !== "dataset-workflow-reference-input" ||
177
+ path.basename(entry.path) !== "foundry-reference-input.json")
178
+ continue;
179
+ const found = readWorkflowArtifact(context, entry);
180
+ if (found.value.schema !== "tiangong-foundry.reference-selection.v1" ||
181
+ found.value.status !== "selected" ||
182
+ typeof found.value.dataset_type !== "string")
183
+ throw new FoundryContextError("reference_input_invalid", "Registered reference selection is invalid.");
184
+ referenceInputs.set(found.value.dataset_type, found);
185
+ }
186
+ const referenceInputsSha256 = referenceInputs.size
187
+ ? createHash("sha256")
188
+ .update(JSON.stringify([...referenceInputs]
189
+ .sort(([a], [b]) => a.localeCompare(b))
190
+ .map(([type, found]) => [type, found.entry.sha256])))
191
+ .digest("hex")
192
+ : null;
193
+ const qualityEntry = entries.findLast((entry) => entry.command === "dataset-workflow-quality-review" &&
194
+ path.basename(entry.path) === "foundry-quality-review.json");
195
+ const qualityReview = qualityEntry ? readWorkflowArtifact(context, qualityEntry) : null;
196
+ let qualityReviewSha256 = null;
197
+ if (qualityReview) {
198
+ const value = qualityReview.value;
199
+ if (value.schema !== "tiangong-foundry.quality-review-receipt.v1" ||
200
+ value.status !== "accepted" ||
201
+ value.grants_permission !== false)
202
+ throw new FoundryContextError("quality_review_invalid", "Registered quality review is invalid.");
203
+ const input = workflowObject(value.input), bound = workflowObject(input.binding);
204
+ const processRows = rows?.value.sets.find((set) => set.type === "process");
205
+ const now = Date.now();
206
+ if (input.rows_manifest_sha256 === rows?.entry.sha256 &&
207
+ input.context_sha256 === contextShaByType.get("process") &&
208
+ input.reference_inputs_sha256 === referenceInputsSha256 &&
209
+ sha256Json(value.runtime) === sha256Json(context.runtime) &&
210
+ bound.workspace_id === context.workspaceId &&
211
+ bound.task_id === context.taskId &&
212
+ bound.actor_id === context.actorId &&
213
+ bound.project_ref === context.accountIntent?.projectRef &&
214
+ bound.user_id === context.accountIntent?.userId &&
215
+ processRows &&
216
+ input.interaction_context_sha256 ===
217
+ qualityReviewInteractionDigest(interaction, readRows(processRows.file)) &&
218
+ bound.input_scope_sha256 === captureFoundryInput(processRows.file).sha256 &&
219
+ typeof input.issued_at_utc === "string" &&
220
+ Date.parse(input.issued_at_utc) <= now &&
221
+ typeof input.expires_at_utc === "string" &&
222
+ Date.parse(input.expires_at_utc) > now)
223
+ qualityReviewSha256 = qualityReview.entry.sha256;
133
224
  }
134
225
  const queueScopeSha256 = rows ? workflowAssessmentQueueScopeSha256(rows.value.sets) : null;
135
226
  let assessment = null;
227
+ let retainedAssessment = null;
136
228
  if (rows) {
137
229
  for (const entry of [...entries].reverse()) {
138
230
  if (entry.command !== "dataset-workflow-assessment" ||
@@ -140,10 +232,11 @@ export function currentWorkflowState(context, entries) {
140
232
  continue;
141
233
  const found = readWorkflowArtifact(context, entry), value = found.value;
142
234
  if (value.schema !== "tiangong-foundry.assessment-stage.v1" ||
143
- value.owner_base !== context.assetRoot ||
235
+ typeof value.owner_base !== "string" ||
144
236
  !["in_progress", "completed"].includes(String(value.status)) ||
145
237
  !Array.isArray(value.sets))
146
238
  throw new FoundryContextError("workflow_assessment_invalid", "Registered assessment metadata is invalid.");
239
+ const owner = assessmentOwner(value.owner_base, entry, value);
147
240
  const sets = value.sets.map(workflowObject);
148
241
  const reportRowsEntry = entries.find((candidate) => ["dataset-workflow-rows", "dataset-semantic-apply"].includes(candidate.command) &&
149
242
  path.basename(candidate.path) === "foundry-rows.json" &&
@@ -198,6 +291,14 @@ export function currentWorkflowState(context, entries) {
198
291
  else if (value.status === "in_progress") {
199
292
  throw new FoundryContextError("workflow_assessment_invalid", "Partial assessment must identify its predecessor boundary.");
200
293
  }
294
+ // Keep verified predecessor reports as immutable history, but qualify machine
295
+ // assessment afresh with the explicitly adopted runtime and CLI combination.
296
+ if (owner === "adopted_original") {
297
+ if (!retainedAssessment &&
298
+ sets.every((set) => rows.value.sets.some((row) => row.type === set.type && row.file === set.rows)))
299
+ retainedAssessment = { ...found, value: value };
300
+ continue;
301
+ }
201
302
  const identityMatches = (value.identity_report ?? null) ===
202
303
  (identity?.value.status === "completed" ? identity.file : null);
203
304
  const currentSets = identityMatches
@@ -205,9 +306,21 @@ export function currentWorkflowState(context, entries) {
205
306
  const row = rows.value.sets.find((candidate) => candidate.type === set.type);
206
307
  if (!row || row.file !== set.rows)
207
308
  return false;
309
+ if (row.type === "process" &&
310
+ (set.quality_review_sha256 ?? null) !== qualityReviewSha256)
311
+ return false;
208
312
  if ((set.interaction_digest ?? null) !==
209
313
  applicableFoundryInteractionDigest(interaction, row.type))
210
314
  return false;
315
+ if (["flow", "process"].includes(row.type) &&
316
+ rows.value.sets.some((set) => set.type === "process")) {
317
+ const selected = referenceInputs.get("process");
318
+ const expected = Array.isArray(selected?.value.qa_files) && selected.value.qa_files.length
319
+ ? selected.entry.sha256
320
+ : null;
321
+ if ((set.reference_input_sha256 ?? null) !== expected)
322
+ return false;
323
+ }
211
324
  const expectedContext = contextShaByType.get(row.type);
212
325
  if ((set.context_report_sha256 !== undefined &&
213
326
  set.context_report_sha256 !== expectedContext) ||
@@ -236,6 +349,50 @@ export function currentWorkflowState(context, entries) {
236
349
  const validationFile = resolveFoundryOutput(context, set.cli_validation_report);
237
350
  if (captureFoundryInput(validationFile).sha256 !== set.cli_validation_report_sha256)
238
351
  throw new FoundryContextError("workflow_assessment_invalid", "CLI validation evidence has changed.");
352
+ let validationInput = set.rows;
353
+ let validationRows = readRows(validationInput);
354
+ const selected = referenceInputs.get("process");
355
+ const qa = Array.isArray(selected?.value.qa_files) ? selected.value.qa_files : [];
356
+ if (qa.length) {
357
+ const source = workflowObject(set.cli_validation_source_rows);
358
+ const derived = workflowObject(set.cli_validation_input);
359
+ const original = captureFoundryInput(validationInput);
360
+ if (sha256Json(source) !== sha256Json(original) ||
361
+ set.cli_validation_reference_input_sha256 !== selected.entry.sha256 ||
362
+ sha256Json(set.cli_validation_reference_files) !== sha256Json(qa) ||
363
+ typeof derived.path !== "string" ||
364
+ !registeredAssessmentFile(context, entries, derived.path))
365
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation projection lineage differs from current rows or selected references.");
366
+ const references = qa.flatMap((raw) => {
367
+ const fact = workflowObject(raw);
368
+ if (typeof fact.path !== "string" ||
369
+ !registeredAssessmentFile(context, entries, fact.path) ||
370
+ sha256Json(captureFoundryInput(fact.path)) !== sha256Json(fact))
371
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation reference snapshot changed.");
372
+ return readRows(fact.path);
373
+ });
374
+ validationRows = projectFoundryValidationReferences(validationRows, references);
375
+ validationInput = derived.path;
376
+ const expected = Buffer.from(`${JSON.stringify(validationRows, null, 2)}\n`);
377
+ const actual = captureFoundryInput(validationInput);
378
+ if (sha256Json(actual) !== sha256Json(derived) ||
379
+ !fs.readFileSync(validationInput).equals(expected))
380
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation-only rows differ from the registered deterministic projection.");
381
+ files.push(validationInput);
382
+ }
383
+ else if (set.cli_validation_input !== undefined ||
384
+ set.cli_validation_source_rows !== undefined ||
385
+ set.cli_validation_reference_input_sha256 !== undefined ||
386
+ set.cli_validation_reference_files !== undefined) {
387
+ throw new FoundryContextError("workflow_assessment_invalid", "Validation projection requires current selected Flow evidence.");
388
+ }
389
+ parseFoundryPreparationCliReport({
390
+ report: JSON.parse(fs.readFileSync(validationFile, "utf8")),
391
+ input: validationInput,
392
+ outDir: path.dirname(path.dirname(validationFile)),
393
+ rows: validationRows,
394
+ exit: set.cli_validation_exit,
395
+ });
239
396
  files.push(set.cli_validation_report);
240
397
  }
241
398
  if (set.interaction_context !== undefined)
@@ -277,25 +434,6 @@ export function currentWorkflowState(context, entries) {
277
434
  const assessmentRemainingTypes = rows
278
435
  ? rows.value.sets.filter((set) => !coveredTypes.has(set.type)).map((set) => set.type)
279
436
  : [];
280
- const referenceInputs = new Map();
281
- for (const entry of entries) {
282
- if (entry.command !== "dataset-workflow-reference-input" ||
283
- path.basename(entry.path) !== "foundry-reference-input.json")
284
- continue;
285
- const found = readWorkflowArtifact(context, entry);
286
- if (found.value.schema !== "tiangong-foundry.reference-selection.v1" ||
287
- found.value.status !== "selected" ||
288
- typeof found.value.dataset_type !== "string")
289
- throw new FoundryContextError("reference_input_invalid", "Registered reference selection is invalid.");
290
- referenceInputs.set(found.value.dataset_type, found);
291
- }
292
- const referenceInputsSha256 = referenceInputs.size
293
- ? createHash("sha256")
294
- .update(JSON.stringify([...referenceInputs]
295
- .sort(([a], [b]) => a.localeCompare(b))
296
- .map(([type, found]) => [type, found.entry.sha256])))
297
- .digest("hex")
298
- : null;
299
437
  let finalization = null;
300
438
  if (rows && assessmentComplete && assessment) {
301
439
  for (const entry of [...entries].reverse()) {
@@ -309,7 +447,8 @@ export function currentWorkflowState(context, entries) {
309
447
  throw new FoundryContextError("workflow_finalize_invalid", "Registered finalization metadata is invalid.");
310
448
  if (found.value.rows_report === rows.file &&
311
449
  found.value.assessment_report === assessment.file &&
312
- (found.value.reference_inputs_sha256 ?? null) === referenceInputsSha256) {
450
+ (found.value.reference_inputs_sha256 ?? null) === referenceInputsSha256 &&
451
+ (found.value.quality_review_sha256 ?? null) === qualityReviewSha256) {
313
452
  finalization = found;
314
453
  break;
315
454
  }
@@ -383,7 +522,9 @@ export function currentWorkflowState(context, entries) {
383
522
  }
384
523
  return {
385
524
  rows,
525
+ currentContextReports: [...contextFilesByType.values()],
386
526
  assessment,
527
+ retainedAssessment,
387
528
  assessmentComplete,
388
529
  assessmentRemainingTypes,
389
530
  interactionSha256,
@@ -393,5 +534,7 @@ export function currentWorkflowState(context, entries) {
393
534
  preparedApproval,
394
535
  referenceInputs,
395
536
  referenceInputsSha256,
537
+ qualityReview,
538
+ qualityReviewSha256,
396
539
  };
397
540
  }
@@ -1,8 +1,5 @@
1
1
  import type { FoundryCommandSpec } from "./foundry-command-spec.ts";
2
2
  type UnknownRecord = Record<string, unknown>;
3
- interface TextNode extends UnknownRecord {
4
- "#text"?: unknown;
5
- }
6
3
  interface NamedReference extends UnknownRecord {
7
4
  "common:shortDescription"?: unknown;
8
5
  shortDescription?: unknown;
@@ -26,10 +23,10 @@ interface ProcessDataSetRecord extends UnknownRecord {
26
23
  processInformation?: {
27
24
  dataSetInformation?: UnknownRecord & {
28
25
  name?: {
29
- baseName?: TextNode;
30
- treatmentStandardsRoutes?: TextNode;
31
- mixAndLocationTypes?: TextNode;
32
- functionalUnitFlowProperties?: TextNode;
26
+ baseName?: unknown;
27
+ treatmentStandardsRoutes?: unknown;
28
+ mixAndLocationTypes?: unknown;
29
+ functionalUnitFlowProperties?: unknown;
33
30
  };
34
31
  };
35
32
  quantitativeReference?: {
@@ -1,6 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { namePartText } from "./bundle-source-context.js";
3
4
  import { createFileArtifactFact, createFoundryCommandSpec } from "./foundry-command-spec.js";
5
+ import { FoundryContextError } from "./foundry-runtime-error.js";
4
6
  function isUnknownRecord(value) {
5
7
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
6
8
  }
@@ -122,10 +124,10 @@ export function createIdentityPreflightArtifactUtils({ asText, bundleClassificat
122
124
  function processNameParts(payload) {
123
125
  const name = payload?.processDataSet?.processInformation?.dataSetInformation?.name ?? {};
124
126
  return {
125
- base_name: asText(name.baseName?.["#text"] ?? name.baseName),
126
- treatment_standards_routes: asText(name.treatmentStandardsRoutes?.["#text"] ?? name.treatmentStandardsRoutes),
127
- mix_and_location_types: asText(name.mixAndLocationTypes?.["#text"] ?? name.mixAndLocationTypes),
128
- functional_unit_flow_properties: asText(name.functionalUnitFlowProperties?.["#text"] ?? name.functionalUnitFlowProperties),
127
+ base_name: namePartText(name.baseName, asText),
128
+ treatment_standards_routes: namePartText(name.treatmentStandardsRoutes, asText),
129
+ mix_and_location_types: namePartText(name.mixAndLocationTypes, asText),
130
+ functional_unit_flow_properties: namePartText(name.functionalUnitFlowProperties, asText),
129
131
  };
130
132
  }
131
133
  function valuesByKeys(payload, keys, limit = 6) {
@@ -409,7 +411,18 @@ export function createIdentityPreflightArtifactUtils({ asText, bundleClassificat
409
411
  function readSourceTracesFromFile(sourceFile) {
410
412
  if (!sourceFile || !fileExists(sourceFile))
411
413
  return [];
412
- return collectSourceTracePayloads(readJson(sourceFile));
414
+ let source;
415
+ try {
416
+ source = sourceFile.toLowerCase().endsWith(".jsonl")
417
+ ? readJsonLines(sourceFile)
418
+ : readJson(sourceFile);
419
+ }
420
+ catch (error) {
421
+ if (isUnknownRecord(error) && typeof error.code === "string")
422
+ throw error;
423
+ throw new FoundryContextError("source_trace_invalid", "The selected identity source trace is not valid JSON or JSONL. Check the original source evidence before continuing.");
424
+ }
425
+ return collectSourceTracePayloads(source);
413
426
  }
414
427
  function buildIdentityPreflightArtifacts({ rowsByType, sourceByType, outDir, cliBin, }) {
415
428
  const cliPrefix = Array.isArray(cliBin) ? cliBin : [cliBin];
@@ -95,6 +95,11 @@ export declare function validateIdentityPreflightExecution(input: {
95
95
  startedAtMs: number;
96
96
  diskReportMtimeMs: number | null;
97
97
  completedAtUtc: string;
98
+ requestFile?: string;
99
+ outputDir?: string;
100
+ reportFile?: string;
101
+ stderrText?: string;
102
+ signal?: string | null;
98
103
  }): ValidationFailure | ValidationSuccess;
99
104
  export declare function validateBoundExecutionManifest(value: unknown, binding: IdentityPreflightBinding, reportText: string | null): {
100
105
  ok: boolean;