@tiangong-lca/foundry 0.1.19 → 0.1.20

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 (51) hide show
  1. package/README.md +5 -3
  2. package/docs/architecture.md +5 -3
  3. package/docs/foundry-task-contracts.md +2 -0
  4. package/docs/package-distribution-contract.md +5 -3
  5. package/docs/public-runtime-contract.md +41 -3
  6. package/docs/runtime-context-contract.md +5 -3
  7. package/docs/task-authorization-contract.md +2 -0
  8. package/package-dist/assets/foundry-package-descriptor.json +142 -74
  9. package/package-dist/scripts/foundry-facade.d.ts +6 -0
  10. package/package-dist/scripts/foundry-facade.js +35 -0
  11. package/package-dist/scripts/foundry-runtime.d.ts +2 -1
  12. package/package-dist/scripts/lib/final-delivery-manifest.d.ts +40 -0
  13. package/package-dist/scripts/lib/final-delivery-manifest.js +145 -0
  14. package/package-dist/scripts/lib/final-delivery-review.d.ts +37 -0
  15. package/package-dist/scripts/lib/final-delivery-review.js +108 -0
  16. package/package-dist/scripts/lib/finalize-owners/native-draft-handoff.js +4 -3
  17. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +3 -0
  18. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +90 -1
  19. package/package-dist/scripts/lib/foundry-edge-session.d.ts +18 -1
  20. package/package-dist/scripts/lib/foundry-edge-session.js +137 -3
  21. package/package-dist/scripts/lib/foundry-edge-support.d.ts +1 -1
  22. package/package-dist/scripts/lib/foundry-interaction-input.js +2 -2
  23. package/package-dist/scripts/lib/foundry-operation-result.d.ts +1 -1
  24. package/package-dist/scripts/lib/foundry-operation-result.js +1 -0
  25. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +3 -2
  26. package/package-dist/scripts/lib/foundry-owner-readback.js +21 -2
  27. package/package-dist/scripts/lib/foundry-package-contract.d.ts +3 -3
  28. package/package-dist/scripts/lib/foundry-package-contract.js +7 -1
  29. package/package-dist/scripts/lib/foundry-repair-census.d.ts +82 -0
  30. package/package-dist/scripts/lib/foundry-repair-census.js +574 -0
  31. package/package-dist/scripts/lib/foundry-repair-scope.d.ts +15 -2
  32. package/package-dist/scripts/lib/foundry-repair-scope.js +62 -10
  33. package/package-dist/scripts/lib/foundry-scientific-repair.d.ts +38 -0
  34. package/package-dist/scripts/lib/foundry-scientific-repair.js +438 -0
  35. package/package-dist/scripts/lib/foundry-semantic-input.js +1 -1
  36. package/package-dist/scripts/lib/foundry-task-input-preparation.d.ts +4 -0
  37. package/package-dist/scripts/lib/foundry-task-input-preparation.js +160 -0
  38. package/package-dist/scripts/lib/foundry-task-registration.js +19 -1
  39. package/package-dist/scripts/lib/foundry-task-types.d.ts +2 -0
  40. package/package-dist/scripts/lib/foundry-workflow-execution.js +3 -0
  41. package/package-dist/scripts/lib/foundry-workflow-repair.d.ts +5 -0
  42. package/package-dist/scripts/lib/foundry-workflow-repair.js +151 -0
  43. package/package-dist/scripts/public-api.d.ts +6 -0
  44. package/package-dist/scripts/runtime-entry.js +15 -6
  45. package/package.json +4 -1
  46. package/specs/schemas/foundry-interaction-draft.schema.json +323 -0
  47. package/specs/schemas/foundry-operation-result.schema.json +1 -0
  48. package/specs/schemas/foundry-package-descriptor.schema.json +4 -1
  49. package/specs/schemas/foundry-scientific-repair.schema.json +66 -0
  50. package/specs/schemas/foundry-semantic-draft.schema.json +50 -0
  51. package/specs/schemas/foundry-task-start.schema.json +10 -2
