@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
@@ -0,0 +1,94 @@
1
+ import { captureFoundryInput, FoundryContextError, readFoundryInput, } from "./foundry-runtime-context.js";
2
+ import { verifyEdgeSupportPlan, } from "./foundry-edge-support-plan.js";
3
+ import { sha256Json } from "./identity-preflight-proof.js";
4
+ import { readRows } from "./import-curation/internal/runtime-io.js";
5
+ import { readNativeDraftHandoff } from "./finalize-owners/native-draft-handoff.js";
6
+ import { workflowObject } from "./foundry-workflow-state.js";
7
+ import { readEdgeReferenceIntent } from "./foundry-edge-reference-intent.js";
8
+ export function verifySelectedEdgeDraftPlan(context, plan, approved, target) {
9
+ const read = (file) => readFoundryInput(context, file).toString("utf8");
10
+ const evidenceFile = plan.reference_evidence?.path;
11
+ const report = evidenceFile ? JSON.parse(read(evidenceFile)) : null;
12
+ const evidence = evidenceFile ? { fact: captureFoundryInput(evidenceFile), report } : undefined;
13
+ const rows = readRows(approved.path, read);
14
+ const recordedIntent = evidence && workflowObject(evidence.report).reference_intent;
15
+ if (recordedIntent || plan.reference_intent) {
16
+ const intent = plan.reference_intent?.[0];
17
+ if (!recordedIntent || !intent)
18
+ throw new FoundryContextError("execution_reference_evidence_unbound", "The sealed Edge plan must carry the original explicit reference intent.");
19
+ const current = readEdgeReferenceIntent(context, intent.path, plan.dataset_type, target, rows);
20
+ if (sha256Json(current.binding) !== sha256Json(recordedIntent))
21
+ throw new FoundryContextError("execution_reference_evidence_unbound", "The reference intent, reviews or consumers differ from the sealed precommit evidence.");
22
+ }
23
+ const update = plan.update;
24
+ const insert = plan.insert_contract;
25
+ if (insert) {
26
+ read(insert.path);
27
+ const native = readNativeDraftHandoff({
28
+ contractFile: insert.path,
29
+ rowsFile: approved.path,
30
+ datasetType: plan.dataset_type,
31
+ verifiedProjectRef: target.project_ref,
32
+ targetUserId: target.user_id,
33
+ stateCode: "0",
34
+ relativePath: (file) => file,
35
+ });
36
+ if (native.metadata.operation !== "insert" ||
37
+ sha256Json(captureFoundryInput(insert.path)) !== sha256Json(insert))
38
+ throw new FoundryContextError("edge_draft_contract_mismatch", "Explicit Edge insertion requires the original exact insert-only contract.");
39
+ }
40
+ if (update) {
41
+ const invalid = (detail) => new FoundryContextError("repair_edge_scope_changed", detail);
42
+ for (const fact of [update.before, update.contract, update.preparation]) {
43
+ read(fact.path);
44
+ const current = captureFoundryInput(fact.path);
45
+ if (current.path !== fact.path ||
46
+ current.bytes !== fact.bytes ||
47
+ current.sha256 !== fact.sha256)
48
+ throw invalid("A selected update input changed after the plan was sealed.");
49
+ }
50
+ const preparation = workflowObject(JSON.parse(read(update.preparation.path)));
51
+ const inputs = workflowObject(preparation.inputs);
52
+ const preparedContract = workflowObject(inputs.contract);
53
+ const evidence = workflowObject(preparation.evidence);
54
+ const preflight = Array.isArray(evidence.detail)
55
+ ? evidence.detail.map(workflowObject).find((item) => item.role === "edge_preflight")
56
+ : undefined;
57
+ const rules = workflowObject(preflight?.report ?? {}).rule_verification;
58
+ const native = readNativeDraftHandoff({
59
+ contractFile: update.contract.path,
60
+ rowsFile: approved.path,
61
+ datasetType: "process",
62
+ verifiedProjectRef: target.project_ref,
63
+ targetUserId: target.user_id,
64
+ stateCode: "0",
65
+ relativePath: (file) => file,
66
+ });
67
+ const validPreparation = {
68
+ schema: preparation.schema === "tiangong-foundry.repair-preparation.v1",
69
+ readiness: preparation.status === "prepared" &&
70
+ preparation.remote_writes === 0 &&
71
+ preparation.publication_ready === false,
72
+ before: sha256Json(inputs.before) === sha256Json(update.before),
73
+ candidate: sha256Json(inputs.candidate) === sha256Json(captureFoundryInput(approved.path)),
74
+ contract: preparedContract.sha256 === update.contract.sha256 &&
75
+ preparedContract.bytes === update.contract.bytes,
76
+ scope: workflowObject(preparation.scope).contract_sha256 === native.canonical_sha256,
77
+ validation: Boolean(rules) && sha256Json(rules) === sha256Json(update.rule_verification),
78
+ };
79
+ const missing = Object.entries(validPreparation).filter(([, valid]) => !valid);
80
+ if (missing.length)
81
+ throw invalid(`Invalid guarded update preparation fields: ${missing.map(([key]) => key).join(", ")}.`);
82
+ if (native.contract.actions.length !== plan.roots.length ||
83
+ native.contract.actions.some((action) => {
84
+ const root = plan.roots.find((item) => item.id === action.id && item.version === action.version);
85
+ return (action.expected_operation !== "save_draft" ||
86
+ !root ||
87
+ action.table !== root.table ||
88
+ action.before_sha256 !== root.before_sha256 ||
89
+ action.desired_sha256 !== root.payload_sha256);
90
+ }))
91
+ throw invalid("The native update actions differ from the sealed exact draft writes.");
92
+ }
93
+ return verifyEdgeSupportPlan(plan, captureFoundryInput(approved.path), target, rows, evidence, update && { binding: update, rows: readRows(update.before.path, read) }, insert);
94
+ }
@@ -0,0 +1,47 @@
1
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import type { QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
+ import type { FoundryAuthentication } from "./foundry-runtime-identity.ts";
4
+ import { type IdentityPreflightBindingInput } from "./identity-preflight-proof.ts";
5
+ export declare function validateEdgeIdentityQuery(type: "flow" | "process", rowValue: unknown, requestText: string): {
6
+ readonly endpoint: "flow_hybrid_search" | "process_hybrid_search";
7
+ readonly body: {
8
+ query: unknown;
9
+ filter?: {} | undefined;
10
+ match_count: unknown;
11
+ page_size: unknown;
12
+ data_source: unknown;
13
+ match_threshold: unknown;
14
+ lexical_weight: unknown;
15
+ semantic_weight: unknown;
16
+ rrf_k: unknown;
17
+ };
18
+ readonly target: import("./import-curation/internal/dataset-payload.ts").DatasetIdentity;
19
+ };
20
+ export declare function edgeIdentityCandidates(type: "flow" | "process", result: unknown, limit: number): {
21
+ id: string;
22
+ version: string;
23
+ content: Record<string, unknown>;
24
+ score: {} | null;
25
+ }[];
26
+ type Claim = {
27
+ dispatchSha256: string;
28
+ sourceSha256: string;
29
+ claimedAt: string;
30
+ receipt: NonNullable<IdentityPreflightBindingInput["authReceipt"]>;
31
+ };
32
+ /** Run the already-audited bounded query and hand the decision to Foundry's existing review lane. */
33
+ export declare function runFoundryEdgeIdentityPreflight(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, type: "flow" | "process", indexFile: string, outDir: string, claim?: Claim): Promise<{
34
+ schema: string;
35
+ status: string;
36
+ producer: string;
37
+ index: string;
38
+ files: {
39
+ report: string;
40
+ };
41
+ }>;
42
+ /** Adopt one original Edge observation only when the persisted dispatch and all response evidence agree. */
43
+ export declare function readRetainedFoundryEdgeIdentity(context: FoundryRuntimeContext, type: "flow" | "process", row: Record<string, unknown>, runDir: string, mode: FoundryAuthentication["mode"], claim: Claim): {
44
+ run: Record<string, unknown>;
45
+ row: Record<string, unknown>;
46
+ };
47
+ export {};
@@ -0,0 +1,268 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FoundryContextError, resolveFoundryOutput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
4
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
5
+ import { createIdentityPreflightBinding, createIdentityPreflightExecutionManifest, sha256Json, sha256Text, parseFreshIntentBoundAuthReceipt, validateBoundExecutionManifest, } from "./identity-preflight-proof.js";
6
+ import { datasetIdentity, datasetRoot, dataSetInformation, } from "./import-curation/internal/dataset-payload.js";
7
+ import { queryFoundryEdgeIdentity } from "./foundry-edge-session.js";
8
+ function invalid() {
9
+ throw new FoundryContextError("edge_identity_evidence_invalid", "The Edge identity evidence does not match the current audited request.");
10
+ }
11
+ function object(value) {
12
+ if (!value || typeof value !== "object" || Array.isArray(value))
13
+ return invalid();
14
+ return value;
15
+ }
16
+ export function validateEdgeIdentityQuery(type, rowValue, requestText) {
17
+ const row = object(rowValue);
18
+ const request = object(JSON.parse(requestText));
19
+ const search = object(request.remote_candidate_search);
20
+ const edge = object(object(row.remote_search).edge_request);
21
+ const endpoint = type === "flow" ? "flow_hybrid_search" : "process_hybrid_search";
22
+ const body = {
23
+ query: search.query,
24
+ ...(search.filter ? { filter: search.filter } : {}),
25
+ match_count: search.limit,
26
+ page_size: search.limit,
27
+ data_source: search.data_source,
28
+ match_threshold: search.match_threshold,
29
+ lexical_weight: search.lexical_weight,
30
+ semantic_weight: search.semantic_weight,
31
+ rrf_k: search.rrf_k,
32
+ };
33
+ if (edge.endpoint !== endpoint ||
34
+ sha256Json(edge.body) !== sha256Json(body) ||
35
+ row.dataset_type !== type ||
36
+ row.request_bytes_sha256 !== sha256Text(requestText) ||
37
+ row.target_sha256 !== sha256Text(JSON.stringify(request.target)) ||
38
+ search.enabled !== true ||
39
+ typeof body.query !== "string" ||
40
+ !body.query.trim() ||
41
+ !Number.isSafeInteger(body.match_count) ||
42
+ Number(body.match_count) < 1 ||
43
+ Number(body.match_count) > 80 ||
44
+ body.data_source !== "tg")
45
+ return invalid();
46
+ const target = datasetIdentity(request.target, 0, type);
47
+ if (target.id !== row.dataset_id || target.version !== row.dataset_version)
48
+ return invalid();
49
+ return { endpoint, body, target };
50
+ }
51
+ export function edgeIdentityCandidates(type, result, limit) {
52
+ const rows = Array.isArray(result) ? result : object(result).data;
53
+ if (!Array.isArray(rows) || rows.length > limit)
54
+ return invalid();
55
+ const keys = new Set();
56
+ return rows.map((value) => {
57
+ const row = object(value);
58
+ const id = row.id;
59
+ const version = row.version;
60
+ const json = row.json_ordered ?? row.json;
61
+ if (typeof id !== "string" ||
62
+ typeof version !== "string" ||
63
+ !/^\d{2}\.\d{2}\.\d{3}$/u.test(version))
64
+ return invalid();
65
+ const key = `${id}@${version}`;
66
+ if (keys.has(key))
67
+ return invalid();
68
+ keys.add(key);
69
+ const content = object(json);
70
+ const root = datasetRoot(content, type);
71
+ const ownership = object(object(root.administrativeInformation).publicationAndOwnership);
72
+ if (dataSetInformation(root, type)["common:UUID"] !== id ||
73
+ ownership["common:dataSetVersion"] !== version)
74
+ return invalid();
75
+ return { id, version, content, score: row.combined_score ?? row.score ?? null };
76
+ });
77
+ }
78
+ function bindingForEdgeObservation(type, row, requestText, receipt, observation, claim) {
79
+ const { endpoint, target } = validateEdgeIdentityQuery(type, row, requestText);
80
+ const cli = resolveInstalledTiangongLcaCliPackage();
81
+ return createIdentityPreflightBinding({
82
+ datasetType: type,
83
+ datasetId: target.id,
84
+ datasetVersion: target.version,
85
+ targetSha256: String(row.target_sha256),
86
+ requestText,
87
+ semanticArgv: ["edge", "POST", endpoint],
88
+ cli: {
89
+ packageName: cli.packageName,
90
+ packageVersion: cli.packageVersion,
91
+ packageIntegrity: null,
92
+ },
93
+ authReceipt: receipt,
94
+ relevantInputHashes: {
95
+ edge_observation: sha256Json(observation),
96
+ ...(claim
97
+ ? { explicit_dispatch: claim.dispatchSha256, source_file: claim.sourceSha256 }
98
+ : {}),
99
+ },
100
+ });
101
+ }
102
+ /** Run the already-audited bounded query and hand the decision to Foundry's existing review lane. */
103
+ export async function runFoundryEdgeIdentityPreflight(context, qualified, authentication, type, indexFile, outDir, claim) {
104
+ const index = fs.readFileSync(resolveFoundryOutput(context, indexFile), "utf8");
105
+ const rows = index
106
+ .split("\n")
107
+ .filter((line) => line.trim())
108
+ .map((line) => object(JSON.parse(line)));
109
+ if (!rows.length || (claim && rows.length !== 1))
110
+ return invalid();
111
+ const results = [];
112
+ for (const row of rows) {
113
+ const file = (value) => {
114
+ if (typeof value !== "string")
115
+ return invalid();
116
+ return resolveFoundryOutput(context, path.resolve(context.assetRoot, value));
117
+ };
118
+ const requestFile = file(row.request_file);
119
+ const reportFile = file(row.expected_report_file);
120
+ const requestText = fs.readFileSync(requestFile, "utf8");
121
+ const { endpoint, body, target } = validateEdgeIdentityQuery(type, row, requestText);
122
+ const { receipt, result } = await queryFoundryEdgeIdentity(context, qualified, authentication, endpoint, body);
123
+ if (fs.readFileSync(requestFile, "utf8") !== requestText)
124
+ return invalid();
125
+ const candidates = edgeIdentityCandidates(type, result, Number(body.match_count));
126
+ const candidateFile = path.join(path.dirname(reportFile), "edge-search-observation.json");
127
+ const observation = {
128
+ schema: "tiangong-foundry.edge-identity-observation.v1",
129
+ endpoint,
130
+ project_ref: receipt.project.project_ref,
131
+ user_id: receipt.identity.user_id,
132
+ query: body,
133
+ ...(claim ? { verified_actor_receipt: receipt } : {}),
134
+ result,
135
+ };
136
+ writeFoundryArtifact(context, candidateFile, JSON.stringify(observation, null, 2) + "\n");
137
+ const binding = bindingForEdgeObservation(type, row, requestText, claim?.receipt ?? receipt, observation, claim);
138
+ const report = {
139
+ schema: "tiangong-foundry.edge-identity-decision.v1",
140
+ producer: "foundry",
141
+ status: "needs_review",
142
+ decision: "manual_review",
143
+ next_action: "queue_manual_review",
144
+ target: { id: target.id, version: target.version },
145
+ candidates,
146
+ candidate_sources: [
147
+ {
148
+ kind: "remote_search",
149
+ endpoint,
150
+ path: candidateFile,
151
+ query: body.query,
152
+ row_count: candidates.length,
153
+ bounded: true,
154
+ },
155
+ ],
156
+ findings: [],
157
+ blockers: [],
158
+ };
159
+ const reportText = JSON.stringify(report, null, 2) + "\n";
160
+ writeFoundryArtifact(context, reportFile, reportText);
161
+ const manifest = createIdentityPreflightExecutionManifest(binding, reportText, new Date().toISOString());
162
+ const manifestFile = path.join(path.dirname(reportFile), "foundry-identity-preflight-execution.json");
163
+ writeFoundryArtifact(context, manifestFile, JSON.stringify(manifest, null, 2) + "\n");
164
+ const { command_spec: _legacyCommand, ...rest } = row;
165
+ results.push({
166
+ ...rest,
167
+ command: `POST ${endpoint}`,
168
+ execution_manifest_file: manifestFile,
169
+ expected_project_ref: receipt.project.project_ref,
170
+ expected_user_id: receipt.identity.user_id,
171
+ });
172
+ }
173
+ const completedIndex = path.join(outDir, "identity-preflight-requests.jsonl");
174
+ writeFoundryArtifact(context, completedIndex, results.map((row) => JSON.stringify(row)).join("\n") + "\n");
175
+ const reportFile = path.join(outDir, "dataset-identity-preflight-run-report.json");
176
+ const report = {
177
+ schema: "tiangong-foundry.edge-identity-preflight.v1",
178
+ status: "completed_with_identity_findings",
179
+ producer: "foundry",
180
+ index: completedIndex,
181
+ files: { report: reportFile },
182
+ };
183
+ writeFoundryArtifact(context, reportFile, JSON.stringify(report, null, 2) + "\n");
184
+ return report;
185
+ }
186
+ /** Adopt one original Edge observation only when the persisted dispatch and all response evidence agree. */
187
+ export function readRetainedFoundryEdgeIdentity(context, type, row, runDir, mode, claim) {
188
+ const file = (value) => {
189
+ if (typeof value !== "string")
190
+ return invalid();
191
+ return resolveFoundryOutput(context, path.resolve(context.assetRoot, value));
192
+ };
193
+ const read = (name) => {
194
+ const stat = fs.lstatSync(name);
195
+ if (!stat.isFile() || stat.size > 8 * 1024 * 1024)
196
+ return invalid();
197
+ return fs.readFileSync(name, "utf8");
198
+ };
199
+ const runFile = file(path.join(runDir, "dataset-identity-preflight-run-report.json"));
200
+ const index = file(path.join(runDir, "identity-preflight-requests.jsonl"));
201
+ const run = object(JSON.parse(read(runFile)));
202
+ const completedRows = read(index).trimEnd().split("\n");
203
+ if (run.schema !== "tiangong-foundry.edge-identity-preflight.v1" ||
204
+ run.producer !== "foundry" ||
205
+ run.status !== "completed_with_identity_findings" ||
206
+ run.index !== index ||
207
+ object(run.files).report !== runFile ||
208
+ completedRows.length !== 1)
209
+ return invalid();
210
+ const requestText = read(file(row.request_file));
211
+ const { endpoint, body, target } = validateEdgeIdentityQuery(type, row, requestText);
212
+ const reportFile = file(row.expected_report_file);
213
+ const directory = path.dirname(reportFile);
214
+ const candidateFile = file(path.join(directory, "edge-search-observation.json"));
215
+ const manifestFile = file(path.join(directory, "foundry-identity-preflight-execution.json"));
216
+ const observation = object(JSON.parse(read(candidateFile)));
217
+ const reportText = read(reportFile);
218
+ const report = object(JSON.parse(reportText));
219
+ const manifest = object(JSON.parse(read(manifestFile)));
220
+ const checkedAt = Date.parse(String(manifest.completed_at_utc));
221
+ const claimedAt = Date.parse(claim.claimedAt);
222
+ const actor = parseFreshIntentBoundAuthReceipt(observation.verified_actor_receipt, {
223
+ nowMs: checkedAt,
224
+ maxAgeMs: 60_000,
225
+ expectedProjectRef: claim.receipt.project.project_ref,
226
+ expectedUserId: claim.receipt.identity.user_id,
227
+ sessionMode: mode,
228
+ });
229
+ const { command_spec: _legacyCommand, ...rest } = row;
230
+ const completed = object(JSON.parse(completedRows[0]));
231
+ const expected = {
232
+ ...rest,
233
+ command: `POST ${endpoint}`,
234
+ execution_manifest_file: manifestFile,
235
+ expected_project_ref: actor.project.project_ref,
236
+ expected_user_id: actor.identity.user_id,
237
+ };
238
+ const candidates = edgeIdentityCandidates(type, observation.result, Number(body.match_count));
239
+ const source = Array.isArray(report.candidate_sources) && report.candidate_sources.length === 1
240
+ ? object(report.candidate_sources[0])
241
+ : invalid();
242
+ const binding = bindingForEdgeObservation(type, row, requestText, claim.receipt, observation, claim);
243
+ if (observation.schema !== "tiangong-foundry.edge-identity-observation.v1" ||
244
+ observation.endpoint !== endpoint ||
245
+ observation.project_ref !== actor.project.project_ref ||
246
+ observation.user_id !== actor.identity.user_id ||
247
+ sha256Json(actor.cli) !== sha256Json(claim.receipt.cli) ||
248
+ actor.project.project_base_url !== claim.receipt.project.project_base_url ||
249
+ sha256Json(observation.query) !== sha256Json(body) ||
250
+ !Number.isFinite(claimedAt) ||
251
+ checkedAt < claimedAt ||
252
+ Date.parse(actor.captured_at_utc) < claimedAt - 5_000 ||
253
+ sha256Json(completed) !== sha256Json(expected) ||
254
+ report.schema !== "tiangong-foundry.edge-identity-decision.v1" ||
255
+ report.producer !== "foundry" ||
256
+ report.decision !== "manual_review" ||
257
+ report.status !== "needs_review" ||
258
+ object(report.target).id !== target.id ||
259
+ object(report.target).version !== target.version ||
260
+ sha256Json(report.candidates) !== sha256Json(candidates) ||
261
+ source.endpoint !== endpoint ||
262
+ source.path !== candidateFile ||
263
+ source.row_count !== candidates.length ||
264
+ source.bounded !== true ||
265
+ !validateBoundExecutionManifest(manifest, binding, reportText).ok)
266
+ return invalid();
267
+ return { run, row: completed };
268
+ }
@@ -0,0 +1,4 @@
1
+ import type { FoundryPublicOAuthConfiguration } from "./foundry-authentication-environment.ts";
2
+ type OpenBrowser = (url: string) => Promise<void>;
3
+ export declare function resolveFoundryEdgeOAuth(origin: string, expectedUser: string, configuration: FoundryPublicOAuthConfiguration, openBrowser?: OpenBrowser): Promise<string>;
4
+ export {};
@@ -0,0 +1,154 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { FoundryContextError } from "./foundry-runtime-context.js";
5
+ // The existing public TianGong CLI registration used by the released CLI 0.4.0.
6
+ const officialOrigin = "https://qgzvkongdjqiiamzbbts.supabase.co";
7
+ const officialClient = "1837c6d3-3c9d-48e0-bbf7-b532b78f9f76";
8
+ const defaultCallback = "http://127.0.0.1:49191/oauth/callback";
9
+ const inMemory = new Map();
10
+ function fail(code, message) {
11
+ throw new FoundryContextError(code, message);
12
+ }
13
+ function browser(url) {
14
+ const windows = process.platform === "win32";
15
+ const command = windows ? "rundll32.exe" : process.platform === "darwin" ? "open" : "xdg-open";
16
+ const args = windows ? ["url.dll,FileProtocolHandler", url] : [url];
17
+ return new Promise((resolve, reject) => {
18
+ const child = spawn(command, args, {
19
+ detached: true,
20
+ shell: false,
21
+ stdio: "ignore",
22
+ windowsHide: true,
23
+ });
24
+ child.once("error", () => reject(new FoundryContextError("edge_oauth_browser_failed", "Open the OAuth authorization in an available system browser.")));
25
+ child.once("spawn", () => {
26
+ child.unref();
27
+ resolve();
28
+ });
29
+ });
30
+ }
31
+ function clientSettings(origin, configuration) {
32
+ const clientId = configuration.oauthClientId || (origin === officialOrigin ? officialClient : "");
33
+ const redirect = new URL(configuration.oauthRedirectUri || defaultCallback);
34
+ if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(clientId) ||
35
+ redirect.protocol !== "http:" ||
36
+ redirect.hostname !== "127.0.0.1" ||
37
+ Number(redirect.port) < 1024 ||
38
+ redirect.username ||
39
+ redirect.password ||
40
+ redirect.search ||
41
+ redirect.hash ||
42
+ redirect.pathname !== "/oauth/callback")
43
+ return fail("edge_oauth_config_invalid", "OAuth requires the selected project's public client and its registered loopback redirect.");
44
+ return { origin, clientId, redirect };
45
+ }
46
+ async function authorize(client, openBrowser) {
47
+ const state = randomBytes(32).toString("base64url");
48
+ const verifier = randomBytes(48).toString("base64url");
49
+ const authorization = new URL("/auth/v1/oauth/authorize", client.origin);
50
+ authorization.search = new URLSearchParams({
51
+ response_type: "code",
52
+ client_id: client.clientId,
53
+ redirect_uri: client.redirect.href,
54
+ scope: "openid email profile",
55
+ code_challenge_method: "S256",
56
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
57
+ state,
58
+ }).toString();
59
+ return new Promise((resolve, reject) => {
60
+ let settled = false;
61
+ const finish = (error, code) => {
62
+ if (settled)
63
+ return;
64
+ settled = true;
65
+ clearTimeout(timeout);
66
+ server.closeAllConnections();
67
+ server.close();
68
+ if (error)
69
+ reject(error);
70
+ else
71
+ resolve({ code: code, verifier });
72
+ };
73
+ const server = createServer((request, response) => {
74
+ const url = new URL(request.url ?? "/", client.redirect.origin);
75
+ if (request.method !== "GET" ||
76
+ request.headers.host !== client.redirect.host ||
77
+ url.origin !== client.redirect.origin ||
78
+ url.pathname !== client.redirect.pathname ||
79
+ url.searchParams.getAll("state").length !== 1 ||
80
+ url.searchParams.get("state") !== state) {
81
+ response.writeHead(400, { "Cache-Control": "no-store" }).end("Invalid OAuth callback.");
82
+ return;
83
+ }
84
+ const code = url.searchParams.get("code");
85
+ if (!code ||
86
+ code.length > 4096 ||
87
+ url.searchParams.getAll("code").length !== 1 ||
88
+ url.searchParams.has("error")) {
89
+ response
90
+ .writeHead(400, { "Cache-Control": "no-store" })
91
+ .end("Authorization was not completed.", () => finish(new FoundryContextError("edge_oauth_not_authorized", "The operator did not authorize the Edge session.")));
92
+ return;
93
+ }
94
+ response
95
+ .writeHead(200, {
96
+ "Cache-Control": "no-store",
97
+ "Content-Type": "text/plain; charset=utf-8",
98
+ })
99
+ .end("Foundry received authorization. You can close this tab.", () => finish(null, code));
100
+ });
101
+ const timeout = setTimeout(() => finish(new FoundryContextError("edge_oauth_timeout", "The loopback OAuth authorization expired.")), 120_000);
102
+ server.once("error", () => finish(new FoundryContextError("edge_oauth_callback_unavailable", "The registered loopback OAuth port is unavailable.")));
103
+ server.listen(Number(client.redirect.port), "127.0.0.1", () => void openBrowser(authorization.href).catch((error) => finish(error)));
104
+ });
105
+ }
106
+ function object(value) {
107
+ return value && typeof value === "object" && !Array.isArray(value)
108
+ ? value
109
+ : {};
110
+ }
111
+ export async function resolveFoundryEdgeOAuth(origin, expectedUser, configuration, openBrowser = browser) {
112
+ if (new URL(origin).protocol !== "https:")
113
+ return fail("edge_oauth_config_invalid", "Use an HTTPS project for operator OAuth.");
114
+ const client = clientSettings(origin, configuration);
115
+ const key = JSON.stringify([origin, client.clientId, expectedUser]);
116
+ let selected = inMemory.get(key);
117
+ if (!selected || selected.expiresAt - Date.now() < 90_000) {
118
+ const { code, verifier } = await authorize(client, openBrowser);
119
+ const response = await fetch(new URL("/auth/v1/oauth/token", origin), {
120
+ method: "POST",
121
+ headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
122
+ body: new URLSearchParams({
123
+ grant_type: "authorization_code",
124
+ client_id: client.clientId,
125
+ redirect_uri: client.redirect.href,
126
+ code,
127
+ code_verifier: verifier,
128
+ }),
129
+ redirect: "error",
130
+ signal: AbortSignal.timeout(15_000),
131
+ });
132
+ if (!response.ok)
133
+ return fail("edge_oauth_token_failed", "The existing OAuth service did not issue an operator session.");
134
+ const body = object(await response.json());
135
+ if (typeof body.access_token !== "string" ||
136
+ !body.access_token ||
137
+ String(body.token_type).toLowerCase() !== "bearer" ||
138
+ !Number.isSafeInteger(body.expires_in) ||
139
+ Number(body.expires_in) <= 0)
140
+ return fail("edge_oauth_token_invalid", "OAuth returned an invalid operator session.");
141
+ selected = { token: body.access_token, expiresAt: Date.now() + Number(body.expires_in) * 1000 };
142
+ }
143
+ const response = await fetch(new URL("/auth/v1/oauth/userinfo", origin), {
144
+ headers: { Accept: "application/json", Authorization: `Bearer ${selected.token}` },
145
+ redirect: "error",
146
+ signal: AbortSignal.timeout(15_000),
147
+ });
148
+ if (!response.ok || object(await response.json()).sub !== expectedUser) {
149
+ inMemory.delete(key);
150
+ return fail("edge_oauth_actor_mismatch", "The browser session does not match the verified task account.");
151
+ }
152
+ inMemory.set(key, selected);
153
+ return selected.token;
154
+ }
@@ -0,0 +1,51 @@
1
+ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type BundleRowType } from "./bundle-row-types.ts";
3
+ export type EdgeReferenceSnapshot = {
4
+ table: string;
5
+ id: string;
6
+ version: string;
7
+ payload_sha256: string;
8
+ user_id: string;
9
+ state_code: 0 | 100;
10
+ };
11
+ export declare function edgeReferenceKey(reference: {
12
+ table: string;
13
+ id: string;
14
+ version: string;
15
+ }): string;
16
+ export declare function readEdgeReferenceSnapshot(value: unknown, actor: string): EdgeReferenceSnapshot;
17
+ export declare function readEdgeReferenceIntent(context: FoundryRuntimeContext, input: string, type: BundleRowType, target: {
18
+ project_ref: string;
19
+ user_id: string;
20
+ }, rows: unknown[]): {
21
+ binding: {
22
+ file: {
23
+ path: string;
24
+ sha256: string;
25
+ bytes: number;
26
+ };
27
+ project_ref: string;
28
+ actor_user_id: string;
29
+ consumers: {
30
+ row_index: number;
31
+ table: string;
32
+ id: string;
33
+ version: string;
34
+ payload_sha256: string;
35
+ }[];
36
+ references: {
37
+ row_index: number;
38
+ path: string;
39
+ selected: EdgeReferenceSnapshot;
40
+ review: {
41
+ file: FoundryInputFact;
42
+ latest: EdgeReferenceSnapshot;
43
+ };
44
+ }[];
45
+ review_files: FoundryInputFact[];
46
+ };
47
+ reviewed: Map<string, {
48
+ selected: EdgeReferenceSnapshot;
49
+ latest: EdgeReferenceSnapshot;
50
+ }>;
51
+ };