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/dist/index.cjs CHANGED
@@ -986,9 +986,13 @@ async function bootstrapVersionLock(root, options = {}) {
986
986
  async function refreshVersionLock(root, options = {}) {
987
987
  const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
988
988
  const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
989
+ const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
989
990
  const all = options.all === true || options.changedOnly !== true;
990
991
  const mode = all ? "all" : "changed-only";
991
992
  const warnings = [];
993
+ if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
994
+ throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
995
+ }
992
996
  if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
993
997
  throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
994
998
  }
@@ -998,9 +1002,16 @@ async function refreshVersionLock(root, options = {}) {
998
1002
  const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
999
1003
  const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
1000
1004
  const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
1005
+ const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1001
1006
  const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
1002
1007
  const currentEntries = /* @__PURE__ */ new Map();
1003
1008
  const changedPathSet = new Set(changedPaths);
1009
+ validatePreciseOrphanRemoval(
1010
+ removeOrphanEdges,
1011
+ lock,
1012
+ new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
1013
+ new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
1014
+ );
1004
1015
  const affectedEdges = /* @__PURE__ */ new Set();
1005
1016
  const addedLocks = [];
1006
1017
  const updatedLocks = [];
@@ -1027,12 +1038,13 @@ async function refreshVersionLock(root, options = {}) {
1027
1038
  }
1028
1039
  for (const existing of lock.locks) {
1029
1040
  const current = currentEntries.get(existing.edgeId);
1030
- const affected = all || lockEntryTouchesAnyPath(existing, changedPathSet);
1041
+ const removePrecisely = removeOrphanEdges.has(existing.edgeId);
1042
+ const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
1031
1043
  if (affected) {
1032
1044
  affectedEdges.add(existing.edgeId);
1033
1045
  }
1034
1046
  if (!current) {
1035
- if (affected && options.removeOrphans === true) {
1047
+ if (removePrecisely || affected && options.removeOrphans === true) {
1036
1048
  removedOrphans.push(existing.edgeId);
1037
1049
  } else {
1038
1050
  if (affected) {
@@ -1067,7 +1079,6 @@ async function refreshVersionLock(root, options = {}) {
1067
1079
  if (mode === "changed-only" && changedPaths.length === 0) {
1068
1080
  warnings.push("No changed paths were provided; no locks were refreshed.");
1069
1081
  }
1070
- const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1071
1082
  const existingArtifactRelationLocks = lock.artifactRelations ?? [];
1072
1083
  const addedArtifactRelationLocks = [];
1073
1084
  const updatedArtifactRelationLocks = [];
@@ -1111,10 +1122,11 @@ async function refreshVersionLock(root, options = {}) {
1111
1122
  if (processedRelationEdgeIds.has(relEdgeId)) {
1112
1123
  continue;
1113
1124
  }
1114
- const affected = all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1125
+ const removePrecisely = removeOrphanEdges.has(relEdgeId);
1126
+ const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1115
1127
  if (affected) {
1116
1128
  affectedEdges.add(relEdgeId);
1117
- if (options.removeOrphans === true) {
1129
+ if (removePrecisely || options.removeOrphans === true) {
1118
1130
  removedArtifactRelationLocks.push(relEdgeId);
1119
1131
  } else {
1120
1132
  retainedArtifactRelationOrphans.push(relEdgeId);
@@ -1150,6 +1162,20 @@ async function refreshVersionLock(root, options = {}) {
1150
1162
  warnings
1151
1163
  };
1152
1164
  }
1165
+ function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
1166
+ for (const edgeId of requestedEdgeIds) {
1167
+ const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
1168
+ if (matches === 0) {
1169
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
1170
+ }
1171
+ if (matches !== 1) {
1172
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
1173
+ }
1174
+ if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
1175
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
1176
+ }
1177
+ }
1178
+ }
1153
1179
  async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
1154
1180
  const index = await buildVersionIndex(root);
1155
1181
  const safeLockPath = normalizeRelativePath(root, lockPath);
@@ -3126,16 +3152,16 @@ function probeNativeBinding(context = {}) {
3126
3152
  }
3127
3153
  return { ok: true };
3128
3154
  }
3129
- function buildNativeBindingDiagnostic(failure, probeContext) {
3155
+ function buildNativeBindingDiagnostic(failure2, probeContext) {
3130
3156
  return {
3131
3157
  selectedCli: probeContext.selectedCli,
3132
3158
  runtime: `${process.execPath} (v${process.versions.node})`,
3133
- abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure.detail)}`,
3159
+ abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
3134
3160
  installSource: probeContext.installSource,
3135
3161
  probedFrom: probeContext.probedFrom,
3136
- failedStage: failure.failedStage,
3137
- cause: failure.cause,
3138
- suggestion: failure.suggestion
3162
+ failedStage: failure2.failedStage,
3163
+ cause: failure2.cause,
3164
+ suggestion: failure2.suggestion
3139
3165
  };
3140
3166
  }
3141
3167
  function buildNativeBindingSuccessDiagnostic(probeContext) {
@@ -3256,7 +3282,7 @@ async function doctorArtifactChain(root, options = {}) {
3256
3282
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3257
3283
  const warnings = [
3258
3284
  ...cli.warnings,
3259
- ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy >=22.0.0.`],
3285
+ ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3260
3286
  ...probe.ok ? [] : [
3261
3287
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3262
3288
  ]
@@ -3268,7 +3294,7 @@ async function doctorArtifactChain(root, options = {}) {
3268
3294
  node: {
3269
3295
  version: process.versions.node,
3270
3296
  compatible: nodeCompatible,
3271
- required: ">=22.0.0"
3297
+ required: REQUIRED_NODE_VERSION
3272
3298
  },
3273
3299
  config: {
3274
3300
  path: configPath,
@@ -3372,8 +3398,10 @@ function resolveCandidatePath(root, candidatePath) {
3372
3398
  return (0, import_node_path7.isAbsolute)(candidatePath) ? candidatePath : (0, import_node_path7.resolve)(root, candidatePath);
3373
3399
  }
3374
3400
  function isNodeCompatible(version) {
3375
- const major = Number(version.split(".")[0]);
3376
- return Number.isFinite(major) && major >= 22;
3401
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
3402
+ if (!match) return false;
3403
+ const [, major, minor, patch] = match.map(Number);
3404
+ return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
3377
3405
  }
3378
3406
  async function detectPnpmVersion() {
3379
3407
  try {
@@ -3434,7 +3462,7 @@ function safeRealpath(path) {
3434
3462
  return path;
3435
3463
  }
3436
3464
  }
3437
- var import_node_child_process2, import_node_fs3, import_promises4, import_node_path7, import_node_util2, execFileAsync2, KNOWN_COMMANDS;
3465
+ var import_node_child_process2, import_node_fs3, import_promises4, import_node_path7, import_node_util2, execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
3438
3466
  var init_cli_resolver = __esm({
3439
3467
  "src/cli-resolver.ts"() {
3440
3468
  "use strict";
@@ -3446,6 +3474,7 @@ var init_cli_resolver = __esm({
3446
3474
  init_versioned_traceability();
3447
3475
  init_native_binding_diagnostics();
3448
3476
  execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
3477
+ REQUIRED_NODE_VERSION = ">=22.22.2 <23";
3449
3478
  KNOWN_COMMANDS = [
3450
3479
  "init",
3451
3480
  "scan",
@@ -4004,8 +4033,8 @@ function validateReviewResult(input) {
4004
4033
  validateReviewData(obj.review, "$.review", errors);
4005
4034
  if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
4006
4035
  const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
4007
- findings.forEach((finding, index) => {
4008
- if (isPlainObject(finding) && finding.severity === "block" && (finding.status === void 0 || finding.status === "open")) {
4036
+ findings.forEach((finding2, index) => {
4037
+ if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
4009
4038
  errors.push({
4010
4039
  path: `$.review.findings[${index}]`,
4011
4040
  message: `${obj.decision} cannot contain an open block finding`
@@ -5023,6 +5052,1686 @@ var init_contract_kernel = __esm({
5023
5052
  }
5024
5053
  });
5025
5054
 
5055
+ // src/restructure-software.ts
5056
+ function lineStarts(raw) {
5057
+ const starts = [0];
5058
+ const buffer = Buffer.from(raw, "utf8");
5059
+ for (let index = 0; index < buffer.length; index += 1) {
5060
+ if (buffer[index] === 10) starts.push(index + 1);
5061
+ }
5062
+ return starts;
5063
+ }
5064
+ function markdownCodeLineMask(lines) {
5065
+ const result = new Array(lines.length).fill(false);
5066
+ let fence;
5067
+ lines.forEach((line, index) => {
5068
+ if (fence) {
5069
+ result[index] = true;
5070
+ const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
5071
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
5072
+ return;
5073
+ }
5074
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
5075
+ if (opening) {
5076
+ result[index] = true;
5077
+ fence = { marker: opening[1][0], length: opening[1].length };
5078
+ return;
5079
+ }
5080
+ if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
5081
+ });
5082
+ return result;
5083
+ }
5084
+ function markdownRecordHeadings(raw, type) {
5085
+ const lines = raw.split("\n");
5086
+ const masked = markdownCodeLineMask(lines);
5087
+ 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;
5088
+ if (!pattern) return [];
5089
+ return lines.flatMap((line, index) => {
5090
+ if (masked[index]) return [];
5091
+ const match = pattern.exec(line.replace(/\r$/, ""));
5092
+ return match ? [{ id: match[1], line: index + 1 }] : [];
5093
+ });
5094
+ }
5095
+ function locateSoftwareRecord(raw, node, nodesInFile) {
5096
+ const byteLength = Buffer.byteLength(raw, "utf8");
5097
+ if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
5098
+ if (node.type !== "scenario" && node.type !== "e2e_test") {
5099
+ return {
5100
+ blockers: [{
5101
+ code: "UNSUPPORTED_RECORD_BOUNDARY",
5102
+ message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
5103
+ path: node.path,
5104
+ line: node.line
5105
+ }]
5106
+ };
5107
+ }
5108
+ const headings = markdownRecordHeadings(raw, node.type);
5109
+ const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
5110
+ const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
5111
+ const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
5112
+ const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
5113
+ const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
5114
+ const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
5115
+ if (inconsistent) {
5116
+ return {
5117
+ blockers: [{
5118
+ code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
5119
+ 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",
5120
+ path: node.path,
5121
+ line: node.line
5122
+ }]
5123
+ };
5124
+ }
5125
+ if (!heading) {
5126
+ return {
5127
+ blockers: [{
5128
+ code: "RECORD_BOUNDARY_MISSING",
5129
+ message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
5130
+ path: node.path,
5131
+ line: node.line
5132
+ }]
5133
+ };
5134
+ }
5135
+ const starts = lineStarts(raw);
5136
+ const nextLine = headings.find((item) => item.line > heading.line)?.line;
5137
+ return {
5138
+ range: {
5139
+ startByte: starts[heading.line - 1] ?? 0,
5140
+ endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
5141
+ },
5142
+ blockers: []
5143
+ };
5144
+ }
5145
+ function replaceSoftwareHeader(raw, header) {
5146
+ const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
5147
+ const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
5148
+ ` : header;
5149
+ return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
5150
+ }
5151
+ var init_restructure_software = __esm({
5152
+ "src/restructure-software.ts"() {
5153
+ "use strict";
5154
+ }
5155
+ });
5156
+
5157
+ // src/restructure-file-set.ts
5158
+ async function loadFoundationModule() {
5159
+ return await import(FOUNDATION_PACKAGE_NAME);
5160
+ }
5161
+ async function loadContractsModule() {
5162
+ return await import(CONTRACTS_PACKAGE_NAME);
5163
+ }
5164
+ async function verifyMechanismResult(result) {
5165
+ if (typeof result !== "object" || result === null || Array.isArray(result)) {
5166
+ return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
5167
+ }
5168
+ let contracts;
5169
+ let registration;
5170
+ try {
5171
+ contracts = await loadContractsModule();
5172
+ registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
5173
+ } catch (cause) {
5174
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
5175
+ }
5176
+ if (registration === null) {
5177
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
5178
+ }
5179
+ const verdict = contracts.validateDocument(result, {
5180
+ schemaId: registration.$id,
5181
+ dialect: registration.dialect,
5182
+ policy: "strict"
5183
+ });
5184
+ if (!verdict.valid) {
5185
+ return failure(
5186
+ "MECHANISM_RESULT_INVALID",
5187
+ `The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
5188
+ { schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
5189
+ );
5190
+ }
5191
+ return { ok: true, data: result };
5192
+ }
5193
+ function failure(code, message, details) {
5194
+ return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
5195
+ }
5196
+ function candidateBytes(content) {
5197
+ return Buffer.from(content ?? "", "utf8");
5198
+ }
5199
+ function candidateByteDigest(content) {
5200
+ return (0, import_node_crypto4.createHash)("sha256").update(candidateBytes(content)).digest("hex");
5201
+ }
5202
+ function rawDigest(value, path) {
5203
+ if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
5204
+ throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
5205
+ }
5206
+ const raw = value.slice(DIGEST_PREFIX.length);
5207
+ if (!RAW_SHA256_PATTERN.test(raw)) {
5208
+ throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
5209
+ }
5210
+ return raw;
5211
+ }
5212
+ async function resolveRealRoot(root) {
5213
+ let canonical;
5214
+ try {
5215
+ canonical = await (0, import_promises7.realpath)((0, import_node_path11.resolve)(root));
5216
+ } catch (cause) {
5217
+ return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5218
+ }
5219
+ let info;
5220
+ try {
5221
+ info = await (0, import_promises7.lstat)(canonical);
5222
+ } catch (cause) {
5223
+ return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
5224
+ }
5225
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5226
+ return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
5227
+ }
5228
+ return { ok: true, data: canonical };
5229
+ }
5230
+ async function qualifyRestructureMechanism(root) {
5231
+ if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
5232
+ return failure(
5233
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5234
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
5235
+ );
5236
+ }
5237
+ const canonical = await resolveRealRoot(root);
5238
+ if (!canonical.ok) return canonical;
5239
+ let type;
5240
+ try {
5241
+ type = (await (0, import_promises7.statfs)(canonical.data)).type;
5242
+ } catch (cause) {
5243
+ return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
5244
+ }
5245
+ if (type !== APFS_STATFS_TYPE) {
5246
+ return failure(
5247
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5248
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
5249
+ );
5250
+ }
5251
+ return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5252
+ }
5253
+ async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5254
+ const target = (0, import_node_path11.join)(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5255
+ const current = async () => (0, import_promises7.lstat)(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5256
+ let info = await current();
5257
+ if (info === null) {
5258
+ if (!options.create) {
5259
+ return failure(
5260
+ "RECOVERY_MATERIALS_MISSING",
5261
+ `No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
5262
+ );
5263
+ }
5264
+ let created = false;
5265
+ try {
5266
+ await (0, import_promises7.mkdir)(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
5267
+ created = true;
5268
+ } catch (cause) {
5269
+ if (cause.code !== "EEXIST") {
5270
+ return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
5271
+ }
5272
+ }
5273
+ info = await current();
5274
+ if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
5275
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5276
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5277
+ }
5278
+ if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5279
+ await (0, import_promises7.chmod)(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
5280
+ info = await current();
5281
+ if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
5282
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5283
+ }
5284
+ }
5285
+ }
5286
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5287
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5288
+ }
5289
+ if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5290
+ return failure(
5291
+ "MECHANISM_ROOT_UNSAFE",
5292
+ `${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
5293
+ );
5294
+ }
5295
+ return { ok: true, data: target };
5296
+ }
5297
+ async function createRestructureRootBinding(canonicalRoot) {
5298
+ try {
5299
+ const module2 = await loadFoundationModule();
5300
+ return { ok: true, data: await module2.createFilesystemRootBinding(canonicalRoot) };
5301
+ } catch (cause) {
5302
+ return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
5303
+ }
5304
+ }
5305
+ function toOperation(candidate) {
5306
+ const expected = candidate.original.exists ? {
5307
+ exists: true,
5308
+ sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
5309
+ size: candidate.original.size,
5310
+ mode: candidate.original.mode
5311
+ } : { exists: false };
5312
+ if (candidate.action === "delete") {
5313
+ return { path: candidate.path, action: "delete", expected, next: null };
5314
+ }
5315
+ const bytes = candidateBytes(candidate.content);
5316
+ const declared = rawDigest(candidate.sha256, candidate.path);
5317
+ if (declared !== candidateByteDigest(candidate.content)) {
5318
+ throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
5319
+ }
5320
+ return {
5321
+ path: candidate.path,
5322
+ action: candidate.action,
5323
+ expected,
5324
+ next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
5325
+ };
5326
+ }
5327
+ async function buildFileSetApplyRequest(canonicalRoot, plan) {
5328
+ if (plan.candidates.length === 0) {
5329
+ return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
5330
+ }
5331
+ const binding = await createRestructureRootBinding(canonicalRoot);
5332
+ if (!binding.ok) return binding;
5333
+ let operations;
5334
+ try {
5335
+ operations = plan.candidates.map(toOperation);
5336
+ } catch (cause) {
5337
+ return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
5338
+ }
5339
+ return {
5340
+ ok: true,
5341
+ data: {
5342
+ schemaVersion: 1,
5343
+ kind: "skill-family.file-set-apply-request",
5344
+ operationId: plan.operation_id,
5345
+ root: canonicalRoot,
5346
+ rootBinding: binding.data,
5347
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5348
+ allowAdjacentStaging: true,
5349
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5350
+ validationTimeoutMs: plan.validation_timeout_ms,
5351
+ operations
5352
+ }
5353
+ };
5354
+ }
5355
+ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5356
+ const request = await buildFileSetApplyRequest(canonicalRoot, plan);
5357
+ if (!request.ok) return request;
5358
+ const module2 = await loadFoundationModule();
5359
+ let raw;
5360
+ try {
5361
+ raw = await module2.applyFileSet(request.data, { validate: options.validate });
5362
+ } catch (cause) {
5363
+ return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
5364
+ }
5365
+ return await verifyMechanismResult(raw);
5366
+ }
5367
+ async function observeRestructureJournal(canonicalRoot) {
5368
+ const journalRoot = (0, import_node_path11.join)(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5369
+ const module2 = await loadFoundationModule();
5370
+ try {
5371
+ return { ok: true, data: await module2.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
5372
+ } catch (cause) {
5373
+ return failure(
5374
+ "MAINTENANCE_OBSERVATION_FAILED",
5375
+ `The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
5376
+ );
5377
+ }
5378
+ }
5379
+ async function recoverRestructureFileSet(canonicalRoot, plan, options) {
5380
+ if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
5381
+ return failure(
5382
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
5383
+ "restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
5384
+ );
5385
+ }
5386
+ const binding = await createRestructureRootBinding(canonicalRoot);
5387
+ if (!binding.ok) return binding;
5388
+ const observation = await observeRestructureJournal(canonicalRoot);
5389
+ if (!observation.ok) return observation;
5390
+ const maintenance = {
5391
+ observation: observation.data,
5392
+ confirmAllParticipantsStopped: true,
5393
+ confirmExclusiveMaintenance: true
5394
+ };
5395
+ const request = {
5396
+ schemaVersion: 1,
5397
+ kind: "skill-family.file-set-recovery-request",
5398
+ operationId: plan.operation_id,
5399
+ root: canonicalRoot,
5400
+ rootBinding: binding.data,
5401
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5402
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5403
+ allowAdjacentStaging: true,
5404
+ maintenance
5405
+ };
5406
+ const module2 = await loadFoundationModule();
5407
+ let raw;
5408
+ try {
5409
+ raw = await module2.recoverFileSet(request);
5410
+ } catch (cause) {
5411
+ return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
5412
+ }
5413
+ return await verifyMechanismResult(raw);
5414
+ }
5415
+ async function pruneRestructureFileSet(canonicalRoot, plan, options) {
5416
+ const binding = await createRestructureRootBinding(canonicalRoot);
5417
+ if (!binding.ok) return binding;
5418
+ const request = {
5419
+ schemaVersion: 1,
5420
+ kind: "skill-family.file-set-prune-request",
5421
+ operationId: plan.operation_id,
5422
+ root: canonicalRoot,
5423
+ rootBinding: binding.data,
5424
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5425
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
5426
+ };
5427
+ if (options.allParticipantsStopped && options.exclusiveMaintenance) {
5428
+ const observation = await observeRestructureJournal(canonicalRoot);
5429
+ if (!observation.ok) return observation;
5430
+ request.maintenance = {
5431
+ observation: observation.data,
5432
+ confirmAllParticipantsStopped: true,
5433
+ confirmExclusiveMaintenance: true
5434
+ };
5435
+ }
5436
+ const module2 = await loadFoundationModule();
5437
+ let raw;
5438
+ try {
5439
+ raw = await module2.pruneFileSetRecovery(request);
5440
+ } catch (cause) {
5441
+ return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
5442
+ }
5443
+ return await verifyMechanismResult(raw);
5444
+ }
5445
+ function validationState(validation) {
5446
+ return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
5447
+ }
5448
+ function errorKinds(result) {
5449
+ return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
5450
+ }
5451
+ function applyProjection(result) {
5452
+ const kinds = errorKinds(result);
5453
+ if (result.outcome === "committed") {
5454
+ if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
5455
+ return {
5456
+ code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
5457
+ 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.",
5458
+ ok: false,
5459
+ rerunApplyPermitted: false
5460
+ };
5461
+ }
5462
+ const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
5463
+ return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
5464
+ code: "APPLY_INCOMPLETE",
5465
+ message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
5466
+ ok: false,
5467
+ rerunApplyPermitted: false
5468
+ };
5469
+ }
5470
+ const codes = {
5471
+ "commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
5472
+ "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."],
5473
+ "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."]
5474
+ };
5475
+ const mapped = codes[result.outcome];
5476
+ if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
5477
+ if (result.outcome === "rejected") {
5478
+ const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
5479
+ return {
5480
+ code: "APPLY_REJECTED",
5481
+ 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.",
5482
+ ok: false,
5483
+ rerunApplyPermitted: !identityTaken
5484
+ };
5485
+ }
5486
+ return {
5487
+ code: "APPLY_UNEXPECTED_OUTCOME",
5488
+ message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
5489
+ ok: false,
5490
+ rerunApplyPermitted: false
5491
+ };
5492
+ }
5493
+ function recoverProjection(result) {
5494
+ const reading = (() => {
5495
+ switch (result.outcome) {
5496
+ case "already-committed":
5497
+ return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
5498
+ case "already-rolled-back":
5499
+ return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
5500
+ case "rolled-back":
5501
+ return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
5502
+ case "pruned":
5503
+ return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
5504
+ case "already-pruned":
5505
+ return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
5506
+ case "commit-unconfirmed":
5507
+ 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 };
5508
+ case "recovery-required":
5509
+ return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
5510
+ case "rejected":
5511
+ return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
5512
+ default:
5513
+ return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
5514
+ }
5515
+ })();
5516
+ return { ...reading, rerunApplyPermitted: false };
5517
+ }
5518
+ function pruneProjection(result) {
5519
+ const reading = (() => {
5520
+ switch (result.outcome) {
5521
+ case "pruned":
5522
+ return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
5523
+ case "already-pruned":
5524
+ return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
5525
+ case "rejected":
5526
+ return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
5527
+ case "recovery-required":
5528
+ 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 };
5529
+ default:
5530
+ return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
5531
+ }
5532
+ })();
5533
+ return { ...reading, rerunApplyPermitted: false };
5534
+ }
5535
+ function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
5536
+ const base = {
5537
+ foundation: result,
5538
+ planPath,
5539
+ planDigest,
5540
+ operation: result.operation,
5541
+ outcome: result.outcome,
5542
+ preflight: result.preflight,
5543
+ businessWrite: result.businessWrite,
5544
+ validation: result.validation,
5545
+ validationState: validationState(result.validation),
5546
+ recovery: result.recovery,
5547
+ paths: result.paths,
5548
+ errors: result.errors,
5549
+ materialPath: result.materials.relPath,
5550
+ errorKinds: errorKinds(result)
5551
+ };
5552
+ const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
5553
+ return { ...base, ...reading };
5554
+ }
5555
+ var import_node_crypto4, import_promises7, import_node_path11, 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;
5556
+ var init_restructure_file_set = __esm({
5557
+ "src/restructure-file-set.ts"() {
5558
+ "use strict";
5559
+ import_node_crypto4 = require("crypto");
5560
+ import_promises7 = require("fs/promises");
5561
+ import_node_path11 = require("path");
5562
+ RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
5563
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
5564
+ RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
5565
+ RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
5566
+ RESTRUCTURE_QUALIFIED_ARCH = "arm64";
5567
+ RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
5568
+ APFS_STATFS_TYPE = 26;
5569
+ DIGEST_PREFIX = "sha256:";
5570
+ RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5571
+ FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
5572
+ CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
5573
+ FILE_SET_RESULT_OBJECT = "file-set-result";
5574
+ APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
5575
+ }
5576
+ });
5577
+
5578
+ // src/restructure.ts
5579
+ function digestBytes(value) {
5580
+ return `sha256:${(0, import_node_crypto5.createHash)("sha256").update(value).digest("hex")}`;
5581
+ }
5582
+ function canonicalJson(value) {
5583
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
5584
+ if (value && typeof value === "object") {
5585
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
5586
+ }
5587
+ return JSON.stringify(value);
5588
+ }
5589
+ function digestRestructureValue(value) {
5590
+ return digestBytes(canonicalJson(value));
5591
+ }
5592
+ function normalizeRelativePath2(value) {
5593
+ if (!value || value.includes("\0") || (0, import_node_path12.isAbsolute)(value)) return void 0;
5594
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5595
+ if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5596
+ return normalized;
5597
+ }
5598
+ function isPathAllowed(path, allowed) {
5599
+ return allowed.some((entry) => {
5600
+ const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
5601
+ return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
5602
+ });
5603
+ }
5604
+ async function readContainedFileWithMode(root, path) {
5605
+ const normalized = normalizeRelativePath2(path);
5606
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5607
+ const absoluteRoot = (0, import_node_path12.resolve)(root);
5608
+ const absolutePath = (0, import_node_path12.resolve)(absoluteRoot, normalized);
5609
+ if ((0, import_node_path12.relative)(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
5610
+ try {
5611
+ const info = await (0, import_promises8.lstat)(absolutePath);
5612
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
5613
+ return { buffer: await (0, import_promises8.readFile)(absolutePath), mode: info.mode & MAX_POSIX_MODE };
5614
+ } catch (error) {
5615
+ if (error.code === "ENOENT") return void 0;
5616
+ throw error;
5617
+ }
5618
+ }
5619
+ async function readContainedFile(root, path) {
5620
+ return (await readContainedFileWithMode(root, path))?.buffer;
5621
+ }
5622
+ async function snapshotFile(root, path) {
5623
+ const normalized = normalizeRelativePath2(path);
5624
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5625
+ const contained = await readContainedFileWithMode(root, normalized);
5626
+ return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
5627
+ path: normalized,
5628
+ exists: true,
5629
+ sha256: digestBytes(contained.buffer),
5630
+ size: contained.buffer.byteLength,
5631
+ mode: contained.mode
5632
+ };
5633
+ }
5634
+ function sameSnapshot(left, right) {
5635
+ return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
5636
+ }
5637
+ async function configSnapshot(root) {
5638
+ return snapshotFile(root, "artifact-graph.config.yaml");
5639
+ }
5640
+ async function loadRestructureContract(name) {
5641
+ return loadContract((0, import_node_path12.join)(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
5642
+ }
5643
+ async function validateDomainContract(name, value) {
5644
+ const contract = await loadRestructureContract(name);
5645
+ return validateContractAgainstSchema(value, contract).errors;
5646
+ }
5647
+ function occurrenceKey(edge2) {
5648
+ return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
5649
+ }
5650
+ function relationOccurrences(graph) {
5651
+ const counts = /* @__PURE__ */ new Map();
5652
+ return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
5653
+ const key = occurrenceKey(edge2);
5654
+ const occurrence = (counts.get(key) ?? 0) + 1;
5655
+ counts.set(key, occurrence);
5656
+ return {
5657
+ from: edge2.from,
5658
+ to: edge2.to,
5659
+ kind: edge2.kind,
5660
+ source: edge2.source,
5661
+ source_path: edge2.sourcePath,
5662
+ source_line: edge2.sourceLine,
5663
+ occurrence
5664
+ };
5665
+ });
5666
+ }
5667
+ function relationKey(value) {
5668
+ return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
5669
+ }
5670
+ function acceptanceCriteria(node) {
5671
+ const raw = node.attrs?.acceptanceCriteria;
5672
+ if (!Array.isArray(raw)) return [];
5673
+ return raw.flatMap((item, index) => {
5674
+ if (typeof item === "string") {
5675
+ const match = /\b(AC\d+)\b/.exec(item);
5676
+ return [match?.[1] ?? `AC${index + 1}`];
5677
+ }
5678
+ if (item && typeof item === "object") {
5679
+ const record = item;
5680
+ const value = String(record.id ?? record.code ?? "").trim();
5681
+ return value ? [value] : [`AC${index + 1}`];
5682
+ }
5683
+ return [`AC${index + 1}`];
5684
+ });
5685
+ }
5686
+ function spanFor(buffer, path, range) {
5687
+ return {
5688
+ path,
5689
+ start_byte: range.startByte,
5690
+ end_byte: range.endByte,
5691
+ sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
5692
+ };
5693
+ }
5694
+ function mappingTemplate(request, requestDigest, config, sources, unresolved) {
5695
+ return {
5696
+ schema_version: "1.0",
5697
+ request,
5698
+ request_digest: requestDigest,
5699
+ config_snapshot: config,
5700
+ sources: sources.map((source) => ({
5701
+ type: source.type,
5702
+ id: source.id,
5703
+ path: source.path,
5704
+ snapshot: source.snapshot,
5705
+ disposition: "preserved"
5706
+ })),
5707
+ targets: [],
5708
+ content_moves: [],
5709
+ identity_map: [],
5710
+ criterion_map: [],
5711
+ relation_map: [],
5712
+ prose_edits: [],
5713
+ file_headers: [],
5714
+ unresolved
5715
+ };
5716
+ }
5717
+ async function inspectRestructure(root, input) {
5718
+ const schemaErrors = await validateDomainContract("request", input);
5719
+ if (schemaErrors.length > 0) {
5720
+ return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
5721
+ }
5722
+ const request = input;
5723
+ const requestDigest = digestRestructureValue(request);
5724
+ const schema = await loadConfig(root);
5725
+ const graph = await scanArtifacts(root, schema);
5726
+ const allOccurrences = relationOccurrences(graph);
5727
+ const blockers = [];
5728
+ const unresolved = [];
5729
+ const inspected = [];
5730
+ for (const requested of request.sources) {
5731
+ const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
5732
+ if (candidates.length !== 1) {
5733
+ blockers.push({
5734
+ code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
5735
+ 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`,
5736
+ ...requested.path ? { path: requested.path } : {}
5737
+ });
5738
+ continue;
5739
+ }
5740
+ const node = candidates[0];
5741
+ const raw = await readContainedFile(root, node.path);
5742
+ if (!raw) {
5743
+ blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
5744
+ continue;
5745
+ }
5746
+ const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
5747
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
5748
+ blockers.push(...boundary.blockers);
5749
+ const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
5750
+ const uid = `${node.type}:${node.code}`;
5751
+ inspected.push({
5752
+ type: node.type,
5753
+ id: node.code,
5754
+ uid,
5755
+ path: node.path,
5756
+ title: node.title,
5757
+ snapshot: await snapshotFile(root, node.path),
5758
+ ...recordSpan ? {
5759
+ record_span: recordSpan,
5760
+ content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
5761
+ } : {},
5762
+ surrounding_spans: recordSpan ? [
5763
+ ...recordSpan.start_byte > 0 ? [{
5764
+ ...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
5765
+ content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
5766
+ }] : [],
5767
+ ...recordSpan.end_byte < raw.byteLength ? [{
5768
+ ...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
5769
+ content: raw.subarray(recordSpan.end_byte).toString("utf8")
5770
+ }] : []
5771
+ ] : [],
5772
+ acceptance_criteria: acceptanceCriteria(node),
5773
+ incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
5774
+ outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
5775
+ });
5776
+ }
5777
+ if (request.numbering_policy?.mode === "configured-next-available") {
5778
+ unresolved.push({
5779
+ code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
5780
+ message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
5781
+ });
5782
+ }
5783
+ mergeFindings(unresolved, await scanUnsupportedReferences(
5784
+ root,
5785
+ [...new Set(inspected.map((item) => item.path))],
5786
+ []
5787
+ ));
5788
+ const config = await configSnapshot(root);
5789
+ const affectedPaths = new Set(inspected.map((item) => item.path));
5790
+ for (const source of inspected) {
5791
+ for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
5792
+ }
5793
+ const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
5794
+ const inspection = {
5795
+ schema_version: "1.0",
5796
+ request,
5797
+ request_digest: requestDigest,
5798
+ config_snapshot: config,
5799
+ sources: inspected,
5800
+ affected_files: affectedFiles,
5801
+ relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
5802
+ blockers,
5803
+ unresolved,
5804
+ mapping_template: {}
5805
+ };
5806
+ inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
5807
+ return { ok: true, data: inspection };
5808
+ }
5809
+ function finding(code, message, path, line) {
5810
+ return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
5811
+ }
5812
+ async function verifySnapshot(root, expected, blockers) {
5813
+ const normalized = normalizeRelativePath2(expected.path);
5814
+ if (!normalized) {
5815
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
5816
+ return void 0;
5817
+ }
5818
+ const actual = await snapshotFile(root, normalized);
5819
+ if (!sameSnapshot(actual, { ...expected, path: normalized })) {
5820
+ blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
5821
+ }
5822
+ return actual;
5823
+ }
5824
+ function validateSpan(buffer, span, blockers) {
5825
+ if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
5826
+ blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
5827
+ return void 0;
5828
+ }
5829
+ const fragment = buffer.subarray(span.start_byte, span.end_byte);
5830
+ if (digestBytes(fragment) !== span.sha256) {
5831
+ blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
5832
+ return void 0;
5833
+ }
5834
+ return fragment;
5835
+ }
5836
+ function rangesCover(range, moves) {
5837
+ 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);
5838
+ let cursor = range.startByte;
5839
+ for (const interval of intervals) {
5840
+ if (interval.start > cursor) return false;
5841
+ cursor = Math.max(cursor, interval.end);
5842
+ }
5843
+ return cursor >= range.endByte;
5844
+ }
5845
+ function edgeDisplay(edge2) {
5846
+ return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
5847
+ }
5848
+ function graphDiff(before, after) {
5849
+ const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
5850
+ const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
5851
+ const beforeEdges = new Set(before.edges.map(edgeDisplay));
5852
+ const afterEdges = new Set(after.edges.map(edgeDisplay));
5853
+ return {
5854
+ added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
5855
+ removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
5856
+ added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
5857
+ removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
5858
+ };
5859
+ }
5860
+ function issueIdentity(issue2) {
5861
+ const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
5862
+ return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
5863
+ }
5864
+ function readableDiff(path, oldContent, newContent) {
5865
+ const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
5866
+ const newLines = newContent?.split(/(?<=\n)/) ?? [];
5867
+ if (oldContent === newContent) return "";
5868
+ return [
5869
+ `--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
5870
+ `+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
5871
+ ...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
5872
+ ...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
5873
+ ].join("\n");
5874
+ }
5875
+ function findRelativeLinks(fragment) {
5876
+ const found = /* @__PURE__ */ new Set();
5877
+ const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
5878
+ let match;
5879
+ while ((match = pattern.exec(fragment)) !== null) {
5880
+ const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
5881
+ if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
5882
+ }
5883
+ return [...found].sort();
5884
+ }
5885
+ function footnoteReferenceLabels(text) {
5886
+ const labels = /* @__PURE__ */ new Set();
5887
+ const pattern = /\[\^([^\]\s]+)\](?!:)/g;
5888
+ let match;
5889
+ while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
5890
+ return [...labels].sort();
5891
+ }
5892
+ function footnoteDefinition(label) {
5893
+ return `[^${label}]:`;
5894
+ }
5895
+ function splitMarkdownTarget(target) {
5896
+ const cleaned = target.trim().replace(/^<|>$/g, "");
5897
+ const hash = cleaned.indexOf("#");
5898
+ return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
5899
+ }
5900
+ async function pathExists2(absolutePath) {
5901
+ try {
5902
+ await (0, import_promises8.lstat)(absolutePath);
5903
+ return true;
5904
+ } catch {
5905
+ return false;
5906
+ }
5907
+ }
5908
+ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
5909
+ const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
5910
+ const migrationNames = new Set(migrationPaths.map((path) => import_node_path12.posix.basename(path)));
5911
+ const directories = new Set(migrationPaths.map((path) => import_node_path12.posix.dirname(path)));
5912
+ const findings = [];
5913
+ async function visit(directory) {
5914
+ for (const entry of await (0, import_promises8.readdir)(directory, { withFileTypes: true })) {
5915
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
5916
+ const absolute = (0, import_node_path12.join)(directory, entry.name);
5917
+ if (entry.isDirectory()) {
5918
+ await visit(absolute);
5919
+ continue;
5920
+ }
5921
+ if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
5922
+ const path = (0, import_node_path12.relative)(root, absolute).replace(/\\/g, "/");
5923
+ const raw = await (0, import_promises8.readFile)(absolute, "utf8");
5924
+ const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
5925
+ const lines = raw.split(/\r?\n/);
5926
+ for (const [index, line] of lines.entries()) {
5927
+ const lineNumber = index + 1;
5928
+ if (MARKDOWN_FILE_SUFFIX.test(path)) {
5929
+ const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
5930
+ let match;
5931
+ while ((match = pattern.exec(line)) !== null) {
5932
+ const literal = match[0];
5933
+ const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
5934
+ if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
5935
+ if (!migrationNames.has(import_node_path12.posix.basename(linkPath))) continue;
5936
+ const resolved = normalizeRelativePath2(import_node_path12.posix.join(import_node_path12.posix.dirname(path), linkPath));
5937
+ if (!resolved || targetPaths.includes(resolved)) continue;
5938
+ if (anchor) {
5939
+ findings.push(finding(
5940
+ "ANCHOR_REFERENCE_UNRESOLVED",
5941
+ `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`,
5942
+ path,
5943
+ lineNumber
5944
+ ));
5945
+ } else if (!await pathExists2((0, import_node_path12.resolve)(root, resolved))) {
5946
+ findings.push(finding(
5947
+ "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
5948
+ `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`,
5949
+ path,
5950
+ lineNumber
5951
+ ));
5952
+ }
5953
+ }
5954
+ }
5955
+ if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
5956
+ const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
5957
+ const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
5958
+ if (directoryLiteral) {
5959
+ findings.push(finding(
5960
+ "RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
5961
+ `A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
5962
+ path,
5963
+ lineNumber
5964
+ ));
5965
+ }
5966
+ }
5967
+ }
5968
+ }
5969
+ }
5970
+ await visit((0, import_node_path12.resolve)(root));
5971
+ const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
5972
+ return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
5973
+ }
5974
+ function mergeFindings(target, additions) {
5975
+ const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
5976
+ for (const item of additions) {
5977
+ const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
5978
+ if (seen.has(key)) continue;
5979
+ seen.add(key);
5980
+ target.push(item);
5981
+ }
5982
+ }
5983
+ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
5984
+ const results = [];
5985
+ async function visit(directory) {
5986
+ for (const entry of await (0, import_promises8.readdir)(directory, { withFileTypes: true })) {
5987
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
5988
+ const absolute = (0, import_node_path12.join)(directory, entry.name);
5989
+ if (entry.isDirectory()) {
5990
+ await visit(absolute);
5991
+ } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
5992
+ const path = (0, import_node_path12.relative)(root, absolute).replace(/\\/g, "/");
5993
+ if (excludedPaths.has(path)) continue;
5994
+ const raw = await (0, import_promises8.readFile)(absolute, "utf8");
5995
+ raw.split(/\r?\n/).forEach((line, index) => {
5996
+ for (const reference of references) {
5997
+ if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
5998
+ }
5999
+ });
6000
+ }
6001
+ }
6002
+ }
6003
+ await visit((0, import_node_path12.resolve)(root));
6004
+ return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6005
+ }
6006
+ function expectedRelationTargets(mapping) {
6007
+ return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
6008
+ }
6009
+ function relationTriples(graph) {
6010
+ return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
6011
+ }
6012
+ function formatMode(value) {
6013
+ return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
6014
+ }
6015
+ function isPosixFileMode(value) {
6016
+ return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
6017
+ }
6018
+ function modeIsUsableAtApply(mode, umask) {
6019
+ return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
6020
+ }
6021
+ function createModeForUmask(umask) {
6022
+ return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
6023
+ }
6024
+ function planningUmask() {
6025
+ return process.umask() & MAX_POSIX_MODE;
6026
+ }
6027
+ function restructureBoundaryFindings(operations, limits) {
6028
+ const findings = [];
6029
+ if (operations.length === 0) {
6030
+ findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
6031
+ return findings;
6032
+ }
6033
+ if (operations.length > limits.max_operations) {
6034
+ findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
6035
+ }
6036
+ const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
6037
+ if (totalBytes > limits.max_total_bytes) {
6038
+ findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
6039
+ }
6040
+ const expectedCreateMode = createModeForUmask(limits.umask);
6041
+ const applyModeContract = limits.mode_contract === "apply";
6042
+ for (const operation of operations) {
6043
+ const parent = (0, import_node_path12.dirname)(operation.path) || ".";
6044
+ if (!operation.parent_exists) {
6045
+ findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6046
+ } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
6047
+ findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
6048
+ }
6049
+ if (!isPosixFileMode(operation.mode)) {
6050
+ findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
6051
+ }
6052
+ if (!isPosixFileMode(operation.original_mode)) {
6053
+ findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
6054
+ }
6055
+ if (operation.original_exists && operation.original_mode === null) {
6056
+ findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
6057
+ }
6058
+ if (!operation.original_exists && operation.original_mode !== null) {
6059
+ findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
6060
+ }
6061
+ if (applyModeContract) {
6062
+ for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
6063
+ if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
6064
+ findings.push(finding(
6065
+ "MODE_NOT_USABLE",
6066
+ `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}`,
6067
+ operation.path
6068
+ ));
6069
+ }
6070
+ }
6071
+ if (operation.action === "create") {
6072
+ if (operation.original_exists) {
6073
+ findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
6074
+ }
6075
+ if (!applyModeContract && operation.mode !== expectedCreateMode) {
6076
+ findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
6077
+ }
6078
+ } else if (operation.action === "replace") {
6079
+ if (!operation.original_exists) {
6080
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
6081
+ } else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
6082
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
6083
+ }
6084
+ } else if (operation.mode !== null) {
6085
+ findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
6086
+ }
6087
+ }
6088
+ return findings;
6089
+ }
6090
+ async function probeDirectory(absolutePath) {
6091
+ try {
6092
+ const info = await (0, import_promises8.stat)(absolutePath);
6093
+ return { exists: info.isDirectory(), device: info.dev };
6094
+ } catch (error) {
6095
+ const code = error.code;
6096
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
6097
+ throw error;
6098
+ }
6099
+ }
6100
+ async function planRestructure(root, input) {
6101
+ const schemaErrors = await validateDomainContract("mapping", input);
6102
+ if (schemaErrors.length > 0) {
6103
+ return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
6104
+ }
6105
+ const mapping = input;
6106
+ const blockers = [];
6107
+ const unresolved = [...mapping.unresolved];
6108
+ const requestErrors = await validateDomainContract("request", mapping.request);
6109
+ if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
6110
+ if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
6111
+ const currentConfig = await configSnapshot(root);
6112
+ if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
6113
+ const schema = await loadConfig(root);
6114
+ const beforeGraph = await scanArtifacts(root, schema);
6115
+ const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
6116
+ const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
6117
+ const seenSourceUids = /* @__PURE__ */ new Set();
6118
+ for (const source of mapping.sources) {
6119
+ const uid = `${source.type}:${source.id}`;
6120
+ if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
6121
+ seenSourceUids.add(uid);
6122
+ 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));
6123
+ }
6124
+ for (const requested of mapping.request.sources) {
6125
+ const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
6126
+ const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
6127
+ if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
6128
+ }
6129
+ for (const source of mapping.sources) {
6130
+ if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
6131
+ blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
6132
+ }
6133
+ }
6134
+ const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
6135
+ const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
6136
+ for (const occurrence of requiredOccurrences) {
6137
+ if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
6138
+ }
6139
+ for (const entry of mapping.relation_map) {
6140
+ 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));
6141
+ }
6142
+ const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
6143
+ const targetKeys = /* @__PURE__ */ new Set();
6144
+ const targetUids = /* @__PURE__ */ new Set();
6145
+ for (const target of mapping.targets) {
6146
+ const path = normalizeRelativePath2(target.path);
6147
+ if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
6148
+ if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
6149
+ targetKeys.add(target.key);
6150
+ 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));
6151
+ const uid = `${target.type}:${target.id}`;
6152
+ if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
6153
+ targetUids.add(uid);
6154
+ if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
6155
+ blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
6156
+ }
6157
+ 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));
6158
+ if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
6159
+ }
6160
+ for (const identity of mapping.identity_map) {
6161
+ 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}`));
6162
+ }
6163
+ for (const source of mapping.sources) {
6164
+ const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
6165
+ 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));
6166
+ 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));
6167
+ }
6168
+ const snapshots = /* @__PURE__ */ new Map();
6169
+ const buffers = /* @__PURE__ */ new Map();
6170
+ for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
6171
+ const normalized = normalizeRelativePath2(expected.path);
6172
+ if (!normalized) {
6173
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6174
+ continue;
6175
+ }
6176
+ if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
6177
+ blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
6178
+ continue;
6179
+ }
6180
+ const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
6181
+ if (actual) snapshots.set(normalized, actual);
6182
+ const raw = await readContainedFile(root, normalized);
6183
+ if (raw) buffers.set(normalized, raw);
6184
+ }
6185
+ snapshots.set(currentConfig.path, currentConfig);
6186
+ const declaredSnapshots = [
6187
+ mapping.config_snapshot,
6188
+ ...mapping.sources.map((source) => source.snapshot),
6189
+ ...mapping.targets.map((target) => target.snapshot)
6190
+ ];
6191
+ const checkedDeclaredModes = /* @__PURE__ */ new Set();
6192
+ for (const declared of declaredSnapshots) {
6193
+ const declaredMode = declared.mode ?? null;
6194
+ const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
6195
+ const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
6196
+ if (checkedDeclaredModes.has(key)) continue;
6197
+ checkedDeclaredModes.add(key);
6198
+ if (!isPosixFileMode(declaredMode)) {
6199
+ blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
6200
+ } else if (declared.exists && declaredMode === null) {
6201
+ blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
6202
+ } else if (!declared.exists && declaredMode !== null) {
6203
+ blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
6204
+ }
6205
+ }
6206
+ const moveIds = /* @__PURE__ */ new Set();
6207
+ const rangesByPath = /* @__PURE__ */ new Map();
6208
+ const fragments = /* @__PURE__ */ new Map();
6209
+ for (const move of mapping.content_moves) {
6210
+ if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
6211
+ moveIds.add(move.id);
6212
+ const sourcePath = normalizeRelativePath2(move.source.path);
6213
+ const targetPath = normalizeRelativePath2(move.target.path);
6214
+ if (!sourcePath || !buffers.has(sourcePath)) {
6215
+ blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
6216
+ continue;
6217
+ }
6218
+ if (!targetPath || !isPathAllowed(targetPath, allowed)) {
6219
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
6220
+ continue;
6221
+ }
6222
+ const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
6223
+ if (!fragment) continue;
6224
+ fragments.set(move.id, fragment);
6225
+ const pathMoves = rangesByPath.get(sourcePath) ?? [];
6226
+ for (const existing of pathMoves) {
6227
+ if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
6228
+ 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;
6229
+ if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
6230
+ }
6231
+ }
6232
+ pathMoves.push(move);
6233
+ rangesByPath.set(sourcePath, pathMoves);
6234
+ if ((0, import_node_path12.dirname)(sourcePath) !== (0, import_node_path12.dirname)(targetPath)) {
6235
+ for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6236
+ const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6237
+ if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
6238
+ }
6239
+ }
6240
+ }
6241
+ for (const source of mapping.sources) {
6242
+ const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
6243
+ const raw = buffers.get(source.path);
6244
+ if (!node || !raw) continue;
6245
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
6246
+ blockers.push(...boundary.blockers);
6247
+ 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));
6248
+ if (source.type === "feature" && source.disposition === "retired") {
6249
+ const criteria = acceptanceCriteria(node);
6250
+ const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
6251
+ 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));
6252
+ }
6253
+ }
6254
+ const candidateBuffers = /* @__PURE__ */ new Map();
6255
+ const touched = /* @__PURE__ */ new Set();
6256
+ for (const [sourcePath, moves] of rangesByPath) {
6257
+ const original = buffers.get(sourcePath);
6258
+ const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
6259
+ const chunks = [];
6260
+ let cursor = 0;
6261
+ for (const move of removals) {
6262
+ chunks.push(original.subarray(cursor, move.source.start_byte));
6263
+ cursor = move.source.end_byte;
6264
+ }
6265
+ chunks.push(original.subarray(cursor));
6266
+ candidateBuffers.set(sourcePath, Buffer.concat(chunks));
6267
+ touched.add(sourcePath);
6268
+ }
6269
+ const movesByTarget = /* @__PURE__ */ new Map();
6270
+ for (const move of mapping.content_moves) {
6271
+ const targetPath = normalizeRelativePath2(move.target.path);
6272
+ if (!targetPath || !fragments.has(move.id)) continue;
6273
+ const list = movesByTarget.get(targetPath) ?? [];
6274
+ list.push(move);
6275
+ movesByTarget.set(targetPath, list);
6276
+ }
6277
+ for (const [targetPath, moves] of movesByTarget) {
6278
+ const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
6279
+ const appended = [base];
6280
+ for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
6281
+ const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
6282
+ appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
6283
+ }
6284
+ candidateBuffers.set(targetPath, Buffer.concat(appended));
6285
+ touched.add(targetPath);
6286
+ if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
6287
+ }
6288
+ for (const header of mapping.file_headers) {
6289
+ const path = normalizeRelativePath2(header.path);
6290
+ if (!path || !isPathAllowed(path, allowed)) {
6291
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
6292
+ continue;
6293
+ }
6294
+ if (header.affected_records.length === 0 && header.content === "") {
6295
+ const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
6296
+ if (unselected.length > 0) {
6297
+ blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
6298
+ } else {
6299
+ candidateBuffers.set(path, Buffer.alloc(0));
6300
+ touched.add(path);
6301
+ }
6302
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6303
+ continue;
6304
+ }
6305
+ const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6306
+ candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
6307
+ touched.add(path);
6308
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6309
+ }
6310
+ for (const edit of mapping.prose_edits) {
6311
+ const path = normalizeRelativePath2(edit.target_path);
6312
+ const sourcePath = normalizeRelativePath2(edit.source.path);
6313
+ if (!path || !sourcePath || !buffers.has(sourcePath)) {
6314
+ blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
6315
+ continue;
6316
+ }
6317
+ if (!isPathAllowed(path, allowed)) {
6318
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
6319
+ continue;
6320
+ }
6321
+ if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
6322
+ const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6323
+ const occurrences = current.split(edit.old_text).length - 1;
6324
+ if (!edit.old_text || occurrences !== 1) {
6325
+ blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
6326
+ continue;
6327
+ }
6328
+ candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
6329
+ touched.add(path);
6330
+ }
6331
+ const candidates = [];
6332
+ const umask = planningUmask();
6333
+ for (const path of [...touched].sort()) {
6334
+ if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
6335
+ const original = buffers.get(path);
6336
+ const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
6337
+ if (original && original.equals(candidate)) continue;
6338
+ const deleteFile = candidate.byteLength === 0;
6339
+ const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
6340
+ const action = deleteFile ? "delete" : original ? "replace" : "create";
6341
+ candidates.push({
6342
+ path,
6343
+ action,
6344
+ content: deleteFile ? null : candidate.toString("utf8"),
6345
+ sha256: deleteFile ? null : digestBytes(candidate),
6346
+ mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
6347
+ original: snapshot,
6348
+ diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6349
+ });
6350
+ }
6351
+ const rootDirectory = await probeDirectory((0, import_node_path12.resolve)(root));
6352
+ const parentProbes = /* @__PURE__ */ new Map();
6353
+ for (const candidate of candidates) {
6354
+ const parent = (0, import_node_path12.dirname)(candidate.path);
6355
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory((0, import_node_path12.resolve)(root, parent)));
6356
+ }
6357
+ blockers.push(...restructureBoundaryFindings(
6358
+ candidates.map((candidate) => {
6359
+ const parent = parentProbes.get((0, import_node_path12.dirname)(candidate.path));
6360
+ return {
6361
+ path: candidate.path,
6362
+ action: candidate.action,
6363
+ original_exists: candidate.original.exists,
6364
+ original_mode: candidate.original.mode,
6365
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6366
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6367
+ mode: candidate.mode,
6368
+ parent_exists: parent.exists,
6369
+ parent_device: parent.device,
6370
+ root_device: rootDirectory.device ?? -1
6371
+ };
6372
+ }),
6373
+ {
6374
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6375
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6376
+ umask
6377
+ }
6378
+ ));
6379
+ const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
6380
+ const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
6381
+ const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
6382
+ const candidateIssues = validateGraph(afterGraph, schema);
6383
+ for (const issue2 of candidateIssues) {
6384
+ if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
6385
+ }
6386
+ const afterTriples = relationTriples(afterGraph);
6387
+ for (const expected of expectedRelationTargets(mapping)) {
6388
+ if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
6389
+ }
6390
+ for (const source of mapping.sources) {
6391
+ const uid = `${source.type}:${source.id}`;
6392
+ const present = afterGraph.nodes.some((node) => node.uid === uid);
6393
+ if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
6394
+ if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
6395
+ }
6396
+ for (const criterion of mapping.criterion_map) {
6397
+ const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
6398
+ 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));
6399
+ for (const target of criterion.targets) {
6400
+ const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
6401
+ 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));
6402
+ }
6403
+ }
6404
+ for (const header of mapping.file_headers) {
6405
+ const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
6406
+ const declaredRecords = [...header.affected_records].sort();
6407
+ 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));
6408
+ }
6409
+ const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
6410
+ for (const move of mapping.content_moves) {
6411
+ if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
6412
+ for (const path of [move.source.path, move.target.path]) {
6413
+ 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));
6414
+ }
6415
+ }
6416
+ for (const target of mapping.targets) {
6417
+ 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));
6418
+ }
6419
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6420
+ root,
6421
+ [...new Set(mapping.sources.map((source) => source.path))],
6422
+ [...new Set([
6423
+ ...mapping.targets.map((target) => target.path),
6424
+ ...mapping.content_moves.map((move) => move.target.path),
6425
+ ...mapping.file_headers.map((header) => header.path)
6426
+ ].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
6427
+ ));
6428
+ for (const move of mapping.content_moves) {
6429
+ const fragment = fragments.get(move.id);
6430
+ const sourcePath = normalizeRelativePath2(move.source.path);
6431
+ const targetPath = normalizeRelativePath2(move.target.path);
6432
+ if (!fragment || !sourcePath || !targetPath) continue;
6433
+ const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
6434
+ const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
6435
+ for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
6436
+ if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
6437
+ blockers.push(finding(
6438
+ "FOOTNOTE_DEFINITION_UNMAPPED",
6439
+ `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`,
6440
+ sourcePath
6441
+ ));
6442
+ }
6443
+ }
6444
+ const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
6445
+ const plan = {
6446
+ schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
6447
+ operation_id: (0, import_node_crypto5.randomUUID)(),
6448
+ validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6449
+ request_digest: mapping.request_digest,
6450
+ mapping_digest: digestRestructureValue(mapping),
6451
+ config_snapshot: currentConfig,
6452
+ input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
6453
+ candidates,
6454
+ graph_diff: graphDiff(beforeGraph, afterGraph),
6455
+ validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
6456
+ applicable: blockers.length === 0 && unresolved.length === 0
6457
+ };
6458
+ const planErrors = await validateDomainContract("plan", plan);
6459
+ if (planErrors.length > 0) {
6460
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
6461
+ }
6462
+ return { ok: true, data: plan };
6463
+ }
6464
+ async function gateRestructureOperationPlan(operation, plan) {
6465
+ const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
6466
+ if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
6467
+ return {
6468
+ ok: false,
6469
+ error: {
6470
+ code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
6471
+ message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
6472
+ }
6473
+ };
6474
+ }
6475
+ const errors = await validateDomainContract("plan", plan);
6476
+ if (errors.length > 0) {
6477
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
6478
+ }
6479
+ return { ok: true, data: plan };
6480
+ }
6481
+ function refusal(code, message, findings = []) {
6482
+ return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
6483
+ }
6484
+ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6485
+ const absolute = (0, import_node_path12.resolve)(planPath);
6486
+ let info;
6487
+ try {
6488
+ info = await (0, import_promises8.lstat)(absolute);
6489
+ } catch (cause) {
6490
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6491
+ }
6492
+ if (info.isSymbolicLink() || !info.isFile()) {
6493
+ return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
6494
+ }
6495
+ let bytes;
6496
+ try {
6497
+ bytes = await (0, import_promises8.readFile)(absolute);
6498
+ } catch (cause) {
6499
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6500
+ }
6501
+ let parsed;
6502
+ try {
6503
+ parsed = JSON.parse(bytes.toString("utf8"));
6504
+ } catch (cause) {
6505
+ return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
6506
+ }
6507
+ const gate = await gateRestructureOperationPlan(operation, parsed);
6508
+ if (!gate.ok) return gate;
6509
+ return { ok: true, data: { path: absolute, realPath: await (0, import_promises8.realpath)(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
6510
+ }
6511
+ function planRootIdentityFindings(document) {
6512
+ const findings = [];
6513
+ const record = (path, label) => {
6514
+ const normalized = normalizeRelativePath2(path);
6515
+ if (!normalized || normalized !== path) {
6516
+ findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
6517
+ }
6518
+ };
6519
+ record(document.plan.config_snapshot.path, "config_snapshot");
6520
+ for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
6521
+ for (const candidate of document.plan.candidates) {
6522
+ record(candidate.path, "candidate");
6523
+ record(candidate.original.path, "candidate original");
6524
+ }
6525
+ if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
6526
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6527
+ }
6528
+ const relativePlan = (0, import_node_path12.relative)(document.root, document.realPath);
6529
+ if (!relativePlan || relativePlan.startsWith("..") || (0, import_node_path12.isAbsolute)(relativePlan)) {
6530
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6531
+ }
6532
+ return findings;
6533
+ }
6534
+ async function operationBoundaries(root, plan) {
6535
+ const rootDirectory = await probeDirectory((0, import_node_path12.resolve)(root));
6536
+ const parents = /* @__PURE__ */ new Map();
6537
+ const boundaries = [];
6538
+ for (const candidate of plan.candidates) {
6539
+ const parent = (0, import_node_path12.dirname)(candidate.path) || ".";
6540
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory((0, import_node_path12.resolve)(root, parent)));
6541
+ const probe = parents.get(parent);
6542
+ boundaries.push({
6543
+ path: candidate.path,
6544
+ action: candidate.action,
6545
+ original_exists: candidate.original.exists,
6546
+ original_mode: candidate.original.mode,
6547
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6548
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6549
+ mode: candidate.mode,
6550
+ parent_exists: probe.exists,
6551
+ parent_device: probe.device,
6552
+ root_device: rootDirectory.device ?? -1
6553
+ });
6554
+ }
6555
+ return boundaries;
6556
+ }
6557
+ async function applyPreconditionFindings(root, document) {
6558
+ const findings = [];
6559
+ const plan = document.plan;
6560
+ const currentConfig = await configSnapshot(root);
6561
+ if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
6562
+ findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
6563
+ }
6564
+ for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
6565
+ const relativePlan = (0, import_node_path12.relative)(root, document.realPath).replace(/\\/g, "/");
6566
+ for (const candidate of plan.candidates) {
6567
+ if (candidate.path === relativePlan) {
6568
+ findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
6569
+ }
6570
+ if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
6571
+ findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
6572
+ }
6573
+ let original;
6574
+ try {
6575
+ original = await snapshotFile(root, candidate.path);
6576
+ } catch (cause) {
6577
+ findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
6578
+ continue;
6579
+ }
6580
+ if (!sameSnapshot(original, candidate.original)) {
6581
+ findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
6582
+ }
6583
+ if (candidate.action === "delete") continue;
6584
+ if (candidate.mode === null) {
6585
+ findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
6586
+ }
6587
+ if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
6588
+ findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
6589
+ }
6590
+ }
6591
+ findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
6592
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6593
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6594
+ umask: planningUmask(),
6595
+ mode_contract: "apply"
6596
+ }));
6597
+ return findings;
6598
+ }
6599
+ function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
6600
+ const excludedConsumers = new Set(excludedConsumerPaths);
6601
+ const addedNodes = plan.graph_diff.added_nodes;
6602
+ const removedNodes = new Set(plan.graph_diff.removed_nodes);
6603
+ const addedEdges = plan.graph_diff.added_edges;
6604
+ const removedEdges = new Set(plan.graph_diff.removed_edges);
6605
+ const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
6606
+ const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
6607
+ const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
6608
+ return async function validateCandidateState(input) {
6609
+ const schema = await loadConfig(input.root);
6610
+ const graph = await scanArtifacts(input.root, schema);
6611
+ if (input.signal.aborted) return { passed: false };
6612
+ const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6613
+ const edges = new Set(graph.edges.map(edgeDisplay));
6614
+ const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
6615
+ const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
6616
+ const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
6617
+ const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
6618
+ const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
6619
+ const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
6620
+ return { passed };
6621
+ };
6622
+ }
6623
+ async function applyRestructure(input) {
6624
+ if (input.confirmCooperativeWriters !== true) {
6625
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
6626
+ }
6627
+ const qualification = await qualifyRestructureMechanism(input.root);
6628
+ if (!qualification.ok) return qualification;
6629
+ const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
6630
+ if (!document.ok) return document;
6631
+ const plan = document.data.plan;
6632
+ if (plan.candidates.length === 0) {
6633
+ return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
6634
+ }
6635
+ if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
6636
+ return refusal(
6637
+ "PLAN_NOT_APPLICABLE",
6638
+ "The plan is not applicable: it still carries blockers or unresolved findings",
6639
+ [...plan.validation.blockers, ...plan.validation.unresolved]
6640
+ );
6641
+ }
6642
+ const identity = planRootIdentityFindings(document.data);
6643
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6644
+ const drift = await applyPreconditionFindings(qualification.data.root, document.data);
6645
+ if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
6646
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
6647
+ if (!mechanismRoot.ok) return mechanismRoot;
6648
+ const planRelPath = (0, import_node_path12.relative)(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
6649
+ const applied = await applyRestructureFileSet(qualification.data.root, plan, {
6650
+ validate: createRestructureValidationCallback(plan, [planRelPath])
6651
+ });
6652
+ if (!applied.ok) return applied;
6653
+ const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
6654
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
6655
+ }
6656
+ async function recoverRestructure(input) {
6657
+ if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
6658
+ return refusal(
6659
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
6660
+ "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
6661
+ );
6662
+ }
6663
+ const qualification = await qualifyRestructureMechanism(input.root);
6664
+ if (!qualification.ok) return qualification;
6665
+ const document = await loadRestructurePlanDocument("recover", 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 recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
6672
+ allParticipantsStopped: true,
6673
+ exclusiveMaintenance: true
6674
+ });
6675
+ if (!recovered.ok) return recovered;
6676
+ const projection = projectRestructureFileSetResult(recovered.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
+ async function pruneRestructureRecovery(input) {
6680
+ if (input.confirmCooperativeWriters !== true) {
6681
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
6682
+ }
6683
+ if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
6684
+ return refusal(
6685
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
6686
+ "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
6687
+ );
6688
+ }
6689
+ const qualification = await qualifyRestructureMechanism(input.root);
6690
+ if (!qualification.ok) return qualification;
6691
+ const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
6692
+ if (!document.ok) return document;
6693
+ const identity = planRootIdentityFindings(document.data);
6694
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6695
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
6696
+ if (!mechanismRoot.ok) return mechanismRoot;
6697
+ const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
6698
+ allParticipantsStopped: input.allParticipantsStopped,
6699
+ exclusiveMaintenance: input.exclusiveMaintenance
6700
+ });
6701
+ if (!pruned.ok) return pruned;
6702
+ const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
6703
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
6704
+ }
6705
+ var import_node_crypto5, import_promises8, import_node_path12, import_node_url2, import_meta2, 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;
6706
+ var init_restructure = __esm({
6707
+ "src/restructure.ts"() {
6708
+ "use strict";
6709
+ import_node_crypto5 = require("crypto");
6710
+ import_promises8 = require("fs/promises");
6711
+ import_node_path12 = require("path");
6712
+ import_node_url2 = require("url");
6713
+ init_index();
6714
+ init_contract_kernel();
6715
+ init_restructure_software();
6716
+ init_restructure_file_set();
6717
+ import_meta2 = {};
6718
+ RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
6719
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
6720
+ RESTRUCTURE_MAX_OPERATIONS = 1024;
6721
+ RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
6722
+ MAX_POSIX_MODE = 511;
6723
+ CREATE_MODE_BASE = 438;
6724
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : (0, import_node_path12.dirname)((0, import_node_url2.fileURLToPath)(import_meta2.url));
6725
+ CONTRACT_ROOT = (0, import_node_path12.join)(MODULE_DIRECTORY, "..", "contracts");
6726
+ SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
6727
+ TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
6728
+ MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
6729
+ RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
6730
+ MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
6731
+ SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
6732
+ }
6733
+ });
6734
+
5026
6735
  // src/index.ts