@@ -0,0 +1,160 @@
1
+ import { registeredAssessmentSetProducerBase } from "./foundry-assessment-producer.js";
2
+ import path from "node:path";
3
+ import { captureFoundryInput, FoundryContextError, resolveFoundryOutput, } from "./foundry-runtime-context.js";
4
+ import { assertNotFoundrySessionFile, migrationCredentialPath } from "./foundry-private-path.js";
5
+ import { advanceFoundryInteractionState, currentFoundryInteractionState, parseFoundryInteractionInput, } from "./foundry-interaction-input.js";
6
+ import { parseFoundrySemanticInput, readSelectedSemanticBytes } from "./foundry-semantic-input.js";
7
+ import { currentFoundryObjectScopes, verifiedFoundryObjectProofs, } from "./foundry-workflow-object-scope.js";
8
+ import { foundryInteractionObjectKey } from "./foundry-interaction-scope.js";
9
+ import { currentWorkflowState, readWorkflowArtifact, workflowObject, } from "./foundry-workflow-state.js";
10
+ function invalid(message) {
11
+ throw new FoundryContextError("task_input_draft_invalid", message);
12
+ }
13
+ function exact(value, keys) {
14
+ if (Object.keys(value).length !== keys.length || keys.some((key) => !Object.hasOwn(value, key)))
15
+ invalid("Input draft has missing or unsupported fields.");
16
+ }
17
+ function selectedFile(context, value) {
18
+ if (typeof value !== "string" || !value || value.length > 4096 || /[\0\r\n]/u.test(value))
19
+ invalid("Input draft file selection must be one bounded path.");
20
+ const file = path.resolve(context.workspaceRoot, value);
21
+ if (migrationCredentialPath(path.relative(context.workspaceRoot, file)))
22
+ invalid("Private files cannot be input draft selections.");
23
+ assertNotFoundrySessionFile(file, context.accountIntent?.sessionReference);
24
+ const fact = captureFoundryInput(file);
25
+ readSelectedSemanticBytes(fact);
26
+ return fact;
27
+ }
28
+ function registeredFile(context, entries, value) {
29
+ const fact = selectedFile(context, value);
30
+ const registered = context.inputs.find((item) => item.path === fact.path) ??
31
+ entries.find((entry) => resolveFoundryOutput(context, entry.path) === fact.path);
32
+ if (!registered || registered.sha256 !== fact.sha256 || registered.bytes !== fact.bytes)
33
+ invalid("Input draft evidence must match a current registered source or artifact's raw file bytes.");
34
+ return fact;
35
+ }
36
+ function currentSemanticTasks(context, entries) {
37
+ const state = currentWorkflowState(context, entries);
38
+ if (!state.assessment)
39
+ invalid("Semantic input preparation requires a current registered assessment.");
40
+ const tasks = new Map();
41
+ for (const set of state.assessment.value.sets) {
42
+ const ownerBase = registeredAssessmentSetProducerBase(context, entries, set);
43
+ for (const raw of Array.isArray(set.decisions) ? set.decisions : []) {
44
+ const decision = workflowObject(raw);
45
+ if (typeof decision.task === "string" && typeof decision.kind === "string")
46
+ tasks.set(path.resolve(ownerBase, decision.task), decision.kind);
47
+ }
48
+ const manifest = registeredFile(context, entries, set.authoring_manifest);
49
+ const entry = entries.find((item) => resolveFoundryOutput(context, item.path) === manifest.path);
50
+ const value = readWorkflowArtifact(context, entry).value;
51
+ if (!Array.isArray(value.tasks))
52
+ invalid("Current assessment authoring manifest has no tasks.");
53
+ for (const raw of value.tasks) {
54
+ const files = workflowObject(workflowObject(raw).files);
55
+ if (typeof files.task_json !== "string")
56
+ invalid("Current authoring task path is missing.");
57
+ tasks.set(path.resolve(ownerBase, files.task_json), "patch");
58
+ }
59
+ }
60
+ return { assessment: state.assessment, tasks };
61
+ }
62
+ /** Derive a strict submission from current indexed facts without registering or executing it. */
63
+ export function prepareFoundryTaskInput(context, entries, targetEntities, kind, draftFile) {
64
+ const selected = selectedFile(context, draftFile);
65
+ let draft;
66
+ try {
67
+ draft = workflowObject(JSON.parse(readSelectedSemanticBytes(selected).toString("utf8")));
68
+ }
69
+ catch (error) {
70
+ if (error instanceof FoundryContextError)
71
+ throw error;
72
+ invalid("Input draft must contain complete JSON.");
73
+ }
74
+ const interaction = currentFoundryInteractionState(context, entries);
75
+ if (kind === "interaction") {
76
+ exact(draft, ["schema", "events"]);
77
+ if (draft.schema !== "tiangong-foundry.interaction-draft.v1" ||
78
+ !Array.isArray(draft.events) ||
79
+ draft.events.length > 16)
80
+ invalid("Interaction draft requires its v1 schema and at most 16 events.");
81
+ const objects = currentFoundryObjectScopes(context, entries);
82
+ const events = draft.events.map((raw) => {
83
+ const event = workflowObject(raw);
84
+ if (Object.hasOwn(event, "evidence_sha256"))
85
+ invalid("Interaction drafts select evidence_files. Submit existing strict digest descriptors directly through resume.");
86
+ const { evidence_files, object_scope, ...fields } = event;
87
+ if (!Array.isArray(evidence_files) || evidence_files.length > 16)
88
+ invalid("Each interaction draft event requires at most 16 evidence_files.");
89
+ const hashes = evidence_files.map((file) => registeredFile(context, entries, file).sha256);
90
+ let scope;
91
+ if (object_scope !== undefined) {
92
+ const selectedScope = workflowObject(object_scope);
93
+ exact(selectedScope, ["entity_id", "version"]);
94
+ if (typeof event.dataset_type !== "string" ||
95
+ typeof selectedScope.entity_id !== "string" ||
96
+ typeof selectedScope.version !== "string")
97
+ invalid("Object scope requires a concrete dataset type, entity_id and version.");
98
+ const current = objects.get(foundryInteractionObjectKey(event.dataset_type, selectedScope.entity_id, selectedScope.version));
99
+ if (!current)
100
+ invalid("Object scope must select one unique current registered row.");
101
+ scope = {
102
+ entity_id: current.entity_id,
103
+ version: current.version,
104
+ row_sha256: current.row_sha256,
105
+ };
106
+ }
107
+ return { ...fields, evidence_sha256: hashes, ...(scope ? { object_scope: scope } : {}) };
108
+ });
109
+ const descriptor = parseFoundryInteractionInput({
110
+ schema: "tiangong-foundry.interaction-input.v1",
111
+ task_id: context.taskId,
112
+ actor_id: context.actorId,
113
+ expected_state_sha256: interaction?.entry.sha256 ?? null,
114
+ events,
115
+ });
116
+ advanceFoundryInteractionState(interaction?.state ?? null, descriptor, interaction?.entry.sha256 ?? null, new Set([
117
+ ...context.inputs.map((item) => item.sha256),
118
+ ...entries.map((item) => item.sha256),
119
+ ]), new Set(targetEntities), verifiedFoundryObjectProofs(context, entries));
120
+ return descriptor;
121
+ }
122
+ exact(draft, ["schema", "submissions"]);
123
+ if (draft.schema !== "tiangong-foundry.semantic-draft.v1" ||
124
+ !Array.isArray(draft.submissions) ||
125
+ draft.submissions.length > 1000)
126
+ invalid("Semantic draft requires its v1 schema and at most 1000 submissions.");
127
+ const current = currentSemanticTasks(context, entries);
128
+ let bytes = selected.bytes;
129
+ const submissions = draft.submissions.map((raw) => {
130
+ const item = workflowObject(raw);
131
+ exact(item, [
132
+ "kind",
133
+ "authoring_task",
134
+ "file",
135
+ ...(Object.hasOwn(item, "decision_ids") ? ["decision_ids"] : []),
136
+ ]);
137
+ const task = registeredFile(context, entries, item.authoring_task);
138
+ if (current.tasks.get(task.path) !== item.kind)
139
+ invalid("Semantic work must select a matching task from the current assessment.");
140
+ const file = selectedFile(context, item.file);
141
+ bytes += file.bytes;
142
+ if (bytes > 64 * 1024 * 1024)
143
+ invalid("Semantic draft selection exceeds 64 MiB.");
144
+ return {
145
+ kind: item.kind,
146
+ authoring_task_sha256: task.sha256,
147
+ file: file.path,
148
+ sha256: file.sha256,
149
+ ...(Object.hasOwn(item, "decision_ids") ? { decision_ids: item.decision_ids } : {}),
150
+ };
151
+ });
152
+ return parseFoundrySemanticInput({
153
+ schema: "tiangong-foundry.semantic-input.v1",
154
+ task_id: context.taskId,
155
+ actor_id: context.actorId,
156
+ assessment_sha256: current.assessment.entry.sha256,
157
+ ...(interaction ? { interaction_sha256: interaction.entry.sha256 } : {}),
158
+ submissions,
159
+ });
160
+ }
@@ -2,7 +2,7 @@ import { assertTaskRuntimeIdentity } from "./foundry-task-runtime-adoption.js";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
- import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, resolveFoundryAsset, resolveFoundryOutput, resolveFoundryInputPath, writeFoundryArtifact, } from "./foundry-runtime-context.js";
5
+ import { assertFoundryRuntimeContext, assertFoundryWorkspaceWrite, assertPendingFoundryTaskIntent, captureFoundryInput, readFoundryInput, resolveFoundryAsset, resolveFoundryOutput, resolveFoundryInputPath, writeFoundryArtifact, } from "./foundry-runtime-context.js";
6
6
  import { sha256Json } from "./identity-preflight-proof.js";
