@tiangong-lca/foundry 0.1.12 → 0.1.14

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 (45) hide show
  1. package/README.md +6 -6
  2. package/docs/architecture.md +8 -6
  3. package/docs/foundry-task-contracts.md +5 -5
  4. package/docs/import-profiles/worldsteel/constraints.md +3 -3
  5. package/docs/import-profiles/worldsteel/import-coverage.md +3 -3
  6. package/docs/import-profiles/worldsteel/import-plan.md +4 -4
  7. package/docs/import-profiles/worldsteel/profile.md +3 -3
  8. package/docs/package-distribution-contract.md +14 -10
  9. package/docs/public-runtime-contract.md +9 -7
  10. package/docs/runtime-context-contract.md +4 -4
  11. package/docs/task-authorization-contract.md +3 -3
  12. package/package-dist/assets/foundry-package-descriptor.json +97 -67
  13. package/package-dist/scripts/foundry-facade.js +217 -9
  14. package/package-dist/scripts/lib/foundry-interaction-input.d.ts +4 -3
  15. package/package-dist/scripts/lib/foundry-interaction-input.js +40 -7
  16. package/package-dist/scripts/lib/foundry-interaction-projection.d.ts +21 -2
  17. package/package-dist/scripts/lib/foundry-interaction-projection.js +49 -8
  18. package/package-dist/scripts/lib/foundry-interaction-scope.d.ts +7 -0
  19. package/package-dist/scripts/lib/foundry-interaction-scope.js +40 -0
  20. package/package-dist/scripts/lib/foundry-interaction-types.d.ts +5 -0
  21. package/package-dist/scripts/lib/foundry-native-validation-failure.d.ts +36 -0
  22. package/package-dist/scripts/lib/foundry-native-validation-failure.js +142 -0
  23. package/package-dist/scripts/lib/foundry-owner-execution-store.js +6 -13
  24. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  25. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  26. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  27. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  28. package/package-dist/scripts/lib/foundry-semantic-interaction.d.ts +11 -1
  29. package/package-dist/scripts/lib/foundry-semantic-interaction.js +64 -14
  30. package/package-dist/scripts/lib/foundry-tidas-source.js +4 -4
  31. package/package-dist/scripts/lib/foundry-workflow-approval-continuation.js +3 -0
  32. package/package-dist/scripts/lib/foundry-workflow-assessment.js +27 -2
  33. package/package-dist/scripts/lib/foundry-workflow-authorization.js +3 -0
  34. package/package-dist/scripts/lib/foundry-workflow-interaction.js +22 -3
  35. package/package-dist/scripts/lib/foundry-workflow-object-scope.d.ts +53 -0
  36. package/package-dist/scripts/lib/foundry-workflow-object-scope.js +326 -0
  37. package/package-dist/scripts/lib/foundry-workflow-semantic.d.ts +5 -0
  38. package/package-dist/scripts/lib/foundry-workflow-semantic.js +200 -6
  39. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  40. package/package.json +2 -2
  41. package/specs/import-profiles.json +1 -1
  42. package/specs/schemas/foundry-interaction-input.schema.json +29 -2
  43. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  44. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  45. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,40 @@
1
+ const supportTypes = new Set(["contact", "source", "unitgroup", "flowproperty"]);
2
+ export function foundryInteractionObjectKey(datasetType, entityId, version) {
3
+ return JSON.stringify([datasetType, entityId, version]);
4
+ }
5
+ export function foundryInteractionObjectProofKey(datasetType, entityId, version, rowSha256) {
6
+ return JSON.stringify([datasetType, entityId, version, rowSha256]);
7
+ }
8
+ export function foundryInteractionScopeApplies(scope, type) {
9
+ return scope === null || scope === type || (scope === "support" && supportTypes.has(type));
10
+ }
11
+ function objectScope(item) {
12
+ if (!Object.hasOwn(item, "object_scope"))
13
+ return null;
14
+ const scope = item.object_scope;
15
+ if (!scope || typeof scope !== "object" || Array.isArray(scope))
16
+ return null;
17
+ const candidate = scope;
18
+ if (typeof candidate.entity_id !== "string" || typeof candidate.version !== "string")
19
+ return null;
20
+ return candidate;
21
+ }
22
+ export function foundryInteractionEventAppliesToObject(item, type, entityId, version) {
23
+ const narrow = objectScope(item);
24
+ if (!narrow)
25
+ return (!Object.hasOwn(item, "object_scope") &&
26
+ foundryInteractionScopeApplies(item.dataset_type, type));
27
+ return (item.dataset_type === type &&
28
+ foundryInteractionObjectKey(type, narrow.entity_id, narrow.version) ===
29
+ foundryInteractionObjectKey(type, entityId, version));
30
+ }
31
+ export function sameFoundryInteractionScope(left, right) {
32
+ if (left.dataset_type !== right.dataset_type)
33
+ return false;
34
+ const leftNarrow = objectScope(left);
35
+ const rightNarrow = objectScope(right);
36
+ if (!leftNarrow || !rightNarrow)
37
+ return !Object.hasOwn(left, "object_scope") && !Object.hasOwn(right, "object_scope");
38
+ return (foundryInteractionObjectKey(String(left.dataset_type), leftNarrow.entity_id, leftNarrow.version) ===
39
+ foundryInteractionObjectKey(String(right.dataset_type), rightNarrow.entity_id, rightNarrow.version));
40
+ }
@@ -2,6 +2,11 @@ export declare const FOUNDRY_INTERACTION_INPUT_SCHEMA: "tiangong-foundry.interac
2
2
  export declare const FOUNDRY_INTERACTION_STATE_SCHEMA: "tiangong-foundry.interaction-state.v1";
