@tiangong-lca/foundry 0.1.16 → 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 (114) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +19 -5
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +47 -15
  5. package/docs/public-runtime-contract.md +77 -5
  6. package/docs/runtime-context-contract.md +21 -5
  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 +351 -137
  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 +22 -0
  44. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +213 -0
  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 +149 -18
  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 +79 -13
  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 +175 -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 +6 -1
  94. package/package-dist/scripts/lib/import-curation/curation-gate.js +48 -2
  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/lib/tidas-adapter.js +38 -15
  99. package/package-dist/scripts/lib/tidas-process-flow-context.d.ts +12 -0
  100. package/package-dist/scripts/lib/tidas-process-flow-context.js +96 -0
  101. package/package-dist/scripts/package-entry.js +2 -3
  102. package/package-dist/scripts/public-api.d.ts +5 -0
  103. package/package-dist/scripts/public-api.js +2 -0
  104. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  105. package/package-dist/scripts/runtime-entry.js +42 -15
  106. package/package.json +6 -2
  107. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  108. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  109. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  110. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  111. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  112. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  113. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  114. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -20,6 +20,7 @@ import { foundryRepairSelection, readFoundryRepairPreparation } from "./foundry-
20
20
  import { createFoundryRepairHandoffPlan } from "./foundry-repair-handoff.js";
21
21
  import { readTaskJson } from "./foundry-task-io.js";
22
22
  import { assertFoundryInteractionWriteReady } from "./foundry-workflow-object-scope.js";
23
+ import { assertFoundryQualityReviewForExecution } from "./foundry-quality-review.js";
23
24
  export async function authorizeFoundryWorkflow(context, qualified, entries, selected, authentication = { mode: "oauth" }) {
24
25
  assertSelectedAuthorizationInput(selected);
25
26
  assertQualifiedFoundryRuntime(context, qualified);
@@ -41,9 +42,15 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
41
42
  if (typeof inputFile !== "string" || captureFoundryInput(inputFile).sha256 !== spec.input_sha256)
42
43
  throw new FoundryContextError("authorization_input_mismatch", "Approval input must match the exact current scope bytes.");
43
44
  readFoundryInput(context, inputFile);
45
+ if (spec.input_kind === "final_rows")
46
+ assertFoundryQualityReviewForExecution(context, qualified, entries, inputFile);
44
47
  if (spec.input_kind === "final_rows" && scope.status !== "ready_for_remote_write")
45
48
  throw new FoundryContextError("authorization_scope_not_ready", "Final-row approval requires a ready owner scope.");
46
- const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
49
+ let identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
50
+ const refreshIdentity = () => {
51
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
52
+ return identity;
53
+ };
47
54
  if (selected.executionContract) {
48
55
  try {
49
56
  readNativeDraftHandoff({
@@ -77,8 +84,9 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
77
84
  })),
78
85
  expectedPreviousSha256: spec.expected_previous_sha256,
79
86
  validateCurrent: (_, index) => current(index),
87
+ refreshIdentity,
80
88
  }, qualified);
81
- const authorization = await loadFoundryTaskAuthorization(context, identity, inputFile, qualified);
89
+ const authorization = await loadFoundryTaskAuthorization(context, identity, inputFile, qualified, refreshIdentity);
82
90
  return recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, {
83
91
  inputFile,
84
92
  approvedInputFile: inputFile,
@@ -173,7 +181,11 @@ async function authorizeFoundryRepair(context, qualified, entries, selected, aut
173
181
  reported.desired_sha256 !== action.desired_sha256)
174
182
  throw new FoundryContextError("authorization_repair_action_mismatch", "Registered repair actions must equal the signed native contract actions.");
175
183
  }
176
- const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
184
+ let identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
185
+ const refreshIdentity = () => {
186
+ identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
187
+ return identity;
188
+ };
177
189
  const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
178
190
  const current = (index) => {
179
191
  assertSelectedAuthorizationInput(selected);
@@ -193,8 +205,9 @@ async function authorizeFoundryRepair(context, qualified, entries, selected, aut
193
205
  })),
