@tiangong-lca/foundry 0.1.17 → 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 (162) hide show
  1. package/README.md +23 -7
  2. package/docs/architecture.md +15 -3
  3. package/docs/foundry-task-contracts.md +27 -3
  4. package/docs/package-distribution-contract.md +45 -13
  5. package/docs/public-runtime-contract.md +85 -5
  6. package/docs/runtime-context-contract.md +22 -4
  7. package/docs/task-authorization-contract.md +15 -3
  8. package/docs/workspace-migration-contract.md +5 -3
  9. package/package-dist/assets/foundry-package-descriptor.json +541 -177
  10. package/package-dist/scripts/foundry-facade.d.ts +5 -0
  11. package/package-dist/scripts/foundry-facade.js +261 -16
  12. package/package-dist/scripts/foundry-runtime.d.ts +2 -2
  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 +18 -6
  17. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  18. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  19. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +11 -1
  20. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +65 -9
  21. package/package-dist/scripts/lib/foundry-assessment-producer.d.ts +6 -0
  22. package/package-dist/scripts/lib/foundry-assessment-producer.js +167 -0
  23. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  24. package/package-dist/scripts/lib/foundry-command-metadata.js +6 -1
  25. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  26. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  27. package/package-dist/scripts/lib/foundry-decision-owners.d.ts +1 -1
  28. package/package-dist/scripts/lib/foundry-decision-owners.js +15 -7
  29. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  30. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  31. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  32. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  33. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  34. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  35. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  36. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  37. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  38. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  39. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  40. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  41. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  42. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  43. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  44. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  45. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  46. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  47. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  48. package/package-dist/scripts/lib/foundry-execution-admission.js +28 -3
  49. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  50. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  51. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  52. package/package-dist/scripts/lib/foundry-finalize-owners.js +126 -13
  53. package/package-dist/scripts/lib/foundry-identity-stage-input.d.ts +24 -0
  54. package/package-dist/scripts/lib/foundry-identity-stage-input.js +122 -0
  55. package/package-dist/scripts/lib/foundry-identity-stage-state.d.ts +17 -0
  56. package/package-dist/scripts/lib/foundry-identity-stage-state.js +48 -0
  57. package/package-dist/scripts/lib/foundry-installed-entry.d.ts +2 -0
  58. package/package-dist/scripts/lib/foundry-installed-entry.js +173 -0
  59. package/package-dist/scripts/lib/foundry-managed-adoption.d.ts +12 -0
  60. package/package-dist/scripts/lib/foundry-managed-adoption.js +108 -0
  61. package/package-dist/scripts/lib/foundry-managed-authentication.d.ts +4 -0
  62. package/package-dist/scripts/lib/foundry-managed-authentication.js +28 -0
  63. package/package-dist/scripts/lib/foundry-managed-host.js +14 -2
  64. package/package-dist/scripts/lib/foundry-migration-transfer-io.d.ts +2 -0
  65. package/package-dist/scripts/lib/foundry-migration-transfer-io.js +27 -3
  66. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  67. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  68. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  69. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  70. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  71. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  72. package/package-dist/scripts/lib/foundry-package-contract.d.ts +4 -4
  73. package/package-dist/scripts/lib/foundry-package-contract.js +10 -2
  74. package/package-dist/scripts/lib/foundry-preparation-cli-validation.d.ts +2 -0
  75. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +96 -3
  76. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  77. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  78. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  79. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  80. package/package-dist/scripts/lib/foundry-quality-review-context.d.ts +3 -0
  81. package/package-dist/scripts/lib/foundry-quality-review-context.js +18 -0
  82. package/package-dist/scripts/lib/foundry-quality-review-input.d.ts +48 -0
  83. package/package-dist/scripts/lib/foundry-quality-review-input.js +284 -0
  84. package/package-dist/scripts/lib/foundry-quality-review-lineage.d.ts +13 -0
  85. package/package-dist/scripts/lib/foundry-quality-review-lineage.js +123 -0
  86. package/package-dist/scripts/lib/foundry-quality-review.d.ts +112 -0
  87. package/package-dist/scripts/lib/foundry-quality-review.js +487 -0
  88. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  89. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  90. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  91. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  92. package/package-dist/scripts/lib/foundry-runtime-identity.js +22 -2
  93. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  94. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  95. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  96. package/package-dist/scripts/lib/foundry-task-authorization.d.ts +2 -1
  97. package/package-dist/scripts/lib/foundry-task-authorization.js +32 -11
  98. package/package-dist/scripts/lib/foundry-task-registration.js +4 -5
  99. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.d.ts +28 -0
  100. package/package-dist/scripts/lib/foundry-task-runtime-adoption-write.js +250 -0
  101. package/package-dist/scripts/lib/foundry-task-runtime-adoption.d.ts +60 -0
  102. package/package-dist/scripts/lib/foundry-task-runtime-adoption.js +549 -0
  103. package/package-dist/scripts/lib/foundry-task-store.d.ts +4 -1
  104. package/package-dist/scripts/lib/foundry-task-store.js +113 -4
  105. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -1
  106. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  107. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  108. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  109. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  110. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  111. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  112. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  113. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  114. package/package-dist/scripts/lib/foundry-validation-reference-context.d.ts +8 -0
  115. package/package-dist/scripts/lib/foundry-validation-reference-context.js +115 -0
  116. package/package-dist/scripts/lib/foundry-workflow-assessment.d.ts +1 -0
  117. package/package-dist/scripts/lib/foundry-workflow-assessment.js +165 -34
  118. package/package-dist/scripts/lib/foundry-workflow-authorization.js +99 -5
  119. package/package-dist/scripts/lib/foundry-workflow-child-failure.d.ts +44 -0
  120. package/package-dist/scripts/lib/foundry-workflow-child-failure.js +439 -0
  121. package/package-dist/scripts/lib/foundry-workflow-context.js +92 -22
  122. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  123. package/package-dist/scripts/lib/foundry-workflow-finalize.js +64 -3
  124. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.d.ts +6 -0
  125. package/package-dist/scripts/lib/foundry-workflow-identity-recovery.js +450 -0
  126. package/package-dist/scripts/lib/foundry-workflow-identity-stage.d.ts +9 -0
  127. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +717 -0
  128. package/package-dist/scripts/lib/foundry-workflow-identity.js +26 -11
  129. package/package-dist/scripts/lib/foundry-workflow-io.d.ts +7 -1
  130. package/package-dist/scripts/lib/foundry-workflow-io.js +102 -16
  131. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  132. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  133. package/package-dist/scripts/lib/foundry-workflow-semantic.js +65 -31
  134. package/package-dist/scripts/lib/foundry-workflow-state.d.ts +4 -0
  135. package/package-dist/scripts/lib/foundry-workflow-state.js +165 -22
  136. package/package-dist/scripts/lib/identity-preflight-artifacts.d.ts +4 -7
  137. package/package-dist/scripts/lib/identity-preflight-artifacts.js +18 -5
  138. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +6 -0
  139. package/package-dist/scripts/lib/identity-preflight-proof.js +92 -13
  140. package/package-dist/scripts/lib/identity-preflight-recovery-proof.d.ts +78 -0
  141. package/package-dist/scripts/lib/identity-preflight-recovery-proof.js +415 -0
  142. package/package-dist/scripts/lib/import-curation/curation-cleanup.d.ts +9 -1
  143. package/package-dist/scripts/lib/import-curation/curation-cleanup.js +39 -2
  144. package/package-dist/scripts/lib/import-curation/curation-gate.d.ts +1 -0
  145. package/package-dist/scripts/lib/import-curation/curation-gate.js +19 -1
  146. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  147. package/package-dist/scripts/lib/import-curation/internal/workflow-identity-preflight.js +11 -2
  148. package/package-dist/scripts/lib/import-curation/internal/workflow-reference-closure.js +4 -1
  149. package/package-dist/scripts/package-entry.js +2 -3
  150. package/package-dist/scripts/public-api.d.ts +5 -0
  151. package/package-dist/scripts/public-api.js +2 -0
  152. package/package-dist/scripts/runtime-entry.d.ts +2 -0
  153. package/package-dist/scripts/runtime-entry.js +42 -15
  154. package/package.json +6 -2
  155. package/specs/schemas/foundry-identity-stage-input.schema.json +47 -0
  156. package/specs/schemas/foundry-managed-adoption.schema.json +40 -0
  157. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  158. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  159. package/specs/schemas/foundry-package-descriptor.schema.json +6 -2
  160. package/specs/schemas/foundry-quality-review-draft.schema.json +271 -0
  161. package/specs/schemas/foundry-quality-review-input.schema.json +271 -0
  162. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -1,12 +1,30 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, writeFoundryArtifact, assertFoundryWorkspaceActive, } from "./foundry-runtime-context.js";
