@tiangong-lca/foundry 0.1.18 → 0.1.19

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 (84) hide show
  1. package/docs/package-distribution-contract.md +5 -5
  2. package/docs/public-runtime-contract.md +12 -0
  3. package/docs/runtime-context-contract.md +2 -0
  4. package/package-dist/assets/foundry-package-descriptor.json +268 -98
  5. package/package-dist/scripts/foundry-facade.js +3 -0
  6. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  7. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  8. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  9. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  10. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  11. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  12. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  13. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  14. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  15. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  16. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  17. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  18. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  19. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  20. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  21. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  22. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  23. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  24. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  25. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  26. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  27. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  28. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  29. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  30. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  31. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  32. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  33. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  34. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  35. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  36. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  37. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  38. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  39. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  40. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  41. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  42. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  43. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  44. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  45. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  46. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  47. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  48. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  49. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  50. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  51. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  52. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  53. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  54. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  55. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  56. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  57. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  58. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  59. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  60. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  61. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  62. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  63. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  64. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  65. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  66. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  67. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  68. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  69. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  70. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  71. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  72. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  73. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  74. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  75. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  76. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  77. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  78. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  79. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  80. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  81. package/package.json +2 -2
  82. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  83. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  84. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -1,4 +1,6 @@
1
1
  import path from "node:path";
2
+ import { isEdgeSupportPlan } from "./foundry-edge-support-plan.js";
3
+ import { sha256Json } from "./identity-preflight-proof.js";
2
4
  import { commandSpecOptionValue } from "@tiangong-lca/cli/command-spec";
3
5
  import { captureFoundryInput, FoundryContextError, resolveFoundryInputPath, } from "./foundry-runtime-context.js";
4
6
  import { readTaskJson } from "./foundry-task-io.js";
