artifact-graph 0.12.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/cli.js CHANGED
@@ -944,9 +944,13 @@ async function bootstrapVersionLock(root, options = {}) {
944
944
  async function refreshVersionLock(root, options = {}) {
945
945
  const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
946
946
  const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
947
+ const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
947
948
  const all = options.all === true || options.changedOnly !== true;
948
949
  const mode = all ? "all" : "changed-only";
949
950
  const warnings = [];
951
+ if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
952
+ throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
953
+ }
950
954
  if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
951
955
  throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
952
956
  }
@@ -956,9 +960,16 @@ async function refreshVersionLock(root, options = {}) {
956
960
  const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
957
961
  const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
958
962
  const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
963
+ const currentArtifactRelationEdgeList = artifactRelationEdges(index);
959
964
  const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
960
965
  const currentEntries = /* @__PURE__ */ new Map();
961
966
  const changedPathSet = new Set(changedPaths);
967
+ validatePreciseOrphanRemoval(
968
+ removeOrphanEdges,
969
+ lock,
970
+ new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
971
+ new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
972
+ );
962
973
  const affectedEdges = /* @__PURE__ */ new Set();
963
974
  const addedLocks = [];
964
975
  const updatedLocks = [];
@@ -985,12 +996,13 @@ async function refreshVersionLock(root, options = {}) {
985
996
  }
986
997
  for (const existing of lock.locks) {
987
998
  const current = currentEntries.get(existing.edgeId);
988
- const affected = all || lockEntryTouchesAnyPath(existing, changedPathSet);
999
+ const removePrecisely = removeOrphanEdges.has(existing.edgeId);
1000
+ const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
989
1001
  if (affected) {
990
1002
  affectedEdges.add(existing.edgeId);
991
1003
  }
992
1004
  if (!current) {
993
- if (affected && options.removeOrphans === true) {
1005
+ if (removePrecisely || affected && options.removeOrphans === true) {
994
1006
  removedOrphans.push(existing.edgeId);
995
1007
  } else {
996
1008
  if (affected) {
@@ -1025,7 +1037,6 @@ async function refreshVersionLock(root, options = {}) {
1025
1037
  if (mode === "changed-only" && changedPaths.length === 0) {
1026
1038
  warnings.push("No changed paths were provided; no locks were refreshed.");
1027
1039
  }
1028
- const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1029
1040
  const existingArtifactRelationLocks = lock.artifactRelations ?? [];
1030
1041
  const addedArtifactRelationLocks = [];
1031
1042
  const updatedArtifactRelationLocks = [];
@@ -1069,10 +1080,11 @@ async function refreshVersionLock(root, options = {}) {
1069
1080
  if (processedRelationEdgeIds.has(relEdgeId)) {
1070
1081
  continue;
1071
1082
  }
1072
- const affected = all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1083
+ const removePrecisely = removeOrphanEdges.has(relEdgeId);
1084
+ const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1073
1085
  if (affected) {
1074
1086
  affectedEdges.add(relEdgeId);
1075
- if (options.removeOrphans === true) {
1087
+ if (removePrecisely || options.removeOrphans === true) {
1076
1088
  removedArtifactRelationLocks.push(relEdgeId);
1077
1089
  } else {
1078
1090
  retainedArtifactRelationOrphans.push(relEdgeId);
@@ -1108,6 +1120,20 @@ async function refreshVersionLock(root, options = {}) {
1108
1120
  warnings
1109
1121
  };
1110
1122
  }
1123
+ function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
1124
+ for (const edgeId of requestedEdgeIds) {
1125
+ const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
1126
+ if (matches === 0) {
1127
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
1128
+ }
1129
+ if (matches !== 1) {
1130
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
1131
+ }
1132
+ if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
1133
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
1134
+ }
1135
+ }
1136
+ }
1111
1137
  async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
1112
1138
  const index = await buildVersionIndex(root);
1113
1139
  const safeLockPath = normalizeRelativePath(root, lockPath);
@@ -3082,16 +3108,16 @@ function probeNativeBinding(context = {}) {
3082
3108
  }
3083
3109
  return { ok: true };
3084
3110
  }
3085
- function buildNativeBindingDiagnostic(failure, probeContext) {
3111
+ function buildNativeBindingDiagnostic(failure2, probeContext) {
3086
3112
  return {
3087
3113
  selectedCli: probeContext.selectedCli,
3088
3114
  runtime: `${process.execPath} (v${process.versions.node})`,
3089
- abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure.detail)}`,
3115
+ abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
3090
3116
  installSource: probeContext.installSource,
3091
3117
  probedFrom: probeContext.probedFrom,
3092
- failedStage: failure.failedStage,
3093
- cause: failure.cause,
3094
- suggestion: failure.suggestion
3118
+ failedStage: failure2.failedStage,
3119
+ cause: failure2.cause,
3120
+ suggestion: failure2.suggestion
3095
3121
  };
3096
3122
  }
3097
3123
  function buildNativeBindingSuccessDiagnostic(probeContext) {
@@ -3115,21 +3141,21 @@ function runningArtifactGraphInstallRoot() {
3115
3141
  const anchor = typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url);
3116
3142
  return findPackageRoot(anchor);
3117
3143
  }
3118
- function structuredNativeBindingError(failure, context = {}) {
3144
+ function structuredNativeBindingError(failure2, context = {}) {
3119
3145
  return {
3120
3146
  error: "native_binding_unavailable",
3121
- stage: failure.failedStage,
3122
- cause: failure.cause,
3123
- detail: failure.detail,
3124
- suggestion: failure.suggestion,
3147
+ stage: failure2.failedStage,
3148
+ cause: failure2.cause,
3149
+ detail: failure2.detail,
3150
+ suggestion: failure2.suggestion,
3125
3151
  doctorHint: "artifact-graph doctor --format json",
3126
3152
  // F-10-P01/F-10-P03:机器读取错误包络也暴露实际探测来源,使 scan/query
3127
3153
  // 与 doctor 的分类依据(同一运行安装根)可被自动测试断言。
3128
3154
  probedFrom: context.probedFrom ?? "(current artifact-graph package)"
3129
3155
  };
3130
3156
  }
3131
- function renderStructuredNativeBindingError(failure, context = {}) {
3132
- return `${JSON.stringify(structuredNativeBindingError(failure, context), null, 2)}
3157
+ function renderStructuredNativeBindingError(failure2, context = {}) {
3158
+ return `${JSON.stringify(structuredNativeBindingError(failure2, context), null, 2)}
3133
3159
  `;
3134
3160
  }
3135
3161
  function safeClose(db) {
@@ -3233,7 +3259,7 @@ async function doctorArtifactChain(root, options = {}) {
3233
3259
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3234
3260
  const warnings = [
3235
3261
  ...cli.warnings,
3236
- ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy >=22.0.0.`],
3262
+ ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3237
3263
  ...probe.ok ? [] : [
3238
3264
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3239
3265
  ]
@@ -3245,7 +3271,7 @@ async function doctorArtifactChain(root, options = {}) {
3245
3271
  node: {
3246
3272
  version: process.versions.node,
3247
3273
  compatible: nodeCompatible,
3248
- required: ">=22.0.0"
3274
+ required: REQUIRED_NODE_VERSION
3249
3275
  },
3250
3276
  config: {
3251
3277
  path: configPath,
@@ -3349,8 +3375,10 @@ function resolveCandidatePath(root, candidatePath) {
3349
3375
  return isAbsolute2(candidatePath) ? candidatePath : resolve3(root, candidatePath);
3350
3376
  }
3351
3377
  function isNodeCompatible(version) {
3352
- const major = Number(version.split(".")[0]);
3353
- return Number.isFinite(major) && major >= 22;
3378
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
3379
+ if (!match) return false;
3380
+ const [, major, minor, patch] = match.map(Number);
3381
+ return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
3354
3382
  }
3355
3383
  async function detectPnpmVersion() {
3356
3384
  try {
@@ -3411,13 +3439,14 @@ function safeRealpath(path) {
3411
3439
  return path;
3412
3440
  }
3413
3441
  }
3414
- var execFileAsync2, KNOWN_COMMANDS;
3442
+ var execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
3415
3443
  var init_cli_resolver = __esm({
3416
3444
  "src/cli-resolver.ts"() {
3417
3445
  "use strict";
3418
3446
  init_versioned_traceability();
3419
3447
  init_native_binding_diagnostics();
3420
3448
  execFileAsync2 = promisify2(execFile2);
3449
+ REQUIRED_NODE_VERSION = ">=22.22.2 <23";
3421
3450
  KNOWN_COMMANDS = [
3422
3451
  "init",
3423
3452
  "scan",
@@ -3972,8 +4001,8 @@ function validateReviewResult(input) {
3972
4001
  validateReviewData(obj.review, "$.review", errors);
3973
4002
  if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
3974
4003
  const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
3975
- findings.forEach((finding, index) => {
3976
- if (isPlainObject(finding) && finding.severity === "block" && (finding.status === void 0 || finding.status === "open")) {
4004
+ findings.forEach((finding2, index) => {
4005
+ if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
3977
4006
  errors.push({
3978
4007
  path: `$.review.findings[${index}]`,
3979
4008
  message: `${obj.decision} cannot contain an open block finding`
@@ -5146,12 +5175,1709 @@ var init_contract_kernel = __esm({
5146
5175
  }
5147
5176
  });
5148
5177
 
5178
+ // src/restructure-software.ts
5179
+ function lineStarts(raw) {
5180
+ const starts = [0];
5181
+ const buffer = Buffer.from(raw, "utf8");
5182
+ for (let index = 0; index < buffer.length; index += 1) {
5183
+ if (buffer[index] === 10) starts.push(index + 1);
5184
+ }
5185
+ return starts;
5186
+ }
5187
+ function markdownCodeLineMask(lines) {
5188
+ const result = new Array(lines.length).fill(false);
5189
+ let fence;
5190
+ lines.forEach((line, index) => {
5191
+ if (fence) {
5192
+ result[index] = true;
5193
+ const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
5194
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
5195
+ return;
5196
+ }
5197
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
5198
+ if (opening) {
5199
+ result[index] = true;
5200
+ fence = { marker: opening[1][0], length: opening[1].length };
5201
+ return;
5202
+ }
5203
+ if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
5204
+ });
5205
+ return result;
5206
+ }
5207
+ function markdownRecordHeadings(raw, type) {
5208
+ const lines = raw.split("\n");
5209
+ const masked = markdownCodeLineMask(lines);
5210
+ 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;
5211
+ if (!pattern) return [];
5212
+ return lines.flatMap((line, index) => {
5213
+ if (masked[index]) return [];
5214
+ const match = pattern.exec(line.replace(/\r$/, ""));
5215
+ return match ? [{ id: match[1], line: index + 1 }] : [];
5216
+ });
5217
+ }
5218
+ function locateSoftwareRecord(raw, node, nodesInFile) {
5219
+ const byteLength = Buffer.byteLength(raw, "utf8");
5220
+ if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
5221
+ if (node.type !== "scenario" && node.type !== "e2e_test") {
5222
+ return {
5223
+ blockers: [{
5224
+ code: "UNSUPPORTED_RECORD_BOUNDARY",
5225
+ message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
5226
+ path: node.path,
5227
+ line: node.line
5228
+ }]
5229
+ };
5230
+ }
5231
+ const headings = markdownRecordHeadings(raw, node.type);
5232
+ const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
5233
+ const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
5234
+ const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
5235
+ const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
5236
+ const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
5237
+ const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
5238
+ if (inconsistent) {
5239
+ return {
5240
+ blockers: [{
5241
+ code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
5242
+ 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",
5243
+ path: node.path,
5244
+ line: node.line
5245
+ }]
5246
+ };
5247
+ }
5248
+ if (!heading) {
5249
+ return {
5250
+ blockers: [{
5251
+ code: "RECORD_BOUNDARY_MISSING",
5252
+ message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
5253
+ path: node.path,
5254
+ line: node.line
5255
+ }]
5256
+ };
5257
+ }
5258
+ const starts = lineStarts(raw);
5259
+ const nextLine = headings.find((item) => item.line > heading.line)?.line;
5260
+ return {
5261
+ range: {
5262
+ startByte: starts[heading.line - 1] ?? 0,
5263
+ endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
5264
+ },
5265
+ blockers: []
5266
+ };
5267
+ }
5268
+ function replaceSoftwareHeader(raw, header) {
5269
+ const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
5270
+ const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
5271
+ ` : header;
5272
+ return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
5273
+ }
5274
+ var init_restructure_software = __esm({
5275
+ "src/restructure-software.ts"() {
5276
+ "use strict";
5277
+ }
5278
+ });
5279
+
5280
+ // src/restructure-file-set.ts
5281
+ import { createHash as createHash3 } from "crypto";
5282
+ import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
5283
+ import { join as join8, resolve as resolve5 } from "path";
5284
+ async function loadFoundationModule() {
5285
+ return await import(FOUNDATION_PACKAGE_NAME);
5286
+ }
5287
+ async function loadContractsModule() {
5288
+ return await import(CONTRACTS_PACKAGE_NAME);
5289
+ }
5290
+ async function verifyMechanismResult(result) {
5291
+ if (typeof result !== "object" || result === null || Array.isArray(result)) {
5292
+ return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
5293
+ }
5294
+ let contracts;
5295
+ let registration;
5296
+ try {
5297
+ contracts = await loadContractsModule();
5298
+ registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
5299
+ } catch (cause) {
5300
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
5301
+ }
5302
+ if (registration === null) {
5303
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
5304
+ }
5305
+ const verdict = contracts.validateDocument(result, {
5306
+ schemaId: registration.$id,
5307
+ dialect: registration.dialect,
5308
+ policy: "strict"
5309
+ });
5310
+ if (!verdict.valid) {
5311
+ return failure(
5312
+ "MECHANISM_RESULT_INVALID",
5313
+ `The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
5314
+ { schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
5315
+ );
5316
+ }
5317
+ return { ok: true, data: result };
5318
+ }
5319
+ function failure(code, message, details) {
5320
+ return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
5321
+ }
5322
+ function candidateBytes(content) {
5323
+ return Buffer.from(content ?? "", "utf8");
5324
+ }
5325
+ function candidateByteDigest(content) {
5326
+ return createHash3("sha256").update(candidateBytes(content)).digest("hex");
5327
+ }
5328
+ function rawDigest(value, path) {
5329
+ if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
5330
+ throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
5331
+ }
5332
+ const raw = value.slice(DIGEST_PREFIX.length);
5333
+ if (!RAW_SHA256_PATTERN.test(raw)) {
5334
+ throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
5335
+ }
5336
+ return raw;
5337
+ }
5338
+ async function resolveRealRoot(root) {
5339
+ let canonical;
5340
+ try {
5341
+ canonical = await realpath(resolve5(root));
5342
+ } catch (cause) {
5343
+ return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5344
+ }
5345
+ let info;
5346
+ try {
5347
+ info = await lstat2(canonical);
5348
+ } catch (cause) {
5349
+ return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
5350
+ }
5351
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5352
+ return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
5353
+ }
5354
+ return { ok: true, data: canonical };
5355
+ }
5356
+ async function qualifyRestructureMechanism(root) {
5357
+ if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
5358
+ return failure(
5359
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5360
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
5361
+ );
5362
+ }
5363
+ const canonical = await resolveRealRoot(root);
5364
+ if (!canonical.ok) return canonical;
5365
+ let type;
5366
+ try {
5367
+ type = (await statfs(canonical.data)).type;
5368
+ } catch (cause) {
5369
+ return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
5370
+ }
5371
+ if (type !== APFS_STATFS_TYPE) {
5372
+ return failure(
5373
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5374
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
5375
+ );
5376
+ }
5377
+ return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5378
+ }
5379
+ async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5380
+ const target = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5381
+ const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5382
+ let info = await current();
5383
+ if (info === null) {
5384
+ if (!options.create) {
5385
+ return failure(
5386
+ "RECOVERY_MATERIALS_MISSING",
5387
+ `No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
5388
+ );
5389
+ }
5390
+ let created = false;
5391
+ try {
5392
+ await mkdir4(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
5393
+ created = true;
5394
+ } catch (cause) {
5395
+ if (cause.code !== "EEXIST") {
5396
+ return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
5397
+ }
5398
+ }
5399
+ info = await current();
5400
+ if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
5401
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5402
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5403
+ }
5404
+ if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5405
+ await chmod(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
5406
+ info = await current();
5407
+ if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
5408
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5409
+ }
5410
+ }
5411
+ }
5412
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5413
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5414
+ }
5415
+ if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5416
+ return failure(
5417
+ "MECHANISM_ROOT_UNSAFE",
5418
+ `${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
5419
+ );
5420
+ }
5421
+ return { ok: true, data: target };
5422
+ }
5423
+ async function createRestructureRootBinding(canonicalRoot) {
5424
+ try {
5425
+ const module = await loadFoundationModule();
5426
+ return { ok: true, data: await module.createFilesystemRootBinding(canonicalRoot) };
5427
+ } catch (cause) {
5428
+ return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
5429
+ }
5430
+ }
5431
+ function toOperation(candidate) {
5432
+ const expected = candidate.original.exists ? {
5433
+ exists: true,
5434
+ sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
5435
+ size: candidate.original.size,
5436
+ mode: candidate.original.mode
5437
+ } : { exists: false };
5438
+ if (candidate.action === "delete") {
5439
+ return { path: candidate.path, action: "delete", expected, next: null };
5440
+ }
5441
+ const bytes = candidateBytes(candidate.content);
5442
+ const declared = rawDigest(candidate.sha256, candidate.path);
5443
+ if (declared !== candidateByteDigest(candidate.content)) {
5444
+ throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
5445
+ }
5446
+ return {
5447
+ path: candidate.path,
5448
+ action: candidate.action,
5449
+ expected,
5450
+ next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
5451
+ };
5452
+ }
5453
+ async function buildFileSetApplyRequest(canonicalRoot, plan) {
5454
+ if (plan.candidates.length === 0) {
5455
+ return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
5456
+ }
5457
+ const binding = await createRestructureRootBinding(canonicalRoot);
5458
+ if (!binding.ok) return binding;
5459
+ let operations;
5460
+ try {
5461
+ operations = plan.candidates.map(toOperation);
5462
+ } catch (cause) {
5463
+ return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
5464
+ }
5465
+ return {
5466
+ ok: true,
5467
+ data: {
5468
+ schemaVersion: 1,
5469
+ kind: "skill-family.file-set-apply-request",
5470
+ operationId: plan.operation_id,
5471
+ root: canonicalRoot,
5472
+ rootBinding: binding.data,
5473
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5474
+ allowAdjacentStaging: true,
5475
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5476
+ validationTimeoutMs: plan.validation_timeout_ms,
5477
+ operations
5478
+ }
5479
+ };
5480
+ }
5481
+ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5482
+ const request = await buildFileSetApplyRequest(canonicalRoot, plan);
5483
+ if (!request.ok) return request;
5484
+ const module = await loadFoundationModule();
5485
+ let raw;
5486
+ try {
5487
+ raw = await module.applyFileSet(request.data, { validate: options.validate });
5488
+ } catch (cause) {
5489
+ return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
5490
+ }
5491
+ return await verifyMechanismResult(raw);
5492
+ }
5493
+ async function observeRestructureJournal(canonicalRoot) {
5494
+ const journalRoot = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5495
+ const module = await loadFoundationModule();
5496
+ try {
5497
+ return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
5498
+ } catch (cause) {
5499
+ return failure(
5500
+ "MAINTENANCE_OBSERVATION_FAILED",
5501
+ `The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
5502
+ );
5503
+ }
5504
+ }
5505
+ async function recoverRestructureFileSet(canonicalRoot, plan, options) {
5506
+ if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
5507
+ return failure(
5508
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
5509
+ "restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
5510
+ );
5511
+ }
5512
+ const binding = await createRestructureRootBinding(canonicalRoot);
5513
+ if (!binding.ok) return binding;
5514
+ const observation = await observeRestructureJournal(canonicalRoot);
5515
+ if (!observation.ok) return observation;
5516
+ const maintenance = {
5517
+ observation: observation.data,
5518
+ confirmAllParticipantsStopped: true,
5519
+ confirmExclusiveMaintenance: true
5520
+ };
5521
+ const request = {
5522
+ schemaVersion: 1,
5523
+ kind: "skill-family.file-set-recovery-request",
5524
+ operationId: plan.operation_id,
5525
+ root: canonicalRoot,
5526
+ rootBinding: binding.data,
5527
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5528
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5529
+ allowAdjacentStaging: true,
5530
+ maintenance
5531
+ };
5532
+ const module = await loadFoundationModule();
5533
+ let raw;
5534
+ try {
5535
+ raw = await module.recoverFileSet(request);
5536
+ } catch (cause) {
5537
+ return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
5538
+ }
5539
+ return await verifyMechanismResult(raw);
5540
+ }
5541
+ async function pruneRestructureFileSet(canonicalRoot, plan, options) {
5542
+ const binding = await createRestructureRootBinding(canonicalRoot);
5543
+ if (!binding.ok) return binding;
5544
+ const request = {
5545
+ schemaVersion: 1,
5546
+ kind: "skill-family.file-set-prune-request",
5547
+ operationId: plan.operation_id,
5548
+ root: canonicalRoot,
5549
+ rootBinding: binding.data,
5550
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5551
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
5552
+ };
5553
+ if (options.allParticipantsStopped && options.exclusiveMaintenance) {
5554
+ const observation = await observeRestructureJournal(canonicalRoot);
5555
+ if (!observation.ok) return observation;
5556
+ request.maintenance = {
5557
+ observation: observation.data,
5558
+ confirmAllParticipantsStopped: true,
5559
+ confirmExclusiveMaintenance: true
5560
+ };
5561
+ }
5562
+ const module = await loadFoundationModule();
5563
+ let raw;
5564
+ try {
5565
+ raw = await module.pruneFileSetRecovery(request);
5566
+ } catch (cause) {
5567
+ return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
5568
+ }
5569
+ return await verifyMechanismResult(raw);
5570
+ }
5571
+ function validationState(validation) {
5572
+ return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
5573
+ }
5574
+ function errorKinds(result) {
5575
+ return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
5576
+ }
5577
+ function applyProjection(result) {
5578
+ const kinds = errorKinds(result);
5579
+ if (result.outcome === "committed") {
5580
+ if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
5581
+ return {
5582
+ code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
5583
+ 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.",
5584
+ ok: false,
5585
+ rerunApplyPermitted: false
5586
+ };
5587
+ }
5588
+ const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
5589
+ return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
5590
+ code: "APPLY_INCOMPLETE",
5591
+ message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
5592
+ ok: false,
5593
+ rerunApplyPermitted: false
5594
+ };
5595
+ }
5596
+ const codes = {
5597
+ "commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
5598
+ "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."],
5599
+ "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."]
5600
+ };
5601
+ const mapped = codes[result.outcome];
5602
+ if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
5603
+ if (result.outcome === "rejected") {
5604
+ const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
5605
+ return {
5606
+ code: "APPLY_REJECTED",
5607
+ 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.",
5608
+ ok: false,
5609
+ rerunApplyPermitted: !identityTaken
5610
+ };
5611
+ }
5612
+ return {
5613
+ code: "APPLY_UNEXPECTED_OUTCOME",
5614
+ message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
5615
+ ok: false,
5616
+ rerunApplyPermitted: false
5617
+ };
5618
+ }
5619
+ function recoverProjection(result) {
5620
+ const reading = (() => {
5621
+ switch (result.outcome) {
5622
+ case "already-committed":
5623
+ return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
5624
+ case "already-rolled-back":
5625
+ return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
5626
+ case "rolled-back":
5627
+ return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
5628
+ case "pruned":
5629
+ return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
5630
+ case "already-pruned":
5631
+ return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
5632
+ case "commit-unconfirmed":
5633
+ 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 };
5634
+ case "recovery-required":
5635
+ return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
5636
+ case "rejected":
5637
+ return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
5638
+ default:
5639
+ return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
5640
+ }
5641
+ })();
5642
+ return { ...reading, rerunApplyPermitted: false };
5643
+ }
5644
+ function pruneProjection(result) {
5645
+ const reading = (() => {
5646
+ switch (result.outcome) {
5647
+ case "pruned":
5648
+ return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
5649
+ case "already-pruned":
5650
+ return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
5651
+ case "rejected":
5652
+ return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
5653
+ case "recovery-required":
5654
+ 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 };
5655
+ default:
5656
+ return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
5657
+ }
5658
+ })();
5659
+ return { ...reading, rerunApplyPermitted: false };
5660
+ }
5661
+ function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
5662
+ const base = {
5663
+ foundation: result,
5664
+ planPath,
5665
+ planDigest,
5666
+ operation: result.operation,
5667
+ outcome: result.outcome,
5668
+ preflight: result.preflight,
5669
+ businessWrite: result.businessWrite,
5670
+ validation: result.validation,
5671
+ validationState: validationState(result.validation),
5672
+ recovery: result.recovery,
5673
+ paths: result.paths,
5674
+ errors: result.errors,
5675
+ materialPath: result.materials.relPath,
5676
+ errorKinds: errorKinds(result)
5677
+ };
5678
+ const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
5679
+ return { ...base, ...reading };
5680
+ }
5681
+ var RESTRUCTURE_RECOVERY_REL_PATH, RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH, RESTRUCTURE_RECOVERY_ROOT_MODE, RESTRUCTURE_QUALIFIED_PLATFORM, RESTRUCTURE_QUALIFIED_ARCH, RESTRUCTURE_QUALIFIED_FILESYSTEM, APFS_STATFS_TYPE, DIGEST_PREFIX, RAW_SHA256_PATTERN, FOUNDATION_PACKAGE_NAME, CONTRACTS_PACKAGE_NAME, FILE_SET_RESULT_OBJECT, APPLY_MAINTENANCE_ERROR_KINDS;
5682
+ var init_restructure_file_set = __esm({
5683
+ "src/restructure-file-set.ts"() {
5684
+ "use strict";
5685
+ RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
5686
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
5687
+ RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
5688
+ RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
5689
+ RESTRUCTURE_QUALIFIED_ARCH = "arm64";
5690
+ RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
5691
+ APFS_STATFS_TYPE = 26;
5692
+ DIGEST_PREFIX = "sha256:";
5693
+ RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5694
+ FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
5695
+ CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
5696
+ FILE_SET_RESULT_OBJECT = "file-set-result";
5697
+ APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
5698
+ }
5699
+ });
5700
+
5701
+ // src/restructure.ts
5702
+ var restructure_exports = {};
5703
+ __export(restructure_exports, {
5704
+ RESTRUCTURE_MAX_OPERATIONS: () => RESTRUCTURE_MAX_OPERATIONS,
5705
+ RESTRUCTURE_MAX_TOTAL_BYTES: () => RESTRUCTURE_MAX_TOTAL_BYTES,
5706
+ RESTRUCTURE_PLAN_SCHEMA_VERSION: () => RESTRUCTURE_PLAN_SCHEMA_VERSION,
5707
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS: () => RESTRUCTURE_VALIDATION_TIMEOUT_MS,
5708
+ applyRestructure: () => applyRestructure,
5709
+ createModeForUmask: () => createModeForUmask,
5710
+ createRestructureValidationCallback: () => createRestructureValidationCallback,
5711
+ digestRestructureValue: () => digestRestructureValue,
5712
+ gateRestructureOperationPlan: () => gateRestructureOperationPlan,
5713
+ inspectRestructure: () => inspectRestructure,
5714
+ planRestructure: () => planRestructure,
5715
+ planningUmask: () => planningUmask,
5716
+ pruneRestructureRecovery: () => pruneRestructureRecovery,
5717
+ recoverRestructure: () => recoverRestructure,
5718
+ restructureBoundaryFindings: () => restructureBoundaryFindings
5719
+ });
5720
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
5721
+ import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
5722
+ import { dirname as dirname5, isAbsolute as isAbsolute4, join as join9, posix, relative as relative4, resolve as resolve6 } from "path";
5723
+ import { fileURLToPath as fileURLToPath2 } from "url";
5724
+ function digestBytes(value) {
5725
+ return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
5726
+ }
5727
+ function canonicalJson(value) {
5728
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
5729
+ if (value && typeof value === "object") {
5730
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
5731
+ }
5732
+ return JSON.stringify(value);
5733
+ }
5734
+ function digestRestructureValue(value) {
5735
+ return digestBytes(canonicalJson(value));
5736
+ }
5737
+ function normalizeRelativePath2(value) {
5738
+ if (!value || value.includes("\0") || isAbsolute4(value)) return void 0;
5739
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5740
+ if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5741
+ return normalized;
5742
+ }
5743
+ function isPathAllowed(path, allowed) {
5744
+ return allowed.some((entry) => {
5745
+ const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
5746
+ return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
5747
+ });
5748
+ }
5749
+ async function readContainedFileWithMode(root, path) {
5750
+ const normalized = normalizeRelativePath2(path);
5751
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5752
+ const absoluteRoot = resolve6(root);
5753
+ const absolutePath = resolve6(absoluteRoot, normalized);
5754
+ if (relative4(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
5755
+ try {
5756
+ const info = await lstat3(absolutePath);
5757
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
5758
+ return { buffer: await readFile3(absolutePath), mode: info.mode & MAX_POSIX_MODE };
5759
+ } catch (error) {
5760
+ if (error.code === "ENOENT") return void 0;
5761
+ throw error;
5762
+ }
5763
+ }
5764
+ async function readContainedFile(root, path) {
5765
+ return (await readContainedFileWithMode(root, path))?.buffer;
5766
+ }
5767
+ async function snapshotFile(root, path) {
5768
+ const normalized = normalizeRelativePath2(path);
5769
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5770
+ const contained = await readContainedFileWithMode(root, normalized);
5771
+ return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
5772
+ path: normalized,
5773
+ exists: true,
5774
+ sha256: digestBytes(contained.buffer),
5775
+ size: contained.buffer.byteLength,
5776
+ mode: contained.mode
5777
+ };
5778
+ }
5779
+ function sameSnapshot(left, right) {
5780
+ return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
5781
+ }
5782
+ async function configSnapshot(root) {
5783
+ return snapshotFile(root, "artifact-graph.config.yaml");
5784
+ }
5785
+ async function loadRestructureContract(name) {
5786
+ return loadContract(join9(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
5787
+ }
5788
+ async function validateDomainContract(name, value) {
5789
+ const contract = await loadRestructureContract(name);
5790
+ return validateContractAgainstSchema(value, contract).errors;
5791
+ }
5792
+ function occurrenceKey(edge2) {
5793
+ return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
5794
+ }
5795
+ function relationOccurrences(graph) {
5796
+ const counts = /* @__PURE__ */ new Map();
5797
+ return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
5798
+ const key = occurrenceKey(edge2);
5799
+ const occurrence = (counts.get(key) ?? 0) + 1;
5800
+ counts.set(key, occurrence);
5801
+ return {
5802
+ from: edge2.from,
5803
+ to: edge2.to,
5804
+ kind: edge2.kind,
5805
+ source: edge2.source,
5806
+ source_path: edge2.sourcePath,
5807
+ source_line: edge2.sourceLine,
5808
+ occurrence
5809
+ };
5810
+ });
5811
+ }
5812
+ function relationKey(value) {
5813
+ return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
5814
+ }
5815
+ function acceptanceCriteria(node) {
5816
+ const raw = node.attrs?.acceptanceCriteria;
5817
+ if (!Array.isArray(raw)) return [];
5818
+ return raw.flatMap((item, index) => {
5819
+ if (typeof item === "string") {
5820
+ const match = /\b(AC\d+)\b/.exec(item);
5821
+ return [match?.[1] ?? `AC${index + 1}`];
5822
+ }
5823
+ if (item && typeof item === "object") {
5824
+ const record = item;
5825
+ const value = String(record.id ?? record.code ?? "").trim();
5826
+ return value ? [value] : [`AC${index + 1}`];
5827
+ }
5828
+ return [`AC${index + 1}`];
5829
+ });
5830
+ }
5831
+ function spanFor(buffer, path, range) {
5832
+ return {
5833
+ path,
5834
+ start_byte: range.startByte,
5835
+ end_byte: range.endByte,
5836
+ sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
5837
+ };
5838
+ }
5839
+ function mappingTemplate(request, requestDigest, config, sources, unresolved) {
5840
+ return {
5841
+ schema_version: "1.0",
5842
+ request,
5843
+ request_digest: requestDigest,
5844
+ config_snapshot: config,
5845
+ sources: sources.map((source) => ({
5846
+ type: source.type,
5847
+ id: source.id,
5848
+ path: source.path,
5849
+ snapshot: source.snapshot,
5850
+ disposition: "preserved"
5851
+ })),
5852
+ targets: [],
5853
+ content_moves: [],
5854
+ identity_map: [],
5855
+ criterion_map: [],
5856
+ relation_map: [],
5857
+ prose_edits: [],
5858
+ file_headers: [],
5859
+ unresolved
5860
+ };
5861
+ }
5862
+ async function inspectRestructure(root, input) {
5863
+ const schemaErrors = await validateDomainContract("request", input);
5864
+ if (schemaErrors.length > 0) {
5865
+ return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
5866
+ }
5867
+ const request = input;
5868
+ const requestDigest = digestRestructureValue(request);
5869
+ const schema = await loadConfig(root);
5870
+ const graph = await scanArtifacts(root, schema);
5871
+ const allOccurrences = relationOccurrences(graph);
5872
+ const blockers = [];
5873
+ const unresolved = [];
5874
+ const inspected = [];
5875
+ for (const requested of request.sources) {
5876
+ const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
5877
+ if (candidates.length !== 1) {
5878
+ blockers.push({
5879
+ code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
5880
+ 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`,
5881
+ ...requested.path ? { path: requested.path } : {}
5882
+ });
5883
+ continue;
5884
+ }
5885
+ const node = candidates[0];
5886
+ const raw = await readContainedFile(root, node.path);
5887
+ if (!raw) {
5888
+ blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
5889
+ continue;
5890
+ }
5891
+ const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
5892
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
5893
+ blockers.push(...boundary.blockers);
5894
+ const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
5895
+ const uid = `${node.type}:${node.code}`;
5896
+ inspected.push({
5897
+ type: node.type,
5898
+ id: node.code,
5899
+ uid,
5900
+ path: node.path,
5901
+ title: node.title,
5902
+ snapshot: await snapshotFile(root, node.path),
5903
+ ...recordSpan ? {
5904
+ record_span: recordSpan,
5905
+ content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
5906
+ } : {},
5907
+ surrounding_spans: recordSpan ? [
5908
+ ...recordSpan.start_byte > 0 ? [{
5909
+ ...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
5910
+ content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
5911
+ }] : [],
5912
+ ...recordSpan.end_byte < raw.byteLength ? [{
5913
+ ...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
5914
+ content: raw.subarray(recordSpan.end_byte).toString("utf8")
5915
+ }] : []
5916
+ ] : [],
5917
+ acceptance_criteria: acceptanceCriteria(node),
5918
+ incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
5919
+ outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
5920
+ });
5921
+ }
5922
+ if (request.numbering_policy?.mode === "configured-next-available") {
5923
+ unresolved.push({
5924
+ code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
5925
+ message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
5926
+ });
5927
+ }
5928
+ mergeFindings(unresolved, await scanUnsupportedReferences(
5929
+ root,
5930
+ [...new Set(inspected.map((item) => item.path))],
5931
+ []
5932
+ ));
5933
+ const config = await configSnapshot(root);
5934
+ const affectedPaths = new Set(inspected.map((item) => item.path));
5935
+ for (const source of inspected) {
5936
+ for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
5937
+ }
5938
+ const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
5939
+ const inspection = {
5940
+ schema_version: "1.0",
5941
+ request,
5942
+ request_digest: requestDigest,
5943
+ config_snapshot: config,
5944
+ sources: inspected,
5945
+ affected_files: affectedFiles,
5946
+ relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
5947
+ blockers,
5948
+ unresolved,
5949
+ mapping_template: {}
5950
+ };
5951
+ inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
5952
+ return { ok: true, data: inspection };
5953
+ }
5954
+ function finding(code, message, path, line) {
5955
+ return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
5956
+ }
5957
+ async function verifySnapshot(root, expected, blockers) {
5958
+ const normalized = normalizeRelativePath2(expected.path);
5959
+ if (!normalized) {
5960
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
5961
+ return void 0;
5962
+ }
5963
+ const actual = await snapshotFile(root, normalized);
5964
+ if (!sameSnapshot(actual, { ...expected, path: normalized })) {
5965
+ blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
5966
+ }
5967
+ return actual;
5968
+ }
5969
+ function validateSpan(buffer, span, blockers) {
5970
+ if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
5971
+ blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
5972
+ return void 0;
5973
+ }
5974
+ const fragment = buffer.subarray(span.start_byte, span.end_byte);
5975
+ if (digestBytes(fragment) !== span.sha256) {
5976
+ blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
5977
+ return void 0;
5978
+ }
5979
+ return fragment;
5980
+ }
5981
+ function rangesCover(range, moves) {
5982
+ 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);
5983
+ let cursor = range.startByte;
5984
+ for (const interval of intervals) {
5985
+ if (interval.start > cursor) return false;
5986
+ cursor = Math.max(cursor, interval.end);
5987
+ }
5988
+ return cursor >= range.endByte;
5989
+ }
5990
+ function edgeDisplay(edge2) {
5991
+ return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
5992
+ }
5993
+ function graphDiff(before, after) {
5994
+ const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
5995
+ const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
5996
+ const beforeEdges = new Set(before.edges.map(edgeDisplay));
5997
+ const afterEdges = new Set(after.edges.map(edgeDisplay));
5998
+ return {
5999
+ added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
6000
+ removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
6001
+ added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
6002
+ removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
6003
+ };
6004
+ }
6005
+ function issueIdentity(issue2) {
6006
+ const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
6007
+ return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
6008
+ }
6009
+ function readableDiff(path, oldContent, newContent) {
6010
+ const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
6011
+ const newLines = newContent?.split(/(?<=\n)/) ?? [];
6012
+ if (oldContent === newContent) return "";
6013
+ return [
6014
+ `--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
6015
+ `+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
6016
+ ...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
6017
+ ...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
6018
+ ].join("\n");
6019
+ }
6020
+ function findRelativeLinks(fragment) {
6021
+ const found = /* @__PURE__ */ new Set();
6022
+ const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
6023
+ let match;
6024
+ while ((match = pattern.exec(fragment)) !== null) {
6025
+ const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
6026
+ if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
6027
+ }
6028
+ return [...found].sort();
6029
+ }
6030
+ function footnoteReferenceLabels(text) {
6031
+ const labels = /* @__PURE__ */ new Set();
6032
+ const pattern = /\[\^([^\]\s]+)\](?!:)/g;
6033
+ let match;
6034
+ while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
6035
+ return [...labels].sort();
6036
+ }
6037
+ function footnoteDefinition(label) {
6038
+ return `[^${label}]:`;
6039
+ }
6040
+ function splitMarkdownTarget(target) {
6041
+ const cleaned = target.trim().replace(/^<|>$/g, "");
6042
+ const hash = cleaned.indexOf("#");
6043
+ return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
6044
+ }
6045
+ async function pathExists2(absolutePath) {
6046
+ try {
6047
+ await lstat3(absolutePath);
6048
+ return true;
6049
+ } catch {
6050
+ return false;
6051
+ }
6052
+ }
6053
+ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6054
+ const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
6055
+ const migrationNames = new Set(migrationPaths.map((path) => posix.basename(path)));
6056
+ const directories = new Set(migrationPaths.map((path) => posix.dirname(path)));
6057
+ const findings = [];
6058
+ async function visit(directory) {
6059
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6060
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6061
+ const absolute = join9(directory, entry.name);
6062
+ if (entry.isDirectory()) {
6063
+ await visit(absolute);
6064
+ continue;
6065
+ }
6066
+ if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
6067
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6068
+ const raw = await readFile3(absolute, "utf8");
6069
+ const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
6070
+ const lines = raw.split(/\r?\n/);
6071
+ for (const [index, line] of lines.entries()) {
6072
+ const lineNumber = index + 1;
6073
+ if (MARKDOWN_FILE_SUFFIX.test(path)) {
6074
+ const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
6075
+ let match;
6076
+ while ((match = pattern.exec(line)) !== null) {
6077
+ const literal = match[0];
6078
+ const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
6079
+ if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
6080
+ if (!migrationNames.has(posix.basename(linkPath))) continue;
6081
+ const resolved = normalizeRelativePath2(posix.join(posix.dirname(path), linkPath));
6082
+ if (!resolved || targetPaths.includes(resolved)) continue;
6083
+ if (anchor) {
6084
+ findings.push(finding(
6085
+ "ANCHOR_REFERENCE_UNRESOLVED",
6086
+ `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`,
6087
+ path,
6088
+ lineNumber
6089
+ ));
6090
+ } else if (!await pathExists2(resolve6(root, resolved))) {
6091
+ findings.push(finding(
6092
+ "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
6093
+ `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`,
6094
+ path,
6095
+ lineNumber
6096
+ ));
6097
+ }
6098
+ }
6099
+ }
6100
+ if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
6101
+ const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
6102
+ const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
6103
+ if (directoryLiteral) {
6104
+ findings.push(finding(
6105
+ "RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
6106
+ `A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
6107
+ path,
6108
+ lineNumber
6109
+ ));
6110
+ }
6111
+ }
6112
+ }
6113
+ }
6114
+ }
6115
+ await visit(resolve6(root));
6116
+ const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
6117
+ return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
6118
+ }
6119
+ function mergeFindings(target, additions) {
6120
+ const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
6121
+ for (const item of additions) {
6122
+ const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
6123
+ if (seen.has(key)) continue;
6124
+ seen.add(key);
6125
+ target.push(item);
6126
+ }
6127
+ }
6128
+ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
6129
+ const results = [];
6130
+ async function visit(directory) {
6131
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6132
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6133
+ const absolute = join9(directory, entry.name);
6134
+ if (entry.isDirectory()) {
6135
+ await visit(absolute);
6136
+ } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
6137
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6138
+ if (excludedPaths.has(path)) continue;
6139
+ const raw = await readFile3(absolute, "utf8");
6140
+ raw.split(/\r?\n/).forEach((line, index) => {
6141
+ for (const reference of references) {
6142
+ if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
6143
+ }
6144
+ });
6145
+ }
6146
+ }
6147
+ }
6148
+ await visit(resolve6(root));
6149
+ return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6150
+ }
6151
+ function expectedRelationTargets(mapping) {
6152
+ return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
6153
+ }
6154
+ function relationTriples(graph) {
6155
+ return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
6156
+ }
6157
+ function formatMode(value) {
6158
+ return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
6159
+ }
6160
+ function isPosixFileMode(value) {
6161
+ return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
6162
+ }
6163
+ function modeIsUsableAtApply(mode, umask) {
6164
+ return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
6165
+ }
6166
+ function createModeForUmask(umask) {
6167
+ return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
6168
+ }
6169
+ function planningUmask() {
6170
+ return process.umask() & MAX_POSIX_MODE;
6171
+ }
6172
+ function restructureBoundaryFindings(operations, limits) {
6173
+ const findings = [];
6174
+ if (operations.length === 0) {
6175
+ findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
6176
+ return findings;
6177
+ }
6178
+ if (operations.length > limits.max_operations) {
6179
+ findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
6180
+ }
6181
+ const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
6182
+ if (totalBytes > limits.max_total_bytes) {
6183
+ findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
6184
+ }
6185
+ const expectedCreateMode = createModeForUmask(limits.umask);
6186
+ const applyModeContract = limits.mode_contract === "apply";
6187
+ for (const operation of operations) {
6188
+ const parent = dirname5(operation.path) || ".";
6189
+ if (!operation.parent_exists) {
6190
+ findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6191
+ } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
6192
+ findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
6193
+ }
6194
+ if (!isPosixFileMode(operation.mode)) {
6195
+ findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
6196
+ }
6197
+ if (!isPosixFileMode(operation.original_mode)) {
6198
+ findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
6199
+ }
6200
+ if (operation.original_exists && operation.original_mode === null) {
6201
+ findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
6202
+ }
6203
+ if (!operation.original_exists && operation.original_mode !== null) {
6204
+ findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
6205
+ }
6206
+ if (applyModeContract) {
6207
+ for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
6208
+ if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
6209
+ findings.push(finding(
6210
+ "MODE_NOT_USABLE",
6211
+ `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}`,
6212
+ operation.path
6213
+ ));
6214
+ }
6215
+ }
6216
+ if (operation.action === "create") {
6217
+ if (operation.original_exists) {
6218
+ findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
6219
+ }
6220
+ if (!applyModeContract && operation.mode !== expectedCreateMode) {
6221
+ findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
6222
+ }
6223
+ } else if (operation.action === "replace") {
6224
+ if (!operation.original_exists) {
6225
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
6226
+ } else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
6227
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
6228
+ }
6229
+ } else if (operation.mode !== null) {
6230
+ findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
6231
+ }
6232
+ }
6233
+ return findings;
6234
+ }
6235
+ async function probeDirectory(absolutePath) {
6236
+ try {
6237
+ const info = await stat(absolutePath);
6238
+ return { exists: info.isDirectory(), device: info.dev };
6239
+ } catch (error) {
6240
+ const code = error.code;
6241
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
6242
+ throw error;
6243
+ }
6244
+ }
6245
+ async function planRestructure(root, input) {
6246
+ const schemaErrors = await validateDomainContract("mapping", input);
6247
+ if (schemaErrors.length > 0) {
6248
+ return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
6249
+ }
6250
+ const mapping = input;
6251
+ const blockers = [];
6252
+ const unresolved = [...mapping.unresolved];
6253
+ const requestErrors = await validateDomainContract("request", mapping.request);
6254
+ if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
6255
+ if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
6256
+ const currentConfig = await configSnapshot(root);
6257
+ if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
6258
+ const schema = await loadConfig(root);
6259
+ const beforeGraph = await scanArtifacts(root, schema);
6260
+ const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
6261
+ const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
6262
+ const seenSourceUids = /* @__PURE__ */ new Set();
6263
+ for (const source of mapping.sources) {
6264
+ const uid = `${source.type}:${source.id}`;
6265
+ if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
6266
+ seenSourceUids.add(uid);
6267
+ 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));
6268
+ }
6269
+ for (const requested of mapping.request.sources) {
6270
+ const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
6271
+ const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
6272
+ if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
6273
+ }
6274
+ for (const source of mapping.sources) {
6275
+ if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
6276
+ blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
6277
+ }
6278
+ }
6279
+ const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
6280
+ const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
6281
+ for (const occurrence of requiredOccurrences) {
6282
+ if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
6283
+ }
6284
+ for (const entry of mapping.relation_map) {
6285
+ 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));
6286
+ }
6287
+ const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
6288
+ const targetKeys = /* @__PURE__ */ new Set();
6289
+ const targetUids = /* @__PURE__ */ new Set();
6290
+ for (const target of mapping.targets) {
6291
+ const path = normalizeRelativePath2(target.path);
6292
+ if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
6293
+ if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
6294
+ targetKeys.add(target.key);
6295
+ 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));
6296
+ const uid = `${target.type}:${target.id}`;
6297
+ if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
6298
+ targetUids.add(uid);
6299
+ if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
6300
+ blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
6301
+ }
6302
+ 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));
6303
+ if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
6304
+ }
6305
+ for (const identity of mapping.identity_map) {
6306
+ 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}`));
6307
+ }
6308
+ for (const source of mapping.sources) {
6309
+ const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
6310
+ 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));
6311
+ 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));
6312
+ }
6313
+ const snapshots = /* @__PURE__ */ new Map();
6314
+ const buffers = /* @__PURE__ */ new Map();
6315
+ for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
6316
+ const normalized = normalizeRelativePath2(expected.path);
6317
+ if (!normalized) {
6318
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6319
+ continue;
6320
+ }
6321
+ if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
6322
+ blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
6323
+ continue;
6324
+ }
6325
+ const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
6326
+ if (actual) snapshots.set(normalized, actual);
6327
+ const raw = await readContainedFile(root, normalized);
6328
+ if (raw) buffers.set(normalized, raw);
6329
+ }
6330
+ snapshots.set(currentConfig.path, currentConfig);
6331
+ const declaredSnapshots = [
6332
+ mapping.config_snapshot,
6333
+ ...mapping.sources.map((source) => source.snapshot),
6334
+ ...mapping.targets.map((target) => target.snapshot)
6335
+ ];
6336
+ const checkedDeclaredModes = /* @__PURE__ */ new Set();
6337
+ for (const declared of declaredSnapshots) {
6338
+ const declaredMode = declared.mode ?? null;
6339
+ const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
6340
+ const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
6341
+ if (checkedDeclaredModes.has(key)) continue;
6342
+ checkedDeclaredModes.add(key);
6343
+ if (!isPosixFileMode(declaredMode)) {
6344
+ blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
6345
+ } else if (declared.exists && declaredMode === null) {
6346
+ blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
6347
+ } else if (!declared.exists && declaredMode !== null) {
6348
+ blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
6349
+ }
6350
+ }
6351
+ const moveIds = /* @__PURE__ */ new Set();
6352
+ const rangesByPath = /* @__PURE__ */ new Map();
6353
+ const fragments = /* @__PURE__ */ new Map();
6354
+ for (const move of mapping.content_moves) {
6355
+ if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
6356
+ moveIds.add(move.id);
6357
+ const sourcePath = normalizeRelativePath2(move.source.path);
6358
+ const targetPath = normalizeRelativePath2(move.target.path);
6359
+ if (!sourcePath || !buffers.has(sourcePath)) {
6360
+ blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
6361
+ continue;
6362
+ }
6363
+ if (!targetPath || !isPathAllowed(targetPath, allowed)) {
6364
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
6365
+ continue;
6366
+ }
6367
+ const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
6368
+ if (!fragment) continue;
6369
+ fragments.set(move.id, fragment);
6370
+ const pathMoves = rangesByPath.get(sourcePath) ?? [];
6371
+ for (const existing of pathMoves) {
6372
+ if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
6373
+ 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;
6374
+ if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
6375
+ }
6376
+ }
6377
+ pathMoves.push(move);
6378
+ rangesByPath.set(sourcePath, pathMoves);
6379
+ if (dirname5(sourcePath) !== dirname5(targetPath)) {
6380
+ for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6381
+ const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6382
+ if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
6383
+ }
6384
+ }
6385
+ }
6386
+ for (const source of mapping.sources) {
6387
+ const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
6388
+ const raw = buffers.get(source.path);
6389
+ if (!node || !raw) continue;
6390
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
6391
+ blockers.push(...boundary.blockers);
6392
+ 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));
6393
+ if (source.type === "feature" && source.disposition === "retired") {
6394
+ const criteria = acceptanceCriteria(node);
6395
+ const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
6396
+ 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));
6397
+ }
6398
+ }
6399
+ const candidateBuffers = /* @__PURE__ */ new Map();
6400
+ const touched = /* @__PURE__ */ new Set();
6401
+ for (const [sourcePath, moves] of rangesByPath) {
6402
+ const original = buffers.get(sourcePath);
6403
+ const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
6404
+ const chunks = [];
6405
+ let cursor = 0;
6406
+ for (const move of removals) {
6407
+ chunks.push(original.subarray(cursor, move.source.start_byte));
6408
+ cursor = move.source.end_byte;
6409
+ }
6410
+ chunks.push(original.subarray(cursor));
6411
+ candidateBuffers.set(sourcePath, Buffer.concat(chunks));
6412
+ touched.add(sourcePath);
6413
+ }
6414
+ const movesByTarget = /* @__PURE__ */ new Map();
6415
+ for (const move of mapping.content_moves) {
6416
+ const targetPath = normalizeRelativePath2(move.target.path);
6417
+ if (!targetPath || !fragments.has(move.id)) continue;
6418
+ const list = movesByTarget.get(targetPath) ?? [];
6419
+ list.push(move);
6420
+ movesByTarget.set(targetPath, list);
6421
+ }
6422
+ for (const [targetPath, moves] of movesByTarget) {
6423
+ const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
6424
+ const appended = [base];
6425
+ for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
6426
+ const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
6427
+ appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
6428
+ }
6429
+ candidateBuffers.set(targetPath, Buffer.concat(appended));
6430
+ touched.add(targetPath);
6431
+ if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
6432
+ }
6433
+ for (const header of mapping.file_headers) {
6434
+ const path = normalizeRelativePath2(header.path);
6435
+ if (!path || !isPathAllowed(path, allowed)) {
6436
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
6437
+ continue;
6438
+ }
6439
+ if (header.affected_records.length === 0 && header.content === "") {
6440
+ const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
6441
+ if (unselected.length > 0) {
6442
+ blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
6443
+ } else {
6444
+ candidateBuffers.set(path, Buffer.alloc(0));
6445
+ touched.add(path);
6446
+ }
6447
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6448
+ continue;
6449
+ }
6450
+ const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6451
+ candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
6452
+ touched.add(path);
6453
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6454
+ }
6455
+ for (const edit of mapping.prose_edits) {
6456
+ const path = normalizeRelativePath2(edit.target_path);
6457
+ const sourcePath = normalizeRelativePath2(edit.source.path);
6458
+ if (!path || !sourcePath || !buffers.has(sourcePath)) {
6459
+ blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
6460
+ continue;
6461
+ }
6462
+ if (!isPathAllowed(path, allowed)) {
6463
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
6464
+ continue;
6465
+ }
6466
+ if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
6467
+ const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6468
+ const occurrences = current.split(edit.old_text).length - 1;
6469
+ if (!edit.old_text || occurrences !== 1) {
6470
+ blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
6471
+ continue;
6472
+ }
6473
+ candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
6474
+ touched.add(path);
6475
+ }
6476
+ const candidates = [];
6477
+ const umask = planningUmask();
6478
+ for (const path of [...touched].sort()) {
6479
+ if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
6480
+ const original = buffers.get(path);
6481
+ const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
6482
+ if (original && original.equals(candidate)) continue;
6483
+ const deleteFile = candidate.byteLength === 0;
6484
+ const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
6485
+ const action = deleteFile ? "delete" : original ? "replace" : "create";
6486
+ candidates.push({
6487
+ path,
6488
+ action,
6489
+ content: deleteFile ? null : candidate.toString("utf8"),
6490
+ sha256: deleteFile ? null : digestBytes(candidate),
6491
+ mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
6492
+ original: snapshot,
6493
+ diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6494
+ });
6495
+ }
6496
+ const rootDirectory = await probeDirectory(resolve6(root));
6497
+ const parentProbes = /* @__PURE__ */ new Map();
6498
+ for (const candidate of candidates) {
6499
+ const parent = dirname5(candidate.path);
6500
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve6(root, parent)));
6501
+ }
6502
+ blockers.push(...restructureBoundaryFindings(
6503
+ candidates.map((candidate) => {
6504
+ const parent = parentProbes.get(dirname5(candidate.path));
6505
+ return {
6506
+ path: candidate.path,
6507
+ action: candidate.action,
6508
+ original_exists: candidate.original.exists,
6509
+ original_mode: candidate.original.mode,
6510
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6511
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6512
+ mode: candidate.mode,
6513
+ parent_exists: parent.exists,
6514
+ parent_device: parent.device,
6515
+ root_device: rootDirectory.device ?? -1
6516
+ };
6517
+ }),
6518
+ {
6519
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6520
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6521
+ umask
6522
+ }
6523
+ ));
6524
+ const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
6525
+ const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
6526
+ const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
6527
+ const candidateIssues = validateGraph(afterGraph, schema);
6528
+ for (const issue2 of candidateIssues) {
6529
+ if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
6530
+ }
6531
+ const afterTriples = relationTriples(afterGraph);
6532
+ for (const expected of expectedRelationTargets(mapping)) {
6533
+ if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
6534
+ }
6535
+ for (const source of mapping.sources) {
6536
+ const uid = `${source.type}:${source.id}`;
6537
+ const present = afterGraph.nodes.some((node) => node.uid === uid);
6538
+ if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
6539
+ if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
6540
+ }
6541
+ for (const criterion of mapping.criterion_map) {
6542
+ const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
6543
+ 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));
6544
+ for (const target of criterion.targets) {
6545
+ const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
6546
+ 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));
6547
+ }
6548
+ }
6549
+ for (const header of mapping.file_headers) {
6550
+ const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
6551
+ const declaredRecords = [...header.affected_records].sort();
6552
+ 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));
6553
+ }
6554
+ const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
6555
+ for (const move of mapping.content_moves) {
6556
+ if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
6557
+ for (const path of [move.source.path, move.target.path]) {
6558
+ 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));
6559
+ }
6560
+ }
6561
+ for (const target of mapping.targets) {
6562
+ 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));
6563
+ }
6564
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6565
+ root,
6566
+ [...new Set(mapping.sources.map((source) => source.path))],
6567
+ [...new Set([
6568
+ ...mapping.targets.map((target) => target.path),
6569
+ ...mapping.content_moves.map((move) => move.target.path),
6570
+ ...mapping.file_headers.map((header) => header.path)
6571
+ ].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
6572
+ ));
6573
+ for (const move of mapping.content_moves) {
6574
+ const fragment = fragments.get(move.id);
6575
+ const sourcePath = normalizeRelativePath2(move.source.path);
6576
+ const targetPath = normalizeRelativePath2(move.target.path);
6577
+ if (!fragment || !sourcePath || !targetPath) continue;
6578
+ const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
6579
+ const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
6580
+ for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
6581
+ if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
6582
+ blockers.push(finding(
6583
+ "FOOTNOTE_DEFINITION_UNMAPPED",
6584
+ `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`,
6585
+ sourcePath
6586
+ ));
6587
+ }
6588
+ }
6589
+ const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
6590
+ const plan = {
6591
+ schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
6592
+ operation_id: randomUUID2(),
6593
+ validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6594
+ request_digest: mapping.request_digest,
6595
+ mapping_digest: digestRestructureValue(mapping),
6596
+ config_snapshot: currentConfig,
6597
+ input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
6598
+ candidates,
6599
+ graph_diff: graphDiff(beforeGraph, afterGraph),
6600
+ validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
6601
+ applicable: blockers.length === 0 && unresolved.length === 0
6602
+ };
6603
+ const planErrors = await validateDomainContract("plan", plan);
6604
+ if (planErrors.length > 0) {
6605
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
6606
+ }
6607
+ return { ok: true, data: plan };
6608
+ }
6609
+ async function gateRestructureOperationPlan(operation, plan) {
6610
+ const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
6611
+ if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
6612
+ return {
6613
+ ok: false,
6614
+ error: {
6615
+ code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
6616
+ message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
6617
+ }
6618
+ };
6619
+ }
6620
+ const errors = await validateDomainContract("plan", plan);
6621
+ if (errors.length > 0) {
6622
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
6623
+ }
6624
+ return { ok: true, data: plan };
6625
+ }
6626
+ function refusal(code, message, findings = []) {
6627
+ return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
6628
+ }
6629
+ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6630
+ const absolute = resolve6(planPath);
6631
+ let info;
6632
+ try {
6633
+ info = await lstat3(absolute);
6634
+ } catch (cause) {
6635
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6636
+ }
6637
+ if (info.isSymbolicLink() || !info.isFile()) {
6638
+ return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
6639
+ }
6640
+ let bytes;
6641
+ try {
6642
+ bytes = await readFile3(absolute);
6643
+ } catch (cause) {
6644
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6645
+ }
6646
+ let parsed;
6647
+ try {
6648
+ parsed = JSON.parse(bytes.toString("utf8"));
6649
+ } catch (cause) {
6650
+ return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
6651
+ }
6652
+ const gate = await gateRestructureOperationPlan(operation, parsed);
6653
+ if (!gate.ok) return gate;
6654
+ return { ok: true, data: { path: absolute, realPath: await realpath2(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
6655
+ }
6656
+ function planRootIdentityFindings(document) {
6657
+ const findings = [];
6658
+ const record = (path, label) => {
6659
+ const normalized = normalizeRelativePath2(path);
6660
+ if (!normalized || normalized !== path) {
6661
+ findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
6662
+ }
6663
+ };
6664
+ record(document.plan.config_snapshot.path, "config_snapshot");
6665
+ for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
6666
+ for (const candidate of document.plan.candidates) {
6667
+ record(candidate.path, "candidate");
6668
+ record(candidate.original.path, "candidate original");
6669
+ }
6670
+ if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
6671
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6672
+ }
6673
+ const relativePlan = relative4(document.root, document.realPath);
6674
+ if (!relativePlan || relativePlan.startsWith("..") || isAbsolute4(relativePlan)) {
6675
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6676
+ }
6677
+ return findings;
6678
+ }
6679
+ async function operationBoundaries(root, plan) {
6680
+ const rootDirectory = await probeDirectory(resolve6(root));
6681
+ const parents = /* @__PURE__ */ new Map();
6682
+ const boundaries = [];
6683
+ for (const candidate of plan.candidates) {
6684
+ const parent = dirname5(candidate.path) || ".";
6685
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve6(root, parent)));
6686
+ const probe = parents.get(parent);
6687
+ boundaries.push({
6688
+ path: candidate.path,
6689
+ action: candidate.action,
6690
+ original_exists: candidate.original.exists,
6691
+ original_mode: candidate.original.mode,
6692
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6693
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6694
+ mode: candidate.mode,
6695
+ parent_exists: probe.exists,
6696
+ parent_device: probe.device,
6697
+ root_device: rootDirectory.device ?? -1
6698
+ });
6699
+ }
6700
+ return boundaries;
6701
+ }
6702
+ async function applyPreconditionFindings(root, document) {
6703
+ const findings = [];
6704
+ const plan = document.plan;
6705
+ const currentConfig = await configSnapshot(root);
6706
+ if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
6707
+ findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
6708
+ }
6709
+ for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
6710
+ const relativePlan = relative4(root, document.realPath).replace(/\\/g, "/");
6711
+ for (const candidate of plan.candidates) {
6712
+ if (candidate.path === relativePlan) {
6713
+ findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
6714
+ }
6715
+ if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
6716
+ findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
6717
+ }
6718
+ let original;
6719
+ try {
6720
+ original = await snapshotFile(root, candidate.path);
6721
+ } catch (cause) {
6722
+ findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
6723
+ continue;
6724
+ }
6725
+ if (!sameSnapshot(original, candidate.original)) {
6726
+ findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
6727
+ }
6728
+ if (candidate.action === "delete") continue;
6729
+ if (candidate.mode === null) {
6730
+ findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
6731
+ }
6732
+ if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
6733
+ findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
6734
+ }
6735
+ }
6736
+ findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
6737
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6738
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6739
+ umask: planningUmask(),
6740
+ mode_contract: "apply"
6741
+ }));
6742
+ return findings;
6743
+ }
6744
+ function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
6745
+ const excludedConsumers = new Set(excludedConsumerPaths);
6746
+ const addedNodes = plan.graph_diff.added_nodes;
6747
+ const removedNodes = new Set(plan.graph_diff.removed_nodes);
6748
+ const addedEdges = plan.graph_diff.added_edges;
6749
+ const removedEdges = new Set(plan.graph_diff.removed_edges);
6750
+ const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
6751
+ const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
6752
+ const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
6753
+ return async function validateCandidateState(input) {
6754
+ const schema = await loadConfig(input.root);
6755
+ const graph = await scanArtifacts(input.root, schema);
6756
+ if (input.signal.aborted) return { passed: false };
6757
+ const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6758
+ const edges = new Set(graph.edges.map(edgeDisplay));
6759
+ const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
6760
+ const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
6761
+ const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
6762
+ const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
6763
+ const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
6764
+ const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
6765
+ return { passed };
6766
+ };
6767
+ }
6768
+ async function applyRestructure(input) {
6769
+ if (input.confirmCooperativeWriters !== true) {
6770
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
6771
+ }
6772
+ const qualification = await qualifyRestructureMechanism(input.root);
6773
+ if (!qualification.ok) return qualification;
6774
+ const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
6775
+ if (!document.ok) return document;
6776
+ const plan = document.data.plan;
6777
+ if (plan.candidates.length === 0) {
6778
+ return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
6779
+ }
6780
+ if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
6781
+ return refusal(
6782
+ "PLAN_NOT_APPLICABLE",
6783
+ "The plan is not applicable: it still carries blockers or unresolved findings",
6784
+ [...plan.validation.blockers, ...plan.validation.unresolved]
6785
+ );
6786
+ }
6787
+ const identity = planRootIdentityFindings(document.data);
6788
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6789
+ const drift = await applyPreconditionFindings(qualification.data.root, document.data);
6790
+ if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
6791
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
6792
+ if (!mechanismRoot.ok) return mechanismRoot;
6793
+ const planRelPath = relative4(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
6794
+ const applied = await applyRestructureFileSet(qualification.data.root, plan, {
6795
+ validate: createRestructureValidationCallback(plan, [planRelPath])
6796
+ });
6797
+ if (!applied.ok) return applied;
6798
+ const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
6799
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
6800
+ }
6801
+ async function recoverRestructure(input) {
6802
+ if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
6803
+ return refusal(
6804
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
6805
+ "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
6806
+ );
6807
+ }
6808
+ const qualification = await qualifyRestructureMechanism(input.root);
6809
+ if (!qualification.ok) return qualification;
6810
+ const document = await loadRestructurePlanDocument("recover", qualification.data.root, input.planPath);
6811
+ if (!document.ok) return document;
6812
+ const identity = planRootIdentityFindings(document.data);
6813
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6814
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
6815
+ if (!mechanismRoot.ok) return mechanismRoot;
6816
+ const recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
6817
+ allParticipantsStopped: true,
6818
+ exclusiveMaintenance: true
6819
+ });
6820
+ if (!recovered.ok) return recovered;
6821
+ const projection = projectRestructureFileSetResult(recovered.data, document.data.realPath, document.data.digest);
6822
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
6823
+ }
6824
+ async function pruneRestructureRecovery(input) {
6825
+ if (input.confirmCooperativeWriters !== true) {
6826
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
6827
+ }
6828
+ if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
6829
+ return refusal(
6830
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
6831
+ "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
6832
+ );
6833
+ }
6834
+ const qualification = await qualifyRestructureMechanism(input.root);
6835
+ if (!qualification.ok) return qualification;
6836
+ const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
6837
+ if (!document.ok) return document;
6838
+ const identity = planRootIdentityFindings(document.data);
6839
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6840
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
6841
+ if (!mechanismRoot.ok) return mechanismRoot;
6842
+ const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
6843
+ allParticipantsStopped: input.allParticipantsStopped,
6844
+ exclusiveMaintenance: input.exclusiveMaintenance
6845
+ });
6846
+ if (!pruned.ok) return pruned;
6847
+ const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
6848
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
6849
+ }
6850
+ var RESTRUCTURE_PLAN_SCHEMA_VERSION, RESTRUCTURE_VALIDATION_TIMEOUT_MS, RESTRUCTURE_MAX_OPERATIONS, RESTRUCTURE_MAX_TOTAL_BYTES, MAX_POSIX_MODE, CREATE_MODE_BASE, MODULE_DIRECTORY, CONTRACT_ROOT, SKIPPED_SCAN_DIRS, TEXT_EXTENSIONS, MARKDOWN_LINK_PATTERN, RUNTIME_PATH_MARKER, MARKDOWN_FILE_SUFFIX, SCRIPT_FILE_SUFFIX;
6851
+ var init_restructure = __esm({
6852
+ "src/restructure.ts"() {
6853
+ "use strict";
6854
+ init_index();
6855
+ init_contract_kernel();
6856
+ init_restructure_software();
6857
+ init_restructure_file_set();
6858
+ RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
6859
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
6860
+ RESTRUCTURE_MAX_OPERATIONS = 1024;
6861
+ RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
6862
+ MAX_POSIX_MODE = 511;
6863
+ CREATE_MODE_BASE = 438;
6864
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname5(fileURLToPath2(import.meta.url));
6865
+ CONTRACT_ROOT = join9(MODULE_DIRECTORY, "..", "contracts");
6866
+ SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
6867
+ TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
6868
+ MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
6869
+ RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
6870
+ MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
6871
+ SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
6872
+ }
6873
+ });
6874
+
5149
6875
  // src/index.ts
5150
6876
  import matter from "gray-matter";
5151
6877
  import yaml from "js-yaml";
5152
6878
  import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
5153
- import { mkdir as mkdir4, readFile as readFile3, readdir as readdir3, writeFile as writeFile3 } from "fs/promises";
5154
- import { basename as basename4, dirname as dirname5, extname, isAbsolute as isAbsolute4, join as join8, relative as relative4, resolve as resolve5 } from "path";
6879
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
6880
+ import { basename as basename4, dirname as dirname6, extname, isAbsolute as isAbsolute5, join as join10, resolve as resolve7 } from "path";
5155
6881
  function isTargetArtifactType(type) {
5156
6882
  return isPacketTargetType(type);
5157
6883
  }
@@ -5193,10 +6919,10 @@ function resolveArtifactTypeName(schema, token) {
5193
6919
  return void 0;
5194
6920
  }
5195
6921
  async function loadConfig(root) {
5196
- const configPath = join8(root, "artifact-graph.config.yaml");
6922
+ const configPath = join10(root, "artifact-graph.config.yaml");
5197
6923
  let parsed = {};
5198
6924
  try {
5199
- const raw = await readFile3(configPath, "utf-8");
6925
+ const raw = await readFile4(configPath, "utf-8");
5200
6926
  parsed = yaml.load(raw) ?? {};
5201
6927
  } catch (error) {
5202
6928
  if (error.code !== "ENOENT") {
@@ -5322,7 +7048,7 @@ function validateE2eConfig(e2e) {
5322
7048
  if (typeof runner.root !== "string" || !runner.root.trim()) {
5323
7049
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
5324
7050
  }
5325
- if (isAbsolute4(runner.root)) {
7051
+ if (isAbsolute5(runner.root)) {
5326
7052
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
5327
7053
  }
5328
7054
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -5385,14 +7111,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
5385
7111
  diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
5386
7112
  };
5387
7113
  }
5388
- async function scanArtifacts(root, schema) {
7114
+ async function scanArtifacts(root, schema, options = {}) {
5389
7115
  const config = schema ?? await loadConfig(root);
5390
7116
  const nodes = [];
5391
7117
  const edges = [];
5392
7118
  const scanDiagnostics = [];
5393
7119
  const scannedFiles = /* @__PURE__ */ new Map();
7120
+ const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
5394
7121
  for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
5395
- const files = await findFiles(root, definition.paths);
7122
+ const diskFiles = await findFiles(root, definition.paths);
7123
+ const files = [.../* @__PURE__ */ new Set([
7124
+ ...diskFiles.filter((file) => contentOverrides.get(file) !== null),
7125
+ ...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
7126
+ ])].sort();
5396
7127
  for (const file of files) {
5397
7128
  if (scannedFiles.has(file)) {
5398
7129
  const existingType = scannedFiles.get(file);
@@ -5406,7 +7137,7 @@ async function scanArtifacts(root, schema) {
5406
7137
  continue;
5407
7138
  }
5408
7139
  scannedFiles.set(file, type);
5409
- const raw = await readFile3(join8(root, file), "utf-8");
7140
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join10(root, file), "utf-8");
5410
7141
  const parsed = parseFile(type, file, raw, config);
5411
7142
  const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
5412
7143
  nodes.push(...parsed.nodes);
@@ -5414,7 +7145,7 @@ async function scanArtifacts(root, schema) {
5414
7145
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
5415
7146
  }
5416
7147
  }
5417
- const absoluteRoot = isAbsolute4(root) ? root : resolve5(root);
7148
+ const absoluteRoot = isAbsolute5(root) ? root : resolve7(root);
5418
7149
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
5419
7150
  return resolveMatrixEdges(graph);
5420
7151
  }
@@ -5697,13 +7428,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
5697
7428
  const scenarioFeatureRefs = /* @__PURE__ */ new Map();
5698
7429
  const featureScenarioRefs = /* @__PURE__ */ new Map();
5699
7430
  for (const node of scenarioNodes) {
5700
- scenarioFeatureRefs.set(node.uid, relationOccurrences(node, "\u5173\u8054\u529F\u80FD", "feature"));
7431
+ scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
5701
7432
  if (!scenarioPattern.test(node.code)) {
5702
7433
  issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
5703
7434
  }
5704
7435
  }
5705
7436
  for (const node of featureNodes) {
5706
- featureScenarioRefs.set(node.uid, relationOccurrences(node, "scenarios", "scenario"));
7437
+ featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
5707
7438
  if (!featurePattern.test(node.code)) {
5708
7439
  issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
5709
7440
  }
@@ -5777,7 +7508,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5777
7508
  const indexPath = "artifacts/prd/feature-index.md";
5778
7509
  let raw = "";
5779
7510
  try {
5780
- raw = await readFile3(join8(root, indexPath), "utf-8");
7511
+ raw = await readFile4(join10(root, indexPath), "utf-8");
5781
7512
  } catch (error) {
5782
7513
  if (error.code === "ENOENT") {
5783
7514
  return [];
@@ -5797,7 +7528,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5797
7528
  if (!feature) {
5798
7529
  return;
5799
7530
  }
5800
- const actualCount = relationOccurrences(feature, "scenarios", "scenario").length;
7531
+ const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
5801
7532
  if (actualCount !== expectedCount) {
5802
7533
  issues.push(issue(
5803
7534
  "INDEX_MISMATCH",
@@ -6025,12 +7756,12 @@ function nextId(graph, schema, type, rangeName) {
6025
7756
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
6026
7757
  }
6027
7758
  async function writeGraphCache(root, graph) {
6028
- const cacheDir = join8(root, ".artifact-graph");
6029
- await mkdir4(cacheDir, { recursive: true });
6030
- await writeFile3(join8(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
7759
+ const cacheDir = join10(root, ".artifact-graph");
7760
+ await mkdir5(cacheDir, { recursive: true });
7761
+ await writeFile3(join10(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
6031
7762
  `);