7
7
  import { parseFoundryRepairSelection, readFoundryRepairScope, } from "./foundry-repair-scope.js";
8
8
  import { fail, object, exact, timestamp, bytes, digest, taskPath, readTaskBytes, readTaskJson, reference, facts, sameFact, maxDocumentBytes, } from "./foundry-task-io.js";
@@ -239,6 +239,8 @@ export function createTask(context, options) {
239
239
  : null;
240
240
  if (repairSelection && (options.targetEntities ?? []).join(",") !== "process")
241
241
  fail("task_spec_repair_invalid", "Phase 1 repair admits exactly one target entity type: process.");
242
+ if (repairSelection?.scientific && profileId !== "generic")
243
+ fail("repair_scientific_profile_unsupported", "Scientific repair currently admits the generic profile with complete validation and no profile waivers.");
242
244
  if (![
243
245
  "external-dataset-curated-import",
244
246
  "source-evidence-dataset-development",
@@ -328,6 +330,21 @@ export function createTask(context, options) {
328
330
  verifiedProjectRef: projectRef,
329
331
  stateCode: "0",
330
332
  relativePath: (file) => path.relative(context.workspaceRoot, file),
333
+ ...(repairSelection.scientific
334
+ ? {
335
+ scientific: {
336
+ descriptorFile: boundPath(repairSelection.scientific),
337
+ actorId: context.actorId,
338
+ selectedFiles: context.inputs.map((input) => input.path),
339
+ excludedRuntimeRoots: [
340
+ context.workspaceRoot,
341
+ context.cacheRoot,
342
+ ...context.inputs.map((input) => input.path),
343
+ ],
344
+ read: (file) => readFoundryInput(context, file, 64 * 1024 * 1024),
345
+ },
346
+ }
347
+ : {}),
331
348
  });
332
349
  repairDocuments = [
333
350
  [
@@ -340,6 +357,7 @@ export function createTask(context, options) {
340
357
  rows_sha256: scope.rows_sha256,
341
358
  changed_paths: [...scope.changed_paths],
342
359
  actions: scope.actions.map((action) => ({ ...action })),
360
+ ...(scope.scientific ? { scientific: scope.scientific } : {}),
343
361
  remote_state_verified: false,
344
362
  }),
345
363
  ],
@@ -35,6 +35,7 @@ export interface FoundryTaskJob {
35
35
  contract: string;
36
36
  before: string;
37
37
  candidate: string;
38
+ scientific?: string;
38
39
  predecessor: Readonly<{
39
40
  task_id: string;
40
41
  receipt_sha256: string;
@@ -59,6 +60,7 @@ export interface FoundryTaskOptions {
59
60
  contract: string;
60
61
  before: string;
61
62
  candidate: string;
63
+ scientific?: string;
62
64
  predecessor: Readonly<{
63
65
  task_id: string;
64
66
  receipt_sha256: string;
@@ -24,6 +24,7 @@ import { isEdgeSupportPlan } from "./foundry-edge-support-plan.js";
24
24
  import { createFoundryEdgeActor } from "./foundry-edge-session.js";
25
25
  import { dispatchFoundryEdgeSupport, verifyFoundryEdgeSupport } from "./foundry-edge-support.js";
26
26
  import { createFoundryTypedModelDraft } from "./foundry-typed-model-write.js";
27
+ import { verifyScientificRepairBeforeDispatch } from "./foundry-workflow-repair.js";
27
28
  export async function executeFoundryOwnerScope(context, qualified, entries, requested, authentication = { mode: "oauth" }) {
28
29
  const request = requested.request;
29
30
  const edgePlan = isEdgeSupportPlan(request.content.commit) ? request.content.commit : null;
@@ -69,6 +70,8 @@ export async function executeFoundryOwnerScope(context, qualified, entries, requ
69
70
  if (observation)
70
71
  throw new FoundryContextError("execution_observation_invalid", "Existing dispatch evidence cannot be treated as unattempted.");
71
72
  if (edgePlan) {
73
+ if (edgePlan.update)
74
+ await verifyScientificRepairBeforeDispatch(context, qualified, authentication, requested.entry.sha256);
72
75
  const rows = verifySelectedEdgeDraftPlan(context, edgePlan, captureFoundryInput(request.content.input.path), request.policy);
73
76
  const actor = await createFoundryEdgeActor(context, qualified, authentication);
74
77
  const before = await verifyFoundryEdgeSupport(actor, edgePlan, "before");
@@ -12,6 +12,7 @@ export interface FoundryRepairSelectionFacts {
12
12
  readonly contract: string;
13
13
  readonly before: string;
14
14
  readonly candidate: string;
15
+ readonly scientific?: string;
15
16
  }
16
17
  export interface FoundryRepairPreparationRead {
17
18
  readonly entry: ArtifactEntry;
@@ -33,4 +34,8 @@ export declare function readFoundryRepairPreparation(context: FoundryRuntimeCont
33
34
  * already-registered report without issuing another remote call.
34
35
  */
35
36
  export declare function prepareFoundryRepair(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, _entries: readonly ArtifactEntry[], authentication: FoundryAuthentication): Promise<JsonRecord>;
37
+ /** Fresh observation belongs before the first consumed attempt. Recovery keeps the original write. */
38
+ export declare function verifyScientificRepairBeforeDispatch(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, requestSha256: string): Promise<void>;
39
+ /** Observe the written overlay and all peers again. This cannot close the interval between reads. */
40
+ export declare function verifyScientificRepairAfterReadback(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, authentication: FoundryAuthentication, directory: string): Promise<JsonRecord | null>;
36
41
  export {};
@@ -15,8 +15,11 @@ import { createWorkflowDirectory, createWorkflowStageDirectory } from "./foundry
15
15
  import { readWorkflowArtifact, workflowObject } from "./foundry-workflow-state.js";
16
16
  import { readFoundryRepairScope } from "./foundry-repair-scope.js";
17
17
  import { FOUNDRY_REPAIR_PREPARATION_SCHEMA, parseFoundryRepairDryRunReport, parseFoundryRepairValidateReport, } from "./foundry-repair-preflight.js";
18
+ import { applyScientificRepairProposals, assertScientificRepairDiagnosticReport, runScientificRepairDiagnostic, } from "./foundry-scientific-repair.js";
19
+ import { verifyFoundryRepairCensus } from "./foundry-repair-census.js";
18
20
  import { readTaskJson, relative as taskRelative } from "./foundry-task-io.js";
19
21
  import { sha256Json } from "./identity-preflight-proof.js";
22
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
20
23
  /** The task-store command this owner registers under; the facade owns invoking it. */
21
24
  export const FOUNDRY_REPAIR_PREFLIGHT_COMMAND = "dataset-workflow-repair-preflight";
22
25
  export const FOUNDRY_REPAIR_REPORT_NAME = "foundry-repair-preflight.json";
@@ -86,6 +89,7 @@ export function foundryRepairSelection(context) {
86
89
  contract: repair.contract,
87
90
  before: repair.before,
88
91
  candidate: repair.candidate,
92
+ ...(typeof repair.scientific === "string" ? { scientific: repair.scientific } : {}),
89
93
  });
90
94
  }
91
95
  /**
@@ -111,7 +115,26 @@ function resolveRepairScope(context) {
111
115
  verifiedProjectRef: account.projectRef,
112
116
  stateCode: "0",
113
117
  relativePath: (file) => path.relative(context.workspaceRoot, file),
118
+ ...(selection.scientific
119
+ ? {
120
+ scientific: {
121
+ descriptorFile: resolveFoundryInputPath(context, selection.scientific),
122
+ actorId: context.actorId,
123
+ selectedFiles: context.inputs.map((input) => input.path),
124
+ excludedRuntimeRoots: [
125
+ context.workspaceRoot,
126
+ context.cacheRoot,
127
+ ...context.inputs.map((input) => input.path),
128
+ ],
129
+ read: (file) => readFoundryInput(context, file, MAX_REPORT_BYTES),
130
+ },
131
+ }
132
+ : {}),
114
133
  });
134
+ if (scope.scientific &&
135
+ sha256Json(readTaskJson(context, "repair-scope.json").scientific) !==
136
+ sha256Json(scope.scientific))
137
+ fail("repair_scientific_runtime_changed", "Scientific repair must retain its originally registered source evidence and trusted provider-impact runtime.");
115
138
  return { scope, contractFile, beforeFile, candidateFile };
116
139
  }
117
140
  function expectationOf(context, scope, contractFile) {
@@ -283,6 +306,57 @@ export function readFoundryRepairPreparation(context, entries) {
283
306
  const reference = artifact("references/edge-support-precommit.json");
284
307
  const before = artifact("edge-before.json");
285
308
  const rules = readEdgeRepairValidation(typed, expected);
309
+ if (currentScope.scope.scientific) {
310
+ const native = verified.get("science:provider-impact-report.json");
311
+ const census = verified.get("science:census/proof.json");
312
+ if (!native ||
313
+ !census ||
314
+ native.sha256 !== currentScope.scope.scientific.worker_report.sha256 ||
315
+ Object.values(rules).some((value) => !value))
316
+ fail("repair_report_invalid", "Scientific repair requires indexed exact native provider-impact, complete census and fully passed validation evidence.");
317
+ const proof = readWorkflowArtifact(context, census).value;
318
+ assertScientificRepairDiagnosticReport(readWorkflowArtifact(context, native).value, currentScope.scope.scientific);
319
+ const gates = workflowObject(report.scientific_gates);
320
+ const workerInput = JSON.parse(readFoundryInput(context, currentScope.scope.scientific.worker_input.path, MAX_REPORT_BYTES).toString("utf8"));
321
+ if (proof.schema !== "tiangong-foundry.repair-census.v1" ||
322
+ proof.status !== "verified" ||
323
+ proof.actor_user_id !== context.accountIntent.userId ||
324
+ proof.project_ref !== context.accountIntent.projectRef ||
325
+ proof.input_object_sha256 !== sha256Json(workerInput) ||
326
+ proof.observation_phase !== "before" ||
327
+ proof.double_scan !== true ||
328
+ proof.transaction_snapshot !== false)
329
+ fail("repair_report_invalid", "Scientific repair census must bind the exact registered Worker input, account and complete observed scope.");
330
+ for (const [kind, role] of [
331
+ ["schema", "schema/outputs/validation-report.json"],
332
+ ["cleanup", "cleanup/dataset-curation-cleanup-report.json"],
333
+ ["curation", "curation/dataset-curation-gate-report.json"],
334
+ ]) {
335
+ const entry = verified.get(`edge-repair:out/${role}`);
336
+ const fact = workflowObject(gates[kind]);
337
+ if (!entry || fact.sha256 !== entry.sha256 || fact.bytes !== entry.bytes)
338
+ fail("repair_report_invalid", "Scientific repair requires complete indexed native schema, cleanup and curation producer evidence.");
339
+ const checked = readWorkflowArtifact(context, entry).value;
340
+ if ((kind === "cleanup" && checked.status !== "completed") ||
341
+ (kind === "curation" && checked.status !== "ready"))
342
+ fail("repair_report_invalid", "Scientific repair cannot adopt failed cleanup or curation evidence.");
343
+ }
344
+ }
345
+ if (currentScope.scope.scientific) {
346
+ const gates = workflowObject(report.scientific_gates);
347
+ const projection = verified.get("edge-repair:out/schema-validation-rows.jsonl");
348
+ const projectionFact = workflowObject(gates.schema_projection);
349
+ if (!projection ||
350
+ projection.sha256 !== projectionFact.sha256 ||
351
+ projection.bytes !== projectionFact.bytes)
352
+ fail("repair_report_invalid", "Scientific native validation requires its indexed exact-payload Flow-context projection.");
353
+ const candidateRows = readRows(currentScope.candidateFile);
354
+ const projectedRows = readRows(resolveFoundryOutput(context, projection.path));
355
+ if (candidateRows.length !== projectedRows.length ||
356
+ candidateRows.some((row, index) => sha256Json(datasetIdentity(row, index, "process").payload) !==
357
+ sha256Json(datasetIdentity(projectedRows[index], index, "process").payload)))
358
+ fail("repair_report_invalid", "Scientific native validation projection changed a reviewed write payload.");
359
+ }
286
360
  const beforeValidation = Object.values(rules).includes(false)
287
361
  ? artifact("before-validation/outputs/validation-report.json")
288
362
  : null;
@@ -355,6 +429,23 @@ export async function prepareFoundryRepair(context, qualified, _entries, authent
355
429
  verifyCommands: [FOUNDRY_REPAIR_PREFLIGHT_COMMAND],
356
430
  });
357
431
  try {
432
+ if (scope.scientific) {
433
+ if (qualified.cli.expectation.package_version !== "0.4.0")
434
+ fail("repair_scientific_runtime_unsupported", "Scientific repair requires the qualified typed Process runtime.");
435
+ const directory = path.join(temporary, "science");
436
+ fs.mkdirSync(directory, { mode: 0o700 });
437
+ stagedTrees.push({ name: "science", directory });
438
+ const workerInput = JSON.parse(readFoundryInput(context, scope.scientific.worker_input.path, MAX_REPORT_BYTES).toString("utf8"));
439
+ const census = await verifyFoundryRepairCensus(context, qualified, authentication, workerInput, path.join(directory, "census"));
440
+ const diagnostic = runScientificRepairDiagnostic(scope.scientific, directory);
441
+ applyScientificRepairProposals(context, qualified, temporary, scope.scientific, beforeFile, candidateFile, path.join(directory, "patch"));
442
+ evidenceDetails.push({
443
+ role: "scientific_preflight",
444
+ census: census.proof,
445
+ diagnostic_sha256: scope.scientific.worker_report.sha256,
446
+ affected_processes: diagnostic.affected_processes,
447
+ });
448
+ }
358
449
  if (qualified.cli.expectation.package_version === "0.4.0") {
359
450
  const root = path.join(temporary, "edge-repair");
360
451
  fs.mkdirSync(root, { mode: 0o700 });
@@ -364,6 +455,7 @@ export async function prepareFoundryRepair(context, qualified, _entries, authent
364
455
  candidate: candidateFile,
365
456
  temporary,
366
457
  directory: path.join(root, "out"),
458
+ scientific: scope.scientific,
367
459
  });
368
460
  evidenceDetails.push({ role: "edge_preflight", report });
369
461
  status = scope.status === "dispatchable" ? "prepared" : "no_change_verified";
@@ -592,6 +684,7 @@ export async function prepareFoundryRepair(context, qualified, _entries, authent
592
684
  rows_sha256: scope.rows_sha256,
593
685
  changed_paths: [...scope.changed_paths],
594
686
  actions: scope.actions.map((action) => ({ ...action })),
687
+ ...(scope.scientific ? { scientific: scope.scientific } : {}),
595
688
  },
596
689
  contract: {
597
690
  role: "execution_contract",
@@ -629,3 +722,61 @@ export async function prepareFoundryRepair(context, qualified, _entries, authent
629
722
  fs.rmSync(temporary, { recursive: true, force: true });
630
723
  }
631
724
  }
725
+ /** Fresh observation belongs before the first consumed attempt. Recovery keeps the original write. */
726
+ export async function verifyScientificRepairBeforeDispatch(context, qualified, authentication, requestSha256) {
727
+ const { scope } = resolveRepairScope(context);
728
+ if (!scope.scientific)
729
+ return;
730
+ const evidence = scope.scientific;
731
+ const temporary = createWorkflowDirectory(context, "tmp/scientific-repair-precommit-");
732
+ try {
733
+ const input = JSON.parse(readFoundryInput(context, evidence.worker_input.path, MAX_REPORT_BYTES).toString("utf8"));
734
+ const census = await verifyFoundryRepairCensus(context, qualified, authentication, input, path.join(temporary, "census"));
735
+ await runFoundryTaskOperation(context, {
736
+ command: FOUNDRY_REPAIR_PREFLIGHT_COMMAND,
737
+ options: {
738
+ task: context.taskId,
739
+ stage: "scientific_precommit",
740
+ request_sha256: requestSha256,
741
+ nonce: randomUUID(),
742
+ },
743
+ validateCurrent: () => {
744
+ resolveRepairScope(context);
745
+ },
746
+ }, (operation) => {
747
+ const stage = createWorkflowStageDirectory(context, operation, "scientific-precommit");
748
+ for (const file of census.files) {
749
+ const relative = path.relative(temporary, file);
750
+ if (relative.startsWith("..") || path.isAbsolute(relative))
751
+ fail("repair_census_unproven", "Scientific precommit evidence must remain inside its producer directory.");
752
+ operation.writeText(path.join(stage, relative), fs.readFileSync(file));
753
+ }
754
+ const report = {
755
+ schema: "tiangong-foundry.scientific-repair-precommit.v1",
756
+ request_sha256: requestSha256,
757
+ worker_input: evidence.worker_input,
758
+ observed_census: census.proof,
759
+ remote_writes: 0,
760
+ };
761
+ operation.writeJson(path.join(stage, "scientific-precommit.json"), report);
762
+ return report;
763
+ });
764
+ }
765
+ finally {
766
+ fs.rmSync(temporary, { recursive: true, force: true });
767
+ }
768
+ }
769
+ /** Observe the written overlay and all peers again. This cannot close the interval between reads. */
770
+ export async function verifyScientificRepairAfterReadback(context, qualified, authentication, directory) {
771
+ const { scope } = resolveRepairScope(context);
772
+ if (!scope.scientific)
773
+ return null;
774
+ const input = JSON.parse(readFoundryInput(context, scope.scientific.worker_input.path, MAX_REPORT_BYTES).toString("utf8"));
775
+ const census = await verifyFoundryRepairCensus(context, qualified, authentication, input, directory, "after");
776
+ return {
777
+ original_worker_input: scope.scientific.worker_input,
778
+ observed_census: census.proof,
779
+ concurrent_interval_atomicity: "unproven",
780
+ publication_ready: false,
781
+ };
782
+ }
@@ -57,6 +57,12 @@ export declare function createFoundryFacade(options: FoundryPackageFacadeOptions
57
57
  start(input: {
58
58
  specFile: string;
59
59
  }): Promise<import("./lib/foundry-operation-result.ts").FoundryOperationResult>;
60
+ prepareInput(input: {
61
+ taskId: string;
62
+ actorId: string;
63
+ kind: "interaction" | "semantic";
64
+ draftFile: string;
65
+ }): Promise<import("./lib/foundry-operation-result.ts").FoundryOperationResult>;
60
66
  status(input: {
61
67
  taskId: string;
62
68
  actorId: string;
@@ -34,7 +34,8 @@ function publicCommand(argv) {
34
34
  return { operation: "workspace.init", args: parseArgs(rest) };
35
35
  if (group === "workspace" && action === "migrate")
36
36
  return { operation: "workspace.migrate", args: parseArgs(rest) };
37
- if (group === "task" && ["start", "status", "resume", "adopt-runtime"].includes(action))
37
+ if (group === "task" &&
38
+ ["start", "status", "resume", "adopt-runtime", "prepare-input"].includes(action))
38
39
  return { operation: `task.${action}`, args: parseArgs(rest) };
39
40
  if (group === "workspace" || group === "task")
40
41
  return { operation: "unknown", args: parseArgs([action, ...rest].filter(Boolean)) };
@@ -131,9 +132,11 @@ async function runPublicCommand(parsed, host) {
131
132
  ]
132
133
  : parsed.operation === "task.adopt-runtime"
133
134
  ? ["task", "actor", "dryRun", "apply", "audit", "selection", "plan"]
134
- : parsed.operation === "task.status"
135
- ? ["task", "actor"]
136
- : []),
135
+ : parsed.operation === "task.prepare-input"
136
+ ? ["task", "actor", "kind", "input"]
137
+ : parsed.operation === "task.status"
138
+ ? ["task", "actor"]
139
+ : []),
137
140
  ]);
138
141
  const unknownOption = Object.keys(parsed.args).find((key) => !allowed.has(key));
139
142
  if (unknownOption)
@@ -302,8 +305,14 @@ async function runPublicCommand(parsed, host) {
302
305
  else {
303
306
  const actorId = option(parsed.args.actor, "--actor");
304
307
  if (!taskId || !actorId)
305
- return invalidResult(parsed.operation, taskId, "argument_task_actor_required", "Task status and resume require exact --task and --actor values.");
306
- if (parsed.operation === "task.adopt-runtime") {
308
+ return invalidResult(parsed.operation, taskId, "argument_task_actor_required", "Task operations require exact --task and --actor values.");
309
+ if (parsed.operation === "task.prepare-input") {
310
+ const kind = option(parsed.args.kind, "--kind"), draftFile = option(parsed.args.input, "--input");
311
+ if ((kind !== "interaction" && kind !== "semantic") || !draftFile)
312
+ return invalidResult(parsed.operation, taskId, "argument_input_draft_required", "Input preparation requires --kind interaction|semantic and one --input draft file.");
313
+ result = await facade.prepareInput({ taskId, actorId, kind, draftFile });
314
+ }
315
+ else if (parsed.operation === "task.adopt-runtime") {
307
316
  const modes = [parsed.args.dryRun, parsed.args.apply, parsed.args.audit];
308
317
  if (modes.filter((value) => value === true).length !== 1 ||
309
318
  modes.some((value) => value !== undefined && value !== true))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiangong-lca/foundry",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "type": "module",
5
5
  "description": "Control plane for TianGong LCA external dataset import and TIDAS authoring work.",
6
6
  "repository": {
@@ -41,6 +41,9 @@
41
41
  "specs/schemas/foundry-package-descriptor.schema.json",
42
42
  "specs/schemas/foundry-task-start.schema.json",
43
43
  "specs/schemas/foundry-semantic-input.schema.json",
44
+ "specs/schemas/foundry-semantic-draft.schema.json",
45
+ "specs/schemas/foundry-interaction-draft.schema.json",
46
+ "specs/schemas/foundry-scientific-repair.schema.json",
44
47
  "specs/schemas/foundry-interaction-input.schema.json",
45
48
  "specs/schemas/foundry-authorization-input.schema.json",
46
49
  "specs/schemas/foundry-reference-input.schema.json",