@@ -28,11 +30,20 @@ export function assertFoundryRepairExecution(context, entries, request) {
28
30
  const approval = readWorkflowArtifact(context, approvalEntry).value;
29
31
  const selection = foundryRepairSelection(context);
30
32
  const candidate = captureFoundryInput(resolveFoundryInputPath(context, selection.candidate));
31
- const contractFile = commandSpecOptionValue(request.content.commit, "--execution-contract");
33
+ const edge = isEdgeSupportPlan(request.content.commit) ? request.content.commit : null;
34
+ const contractFile = edge
35
+ ? edge.update?.contract.path
36
+ : commandSpecOptionValue(request.content.commit, "--execution-contract");
32
37
  if (!contractFile)
33
38
  return fail();
34
39
  const contract = captureFoundryInput(contractFile);
35
- const expectedContract = workflowObject(workflowObject(preparation.value.inputs).contract);
40
+ const inputs = workflowObject(preparation.value.inputs);
41
+ const expectedContract = workflowObject(inputs.contract);
42
+ if (edge &&
43
+ (!edge.update ||
44
+ sha256Json(edge.update.preparation) !== sha256Json(captureFoundryInput(preparation.file)) ||
45
+ sha256Json(edge.update.before) !== sha256Json(inputs.before)))
46
+ return fail();
36
47
  if (job.target_profile !== "generic" ||
37
48
  handoff.repair_scope !== true ||
38
49
  preparation.value.status !== "prepared" ||
@@ -7,3 +7,5 @@ export interface FoundryIsolatedChildEnvironmentOptions {
7
7
  }
8
8
  export declare function copyFoundryIsolatedExecutable(sourcePath: string, targetPath: string): void;
9
9
  export declare function createFoundryIsolatedChildEnvironment({ tempRoot, sourceEnv, overrides, }: FoundryIsolatedChildEnvironmentOptions): NodeJS.ProcessEnv;
10
+ /** Node 24 uses a fixed PATH_MAX buffer for os.homedir() on Windows. */
11
+ export declare function withFoundryIsolatedLocalCliEnvironment<T>(tempRoot: string, run: (environment: NodeJS.ProcessEnv) => T): T;
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import os from "node:os";
2
3
  import path from "node:path";
3
4
  import process from "node:process";
4
5
  export const runtimeEnvFilePolicyKey = "FOUNDRY_RUNTIME_ENV_FILE_POLICY";
@@ -88,3 +89,20 @@ export function createFoundryIsolatedChildEnvironment({ tempRoot, sourceEnv = pr
88
89
  }
89
90
  return environment;
90
91
  }
92
+ /** Node 24 uses a fixed PATH_MAX buffer for os.homedir() on Windows. */
93
+ export function withFoundryIsolatedLocalCliEnvironment(tempRoot, run) {
94
+ const fitsWindowsHome = (root) => Buffer.byteLength(path.join(root, "home")) < 260;
95
+ if (process.platform !== "win32" || fitsWindowsHome(tempRoot))
96
+ return run(createFoundryIsolatedChildEnvironment({ tempRoot }));
97
+ const base = os.tmpdir();
98
+ const prefix = path.join(base, "foundry-cli-");
99
+ if (!fitsWindowsHome(`${prefix}XXXXXX`))
100
+ throw new Error("Windows temporary directory is too long for an isolated CLI user profile.");
101
+ const shortRoot = fs.mkdtempSync(prefix);
102
+ try {
103
+ return run(createFoundryIsolatedChildEnvironment({ tempRoot: shortRoot }));
104
+ }
105
+ finally {
106
+ fs.rmSync(shortRoot, { recursive: true, force: true });
107
+ }
108
+ }
@@ -3,6 +3,7 @@ import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts
3
3
  import { type AuthIdentityReceipt } from "./identity-preflight-proof.ts";
4
4
  import { type FoundryAuthentication } from "./foundry-authentication-environment.ts";
5
5
  export type { FoundryPublicOAuthConfiguration, FoundryAuthentication, } from "./foundry-authentication-environment.ts";
6
+ export declare function readFoundryCliIdentityResult(stdout: string, packageVersion: string): unknown;
6
7
  export interface VerifiedFoundryIdentity {
7
8
  readonly receipt: AuthIdentityReceipt;
8
9
  readonly workspaceId: string;
@@ -7,6 +7,24 @@ import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.
7
7
  import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
8
8
  import { parseFreshIntentBoundAuthReceipt, } from "./identity-preflight-proof.js";
9
9
  import { createFoundryAuthenticationEnvironment, } from "./foundry-authentication-environment.js";
10
+ function resultRecord(value) {
11
+ if (!value || typeof value !== "object" || Array.isArray(value))
12
+ throw new Error("CLI identity result must be an object.");
13
+ return value;
14
+ }
15
+ export function readFoundryCliIdentityResult(stdout, packageVersion) {
16
+ const value = JSON.parse(stdout);
17
+ if (packageVersion !== "0.4.0")
18
+ return value;
19
+ const envelope = resultRecord(value);
20
+ if (envelope.schemaVersion !== 1 ||
21
+ envelope.operation !== "auth identity-receipt" ||
22
+ envelope.status !== "completed" ||
23
+ envelope.outcome !== "identity_verified" ||
24
+ envelope.error !== null)
25
+ throw new Error("Expected a completed CLI identity receipt.");
26
+ return resultRecord(envelope.data).receipt;
27
+ }
10
28
  const verifiedIdentities = new WeakSet();
11
29
  const maxAgeMs = 60_000;
12
30
  function reject(code, message) {
@@ -64,7 +82,7 @@ export function verifyFoundryRuntimeIdentity(context, authentication = { mode: "
64
82
  reject("needs_auth", "The owner CLI could not verify the intended task account.");
65
83
  let receipt;
66
84
  try {
67
- receipt = parseFreshIntentBoundAuthReceipt(JSON.parse(result.stdout), {
85
+ receipt = parseFreshIntentBoundAuthReceipt(readFoundryCliIdentityResult(result.stdout, cli.packageVersion), {
68
86
  nowMs: Date.now(),
69
87
  maxAgeMs,
70
88
  expectedProjectRef: account.projectRef,
@@ -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.28" || cli.platform !== context.platform)
161
- fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.1.28 C1 runtime on the selected platform.");
160
+ if (cli.package.version !== "0.4.0" || cli.platform !== context.platform)
161
+ fail("runtime_cli_unqualified", "Foundry requires the exact CLI 0.4.0 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.");
@@ -1,4 +1,5 @@
1
1
  import { type TiangongLcaCliTidasSchemaSource } from "./foundry-tidas-source.ts";
2
+ export declare const tiangongLcaCliPackageVersion = "0.4.0";
2
3
  export interface InstalledTiangongLcaCliPackage {
3
4
  packageName: string;
4
5
  packageVersion: string;
@@ -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.28";
12
+ export const tiangongLcaCliPackageVersion = "0.4.0";
13
13
  const tiangongLcaCliBinName = "tiangong-lca";
14
14
  const { repoRoot: foundryRepoRoot } = resolveFoundryRuntimePaths(import.meta.url);
15
15
  function isRecord(value) {
@@ -0,0 +1,76 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ type RecordValue = Record<string, unknown>;
4
+ type PatchDestinations = {
5
+ input: string;
6
+ patch: string;
7
+ output: string;
8
+ directory: string;
9
+ writeJson: (file: string, value: unknown) => void;
10
+ writeText: (file: string, value: string) => void;
11
+ };
12
+ type PatchExecution = {
13
+ readInput: (file: string) => Buffer;
14
+ readResult: (file: string) => Buffer;
15
+ workspace: string;
16
+ run: (argv: string[]) => {
17
+ exit: number;
18
+ report: RecordValue;
19
+ validate: <T>(check: () => T) => T;
20
+ };
21
+ };
22
+ export declare function applyFoundryTypedAuthoringPatch(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, temporary: string, options: PatchDestinations & {
23
+ type: string;
24
+ packageDirectory: string;
25
+ }): {
26
+ report: {
27
+ schema_version: number;
28
+ generated_at_utc: string;
29
+ status: string;
30
+ input_path: string;
31
+ patch_path: string;
32
+ out_path: string;
33
+ row_count: number;
34
+ patch_count: number;
35
+ operation_count: number;
36
+ applied_operation_count: number;
37
+ evidence_count: number;
38
+ closed_action_item_count: number;
39
+ blockers: RecordValue[];
40
+ files: {
41
+ report: string;
42
+ patched_rows: string;
43
+ patch_evidence: string;
44
+ };
45
+ };
46
+ exit: number;
47
+ };
48
+ export declare function applyTypedAuthoringPatch(options: PatchDestinations & {
49
+ type?: string;
50
+ packageDirectory?: string;
51
+ requirePackage: boolean;
52
+ requireClosure: boolean;
53
+ }, execution: PatchExecution): {
54
+ report: {
55
+ schema_version: number;
56
+ generated_at_utc: string;
57
+ status: string;
58
+ input_path: string;
59
+ patch_path: string;
60
+ out_path: string;
61
+ row_count: number;
62
+ patch_count: number;
63
+ operation_count: number;
64
+ applied_operation_count: number;
65
+ evidence_count: number;
66
+ closed_action_item_count: number;
67
+ blockers: RecordValue[];
68
+ files: {
69
+ report: string;
70
+ patched_rows: string;
71
+ patch_evidence: string;
72
+ };
73
+ };
74
+ exit: number;
75
+ };
76
+ export {};
@@ -0,0 +1,237 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readFoundryInput } from "./foundry-runtime-context.js";
4
+ import { datasetIdentity, detectDatasetType } from "./import-curation/internal/dataset-payload.js";
5
+ import { readRows } from "./import-curation/internal/runtime-io.js";
6
+ import { operationHasEvidence, patchPayloadPatchSets, patchSetAuthoringPackage, patchSetDatasetId, patchSetOperations, } from "./import-curation/internal/workflow-authoring-tasks.js";
7
+ import { operationClosureKeys, taskActionItemKeys, } from "./import-curation/internal/workflow-patch-evidence.js";
8
+ import { assertWorkflowReportArtifact, runWorkflowLocalCliResult } from "./foundry-workflow-io.js";
9
+ import { workflowObject } from "./foundry-workflow-state.js";
10
+ import { sha256Text } from "./identity-preflight-proof.js";
11
+ export function applyFoundryTypedAuthoringPatch(context, qualified, temporary, options) {
12
+ return applyTypedAuthoringPatch({ ...options, requirePackage: true, requireClosure: true }, {
13
+ readInput: (file) => readFoundryInput(context, file),
14
+ readResult: (file) => fs.readFileSync(assertWorkflowReportArtifact(context, file, options.directory)),
15
+ workspace: options.directory,
16
+ run: (argv) => runWorkflowLocalCliResult(context, qualified, temporary, argv),
17
+ });
18
+ }
19
+ export function applyTypedAuthoringPatch(options, execution) {
20
+ const rows = readRows(options.input, (file) => execution.readInput(file).toString("utf8"));
21
+ const patches = patchPayloadPatchSets(JSON.parse(fs.readFileSync(options.patch, "utf8")));
22
+ const candidates = [...rows];
23
+ const blockers = [];
24
+ const evidence = [];
25
+ let operationCount = 0;
26
+ if (!patches.length)
27
+ blockers.push({
28
+ code: "patch_payload_invalid",
29
+ message: "At least one dataset patch set is required.",
30
+ });
31
+ for (const [patchIndex, raw] of patches.entries()) {
32
+ const patch = workflowObject(raw);
33
+ const packageName = patchSetAuthoringPackage(patch);
34
+ const declaredId = patchSetDatasetId(patch);
35
+ const declaredVersion = patch.dataset_version ?? patch.version;
36
+ const declaredIndex = patch.row_index ?? patch.rowIndex;
37
+ if ((!packageName || !options.packageDirectory) &&
38
+ (options.requirePackage || options.requireClosure)) {
39
+ blockers.push({ code: "authoring_package_required", patch_index: patchIndex });
40
+ continue;
41
+ }
42
+ const packageBytes = packageName && options.packageDirectory
43
+ ? execution.readInput(path.join(options.packageDirectory, path.basename(packageName)))
44
+ : null;
45
+ const authoring = packageBytes
46
+ ? workflowObject(JSON.parse(packageBytes.toString("utf8")))
47
+ : null;
48
+ const packageId = authoring?.entity_id ?? authoring?.process_id;
49
+ const packageVersion = authoring?.version;
50
+ const matches = rows.flatMap((row, index) => {
51
+ const type = options.type ?? detectDatasetType(row);
52
+ if (!type)
53
+ return [];
54
+ const identity = datasetIdentity(row, index, type);
55
+ const expectedIndex = authoring ||
56
+ declaredIndex === undefined ||
57
+ (/^\d+$/u.test(String(declaredIndex)) && Number(declaredIndex) === index);
58
+ const expectedId = !declaredId || identity.id === declaredId;
59
+ const expectedVersion = declaredVersion === undefined || identity.version === declaredVersion;
60
+ const expectedPackage = !authoring || (identity.id === packageId && identity.version === packageVersion);
61
+ return expectedIndex && expectedId && expectedVersion && expectedPackage
62
+ ? [{ index, identity, type }]
63
+ : [];
64
+ });
65
+ const selected = matches[0];
66
+ const reject = (code, message) => blockers.push({
67
+ code,
68
+ message,
69
+ patch_index: patchIndex,
70
+ row_index: selected?.index,
71
+ dataset_id: selected?.identity.id ?? declaredId,
72
+ dataset_version: selected?.identity.version ?? declaredVersion,
73
+ });
74
+ const contradictoryIndex = authoring &&
75
+ declaredIndex !== undefined &&
76
+ (!/^\d+$/u.test(String(declaredIndex)) || Number(declaredIndex) !== selected?.index);
77
+ if (matches.length !== 1 ||
78
+ contradictoryIndex ||
79
+ (!authoring && !declaredId && declaredIndex === undefined)) {
80
+ reject("authoring_patch_scope_mismatch", "Select one exact dataset row and its required authoring package.");
81
+ continue;
82
+ }
83
+ const { index: rowIndex, identity: { id, version }, type, } = selected;
84
+ const operationName = `dataset ${type === "lifecyclemodel" ? "model" : type} patch`;
85
+ const rawOperations = patchSetOperations(patch);
86
+ if (!rawOperations?.length) {
87
+ reject("patch_operations_missing", "Authoring patch must contain an operation.");
88
+ continue;
89
+ }
90
+ operationCount += rawOperations.length;
91
+ const required = taskActionItemKeys({
92
+ ...authoring,
93
+ action_items: Array.isArray(authoring?.action_items)
94
+ ? authoring.action_items.filter((value) => {
95
+ const item = workflowObject(value);
96
+ return (item.ai_required !== false &&
97
+ ![
98
+ "identity_decision_authoring",
99
+ "classification_decision_authoring",
100
+ "location_decision_authoring",
101
+ ].includes(String(item.action_kind ?? item.actionKind)));
102
+ })
103
+ : [],
104
+ });
105
+ const closed = rawOperations.flatMap((item) => item.op === "test" ? [] : operationClosureKeys(item));
106
+ const matchesClosure = (left, right) => {
107
+ const [leftCode, leftPath] = left.split("\u0000");
108
+ const [rightCode, rightPath] = right.split("\u0000");
109
+ return leftCode === rightCode && (!leftPath || !rightPath || leftPath === rightPath);
110
+ };
111
+ if (options.requireClosure &&
112
+ (closed.some((closure) => !required.some((item) => matchesClosure(closure, item))) ||
113
+ required.some((item) => !closed.some((closure) => matchesClosure(closure, item))))) {
114
+ reject("authoring_action_item_closure_invalid", "Patch closure must match the selected authoring package.");
115
+ continue;
116
+ }
117
+ if (rawOperations.some((item) => item.op !== "test" && !operationHasEvidence(item))) {
118
+ reject("patch_evidence_required", "Each mutation needs its source evidence or basis.");
119
+ continue;
120
+ }
121
+ const row = workflowObject(candidates[rowIndex]);
122
+ const original = datasetIdentity(row, rowIndex, type);
123
+ const wrapper = original.payload === row
124
+ ? null
125
+ : Object.keys(row).find((name) => row[name] === original.payload);
126
+ const prefix = wrapper ? `/${wrapper}` : "";
127
+ const operations = rawOperations.map((item) => {
128
+ const operation = workflowObject(item);
129
+ const location = typeof operation.path === "string" ? operation.path : "";
130
+ return {
131
+ op: operation.op,
132
+ path: location.startsWith(prefix + "/") ? location.slice(prefix.length) : null,
133
+ ...(Object.hasOwn(operation, "value") ? { value: operation.value } : {}),
134
+ ...(operation.op === "test"
135
+ ? {}
136
+ : {
137
+ basis: typeof operation.basis === "string" && operation.basis.trim()
138
+ ? operation.basis
139
+ : "Source evidence retained in the selected Foundry authoring patch.",
140
+ }),
141
+ };
142
+ });
143
+ if (operations.some((operation) => operation.path === null)) {
144
+ reject("patch_path_invalid", "Authoring patch pointer must select a field inside the dataset payload.");
145
+ continue;
146
+ }
147
+ const input = path.join(execution.workspace, `request-${patchIndex + 1}.json`);
148
+ const output = path.join(execution.workspace, `result-${patchIndex + 1}.json`);
149
+ options.writeJson(input, {
150
+ content: original.payload,
151
+ expectedDigest: sha256Text(JSON.stringify(original.payload)),
152
+ operations,
153
+ });
154
+ const result = execution.run([
155
+ ...operationName.split(" "),
156
+ "--input",
157
+ input,
158
+ "--output",
159
+ output,
160
+ "--json",
161
+ ]);
162
+ if (result.exit !== 0) {
163
+ const error = workflowObject(result.report.error);
164
+ reject(String(error.code), String(error.message));
165
+ continue;
166
+ }
167
+ const content = result.validate(() => {
168
+ const bytes = execution.readResult(output);
169
+ const payload = workflowObject(JSON.parse(bytes.toString("utf8")));
170
+ const identity = datasetIdentity(payload, rowIndex, type);
171
+ const artifact = Array.isArray(result.report.artifacts)
172
+ ? workflowObject(result.report.artifacts[0])
173
+ : {};
174
+ if (result.report.schemaVersion !== 1 ||
175
+ result.report.operation !== operationName ||
176
+ result.report.status !== "completed" ||
177
+ result.report.outcome !== "content_processed" ||
178
+ result.report.error !== null ||
179
+ artifact.path !== output ||
180
+ artifact.purpose !== "complete_result" ||
181
+ artifact.bytes !== bytes.length ||
182
+ workflowObject(result.report.data).contentDigest !== sha256Text(JSON.stringify(payload)) ||
183
+ identity.id !== id ||
184
+ identity.version !== version)
185
+ throw new Error("Typed patch receipt does not bind the exact output and selected row.");
186
+ return payload;
187
+ });
188
+ candidates[rowIndex] = wrapper ? { ...row, [wrapper]: content } : content;
189
+ rawOperations.forEach((item, operationIndex) => {
190
+ if (item.op === "test")
191
+ return;
192
+ evidence.push({
193
+ row_index: rowIndex,
194
+ dataset_id: id,
195
+ dataset_version: version,
196
+ patch_index: patchIndex,
197
+ operation_index: operationIndex,
198
+ op: item.op,
199
+ path: item.path,
200
+ basis: item.basis ?? null,
201
+ evidence: item.evidence ?? null,
202
+ resolution: item.resolution ?? null,
203
+ authoring_package: packageName || null,
204
+ authoring_package_sha256: packageBytes ? sha256Text(packageBytes.toString("utf8")) : null,
205
+ closes_action_items: operationClosureKeys(item).map((key) => {
206
+ const [code, itemPath] = key.split("\u0000");
207
+ return { code, path: itemPath || null };
208
+ }),
209
+ });
210
+ });
211
+ }
212
+ const accepted = !blockers.length;
213
+ const reportFile = path.join(options.directory, "outputs", "dataset-patch-apply-report.json");
214
+ const evidenceFile = path.join(options.directory, "outputs", "patch-evidence.jsonl");
215
+ options.writeText(options.output, (accepted ? candidates : rows).map((row) => JSON.stringify(row) + "\n").join(""));
216
+ options.writeText(evidenceFile, accepted ? evidence.map((row) => JSON.stringify(row) + "\n").join("") : "");
217
+ const report = {
218
+ schema_version: 1,
219
+ generated_at_utc: new Date().toISOString(),
220
+ status: accepted ? "completed" : "blocked",
221
+ input_path: options.input,
222
+ patch_path: options.patch,
223
+ out_path: options.output,
224
+ row_count: rows.length,
225
+ patch_count: patches.length,
226
+ operation_count: operationCount,
227
+ applied_operation_count: accepted ? evidence.length : 0,
228
+ evidence_count: accepted ? evidence.length : 0,
229
+ closed_action_item_count: accepted
230
+ ? evidence.reduce((sum, row) => sum + row.closes_action_items.length, 0)
231
+ : 0,
232
+ blockers,
233
+ files: { report: reportFile, patched_rows: options.output, patch_evidence: evidenceFile },
234
+ };
235
+ options.writeJson(reportFile, report);
236
+ return { report, exit: accepted ? 0 : 1 };
237
+ }
@@ -0,0 +1,11 @@
1
+ export declare function createTypedContextCommand(type: string, output: string): string[];
2
+ export declare function projectTypedContext(type: string, output: string, receipt: unknown, bytes: Buffer): {
3
+ source: unknown;
4
+ manifest: Record<string, unknown>;
5
+ profile: string;
6
+ files: {
7
+ key: "methodology" | "ruleset" | "schema";
8
+ name: "methodology.yaml" | "runtime-ruleset.json" | "schema.json";
9
+ text: string;
10
+ }[];
11
+ };
@@ -0,0 +1,79 @@
1
+ import { createHash } from "node:crypto";
2
+ import { FoundryContextError } from "./foundry-runtime-context.js";
3
+ const components = [
4
+ { key: "schema", name: "schema.json" },
5
+ { key: "methodology", name: "methodology.yaml" },
6
+ { key: "ruleset", name: "runtime-ruleset.json" },
7
+ ];
8
+ function cliType(type) {
9
+ return type === "lifecyclemodel" ? "model" : type;
10
+ }
11
+ export function createTypedContextCommand(type, output) {
12
+ return [
13
+ "dataset",
14
+ cliType(type),
15
+ "contract",
16
+ "--include",
17
+ components.map(({ key }) => key).join(","),
18
+ "--output",
19
+ output,
20
+ "--json",
21
+ ];
22
+ }
23
+ function record(value) {
24
+ return value && typeof value === "object" && !Array.isArray(value)
25
+ ? value
26
+ : {};
27
+ }
28
+ function reject(message) {
29
+ throw new FoundryContextError("workflow_context_invalid", message);
30
+ }
31
+ export function projectTypedContext(type, output, receipt, bytes) {
32
+ const result = record(receipt);
33
+ const artifact = Array.isArray(result.artifacts) ? record(result.artifacts[0]) : {};
34
+ if (result.schemaVersion !== 1 ||
35
+ result.operation !== `dataset ${cliType(type)} contract` ||
36
+ result.status !== "completed" ||
37
+ result.outcome !== "contract_read" ||
38
+ artifact.path !== output ||
39
+ artifact.purpose !== "complete_result" ||
40
+ artifact.bytes !== bytes.length)
41
+ return reject("Invalid typed CLI contract receipt for the current task scope.");
42
+ let parsed;
43
+ try {
44
+ parsed = JSON.parse(bytes.toString("utf8"));
45
+ }
46
+ catch {
47
+ return reject("Typed CLI contract output must be valid JSON.");
48
+ }
49
+ const contract = record(parsed);
50
+ const manifest = record(contract.manifest);
51
+ if (!["sdk-contract-api", "sdk-runtime-assets"].includes(String(contract.source)) ||
52
+ manifest.kind !== type ||
53
+ typeof manifest.profile !== "string" ||
54
+ !Array.isArray(contract.unavailable))
55
+ return reject("Typed CLI contract manifest does not match the task dataset type.");
56
+ const payload = record(contract.components);
57
+ const files = [];
58
+ for (const { key, name } of components) {
59
+ const value = payload[key];
60
+ const fact = record(manifest[key]);
61
+ if (value === null &&
62
+ manifest[key] === null &&
63
+ contract.unavailable.includes(key) &&
64
+ key !== "schema" &&
65
+ type !== "flow" &&
66
+ type !== "process")
67
+ continue;
68
+ const text = key === "ruleset" && value && typeof value === "object" && !Array.isArray(value)
69
+ ? JSON.stringify(value, null, 2)
70
+ : value;
71
+ if (typeof text !== "string" || !text.length || contract.unavailable.includes(key))
72
+ return reject(`Typed CLI contract is missing ${key} for ${type}.`);
73
+ if (Buffer.byteLength(text) !== fact.bytes ||
74
+ createHash("sha256").update(text).digest("hex") !== fact.sha256)
75
+ return reject(`Typed CLI contract ${key} digest does not match its manifest.`);
76
+ files.push({ key, name, text });
77
+ }
78
+ return { source: contract.source, manifest, profile: manifest.profile, files };
79
+ }