194
206
  expectedPreviousSha256: spec.expected_previous_sha256,
195
207
  validateCurrent: (_, index) => current(index),
208
+ refreshIdentity,
196
209
  }, qualified);
197
- const authorization = await loadFoundryTaskAuthorization(context, identity, candidateFile, qualified);
210
+ const authorization = await loadFoundryTaskAuthorization(context, identity, candidateFile, qualified, refreshIdentity);
198
211
  return recordFoundryWorkflowAuthorization(context, qualified, identity, authorization, authentication, {
199
212
  inputFile: candidateFile,
200
213
  approvedInputFile: candidateFile,
@@ -0,0 +1,44 @@
1
+ import type { SpawnSyncReturns } from "node:child_process";
2
+ import { FoundryContextError, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
3
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
4
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ export declare const workflowFailureCommand = "dataset-workflow-failure";
6
+ export declare const workflowFailureFile = "workflow-child-failure.json";
7
+ export declare const workflowFailureArtifactLimit: number;
8
+ export declare const workflowFailurePreviewLimit = 4096;
9
+ /** Bound the complete persisted wrapper, including JSON escaping, indentation and task fields. */
10
+ export declare function serializeWorkflowFailureResult(result: Record<string, unknown>): Buffer;
11
+ export declare class WorkflowChildFailure extends FoundryContextError {
12
+ readonly evidence: Record<string, unknown>;
13
+ retainedArtifact?: Readonly<{
14
+ path: string;
15
+ bytes: number;
16
+ sha256: string;
17
+ }>;
18
+ constructor(evidence: Record<string, unknown>);
19
+ }
20
+ export declare function bindWorkflowChildExecution(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, cliPath: string, argv: readonly string[], cwd?: string, executable?: string): Readonly<{
21
+ execution_id: `${string}-${string}-${string}-${string}-${string}`;
22
+ started_at_utc: string;
23
+ invocation: Readonly<{
24
+ argv: readonly string[];
25
+ argv_count: number;
26
+ argv_truncated: boolean;
27
+ executable: string;
28
+ executable_sha256: string;
29
+ cli_path: string;
30
+ cli_sha256: string;
31
+ argv_sha256: string;
32
+ cwd: string;
33
+ cwd_relative: string;
34
+ cwd_sha256: string;
35
+ qualification_sha256: string;
36
+ }>;
37
+ }>;
38
+ export declare function workflowChildFailure(execution: ReturnType<typeof bindWorkflowChildExecution>, child: SpawnSyncReturns<string>, kind: string, rejection?: unknown): WorkflowChildFailure;
39
+ /** Read-only proof of a failed local operation. Failure artifacts never enter producer lineage. */
40
+ export declare function readWorkflowChildFailure(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): {
41
+ entry: ArtifactEntry;
42
+ result: import("./foundry-task-types.ts").JsonRecord;
43
+ failure: import("./foundry-task-types.ts").JsonRecord;
44
+ } | null;
@@ -0,0 +1,439 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { FoundryContextError, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
+ import { bytes, digest, exact, facts, object, readTaskBytes, reference, shaPattern, timestamp, } from "./foundry-task-io.js";
6
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ export const workflowFailureCommand = "dataset-workflow-failure";
8
+ export const workflowFailureFile = "workflow-child-failure.json";
9
+ const kinds = [
10
+ "spawn_error",
11
+ "signal",
12
+ "exit_code",
13
+ "empty_stdout",
14
+ "malformed_json",
15
+ "invalid_report",
16
+ "stage_rejected",
17
+ ];
18
+ export const workflowFailureArtifactLimit = 64 * 1024;
19
+ export const workflowFailurePreviewLimit = 4096;
20
+ const previewLimit = workflowFailurePreviewLimit;
21
+ const argvPreviewBudget = 16 * 1024;
22
+ const evidenceBudget = 48 * 1024;
23
+ const truncatableFields = [
24
+ "invocation.argv",
25
+ "stdout.preview",
26
+ "stderr.preview",
27
+ "child.error_message",
28
+ "rejection.code",
29
+ "rejection.message",
30
+ "invocation.executable",
31
+ "invocation.cli_path",
32
+ "invocation.cwd",
33
+ ];
34
+ function utf8Prefix(value, budget) {
35
+ let used = 0, end = 0;
36
+ for (const character of value) {
37
+ const length = Buffer.byteLength(character);
38
+ if (used + length > budget)
39
+ break;
40
+ used += length;
41
+ end += character.length;
42
+ }
43
+ return value.slice(0, end);
44
+ }
45
+ function renderPreview(value) {
46
+ // Facts hash the complete stream, while display work never scans its unbounded tail.
47
+ const prefix = utf8Prefix(value, previewLimit * 2);
48
+ const clean = prefix
49
+ .split("")
50
+ .filter((character) => {
51
+ const code = character.charCodeAt(0);
52
+ return (code >= 32 && code !== 127) || [9, 10, 13].includes(code);
53
+ })
54
+ .join("");
55
+ const redact = (text) => text
56
+ .replace(/(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/giu, "[redacted authorization]")
57
+ .replace(/\beyJ[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]*){0,2}/gu, "[redacted token]")
58
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+:[^\s/@]+(?:@|$)/giu, "$1[redacted]@")
59
+ .replace(/(["']?(?:[a-z0-9_]*(?:token|secret|password|passwd|key|cookie|session|credential|auth)[a-z0-9_]*)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
60
+ const redacted = redact(clean);
61
+ const preview = utf8Prefix(redacted, previewLimit);
62
+ // Cropping can shorten a redaction placeholder; render that bounded suffix consistently.
63
+ const renderedAgain = redact(preview);
64
+ const rendered = utf8Prefix(renderedAgain, previewLimit);
65
+ return {
66
+ preview: rendered,
67
+ truncated: prefix.length < value.length ||
68
+ preview.length < redacted.length ||
69
+ rendered.length < renderedAgain.length,
70
+ };
71
+ }
72
+ function safePreview(value) {
73
+ return renderPreview(value).preview;
74
+ }
75
+ function diagnostic(value) {
76
+ const raw = Buffer.from(value);
77
+ const rendered = renderPreview(value);
78
+ return {
79
+ bytes: raw.length,
80
+ sha256: digest(raw),
81
+ preview: rendered.preview,
82
+ truncated: raw.length > previewLimit || rendered.truncated,
83
+ };
84
+ }
85
+ function previewArgv(argv) {
86
+ const preview = [];
87
+ let cost = 2, truncated = false;
88
+ for (const argument of argv) {
89
+ const rendered = renderPreview(argument);
90
+ const value = rendered.preview;
91
+ // Include escaping, commas/newlines and more indentation than the final receipt uses.
92
+ const nextCost = Buffer.byteLength(JSON.stringify(value)) + 16;
93
+ if (cost + nextCost > argvPreviewBudget) {
94
+ truncated = true;
95
+ break;
96
+ }
97
+ cost += nextCost;
98
+ preview.push(value);
99
+ if (Buffer.byteLength(argument) > previewLimit || rendered.truncated)
100
+ truncated = true;
101
+ }
102
+ return { argv: Object.freeze(preview), argv_count: argv.length, argv_truncated: truncated };
103
+ }
104
+ function boundFailureRecord(record, limit) {
105
+ const failure = object(record.failure), invocation = object(failure.invocation);
106
+ const truncated = new Set(Array.isArray(failure.truncated_fields) ? failure.truncated_fields.map(String) : []);
107
+ const sources = object(failure.preview_sources);
108
+ let content = bytes(record);
109
+ const mark = (field) => {
110
+ truncated.add(field);
111
+ failure.truncated_fields = [...truncated];
112
+ };
113
+ const argv = Array.isArray(invocation.argv) ? [...invocation.argv] : [];
114
+ while (content.length > limit && argv.length) {
115
+ argv.splice(Math.floor(argv.length / 2));
116
+ invocation.argv = [...argv];
117
+ invocation.argv_truncated = true;
118
+ mark("invocation.argv");
119
+ content = bytes(record);
120
+ }
121
+ for (const field of truncatableFields.filter((field) => field !== "invocation.argv")) {
122
+ if (content.length <= limit)
123
+ break;
124
+ const [owner, key] = field.split(".");
125
+ if (failure[owner] === null)
126
+ continue;
127
+ const container = object(failure[owner]), original = container[key];
128
+ if (typeof original !== "string")
129
+ continue;
130
+ if (!["stdout.preview", "stderr.preview"].includes(field) && !Object.hasOwn(sources, field))
131
+ sources[field] = {
132
+ bytes: Buffer.byteLength(original),
133
+ sha256: digest(Buffer.from(original)),
134
+ };
135
+ let budget = Math.floor(Buffer.byteLength(original) / 2);
136
+ do {
137
+ const cropped = utf8Prefix(original, budget);
138
+ container[key] = owner === "invocation" ? cropped : safePreview(cropped);
139
+ mark(field);
140
+ if (owner === "stdout" || owner === "stderr")
141
+ container.truncated = true;
142
+ content = bytes(record);
143
+ budget = Math.floor(budget / 2);
144
+ } while (content.length > limit && container[key] !== "");
145
+ }
146
+ if (content.length > limit)
147
+ throw new FoundryContextError("workflow_failure_limit", "The fixed task failure identity exceeds its bounded protocol.");
148
+ return content;
149
+ }
150
+ /** Bound the complete persisted wrapper, including JSON escaping, indentation and task fields. */
151
+ export function serializeWorkflowFailureResult(result) {
152
+ const record = object(JSON.parse(bytes(result).toString("utf8")));
153
+ return boundFailureRecord(record, workflowFailureArtifactLimit);
154
+ }
155
+ export class WorkflowChildFailure extends FoundryContextError {
156
+ evidence;
157
+ retainedArtifact;
158
+ constructor(evidence) {
159
+ super("workflow_child_failed", "The original local CLI call failed; its task-bound diagnostic receipt is retained and requires a reviewed task revision.");
160
+ this.evidence = evidence;
161
+ }
162
+ }
163
+ export function bindWorkflowChildExecution(context, qualified, cliPath, argv, cwd = context.workspaceRoot, executable = process.execPath) {
164
+ return Object.freeze({
165
+ execution_id: randomUUID(),
166
+ started_at_utc: new Date().toISOString(),
167
+ invocation: Object.freeze({
168
+ executable,
169
+ executable_sha256: createHash("sha256").update(fs.readFileSync(executable)).digest("hex"),
170
+ cli_path: cliPath,
171
+ cli_sha256: createHash("sha256").update(fs.readFileSync(cliPath)).digest("hex"),
172
+ ...previewArgv(argv),
173
+ argv_sha256: sha256Json(argv),
174
+ cwd,
175
+ cwd_relative: path.relative(context.workspaceRoot, cwd),
176
+ cwd_sha256: digest(Buffer.from(cwd)),
177
+ qualification_sha256: qualified.qualification_sha256,
178
+ }),
179
+ });
180
+ }
181
+ export function workflowChildFailure(execution, child, kind, rejection) {
182
+ const error = child.error;
183
+ const evidence = {
184
+ schema: "tiangong-foundry.workflow-child-failure.v1",
185
+ ...execution,
186
+ finished_at_utc: new Date().toISOString(),
187
+ kind,
188
+ truncated_fields: [],
189
+ preview_sources: {},
190
+ rejection: rejection instanceof Error
191
+ ? {
192
+ code: "code" in rejection && typeof rejection.code === "string"
193
+ ? safePreview(rejection.code)
194
+ : null,
195
+ message: safePreview(rejection.message),
196
+ }
197
+ : null,
198
+ child: {
199
+ pid: Number.isSafeInteger(child.pid) ? child.pid : null,
200
+ exit_code: child.status,
201
+ signal: child.signal,
202
+ error_name: error && /^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(error.name) ? error.name : null,
203
+ error_code: error &&
204
+ "code" in error &&
205
+ typeof error.code === "string" &&
206
+ /^[A-Z0-9_]{1,64}$/u.test(error.code)
207
+ ? error.code
208
+ : null,
209
+ error_message: error ? safePreview(error.message) : null,
210
+ },
211
+ stdout: diagnostic(child.stdout ?? ""),
212
+ stderr: diagnostic(child.stderr ?? ""),
213
+ };
214
+ const sources = evidence.preview_sources;
215
+ const note = (field, value) => {
216
+ if (Buffer.byteLength(value) > previewLimit || renderPreview(value).truncated) {
217
+ evidence.truncated_fields.push(field);
218
+ sources[field] = { bytes: Buffer.byteLength(value), sha256: digest(Buffer.from(value)) };
219
+ }
220
+ };
221
+ if (execution.invocation.argv_truncated)
222
+ evidence.truncated_fields.push("invocation.argv");
223
+ if (error)
224
+ note("child.error_message", error.message);
225
+ if (rejection instanceof Error) {
226
+ note("rejection.message", rejection.message);
227
+ if ("code" in rejection && typeof rejection.code === "string")
228
+ note("rejection.code", rejection.code);
229
+ }
230
+ // Reserve space for the actual task wrapper; the writer additionally measures that wrapper.
231
+ const bounded = boundFailureRecord(object(JSON.parse(bytes({ failure: evidence }).toString("utf8"))), evidenceBudget);
232
+ return new WorkflowChildFailure(object(object(JSON.parse(bounded.toString("utf8"))).failure));
233
+ }
234
+ /** Read-only proof of a failed local operation. Failure artifacts never enter producer lineage. */
235
+ export function readWorkflowChildFailure(context, entries) {
236
+ const entry = entries.findLast((candidate) => candidate.command === workflowFailureCommand);
237
+ if (!entry)
238
+ return null;
239
+ const invalid = () => {
240
+ throw new FoundryContextError("workflow_failure_receipt_invalid", "The original failed operation evidence is missing, changed or inconsistent; do not rerun it.");
241
+ };
242
+ try {
243
+ if (entry.path !== `evidence/failures/${entry.operation_id}/${workflowFailureFile}` ||
244
+ entry.receipt.path !== `checkpoints/${entry.operation_id}.json`)
245
+ invalid();
246
+ const resultBytes = readTaskBytes(context, entry.path, workflowFailureArtifactLimit);
247
+ if (resultBytes.length !== entry.bytes || digest(resultBytes) !== entry.sha256)
248
+ invalid();
249
+ const result = object(JSON.parse(resultBytes.toString("utf8")));
250
+ exact(result, [
251
+ "schema",
252
+ "status",
253
+ "task_id",
254
+ "operation_id",
255
+ "command",
256
+ "input_scope_sha256",
257
+ "failure",
258
+ ]);
259
+ if (result.schema !== "tiangong-foundry.workflow-operation-failure.v1" ||
260
+ result.status !== "failed" ||
261
+ result.task_id !== context.taskId ||
262
+ result.operation_id !== entry.operation_id ||
263
+ result.input_scope_sha256 !== entry.input_scope_sha256 ||
264
+ typeof result.command !== "string")
265
+ invalid();
266
+ const receiptBytes = readTaskBytes(context, entry.receipt.path);
267
+ if (digest(receiptBytes) !== entry.receipt.sha256)
268
+ invalid();
269
+ const receipt = object(JSON.parse(receiptBytes.toString("utf8")));
270
+ exact(receipt, ["schema", "mode", "status", "plan", "job_sha256", "outputs", "result"]);
271
+ const output = facts(receipt.outputs);
272
+ if (receipt.schema !== "tiangong-foundry.operation-receipt.v1" ||
273
+ receipt.mode !== "deterministic-local" ||
274
+ receipt.status !== "failed" ||
275
+ output.length !== 1 ||
276
+ output[0].path !== entry.path ||
277
+ output[0].sha256 !== entry.sha256 ||
278
+ output[0].bytes !== entry.bytes ||
279
+ sha256Json(receipt.result) !== sha256Json({ path: entry.path, sha256: entry.sha256 }))
280
+ invalid();
281
+ const planRef = reference(receipt.plan), planBytes = readTaskBytes(context, planRef.path);
282
+ if (planRef.path !== `checkpoints/${entry.operation_id}.plan.json` ||
283
+ digest(planBytes) !== planRef.sha256)
284
+ invalid();
285
+ const plan = object(JSON.parse(planBytes.toString("utf8")));
286
+ exact(plan, [
287
+ "schema",
288
+ "operation_id",
289
+ "job_sha256",
290
+ "command",
291
+ "options_sha256",
292
+ "input_scope_sha256",
293
+ "inputs",
294
+ "created_at_utc",
295
+ ]);
296
+ const inputs = facts(plan.inputs);
297
+ const job = digest(readTaskBytes(context, "foundry-job.json"));
298
+ if (plan.schema !== "tiangong-foundry.operation-plan.v1" ||
299
+ plan.operation_id !== entry.operation_id ||
300
+ plan.command !== result.command ||
301
+ plan.job_sha256 !== job ||
302
+ receipt.job_sha256 !== job ||
303
+ sha256Json(inputs) !== entry.input_scope_sha256 ||
304
+ plan.input_scope_sha256 !== entry.input_scope_sha256 ||
305
+ !timestamp(plan.created_at_utc) ||
306
+ sha256Json({
307
+ job,
308
+ command: plan.command,
309
+ input_scope: entry.input_scope_sha256,
310
+ options: plan.options_sha256,
311
+ }) !== entry.operation_id)
312
+ invalid();
313
+ const failure = object(result.failure);
314
+ exact(failure, [
315
+ "schema",
316
+ "execution_id",
317
+ "started_at_utc",
318
+ "finished_at_utc",
319
+ "kind",
320
+ "truncated_fields",
321
+ "preview_sources",
322
+ "rejection",
323
+ "invocation",
324
+ "child",
325
+ "stdout",
326
+ "stderr",
327
+ ]);
328
+ if (failure.rejection !== null) {
329
+ const rejection = object(failure.rejection);
330
+ exact(rejection, ["code", "message"]);
331
+ if (!(rejection.code === null ||
332
+ (typeof rejection.code === "string" &&
333
+ Buffer.byteLength(rejection.code) <= previewLimit &&
334
+ safePreview(rejection.code) === rejection.code)) ||
335
+ typeof rejection.message !== "string" ||
336
+ Buffer.byteLength(rejection.message) > previewLimit ||
337
+ safePreview(rejection.message) !== rejection.message)
338
+ invalid();
339
+ }
340
+ const invocation = object(failure.invocation), child = object(failure.child);
341
+ exact(invocation, [
342
+ "executable",
343
+ "executable_sha256",
344
+ "cli_path",
345
+ "cli_sha256",
346
+ "argv",
347
+ "argv_count",
348
+ "argv_truncated",
349
+ "argv_sha256",
350
+ "cwd",
351
+ "cwd_relative",
352
+ "cwd_sha256",
353
+ "qualification_sha256",
354
+ ]);
355
+ exact(child, ["pid", "exit_code", "signal", "error_name", "error_code", "error_message"]);
356
+ if (!Array.isArray(failure.truncated_fields) ||
357
+ failure.truncated_fields.some((field) => typeof field !== "string" || !truncatableFields.includes(field)))
358
+ invalid();
359
+ const truncatedFields = Array.isArray(failure.truncated_fields)
360
+ ? failure.truncated_fields
361
+ : invalid();
362
+ const sources = object(failure.preview_sources);
363
+ for (const [field, value] of Object.entries(sources)) {
364
+ if (!truncatableFields.includes(field))
365
+ invalid();
366
+ const source = object(value);
367
+ exact(source, ["bytes", "sha256"]);
368
+ if (!Number.isSafeInteger(source.bytes) ||
369
+ Number(source.bytes) < 0 ||
370
+ typeof source.sha256 !== "string" ||
371
+ !shaPattern.test(source.sha256))
372
+ invalid();
373
+ }
374
+ const cwdRelative = typeof invocation.cwd_relative === "string" ? invocation.cwd_relative : invalid();
375
+ if (typeof invocation.cwd !== "string" ||
376
+ typeof invocation.cwd_sha256 !== "string" ||
377
+ !shaPattern.test(invocation.cwd_sha256))
378
+ invalid();
379
+ const cwd = path.resolve(context.workspaceRoot, cwdRelative);
380
+ if (digest(Buffer.from(cwd)) !== invocation.cwd_sha256 ||
381
+ (!truncatedFields.includes("invocation.cwd") && invocation.cwd !== cwd))
382
+ invalid();
383
+ if (cwd !== context.workspaceRoot) {
384
+ const relative = path.relative(context.tempRoot, resolveFoundryOutput(context, cwd));
385
+ if (!relative ||
386
+ relative === ".." ||
387
+ relative.startsWith(`..${path.sep}`) ||
388
+ path.isAbsolute(relative))
389
+ invalid();
390
+ }
391
+ if (failure.schema !== "tiangong-foundry.workflow-child-failure.v1" ||
392
+ typeof failure.kind !== "string" ||
393
+ !kinds.includes(failure.kind) ||
394
+ typeof failure.execution_id !== "string" ||
395
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(failure.execution_id) ||
396
+ !timestamp(failure.started_at_utc) ||
397
+ !timestamp(failure.finished_at_utc) ||
398
+ !Number.isSafeInteger(invocation.argv_count) ||
399
+ Number(invocation.argv_count) < 0 ||
400
+ typeof invocation.argv_truncated !== "boolean" ||
401
+ !Array.isArray(invocation.argv) ||
402
+ Number(invocation.argv_count) < invocation.argv.length ||
403
+ (Number(invocation.argv_count) > invocation.argv.length && !invocation.argv_truncated) ||
404
+ invocation.argv.some((arg) => typeof arg !== "string" || Buffer.byteLength(arg) > previewLimit) ||
405
+ ![child.signal, child.error_name, child.error_code, child.error_message].every((value) => value === null ||
406
+ (typeof value === "string" &&
407
+ Buffer.byteLength(value) <= previewLimit &&
408
+ safePreview(value) === value)) ||
409
+ (failure.kind === "signal" && child.signal === null) ||
410
+ (failure.kind === "spawn_error" && child.error_message === null) ||
411
+ typeof invocation.cli_path !== "string" ||
412
+ typeof invocation.executable !== "string" ||
413
+ ![
414
+ invocation.argv_sha256,
415
+ invocation.cli_sha256,
416
+ invocation.executable_sha256,
417
+ invocation.qualification_sha256,
418
+ ].every((hash) => typeof hash === "string" && shaPattern.test(hash)) ||
419
+ ![child.pid, child.exit_code].every((value) => value === null || Number.isSafeInteger(value)))
420
+ invalid();
421
+ for (const name of ["stdout", "stderr"]) {
422
+ const detail = object(failure[name]);
423
+ exact(detail, ["bytes", "sha256", "preview", "truncated"]);
424
+ if (!Number.isSafeInteger(detail.bytes) ||
425
+ Number(detail.bytes) < 0 ||
426
+ typeof detail.sha256 !== "string" ||
427
+ !shaPattern.test(detail.sha256) ||
428
+ typeof detail.preview !== "string" ||
429
+ Buffer.byteLength(detail.preview) > previewLimit ||
430
+ safePreview(detail.preview) !== detail.preview ||
431
+ typeof detail.truncated !== "boolean")
432
+ invalid();
433
+ }
434
+ return { entry, result, failure };
435
+ }
436
+ catch {
437
+ return invalid();
438
+ }
439
+ }
@@ -7,7 +7,9 @@ import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environ
7
7
  import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
8
8
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
9
9
  import { supportedDatasetTypes } from "./import-curation/internal/dataset-types.js";
10
+ import { bindWorkflowChildExecution, workflowChildFailure, } from "./foundry-workflow-child-failure.js";
10
11
  import { createWorkflowDirectory } from "./foundry-workflow-io.js";
12
+ import { readFoundryTaskRuntimeAdoption } from "./foundry-task-runtime-adoption.js";
11
13
  export async function prepareFoundryWorkflowContext(context, qualified, selectedTypes) {
12
14
  assertQualifiedFoundryRuntime(context, qualified);
13
15
  if (!selectedTypes.length || selectedTypes.some((type) => !supportedDatasetTypes.has(type)))
@@ -15,7 +17,15 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
15
17
  const types = [
16
18
  ...new Set(selectedTypes.flatMap((type) => type === "support" ? ["contact", "source", "flowproperty", "unitgroup"] : [type])),
17
19
  ].sort();
18
- return runFoundryTaskOperation(context, { command: "dataset-context-pack", options: { types, profile: "ai-import" } }, (operation) => {
20
+ const adoption = readFoundryTaskRuntimeAdoption(context);
21
+ return runFoundryTaskOperation(context, {
22
+ command: "dataset-context-pack",
23
+ options: {
24
+ types,
25
+ profile: "ai-import",
26
+ ...(adoption ? { runtime_adoption_plan_sha256: adoption.plan_sha256 } : {}),
27
+ },
28
+ }, (operation) => {
19
29
  assertQualifiedFoundryRuntime(context, qualified);
20
30
  for (const input of context.inputs)
21
31
  readFoundryInput(context, input.path);
@@ -34,8 +44,7 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
34
44
  for (const type of types) {
35
45
  assertQualifiedFoundryRuntime(context, qualified);
36
46
  const destination = path.join(output, type);
37
- const child = spawnSync(process.execPath, [
38
- cli.binPath,
47
+ const argv = [
39
48
  "dataset",
40
49
  "context-pack",
41
50
  "--type",
@@ -45,7 +54,9 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
45
54
  "--out-dir",
46
55
  destination,
47
56
  "--json",
48
- ], {
57
+ ];
58
+ const execution = bindWorkflowChildExecution(context, qualified, cli.binPath, argv);
59
+ const child = spawnSync(process.execPath, [cli.binPath, ...argv], {
49
60
  cwd: context.workspaceRoot,
50
61
  env: environment,
51
62
  encoding: "utf8",
@@ -53,14 +64,32 @@ export async function prepareFoundryWorkflowContext(context, qualified, selected
53
64
  maxBuffer: 8 * 1024 * 1024,
54
65
  timeout: 120_000,
55
66
  });
56
- if (child.error || child.signal || child.status !== 0 || child.stderr)
57
- throw new FoundryContextError("workflow_context_failed", `CLI context preparation failed for ${type}.`);
58
- const value = JSON.parse(child.stdout);
67
+ const kind = child.error
68
+ ? "spawn_error"
69
+ : child.signal
70
+ ? "signal"
71
+ : child.status !== 0
72
+ ? "exit_code"
73
+ : !child.stdout.trim()
74
+ ? "empty_stdout"
75
+ : child.stderr
76
+ ? "stage_rejected"
77
+ : null;
78
+ if (kind)
79
+ throw workflowChildFailure(execution, child, kind);
80
+ let value;
81
+ try {
82
+ value = JSON.parse(child.stdout);
83
+ }
84
+ catch {
85
+ throw workflowChildFailure(execution, child, "malformed_json");
86
+ }
59
87
  if (!value ||
60
88
  typeof value !== "object" ||
89
+ Array.isArray(value) ||
61
90
  !("status" in value) ||
62
91
  value.status !== "completed")
63
- throw new FoundryContextError("workflow_context_invalid", "CLI returned no completed context pack.");
92
+ throw workflowChildFailure(execution, child, "invalid_report");
64
93
  reports.push({ type, report: path.join(destination, "outputs/contract-report.json") });
65
94
  }
66
95
  const files = [];