@tiangong-lca/foundry 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +5 -5
  2. package/docs/architecture.md +7 -5
  3. package/docs/foundry-task-contracts.md +4 -4
  4. package/docs/import-profiles/worldsteel/constraints.md +3 -3
  5. package/docs/import-profiles/worldsteel/import-coverage.md +3 -3
  6. package/docs/import-profiles/worldsteel/import-plan.md +4 -4
  7. package/docs/import-profiles/worldsteel/profile.md +3 -3
  8. package/docs/package-distribution-contract.md +9 -9
  9. package/docs/public-runtime-contract.md +8 -6
  10. package/docs/runtime-context-contract.md +3 -3
  11. package/docs/task-authorization-contract.md +3 -3
  12. package/package-dist/assets/foundry-package-descriptor.json +97 -67
  13. package/package-dist/scripts/foundry-facade.js +217 -9
  14. package/package-dist/scripts/lib/foundry-interaction-input.d.ts +4 -3
  15. package/package-dist/scripts/lib/foundry-interaction-input.js +40 -7
  16. package/package-dist/scripts/lib/foundry-interaction-projection.d.ts +21 -2
  17. package/package-dist/scripts/lib/foundry-interaction-projection.js +49 -8
  18. package/package-dist/scripts/lib/foundry-interaction-scope.d.ts +7 -0
  19. package/package-dist/scripts/lib/foundry-interaction-scope.js +40 -0
  20. package/package-dist/scripts/lib/foundry-interaction-types.d.ts +5 -0
  21. package/package-dist/scripts/lib/foundry-native-validation-failure.d.ts +36 -0
  22. package/package-dist/scripts/lib/foundry-native-validation-failure.js +142 -0
  23. package/package-dist/scripts/lib/foundry-owner-execution-store.js +6 -13
  24. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  25. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  26. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  27. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  28. package/package-dist/scripts/lib/foundry-semantic-interaction.d.ts +11 -1
  29. package/package-dist/scripts/lib/foundry-semantic-interaction.js +64 -14
  30. package/package-dist/scripts/lib/foundry-tidas-source.js +4 -4
  31. package/package-dist/scripts/lib/foundry-workflow-approval-continuation.js +3 -0
  32. package/package-dist/scripts/lib/foundry-workflow-assessment.js +27 -2
  33. package/package-dist/scripts/lib/foundry-workflow-authorization.js +3 -0
  34. package/package-dist/scripts/lib/foundry-workflow-interaction.js +22 -3
  35. package/package-dist/scripts/lib/foundry-workflow-object-scope.d.ts +53 -0
  36. package/package-dist/scripts/lib/foundry-workflow-object-scope.js +326 -0
  37. package/package-dist/scripts/lib/foundry-workflow-semantic.d.ts +5 -0
  38. package/package-dist/scripts/lib/foundry-workflow-semantic.js +200 -6
  39. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  40. package/package.json +2 -2
  41. package/specs/import-profiles.json +1 -1
  42. package/specs/schemas/foundry-interaction-input.schema.json +29 -2
  43. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  44. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  45. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,53 @@