4
+ import { captureFoundryInput, resolveFoundryInputPath, resolveFoundryOutput, writeFoundryArtifact, assertFoundryWorkspaceActive, FoundryContextError, } from "./foundry-runtime-context.js";
5
5
  import { assertVerifiedFoundryIdentity, } from "./foundry-runtime-identity.js";
6
6
  import { assertFoundryTaskInputLineage, withFoundryTaskMetadata } from "./foundry-task-store.js";
7
7
  import { bytes, digest, exact, fail, object, readTaskBytes, reference, shaPattern, taskPath, } from "./foundry-task-io.js";
8
8
  import { validateTaskAuthorization, deriveTaskAuthorizationGrant, taskAuthorizationMatches, } from "./task-authorization.js";
9
9
  import { sha256Json } from "./identity-preflight-proof.js";
10
+ /** Only the trusted host can refresh identity, after the locked current snapshot is verified. */
11
+ function metadataIdentity(context, identity, qualification, refreshIdentity) {
12
+ try {
13
+ assertVerifiedFoundryIdentity(context, identity, qualification);
14
+ return identity;
15
+ }
16
+ catch (error) {
17
+ if (!refreshIdentity ||
18
+ !(error instanceof FoundryContextError) ||
19
+ error.code !== "identity_receipt_stale")
20
+ throw error;
21
+ }
22
+ const refreshed = refreshIdentity();
23
+ assertVerifiedFoundryIdentity(context, refreshed, qualification);
24
+ if (refreshed.mode !== identity.mode)
25
+ fail("identity_context_mismatch", "Identity refresh must retain the host authentication mode.");
26
+ return refreshed;
27
+ }
10
28
  function inputFact(context, file) {
11
29
  const resolved = resolveFoundryInputPath(context, file);
12
30
  return context.inputs.find((fact) => fact.path === resolved);
@@ -117,7 +135,7 @@ export async function registerFoundryTaskAuthorization(context, identity, option
117
135
  assertFoundryWorkspaceActive(context);
118
136
  assertVerifiedFoundryIdentity(context, identity, qualification);
119
137
  return withFoundryTaskMetadata(context, (task, index) => {
120
- assertVerifiedFoundryIdentity(context, identity, qualification);
138
+ identity = metadataIdentity(context, identity, qualification, options.refreshIdentity);
121
139
  options.validateCurrent?.(task, index);
122
140
  const input = inputFact(context, options.inputFile);
123
141
  const result = validateTaskAuthorization(options.grant, binding(context, task, input));
@@ -165,12 +183,12 @@ export async function registerFoundryTaskAuthorization(context, identity, option
165
183
  user_id: identity.receipt.identity.user_id,
166
184
  },
167
185
  };
168
- assertVerifiedFoundryIdentity(context, identity, qualification);
186
+ const registrationBytes = writeRegistration(context, registration);
187
+ options.validateCurrent?.(task, index);
188
+ identity = metadataIdentity(context, identity, qualification, options.refreshIdentity);
169
189
  if (validateTaskAuthorization(options.grant, binding(context, task, input)).status !==
170
190
  "authorized")
171
191
  fail("task_authorization_invalid", "Authorization expired or changed before it could be activated.");
172
- const registrationBytes = writeRegistration(context, registration);
173
- options.validateCurrent?.(task, index);
174
192
  const pointer = bytes({
175
193
  schema: "tiangong-foundry.authorization-pointer.v1",
176
194
  authorization_sha256: authorization.authorization_sha256,
@@ -183,14 +201,15 @@ export async function registerFoundryTaskAuthorization(context, identity, option
183
201
  };
184
202
  });
185
203
  }
186
- export async function loadFoundryTaskAuthorization(context, identity, inputFile, qualification) {
204
+ export async function loadFoundryTaskAuthorization(context, identity, inputFile, qualification, refreshIdentity) {
187
205
  assertVerifiedFoundryIdentity(context, identity, qualification);
188
206
  const loaded = await withFoundryTaskMetadata(context, (task) => {
189
- assertVerifiedFoundryIdentity(context, identity, qualification);
207
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
190
208
  const input = inputFact(context, inputFile);
191
209
  if (!fs.existsSync(taskPath(context, "authorization.json")))
192
210
  fail("task_authorization_required", "This task has no active registered authorization.");
193
- const pointer = object(JSON.parse(readTaskBytes(context, "authorization.json").toString("utf8")));
211
+ const pointerBytes = readTaskBytes(context, "authorization.json");
212
+ const pointer = object(JSON.parse(pointerBytes.toString("utf8")));
194
213
  exact(pointer, ["schema", "authorization_sha256", "registration_sha256"]);
195
214
  if (pointer.schema !== "tiangong-foundry.authorization-pointer.v1" ||
196
215
  typeof pointer.authorization_sha256 !== "string")
@@ -273,21 +292,23 @@ export async function loadFoundryTaskAuthorization(context, identity, inputFile,
273
292
  evidencePath !== file.path)
274
293
  fail("authorization_evidence_invalid", "Grant and selected evidence no longer agree.");
275
294
  }
276
- assertVerifiedFoundryIdentity(context, identity, qualification);
295
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
277
296
  const refreshed = validateTaskAuthorization(JSON.parse(grantBytes.toString("utf8")), binding(context, task, input));
278
297
  if (refreshed.status !== "authorized")
279
298
  fail("task_authorization_invalid", "Task authorization expired during evidence verification.");
299
+ if (!readTaskBytes(context, "authorization.json").equals(pointerBytes))
300
+ fail("authorization_update_conflict", "Approval changed during locked identity and evidence verification.");
280
301
  return {
281
302
  authorization: refreshed.authorization,
282
303
  registeredInput: registeredInput.path,
283
- pointerSha256: digest(readTaskBytes(context, "authorization.json")),
304
+ pointerSha256: digest(pointerBytes),
284
305
  inputPath: input.path,
285
306
  };
286
307
  });
287
308
  if (loaded.registeredInput !== loaded.inputPath) {
288
309
  await assertFoundryTaskInputLineage(context, loaded.registeredInput, loaded.inputPath);
289
310
  return withFoundryTaskMetadata(context, (task) => {
290
- assertVerifiedFoundryIdentity(context, identity, qualification);
311
+ identity = metadataIdentity(context, identity, qualification, refreshIdentity);
291
312
  if (digest(readTaskBytes(context, "authorization.json")) !== loaded.pointerSha256)
292
313
  fail("authorization_update_conflict", "Approval changed during equivalent-content lineage verification.");
293
314
  if (!taskAuthorizationMatches(loaded.authorization, binding(context, task, inputFact(context, inputFile))))
@@ -1,3 +1,4 @@
1
+ import { assertTaskRuntimeIdentity } from "./foundry-task-runtime-adoption.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { randomUUID } from "node:crypto";
@@ -75,9 +76,8 @@ function readRegistration(context) {
75
76
  fail("task_binding_mismatch", "Registered task belongs to another workspace or task.");
76
77
  if (job.actor_id !== context.actorId)
77
78
  fail("task_actor_mismatch", "Task actor does not match the registered task intent.");
78
- if (context.workspaceAccess === "write" &&
79
- sha256Json(job.runtime_identity) !== sha256Json(runtimeIdentity(context)))
80
- fail("task_runtime_changed", "Task runtime differs from its registration.");
79
+ if (context.workspaceAccess === "write")
80
+ assertTaskRuntimeIdentity(context, job.runtime_identity);
81
81
  if (typeof job.target_profile !== "string" ||
82
82
  (context.workspaceAccess === "write" &&
83
83
  !bytes(value.profile_lock).equals(bytes(profileLock(context, job.target_profile)))))
@@ -159,8 +159,7 @@ export function loadTask(context, options) {
159
159
  (options.profileId && options.profileId !== raw.target_profile) ||
160
160
  options.targetEntities?.some((kind) => !raw.target_entities.includes(kind)))
161
161
  fail("task_request_mismatch", "Task request, lane, profile or entity scope changed.");
162
- if (sha256Json(raw.runtime_identity) !== sha256Json(runtimeIdentity(context)))
163
- fail("task_runtime_changed", "Task runtime identity changed; use the pinned runtime or an explicit migration.");
162
+ assertTaskRuntimeIdentity(context, raw.runtime_identity);
164
163
  if (sha256Json(raw.write_policy) !== sha256Json({ mode: "dry-run", remote_state_code: 0 }))
165
164
  fail("task_write_policy_invalid", "Task metadata cannot grant remote write authority.");
166
165
  const sourceRef = reference(raw.source_manifest, "source-manifest.json");
@@ -0,0 +1,28 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { FoundryFacadeTaskRecord } from "./foundry-facade-store.ts";
3
+ import { type TrustedFoundryRuntimeAdoptionQualification } from "./foundry-task-runtime-adoption.ts";
4
+ export declare function planFoundryTaskRuntimeAdoption(context: FoundryRuntimeContext, record: FoundryFacadeTaskRecord, selection: unknown, trusted?: TrustedFoundryRuntimeAdoptionQualification): {
5
+ schema: string;
6
+ workspace_id: string | null;
7
+ task_id: string | null;
8
+ actor_id: string | null;
9
+ registration_sha256: string;
10
+ job_sha256: string;
11
+ selection: unknown;
12
+ predecessor_plan_sha256: {} | null;
13
+ successor_entry: import("./foundry-runtime-context-types.ts").FoundryInputFact;
14
+ successor_descriptor: import("./foundry-runtime-context-types.ts").FoundryInputFact;
15
+ continuation: "original_owner_recovery" | "preparation_only";
16
+ prior_context_reports: {
17
+ path: string;
18
+ bytes: number;
19
+ sha256: string;
20
+ }[];
21
+ witness: {
22
+ path: string;
23
+ bytes: number;
24
+ sha256: string;
25
+ }[];
26
+ plan_sha256: string;
27
+ };
28
+ export declare function applyFoundryTaskRuntimeAdoption(context: FoundryRuntimeContext, record: FoundryFacadeTaskRecord, value: unknown, trusted?: TrustedFoundryRuntimeAdoptionQualification): Promise<unknown>;
@@ -0,0 +1,250 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { withBatchRunLock } from "@tiangong-lca/cli/batch";
4
+ import { assertFoundryWorkspaceWrite, resolveFoundryOutput, } from "./foundry-runtime-context.js";
5
+ import { bytes, digest, fail, facts, object, readTaskBytes, reference } from "./foundry-task-io.js";
6
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ import { transferWriteOnce } from "./foundry-migration-transfer-io.js";
8
+ import { readFoundryTaskArtifactIndex, verifyFoundryTaskArtifactLineage, } from "./foundry-task-store.js";
9
+ import { readOwnerExecutionRequests } from "./foundry-owner-execution-store.js";
10
+ import { TASK_RUNTIME_ADOPTION_SCHEMA, assertTrustedQualification, verifyEvidence, registration, validateSelection, parsePlan, readFoundryTaskRuntimeAdoption, readFoundryTaskRuntimeAdoptionChain, currentAdoptionRuntimeFacts, adoptionSuccessorPath, } from "./foundry-task-runtime-adoption.js";
11
+ function validateTask(context, record, selection, reapplyingPlanSha256) {
12
+ const selected = validateSelection(context, selection), registered = registration(context);
13
+ const chain = readFoundryTaskRuntimeAdoptionChain(context, selection);
14
+ const reapplying = chain?.tip.plan_sha256 === reapplyingPlanSha256;
15
+ const predecessor = reapplying ? chain?.plans.at(-2) : chain?.tip;
16
+ const expectedOriginal = predecessor
17
+ ? object(predecessor.selection).successor_runtime
18
+ : registered.job.runtime_identity;
19
+ if (record.spec.lane !== "source-evidence-dataset-development" ||
20
+ record.spec.preparation ||
21
+ record.spec.repair ||
22
+ !record.spec.seed ||
23
+ !selected.scope.some((row) => row.task_id === context.taskId && row.registration_sha256 === registered.sha256) ||
24
+ sha256Json(expectedOriginal) !== sha256Json(selected.value.original_runtime))
25
+ fail("runtime_adoption_scope_mismatch", "Adoption is limited to selected unchanged source-evidence registrations.");
26
+ if (predecessor) {
27
+ const priorQualification = object(object(predecessor.selection).qualification);
28
+ const currentQualification = object(selected.value.qualification);
29
+ const retained = chain.runtimes[reapplying ? chain.runtimes.length - 2 : chain.runtimes.length - 1];
30
+ const priorToolkit = facts(priorQualification.tidas)[1], originalToolkit = facts(currentQualification.tidas)[0];
31
+ if (sha256Json(selected.value.original_entry) !== sha256Json(retained.entry) ||
32
+ sha256Json(selected.value.original_descriptor) !== sha256Json(retained.descriptor) ||
33
+ currentQualification.original_manifest_sha256 !==
34
+ priorQualification.successor_manifest_sha256 ||
35
+ sha256Json(currentQualification.original_cli) !==
36
+ sha256Json(priorQualification.successor_cli) ||
37
+ originalToolkit.sha256 !== priorToolkit.sha256 ||
38
+ originalToolkit.bytes !== priorToolkit.bytes ||
39
+ object(selected.value.writer_handoff).predecessor_plan_sha256 !== predecessor.plan_sha256)
40
+ fail("runtime_adoption_predecessor_mismatch", "Select the exact immediately preceding runtime and its stopped-writer handoff.");
41
+ }
42
+ for (const fact of record.inputs)
43
+ verifyEvidence([fact]);
44
+ return { registered, chain };
45
+ }
46
+ function witness(context) {
47
+ const paths = new Set();
48
+ const add = (relative) => {
49
+ if (paths.size >= 8192 && !paths.has(relative))
50
+ fail("runtime_adoption_limit", "Task witness exceeds its bound.");
51
+ paths.add(relative);
52
+ };
53
+ const visit = (relative, depth) => {
54
+ if (depth > 20)
55
+ fail("runtime_adoption_limit", "Task witness exceeds its bound.");
56
+ const target = resolveFoundryOutput(context, relative);
57
+ if (!fs.existsSync(target))
58
+ return;
59
+ const stat = fs.lstatSync(target);
60
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
61
+ for (const name of fs.readdirSync(target).sort())
62
+ visit(`${relative}/${name}`, depth + 1);
63
+ }
64
+ else
65
+ add(relative);
66
+ };
67
+ for (const name of [
68
+ "foundry-job.json",
69
+ "source-manifest.json",
70
+ "profile-lock.json",
71
+ "seed-manifest.json",
72
+ "artifact-index.jsonl",
73
+ "account-intent.json",
74
+ "authorization.json",
75
+ "attempts",
76
+ "outputs/execution-requests",
77
+ ])
78
+ visit(name, 0);
79
+ const registered = registration(context);
80
+ for (const name of ["source_manifest", "profile_lock", "seed_manifest"]) {
81
+ const retained = registered.value[name];
82
+ if (retained === null)
83
+ continue;
84
+ const ref = reference(registered.job[name]);
85
+ const content = readTaskBytes(context, ref.path);
86
+ if (!content.equals(bytes(retained)) || digest(content) !== ref.sha256)
87
+ fail("runtime_adoption_evidence_changed", "Original registered task snapshot changed.");
88
+ }
89
+ const index = readFoundryTaskArtifactIndex(context);
90
+ if (index.length > 8192)
91
+ fail("runtime_adoption_limit", "Task artifact witness exceeds its bound.");
92
+ // Check registered hashes before accepting a current-byte witness: drift cannot become a fresh preimage.
93
+ let total = 0;
94
+ const observed = new Map();
95
+ const observe = (relative, expected) => {
96
+ if (observed.has(relative)) {
97
+ const prior = observed.get(relative);
98
+ if (expected &&
99
+ (prior.sha256 !== expected.sha256 ||
100
+ (expected.bytes !== undefined && prior.bytes !== expected.bytes)))
101
+ fail("runtime_adoption_evidence_changed", "Registered task artifact facts conflict.");
102
+ return;
103
+ }
104
+ const content = readTaskBytes(context, relative);
105
+ const fact = { path: relative, bytes: content.length, sha256: digest(content) };
106
+ if (expected &&
107
+ (fact.sha256 !== expected.sha256 ||
108
+ (expected.bytes !== undefined && fact.bytes !== expected.bytes)))
109
+ fail("runtime_adoption_evidence_changed", "Registered task artifact or producer changed.");
110
+ total += content.length;
111
+ if (total > 64 * 1024 * 1024)
112
+ fail("runtime_adoption_limit", "Task witness exceeds 64 MiB.");
113
+ add(relative);
114
+ observed.set(relative, fact);
115
+ };
116
+ for (const entry of index) {
117
+ observe(entry.path, entry);
118
+ observe(entry.receipt.path, entry.receipt);
119
+ const receipt = object(JSON.parse(readTaskBytes(context, entry.receipt.path).toString("utf8")));
120
+ for (const name of ["plan", "result"]) {
121
+ const ref = reference(receipt[name]);
122
+ observe(ref.path, ref);
123
+ }
124
+ }
125
+ verifyFoundryTaskArtifactLineage(context, {
126
+ job: registered.job,
127
+ jobSha256: digest(bytes(registered.job)),
128
+ sources: facts(object(registered.value.source_manifest).source_paths),
129
+ }, index);
130
+ for (const relative of paths)
131
+ observe(relative);
132
+ return [...observed.values()].sort((left, right) => left.path.localeCompare(right.path));
133
+ }
134
+ function adoptionContinuation(context) {
135
+ const attempts = resolveFoundryOutput(context, "attempts");
136
+ const sensitive = new Set([
137
+ "dataset-workflow-finalize",
138
+ "dataset-workflow-authorization",
139
+ "dataset-workflow-native-contract",
140
+ "dataset-workflow-execution-prepare",
141
+ "dataset-workflow-execution-result",
142
+ "dataset-workflow-execution-consume",
143
+ "dataset-workflow-execution-observation",
144
+ ]);
145
+ if ((fs.existsSync(attempts) && fs.readdirSync(attempts).length > 0) ||
146
+ fs.existsSync(resolveFoundryOutput(context, "authorization.json")) ||
147
+ readFoundryTaskArtifactIndex(context).some((entry) => sensitive.has(entry.command)))
148
+ return "original_owner_recovery";
149
+ return "preparation_only";
150
+ }
151
+ export function planFoundryTaskRuntimeAdoption(context, record, selection, trusted) {
152
+ assertTrustedQualification(selection, trusted);
153
+ const { registered, chain } = validateTask(context, record, selection);
154
+ if (chain && chain.plans.length >= 64)
155
+ fail("runtime_adoption_limit", "Runtime adoption chain reached its bound.");
156
+ const successor = currentAdoptionRuntimeFacts(context);
157
+ const payload = {
158
+ schema: TASK_RUNTIME_ADOPTION_SCHEMA,
159
+ workspace_id: context.workspaceId,
160
+ task_id: context.taskId,
161
+ actor_id: context.actorId,
162
+ registration_sha256: registered.sha256,
163
+ job_sha256: digest(bytes(registered.job)),
164
+ selection,
165
+ predecessor_plan_sha256: chain?.tip.plan_sha256 ?? null,
166
+ successor_entry: successor.entry,
167
+ successor_descriptor: successor.descriptor,
168
+ continuation: chain?.plans.some((plan) => plan.continuation === "original_owner_recovery")
169
+ ? "original_owner_recovery"
170
+ : adoptionContinuation(context),
171
+ prior_context_reports: readFoundryTaskArtifactIndex(context)
172
+ .filter((entry) => entry.command === "dataset-context-pack" &&
173
+ path.basename(entry.path) === "contract-report.json")
174
+ .map(({ path: file, bytes: size, sha256 }) => ({ path: file, bytes: size, sha256 })),
175
+ witness: witness(context),
176
+ };
177
+ return { ...payload, plan_sha256: sha256Json(payload) };
178
+ }
179
+ export async function applyFoundryTaskRuntimeAdoption(context, record, value, trusted) {
180
+ assertFoundryWorkspaceWrite(context);
181
+ const plan = parsePlan(value);
182
+ assertTrustedQualification(plan.selection, trusted);
183
+ const plannedChain = readFoundryTaskRuntimeAdoptionChain(context, plan.selection);
184
+ if (plannedChain?.tip.plan_sha256 !== plan.plan_sha256 &&
185
+ (plannedChain?.tip.plan_sha256 ?? null) !== (plan.predecessor_plan_sha256 ?? null))
186
+ fail("runtime_adoption_plan_stale", "The immediately preceding adoption changed after planning.");
187
+ const { registered } = validateTask(context, record, plan.selection, plan.plan_sha256);
188
+ const actualScopes = () => [
189
+ ...new Set(readOwnerExecutionRequests(context, readFoundryTaskArtifactIndex(context)).map((item) => item.request.scope_id)),
190
+ ].sort();
191
+ const originalScopes = actualScopes();
192
+ const scopes = [
193
+ ...new Set([
194
+ ...originalScopes,
195
+ ...registered.job.target_entities.map((type) => sha256Json({ task: context.taskId, type })),
196
+ ]),
197
+ ].sort();
198
+ const locked = (index) => {
199
+ if (index < scopes.length)
200
+ return withBatchRunLock({
201
+ runPath: resolveFoundryOutput(context, `owner-locks/${context.taskId}-${scopes[index]}.json`, "state"),
202
+ identity: { task: context.taskId, scope: scopes[index] },
203
+ timeoutMs: 0,
204
+ reason: "Foundry adoption excludes owner execution",
205
+ }, () => locked(index + 1));
206
+ return withBatchRunLock({
207
+ runPath: resolveFoundryOutput(context, `task-locks/${context.taskId}.json`, "state"),
208
+ identity: {
209
+ schema: "foundry-task-store-lock.v1",
210
+ workspace_id: context.workspaceId,
211
+ task_id: context.taskId,
212
+ },
213
+ timeoutMs: 0,
214
+ reason: "Foundry explicit same-task runtime adoption",
215
+ }, () => {
216
+ if (sha256Json(actualScopes()) !== sha256Json(originalScopes))
217
+ fail("runtime_adoption_plan_stale", "Owner scope changed before adoption lock.");
218
+ const existing = readFoundryTaskRuntimeAdoptionChain(context, plan.selection);
219
+ if (existing?.tip.plan_sha256 === plan.plan_sha256) {
220
+ return { status: "adopted", already_applied: true, plan_sha256: plan.plan_sha256 };
221
+ }
222
+ if ((existing?.tip.plan_sha256 ?? null) !== (plan.predecessor_plan_sha256 ?? null))
223
+ fail("runtime_adoption_plan_stale", "The immediately preceding adoption changed after planning.");
224
+ const current = planFoundryTaskRuntimeAdoption(context, record, plan.selection, trusted);
225
+ if (current.plan_sha256 !== plan.plan_sha256)
226
+ fail("runtime_adoption_plan_stale", "Task facts changed after adoption planning.");
227
+ const content = bytes(plan);
228
+ transferWriteOnce(context.taskRoot, `runtime-adoptions/${plan.plan_sha256}.json`, content);
229
+ const anchor = {
230
+ schema: existing
231
+ ? "tiangong-foundry.task-runtime-adoption-successor.v1"
232
+ : "tiangong-foundry.task-runtime-adoption-anchor.v1",
233
+ workspace_id: context.workspaceId,
234
+ task_id: context.taskId,
235
+ plan_sha256: plan.plan_sha256,
236
+ receipt_sha256: digest(content),
237
+ ...(existing ? { predecessor_plan_sha256: existing.tip.plan_sha256 } : {}),
238
+ };
239
+ transferWriteOnce(context.stateRoot, existing
240
+ ? path
241
+ .relative(context.stateRoot, adoptionSuccessorPath(context, String(existing.tip.plan_sha256)))
242
+ .split(path.sep)
243
+ .join("/")
244
+ : `task-runtime-adoptions/${context.taskId}.json`, bytes(anchor));
245
+ readFoundryTaskRuntimeAdoption(context);
246
+ return { status: "adopted", already_applied: false, plan_sha256: plan.plan_sha256 };
247
+ });
248
+ };
249
+ return locked(0);
250
+ }
@@ -0,0 +1,60 @@
1
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
2
+ import { type FoundryRuntimeContext, type FoundryInputFact } from "./foundry-runtime-context.ts";
3
+ import type { TaskRuntimeIdentity } from "./foundry-task-types.ts";
4
+ export interface TrustedFoundryRuntimeAdoptionQualification {
5
+ readonly sha256: string;
6
+ readonly value: Readonly<Record<string, unknown>>;
7
+ }
8
+ /** The independent host supplies the expected digest; task input cannot grant compatibility. */
9
+ export declare function createFoundryRuntimeAdoptionQualification(input: {
10
+ bytes: Uint8Array;
11
+ expectedSha256: string;
12
+ }): TrustedFoundryRuntimeAdoptionQualification;
13
+ export declare function assertTrustedQualification(selection: unknown, trusted?: TrustedFoundryRuntimeAdoptionQualification): void;
14
+ export declare function verifyEvidence(value: unknown): FoundryInputFact[];
15
+ export interface RetainedAdoptionRuntime {
16
+ readonly root: string;
17
+ readonly identity: TaskRuntimeIdentity;
18
+ readonly entry: FoundryInputFact;
19
+ readonly descriptor: FoundryInputFact;
20
+ }
21
+ export declare function currentAdoptionRuntimeFacts(context: FoundryRuntimeContext): RetainedAdoptionRuntime;
22
+ /** Bind an adopted task's actual selected Toolkit to the independently reviewed executable. */
23
+ export declare function assertRuntimeAdoptionToolkit(selected: QualifiedFoundryRuntime | undefined, selection: unknown): void;
24
+ export declare const TASK_RUNTIME_ADOPTION_SCHEMA = "tiangong-foundry.task-runtime-adoption-plan.v2";
25
+ export interface FoundryTaskRuntimeAdoptionInput {
26
+ taskId: string;
27
+ actorId: string;
28
+ mode: "plan" | "apply" | "audit";
29
+ selection?: unknown;
30
+ plan?: unknown;
31
+ }
32
+ export declare function currentAdoptionRuntime(context: FoundryRuntimeContext): TaskRuntimeIdentity;
33
+ export declare function anchorPath(context: FoundryRuntimeContext): string;
34
+ export declare function registration(context: FoundryRuntimeContext): {
35
+ value: import("./foundry-task-types.ts").JsonRecord;
36
+ job: import("./foundry-task-types.ts").JsonRecord;
37
+ sha256: string;
38
+ };
39
+ /** Explicit operator-selected evidence does not grant business permission. It authorizes only these exact registrations. */
40
+ export declare function validateSelection(context: FoundryRuntimeContext, selection: unknown, options?: {
41
+ successor?: RetainedAdoptionRuntime;
42
+ historical?: boolean;
43
+ }): {
44
+ value: import("./foundry-task-types.ts").JsonRecord;
45
+ scope: import("./foundry-task-types.ts").JsonRecord[];
46
+ };
47
+ export declare function parsePlan(value: unknown): import("./foundry-task-types.ts").JsonRecord;
48
+ export declare function adoptionSuccessorPath(context: FoundryRuntimeContext, predecessor: string): string;
49
+ export interface FoundryTaskRuntimeAdoptionChain {
50
+ readonly plans: readonly Readonly<Record<string, unknown>>[];
51
+ readonly tip: Readonly<Record<string, unknown>>;
52
+ readonly runtimes: readonly RetainedAdoptionRuntime[];
53
+ readonly retained_runtime_roots: readonly string[];
54
+ readonly prior_context_reports: readonly FoundryInputFact[];
55
+ }
56
+ /** Inspect anchored historical proofs; a locator for a legacy tip cannot replace its stored pair claims. */
57
+ export declare function readFoundryTaskRuntimeAdoptionChain(context: FoundryRuntimeContext, legacyTipSelection?: unknown): FoundryTaskRuntimeAdoptionChain | null;
58
+ export declare function readFoundryTaskRuntimeAdoption(context: FoundryRuntimeContext): Readonly<Record<string, unknown>> | null;
59
+ export declare function assertAdoptedRuntimeToolkit(context: FoundryRuntimeContext, selected: QualifiedFoundryRuntime | undefined, allowTransition?: boolean): void;
60
+ export declare function assertTaskRuntimeIdentity(context: FoundryRuntimeContext, original: unknown): void;