3
3
  export declare const FOUNDRY_INTERACTION_COMMAND: "dataset-workflow-interaction";
4
4
  export declare const FOUNDRY_INTERACTION_REPORT: "interaction-state.json";
5
+ export interface FoundryInteractionObjectScope {
6
+ readonly entity_id: string;
7
+ readonly version: string;
8
+ readonly row_sha256: string;
9
+ }
5
10
  export interface FoundryInteractionInput {
6
11
  readonly schema: typeof FOUNDRY_INTERACTION_INPUT_SCHEMA;
7
12
  readonly task_id: string;
@@ -0,0 +1,36 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
3
+ import { runTidasRowsValidation } from "./tidas-adapter.ts";
4
+ export declare const nativeFailureFileName = "native-validation-failure.json";
5
+ export declare const nativeFailureResultName = "foundry-assessment-failure.json";
6
+ export declare function nativeValidationFailureEvidence(native: ReturnType<typeof runTidasRowsValidation>, datasetType: string, rowsFile: string, rowsSha256: string, rowCount: number): {
7
+ schema: string;
8
+ dataset_type: string;
9
+ rows_file: string;
10
+ rows_sha256: string;
11
+ row_count: number;
12
+ exit_code: number;
13
+ exit_class: unknown;
14
+ diagnostic_code: unknown;
15
+ diagnostic_message: unknown;
16
+ native_report: Record<string, unknown>;
17
+ stderr: {
18
+ bytes: number;
19
+ sha256: string;
20
+ } | null;
21
+ stderr_text: string;
22
+ };
23
+ export declare function currentNativeValidationFailure(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], rowsReport: {
24
+ file: string;
25
+ sha256: string;
26
+ sets: readonly {
27
+ type: string;
28
+ file: string;
29
+ count: number;
30
+ }[];
31
+ } | null): {
32
+ entry: ArtifactEntry;
33
+ result: Record<string, unknown>;
34
+ detail: Record<string, unknown>;
35
+ file: string;
36
+ } | null;
@@ -0,0 +1,142 @@
1
+ import path from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { captureFoundryInput, FoundryContextError, } from "./foundry-runtime-context.js";
4
+ import { readWorkflowArtifact, workflowObject } from "./foundry-workflow-state.js";
5
+ import { runTidasRowsValidation } from "./tidas-adapter.js";
6
+ export const nativeFailureFileName = "native-validation-failure.json";
7
+ export const nativeFailureResultName = "foundry-assessment-failure.json";
8
+ const nativeFailureSchema = "tiangong-foundry.native-validation-failure.v1";
9
+ const nativeFailureResultSchema = "tiangong-foundry.assessment-failure.v1";
10
+ const maxNativeReportBytes = 256 * 1024;
11
+ const maxNativeStderrBytes = 64 * 1024;
12
+ const exitClasses = new Map([
13
+ [64, "usage"],
14
+ [69, "unavailable"],
15
+ [70, "internal"],
16
+ [74, "io"],
17
+ [130, "cancelled"],
18
+ ]);
19
+ function invalid() {
20
+ throw new FoundryContextError("workflow_native_report_invalid", "Native validation did not return complete bounded failure evidence.");
21
+ }
22
+ function sha256(bytes) {
23
+ return createHash("sha256").update(bytes).digest("hex");
24
+ }
25
+ export function nativeValidationFailureEvidence(native, datasetType, rowsFile, rowsSha256, rowCount) {
26
+ const report = workflowObject(native.report);
27
+ const diagnostics = report.diagnostics;
28
+ const stderr = native.stderr ?? "";
29
+ if (!exitClasses.has(native.exit_code) ||
30
+ report.schema_version !== "tidas.operation-report.v1" ||
31
+ report.command !== "validate" ||
32
+ report.status !== (native.exit_code === 130 ? "cancelled" : "failed") ||
33
+ report.exit_class !== exitClasses.get(native.exit_code) ||
34
+ !Array.isArray(diagnostics) ||
35
+ diagnostics.length < 1 ||
36
+ ![
37
+ "process",
38
+ "flow",
39
+ "source",
40
+ "contact",
41
+ "unitgroup",
42
+ "flowproperty",
43
+ "lifecyclemodel",
44
+ ].includes(datasetType) ||
45
+ !/^[0-9a-f]{64}$/u.test(rowsSha256) ||
46
+ !Number.isSafeInteger(rowCount) ||
47
+ rowCount < 0 ||
48
+ Buffer.byteLength(JSON.stringify(report)) > maxNativeReportBytes ||
49
+ Buffer.byteLength(stderr) > maxNativeStderrBytes)
50
+ invalid();
51
+ for (const candidate of diagnostics) {
52
+ const detail = workflowObject(candidate);
53
+ if (detail.schema_version !== "tidas.diagnostic.v1" ||
54
+ typeof detail.code !== "string" ||
55
+ !/^[a-z][a-z0-9_]{0,79}$/u.test(detail.code) ||
56
+ typeof detail.message !== "string" ||
57
+ !detail.message.trim() ||
58
+ detail.message.length > 4096 ||
59
+ Array.from(detail.message).some((character) => {
60
+ const codePoint = character.codePointAt(0) ?? 0;
61
+ return codePoint < 32 && ![9, 10, 13].includes(codePoint);
62
+ }))
63
+ invalid();
64
+ }
65
+ const first = workflowObject(diagnostics[0]);
66
+ return {
67
+ schema: nativeFailureSchema,
68
+ dataset_type: datasetType,
69
+ rows_file: rowsFile,
70
+ rows_sha256: rowsSha256,
71
+ row_count: rowCount,
72
+ exit_code: native.exit_code,
73
+ exit_class: report.exit_class,
74
+ diagnostic_code: first.code,
75
+ diagnostic_message: first.message,
76
+ native_report: report,
77
+ stderr: stderr ? { bytes: Buffer.byteLength(stderr), sha256: sha256(stderr) } : null,
78
+ stderr_text: stderr,
79
+ };
80
+ }
81
+ export function currentNativeValidationFailure(context, entries, rowsReport) {
82
+ for (const entry of [...entries].reverse()) {
83
+ if (entry.command !== "dataset-workflow-assessment" ||
84
+ path.basename(entry.path) !== nativeFailureResultName)
85
+ continue;
86
+ const result = readWorkflowArtifact(context, entry);
87
+ const value = result.value;
88
+ if (value.schema !== nativeFailureResultSchema ||
89
+ value.status !== "blocked" ||
90
+ value.task_id !== context.taskId ||
91
+ value.rows_report !== rowsReport?.file ||
92
+ value.rows_report_sha256 !== rowsReport?.sha256 ||
93
+ typeof value.evidence_file !== "string" ||
94
+ typeof value.evidence_sha256 !== "string" ||
95
+ typeof value.dataset_type !== "string" ||
96
+ typeof value.rows_file !== "string" ||
97
+ !Number.isSafeInteger(value.row_count))
98
+ invalid();
99
+ const detailEntry = entries.find((candidate) => candidate.command === entry.command &&
100
+ candidate.operation_id === entry.operation_id &&
101
+ candidate.sha256 === value.evidence_sha256 &&
102
+ path.join(context.taskRoot, candidate.path) === value.evidence_file &&
103
+ path.basename(candidate.path) === nativeFailureFileName);
104
+ if (!detailEntry)
105
+ invalid();
106
+ const detail = readWorkflowArtifact(context, detailEntry);
107
+ const selected = rowsReport?.sets.find((set) => set.type === value.dataset_type);
108
+ if (!selected ||
109
+ selected.file !== value.rows_file ||
110
+ selected.count !== value.row_count ||
111
+ captureFoundryInput(selected.file).sha256 !== value.rows_file_sha256)
112
+ invalid();
113
+ const nativeReport = workflowObject(detail.value.native_report);
114
+ const diagnostics = nativeReport.diagnostics;
115
+ const first = Array.isArray(diagnostics) && diagnostics.length ? workflowObject(diagnostics[0]) : invalid();
116
+ if (detail.value.schema !== nativeFailureSchema ||
117
+ detail.value.dataset_type !== value.dataset_type ||
118
+ detail.value.rows_file !== value.rows_file ||
119
+ detail.value.rows_sha256 !== value.rows_file_sha256 ||
120
+ detail.value.row_count !== value.row_count ||
121
+ detail.value.exit_code !== value.exit_code ||
122
+ detail.value.exit_class !== value.exit_class ||
123
+ detail.value.diagnostic_code !== value.diagnostic_code ||
124
+ detail.value.diagnostic_message !== value.diagnostic_message ||
125
+ nativeReport.exit_class !== value.exit_class ||
126
+ typeof first.code !== "string" ||
127
+ first.code !== value.diagnostic_code ||
128
+ first.message !== value.diagnostic_message)
129
+ invalid();
130
+ const stderrText = detail.value.stderr_text;
131
+ const stderr = detail.value.stderr;
132
+ if (typeof stderrText !== "string" ||
133
+ (stderr === null && stderrText !== "") ||
134
+ (stderr !== null &&
135
+ (typeof stderr !== "object" ||
136
+ stderr.bytes !== Buffer.byteLength(stderrText) ||
137
+ stderr.sha256 !== sha256(stderrText))))
138
+ invalid();
139
+ return { entry, result: value, detail: detail.value, file: detail.file };
140
+ }
141
+ return null;
142
+ }
@@ -8,21 +8,14 @@ import { captureFoundryInput, FoundryContextError, readFoundryInput, resolveFoun
8
8
  import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
9
9
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
10
10
  import { sha256Json } from "./identity-preflight-proof.js";
11
- import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
12
- import { currentFoundryQuestions, currentFoundryInvestigations, foundryInteractionScopeApplies, } from "./foundry-interaction-projection.js";
13
- function assertOwnerInteractionReady(context, entries, datasetType, repairScope) {
11
+ import { assertFoundryInteractionWriteReady } from "./foundry-workflow-object-scope.js";
12
+ function assertOwnerInteractionReady(context, entries, repairScope) {
14
13
  if (repairScope)
15
14
  return;
16
15
  const state = currentWorkflowState(context, entries);
17
16
  if (!state.assessmentComplete)
18
17
  throw new FoundryContextError("execution_assessment_incomplete", "Owner execution requires complete current assessment coverage.");
19
- const interaction = currentFoundryInteractionState(context, entries);
20
- if (interaction &&
21
- [
22
- ...currentFoundryQuestions(interaction.state),
23
- ...currentFoundryInvestigations(interaction.state),
24
- ].some((question) => foundryInteractionScopeApplies(question.dataset_type, datasetType)))
25
- throw new FoundryContextError("interaction_decision_pending", "An applicable question or investigation remains unresolved before owner execution.");
18
+ assertFoundryInteractionWriteReady(context, entries);
26
19
  }
27
20
  /**
28
21
  * The finalization and mutation evidence a sealed owner scope must retain. Only the registered repair
@@ -101,7 +94,7 @@ export async function prepareFoundryOwnerExecution(context, entries) {
101
94
  if (!approval || approval.value.status !== "sealed")
102
95
  throw new FoundryContextError("execution_approval_required", "A current sealed approval is required.");
103
96
  const request = buildRequest(context, approval);
104
- assertOwnerInteractionReady(context, entries, request.policy.dataset_type, request.policy.repair_scope === true);
97
+ assertOwnerInteractionReady(context, entries, request.policy.repair_scope === true);
105
98
  return runFoundryTaskOperation(context, {
106
99
  command: "dataset-workflow-execution-prepare",
107
100
  options: { authorization: approval.entry.sha256 },
@@ -109,7 +102,7 @@ export async function prepareFoundryOwnerExecution(context, entries) {
109
102
  const latest = currentWorkflowState(context, index);
110
103
  if (latest.authorization?.entry.sha256 !== approval.entry.sha256)
111
104
  throw new FoundryContextError("execution_approval_changed", "Approval changed before execution preparation.");
112
- assertOwnerInteractionReady(context, index, request.policy.dataset_type, request.policy.repair_scope === true);
105
+ assertOwnerInteractionReady(context, index, request.policy.repair_scope === true);
113
106
  },
114
107
  }, (operation) => {
115
108
  operation.writeJson(`outputs/execution-requests/${request.scope_id}/${approval.entry.sha256}/owner-execution-request.json`, request);
@@ -222,7 +215,7 @@ export async function markOwnerAttemptConsumed(context, artifact) {
222
215
  const current = readOwnerExecutionRequests(context, index);
223
216
  if (!current.some((item) => item.entry.sha256 === artifact.entry.sha256))
224
217
  throw new FoundryContextError("execution_request_changed", "The owner request changed before its attempt was consumed.");
225
- assertOwnerInteractionReady(context, index, artifact.request.policy.dataset_type, artifact.request.policy.repair_scope === true);
218
+ assertOwnerInteractionReady(context, index, artifact.request.policy.repair_scope === true);
226
219
  if (artifact.request.policy.repair_scope !== true &&
227
220
  currentWorkflowState(context, index).authorization?.entry.sha256 !==
228
221
  artifact.request.content.authorization)
@@ -2,9 +2,9 @@ export declare const FOUNDRY_PACKAGE_DESCRIPTOR_SCHEMA: "tiangong-foundry.packag
2
2
  export declare const foundryPackageDescriptorPath: "package-dist/assets/foundry-package-descriptor.json";
3
3
  export declare const foundryPackageStaticFiles: readonly ["package-dist/", "specs/import-profiles.json", "specs/prewrite-content-policy.json", "specs/canonical-support/flow-properties-unit-groups.json", "specs/schemas/authorization-derivation.schema.json", "specs/schemas/execution-context.schema.json", "specs/schemas/foundry-facade-request-index.schema.json", "specs/schemas/foundry-operation-result.schema.json", "specs/schemas/foundry-package-descriptor.schema.json", "specs/schemas/foundry-task-start.schema.json", "specs/schemas/foundry-semantic-input.schema.json", "specs/schemas/foundry-interaction-input.schema.json", "specs/schemas/foundry-authorization-input.schema.json", "specs/schemas/foundry-reference-input.schema.json", "specs/schemas/foundry-workspace-migration-plan.schema.json", "specs/schemas/foundry-workspace-migration-transfer-plan.schema.json", "specs/schemas/foundry-migration-transfer-receipt.schema.json", "specs/schemas/foundry-workspace-migration-pending.schema.json", "specs/schemas/foundry-migration-adoption-plan.schema.json", "specs/schemas/foundry-migration-activation.schema.json", "specs/schemas/foundry-workspace-v2.schema.json", "specs/schemas/foundry-runtime-selection.schema.json", "specs/schemas/foundry-managed-runtime.schema.json", "specs/schemas/runtime-qualification.schema.json", "specs/schemas/task-authorization.schema.json", "specs/schemas/tidas-runtime-expectation.schema.json", "docs/architecture.md", "docs/package-distribution-contract.md", "docs/foundry-task-contracts.md", "docs/public-runtime-contract.md", "docs/runtime-context-contract.md", "docs/workspace-migration-contract.md", "docs/safety-policy.md", "docs/task-authorization-contract.md", "docs/import-profiles/bafu/constraints.md", "docs/import-profiles/bafu/leaf-process-classification-authoring.md", "docs/import-profiles/bafu/profile.md", "docs/import-profiles/uslci/constraints.md", "docs/import-profiles/uslci/profile.md", "docs/uslci-import-runbook.md", "docs/import-profiles/worldsteel/constraints.md", "docs/import-profiles/worldsteel/import-coverage.md", "docs/import-profiles/worldsteel/import-plan.md", "docs/import-profiles/worldsteel/profile.md", "README.md", "LICENSE"];
4
4
  declare const packageName = "@tiangong-lca/foundry";
5
- declare const packageVersion = "0.1.12";
5
+ declare const packageVersion = "0.1.14";
6
6
  declare const cliPackageName = "@tiangong-lca/cli";
7
- declare const cliPackageVersion = "0.1.19";
7
+ declare const cliPackageVersion = "0.1.23";
8
8
  declare const packageBin = "package-dist/scripts/package-entry.js";
9
9
  declare const packageApi = "package-dist/scripts/public-api.js";
10
10
  declare const packageTypes = "package-dist/scripts/public-api.d.ts";
@@ -53,10 +53,10 @@ export const foundryPackageStaticFiles = Object.freeze([
53
53
  "LICENSE",
54
54
  ]);
55
55
  const packageName = "@tiangong-lca/foundry";
56
- const packageVersion = "0.1.12";
56
+ const packageVersion = "0.1.14";
57
57
  const packageDescription = "Control plane for TianGong LCA external dataset import and TIDAS authoring work.";
58
58
  const cliPackageName = "@tiangong-lca/cli";
59
- const cliPackageVersion = "0.1.19";
59
+ const cliPackageVersion = "0.1.23";
60
60
  const packageBin = "package-dist/scripts/package-entry.js";
61
61
  const packageApi = "package-dist/scripts/public-api.js";
62
62
  const packageTypes = "package-dist/scripts/public-api.d.ts";
@@ -157,8 +157,8 @@ export function qualifyFoundryRuntime(context, options) {
157
157
  catch {
158
158
  return fail("runtime_cli_unqualified", "CLI runtime bytes do not match the independently selected C1 expectation.");
159
159
  }
160
- if (cli.package.version !== "0.1.19" || cli.platform !== context.platform)
161
- fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.19 C1 runtime on the selected platform.");
160
+ if (cli.package.version !== "0.1.23" || cli.platform !== context.platform)
161
+ fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.23 C1 runtime on the selected platform.");
162
162
  const cliExpectation = Object.freeze({ ...options.cliExpectation });
163
163
  if (cliExpectation.schema !== CLI_RUNTIME_EXPECTATION_SCHEMA)
164
164
  fail("runtime_cli_unqualified", "CLI runtime expectation is not the supported schema.");
@@ -9,7 +9,7 @@ import { resolveFoundryRuntimePaths } from "./foundry-runtime-paths.js";
9
9
  import { resolveTiangongLcaCliTidasSource, } from "./foundry-tidas-source.js";
10
10
  const require = createRequire(import.meta.url);
11
11
  const tiangongLcaCliPackageName = "@tiangong-lca/cli";
12
- const tiangongLcaCliPackageVersion = "0.1.19";
12
+ const tiangongLcaCliPackageVersion = "0.1.23";
13
13
  const tiangongLcaCliBinName = "tiangong-lca";
14
14
  const { repoRoot: foundryRepoRoot } = resolveFoundryRuntimePaths(import.meta.url);
15
15
  function isRecord(value) {
@@ -1,12 +1,22 @@
1
1
  import type { FoundrySemanticInput } from "./foundry-semantic-input.ts";
2
2
  import type { FoundryInteractionState } from "./foundry-interaction-input.ts";
3
+ export interface SemanticObjectIdentity {
4
+ readonly dataset_type: string;
5
+ readonly entity_id: string;
6
+ readonly version: string;
7
+ }
8
+ export type SemanticSelectedScope = string | SemanticObjectIdentity | readonly SemanticObjectIdentity[];
3
9
  export interface SemanticInteractionScope {
4
10
  readonly work_item_sha256: string;
5
11
  readonly dataset_type: string;
6
12
  readonly decision_ids: readonly string[];
13
+ readonly object_scope?: Readonly<{
14
+ entity_id: string;
15
+ version: string;
16
+ }>;
7
17
  }
8
18
  /** Bind a semantic proposal to the latest applicable user choices without treating them as data proof. */
9
19
  export declare function verifyFoundrySemanticInteraction(input: FoundrySemanticInput, interaction: {
10
20
  readonly sha256: string;
11
21
  readonly state: FoundryInteractionState;
12
- } | null, selectedScopes: ReadonlyMap<string, string>): readonly SemanticInteractionScope[];
22
+ } | null, selectedScopes: ReadonlyMap<string, SemanticSelectedScope>): readonly SemanticInteractionScope[];
@@ -1,19 +1,52 @@
1
1
  import { FoundryContextError } from "./foundry-runtime-context.js";