5027
6736
  var index_exports = {};
5028
6737
  __export(index_exports, {
@@ -5030,6 +6739,7 @@ __export(index_exports, {
5030
6739
  BASELINE_CONSTRAINTS: () => BASELINE_CONSTRAINTS,
5031
6740
  BASELINE_CONSTRAINTS_COUNT: () => BASELINE_CONSTRAINTS_COUNT,
5032
6741
  BASELINE_ITEMS_COUNT: () => BASELINE_ITEMS_COUNT,
6742
+ CONTRACTS_PACKAGE_NAME: () => CONTRACTS_PACKAGE_NAME,
5033
6743
  CONTRACT_ERROR_CODES: () => CONTRACT_ERROR_CODES,
5034
6744
  ContractCatalog: () => ContractCatalog,
5035
6745
  ContractError: () => ContractError,
@@ -5037,35 +6747,58 @@ __export(index_exports, {
5037
6747
  DEFAULT_MAX_CHARS: () => DEFAULT_MAX_CHARS,
5038
6748
  DEFAULT_SCHEMA: () => DEFAULT_SCHEMA,
5039
6749
  E2E_NORMALIZER_CONFIG: () => E2E_NORMALIZER_CONFIG,
6750
+ FILE_SET_RESULT_OBJECT: () => FILE_SET_RESULT_OBJECT,
6751
+ FOUNDATION_PACKAGE_NAME: () => FOUNDATION_PACKAGE_NAME,
5040
6752
  MIN_PROMPT_CHARS: () => MIN_PROMPT_CHARS,
6753
+ RESTRUCTURE_MAX_OPERATIONS: () => RESTRUCTURE_MAX_OPERATIONS,
6754
+ RESTRUCTURE_MAX_TOTAL_BYTES: () => RESTRUCTURE_MAX_TOTAL_BYTES,
6755
+ RESTRUCTURE_PLAN_SCHEMA_VERSION: () => RESTRUCTURE_PLAN_SCHEMA_VERSION,
6756
+ RESTRUCTURE_QUALIFIED_ARCH: () => RESTRUCTURE_QUALIFIED_ARCH,
6757
+ RESTRUCTURE_QUALIFIED_FILESYSTEM: () => RESTRUCTURE_QUALIFIED_FILESYSTEM,
6758
+ RESTRUCTURE_QUALIFIED_PLATFORM: () => RESTRUCTURE_QUALIFIED_PLATFORM,
6759
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH: () => RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
6760
+ RESTRUCTURE_RECOVERY_REL_PATH: () => RESTRUCTURE_RECOVERY_REL_PATH,
6761
+ RESTRUCTURE_RECOVERY_ROOT_MODE: () => RESTRUCTURE_RECOVERY_ROOT_MODE,
6762
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS: () => RESTRUCTURE_VALIDATION_TIMEOUT_MS,
5041
6763
  TARGET_ARTIFACT_TYPES: () => TARGET_ARTIFACT_TYPES,
5042
6764
  VALID_PACKET_TARGET_TYPES: () => VALID_PACKET_TARGET_TYPES,
5043
6765
  VERSION_INDEX_SCHEMA_VERSION: () => VERSION_INDEX_SCHEMA_VERSION,
5044
6766
  VERSION_LOCK_PATH: () => VERSION_LOCK_PATH,
5045
6767
  VERSION_LOCK_SCHEMA_VERSION: () => VERSION_LOCK_SCHEMA_VERSION,
5046
6768
  applyPreparedManagedHookBlocks: () => applyPreparedManagedHookBlocks,
6769
+ applyRestructure: () => applyRestructure,
6770
+ applyRestructureFileSet: () => applyRestructureFileSet,
5047
6771
  assemblePacket: () => assemblePacket,
5048
6772
  auditPackets: () => auditPackets,
5049
6773
  auditVersionLock: () => auditVersionLock,
5050
6774
  bootstrapVersionLock: () => bootstrapVersionLock,
6775
+ buildFileSetApplyRequest: () => buildFileSetApplyRequest,
5051
6776
  buildGraph: () => buildGraph,
5052
6777
  buildVersionIndex: () => buildVersionIndex,
6778
+ candidateByteDigest: () => candidateByteDigest,
5053
6779
  collectChangedPaths: () => collectChangedPaths,
5054
6780
  computeCoverageBoundary: () => computeCoverageBoundary,
5055
6781
  computeE2eCoverageStats: () => computeE2eCoverageStats,
5056
6782
  computeImpact: () => computeImpact,
5057
6783
  computeRevisionDigest: () => computeRevisionDigest,
5058
- dirname: () => import_node_path11.dirname,
6784
+ createModeForUmask: () => createModeForUmask,
6785
+ createRestructureRootBinding: () => createRestructureRootBinding,
6786
+ createRestructureValidationCallback: () => createRestructureValidationCallback,
6787
+ digestRestructureValue: () => digestRestructureValue,
6788
+ dirname: () => import_node_path13.dirname,
5059
6789
  discoverAndAuditPackets: () => discoverAndAuditPackets,
5060
6790
  discoverTargets: () => discoverTargets,
5061
6791
  doctorArtifactChain: () => doctorArtifactChain,
5062
- extname: () => import_node_path11.extname,
6792
+ ensureRestructureMechanismRoot: () => ensureRestructureMechanismRoot,
6793
+ extname: () => import_node_path13.extname,
5063
6794
  filterGraphByView: () => filterGraphByView,
5064
6795
  formatContextMarkdown: () => formatContextMarkdown,
6796
+ gateRestructureOperationPlan: () => gateRestructureOperationPlan,
5065
6797
  generateE2eRegistry: () => generateE2eRegistry,
5066
6798
  getArtifactTypeMetadata: () => getArtifactTypeMetadata,
5067
6799
  getExternalEntryInfo: () => getExternalEntryInfo,
5068
6800
  getTargetArtifactTypes: () => getTargetArtifactTypes,
6801
+ inspectRestructure: () => inspectRestructure,
5069
6802
  installManagedHookBlock: () => installManagedHookBlock,
5070
6803
  isOfficialNamespace: () => isOfficialNamespace,
5071
6804
  isPacketTargetType: () => isPacketTargetType,
@@ -5076,14 +6809,26 @@ __export(index_exports, {
5076
6809
  loadContract: () => loadContract,
5077
6810
  loadContractCatalog: () => loadContractCatalog,
5078
6811
  loadContractsFromDirectory: () => loadContractsFromDirectory,
6812
+ loadFoundationModule: () => loadFoundationModule,
6813
+ locateSoftwareRecord: () => locateSoftwareRecord,
6814
+ markdownRecordHeadings: () => markdownRecordHeadings,
5079
6815
  matchesConfiguredArtifactPath: () => matchesConfiguredArtifactPath,
5080
6816
  nextId: () => nextId,
5081
6817
  normalizeE2eLegacyArtifact: () => normalizeE2eLegacyArtifact,
5082
6818
  normalizeToCanonical: () => normalizeToCanonical,
6819
+ observeRestructureJournal: () => observeRestructureJournal,
5083
6820
  parseTargetSelector: () => parseTargetSelector,
5084
6821
  parseTargetsFile: () => parseTargetsFile,
6822
+ planRestructure: () => planRestructure,
6823
+ planningUmask: () => planningUmask,
5085
6824
  prepareManagedHookBlock: () => prepareManagedHookBlock,
6825
+ projectRestructureFileSetResult: () => projectRestructureFileSetResult,
6826
+ pruneRestructureFileSet: () => pruneRestructureFileSet,
6827
+ pruneRestructureRecovery: () => pruneRestructureRecovery,
6828
+ qualifyRestructureMechanism: () => qualifyRestructureMechanism,
5086
6829
  queryGraph: () => queryGraph,
6830
+ recoverRestructure: () => recoverRestructure,
6831
+ recoverRestructureFileSet: () => recoverRestructureFileSet,
5087
6832
  refreshVersionLock: () => refreshVersionLock,
5088
6833
  renderCoverageBoundaryMarkdown: () => renderCoverageBoundaryMarkdown,
5089
6834
  renderDoctorMarkdown: () => renderDoctorMarkdown,
@@ -5094,6 +6839,7 @@ __export(index_exports, {
5094
6839
  renderTraceVersionMarkdown: () => renderTraceVersionMarkdown,
5095
6840
  renderVersionLockAuditMarkdown: () => renderVersionLockAuditMarkdown,
5096
6841
  renderVersionLockRefreshMarkdown: () => renderVersionLockRefreshMarkdown,
6842
+ replaceSoftwareHeader: () => replaceSoftwareHeader,
5097
6843
  resolveArtifactContext: () => resolveArtifactContext,
5098
6844
  resolveArtifactGraphCli: () => resolveArtifactGraphCli,
5099
6845
  resolveArtifactTypeName: () => resolveArtifactTypeName,
@@ -5101,6 +6847,8 @@ __export(index_exports, {
5101
6847
  resolveGitHookPath: () => resolveGitHookPath,
5102
6848
  resolveMatrixEdges: () => resolveMatrixEdges,
5103
6849
  resolveNodeTimeView: () => resolveNodeTimeView,
6850
+ resolveRealRoot: () => resolveRealRoot,
6851
+ restructureBoundaryFindings: () => restructureBoundaryFindings,
5104
6852
  scanArtifacts: () => scanArtifacts,
5105
6853
  traceVersion: () => traceVersion,
5106
6854
  updateVersionLock: () => updateVersionLock,
@@ -5116,6 +6864,7 @@ __export(index_exports, {
5116
6864
  validateScenarioPrdLinkIndex: () => validateScenarioPrdLinkIndex,
5117
6865
  validateScenarioPrdLinks: () => validateScenarioPrdLinks,
5118
6866
  verifyDigest: () => verifyDigest,
6867
+ verifyMechanismResult: () => verifyMechanismResult,
5119
6868
  versionLockIssueSeverity: () => versionLockIssueSeverity,
5120
6869
  writeGraphCache: () => writeGraphCache
5121
6870
  });
@@ -5161,10 +6910,10 @@ function resolveArtifactTypeName(schema, token) {
5161
6910
  return void 0;
5162
6911
  }
5163
6912
  async function loadConfig(root) {
5164
- const configPath = (0, import_node_path11.join)(root, "artifact-graph.config.yaml");
6913
+ const configPath = (0, import_node_path13.join)(root, "artifact-graph.config.yaml");
5165
6914
  let parsed = {};
5166
6915
  try {
5167
- const raw = await (0, import_promises7.readFile)(configPath, "utf-8");
6916
+ const raw = await (0, import_promises9.readFile)(configPath, "utf-8");
5168
6917
  parsed = import_js_yaml.default.load(raw) ?? {};
5169
6918
  } catch (error) {
5170
6919
  if (error.code !== "ENOENT") {
@@ -5290,7 +7039,7 @@ function validateE2eConfig(e2e) {
5290
7039
  if (typeof runner.root !== "string" || !runner.root.trim()) {
5291
7040
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
5292
7041
  }
5293
- if ((0, import_node_path11.isAbsolute)(runner.root)) {
7042
+ if ((0, import_node_path13.isAbsolute)(runner.root)) {
5294
7043
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
5295
7044
  }
5296
7045
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -5353,14 +7102,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
5353
7102
  diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
5354
7103
  };
5355
7104
  }
5356
- async function scanArtifacts(root, schema) {
7105
+ async function scanArtifacts(root, schema, options = {}) {
5357
7106
  const config = schema ?? await loadConfig(root);
5358
7107
  const nodes = [];
5359
7108
  const edges = [];
5360
7109
  const scanDiagnostics = [];
5361
7110
  const scannedFiles = /* @__PURE__ */ new Map();
7111
+ const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
5362
7112
  for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
5363
- const files = await findFiles(root, definition.paths);
7113
+ const diskFiles = await findFiles(root, definition.paths);
7114
+ const files = [.../* @__PURE__ */ new Set([
7115
+ ...diskFiles.filter((file) => contentOverrides.get(file) !== null),
7116
+ ...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
7117
+ ])].sort();
5364
7118
  for (const file of files) {
5365
7119
  if (scannedFiles.has(file)) {
5366
7120
  const existingType = scannedFiles.get(file);
@@ -5374,7 +7128,7 @@ async function scanArtifacts(root, schema) {
5374
7128
  continue;
5375
7129
  }
5376
7130
  scannedFiles.set(file, type);
5377
- const raw = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, file), "utf-8");
7131
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await (0, import_promises9.readFile)((0, import_node_path13.join)(root, file), "utf-8");
5378
7132
  const parsed = parseFile(type, file, raw, config);
5379
7133
  const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
5380
7134
  nodes.push(...parsed.nodes);
@@ -5382,7 +7136,7 @@ async function scanArtifacts(root, schema) {
5382
7136
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
5383
7137
  }
5384
7138
  }
5385
- const absoluteRoot = (0, import_node_path11.isAbsolute)(root) ? root : (0, import_node_path11.resolve)(root);
7139
+ const absoluteRoot = (0, import_node_path13.isAbsolute)(root) ? root : (0, import_node_path13.resolve)(root);
5386
7140
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
5387
7141
  return resolveMatrixEdges(graph);
5388
7142
  }
@@ -5668,13 +7422,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
5668
7422
  const scenarioFeatureRefs = /* @__PURE__ */ new Map();
5669
7423
  const featureScenarioRefs = /* @__PURE__ */ new Map();
5670
7424
  for (const node of scenarioNodes) {
5671
- scenarioFeatureRefs.set(node.uid, relationOccurrences(node, "\u5173\u8054\u529F\u80FD", "feature"));
7425
+ scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
5672
7426
  if (!scenarioPattern.test(node.code)) {
5673
7427
  issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
5674
7428
  }
5675
7429
  }
5676
7430
  for (const node of featureNodes) {
5677
- featureScenarioRefs.set(node.uid, relationOccurrences(node, "scenarios", "scenario"));
7431
+ featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
5678
7432
  if (!featurePattern.test(node.code)) {
5679
7433
  issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
5680
7434
  }
@@ -5748,7 +7502,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5748
7502
  const indexPath = "artifacts/prd/feature-index.md";
5749
7503
  let raw = "";
5750
7504
  try {
5751
- raw = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, indexPath), "utf-8");
7505
+ raw = await (0, import_promises9.readFile)((0, import_node_path13.join)(root, indexPath), "utf-8");
5752
7506
  } catch (error) {
5753
7507
  if (error.code === "ENOENT") {
5754
7508
  return [];
@@ -5768,7 +7522,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5768
7522
  if (!feature) {
5769
7523
  return;
5770
7524
  }
5771
- const actualCount = relationOccurrences(feature, "scenarios", "scenario").length;
7525
+ const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
5772
7526
  if (actualCount !== expectedCount) {
5773
7527
  issues.push(issue(
5774
7528
  "INDEX_MISMATCH",
@@ -5996,12 +7750,12 @@ function nextId(graph, schema, type, rangeName) {
5996
7750
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
5997
7751
  }
5998
7752
  async function writeGraphCache(root, graph) {
5999
- const cacheDir = (0, import_node_path11.join)(root, ".artifact-graph");
6000
- await (0, import_promises7.mkdir)(cacheDir, { recursive: true });
6001
- await (0, import_promises7.writeFile)((0, import_node_path11.join)(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
7753
+ const cacheDir = (0, import_node_path13.join)(root, ".artifact-graph");
7754
+ await (0, import_promises9.mkdir)(cacheDir, { recursive: true });
7755
+ await (0, import_promises9.writeFile)((0, import_node_path13.join)(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
6002
7756
  `);
6003
7757
  const { default: Database } = await import("better-sqlite3");
6004
- const db = new Database((0, import_node_path11.join)(cacheDir, "graph.sqlite"));
7758
+ const db = new Database((0, import_node_path13.join)(cacheDir, "graph.sqlite"));
6005
7759
  try {
6006
7760
  db.exec(`
6007
7761
  DROP TABLE IF EXISTS nodes;
@@ -6113,7 +7867,7 @@ function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
6113
7867
  }
6114
7868
  function parseGenericMarkdown(type, path, raw, schema) {
6115
7869
  const diagnostics = [];
6116
- const ext = (0, import_node_path11.extname)(path).toLowerCase();
7870
+ const ext = (0, import_node_path13.extname)(path).toLowerCase();
6117
7871
  if (ext !== ".md" && ext !== ".markdown") {
6118
7872
  diagnostics.push(issue(
6119
7873
  "UNSUPPORTED_FORMAT",
@@ -6363,7 +8117,7 @@ function parseFeature(path, raw) {
6363
8117
  }
6364
8118
  function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
6365
8119
  const lines = raw.split(/\r?\n/);
6366
- const codeLines = markdownCodeLineMask(lines);
8120
+ const codeLines = markdownCodeLineMask2(lines);
6367
8121
  const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
6368
8122
  const starts = [];
6369
8123
  lines.forEach((line, index) => {
@@ -6469,7 +8223,7 @@ function parseDecisions(path, raw) {
6469
8223
  }
6470
8224
  function isTestFile(filePath) {
6471
8225
  const normalized = filePath.replace(/\\/g, "/");
6472
- const name = (0, import_node_path11.basename)(normalized);
8226
+ const name = (0, import_node_path13.basename)(normalized);
6473
8227
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
6474
8228
  if (/(^|\/)(tests|test|__tests__)\//.test(normalized)) return true;
6475
8229
  if (/\w+Tests?\.java$/.test(name)) return true;
@@ -6781,41 +8535,15 @@ function parseE2eTest(path, raw) {
6781
8535
  const parsed = (0, import_gray_matter.default)(raw);
6782
8536
  const data = parsed.data;
6783
8537
  const lines = raw.split(/\r?\n/);
6784
- const starts = [];
6785
- lines.forEach((line, index) => {
6786
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
6787
- if (match) {
6788
- starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
6789
- }
6790
- });
8538
+ const starts = extractE2eTestCaseStarts(lines);
6791
8539
  const nodes = [];
6792
8540
  const edges = [];
6793
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(path, (0, import_node_path11.extname)(path))).trim();
8541
+ const batch = String(data.test_batch ?? (0, import_node_path13.basename)(path, (0, import_node_path13.extname)(path))).trim();
6794
8542
  const frontmatterScenarios = toArray(data.related_scenarios).map((value) => String(value).trim()).filter(Boolean);
6795
8543
  const scopeFeatures = extractCodes(String(data.scope ?? ""), "feature");
6796
8544
  const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
6797
8545
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
6798
8546
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
6799
- if (starts.length === 0) {
6800
- const code = `${batch}:FILE`;
6801
- nodes.push({
6802
- type: "e2e_test",
6803
- code,
6804
- title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
6805
- path,
6806
- line: 1,
6807
- attrs: {
6808
- ...data,
6809
- testCaseId: "FILE",
6810
- fileLevelOnly: true,
6811
- tcFields: {},
6812
- blockText: raw,
6813
- coveredFeatures: [],
6814
- coveredScenarios: []
6815
- }
6816
- });
6817
- addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
6818
- }
6819
8547
  for (let index = 0; index < starts.length; index += 1) {
6820
8548
  const start = starts[index];
6821
8549
  const end = starts[index + 1]?.index ?? lines.length;
@@ -6841,6 +8569,16 @@ function parseE2eTest(path, raw) {
6841
8569
  }
6842
8570
  return { nodes, edges };
6843
8571
  }
8572
+ function extractE2eTestCaseStarts(lines) {
8573
+ const codeLines = markdownCodeLineMask2(lines);
8574
+ return lines.flatMap((line, index) => {
8575
+ if (codeLines[index]) {
8576
+ return [];
8577
+ }
8578
+ const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
8579
+ return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
8580
+ });
8581
+ }
6844
8582
  function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
6845
8583
  for (const scenario of scenarios) {
6846
8584
  edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
@@ -6863,7 +8601,7 @@ function parseE2eRegistry(path, raw) {
6863
8601
  data = { parseError: error.message };
6864
8602
  }
6865
8603
  return {
6866
- nodes: [{ type: "e2e_registry", code: (0, import_node_path11.basename)(path, (0, import_node_path11.extname)(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
8604
+ nodes: [{ type: "e2e_registry", code: (0, import_node_path13.basename)(path, (0, import_node_path13.extname)(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
6867
8605
  edges: []
6868
8606
  };
6869
8607
  }
@@ -7625,7 +9363,7 @@ function matchExplicitRelationFieldLine(line, label) {
7625
9363
  const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
7626
9364
  return match?.[1] ?? null;
7627
9365
  }
7628
- function markdownCodeLineMask(lines) {
9366
+ function markdownCodeLineMask2(lines) {
7629
9367
  const result = new Array(lines.length).fill(false);
7630
9368
  let fence;
7631
9369
  lines.forEach((line, index) => {
@@ -7670,7 +9408,7 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
7670
9408
  });
7671
9409
  return result;
7672
9410
  }
7673
- function relationOccurrences(node, field, targetType) {
9411
+ function relationOccurrences2(node, field, targetType) {
7674
9412
  const relationRecord = asRecord(node.attrs?.relationOccurrences);
7675
9413
  const rawOccurrences = toArray(relationRecord[field]);
7676
9414
  return rawOccurrences.flatMap((value) => {
@@ -7869,6 +9607,9 @@ function validateE2eRegistry(graph) {
7869
9607
  }
7870
9608
  const actualNodes = byPath.get(file) ?? [];
7871
9609
  if (actualNodes.length === 0) {
9610
+ if (Number(batch.test_case_count ?? NaN) === 0) {
9611
+ continue;
9612
+ }
7872
9613
  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" }));
7873
9614
  continue;
7874
9615
  }
@@ -7889,31 +9630,21 @@ function validateE2eRegistry(graph) {
7889
9630
  async function validateExecutableTraceability(root, config) {
7890
9631
  const issues = [];
7891
9632
  const schema = config ?? await loadConfig(root);
7892
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
7893
- let e2eFiles;
7894
- try {
7895
- e2eFiles = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => (0, import_node_path11.join)(e2eDir, name));
7896
- } catch {
9633
+ const e2eFiles = await findConfiguredE2eFiles(root, schema);
9634
+ if (e2eFiles.length === 0) {
7897
9635
  return [];
7898
9636
  }
7899
9637
  const mdToRef = /* @__PURE__ */ new Map();
7900
9638
  const allMdTcInfo = /* @__PURE__ */ new Map();
7901
9639
  const tcKeyToFields = /* @__PURE__ */ new Map();
7902
9640
  const mdBatches = /* @__PURE__ */ new Set();
7903
- for (const filePath of e2eFiles) {
7904
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
7905
- const relPath = (0, import_node_path11.relative)(root, filePath).split("\\").join("/");
9641
+ for (const relPath of e2eFiles) {
9642
+ const raw = await (0, import_promises9.readFile)((0, import_node_path13.join)(root, relPath), "utf-8");
7906
9643
  const parsed = (0, import_gray_matter.default)(raw);
7907
9644
  const data = parsed.data;
7908
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(filePath, (0, import_node_path11.extname)(filePath))).trim();
9645
+ const batch = String(data.test_batch ?? (0, import_node_path13.basename)(relPath, (0, import_node_path13.extname)(relPath))).trim();
7909
9646
  const lines = raw.split(/\r?\n/);
7910
- const tcStarts = [];
7911
- lines.forEach((line, index) => {
7912
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
7913
- if (match) {
7914
- tcStarts.push({ id: match[1], line: index + 1, index });
7915
- }
7916
- });
9647
+ const tcStarts = extractE2eTestCaseStarts(lines);
7917
9648
  for (let i = 0; i < tcStarts.length; i += 1) {
7918
9649
  const start = tcStarts[i];
7919
9650
  const end = tcStarts[i + 1]?.index ?? lines.length;
@@ -7950,10 +9681,10 @@ async function validateExecutableTraceability(root, config) {
7950
9681
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
7951
9682
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
7952
9683
  for (const specFile of specFiles) {
7953
- const fullSpecPath = (0, import_node_path11.join)(root, specFile);
9684
+ const fullSpecPath = (0, import_node_path13.join)(root, specFile);
7954
9685
  let content;
7955
9686
  try {
7956
- content = await (0, import_promises7.readFile)(fullSpecPath, "utf-8");
9687
+ content = await (0, import_promises9.readFile)(fullSpecPath, "utf-8");
7957
9688
  } catch {
7958
9689
  continue;
7959
9690
  }
@@ -8032,7 +9763,7 @@ async function validateExecutableTraceability(root, config) {
8032
9763
  if (entry.testId) {
8033
9764
  let content;
8034
9765
  try {
8035
- content = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, normalizedRefFile), "utf-8");
9766
+ content = await (0, import_promises9.readFile)((0, import_node_path13.join)(root, normalizedRefFile), "utf-8");
8036
9767
  } catch {
8037
9768
  continue;
8038
9769
  }
@@ -8060,7 +9791,7 @@ async function validateExecutableTraceability(root, config) {
8060
9791
  }
8061
9792
  continue;
8062
9793
  }
8063
- if (!mdToRef.has(tcKey) && !await hasMarkdownTc(tcKey, e2eDir)) {
9794
+ if (!allMdTcInfo.has(tcKey)) {
8064
9795
  for (const ann of annotations) {
8065
9796
  issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
8066
9797
  }
@@ -8209,34 +9940,10 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8209
9940
  let withExecutableRef = 0;
8210
9941
  const statusBreakdown = {};
8211
9942
  const chainTypeBreakdown = {};
8212
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
8213
- const tcFieldsMap = /* @__PURE__ */ new Map();
8214
- let e2eFiles;
8215
- try {
8216
- e2eFiles = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => (0, import_node_path11.join)(e2eDir, name));
8217
- } catch {
8218
- e2eFiles = [];
8219
- }
8220
- for (const filePath of e2eFiles) {
8221
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
8222
- const lines = raw.split(/\r?\n/);
8223
- const tcStarts = [];
8224
- lines.forEach((line, index) => {
8225
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8226
- if (match) {
8227
- tcStarts.push({ id: match[1], index });
8228
- }
8229
- });
8230
- const parsed = (0, import_gray_matter.default)(raw);
8231
- const batch = String(parsed.data.test_batch ?? (0, import_node_path11.basename)(filePath, (0, import_node_path11.extname)(filePath))).trim();
8232
- for (let i = 0; i < tcStarts.length; i++) {
8233
- const start = tcStarts[i];
8234
- const end = tcStarts[i + 1]?.index ?? lines.length;
8235
- const block = lines.slice(start.index, end);
8236
- const fields = extractE2eTcFields(block);
8237
- tcFieldsMap.set(`${batch}:${start.id}`, fields);
8238
- }
8239
- }
9943
+ const tcFieldsMap = new Map(e2eNodes.map((node) => [
9944
+ node.code,
9945
+ asRecord(node.attrs?.tcFields)
9946
+ ]));
8240
9947
  for (const node of e2eNodes) {
8241
9948
  const tcKey = node.code;
8242
9949
  const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
@@ -8291,7 +9998,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8291
9998
  let hasActiveE2eRef = false;
8292
9999
  for (const entry of parseExecutableRefLines(execRef)) {
8293
10000
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
8294
- if (!normalized || !(0, import_node_fs5.existsSync)((0, import_node_path11.join)(root, normalized))) continue;
10001
+ if (!normalized || !(0, import_node_fs5.existsSync)((0, import_node_path13.join)(root, normalized))) continue;
8295
10002
  const accepting = await getAcceptingRunners(root, normalized, runners);
8296
10003
  if (accepting.some((runner) => runner.kind === "e2e")) {
8297
10004
  hasActiveE2eRef = true;
@@ -8350,7 +10057,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8350
10057
  const acCoverageRateByFeature = {};
8351
10058
  const featureAcMap = /* @__PURE__ */ new Map();
8352
10059
  for (const node of featureNodes) {
8353
- const acs = parseAcceptanceCriteria(await (0, import_promises7.readFile)((0, import_node_path11.join)(root, node.path), "utf-8"));
10060
+ const acs = parseAcceptanceCriteria(await (0, import_promises9.readFile)((0, import_node_path13.join)(root, node.path), "utf-8"));
8354
10061
  featureAcMap.set(node.code, new Set(acs));
8355
10062
  }
8356
10063
  const coveredAcByFeature = /* @__PURE__ */ new Map();
@@ -8392,39 +10099,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8392
10099
  };
8393
10100
  }
8394
10101
  async function generateE2eRegistry(root, opts) {
8395
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
8396
- let files;
8397
- try {
8398
- files = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
8399
- } catch {
8400
- return {
8401
- registry_version: "1.0",
8402
- generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8403
- total_batches: 0,
8404
- total_test_cases: 0,
8405
- batches: []
8406
- };
8407
- }
10102
+ const schema = await loadConfig(root);
10103
+ const files = await findConfiguredE2eFiles(root, schema);
8408
10104
  const batches = [];
10105
+ const batchIds = /* @__PURE__ */ new Set();
8409
10106
  let totalTestCases = 0;
8410
10107
  for (const file of files) {
8411
- const filePath = (0, import_node_path11.join)(e2eDir, file);
8412
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
10108
+ const filePath = (0, import_node_path13.join)(root, file);
10109
+ const raw = await (0, import_promises9.readFile)(filePath, "utf-8");
8413
10110
  const parsed = (0, import_gray_matter.default)(raw);
8414
10111
  const data = parsed.data;
8415
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(file, (0, import_node_path11.extname)(file))).trim();
8416
- const relPath = `artifacts/tests/e2e/${file}`;
10112
+ const batch = String(data.test_batch ?? (0, import_node_path13.basename)(file, (0, import_node_path13.extname)(file))).trim();
10113
+ const relPath = file;
8417
10114
  const scope = String(data.scope ?? "").trim();
8418
10115
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
8419
10116
  const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
8420
10117
  const lines = raw.split(/\r?\n/);
8421
- const tcStarts = [];
8422
- lines.forEach((line, index) => {
8423
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8424
- if (match) {
8425
- tcStarts.push({ id: match[1], index });
8426
- }
8427
- });
10118
+ const tcStarts = extractE2eTestCaseStarts(lines);
10119
+ if (tcStarts.length > 0) {
10120
+ batchIds.add(batch);
10121
+ }
8428
10122
  const statusSummary = {};
8429
10123
  const blockingReasons = {};
8430
10124
  const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
@@ -8433,8 +10127,9 @@ async function generateE2eRegistry(root, opts) {
8433
10127
  blockingReasons[tc.id] = frontmatterFixesBlock;
8434
10128
  }
8435
10129
  }
8436
- for (const start of tcStarts) {
8437
- const end = tcStarts[tcStarts.indexOf(start) + 1]?.index ?? lines.length;
10130
+ for (let index = 0; index < tcStarts.length; index += 1) {
10131
+ const start = tcStarts[index];
10132
+ const end = tcStarts[index + 1]?.index ?? lines.length;
8438
10133
  const block = lines.slice(start.index, end);
8439
10134
  const fields = extractE2eTcFields(block);
8440
10135
  const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
@@ -8467,7 +10162,7 @@ async function generateE2eRegistry(root, opts) {
8467
10162
  return {
8468
10163
  registry_version: "1.0",
8469
10164
  generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8470
- total_batches: batches.length,
10165
+ total_batches: batchIds.size,
8471
10166
  total_test_cases: totalTestCases,
8472
10167
  batches
8473
10168
  };
@@ -8536,10 +10231,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
8536
10231
  if (!normalizedPath) {
8537
10232
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8538
10233
  }
8539
- const fullPath = (0, import_node_path11.join)(root, normalizedPath);
10234
+ const fullPath = (0, import_node_path13.join)(root, normalizedPath);
8540
10235
  let content;
8541
10236
  try {
8542
- content = await (0, import_promises7.readFile)(fullPath, "utf-8");
10237
+ content = await (0, import_promises9.readFile)(fullPath, "utf-8");
8543
10238
  } catch {
8544
10239
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8545
10240
  }
@@ -8573,7 +10268,7 @@ function detectTestLevel(specFile, content) {
8573
10268
  }
8574
10269
  function resolveExecutableRefFile(refFile, allFiles) {
8575
10270
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
8576
- if (!normalized || (0, import_node_path11.isAbsolute)(refFile) || normalized.split("/").includes("..")) {
10271
+ if (!normalized || (0, import_node_path13.isAbsolute)(refFile) || normalized.split("/").includes("..")) {
8577
10272
  return void 0;
8578
10273
  }
8579
10274
  if (allFiles.includes(normalized)) {
@@ -8646,17 +10341,6 @@ function splitMarkdownCells(line) {
8646
10341
  function escapeRegExp(value) {
8647
10342
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8648
10343
  }
8649
- async function hasMarkdownTc(tcKey, e2eDir) {
8650
- const [batch, tcId] = tcKey.split(":");
8651
- const filePath = (0, import_node_path11.join)(e2eDir, `${batch}.md`);
8652
- try {
8653
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
8654
- const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
8655
- return tcRegex.test(raw);
8656
- } catch {
8657
- return false;
8658
- }
8659
- }
8660
10344
  async function findFiles(root, patterns) {
8661
10345
  const all = await walkFiles(root);
8662
10346
  const matched = /* @__PURE__ */ new Set();
@@ -8669,6 +10353,10 @@ async function findFiles(root, patterns) {
8669
10353
  }
8670
10354
  return [...matched].sort();
8671
10355
  }
10356
+ async function findConfiguredE2eFiles(root, schema) {
10357
+ const patterns = schema.types.e2e_test?.paths ?? [];
10358
+ return findFiles(root, patterns);
10359
+ }
8672
10360
  function matchesConfiguredArtifactPath(path, schema) {
8673
10361
  const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
8674
10362
  return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
@@ -8697,8 +10385,13 @@ function extractCodes(text, type, schema) {
8697
10385
  }
8698
10386
  function extractE2eTcFields(block) {
8699
10387
  const fields = {};
10388
+ const codeLines = markdownCodeLineMask2(block);
8700
10389
  let current = "";
8701
- for (const line of block) {
10390
+ for (let index = 0; index < block.length; index += 1) {
10391
+ if (codeLines[index]) {
10392
+ continue;
10393
+ }
10394
+ const line = block[index];
8702
10395
  const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
8703
10396
  if (match) {
8704
10397
  current = match[1].trim();
@@ -8881,7 +10574,7 @@ function normalizeDesignCode(value) {
8881
10574
  if (!raw) {
8882
10575
  return "";
8883
10576
  }
8884
- return (0, import_node_path11.basename)(raw, (0, import_node_path11.extname)(raw));
10577
+ return (0, import_node_path13.basename)(raw, (0, import_node_path13.extname)(raw));
8885
10578
  }
8886
10579
  function toUid(type, code) {
8887
10580
  return `${type}:${code}`;
@@ -9157,14 +10850,14 @@ function resolveArtifactContext(graph, opts) {
9157
10850
  }
9158
10851
  if (root) {
9159
10852
  for (const ap of ALWAYS_PRESENT_ITEMS) {
9160
- const fullPath = (0, import_node_path11.join)(root, ap.path);
9161
- let stat;
10853
+ const fullPath = (0, import_node_path13.join)(root, ap.path);
10854
+ let stat2;
9162
10855
  try {
9163
- stat = (0, import_node_fs5.statSync)(fullPath);
10856
+ stat2 = (0, import_node_fs5.statSync)(fullPath);
9164
10857
  } catch {
9165
- stat = null;
10858
+ stat2 = null;
9166
10859
  }
9167
- if (!stat) {
10860
+ if (!stat2) {
9168
10861
  const msg = `Required baseline artifact not found: ${ap.path}`;
9169
10862
  if (!missing.includes(msg)) {
9170
10863
  missing.push(msg);
@@ -9176,7 +10869,7 @@ function resolveArtifactContext(graph, opts) {
9176
10869
  suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
9177
10870
  });
9178
10871
  }
9179
- } else if (!stat.isFile()) {
10872
+ } else if (!stat2.isFile()) {
9180
10873
  const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
9181
10874
  if (!missing.includes(msg)) {
9182
10875
  missing.push(msg);
@@ -9399,14 +11092,14 @@ function formatContextMarkdown(manifest) {
9399
11092
  }
9400
11093
  return lines.join("\n");
9401
11094
  }
9402
- var import_gray_matter, import_js_yaml, import_node_fs5, import_promises7, import_node_path11, TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
11095
+ var import_gray_matter, import_js_yaml, import_node_fs5, import_promises9, import_node_path13, TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
9403
11096
  var init_index = __esm({
9404
11097
  "src/index.ts"() {
9405
11098
  import_gray_matter = __toESM(require("gray-matter"), 1);
9406
11099
  import_js_yaml = __toESM(require("js-yaml"), 1);
9407
11100
  import_node_fs5 = require("fs");
9408
- import_promises7 = require("fs/promises");
9409
- import_node_path11 = require("path");
11101
+ import_promises9 = require("fs/promises");
11102
+ import_node_path13 = require("path");
9410
11103
  init_packet_constants();
9411
11104
  init_packet_validator();
9412
11105
  init_glob_matcher();
@@ -9427,6 +11120,9 @@ var init_index = __esm({
9427
11120
  init_hook_installer();
9428
11121
  init_review_result_validator();
9429
11122
  init_contract_kernel();
11123
+ init_restructure();
11124
+ init_restructure_file_set();
11125
+ init_restructure_software();
9430
11126
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
9431
11127
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
9432
11128
  DEFAULT_SCHEMA = {
@@ -9522,6 +11218,7 @@ init_index();
9522
11218
  BASELINE_CONSTRAINTS,
9523
11219
  BASELINE_CONSTRAINTS_COUNT,
9524
11220
  BASELINE_ITEMS_COUNT,
11221
+ CONTRACTS_PACKAGE_NAME,
9525
11222
  CONTRACT_ERROR_CODES,
9526
11223
  ContractCatalog,
9527
11224
  ContractError,
@@ -9529,35 +11226,58 @@ init_index();
9529
11226
  DEFAULT_MAX_CHARS,
9530
11227
  DEFAULT_SCHEMA,
9531
11228
  E2E_NORMALIZER_CONFIG,
11229
+ FILE_SET_RESULT_OBJECT,
11230
+ FOUNDATION_PACKAGE_NAME,
9532
11231
  MIN_PROMPT_CHARS,
11232
+ RESTRUCTURE_MAX_OPERATIONS,
11233
+ RESTRUCTURE_MAX_TOTAL_BYTES,
11234
+ RESTRUCTURE_PLAN_SCHEMA_VERSION,
11235
+ RESTRUCTURE_QUALIFIED_ARCH,
11236
+ RESTRUCTURE_QUALIFIED_FILESYSTEM,
11237
+ RESTRUCTURE_QUALIFIED_PLATFORM,
11238
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
11239
+ RESTRUCTURE_RECOVERY_REL_PATH,
11240
+ RESTRUCTURE_RECOVERY_ROOT_MODE,
11241
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS,
9533
11242
  TARGET_ARTIFACT_TYPES,
9534
11243
  VALID_PACKET_TARGET_TYPES,
9535
11244
  VERSION_INDEX_SCHEMA_VERSION,
9536
11245
  VERSION_LOCK_PATH,
9537
11246
  VERSION_LOCK_SCHEMA_VERSION,
9538
11247
  applyPreparedManagedHookBlocks,
11248
+ applyRestructure,
11249
+ applyRestructureFileSet,
9539
11250
  assemblePacket,
9540
11251
  auditPackets,
9541
11252
  auditVersionLock,
9542
11253
  bootstrapVersionLock,
11254
+ buildFileSetApplyRequest,
9543
11255
  buildGraph,
9544
11256
  buildVersionIndex,
11257
+ candidateByteDigest,
9545
11258
  collectChangedPaths,
9546
11259
  computeCoverageBoundary,
9547
11260
  computeE2eCoverageStats,
9548
11261
  computeImpact,
9549
11262
  computeRevisionDigest,
11263
+ createModeForUmask,
11264
+ createRestructureRootBinding,
11265
+ createRestructureValidationCallback,
11266
+ digestRestructureValue,
9550
11267
  dirname,
9551
11268
  discoverAndAuditPackets,
9552
11269
  discoverTargets,
9553
11270
  doctorArtifactChain,
11271
+ ensureRestructureMechanismRoot,
9554
11272
  extname,
9555
11273
  filterGraphByView,
9556
11274
  formatContextMarkdown,
11275
+ gateRestructureOperationPlan,
9557
11276
  generateE2eRegistry,
9558
11277
  getArtifactTypeMetadata,
9559
11278
  getExternalEntryInfo,
9560
11279
  getTargetArtifactTypes,
11280
+ inspectRestructure,
9561
11281
  installManagedHookBlock,
9562
11282
  isOfficialNamespace,
9563
11283
  isPacketTargetType,
@@ -9568,14 +11288,26 @@ init_index();
9568
11288
  loadContract,
9569
11289
  loadContractCatalog,
9570
11290
  loadContractsFromDirectory,
11291
+ loadFoundationModule,
11292
+ locateSoftwareRecord,
11293
+ markdownRecordHeadings,
9571
11294
  matchesConfiguredArtifactPath,
9572
11295
  nextId,
9573
11296
  normalizeE2eLegacyArtifact,
9574
11297
  normalizeToCanonical,
11298
+ observeRestructureJournal,
9575
11299
  parseTargetSelector,
9576
11300
  parseTargetsFile,
11301
+ planRestructure,
11302
+ planningUmask,
9577
11303
  prepareManagedHookBlock,
11304
+ projectRestructureFileSetResult,
11305
+ pruneRestructureFileSet,
11306
+ pruneRestructureRecovery,
11307
+ qualifyRestructureMechanism,
9578
11308
  queryGraph,
11309
+ recoverRestructure,
11310
+ recoverRestructureFileSet,
9579
11311
  refreshVersionLock,
9580
11312
  renderCoverageBoundaryMarkdown,
9581
11313
  renderDoctorMarkdown,
@@ -9586,6 +11318,7 @@ init_index();
9586
11318
  renderTraceVersionMarkdown,
9587
11319
  renderVersionLockAuditMarkdown,
9588
11320
  renderVersionLockRefreshMarkdown,
11321
+ replaceSoftwareHeader,
9589
11322
  resolveArtifactContext,
9590
11323
  resolveArtifactGraphCli,
9591
11324
  resolveArtifactTypeName,
@@ -9593,6 +11326,8 @@ init_index();
9593
11326
  resolveGitHookPath,
9594
11327
  resolveMatrixEdges,
9595
11328
  resolveNodeTimeView,
11329
+ resolveRealRoot,
11330
+ restructureBoundaryFindings,
9596
11331
  scanArtifacts,
9597
11332
  traceVersion,
9598
11333
  updateVersionLock,
@@ -9608,6 +11343,7 @@ init_index();
9608
11343
  validateScenarioPrdLinkIndex,
9609
11344
  validateScenarioPrdLinks,
9610
11345
  verifyDigest,
11346
+ verifyMechanismResult,
9611
11347
  versionLockIssueSeverity,
9612
11348
  writeGraphCache
9613
11349
  });