farseer-cli 1.15.0 → 1.17.0
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.
- package/README.md +328 -0
- package/dist/commands/code.js +104 -0
- package/dist/commands/code.js.map +7 -0
- package/dist/commands/model.js +14 -4
- package/dist/commands/model.js.map +2 -2
- package/dist/index.js +16 -0
- package/dist/index.js.map +2 -2
- package/dist/pipeline/generated-reference.json +30 -30
- package/dist/pipeline/service.js +2 -2
- package/dist/pipeline/service.js.map +2 -2
- package/dist/services/codefirst/api.js +269 -0
- package/dist/services/codefirst/api.js.map +7 -0
- package/dist/services/codefirst/binaryDisk.js +67 -0
- package/dist/services/codefirst/binaryDisk.js.map +7 -0
- package/dist/services/codefirst/byteHashes.js +129 -0
- package/dist/services/codefirst/byteHashes.js.map +7 -0
- package/dist/services/codefirst/documents.js +563 -0
- package/dist/services/codefirst/documents.js.map +7 -0
- package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
- package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
- package/dist/services/codefirst/layoutCompose.js +593 -0
- package/dist/services/codefirst/layoutCompose.js.map +7 -0
- package/dist/services/codefirst/layoutCore.js +260 -0
- package/dist/services/codefirst/layoutCore.js.map +7 -0
- package/dist/services/codefirst/layoutPaths.js +492 -0
- package/dist/services/codefirst/layoutPaths.js.map +7 -0
- package/dist/services/codefirst/layoutProjection.js +995 -0
- package/dist/services/codefirst/layoutProjection.js.map +7 -0
- package/dist/services/codefirst/layoutReadback.js +2552 -0
- package/dist/services/codefirst/layoutReadback.js.map +7 -0
- package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
- package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
- package/dist/services/codefirst/layoutReceipt.js +1592 -0
- package/dist/services/codefirst/layoutReceipt.js.map +7 -0
- package/dist/services/codefirst/layoutScan.js +882 -0
- package/dist/services/codefirst/layoutScan.js.map +7 -0
- package/dist/services/codefirst/output.js +179 -0
- package/dist/services/codefirst/output.js.map +7 -0
- package/dist/services/codefirst/types.js +17 -0
- package/dist/services/codefirst/types.js.map +7 -0
- package/dist/services/codefirst/workflow.js +581 -0
- package/dist/services/codefirst/workflow.js.map +7 -0
- package/dist/services/codefirst/workspace.js +310 -0
- package/dist/services/codefirst/workspace.js.map +7 -0
- package/dist/services/codefirst/workspaceLock.js +148 -0
- package/dist/services/codefirst/workspaceLock.js.map +7 -0
- package/dist/services/codefirst/workspaceRoot.js +147 -0
- package/dist/services/codefirst/workspaceRoot.js.map +7 -0
- package/dist/utils/logger.js +9 -3
- package/dist/utils/logger.js.map +2 -2
- package/docs/pipeline-client-guide.md +2 -2
- package/docs/pipeline-reference.md +156 -99
- package/package.json +3 -2
- package/skills/pipeline-authoring/SKILL.md +10 -8
- package/skills/pipeline-authoring/practices.md +39 -25
|
@@ -0,0 +1,1592 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var layoutReceipt_exports = {};
|
|
30
|
+
__export(layoutReceipt_exports, {
|
|
31
|
+
createLayoutDestinationDirectories: () => createLayoutDestinationDirectories,
|
|
32
|
+
exitAfterWrites: () => exitAfterWrites,
|
|
33
|
+
layoutReceiptDrafts: () => layoutReceiptDrafts,
|
|
34
|
+
materializeLayoutPlan: () => materializeLayoutPlan,
|
|
35
|
+
materializeLayoutRemovals: () => materializeLayoutRemovals,
|
|
36
|
+
quarantinedApplyAdvice: () => quarantinedApplyAdvice,
|
|
37
|
+
refuseUnwrittenReceipts: () => refuseUnwrittenReceipts,
|
|
38
|
+
removeLayoutState: () => removeLayoutState,
|
|
39
|
+
vacateLayoutAliases: () => vacateLayoutAliases
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(layoutReceipt_exports);
|
|
42
|
+
var fs = __toESM(require("fs"));
|
|
43
|
+
var path = __toESM(require("path"));
|
|
44
|
+
var import_crypto = require("crypto");
|
|
45
|
+
var import_binaryDisk = require("./binaryDisk");
|
|
46
|
+
var import_documents = require("./documents");
|
|
47
|
+
var import_layoutCompose = require("./layoutCompose");
|
|
48
|
+
var import_layoutCore = require("./layoutCore");
|
|
49
|
+
var import_layoutPaths = require("./layoutPaths");
|
|
50
|
+
var import_layoutProjection = require("./layoutProjection");
|
|
51
|
+
var import_layoutReadback = require("./layoutReadback");
|
|
52
|
+
var import_layoutScan = require("./layoutScan");
|
|
53
|
+
var import_farseer_client = require("farseer-client");
|
|
54
|
+
var import_workspace = require("./workspace");
|
|
55
|
+
function same(left, right) {
|
|
56
|
+
try {
|
|
57
|
+
return (0, import_documents.canonicalEqual)(left, right);
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function persistedEvidence(state) {
|
|
63
|
+
const evidence = state.layout.evidence;
|
|
64
|
+
return {
|
|
65
|
+
groupedRoutes: (0, import_layoutCore.clone)(evidence.groupedRoutes),
|
|
66
|
+
binaryRoutes: (0, import_layoutCore.clone)(evidence.binaryRoutes),
|
|
67
|
+
groupedSubmissionProofs: [],
|
|
68
|
+
binarySubmissionProofs: [],
|
|
69
|
+
derivedSourceProofs: (0, import_layoutCore.clone)(evidence.derivedSourceProofs),
|
|
70
|
+
rawNavigationRoutes: (0, import_layoutCore.clone)(evidence.rawNavigationRoutes),
|
|
71
|
+
canonicalBaseline: (0, import_layoutCore.clone)(state.baseline),
|
|
72
|
+
detachedFileProofs: (0, import_layoutCore.clone)(evidence.detachedFileProofs),
|
|
73
|
+
detachedDocumentProofs: (0, import_layoutCore.clone)(evidence.detachedDocumentProofs)
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function managedJsonArtifacts(scan) {
|
|
77
|
+
return scan.artifacts.filter(
|
|
78
|
+
(artifact) => artifact.present && !["raw", "attachment"].includes(artifact.role) && artifact.json !== void 0
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
function expectedBytePaths(scan, evidence) {
|
|
82
|
+
const expected = new Set(
|
|
83
|
+
scan.artifacts.filter((artifact) => artifact.role === "raw" || artifact.role === "attachment").map((artifact) => artifact.path)
|
|
84
|
+
);
|
|
85
|
+
for (const route of evidence.binaryRoutes) if (route.bytes) expected.add(route.bytes);
|
|
86
|
+
return expected;
|
|
87
|
+
}
|
|
88
|
+
function snapshotSeedDiagnostics(state, snapshot) {
|
|
89
|
+
const diagnostics = [];
|
|
90
|
+
const expectedJson = new Map(managedJsonArtifacts(snapshot.scan).map((artifact) => [artifact.path, artifact]));
|
|
91
|
+
const actualJsonPaths = Object.keys(snapshot.jsonText);
|
|
92
|
+
for (const [file, artifact] of expectedJson) {
|
|
93
|
+
const text = snapshot.jsonText[file];
|
|
94
|
+
if (typeof text !== "string") {
|
|
95
|
+
diagnostics.push((0, import_layoutCore.diagnostic)("missing-layout-json-text", file, "Managed JSON text is missing"));
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
if (!same(JSON.parse(text), artifact.json))
|
|
100
|
+
diagnostics.push(
|
|
101
|
+
(0, import_layoutCore.diagnostic)("layout-json-text-mismatch", file, "Managed JSON text does not match scan")
|
|
102
|
+
);
|
|
103
|
+
} catch {
|
|
104
|
+
diagnostics.push((0, import_layoutCore.diagnostic)("invalid-layout-json-text", file, "Managed JSON text is invalid"));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
for (const file of actualJsonPaths)
|
|
108
|
+
if (!expectedJson.has(file))
|
|
109
|
+
diagnostics.push(
|
|
110
|
+
(0, import_layoutCore.diagnostic)("extra-layout-json-text", file, "JSON text does not identify a managed JSON artifact")
|
|
111
|
+
);
|
|
112
|
+
const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));
|
|
113
|
+
if (persistentTracked.size !== snapshot.scan.tracked.length)
|
|
114
|
+
diagnostics.push(
|
|
115
|
+
(0, import_layoutCore.diagnostic)("layout-tracking-mismatch", ".", "Tracked mapping does not match the supplied scan")
|
|
116
|
+
);
|
|
117
|
+
for (const tracked of snapshot.scan.tracked) {
|
|
118
|
+
const original = persistentTracked.get(tracked.route);
|
|
119
|
+
if (!original || original.path !== tracked.path)
|
|
120
|
+
diagnostics.push(
|
|
121
|
+
(0, import_layoutCore.diagnostic)("layout-tracking-mismatch", tracked.path, "Tracked mapping does not match the scan")
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
return diagnostics;
|
|
125
|
+
}
|
|
126
|
+
function snapshotPathDiagnostics(state, snapshot, evidence) {
|
|
127
|
+
const diagnostics = [];
|
|
128
|
+
const expectedBytes = expectedBytePaths(snapshot.scan, evidence);
|
|
129
|
+
const byteFacts = new Map(snapshot.byteFacts.map((fact) => [fact.path, fact]));
|
|
130
|
+
const pathFacts = /* @__PURE__ */ new Map();
|
|
131
|
+
for (const fact of snapshot.pathFacts) {
|
|
132
|
+
if (pathFacts.has(fact.path)) throw new Error(`Path fact ${JSON.stringify(fact.path)} is duplicated`);
|
|
133
|
+
pathFacts.set(fact.path, fact);
|
|
134
|
+
}
|
|
135
|
+
const requireState = (file, state2, message) => {
|
|
136
|
+
if (pathFacts.get(file)?.state !== state2)
|
|
137
|
+
diagnostics.push((0, import_layoutCore.diagnostic)("layout-path-fact-mismatch", file, message));
|
|
138
|
+
};
|
|
139
|
+
for (const artifact of snapshot.scan.artifacts)
|
|
140
|
+
requireState(artifact.path, artifact.present ? "file" : "absent", "Artifact path fact does not match scan");
|
|
141
|
+
for (const directory of snapshot.scan.opaqueDirectories)
|
|
142
|
+
if ((0, import_layoutPaths.isPortableWorkspacePointer)(directory))
|
|
143
|
+
requireState(directory, "directory", "Opaque directory fact is missing");
|
|
144
|
+
const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));
|
|
145
|
+
for (const tracked of snapshot.scan.tracked) {
|
|
146
|
+
const original = persistentTracked.get(tracked.route);
|
|
147
|
+
if (!original || original.path !== tracked.path) continue;
|
|
148
|
+
const fact = pathFacts.get(original.path);
|
|
149
|
+
if (tracked.status === "present") {
|
|
150
|
+
requireState(tracked.path, original.kind, "Tracked path fact does not match scan");
|
|
151
|
+
} else if (fact?.state !== "absent" || tracked.status === "missing-subtree" && fact.missingAncestor !== tracked.missingAncestor)
|
|
152
|
+
diagnostics.push(
|
|
153
|
+
(0, import_layoutCore.diagnostic)("layout-path-fact-mismatch", tracked.path, "Tracked absence fact does not match scan")
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
for (const file of expectedBytes) {
|
|
157
|
+
const byte = byteFacts.get(file);
|
|
158
|
+
const physical = pathFacts.get(file);
|
|
159
|
+
if (byte && (byte.state === "present" && physical?.state !== "file" || byte.state === "absent" && physical?.state !== "absent"))
|
|
160
|
+
diagnostics.push((0, import_layoutCore.diagnostic)("layout-byte-path-mismatch", file, "Byte and path facts disagree"));
|
|
161
|
+
}
|
|
162
|
+
return diagnostics;
|
|
163
|
+
}
|
|
164
|
+
function compositionIndex(composition) {
|
|
165
|
+
const bySource = (items, key) => (0, import_layoutCore.groupBySource)(items, key);
|
|
166
|
+
return {
|
|
167
|
+
composition,
|
|
168
|
+
sources: bySource(composition.sources, (item) => (0, import_layoutCore.sourceIdentityKey)(item.mapping.source)),
|
|
169
|
+
groupedObservations: bySource(composition.grouped.observations, (item) => (0, import_layoutCore.sourceIdentityKey)(item.source)),
|
|
170
|
+
rawObservations: bySource(composition.binary.rawObservations, (item) => (0, import_layoutCore.sourceIdentityKey)(item.source)),
|
|
171
|
+
attachmentObservations: bySource(
|
|
172
|
+
composition.binary.attachmentObservations,
|
|
173
|
+
(item) => (0, import_layoutCore.sourceIdentityKey)(item.source)
|
|
174
|
+
),
|
|
175
|
+
ownerFields: bySource(composition.binary.ownerFields, (item) => (0, import_layoutCore.sourceIdentityKey)(item.ownerSource)),
|
|
176
|
+
binaryRoutes: bySource(composition.context.evidence.binaryRoutes, (item) => (0, import_layoutCore.sourceIdentityKey)(item.source)),
|
|
177
|
+
groupedRoutes: bySource(composition.context.evidence.groupedRoutes, (item) => (0, import_layoutCore.sourceIdentityKey)(item.source))
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function observationForSource(index, source) {
|
|
181
|
+
const key = (0, import_layoutCore.sourceIdentityKey)(source);
|
|
182
|
+
const mappings = index.sources.get(key) ?? [];
|
|
183
|
+
if (mappings.length !== 1) return void 0;
|
|
184
|
+
const selected = mappings[0];
|
|
185
|
+
const candidates = selected.codec === "grouped" ? index.groupedObservations : index.rawObservations;
|
|
186
|
+
const observations = (candidates.get(key) ?? []).filter((item) => same(item.selector, selected.mapping.selector));
|
|
187
|
+
return observations.length === 1 ? { source: selected, observation: observations[0] } : void 0;
|
|
188
|
+
}
|
|
189
|
+
function observationForDocumentKey(index, documentKey) {
|
|
190
|
+
const source = (0, import_layoutCore.stableSource)(documentKey);
|
|
191
|
+
return source ? observationForSource(index, source) : void 0;
|
|
192
|
+
}
|
|
193
|
+
function sameLogicalSelector(left, right) {
|
|
194
|
+
if (left.slot !== right.slot) return false;
|
|
195
|
+
if (left.slot === "owner-attachment" && right.slot === "owner-attachment") return left.field === right.field;
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
function retainedRouteFor(index, selected) {
|
|
199
|
+
const routes = selected.source.codec === "grouped" ? index.groupedRoutes : index.binaryRoutes;
|
|
200
|
+
const matches = (routes.get((0, import_layoutCore.sourceIdentityKey)(selected.source.mapping.source)) ?? []).filter(
|
|
201
|
+
(route) => sameLogicalSelector(route.selector, selected.observation.selector)
|
|
202
|
+
);
|
|
203
|
+
return matches.length === 1 ? matches[0] : void 0;
|
|
204
|
+
}
|
|
205
|
+
function replayMappingValid(index, documentKey) {
|
|
206
|
+
const source = (0, import_layoutCore.stableSource)(documentKey);
|
|
207
|
+
const selected = source && observationForSource(index, source);
|
|
208
|
+
if (!source || !selected?.observation.currentHash || !selected.observation.contributor || !["clean", "dirty", "new"].includes(selected.observation.state))
|
|
209
|
+
return false;
|
|
210
|
+
const route = retainedRouteFor(index, selected);
|
|
211
|
+
return !!route && route.contributor && attachmentReplayValid(index, source);
|
|
212
|
+
}
|
|
213
|
+
function attachmentReplayValid(index, source) {
|
|
214
|
+
const key = (0, import_layoutCore.sourceIdentityKey)(source);
|
|
215
|
+
for (const field of index.ownerFields.get(key) ?? []) {
|
|
216
|
+
if (!field.currentHash && !field.bytes) continue;
|
|
217
|
+
const matches = (index.attachmentObservations.get(key) ?? []).filter(
|
|
218
|
+
(item) => item.selector.slot === "owner-attachment" && item.selector.ownerFile === field.ownerFile && item.selector.field === field.field
|
|
219
|
+
);
|
|
220
|
+
const routes = (index.binaryRoutes.get(key) ?? []).filter(
|
|
221
|
+
(route) => route.selector.slot === "owner-attachment" && route.selector.field === field.field
|
|
222
|
+
);
|
|
223
|
+
if (matches.length !== 1 || !matches[0].currentHash || !["clean", "dirty", "new"].includes(matches[0].state) || routes.length !== 1)
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
function filterReplay(readback, replayed) {
|
|
229
|
+
const materializations = readback.materializations.filter(
|
|
230
|
+
(item) => !("documentKey" in item && item.documentKey && replayed.has(item.documentKey))
|
|
231
|
+
);
|
|
232
|
+
const setKeys = new Set(
|
|
233
|
+
materializations.filter((item) => item.mode === "set").map((item) => item.documentKey)
|
|
234
|
+
);
|
|
235
|
+
const groupedCompanions = readback.groupedCompanions.flatMap((companion) => {
|
|
236
|
+
const authorizingDocumentKeys = companion.authorizingDocumentKeys.filter((key) => setKeys.has(key));
|
|
237
|
+
return authorizingDocumentKeys.length > 0 ? [{ ...(0, import_layoutCore.clone)(companion), authorizingDocumentKeys }] : [];
|
|
238
|
+
});
|
|
239
|
+
const attachments = readback.attachments.filter((item) => setKeys.has(item.ownerDocumentKey));
|
|
240
|
+
return {
|
|
241
|
+
...readback,
|
|
242
|
+
materializations,
|
|
243
|
+
groupedCompanions,
|
|
244
|
+
attachments,
|
|
245
|
+
pendingDamage: readback.pendingDamage.filter((item) => setKeys.has(item.evidence.documentKey)),
|
|
246
|
+
groupedPatches: [
|
|
247
|
+
...materializations.flatMap(
|
|
248
|
+
(item) => item.mode === "set" && item.codec === "grouped" ? [...item.patches] : []
|
|
249
|
+
),
|
|
250
|
+
...groupedCompanions.map((item) => item.patch)
|
|
251
|
+
],
|
|
252
|
+
rawPatches: materializations.flatMap(
|
|
253
|
+
(item) => item.mode === "set" && item.codec === "raw" ? [item.patch] : []
|
|
254
|
+
)
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
const ADOPTABLE = /* @__PURE__ */ new Set(["eligible-stable-set", "eligible-assigned-create", "generated-share-deferred"]);
|
|
258
|
+
function receiptHash(readback, key) {
|
|
259
|
+
const matches = readback.receiptResults.filter(
|
|
260
|
+
(item) => item.documentKey === key && ADOPTABLE.has(item.classification)
|
|
261
|
+
);
|
|
262
|
+
return matches.length === 1 && matches[0].receiptHash === matches[0].headHash ? matches[0].receiptHash : void 0;
|
|
263
|
+
}
|
|
264
|
+
function trackedRole(scan, path2, fallback) {
|
|
265
|
+
const roles = [
|
|
266
|
+
...new Set(
|
|
267
|
+
scan.artifacts.filter((artifact) => artifact.path === path2).map((artifact) => {
|
|
268
|
+
if (["folder-control", "raw-metadata", "raw", "attachment"].includes(artifact.role))
|
|
269
|
+
return artifact.role;
|
|
270
|
+
return "document";
|
|
271
|
+
})
|
|
272
|
+
)
|
|
273
|
+
];
|
|
274
|
+
return roles.length === 1 ? roles[0] : fallback;
|
|
275
|
+
}
|
|
276
|
+
function evidenceClaims(evidence, scan) {
|
|
277
|
+
const claims = [];
|
|
278
|
+
for (const route of evidence.groupedRoutes) {
|
|
279
|
+
const role = trackedRole(
|
|
280
|
+
scan,
|
|
281
|
+
route.selector.file,
|
|
282
|
+
route.selector.file.endsWith("/_folder.json") ? "folder-control" : "document"
|
|
283
|
+
);
|
|
284
|
+
claims.push({
|
|
285
|
+
logical: `grouped:${(0, import_layoutCore.sourceIdentityKey)(route.source)}:${route.selector.slot}`,
|
|
286
|
+
path: route.selector.file,
|
|
287
|
+
kind: "file",
|
|
288
|
+
role
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
for (const route of evidence.binaryRoutes) {
|
|
292
|
+
const source = (0, import_layoutCore.sourceIdentityKey)(route.source);
|
|
293
|
+
if (route.selector.slot === "file-entry") {
|
|
294
|
+
claims.push({
|
|
295
|
+
logical: `binary:${source}:file-entry:sidecar`,
|
|
296
|
+
path: route.selector.sidecar,
|
|
297
|
+
kind: "file",
|
|
298
|
+
role: "raw-metadata"
|
|
299
|
+
});
|
|
300
|
+
if (route.bytes)
|
|
301
|
+
claims.push({
|
|
302
|
+
logical: `binary:${source}:file-entry:bytes`,
|
|
303
|
+
path: route.bytes,
|
|
304
|
+
kind: "file",
|
|
305
|
+
role: "raw"
|
|
306
|
+
});
|
|
307
|
+
} else if (route.bytes) {
|
|
308
|
+
claims.push({
|
|
309
|
+
logical: `binary:${source}:owner-attachment:${route.selector.field}`,
|
|
310
|
+
path: route.bytes,
|
|
311
|
+
kind: "file",
|
|
312
|
+
role: "attachment"
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
for (const route of evidence.rawNavigationRoutes)
|
|
317
|
+
claims.push({
|
|
318
|
+
logical: `navigation:${(0, import_layoutCore.sourceIdentityKey)(route.source)}:raw-share`,
|
|
319
|
+
path: route.groupFile,
|
|
320
|
+
kind: "file",
|
|
321
|
+
role: trackedRole(scan, route.groupFile, "document")
|
|
322
|
+
});
|
|
323
|
+
const unique = /* @__PURE__ */ new Map();
|
|
324
|
+
for (const claim of claims) unique.set((0, import_documents.canonicalText)([claim.logical, claim.path, claim.kind, claim.role]), claim);
|
|
325
|
+
return [...unique.values()];
|
|
326
|
+
}
|
|
327
|
+
function physicalClaimKey(claim) {
|
|
328
|
+
return (0, import_documents.canonicalText)([claim.path, claim.kind, claim.role]);
|
|
329
|
+
}
|
|
330
|
+
function trackedRoute(logical) {
|
|
331
|
+
return `layout/v1/${(0, import_layoutCore.canonicalFragmentHash)(logical)}`;
|
|
332
|
+
}
|
|
333
|
+
function trackedAfter(input) {
|
|
334
|
+
const beforeClaims = evidenceClaims(input.before, input.beforeScan);
|
|
335
|
+
const afterClaims = evidenceClaims(input.after, input.afterScan);
|
|
336
|
+
const beforeByPhysical = /* @__PURE__ */ new Map();
|
|
337
|
+
const beforeByRoute = new Map(beforeClaims.map((claim) => [trackedRoute(claim.logical), claim]));
|
|
338
|
+
const afterByLogical = /* @__PURE__ */ new Map();
|
|
339
|
+
for (const claim of beforeClaims)
|
|
340
|
+
beforeByPhysical.set(physicalClaimKey(claim), [
|
|
341
|
+
...beforeByPhysical.get(physicalClaimKey(claim)) ?? [],
|
|
342
|
+
claim
|
|
343
|
+
]);
|
|
344
|
+
for (const claim of afterClaims)
|
|
345
|
+
afterByLogical.set(claim.logical, [...afterByLogical.get(claim.logical) ?? [], claim]);
|
|
346
|
+
const output = [];
|
|
347
|
+
const represented = /* @__PURE__ */ new Set();
|
|
348
|
+
const diagnostics = [];
|
|
349
|
+
for (const claims of afterByLogical.values())
|
|
350
|
+
if (new Set(claims.map(physicalClaimKey)).size !== 1)
|
|
351
|
+
diagnostics.push(
|
|
352
|
+
(0, import_layoutCore.diagnostic)(
|
|
353
|
+
"ambiguous-layout-tracking",
|
|
354
|
+
claims[0].path,
|
|
355
|
+
"One logical route has multiple projected physical claims"
|
|
356
|
+
)
|
|
357
|
+
);
|
|
358
|
+
if (diagnostics.length > 0) return { diagnostics };
|
|
359
|
+
for (const item of input.tracked) {
|
|
360
|
+
const exact = beforeByRoute.get(item.route);
|
|
361
|
+
const matched = exact ? [exact] : beforeByPhysical.get(physicalClaimKey(item)) ?? [];
|
|
362
|
+
if (matched.length === 0) {
|
|
363
|
+
output.push((0, import_layoutCore.clone)(item));
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const next = /* @__PURE__ */ new Map();
|
|
367
|
+
for (const prior of matched)
|
|
368
|
+
for (const claim2 of afterByLogical.get(prior.logical) ?? []) next.set(physicalClaimKey(claim2), claim2);
|
|
369
|
+
if (next.size === 0) continue;
|
|
370
|
+
if (next.size !== 1) {
|
|
371
|
+
if (exact) {
|
|
372
|
+
diagnostics.push(
|
|
373
|
+
(0, import_layoutCore.diagnostic)(
|
|
374
|
+
"ambiguous-layout-tracking",
|
|
375
|
+
item.path,
|
|
376
|
+
"Generated tracked route maps to multiple projected physical claims"
|
|
377
|
+
)
|
|
378
|
+
);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
const currentKey = physicalClaimKey(item);
|
|
382
|
+
const retained = matched.filter(
|
|
383
|
+
(prior) => (afterByLogical.get(prior.logical) ?? []).some((claim2) => physicalClaimKey(claim2) === currentKey)
|
|
384
|
+
);
|
|
385
|
+
if (retained.length > 0) {
|
|
386
|
+
output.push((0, import_layoutCore.clone)(item));
|
|
387
|
+
for (const claim2 of retained) represented.add(claim2.logical);
|
|
388
|
+
}
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const claim = [...next.values()][0];
|
|
392
|
+
output.push({ route: item.route, path: claim.path, kind: claim.kind, role: claim.role });
|
|
393
|
+
if (exact || matched.length === 1) represented.add(claim.logical);
|
|
394
|
+
}
|
|
395
|
+
if (diagnostics.length > 0) return { diagnostics };
|
|
396
|
+
const usedRoutes = new Set(output.map((item) => item.route));
|
|
397
|
+
for (const claim of [...afterClaims].sort((left, right) => left.logical.localeCompare(right.logical))) {
|
|
398
|
+
if (represented.has(claim.logical)) continue;
|
|
399
|
+
const route = trackedRoute(claim.logical);
|
|
400
|
+
if (usedRoutes.has(route))
|
|
401
|
+
return {
|
|
402
|
+
diagnostics: [
|
|
403
|
+
(0, import_layoutCore.diagnostic)("duplicate-layout-tracking", claim.path, "Generated tracked route collides with state")
|
|
404
|
+
]
|
|
405
|
+
};
|
|
406
|
+
usedRoutes.add(route);
|
|
407
|
+
represented.add(claim.logical);
|
|
408
|
+
output.push({ route, path: claim.path, kind: claim.kind, role: claim.role });
|
|
409
|
+
}
|
|
410
|
+
output.sort((left, right) => left.route.localeCompare(right.route));
|
|
411
|
+
return { tracked: output };
|
|
412
|
+
}
|
|
413
|
+
function byteWrite(materialization) {
|
|
414
|
+
return {
|
|
415
|
+
path: materialization.destination,
|
|
416
|
+
descriptor: (0, import_layoutCore.clone)(materialization.descriptor),
|
|
417
|
+
authorizingDocumentKey: materialization.kind === "raw" ? materialization.documentKey : materialization.ownerDocumentKey
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function quarantinedApplyAdvice(planId) {
|
|
421
|
+
return `The saved receipt for plan p${planId} could not be read while its apply was in flight; run farseer code pull --force to reset the workspace to the head, then plan again`;
|
|
422
|
+
}
|
|
423
|
+
function quarantinedDraft(value) {
|
|
424
|
+
const draft = value ?? {};
|
|
425
|
+
const receipt = draft.receipt ?? void 0;
|
|
426
|
+
const applying = draft.applying === true;
|
|
427
|
+
return typeof receipt?.revisionId === "string" ? { applying, receipt: true, quarantined: true } : { applying, quarantined: true };
|
|
428
|
+
}
|
|
429
|
+
function layoutReceiptDrafts(state) {
|
|
430
|
+
return [
|
|
431
|
+
...Object.entries(state.layout?.receipts ?? {}),
|
|
432
|
+
...Object.entries(state.layout?.unreadableReceipts ?? {}).map(([planId, draft]) => [
|
|
433
|
+
planId,
|
|
434
|
+
quarantinedDraft(draft)
|
|
435
|
+
])
|
|
436
|
+
];
|
|
437
|
+
}
|
|
438
|
+
function refuseUnwrittenReceipts(state) {
|
|
439
|
+
for (const [planId, draft] of layoutReceiptDrafts(state)) {
|
|
440
|
+
if (draft.applying && draft.quarantined) throw new Error(quarantinedApplyAdvice(planId));
|
|
441
|
+
if (draft.applying && !draft.receipt)
|
|
442
|
+
throw new Error(`Resume farseer code apply p${planId} before creating another plan`);
|
|
443
|
+
if (draft.applying)
|
|
444
|
+
throw new Error(`Run farseer code pull to write the receipt of p${planId} before creating another plan`);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
function fileIdentity(root, relative) {
|
|
448
|
+
try {
|
|
449
|
+
const stat = fs.lstatSync((0, import_layoutScan.resolveLayoutPath)(root, relative));
|
|
450
|
+
return stat.isFile() ? `${stat.dev}:${stat.ino}` : void 0;
|
|
451
|
+
} catch {
|
|
452
|
+
return void 0;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
function directoryIdentity(root, relative) {
|
|
456
|
+
try {
|
|
457
|
+
const stat = fs.lstatSync((0, import_layoutScan.resolveLayoutPath)(root, relative));
|
|
458
|
+
return stat.isDirectory() ? `${stat.dev}:${stat.ino}` : void 0;
|
|
459
|
+
} catch {
|
|
460
|
+
return void 0;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function renameDirectorySpelling(root, rename) {
|
|
464
|
+
const identity = directoryIdentity(root, rename.from);
|
|
465
|
+
if (identity === void 0 || identity !== directoryIdentity(root, rename.to)) return;
|
|
466
|
+
const slash = rename.to.lastIndexOf("/");
|
|
467
|
+
const parent = rename.to.slice(0, slash), name = rename.to.slice(slash + 1), oldName = rename.from.slice(rename.from.lastIndexOf("/") + 1);
|
|
468
|
+
if (fs.readdirSync((0, import_layoutScan.resolveLayoutPath)(root, parent)).includes(name)) return;
|
|
469
|
+
const temporary = path.join((0, import_layoutScan.resolveLayoutPath)(root, parent), `${oldName}.tmp-${(0, import_crypto.randomUUID)()}`);
|
|
470
|
+
fs.renameSync((0, import_layoutScan.resolveLayoutPath)(root, rename.from), temporary);
|
|
471
|
+
try {
|
|
472
|
+
fs.renameSync(temporary, (0, import_layoutScan.resolveLayoutPath)(root, rename.to));
|
|
473
|
+
} catch (error) {
|
|
474
|
+
fs.renameSync(temporary, (0, import_layoutScan.resolveLayoutPath)(root, rename.from));
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function readLayoutText(root, relative) {
|
|
479
|
+
try {
|
|
480
|
+
const absolute = (0, import_layoutScan.resolveLayoutPath)(root, relative);
|
|
481
|
+
return fs.lstatSync(absolute).isFile() ? fs.readFileSync(absolute, "utf8") : void 0;
|
|
482
|
+
} catch {
|
|
483
|
+
return void 0;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function unlinkLayoutFile(root, relative) {
|
|
487
|
+
const absolute = (0, import_layoutScan.resolveLayoutPath)(root, relative);
|
|
488
|
+
if (!fs.lstatSync(absolute).isFile()) return false;
|
|
489
|
+
fs.unlinkSync(absolute);
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
function removalMatchesCapture(root, snapshot, removal) {
|
|
493
|
+
if (removal.kind === "directory" || removal.kind === "rewrite") return true;
|
|
494
|
+
if (removal.kind === "bytes") {
|
|
495
|
+
const expected = snapshot.byteFacts.find((fact) => fact.path === removal.path);
|
|
496
|
+
const actual = (0, import_layoutScan.hashLayoutPath)(root, removal.path);
|
|
497
|
+
return expected?.state === "present" && actual.state === "present" && (0, import_binaryDisk.sameBytes)(actual.content, expected.content);
|
|
498
|
+
}
|
|
499
|
+
const captured = snapshot.jsonText[removal.path];
|
|
500
|
+
return captured !== void 0 && readLayoutText(root, removal.path) === captured;
|
|
501
|
+
}
|
|
502
|
+
function removeLayoutDirectory(absolute) {
|
|
503
|
+
const entries = fs.readdirSync(absolute, { withFileTypes: true });
|
|
504
|
+
const ignored = entries.filter(
|
|
505
|
+
(entry) => entry.name !== ".git" && (0, import_layoutPaths.isIgnoredLayoutName)(entry.name) && (entry.isFile() || entry.isDirectory() && entry.name === "__pycache__")
|
|
506
|
+
);
|
|
507
|
+
if (ignored.length === entries.length)
|
|
508
|
+
for (const entry of ignored) fs.rmSync(path.join(absolute, entry.name), { recursive: entry.isDirectory() });
|
|
509
|
+
fs.rmdirSync(absolute);
|
|
510
|
+
}
|
|
511
|
+
function materializeLayoutRemovals(input) {
|
|
512
|
+
const removed = [];
|
|
513
|
+
const rewritten = [];
|
|
514
|
+
const kept = [];
|
|
515
|
+
const writtenPaths = new Set(input.written ?? []);
|
|
516
|
+
const writtenIdentities = new Set(
|
|
517
|
+
[...writtenPaths].flatMap((path2) => {
|
|
518
|
+
const identity = fileIdentity(input.root, path2);
|
|
519
|
+
return identity ? [identity] : [];
|
|
520
|
+
})
|
|
521
|
+
);
|
|
522
|
+
const capturedStill = (removal) => removalMatchesCapture(input.root, input.snapshot, removal);
|
|
523
|
+
const groupKeys = (removal) => removal.documentKeys.length > 0 ? removal.documentKeys : [`path:${removal.kind}:${removal.path}`];
|
|
524
|
+
const proven = new Map(input.removals.map((removal) => [removal, capturedStill(removal)]));
|
|
525
|
+
const failed = new Set(input.keep ?? []);
|
|
526
|
+
for (const removal of input.removals)
|
|
527
|
+
if (!proven.get(removal)) for (const key of groupKeys(removal)) failed.add(key);
|
|
528
|
+
for (let changed = true; changed; ) {
|
|
529
|
+
changed = false;
|
|
530
|
+
for (const removal of input.removals) {
|
|
531
|
+
const keys = groupKeys(removal);
|
|
532
|
+
if (!keys.some((key) => failed.has(key))) continue;
|
|
533
|
+
for (const key of keys)
|
|
534
|
+
if (!failed.has(key)) {
|
|
535
|
+
failed.add(key);
|
|
536
|
+
changed = true;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const retained = [...failed].filter((key) => !key.startsWith("path:")).sort(import_layoutCore.compareText);
|
|
541
|
+
const order = { bytes: 0, file: 0, rewrite: 1, directory: 2 };
|
|
542
|
+
const ordered = [...input.removals].sort(
|
|
543
|
+
(left, right) => order[left.kind] - order[right.kind] || (left.kind === "directory" ? (0, import_layoutCore.compareText)(right.path, left.path) : (0, import_layoutCore.compareText)(left.path, right.path))
|
|
544
|
+
);
|
|
545
|
+
for (const removal of ordered) {
|
|
546
|
+
if (groupKeys(removal).some((key) => failed.has(key))) {
|
|
547
|
+
kept.push(removal.path);
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (removal.kind === "directory") {
|
|
551
|
+
try {
|
|
552
|
+
removeLayoutDirectory((0, import_layoutScan.resolveLayoutPath)(input.root, removal.path));
|
|
553
|
+
removed.push(removal.path);
|
|
554
|
+
} catch (error) {
|
|
555
|
+
const code = error.code;
|
|
556
|
+
if (code !== "ENOTEMPTY" && code !== "ENOENT" && code !== "EEXIST") throw error;
|
|
557
|
+
kept.push(removal.path);
|
|
558
|
+
}
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
const identity = fileIdentity(input.root, removal.path);
|
|
562
|
+
if (writtenPaths.has(removal.path) || identity !== void 0 && writtenIdentities.has(identity)) {
|
|
563
|
+
kept.push(removal.path);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (removal.kind === "rewrite") {
|
|
567
|
+
(0, import_workspace.atomicReplaceText)(
|
|
568
|
+
(0, import_layoutScan.resolveLayoutPath)(input.root, removal.path),
|
|
569
|
+
`${JSON.stringify(removal.value, null, 2)}
|
|
570
|
+
`
|
|
571
|
+
);
|
|
572
|
+
rewritten.push(removal.path);
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
if (unlinkLayoutFile(input.root, removal.path)) removed.push(removal.path);
|
|
576
|
+
else kept.push(removal.path);
|
|
577
|
+
}
|
|
578
|
+
return { removed, rewritten, kept, retained };
|
|
579
|
+
}
|
|
580
|
+
function removeLayoutState(state, deletes, removedPaths) {
|
|
581
|
+
const sources = new Set(deletes.sources.map((source) => (0, import_layoutCore.sourceIdentityKey)(source)));
|
|
582
|
+
const gone = new Set(removedPaths);
|
|
583
|
+
const baseline = { ...state.baseline };
|
|
584
|
+
for (const key of deletes.keys) delete baseline[key];
|
|
585
|
+
if (!state.layout) return { ...state, baseline };
|
|
586
|
+
const kept = (items) => items.filter((item) => !sources.has((0, import_layoutCore.sourceIdentityKey)(item.source)));
|
|
587
|
+
const evidence = state.layout.evidence;
|
|
588
|
+
const detachedDocumentProofs = Object.fromEntries(
|
|
589
|
+
Object.entries(evidence.detachedDocumentProofs).filter(
|
|
590
|
+
([file, proof]) => !gone.has(file) && !sources.has(proof.sourceKey)
|
|
591
|
+
)
|
|
592
|
+
);
|
|
593
|
+
const detachedFileProofs = Object.fromEntries(
|
|
594
|
+
Object.entries(evidence.detachedFileProofs).filter(
|
|
595
|
+
([file, proof]) => !gone.has(file) && !sources.has(proof.sourceKey)
|
|
596
|
+
)
|
|
597
|
+
);
|
|
598
|
+
return {
|
|
599
|
+
...state,
|
|
600
|
+
baseline,
|
|
601
|
+
layout: {
|
|
602
|
+
...state.layout,
|
|
603
|
+
evidence: {
|
|
604
|
+
groupedRoutes: kept(evidence.groupedRoutes),
|
|
605
|
+
binaryRoutes: kept(evidence.binaryRoutes),
|
|
606
|
+
derivedSourceProofs: kept(evidence.derivedSourceProofs),
|
|
607
|
+
rawNavigationRoutes: kept(evidence.rawNavigationRoutes),
|
|
608
|
+
detachedDocumentProofs,
|
|
609
|
+
detachedFileProofs
|
|
610
|
+
},
|
|
611
|
+
tracked: state.layout.tracked.filter((item) => !gone.has(item.path))
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function vacateLayoutAliases(root, snapshot, removals, written) {
|
|
616
|
+
const destinations = new Set(written);
|
|
617
|
+
const identities = new Set(
|
|
618
|
+
written.flatMap((path2) => {
|
|
619
|
+
const identity = fileIdentity(root, path2);
|
|
620
|
+
return identity ? [identity] : [];
|
|
621
|
+
})
|
|
622
|
+
);
|
|
623
|
+
if (identities.size === 0) return [];
|
|
624
|
+
const vacated = [];
|
|
625
|
+
for (const removal of removals) {
|
|
626
|
+
if (removal.kind !== "file" && removal.kind !== "bytes") continue;
|
|
627
|
+
if (destinations.has(removal.path)) continue;
|
|
628
|
+
const identity = fileIdentity(root, removal.path);
|
|
629
|
+
if (identity === void 0 || !identities.has(identity)) continue;
|
|
630
|
+
if (!removalMatchesCapture(root, snapshot, removal)) continue;
|
|
631
|
+
unlinkLayoutFile(root, removal.path);
|
|
632
|
+
vacated.push(removal.path);
|
|
633
|
+
}
|
|
634
|
+
return vacated;
|
|
635
|
+
}
|
|
636
|
+
function createLayoutDestinationDirectories(root, destinations) {
|
|
637
|
+
const directories = /* @__PURE__ */ new Set();
|
|
638
|
+
const created = [];
|
|
639
|
+
for (const destination of destinations)
|
|
640
|
+
for (const ancestor of (0, import_layoutCore.pathAncestors)((0, import_layoutPaths.parseWorkspacePointer)(destination))) directories.add(ancestor);
|
|
641
|
+
for (const relative of [...directories].sort(import_layoutCore.compareText)) {
|
|
642
|
+
const absolute = (0, import_layoutScan.resolveLayoutPath)(root, relative);
|
|
643
|
+
try {
|
|
644
|
+
fs.mkdirSync(absolute, { mode: 493 });
|
|
645
|
+
created.push(relative);
|
|
646
|
+
} catch (error) {
|
|
647
|
+
if (error.code !== "EEXIST") throw error;
|
|
648
|
+
if (!fs.lstatSync(absolute).isDirectory())
|
|
649
|
+
throw new Error(`Managed destination ancestor is not a directory: ${relative}`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return created;
|
|
653
|
+
}
|
|
654
|
+
function removeEmptyDirectories(root, created) {
|
|
655
|
+
for (const relative of [...created].sort((left, right) => (0, import_layoutCore.compareText)(right, left)))
|
|
656
|
+
try {
|
|
657
|
+
fs.rmdirSync((0, import_layoutScan.resolveLayoutPath)(root, relative));
|
|
658
|
+
} catch {
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
function descriptorKey(content) {
|
|
662
|
+
return `${content.sha256}/${content.size}`;
|
|
663
|
+
}
|
|
664
|
+
async function stageByteWrites(input, snapshot, prepared, into) {
|
|
665
|
+
const local = snapshot.byteFacts.filter(
|
|
666
|
+
(fact) => fact.state === "present"
|
|
667
|
+
);
|
|
668
|
+
const sources = /* @__PURE__ */ new Map();
|
|
669
|
+
const sidecars = new Map(prepared.jsonWrites.map((item) => [item.path, item]));
|
|
670
|
+
for (const write of prepared.byteWrites) {
|
|
671
|
+
const key = descriptorKey(write.descriptor);
|
|
672
|
+
const destination = (0, import_layoutScan.resolveLayoutPath)(input.root, write.path);
|
|
673
|
+
const supplied = sources.get(key);
|
|
674
|
+
const reusable = local.find((fact) => (0, import_binaryDisk.sameBytes)(fact.content, write.descriptor));
|
|
675
|
+
let file;
|
|
676
|
+
if (supplied) file = (0, import_workspace.stageVerifiedFile)(supplied, destination, write.descriptor, write.path);
|
|
677
|
+
else if (reusable)
|
|
678
|
+
file = (0, import_workspace.stageVerifiedFile)(
|
|
679
|
+
(0, import_layoutScan.resolveLayoutPath)(input.root, reusable.path),
|
|
680
|
+
destination,
|
|
681
|
+
write.descriptor,
|
|
682
|
+
write.path
|
|
683
|
+
);
|
|
684
|
+
else {
|
|
685
|
+
if (!input.api) throw new Error(`No byte source for ${write.path}`);
|
|
686
|
+
try {
|
|
687
|
+
file = await (0, import_workspace.stageDownloadedFile)(input.api, destination, write.descriptor, (abandon) => {
|
|
688
|
+
into.inFlight = abandon;
|
|
689
|
+
});
|
|
690
|
+
} finally {
|
|
691
|
+
into.inFlight = void 0;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
into.staged.push({ path: write.path, file });
|
|
695
|
+
if (!sources.has(key)) sources.set(key, file.temporary);
|
|
696
|
+
const sidecar = sidecars.get((0, import_layoutPaths.rawSidecarPath)(write.path));
|
|
697
|
+
if (!sidecar) continue;
|
|
698
|
+
into.sidecars.set(write.path, (0, import_workspace.stageText)((0, import_layoutScan.resolveLayoutPath)(input.root, sidecar.path), sidecar.text));
|
|
699
|
+
into.paired.add(sidecar.path);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function validateDestinations(snapshot, prepared) {
|
|
703
|
+
const facts = new Map(snapshot.pathFacts.map((fact) => [fact.path, fact]));
|
|
704
|
+
const destination = (path2, label) => {
|
|
705
|
+
const fact = facts.get(path2);
|
|
706
|
+
if (!fact) throw new Error(`${label} destination was never probed: ${path2}`);
|
|
707
|
+
if (fact.state !== "file" && fact.state !== "absent")
|
|
708
|
+
throw new Error(`${label} destination is not replaceable: ${path2}`);
|
|
709
|
+
for (const ancestor of (0, import_layoutCore.pathAncestors)(path2)) {
|
|
710
|
+
const parent = facts.get(ancestor);
|
|
711
|
+
if (!parent || parent.state !== "directory" && parent.state !== "absent")
|
|
712
|
+
throw new Error(`${label} destination ancestor is unavailable: ${ancestor}`);
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
for (const write of prepared.byteWrites) destination(write.path, "Byte");
|
|
716
|
+
for (const write of prepared.jsonWrites) destination(write.path, "JSON");
|
|
717
|
+
}
|
|
718
|
+
function localPathNotices(scan) {
|
|
719
|
+
const temporaries = [...scan.localOnlyFiles, ...scan.opaqueDirectories].filter((file) => (0, import_layoutPaths.isTemporaryLayoutPath)(file)).sort(import_layoutCore.compareText).map((path2) => ({ status: "stale-temporary", path: path2 }));
|
|
720
|
+
const unmanageable = [...scan.unmanageableDirectories ?? []].sort(import_layoutCore.compareText).map((path2) => ({ status: "unmanageable-path", path: path2 }));
|
|
721
|
+
return [...temporaries, ...unmanageable];
|
|
722
|
+
}
|
|
723
|
+
function stableSourceKeyOf(source) {
|
|
724
|
+
return source.type === "resource" && "id" in source.resource ? `${source.resource.kind}/${source.resource.id}` : void 0;
|
|
725
|
+
}
|
|
726
|
+
function parsedLayoutState(text) {
|
|
727
|
+
let parsed;
|
|
728
|
+
try {
|
|
729
|
+
parsed = (0, import_documents.parseState)(text);
|
|
730
|
+
} catch (error) {
|
|
731
|
+
return [(0, import_layoutCore.diagnostic)("invalid-layout-state", ".", error instanceof Error ? error.message : "invalid state")];
|
|
732
|
+
}
|
|
733
|
+
return parsed;
|
|
734
|
+
}
|
|
735
|
+
function receiptDecisions(state, planId, head, current) {
|
|
736
|
+
const draft = state.layout.receipts?.[planId];
|
|
737
|
+
if (!draft?.receipt || !draft.submission || draft.submission.planId !== planId)
|
|
738
|
+
return { diagnostics: [(0, import_layoutCore.diagnostic)("missing-layout-receipt", planId, "Stored layout receipt is incomplete")] };
|
|
739
|
+
const submission = draft.submission;
|
|
740
|
+
const eligibility = (0, import_layoutReadback.decideReceiptEligibility)({ head, receipt: draft.receipt, submission, current });
|
|
741
|
+
if (eligibility.status === "blocked") return { diagnostics: [...eligibility.diagnostics] };
|
|
742
|
+
const readback = (0, import_layoutReadback.planMaterialization)({ eligibility, head, current });
|
|
743
|
+
if (readback.status === "blocked") return { diagnostics: [...readback.diagnostics] };
|
|
744
|
+
const index = compositionIndex(current);
|
|
745
|
+
const replayed = /* @__PURE__ */ new Set();
|
|
746
|
+
for (const item of readback.receiptResults)
|
|
747
|
+
if ((item.classification === "eligible-stable-set" || item.classification === "eligible-assigned-create") && item.documentKey && item.receiptHash && state.baseline[item.documentKey] === item.receiptHash && replayMappingValid(index, item.documentKey))
|
|
748
|
+
replayed.add(item.documentKey);
|
|
749
|
+
return { readback: filterReplay(readback, replayed) };
|
|
750
|
+
}
|
|
751
|
+
function planSubmissionProofs(state, source) {
|
|
752
|
+
if (source.kind !== "receipt") return {};
|
|
753
|
+
const draft = state.layout.receipts?.[source.planId];
|
|
754
|
+
return {
|
|
755
|
+
groupedSubmissionProofs: (0, import_layoutCore.clone)(draft?.submission?.composition.groupedSubmissions ?? []),
|
|
756
|
+
binarySubmissionProofs: (0, import_layoutCore.clone)(draft?.submission?.composition.binarySubmissions ?? []),
|
|
757
|
+
reservedTransientTokens: (draft?.submission?.composition.sources ?? []).flatMap(
|
|
758
|
+
(item) => item.mapping.source.type === "transient" ? [item.mapping.source.token] : []
|
|
759
|
+
)
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
function requiredPathsFor(snapshot, state, rendering) {
|
|
763
|
+
const paths = /* @__PURE__ */ new Set();
|
|
764
|
+
const add = (candidate) => {
|
|
765
|
+
paths.add(candidate);
|
|
766
|
+
for (const ancestor of (0, import_layoutCore.pathAncestors)(candidate)) paths.add(ancestor);
|
|
767
|
+
};
|
|
768
|
+
for (const artifact of snapshot.scan.artifacts) add(artifact.path);
|
|
769
|
+
for (const directory of snapshot.scan.opaqueDirectories) if ((0, import_layoutPaths.isPortableWorkspacePointer)(directory)) add(directory);
|
|
770
|
+
for (const tracked of snapshot.scan.tracked) {
|
|
771
|
+
add(tracked.path);
|
|
772
|
+
if (tracked.missingAncestor) add(tracked.missingAncestor);
|
|
773
|
+
}
|
|
774
|
+
for (const tracked of state.layout.tracked) add(tracked.path);
|
|
775
|
+
for (const file of Object.keys(snapshot.jsonText)) add(file);
|
|
776
|
+
for (const fact of snapshot.byteFacts) add(fact.path);
|
|
777
|
+
for (const rendered of rendering.json) add(rendered.path);
|
|
778
|
+
for (const rendered of rendering.bytes) add(rendered.destination);
|
|
779
|
+
for (const removal of rendering.removals) add(removal.path);
|
|
780
|
+
return [...paths].sort(import_layoutCore.compareText);
|
|
781
|
+
}
|
|
782
|
+
const PLAIN_ROUTE_KINDS = /* @__PURE__ */ new Set(["variable", "sheet", "dashboard", "remote_job"]);
|
|
783
|
+
function plainHeadRoute(document) {
|
|
784
|
+
const value = document;
|
|
785
|
+
const folder = value.folder;
|
|
786
|
+
if (!PLAIN_ROUTE_KINDS.has(document.kind) || typeof value.name !== "string") return void 0;
|
|
787
|
+
if (!Array.isArray(folder) || folder.some((segment) => typeof segment !== "string")) return void 0;
|
|
788
|
+
const segments = [...folder, value.name];
|
|
789
|
+
if (segments.some((segment) => (0, import_layoutPaths.layoutNameNeedsOverride)(segment))) return void 0;
|
|
790
|
+
try {
|
|
791
|
+
return `tree/${segments.map(import_layoutPaths.encodeLayoutSegment).join("/")}.json`;
|
|
792
|
+
} catch {
|
|
793
|
+
return void 0;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
function staleDuplicateOrigins(scan, diagnostics, head, provenRoutes) {
|
|
797
|
+
const artifact = (path2) => scan.artifacts.find((candidate) => candidate.path === path2 && candidate.present);
|
|
798
|
+
const stale = [];
|
|
799
|
+
for (const item of diagnostics) {
|
|
800
|
+
if (item.code !== "duplicate-resource-identity" || !item.relatedPath) return [];
|
|
801
|
+
const pair = [artifact(item.path), artifact(item.relatedPath)];
|
|
802
|
+
const [left, right] = pair;
|
|
803
|
+
if (!left?.json || !right?.json || (0, import_documents.canonicalText)(left.json) !== (0, import_documents.canonicalText)(right.json))
|
|
804
|
+
return [];
|
|
805
|
+
const identity = left.json;
|
|
806
|
+
if (typeof identity.kind !== "string" || typeof identity.id !== "string") return [];
|
|
807
|
+
const index = head.documentKeys.indexOf(`${identity.kind}/${identity.id}`);
|
|
808
|
+
const route = index < 0 ? void 0 : plainHeadRoute(head.documents[index]);
|
|
809
|
+
const origins = pair.filter((candidate) => candidate.path !== route);
|
|
810
|
+
if (route === void 0 || origins.length !== 1) return [];
|
|
811
|
+
const proven = provenRoutes.filter(
|
|
812
|
+
(candidate) => candidate.selector.slot === "document" && candidate.source.type === "resource" && "id" in candidate.source.resource && candidate.source.resource.kind === identity.kind && candidate.source.resource.id === identity.id
|
|
813
|
+
);
|
|
814
|
+
if (proven.length !== 1 || proven[0].selector.file !== origins[0].path) return [];
|
|
815
|
+
stale.push(origins[0].path);
|
|
816
|
+
}
|
|
817
|
+
return stale;
|
|
818
|
+
}
|
|
819
|
+
function restoreVacatedOrigins(root, snapshot, vacated, staged) {
|
|
820
|
+
const temporaries = new Map(staged.map((item) => [item.path, item.file.temporary]));
|
|
821
|
+
const beside = new Set(staged.flatMap((item) => item.beside ? [item.path] : []));
|
|
822
|
+
const lost = [];
|
|
823
|
+
for (const { origin, destination } of vacated) {
|
|
824
|
+
if (fs.existsSync((0, import_layoutScan.resolveLayoutPath)(root, origin))) continue;
|
|
825
|
+
const target = beside.has(destination) ? destination : origin;
|
|
826
|
+
const absolute = (0, import_layoutScan.resolveLayoutPath)(root, target);
|
|
827
|
+
const text = beside.has(destination) ? void 0 : snapshot.jsonText[origin];
|
|
828
|
+
const temporary = temporaries.get(destination);
|
|
829
|
+
try {
|
|
830
|
+
if (text !== void 0) (0, import_workspace.atomicReplaceText)(absolute, text);
|
|
831
|
+
else if (temporary !== void 0) fs.copyFileSync(temporary, absolute);
|
|
832
|
+
} catch {
|
|
833
|
+
}
|
|
834
|
+
if (!fs.existsSync(absolute)) lost.push(target);
|
|
835
|
+
}
|
|
836
|
+
return [...new Set(lost)].sort(import_layoutCore.compareText);
|
|
837
|
+
}
|
|
838
|
+
function withdrawUnpairedBytes(root, snapshot, vacated, unpaired) {
|
|
839
|
+
if (unpaired === void 0 || unpaired.identity === void 0) return [];
|
|
840
|
+
const sidecar = (0, import_layoutPaths.rawSidecarPath)(unpaired.path);
|
|
841
|
+
if (snapshot.pathFacts.find((fact) => fact.path === unpaired.path)?.state !== "absent") return [];
|
|
842
|
+
if (vacated.some(({ destination }) => destination === unpaired.path || destination === sidecar)) return [];
|
|
843
|
+
if (fileIdentity(root, unpaired.path) !== unpaired.identity) return [];
|
|
844
|
+
try {
|
|
845
|
+
unlinkLayoutFile(root, unpaired.path);
|
|
846
|
+
} catch {
|
|
847
|
+
}
|
|
848
|
+
return fileIdentity(root, unpaired.path) === unpaired.identity ? [unpaired.path] : [];
|
|
849
|
+
}
|
|
850
|
+
const activeWrites = /* @__PURE__ */ new Set();
|
|
851
|
+
function exitAfterWrites() {
|
|
852
|
+
for (const abandon of activeWrites)
|
|
853
|
+
try {
|
|
854
|
+
abandon();
|
|
855
|
+
} catch {
|
|
856
|
+
}
|
|
857
|
+
process.exit(130);
|
|
858
|
+
}
|
|
859
|
+
function deferInterrupts() {
|
|
860
|
+
if (!process.listeners("SIGINT").includes(exitAfterWrites)) process.on("SIGINT", exitAfterWrites);
|
|
861
|
+
}
|
|
862
|
+
function currentHolders(current) {
|
|
863
|
+
const holders = /* @__PURE__ */ new Map();
|
|
864
|
+
const hold = (path2, key) => {
|
|
865
|
+
const folded = (0, import_layoutPaths.layoutCollisionKey)(path2);
|
|
866
|
+
holders.set(folded, (holders.get(folded) ?? /* @__PURE__ */ new Set()).add(key));
|
|
867
|
+
};
|
|
868
|
+
for (const item of current.sources) {
|
|
869
|
+
const key = stableSourceKeyOf(item.mapping.source);
|
|
870
|
+
if (!key) continue;
|
|
871
|
+
if (item.codec === "grouped") hold(item.mapping.selector.file, key);
|
|
872
|
+
else {
|
|
873
|
+
hold(item.mapping.selector.sidecar, key);
|
|
874
|
+
hold(item.mapping.bytes, key);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return holders;
|
|
878
|
+
}
|
|
879
|
+
function destinationsMatchCapture(root, snapshot) {
|
|
880
|
+
const bytesAt = new Map(snapshot.byteFacts.map((fact) => [fact.path, fact]));
|
|
881
|
+
const factAt = new Map(snapshot.pathFacts.map((fact) => [fact.path, fact]));
|
|
882
|
+
return (path2) => {
|
|
883
|
+
const text = snapshot.jsonText[path2];
|
|
884
|
+
if (text !== void 0) return readLayoutText(root, path2) === text;
|
|
885
|
+
const bytes = bytesAt.get(path2);
|
|
886
|
+
if (bytes) {
|
|
887
|
+
const actual = (0, import_layoutScan.hashLayoutPath)(root, path2);
|
|
888
|
+
return bytes.state === "present" ? actual.state === "present" && (0, import_binaryDisk.sameBytes)(actual.content, bytes.content) : actual.state === bytes.state;
|
|
889
|
+
}
|
|
890
|
+
return factAt.get(path2)?.state !== "absent" || (0, import_layoutScan.probeLayoutPath)(root, path2).state === "absent";
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
function orderedWrites(units, holders, unchanged) {
|
|
894
|
+
const writers = /* @__PURE__ */ new Map();
|
|
895
|
+
units.forEach((unit, index) => {
|
|
896
|
+
for (const key of unit.keys) writers.set(key, [...writers.get(key) ?? [], index]);
|
|
897
|
+
});
|
|
898
|
+
const folded = units.map((unit) => unit.paths.map(import_layoutPaths.layoutCollisionKey));
|
|
899
|
+
const waits = units.map((unit, index) => {
|
|
900
|
+
const wait = /* @__PURE__ */ new Set();
|
|
901
|
+
for (const path2 of folded[index])
|
|
902
|
+
for (const key of holders.get(path2) ?? [])
|
|
903
|
+
if (!unit.keys.has(key)) {
|
|
904
|
+
for (const other of writers.get(key) ?? [])
|
|
905
|
+
if (other !== index && !folded[other].includes(path2)) wait.add(other);
|
|
906
|
+
}
|
|
907
|
+
return wait;
|
|
908
|
+
});
|
|
909
|
+
const dependents = units.map(() => []);
|
|
910
|
+
waits.forEach((wait, index) => {
|
|
911
|
+
for (const other of wait) dependents[other].push(index);
|
|
912
|
+
});
|
|
913
|
+
const unsettled = waits.map((wait) => wait.size);
|
|
914
|
+
const done = /* @__PURE__ */ new Set(), held = /* @__PURE__ */ new Set(), skippedUnits = /* @__PURE__ */ new Set(), released = /* @__PURE__ */ new Set();
|
|
915
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
916
|
+
const ready = [];
|
|
917
|
+
let next = 0;
|
|
918
|
+
const release = (index) => {
|
|
919
|
+
if (released.has(index)) return;
|
|
920
|
+
released.add(index);
|
|
921
|
+
for (const dependent of dependents[index]) if (--unsettled[dependent] === 0) ready.push(dependent);
|
|
922
|
+
};
|
|
923
|
+
const skip = (index) => {
|
|
924
|
+
skippedUnits.add(index);
|
|
925
|
+
for (const key of units[index].keys) skipped.add(key);
|
|
926
|
+
release(index);
|
|
927
|
+
};
|
|
928
|
+
return {
|
|
929
|
+
skipped,
|
|
930
|
+
run() {
|
|
931
|
+
const kept = new Set(units.flatMap((unit, index) => unit.paths.every(unchanged) ? [] : [index]));
|
|
932
|
+
for (const queue = [...kept]; queue.length > 0; ) {
|
|
933
|
+
const index = queue.pop();
|
|
934
|
+
const keys = [...units[index].keys];
|
|
935
|
+
for (const other of [...dependents[index], ...keys.flatMap((key) => writers.get(key) ?? [])])
|
|
936
|
+
if (!kept.has(other)) {
|
|
937
|
+
kept.add(other);
|
|
938
|
+
queue.push(other);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
for (const index of kept) skip(index);
|
|
942
|
+
units.forEach((_, index) => {
|
|
943
|
+
if (unsettled[index] === 0) ready.push(index);
|
|
944
|
+
});
|
|
945
|
+
let finished = kept.size;
|
|
946
|
+
while (finished < units.length) {
|
|
947
|
+
const unit = next < ready.length ? ready[next++] : void 0;
|
|
948
|
+
if (unit === void 0) {
|
|
949
|
+
const open = (index) => !done.has(index) && !skippedUnits.has(index);
|
|
950
|
+
const cycle = units.findIndex(
|
|
951
|
+
(_, index) => open(index) && !held.has(index) && dependents[index].some((other) => open(other))
|
|
952
|
+
);
|
|
953
|
+
if (cycle < 0) throw new Error("Layout writes wait on each other with nothing left to stage");
|
|
954
|
+
if (units[cycle].paths.every(unchanged)) {
|
|
955
|
+
units[cycle].hold?.();
|
|
956
|
+
held.add(cycle);
|
|
957
|
+
release(cycle);
|
|
958
|
+
} else {
|
|
959
|
+
skip(cycle);
|
|
960
|
+
finished++;
|
|
961
|
+
}
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (done.has(unit) || skippedUnits.has(unit)) continue;
|
|
965
|
+
finished++;
|
|
966
|
+
const blockers = [...waits[unit]];
|
|
967
|
+
if (blockers.some((index) => skippedUnits.has(index)) || [...units[unit].keys].some((key) => skipped.has(key)) || !held.has(unit) && !units[unit].paths.every(unchanged)) {
|
|
968
|
+
skip(unit);
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
units[unit].run();
|
|
972
|
+
done.add(unit);
|
|
973
|
+
release(unit);
|
|
974
|
+
}
|
|
975
|
+
},
|
|
976
|
+
notices() {
|
|
977
|
+
return [...skippedUnits].flatMap(
|
|
978
|
+
(index) => [...units[index].keys].sort(import_layoutCore.compareText).map(
|
|
979
|
+
(key) => ({ status: "unmaterialized", path: units[index].paths[0], key })
|
|
980
|
+
)
|
|
981
|
+
);
|
|
982
|
+
},
|
|
983
|
+
revertUnfinished(revert) {
|
|
984
|
+
const lost = [];
|
|
985
|
+
for (let changed = true; changed; ) {
|
|
986
|
+
changed = false;
|
|
987
|
+
for (const index of [...done])
|
|
988
|
+
if ([...waits[index]].some((blocker) => !done.has(blocker)) || [...units[index].keys].some((key) => skipped.has(key))) {
|
|
989
|
+
done.delete(index);
|
|
990
|
+
lost.push(...revert(units[index]));
|
|
991
|
+
skippedUnits.add(index);
|
|
992
|
+
for (const key of units[index].keys) skipped.add(key);
|
|
993
|
+
changed = true;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
return [...new Set(lost)];
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
function contentOf(file) {
|
|
1001
|
+
try {
|
|
1002
|
+
return (0, import_binaryDisk.hashFile)(file);
|
|
1003
|
+
} catch {
|
|
1004
|
+
return void 0;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
function restoreCapturedPaths(root, snapshot, paths, staged) {
|
|
1008
|
+
const lost = [];
|
|
1009
|
+
const bytesAt = new Map(
|
|
1010
|
+
snapshot.byteFacts.flatMap((fact) => fact.state === "present" ? [[fact.path, fact.content]] : [])
|
|
1011
|
+
);
|
|
1012
|
+
const captured = [...Object.keys(snapshot.jsonText), ...bytesAt.keys()];
|
|
1013
|
+
const sources = staged.flatMap((item) => [item.file.temporary, (0, import_layoutScan.resolveLayoutPath)(root, item.path)]);
|
|
1014
|
+
for (const path2 of paths) {
|
|
1015
|
+
const origins = captured.filter((origin) => (0, import_layoutPaths.layoutCollisionKey)(origin) === (0, import_layoutPaths.layoutCollisionKey)(path2));
|
|
1016
|
+
try {
|
|
1017
|
+
if (!origins.includes(path2) && fs.existsSync((0, import_layoutScan.resolveLayoutPath)(root, path2))) unlinkLayoutFile(root, path2);
|
|
1018
|
+
for (const origin of origins) {
|
|
1019
|
+
const text = snapshot.jsonText[origin];
|
|
1020
|
+
const bytes = bytesAt.get(origin);
|
|
1021
|
+
const twin = bytes && sources.find((file) => (0, import_binaryDisk.sameBytes)(contentOf(file), bytes));
|
|
1022
|
+
if (text !== void 0) (0, import_workspace.atomicReplaceText)((0, import_layoutScan.resolveLayoutPath)(root, origin), text);
|
|
1023
|
+
else if (twin) fs.copyFileSync(twin, (0, import_layoutScan.resolveLayoutPath)(root, origin));
|
|
1024
|
+
else lost.push(origin);
|
|
1025
|
+
}
|
|
1026
|
+
} catch {
|
|
1027
|
+
lost.push(path2);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return lost;
|
|
1031
|
+
}
|
|
1032
|
+
function prepareLayoutPlan(input, captured) {
|
|
1033
|
+
const parsed = parsedLayoutState(captured.snapshot.stateText);
|
|
1034
|
+
if (Array.isArray(parsed)) return { status: "blocked", diagnostics: parsed };
|
|
1035
|
+
const state = parsed;
|
|
1036
|
+
const evidence = { ...persistedEvidence(state), ...planSubmissionProofs(state, input.source) };
|
|
1037
|
+
const diagnostics = snapshotSeedDiagnostics(state, captured.snapshot);
|
|
1038
|
+
if (diagnostics.length > 0) return { status: "blocked", diagnostics };
|
|
1039
|
+
const byteEvidence = { facts: captured.snapshot.byteFacts, diagnostics: [] };
|
|
1040
|
+
const composed = (0, import_layoutCompose.composeLayoutSubmission)({ scan: captured.snapshot.scan, byteEvidence, evidence });
|
|
1041
|
+
let staleOrigins = [];
|
|
1042
|
+
let current = composed;
|
|
1043
|
+
if (composed.status === "blocked" && input.source.kind === "checkout" && input.head) {
|
|
1044
|
+
staleOrigins = staleDuplicateOrigins(
|
|
1045
|
+
captured.snapshot.scan,
|
|
1046
|
+
composed.diagnostics,
|
|
1047
|
+
input.head,
|
|
1048
|
+
evidence.groupedRoutes
|
|
1049
|
+
);
|
|
1050
|
+
const dropped = new Set(staleOrigins);
|
|
1051
|
+
const retry = dropped.size ? (0, import_layoutCompose.composeLayoutSubmission)({
|
|
1052
|
+
scan: {
|
|
1053
|
+
...captured.snapshot.scan,
|
|
1054
|
+
artifacts: captured.snapshot.scan.artifacts.filter((item) => !dropped.has(item.path))
|
|
1055
|
+
},
|
|
1056
|
+
byteEvidence,
|
|
1057
|
+
evidence
|
|
1058
|
+
}) : composed;
|
|
1059
|
+
if (retry.status === "complete") current = retry;
|
|
1060
|
+
else staleOrigins = [];
|
|
1061
|
+
}
|
|
1062
|
+
if (current.status === "blocked") return { status: "blocked", diagnostics: current.diagnostics };
|
|
1063
|
+
let readback;
|
|
1064
|
+
const authoritative = input.head;
|
|
1065
|
+
if (input.source.kind === "receipt" || input.source.kind === "checkout") {
|
|
1066
|
+
if (!input.head)
|
|
1067
|
+
return { status: "blocked", diagnostics: [(0, import_layoutCore.diagnostic)("missing-head", ".", "This plan needs a Head")] };
|
|
1068
|
+
}
|
|
1069
|
+
if (input.source.kind === "receipt") {
|
|
1070
|
+
const decided = receiptDecisions(state, input.source.planId, input.head, current);
|
|
1071
|
+
if ("diagnostics" in decided) return { status: "blocked", diagnostics: decided.diagnostics };
|
|
1072
|
+
readback = decided.readback;
|
|
1073
|
+
} else {
|
|
1074
|
+
const eligibility = (0, import_layoutReadback.decideCheckoutEligibility)({
|
|
1075
|
+
head: input.head,
|
|
1076
|
+
baseline: state.baseline,
|
|
1077
|
+
current,
|
|
1078
|
+
force: input.source.force
|
|
1079
|
+
});
|
|
1080
|
+
if (eligibility.status === "blocked") return { status: "blocked", diagnostics: [...eligibility.diagnostics] };
|
|
1081
|
+
const materialized = (0, import_layoutReadback.planMaterialization)({
|
|
1082
|
+
eligibility,
|
|
1083
|
+
...authoritative ? { head: authoritative } : {},
|
|
1084
|
+
current
|
|
1085
|
+
});
|
|
1086
|
+
if (materialized.status === "blocked") return { status: "blocked", diagnostics: [...materialized.diagnostics] };
|
|
1087
|
+
readback = materialized;
|
|
1088
|
+
}
|
|
1089
|
+
const destinations = new Set(
|
|
1090
|
+
readback.materializations.flatMap(
|
|
1091
|
+
(item) => item.mode === "set" ? [item.codec === "grouped" ? item.destination.file : item.bytes] : []
|
|
1092
|
+
)
|
|
1093
|
+
);
|
|
1094
|
+
const staleRemovals = staleOrigins.filter((path2) => !destinations.has(path2));
|
|
1095
|
+
if (staleRemovals.length > 0)
|
|
1096
|
+
readback = {
|
|
1097
|
+
...readback,
|
|
1098
|
+
deletes: {
|
|
1099
|
+
...readback.deletes,
|
|
1100
|
+
json: [...readback.deletes.json, ...staleRemovals.map((path2) => ({ path: path2, documentKeys: [] }))]
|
|
1101
|
+
}
|
|
1102
|
+
};
|
|
1103
|
+
const rendering = (0, import_layoutReadback.planReceiptRendering)({ readback });
|
|
1104
|
+
if (rendering.status === "blocked") return { status: "blocked", diagnostics: [...rendering.diagnostics] };
|
|
1105
|
+
if (rendering.retainedRemovalKeys.length > 0) {
|
|
1106
|
+
const retained = new Set(rendering.retainedRemovalKeys);
|
|
1107
|
+
readback = {
|
|
1108
|
+
...readback,
|
|
1109
|
+
deletes: {
|
|
1110
|
+
...readback.deletes,
|
|
1111
|
+
keys: readback.deletes.keys.filter((key) => !retained.has(key)),
|
|
1112
|
+
sources: readback.deletes.sources.filter((source) => {
|
|
1113
|
+
const key = stableSourceKeyOf(source);
|
|
1114
|
+
return key === void 0 || !retained.has(key);
|
|
1115
|
+
})
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
if (rendering.unmaterializedKeys.length > 0) {
|
|
1120
|
+
const dropped = new Set(rendering.unmaterializedKeys);
|
|
1121
|
+
readback = {
|
|
1122
|
+
...readback,
|
|
1123
|
+
materializations: readback.materializations.filter(
|
|
1124
|
+
(item) => !(item.mode === "set" && dropped.has(item.documentKey))
|
|
1125
|
+
)
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
const sets = readback.materializations.filter(
|
|
1129
|
+
(item) => item.mode === "set"
|
|
1130
|
+
);
|
|
1131
|
+
const authoritativeDocuments = new Map(sets.map((item) => [item.documentKey, item.document]));
|
|
1132
|
+
const adoptedKeys = sets.map((item) => item.documentKey).sort(import_layoutCore.compareText);
|
|
1133
|
+
const baselineSet = {};
|
|
1134
|
+
for (const key of adoptedKeys) {
|
|
1135
|
+
const hash = input.source.kind === "receipt" ? receiptHash(readback, key) : input.head.manifest[key];
|
|
1136
|
+
if (!hash)
|
|
1137
|
+
return {
|
|
1138
|
+
status: "blocked",
|
|
1139
|
+
diagnostics: [(0, import_layoutCore.diagnostic)("missing-adopted-baseline", key, "Accepted resource has no baseline hash")]
|
|
1140
|
+
};
|
|
1141
|
+
baselineSet[key] = hash;
|
|
1142
|
+
}
|
|
1143
|
+
const appliedBaseline = {};
|
|
1144
|
+
if (input.source.kind === "receipt") {
|
|
1145
|
+
const deleted = new Set(readback.deletes.keys);
|
|
1146
|
+
for (const item of readback.receiptResults)
|
|
1147
|
+
if ((item.outcome === import_farseer_client.OperationOutcomeOutcomeEnum.Applied || item.handle !== void 0 && item.assignment !== void 0) && item.documentKey && item.receiptHash && !deleted.has(item.documentKey) && baselineSet[item.documentKey] === void 0 && state.baseline[item.documentKey] !== item.receiptHash)
|
|
1148
|
+
appliedBaseline[item.documentKey] = item.receiptHash;
|
|
1149
|
+
}
|
|
1150
|
+
const currentBytes = new Map(captured.snapshot.byteFacts.map((fact) => [fact.path, fact]));
|
|
1151
|
+
const jsonWrites = rendering.json.flatMap((item) => {
|
|
1152
|
+
const text = `${JSON.stringify(item.value, null, 2)}
|
|
1153
|
+
`;
|
|
1154
|
+
return captured.snapshot.jsonText[item.path] === text ? [] : [{ path: item.path, text, authorizingDocumentKeys: [...item.authorizingDocumentKeys] }];
|
|
1155
|
+
});
|
|
1156
|
+
const byteWrites = rendering.bytes.flatMap((item) => {
|
|
1157
|
+
const fact = currentBytes.get(item.destination);
|
|
1158
|
+
return fact?.state === "present" && same(fact.content, item.descriptor) ? [] : [byteWrite(item)];
|
|
1159
|
+
});
|
|
1160
|
+
const pending = jsonWrites.length + byteWrites.length + rendering.removals.length + readback.identityPatches.length + adoptedKeys.length + Object.keys(appliedBaseline).length + readback.deletes.keys.length;
|
|
1161
|
+
const action = pending === 0 ? "noop" : "write";
|
|
1162
|
+
return {
|
|
1163
|
+
status: "complete",
|
|
1164
|
+
prepared: {
|
|
1165
|
+
state,
|
|
1166
|
+
current,
|
|
1167
|
+
readback,
|
|
1168
|
+
rendering,
|
|
1169
|
+
authoritative,
|
|
1170
|
+
authoritativeDocuments,
|
|
1171
|
+
adoptedKeys,
|
|
1172
|
+
baselineSet,
|
|
1173
|
+
appliedBaseline,
|
|
1174
|
+
jsonWrites,
|
|
1175
|
+
byteWrites,
|
|
1176
|
+
requiredPaths: requiredPathsFor(captured.snapshot, state, rendering),
|
|
1177
|
+
notices: [...readback.notices, ...rendering.notices, ...localPathNotices(captured.snapshot.scan)],
|
|
1178
|
+
dropQuarantinedReceipts: input.source.kind === "checkout" && input.source.force === true,
|
|
1179
|
+
compositionWarnings: [
|
|
1180
|
+
...(0, import_layoutCore.clone)(current.warnings),
|
|
1181
|
+
...readback.unmaterializedDiagnostics,
|
|
1182
|
+
...rendering.unmaterializedDiagnostics
|
|
1183
|
+
],
|
|
1184
|
+
action
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
function harvestRoutes(recomposed, sources, rewritten) {
|
|
1189
|
+
const mine = (source) => sources.has((0, import_layoutCore.sourceIdentityKey)(source));
|
|
1190
|
+
return {
|
|
1191
|
+
grouped: recomposed.grouped.observations.flatMap(
|
|
1192
|
+
(observation) => (mine(observation.source) || groupHeader(observation.source, observation.selector.file, rewritten)) && observation.currentHash ? [
|
|
1193
|
+
{
|
|
1194
|
+
source: (0, import_layoutCore.clone)(observation.source),
|
|
1195
|
+
selector: (0, import_layoutCore.clone)(observation.selector),
|
|
1196
|
+
sourcePath: (0, import_layoutCore.clone)(observation.sourcePath),
|
|
1197
|
+
priorCleanHash: observation.currentHash,
|
|
1198
|
+
...observation.derivedSelectorHash ? { derivedSelectorHash: observation.derivedSelectorHash } : {},
|
|
1199
|
+
contributor: observation.contributor
|
|
1200
|
+
}
|
|
1201
|
+
] : []
|
|
1202
|
+
),
|
|
1203
|
+
binary: [...recomposed.binary.rawObservations, ...recomposed.binary.attachmentObservations].flatMap(
|
|
1204
|
+
(observation) => mine(observation.source) && observation.currentHash ? [
|
|
1205
|
+
{
|
|
1206
|
+
source: (0, import_layoutCore.clone)(observation.source),
|
|
1207
|
+
selector: (0, import_layoutCore.clone)(observation.selector),
|
|
1208
|
+
sourcePath: (0, import_layoutCore.clone)(observation.sourcePath),
|
|
1209
|
+
...observation.bytes ? { bytes: observation.bytes } : {},
|
|
1210
|
+
priorCleanHash: observation.currentHash,
|
|
1211
|
+
contributor: observation.contributor,
|
|
1212
|
+
...observation.entryHash ? { entryHash: observation.entryHash } : {},
|
|
1213
|
+
...observation.byteHash ? { byteHash: observation.byteHash } : {}
|
|
1214
|
+
}
|
|
1215
|
+
] : []
|
|
1216
|
+
),
|
|
1217
|
+
navigation: recomposed.rawNavigation.flatMap(
|
|
1218
|
+
(observation) => mine(observation.source) && observation.groupFile && observation.currentHash ? [
|
|
1219
|
+
{
|
|
1220
|
+
source: (0, import_layoutCore.clone)(observation.source),
|
|
1221
|
+
selector: (0, import_layoutCore.clone)(observation.selector),
|
|
1222
|
+
sourcePath: (0, import_layoutCore.clone)(observation.sourcePath),
|
|
1223
|
+
groupFile: observation.groupFile,
|
|
1224
|
+
priorCleanHash: observation.currentHash
|
|
1225
|
+
}
|
|
1226
|
+
] : []
|
|
1227
|
+
)
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
function groupHeader(source, file, rewritten) {
|
|
1231
|
+
return source.type === "group" && rewritten.has(file);
|
|
1232
|
+
}
|
|
1233
|
+
function observedCleanly(recomposed, source) {
|
|
1234
|
+
const key = (0, import_layoutCore.sourceIdentityKey)(source);
|
|
1235
|
+
const observations = [
|
|
1236
|
+
...recomposed.grouped.observations,
|
|
1237
|
+
...recomposed.binary.rawObservations,
|
|
1238
|
+
...recomposed.binary.attachmentObservations
|
|
1239
|
+
].filter((observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source) === key);
|
|
1240
|
+
return observations.every(
|
|
1241
|
+
(observation) => !!observation.currentHash && ["clean", "new"].includes(observation.state)
|
|
1242
|
+
);
|
|
1243
|
+
}
|
|
1244
|
+
function sameDocument(left, right) {
|
|
1245
|
+
return (0, import_documents.canonicalText)((0, import_layoutReadback.withoutContainerSuppliedFields)(left)) === (0, import_documents.canonicalText)((0, import_layoutReadback.withoutContainerSuppliedFields)(right));
|
|
1246
|
+
}
|
|
1247
|
+
function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
|
|
1248
|
+
const original = (0, import_documents.parseState)(captured.snapshot.stateText);
|
|
1249
|
+
const base = removeLayoutState(original, deletes, removal.removed);
|
|
1250
|
+
const previous = base.layout.evidence;
|
|
1251
|
+
const sourceOf = (key) => (0, import_layoutCore.stableSource)(key);
|
|
1252
|
+
const adoptedSources = new Set(
|
|
1253
|
+
prepared.adoptedKeys.flatMap((key) => {
|
|
1254
|
+
const source = sourceOf(key);
|
|
1255
|
+
return source ? [(0, import_layoutCore.sourceIdentityKey)(source)] : [];
|
|
1256
|
+
})
|
|
1257
|
+
);
|
|
1258
|
+
const rewrittenFiles = new Set(prepared.rendering.json.map((item) => item.path));
|
|
1259
|
+
const refreshed = new Set(adoptedSources);
|
|
1260
|
+
const untouched = (items) => items.filter((item) => !refreshed.has((0, import_layoutCore.sourceIdentityKey)(item.source)));
|
|
1261
|
+
const untouchedGrouped = (items) => items.filter(
|
|
1262
|
+
(item) => !refreshed.has((0, import_layoutCore.sourceIdentityKey)(item.source)) && !groupHeader(item.source, item.selector.file, rewrittenFiles)
|
|
1263
|
+
);
|
|
1264
|
+
const derived = [...untouched(previous.derivedSourceProofs)];
|
|
1265
|
+
for (const proof of prepared.readback.derivedSourceProofs) derived.push((0, import_layoutCore.clone)(proof));
|
|
1266
|
+
for (const key of prepared.adoptedKeys) {
|
|
1267
|
+
if (!key.startsWith("user_permissions/")) continue;
|
|
1268
|
+
const source = sourceOf(key);
|
|
1269
|
+
const document = prepared.authoritativeDocuments.get(key);
|
|
1270
|
+
const selectorHash = document && (0, import_layoutProjection.derivedSourceSelectorHash)(document);
|
|
1271
|
+
if (!source || !selectorHash) continue;
|
|
1272
|
+
if (derived.some((proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source) === (0, import_layoutCore.sourceIdentityKey)(source))) continue;
|
|
1273
|
+
derived.push({
|
|
1274
|
+
source: { type: "resource", resource: { kind: "user_permissions", id: source.resource.id } },
|
|
1275
|
+
selectorHash
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
let detachedDocumentProofs = { ...previous.detachedDocumentProofs };
|
|
1279
|
+
let detachedFileProofs = { ...previous.detachedFileProofs };
|
|
1280
|
+
for (const damage of prepared.readback.pendingDamage) {
|
|
1281
|
+
const proof = {
|
|
1282
|
+
reason: "damage-proof",
|
|
1283
|
+
sourceKey: (0, import_layoutCore.sourceIdentityKey)(damage.evidence.source),
|
|
1284
|
+
placementHash: damage.evidence.locationHash,
|
|
1285
|
+
baselineHash: damage.evidence.canonicalHash
|
|
1286
|
+
};
|
|
1287
|
+
if (damage.codec === "grouped")
|
|
1288
|
+
detachedDocumentProofs = { ...detachedDocumentProofs, [damage.destination.file]: proof };
|
|
1289
|
+
else detachedFileProofs = { ...detachedFileProofs, [damage.destination.sidecar]: proof };
|
|
1290
|
+
}
|
|
1291
|
+
const candidate = {
|
|
1292
|
+
groupedRoutes: untouchedGrouped(previous.groupedRoutes),
|
|
1293
|
+
binaryRoutes: untouched(previous.binaryRoutes),
|
|
1294
|
+
groupedSubmissionProofs: [],
|
|
1295
|
+
binarySubmissionProofs: [],
|
|
1296
|
+
derivedSourceProofs: derived,
|
|
1297
|
+
rawNavigationRoutes: untouched(previous.rawNavigationRoutes),
|
|
1298
|
+
canonicalBaseline: { ...base.baseline, ...prepared.appliedBaseline, ...prepared.baselineSet },
|
|
1299
|
+
detachedFileProofs,
|
|
1300
|
+
detachedDocumentProofs
|
|
1301
|
+
};
|
|
1302
|
+
const scan = (0, import_layoutScan.scanLayout)({ root, tracked: base.layout.tracked });
|
|
1303
|
+
const recomposed = (0, import_layoutCompose.composeLayoutSubmission)({
|
|
1304
|
+
scan,
|
|
1305
|
+
byteEvidence: (0, import_layoutScan.loadLayoutByteEvidence)({ root, scan, evidence: candidate }),
|
|
1306
|
+
evidence: candidate
|
|
1307
|
+
});
|
|
1308
|
+
const keep = (state, unverified2, diagnostics = [], notices = []) => ({ state, unverified: unverified2, diagnostics, notices });
|
|
1309
|
+
if (recomposed.status === "blocked")
|
|
1310
|
+
return keep(
|
|
1311
|
+
{ ...base, revisionId: prepared.authoritative.revisionId },
|
|
1312
|
+
[...prepared.adoptedKeys],
|
|
1313
|
+
recomposed.diagnostics
|
|
1314
|
+
);
|
|
1315
|
+
const bySource = (0, import_layoutCore.groupBySource)(recomposed.sources, (item) => (0, import_layoutCore.sourceIdentityKey)(item.mapping.source));
|
|
1316
|
+
const verified = [];
|
|
1317
|
+
const unverified = [];
|
|
1318
|
+
for (const key of prepared.adoptedKeys) {
|
|
1319
|
+
const source = sourceOf(key);
|
|
1320
|
+
const mappings = source ? bySource.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? [] : [];
|
|
1321
|
+
const composed = mappings.length === 1 ? recomposed.documents[mappings[0].mapping.documentIndex] : void 0;
|
|
1322
|
+
const expected = prepared.authoritativeDocuments.get(key);
|
|
1323
|
+
if (source && composed && expected && sameDocument(composed, expected) && observedCleanly(recomposed, source))
|
|
1324
|
+
verified.push(key);
|
|
1325
|
+
else unverified.push(key);
|
|
1326
|
+
}
|
|
1327
|
+
const verifiedSources = new Set(
|
|
1328
|
+
verified.flatMap((key) => {
|
|
1329
|
+
const source = sourceOf(key);
|
|
1330
|
+
return source ? [(0, import_layoutCore.sourceIdentityKey)(source)] : [];
|
|
1331
|
+
})
|
|
1332
|
+
);
|
|
1333
|
+
const appliedNotices = [];
|
|
1334
|
+
const applied = {};
|
|
1335
|
+
const appliedPath = (key) => {
|
|
1336
|
+
for (const patch of prepared.readback.identityPatches) if (patch.documentKey === key) return patch.container;
|
|
1337
|
+
for (const artifact of prepared.rendering.json)
|
|
1338
|
+
if (artifact.authorizingDocumentKeys.includes(key)) return artifact.path;
|
|
1339
|
+
return void 0;
|
|
1340
|
+
};
|
|
1341
|
+
for (const [key, hash] of Object.entries(prepared.appliedBaseline)) {
|
|
1342
|
+
const source = sourceOf(key);
|
|
1343
|
+
const mappings = source ? bySource.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? [] : [];
|
|
1344
|
+
const path2 = appliedPath(key);
|
|
1345
|
+
if (mappings.length === 1) applied[key] = hash;
|
|
1346
|
+
else appliedNotices.push({ status: path2 ? "unpatched-create" : "unmaterialized", path: path2 ?? key, key });
|
|
1347
|
+
}
|
|
1348
|
+
const restored = new Set([...refreshed].filter((key) => !verifiedSources.has(key)));
|
|
1349
|
+
const mineAgain = (items) => items.filter((item) => restored.has((0, import_layoutCore.sourceIdentityKey)(item.source)));
|
|
1350
|
+
const harvested = harvestRoutes(recomposed, verifiedSources, rewrittenFiles);
|
|
1351
|
+
const evidence = {
|
|
1352
|
+
groupedRoutes: [...candidate.groupedRoutes, ...harvested.grouped, ...mineAgain(previous.groupedRoutes)],
|
|
1353
|
+
binaryRoutes: [...candidate.binaryRoutes, ...harvested.binary, ...mineAgain(previous.binaryRoutes)],
|
|
1354
|
+
derivedSourceProofs: derived,
|
|
1355
|
+
rawNavigationRoutes: [
|
|
1356
|
+
...candidate.rawNavigationRoutes,
|
|
1357
|
+
...harvested.navigation,
|
|
1358
|
+
...mineAgain(previous.rawNavigationRoutes)
|
|
1359
|
+
],
|
|
1360
|
+
detachedFileProofs,
|
|
1361
|
+
detachedDocumentProofs
|
|
1362
|
+
};
|
|
1363
|
+
const tracking = trackedAfter({
|
|
1364
|
+
tracked: base.layout.tracked,
|
|
1365
|
+
before: original.layout.evidence,
|
|
1366
|
+
beforeScan: captured.snapshot.scan,
|
|
1367
|
+
after: evidence,
|
|
1368
|
+
afterScan: scan
|
|
1369
|
+
});
|
|
1370
|
+
const baseline = { ...base.baseline, ...applied };
|
|
1371
|
+
for (const key of verified) baseline[key] = prepared.baselineSet[key];
|
|
1372
|
+
const layout = {
|
|
1373
|
+
...base.layout,
|
|
1374
|
+
evidence,
|
|
1375
|
+
tracked: "tracked" in tracking ? tracking.tracked : (0, import_layoutCore.clone)(base.layout.tracked)
|
|
1376
|
+
};
|
|
1377
|
+
if (prepared.dropQuarantinedReceipts) delete layout.unreadableReceipts;
|
|
1378
|
+
return keep(
|
|
1379
|
+
{
|
|
1380
|
+
...base,
|
|
1381
|
+
revisionId: prepared.authoritative.revisionId,
|
|
1382
|
+
baseline,
|
|
1383
|
+
layout
|
|
1384
|
+
},
|
|
1385
|
+
unverified,
|
|
1386
|
+
[],
|
|
1387
|
+
appliedNotices
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
async function materializeLayoutPlan(input) {
|
|
1391
|
+
const seed = (0, import_layoutScan.captureLayoutWorkspaceSeed)(input.root);
|
|
1392
|
+
const first = prepareLayoutPlan(input, seed);
|
|
1393
|
+
if (first.status === "blocked") return first;
|
|
1394
|
+
const captured = (0, import_layoutScan.captureLayoutWorkspace)(input.root, first.prepared.requiredPaths);
|
|
1395
|
+
const second = prepareLayoutPlan(input, captured);
|
|
1396
|
+
if (second.status === "blocked") return second;
|
|
1397
|
+
const prepared = second.prepared;
|
|
1398
|
+
if (prepared.action !== first.prepared.action || !(0, import_layoutScan.sameValue)(prepared.requiredPaths, first.prepared.requiredPaths))
|
|
1399
|
+
return (0, import_layoutCore.blocked)([
|
|
1400
|
+
(0, import_layoutCore.diagnostic)("layout-path-requirements-changed", ".", "Layout paths changed while preparing the plan")
|
|
1401
|
+
]);
|
|
1402
|
+
const pathDiagnostics = snapshotPathDiagnostics(prepared.state, captured.snapshot, {
|
|
1403
|
+
...persistedEvidence(prepared.state),
|
|
1404
|
+
...planSubmissionProofs(prepared.state, input.source)
|
|
1405
|
+
});
|
|
1406
|
+
if (pathDiagnostics.length > 0) return (0, import_layoutCore.blocked)(pathDiagnostics);
|
|
1407
|
+
const performedDeletes = (removals) => {
|
|
1408
|
+
const retained = new Set(removals.retained);
|
|
1409
|
+
if (retained.size === 0) return prepared.readback.deletes;
|
|
1410
|
+
return {
|
|
1411
|
+
...prepared.readback.deletes,
|
|
1412
|
+
keys: prepared.readback.deletes.keys.filter((key) => !retained.has(key)),
|
|
1413
|
+
sources: prepared.readback.deletes.sources.filter((source) => {
|
|
1414
|
+
const key = stableSourceKeyOf(source);
|
|
1415
|
+
return key === void 0 || !retained.has(key);
|
|
1416
|
+
})
|
|
1417
|
+
};
|
|
1418
|
+
};
|
|
1419
|
+
const outcome = (removals, unverified, verificationDiagnostics = [], extraNotices = [], unwritten = /* @__PURE__ */ new Set()) => ({
|
|
1420
|
+
status: "complete",
|
|
1421
|
+
action: prepared.action,
|
|
1422
|
+
// A set the writer left unwritten is reported as `unmaterialized`, never as written.
|
|
1423
|
+
materializations: prepared.readback.materializations.filter(
|
|
1424
|
+
(item) => item.mode !== "set" || !unwritten.has(item.documentKey)
|
|
1425
|
+
),
|
|
1426
|
+
deletes: performedDeletes(removals),
|
|
1427
|
+
adoptedDocumentKeys: prepared.adoptedKeys.filter((key) => !unverified.includes(key)),
|
|
1428
|
+
unverifiedDocumentKeys: [...unverified],
|
|
1429
|
+
verificationDiagnostics,
|
|
1430
|
+
compositionWarnings: prepared.compositionWarnings,
|
|
1431
|
+
jsonWrites: prepared.jsonWrites,
|
|
1432
|
+
byteWrites: prepared.byteWrites,
|
|
1433
|
+
removals,
|
|
1434
|
+
notices: [...prepared.notices, ...extraNotices]
|
|
1435
|
+
});
|
|
1436
|
+
if (prepared.action === "noop") {
|
|
1437
|
+
(0, import_workspace.saveLearnedByteHashes)(input.root, captured.snapshot.stateText);
|
|
1438
|
+
return outcome({ removed: [], rewritten: [], kept: [], retained: [] }, []);
|
|
1439
|
+
}
|
|
1440
|
+
const written = [
|
|
1441
|
+
...prepared.jsonWrites.map((write) => write.path),
|
|
1442
|
+
...prepared.byteWrites.map((write) => write.path)
|
|
1443
|
+
];
|
|
1444
|
+
const bytes = { staged: [], sidecars: /* @__PURE__ */ new Map(), paired: /* @__PURE__ */ new Set() };
|
|
1445
|
+
const held = /* @__PURE__ */ new Map();
|
|
1446
|
+
const cleanupWarnings = [];
|
|
1447
|
+
const vacated = [];
|
|
1448
|
+
let createdDirectories = [];
|
|
1449
|
+
let unpaired;
|
|
1450
|
+
let order;
|
|
1451
|
+
let result;
|
|
1452
|
+
const abandon = () => {
|
|
1453
|
+
bytes.inFlight?.();
|
|
1454
|
+
for (const item of [...bytes.staged.map((entry) => entry.file), ...bytes.sidecars.values(), ...held.values()])
|
|
1455
|
+
item.cleanup();
|
|
1456
|
+
removeEmptyDirectories(input.root, createdDirectories);
|
|
1457
|
+
};
|
|
1458
|
+
deferInterrupts();
|
|
1459
|
+
activeWrites.add(abandon);
|
|
1460
|
+
try {
|
|
1461
|
+
const current = (0, import_layoutScan.captureLayoutWorkspace)(input.root, prepared.requiredPaths);
|
|
1462
|
+
if (!(0, import_layoutScan.sameValue)(current.snapshot, captured.snapshot)) throw new Error("Layout changed before materialization");
|
|
1463
|
+
validateDestinations(current.snapshot, prepared);
|
|
1464
|
+
createdDirectories = createLayoutDestinationDirectories(input.root, written);
|
|
1465
|
+
await stageByteWrites(input, captured.snapshot, prepared, bytes);
|
|
1466
|
+
activeWrites.delete(abandon);
|
|
1467
|
+
for (const rename of prepared.rendering.directoryRenames) renameDirectorySpelling(input.root, rename);
|
|
1468
|
+
const vacate = (destination) => {
|
|
1469
|
+
for (const origin of vacateLayoutAliases(input.root, captured.snapshot, prepared.rendering.removals, [
|
|
1470
|
+
destination
|
|
1471
|
+
]))
|
|
1472
|
+
vacated.push({ origin, destination });
|
|
1473
|
+
};
|
|
1474
|
+
const byteWriteAt = new Map(prepared.byteWrites.map((write) => [write.path, write]));
|
|
1475
|
+
const jsonWriteAt = new Map(prepared.jsonWrites.map((write) => [write.path, write]));
|
|
1476
|
+
const units = [
|
|
1477
|
+
...bytes.staged.map((item) => {
|
|
1478
|
+
const sidecar = bytes.sidecars.get(item.path);
|
|
1479
|
+
const write = byteWriteAt.get(item.path);
|
|
1480
|
+
const sidecarWrite = sidecar && jsonWriteAt.get((0, import_layoutPaths.rawSidecarPath)(item.path));
|
|
1481
|
+
return {
|
|
1482
|
+
paths: sidecar ? [item.path, (0, import_layoutPaths.rawSidecarPath)(item.path)] : [item.path],
|
|
1483
|
+
keys: /* @__PURE__ */ new Set([write.authorizingDocumentKey, ...sidecarWrite?.authorizingDocumentKeys ?? []]),
|
|
1484
|
+
run: () => {
|
|
1485
|
+
vacate(item.path);
|
|
1486
|
+
item.file.commit((0, import_layoutScan.resolveLayoutPath)(input.root, item.path));
|
|
1487
|
+
if (!sidecar) return;
|
|
1488
|
+
unpaired = { path: item.path, identity: fileIdentity(input.root, item.path) };
|
|
1489
|
+
vacate((0, import_layoutPaths.rawSidecarPath)(item.path));
|
|
1490
|
+
sidecar.commit(sidecar.destination);
|
|
1491
|
+
unpaired = void 0;
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
}),
|
|
1495
|
+
...prepared.jsonWrites.filter((item) => !bytes.paired.has(item.path)).map(
|
|
1496
|
+
(item) => ({
|
|
1497
|
+
paths: [item.path],
|
|
1498
|
+
keys: new Set(item.authorizingDocumentKeys),
|
|
1499
|
+
hold: () => held.set(item.path, (0, import_workspace.stageText)((0, import_layoutScan.resolveLayoutPath)(input.root, item.path), item.text)),
|
|
1500
|
+
run: () => {
|
|
1501
|
+
vacate(item.path);
|
|
1502
|
+
const staged = held.get(item.path);
|
|
1503
|
+
if (staged) staged.commit((0, import_layoutScan.resolveLayoutPath)(input.root, item.path));
|
|
1504
|
+
else (0, import_workspace.atomicReplaceText)((0, import_layoutScan.resolveLayoutPath)(input.root, item.path), item.text);
|
|
1505
|
+
}
|
|
1506
|
+
})
|
|
1507
|
+
)
|
|
1508
|
+
];
|
|
1509
|
+
order = orderedWrites(
|
|
1510
|
+
units,
|
|
1511
|
+
currentHolders(prepared.current),
|
|
1512
|
+
destinationsMatchCapture(input.root, captured.snapshot)
|
|
1513
|
+
);
|
|
1514
|
+
order.run();
|
|
1515
|
+
const unrestored = order.revertUnfinished(
|
|
1516
|
+
(unit) => restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged)
|
|
1517
|
+
);
|
|
1518
|
+
if (unrestored.length > 0)
|
|
1519
|
+
throw new Error(
|
|
1520
|
+
`A changed destination stopped a rename cycle, and it could not put back ${unrestored.join(", ")}`
|
|
1521
|
+
);
|
|
1522
|
+
const removals = materializeLayoutRemovals({
|
|
1523
|
+
root: input.root,
|
|
1524
|
+
snapshot: captured.snapshot,
|
|
1525
|
+
removals: prepared.rendering.removals,
|
|
1526
|
+
written,
|
|
1527
|
+
keep: [...order.skipped]
|
|
1528
|
+
});
|
|
1529
|
+
const changed = order.notices();
|
|
1530
|
+
const adopted = adoptLayoutPlan(input.root, captured, prepared, removals, performedDeletes(removals));
|
|
1531
|
+
if ((0, import_layoutScan.stateText)(input.root) !== captured.snapshot.stateText)
|
|
1532
|
+
throw new Error("Layout state changed before the final save");
|
|
1533
|
+
(0, import_workspace.saveState)(input.root, adopted.state);
|
|
1534
|
+
result = outcome(
|
|
1535
|
+
removals,
|
|
1536
|
+
adopted.unverified,
|
|
1537
|
+
adopted.diagnostics,
|
|
1538
|
+
[...adopted.notices, ...changed],
|
|
1539
|
+
order.skipped
|
|
1540
|
+
);
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
activeWrites.delete(abandon);
|
|
1543
|
+
const lost = [
|
|
1544
|
+
...restoreVacatedOrigins(input.root, captured.snapshot, vacated, [
|
|
1545
|
+
...bytes.staged,
|
|
1546
|
+
...[...bytes.sidecars].map(([path2, file]) => ({
|
|
1547
|
+
path: (0, import_layoutPaths.rawSidecarPath)(path2),
|
|
1548
|
+
file,
|
|
1549
|
+
beside: true
|
|
1550
|
+
}))
|
|
1551
|
+
]),
|
|
1552
|
+
...order?.revertUnfinished(
|
|
1553
|
+
(unit) => restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged)
|
|
1554
|
+
) ?? []
|
|
1555
|
+
];
|
|
1556
|
+
const stray = withdrawUnpairedBytes(input.root, captured.snapshot, vacated, unpaired);
|
|
1557
|
+
if (lost.length === 0 && stray.length === 0) throw error;
|
|
1558
|
+
const message = [
|
|
1559
|
+
error instanceof Error ? error.message : String(error),
|
|
1560
|
+
...lost.length > 0 ? [`freed for a rename before the write: ${[...new Set(lost)].join(", ")}`] : [],
|
|
1561
|
+
...stray.length > 0 ? [`written without its sidecar: ${stray.join(", ")}`] : []
|
|
1562
|
+
];
|
|
1563
|
+
throw new Error(message.join("; "), { cause: error });
|
|
1564
|
+
} finally {
|
|
1565
|
+
const clean = (remove, label) => {
|
|
1566
|
+
try {
|
|
1567
|
+
remove();
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
cleanupWarnings.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
for (const item of bytes.staged) clean(() => item.file.cleanup(), `temporary file for ${item.path}`);
|
|
1573
|
+
for (const [path2, sidecar] of bytes.sidecars)
|
|
1574
|
+
clean(() => sidecar.cleanup(), `temporary file for ${(0, import_layoutPaths.rawSidecarPath)(path2)}`);
|
|
1575
|
+
for (const [path2, item] of held) clean(() => item.cleanup(), `temporary file for ${path2}`);
|
|
1576
|
+
removeEmptyDirectories(input.root, createdDirectories);
|
|
1577
|
+
}
|
|
1578
|
+
return { ...result, cleanupWarnings };
|
|
1579
|
+
}
|
|
1580
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1581
|
+
0 && (module.exports = {
|
|
1582
|
+
createLayoutDestinationDirectories,
|
|
1583
|
+
exitAfterWrites,
|
|
1584
|
+
layoutReceiptDrafts,
|
|
1585
|
+
materializeLayoutPlan,
|
|
1586
|
+
materializeLayoutRemovals,
|
|
1587
|
+
quarantinedApplyAdvice,
|
|
1588
|
+
refuseUnwrittenReceipts,
|
|
1589
|
+
removeLayoutState,
|
|
1590
|
+
vacateLayoutAliases
|
|
1591
|
+
});
|
|
1592
|
+
//# sourceMappingURL=layoutReceipt.js.map
|