2
- import { currentFoundryDecisionsForType, currentFoundryQuestions, currentFoundryInvestigations, foundryInteractionScopeApplies, } from "./foundry-interaction-projection.js";
2
+ import { currentFoundryDecisionsForType, currentFoundryDecisionsForObject, currentFoundryDecisions, currentFoundryQuestions, currentFoundryQuestionsForObject, currentFoundryInvestigations, currentFoundryInvestigationsForObject, currentFoundryAssumptions, foundryInteractionScopeApplies, } from "./foundry-interaction-projection.js";
3
3
  function fail(message) {
4
4
  throw new FoundryContextError("semantic_interaction_invalid", message);
5
5
  }
6
+ function hasCurrentNarrowInteraction(state, type) {
7
+ const questions = new Map(state.events.filter((item) => item.kind === "question").map((item) => [String(item.id), item]));
8
+ return [
9
+ ...currentFoundryQuestions(state),
10
+ ...currentFoundryInvestigations(state),
11
+ ...currentFoundryAssumptions(state),
12
+ ...currentFoundryDecisions(state).map((item) => questions.get(String(item.question_id))),
13
+ ].some((item) => item?.dataset_type === type && Object.hasOwn(item, "object_scope"));
14
+ }
6
15
  /** Bind a semantic proposal to the latest applicable user choices without treating them as data proof. */