1
+ import type { FoundryInteractionState } from "./foundry-interaction-types.ts";
2
+ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
3
+ import type { ArtifactEntry } from "./foundry-task-types.ts";
4
+ export interface CurrentFoundryObject {
5
+ readonly dataset_type: string;
6
+ readonly entity_id: string;
7
+ readonly version: string;
8
+ readonly row_sha256: string;
9
+ }
10
+ export interface IndexedFoundryRowAdoption {
11
+ readonly dataset_type: string;
12
+ readonly object_scope: Readonly<{
13
+ entity_id: string;
14
+ version: string;
15
+ }>;
16
+ readonly work_item_sha256: string;
17
+ readonly before_row_sha256: string;
18
+ readonly after_row_sha256: string;
19
+ readonly decision_ids: readonly string[];
20
+ readonly semantic_result_sha256: string;
21
+ }
22
+ export declare function foundryExplicitObjectIdentity(row: unknown, type: string): {
23
+ entity_id: string;
24
+ version: string;
25
+ } | null;
26
+ /** Read current registered row bytes, never a caller-supplied identity alone. */
27
+ export declare function currentFoundryObjectScopes(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): ReadonlyMap<string, CurrentFoundryObject | null>;
28
+ export declare function verifiedFoundryObjectProofs(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): ReadonlySet<string>;
29
+ export declare function requireCurrentFoundryObject(objects: ReadonlyMap<string, CurrentFoundryObject | null>, type: string, entityId: string, version: string): CurrentFoundryObject;
30
+ export declare function requireUniqueFoundryObjectInRows(file: string, type: string, entityId: string, version: string, reader?: (file: string) => string): CurrentFoundryObject;
31
+ export declare function indexedFoundryRowAdoptions(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): readonly IndexedFoundryRowAdoption[];
32
+ /** A new answer needs its own indexed adoption after earlier semantic work on that object. */
33
+ export declare function currentFoundryObjectDecisionReassessments(state: FoundryInteractionState, objects: ReadonlyMap<string, CurrentFoundryObject | null>, adoptions: readonly IndexedFoundryRowAdoption[], requireEarlierWork?: boolean): ReadonlyArray<{
34
+ readonly dataset_type: string;
35
+ readonly entity_id: string;
36
+ readonly version: string;
37
+ readonly decision_id: string;
38
+ }>;
39
+ export declare function currentFoundryNarrowObjects(state: FoundryInteractionState): ReadonlyArray<{
40
+ dataset_type: string;
41
+ entity_id: string;
42
+ version: string;
43
+ }>;
44
+ /** An old row proof may follow only a recorded, decision-bound semantic successor. */
45
+ export declare function currentFoundryObjectScopeIsBound(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], state: FoundryInteractionState, objects: ReadonlyMap<string, CurrentFoundryObject | null>, type: string, entityId: string, version: string, adoptions?: readonly IndexedFoundryRowAdoption[]): boolean;
46
+ export declare function requireCurrentFoundryObjectScope(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[], state: FoundryInteractionState, objects: ReadonlyMap<string, CurrentFoundryObject | null>, type: string, entityId: string, version: string): CurrentFoundryObject;
47
+ /** Recheck the current indexed interaction before any write approval or approved continuation. */
48
+ export declare function currentFoundryInteractionWriteBlocker(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): Readonly<{
49
+ code: string;
50
+ message: string;
51
+ scope?: string;
52
+ }> | null;
53
+ export declare function assertFoundryInteractionWriteReady(context: FoundryRuntimeContext, entries: readonly ArtifactEntry[]): void;
@@ -0,0 +1,326 @@
1
+ import fs from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { sha256Json } from "./identity-preflight-proof.js";
4
+ import { dataSetInformation, datasetRoot, unwrapDatasetPayload, } from "./import-curation/internal/dataset-payload.js";
5
+ import { readRows } from "./import-curation/internal/runtime-io.js";
6
+ import { foundryInteractionObjectKey, foundryInteractionObjectProofKey, } from "./foundry-interaction-scope.js";
7
+ import { currentFoundryAssumptions, currentFoundryDecisions, currentFoundryInvestigations, currentFoundryQuestions, } from "./foundry-interaction-projection.js";
8
+ import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
9
+ import { FoundryContextError, resolveFoundryOutput, } from "./foundry-runtime-context.js";
10
+ import { currentWorkflowState, readWorkflowArtifact } from "./foundry-workflow-state.js";
11
+ function scopeError(message) {
12
+ throw new FoundryContextError("interaction_scope_invalid", message);
13
+ }
14
+ function record(value) {
15
+ return value && typeof value === "object" && !Array.isArray(value)
16
+ ? value
17
+ : {};
18
+ }
19
+ function readRegisteredRows(context, entries, file) {
20
+ const entry = entries.findLast((candidate) => resolveFoundryOutput(context, candidate.path) === file);
21
+ if (!entry)
22
+ scopeError("Object scope row evidence is not registered in this task.");
23
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
24
+ try {
25
+ const stat = fs.fstatSync(fd);
26
+ if (!stat.isFile() || stat.size !== entry.bytes || stat.size > 128 * 1024 * 1024)
27
+ scopeError("Object scope row evidence has an invalid size or file type.");
28
+ const bytes = fs.readFileSync(fd);
29
+ if (bytes.length !== entry.bytes ||
30
+ createHash("sha256").update(bytes).digest("hex") !== entry.sha256)
31
+ scopeError("Object scope row evidence changed after registration.");
32
+ return bytes.toString("utf8");
33
+ }
34
+ finally {
35
+ fs.closeSync(fd);
36
+ }
37
+ }
38
+ export function foundryExplicitObjectIdentity(row, type) {
39
+ const outer = record(row);
40
+ const root = datasetRoot(unwrapDatasetPayload(row, type), type);
41
+ const information = dataSetInformation(root, type);
42
+ const publication = record(record(root.administrativeInformation).publicationAndOwnership);
43
+ const outerId = outer.id ?? outer[`${type}_id`] ?? outer.dataset_id;
44
+ const payloadId = information["common:UUID"];
45
+ const outerVersion = outer.version;
46
+ const payloadVersion = publication["common:dataSetVersion"];
47
+ if ((typeof outerId === "string" && typeof payloadId === "string" && outerId !== payloadId) ||
48
+ (typeof outerVersion === "string" &&
49
+ typeof payloadVersion === "string" &&
50
+ outerVersion !== payloadVersion))
51
+ return null;
52
+ const id = payloadId ?? outerId;
53
+ const version = payloadVersion ?? outerVersion;
54
+ if (typeof id !== "string" || !id.trim() || typeof version !== "string" || !version.trim())
55
+ return null;
56
+ return { entity_id: id, version };
57
+ }
58
+ /** Read current registered row bytes, never a caller-supplied identity alone. */
59
+ export function currentFoundryObjectScopes(context, entries) {
60
+ const rows = currentWorkflowState(context, entries).rows;
61
+ const objects = new Map();
62
+ if (!rows)
63
+ return objects;
64
+ for (const set of rows.value.sets) {
65
+ const values = readRows(set.file, (file) => readRegisteredRows(context, entries, file));
66
+ if (values.length !== set.count)
67
+ scopeError("Current registered row count changed before object scope binding.");
68
+ for (const row of values) {
69
+ const identity = foundryExplicitObjectIdentity(row, set.type);
70
+ if (!identity)
71
+ continue;
72
+ const key = foundryInteractionObjectKey(set.type, identity.entity_id, identity.version);
73
+ if (objects.has(key)) {
74
+ objects.set(key, null);
75
+ continue;
76
+ }
77
+ objects.set(key, {
78
+ dataset_type: set.type,
79
+ ...identity,
80
+ row_sha256: sha256Json(row),
81
+ });
82
+ }
83
+ }
84
+ return objects;
85
+ }
86
+ export function verifiedFoundryObjectProofs(context, entries) {
87
+ const proofs = new Set();
88
+ for (const item of currentFoundryObjectScopes(context, entries).values()) {
89
+ if (!item)
90
+ continue;
91
+ proofs.add(foundryInteractionObjectProofKey(item.dataset_type, item.entity_id, item.version, item.row_sha256));
92
+ }
93
+ return proofs;
94
+ }
95
+ export function requireCurrentFoundryObject(objects, type, entityId, version) {
96
+ const item = objects.get(foundryInteractionObjectKey(type, entityId, version));
97
+ if (!item)
98
+ scopeError("Object scope is missing or ambiguous in current registered rows; materialize or review the exact row before continuing.");
99
+ return item;
100
+ }
101
+ export function requireUniqueFoundryObjectInRows(file, type, entityId, version, reader) {
102
+ const matches = readRows(file, reader)
103
+ .filter((row) => {
104
+ const identity = foundryExplicitObjectIdentity(row, type);
105
+ return identity?.entity_id === entityId && identity.version === version;
106
+ })
107
+ .map((row) => ({
108
+ dataset_type: type,
109
+ entity_id: entityId,
110
+ version,
111
+ row_sha256: sha256Json(row),
112
+ }));
113
+ if (matches.length !== 1)
114
+ scopeError("Object scope is missing or duplicated in its registered row set.");
115
+ return matches[0];
116
+ }
117
+ function decisionFamily(state, questionId) {
118
+ const answers = state.events.filter((item) => item.kind === "answer" && item.question_id === questionId);
119
+ const current = answers.at(-1);
120
+ const byId = new Map(answers.map((item) => [String(item.decision_id), item]));
121
+ const family = new Set();
122
+ let decision = current;
123
+ while (decision && !family.has(String(decision.decision_id))) {
124
+ family.add(String(decision.decision_id));
125
+ decision = decision.supersedes_decision_id
126
+ ? byId.get(String(decision.supersedes_decision_id))
127
+ : undefined;
128
+ }
129
+ return family;
130
+ }
131
+ export function indexedFoundryRowAdoptions(context, entries) {
132
+ const adoptions = [];
133
+ for (const entry of entries) {
134
+ if (entry.command !== "dataset-semantic-apply" || !entry.path.endsWith("/semantic-result.json"))
135
+ continue;
136
+ const result = readWorkflowArtifact(context, entry).value;
137
+ if (result.status !== "completed" || !Array.isArray(result.row_adoptions))
138
+ continue;
139
+ if (result.row_adoptions.length > 1_000)
140
+ scopeError("Indexed object adoption lineage exceeds its bounded size.");
141
+ if (!Array.isArray(result.adopted_decisions))
142
+ scopeError("Indexed object adoption lineage has no matching decision record.");
143
+ for (const raw of result.row_adoptions) {
144
+ const adoption = record(raw);
145
+ const object = record(adoption.object_scope);
146
+ if (typeof adoption.dataset_type !== "string" ||
147
+ typeof object.entity_id !== "string" ||
148
+ typeof object.version !== "string" ||
149
+ typeof adoption.work_item_sha256 !== "string" ||
150
+ typeof adoption.before_row_sha256 !== "string" ||
151
+ typeof adoption.after_row_sha256 !== "string" ||
152
+ !Array.isArray(adoption.decision_ids) ||
153
+ adoption.decision_ids.some((id) => typeof id !== "string"))
154
+ scopeError("Indexed object adoption lineage is malformed.");
155
+ const declared = result.adopted_decisions.some((rawDecision) => {
156
+ const decision = record(rawDecision);
157
+ const decisionObject = record(decision.object_scope);
158
+ return (decision.work_item_sha256 === adoption.work_item_sha256 &&
159
+ decision.dataset_type === adoption.dataset_type &&
160
+ decisionObject.entity_id === object.entity_id &&
161
+ decisionObject.version === object.version &&
162
+ JSON.stringify(decision.decision_ids) === JSON.stringify(adoption.decision_ids));
163
+ });
164
+ if (!declared)
165
+ scopeError("Indexed row lineage does not match its adopted decision record.");
166
+ adoptions.push({
167
+ dataset_type: adoption.dataset_type,
168
+ object_scope: {
169
+ entity_id: object.entity_id,
170
+ version: object.version,
171
+ },
172
+ work_item_sha256: adoption.work_item_sha256,
173
+ before_row_sha256: adoption.before_row_sha256,
174
+ after_row_sha256: adoption.after_row_sha256,
175
+ decision_ids: adoption.decision_ids,
176
+ semantic_result_sha256: entry.sha256,
177
+ });
178
+ }
179
+ }
180
+ return adoptions;
181
+ }
182
+ function indexedAdoptionLineage(adoptions, scope, originalRowSha256, decisionIds) {
183
+ let known = originalRowSha256;
184
+ const adopted = new Set();
185
+ for (const adoption of adoptions) {
186
+ if (adoption.dataset_type === scope.dataset_type &&
187
+ adoption.object_scope.entity_id === scope.entity_id &&
188
+ adoption.object_scope.version === scope.version &&
189
+ adoption.before_row_sha256 === known &&
190
+ adoption.decision_ids.some((id) => decisionIds.has(id))) {
191
+ known = adoption.after_row_sha256;
192
+ for (const id of adoption.decision_ids)
193
+ adopted.add(id);
194
+ }
195
+ }
196
+ return { current: known === scope.row_sha256, adopted_decision_ids: adopted };
197
+ }
198
+ /** A new answer needs its own indexed adoption after earlier semantic work on that object. */
199
+ export function currentFoundryObjectDecisionReassessments(state, objects, adoptions, requireEarlierWork = true) {
200
+ const questions = new Map(state.events.filter((item) => item.kind === "question").map((item) => [String(item.id), item]));
201
+ const pending = [];
202
+ for (const answer of currentFoundryDecisions(state)) {
203
+ const question = questions.get(String(answer.question_id));
204
+ if (!question || !Object.hasOwn(question, "object_scope"))
205
+ continue;
206
+ const original = record(question.object_scope);
207
+ const type = String(question.dataset_type);
208
+ const entityId = String(original.entity_id);
209
+ const version = String(original.version);
210
+ const current = objects.get(foundryInteractionObjectKey(type, entityId, version));
211
+ if (!current)
212
+ continue; // Missing or ambiguous row is separately marked stale for this object.
213
+ const lineage = indexedAdoptionLineage(adoptions, current, String(original.row_sha256), decisionFamily(state, String(question.id)));
214
+ const hasEarlierObjectWork = adoptions.some((adoption) => adoption.dataset_type === type &&
215
+ adoption.object_scope.entity_id === entityId &&
216
+ adoption.object_scope.version === version);
217
+ if (lineage.current &&
218
+ (!requireEarlierWork || hasEarlierObjectWork) &&
219
+ !lineage.adopted_decision_ids.has(String(answer.decision_id)))
220
+ pending.push({
221
+ dataset_type: type,
222
+ entity_id: entityId,
223
+ version,
224
+ decision_id: String(answer.decision_id),
225
+ });
226
+ }
227
+ return pending;
228
+ }
229
+ export function currentFoundryNarrowObjects(state) {
230
+ const questions = new Map(state.events.filter((item) => item.kind === "question").map((item) => [String(item.id), item]));
231
+ const active = [
232
+ ...currentFoundryQuestions(state),
233
+ ...currentFoundryInvestigations(state),
234
+ ...currentFoundryDecisions(state)
235
+ .map((answer) => questions.get(String(answer.question_id)))
236
+ .filter((item) => item !== undefined),
237
+ ...currentFoundryAssumptions(state),
238
+ ];
239
+ const objects = new Map();
240
+ for (const item of active) {
241
+ if (!Object.hasOwn(item, "object_scope"))
242
+ continue;
243
+ const scope = record(item.object_scope);
244
+ const type = String(item.dataset_type);
245
+ const id = String(scope.entity_id);
246
+ const version = String(scope.version);
247
+ objects.set(foundryInteractionObjectKey(type, id, version), {
248
+ dataset_type: type,
249
+ entity_id: id,
250
+ version,
251
+ });
252
+ }
253
+ return [...objects.values()];
254
+ }
255
+ /** An old row proof may follow only a recorded, decision-bound semantic successor. */
256
+ export function currentFoundryObjectScopeIsBound(context, entries, state, objects, type, entityId, version, adoptions) {
257
+ const current = objects.get(foundryInteractionObjectKey(type, entityId, version));
258
+ if (!current)
259
+ return false;
260
+ const questions = new Map(state.events.filter((item) => item.kind === "question").map((item) => [String(item.id), item]));
261
+ const active = [
262
+ ...currentFoundryQuestions(state),
263
+ ...currentFoundryInvestigations(state),
264
+ ...currentFoundryDecisions(state)
265
+ .map((answer) => questions.get(String(answer.question_id)))
266
+ .filter((item) => item !== undefined),
267
+ ...currentFoundryAssumptions(state),
268
+ ];
269
+ for (const item of active) {
270
+ if (!Object.hasOwn(item, "object_scope") || item.dataset_type !== type)
271
+ continue;
272
+ const scope = record(item.object_scope);
273
+ if (scope.entity_id !== entityId || scope.version !== version)
274
+ continue;
275
+ if (scope.row_sha256 === current.row_sha256)
276
+ continue;
277
+ if (item.kind === "question" &&
278
+ indexedAdoptionLineage(adoptions ?? indexedFoundryRowAdoptions(context, entries), current, String(scope.row_sha256), decisionFamily(state, String(item.id))).current)
279
+ continue;
280
+ return false;
281
+ }
282
+ return true;
283
+ }
284
+ export function requireCurrentFoundryObjectScope(context, entries, state, objects, type, entityId, version) {
285
+ const current = requireCurrentFoundryObject(objects, type, entityId, version);
286
+ if (!currentFoundryObjectScopeIsBound(context, entries, state, objects, type, entityId, version))
287
+ scopeError("Object evidence changed without an indexed decision-bound row successor; review this object again before applying its old choice.");
288
+ return current;
289
+ }
290
+ /** Recheck the current indexed interaction before any write approval or approved continuation. */
291
+ export function currentFoundryInteractionWriteBlocker(context, entries) {
292
+ const interaction = currentFoundryInteractionState(context, entries);
293
+ if (!interaction)
294
+ return null;
295
+ if (currentFoundryQuestions(interaction.state).length ||
296
+ currentFoundryInvestigations(interaction.state).length)
297
+ return {
298
+ code: "interaction_decision_pending",
299
+ message: "Resolve the current question or investigation before a write handoff.",
300
+ };
301
+ const narrow = currentFoundryNarrowObjects(interaction.state);
302
+ if (!narrow.length)
303
+ return null;
304
+ const objects = currentFoundryObjectScopes(context, entries);
305
+ const adoptions = indexedFoundryRowAdoptions(context, entries);
306
+ for (const item of narrow)
307
+ if (!currentFoundryObjectScopeIsBound(context, entries, interaction.state, objects, item.dataset_type, item.entity_id, item.version, adoptions))
308
+ return {
309
+ code: "interaction_object_evidence_changed",
310
+ message: `Review ${item.dataset_type} ${item.entity_id}@${item.version} against its current registered row before a write handoff.`,
311
+ scope: `${item.dataset_type}:${item.entity_id}`,
312
+ };
313
+ const pending = currentFoundryObjectDecisionReassessments(interaction.state, objects, adoptions, false)[0];
314
+ return pending
315
+ ? {
316
+ code: "interaction_object_decision_changed",
317
+ message: `Review and adopt current decision ${pending.decision_id} for ${pending.dataset_type} ${pending.entity_id}@${pending.version} before a write handoff.`,
318
+ scope: `${pending.dataset_type}:${pending.entity_id}`,
319
+ }
320
+ : null;
321
+ }
322
+ export function assertFoundryInteractionWriteReady(context, entries) {
323
+ const blocker = currentFoundryInteractionWriteBlocker(context, entries);
324
+ if (blocker)
325
+ throw new FoundryContextError(blocker.code, blocker.message);
326
+ }
@@ -2,4 +2,9 @@ import { type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
2
  import { type QualifiedFoundryRuntime } from "./foundry-runtime-qualification.ts";
3
3
  import { type SelectedSemanticInput } from "./foundry-semantic-input.ts";
4
4
  import type { ArtifactEntry } from "./foundry-task-types.ts";
5
+ import { type SemanticObjectIdentity } from "./foundry-semantic-interaction.ts";
6
+ /** Index only selected identities while reading one row set once. Null marks an ambiguous match. */
7
+ export declare function indexedFoundryAdoptionRows(file: string, type: string, selectedKeys: ReadonlySet<string>, reader?: (file: string) => string): ReadonlyMap<string, string | null>;
8
+ /** Keep one target per object even when a decision queue has several paths or categories. */
9
+ export declare function indexedFoundryDecisionWorkObjects(kind: "classification" | "location" | "identity", ownerType: string, targets: readonly unknown[]): readonly SemanticObjectIdentity[];
5
10
  export declare function applyFoundrySemanticInput(context: FoundryRuntimeContext, qualified: QualifiedFoundryRuntime, entries: readonly ArtifactEntry[], submission: SelectedSemanticInput): Promise<import("./foundry-task-types.ts").JsonRecord>;
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { FoundryContextError, readFoundryInput, resolveFoundryOutput, } from "./foundry-runtime-context.js";
4
5
  import { assertQualifiedFoundryRuntime, } from "./foundry-runtime-qualification.js";
5
6
  import { assertSelectedSemanticInput, readSelectedSemanticBytes, } from "./foundry-semantic-input.js";
@@ -11,7 +12,10 @@ import { readJsonOrJsonl, ensureArray, readRows } from "./import-curation/intern
11
12
  import { createFoundryDecisionOwners } from "./foundry-decision-owners.js";
12
13
  import { applyFoundryIdentityDecisions } from "./foundry-workflow-identity-apply.js";
13
14
  import { currentFoundryInteractionState } from "./foundry-interaction-input.js";
14
- import { verifyFoundrySemanticInteraction } from "./foundry-semantic-interaction.js";
15
+ import { verifyFoundrySemanticInteraction, } from "./foundry-semantic-interaction.js";
16
+ import { currentFoundryObjectScopes, currentFoundryNarrowObjects, foundryExplicitObjectIdentity, requireCurrentFoundryObject, requireCurrentFoundryObjectScope, } from "./foundry-workflow-object-scope.js";
17
+ import { foundryInteractionObjectKey } from "./foundry-interaction-scope.js";
18
+ import { sha256Json } from "./identity-preflight-proof.js";
15
19
  import { operationFullContextEvidenceBlockers, operationUsedContextKinds, patchPayloadPatchSets, patchSetOperations, taskRequiredContextKinds, } from "./import-curation/internal/workflow-authoring-tasks.js";
16
20
  function fail(code, message) {
17
21
  throw new FoundryContextError(code, message);
@@ -21,6 +25,89 @@ function text(value, label) {
21
25
  fail("semantic_work_invalid", `${label} is missing.`);
22
26
  return value;
23
27
  }
28
+ /** Index only selected identities while reading one row set once. Null marks an ambiguous match. */
29
+ export function indexedFoundryAdoptionRows(file, type, selectedKeys, reader) {
30
+ const indexed = new Map();
31
+ for (const row of readRows(file, reader)) {
32
+ const identity = foundryExplicitObjectIdentity(row, type);
33
+ if (!identity)
34
+ continue;
35
+ const key = foundryInteractionObjectKey(type, identity.entity_id, identity.version);
36
+ if (!selectedKeys.has(key))
37
+ continue;
38
+ indexed.set(key, indexed.has(key) ? null : sha256Json(row));
39
+ }
40
+ return indexed;
41
+ }
42
+ function uniqueAdoptionRowSha(indexed, key) {
43
+ const sha = indexed.get(key);
44
+ if (!sha)
45
+ fail("interaction_scope_invalid", "Object scope is missing or duplicated in its registered row set.");
46
+ return sha;
47
+ }
48
+ /** Keep one target per object even when a decision queue has several paths or categories. */
49
+ export function indexedFoundryDecisionWorkObjects(kind, ownerType, targets) {
50
+ if (!targets.length)
51
+ fail("semantic_work_scope_invalid", "The registered decision task has no target objects.");
52
+ const objects = new Map();
53
+ for (const raw of targets) {
54
+ const target = workflowObject(raw);
55
+ const type = text(target.dataset_type, "Decision target dataset type");
56
+ const entityId = text(target.dataset_id, "Decision target entity id");
57
+ const version = text(target.dataset_version, "Decision target version");
58
+ if (!type.trim() || !entityId.trim() || !version.trim())
59
+ fail("semantic_work_scope_invalid", "Decision target needs an explicit id and version.");
60
+ if (type !== ownerType)
61
+ fail("semantic_work_scope_invalid", `${kind} decision task targets another row type; review the exact target and reassess it separately before applying scoped human decisions.`);
62
+ objects.set(foundryInteractionObjectKey(type, entityId, version), {
63
+ dataset_type: type,
64
+ entity_id: entityId,
65
+ version,
66
+ });
67
+ if (objects.size > 1_000)
68
+ fail("semantic_work_scope_invalid", "Decision task spans more than 1,000 objects; split and reassess exact target batches.");
69
+ }
70
+ return [...objects.values()];
71
+ }
72
+ function registeredDecisionWorkObjects(context, entries, item) {
73
+ const taskEntry = entries.find((entry) => resolveFoundryOutput(context, entry.path) === item.task);
74
+ if (!taskEntry || taskEntry.sha256 !== item.sha)
75
+ fail("semantic_work_unregistered", "Decision target task is not the registered work item.");
76
+ const task = readWorkflowArtifact(context, taskEntry).value;
77
+ if (task.task_kind !== `${item.kind}_decision_authoring`)
78
+ fail("semantic_work_scope_invalid", "Decision task kind differs from its assessed owner.");
79
+ if (item.kind === "identity") {
80
+ if (!Array.isArray(task.identity_action_items) ||
81
+ Number(workflowObject(task.counts).selected_unique_identity_targets) !==
82
+ task.identity_action_items.length)
83
+ fail("semantic_work_scope_invalid", "Identity task has no exact target roster.");
84
+ return indexedFoundryDecisionWorkObjects(item.kind, item.type, task.identity_action_items);
85
+ }
86
+ if (!item.queue)
87
+ fail("semantic_work_scope_invalid", "Decision task has no registered target queue.");
88
+ const queueEntry = entries.find((entry) => resolveFoundryOutput(context, entry.path) === item.queue);
89
+ if (!queueEntry)
90
+ fail("semantic_work_unregistered", "Decision target queue is not registered in this task.");
91
+ const declaredQueue = text(task[`${item.kind}_queue`], "Decision task queue");
92
+ if (path.resolve(context.assetRoot, declaredQueue) !== item.queue)
93
+ fail("semantic_work_scope_invalid", "Decision task and assessed queue differ.");
94
+ const bytes = readFoundryInput(context, item.queue);
95
+ if (bytes.length !== queueEntry.bytes ||
96
+ createHash("sha256").update(bytes).digest("hex") !== queueEntry.sha256)
97
+ fail("semantic_work_scope_invalid", "Registered decision queue bytes changed.");
98
+ const targets = ensureArray(readJsonOrJsonl(item.queue, () => bytes.toString("utf8")));
99
+ if (!Array.isArray(task[`${item.kind}_queue_rows`]) ||
100
+ JSON.stringify(targets) !== JSON.stringify(task[`${item.kind}_queue_rows`]) ||
101
+ Number(workflowObject(task.counts).queue_rows) !== targets.length)
102
+ fail("semantic_work_scope_invalid", "Decision task target queue is inconsistent.");
103
+ for (const raw of targets) {
104
+ const target = workflowObject(raw);
105
+ if (typeof target.source_file !== "string" ||
106
+ path.resolve(context.assetRoot, target.source_file) !== item.rows)
107
+ fail("semantic_work_scope_invalid", "Decision queue targets a different assessed row set.");
108
+ }
109
+ return indexedFoundryDecisionWorkObjects(item.kind, item.type, targets);
110
+ }
24
111
  function priorApplication(context, entries, submission) {
25
112
  for (const entry of [...entries].reverse()) {
26
113
  if (entry.command !== "dataset-semantic-apply" ||
@@ -119,12 +206,42 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
119
206
  fail("task_semantic_owner_conflict", "Submit one decision/patch owner per row set, then reassess before the next owner.");
120
207
  rowOwners.add(item.type);
121
208
  }
209
+ const narrowObjects = interaction ? currentFoundryNarrowObjects(interaction.state) : [];
210
+ const narrowTypes = new Set(narrowObjects.map((item) => item.dataset_type));
211
+ const currentObjects = narrowTypes.size ? currentFoundryObjectScopes(context, entries) : null;
122
212
  const selectedScopes = new Map();
123
213
  for (const group of work)
124
- for (const item of group.tasks)
125
- selectedScopes.set(item.sha, text(group.set.type, "Dataset type"));
126
- for (const item of decisionWork)
127
- selectedScopes.set(item.sha, item.type);
214
+ for (const item of group.tasks) {
215
+ const type = text(group.set.type, "Dataset type");
216
+ if (!narrowTypes.has(type)) {
217
+ selectedScopes.set(item.sha, type);
218
+ continue;
219
+ }
220
+ const entity = workflowObject(item.task.entity);
221
+ if (entity.dataset_type !== type)
222
+ fail("semantic_work_invalid", "Authoring task entity type differs from its assessed row set.");
223
+ const entityId = text(entity.entity_id, "Authoring entity id");
224
+ const version = text(entity.version, "Authoring entity version");
225
+ if (interaction)
226
+ requireCurrentFoundryObjectScope(context, entries, interaction.state, currentObjects, type, entityId, version);
227
+ else
228
+ requireCurrentFoundryObject(currentObjects, type, entityId, version);
229
+ selectedScopes.set(item.sha, { dataset_type: type, entity_id: entityId, version });
230
+ }
231
+ for (const item of decisionWork) {
232
+ if (!narrowTypes.has(item.type) && !(item.kind === "identity" && narrowTypes.size)) {
233
+ selectedScopes.set(item.sha, item.type);
234
+ continue;
235
+ }
236
+ const objects = registeredDecisionWorkObjects(context, entries, item);
237
+ if (item.kind === "identity" &&
238
+ narrowTypes.has("process") &&
239
+ objects.some((object) => object.dataset_type === "flow"))
240
+ fail("semantic_identity_scope_unverifiable", "Flow identity may rewrite Process references with active object decisions. Review or separate those Process objects before submitting this identity task.");
241
+ for (const object of objects)
242
+ requireCurrentFoundryObjectScope(context, entries, interaction.state, currentObjects, object.dataset_type, object.entity_id, object.version);
243
+ selectedScopes.set(item.sha, objects);
244
+ }
128
245
  const adoptedDecisions = verifyFoundrySemanticInteraction(submission.spec, interaction ? { sha256: interaction.entry.sha256, state: interaction.state } : null, selectedScopes);
129
246
  return runFoundryTaskOperation(context, {
130
247
  command: "dataset-semantic-apply",
@@ -353,6 +470,79 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
353
470
  for (const input of context.inputs)
354
471
  readFoundryInput(context, input.path);
355
472
  assertQualifiedFoundryRuntime(context, qualified);
473
+ if (!blockers.length && decisionWork.length && narrowObjects.length) {
474
+ const decisionTargetKeys = new Set(adoptedDecisions
475
+ .filter((adopted) => decisionWork.some((item) => item.sha === adopted.work_item_sha256))
476
+ .filter((adopted) => adopted.object_scope)
477
+ .map((adopted) => foundryInteractionObjectKey(adopted.dataset_type, adopted.object_scope.entity_id, adopted.object_scope.version)));
478
+ const narrowByUpdatedType = new Map();
479
+ for (const object of narrowObjects) {
480
+ if (!updated.has(object.dataset_type))
481
+ continue;
482
+ const selected = narrowByUpdatedType.get(object.dataset_type) ?? new Set();
483
+ selected.add(foundryInteractionObjectKey(object.dataset_type, object.entity_id, object.version));
484
+ narrowByUpdatedType.set(object.dataset_type, selected);
485
+ }
486
+ for (const [type, keys] of narrowByUpdatedType) {
487
+ const after = indexedFoundryAdoptionRows(updated.get(type).file, type, keys);
488
+ for (const key of keys) {
489
+ const before = currentObjects.get(key);
490
+ if (!before)
491
+ fail("semantic_work_scope_invalid", "A reviewed object is missing or ambiguous in the current row set; recheck that exact object before applying decisions to this row set.");
492
+ if (after.get(key) === before.row_sha256)
493
+ continue;
494
+ if (decisionWork.some((item) => item.kind === "identity"))
495
+ fail("semantic_identity_scope_unverifiable", "Identity decisions changed a reviewed object or its references without a stable row successor. Reassess that exact object before continuing.");
496
+ if (!decisionTargetKeys.has(key))
497
+ fail("semantic_work_scope_invalid", "A decision task changed a reviewed object outside its registered target queue; reassess the affected object and decision task.");
498
+ }
499
+ }
500
+ }
501
+ const adoptionKeysByType = new Map();
502
+ if (!blockers.length)
503
+ for (const adopted of adoptedDecisions) {
504
+ const object = adopted.object_scope;
505
+ if (!object)
506
+ continue;
507
+ const keys = adoptionKeysByType.get(adopted.dataset_type) ?? new Set();
508
+ keys.add(foundryInteractionObjectKey(adopted.dataset_type, object.entity_id, object.version));
509
+ adoptionKeysByType.set(adopted.dataset_type, keys);
510
+ }
511
+ const adoptionRowsByType = new Map();
512
+ for (const [type, keys] of adoptionKeysByType) {
513
+ const before = rows.value.sets.find((set) => set.type === type);
514
+ const after = updated.get(type);
515
+ if (!before || !after)
516
+ fail("semantic_row_scope_changed", "Object adoption has no exact row successor.");
517
+ adoptionRowsByType.set(type, {
518
+ before: indexedFoundryAdoptionRows(before.file, type, keys, (file) => readFoundryInput(context, file).toString("utf8")),
519
+ after: indexedFoundryAdoptionRows(after.file, type, keys),
520
+ });
521
+ }
522
+ const rowAdoptions = blockers.length
523
+ ? []
524
+ : adoptedDecisions.flatMap((adopted) => {
525
+ const object = adopted.object_scope;
526
+ if (!object)
527
+ return [];
528
+ const key = foundryInteractionObjectKey(adopted.dataset_type, object.entity_id, object.version);
529
+ const indexed = adoptionRowsByType.get(adopted.dataset_type);
530
+ if (!indexed)
531
+ fail("semantic_row_scope_changed", "Object adoption has no exact row successor.");
532
+ if (!indexed.after.get(key) &&
533
+ decisionWork.some((item) => item.sha === adopted.work_item_sha256 && item.kind === "identity"))
534
+ fail("semantic_identity_scope_unverifiable", "Identity decision removed or duplicated a target object, so its object-level adoption cannot be proven. Review that exact identity outcome before continuing.");
535
+ return [
536
+ {
537
+ dataset_type: adopted.dataset_type,
538
+ object_scope: object,
539
+ work_item_sha256: adopted.work_item_sha256,
540
+ before_row_sha256: uniqueAdoptionRowSha(indexed.before, key),
541
+ after_row_sha256: uniqueAdoptionRowSha(indexed.after, key),
542
+ decision_ids: adopted.decision_ids,
543
+ },
544
+ ];
545
+ });
356
546
  registerWorkflowStageFiles(context, operation, output);
357
547
  if (!blockers.length)
358
548
  operation.writeJson(path.join(output, "foundry-rows.json"), {
@@ -372,7 +562,11 @@ export async function applyFoundrySemanticInput(context, qualified, entries, sub
372
562
  assessment_sha256: assessment.entry.sha256,
373
563
  work_items: [...used],
374
564
  ...(interaction
375
- ? { interaction_sha256: interaction.entry.sha256, adopted_decisions: adoptedDecisions }
565
+ ? {
566
+ interaction_sha256: interaction.entry.sha256,
567
+ adopted_decisions: adoptedDecisions,
568
+ ...(rowAdoptions.length ? { row_adoptions: rowAdoptions } : {}),
569
+ }
376
570
  : {}),
377
571
  results,
378
572
  blockers,
@@ -6,7 +6,7 @@ import { asText, directoryExists, ensureArray, fileExists, readJson, readText, r
6
6
  function asJsonRecord(value) {
7
7
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8
8
  }
9
- export const tidasSchemaSearchRoots = ["@tiangong-lca/cli@0.1.19/assets/tidas-schemas"];
9
+ export const tidasSchemaSearchRoots = ["@tiangong-lca/cli@0.1.22/assets/tidas-schemas"];
10
10
  export function tidasSchemaPath(repoRoot, schemaFile) {
11
11
  void repoRoot;
12
12
  const candidate = path.join(resolveInstalledTiangongLcaCliPackage().schemaDir, schemaFile);