artifact-graph 0.11.0 → 0.13.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/CHANGELOG.md +25 -0
- package/CONTRIBUTING.md +1 -1
- package/INSTALL.md +1 -1
- package/README.md +50 -2
- package/README.zh-CN.md +43 -2
- package/contracts/restructure-mapping/schema.json +263 -0
- package/contracts/restructure-plan/schema.json +112 -0
- package/contracts/restructure-request/schema.json +48 -0
- package/dist/cli.js +2038 -225
- package/dist/index.cjs +1906 -170
- package/dist/index.d.cts +480 -3
- package/dist/index.d.ts +480 -3
- package/dist/index.js +1857 -162
- package/package.json +7 -4
package/dist/index.js
CHANGED
|
@@ -963,9 +963,13 @@ async function bootstrapVersionLock(root, options = {}) {
|
|
|
963
963
|
async function refreshVersionLock(root, options = {}) {
|
|
964
964
|
const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
|
|
965
965
|
const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
|
|
966
|
+
const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
|
|
966
967
|
const all = options.all === true || options.changedOnly !== true;
|
|
967
968
|
const mode = all ? "all" : "changed-only";
|
|
968
969
|
const warnings = [];
|
|
970
|
+
if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
|
|
971
|
+
throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
|
|
972
|
+
}
|
|
969
973
|
if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
|
|
970
974
|
throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
|
|
971
975
|
}
|
|
@@ -975,9 +979,16 @@ async function refreshVersionLock(root, options = {}) {
|
|
|
975
979
|
const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
|
|
976
980
|
const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
|
|
977
981
|
const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
|
|
982
|
+
const currentArtifactRelationEdgeList = artifactRelationEdges(index);
|
|
978
983
|
const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
|
|
979
984
|
const currentEntries = /* @__PURE__ */ new Map();
|
|
980
985
|
const changedPathSet = new Set(changedPaths);
|
|
986
|
+
validatePreciseOrphanRemoval(
|
|
987
|
+
removeOrphanEdges,
|
|
988
|
+
lock,
|
|
989
|
+
new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
|
|
990
|
+
new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
|
|
991
|
+
);
|
|
981
992
|
const affectedEdges = /* @__PURE__ */ new Set();
|
|
982
993
|
const addedLocks = [];
|
|
983
994
|
const updatedLocks = [];
|
|
@@ -1004,12 +1015,13 @@ async function refreshVersionLock(root, options = {}) {
|
|
|
1004
1015
|
}
|
|
1005
1016
|
for (const existing of lock.locks) {
|
|
1006
1017
|
const current = currentEntries.get(existing.edgeId);
|
|
1007
|
-
const
|
|
1018
|
+
const removePrecisely = removeOrphanEdges.has(existing.edgeId);
|
|
1019
|
+
const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
|
|
1008
1020
|
if (affected) {
|
|
1009
1021
|
affectedEdges.add(existing.edgeId);
|
|
1010
1022
|
}
|
|
1011
1023
|
if (!current) {
|
|
1012
|
-
if (affected && options.removeOrphans === true) {
|
|
1024
|
+
if (removePrecisely || affected && options.removeOrphans === true) {
|
|
1013
1025
|
removedOrphans.push(existing.edgeId);
|
|
1014
1026
|
} else {
|
|
1015
1027
|
if (affected) {
|
|
@@ -1044,7 +1056,6 @@ async function refreshVersionLock(root, options = {}) {
|
|
|
1044
1056
|
if (mode === "changed-only" && changedPaths.length === 0) {
|
|
1045
1057
|
warnings.push("No changed paths were provided; no locks were refreshed.");
|
|
1046
1058
|
}
|
|
1047
|
-
const currentArtifactRelationEdgeList = artifactRelationEdges(index);
|
|
1048
1059
|
const existingArtifactRelationLocks = lock.artifactRelations ?? [];
|
|
1049
1060
|
const addedArtifactRelationLocks = [];
|
|
1050
1061
|
const updatedArtifactRelationLocks = [];
|
|
@@ -1088,10 +1099,11 @@ async function refreshVersionLock(root, options = {}) {
|
|
|
1088
1099
|
if (processedRelationEdgeIds.has(relEdgeId)) {
|
|
1089
1100
|
continue;
|
|
1090
1101
|
}
|
|
1091
|
-
const
|
|
1102
|
+
const removePrecisely = removeOrphanEdges.has(relEdgeId);
|
|
1103
|
+
const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
|
|
1092
1104
|
if (affected) {
|
|
1093
1105
|
affectedEdges.add(relEdgeId);
|
|
1094
|
-
if (options.removeOrphans === true) {
|
|
1106
|
+
if (removePrecisely || options.removeOrphans === true) {
|
|
1095
1107
|
removedArtifactRelationLocks.push(relEdgeId);
|
|
1096
1108
|
} else {
|
|
1097
1109
|
retainedArtifactRelationOrphans.push(relEdgeId);
|
|
@@ -1127,6 +1139,20 @@ async function refreshVersionLock(root, options = {}) {
|
|
|
1127
1139
|
warnings
|
|
1128
1140
|
};
|
|
1129
1141
|
}
|
|
1142
|
+
function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
|
|
1143
|
+
for (const edgeId of requestedEdgeIds) {
|
|
1144
|
+
const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
|
|
1145
|
+
if (matches === 0) {
|
|
1146
|
+
throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
|
|
1147
|
+
}
|
|
1148
|
+
if (matches !== 1) {
|
|
1149
|
+
throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
|
|
1150
|
+
}
|
|
1151
|
+
if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
|
|
1152
|
+
throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1130
1156
|
async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
|
|
1131
1157
|
const index = await buildVersionIndex(root);
|
|
1132
1158
|
const safeLockPath = normalizeRelativePath(root, lockPath);
|
|
@@ -3101,16 +3127,16 @@ function probeNativeBinding(context = {}) {
|
|
|
3101
3127
|
}
|
|
3102
3128
|
return { ok: true };
|
|
3103
3129
|
}
|
|
3104
|
-
function buildNativeBindingDiagnostic(
|
|
3130
|
+
function buildNativeBindingDiagnostic(failure2, probeContext) {
|
|
3105
3131
|
return {
|
|
3106
3132
|
selectedCli: probeContext.selectedCli,
|
|
3107
3133
|
runtime: `${process.execPath} (v${process.versions.node})`,
|
|
3108
|
-
abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(
|
|
3134
|
+
abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
|
|
3109
3135
|
installSource: probeContext.installSource,
|
|
3110
3136
|
probedFrom: probeContext.probedFrom,
|
|
3111
|
-
failedStage:
|
|
3112
|
-
cause:
|
|
3113
|
-
suggestion:
|
|
3137
|
+
failedStage: failure2.failedStage,
|
|
3138
|
+
cause: failure2.cause,
|
|
3139
|
+
suggestion: failure2.suggestion
|
|
3114
3140
|
};
|
|
3115
3141
|
}
|
|
3116
3142
|
function buildNativeBindingSuccessDiagnostic(probeContext) {
|
|
@@ -3231,7 +3257,7 @@ async function doctorArtifactChain(root, options = {}) {
|
|
|
3231
3257
|
const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
|
|
3232
3258
|
const warnings = [
|
|
3233
3259
|
...cli.warnings,
|
|
3234
|
-
...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy
|
|
3260
|
+
...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
|
|
3235
3261
|
...probe.ok ? [] : [
|
|
3236
3262
|
`better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
|
|
3237
3263
|
]
|
|
@@ -3243,7 +3269,7 @@ async function doctorArtifactChain(root, options = {}) {
|
|
|
3243
3269
|
node: {
|
|
3244
3270
|
version: process.versions.node,
|
|
3245
3271
|
compatible: nodeCompatible,
|
|
3246
|
-
required:
|
|
3272
|
+
required: REQUIRED_NODE_VERSION
|
|
3247
3273
|
},
|
|
3248
3274
|
config: {
|
|
3249
3275
|
path: configPath,
|
|
@@ -3347,8 +3373,10 @@ function resolveCandidatePath(root, candidatePath) {
|
|
|
3347
3373
|
return isAbsolute2(candidatePath) ? candidatePath : resolve3(root, candidatePath);
|
|
3348
3374
|
}
|
|
3349
3375
|
function isNodeCompatible(version) {
|
|
3350
|
-
const
|
|
3351
|
-
|
|
3376
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
|
|
3377
|
+
if (!match) return false;
|
|
3378
|
+
const [, major, minor, patch] = match.map(Number);
|
|
3379
|
+
return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
|
|
3352
3380
|
}
|
|
3353
3381
|
async function detectPnpmVersion() {
|
|
3354
3382
|
try {
|
|
@@ -3409,13 +3437,14 @@ function safeRealpath(path) {
|
|
|
3409
3437
|
return path;
|
|
3410
3438
|
}
|
|
3411
3439
|
}
|
|
3412
|
-
var execFileAsync2, KNOWN_COMMANDS;
|
|
3440
|
+
var execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
|
|
3413
3441
|
var init_cli_resolver = __esm({
|
|
3414
3442
|
"src/cli-resolver.ts"() {
|
|
3415
3443
|
"use strict";
|
|
3416
3444
|
init_versioned_traceability();
|
|
3417
3445
|
init_native_binding_diagnostics();
|
|
3418
3446
|
execFileAsync2 = promisify2(execFile2);
|
|
3447
|
+
REQUIRED_NODE_VERSION = ">=22.22.2 <23";
|
|
3419
3448
|
KNOWN_COMMANDS = [
|
|
3420
3449
|
"init",
|
|
3421
3450
|
"scan",
|
|
@@ -3974,8 +4003,8 @@ function validateReviewResult(input) {
|
|
|
3974
4003
|
validateReviewData(obj.review, "$.review", errors);
|
|
3975
4004
|
if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
|
|
3976
4005
|
const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
|
|
3977
|
-
findings.forEach((
|
|
3978
|
-
if (isPlainObject(
|
|
4006
|
+
findings.forEach((finding2, index) => {
|
|
4007
|
+
if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
|
|
3979
4008
|
errors.push({
|
|
3980
4009
|
path: `$.review.findings[${index}]`,
|
|
3981
4010
|
message: `${obj.decision} cannot contain an open block finding`
|
|
@@ -4993,12 +5022,1691 @@ var init_contract_kernel = __esm({
|
|
|
4993
5022
|
}
|
|
4994
5023
|
});
|
|
4995
5024
|
|
|
5025
|
+
// src/restructure-software.ts
|
|
5026
|
+
function lineStarts(raw) {
|
|
5027
|
+
const starts = [0];
|
|
5028
|
+
const buffer = Buffer.from(raw, "utf8");
|
|
5029
|
+
for (let index = 0; index < buffer.length; index += 1) {
|
|
5030
|
+
if (buffer[index] === 10) starts.push(index + 1);
|
|
5031
|
+
}
|
|
5032
|
+
return starts;
|
|
5033
|
+
}
|
|
5034
|
+
function markdownCodeLineMask(lines) {
|
|
5035
|
+
const result = new Array(lines.length).fill(false);
|
|
5036
|
+
let fence;
|
|
5037
|
+
lines.forEach((line, index) => {
|
|
5038
|
+
if (fence) {
|
|
5039
|
+
result[index] = true;
|
|
5040
|
+
const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
|
|
5041
|
+
if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
|
|
5042
|
+
return;
|
|
5043
|
+
}
|
|
5044
|
+
const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
|
|
5045
|
+
if (opening) {
|
|
5046
|
+
result[index] = true;
|
|
5047
|
+
fence = { marker: opening[1][0], length: opening[1].length };
|
|
5048
|
+
return;
|
|
5049
|
+
}
|
|
5050
|
+
if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
|
|
5051
|
+
});
|
|
5052
|
+
return result;
|
|
5053
|
+
}
|
|
5054
|
+
function markdownRecordHeadings(raw, type) {
|
|
5055
|
+
const lines = raw.split("\n");
|
|
5056
|
+
const masked = markdownCodeLineMask(lines);
|
|
5057
|
+
const pattern = type === "scenario" ? /^#{2,3}\s+(S-\d+[a-z]?)\s*[::]/ : type === "e2e_test" ? /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?/ : void 0;
|
|
5058
|
+
if (!pattern) return [];
|
|
5059
|
+
return lines.flatMap((line, index) => {
|
|
5060
|
+
if (masked[index]) return [];
|
|
5061
|
+
const match = pattern.exec(line.replace(/\r$/, ""));
|
|
5062
|
+
return match ? [{ id: match[1], line: index + 1 }] : [];
|
|
5063
|
+
});
|
|
5064
|
+
}
|
|
5065
|
+
function locateSoftwareRecord(raw, node, nodesInFile) {
|
|
5066
|
+
const byteLength = Buffer.byteLength(raw, "utf8");
|
|
5067
|
+
if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
|
|
5068
|
+
if (node.type !== "scenario" && node.type !== "e2e_test") {
|
|
5069
|
+
return {
|
|
5070
|
+
blockers: [{
|
|
5071
|
+
code: "UNSUPPORTED_RECORD_BOUNDARY",
|
|
5072
|
+
message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
|
|
5073
|
+
path: node.path,
|
|
5074
|
+
line: node.line
|
|
5075
|
+
}]
|
|
5076
|
+
};
|
|
5077
|
+
}
|
|
5078
|
+
const headings = markdownRecordHeadings(raw, node.type);
|
|
5079
|
+
const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
|
|
5080
|
+
const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
|
|
5081
|
+
const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
|
|
5082
|
+
const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
|
|
5083
|
+
const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
|
|
5084
|
+
const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
|
|
5085
|
+
if (inconsistent) {
|
|
5086
|
+
return {
|
|
5087
|
+
blockers: [{
|
|
5088
|
+
code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
|
|
5089
|
+
message: "\u4EE3\u7801\u56F4\u680F\u611F\u77E5\u7684\u8BB0\u5F55\u8FB9\u754C\u4E0E\u73B0\u6709\u56FE\u89E3\u6790\u7ED3\u679C\u4E0D\u4E00\u81F4\uFF1B\u5FC5\u987B\u5148\u7EDF\u4E00\u89E3\u6790\u8D23\u4EFB",
|
|
5090
|
+
path: node.path,
|
|
5091
|
+
line: node.line
|
|
5092
|
+
}]
|
|
5093
|
+
};
|
|
5094
|
+
}
|
|
5095
|
+
if (!heading) {
|
|
5096
|
+
return {
|
|
5097
|
+
blockers: [{
|
|
5098
|
+
code: "RECORD_BOUNDARY_MISSING",
|
|
5099
|
+
message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
|
|
5100
|
+
path: node.path,
|
|
5101
|
+
line: node.line
|
|
5102
|
+
}]
|
|
5103
|
+
};
|
|
5104
|
+
}
|
|
5105
|
+
const starts = lineStarts(raw);
|
|
5106
|
+
const nextLine = headings.find((item) => item.line > heading.line)?.line;
|
|
5107
|
+
return {
|
|
5108
|
+
range: {
|
|
5109
|
+
startByte: starts[heading.line - 1] ?? 0,
|
|
5110
|
+
endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
|
|
5111
|
+
},
|
|
5112
|
+
blockers: []
|
|
5113
|
+
};
|
|
5114
|
+
}
|
|
5115
|
+
function replaceSoftwareHeader(raw, header) {
|
|
5116
|
+
const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
|
|
5117
|
+
const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
|
|
5118
|
+
` : header;
|
|
5119
|
+
return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
|
|
5120
|
+
}
|
|
5121
|
+
var init_restructure_software = __esm({
|
|
5122
|
+
"src/restructure-software.ts"() {
|
|
5123
|
+
"use strict";
|
|
5124
|
+
}
|
|
5125
|
+
});
|
|
5126
|
+
|
|
5127
|
+
// src/restructure-file-set.ts
|
|
5128
|
+
import { createHash as createHash3 } from "crypto";
|
|
5129
|
+
import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
|
|
5130
|
+
import { join as join8, resolve as resolve5 } from "path";
|
|
5131
|
+
async function loadFoundationModule() {
|
|
5132
|
+
return await import(FOUNDATION_PACKAGE_NAME);
|
|
5133
|
+
}
|
|
5134
|
+
async function loadContractsModule() {
|
|
5135
|
+
return await import(CONTRACTS_PACKAGE_NAME);
|
|
5136
|
+
}
|
|
5137
|
+
async function verifyMechanismResult(result) {
|
|
5138
|
+
if (typeof result !== "object" || result === null || Array.isArray(result)) {
|
|
5139
|
+
return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
|
|
5140
|
+
}
|
|
5141
|
+
let contracts;
|
|
5142
|
+
let registration;
|
|
5143
|
+
try {
|
|
5144
|
+
contracts = await loadContractsModule();
|
|
5145
|
+
registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
|
|
5146
|
+
} catch (cause) {
|
|
5147
|
+
return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
|
|
5148
|
+
}
|
|
5149
|
+
if (registration === null) {
|
|
5150
|
+
return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
|
|
5151
|
+
}
|
|
5152
|
+
const verdict = contracts.validateDocument(result, {
|
|
5153
|
+
schemaId: registration.$id,
|
|
5154
|
+
dialect: registration.dialect,
|
|
5155
|
+
policy: "strict"
|
|
5156
|
+
});
|
|
5157
|
+
if (!verdict.valid) {
|
|
5158
|
+
return failure(
|
|
5159
|
+
"MECHANISM_RESULT_INVALID",
|
|
5160
|
+
`The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
|
|
5161
|
+
{ schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
|
|
5162
|
+
);
|
|
5163
|
+
}
|
|
5164
|
+
return { ok: true, data: result };
|
|
5165
|
+
}
|
|
5166
|
+
function failure(code, message, details) {
|
|
5167
|
+
return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
|
|
5168
|
+
}
|
|
5169
|
+
function candidateBytes(content) {
|
|
5170
|
+
return Buffer.from(content ?? "", "utf8");
|
|
5171
|
+
}
|
|
5172
|
+
function candidateByteDigest(content) {
|
|
5173
|
+
return createHash3("sha256").update(candidateBytes(content)).digest("hex");
|
|
5174
|
+
}
|
|
5175
|
+
function rawDigest(value, path) {
|
|
5176
|
+
if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
|
|
5177
|
+
throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
|
|
5178
|
+
}
|
|
5179
|
+
const raw = value.slice(DIGEST_PREFIX.length);
|
|
5180
|
+
if (!RAW_SHA256_PATTERN.test(raw)) {
|
|
5181
|
+
throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
|
|
5182
|
+
}
|
|
5183
|
+
return raw;
|
|
5184
|
+
}
|
|
5185
|
+
async function resolveRealRoot(root) {
|
|
5186
|
+
let canonical;
|
|
5187
|
+
try {
|
|
5188
|
+
canonical = await realpath(resolve5(root));
|
|
5189
|
+
} catch (cause) {
|
|
5190
|
+
return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
|
|
5191
|
+
}
|
|
5192
|
+
let info;
|
|
5193
|
+
try {
|
|
5194
|
+
info = await lstat2(canonical);
|
|
5195
|
+
} catch (cause) {
|
|
5196
|
+
return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
|
|
5197
|
+
}
|
|
5198
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
5199
|
+
return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
|
|
5200
|
+
}
|
|
5201
|
+
return { ok: true, data: canonical };
|
|
5202
|
+
}
|
|
5203
|
+
async function qualifyRestructureMechanism(root) {
|
|
5204
|
+
if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
|
|
5205
|
+
return failure(
|
|
5206
|
+
"APPLY_ENVIRONMENT_UNSUPPORTED",
|
|
5207
|
+
`Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
|
|
5208
|
+
);
|
|
5209
|
+
}
|
|
5210
|
+
const canonical = await resolveRealRoot(root);
|
|
5211
|
+
if (!canonical.ok) return canonical;
|
|
5212
|
+
let type;
|
|
5213
|
+
try {
|
|
5214
|
+
type = (await statfs(canonical.data)).type;
|
|
5215
|
+
} catch (cause) {
|
|
5216
|
+
return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
|
|
5217
|
+
}
|
|
5218
|
+
if (type !== APFS_STATFS_TYPE) {
|
|
5219
|
+
return failure(
|
|
5220
|
+
"APPLY_ENVIRONMENT_UNSUPPORTED",
|
|
5221
|
+
`Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
|
|
5222
|
+
);
|
|
5223
|
+
}
|
|
5224
|
+
return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
|
|
5225
|
+
}
|
|
5226
|
+
async function ensureRestructureMechanismRoot(canonicalRoot, options) {
|
|
5227
|
+
const target = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
|
|
5228
|
+
const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
|
|
5229
|
+
let info = await current();
|
|
5230
|
+
if (info === null) {
|
|
5231
|
+
if (!options.create) {
|
|
5232
|
+
return failure(
|
|
5233
|
+
"RECOVERY_MATERIALS_MISSING",
|
|
5234
|
+
`No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
|
|
5235
|
+
);
|
|
5236
|
+
}
|
|
5237
|
+
let created = false;
|
|
5238
|
+
try {
|
|
5239
|
+
await mkdir4(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
|
|
5240
|
+
created = true;
|
|
5241
|
+
} catch (cause) {
|
|
5242
|
+
if (cause.code !== "EEXIST") {
|
|
5243
|
+
return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
|
|
5244
|
+
}
|
|
5245
|
+
}
|
|
5246
|
+
info = await current();
|
|
5247
|
+
if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
|
|
5248
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
5249
|
+
return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
|
|
5250
|
+
}
|
|
5251
|
+
if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
|
|
5252
|
+
await chmod(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
|
|
5253
|
+
info = await current();
|
|
5254
|
+
if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
|
|
5255
|
+
return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
|
|
5256
|
+
}
|
|
5257
|
+
}
|
|
5258
|
+
}
|
|
5259
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
5260
|
+
return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
|
|
5261
|
+
}
|
|
5262
|
+
if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
|
|
5263
|
+
return failure(
|
|
5264
|
+
"MECHANISM_ROOT_UNSAFE",
|
|
5265
|
+
`${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
|
|
5266
|
+
);
|
|
5267
|
+
}
|
|
5268
|
+
return { ok: true, data: target };
|
|
5269
|
+
}
|
|
5270
|
+
async function createRestructureRootBinding(canonicalRoot) {
|
|
5271
|
+
try {
|
|
5272
|
+
const module = await loadFoundationModule();
|
|
5273
|
+
return { ok: true, data: await module.createFilesystemRootBinding(canonicalRoot) };
|
|
5274
|
+
} catch (cause) {
|
|
5275
|
+
return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
|
|
5276
|
+
}
|
|
5277
|
+
}
|
|
5278
|
+
function toOperation(candidate) {
|
|
5279
|
+
const expected = candidate.original.exists ? {
|
|
5280
|
+
exists: true,
|
|
5281
|
+
sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
|
|
5282
|
+
size: candidate.original.size,
|
|
5283
|
+
mode: candidate.original.mode
|
|
5284
|
+
} : { exists: false };
|
|
5285
|
+
if (candidate.action === "delete") {
|
|
5286
|
+
return { path: candidate.path, action: "delete", expected, next: null };
|
|
5287
|
+
}
|
|
5288
|
+
const bytes = candidateBytes(candidate.content);
|
|
5289
|
+
const declared = rawDigest(candidate.sha256, candidate.path);
|
|
5290
|
+
if (declared !== candidateByteDigest(candidate.content)) {
|
|
5291
|
+
throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
|
|
5292
|
+
}
|
|
5293
|
+
return {
|
|
5294
|
+
path: candidate.path,
|
|
5295
|
+
action: candidate.action,
|
|
5296
|
+
expected,
|
|
5297
|
+
next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
|
|
5298
|
+
};
|
|
5299
|
+
}
|
|
5300
|
+
async function buildFileSetApplyRequest(canonicalRoot, plan) {
|
|
5301
|
+
if (plan.candidates.length === 0) {
|
|
5302
|
+
return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
|
|
5303
|
+
}
|
|
5304
|
+
const binding = await createRestructureRootBinding(canonicalRoot);
|
|
5305
|
+
if (!binding.ok) return binding;
|
|
5306
|
+
let operations;
|
|
5307
|
+
try {
|
|
5308
|
+
operations = plan.candidates.map(toOperation);
|
|
5309
|
+
} catch (cause) {
|
|
5310
|
+
return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
|
|
5311
|
+
}
|
|
5312
|
+
return {
|
|
5313
|
+
ok: true,
|
|
5314
|
+
data: {
|
|
5315
|
+
schemaVersion: 1,
|
|
5316
|
+
kind: "skill-family.file-set-apply-request",
|
|
5317
|
+
operationId: plan.operation_id,
|
|
5318
|
+
root: canonicalRoot,
|
|
5319
|
+
rootBinding: binding.data,
|
|
5320
|
+
recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
|
|
5321
|
+
allowAdjacentStaging: true,
|
|
5322
|
+
environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
|
|
5323
|
+
validationTimeoutMs: plan.validation_timeout_ms,
|
|
5324
|
+
operations
|
|
5325
|
+
}
|
|
5326
|
+
};
|
|
5327
|
+
}
|
|
5328
|
+
async function applyRestructureFileSet(canonicalRoot, plan, options) {
|
|
5329
|
+
const request = await buildFileSetApplyRequest(canonicalRoot, plan);
|
|
5330
|
+
if (!request.ok) return request;
|
|
5331
|
+
const module = await loadFoundationModule();
|
|
5332
|
+
let raw;
|
|
5333
|
+
try {
|
|
5334
|
+
raw = await module.applyFileSet(request.data, { validate: options.validate });
|
|
5335
|
+
} catch (cause) {
|
|
5336
|
+
return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
|
|
5337
|
+
}
|
|
5338
|
+
return await verifyMechanismResult(raw);
|
|
5339
|
+
}
|
|
5340
|
+
async function observeRestructureJournal(canonicalRoot) {
|
|
5341
|
+
const journalRoot = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
|
|
5342
|
+
const module = await loadFoundationModule();
|
|
5343
|
+
try {
|
|
5344
|
+
return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
|
|
5345
|
+
} catch (cause) {
|
|
5346
|
+
return failure(
|
|
5347
|
+
"MAINTENANCE_OBSERVATION_FAILED",
|
|
5348
|
+
`The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
|
|
5349
|
+
);
|
|
5350
|
+
}
|
|
5351
|
+
}
|
|
5352
|
+
async function recoverRestructureFileSet(canonicalRoot, plan, options) {
|
|
5353
|
+
if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
|
|
5354
|
+
return failure(
|
|
5355
|
+
"MAINTENANCE_CONFIRMATION_REQUIRED",
|
|
5356
|
+
"restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
|
|
5357
|
+
);
|
|
5358
|
+
}
|
|
5359
|
+
const binding = await createRestructureRootBinding(canonicalRoot);
|
|
5360
|
+
if (!binding.ok) return binding;
|
|
5361
|
+
const observation = await observeRestructureJournal(canonicalRoot);
|
|
5362
|
+
if (!observation.ok) return observation;
|
|
5363
|
+
const maintenance = {
|
|
5364
|
+
observation: observation.data,
|
|
5365
|
+
confirmAllParticipantsStopped: true,
|
|
5366
|
+
confirmExclusiveMaintenance: true
|
|
5367
|
+
};
|
|
5368
|
+
const request = {
|
|
5369
|
+
schemaVersion: 1,
|
|
5370
|
+
kind: "skill-family.file-set-recovery-request",
|
|
5371
|
+
operationId: plan.operation_id,
|
|
5372
|
+
root: canonicalRoot,
|
|
5373
|
+
rootBinding: binding.data,
|
|
5374
|
+
recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
|
|
5375
|
+
environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
|
|
5376
|
+
allowAdjacentStaging: true,
|
|
5377
|
+
maintenance
|
|
5378
|
+
};
|
|
5379
|
+
const module = await loadFoundationModule();
|
|
5380
|
+
let raw;
|
|
5381
|
+
try {
|
|
5382
|
+
raw = await module.recoverFileSet(request);
|
|
5383
|
+
} catch (cause) {
|
|
5384
|
+
return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
|
|
5385
|
+
}
|
|
5386
|
+
return await verifyMechanismResult(raw);
|
|
5387
|
+
}
|
|
5388
|
+
async function pruneRestructureFileSet(canonicalRoot, plan, options) {
|
|
5389
|
+
const binding = await createRestructureRootBinding(canonicalRoot);
|
|
5390
|
+
if (!binding.ok) return binding;
|
|
5391
|
+
const request = {
|
|
5392
|
+
schemaVersion: 1,
|
|
5393
|
+
kind: "skill-family.file-set-prune-request",
|
|
5394
|
+
operationId: plan.operation_id,
|
|
5395
|
+
root: canonicalRoot,
|
|
5396
|
+
rootBinding: binding.data,
|
|
5397
|
+
recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
|
|
5398
|
+
environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
|
|
5399
|
+
};
|
|
5400
|
+
if (options.allParticipantsStopped && options.exclusiveMaintenance) {
|
|
5401
|
+
const observation = await observeRestructureJournal(canonicalRoot);
|
|
5402
|
+
if (!observation.ok) return observation;
|
|
5403
|
+
request.maintenance = {
|
|
5404
|
+
observation: observation.data,
|
|
5405
|
+
confirmAllParticipantsStopped: true,
|
|
5406
|
+
confirmExclusiveMaintenance: true
|
|
5407
|
+
};
|
|
5408
|
+
}
|
|
5409
|
+
const module = await loadFoundationModule();
|
|
5410
|
+
let raw;
|
|
5411
|
+
try {
|
|
5412
|
+
raw = await module.pruneFileSetRecovery(request);
|
|
5413
|
+
} catch (cause) {
|
|
5414
|
+
return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
|
|
5415
|
+
}
|
|
5416
|
+
return await verifyMechanismResult(raw);
|
|
5417
|
+
}
|
|
5418
|
+
function validationState(validation) {
|
|
5419
|
+
return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
|
|
5420
|
+
}
|
|
5421
|
+
function errorKinds(result) {
|
|
5422
|
+
return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
|
|
5423
|
+
}
|
|
5424
|
+
function applyProjection(result) {
|
|
5425
|
+
const kinds = errorKinds(result);
|
|
5426
|
+
if (result.outcome === "committed") {
|
|
5427
|
+
if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
|
|
5428
|
+
return {
|
|
5429
|
+
code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
|
|
5430
|
+
message: "The file set is committed but the exclusive project lock could not be released. Do not re-run apply for this plan; establish an exclusive maintenance interval and run restructure recover to confirm the terminal state.",
|
|
5431
|
+
ok: false,
|
|
5432
|
+
rerunApplyPermitted: false
|
|
5433
|
+
};
|
|
5434
|
+
}
|
|
5435
|
+
const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
|
|
5436
|
+
return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
|
|
5437
|
+
code: "APPLY_INCOMPLETE",
|
|
5438
|
+
message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
|
|
5439
|
+
ok: false,
|
|
5440
|
+
rerunApplyPermitted: false
|
|
5441
|
+
};
|
|
5442
|
+
}
|
|
5443
|
+
const codes = {
|
|
5444
|
+
"commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
|
|
5445
|
+
"recovery-required": ["APPLY_RECOVERY_REQUIRED", "The mechanism could not prove a safe terminal state. Materials and recorded facts are retained for an explicit maintenance recovery."],
|
|
5446
|
+
"rolled-back": ["APPLY_ROLLED_BACK", "The file set was rolled back to its original bytes and modes. This operation id is registered; re-plan to obtain a new id before applying again."]
|
|
5447
|
+
};
|
|
5448
|
+
const mapped = codes[result.outcome];
|
|
5449
|
+
if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
|
|
5450
|
+
if (result.outcome === "rejected") {
|
|
5451
|
+
const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
|
|
5452
|
+
return {
|
|
5453
|
+
code: "APPLY_REJECTED",
|
|
5454
|
+
message: identityTaken ? "The mechanism refused this plan because its operation id is already registered. Re-plan to obtain a new id before applying again." : "The mechanism refused the whole group before any business write. The environment can be corrected and the same plan retried.",
|
|
5455
|
+
ok: false,
|
|
5456
|
+
rerunApplyPermitted: !identityTaken
|
|
5457
|
+
};
|
|
5458
|
+
}
|
|
5459
|
+
return {
|
|
5460
|
+
code: "APPLY_UNEXPECTED_OUTCOME",
|
|
5461
|
+
message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
|
|
5462
|
+
ok: false,
|
|
5463
|
+
rerunApplyPermitted: false
|
|
5464
|
+
};
|
|
5465
|
+
}
|
|
5466
|
+
function recoverProjection(result) {
|
|
5467
|
+
const reading = (() => {
|
|
5468
|
+
switch (result.outcome) {
|
|
5469
|
+
case "already-committed":
|
|
5470
|
+
return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
|
|
5471
|
+
case "already-rolled-back":
|
|
5472
|
+
return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
|
|
5473
|
+
case "rolled-back":
|
|
5474
|
+
return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
|
|
5475
|
+
case "pruned":
|
|
5476
|
+
return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
|
|
5477
|
+
case "already-pruned":
|
|
5478
|
+
return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
|
|
5479
|
+
case "commit-unconfirmed":
|
|
5480
|
+
return { code: "RECOVER_COMMIT_UNCONFIRMED", message: "A valid commit decision is durable but its strict confirmation did not hold; it is never reversed automatically.", ok: false };
|
|
5481
|
+
case "recovery-required":
|
|
5482
|
+
return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
|
|
5483
|
+
case "rejected":
|
|
5484
|
+
return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
|
|
5485
|
+
default:
|
|
5486
|
+
return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
|
|
5487
|
+
}
|
|
5488
|
+
})();
|
|
5489
|
+
return { ...reading, rerunApplyPermitted: false };
|
|
5490
|
+
}
|
|
5491
|
+
function pruneProjection(result) {
|
|
5492
|
+
const reading = (() => {
|
|
5493
|
+
switch (result.outcome) {
|
|
5494
|
+
case "pruned":
|
|
5495
|
+
return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
|
|
5496
|
+
case "already-pruned":
|
|
5497
|
+
return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
|
|
5498
|
+
case "rejected":
|
|
5499
|
+
return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
|
|
5500
|
+
case "recovery-required":
|
|
5501
|
+
return { code: "PRUNE_RECOVERY_REQUIRED", message: "The cleanup stopped half way; the refusal and material facts are retained and a retry resumes the same plan.", ok: false };
|
|
5502
|
+
default:
|
|
5503
|
+
return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
|
|
5504
|
+
}
|
|
5505
|
+
})();
|
|
5506
|
+
return { ...reading, rerunApplyPermitted: false };
|
|
5507
|
+
}
|
|
5508
|
+
function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
|
|
5509
|
+
const base = {
|
|
5510
|
+
foundation: result,
|
|
5511
|
+
planPath,
|
|
5512
|
+
planDigest,
|
|
5513
|
+
operation: result.operation,
|
|
5514
|
+
outcome: result.outcome,
|
|
5515
|
+
preflight: result.preflight,
|
|
5516
|
+
businessWrite: result.businessWrite,
|
|
5517
|
+
validation: result.validation,
|
|
5518
|
+
validationState: validationState(result.validation),
|
|
5519
|
+
recovery: result.recovery,
|
|
5520
|
+
paths: result.paths,
|
|
5521
|
+
errors: result.errors,
|
|
5522
|
+
materialPath: result.materials.relPath,
|
|
5523
|
+
errorKinds: errorKinds(result)
|
|
5524
|
+
};
|
|
5525
|
+
const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
|
|
5526
|
+
return { ...base, ...reading };
|
|
5527
|
+
}
|
|
5528
|
+
var RESTRUCTURE_RECOVERY_REL_PATH, RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH, RESTRUCTURE_RECOVERY_ROOT_MODE, RESTRUCTURE_QUALIFIED_PLATFORM, RESTRUCTURE_QUALIFIED_ARCH, RESTRUCTURE_QUALIFIED_FILESYSTEM, APFS_STATFS_TYPE, DIGEST_PREFIX, RAW_SHA256_PATTERN, FOUNDATION_PACKAGE_NAME, CONTRACTS_PACKAGE_NAME, FILE_SET_RESULT_OBJECT, APPLY_MAINTENANCE_ERROR_KINDS;
|
|
5529
|
+
var init_restructure_file_set = __esm({
|
|
5530
|
+
"src/restructure-file-set.ts"() {
|
|
5531
|
+
"use strict";
|
|
5532
|
+
RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
|
|
5533
|
+
RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
|
|
5534
|
+
RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
|
|
5535
|
+
RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
|
|
5536
|
+
RESTRUCTURE_QUALIFIED_ARCH = "arm64";
|
|
5537
|
+
RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
|
|
5538
|
+
APFS_STATFS_TYPE = 26;
|
|
5539
|
+
DIGEST_PREFIX = "sha256:";
|
|
5540
|
+
RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
|
|
5541
|
+
FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
|
|
5542
|
+
CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
|
|
5543
|
+
FILE_SET_RESULT_OBJECT = "file-set-result";
|
|
5544
|
+
APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
|
|
5545
|
+
}
|
|
5546
|
+
});
|
|
5547
|
+
|
|
5548
|
+
// src/restructure.ts
|
|
5549
|
+
import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
|
|
5550
|
+
import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
|
|
5551
|
+
import { dirname as dirname5, isAbsolute as isAbsolute4, join as join9, posix, relative as relative4, resolve as resolve6 } from "path";
|
|
5552
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
5553
|
+
function digestBytes(value) {
|
|
5554
|
+
return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
|
|
5555
|
+
}
|
|
5556
|
+
function canonicalJson(value) {
|
|
5557
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
5558
|
+
if (value && typeof value === "object") {
|
|
5559
|
+
return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
|
|
5560
|
+
}
|
|
5561
|
+
return JSON.stringify(value);
|
|
5562
|
+
}
|
|
5563
|
+
function digestRestructureValue(value) {
|
|
5564
|
+
return digestBytes(canonicalJson(value));
|
|
5565
|
+
}
|
|
5566
|
+
function normalizeRelativePath2(value) {
|
|
5567
|
+
if (!value || value.includes("\0") || isAbsolute4(value)) return void 0;
|
|
5568
|
+
const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
5569
|
+
if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
|
|
5570
|
+
return normalized;
|
|
5571
|
+
}
|
|
5572
|
+
function isPathAllowed(path, allowed) {
|
|
5573
|
+
return allowed.some((entry) => {
|
|
5574
|
+
const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
|
|
5575
|
+
return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
|
|
5576
|
+
});
|
|
5577
|
+
}
|
|
5578
|
+
async function readContainedFileWithMode(root, path) {
|
|
5579
|
+
const normalized = normalizeRelativePath2(path);
|
|
5580
|
+
if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
|
|
5581
|
+
const absoluteRoot = resolve6(root);
|
|
5582
|
+
const absolutePath = resolve6(absoluteRoot, normalized);
|
|
5583
|
+
if (relative4(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
|
|
5584
|
+
try {
|
|
5585
|
+
const info = await lstat3(absolutePath);
|
|
5586
|
+
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
|
|
5587
|
+
return { buffer: await readFile3(absolutePath), mode: info.mode & MAX_POSIX_MODE };
|
|
5588
|
+
} catch (error) {
|
|
5589
|
+
if (error.code === "ENOENT") return void 0;
|
|
5590
|
+
throw error;
|
|
5591
|
+
}
|
|
5592
|
+
}
|
|
5593
|
+
async function readContainedFile(root, path) {
|
|
5594
|
+
return (await readContainedFileWithMode(root, path))?.buffer;
|
|
5595
|
+
}
|
|
5596
|
+
async function snapshotFile(root, path) {
|
|
5597
|
+
const normalized = normalizeRelativePath2(path);
|
|
5598
|
+
if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
|
|
5599
|
+
const contained = await readContainedFileWithMode(root, normalized);
|
|
5600
|
+
return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
|
|
5601
|
+
path: normalized,
|
|
5602
|
+
exists: true,
|
|
5603
|
+
sha256: digestBytes(contained.buffer),
|
|
5604
|
+
size: contained.buffer.byteLength,
|
|
5605
|
+
mode: contained.mode
|
|
5606
|
+
};
|
|
5607
|
+
}
|
|
5608
|
+
function sameSnapshot(left, right) {
|
|
5609
|
+
return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
|
|
5610
|
+
}
|
|
5611
|
+
async function configSnapshot(root) {
|
|
5612
|
+
return snapshotFile(root, "artifact-graph.config.yaml");
|
|
5613
|
+
}
|
|
5614
|
+
async function loadRestructureContract(name) {
|
|
5615
|
+
return loadContract(join9(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
|
|
5616
|
+
}
|
|
5617
|
+
async function validateDomainContract(name, value) {
|
|
5618
|
+
const contract = await loadRestructureContract(name);
|
|
5619
|
+
return validateContractAgainstSchema(value, contract).errors;
|
|
5620
|
+
}
|
|
5621
|
+
function occurrenceKey(edge2) {
|
|
5622
|
+
return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
|
|
5623
|
+
}
|
|
5624
|
+
function relationOccurrences(graph) {
|
|
5625
|
+
const counts = /* @__PURE__ */ new Map();
|
|
5626
|
+
return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
|
|
5627
|
+
const key = occurrenceKey(edge2);
|
|
5628
|
+
const occurrence = (counts.get(key) ?? 0) + 1;
|
|
5629
|
+
counts.set(key, occurrence);
|
|
5630
|
+
return {
|
|
5631
|
+
from: edge2.from,
|
|
5632
|
+
to: edge2.to,
|
|
5633
|
+
kind: edge2.kind,
|
|
5634
|
+
source: edge2.source,
|
|
5635
|
+
source_path: edge2.sourcePath,
|
|
5636
|
+
source_line: edge2.sourceLine,
|
|
5637
|
+
occurrence
|
|
5638
|
+
};
|
|
5639
|
+
});
|
|
5640
|
+
}
|
|
5641
|
+
function relationKey(value) {
|
|
5642
|
+
return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
|
|
5643
|
+
}
|
|
5644
|
+
function acceptanceCriteria(node) {
|
|
5645
|
+
const raw = node.attrs?.acceptanceCriteria;
|
|
5646
|
+
if (!Array.isArray(raw)) return [];
|
|
5647
|
+
return raw.flatMap((item, index) => {
|
|
5648
|
+
if (typeof item === "string") {
|
|
5649
|
+
const match = /\b(AC\d+)\b/.exec(item);
|
|
5650
|
+
return [match?.[1] ?? `AC${index + 1}`];
|
|
5651
|
+
}
|
|
5652
|
+
if (item && typeof item === "object") {
|
|
5653
|
+
const record = item;
|
|
5654
|
+
const value = String(record.id ?? record.code ?? "").trim();
|
|
5655
|
+
return value ? [value] : [`AC${index + 1}`];
|
|
5656
|
+
}
|
|
5657
|
+
return [`AC${index + 1}`];
|
|
5658
|
+
});
|
|
5659
|
+
}
|
|
5660
|
+
function spanFor(buffer, path, range) {
|
|
5661
|
+
return {
|
|
5662
|
+
path,
|
|
5663
|
+
start_byte: range.startByte,
|
|
5664
|
+
end_byte: range.endByte,
|
|
5665
|
+
sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
|
|
5666
|
+
};
|
|
5667
|
+
}
|
|
5668
|
+
function mappingTemplate(request, requestDigest, config, sources, unresolved) {
|
|
5669
|
+
return {
|
|
5670
|
+
schema_version: "1.0",
|
|
5671
|
+
request,
|
|
5672
|
+
request_digest: requestDigest,
|
|
5673
|
+
config_snapshot: config,
|
|
5674
|
+
sources: sources.map((source) => ({
|
|
5675
|
+
type: source.type,
|
|
5676
|
+
id: source.id,
|
|
5677
|
+
path: source.path,
|
|
5678
|
+
snapshot: source.snapshot,
|
|
5679
|
+
disposition: "preserved"
|
|
5680
|
+
})),
|
|
5681
|
+
targets: [],
|
|
5682
|
+
content_moves: [],
|
|
5683
|
+
identity_map: [],
|
|
5684
|
+
criterion_map: [],
|
|
5685
|
+
relation_map: [],
|
|
5686
|
+
prose_edits: [],
|
|
5687
|
+
file_headers: [],
|
|
5688
|
+
unresolved
|
|
5689
|
+
};
|
|
5690
|
+
}
|
|
5691
|
+
async function inspectRestructure(root, input) {
|
|
5692
|
+
const schemaErrors = await validateDomainContract("request", input);
|
|
5693
|
+
if (schemaErrors.length > 0) {
|
|
5694
|
+
return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
|
|
5695
|
+
}
|
|
5696
|
+
const request = input;
|
|
5697
|
+
const requestDigest = digestRestructureValue(request);
|
|
5698
|
+
const schema = await loadConfig(root);
|
|
5699
|
+
const graph = await scanArtifacts(root, schema);
|
|
5700
|
+
const allOccurrences = relationOccurrences(graph);
|
|
5701
|
+
const blockers = [];
|
|
5702
|
+
const unresolved = [];
|
|
5703
|
+
const inspected = [];
|
|
5704
|
+
for (const requested of request.sources) {
|
|
5705
|
+
const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
|
|
5706
|
+
if (candidates.length !== 1) {
|
|
5707
|
+
blockers.push({
|
|
5708
|
+
code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
|
|
5709
|
+
message: candidates.length === 0 ? `Source ${requested.type}:${requested.id} was not found` : `Source ${requested.type}:${requested.id} resolves to ${candidates.length} records; specify a path`,
|
|
5710
|
+
...requested.path ? { path: requested.path } : {}
|
|
5711
|
+
});
|
|
5712
|
+
continue;
|
|
5713
|
+
}
|
|
5714
|
+
const node = candidates[0];
|
|
5715
|
+
const raw = await readContainedFile(root, node.path);
|
|
5716
|
+
if (!raw) {
|
|
5717
|
+
blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
|
|
5718
|
+
continue;
|
|
5719
|
+
}
|
|
5720
|
+
const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
|
|
5721
|
+
const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
|
|
5722
|
+
blockers.push(...boundary.blockers);
|
|
5723
|
+
const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
|
|
5724
|
+
const uid = `${node.type}:${node.code}`;
|
|
5725
|
+
inspected.push({
|
|
5726
|
+
type: node.type,
|
|
5727
|
+
id: node.code,
|
|
5728
|
+
uid,
|
|
5729
|
+
path: node.path,
|
|
5730
|
+
title: node.title,
|
|
5731
|
+
snapshot: await snapshotFile(root, node.path),
|
|
5732
|
+
...recordSpan ? {
|
|
5733
|
+
record_span: recordSpan,
|
|
5734
|
+
content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
|
|
5735
|
+
} : {},
|
|
5736
|
+
surrounding_spans: recordSpan ? [
|
|
5737
|
+
...recordSpan.start_byte > 0 ? [{
|
|
5738
|
+
...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
|
|
5739
|
+
content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
|
|
5740
|
+
}] : [],
|
|
5741
|
+
...recordSpan.end_byte < raw.byteLength ? [{
|
|
5742
|
+
...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
|
|
5743
|
+
content: raw.subarray(recordSpan.end_byte).toString("utf8")
|
|
5744
|
+
}] : []
|
|
5745
|
+
] : [],
|
|
5746
|
+
acceptance_criteria: acceptanceCriteria(node),
|
|
5747
|
+
incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
|
|
5748
|
+
outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
|
|
5749
|
+
});
|
|
5750
|
+
}
|
|
5751
|
+
if (request.numbering_policy?.mode === "configured-next-available") {
|
|
5752
|
+
unresolved.push({
|
|
5753
|
+
code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
|
|
5754
|
+
message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
|
|
5755
|
+
});
|
|
5756
|
+
}
|
|
5757
|
+
mergeFindings(unresolved, await scanUnsupportedReferences(
|
|
5758
|
+
root,
|
|
5759
|
+
[...new Set(inspected.map((item) => item.path))],
|
|
5760
|
+
[]
|
|
5761
|
+
));
|
|
5762
|
+
const config = await configSnapshot(root);
|
|
5763
|
+
const affectedPaths = new Set(inspected.map((item) => item.path));
|
|
5764
|
+
for (const source of inspected) {
|
|
5765
|
+
for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
|
|
5766
|
+
}
|
|
5767
|
+
const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
|
|
5768
|
+
const inspection = {
|
|
5769
|
+
schema_version: "1.0",
|
|
5770
|
+
request,
|
|
5771
|
+
request_digest: requestDigest,
|
|
5772
|
+
config_snapshot: config,
|
|
5773
|
+
sources: inspected,
|
|
5774
|
+
affected_files: affectedFiles,
|
|
5775
|
+
relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
|
|
5776
|
+
blockers,
|
|
5777
|
+
unresolved,
|
|
5778
|
+
mapping_template: {}
|
|
5779
|
+
};
|
|
5780
|
+
inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
|
|
5781
|
+
return { ok: true, data: inspection };
|
|
5782
|
+
}
|
|
5783
|
+
function finding(code, message, path, line) {
|
|
5784
|
+
return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
|
|
5785
|
+
}
|
|
5786
|
+
async function verifySnapshot(root, expected, blockers) {
|
|
5787
|
+
const normalized = normalizeRelativePath2(expected.path);
|
|
5788
|
+
if (!normalized) {
|
|
5789
|
+
blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
|
|
5790
|
+
return void 0;
|
|
5791
|
+
}
|
|
5792
|
+
const actual = await snapshotFile(root, normalized);
|
|
5793
|
+
if (!sameSnapshot(actual, { ...expected, path: normalized })) {
|
|
5794
|
+
blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
|
|
5795
|
+
}
|
|
5796
|
+
return actual;
|
|
5797
|
+
}
|
|
5798
|
+
function validateSpan(buffer, span, blockers) {
|
|
5799
|
+
if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
|
|
5800
|
+
blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
|
|
5801
|
+
return void 0;
|
|
5802
|
+
}
|
|
5803
|
+
const fragment = buffer.subarray(span.start_byte, span.end_byte);
|
|
5804
|
+
if (digestBytes(fragment) !== span.sha256) {
|
|
5805
|
+
blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
|
|
5806
|
+
return void 0;
|
|
5807
|
+
}
|
|
5808
|
+
return fragment;
|
|
5809
|
+
}
|
|
5810
|
+
function rangesCover(range, moves) {
|
|
5811
|
+
const intervals = moves.map((move) => ({ start: move.source.start_byte, end: move.source.end_byte })).filter((item) => item.end > range.startByte && item.start < range.endByte).sort((left, right) => left.start - right.start || left.end - right.end);
|
|
5812
|
+
let cursor = range.startByte;
|
|
5813
|
+
for (const interval of intervals) {
|
|
5814
|
+
if (interval.start > cursor) return false;
|
|
5815
|
+
cursor = Math.max(cursor, interval.end);
|
|
5816
|
+
}
|
|
5817
|
+
return cursor >= range.endByte;
|
|
5818
|
+
}
|
|
5819
|
+
function edgeDisplay(edge2) {
|
|
5820
|
+
return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
|
|
5821
|
+
}
|
|
5822
|
+
function graphDiff(before, after) {
|
|
5823
|
+
const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
|
|
5824
|
+
const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
|
|
5825
|
+
const beforeEdges = new Set(before.edges.map(edgeDisplay));
|
|
5826
|
+
const afterEdges = new Set(after.edges.map(edgeDisplay));
|
|
5827
|
+
return {
|
|
5828
|
+
added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
|
|
5829
|
+
removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
|
|
5830
|
+
added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
|
|
5831
|
+
removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
|
|
5832
|
+
};
|
|
5833
|
+
}
|
|
5834
|
+
function issueIdentity(issue2) {
|
|
5835
|
+
const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
|
|
5836
|
+
return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
|
|
5837
|
+
}
|
|
5838
|
+
function readableDiff(path, oldContent, newContent) {
|
|
5839
|
+
const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
|
|
5840
|
+
const newLines = newContent?.split(/(?<=\n)/) ?? [];
|
|
5841
|
+
if (oldContent === newContent) return "";
|
|
5842
|
+
return [
|
|
5843
|
+
`--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
|
|
5844
|
+
`+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
|
|
5845
|
+
...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
|
|
5846
|
+
...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
|
|
5847
|
+
].join("\n");
|
|
5848
|
+
}
|
|
5849
|
+
function findRelativeLinks(fragment) {
|
|
5850
|
+
const found = /* @__PURE__ */ new Set();
|
|
5851
|
+
const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
|
|
5852
|
+
let match;
|
|
5853
|
+
while ((match = pattern.exec(fragment)) !== null) {
|
|
5854
|
+
const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
|
|
5855
|
+
if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
|
|
5856
|
+
}
|
|
5857
|
+
return [...found].sort();
|
|
5858
|
+
}
|
|
5859
|
+
function footnoteReferenceLabels(text) {
|
|
5860
|
+
const labels = /* @__PURE__ */ new Set();
|
|
5861
|
+
const pattern = /\[\^([^\]\s]+)\](?!:)/g;
|
|
5862
|
+
let match;
|
|
5863
|
+
while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
|
|
5864
|
+
return [...labels].sort();
|
|
5865
|
+
}
|
|
5866
|
+
function footnoteDefinition(label) {
|
|
5867
|
+
return `[^${label}]:`;
|
|
5868
|
+
}
|
|
5869
|
+
function splitMarkdownTarget(target) {
|
|
5870
|
+
const cleaned = target.trim().replace(/^<|>$/g, "");
|
|
5871
|
+
const hash = cleaned.indexOf("#");
|
|
5872
|
+
return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
|
|
5873
|
+
}
|
|
5874
|
+
async function pathExists2(absolutePath) {
|
|
5875
|
+
try {
|
|
5876
|
+
await lstat3(absolutePath);
|
|
5877
|
+
return true;
|
|
5878
|
+
} catch {
|
|
5879
|
+
return false;
|
|
5880
|
+
}
|
|
5881
|
+
}
|
|
5882
|
+
async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
|
|
5883
|
+
const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
|
|
5884
|
+
const migrationNames = new Set(migrationPaths.map((path) => posix.basename(path)));
|
|
5885
|
+
const directories = new Set(migrationPaths.map((path) => posix.dirname(path)));
|
|
5886
|
+
const findings = [];
|
|
5887
|
+
async function visit(directory) {
|
|
5888
|
+
for (const entry of await readdir3(directory, { withFileTypes: true })) {
|
|
5889
|
+
if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
|
|
5890
|
+
const absolute = join9(directory, entry.name);
|
|
5891
|
+
if (entry.isDirectory()) {
|
|
5892
|
+
await visit(absolute);
|
|
5893
|
+
continue;
|
|
5894
|
+
}
|
|
5895
|
+
if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
|
|
5896
|
+
const path = relative4(root, absolute).replace(/\\/g, "/");
|
|
5897
|
+
const raw = await readFile3(absolute, "utf8");
|
|
5898
|
+
const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
|
|
5899
|
+
const lines = raw.split(/\r?\n/);
|
|
5900
|
+
for (const [index, line] of lines.entries()) {
|
|
5901
|
+
const lineNumber = index + 1;
|
|
5902
|
+
if (MARKDOWN_FILE_SUFFIX.test(path)) {
|
|
5903
|
+
const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
|
|
5904
|
+
let match;
|
|
5905
|
+
while ((match = pattern.exec(line)) !== null) {
|
|
5906
|
+
const literal = match[0];
|
|
5907
|
+
const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
|
|
5908
|
+
if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
|
|
5909
|
+
if (!migrationNames.has(posix.basename(linkPath))) continue;
|
|
5910
|
+
const resolved = normalizeRelativePath2(posix.join(posix.dirname(path), linkPath));
|
|
5911
|
+
if (!resolved || targetPaths.includes(resolved)) continue;
|
|
5912
|
+
if (anchor) {
|
|
5913
|
+
findings.push(finding(
|
|
5914
|
+
"ANCHOR_REFERENCE_UNRESOLVED",
|
|
5915
|
+
`The anchored reference "${literal}" points at a migration path; the renderer anchor rules are unknown and the anchor ${JSON.stringify(anchor)} may leave the file with its record`,
|
|
5916
|
+
path,
|
|
5917
|
+
lineNumber
|
|
5918
|
+
));
|
|
5919
|
+
} else if (!await pathExists2(resolve6(root, resolved))) {
|
|
5920
|
+
findings.push(finding(
|
|
5921
|
+
"SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
|
|
5922
|
+
`The relative reference "${literal}" does not resolve inside the project although its file name matches a migration path; its intended destination must be decided explicitly`,
|
|
5923
|
+
path,
|
|
5924
|
+
lineNumber
|
|
5925
|
+
));
|
|
5926
|
+
}
|
|
5927
|
+
}
|
|
5928
|
+
}
|
|
5929
|
+
if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
|
|
5930
|
+
const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
|
|
5931
|
+
const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
|
|
5932
|
+
if (directoryLiteral) {
|
|
5933
|
+
findings.push(finding(
|
|
5934
|
+
"RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
|
|
5935
|
+
`A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
|
|
5936
|
+
path,
|
|
5937
|
+
lineNumber
|
|
5938
|
+
));
|
|
5939
|
+
}
|
|
5940
|
+
}
|
|
5941
|
+
}
|
|
5942
|
+
}
|
|
5943
|
+
}
|
|
5944
|
+
await visit(resolve6(root));
|
|
5945
|
+
const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
|
|
5946
|
+
return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
|
|
5947
|
+
}
|
|
5948
|
+
function mergeFindings(target, additions) {
|
|
5949
|
+
const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
|
|
5950
|
+
for (const item of additions) {
|
|
5951
|
+
const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
|
|
5952
|
+
if (seen.has(key)) continue;
|
|
5953
|
+
seen.add(key);
|
|
5954
|
+
target.push(item);
|
|
5955
|
+
}
|
|
5956
|
+
}
|
|
5957
|
+
async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
|
|
5958
|
+
const results = [];
|
|
5959
|
+
async function visit(directory) {
|
|
5960
|
+
for (const entry of await readdir3(directory, { withFileTypes: true })) {
|
|
5961
|
+
if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
|
|
5962
|
+
const absolute = join9(directory, entry.name);
|
|
5963
|
+
if (entry.isDirectory()) {
|
|
5964
|
+
await visit(absolute);
|
|
5965
|
+
} else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
|
|
5966
|
+
const path = relative4(root, absolute).replace(/\\/g, "/");
|
|
5967
|
+
if (excludedPaths.has(path)) continue;
|
|
5968
|
+
const raw = await readFile3(absolute, "utf8");
|
|
5969
|
+
raw.split(/\r?\n/).forEach((line, index) => {
|
|
5970
|
+
for (const reference of references) {
|
|
5971
|
+
if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
|
|
5972
|
+
}
|
|
5973
|
+
});
|
|
5974
|
+
}
|
|
5975
|
+
}
|
|
5976
|
+
}
|
|
5977
|
+
await visit(resolve6(root));
|
|
5978
|
+
return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
|
|
5979
|
+
}
|
|
5980
|
+
function expectedRelationTargets(mapping) {
|
|
5981
|
+
return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
|
|
5982
|
+
}
|
|
5983
|
+
function relationTriples(graph) {
|
|
5984
|
+
return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
|
|
5985
|
+
}
|
|
5986
|
+
function formatMode(value) {
|
|
5987
|
+
return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
|
|
5988
|
+
}
|
|
5989
|
+
function isPosixFileMode(value) {
|
|
5990
|
+
return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
|
|
5991
|
+
}
|
|
5992
|
+
function modeIsUsableAtApply(mode, umask) {
|
|
5993
|
+
return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
|
|
5994
|
+
}
|
|
5995
|
+
function createModeForUmask(umask) {
|
|
5996
|
+
return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
|
|
5997
|
+
}
|
|
5998
|
+
function planningUmask() {
|
|
5999
|
+
return process.umask() & MAX_POSIX_MODE;
|
|
6000
|
+
}
|
|
6001
|
+
function restructureBoundaryFindings(operations, limits) {
|
|
6002
|
+
const findings = [];
|
|
6003
|
+
if (operations.length === 0) {
|
|
6004
|
+
findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
|
|
6005
|
+
return findings;
|
|
6006
|
+
}
|
|
6007
|
+
if (operations.length > limits.max_operations) {
|
|
6008
|
+
findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
|
|
6009
|
+
}
|
|
6010
|
+
const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
|
|
6011
|
+
if (totalBytes > limits.max_total_bytes) {
|
|
6012
|
+
findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
|
|
6013
|
+
}
|
|
6014
|
+
const expectedCreateMode = createModeForUmask(limits.umask);
|
|
6015
|
+
const applyModeContract = limits.mode_contract === "apply";
|
|
6016
|
+
for (const operation of operations) {
|
|
6017
|
+
const parent = dirname5(operation.path) || ".";
|
|
6018
|
+
if (!operation.parent_exists) {
|
|
6019
|
+
findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
|
|
6020
|
+
} else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
|
|
6021
|
+
findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
|
|
6022
|
+
}
|
|
6023
|
+
if (!isPosixFileMode(operation.mode)) {
|
|
6024
|
+
findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
|
|
6025
|
+
}
|
|
6026
|
+
if (!isPosixFileMode(operation.original_mode)) {
|
|
6027
|
+
findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
|
|
6028
|
+
}
|
|
6029
|
+
if (operation.original_exists && operation.original_mode === null) {
|
|
6030
|
+
findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
|
|
6031
|
+
}
|
|
6032
|
+
if (!operation.original_exists && operation.original_mode !== null) {
|
|
6033
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
|
|
6034
|
+
}
|
|
6035
|
+
if (applyModeContract) {
|
|
6036
|
+
for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
|
|
6037
|
+
if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
|
|
6038
|
+
findings.push(finding(
|
|
6039
|
+
"MODE_NOT_USABLE",
|
|
6040
|
+
`Frozen ${label} ${formatMode(value)} cannot be reproduced by the applying process, which requires owner-read, no setuid/setgid/sticky bit, and no bit masked by umask ${formatMode(limits.umask)}: ${operation.path}`,
|
|
6041
|
+
operation.path
|
|
6042
|
+
));
|
|
6043
|
+
}
|
|
6044
|
+
}
|
|
6045
|
+
if (operation.action === "create") {
|
|
6046
|
+
if (operation.original_exists) {
|
|
6047
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
|
|
6048
|
+
}
|
|
6049
|
+
if (!applyModeContract && operation.mode !== expectedCreateMode) {
|
|
6050
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
|
|
6051
|
+
}
|
|
6052
|
+
} else if (operation.action === "replace") {
|
|
6053
|
+
if (!operation.original_exists) {
|
|
6054
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
|
|
6055
|
+
} else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
|
|
6056
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
|
|
6057
|
+
}
|
|
6058
|
+
} else if (operation.mode !== null) {
|
|
6059
|
+
findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
|
|
6060
|
+
}
|
|
6061
|
+
}
|
|
6062
|
+
return findings;
|
|
6063
|
+
}
|
|
6064
|
+
async function probeDirectory(absolutePath) {
|
|
6065
|
+
try {
|
|
6066
|
+
const info = await stat(absolutePath);
|
|
6067
|
+
return { exists: info.isDirectory(), device: info.dev };
|
|
6068
|
+
} catch (error) {
|
|
6069
|
+
const code = error.code;
|
|
6070
|
+
if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
|
|
6071
|
+
throw error;
|
|
6072
|
+
}
|
|
6073
|
+
}
|
|
6074
|
+
async function planRestructure(root, input) {
|
|
6075
|
+
const schemaErrors = await validateDomainContract("mapping", input);
|
|
6076
|
+
if (schemaErrors.length > 0) {
|
|
6077
|
+
return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
|
|
6078
|
+
}
|
|
6079
|
+
const mapping = input;
|
|
6080
|
+
const blockers = [];
|
|
6081
|
+
const unresolved = [...mapping.unresolved];
|
|
6082
|
+
const requestErrors = await validateDomainContract("request", mapping.request);
|
|
6083
|
+
if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
|
|
6084
|
+
if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
|
|
6085
|
+
const currentConfig = await configSnapshot(root);
|
|
6086
|
+
if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
|
|
6087
|
+
const schema = await loadConfig(root);
|
|
6088
|
+
const beforeGraph = await scanArtifacts(root, schema);
|
|
6089
|
+
const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
|
|
6090
|
+
const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
|
|
6091
|
+
const seenSourceUids = /* @__PURE__ */ new Set();
|
|
6092
|
+
for (const source of mapping.sources) {
|
|
6093
|
+
const uid = `${source.type}:${source.id}`;
|
|
6094
|
+
if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
|
|
6095
|
+
seenSourceUids.add(uid);
|
|
6096
|
+
if (source.snapshot.path !== source.path) blockers.push(finding("SOURCE_SNAPSHOT_PATH_MISMATCH", `Source snapshot path does not match source.path for ${uid}`, source.path));
|
|
6097
|
+
}
|
|
6098
|
+
for (const requested of mapping.request.sources) {
|
|
6099
|
+
const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
|
|
6100
|
+
const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
|
|
6101
|
+
if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
|
|
6102
|
+
}
|
|
6103
|
+
for (const source of mapping.sources) {
|
|
6104
|
+
if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
|
|
6105
|
+
blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
|
|
6106
|
+
}
|
|
6107
|
+
}
|
|
6108
|
+
const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
|
|
6109
|
+
const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
|
|
6110
|
+
for (const occurrence of requiredOccurrences) {
|
|
6111
|
+
if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
|
|
6112
|
+
}
|
|
6113
|
+
for (const entry of mapping.relation_map) {
|
|
6114
|
+
if (!beforeOccurrences.has(relationKey(entry.occurrence))) blockers.push(finding("RELATION_OCCURRENCE_CHANGED", `Relation occurrence no longer exists: ${relationKey(entry.occurrence)}`, entry.occurrence.source_path, entry.occurrence.source_line));
|
|
6115
|
+
}
|
|
6116
|
+
const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
|
|
6117
|
+
const targetKeys = /* @__PURE__ */ new Set();
|
|
6118
|
+
const targetUids = /* @__PURE__ */ new Set();
|
|
6119
|
+
for (const target of mapping.targets) {
|
|
6120
|
+
const path = normalizeRelativePath2(target.path);
|
|
6121
|
+
if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
|
|
6122
|
+
if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
|
|
6123
|
+
targetKeys.add(target.key);
|
|
6124
|
+
if (target.snapshot.path !== target.path) blockers.push(finding("TARGET_SNAPSHOT_PATH_MISMATCH", `Target snapshot path does not match target.path for ${target.key}`, target.path));
|
|
6125
|
+
const uid = `${target.type}:${target.id}`;
|
|
6126
|
+
if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
|
|
6127
|
+
targetUids.add(uid);
|
|
6128
|
+
if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
|
|
6129
|
+
blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
|
|
6130
|
+
}
|
|
6131
|
+
if (!schema.types[target.type] || !new RegExp(schema.idPatterns[target.type] ?? ".*").test(target.id)) blockers.push(finding("INVALID_TARGET_ID", `Target identity does not match configured type/id: ${uid}`, target.path));
|
|
6132
|
+
if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
|
|
6133
|
+
}
|
|
6134
|
+
for (const identity of mapping.identity_map) {
|
|
6135
|
+
for (const key of identity.target_keys) if (!targetKeys.has(key)) blockers.push(finding("TARGET_KEY_NOT_FOUND", `identity_map refers to unknown target key: ${key}`));
|
|
6136
|
+
}
|
|
6137
|
+
for (const source of mapping.sources) {
|
|
6138
|
+
const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
|
|
6139
|
+
if (identities.length !== 1) blockers.push(finding("IDENTITY_MAP_INCOMPLETE", `Expected exactly one identity_map entry for ${source.type}:${source.id}, found ${identities.length}`, source.path));
|
|
6140
|
+
if (identities[0] && identities[0].source_disposition !== source.disposition) blockers.push(finding("IDENTITY_DISPOSITION_MISMATCH", `identity_map disposition differs for ${source.type}:${source.id}`, source.path));
|
|
6141
|
+
}
|
|
6142
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
6143
|
+
const buffers = /* @__PURE__ */ new Map();
|
|
6144
|
+
for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
|
|
6145
|
+
const normalized = normalizeRelativePath2(expected.path);
|
|
6146
|
+
if (!normalized) {
|
|
6147
|
+
blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
|
|
6148
|
+
continue;
|
|
6149
|
+
}
|
|
6150
|
+
if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
|
|
6151
|
+
blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
|
|
6152
|
+
continue;
|
|
6153
|
+
}
|
|
6154
|
+
const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
|
|
6155
|
+
if (actual) snapshots.set(normalized, actual);
|
|
6156
|
+
const raw = await readContainedFile(root, normalized);
|
|
6157
|
+
if (raw) buffers.set(normalized, raw);
|
|
6158
|
+
}
|
|
6159
|
+
snapshots.set(currentConfig.path, currentConfig);
|
|
6160
|
+
const declaredSnapshots = [
|
|
6161
|
+
mapping.config_snapshot,
|
|
6162
|
+
...mapping.sources.map((source) => source.snapshot),
|
|
6163
|
+
...mapping.targets.map((target) => target.snapshot)
|
|
6164
|
+
];
|
|
6165
|
+
const checkedDeclaredModes = /* @__PURE__ */ new Set();
|
|
6166
|
+
for (const declared of declaredSnapshots) {
|
|
6167
|
+
const declaredMode = declared.mode ?? null;
|
|
6168
|
+
const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
|
|
6169
|
+
const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
|
|
6170
|
+
if (checkedDeclaredModes.has(key)) continue;
|
|
6171
|
+
checkedDeclaredModes.add(key);
|
|
6172
|
+
if (!isPosixFileMode(declaredMode)) {
|
|
6173
|
+
blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
|
|
6174
|
+
} else if (declared.exists && declaredMode === null) {
|
|
6175
|
+
blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
|
|
6176
|
+
} else if (!declared.exists && declaredMode !== null) {
|
|
6177
|
+
blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
|
|
6178
|
+
}
|
|
6179
|
+
}
|
|
6180
|
+
const moveIds = /* @__PURE__ */ new Set();
|
|
6181
|
+
const rangesByPath = /* @__PURE__ */ new Map();
|
|
6182
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
6183
|
+
for (const move of mapping.content_moves) {
|
|
6184
|
+
if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
|
|
6185
|
+
moveIds.add(move.id);
|
|
6186
|
+
const sourcePath = normalizeRelativePath2(move.source.path);
|
|
6187
|
+
const targetPath = normalizeRelativePath2(move.target.path);
|
|
6188
|
+
if (!sourcePath || !buffers.has(sourcePath)) {
|
|
6189
|
+
blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
|
|
6190
|
+
continue;
|
|
6191
|
+
}
|
|
6192
|
+
if (!targetPath || !isPathAllowed(targetPath, allowed)) {
|
|
6193
|
+
blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
|
|
6194
|
+
continue;
|
|
6195
|
+
}
|
|
6196
|
+
const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
|
|
6197
|
+
if (!fragment) continue;
|
|
6198
|
+
fragments.set(move.id, fragment);
|
|
6199
|
+
const pathMoves = rangesByPath.get(sourcePath) ?? [];
|
|
6200
|
+
for (const existing of pathMoves) {
|
|
6201
|
+
if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
|
|
6202
|
+
const exactExplicitCopy = existing.source.start_byte === move.source.start_byte && existing.source.end_byte === move.source.end_byte && [existing, move].filter((item) => item.target.mode === "move").length <= 1;
|
|
6203
|
+
if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
|
|
6204
|
+
}
|
|
6205
|
+
}
|
|
6206
|
+
pathMoves.push(move);
|
|
6207
|
+
rangesByPath.set(sourcePath, pathMoves);
|
|
6208
|
+
if (dirname5(sourcePath) !== dirname5(targetPath)) {
|
|
6209
|
+
for (const link of findRelativeLinks(fragment.toString("utf8"))) {
|
|
6210
|
+
const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
|
|
6211
|
+
if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
|
|
6212
|
+
}
|
|
6213
|
+
}
|
|
6214
|
+
}
|
|
6215
|
+
for (const source of mapping.sources) {
|
|
6216
|
+
const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
|
|
6217
|
+
const raw = buffers.get(source.path);
|
|
6218
|
+
if (!node || !raw) continue;
|
|
6219
|
+
const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
|
|
6220
|
+
blockers.push(...boundary.blockers);
|
|
6221
|
+
if (boundary.range && !rangesCover(boundary.range, rangesByPath.get(source.path) ?? [])) blockers.push(finding("SOURCE_CONTENT_UNMAPPED", `The complete source record ${node.uid} does not have an explicit content destination`, source.path, node.line));
|
|
6222
|
+
if (source.type === "feature" && source.disposition === "retired") {
|
|
6223
|
+
const criteria = acceptanceCriteria(node);
|
|
6224
|
+
const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
|
|
6225
|
+
for (const criterion of criteria) if (!mapped.has(criterion)) blockers.push(finding("CRITERION_UNMAPPED", `${source.id}:${criterion} has no target criterion`, source.path, node.line));
|
|
6226
|
+
}
|
|
6227
|
+
}
|
|
6228
|
+
const candidateBuffers = /* @__PURE__ */ new Map();
|
|
6229
|
+
const touched = /* @__PURE__ */ new Set();
|
|
6230
|
+
for (const [sourcePath, moves] of rangesByPath) {
|
|
6231
|
+
const original = buffers.get(sourcePath);
|
|
6232
|
+
const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
|
|
6233
|
+
const chunks = [];
|
|
6234
|
+
let cursor = 0;
|
|
6235
|
+
for (const move of removals) {
|
|
6236
|
+
chunks.push(original.subarray(cursor, move.source.start_byte));
|
|
6237
|
+
cursor = move.source.end_byte;
|
|
6238
|
+
}
|
|
6239
|
+
chunks.push(original.subarray(cursor));
|
|
6240
|
+
candidateBuffers.set(sourcePath, Buffer.concat(chunks));
|
|
6241
|
+
touched.add(sourcePath);
|
|
6242
|
+
}
|
|
6243
|
+
const movesByTarget = /* @__PURE__ */ new Map();
|
|
6244
|
+
for (const move of mapping.content_moves) {
|
|
6245
|
+
const targetPath = normalizeRelativePath2(move.target.path);
|
|
6246
|
+
if (!targetPath || !fragments.has(move.id)) continue;
|
|
6247
|
+
const list = movesByTarget.get(targetPath) ?? [];
|
|
6248
|
+
list.push(move);
|
|
6249
|
+
movesByTarget.set(targetPath, list);
|
|
6250
|
+
}
|
|
6251
|
+
for (const [targetPath, moves] of movesByTarget) {
|
|
6252
|
+
const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
|
|
6253
|
+
const appended = [base];
|
|
6254
|
+
for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
|
|
6255
|
+
const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
|
|
6256
|
+
appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
|
|
6257
|
+
}
|
|
6258
|
+
candidateBuffers.set(targetPath, Buffer.concat(appended));
|
|
6259
|
+
touched.add(targetPath);
|
|
6260
|
+
if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
|
|
6261
|
+
}
|
|
6262
|
+
for (const header of mapping.file_headers) {
|
|
6263
|
+
const path = normalizeRelativePath2(header.path);
|
|
6264
|
+
if (!path || !isPathAllowed(path, allowed)) {
|
|
6265
|
+
blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
|
|
6266
|
+
continue;
|
|
6267
|
+
}
|
|
6268
|
+
if (header.affected_records.length === 0 && header.content === "") {
|
|
6269
|
+
const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
|
|
6270
|
+
if (unselected.length > 0) {
|
|
6271
|
+
blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
|
|
6272
|
+
} else {
|
|
6273
|
+
candidateBuffers.set(path, Buffer.alloc(0));
|
|
6274
|
+
touched.add(path);
|
|
6275
|
+
}
|
|
6276
|
+
if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
|
|
6277
|
+
continue;
|
|
6278
|
+
}
|
|
6279
|
+
const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
|
|
6280
|
+
candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
|
|
6281
|
+
touched.add(path);
|
|
6282
|
+
if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
|
|
6283
|
+
}
|
|
6284
|
+
for (const edit of mapping.prose_edits) {
|
|
6285
|
+
const path = normalizeRelativePath2(edit.target_path);
|
|
6286
|
+
const sourcePath = normalizeRelativePath2(edit.source.path);
|
|
6287
|
+
if (!path || !sourcePath || !buffers.has(sourcePath)) {
|
|
6288
|
+
blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
|
|
6289
|
+
continue;
|
|
6290
|
+
}
|
|
6291
|
+
if (!isPathAllowed(path, allowed)) {
|
|
6292
|
+
blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
|
|
6293
|
+
continue;
|
|
6294
|
+
}
|
|
6295
|
+
if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
|
|
6296
|
+
const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
|
|
6297
|
+
const occurrences = current.split(edit.old_text).length - 1;
|
|
6298
|
+
if (!edit.old_text || occurrences !== 1) {
|
|
6299
|
+
blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
|
|
6300
|
+
continue;
|
|
6301
|
+
}
|
|
6302
|
+
candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
|
|
6303
|
+
touched.add(path);
|
|
6304
|
+
}
|
|
6305
|
+
const candidates = [];
|
|
6306
|
+
const umask = planningUmask();
|
|
6307
|
+
for (const path of [...touched].sort()) {
|
|
6308
|
+
if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
|
|
6309
|
+
const original = buffers.get(path);
|
|
6310
|
+
const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
|
|
6311
|
+
if (original && original.equals(candidate)) continue;
|
|
6312
|
+
const deleteFile = candidate.byteLength === 0;
|
|
6313
|
+
const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
|
|
6314
|
+
const action = deleteFile ? "delete" : original ? "replace" : "create";
|
|
6315
|
+
candidates.push({
|
|
6316
|
+
path,
|
|
6317
|
+
action,
|
|
6318
|
+
content: deleteFile ? null : candidate.toString("utf8"),
|
|
6319
|
+
sha256: deleteFile ? null : digestBytes(candidate),
|
|
6320
|
+
mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
|
|
6321
|
+
original: snapshot,
|
|
6322
|
+
diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
|
|
6323
|
+
});
|
|
6324
|
+
}
|
|
6325
|
+
const rootDirectory = await probeDirectory(resolve6(root));
|
|
6326
|
+
const parentProbes = /* @__PURE__ */ new Map();
|
|
6327
|
+
for (const candidate of candidates) {
|
|
6328
|
+
const parent = dirname5(candidate.path);
|
|
6329
|
+
if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve6(root, parent)));
|
|
6330
|
+
}
|
|
6331
|
+
blockers.push(...restructureBoundaryFindings(
|
|
6332
|
+
candidates.map((candidate) => {
|
|
6333
|
+
const parent = parentProbes.get(dirname5(candidate.path));
|
|
6334
|
+
return {
|
|
6335
|
+
path: candidate.path,
|
|
6336
|
+
action: candidate.action,
|
|
6337
|
+
original_exists: candidate.original.exists,
|
|
6338
|
+
original_mode: candidate.original.mode,
|
|
6339
|
+
original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
|
|
6340
|
+
new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
|
|
6341
|
+
mode: candidate.mode,
|
|
6342
|
+
parent_exists: parent.exists,
|
|
6343
|
+
parent_device: parent.device,
|
|
6344
|
+
root_device: rootDirectory.device ?? -1
|
|
6345
|
+
};
|
|
6346
|
+
}),
|
|
6347
|
+
{
|
|
6348
|
+
max_operations: RESTRUCTURE_MAX_OPERATIONS,
|
|
6349
|
+
max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
|
|
6350
|
+
umask
|
|
6351
|
+
}
|
|
6352
|
+
));
|
|
6353
|
+
const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
|
|
6354
|
+
const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
|
|
6355
|
+
const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
|
|
6356
|
+
const candidateIssues = validateGraph(afterGraph, schema);
|
|
6357
|
+
for (const issue2 of candidateIssues) {
|
|
6358
|
+
if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
|
|
6359
|
+
}
|
|
6360
|
+
const afterTriples = relationTriples(afterGraph);
|
|
6361
|
+
for (const expected of expectedRelationTargets(mapping)) {
|
|
6362
|
+
if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
|
|
6363
|
+
}
|
|
6364
|
+
for (const source of mapping.sources) {
|
|
6365
|
+
const uid = `${source.type}:${source.id}`;
|
|
6366
|
+
const present = afterGraph.nodes.some((node) => node.uid === uid);
|
|
6367
|
+
if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
|
|
6368
|
+
if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
|
|
6369
|
+
}
|
|
6370
|
+
for (const criterion of mapping.criterion_map) {
|
|
6371
|
+
const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
|
|
6372
|
+
if (!sourceNode || !acceptanceCriteria(sourceNode).includes(criterion.source_criterion)) blockers.push(finding("SOURCE_CRITERION_NOT_FOUND", `Source criterion does not exist: ${criterion.source_feature}:${criterion.source_criterion}`, sourceNode?.path, sourceNode?.line));
|
|
6373
|
+
for (const target of criterion.targets) {
|
|
6374
|
+
const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
|
|
6375
|
+
if (!targetNode || !acceptanceCriteria(targetNode).includes(target.criterion)) blockers.push(finding("TARGET_CRITERION_NOT_FOUND", `Target criterion does not exist: ${target.feature}:${target.criterion}`, targetNode?.path, targetNode?.line));
|
|
6376
|
+
}
|
|
6377
|
+
}
|
|
6378
|
+
for (const header of mapping.file_headers) {
|
|
6379
|
+
const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
|
|
6380
|
+
const declaredRecords = [...header.affected_records].sort();
|
|
6381
|
+
if (canonicalJson(actualRecords) !== canonicalJson(declaredRecords)) blockers.push(finding("FILE_HEADER_RECORD_SET_MISMATCH", `file_headers must name every affected record in ${header.path}`, header.path));
|
|
6382
|
+
}
|
|
6383
|
+
const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
|
|
6384
|
+
for (const move of mapping.content_moves) {
|
|
6385
|
+
if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
|
|
6386
|
+
for (const path of [move.source.path, move.target.path]) {
|
|
6387
|
+
if (!mapping.file_headers.some((header) => header.path === path)) blockers.push(finding("E2E_FILE_HEADER_REQUIRED", `Cross-file E2E moves require final headers for both source and target files: ${path}`, path));
|
|
6388
|
+
}
|
|
6389
|
+
}
|
|
6390
|
+
for (const target of mapping.targets) {
|
|
6391
|
+
if (!afterGraph.nodes.some((node) => node.uid === `${target.type}:${target.id}` && node.path === target.path)) blockers.push(finding("TARGET_NOT_COMPILED", `Target identity was not produced at the declared path: ${target.type}:${target.id}`, target.path));
|
|
6392
|
+
}
|
|
6393
|
+
mergeFindings(unresolved, await scanUnsupportedReferences(
|
|
6394
|
+
root,
|
|
6395
|
+
[...new Set(mapping.sources.map((source) => source.path))],
|
|
6396
|
+
[...new Set([
|
|
6397
|
+
...mapping.targets.map((target) => target.path),
|
|
6398
|
+
...mapping.content_moves.map((move) => move.target.path),
|
|
6399
|
+
...mapping.file_headers.map((header) => header.path)
|
|
6400
|
+
].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
|
|
6401
|
+
));
|
|
6402
|
+
for (const move of mapping.content_moves) {
|
|
6403
|
+
const fragment = fragments.get(move.id);
|
|
6404
|
+
const sourcePath = normalizeRelativePath2(move.source.path);
|
|
6405
|
+
const targetPath = normalizeRelativePath2(move.target.path);
|
|
6406
|
+
if (!fragment || !sourcePath || !targetPath) continue;
|
|
6407
|
+
const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
|
|
6408
|
+
const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
|
|
6409
|
+
for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
|
|
6410
|
+
if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
|
|
6411
|
+
blockers.push(finding(
|
|
6412
|
+
"FOOTNOTE_DEFINITION_UNMAPPED",
|
|
6413
|
+
`The footnote definition ${footnoteDefinition(label)} stays outside the moved content; ${targetPath} would keep a dangling footnote reference and the mapping must carry the definition explicitly`,
|
|
6414
|
+
sourcePath
|
|
6415
|
+
));
|
|
6416
|
+
}
|
|
6417
|
+
}
|
|
6418
|
+
const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
|
|
6419
|
+
const plan = {
|
|
6420
|
+
schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
|
|
6421
|
+
operation_id: randomUUID2(),
|
|
6422
|
+
validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
|
|
6423
|
+
request_digest: mapping.request_digest,
|
|
6424
|
+
mapping_digest: digestRestructureValue(mapping),
|
|
6425
|
+
config_snapshot: currentConfig,
|
|
6426
|
+
input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
|
|
6427
|
+
candidates,
|
|
6428
|
+
graph_diff: graphDiff(beforeGraph, afterGraph),
|
|
6429
|
+
validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
|
|
6430
|
+
applicable: blockers.length === 0 && unresolved.length === 0
|
|
6431
|
+
};
|
|
6432
|
+
const planErrors = await validateDomainContract("plan", plan);
|
|
6433
|
+
if (planErrors.length > 0) {
|
|
6434
|
+
return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
|
|
6435
|
+
}
|
|
6436
|
+
return { ok: true, data: plan };
|
|
6437
|
+
}
|
|
6438
|
+
async function gateRestructureOperationPlan(operation, plan) {
|
|
6439
|
+
const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
|
|
6440
|
+
if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
|
|
6441
|
+
return {
|
|
6442
|
+
ok: false,
|
|
6443
|
+
error: {
|
|
6444
|
+
code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
|
|
6445
|
+
message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
|
|
6446
|
+
}
|
|
6447
|
+
};
|
|
6448
|
+
}
|
|
6449
|
+
const errors = await validateDomainContract("plan", plan);
|
|
6450
|
+
if (errors.length > 0) {
|
|
6451
|
+
return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
|
|
6452
|
+
}
|
|
6453
|
+
return { ok: true, data: plan };
|
|
6454
|
+
}
|
|
6455
|
+
function refusal(code, message, findings = []) {
|
|
6456
|
+
return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
|
|
6457
|
+
}
|
|
6458
|
+
async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
|
|
6459
|
+
const absolute = resolve6(planPath);
|
|
6460
|
+
let info;
|
|
6461
|
+
try {
|
|
6462
|
+
info = await lstat3(absolute);
|
|
6463
|
+
} catch (cause) {
|
|
6464
|
+
return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
|
|
6465
|
+
}
|
|
6466
|
+
if (info.isSymbolicLink() || !info.isFile()) {
|
|
6467
|
+
return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
|
|
6468
|
+
}
|
|
6469
|
+
let bytes;
|
|
6470
|
+
try {
|
|
6471
|
+
bytes = await readFile3(absolute);
|
|
6472
|
+
} catch (cause) {
|
|
6473
|
+
return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
|
|
6474
|
+
}
|
|
6475
|
+
let parsed;
|
|
6476
|
+
try {
|
|
6477
|
+
parsed = JSON.parse(bytes.toString("utf8"));
|
|
6478
|
+
} catch (cause) {
|
|
6479
|
+
return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
|
|
6480
|
+
}
|
|
6481
|
+
const gate = await gateRestructureOperationPlan(operation, parsed);
|
|
6482
|
+
if (!gate.ok) return gate;
|
|
6483
|
+
return { ok: true, data: { path: absolute, realPath: await realpath2(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
|
|
6484
|
+
}
|
|
6485
|
+
function planRootIdentityFindings(document) {
|
|
6486
|
+
const findings = [];
|
|
6487
|
+
const record = (path, label) => {
|
|
6488
|
+
const normalized = normalizeRelativePath2(path);
|
|
6489
|
+
if (!normalized || normalized !== path) {
|
|
6490
|
+
findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
|
|
6491
|
+
}
|
|
6492
|
+
};
|
|
6493
|
+
record(document.plan.config_snapshot.path, "config_snapshot");
|
|
6494
|
+
for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
|
|
6495
|
+
for (const candidate of document.plan.candidates) {
|
|
6496
|
+
record(candidate.path, "candidate");
|
|
6497
|
+
record(candidate.original.path, "candidate original");
|
|
6498
|
+
}
|
|
6499
|
+
if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
|
|
6500
|
+
findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
|
|
6501
|
+
}
|
|
6502
|
+
const relativePlan = relative4(document.root, document.realPath);
|
|
6503
|
+
if (!relativePlan || relativePlan.startsWith("..") || isAbsolute4(relativePlan)) {
|
|
6504
|
+
findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
|
|
6505
|
+
}
|
|
6506
|
+
return findings;
|
|
6507
|
+
}
|
|
6508
|
+
async function operationBoundaries(root, plan) {
|
|
6509
|
+
const rootDirectory = await probeDirectory(resolve6(root));
|
|
6510
|
+
const parents = /* @__PURE__ */ new Map();
|
|
6511
|
+
const boundaries = [];
|
|
6512
|
+
for (const candidate of plan.candidates) {
|
|
6513
|
+
const parent = dirname5(candidate.path) || ".";
|
|
6514
|
+
if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve6(root, parent)));
|
|
6515
|
+
const probe = parents.get(parent);
|
|
6516
|
+
boundaries.push({
|
|
6517
|
+
path: candidate.path,
|
|
6518
|
+
action: candidate.action,
|
|
6519
|
+
original_exists: candidate.original.exists,
|
|
6520
|
+
original_mode: candidate.original.mode,
|
|
6521
|
+
original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
|
|
6522
|
+
new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
|
|
6523
|
+
mode: candidate.mode,
|
|
6524
|
+
parent_exists: probe.exists,
|
|
6525
|
+
parent_device: probe.device,
|
|
6526
|
+
root_device: rootDirectory.device ?? -1
|
|
6527
|
+
});
|
|
6528
|
+
}
|
|
6529
|
+
return boundaries;
|
|
6530
|
+
}
|
|
6531
|
+
async function applyPreconditionFindings(root, document) {
|
|
6532
|
+
const findings = [];
|
|
6533
|
+
const plan = document.plan;
|
|
6534
|
+
const currentConfig = await configSnapshot(root);
|
|
6535
|
+
if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
|
|
6536
|
+
findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
|
|
6537
|
+
}
|
|
6538
|
+
for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
|
|
6539
|
+
const relativePlan = relative4(root, document.realPath).replace(/\\/g, "/");
|
|
6540
|
+
for (const candidate of plan.candidates) {
|
|
6541
|
+
if (candidate.path === relativePlan) {
|
|
6542
|
+
findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
|
|
6543
|
+
}
|
|
6544
|
+
if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
|
|
6545
|
+
findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
|
|
6546
|
+
}
|
|
6547
|
+
let original;
|
|
6548
|
+
try {
|
|
6549
|
+
original = await snapshotFile(root, candidate.path);
|
|
6550
|
+
} catch (cause) {
|
|
6551
|
+
findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
|
|
6552
|
+
continue;
|
|
6553
|
+
}
|
|
6554
|
+
if (!sameSnapshot(original, candidate.original)) {
|
|
6555
|
+
findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
|
|
6556
|
+
}
|
|
6557
|
+
if (candidate.action === "delete") continue;
|
|
6558
|
+
if (candidate.mode === null) {
|
|
6559
|
+
findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
|
|
6560
|
+
}
|
|
6561
|
+
if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
|
|
6562
|
+
findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
|
|
6563
|
+
}
|
|
6564
|
+
}
|
|
6565
|
+
findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
|
|
6566
|
+
max_operations: RESTRUCTURE_MAX_OPERATIONS,
|
|
6567
|
+
max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
|
|
6568
|
+
umask: planningUmask(),
|
|
6569
|
+
mode_contract: "apply"
|
|
6570
|
+
}));
|
|
6571
|
+
return findings;
|
|
6572
|
+
}
|
|
6573
|
+
function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
|
|
6574
|
+
const excludedConsumers = new Set(excludedConsumerPaths);
|
|
6575
|
+
const addedNodes = plan.graph_diff.added_nodes;
|
|
6576
|
+
const removedNodes = new Set(plan.graph_diff.removed_nodes);
|
|
6577
|
+
const addedEdges = plan.graph_diff.added_edges;
|
|
6578
|
+
const removedEdges = new Set(plan.graph_diff.removed_edges);
|
|
6579
|
+
const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
|
|
6580
|
+
const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
|
|
6581
|
+
const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
|
|
6582
|
+
return async function validateCandidateState(input) {
|
|
6583
|
+
const schema = await loadConfig(input.root);
|
|
6584
|
+
const graph = await scanArtifacts(input.root, schema);
|
|
6585
|
+
if (input.signal.aborted) return { passed: false };
|
|
6586
|
+
const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
|
|
6587
|
+
const edges = new Set(graph.edges.map(edgeDisplay));
|
|
6588
|
+
const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
|
|
6589
|
+
const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
|
|
6590
|
+
const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
|
|
6591
|
+
const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
|
|
6592
|
+
const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
|
|
6593
|
+
const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
|
|
6594
|
+
return { passed };
|
|
6595
|
+
};
|
|
6596
|
+
}
|
|
6597
|
+
async function applyRestructure(input) {
|
|
6598
|
+
if (input.confirmCooperativeWriters !== true) {
|
|
6599
|
+
return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
|
|
6600
|
+
}
|
|
6601
|
+
const qualification = await qualifyRestructureMechanism(input.root);
|
|
6602
|
+
if (!qualification.ok) return qualification;
|
|
6603
|
+
const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
|
|
6604
|
+
if (!document.ok) return document;
|
|
6605
|
+
const plan = document.data.plan;
|
|
6606
|
+
if (plan.candidates.length === 0) {
|
|
6607
|
+
return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
|
|
6608
|
+
}
|
|
6609
|
+
if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
|
|
6610
|
+
return refusal(
|
|
6611
|
+
"PLAN_NOT_APPLICABLE",
|
|
6612
|
+
"The plan is not applicable: it still carries blockers or unresolved findings",
|
|
6613
|
+
[...plan.validation.blockers, ...plan.validation.unresolved]
|
|
6614
|
+
);
|
|
6615
|
+
}
|
|
6616
|
+
const identity = planRootIdentityFindings(document.data);
|
|
6617
|
+
if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
|
|
6618
|
+
const drift = await applyPreconditionFindings(qualification.data.root, document.data);
|
|
6619
|
+
if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
|
|
6620
|
+
const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
|
|
6621
|
+
if (!mechanismRoot.ok) return mechanismRoot;
|
|
6622
|
+
const planRelPath = relative4(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
|
|
6623
|
+
const applied = await applyRestructureFileSet(qualification.data.root, plan, {
|
|
6624
|
+
validate: createRestructureValidationCallback(plan, [planRelPath])
|
|
6625
|
+
});
|
|
6626
|
+
if (!applied.ok) return applied;
|
|
6627
|
+
const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
|
|
6628
|
+
return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
|
|
6629
|
+
}
|
|
6630
|
+
async function recoverRestructure(input) {
|
|
6631
|
+
if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
|
|
6632
|
+
return refusal(
|
|
6633
|
+
"MAINTENANCE_CONFIRMATION_REQUIRED",
|
|
6634
|
+
"restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
|
|
6635
|
+
);
|
|
6636
|
+
}
|
|
6637
|
+
const qualification = await qualifyRestructureMechanism(input.root);
|
|
6638
|
+
if (!qualification.ok) return qualification;
|
|
6639
|
+
const document = await loadRestructurePlanDocument("recover", qualification.data.root, input.planPath);
|
|
6640
|
+
if (!document.ok) return document;
|
|
6641
|
+
const identity = planRootIdentityFindings(document.data);
|
|
6642
|
+
if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
|
|
6643
|
+
const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
|
|
6644
|
+
if (!mechanismRoot.ok) return mechanismRoot;
|
|
6645
|
+
const recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
|
|
6646
|
+
allParticipantsStopped: true,
|
|
6647
|
+
exclusiveMaintenance: true
|
|
6648
|
+
});
|
|
6649
|
+
if (!recovered.ok) return recovered;
|
|
6650
|
+
const projection = projectRestructureFileSetResult(recovered.data, document.data.realPath, document.data.digest);
|
|
6651
|
+
return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
|
|
6652
|
+
}
|
|
6653
|
+
async function pruneRestructureRecovery(input) {
|
|
6654
|
+
if (input.confirmCooperativeWriters !== true) {
|
|
6655
|
+
return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
|
|
6656
|
+
}
|
|
6657
|
+
if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
|
|
6658
|
+
return refusal(
|
|
6659
|
+
"MAINTENANCE_CONFIRMATION_REQUIRED",
|
|
6660
|
+
"A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
|
|
6661
|
+
);
|
|
6662
|
+
}
|
|
6663
|
+
const qualification = await qualifyRestructureMechanism(input.root);
|
|
6664
|
+
if (!qualification.ok) return qualification;
|
|
6665
|
+
const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
|
|
6666
|
+
if (!document.ok) return document;
|
|
6667
|
+
const identity = planRootIdentityFindings(document.data);
|
|
6668
|
+
if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
|
|
6669
|
+
const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
|
|
6670
|
+
if (!mechanismRoot.ok) return mechanismRoot;
|
|
6671
|
+
const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
|
|
6672
|
+
allParticipantsStopped: input.allParticipantsStopped,
|
|
6673
|
+
exclusiveMaintenance: input.exclusiveMaintenance
|
|
6674
|
+
});
|
|
6675
|
+
if (!pruned.ok) return pruned;
|
|
6676
|
+
const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
|
|
6677
|
+
return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
|
|
6678
|
+
}
|
|
6679
|
+
var RESTRUCTURE_PLAN_SCHEMA_VERSION, RESTRUCTURE_VALIDATION_TIMEOUT_MS, RESTRUCTURE_MAX_OPERATIONS, RESTRUCTURE_MAX_TOTAL_BYTES, MAX_POSIX_MODE, CREATE_MODE_BASE, MODULE_DIRECTORY, CONTRACT_ROOT, SKIPPED_SCAN_DIRS, TEXT_EXTENSIONS, MARKDOWN_LINK_PATTERN, RUNTIME_PATH_MARKER, MARKDOWN_FILE_SUFFIX, SCRIPT_FILE_SUFFIX;
|
|
6680
|
+
var init_restructure = __esm({
|
|
6681
|
+
"src/restructure.ts"() {
|
|
6682
|
+
"use strict";
|
|
6683
|
+
init_index();
|
|
6684
|
+
init_contract_kernel();
|
|
6685
|
+
init_restructure_software();
|
|
6686
|
+
init_restructure_file_set();
|
|
6687
|
+
RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
|
|
6688
|
+
RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
|
|
6689
|
+
RESTRUCTURE_MAX_OPERATIONS = 1024;
|
|
6690
|
+
RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
|
|
6691
|
+
MAX_POSIX_MODE = 511;
|
|
6692
|
+
CREATE_MODE_BASE = 438;
|
|
6693
|
+
MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname5(fileURLToPath2(import.meta.url));
|
|
6694
|
+
CONTRACT_ROOT = join9(MODULE_DIRECTORY, "..", "contracts");
|
|
6695
|
+
SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
|
|
6696
|
+
TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
|
|
6697
|
+
MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
|
|
6698
|
+
RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
|
|
6699
|
+
MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
|
|
6700
|
+
SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
|
|
6701
|
+
}
|
|
6702
|
+
});
|
|
6703
|
+
|
|
4996
6704
|
// src/index.ts
|
|
4997
6705
|
import matter from "gray-matter";
|
|
4998
6706
|
import yaml from "js-yaml";
|
|
4999
6707
|
import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
|
|
5000
|
-
import { mkdir as
|
|
5001
|
-
import { basename as basename4, dirname as
|
|
6708
|
+
import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
|
|
6709
|
+
import { basename as basename4, dirname as dirname6, extname, isAbsolute as isAbsolute5, join as join10, resolve as resolve7 } from "path";
|
|
5002
6710
|
function isTargetArtifactType(type) {
|
|
5003
6711
|
return isPacketTargetType(type);
|
|
5004
6712
|
}
|
|
@@ -5040,10 +6748,10 @@ function resolveArtifactTypeName(schema, token) {
|
|
|
5040
6748
|
return void 0;
|
|
5041
6749
|
}
|
|
5042
6750
|
async function loadConfig(root) {
|
|
5043
|
-
const configPath =
|
|
6751
|
+
const configPath = join10(root, "artifact-graph.config.yaml");
|
|
5044
6752
|
let parsed = {};
|
|
5045
6753
|
try {
|
|
5046
|
-
const raw = await
|
|
6754
|
+
const raw = await readFile4(configPath, "utf-8");
|
|
5047
6755
|
parsed = yaml.load(raw) ?? {};
|
|
5048
6756
|
} catch (error) {
|
|
5049
6757
|
if (error.code !== "ENOENT") {
|
|
@@ -5169,7 +6877,7 @@ function validateE2eConfig(e2e) {
|
|
|
5169
6877
|
if (typeof runner.root !== "string" || !runner.root.trim()) {
|
|
5170
6878
|
throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
|
|
5171
6879
|
}
|
|
5172
|
-
if (
|
|
6880
|
+
if (isAbsolute5(runner.root)) {
|
|
5173
6881
|
throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
|
|
5174
6882
|
}
|
|
5175
6883
|
if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
|
|
@@ -5232,14 +6940,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
|
|
|
5232
6940
|
diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
|
|
5233
6941
|
};
|
|
5234
6942
|
}
|
|
5235
|
-
async function scanArtifacts(root, schema) {
|
|
6943
|
+
async function scanArtifacts(root, schema, options = {}) {
|
|
5236
6944
|
const config = schema ?? await loadConfig(root);
|
|
5237
6945
|
const nodes = [];
|
|
5238
6946
|
const edges = [];
|
|
5239
6947
|
const scanDiagnostics = [];
|
|
5240
6948
|
const scannedFiles = /* @__PURE__ */ new Map();
|
|
6949
|
+
const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
|
|
5241
6950
|
for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
|
|
5242
|
-
const
|
|
6951
|
+
const diskFiles = await findFiles(root, definition.paths);
|
|
6952
|
+
const files = [.../* @__PURE__ */ new Set([
|
|
6953
|
+
...diskFiles.filter((file) => contentOverrides.get(file) !== null),
|
|
6954
|
+
...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
|
|
6955
|
+
])].sort();
|
|
5243
6956
|
for (const file of files) {
|
|
5244
6957
|
if (scannedFiles.has(file)) {
|
|
5245
6958
|
const existingType = scannedFiles.get(file);
|
|
@@ -5253,7 +6966,7 @@ async function scanArtifacts(root, schema) {
|
|
|
5253
6966
|
continue;
|
|
5254
6967
|
}
|
|
5255
6968
|
scannedFiles.set(file, type);
|
|
5256
|
-
const raw = await
|
|
6969
|
+
const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join10(root, file), "utf-8");
|
|
5257
6970
|
const parsed = parseFile(type, file, raw, config);
|
|
5258
6971
|
const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
|
|
5259
6972
|
nodes.push(...parsed.nodes);
|
|
@@ -5261,7 +6974,7 @@ async function scanArtifacts(root, schema) {
|
|
|
5261
6974
|
scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
|
|
5262
6975
|
}
|
|
5263
6976
|
}
|
|
5264
|
-
const absoluteRoot =
|
|
6977
|
+
const absoluteRoot = isAbsolute5(root) ? root : resolve7(root);
|
|
5265
6978
|
const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
|
|
5266
6979
|
return resolveMatrixEdges(graph);
|
|
5267
6980
|
}
|
|
@@ -5547,13 +7260,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
|
|
|
5547
7260
|
const scenarioFeatureRefs = /* @__PURE__ */ new Map();
|
|
5548
7261
|
const featureScenarioRefs = /* @__PURE__ */ new Map();
|
|
5549
7262
|
for (const node of scenarioNodes) {
|
|
5550
|
-
scenarioFeatureRefs.set(node.uid,
|
|
7263
|
+
scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
|
|
5551
7264
|
if (!scenarioPattern.test(node.code)) {
|
|
5552
7265
|
issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
|
|
5553
7266
|
}
|
|
5554
7267
|
}
|
|
5555
7268
|
for (const node of featureNodes) {
|
|
5556
|
-
featureScenarioRefs.set(node.uid,
|
|
7269
|
+
featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
|
|
5557
7270
|
if (!featurePattern.test(node.code)) {
|
|
5558
7271
|
issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
|
|
5559
7272
|
}
|
|
@@ -5627,7 +7340,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
|
|
|
5627
7340
|
const indexPath = "artifacts/prd/feature-index.md";
|
|
5628
7341
|
let raw = "";
|
|
5629
7342
|
try {
|
|
5630
|
-
raw = await
|
|
7343
|
+
raw = await readFile4(join10(root, indexPath), "utf-8");
|
|
5631
7344
|
} catch (error) {
|
|
5632
7345
|
if (error.code === "ENOENT") {
|
|
5633
7346
|
return [];
|
|
@@ -5647,7 +7360,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
|
|
|
5647
7360
|
if (!feature) {
|
|
5648
7361
|
return;
|
|
5649
7362
|
}
|
|
5650
|
-
const actualCount =
|
|
7363
|
+
const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
|
|
5651
7364
|
if (actualCount !== expectedCount) {
|
|
5652
7365
|
issues.push(issue(
|
|
5653
7366
|
"INDEX_MISMATCH",
|
|
@@ -5875,12 +7588,12 @@ function nextId(graph, schema, type, rangeName) {
|
|
|
5875
7588
|
throw new Error(`ID range ${type}.${rangeName} is exhausted`);
|
|
5876
7589
|
}
|
|
5877
7590
|
async function writeGraphCache(root, graph) {
|
|
5878
|
-
const cacheDir =
|
|
5879
|
-
await
|
|
5880
|
-
await writeFile3(
|
|
7591
|
+
const cacheDir = join10(root, ".artifact-graph");
|
|
7592
|
+
await mkdir5(cacheDir, { recursive: true });
|
|
7593
|
+
await writeFile3(join10(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
|
|
5881
7594
|
`);
|
|
5882
7595
|
const { default: Database } = await import("better-sqlite3");
|
|
5883
|
-
const db = new Database(
|
|
7596
|
+
const db = new Database(join10(cacheDir, "graph.sqlite"));
|
|
5884
7597
|
try {
|
|
5885
7598
|
db.exec(`
|
|
5886
7599
|
DROP TABLE IF EXISTS nodes;
|
|
@@ -6242,7 +7955,7 @@ function parseFeature(path, raw) {
|
|
|
6242
7955
|
}
|
|
6243
7956
|
function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
|
|
6244
7957
|
const lines = raw.split(/\r?\n/);
|
|
6245
|
-
const codeLines =
|
|
7958
|
+
const codeLines = markdownCodeLineMask2(lines);
|
|
6246
7959
|
const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
|
|
6247
7960
|
const starts = [];
|
|
6248
7961
|
lines.forEach((line, index) => {
|
|
@@ -6660,13 +8373,7 @@ function parseE2eTest(path, raw) {
|
|
|
6660
8373
|
const parsed = matter(raw);
|
|
6661
8374
|
const data = parsed.data;
|
|
6662
8375
|
const lines = raw.split(/\r?\n/);
|
|
6663
|
-
const starts =
|
|
6664
|
-
lines.forEach((line, index) => {
|
|
6665
|
-
const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
|
|
6666
|
-
if (match) {
|
|
6667
|
-
starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
|
|
6668
|
-
}
|
|
6669
|
-
});
|
|
8376
|
+
const starts = extractE2eTestCaseStarts(lines);
|
|
6670
8377
|
const nodes = [];
|
|
6671
8378
|
const edges = [];
|
|
6672
8379
|
const batch = String(data.test_batch ?? basename4(path, extname(path))).trim();
|
|
@@ -6675,26 +8382,6 @@ function parseE2eTest(path, raw) {
|
|
|
6675
8382
|
const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
|
|
6676
8383
|
const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
|
|
6677
8384
|
const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
|
|
6678
|
-
if (starts.length === 0) {
|
|
6679
|
-
const code = `${batch}:FILE`;
|
|
6680
|
-
nodes.push({
|
|
6681
|
-
type: "e2e_test",
|
|
6682
|
-
code,
|
|
6683
|
-
title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
|
|
6684
|
-
path,
|
|
6685
|
-
line: 1,
|
|
6686
|
-
attrs: {
|
|
6687
|
-
...data,
|
|
6688
|
-
testCaseId: "FILE",
|
|
6689
|
-
fileLevelOnly: true,
|
|
6690
|
-
tcFields: {},
|
|
6691
|
-
blockText: raw,
|
|
6692
|
-
coveredFeatures: [],
|
|
6693
|
-
coveredScenarios: []
|
|
6694
|
-
}
|
|
6695
|
-
});
|
|
6696
|
-
addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
|
|
6697
|
-
}
|
|
6698
8385
|
for (let index = 0; index < starts.length; index += 1) {
|
|
6699
8386
|
const start = starts[index];
|
|
6700
8387
|
const end = starts[index + 1]?.index ?? lines.length;
|
|
@@ -6720,6 +8407,16 @@ function parseE2eTest(path, raw) {
|
|
|
6720
8407
|
}
|
|
6721
8408
|
return { nodes, edges };
|
|
6722
8409
|
}
|
|
8410
|
+
function extractE2eTestCaseStarts(lines) {
|
|
8411
|
+
const codeLines = markdownCodeLineMask2(lines);
|
|
8412
|
+
return lines.flatMap((line, index) => {
|
|
8413
|
+
if (codeLines[index]) {
|
|
8414
|
+
return [];
|
|
8415
|
+
}
|
|
8416
|
+
const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
|
|
8417
|
+
return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
|
|
8418
|
+
});
|
|
8419
|
+
}
|
|
6723
8420
|
function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
|
|
6724
8421
|
for (const scenario of scenarios) {
|
|
6725
8422
|
edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
|
|
@@ -7504,7 +9201,7 @@ function matchExplicitRelationFieldLine(line, label) {
|
|
|
7504
9201
|
const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
|
|
7505
9202
|
return match?.[1] ?? null;
|
|
7506
9203
|
}
|
|
7507
|
-
function
|
|
9204
|
+
function markdownCodeLineMask2(lines) {
|
|
7508
9205
|
const result = new Array(lines.length).fill(false);
|
|
7509
9206
|
let fence;
|
|
7510
9207
|
lines.forEach((line, index) => {
|
|
@@ -7549,7 +9246,7 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
|
|
|
7549
9246
|
});
|
|
7550
9247
|
return result;
|
|
7551
9248
|
}
|
|
7552
|
-
function
|
|
9249
|
+
function relationOccurrences2(node, field, targetType) {
|
|
7553
9250
|
const relationRecord = asRecord(node.attrs?.relationOccurrences);
|
|
7554
9251
|
const rawOccurrences = toArray(relationRecord[field]);
|
|
7555
9252
|
return rawOccurrences.flatMap((value) => {
|
|
@@ -7748,6 +9445,9 @@ function validateE2eRegistry(graph) {
|
|
|
7748
9445
|
}
|
|
7749
9446
|
const actualNodes = byPath.get(file) ?? [];
|
|
7750
9447
|
if (actualNodes.length === 0) {
|
|
9448
|
+
if (Number(batch.test_case_count ?? NaN) === 0) {
|
|
9449
|
+
continue;
|
|
9450
|
+
}
|
|
7751
9451
|
issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? file)} file ${file || "<missing>"} does not match any E2E test file`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
|
|
7752
9452
|
continue;
|
|
7753
9453
|
}
|
|
@@ -7768,31 +9468,21 @@ function validateE2eRegistry(graph) {
|
|
|
7768
9468
|
async function validateExecutableTraceability(root, config) {
|
|
7769
9469
|
const issues = [];
|
|
7770
9470
|
const schema = config ?? await loadConfig(root);
|
|
7771
|
-
const
|
|
7772
|
-
|
|
7773
|
-
try {
|
|
7774
|
-
e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
|
|
7775
|
-
} catch {
|
|
9471
|
+
const e2eFiles = await findConfiguredE2eFiles(root, schema);
|
|
9472
|
+
if (e2eFiles.length === 0) {
|
|
7776
9473
|
return [];
|
|
7777
9474
|
}
|
|
7778
9475
|
const mdToRef = /* @__PURE__ */ new Map();
|
|
7779
9476
|
const allMdTcInfo = /* @__PURE__ */ new Map();
|
|
7780
9477
|
const tcKeyToFields = /* @__PURE__ */ new Map();
|
|
7781
9478
|
const mdBatches = /* @__PURE__ */ new Set();
|
|
7782
|
-
for (const
|
|
7783
|
-
const raw = await
|
|
7784
|
-
const relPath = relative4(root, filePath).split("\\").join("/");
|
|
9479
|
+
for (const relPath of e2eFiles) {
|
|
9480
|
+
const raw = await readFile4(join10(root, relPath), "utf-8");
|
|
7785
9481
|
const parsed = matter(raw);
|
|
7786
9482
|
const data = parsed.data;
|
|
7787
|
-
const batch = String(data.test_batch ?? basename4(
|
|
9483
|
+
const batch = String(data.test_batch ?? basename4(relPath, extname(relPath))).trim();
|
|
7788
9484
|
const lines = raw.split(/\r?\n/);
|
|
7789
|
-
const tcStarts =
|
|
7790
|
-
lines.forEach((line, index) => {
|
|
7791
|
-
const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
|
|
7792
|
-
if (match) {
|
|
7793
|
-
tcStarts.push({ id: match[1], line: index + 1, index });
|
|
7794
|
-
}
|
|
7795
|
-
});
|
|
9485
|
+
const tcStarts = extractE2eTestCaseStarts(lines);
|
|
7796
9486
|
for (let i = 0; i < tcStarts.length; i += 1) {
|
|
7797
9487
|
const start = tcStarts[i];
|
|
7798
9488
|
const end = tcStarts[i + 1]?.index ?? lines.length;
|
|
@@ -7829,10 +9519,10 @@ async function validateExecutableTraceability(root, config) {
|
|
|
7829
9519
|
const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
|
|
7830
9520
|
const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
|
|
7831
9521
|
for (const specFile of specFiles) {
|
|
7832
|
-
const fullSpecPath =
|
|
9522
|
+
const fullSpecPath = join10(root, specFile);
|
|
7833
9523
|
let content;
|
|
7834
9524
|
try {
|
|
7835
|
-
content = await
|
|
9525
|
+
content = await readFile4(fullSpecPath, "utf-8");
|
|
7836
9526
|
} catch {
|
|
7837
9527
|
continue;
|
|
7838
9528
|
}
|
|
@@ -7911,7 +9601,7 @@ async function validateExecutableTraceability(root, config) {
|
|
|
7911
9601
|
if (entry.testId) {
|
|
7912
9602
|
let content;
|
|
7913
9603
|
try {
|
|
7914
|
-
content = await
|
|
9604
|
+
content = await readFile4(join10(root, normalizedRefFile), "utf-8");
|
|
7915
9605
|
} catch {
|
|
7916
9606
|
continue;
|
|
7917
9607
|
}
|
|
@@ -7939,7 +9629,7 @@ async function validateExecutableTraceability(root, config) {
|
|
|
7939
9629
|
}
|
|
7940
9630
|
continue;
|
|
7941
9631
|
}
|
|
7942
|
-
if (!
|
|
9632
|
+
if (!allMdTcInfo.has(tcKey)) {
|
|
7943
9633
|
for (const ann of annotations) {
|
|
7944
9634
|
issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
|
|
7945
9635
|
}
|
|
@@ -8088,34 +9778,10 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
|
|
|
8088
9778
|
let withExecutableRef = 0;
|
|
8089
9779
|
const statusBreakdown = {};
|
|
8090
9780
|
const chainTypeBreakdown = {};
|
|
8091
|
-
const
|
|
8092
|
-
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
|
|
8096
|
-
} catch {
|
|
8097
|
-
e2eFiles = [];
|
|
8098
|
-
}
|
|
8099
|
-
for (const filePath of e2eFiles) {
|
|
8100
|
-
const raw = await readFile3(filePath, "utf-8");
|
|
8101
|
-
const lines = raw.split(/\r?\n/);
|
|
8102
|
-
const tcStarts = [];
|
|
8103
|
-
lines.forEach((line, index) => {
|
|
8104
|
-
const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
|
|
8105
|
-
if (match) {
|
|
8106
|
-
tcStarts.push({ id: match[1], index });
|
|
8107
|
-
}
|
|
8108
|
-
});
|
|
8109
|
-
const parsed = matter(raw);
|
|
8110
|
-
const batch = String(parsed.data.test_batch ?? basename4(filePath, extname(filePath))).trim();
|
|
8111
|
-
for (let i = 0; i < tcStarts.length; i++) {
|
|
8112
|
-
const start = tcStarts[i];
|
|
8113
|
-
const end = tcStarts[i + 1]?.index ?? lines.length;
|
|
8114
|
-
const block = lines.slice(start.index, end);
|
|
8115
|
-
const fields = extractE2eTcFields(block);
|
|
8116
|
-
tcFieldsMap.set(`${batch}:${start.id}`, fields);
|
|
8117
|
-
}
|
|
8118
|
-
}
|
|
9781
|
+
const tcFieldsMap = new Map(e2eNodes.map((node) => [
|
|
9782
|
+
node.code,
|
|
9783
|
+
asRecord(node.attrs?.tcFields)
|
|
9784
|
+
]));
|
|
8119
9785
|
for (const node of e2eNodes) {
|
|
8120
9786
|
const tcKey = node.code;
|
|
8121
9787
|
const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
|
|
@@ -8170,7 +9836,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
|
|
|
8170
9836
|
let hasActiveE2eRef = false;
|
|
8171
9837
|
for (const entry of parseExecutableRefLines(execRef)) {
|
|
8172
9838
|
const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
|
|
8173
|
-
if (!normalized || !existsSync3(
|
|
9839
|
+
if (!normalized || !existsSync3(join10(root, normalized))) continue;
|
|
8174
9840
|
const accepting = await getAcceptingRunners(root, normalized, runners);
|
|
8175
9841
|
if (accepting.some((runner) => runner.kind === "e2e")) {
|
|
8176
9842
|
hasActiveE2eRef = true;
|
|
@@ -8229,7 +9895,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
|
|
|
8229
9895
|
const acCoverageRateByFeature = {};
|
|
8230
9896
|
const featureAcMap = /* @__PURE__ */ new Map();
|
|
8231
9897
|
for (const node of featureNodes) {
|
|
8232
|
-
const acs = parseAcceptanceCriteria(await
|
|
9898
|
+
const acs = parseAcceptanceCriteria(await readFile4(join10(root, node.path), "utf-8"));
|
|
8233
9899
|
featureAcMap.set(node.code, new Set(acs));
|
|
8234
9900
|
}
|
|
8235
9901
|
const coveredAcByFeature = /* @__PURE__ */ new Map();
|
|
@@ -8271,39 +9937,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
|
|
|
8271
9937
|
};
|
|
8272
9938
|
}
|
|
8273
9939
|
async function generateE2eRegistry(root, opts) {
|
|
8274
|
-
const
|
|
8275
|
-
|
|
8276
|
-
try {
|
|
8277
|
-
files = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
|
|
8278
|
-
} catch {
|
|
8279
|
-
return {
|
|
8280
|
-
registry_version: "1.0",
|
|
8281
|
-
generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
|
|
8282
|
-
total_batches: 0,
|
|
8283
|
-
total_test_cases: 0,
|
|
8284
|
-
batches: []
|
|
8285
|
-
};
|
|
8286
|
-
}
|
|
9940
|
+
const schema = await loadConfig(root);
|
|
9941
|
+
const files = await findConfiguredE2eFiles(root, schema);
|
|
8287
9942
|
const batches = [];
|
|
9943
|
+
const batchIds = /* @__PURE__ */ new Set();
|
|
8288
9944
|
let totalTestCases = 0;
|
|
8289
9945
|
for (const file of files) {
|
|
8290
|
-
const filePath =
|
|
8291
|
-
const raw = await
|
|
9946
|
+
const filePath = join10(root, file);
|
|
9947
|
+
const raw = await readFile4(filePath, "utf-8");
|
|
8292
9948
|
const parsed = matter(raw);
|
|
8293
9949
|
const data = parsed.data;
|
|
8294
9950
|
const batch = String(data.test_batch ?? basename4(file, extname(file))).trim();
|
|
8295
|
-
const relPath =
|
|
9951
|
+
const relPath = file;
|
|
8296
9952
|
const scope = String(data.scope ?? "").trim();
|
|
8297
9953
|
const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
|
|
8298
9954
|
const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
|
|
8299
9955
|
const lines = raw.split(/\r?\n/);
|
|
8300
|
-
const tcStarts =
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
tcStarts.push({ id: match[1], index });
|
|
8305
|
-
}
|
|
8306
|
-
});
|
|
9956
|
+
const tcStarts = extractE2eTestCaseStarts(lines);
|
|
9957
|
+
if (tcStarts.length > 0) {
|
|
9958
|
+
batchIds.add(batch);
|
|
9959
|
+
}
|
|
8307
9960
|
const statusSummary = {};
|
|
8308
9961
|
const blockingReasons = {};
|
|
8309
9962
|
const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
|
|
@@ -8312,8 +9965,9 @@ async function generateE2eRegistry(root, opts) {
|
|
|
8312
9965
|
blockingReasons[tc.id] = frontmatterFixesBlock;
|
|
8313
9966
|
}
|
|
8314
9967
|
}
|
|
8315
|
-
for (
|
|
8316
|
-
const
|
|
9968
|
+
for (let index = 0; index < tcStarts.length; index += 1) {
|
|
9969
|
+
const start = tcStarts[index];
|
|
9970
|
+
const end = tcStarts[index + 1]?.index ?? lines.length;
|
|
8317
9971
|
const block = lines.slice(start.index, end);
|
|
8318
9972
|
const fields = extractE2eTcFields(block);
|
|
8319
9973
|
const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
|
|
@@ -8346,7 +10000,7 @@ async function generateE2eRegistry(root, opts) {
|
|
|
8346
10000
|
return {
|
|
8347
10001
|
registry_version: "1.0",
|
|
8348
10002
|
generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
|
|
8349
|
-
total_batches:
|
|
10003
|
+
total_batches: batchIds.size,
|
|
8350
10004
|
total_test_cases: totalTestCases,
|
|
8351
10005
|
batches
|
|
8352
10006
|
};
|
|
@@ -8415,10 +10069,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
|
|
|
8415
10069
|
if (!normalizedPath) {
|
|
8416
10070
|
return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
|
|
8417
10071
|
}
|
|
8418
|
-
const fullPath =
|
|
10072
|
+
const fullPath = join10(root, normalizedPath);
|
|
8419
10073
|
let content;
|
|
8420
10074
|
try {
|
|
8421
|
-
content = await
|
|
10075
|
+
content = await readFile4(fullPath, "utf-8");
|
|
8422
10076
|
} catch {
|
|
8423
10077
|
return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
|
|
8424
10078
|
}
|
|
@@ -8452,7 +10106,7 @@ function detectTestLevel(specFile, content) {
|
|
|
8452
10106
|
}
|
|
8453
10107
|
function resolveExecutableRefFile(refFile, allFiles) {
|
|
8454
10108
|
const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
8455
|
-
if (!normalized ||
|
|
10109
|
+
if (!normalized || isAbsolute5(refFile) || normalized.split("/").includes("..")) {
|
|
8456
10110
|
return void 0;
|
|
8457
10111
|
}
|
|
8458
10112
|
if (allFiles.includes(normalized)) {
|
|
@@ -8525,17 +10179,6 @@ function splitMarkdownCells(line) {
|
|
|
8525
10179
|
function escapeRegExp(value) {
|
|
8526
10180
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
8527
10181
|
}
|
|
8528
|
-
async function hasMarkdownTc(tcKey, e2eDir) {
|
|
8529
|
-
const [batch, tcId] = tcKey.split(":");
|
|
8530
|
-
const filePath = join8(e2eDir, `${batch}.md`);
|
|
8531
|
-
try {
|
|
8532
|
-
const raw = await readFile3(filePath, "utf-8");
|
|
8533
|
-
const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
|
|
8534
|
-
return tcRegex.test(raw);
|
|
8535
|
-
} catch {
|
|
8536
|
-
return false;
|
|
8537
|
-
}
|
|
8538
|
-
}
|
|
8539
10182
|
async function findFiles(root, patterns) {
|
|
8540
10183
|
const all = await walkFiles(root);
|
|
8541
10184
|
const matched = /* @__PURE__ */ new Set();
|
|
@@ -8548,6 +10191,10 @@ async function findFiles(root, patterns) {
|
|
|
8548
10191
|
}
|
|
8549
10192
|
return [...matched].sort();
|
|
8550
10193
|
}
|
|
10194
|
+
async function findConfiguredE2eFiles(root, schema) {
|
|
10195
|
+
const patterns = schema.types.e2e_test?.paths ?? [];
|
|
10196
|
+
return findFiles(root, patterns);
|
|
10197
|
+
}
|
|
8551
10198
|
function matchesConfiguredArtifactPath(path, schema) {
|
|
8552
10199
|
const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
8553
10200
|
return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
|
|
@@ -8576,8 +10223,13 @@ function extractCodes(text, type, schema) {
|
|
|
8576
10223
|
}
|
|
8577
10224
|
function extractE2eTcFields(block) {
|
|
8578
10225
|
const fields = {};
|
|
10226
|
+
const codeLines = markdownCodeLineMask2(block);
|
|
8579
10227
|
let current = "";
|
|
8580
|
-
for (
|
|
10228
|
+
for (let index = 0; index < block.length; index += 1) {
|
|
10229
|
+
if (codeLines[index]) {
|
|
10230
|
+
continue;
|
|
10231
|
+
}
|
|
10232
|
+
const line = block[index];
|
|
8581
10233
|
const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
|
|
8582
10234
|
if (match) {
|
|
8583
10235
|
current = match[1].trim();
|
|
@@ -9036,14 +10688,14 @@ function resolveArtifactContext(graph, opts) {
|
|
|
9036
10688
|
}
|
|
9037
10689
|
if (root) {
|
|
9038
10690
|
for (const ap of ALWAYS_PRESENT_ITEMS) {
|
|
9039
|
-
const fullPath =
|
|
9040
|
-
let
|
|
10691
|
+
const fullPath = join10(root, ap.path);
|
|
10692
|
+
let stat2;
|
|
9041
10693
|
try {
|
|
9042
|
-
|
|
10694
|
+
stat2 = statSync(fullPath);
|
|
9043
10695
|
} catch {
|
|
9044
|
-
|
|
10696
|
+
stat2 = null;
|
|
9045
10697
|
}
|
|
9046
|
-
if (!
|
|
10698
|
+
if (!stat2) {
|
|
9047
10699
|
const msg = `Required baseline artifact not found: ${ap.path}`;
|
|
9048
10700
|
if (!missing.includes(msg)) {
|
|
9049
10701
|
missing.push(msg);
|
|
@@ -9055,7 +10707,7 @@ function resolveArtifactContext(graph, opts) {
|
|
|
9055
10707
|
suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
|
|
9056
10708
|
});
|
|
9057
10709
|
}
|
|
9058
|
-
} else if (!
|
|
10710
|
+
} else if (!stat2.isFile()) {
|
|
9059
10711
|
const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
|
|
9060
10712
|
if (!missing.includes(msg)) {
|
|
9061
10713
|
missing.push(msg);
|
|
@@ -9301,6 +10953,9 @@ var init_index = __esm({
|
|
|
9301
10953
|
init_hook_installer();
|
|
9302
10954
|
init_review_result_validator();
|
|
9303
10955
|
init_contract_kernel();
|
|
10956
|
+
init_restructure();
|
|
10957
|
+
init_restructure_file_set();
|
|
10958
|
+
init_restructure_software();
|
|
9304
10959
|
TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
|
|
9305
10960
|
NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
|
|
9306
10961
|
DEFAULT_SCHEMA = {
|
|
@@ -9395,6 +11050,7 @@ export {
|
|
|
9395
11050
|
BASELINE_CONSTRAINTS,
|
|
9396
11051
|
BASELINE_CONSTRAINTS_COUNT,
|
|
9397
11052
|
BASELINE_ITEMS_COUNT,
|
|
11053
|
+
CONTRACTS_PACKAGE_NAME,
|
|
9398
11054
|
CONTRACT_ERROR_CODES,
|
|
9399
11055
|
ContractCatalog,
|
|
9400
11056
|
ContractError,
|
|
@@ -9402,35 +11058,58 @@ export {
|
|
|
9402
11058
|
DEFAULT_MAX_CHARS,
|
|
9403
11059
|
DEFAULT_SCHEMA,
|
|
9404
11060
|
E2E_NORMALIZER_CONFIG,
|
|
11061
|
+
FILE_SET_RESULT_OBJECT,
|
|
11062
|
+
FOUNDATION_PACKAGE_NAME,
|
|
9405
11063
|
MIN_PROMPT_CHARS,
|
|
11064
|
+
RESTRUCTURE_MAX_OPERATIONS,
|
|
11065
|
+
RESTRUCTURE_MAX_TOTAL_BYTES,
|
|
11066
|
+
RESTRUCTURE_PLAN_SCHEMA_VERSION,
|
|
11067
|
+
RESTRUCTURE_QUALIFIED_ARCH,
|
|
11068
|
+
RESTRUCTURE_QUALIFIED_FILESYSTEM,
|
|
11069
|
+
RESTRUCTURE_QUALIFIED_PLATFORM,
|
|
11070
|
+
RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
|
|
11071
|
+
RESTRUCTURE_RECOVERY_REL_PATH,
|
|
11072
|
+
RESTRUCTURE_RECOVERY_ROOT_MODE,
|
|
11073
|
+
RESTRUCTURE_VALIDATION_TIMEOUT_MS,
|
|
9406
11074
|
TARGET_ARTIFACT_TYPES,
|
|
9407
11075
|
VALID_PACKET_TARGET_TYPES,
|
|
9408
11076
|
VERSION_INDEX_SCHEMA_VERSION,
|
|
9409
11077
|
VERSION_LOCK_PATH,
|
|
9410
11078
|
VERSION_LOCK_SCHEMA_VERSION,
|
|
9411
11079
|
applyPreparedManagedHookBlocks,
|
|
11080
|
+
applyRestructure,
|
|
11081
|
+
applyRestructureFileSet,
|
|
9412
11082
|
assemblePacket,
|
|
9413
11083
|
auditPackets,
|
|
9414
11084
|
auditVersionLock,
|
|
9415
11085
|
bootstrapVersionLock,
|
|
11086
|
+
buildFileSetApplyRequest,
|
|
9416
11087
|
buildGraph,
|
|
9417
11088
|
buildVersionIndex,
|
|
11089
|
+
candidateByteDigest,
|
|
9418
11090
|
collectChangedPaths,
|
|
9419
11091
|
computeCoverageBoundary,
|
|
9420
11092
|
computeE2eCoverageStats,
|
|
9421
11093
|
computeImpact,
|
|
9422
11094
|
computeRevisionDigest,
|
|
9423
|
-
|
|
11095
|
+
createModeForUmask,
|
|
11096
|
+
createRestructureRootBinding,
|
|
11097
|
+
createRestructureValidationCallback,
|
|
11098
|
+
digestRestructureValue,
|
|
11099
|
+
dirname6 as dirname,
|
|
9424
11100
|
discoverAndAuditPackets,
|
|
9425
11101
|
discoverTargets,
|
|
9426
11102
|
doctorArtifactChain,
|
|
11103
|
+
ensureRestructureMechanismRoot,
|
|
9427
11104
|
extname,
|
|
9428
11105
|
filterGraphByView,
|
|
9429
11106
|
formatContextMarkdown,
|
|
11107
|
+
gateRestructureOperationPlan,
|
|
9430
11108
|
generateE2eRegistry,
|
|
9431
11109
|
getArtifactTypeMetadata,
|
|
9432
11110
|
getExternalEntryInfo,
|
|
9433
11111
|
getTargetArtifactTypes,
|
|
11112
|
+
inspectRestructure,
|
|
9434
11113
|
installManagedHookBlock,
|
|
9435
11114
|
isOfficialNamespace,
|
|
9436
11115
|
isPacketTargetType,
|
|
@@ -9441,14 +11120,26 @@ export {
|
|
|
9441
11120
|
loadContract,
|
|
9442
11121
|
loadContractCatalog,
|
|
9443
11122
|
loadContractsFromDirectory,
|
|
11123
|
+
loadFoundationModule,
|
|
11124
|
+
locateSoftwareRecord,
|
|
11125
|
+
markdownRecordHeadings,
|
|
9444
11126
|
matchesConfiguredArtifactPath,
|
|
9445
11127
|
nextId,
|
|
9446
11128
|
normalizeE2eLegacyArtifact,
|
|
9447
11129
|
normalizeToCanonical,
|
|
11130
|
+
observeRestructureJournal,
|
|
9448
11131
|
parseTargetSelector,
|
|
9449
11132
|
parseTargetsFile,
|
|
11133
|
+
planRestructure,
|
|
11134
|
+
planningUmask,
|
|
9450
11135
|
prepareManagedHookBlock,
|
|
11136
|
+
projectRestructureFileSetResult,
|
|
11137
|
+
pruneRestructureFileSet,
|
|
11138
|
+
pruneRestructureRecovery,
|
|
11139
|
+
qualifyRestructureMechanism,
|
|
9451
11140
|
queryGraph,
|
|
11141
|
+
recoverRestructure,
|
|
11142
|
+
recoverRestructureFileSet,
|
|
9452
11143
|
refreshVersionLock,
|
|
9453
11144
|
renderCoverageBoundaryMarkdown,
|
|
9454
11145
|
renderDoctorMarkdown,
|
|
@@ -9459,6 +11150,7 @@ export {
|
|
|
9459
11150
|
renderTraceVersionMarkdown,
|
|
9460
11151
|
renderVersionLockAuditMarkdown,
|
|
9461
11152
|
renderVersionLockRefreshMarkdown,
|
|
11153
|
+
replaceSoftwareHeader,
|
|
9462
11154
|
resolveArtifactContext,
|
|
9463
11155
|
resolveArtifactGraphCli,
|
|
9464
11156
|
resolveArtifactTypeName,
|
|
@@ -9466,6 +11158,8 @@ export {
|
|
|
9466
11158
|
resolveGitHookPath,
|
|
9467
11159
|
resolveMatrixEdges,
|
|
9468
11160
|
resolveNodeTimeView,
|
|
11161
|
+
resolveRealRoot,
|
|
11162
|
+
restructureBoundaryFindings,
|
|
9469
11163
|
scanArtifacts,
|
|
9470
11164
|
traceVersion,
|
|
9471
11165
|
updateVersionLock,
|
|
@@ -9481,6 +11175,7 @@ export {
|
|
|
9481
11175
|
validateScenarioPrdLinkIndex,
|
|
9482
11176
|
validateScenarioPrdLinks,
|
|
9483
11177
|
verifyDigest,
|
|
11178
|
+
verifyMechanismResult,
|
|
9484
11179
|
versionLockIssueSeverity,
|
|
9485
11180
|
writeGraphCache
|
|
9486
11181
|
};
|