7
16
  export function verifyFoundrySemanticInteraction(input, interaction, selectedScopes) {
8
17
  if ((input.interaction_sha256 ?? null) !== (interaction?.sha256 ?? null))
9
18
  fail("Semantic input must name the current registered interaction state.");
10
19
  const result = [];
11
20
  for (const part of input.submissions) {
12
- const type = selectedScopes.get(part.authoring_task_sha256);
13
- if (!type)
21
+ const selected = selectedScopes.get(part.authoring_task_sha256);
22
+ if (!selected)
14
23
  fail("Semantic work is not in the current assessed scope.");
24
+ const objects = typeof selected === "string"
25
+ ? null
26
+ : Array.isArray(selected)
27
+ ? selected
28
+ : [selected];
29
+ const type = typeof selected === "string" ? selected : objects?.[0]?.dataset_type;
30
+ if (!type)
31
+ fail("Semantic work has no verified current dataset type.");
32
+ if (objects) {
33
+ const keys = new Set();
34
+ for (const object of objects) {
35
+ if (object.dataset_type !== type ||
36
+ !object.entity_id ||
37
+ !object.version ||
38
+ keys.has(JSON.stringify([type, object.entity_id, object.version])))
39
+ fail("Semantic work has missing, mixed or duplicate current object identities.");
40
+ keys.add(JSON.stringify([type, object.entity_id, object.version]));
41
+ }
42
+ }
43
+ const expectedByObject = objects?.map((object) => interaction
44
+ ? currentFoundryDecisionsForObject(interaction.state, type, object.entity_id, object.version).map((decision) => String(decision.decision_id))
45
+ : []);
15
46
  const expected = interaction
16
- ? currentFoundryDecisionsForType(interaction.state, type).map((decision) => String(decision.decision_id))
47
+ ? objects
48
+ ? [...new Set(expectedByObject.flat())]
49
+ : currentFoundryDecisionsForType(interaction.state, type).map((decision) => String(decision.decision_id))
17
50
  : [];
18
51
  const actual = part.decision_ids ?? [];
19
52
  if (expected.length !== actual.length ||
@@ -21,18 +54,35 @@ export function verifyFoundrySemanticInteraction(input, interaction, selectedSco
21
54
  actual.some((id) => !expected.includes(id)))
22
55
  fail("Semantic work must name exactly the current applicable user decision ids.");
23
56
  if (interaction) {
24
- const unresolved = [
25
- ...currentFoundryQuestions(interaction.state),
26
- ...currentFoundryInvestigations(interaction.state),
27
- ];
28
- if (unresolved.some((item) => foundryInteractionScopeApplies(item.dataset_type, type)))
57
+ const unresolved = objects
58
+ ? objects.flatMap((object) => [
59
+ ...currentFoundryQuestionsForObject(interaction.state, type, object.entity_id, object.version),
60
+ ...currentFoundryInvestigationsForObject(interaction.state, type, object.entity_id, object.version),
61
+ ])
62
+ : [
63
+ ...currentFoundryQuestions(interaction.state),
64
+ ...currentFoundryInvestigations(interaction.state),
65
+ ].filter((item) => foundryInteractionScopeApplies(item.dataset_type, type));
66
+ if (unresolved.length)
29
67
  fail("Resolve or investigate the current decision gap before applying dependent semantic work.");
68
+ if (!objects && hasCurrentNarrowInteraction(interaction.state, type))
69
+ fail("A multi-object semantic owner cannot prove the applicable object decision scope.");
70
+ }
71
+ if (objects) {
72
+ for (const [index, object] of objects.entries())
73
+ result.push(Object.freeze({
74
+ work_item_sha256: part.authoring_task_sha256,
75
+ dataset_type: type,
76
+ decision_ids: Object.freeze([...(expectedByObject?.[index] ?? [])]),
77
+ object_scope: Object.freeze({ entity_id: object.entity_id, version: object.version }),
78
+ }));
30
79
  }
31
- result.push(Object.freeze({
32
- work_item_sha256: part.authoring_task_sha256,
33
- dataset_type: type,
34
- decision_ids: Object.freeze([...expected]),
35
- }));
80
+ else
81
+ result.push(Object.freeze({
82
+ work_item_sha256: part.authoring_task_sha256,
83
+ dataset_type: type,
84
+ decision_ids: Object.freeze([...expected]),
85
+ }));
36
86
  }
37
87
  return Object.freeze(result);
38
88
  }
@@ -6,11 +6,11 @@ export const TIANGONG_LCA_CLI_TIDAS_SOURCE_SCHEMA = "tiangong-lca.cli-tidas-spec
6
6
  const expectedSource = Object.freeze({
7
7
  schema: TIANGONG_LCA_CLI_TIDAS_SOURCE_SCHEMA,
8
8
  spec_repository: "tiangong-lca/tidas-spec",
9
- spec_commit: "d4cb089c753ffd20b173db2e56fb553a364f48f4",
10
- spec_version: "0.2.1",
9
+ spec_commit: "f118660dbcbfbf736be74837cce0bf26cd177245",
10
+ spec_version: "0.2.3",
11
11
  source_repository: "https://github.com/tiangong-lca/tidas-toolkit",
12
12
  source_commit: "9c0d8b1c8ceb1841074f5bc6de5fbb7fcc9318f5",
13
- manifest_sha256: "16d4d5950496544b50cd6b1570789930da104af313a325bb9eaa466507ec6bb5",
13
+ manifest_sha256: "5b69ab859e26a253dc51c6aeee68c971d727b1f8db44128143795113fe3eee6a",
14
14
  });
15
15
  function isRecord(value) {
16
16
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -38,7 +38,7 @@ function parseSource(value) {
38
38
  value.source_repository !== expectedSource.source_repository ||
39
39
  value.source_commit !== expectedSource.source_commit ||
40
40
  value.manifest_sha256 !== expectedSource.manifest_sha256)
41
- throw new Error(`Installed ${cliPackageName} TIDAS source manifest does not match the approved spec 0.2.1 source identity.`);
41
+ throw new Error(`Installed ${cliPackageName} TIDAS source manifest does not match the approved spec 0.2.3 source identity.`);
42
42
  if (!Array.isArray(value.schemas) || value.schemas.length !== 18)
43
43
  throw new Error(`Installed ${cliPackageName} TIDAS source manifest must enumerate exactly 18 schemas.`);
44
44
  const schemas = value.schemas.map((entry, index) => {
@@ -10,11 +10,13 @@ import { readTaskBytes } from "./foundry-task-io.js";
10
10
  import { deriveTaskAuthorizationGrant, validateTaskAuthorization } from "./task-authorization.js";
11
11
  import { sha256Json } from "./identity-preflight-proof.js";
12
12
  import { completedOwnerScopes } from "./foundry-owner-execution-store.js";
13
+ import { assertFoundryInteractionWriteReady } from "./foundry-workflow-object-scope.js";
13
14
  const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
14
15
  function invalid(message) {
15
16
  throw new FoundryContextError("authorization_continuation_invalid", message);
16
17
  }
17
18
  export async function continueFoundryPreparedApproval(context, qualified, entries, approval, authentication = { mode: "oauth" }) {
19
+ assertFoundryInteractionWriteReady(context, entries);
18
20
  const state = currentWorkflowState(context, entries), finalization = state.finalization;
19
21
  if (!finalization || approval.value.input_kind !== "current_rows")
20
22
  invalid("Select current prepared-row approval evidence.");
@@ -69,6 +71,7 @@ export async function continueFoundryPreparedApproval(context, qualified, entrie
69
71
  const identity = verifyFoundryRuntimeIdentity(context, authentication, process.env, qualified);
70
72
  const pointer = digest(readTaskBytes(context, "authorization.json"));
71
73
  const current = (index) => {
74
+ assertFoundryInteractionWriteReady(context, index);
72
75
  const now = currentWorkflowState(context, index);
73
76
  if (now.finalization?.entry.sha256 !== finalization.entry.sha256)
74
77
  invalid("Finalization changed during prepared-approval continuation.");
@@ -7,6 +7,7 @@ import { copyFoundryIsolatedExecutable } from "./foundry-runtime-environment.js"
7
7
  import { createFoundryIsolatedChildEnvironment } from "./foundry-runtime-environment.js";
8
8
  import { runFoundryTaskOperation } from "./foundry-task-store.js";
9
9
  import { runTidasRowsValidation } from "./tidas-adapter.js";
10
+ import { nativeFailureFileName, nativeFailureResultName, nativeValidationFailureEvidence, } from "./foundry-native-validation-failure.js";
10
11
  import { runDatasetCurationGate } from "./import-curation/curation-gate.js";
11
12
  import { runDatasetAuthoringTaskBuild } from "./import-curation/authoring-packages.js";
12
13
  import { routeFoundryDecisionAction } from "./foundry-decision-routing.js";
@@ -383,8 +384,32 @@ export function assessFoundryWorkflowRows(context, qualified, rowsReport, contex
383
384
  },
384
385
  environment,
385
386
  });
386
- if (typeof schema.report_file !== "string")
387
- throw new FoundryContextError("workflow_schema_failed", "Native validation returned no compatible report.");
387
+ if (typeof schema.report_file !== "string") {
388
+ const evidence = nativeValidationFailureEvidence(schema, set.type, set.file, captureFoundryInput(set.file).sha256, Number(set.count));
389
+ const evidenceFile = path.join(output, set.type, nativeFailureFileName);
390
+ operation.writeJson(evidenceFile, evidence);
391
+ const result = {
392
+ schema: "tiangong-foundry.assessment-failure.v1",
393
+ status: "blocked",
394
+ task_id: context.taskId,
395
+ rows_report: rowsReport,
396
+ rows_report_sha256: captureFoundryInput(rowsReport).sha256,
397
+ rows_file: set.file,
398
+ rows_file_sha256: evidence.rows_sha256,
399
+ row_count: evidence.row_count,
400
+ dataset_type: set.type,
401
+ exit_code: evidence.exit_code,
402
+ exit_class: evidence.exit_class,
403
+ diagnostic_code: evidence.diagnostic_code,
404
+ diagnostic_message: evidence.diagnostic_message,
405
+ evidence_file: evidenceFile,
406
+ evidence_sha256: "",
407
+ };
408
+ result.evidence_sha256 = captureFoundryInput(evidenceFile).sha256;
409
+ operation.writeJson(path.join(output, nativeFailureResultName), result);
410
+ registerWorkflowStageFiles(context, operation, output);
411
+ return result;
412
+ }
388
413
  const qaDir = path.join(output, set.type, "qa");
389
414
  let qaReport;
390
415
  if (["flow", "process", "lifecyclemodel"].includes(set.type)) {
@@ -19,9 +19,11 @@ import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.j
19
19
  import { foundryRepairSelection, readFoundryRepairPreparation } from "./foundry-workflow-repair.js";
20
20
  import { createFoundryRepairHandoffPlan } from "./foundry-repair-handoff.js";
21
21
  import { readTaskJson } from "./foundry-task-io.js";
22
+ import { assertFoundryInteractionWriteReady } from "./foundry-workflow-object-scope.js";
22
23
  export async function authorizeFoundryWorkflow(context, qualified, entries, selected, authentication = { mode: "oauth" }) {
23
24
  assertSelectedAuthorizationInput(selected);
24
25
  assertQualifiedFoundryRuntime(context, qualified);
26
+ assertFoundryInteractionWriteReady(context, entries);
25
27
  const state = currentWorkflowState(context, entries), spec = selected.spec;
26
28
  if (spec.input_kind === "repair_rows")
27
29
  return authorizeFoundryRepair(context, qualified, entries, selected, authentication, state);
@@ -61,6 +63,7 @@ export async function authorizeFoundryWorkflow(context, qualified, entries, sele
61
63
  const grant = JSON.parse(readSelectedSemanticBytes(selected.grant).toString("utf8"));
62
64
  const current = (index) => {
63
65
  assertSelectedAuthorizationInput(selected);
66
+ assertFoundryInteractionWriteReady(context, index);
64
67
  if (currentWorkflowState(context, index).finalization?.entry.sha256 !== finalization.entry.sha256)
65
68
  throw new FoundryContextError("authorization_finalization_changed", "Finalization changed before approval activation.");
66
69
  };
@@ -4,6 +4,8 @@ import { runFoundryTaskOperation } from "./foundry-task-store.js";
4
4
  import { advanceFoundryInteractionState, assertSelectedFoundryInteractionInput, currentFoundryInteractionState, FOUNDRY_INTERACTION_COMMAND, FOUNDRY_INTERACTION_REPORT, readSelectedFoundryInteractionBytes, } from "./foundry-interaction-input.js";
5
5
  import { readWorkflowArtifact } from "./foundry-workflow-state.js";
6
6
  import { createWorkflowStageDirectory } from "./foundry-workflow-io.js";
7
+ import { sha256Json } from "./identity-preflight-proof.js";
8
+ import { currentFoundryObjectScopes, currentFoundryNarrowObjects, requireCurrentFoundryObjectScope, verifiedFoundryObjectProofs, } from "./foundry-workflow-object-scope.js";
7
9
  const resultName = "interaction-result.json";
8
10
  function priorSubmission(context, entries, sha256) {
9
11
  for (const entry of [...entries].reverse()) {
@@ -27,7 +29,8 @@ export async function recordFoundryInteractionInput(context, entries, selected,
27
29
  ...context.inputs.map((fact) => fact.sha256),
28
30
  ...entries.map((entry) => entry.sha256),
29
31
  ]);
30
- const accepted = advanceFoundryInteractionState(current?.state ?? null, selected.spec, currentSha, known, new Set(targetEntities));
32
+ const newObjectScope = selected.spec.events.some((item) => Object.hasOwn(item, "object_scope"));
33
+ const accepted = advanceFoundryInteractionState(current?.state ?? null, selected.spec, currentSha, known, new Set(targetEntities), newObjectScope ? verifiedFoundryObjectProofs(context, entries) : new Set());
31
34
  return runFoundryTaskOperation(context, {
32
35
  command: FOUNDRY_INTERACTION_COMMAND,
33
36
  options: {
@@ -35,11 +38,27 @@ export async function recordFoundryInteractionInput(context, entries, selected,
35
38
  expected_state_sha256: currentSha,
36
39
  },
37
40
  validateCurrent(index) {
38
- if (index.some((entry) => ["dataset-workflow-execution-prepare", "dataset-workflow-execution-consume"].includes(entry.command)))
39
- throw new FoundryContextError("interaction_after_approval", "Preserve the approved or attempted scope; a changed decision needs a separately reviewed task revision.");
41
+ if (index.some((entry) => [
42
+ "dataset-workflow-authorization",
43
+ "dataset-workflow-execution-prepare",
44
+ "dataset-workflow-execution-consume",
45
+ ].includes(entry.command)))
46
+ throw new FoundryContextError("interaction_after_approval", "Preserve the authorized or attempted scope; a changed decision needs a separately reviewed task revision.");
40
47
  const present = currentFoundryInteractionState(context, index);
41
48
  if ((present?.entry.sha256 ?? null) !== currentSha)
42
49
  throw new FoundryContextError("interaction_state_changed", "Interaction state changed before this input acquired the task lock.");
50
+ if (accepted.events.some((item) => Object.hasOwn(item, "object_scope"))) {
51
+ const objects = currentFoundryObjectScopes(context, index);
52
+ for (const item of currentFoundryNarrowObjects(accepted)) {
53
+ requireCurrentFoundryObjectScope(context, index, accepted, objects, item.dataset_type, item.entity_id, item.version);
54
+ }
55
+ }
56
+ const rechecked = advanceFoundryInteractionState(present?.state ?? null, selected.spec, currentSha, new Set([
57
+ ...context.inputs.map((fact) => fact.sha256),
58
+ ...index.map((item) => item.sha256),
59
+ ]), new Set(targetEntities), newObjectScope ? verifiedFoundryObjectProofs(context, index) : new Set());
60
+ if (sha256Json(rechecked) !== sha256Json(accepted))
61
+ throw new FoundryContextError("interaction_state_changed", "Object scope or current row evidence changed before this input acquired the task lock.");
43
62
  },
44
63
  }, (operation) => {
45
64
  assertSelectedFoundryInteractionInput(selected);