6032
7763
  const { default: Database } = await import("better-sqlite3");
6033
- const db = new Database(join8(cacheDir, "graph.sqlite"));
7764
+ const db = new Database(join10(cacheDir, "graph.sqlite"));
6034
7765
  try {
6035
7766
  db.exec(`
6036
7767
  DROP TABLE IF EXISTS nodes;
@@ -6392,7 +8123,7 @@ function parseFeature(path, raw) {
6392
8123
  }
6393
8124
  function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
6394
8125
  const lines = raw.split(/\r?\n/);
6395
- const codeLines = markdownCodeLineMask(lines);
8126
+ const codeLines = markdownCodeLineMask2(lines);
6396
8127
  const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
6397
8128
  const starts = [];
6398
8129
  lines.forEach((line, index) => {
@@ -6810,13 +8541,7 @@ function parseE2eTest(path, raw) {
6810
8541
  const parsed = matter(raw);
6811
8542
  const data = parsed.data;
6812
8543
  const lines = raw.split(/\r?\n/);
6813
- const starts = [];
6814
- lines.forEach((line, index) => {
6815
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
6816
- if (match) {
6817
- starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
6818
- }
6819
- });
8544
+ const starts = extractE2eTestCaseStarts(lines);
6820
8545
  const nodes = [];
6821
8546
  const edges = [];
6822
8547
  const batch = String(data.test_batch ?? basename4(path, extname(path))).trim();
@@ -6825,26 +8550,6 @@ function parseE2eTest(path, raw) {
6825
8550
  const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
6826
8551
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
6827
8552
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
6828
- if (starts.length === 0) {
6829
- const code = `${batch}:FILE`;
6830
- nodes.push({
6831
- type: "e2e_test",
6832
- code,
6833
- title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
6834
- path,
6835
- line: 1,
6836
- attrs: {
6837
- ...data,
6838
- testCaseId: "FILE",
6839
- fileLevelOnly: true,
6840
- tcFields: {},
6841
- blockText: raw,
6842
- coveredFeatures: [],
6843
- coveredScenarios: []
6844
- }
6845
- });
6846
- addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
6847
- }
6848
8553
  for (let index = 0; index < starts.length; index += 1) {
6849
8554
  const start = starts[index];
6850
8555
  const end = starts[index + 1]?.index ?? lines.length;
@@ -6870,6 +8575,16 @@ function parseE2eTest(path, raw) {
6870
8575
  }
6871
8576
  return { nodes, edges };
6872
8577
  }
8578
+ function extractE2eTestCaseStarts(lines) {
8579
+ const codeLines = markdownCodeLineMask2(lines);
8580
+ return lines.flatMap((line, index) => {
8581
+ if (codeLines[index]) {
8582
+ return [];
8583
+ }
8584
+ const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
8585
+ return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
8586
+ });
8587
+ }
6873
8588
  function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
6874
8589
  for (const scenario of scenarios) {
6875
8590
  edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
@@ -7654,7 +9369,7 @@ function matchExplicitRelationFieldLine(line, label) {
7654
9369
  const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
7655
9370
  return match?.[1] ?? null;
7656
9371
  }
7657
- function markdownCodeLineMask(lines) {
9372
+ function markdownCodeLineMask2(lines) {
7658
9373
  const result = new Array(lines.length).fill(false);
7659
9374
  let fence;
7660
9375
  lines.forEach((line, index) => {
@@ -7699,7 +9414,7 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
7699
9414
  });
7700
9415
  return result;
7701
9416
  }
7702
- function relationOccurrences(node, field, targetType) {
9417
+ function relationOccurrences2(node, field, targetType) {
7703
9418
  const relationRecord = asRecord(node.attrs?.relationOccurrences);
7704
9419
  const rawOccurrences = toArray(relationRecord[field]);
7705
9420
  return rawOccurrences.flatMap((value) => {
@@ -7898,6 +9613,9 @@ function validateE2eRegistry(graph) {
7898
9613
  }
7899
9614
  const actualNodes = byPath.get(file) ?? [];
7900
9615
  if (actualNodes.length === 0) {
9616
+ if (Number(batch.test_case_count ?? NaN) === 0) {
9617
+ continue;
9618
+ }
7901
9619
  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" }));
7902
9620
  continue;
7903
9621
  }
@@ -7918,31 +9636,21 @@ function validateE2eRegistry(graph) {
7918
9636
  async function validateExecutableTraceability(root, config) {
7919
9637
  const issues = [];
7920
9638
  const schema = config ?? await loadConfig(root);
7921
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
7922
- let e2eFiles;
7923
- try {
7924
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
7925
- } catch {
9639
+ const e2eFiles = await findConfiguredE2eFiles(root, schema);
9640
+ if (e2eFiles.length === 0) {
7926
9641
  return [];
7927
9642
  }
7928
9643
  const mdToRef = /* @__PURE__ */ new Map();
7929
9644
  const allMdTcInfo = /* @__PURE__ */ new Map();
7930
9645
  const tcKeyToFields = /* @__PURE__ */ new Map();
7931
9646
  const mdBatches = /* @__PURE__ */ new Set();
7932
- for (const filePath of e2eFiles) {
7933
- const raw = await readFile3(filePath, "utf-8");
7934
- const relPath = relative4(root, filePath).split("\\").join("/");
9647
+ for (const relPath of e2eFiles) {
9648
+ const raw = await readFile4(join10(root, relPath), "utf-8");
7935
9649
  const parsed = matter(raw);
7936
9650
  const data = parsed.data;
7937
- const batch = String(data.test_batch ?? basename4(filePath, extname(filePath))).trim();
9651
+ const batch = String(data.test_batch ?? basename4(relPath, extname(relPath))).trim();
7938
9652
  const lines = raw.split(/\r?\n/);
7939
- const tcStarts = [];
7940
- lines.forEach((line, index) => {
7941
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
7942
- if (match) {
7943
- tcStarts.push({ id: match[1], line: index + 1, index });
7944
- }
7945
- });
9653
+ const tcStarts = extractE2eTestCaseStarts(lines);
7946
9654
  for (let i = 0; i < tcStarts.length; i += 1) {
7947
9655
  const start = tcStarts[i];
7948
9656
  const end = tcStarts[i + 1]?.index ?? lines.length;
@@ -7979,10 +9687,10 @@ async function validateExecutableTraceability(root, config) {
7979
9687
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
7980
9688
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
7981
9689
  for (const specFile of specFiles) {
7982
- const fullSpecPath = join8(root, specFile);
9690
+ const fullSpecPath = join10(root, specFile);
7983
9691
  let content;
7984
9692
  try {
7985
- content = await readFile3(fullSpecPath, "utf-8");
9693
+ content = await readFile4(fullSpecPath, "utf-8");
7986
9694
  } catch {
7987
9695
  continue;
7988
9696
  }
@@ -8061,7 +9769,7 @@ async function validateExecutableTraceability(root, config) {
8061
9769
  if (entry.testId) {
8062
9770
  let content;
8063
9771
  try {
8064
- content = await readFile3(join8(root, normalizedRefFile), "utf-8");
9772
+ content = await readFile4(join10(root, normalizedRefFile), "utf-8");
8065
9773
  } catch {
8066
9774
  continue;
8067
9775
  }
@@ -8089,7 +9797,7 @@ async function validateExecutableTraceability(root, config) {
8089
9797
  }
8090
9798
  continue;
8091
9799
  }
8092
- if (!mdToRef.has(tcKey) && !await hasMarkdownTc(tcKey, e2eDir)) {
9800
+ if (!allMdTcInfo.has(tcKey)) {
8093
9801
  for (const ann of annotations) {
8094
9802
  issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
8095
9803
  }
@@ -8238,34 +9946,10 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8238
9946
  let withExecutableRef = 0;
8239
9947
  const statusBreakdown = {};
8240
9948
  const chainTypeBreakdown = {};
8241
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8242
- const tcFieldsMap = /* @__PURE__ */ new Map();
8243
- let e2eFiles;
8244
- try {
8245
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
8246
- } catch {
8247
- e2eFiles = [];
8248
- }
8249
- for (const filePath of e2eFiles) {
8250
- const raw = await readFile3(filePath, "utf-8");
8251
- const lines = raw.split(/\r?\n/);
8252
- const tcStarts = [];
8253
- lines.forEach((line, index) => {
8254
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8255
- if (match) {
8256
- tcStarts.push({ id: match[1], index });
8257
- }
8258
- });
8259
- const parsed = matter(raw);
8260
- const batch = String(parsed.data.test_batch ?? basename4(filePath, extname(filePath))).trim();
8261
- for (let i = 0; i < tcStarts.length; i++) {
8262
- const start = tcStarts[i];
8263
- const end = tcStarts[i + 1]?.index ?? lines.length;
8264
- const block = lines.slice(start.index, end);
8265
- const fields = extractE2eTcFields(block);
8266
- tcFieldsMap.set(`${batch}:${start.id}`, fields);
8267
- }
8268
- }
9949
+ const tcFieldsMap = new Map(e2eNodes.map((node) => [
9950
+ node.code,
9951
+ asRecord(node.attrs?.tcFields)
9952
+ ]));
8269
9953
  for (const node of e2eNodes) {
8270
9954
  const tcKey = node.code;
8271
9955
  const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
@@ -8320,7 +10004,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8320
10004
  let hasActiveE2eRef = false;
8321
10005
  for (const entry of parseExecutableRefLines(execRef)) {
8322
10006
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
8323
- if (!normalized || !existsSync3(join8(root, normalized))) continue;
10007
+ if (!normalized || !existsSync3(join10(root, normalized))) continue;
8324
10008
  const accepting = await getAcceptingRunners(root, normalized, runners);
8325
10009
  if (accepting.some((runner) => runner.kind === "e2e")) {
8326
10010
  hasActiveE2eRef = true;
@@ -8379,7 +10063,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8379
10063
  const acCoverageRateByFeature = {};
8380
10064
  const featureAcMap = /* @__PURE__ */ new Map();
8381
10065
  for (const node of featureNodes) {
8382
- const acs = parseAcceptanceCriteria(await readFile3(join8(root, node.path), "utf-8"));
10066
+ const acs = parseAcceptanceCriteria(await readFile4(join10(root, node.path), "utf-8"));
8383
10067
  featureAcMap.set(node.code, new Set(acs));
8384
10068
  }
8385
10069
  const coveredAcByFeature = /* @__PURE__ */ new Map();
@@ -8421,39 +10105,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8421
10105
  };
8422
10106
  }
8423
10107
  async function generateE2eRegistry(root, opts) {
8424
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8425
- let files;
8426
- try {
8427
- files = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
8428
- } catch {
8429
- return {
8430
- registry_version: "1.0",
8431
- generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8432
- total_batches: 0,
8433
- total_test_cases: 0,
8434
- batches: []
8435
- };
8436
- }
10108
+ const schema = await loadConfig(root);
10109
+ const files = await findConfiguredE2eFiles(root, schema);
8437
10110
  const batches = [];
10111
+ const batchIds = /* @__PURE__ */ new Set();
8438
10112
  let totalTestCases = 0;
8439
10113
  for (const file of files) {
8440
- const filePath = join8(e2eDir, file);
8441
- const raw = await readFile3(filePath, "utf-8");
10114
+ const filePath = join10(root, file);
10115
+ const raw = await readFile4(filePath, "utf-8");
8442
10116
  const parsed = matter(raw);
8443
10117
  const data = parsed.data;
8444
10118
  const batch = String(data.test_batch ?? basename4(file, extname(file))).trim();
8445
- const relPath = `artifacts/tests/e2e/${file}`;
10119
+ const relPath = file;
8446
10120
  const scope = String(data.scope ?? "").trim();
8447
10121
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
8448
10122
  const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
8449
10123
  const lines = raw.split(/\r?\n/);
8450
- const tcStarts = [];
8451
- lines.forEach((line, index) => {
8452
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8453
- if (match) {
8454
- tcStarts.push({ id: match[1], index });
8455
- }
8456
- });
10124
+ const tcStarts = extractE2eTestCaseStarts(lines);
10125
+ if (tcStarts.length > 0) {
10126
+ batchIds.add(batch);
10127
+ }
8457
10128
  const statusSummary = {};
8458
10129
  const blockingReasons = {};
8459
10130
  const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
@@ -8462,8 +10133,9 @@ async function generateE2eRegistry(root, opts) {
8462
10133
  blockingReasons[tc.id] = frontmatterFixesBlock;
8463
10134
  }
8464
10135
  }
8465
- for (const start of tcStarts) {
8466
- const end = tcStarts[tcStarts.indexOf(start) + 1]?.index ?? lines.length;
10136
+ for (let index = 0; index < tcStarts.length; index += 1) {
10137
+ const start = tcStarts[index];
10138
+ const end = tcStarts[index + 1]?.index ?? lines.length;
8467
10139
  const block = lines.slice(start.index, end);
8468
10140
  const fields = extractE2eTcFields(block);
8469
10141
  const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
@@ -8496,7 +10168,7 @@ async function generateE2eRegistry(root, opts) {
8496
10168
  return {
8497
10169
  registry_version: "1.0",
8498
10170
  generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8499
- total_batches: batches.length,
10171
+ total_batches: batchIds.size,
8500
10172
  total_test_cases: totalTestCases,
8501
10173
  batches
8502
10174
  };
@@ -8565,10 +10237,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
8565
10237
  if (!normalizedPath) {
8566
10238
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8567
10239
  }
8568
- const fullPath = join8(root, normalizedPath);
10240
+ const fullPath = join10(root, normalizedPath);
8569
10241
  let content;
8570
10242
  try {
8571
- content = await readFile3(fullPath, "utf-8");
10243
+ content = await readFile4(fullPath, "utf-8");
8572
10244
  } catch {
8573
10245
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8574
10246
  }
@@ -8602,7 +10274,7 @@ function detectTestLevel(specFile, content) {
8602
10274
  }
8603
10275
  function resolveExecutableRefFile(refFile, allFiles) {
8604
10276
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
8605
- if (!normalized || isAbsolute4(refFile) || normalized.split("/").includes("..")) {
10277
+ if (!normalized || isAbsolute5(refFile) || normalized.split("/").includes("..")) {
8606
10278
  return void 0;
8607
10279
  }
8608
10280
  if (allFiles.includes(normalized)) {
@@ -8675,17 +10347,6 @@ function splitMarkdownCells(line) {
8675
10347
  function escapeRegExp(value) {
8676
10348
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8677
10349
  }
8678
- async function hasMarkdownTc(tcKey, e2eDir) {
8679
- const [batch, tcId] = tcKey.split(":");
8680
- const filePath = join8(e2eDir, `${batch}.md`);
8681
- try {
8682
- const raw = await readFile3(filePath, "utf-8");
8683
- const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
8684
- return tcRegex.test(raw);
8685
- } catch {
8686
- return false;
8687
- }
8688
- }
8689
10350
  async function findFiles(root, patterns) {
8690
10351
  const all = await walkFiles(root);
8691
10352
  const matched = /* @__PURE__ */ new Set();
@@ -8698,6 +10359,10 @@ async function findFiles(root, patterns) {
8698
10359
  }
8699
10360
  return [...matched].sort();
8700
10361
  }
10362
+ async function findConfiguredE2eFiles(root, schema) {
10363
+ const patterns = schema.types.e2e_test?.paths ?? [];
10364
+ return findFiles(root, patterns);
10365
+ }
8701
10366
  function matchesConfiguredArtifactPath(path, schema) {
8702
10367
  const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
8703
10368
  return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
@@ -8726,8 +10391,13 @@ function extractCodes(text, type, schema) {
8726
10391
  }
8727
10392
  function extractE2eTcFields(block) {
8728
10393
  const fields = {};
10394
+ const codeLines = markdownCodeLineMask2(block);
8729
10395
  let current = "";
8730
- for (const line of block) {
10396
+ for (let index = 0; index < block.length; index += 1) {
10397
+ if (codeLines[index]) {
10398
+ continue;
10399
+ }
10400
+ const line = block[index];
8731
10401
  const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
8732
10402
  if (match) {
8733
10403
  current = match[1].trim();
@@ -9186,14 +10856,14 @@ function resolveArtifactContext(graph, opts) {
9186
10856
  }
9187
10857
  if (root) {
9188
10858
  for (const ap of ALWAYS_PRESENT_ITEMS) {
9189
- const fullPath = join8(root, ap.path);
9190
- let stat2;
10859
+ const fullPath = join10(root, ap.path);
10860
+ let stat3;
9191
10861
  try {
9192
- stat2 = statSync(fullPath);
10862
+ stat3 = statSync(fullPath);
9193
10863
  } catch {
9194
- stat2 = null;
10864
+ stat3 = null;
9195
10865
  }
9196
- if (!stat2) {
10866
+ if (!stat3) {
9197
10867
  const msg = `Required baseline artifact not found: ${ap.path}`;
9198
10868
  if (!missing.includes(msg)) {
9199
10869
  missing.push(msg);
@@ -9205,7 +10875,7 @@ function resolveArtifactContext(graph, opts) {
9205
10875
  suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
9206
10876
  });
9207
10877
  }
9208
- } else if (!stat2.isFile()) {
10878
+ } else if (!stat3.isFile()) {
9209
10879
  const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
9210
10880
  if (!missing.includes(msg)) {
9211
10881
  missing.push(msg);
@@ -9452,6 +11122,9 @@ var init_index = __esm({
9452
11122
  init_hook_installer();
9453
11123
  init_review_result_validator();
9454
11124
  init_contract_kernel();
11125
+ init_restructure();
11126
+ init_restructure_file_set();
11127
+ init_restructure_software();
9455
11128
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
9456
11129
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
9457
11130
  DEFAULT_SCHEMA = {
@@ -9542,8 +11215,8 @@ var init_index = __esm({
9542
11215
  });
9543
11216
 
9544
11217
  // src/packet-prompt-audit.ts
9545
- import { mkdir as mkdir5, writeFile as writeFile4 } from "fs/promises";
9546
- import { join as join9 } from "path";
11218
+ import { mkdir as mkdir6, writeFile as writeFile4 } from "fs/promises";
11219
+ import { join as join11 } from "path";
9547
11220
  function promptFilename(target) {
9548
11221
  return `prompt-${target.type}-${target.id}.md`;
9549
11222
  }
@@ -9595,7 +11268,7 @@ async function auditSinglePromptTarget(target, graph, options) {
9595
11268
  }
9596
11269
  if (options.outDir) {
9597
11270
  const filename = promptFilename(target);
9598
- const outPath = join9(options.outDir, filename);
11271
+ const outPath = join11(options.outDir, filename);
9599
11272
  await writeFile4(outPath, prompt, "utf-8");
9600
11273
  entry.outputPath = outPath;
9601
11274
  }
@@ -9671,7 +11344,7 @@ function computeCountsByType(entries) {
9671
11344
  async function auditPromptBatch(root, targets, options, graph) {
9672
11345
  const resolvedGraph = graph ?? await scanArtifacts(root);
9673
11346
  if (options.outDir) {
9674
- await mkdir5(options.outDir, { recursive: true });
11347
+ await mkdir6(options.outDir, { recursive: true });
9675
11348
  }
9676
11349
  const entries = [];
9677
11350
  for (const target of targets) {
@@ -9700,10 +11373,10 @@ async function auditPromptBatch(root, targets, options, graph) {
9700
11373
  targets: summaryTargets
9701
11374
  };
9702
11375
  if (options.outDir) {
9703
- await mkdir5(options.outDir, { recursive: true });
9704
- const jsonPath = join9(options.outDir, "prompt-audit-summary.json");
11376
+ await mkdir6(options.outDir, { recursive: true });
11377
+ const jsonPath = join11(options.outDir, "prompt-audit-summary.json");
9705
11378
  await writeFile4(jsonPath, JSON.stringify(summary, null, 2) + "\n", "utf-8");
9706
- const mdPath = join9(options.outDir, "prompt-audit-summary.md");
11379
+ const mdPath = join11(options.outDir, "prompt-audit-summary.md");
9707
11380
  await writeFile4(mdPath, renderPromptAuditSummaryMarkdown(summary), "utf-8");
9708
11381
  }
9709
11382
  return summary;
@@ -9743,9 +11416,9 @@ __export(refactor_id_exports, {
9743
11416
  refactorId: () => refactorId,
9744
11417
  renderRefactorIdMarkdown: () => renderRefactorIdMarkdown
9745
11418
  });
9746
- import { chmod, readFile as readFile4, rename as rename2, rm, readdir as readdir4, stat, writeFile as writeFile5 } from "fs/promises";
11419
+ import { chmod as chmod2, readFile as readFile5, rename as rename2, rm, readdir as readdir4, stat as stat2, writeFile as writeFile5 } from "fs/promises";
9747
11420
  import { randomBytes } from "crypto";
9748
- import { basename as basename5, dirname as dirname6, join as join10, relative as relative5 } from "path";
11421
+ import { basename as basename5, dirname as dirname7, join as join12, relative as relative5 } from "path";
9749
11422
  import yaml2 from "js-yaml";
9750
11423
  function escapeRegExp2(value) {
9751
11424
  return value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
@@ -9923,12 +11596,12 @@ async function walkTextFiles(root) {
9923
11596
  for (const entry of entries) {
9924
11597
  if (entry.name.startsWith(".") && PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
9925
11598
  if (PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
9926
- const full = join10(dir, entry.name);
11599
+ const full = join12(dir, entry.name);
9927
11600
  if (entry.isDirectory()) {
9928
11601
  await visit(full);
9929
11602
  } else if (entry.isFile()) {
9930
11603
  const ext = entry.name.includes(".") ? `.${entry.name.split(".").slice(-1)[0]}` : "";
9931
- if (TEXT_EXTENSIONS.has(ext.toLowerCase())) {
11604
+ if (TEXT_EXTENSIONS2.has(ext.toLowerCase())) {
9932
11605
  found.push(relative5(root, full).replace(/\\/g, "/"));
9933
11606
  }
9934
11607
  }
@@ -9938,7 +11611,7 @@ async function walkTextFiles(root) {
9938
11611
  return found.sort();
9939
11612
  }
9940
11613
  async function computeLockImpact(root, type, oldId) {
9941
- const lockPath = join10(root, VERSION_LOCK_PATH);
11614
+ const lockPath = join12(root, VERSION_LOCK_PATH);
9942
11615
  const impact = {
9943
11616
  lockPath: VERSION_LOCK_PATH,
9944
11617
  affectedImplementationLocks: [],
@@ -9947,7 +11620,7 @@ async function computeLockImpact(root, type, oldId) {
9947
11620
  };
9948
11621
  let raw;
9949
11622
  try {
9950
- raw = await readFile4(lockPath, "utf-8");
11623
+ raw = await readFile5(lockPath, "utf-8");
9951
11624
  } catch {
9952
11625
  return impact;
9953
11626
  }
@@ -10030,7 +11703,7 @@ async function refactorId(options) {
10030
11703
  const fileContents = /* @__PURE__ */ new Map();
10031
11704
  const readArtifactFile = async (path) => {
10032
11705
  if (!fileContents.has(path)) {
10033
- fileContents.set(path, await readFile4(join10(root, path), "utf-8"));
11706
+ fileContents.set(path, await readFile5(join12(root, path), "utf-8"));
10034
11707
  }
10035
11708
  return fileContents.get(path);
10036
11709
  };
@@ -10106,7 +11779,7 @@ async function refactorId(options) {
10106
11779
  for (const relativePath of await walkTextFiles(root)) {
10107
11780
  if (relativePath === VERSION_LOCK_PATH) continue;
10108
11781
  if (relativePath === "artifact-graph.config.yaml") continue;
10109
- const raw = await readFile4(join10(root, relativePath), "utf-8");
11782
+ const raw = await readFile5(join12(root, relativePath), "utf-8");
10110
11783
  if (!containsIdToken(raw, oldId)) continue;
10111
11784
  const lines = raw.split(/\r?\n/);
10112
11785
  lines.forEach((line, index) => {
@@ -10182,7 +11855,7 @@ async function refactorId(options) {
10182
11855
  }
10183
11856
  if (options.__beforeWriteVerify) await options.__beforeWriteVerify();
10184
11857
  for (const path of targetFiles) {
10185
- const disk = await readFile4(join10(root, path), "utf-8");
11858
+ const disk = await readFile5(join12(root, path), "utf-8");
10186
11859
  if (disk !== fileContents.get(path)) {
10187
11860
  return fail("PLAN_DRIFT", `\u8BA1\u5212\u4E0E\u5199\u5165\u4E4B\u95F4\u76EE\u6807\u6587\u4EF6\u53D1\u751F\u53D8\u5316\uFF08apply \u4E2D\u6B62\uFF0C\u96F6\u5199\u5165\uFF09\uFF1A${path}`, { path });
10188
11861
  }
@@ -10193,7 +11866,7 @@ async function refactorId(options) {
10193
11866
  const tempPathFor = options.__tempPathFor ?? ((targetPath) => {
10194
11867
  tempSequence += 1;
10195
11868
  const suffix = randomBytes(4).toString("hex");
10196
- return join10(dirname6(targetPath), `.${basename5(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
11869
+ return join12(dirname7(targetPath), `.${basename5(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
10197
11870
  });
10198
11871
  let stage = "write";
10199
11872
  try {
@@ -10202,13 +11875,13 @@ async function refactorId(options) {
10202
11875
  if (options.__injectWriteFailure?.(path)) {
10203
11876
  throw Object.assign(new Error(`injected write failure: ${path}`), { code: "EINJECTED" });
10204
11877
  }
10205
- const original = fileContents.has(path) ? fileContents.get(path) : await readFile4(join10(root, path), "utf-8");
10206
- const targetPath = join10(root, path);
10207
- const originalMode = (await stat(targetPath)).mode & 4095;
11878
+ const original = fileContents.has(path) ? fileContents.get(path) : await readFile5(join12(root, path), "utf-8");
11879
+ const targetPath = join12(root, path);
11880
+ const originalMode = (await stat2(targetPath)).mode & 4095;
10208
11881
  const tempPath = tempPathFor(targetPath);
10209
11882
  await writeFile5(tempPath, newContents.get(path), { encoding: "utf-8", flag: "wx" });
10210
11883
  createdTempPaths.push(tempPath);
10211
- await chmod(tempPath, originalMode);
11884
+ await chmod2(tempPath, originalMode);
10212
11885
  stage = "rename";
10213
11886
  if (options.__injectRenameFailure?.(tempPath, targetPath)) {
10214
11887
  throw Object.assign(new Error(`injected rename failure: ${tempPath} -> ${targetPath}`), { code: "ERENAMEINJECTED" });
@@ -10226,21 +11899,21 @@ async function refactorId(options) {
10226
11899
  if (options.__injectRollbackFailure?.(entry.path)) {
10227
11900
  throw Object.assign(new Error(`injected rollback failure: ${entry.path}`), { code: "EROLLBACKINJECTED" });
10228
11901
  }
10229
- await writeFile5(join10(root, entry.path), entry.original, "utf-8");
10230
- await chmod(join10(root, entry.path), entry.originalMode);
11902
+ await writeFile5(join12(root, entry.path), entry.original, "utf-8");
11903
+ await chmod2(join12(root, entry.path), entry.originalMode);
10231
11904
  } catch (rollbackError) {
10232
11905
  rollbackErrors.push({ path: entry.path, message: rollbackError.message });
10233
11906
  }
10234
11907
  }
10235
- const failure = error;
10236
- const writeCode = failure.code === "EEXIST" ? "TEMP_FILE_COLLISION" : stage === "rename" || failure.code === "ERENAMEINJECTED" ? "RENAME_FAILED" : "WRITE_FAILED";
11908
+ const failure2 = error;
11909
+ const writeCode = failure2.code === "EEXIST" ? "TEMP_FILE_COLLISION" : stage === "rename" || failure2.code === "ERENAMEINJECTED" ? "RENAME_FAILED" : "WRITE_FAILED";
10237
11910
  if (rollbackErrors.length > 0) {
10238
11911
  return {
10239
11912
  ok: false,
10240
11913
  error: {
10241
11914
  code: "ROLLBACK_FAILED",
10242
- message: `apply \u5199\u5165\u5931\u8D25\uFF08${writeCode}\uFF09\u4E14\u56DE\u6EDA\u672A\u5B8C\u5168\u6210\u529F\uFF0C\u9700\u4EBA\u5DE5\u590D\u6838\uFF1A${failure.message}`,
10243
- details: { writeError: { code: writeCode, message: failure.message }, rollbackErrors }
11915
+ message: `apply \u5199\u5165\u5931\u8D25\uFF08${writeCode}\uFF09\u4E14\u56DE\u6EDA\u672A\u5B8C\u5168\u6210\u529F\uFF0C\u9700\u4EBA\u5DE5\u590D\u6838\uFF1A${failure2.message}`,
11916
+ details: { writeError: { code: writeCode, message: failure2.message }, rollbackErrors }
10244
11917
  }
10245
11918
  };
10246
11919
  }
@@ -10248,7 +11921,7 @@ async function refactorId(options) {
10248
11921
  ok: false,
10249
11922
  error: {
10250
11923
  code: writeCode,
10251
- message: `apply \u5199\u5165\u5931\u8D25\u5E76\u5DF2\u56DE\u6EDA\uFF1A${failure.message}`,
11924
+ message: `apply \u5199\u5165\u5931\u8D25\u5E76\u5DF2\u56DE\u6EDA\uFF1A${failure2.message}`,
10252
11925
  details: { stage }
10253
11926
  }
10254
11927
  };
@@ -10343,12 +12016,12 @@ function renderRefactorIdMarkdown(result) {
10343
12016
  lines.push("");
10344
12017
  return lines.join("\n");
10345
12018
  }
10346
- var TEXT_EXTENSIONS, PROSE_SCAN_SKIP_DIRS;
12019
+ var TEXT_EXTENSIONS2, PROSE_SCAN_SKIP_DIRS;
10347
12020
  var init_refactor_id = __esm({
10348
12021
  "src/refactor-id.ts"() {
10349
12022
  "use strict";
10350
12023
  init_index();
10351
- TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".ts", ".tsx", ".mts", ".mjs", ".js", ".yaml", ".yml", ".json"]);
12024
+ TEXT_EXTENSIONS2 = /* @__PURE__ */ new Set([".md", ".markdown", ".ts", ".tsx", ".mts", ".mjs", ".js", ".yaml", ".yml", ".json"]);
10352
12025
  PROSE_SCAN_SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".qoder", ".agents"]);
10353
12026
  }
10354
12027
  });
@@ -10360,9 +12033,9 @@ __export(cli_exports, {
10360
12033
  });
10361
12034
  import yaml3 from "js-yaml";
10362
12035
  import { realpathSync as realpathSync2 } from "fs";
10363
- import { access as access2, mkdir as mkdir6, readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
10364
- import { dirname as dirname7, isAbsolute as isAbsolute5, join as join11 } from "path";
10365
- import { fileURLToPath as fileURLToPath2 } from "url";
12036
+ import { access as access2, mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
12037
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join13 } from "path";
12038
+ import { fileURLToPath as fileURLToPath3 } from "url";
10366
12039
  async function runCli(argv, io = {}) {
10367
12040
  const parsed = parseArgs(argv);
10368
12041
  const cwd = io.cwd ?? process.cwd();
@@ -10389,7 +12062,7 @@ async function runCli(argv, io = {}) {
10389
12062
  switch (parsed.command) {
10390
12063
  case "init": {
10391
12064
  await initConfig(root);
10392
- out(`Created ${join11(root, "artifact-graph.config.yaml")}
12065
+ out(`Created ${join13(root, "artifact-graph.config.yaml")}
10393
12066
  `);
10394
12067
  return 0;
10395
12068
  }
@@ -10780,7 +12453,7 @@ async function runCli(argv, io = {}) {
10780
12453
  if (packetJsonPath) {
10781
12454
  let rawJson;
10782
12455
  try {
10783
- rawJson = await readFile5(packetJsonPath, "utf-8");
12456
+ rawJson = await readFile6(packetJsonPath, "utf-8");
10784
12457
  } catch (readErr) {
10785
12458
  err(`\u9519\u8BEF\uFF1A\u65E0\u6CD5\u8BFB\u53D6 packet \u6587\u4EF6: "${packetJsonPath}" \u2014 ${readErr.message}
10786
12459
  `);
@@ -10981,7 +12654,7 @@ async function runCli(argv, io = {}) {
10981
12654
  universalBaseline: discoverConfig.context?.universal_baseline
10982
12655
  });
10983
12656
  } else {
10984
- const targetsContent = await readFile5(targetsFile, "utf-8");
12657
+ const targetsContent = await readFile6(targetsFile, "utf-8");
10985
12658
  const auditConfig2 = await loadConfig(root);
10986
12659
  const parseResult = parseTargetsFile(targetsContent, auditConfig2);
10987
12660
  if (parseResult.errors.length > 0) {
@@ -11106,7 +12779,7 @@ async function runCli(argv, io = {}) {
11106
12779
  } else {
11107
12780
  let ppaTargetsContent;
11108
12781
  try {
11109
- ppaTargetsContent = await readFile5(ppaTargetsFile, "utf-8");
12782
+ ppaTargetsContent = await readFile6(ppaTargetsFile, "utf-8");
11110
12783
  } catch (readErr) {
11111
12784
  err(`\u9519\u8BEF\uFF1A\u65E0\u6CD5\u8BFB\u53D6 targets \u6587\u4EF6: "${ppaTargetsFile}" \u2014 ${readErr.message}
11112
12785
  `);
@@ -11249,18 +12922,27 @@ async function runCli(argv, io = {}) {
11249
12922
  }
11250
12923
  const refreshAll = parsed.flags.all === true;
11251
12924
  const refreshChangedOnly = parsed.flags["changed-only"] === true;
12925
+ const removeOrphanEdges = parsed.multiFlags["remove-orphan-edge"] ?? [];
11252
12926
  if (!refreshAll && !refreshChangedOnly) {
11253
- err("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
12927
+ err("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11254
12928
  return 1;
11255
12929
  }
11256
12930
  if (parsed.flags.help === true) {
11257
- out("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
12931
+ out("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11258
12932
  return 0;
11259
12933
  }
11260
12934
  if (refreshAll && refreshChangedOnly) {
11261
12935
  err("Error: --all and --changed-only are mutually exclusive\n");
11262
12936
  return 1;
11263
12937
  }
12938
+ if (parsed.flags["remove-orphan-edge"] === true) {
12939
+ err("Error: --remove-orphan-edge requires an edgeId\n");
12940
+ return 1;
12941
+ }
12942
+ if (parsed.flags["remove-orphans"] === true && removeOrphanEdges.length > 0) {
12943
+ err("Error: --remove-orphans and --remove-orphan-edge are mutually exclusive\n");
12944
+ return 1;
12945
+ }
11264
12946
  let changedPaths = [];
11265
12947
  if (refreshChangedOnly) {
11266
12948
  const changeModeFlags = [
@@ -11269,7 +12951,7 @@ async function runCli(argv, io = {}) {
11269
12951
  typeof parsed.flags.base === "string" ? "base" : null
11270
12952
  ].filter(Boolean);
11271
12953
  if (changeModeFlags.length !== 1) {
11272
- err("Usage: artifact-graph version-lock refresh --changed-only (--staged | --worktree | --base <ref>) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
12954
+ err("Usage: artifact-graph version-lock refresh --changed-only (--staged | --worktree | --base <ref>) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11273
12955
  return 1;
11274
12956
  }
11275
12957
  const changeResult = await collectChangedPaths(root, {
@@ -11303,7 +12985,8 @@ async function runCli(argv, io = {}) {
11303
12985
  changedOnly: refreshChangedOnly,
11304
12986
  changedPaths,
11305
12987
  all: refreshAll,
11306
- removeOrphans: parsed.flags["remove-orphans"] === true
12988
+ removeOrphans: parsed.flags["remove-orphans"] === true,
12989
+ removeOrphanEdges
11307
12990
  });
11308
12991
  if (refreshFormat === "json") {
11309
12992
  out(`${JSON.stringify(result, null, 2)}
@@ -11353,8 +13036,8 @@ async function runCli(argv, io = {}) {
11353
13036
  const hooks = hookFlag === "all" ? ["pre-commit", "pre-push"] : [hookFlag];
11354
13037
  const prepared = [];
11355
13038
  for (const hookName of hooks) {
11356
- const templatePath = fileURLToPath2(new URL(`../templates/git-hooks/${hookName}.sh`, import.meta.url));
11357
- const block = await readFile5(templatePath, "utf-8");
13039
+ const templatePath = fileURLToPath3(new URL(`../templates/git-hooks/${hookName}.sh`, import.meta.url));
13040
+ const block = await readFile6(templatePath, "utf-8");
11358
13041
  prepared.push(await prepareManagedHookBlock({
11359
13042
  hookPath: await resolveGitHookPath(root, hookName),
11360
13043
  block,
@@ -11398,10 +13081,10 @@ async function runCli(argv, io = {}) {
11398
13081
  err("Usage: artifact-graph validate-review-result --file <path> [--format json]\n");
11399
13082
  return 1;
11400
13083
  }
11401
- const resolvedPath = isAbsolute5(filePath) ? filePath : join11(root, filePath);
13084
+ const resolvedPath = isAbsolute6(filePath) ? filePath : join13(root, filePath);
11402
13085
  let content;
11403
13086
  try {
11404
- content = await readFile5(resolvedPath, "utf-8");
13087
+ content = await readFile6(resolvedPath, "utf-8");
11405
13088
  } catch (readErr) {
11406
13089
  err(`Error: Cannot read file: "${resolvedPath}" \u2014 ${readErr.message}
11407
13090
  `);
@@ -11436,11 +13119,11 @@ async function runCli(argv, io = {}) {
11436
13119
  const deterministic = checkMode || parsed.flags.deterministic === true;
11437
13120
  const registry = await generateE2eRegistry(root, { deterministic });
11438
13121
  const output = JSON.stringify(registry, null, 2) + "\n";
11439
- const outPath = typeof parsed.flags.out === "string" ? parsed.flags.out : join11(root, "artifacts/tests/e2e/e2e-test-registry.json");
13122
+ const outPath = typeof parsed.flags.out === "string" ? parsed.flags.out : join13(root, "artifacts/tests/e2e/e2e-test-registry.json");
11440
13123
  if (checkMode) {
11441
13124
  let existing = "";
11442
13125
  try {
11443
- existing = await readFile5(outPath, "utf-8");
13126
+ existing = await readFile6(outPath, "utf-8");
11444
13127
  } catch {
11445
13128
  err(`Check failed: ${outPath} does not exist or is not readable
11446
13129
  `);
@@ -11464,6 +13147,117 @@ async function runCli(argv, io = {}) {
11464
13147
  }
11465
13148
  return 0;
11466
13149
  }
13150
+ case "restructure": {
13151
+ const action = parsed.positional[0];
13152
+ const format = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
13153
+ const {
13154
+ applyRestructure: applyRestructure2,
13155
+ gateRestructureOperationPlan: gateRestructureOperationPlan2,
13156
+ inspectRestructure: inspectRestructure2,
13157
+ planRestructure: planRestructure2,
13158
+ pruneRestructureRecovery: pruneRestructureRecovery2,
13159
+ recoverRestructure: recoverRestructure2
13160
+ } = await Promise.resolve().then(() => (init_restructure(), restructure_exports));
13161
+ if (format !== "json") {
13162
+ out(`${JSON.stringify({ ok: false, error: { code: "INVALID_FORMAT", message: `Invalid --format: "${format}". Allowed values: json` } }, null, 2)}
13163
+ `);
13164
+ return 1;
13165
+ }
13166
+ const mechanismOperation = action === "apply" || action === "recover" || action === "prune-recovery" ? action : void 0;
13167
+ if (mechanismOperation) {
13168
+ const planFlag = typeof parsed.flags.plan === "string" ? parsed.flags.plan : void 0;
13169
+ if (!planFlag) {
13170
+ out(`${JSON.stringify({ ok: false, error: { code: "PLAN_REQUIRED", message: `restructure ${mechanismOperation} requires --plan <plan.json>` } }, null, 2)}
13171
+ `);
13172
+ return 1;
13173
+ }
13174
+ const planPath = isAbsolute6(planFlag) ? planFlag : join13(cwd, planFlag);
13175
+ let planDocument;
13176
+ try {
13177
+ planDocument = JSON.parse(await readFile6(planPath, "utf8"));
13178
+ } catch (planError) {
13179
+ out(`${JSON.stringify({ ok: false, error: { code: "PLAN_UNREADABLE", message: `Cannot read a plan document from ${planPath}: ${planError.message}` } }, null, 2)}
13180
+ `);
13181
+ return 1;
13182
+ }
13183
+ const gate = await gateRestructureOperationPlan2(mechanismOperation, planDocument);
13184
+ if (!gate.ok) {
13185
+ out(`${JSON.stringify(gate, null, 2)}
13186
+ `);
13187
+ return 1;
13188
+ }
13189
+ const confirmCooperativeWriters = parsed.flags["confirm-cooperative-writers"] === true;
13190
+ const confirmAllParticipantsStopped = parsed.flags["confirm-all-participants-stopped"] === true;
13191
+ const confirmExclusiveMaintenance = parsed.flags["confirm-exclusive-maintenance"] === true;
13192
+ if (mechanismOperation === "apply" && !confirmCooperativeWriters) {
13193
+ out(`${JSON.stringify({ ok: false, error: { code: "COOPERATIVE_WRITERS_UNCONFIRMED", message: "restructure apply requires --confirm-cooperative-writers" } }, null, 2)}
13194
+ `);
13195
+ return 1;
13196
+ }
13197
+ if (mechanismOperation === "recover" && !(confirmAllParticipantsStopped && confirmExclusiveMaintenance)) {
13198
+ out(`${JSON.stringify({ ok: false, error: { code: "MAINTENANCE_CONFIRMATION_REQUIRED", message: "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance" } }, null, 2)}
13199
+ `);
13200
+ return 1;
13201
+ }
13202
+ if (mechanismOperation === "prune-recovery") {
13203
+ if (!confirmCooperativeWriters) {
13204
+ out(`${JSON.stringify({ ok: false, error: { code: "COOPERATIVE_WRITERS_UNCONFIRMED", message: "restructure prune-recovery requires --confirm-cooperative-writers" } }, null, 2)}
13205
+ `);
13206
+ return 1;
13207
+ }
13208
+ if (confirmAllParticipantsStopped !== confirmExclusiveMaintenance) {
13209
+ out(`${JSON.stringify({ ok: false, error: { code: "MAINTENANCE_CONFIRMATION_REQUIRED", message: "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone" } }, null, 2)}
13210
+ `);
13211
+ return 1;
13212
+ }
13213
+ }
13214
+ const result2 = mechanismOperation === "apply" ? await applyRestructure2({ root, planPath, confirmCooperativeWriters }) : mechanismOperation === "recover" ? await recoverRestructure2({
13215
+ root,
13216
+ planPath,
13217
+ allParticipantsStopped: confirmAllParticipantsStopped,
13218
+ exclusiveMaintenance: confirmExclusiveMaintenance
13219
+ }) : await pruneRestructureRecovery2({
13220
+ root,
13221
+ planPath,
13222
+ confirmCooperativeWriters,
13223
+ allParticipantsStopped: confirmAllParticipantsStopped,
13224
+ exclusiveMaintenance: confirmExclusiveMaintenance
13225
+ });
13226
+ out(`${JSON.stringify(result2, null, 2)}
13227
+ `);
13228
+ return result2.ok ? 0 : 1;
13229
+ }
13230
+ if (action !== "inspect" && action !== "plan") {
13231
+ out(`${JSON.stringify({ ok: false, error: { code: "INVALID_COMMAND", message: "Usage: artifact-graph restructure inspect|plan --root <project> --input <file> --format json; restructure apply|recover|prune-recovery --root <project> --plan <plan.json> [--format json]" } }, null, 2)}
13232
+ `);
13233
+ return 1;
13234
+ }
13235
+ const inputPath = typeof parsed.flags.input === "string" ? parsed.flags.input : void 0;
13236
+ if (!inputPath) {
13237
+ out(`${JSON.stringify({ ok: false, error: { code: "INPUT_REQUIRED", message: "--input is required" } }, null, 2)}
13238
+ `);
13239
+ return 1;
13240
+ }
13241
+ const resolvedInput = isAbsolute6(inputPath) ? inputPath : join13(cwd, inputPath);
13242
+ let input;
13243
+ try {
13244
+ input = JSON.parse(await readFile6(resolvedInput, "utf8"));
13245
+ } catch (inputError) {
13246
+ out(`${JSON.stringify({ ok: false, error: { code: "INPUT_INVALID", message: `Cannot read valid JSON from ${inputPath}: ${inputError.message}` } }, null, 2)}
13247
+ `);
13248
+ return 1;
13249
+ }
13250
+ if (action === "inspect") {
13251
+ const result2 = await inspectRestructure2(root, input);
13252
+ out(`${JSON.stringify(result2, null, 2)}
13253
+ `);
13254
+ return result2.ok ? 0 : 1;
13255
+ }
13256
+ const result = await planRestructure2(root, input);
13257
+ out(`${JSON.stringify(result, null, 2)}
13258
+ `);
13259
+ return result.ok && result.data.applicable ? 0 : 1;
13260
+ }
11467
13261
  case "contract": {
11468
13262
  const contractAction = parsed.positional[0];
11469
13263
  const contractFormat = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
@@ -11472,8 +13266,8 @@ async function runCli(argv, io = {}) {
11472
13266
  `);
11473
13267
  return 1;
11474
13268
  }
11475
- const packageDir = dirname7(fileURLToPath2(import.meta.url));
11476
- const contractsDir = typeof parsed.flags["contracts-dir"] === "string" ? parsed.flags["contracts-dir"] : join11(packageDir, "..", "contracts");
13269
+ const packageDir = dirname8(fileURLToPath3(import.meta.url));
13270
+ const contractsDir = typeof parsed.flags["contracts-dir"] === "string" ? parsed.flags["contracts-dir"] : join13(packageDir, "..", "contracts");
11477
13271
  const revisionDigest = typeof parsed.flags["revision-digest"] === "string" ? parsed.flags["revision-digest"] : void 0;
11478
13272
  async function resolveContract(contractId) {
11479
13273
  const catalog = await loadContractCatalog(contractsDir);
@@ -11687,7 +13481,7 @@ async function runCli(argv, io = {}) {
11687
13481
  }
11688
13482
  let markdownContent;
11689
13483
  try {
11690
- markdownContent = await readFile5(markdownPath, "utf-8");
13484
+ markdownContent = await readFile6(markdownPath, "utf-8");
11691
13485
  } catch {
11692
13486
  out(`${JSON.stringify({ ok: false, error: { code: "SCHEMA_VALIDATION_FAILED", path: "/markdown", message: `Could not read markdown file "${markdownPath}"` } }, null, 2)}
11693
13487
  `);
@@ -11786,7 +13580,7 @@ function isGraphRelevantPath(path, schema) {
11786
13580
  return path === "artifact-graph.config.yaml" || path === VERSION_LOCK_PATH || matchesConfiguredArtifactPath(path, schema);
11787
13581
  }
11788
13582
  async function initConfig(root) {
11789
- const configPath = join11(root, "artifact-graph.config.yaml");
13583
+ const configPath = join13(root, "artifact-graph.config.yaml");
11790
13584
  try {
11791
13585
  await access2(configPath);
11792
13586
  throw new Error(`Config already exists: ${configPath}`);
@@ -11795,12 +13589,13 @@ async function initConfig(root) {
11795
13589
  throw error;
11796
13590
  }
11797
13591
  }
11798
- await mkdir6(root, { recursive: true });
13592
+ await mkdir7(root, { recursive: true });
11799
13593
  await writeFile6(configPath, yaml3.dump(DEFAULT_SCHEMA, { lineWidth: 120 }));
11800
13594
  }
11801
13595
  function parseArgs(argv) {
11802
13596
  const [command, ...rest] = argv;
11803
13597
  const flags = {};
13598
+ const multiFlags = {};
11804
13599
  const positional = [];
11805
13600
  for (let index = 0; index < rest.length; index += 1) {
11806
13601
  const token = rest[index];
@@ -11810,6 +13605,9 @@ function parseArgs(argv) {
11810
13605
  const nextLooksLikeFlag = next && next.startsWith("-") && next.length > 1 && !/\d/.test(next[1]);
11811
13606
  if (next && !nextLooksLikeFlag) {
11812
13607
  flags[key] = next;
13608
+ const values = multiFlags[key] ?? [];
13609
+ values.push(next);
13610
+ multiFlags[key] = values;
11813
13611
  index += 1;
11814
13612
  } else {
11815
13613
  flags[key] = true;
@@ -11823,7 +13621,7 @@ function parseArgs(argv) {
11823
13621
  positional.push(token);
11824
13622
  }
11825
13623
  }
11826
- return { command, positional, flags };
13624
+ return { command, positional, flags, multiFlags };
11827
13625
  }
11828
13626
  function parseTimeViewFlag(value, err) {
11829
13627
  if (value === void 0) return void 0;
@@ -11836,13 +13634,13 @@ function parseTimeViewFlag(value, err) {
11836
13634
  }
11837
13635
  async function readReleaseInput(root, value) {
11838
13636
  if (value.includes(",")) return value.split(",");
11839
- const candidate = isAbsolute5(value) ? value : join11(root, value);
13637
+ const candidate = isAbsolute6(value) ? value : join13(root, value);
11840
13638
  try {
11841
13639
  await access2(candidate);
11842
13640
  } catch {
11843
13641
  return [value];
11844
13642
  }
11845
- const raw = await readFile5(candidate, "utf-8");
13643
+ const raw = await readFile6(candidate, "utf-8");
11846
13644
  try {
11847
13645
  const parsed = JSON.parse(raw);
11848
13646
  if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) return parsed;
@@ -11874,13 +13672,16 @@ Commands:
11874
13672
  configure types.test.paths. See INSTALL.md: Code Traceability And Coverage Boundaries.
11875
13673
  version-lock update --target <type:id> --source <path> [--verified-by <path,path>] [--lock-path <path>]
11876
13674
  version-lock bootstrap [--force] [--lock-path <path>]
11877
- version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]
13675
+ version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]
11878
13676
  --remove-orphans delete locks whose artifact, source, or traceability edge no longer
11879
13677
  exists (default: retain them). Typical cleanup after deleting or
11880
13678
  splitting artifacts:
11881
13679
  artifact-graph version-lock refresh --all --remove-orphans --format markdown
11882
13680
  git diff artifacts/traceability-version-lock.json # review
11883
13681
  git add artifacts/traceability-version-lock.json # stage, then commit
13682
+ --remove-orphan-edge <edgeId>
13683
+ delete only the named edge when it is still orphaned; repeat for
13684
+ multiple edges. Mutually exclusive with --remove-orphans.
11884
13685
  trace-version --target <type:id> [--format json|markdown] [--warning-only] [--strict-missing-lock] [--lock-path <path>]
11885
13686
  hooks install-git [--hook pre-commit|pre-push|all] [--uninstall]
11886
13687
  next-id <type> --range <name>
@@ -11890,6 +13691,18 @@ Commands:
11890
13691
  \u5B89\u5168\u5236\u54C1\u6807\u8BC6\u4E00\u5BF9\u4E00\u91CD\u6784\uFF1A\u7F3A\u7701 dry-run \u53EA\u8F93\u51FA\u8BA1\u5212\uFF1B--apply \u4EE5\u5355\u4E00\u4E8B\u52A1\u6539\u5199\u7ED3\u6784\u5316
11891
13692
  \u767D\u540D\u5355\u4F4D\u7F6E\u5E76\u81EA\u52A8 rescan \u8BC1\u660E\u3002\u9501\u4E0D\u81EA\u52A8\u5237\u65B0\uFF0Capply \u540E\u6309\u63D0\u793A\u8FD0\u884C
11892
13693
  version-lock refresh --changed-only --worktree\u3002
13694
+ restructure inspect --root <project> --input <request.json> [--format json]
13695
+ restructure plan --root <project> --input <mapping.json> [--format json]
13696
+ restructure apply --root <project> --plan <plan.json> --confirm-cooperative-writers [--format json]
13697
+ restructure recover --root <project> --plan <plan.json> --confirm-all-participants-stopped --confirm-exclusive-maintenance [--format json]
13698
+ restructure prune-recovery --root <project> --plan <plan.json> --confirm-cooperative-writers [--confirm-all-participants-stopped --confirm-exclusive-maintenance] [--format json]
13699
+ apply \u5DF2\u5F00\u653E\u5E76\u5728\u5408\u683C\u73AF\u5883\u771F\u5B9E\u5199\u5165\uFF1A\u5E73\u53F0\u8D44\u683C\u4EC5 Darwin/arm64/APFS\uFF0C\u5176\u4ED6\u5E73\u53F0\u4ECD\u53EF\u7528 inspect/plan\uFF0C
13700
+ apply \u4EE5 APPLY_ENVIRONMENT_UNSUPPORTED \u62D2\u7EDD\uFF0C\u4E0D\u4F1A\u964D\u7EA7\u6210\u65E0\u4E8B\u52A1\u5199\u5165\u3002\u6587\u4EF6\u96C6\u5408\u5199\u5165\u80FD\u529B\u7684\u6210\u719F\u5EA6\u4E3A
13701
+ candidate\uFF1A\u4EE5\u5408\u4F5C\u5F0F\u5199\u8005\u4E3A\u524D\u63D0\u4E14\u4E0D\u81EA\u8BC1\u8BE5\u524D\u63D0\uFF0Capply \u4E0E prune-recovery \u5FC5\u987B\u7ED9\u51FA
13702
+ --confirm-cooperative-writers\uFF0C\u7F3A\u5931\u5373\u62D2\u7EDD\u5199\u5165\uFF1Brecover \u5FC5\u987B\u540C\u65F6\u7ED9\u51FA
13703
+ --confirm-all-participants-stopped \u4E0E --confirm-exclusive-maintenance\u3002\u6062\u590D\u6750\u6599\u9ED8\u8BA4\u4FDD\u7559\uFF0C
13704
+ \u53EA\u6709\u663E\u5F0F prune-recovery \u624D\u6E05\u7406\u3002\u8BA1\u5212\u6587\u6863\u4FDD\u5B58\u5728\u5199\u96C6\u4E4B\u5916\u7684\u666E\u901A\u76EE\u5F55\uFF1A\u6062\u590D\u53EA\u4F9D\u8D56\u8BE5\u6587\u6863\uFF0C
13705
+ \u4E0D\u4F9D\u8D56\u8FDB\u7A0B\u72B6\u6001\u3002
11893
13706
  validate-review-result --file <path> [--format json]
11894
13707
  generate-e2e-registry [--deterministic] [--out <path>] [--check]
11895
13708
  contract list [--contracts-dir <path>] [--format json]
@@ -11905,7 +13718,7 @@ function isCliEntrypoint(argvPath) {
11905
13718
  return false;
11906
13719
  }
11907
13720
  try {
11908
- return realpathSync2(argvPath) === realpathSync2(fileURLToPath2(import.meta.url));
13721
+ return realpathSync2(argvPath) === realpathSync2(fileURLToPath3(import.meta.url));
11909
13722
  } catch {
11910
13723
  return false;
11911
13724
  }