artifact-graph 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -986,9 +986,13 @@ async function bootstrapVersionLock(root, options = {}) {
986
986
  async function refreshVersionLock(root, options = {}) {
987
987
  const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
988
988
  const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
989
+ const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
989
990
  const all = options.all === true || options.changedOnly !== true;
990
991
  const mode = all ? "all" : "changed-only";
991
992
  const warnings = [];
993
+ if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
994
+ throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
995
+ }
992
996
  if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
993
997
  throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
994
998
  }
@@ -998,9 +1002,16 @@ async function refreshVersionLock(root, options = {}) {
998
1002
  const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
999
1003
  const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
1000
1004
  const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
1005
+ const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1001
1006
  const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
1002
1007
  const currentEntries = /* @__PURE__ */ new Map();
1003
1008
  const changedPathSet = new Set(changedPaths);
1009
+ validatePreciseOrphanRemoval(
1010
+ removeOrphanEdges,
1011
+ lock,
1012
+ new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
1013
+ new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
1014
+ );
1004
1015
  const affectedEdges = /* @__PURE__ */ new Set();
1005
1016
  const addedLocks = [];
1006
1017
  const updatedLocks = [];
@@ -1027,12 +1038,13 @@ async function refreshVersionLock(root, options = {}) {
1027
1038
  }
1028
1039
  for (const existing of lock.locks) {
1029
1040
  const current = currentEntries.get(existing.edgeId);
1030
- const affected = all || lockEntryTouchesAnyPath(existing, changedPathSet);
1041
+ const removePrecisely = removeOrphanEdges.has(existing.edgeId);
1042
+ const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
1031
1043
  if (affected) {
1032
1044
  affectedEdges.add(existing.edgeId);
1033
1045
  }
1034
1046
  if (!current) {
1035
- if (affected && options.removeOrphans === true) {
1047
+ if (removePrecisely || affected && options.removeOrphans === true) {
1036
1048
  removedOrphans.push(existing.edgeId);
1037
1049
  } else {
1038
1050
  if (affected) {
@@ -1067,7 +1079,6 @@ async function refreshVersionLock(root, options = {}) {
1067
1079
  if (mode === "changed-only" && changedPaths.length === 0) {
1068
1080
  warnings.push("No changed paths were provided; no locks were refreshed.");
1069
1081
  }
1070
- const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1071
1082
  const existingArtifactRelationLocks = lock.artifactRelations ?? [];
1072
1083
  const addedArtifactRelationLocks = [];
1073
1084
  const updatedArtifactRelationLocks = [];
@@ -1111,10 +1122,11 @@ async function refreshVersionLock(root, options = {}) {
1111
1122
  if (processedRelationEdgeIds.has(relEdgeId)) {
1112
1123
  continue;
1113
1124
  }
1114
- const affected = all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1125
+ const removePrecisely = removeOrphanEdges.has(relEdgeId);
1126
+ const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1115
1127
  if (affected) {
1116
1128
  affectedEdges.add(relEdgeId);
1117
- if (options.removeOrphans === true) {
1129
+ if (removePrecisely || options.removeOrphans === true) {
1118
1130
  removedArtifactRelationLocks.push(relEdgeId);
1119
1131
  } else {
1120
1132
  retainedArtifactRelationOrphans.push(relEdgeId);
@@ -1150,6 +1162,20 @@ async function refreshVersionLock(root, options = {}) {
1150
1162
  warnings
1151
1163
  };
1152
1164
  }
1165
+ function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
1166
+ for (const edgeId of requestedEdgeIds) {
1167
+ const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
1168
+ if (matches === 0) {
1169
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
1170
+ }
1171
+ if (matches !== 1) {
1172
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
1173
+ }
1174
+ if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
1175
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
1176
+ }
1177
+ }
1178
+ }
1153
1179
  async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
1154
1180
  const index = await buildVersionIndex(root);
1155
1181
  const safeLockPath = normalizeRelativePath(root, lockPath);
@@ -3126,16 +3152,16 @@ function probeNativeBinding(context = {}) {
3126
3152
  }
3127
3153
  return { ok: true };
3128
3154
  }
3129
- function buildNativeBindingDiagnostic(failure, probeContext) {
3155
+ function buildNativeBindingDiagnostic(failure2, probeContext) {
3130
3156
  return {
3131
3157
  selectedCli: probeContext.selectedCli,
3132
3158
  runtime: `${process.execPath} (v${process.versions.node})`,
3133
- abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure.detail)}`,
3159
+ abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
3134
3160
  installSource: probeContext.installSource,
3135
3161
  probedFrom: probeContext.probedFrom,
3136
- failedStage: failure.failedStage,
3137
- cause: failure.cause,
3138
- suggestion: failure.suggestion
3162
+ failedStage: failure2.failedStage,
3163
+ cause: failure2.cause,
3164
+ suggestion: failure2.suggestion
3139
3165
  };
3140
3166
  }
3141
3167
  function buildNativeBindingSuccessDiagnostic(probeContext) {
@@ -3256,7 +3282,7 @@ async function doctorArtifactChain(root, options = {}) {
3256
3282
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3257
3283
  const warnings = [
3258
3284
  ...cli.warnings,
3259
- ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy >=22.0.0.`],
3285
+ ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3260
3286
  ...probe.ok ? [] : [
3261
3287
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3262
3288
  ]
@@ -3268,7 +3294,7 @@ async function doctorArtifactChain(root, options = {}) {
3268
3294
  node: {
3269
3295
  version: process.versions.node,
3270
3296
  compatible: nodeCompatible,
3271
- required: ">=22.0.0"
3297
+ required: REQUIRED_NODE_VERSION
3272
3298
  },
3273
3299
  config: {
3274
3300
  path: configPath,
@@ -3372,8 +3398,10 @@ function resolveCandidatePath(root, candidatePath) {
3372
3398
  return (0, import_node_path7.isAbsolute)(candidatePath) ? candidatePath : (0, import_node_path7.resolve)(root, candidatePath);
3373
3399
  }
3374
3400
  function isNodeCompatible(version) {
3375
- const major = Number(version.split(".")[0]);
3376
- return Number.isFinite(major) && major >= 22;
3401
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
3402
+ if (!match) return false;
3403
+ const [, major, minor, patch] = match.map(Number);
3404
+ return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
3377
3405
  }
3378
3406
  async function detectPnpmVersion() {
3379
3407
  try {
@@ -3434,7 +3462,7 @@ function safeRealpath(path) {
3434
3462
  return path;
3435
3463
  }
3436
3464
  }
3437
- var import_node_child_process2, import_node_fs3, import_promises4, import_node_path7, import_node_util2, execFileAsync2, KNOWN_COMMANDS;
3465
+ var import_node_child_process2, import_node_fs3, import_promises4, import_node_path7, import_node_util2, execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
3438
3466
  var init_cli_resolver = __esm({
3439
3467
  "src/cli-resolver.ts"() {
3440
3468
  "use strict";
@@ -3446,6 +3474,7 @@ var init_cli_resolver = __esm({
3446
3474
  init_versioned_traceability();
3447
3475
  init_native_binding_diagnostics();
3448
3476
  execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
3477
+ REQUIRED_NODE_VERSION = ">=22.22.2 <23";
3449
3478
  KNOWN_COMMANDS = [
3450
3479
  "init",
3451
3480
  "scan",
@@ -3927,6 +3956,379 @@ var init_hook_installer = __esm({
3927
3956
  }
3928
3957
  });
3929
3958
 
3959
+ // src/professional-conclusion.ts
3960
+ async function loadContracts() {
3961
+ return await import(CONTRACTS_PACKAGE_NAME);
3962
+ }
3963
+ async function loadHarness() {
3964
+ return await import("skill-family-harness-node");
3965
+ }
3966
+ function providerVersion() {
3967
+ const anchor = typeof __filename === "string" ? __filename : import_meta2.url;
3968
+ const parsed = (0, import_node_module2.createRequire)(anchor)("../package.json");
3969
+ if (typeof parsed.version !== "string" || parsed.version.length === 0) {
3970
+ throw new Error("artifact-graph package.json is missing version");
3971
+ }
3972
+ return parsed.version;
3973
+ }
3974
+ function errorMessage(error) {
3975
+ return error instanceof Error ? error.message : String(error);
3976
+ }
3977
+ function harnessKind(error) {
3978
+ if (error === null || typeof error !== "object" || !("details" in error)) {
3979
+ return void 0;
3980
+ }
3981
+ const details = error.details;
3982
+ return typeof details?.kind === "string" ? details.kind : void 0;
3983
+ }
3984
+ async function missingRequiredConfig(root) {
3985
+ const configPath = (0, import_node_path10.join)(root, "artifact-graph.config.yaml");
3986
+ try {
3987
+ await (0, import_promises6.access)(configPath);
3988
+ return void 0;
3989
+ } catch (error) {
3990
+ if (error.code === "ENOENT") {
3991
+ return `required configuration is missing: ${configPath}`;
3992
+ }
3993
+ return errorMessage(error);
3994
+ }
3995
+ }
3996
+ async function runValidate(root) {
3997
+ const config = await loadConfig(root);
3998
+ const graph = await scanArtifacts(root, config);
3999
+ const issues = validateGraph(graph, config);
4000
+ issues.push(...await validateScenarioPrdLinkIndex(root, graph));
4001
+ issues.push(...await validateExecutableTraceability(root, config));
4002
+ const includeCoverage = config.e2e?.executable_ref_warning !== void 0 || config.e2e?.executable_ref_error !== void 0;
4003
+ if (includeCoverage) {
4004
+ const e2eConfig = config.e2e ?? {};
4005
+ const coverageStats = await computeE2eCoverageStats(graph, root, {
4006
+ executableRefWarning: e2eConfig.executable_ref_warning,
4007
+ executableRefError: e2eConfig.executable_ref_error,
4008
+ reportUncoveredScenarios: e2eConfig.report_uncovered_scenarios,
4009
+ reportUncoveredFeatures: e2eConfig.report_uncovered_features,
4010
+ scenarioWaivers: e2eConfig.scenario_waivers,
4011
+ featureWaivers: e2eConfig.feature_waivers
4012
+ });
4013
+ for (const msg of coverageStats.thresholdWarnings) {
4014
+ issues.push({
4015
+ code: "E2E_COVERAGE_WARNING",
4016
+ severity: "warning",
4017
+ message: msg,
4018
+ path: "e2e-coverage",
4019
+ line: 1
4020
+ });
4021
+ }
4022
+ for (const msg of coverageStats.thresholdErrors) {
4023
+ issues.push({
4024
+ code: "E2E_COVERAGE_ERROR",
4025
+ severity: "error",
4026
+ message: msg,
4027
+ path: "e2e-coverage",
4028
+ line: 1
4029
+ });
4030
+ }
4031
+ }
4032
+ return { name: CHECK_VALIDATE, status: "completed", issues };
4033
+ }
4034
+ async function runLockAudit(root) {
4035
+ const result = await auditVersionLock(root);
4036
+ return { name: CHECK_LOCK, status: "completed", issues: result.issues };
4037
+ }
4038
+ async function runCoverage(root) {
4039
+ const report = await computeCoverageBoundary(root);
4040
+ return {
4041
+ name: CHECK_COVERAGE,
4042
+ status: "completed",
4043
+ issues: [],
4044
+ coverage: {
4045
+ assessment: report.graphHealth.assessment,
4046
+ changedPathScope: report.scanCoverage.changedPathScope,
4047
+ behaviorStatus: report.behaviorVerification.status
4048
+ }
4049
+ };
4050
+ }
4051
+ async function settleCheck(name, run) {
4052
+ try {
4053
+ return await run();
4054
+ } catch (error) {
4055
+ return { name, status: "not-performed", issues: [], reason: errorMessage(error) };
4056
+ }
4057
+ }
4058
+ function mapDomain(checks) {
4059
+ const completed = checks.filter((check) => check.status === "completed");
4060
+ const missing = checks.filter((check) => check.status === "not-performed");
4061
+ const hasFindings = completed.some((check) => check.issues.length > 0);
4062
+ if (completed.length === 0) {
4063
+ return {
4064
+ code: GRAPH_DOMAIN_CODES.UNAVAILABLE,
4065
+ completion: "not-performed",
4066
+ summary: "Graph checks did not start because configuration, runtime, or inputs were unavailable."
4067
+ };
4068
+ }
4069
+ if (hasFindings) {
4070
+ return {
4071
+ code: GRAPH_DOMAIN_CODES.FINDINGS,
4072
+ completion: missing.length > 0 ? "partial" : "complete",
4073
+ summary: "At least one completed graph check reported issues. Original issues are preserved."
4074
+ };
4075
+ }
4076
+ if (missing.length > 0) {
4077
+ return {
4078
+ code: GRAPH_DOMAIN_CODES.INCOMPLETE,
4079
+ completion: "partial",
4080
+ summary: "Some declared graph checks completed without findings; others lacked input or could not finish."
4081
+ };
4082
+ }
4083
+ return {
4084
+ code: GRAPH_DOMAIN_CODES.CLEAR,
4085
+ completion: "complete",
4086
+ summary: "Declared graph checks completed without issues. This does not prove unregistered relations or content correctness."
4087
+ };
4088
+ }
4089
+ function buildLimitations(checks) {
4090
+ const limitations = [STANDING_LIMITATION];
4091
+ for (const check of checks) {
4092
+ if (check.status === "not-performed") {
4093
+ limitations.push(`${check.name} did not complete: ${check.reason ?? "unknown error"}`);
4094
+ }
4095
+ if (check.coverage?.behaviorStatus === "not-evaluated") {
4096
+ limitations.push("coverage does not evaluate whether declared verification actually ran.");
4097
+ }
4098
+ if (check.coverage?.changedPathScope === "unavailable") {
4099
+ limitations.push("coverage could not observe Git worktree changes.");
4100
+ }
4101
+ }
4102
+ return [...new Set(limitations)];
4103
+ }
4104
+ function buildConclusion(root, checks) {
4105
+ const absoluteRoot = (0, import_node_path10.resolve)(root);
4106
+ const mapped = mapDomain(checks);
4107
+ const checked = checks.filter((check) => check.status === "completed").map((check) => check.name);
4108
+ const limitations = buildLimitations(checks);
4109
+ const issues = checks.flatMap((check) => check.issues);
4110
+ return {
4111
+ schemaVersion: 1,
4112
+ kind: "skill-family.professional-conclusion",
4113
+ provider: {
4114
+ id: GRAPH_PROVIDER_ID,
4115
+ version: providerVersion(),
4116
+ entry: GRAPH_PROVIDER_ENTRY
4117
+ },
4118
+ subject: {
4119
+ ref: (0, import_node_url2.pathToFileURL)(absoluteRoot).href
4120
+ },
4121
+ scope: {
4122
+ checked: mapped.completion === "not-performed" ? [] : checked,
4123
+ limitations
4124
+ },
4125
+ outcome: {
4126
+ completion: mapped.completion,
4127
+ code: mapped.code,
4128
+ summary: mapped.summary
4129
+ },
4130
+ details: {
4131
+ checks: checks.map((check) => ({
4132
+ name: check.name,
4133
+ status: check.status,
4134
+ issueCount: check.issues.length,
4135
+ ...check.reason ? { reason: check.reason } : {},
4136
+ ...check.coverage ? { coverage: check.coverage } : {}
4137
+ })),
4138
+ issues
4139
+ }
4140
+ };
4141
+ }
4142
+ async function assertConclusionShape(conclusion) {
4143
+ const contracts = await loadContracts();
4144
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4145
+ if (registration === null) {
4146
+ throw new Error("skill-family-contracts 0.22.0 does not register professional-conclusion");
4147
+ }
4148
+ const verdict = contracts.validateDocument(conclusion, {
4149
+ schemaId: registration.$id,
4150
+ dialect: registration.dialect,
4151
+ policy: "strict"
4152
+ });
4153
+ if (!verdict.valid) {
4154
+ throw new Error(`constructed professional conclusion failed public schema validation (${verdict.errorCode ?? "invalid"})`);
4155
+ }
4156
+ }
4157
+ async function publishConclusion(absoluteOutput, conclusion) {
4158
+ if (!(0, import_node_path10.isAbsolute)(absoluteOutput)) {
4159
+ return "--conclusion-output must be an absolute path";
4160
+ }
4161
+ const outputRoot = (0, import_node_path10.dirname)(absoluteOutput);
4162
+ const relPath = (0, import_node_path10.basename)(absoluteOutput);
4163
+ if (relPath.length === 0 || relPath === "." || relPath === "..") {
4164
+ return "--conclusion-output must name a file";
4165
+ }
4166
+ try {
4167
+ const harness = await loadHarness();
4168
+ await harness.publishFileExclusive(outputRoot, relPath, `${JSON.stringify(conclusion, null, 2)}
4169
+ `);
4170
+ return void 0;
4171
+ } catch (error) {
4172
+ const kind = harnessKind(error);
4173
+ if (kind === "exclusive-publish-conflict") {
4174
+ return `exclusive publication target already exists: ${absoluteOutput}`;
4175
+ }
4176
+ return errorMessage(error);
4177
+ }
4178
+ }
4179
+ async function runCheckProfessional(options) {
4180
+ const root = (0, import_node_path10.resolve)(options.root);
4181
+ const configGap = await missingRequiredConfig(root);
4182
+ const checks = configGap === void 0 ? await Promise.all([
4183
+ settleCheck(CHECK_VALIDATE, () => runValidate(root)),
4184
+ settleCheck(CHECK_LOCK, () => runLockAudit(root)),
4185
+ settleCheck(CHECK_COVERAGE, () => runCoverage(root))
4186
+ ]) : [
4187
+ { name: CHECK_VALIDATE, status: "not-performed", issues: [], reason: configGap },
4188
+ { name: CHECK_LOCK, status: "not-performed", issues: [], reason: configGap },
4189
+ { name: CHECK_COVERAGE, status: "not-performed", issues: [], reason: configGap }
4190
+ ];
4191
+ const conclusion = buildConclusion(root, checks);
4192
+ await assertConclusionShape(conclusion);
4193
+ if (options.conclusionOutput === void 0) {
4194
+ return { conclusion };
4195
+ }
4196
+ if (!(0, import_node_path10.isAbsolute)(options.conclusionOutput)) {
4197
+ return { conclusion, writeError: "--conclusion-output must be an absolute path" };
4198
+ }
4199
+ const writeError = await publishConclusion((0, import_node_path10.resolve)(options.conclusionOutput), conclusion);
4200
+ return { conclusion, ...writeError ? { writeError } : {} };
4201
+ }
4202
+ function asRecord(value) {
4203
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
4204
+ return null;
4205
+ }
4206
+ return value;
4207
+ }
4208
+ function readProvider(value) {
4209
+ const record = asRecord(value);
4210
+ if (record === null) {
4211
+ return null;
4212
+ }
4213
+ const provider = {};
4214
+ if (typeof record.id === "string") provider.id = record.id;
4215
+ if (typeof record.version === "string") provider.version = record.version;
4216
+ if (typeof record.entry === "string") provider.entry = record.entry;
4217
+ return Object.keys(provider).length > 0 ? provider : null;
4218
+ }
4219
+ function interpretConclusion(conclusion) {
4220
+ const provider = conclusion.provider;
4221
+ if (provider.id !== GRAPH_PROVIDER_ID) {
4222
+ return {
4223
+ status: "unavailable",
4224
+ reason: `proof provider ${provider.id} is not ${GRAPH_PROVIDER_ID}`,
4225
+ provider,
4226
+ conclusion
4227
+ };
4228
+ }
4229
+ if (!KNOWN_DOMAIN_CODES.has(conclusion.outcome.code)) {
4230
+ return {
4231
+ status: "unavailable",
4232
+ reason: `unknown same-version domain code: ${conclusion.outcome.code}`,
4233
+ provider,
4234
+ conclusion
4235
+ };
4236
+ }
4237
+ if (conclusion.outcome.code === GRAPH_DOMAIN_CODES.CLEAR && conclusion.outcome.completion === "complete") {
4238
+ return {
4239
+ status: "pass",
4240
+ reason: "GRAPH_CLEAR with complete scope is acceptable for this provider version.",
4241
+ provider,
4242
+ conclusion
4243
+ };
4244
+ }
4245
+ return {
4246
+ status: "not_pass",
4247
+ reason: `proof records ${conclusion.outcome.code} (${conclusion.outcome.completion}); complete does not mean pass.`,
4248
+ provider,
4249
+ conclusion
4250
+ };
4251
+ }
4252
+ async function runReadProof(options) {
4253
+ const unavailable = (reason, provider = null, conclusion = null) => ({
4254
+ result: { status: "unavailable", reason, provider, conclusion },
4255
+ exitCode: 2
4256
+ });
4257
+ let receipt;
4258
+ try {
4259
+ const harness = await loadHarness();
4260
+ receipt = await harness.readFileStrict(options.proofRoot, options.proof, { encoding: "utf8" });
4261
+ } catch (error) {
4262
+ const kind = harnessKind(error);
4263
+ if (kind === "missing-resource") {
4264
+ return unavailable(`proof file does not exist: ${options.proof}`, null, null);
4265
+ }
4266
+ return unavailable(errorMessage(error), null, null);
4267
+ }
4268
+ const raw = typeof receipt.content === "string" ? receipt.content : receipt.content.toString("utf8");
4269
+ let parsed;
4270
+ try {
4271
+ parsed = JSON.parse(raw);
4272
+ } catch (error) {
4273
+ return unavailable(`proof is not valid JSON: ${errorMessage(error)}`, null, null);
4274
+ }
4275
+ const previewProvider = readProvider(asRecord(parsed)?.provider);
4276
+ let contracts;
4277
+ try {
4278
+ contracts = await loadContracts();
4279
+ } catch (error) {
4280
+ return unavailable(`cannot load skill-family-contracts: ${errorMessage(error)}`, previewProvider, null);
4281
+ }
4282
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4283
+ if (registration === null) {
4284
+ return unavailable("professional-conclusion schema is not registered", previewProvider, null);
4285
+ }
4286
+ const verdict = contracts.validateDocument(parsed, {
4287
+ schemaId: registration.$id,
4288
+ dialect: registration.dialect,
4289
+ policy: "strict"
4290
+ });
4291
+ if (!verdict.valid) {
4292
+ return unavailable(
4293
+ `proof failed professional-conclusion schema validation (${verdict.errorCode ?? "invalid"})`,
4294
+ previewProvider,
4295
+ null
4296
+ );
4297
+ }
4298
+ const interpreted = interpretConclusion(parsed);
4299
+ const exitCode = interpreted.status === "pass" ? 0 : interpreted.status === "not_pass" ? 1 : 2;
4300
+ return { result: interpreted, exitCode };
4301
+ }
4302
+ var import_promises6, import_node_module2, import_node_path10, import_node_url2, import_meta2, GRAPH_PROVIDER_ID, GRAPH_PROVIDER_ENTRY, PROFESSIONAL_CONCLUSION_OBJECT, GRAPH_DOMAIN_CODES, KNOWN_DOMAIN_CODES, CHECK_VALIDATE, CHECK_LOCK, CHECK_COVERAGE, STANDING_LIMITATION, CONTRACTS_PACKAGE_NAME;
4303
+ var init_professional_conclusion = __esm({
4304
+ "src/professional-conclusion.ts"() {
4305
+ "use strict";
4306
+ import_promises6 = require("fs/promises");
4307
+ import_node_module2 = require("module");
4308
+ import_node_path10 = require("path");
4309
+ import_node_url2 = require("url");
4310
+ init_coverage();
4311
+ init_index();
4312
+ init_versioned_traceability();
4313
+ import_meta2 = {};
4314
+ GRAPH_PROVIDER_ID = "artifact-graph";
4315
+ GRAPH_PROVIDER_ENTRY = "check-professional";
4316
+ PROFESSIONAL_CONCLUSION_OBJECT = "professional-conclusion";
4317
+ GRAPH_DOMAIN_CODES = Object.freeze({
4318
+ CLEAR: "GRAPH_CLEAR",
4319
+ FINDINGS: "GRAPH_FINDINGS",
4320
+ INCOMPLETE: "GRAPH_CHECK_INCOMPLETE",
4321
+ UNAVAILABLE: "GRAPH_CHECK_UNAVAILABLE"
4322
+ });
4323
+ KNOWN_DOMAIN_CODES = new Set(Object.values(GRAPH_DOMAIN_CODES));
4324
+ CHECK_VALIDATE = "validate";
4325
+ CHECK_LOCK = "version-lock-audit";
4326
+ CHECK_COVERAGE = "coverage";
4327
+ STANDING_LIMITATION = "Graph checks do not prove content semantics, method execution, or publication facts.";
4328
+ CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
4329
+ }
4330
+ });
4331
+
3930
4332
  // src/review-result-validator.ts
3931
4333
  function validateReviewResult(input) {
3932
4334
  const errors = [];
@@ -4004,8 +4406,8 @@ function validateReviewResult(input) {
4004
4406
  validateReviewData(obj.review, "$.review", errors);
4005
4407
  if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
4006
4408
  const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
4007
- findings.forEach((finding, index) => {
4008
- if (isPlainObject(finding) && finding.severity === "block" && (finding.status === void 0 || finding.status === "open")) {
4409
+ findings.forEach((finding2, index) => {
4410
+ if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
4009
4411
  errors.push({
4010
4412
  path: `$.review.findings[${index}]`,
4011
4413
  message: `${obj.decision} cannot contain an open block finding`
@@ -4528,7 +4930,7 @@ function validatePolicyCompatibility(policy, baseContract) {
4528
4930
  };
4529
4931
  }
4530
4932
  async function loadContract(contractPath, options) {
4531
- const rawContent = await (0, import_promises6.readFile)(contractPath, "utf-8");
4933
+ const rawContent = await (0, import_promises7.readFile)(contractPath, "utf-8");
4532
4934
  let schema;
4533
4935
  try {
4534
4936
  schema = JSON.parse(rawContent);
@@ -4576,10 +4978,10 @@ async function loadContract(contractPath, options) {
4576
4978
  }
4577
4979
  async function loadContractsFromDirectory(contractsDir, options) {
4578
4980
  const contracts = [];
4579
- const entries = await (0, import_promises6.readdir)(contractsDir, { withFileTypes: true });
4981
+ const entries = await (0, import_promises7.readdir)(contractsDir, { withFileTypes: true });
4580
4982
  for (const entry of entries) {
4581
4983
  if (entry.isDirectory()) {
4582
- const schemaPath = (0, import_node_path10.join)(contractsDir, entry.name, "schema.json");
4984
+ const schemaPath = (0, import_node_path11.join)(contractsDir, entry.name, "schema.json");
4583
4985
  const contract = await loadContract(schemaPath, options);
4584
4986
  contracts.push(contract);
4585
4987
  }
@@ -4694,13 +5096,13 @@ async function loadContractCatalog(contractsDir, options) {
4694
5096
  }
4695
5097
  return catalog;
4696
5098
  }
4697
- var import_node_crypto3, import_promises6, import_node_path10, import_ajv, CONTRACT_ERROR_CODES, ContractError, OFFICIAL_AUTHORITY, OFFICIAL_NAMESPACE_PATTERN, ContractRegistry, _validatorCache, E2E_NORMALIZER_CONFIG, ContractCatalog;
5099
+ var import_node_crypto3, import_promises7, import_node_path11, import_ajv, CONTRACT_ERROR_CODES, ContractError, OFFICIAL_AUTHORITY, OFFICIAL_NAMESPACE_PATTERN, ContractRegistry, _validatorCache, E2E_NORMALIZER_CONFIG, ContractCatalog;
4698
5100
  var init_contract_kernel = __esm({
4699
5101
  "src/contract-kernel.ts"() {
4700
5102
  "use strict";
4701
5103
  import_node_crypto3 = require("crypto");
4702
- import_promises6 = require("fs/promises");
4703
- import_node_path10 = require("path");
5104
+ import_promises7 = require("fs/promises");
5105
+ import_node_path11 = require("path");
4704
5106
  import_ajv = __toESM(require("ajv"), 1);
4705
5107
  CONTRACT_ERROR_CODES = {
4706
5108
  /** Contract identity not found */
@@ -5023,6 +5425,1686 @@ var init_contract_kernel = __esm({
5023
5425
  }
5024
5426
  });
5025
5427
 
5428
+ // src/restructure-software.ts
5429
+ function lineStarts(raw) {
5430
+ const starts = [0];
5431
+ const buffer = Buffer.from(raw, "utf8");
5432
+ for (let index = 0; index < buffer.length; index += 1) {
5433
+ if (buffer[index] === 10) starts.push(index + 1);
5434
+ }
5435
+ return starts;
5436
+ }
5437
+ function markdownCodeLineMask(lines) {
5438
+ const result = new Array(lines.length).fill(false);
5439
+ let fence;
5440
+ lines.forEach((line, index) => {
5441
+ if (fence) {
5442
+ result[index] = true;
5443
+ const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
5444
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
5445
+ return;
5446
+ }
5447
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
5448
+ if (opening) {
5449
+ result[index] = true;
5450
+ fence = { marker: opening[1][0], length: opening[1].length };
5451
+ return;
5452
+ }
5453
+ if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
5454
+ });
5455
+ return result;
5456
+ }
5457
+ function markdownRecordHeadings(raw, type) {
5458
+ const lines = raw.split("\n");
5459
+ const masked = markdownCodeLineMask(lines);
5460
+ 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;
5461
+ if (!pattern) return [];
5462
+ return lines.flatMap((line, index) => {
5463
+ if (masked[index]) return [];
5464
+ const match = pattern.exec(line.replace(/\r$/, ""));
5465
+ return match ? [{ id: match[1], line: index + 1 }] : [];
5466
+ });
5467
+ }
5468
+ function locateSoftwareRecord(raw, node, nodesInFile) {
5469
+ const byteLength = Buffer.byteLength(raw, "utf8");
5470
+ if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
5471
+ if (node.type !== "scenario" && node.type !== "e2e_test") {
5472
+ return {
5473
+ blockers: [{
5474
+ code: "UNSUPPORTED_RECORD_BOUNDARY",
5475
+ message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
5476
+ path: node.path,
5477
+ line: node.line
5478
+ }]
5479
+ };
5480
+ }
5481
+ const headings = markdownRecordHeadings(raw, node.type);
5482
+ const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
5483
+ const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
5484
+ const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
5485
+ const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
5486
+ const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
5487
+ const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
5488
+ if (inconsistent) {
5489
+ return {
5490
+ blockers: [{
5491
+ code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
5492
+ 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",
5493
+ path: node.path,
5494
+ line: node.line
5495
+ }]
5496
+ };
5497
+ }
5498
+ if (!heading) {
5499
+ return {
5500
+ blockers: [{
5501
+ code: "RECORD_BOUNDARY_MISSING",
5502
+ message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
5503
+ path: node.path,
5504
+ line: node.line
5505
+ }]
5506
+ };
5507
+ }
5508
+ const starts = lineStarts(raw);
5509
+ const nextLine = headings.find((item) => item.line > heading.line)?.line;
5510
+ return {
5511
+ range: {
5512
+ startByte: starts[heading.line - 1] ?? 0,
5513
+ endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
5514
+ },
5515
+ blockers: []
5516
+ };
5517
+ }
5518
+ function replaceSoftwareHeader(raw, header) {
5519
+ const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
5520
+ const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
5521
+ ` : header;
5522
+ return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
5523
+ }
5524
+ var init_restructure_software = __esm({
5525
+ "src/restructure-software.ts"() {
5526
+ "use strict";
5527
+ }
5528
+ });
5529
+
5530
+ // src/restructure-file-set.ts
5531
+ async function loadFoundationModule() {
5532
+ return await import(FOUNDATION_PACKAGE_NAME);
5533
+ }
5534
+ async function loadContractsModule() {
5535
+ return await import(CONTRACTS_PACKAGE_NAME2);
5536
+ }
5537
+ async function verifyMechanismResult(result) {
5538
+ if (typeof result !== "object" || result === null || Array.isArray(result)) {
5539
+ return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
5540
+ }
5541
+ let contracts;
5542
+ let registration;
5543
+ try {
5544
+ contracts = await loadContractsModule();
5545
+ registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
5546
+ } catch (cause) {
5547
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
5548
+ }
5549
+ if (registration === null) {
5550
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
5551
+ }
5552
+ const verdict = contracts.validateDocument(result, {
5553
+ schemaId: registration.$id,
5554
+ dialect: registration.dialect,
5555
+ policy: "strict"
5556
+ });
5557
+ if (!verdict.valid) {
5558
+ return failure(
5559
+ "MECHANISM_RESULT_INVALID",
5560
+ `The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
5561
+ { schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
5562
+ );
5563
+ }
5564
+ return { ok: true, data: result };
5565
+ }
5566
+ function failure(code, message, details) {
5567
+ return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
5568
+ }
5569
+ function candidateBytes(content) {
5570
+ return Buffer.from(content ?? "", "utf8");
5571
+ }
5572
+ function candidateByteDigest(content) {
5573
+ return (0, import_node_crypto4.createHash)("sha256").update(candidateBytes(content)).digest("hex");
5574
+ }
5575
+ function rawDigest(value, path) {
5576
+ if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
5577
+ throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
5578
+ }
5579
+ const raw = value.slice(DIGEST_PREFIX.length);
5580
+ if (!RAW_SHA256_PATTERN.test(raw)) {
5581
+ throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
5582
+ }
5583
+ return raw;
5584
+ }
5585
+ async function resolveRealRoot(root) {
5586
+ let canonical;
5587
+ try {
5588
+ canonical = await (0, import_promises8.realpath)((0, import_node_path12.resolve)(root));
5589
+ } catch (cause) {
5590
+ return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5591
+ }
5592
+ let info;
5593
+ try {
5594
+ info = await (0, import_promises8.lstat)(canonical);
5595
+ } catch (cause) {
5596
+ return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
5597
+ }
5598
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5599
+ return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
5600
+ }
5601
+ return { ok: true, data: canonical };
5602
+ }
5603
+ async function qualifyRestructureMechanism(root) {
5604
+ if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
5605
+ return failure(
5606
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5607
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
5608
+ );
5609
+ }
5610
+ const canonical = await resolveRealRoot(root);
5611
+ if (!canonical.ok) return canonical;
5612
+ let type;
5613
+ try {
5614
+ type = (await (0, import_promises8.statfs)(canonical.data)).type;
5615
+ } catch (cause) {
5616
+ return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
5617
+ }
5618
+ if (type !== APFS_STATFS_TYPE) {
5619
+ return failure(
5620
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5621
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
5622
+ );
5623
+ }
5624
+ return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5625
+ }
5626
+ async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5627
+ const target = (0, import_node_path12.join)(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5628
+ const current = async () => (0, import_promises8.lstat)(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5629
+ let info = await current();
5630
+ if (info === null) {
5631
+ if (!options.create) {
5632
+ return failure(
5633
+ "RECOVERY_MATERIALS_MISSING",
5634
+ `No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
5635
+ );
5636
+ }
5637
+ let created = false;
5638
+ try {
5639
+ await (0, import_promises8.mkdir)(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
5640
+ created = true;
5641
+ } catch (cause) {
5642
+ if (cause.code !== "EEXIST") {
5643
+ return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
5644
+ }
5645
+ }
5646
+ info = await current();
5647
+ if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
5648
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5649
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5650
+ }
5651
+ if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5652
+ await (0, import_promises8.chmod)(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
5653
+ info = await current();
5654
+ if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
5655
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5656
+ }
5657
+ }
5658
+ }
5659
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5660
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5661
+ }
5662
+ if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5663
+ return failure(
5664
+ "MECHANISM_ROOT_UNSAFE",
5665
+ `${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
5666
+ );
5667
+ }
5668
+ return { ok: true, data: target };
5669
+ }
5670
+ async function createRestructureRootBinding(canonicalRoot) {
5671
+ try {
5672
+ const module2 = await loadFoundationModule();
5673
+ return { ok: true, data: await module2.createFilesystemRootBinding(canonicalRoot) };
5674
+ } catch (cause) {
5675
+ return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
5676
+ }
5677
+ }
5678
+ function toOperation(candidate) {
5679
+ const expected = candidate.original.exists ? {
5680
+ exists: true,
5681
+ sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
5682
+ size: candidate.original.size,
5683
+ mode: candidate.original.mode
5684
+ } : { exists: false };
5685
+ if (candidate.action === "delete") {
5686
+ return { path: candidate.path, action: "delete", expected, next: null };
5687
+ }
5688
+ const bytes = candidateBytes(candidate.content);
5689
+ const declared = rawDigest(candidate.sha256, candidate.path);
5690
+ if (declared !== candidateByteDigest(candidate.content)) {
5691
+ throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
5692
+ }
5693
+ return {
5694
+ path: candidate.path,
5695
+ action: candidate.action,
5696
+ expected,
5697
+ next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
5698
+ };
5699
+ }
5700
+ async function buildFileSetApplyRequest(canonicalRoot, plan) {
5701
+ if (plan.candidates.length === 0) {
5702
+ return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
5703
+ }
5704
+ const binding = await createRestructureRootBinding(canonicalRoot);
5705
+ if (!binding.ok) return binding;
5706
+ let operations;
5707
+ try {
5708
+ operations = plan.candidates.map(toOperation);
5709
+ } catch (cause) {
5710
+ return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
5711
+ }
5712
+ return {
5713
+ ok: true,
5714
+ data: {
5715
+ schemaVersion: 1,
5716
+ kind: "skill-family.file-set-apply-request",
5717
+ operationId: plan.operation_id,
5718
+ root: canonicalRoot,
5719
+ rootBinding: binding.data,
5720
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5721
+ allowAdjacentStaging: true,
5722
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5723
+ validationTimeoutMs: plan.validation_timeout_ms,
5724
+ operations
5725
+ }
5726
+ };
5727
+ }
5728
+ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5729
+ const request = await buildFileSetApplyRequest(canonicalRoot, plan);
5730
+ if (!request.ok) return request;
5731
+ const module2 = await loadFoundationModule();
5732
+ let raw;
5733
+ try {
5734
+ raw = await module2.applyFileSet(request.data, { validate: options.validate });
5735
+ } catch (cause) {
5736
+ return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
5737
+ }
5738
+ return await verifyMechanismResult(raw);
5739
+ }
5740
+ async function observeRestructureJournal(canonicalRoot) {
5741
+ const journalRoot = (0, import_node_path12.join)(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5742
+ const module2 = await loadFoundationModule();
5743
+ try {
5744
+ return { ok: true, data: await module2.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
5745
+ } catch (cause) {
5746
+ return failure(
5747
+ "MAINTENANCE_OBSERVATION_FAILED",
5748
+ `The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
5749
+ );
5750
+ }
5751
+ }
5752
+ async function recoverRestructureFileSet(canonicalRoot, plan, options) {
5753
+ if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
5754
+ return failure(
5755
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
5756
+ "restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
5757
+ );
5758
+ }
5759
+ const binding = await createRestructureRootBinding(canonicalRoot);
5760
+ if (!binding.ok) return binding;
5761
+ const observation = await observeRestructureJournal(canonicalRoot);
5762
+ if (!observation.ok) return observation;
5763
+ const maintenance = {
5764
+ observation: observation.data,
5765
+ confirmAllParticipantsStopped: true,
5766
+ confirmExclusiveMaintenance: true
5767
+ };
5768
+ const request = {
5769
+ schemaVersion: 1,
5770
+ kind: "skill-family.file-set-recovery-request",
5771
+ operationId: plan.operation_id,
5772
+ root: canonicalRoot,
5773
+ rootBinding: binding.data,
5774
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5775
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5776
+ allowAdjacentStaging: true,
5777
+ maintenance
5778
+ };
5779
+ const module2 = await loadFoundationModule();
5780
+ let raw;
5781
+ try {
5782
+ raw = await module2.recoverFileSet(request);
5783
+ } catch (cause) {
5784
+ return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
5785
+ }
5786
+ return await verifyMechanismResult(raw);
5787
+ }
5788
+ async function pruneRestructureFileSet(canonicalRoot, plan, options) {
5789
+ const binding = await createRestructureRootBinding(canonicalRoot);
5790
+ if (!binding.ok) return binding;
5791
+ const request = {
5792
+ schemaVersion: 1,
5793
+ kind: "skill-family.file-set-prune-request",
5794
+ operationId: plan.operation_id,
5795
+ root: canonicalRoot,
5796
+ rootBinding: binding.data,
5797
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5798
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
5799
+ };
5800
+ if (options.allParticipantsStopped && options.exclusiveMaintenance) {
5801
+ const observation = await observeRestructureJournal(canonicalRoot);
5802
+ if (!observation.ok) return observation;
5803
+ request.maintenance = {
5804
+ observation: observation.data,
5805
+ confirmAllParticipantsStopped: true,
5806
+ confirmExclusiveMaintenance: true
5807
+ };
5808
+ }
5809
+ const module2 = await loadFoundationModule();
5810
+ let raw;
5811
+ try {
5812
+ raw = await module2.pruneFileSetRecovery(request);
5813
+ } catch (cause) {
5814
+ return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
5815
+ }
5816
+ return await verifyMechanismResult(raw);
5817
+ }
5818
+ function validationState(validation) {
5819
+ return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
5820
+ }
5821
+ function errorKinds(result) {
5822
+ return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
5823
+ }
5824
+ function applyProjection(result) {
5825
+ const kinds = errorKinds(result);
5826
+ if (result.outcome === "committed") {
5827
+ if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
5828
+ return {
5829
+ code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
5830
+ 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.",
5831
+ ok: false,
5832
+ rerunApplyPermitted: false
5833
+ };
5834
+ }
5835
+ const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
5836
+ return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
5837
+ code: "APPLY_INCOMPLETE",
5838
+ message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
5839
+ ok: false,
5840
+ rerunApplyPermitted: false
5841
+ };
5842
+ }
5843
+ const codes = {
5844
+ "commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
5845
+ "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."],
5846
+ "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."]
5847
+ };
5848
+ const mapped = codes[result.outcome];
5849
+ if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
5850
+ if (result.outcome === "rejected") {
5851
+ const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
5852
+ return {
5853
+ code: "APPLY_REJECTED",
5854
+ 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.",
5855
+ ok: false,
5856
+ rerunApplyPermitted: !identityTaken
5857
+ };
5858
+ }
5859
+ return {
5860
+ code: "APPLY_UNEXPECTED_OUTCOME",
5861
+ message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
5862
+ ok: false,
5863
+ rerunApplyPermitted: false
5864
+ };
5865
+ }
5866
+ function recoverProjection(result) {
5867
+ const reading = (() => {
5868
+ switch (result.outcome) {
5869
+ case "already-committed":
5870
+ return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
5871
+ case "already-rolled-back":
5872
+ return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
5873
+ case "rolled-back":
5874
+ return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
5875
+ case "pruned":
5876
+ return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
5877
+ case "already-pruned":
5878
+ return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
5879
+ case "commit-unconfirmed":
5880
+ 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 };
5881
+ case "recovery-required":
5882
+ return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
5883
+ case "rejected":
5884
+ return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
5885
+ default:
5886
+ return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
5887
+ }
5888
+ })();
5889
+ return { ...reading, rerunApplyPermitted: false };
5890
+ }
5891
+ function pruneProjection(result) {
5892
+ const reading = (() => {
5893
+ switch (result.outcome) {
5894
+ case "pruned":
5895
+ return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
5896
+ case "already-pruned":
5897
+ return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
5898
+ case "rejected":
5899
+ return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
5900
+ case "recovery-required":
5901
+ 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 };
5902
+ default:
5903
+ return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
5904
+ }
5905
+ })();
5906
+ return { ...reading, rerunApplyPermitted: false };
5907
+ }
5908
+ function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
5909
+ const base = {
5910
+ foundation: result,
5911
+ planPath,
5912
+ planDigest,
5913
+ operation: result.operation,
5914
+ outcome: result.outcome,
5915
+ preflight: result.preflight,
5916
+ businessWrite: result.businessWrite,
5917
+ validation: result.validation,
5918
+ validationState: validationState(result.validation),
5919
+ recovery: result.recovery,
5920
+ paths: result.paths,
5921
+ errors: result.errors,
5922
+ materialPath: result.materials.relPath,
5923
+ errorKinds: errorKinds(result)
5924
+ };
5925
+ const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
5926
+ return { ...base, ...reading };
5927
+ }
5928
+ var import_node_crypto4, import_promises8, import_node_path12, 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_NAME2, FILE_SET_RESULT_OBJECT, APPLY_MAINTENANCE_ERROR_KINDS;
5929
+ var init_restructure_file_set = __esm({
5930
+ "src/restructure-file-set.ts"() {
5931
+ "use strict";
5932
+ import_node_crypto4 = require("crypto");
5933
+ import_promises8 = require("fs/promises");
5934
+ import_node_path12 = require("path");
5935
+ RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
5936
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
5937
+ RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
5938
+ RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
5939
+ RESTRUCTURE_QUALIFIED_ARCH = "arm64";
5940
+ RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
5941
+ APFS_STATFS_TYPE = 26;
5942
+ DIGEST_PREFIX = "sha256:";
5943
+ RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5944
+ FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
5945
+ CONTRACTS_PACKAGE_NAME2 = "skill-family-contracts";
5946
+ FILE_SET_RESULT_OBJECT = "file-set-result";
5947
+ APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
5948
+ }
5949
+ });
5950
+
5951
+ // src/restructure.ts
5952
+ function digestBytes(value) {
5953
+ return `sha256:${(0, import_node_crypto5.createHash)("sha256").update(value).digest("hex")}`;
5954
+ }
5955
+ function canonicalJson(value) {
5956
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
5957
+ if (value && typeof value === "object") {
5958
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
5959
+ }
5960
+ return JSON.stringify(value);
5961
+ }
5962
+ function digestRestructureValue(value) {
5963
+ return digestBytes(canonicalJson(value));
5964
+ }
5965
+ function normalizeRelativePath2(value) {
5966
+ if (!value || value.includes("\0") || (0, import_node_path13.isAbsolute)(value)) return void 0;
5967
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5968
+ if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5969
+ return normalized;
5970
+ }
5971
+ function isPathAllowed(path, allowed) {
5972
+ return allowed.some((entry) => {
5973
+ const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
5974
+ return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
5975
+ });
5976
+ }
5977
+ async function readContainedFileWithMode(root, path) {
5978
+ const normalized = normalizeRelativePath2(path);
5979
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5980
+ const absoluteRoot = (0, import_node_path13.resolve)(root);
5981
+ const absolutePath = (0, import_node_path13.resolve)(absoluteRoot, normalized);
5982
+ if ((0, import_node_path13.relative)(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
5983
+ try {
5984
+ const info = await (0, import_promises9.lstat)(absolutePath);
5985
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
5986
+ return { buffer: await (0, import_promises9.readFile)(absolutePath), mode: info.mode & MAX_POSIX_MODE };
5987
+ } catch (error) {
5988
+ if (error.code === "ENOENT") return void 0;
5989
+ throw error;
5990
+ }
5991
+ }
5992
+ async function readContainedFile(root, path) {
5993
+ return (await readContainedFileWithMode(root, path))?.buffer;
5994
+ }
5995
+ async function snapshotFile(root, path) {
5996
+ const normalized = normalizeRelativePath2(path);
5997
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5998
+ const contained = await readContainedFileWithMode(root, normalized);
5999
+ return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
6000
+ path: normalized,
6001
+ exists: true,
6002
+ sha256: digestBytes(contained.buffer),
6003
+ size: contained.buffer.byteLength,
6004
+ mode: contained.mode
6005
+ };
6006
+ }
6007
+ function sameSnapshot(left, right) {
6008
+ return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
6009
+ }
6010
+ async function configSnapshot(root) {
6011
+ return snapshotFile(root, "artifact-graph.config.yaml");
6012
+ }
6013
+ async function loadRestructureContract(name) {
6014
+ return loadContract((0, import_node_path13.join)(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
6015
+ }
6016
+ async function validateDomainContract(name, value) {
6017
+ const contract = await loadRestructureContract(name);
6018
+ return validateContractAgainstSchema(value, contract).errors;
6019
+ }
6020
+ function occurrenceKey(edge2) {
6021
+ return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
6022
+ }
6023
+ function relationOccurrences(graph) {
6024
+ const counts = /* @__PURE__ */ new Map();
6025
+ return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
6026
+ const key = occurrenceKey(edge2);
6027
+ const occurrence = (counts.get(key) ?? 0) + 1;
6028
+ counts.set(key, occurrence);
6029
+ return {
6030
+ from: edge2.from,
6031
+ to: edge2.to,
6032
+ kind: edge2.kind,
6033
+ source: edge2.source,
6034
+ source_path: edge2.sourcePath,
6035
+ source_line: edge2.sourceLine,
6036
+ occurrence
6037
+ };
6038
+ });
6039
+ }
6040
+ function relationKey(value) {
6041
+ return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
6042
+ }
6043
+ function acceptanceCriteria(node) {
6044
+ const raw = node.attrs?.acceptanceCriteria;
6045
+ if (!Array.isArray(raw)) return [];
6046
+ return raw.flatMap((item, index) => {
6047
+ if (typeof item === "string") {
6048
+ const match = /\b(AC\d+)\b/.exec(item);
6049
+ return [match?.[1] ?? `AC${index + 1}`];
6050
+ }
6051
+ if (item && typeof item === "object") {
6052
+ const record = item;
6053
+ const value = String(record.id ?? record.code ?? "").trim();
6054
+ return value ? [value] : [`AC${index + 1}`];
6055
+ }
6056
+ return [`AC${index + 1}`];
6057
+ });
6058
+ }
6059
+ function spanFor(buffer, path, range) {
6060
+ return {
6061
+ path,
6062
+ start_byte: range.startByte,
6063
+ end_byte: range.endByte,
6064
+ sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
6065
+ };
6066
+ }
6067
+ function mappingTemplate(request, requestDigest, config, sources, unresolved) {
6068
+ return {
6069
+ schema_version: "1.0",
6070
+ request,
6071
+ request_digest: requestDigest,
6072
+ config_snapshot: config,
6073
+ sources: sources.map((source) => ({
6074
+ type: source.type,
6075
+ id: source.id,
6076
+ path: source.path,
6077
+ snapshot: source.snapshot,
6078
+ disposition: "preserved"
6079
+ })),
6080
+ targets: [],
6081
+ content_moves: [],
6082
+ identity_map: [],
6083
+ criterion_map: [],
6084
+ relation_map: [],
6085
+ prose_edits: [],
6086
+ file_headers: [],
6087
+ unresolved
6088
+ };
6089
+ }
6090
+ async function inspectRestructure(root, input) {
6091
+ const schemaErrors = await validateDomainContract("request", input);
6092
+ if (schemaErrors.length > 0) {
6093
+ return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
6094
+ }
6095
+ const request = input;
6096
+ const requestDigest = digestRestructureValue(request);
6097
+ const schema = await loadConfig(root);
6098
+ const graph = await scanArtifacts(root, schema);
6099
+ const allOccurrences = relationOccurrences(graph);
6100
+ const blockers = [];
6101
+ const unresolved = [];
6102
+ const inspected = [];
6103
+ for (const requested of request.sources) {
6104
+ const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
6105
+ if (candidates.length !== 1) {
6106
+ blockers.push({
6107
+ code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
6108
+ 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`,
6109
+ ...requested.path ? { path: requested.path } : {}
6110
+ });
6111
+ continue;
6112
+ }
6113
+ const node = candidates[0];
6114
+ const raw = await readContainedFile(root, node.path);
6115
+ if (!raw) {
6116
+ blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
6117
+ continue;
6118
+ }
6119
+ const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
6120
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
6121
+ blockers.push(...boundary.blockers);
6122
+ const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
6123
+ const uid = `${node.type}:${node.code}`;
6124
+ inspected.push({
6125
+ type: node.type,
6126
+ id: node.code,
6127
+ uid,
6128
+ path: node.path,
6129
+ title: node.title,
6130
+ snapshot: await snapshotFile(root, node.path),
6131
+ ...recordSpan ? {
6132
+ record_span: recordSpan,
6133
+ content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
6134
+ } : {},
6135
+ surrounding_spans: recordSpan ? [
6136
+ ...recordSpan.start_byte > 0 ? [{
6137
+ ...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
6138
+ content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
6139
+ }] : [],
6140
+ ...recordSpan.end_byte < raw.byteLength ? [{
6141
+ ...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
6142
+ content: raw.subarray(recordSpan.end_byte).toString("utf8")
6143
+ }] : []
6144
+ ] : [],
6145
+ acceptance_criteria: acceptanceCriteria(node),
6146
+ incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
6147
+ outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
6148
+ });
6149
+ }
6150
+ if (request.numbering_policy?.mode === "configured-next-available") {
6151
+ unresolved.push({
6152
+ code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
6153
+ message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
6154
+ });
6155
+ }
6156
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6157
+ root,
6158
+ [...new Set(inspected.map((item) => item.path))],
6159
+ []
6160
+ ));
6161
+ const config = await configSnapshot(root);
6162
+ const affectedPaths = new Set(inspected.map((item) => item.path));
6163
+ for (const source of inspected) {
6164
+ for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
6165
+ }
6166
+ const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
6167
+ const inspection = {
6168
+ schema_version: "1.0",
6169
+ request,
6170
+ request_digest: requestDigest,
6171
+ config_snapshot: config,
6172
+ sources: inspected,
6173
+ affected_files: affectedFiles,
6174
+ relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
6175
+ blockers,
6176
+ unresolved,
6177
+ mapping_template: {}
6178
+ };
6179
+ inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
6180
+ return { ok: true, data: inspection };
6181
+ }
6182
+ function finding(code, message, path, line) {
6183
+ return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
6184
+ }
6185
+ async function verifySnapshot(root, expected, blockers) {
6186
+ const normalized = normalizeRelativePath2(expected.path);
6187
+ if (!normalized) {
6188
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6189
+ return void 0;
6190
+ }
6191
+ const actual = await snapshotFile(root, normalized);
6192
+ if (!sameSnapshot(actual, { ...expected, path: normalized })) {
6193
+ blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
6194
+ }
6195
+ return actual;
6196
+ }
6197
+ function validateSpan(buffer, span, blockers) {
6198
+ if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
6199
+ blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
6200
+ return void 0;
6201
+ }
6202
+ const fragment = buffer.subarray(span.start_byte, span.end_byte);
6203
+ if (digestBytes(fragment) !== span.sha256) {
6204
+ blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
6205
+ return void 0;
6206
+ }
6207
+ return fragment;
6208
+ }
6209
+ function rangesCover(range, moves) {
6210
+ 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);
6211
+ let cursor = range.startByte;
6212
+ for (const interval of intervals) {
6213
+ if (interval.start > cursor) return false;
6214
+ cursor = Math.max(cursor, interval.end);
6215
+ }
6216
+ return cursor >= range.endByte;
6217
+ }
6218
+ function edgeDisplay(edge2) {
6219
+ return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
6220
+ }
6221
+ function graphDiff(before, after) {
6222
+ const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6223
+ const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6224
+ const beforeEdges = new Set(before.edges.map(edgeDisplay));
6225
+ const afterEdges = new Set(after.edges.map(edgeDisplay));
6226
+ return {
6227
+ added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
6228
+ removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
6229
+ added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
6230
+ removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
6231
+ };
6232
+ }
6233
+ function issueIdentity(issue2) {
6234
+ const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
6235
+ return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
6236
+ }
6237
+ function readableDiff(path, oldContent, newContent) {
6238
+ const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
6239
+ const newLines = newContent?.split(/(?<=\n)/) ?? [];
6240
+ if (oldContent === newContent) return "";
6241
+ return [
6242
+ `--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
6243
+ `+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
6244
+ ...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
6245
+ ...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
6246
+ ].join("\n");
6247
+ }
6248
+ function findRelativeLinks(fragment) {
6249
+ const found = /* @__PURE__ */ new Set();
6250
+ const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
6251
+ let match;
6252
+ while ((match = pattern.exec(fragment)) !== null) {
6253
+ const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
6254
+ if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
6255
+ }
6256
+ return [...found].sort();
6257
+ }
6258
+ function footnoteReferenceLabels(text) {
6259
+ const labels = /* @__PURE__ */ new Set();
6260
+ const pattern = /\[\^([^\]\s]+)\](?!:)/g;
6261
+ let match;
6262
+ while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
6263
+ return [...labels].sort();
6264
+ }
6265
+ function footnoteDefinition(label) {
6266
+ return `[^${label}]:`;
6267
+ }
6268
+ function splitMarkdownTarget(target) {
6269
+ const cleaned = target.trim().replace(/^<|>$/g, "");
6270
+ const hash = cleaned.indexOf("#");
6271
+ return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
6272
+ }
6273
+ async function pathExists2(absolutePath) {
6274
+ try {
6275
+ await (0, import_promises9.lstat)(absolutePath);
6276
+ return true;
6277
+ } catch {
6278
+ return false;
6279
+ }
6280
+ }
6281
+ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6282
+ const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
6283
+ const migrationNames = new Set(migrationPaths.map((path) => import_node_path13.posix.basename(path)));
6284
+ const directories = new Set(migrationPaths.map((path) => import_node_path13.posix.dirname(path)));
6285
+ const findings = [];
6286
+ async function visit(directory) {
6287
+ for (const entry of await (0, import_promises9.readdir)(directory, { withFileTypes: true })) {
6288
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6289
+ const absolute = (0, import_node_path13.join)(directory, entry.name);
6290
+ if (entry.isDirectory()) {
6291
+ await visit(absolute);
6292
+ continue;
6293
+ }
6294
+ if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
6295
+ const path = (0, import_node_path13.relative)(root, absolute).replace(/\\/g, "/");
6296
+ const raw = await (0, import_promises9.readFile)(absolute, "utf8");
6297
+ const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
6298
+ const lines = raw.split(/\r?\n/);
6299
+ for (const [index, line] of lines.entries()) {
6300
+ const lineNumber = index + 1;
6301
+ if (MARKDOWN_FILE_SUFFIX.test(path)) {
6302
+ const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
6303
+ let match;
6304
+ while ((match = pattern.exec(line)) !== null) {
6305
+ const literal = match[0];
6306
+ const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
6307
+ if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
6308
+ if (!migrationNames.has(import_node_path13.posix.basename(linkPath))) continue;
6309
+ const resolved = normalizeRelativePath2(import_node_path13.posix.join(import_node_path13.posix.dirname(path), linkPath));
6310
+ if (!resolved || targetPaths.includes(resolved)) continue;
6311
+ if (anchor) {
6312
+ findings.push(finding(
6313
+ "ANCHOR_REFERENCE_UNRESOLVED",
6314
+ `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`,
6315
+ path,
6316
+ lineNumber
6317
+ ));
6318
+ } else if (!await pathExists2((0, import_node_path13.resolve)(root, resolved))) {
6319
+ findings.push(finding(
6320
+ "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
6321
+ `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`,
6322
+ path,
6323
+ lineNumber
6324
+ ));
6325
+ }
6326
+ }
6327
+ }
6328
+ if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
6329
+ const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
6330
+ const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
6331
+ if (directoryLiteral) {
6332
+ findings.push(finding(
6333
+ "RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
6334
+ `A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
6335
+ path,
6336
+ lineNumber
6337
+ ));
6338
+ }
6339
+ }
6340
+ }
6341
+ }
6342
+ }
6343
+ await visit((0, import_node_path13.resolve)(root));
6344
+ const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
6345
+ return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
6346
+ }
6347
+ function mergeFindings(target, additions) {
6348
+ const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
6349
+ for (const item of additions) {
6350
+ const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
6351
+ if (seen.has(key)) continue;
6352
+ seen.add(key);
6353
+ target.push(item);
6354
+ }
6355
+ }
6356
+ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
6357
+ const results = [];
6358
+ async function visit(directory) {
6359
+ for (const entry of await (0, import_promises9.readdir)(directory, { withFileTypes: true })) {
6360
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6361
+ const absolute = (0, import_node_path13.join)(directory, entry.name);
6362
+ if (entry.isDirectory()) {
6363
+ await visit(absolute);
6364
+ } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
6365
+ const path = (0, import_node_path13.relative)(root, absolute).replace(/\\/g, "/");
6366
+ if (excludedPaths.has(path)) continue;
6367
+ const raw = await (0, import_promises9.readFile)(absolute, "utf8");
6368
+ raw.split(/\r?\n/).forEach((line, index) => {
6369
+ for (const reference of references) {
6370
+ if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
6371
+ }
6372
+ });
6373
+ }
6374
+ }
6375
+ }
6376
+ await visit((0, import_node_path13.resolve)(root));
6377
+ return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6378
+ }
6379
+ function expectedRelationTargets(mapping) {
6380
+ return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
6381
+ }
6382
+ function relationTriples(graph) {
6383
+ return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
6384
+ }
6385
+ function formatMode(value) {
6386
+ return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
6387
+ }
6388
+ function isPosixFileMode(value) {
6389
+ return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
6390
+ }
6391
+ function modeIsUsableAtApply(mode, umask) {
6392
+ return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
6393
+ }
6394
+ function createModeForUmask(umask) {
6395
+ return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
6396
+ }
6397
+ function planningUmask() {
6398
+ return process.umask() & MAX_POSIX_MODE;
6399
+ }
6400
+ function restructureBoundaryFindings(operations, limits) {
6401
+ const findings = [];
6402
+ if (operations.length === 0) {
6403
+ findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
6404
+ return findings;
6405
+ }
6406
+ if (operations.length > limits.max_operations) {
6407
+ findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
6408
+ }
6409
+ const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
6410
+ if (totalBytes > limits.max_total_bytes) {
6411
+ findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
6412
+ }
6413
+ const expectedCreateMode = createModeForUmask(limits.umask);
6414
+ const applyModeContract = limits.mode_contract === "apply";
6415
+ for (const operation of operations) {
6416
+ const parent = (0, import_node_path13.dirname)(operation.path) || ".";
6417
+ if (!operation.parent_exists) {
6418
+ findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6419
+ } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
6420
+ findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
6421
+ }
6422
+ if (!isPosixFileMode(operation.mode)) {
6423
+ findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
6424
+ }
6425
+ if (!isPosixFileMode(operation.original_mode)) {
6426
+ findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
6427
+ }
6428
+ if (operation.original_exists && operation.original_mode === null) {
6429
+ findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
6430
+ }
6431
+ if (!operation.original_exists && operation.original_mode !== null) {
6432
+ findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
6433
+ }
6434
+ if (applyModeContract) {
6435
+ for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
6436
+ if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
6437
+ findings.push(finding(
6438
+ "MODE_NOT_USABLE",
6439
+ `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}`,
6440
+ operation.path
6441
+ ));
6442
+ }
6443
+ }
6444
+ if (operation.action === "create") {
6445
+ if (operation.original_exists) {
6446
+ findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
6447
+ }
6448
+ if (!applyModeContract && operation.mode !== expectedCreateMode) {
6449
+ findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
6450
+ }
6451
+ } else if (operation.action === "replace") {
6452
+ if (!operation.original_exists) {
6453
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
6454
+ } else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
6455
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
6456
+ }
6457
+ } else if (operation.mode !== null) {
6458
+ findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
6459
+ }
6460
+ }
6461
+ return findings;
6462
+ }
6463
+ async function probeDirectory(absolutePath) {
6464
+ try {
6465
+ const info = await (0, import_promises9.stat)(absolutePath);
6466
+ return { exists: info.isDirectory(), device: info.dev };
6467
+ } catch (error) {
6468
+ const code = error.code;
6469
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
6470
+ throw error;
6471
+ }
6472
+ }
6473
+ async function planRestructure(root, input) {
6474
+ const schemaErrors = await validateDomainContract("mapping", input);
6475
+ if (schemaErrors.length > 0) {
6476
+ return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
6477
+ }
6478
+ const mapping = input;
6479
+ const blockers = [];
6480
+ const unresolved = [...mapping.unresolved];
6481
+ const requestErrors = await validateDomainContract("request", mapping.request);
6482
+ if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
6483
+ if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
6484
+ const currentConfig = await configSnapshot(root);
6485
+ if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
6486
+ const schema = await loadConfig(root);
6487
+ const beforeGraph = await scanArtifacts(root, schema);
6488
+ const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
6489
+ const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
6490
+ const seenSourceUids = /* @__PURE__ */ new Set();
6491
+ for (const source of mapping.sources) {
6492
+ const uid = `${source.type}:${source.id}`;
6493
+ if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
6494
+ seenSourceUids.add(uid);
6495
+ 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));
6496
+ }
6497
+ for (const requested of mapping.request.sources) {
6498
+ const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
6499
+ const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
6500
+ if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
6501
+ }
6502
+ for (const source of mapping.sources) {
6503
+ if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
6504
+ blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
6505
+ }
6506
+ }
6507
+ const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
6508
+ const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
6509
+ for (const occurrence of requiredOccurrences) {
6510
+ if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
6511
+ }
6512
+ for (const entry of mapping.relation_map) {
6513
+ 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));
6514
+ }
6515
+ const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
6516
+ const targetKeys = /* @__PURE__ */ new Set();
6517
+ const targetUids = /* @__PURE__ */ new Set();
6518
+ for (const target of mapping.targets) {
6519
+ const path = normalizeRelativePath2(target.path);
6520
+ if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
6521
+ if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
6522
+ targetKeys.add(target.key);
6523
+ 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));
6524
+ const uid = `${target.type}:${target.id}`;
6525
+ if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
6526
+ targetUids.add(uid);
6527
+ if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
6528
+ blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
6529
+ }
6530
+ 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));
6531
+ if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
6532
+ }
6533
+ for (const identity of mapping.identity_map) {
6534
+ 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}`));
6535
+ }
6536
+ for (const source of mapping.sources) {
6537
+ const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
6538
+ 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));
6539
+ 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));
6540
+ }
6541
+ const snapshots = /* @__PURE__ */ new Map();
6542
+ const buffers = /* @__PURE__ */ new Map();
6543
+ for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
6544
+ const normalized = normalizeRelativePath2(expected.path);
6545
+ if (!normalized) {
6546
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6547
+ continue;
6548
+ }
6549
+ if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
6550
+ blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
6551
+ continue;
6552
+ }
6553
+ const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
6554
+ if (actual) snapshots.set(normalized, actual);
6555
+ const raw = await readContainedFile(root, normalized);
6556
+ if (raw) buffers.set(normalized, raw);
6557
+ }
6558
+ snapshots.set(currentConfig.path, currentConfig);
6559
+ const declaredSnapshots = [
6560
+ mapping.config_snapshot,
6561
+ ...mapping.sources.map((source) => source.snapshot),
6562
+ ...mapping.targets.map((target) => target.snapshot)
6563
+ ];
6564
+ const checkedDeclaredModes = /* @__PURE__ */ new Set();
6565
+ for (const declared of declaredSnapshots) {
6566
+ const declaredMode = declared.mode ?? null;
6567
+ const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
6568
+ const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
6569
+ if (checkedDeclaredModes.has(key)) continue;
6570
+ checkedDeclaredModes.add(key);
6571
+ if (!isPosixFileMode(declaredMode)) {
6572
+ blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
6573
+ } else if (declared.exists && declaredMode === null) {
6574
+ blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
6575
+ } else if (!declared.exists && declaredMode !== null) {
6576
+ blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
6577
+ }
6578
+ }
6579
+ const moveIds = /* @__PURE__ */ new Set();
6580
+ const rangesByPath = /* @__PURE__ */ new Map();
6581
+ const fragments = /* @__PURE__ */ new Map();
6582
+ for (const move of mapping.content_moves) {
6583
+ if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
6584
+ moveIds.add(move.id);
6585
+ const sourcePath = normalizeRelativePath2(move.source.path);
6586
+ const targetPath = normalizeRelativePath2(move.target.path);
6587
+ if (!sourcePath || !buffers.has(sourcePath)) {
6588
+ blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
6589
+ continue;
6590
+ }
6591
+ if (!targetPath || !isPathAllowed(targetPath, allowed)) {
6592
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
6593
+ continue;
6594
+ }
6595
+ const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
6596
+ if (!fragment) continue;
6597
+ fragments.set(move.id, fragment);
6598
+ const pathMoves = rangesByPath.get(sourcePath) ?? [];
6599
+ for (const existing of pathMoves) {
6600
+ if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
6601
+ 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;
6602
+ if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
6603
+ }
6604
+ }
6605
+ pathMoves.push(move);
6606
+ rangesByPath.set(sourcePath, pathMoves);
6607
+ if ((0, import_node_path13.dirname)(sourcePath) !== (0, import_node_path13.dirname)(targetPath)) {
6608
+ for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6609
+ const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6610
+ if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
6611
+ }
6612
+ }
6613
+ }
6614
+ for (const source of mapping.sources) {
6615
+ const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
6616
+ const raw = buffers.get(source.path);
6617
+ if (!node || !raw) continue;
6618
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
6619
+ blockers.push(...boundary.blockers);
6620
+ 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));
6621
+ if (source.type === "feature" && source.disposition === "retired") {
6622
+ const criteria = acceptanceCriteria(node);
6623
+ const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
6624
+ 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));
6625
+ }
6626
+ }
6627
+ const candidateBuffers = /* @__PURE__ */ new Map();
6628
+ const touched = /* @__PURE__ */ new Set();
6629
+ for (const [sourcePath, moves] of rangesByPath) {
6630
+ const original = buffers.get(sourcePath);
6631
+ const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
6632
+ const chunks = [];
6633
+ let cursor = 0;
6634
+ for (const move of removals) {
6635
+ chunks.push(original.subarray(cursor, move.source.start_byte));
6636
+ cursor = move.source.end_byte;
6637
+ }
6638
+ chunks.push(original.subarray(cursor));
6639
+ candidateBuffers.set(sourcePath, Buffer.concat(chunks));
6640
+ touched.add(sourcePath);
6641
+ }
6642
+ const movesByTarget = /* @__PURE__ */ new Map();
6643
+ for (const move of mapping.content_moves) {
6644
+ const targetPath = normalizeRelativePath2(move.target.path);
6645
+ if (!targetPath || !fragments.has(move.id)) continue;
6646
+ const list = movesByTarget.get(targetPath) ?? [];
6647
+ list.push(move);
6648
+ movesByTarget.set(targetPath, list);
6649
+ }
6650
+ for (const [targetPath, moves] of movesByTarget) {
6651
+ const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
6652
+ const appended = [base];
6653
+ for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
6654
+ const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
6655
+ appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
6656
+ }
6657
+ candidateBuffers.set(targetPath, Buffer.concat(appended));
6658
+ touched.add(targetPath);
6659
+ if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
6660
+ }
6661
+ for (const header of mapping.file_headers) {
6662
+ const path = normalizeRelativePath2(header.path);
6663
+ if (!path || !isPathAllowed(path, allowed)) {
6664
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
6665
+ continue;
6666
+ }
6667
+ if (header.affected_records.length === 0 && header.content === "") {
6668
+ const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
6669
+ if (unselected.length > 0) {
6670
+ blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
6671
+ } else {
6672
+ candidateBuffers.set(path, Buffer.alloc(0));
6673
+ touched.add(path);
6674
+ }
6675
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6676
+ continue;
6677
+ }
6678
+ const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6679
+ candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
6680
+ touched.add(path);
6681
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6682
+ }
6683
+ for (const edit of mapping.prose_edits) {
6684
+ const path = normalizeRelativePath2(edit.target_path);
6685
+ const sourcePath = normalizeRelativePath2(edit.source.path);
6686
+ if (!path || !sourcePath || !buffers.has(sourcePath)) {
6687
+ blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
6688
+ continue;
6689
+ }
6690
+ if (!isPathAllowed(path, allowed)) {
6691
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
6692
+ continue;
6693
+ }
6694
+ if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
6695
+ const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6696
+ const occurrences = current.split(edit.old_text).length - 1;
6697
+ if (!edit.old_text || occurrences !== 1) {
6698
+ blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
6699
+ continue;
6700
+ }
6701
+ candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
6702
+ touched.add(path);
6703
+ }
6704
+ const candidates = [];
6705
+ const umask = planningUmask();
6706
+ for (const path of [...touched].sort()) {
6707
+ if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
6708
+ const original = buffers.get(path);
6709
+ const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
6710
+ if (original && original.equals(candidate)) continue;
6711
+ const deleteFile = candidate.byteLength === 0;
6712
+ const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
6713
+ const action = deleteFile ? "delete" : original ? "replace" : "create";
6714
+ candidates.push({
6715
+ path,
6716
+ action,
6717
+ content: deleteFile ? null : candidate.toString("utf8"),
6718
+ sha256: deleteFile ? null : digestBytes(candidate),
6719
+ mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
6720
+ original: snapshot,
6721
+ diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6722
+ });
6723
+ }
6724
+ const rootDirectory = await probeDirectory((0, import_node_path13.resolve)(root));
6725
+ const parentProbes = /* @__PURE__ */ new Map();
6726
+ for (const candidate of candidates) {
6727
+ const parent = (0, import_node_path13.dirname)(candidate.path);
6728
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory((0, import_node_path13.resolve)(root, parent)));
6729
+ }
6730
+ blockers.push(...restructureBoundaryFindings(
6731
+ candidates.map((candidate) => {
6732
+ const parent = parentProbes.get((0, import_node_path13.dirname)(candidate.path));
6733
+ return {
6734
+ path: candidate.path,
6735
+ action: candidate.action,
6736
+ original_exists: candidate.original.exists,
6737
+ original_mode: candidate.original.mode,
6738
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6739
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6740
+ mode: candidate.mode,
6741
+ parent_exists: parent.exists,
6742
+ parent_device: parent.device,
6743
+ root_device: rootDirectory.device ?? -1
6744
+ };
6745
+ }),
6746
+ {
6747
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6748
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6749
+ umask
6750
+ }
6751
+ ));
6752
+ const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
6753
+ const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
6754
+ const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
6755
+ const candidateIssues = validateGraph(afterGraph, schema);
6756
+ for (const issue2 of candidateIssues) {
6757
+ if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
6758
+ }
6759
+ const afterTriples = relationTriples(afterGraph);
6760
+ for (const expected of expectedRelationTargets(mapping)) {
6761
+ if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
6762
+ }
6763
+ for (const source of mapping.sources) {
6764
+ const uid = `${source.type}:${source.id}`;
6765
+ const present = afterGraph.nodes.some((node) => node.uid === uid);
6766
+ if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
6767
+ if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
6768
+ }
6769
+ for (const criterion of mapping.criterion_map) {
6770
+ const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
6771
+ 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));
6772
+ for (const target of criterion.targets) {
6773
+ const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
6774
+ 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));
6775
+ }
6776
+ }
6777
+ for (const header of mapping.file_headers) {
6778
+ const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
6779
+ const declaredRecords = [...header.affected_records].sort();
6780
+ 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));
6781
+ }
6782
+ const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
6783
+ for (const move of mapping.content_moves) {
6784
+ if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
6785
+ for (const path of [move.source.path, move.target.path]) {
6786
+ 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));
6787
+ }
6788
+ }
6789
+ for (const target of mapping.targets) {
6790
+ 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));
6791
+ }
6792
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6793
+ root,
6794
+ [...new Set(mapping.sources.map((source) => source.path))],
6795
+ [...new Set([
6796
+ ...mapping.targets.map((target) => target.path),
6797
+ ...mapping.content_moves.map((move) => move.target.path),
6798
+ ...mapping.file_headers.map((header) => header.path)
6799
+ ].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
6800
+ ));
6801
+ for (const move of mapping.content_moves) {
6802
+ const fragment = fragments.get(move.id);
6803
+ const sourcePath = normalizeRelativePath2(move.source.path);
6804
+ const targetPath = normalizeRelativePath2(move.target.path);
6805
+ if (!fragment || !sourcePath || !targetPath) continue;
6806
+ const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
6807
+ const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
6808
+ for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
6809
+ if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
6810
+ blockers.push(finding(
6811
+ "FOOTNOTE_DEFINITION_UNMAPPED",
6812
+ `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`,
6813
+ sourcePath
6814
+ ));
6815
+ }
6816
+ }
6817
+ const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
6818
+ const plan = {
6819
+ schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
6820
+ operation_id: (0, import_node_crypto5.randomUUID)(),
6821
+ validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6822
+ request_digest: mapping.request_digest,
6823
+ mapping_digest: digestRestructureValue(mapping),
6824
+ config_snapshot: currentConfig,
6825
+ input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
6826
+ candidates,
6827
+ graph_diff: graphDiff(beforeGraph, afterGraph),
6828
+ validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
6829
+ applicable: blockers.length === 0 && unresolved.length === 0
6830
+ };
6831
+ const planErrors = await validateDomainContract("plan", plan);
6832
+ if (planErrors.length > 0) {
6833
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
6834
+ }
6835
+ return { ok: true, data: plan };
6836
+ }
6837
+ async function gateRestructureOperationPlan(operation, plan) {
6838
+ const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
6839
+ if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
6840
+ return {
6841
+ ok: false,
6842
+ error: {
6843
+ code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
6844
+ message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
6845
+ }
6846
+ };
6847
+ }
6848
+ const errors = await validateDomainContract("plan", plan);
6849
+ if (errors.length > 0) {
6850
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
6851
+ }
6852
+ return { ok: true, data: plan };
6853
+ }
6854
+ function refusal(code, message, findings = []) {
6855
+ return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
6856
+ }
6857
+ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6858
+ const absolute = (0, import_node_path13.resolve)(planPath);
6859
+ let info;
6860
+ try {
6861
+ info = await (0, import_promises9.lstat)(absolute);
6862
+ } catch (cause) {
6863
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6864
+ }
6865
+ if (info.isSymbolicLink() || !info.isFile()) {
6866
+ return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
6867
+ }
6868
+ let bytes;
6869
+ try {
6870
+ bytes = await (0, import_promises9.readFile)(absolute);
6871
+ } catch (cause) {
6872
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6873
+ }
6874
+ let parsed;
6875
+ try {
6876
+ parsed = JSON.parse(bytes.toString("utf8"));
6877
+ } catch (cause) {
6878
+ return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
6879
+ }
6880
+ const gate = await gateRestructureOperationPlan(operation, parsed);
6881
+ if (!gate.ok) return gate;
6882
+ return { ok: true, data: { path: absolute, realPath: await (0, import_promises9.realpath)(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
6883
+ }
6884
+ function planRootIdentityFindings(document) {
6885
+ const findings = [];
6886
+ const record = (path, label) => {
6887
+ const normalized = normalizeRelativePath2(path);
6888
+ if (!normalized || normalized !== path) {
6889
+ findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
6890
+ }
6891
+ };
6892
+ record(document.plan.config_snapshot.path, "config_snapshot");
6893
+ for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
6894
+ for (const candidate of document.plan.candidates) {
6895
+ record(candidate.path, "candidate");
6896
+ record(candidate.original.path, "candidate original");
6897
+ }
6898
+ if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
6899
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6900
+ }
6901
+ const relativePlan = (0, import_node_path13.relative)(document.root, document.realPath);
6902
+ if (!relativePlan || relativePlan.startsWith("..") || (0, import_node_path13.isAbsolute)(relativePlan)) {
6903
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6904
+ }
6905
+ return findings;
6906
+ }
6907
+ async function operationBoundaries(root, plan) {
6908
+ const rootDirectory = await probeDirectory((0, import_node_path13.resolve)(root));
6909
+ const parents = /* @__PURE__ */ new Map();
6910
+ const boundaries = [];
6911
+ for (const candidate of plan.candidates) {
6912
+ const parent = (0, import_node_path13.dirname)(candidate.path) || ".";
6913
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory((0, import_node_path13.resolve)(root, parent)));
6914
+ const probe = parents.get(parent);
6915
+ boundaries.push({
6916
+ path: candidate.path,
6917
+ action: candidate.action,
6918
+ original_exists: candidate.original.exists,
6919
+ original_mode: candidate.original.mode,
6920
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6921
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6922
+ mode: candidate.mode,
6923
+ parent_exists: probe.exists,
6924
+ parent_device: probe.device,
6925
+ root_device: rootDirectory.device ?? -1
6926
+ });
6927
+ }
6928
+ return boundaries;
6929
+ }
6930
+ async function applyPreconditionFindings(root, document) {
6931
+ const findings = [];
6932
+ const plan = document.plan;
6933
+ const currentConfig = await configSnapshot(root);
6934
+ if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
6935
+ findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
6936
+ }
6937
+ for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
6938
+ const relativePlan = (0, import_node_path13.relative)(root, document.realPath).replace(/\\/g, "/");
6939
+ for (const candidate of plan.candidates) {
6940
+ if (candidate.path === relativePlan) {
6941
+ findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
6942
+ }
6943
+ if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
6944
+ findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
6945
+ }
6946
+ let original;
6947
+ try {
6948
+ original = await snapshotFile(root, candidate.path);
6949
+ } catch (cause) {
6950
+ findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
6951
+ continue;
6952
+ }
6953
+ if (!sameSnapshot(original, candidate.original)) {
6954
+ findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
6955
+ }
6956
+ if (candidate.action === "delete") continue;
6957
+ if (candidate.mode === null) {
6958
+ findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
6959
+ }
6960
+ if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
6961
+ findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
6962
+ }
6963
+ }
6964
+ findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
6965
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6966
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6967
+ umask: planningUmask(),
6968
+ mode_contract: "apply"
6969
+ }));
6970
+ return findings;
6971
+ }
6972
+ function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
6973
+ const excludedConsumers = new Set(excludedConsumerPaths);
6974
+ const addedNodes = plan.graph_diff.added_nodes;
6975
+ const removedNodes = new Set(plan.graph_diff.removed_nodes);
6976
+ const addedEdges = plan.graph_diff.added_edges;
6977
+ const removedEdges = new Set(plan.graph_diff.removed_edges);
6978
+ const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
6979
+ const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
6980
+ const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
6981
+ return async function validateCandidateState(input) {
6982
+ const schema = await loadConfig(input.root);
6983
+ const graph = await scanArtifacts(input.root, schema);
6984
+ if (input.signal.aborted) return { passed: false };
6985
+ const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6986
+ const edges = new Set(graph.edges.map(edgeDisplay));
6987
+ const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
6988
+ const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
6989
+ const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
6990
+ const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
6991
+ const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
6992
+ const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
6993
+ return { passed };
6994
+ };
6995
+ }
6996
+ async function applyRestructure(input) {
6997
+ if (input.confirmCooperativeWriters !== true) {
6998
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
6999
+ }
7000
+ const qualification = await qualifyRestructureMechanism(input.root);
7001
+ if (!qualification.ok) return qualification;
7002
+ const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
7003
+ if (!document.ok) return document;
7004
+ const plan = document.data.plan;
7005
+ if (plan.candidates.length === 0) {
7006
+ return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
7007
+ }
7008
+ if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
7009
+ return refusal(
7010
+ "PLAN_NOT_APPLICABLE",
7011
+ "The plan is not applicable: it still carries blockers or unresolved findings",
7012
+ [...plan.validation.blockers, ...plan.validation.unresolved]
7013
+ );
7014
+ }
7015
+ const identity = planRootIdentityFindings(document.data);
7016
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7017
+ const drift = await applyPreconditionFindings(qualification.data.root, document.data);
7018
+ if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
7019
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
7020
+ if (!mechanismRoot.ok) return mechanismRoot;
7021
+ const planRelPath = (0, import_node_path13.relative)(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
7022
+ const applied = await applyRestructureFileSet(qualification.data.root, plan, {
7023
+ validate: createRestructureValidationCallback(plan, [planRelPath])
7024
+ });
7025
+ if (!applied.ok) return applied;
7026
+ const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
7027
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7028
+ }
7029
+ async function recoverRestructure(input) {
7030
+ if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
7031
+ return refusal(
7032
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7033
+ "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
7034
+ );
7035
+ }
7036
+ const qualification = await qualifyRestructureMechanism(input.root);
7037
+ if (!qualification.ok) return qualification;
7038
+ const document = await loadRestructurePlanDocument("recover", qualification.data.root, input.planPath);
7039
+ if (!document.ok) return document;
7040
+ const identity = planRootIdentityFindings(document.data);
7041
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7042
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7043
+ if (!mechanismRoot.ok) return mechanismRoot;
7044
+ const recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
7045
+ allParticipantsStopped: true,
7046
+ exclusiveMaintenance: true
7047
+ });
7048
+ if (!recovered.ok) return recovered;
7049
+ const projection = projectRestructureFileSetResult(recovered.data, document.data.realPath, document.data.digest);
7050
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7051
+ }
7052
+ async function pruneRestructureRecovery(input) {
7053
+ if (input.confirmCooperativeWriters !== true) {
7054
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
7055
+ }
7056
+ if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
7057
+ return refusal(
7058
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7059
+ "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
7060
+ );
7061
+ }
7062
+ const qualification = await qualifyRestructureMechanism(input.root);
7063
+ if (!qualification.ok) return qualification;
7064
+ const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
7065
+ if (!document.ok) return document;
7066
+ const identity = planRootIdentityFindings(document.data);
7067
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7068
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7069
+ if (!mechanismRoot.ok) return mechanismRoot;
7070
+ const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
7071
+ allParticipantsStopped: input.allParticipantsStopped,
7072
+ exclusiveMaintenance: input.exclusiveMaintenance
7073
+ });
7074
+ if (!pruned.ok) return pruned;
7075
+ const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
7076
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7077
+ }
7078
+ var import_node_crypto5, import_promises9, import_node_path13, import_node_url3, import_meta3, 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;
7079
+ var init_restructure = __esm({
7080
+ "src/restructure.ts"() {
7081
+ "use strict";
7082
+ import_node_crypto5 = require("crypto");
7083
+ import_promises9 = require("fs/promises");
7084
+ import_node_path13 = require("path");
7085
+ import_node_url3 = require("url");
7086
+ init_index();
7087
+ init_contract_kernel();
7088
+ init_restructure_software();
7089
+ init_restructure_file_set();
7090
+ import_meta3 = {};
7091
+ RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
7092
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
7093
+ RESTRUCTURE_MAX_OPERATIONS = 1024;
7094
+ RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
7095
+ MAX_POSIX_MODE = 511;
7096
+ CREATE_MODE_BASE = 438;
7097
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : (0, import_node_path13.dirname)((0, import_node_url3.fileURLToPath)(import_meta3.url));
7098
+ CONTRACT_ROOT = (0, import_node_path13.join)(MODULE_DIRECTORY, "..", "contracts");
7099
+ SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
7100
+ TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
7101
+ MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
7102
+ RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
7103
+ MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
7104
+ SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
7105
+ }
7106
+ });
7107
+
5026
7108
  // src/index.ts
5027
7109
  var index_exports = {};
5028
7110
  __export(index_exports, {
@@ -5030,6 +7112,7 @@ __export(index_exports, {
5030
7112
  BASELINE_CONSTRAINTS: () => BASELINE_CONSTRAINTS,
5031
7113
  BASELINE_CONSTRAINTS_COUNT: () => BASELINE_CONSTRAINTS_COUNT,
5032
7114
  BASELINE_ITEMS_COUNT: () => BASELINE_ITEMS_COUNT,
7115
+ CONTRACTS_PACKAGE_NAME: () => CONTRACTS_PACKAGE_NAME2,
5033
7116
  CONTRACT_ERROR_CODES: () => CONTRACT_ERROR_CODES,
5034
7117
  ContractCatalog: () => ContractCatalog,
5035
7118
  ContractError: () => ContractError,
@@ -5037,35 +7120,62 @@ __export(index_exports, {
5037
7120
  DEFAULT_MAX_CHARS: () => DEFAULT_MAX_CHARS,
5038
7121
  DEFAULT_SCHEMA: () => DEFAULT_SCHEMA,
5039
7122
  E2E_NORMALIZER_CONFIG: () => E2E_NORMALIZER_CONFIG,
7123
+ FILE_SET_RESULT_OBJECT: () => FILE_SET_RESULT_OBJECT,
7124
+ FOUNDATION_PACKAGE_NAME: () => FOUNDATION_PACKAGE_NAME,
7125
+ GRAPH_DOMAIN_CODES: () => GRAPH_DOMAIN_CODES,
7126
+ GRAPH_PROVIDER_ENTRY: () => GRAPH_PROVIDER_ENTRY,
7127
+ GRAPH_PROVIDER_ID: () => GRAPH_PROVIDER_ID,
5040
7128
  MIN_PROMPT_CHARS: () => MIN_PROMPT_CHARS,
7129
+ PROFESSIONAL_CONCLUSION_OBJECT: () => PROFESSIONAL_CONCLUSION_OBJECT,
7130
+ RESTRUCTURE_MAX_OPERATIONS: () => RESTRUCTURE_MAX_OPERATIONS,
7131
+ RESTRUCTURE_MAX_TOTAL_BYTES: () => RESTRUCTURE_MAX_TOTAL_BYTES,
7132
+ RESTRUCTURE_PLAN_SCHEMA_VERSION: () => RESTRUCTURE_PLAN_SCHEMA_VERSION,
7133
+ RESTRUCTURE_QUALIFIED_ARCH: () => RESTRUCTURE_QUALIFIED_ARCH,
7134
+ RESTRUCTURE_QUALIFIED_FILESYSTEM: () => RESTRUCTURE_QUALIFIED_FILESYSTEM,
7135
+ RESTRUCTURE_QUALIFIED_PLATFORM: () => RESTRUCTURE_QUALIFIED_PLATFORM,
7136
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH: () => RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
7137
+ RESTRUCTURE_RECOVERY_REL_PATH: () => RESTRUCTURE_RECOVERY_REL_PATH,
7138
+ RESTRUCTURE_RECOVERY_ROOT_MODE: () => RESTRUCTURE_RECOVERY_ROOT_MODE,
7139
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS: () => RESTRUCTURE_VALIDATION_TIMEOUT_MS,
5041
7140
  TARGET_ARTIFACT_TYPES: () => TARGET_ARTIFACT_TYPES,
5042
7141
  VALID_PACKET_TARGET_TYPES: () => VALID_PACKET_TARGET_TYPES,
5043
7142
  VERSION_INDEX_SCHEMA_VERSION: () => VERSION_INDEX_SCHEMA_VERSION,
5044
7143
  VERSION_LOCK_PATH: () => VERSION_LOCK_PATH,
5045
7144
  VERSION_LOCK_SCHEMA_VERSION: () => VERSION_LOCK_SCHEMA_VERSION,
5046
7145
  applyPreparedManagedHookBlocks: () => applyPreparedManagedHookBlocks,
7146
+ applyRestructure: () => applyRestructure,
7147
+ applyRestructureFileSet: () => applyRestructureFileSet,
5047
7148
  assemblePacket: () => assemblePacket,
5048
7149
  auditPackets: () => auditPackets,
5049
7150
  auditVersionLock: () => auditVersionLock,
5050
7151
  bootstrapVersionLock: () => bootstrapVersionLock,
7152
+ buildFileSetApplyRequest: () => buildFileSetApplyRequest,
5051
7153
  buildGraph: () => buildGraph,
5052
7154
  buildVersionIndex: () => buildVersionIndex,
7155
+ candidateByteDigest: () => candidateByteDigest,
5053
7156
  collectChangedPaths: () => collectChangedPaths,
5054
7157
  computeCoverageBoundary: () => computeCoverageBoundary,
5055
7158
  computeE2eCoverageStats: () => computeE2eCoverageStats,
5056
7159
  computeImpact: () => computeImpact,
5057
7160
  computeRevisionDigest: () => computeRevisionDigest,
5058
- dirname: () => import_node_path11.dirname,
7161
+ createModeForUmask: () => createModeForUmask,
7162
+ createRestructureRootBinding: () => createRestructureRootBinding,
7163
+ createRestructureValidationCallback: () => createRestructureValidationCallback,
7164
+ digestRestructureValue: () => digestRestructureValue,
7165
+ dirname: () => import_node_path14.dirname,
5059
7166
  discoverAndAuditPackets: () => discoverAndAuditPackets,
5060
7167
  discoverTargets: () => discoverTargets,
5061
7168
  doctorArtifactChain: () => doctorArtifactChain,
5062
- extname: () => import_node_path11.extname,
7169
+ ensureRestructureMechanismRoot: () => ensureRestructureMechanismRoot,
7170
+ extname: () => import_node_path14.extname,
5063
7171
  filterGraphByView: () => filterGraphByView,
5064
7172
  formatContextMarkdown: () => formatContextMarkdown,
7173
+ gateRestructureOperationPlan: () => gateRestructureOperationPlan,
5065
7174
  generateE2eRegistry: () => generateE2eRegistry,
5066
7175
  getArtifactTypeMetadata: () => getArtifactTypeMetadata,
5067
7176
  getExternalEntryInfo: () => getExternalEntryInfo,
5068
7177
  getTargetArtifactTypes: () => getTargetArtifactTypes,
7178
+ inspectRestructure: () => inspectRestructure,
5069
7179
  installManagedHookBlock: () => installManagedHookBlock,
5070
7180
  isOfficialNamespace: () => isOfficialNamespace,
5071
7181
  isPacketTargetType: () => isPacketTargetType,
@@ -5076,14 +7186,26 @@ __export(index_exports, {
5076
7186
  loadContract: () => loadContract,
5077
7187
  loadContractCatalog: () => loadContractCatalog,
5078
7188
  loadContractsFromDirectory: () => loadContractsFromDirectory,
7189
+ loadFoundationModule: () => loadFoundationModule,
7190
+ locateSoftwareRecord: () => locateSoftwareRecord,
7191
+ markdownRecordHeadings: () => markdownRecordHeadings,
5079
7192
  matchesConfiguredArtifactPath: () => matchesConfiguredArtifactPath,
5080
7193
  nextId: () => nextId,
5081
7194
  normalizeE2eLegacyArtifact: () => normalizeE2eLegacyArtifact,
5082
7195
  normalizeToCanonical: () => normalizeToCanonical,
7196
+ observeRestructureJournal: () => observeRestructureJournal,
5083
7197
  parseTargetSelector: () => parseTargetSelector,
5084
7198
  parseTargetsFile: () => parseTargetsFile,
7199
+ planRestructure: () => planRestructure,
7200
+ planningUmask: () => planningUmask,
5085
7201
  prepareManagedHookBlock: () => prepareManagedHookBlock,
7202
+ projectRestructureFileSetResult: () => projectRestructureFileSetResult,
7203
+ pruneRestructureFileSet: () => pruneRestructureFileSet,
7204
+ pruneRestructureRecovery: () => pruneRestructureRecovery,
7205
+ qualifyRestructureMechanism: () => qualifyRestructureMechanism,
5086
7206
  queryGraph: () => queryGraph,
7207
+ recoverRestructure: () => recoverRestructure,
7208
+ recoverRestructureFileSet: () => recoverRestructureFileSet,
5087
7209
  refreshVersionLock: () => refreshVersionLock,
5088
7210
  renderCoverageBoundaryMarkdown: () => renderCoverageBoundaryMarkdown,
5089
7211
  renderDoctorMarkdown: () => renderDoctorMarkdown,
@@ -5094,6 +7216,7 @@ __export(index_exports, {
5094
7216
  renderTraceVersionMarkdown: () => renderTraceVersionMarkdown,
5095
7217
  renderVersionLockAuditMarkdown: () => renderVersionLockAuditMarkdown,
5096
7218
  renderVersionLockRefreshMarkdown: () => renderVersionLockRefreshMarkdown,
7219
+ replaceSoftwareHeader: () => replaceSoftwareHeader,
5097
7220
  resolveArtifactContext: () => resolveArtifactContext,
5098
7221
  resolveArtifactGraphCli: () => resolveArtifactGraphCli,
5099
7222
  resolveArtifactTypeName: () => resolveArtifactTypeName,
@@ -5101,6 +7224,10 @@ __export(index_exports, {
5101
7224
  resolveGitHookPath: () => resolveGitHookPath,
5102
7225
  resolveMatrixEdges: () => resolveMatrixEdges,
5103
7226
  resolveNodeTimeView: () => resolveNodeTimeView,
7227
+ resolveRealRoot: () => resolveRealRoot,
7228
+ restructureBoundaryFindings: () => restructureBoundaryFindings,
7229
+ runCheckProfessional: () => runCheckProfessional,
7230
+ runReadProof: () => runReadProof,
5104
7231
  scanArtifacts: () => scanArtifacts,
5105
7232
  traceVersion: () => traceVersion,
5106
7233
  updateVersionLock: () => updateVersionLock,
@@ -5116,6 +7243,7 @@ __export(index_exports, {
5116
7243
  validateScenarioPrdLinkIndex: () => validateScenarioPrdLinkIndex,
5117
7244
  validateScenarioPrdLinks: () => validateScenarioPrdLinks,
5118
7245
  verifyDigest: () => verifyDigest,
7246
+ verifyMechanismResult: () => verifyMechanismResult,
5119
7247
  versionLockIssueSeverity: () => versionLockIssueSeverity,
5120
7248
  writeGraphCache: () => writeGraphCache
5121
7249
  });
@@ -5161,10 +7289,10 @@ function resolveArtifactTypeName(schema, token) {
5161
7289
  return void 0;
5162
7290
  }
5163
7291
  async function loadConfig(root) {
5164
- const configPath = (0, import_node_path11.join)(root, "artifact-graph.config.yaml");
7292
+ const configPath = (0, import_node_path14.join)(root, "artifact-graph.config.yaml");
5165
7293
  let parsed = {};
5166
7294
  try {
5167
- const raw = await (0, import_promises7.readFile)(configPath, "utf-8");
7295
+ const raw = await (0, import_promises10.readFile)(configPath, "utf-8");
5168
7296
  parsed = import_js_yaml.default.load(raw) ?? {};
5169
7297
  } catch (error) {
5170
7298
  if (error.code !== "ENOENT") {
@@ -5205,8 +7333,31 @@ async function loadConfig(root) {
5205
7333
  idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
5206
7334
  e2e: mergedE2e
5207
7335
  };
7336
+ validateJsonArtifactTypes(merged.types);
5208
7337
  return merged;
5209
7338
  }
7339
+ function validateJsonArtifactTypes(types) {
7340
+ for (const [type, definition] of Object.entries(types)) {
7341
+ const raw = definition;
7342
+ const format = raw.format;
7343
+ const idField = raw.idField;
7344
+ if (format === void 0) {
7345
+ if (idField !== void 0) {
7346
+ throw new Error(`Invalid types.${type}.idField: idField requires format json.`);
7347
+ }
7348
+ continue;
7349
+ }
7350
+ if (format !== "json") {
7351
+ throw new Error(`Invalid types.${type}.format: only json is supported. Omit format to keep Markdown parsing.`);
7352
+ }
7353
+ if (SPECIALIZED_PARSER_TYPES.has(type)) {
7354
+ throw new Error(`Invalid types.${type}.format: JSON format applies only to custom types. ${type} keeps its dedicated parser.`);
7355
+ }
7356
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
7357
+ throw new Error(`Invalid types.${type}.idField: format json requires the name of one root property.`);
7358
+ }
7359
+ }
7360
+ }
5210
7361
  function validateRelationSemanticsConfig(value) {
5211
7362
  if (value === void 0) return;
5212
7363
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -5290,7 +7441,7 @@ function validateE2eConfig(e2e) {
5290
7441
  if (typeof runner.root !== "string" || !runner.root.trim()) {
5291
7442
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
5292
7443
  }
5293
- if ((0, import_node_path11.isAbsolute)(runner.root)) {
7444
+ if ((0, import_node_path14.isAbsolute)(runner.root)) {
5294
7445
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
5295
7446
  }
5296
7447
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -5353,14 +7504,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
5353
7504
  diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
5354
7505
  };
5355
7506
  }
5356
- async function scanArtifacts(root, schema) {
7507
+ async function scanArtifacts(root, schema, options = {}) {
5357
7508
  const config = schema ?? await loadConfig(root);
5358
7509
  const nodes = [];
5359
7510
  const edges = [];
5360
7511
  const scanDiagnostics = [];
5361
7512
  const scannedFiles = /* @__PURE__ */ new Map();
7513
+ const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
5362
7514
  for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
5363
- const files = await findFiles(root, definition.paths);
7515
+ const diskFiles = await findFiles(root, definition.paths);
7516
+ const files = [.../* @__PURE__ */ new Set([
7517
+ ...diskFiles.filter((file) => contentOverrides.get(file) !== null),
7518
+ ...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
7519
+ ])].sort();
5364
7520
  for (const file of files) {
5365
7521
  if (scannedFiles.has(file)) {
5366
7522
  const existingType = scannedFiles.get(file);
@@ -5374,15 +7530,15 @@ async function scanArtifacts(root, schema) {
5374
7530
  continue;
5375
7531
  }
5376
7532
  scannedFiles.set(file, type);
5377
- const raw = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, file), "utf-8");
7533
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await (0, import_promises10.readFile)((0, import_node_path14.join)(root, file), "utf-8");
5378
7534
  const parsed = parseFile(type, file, raw, config);
5379
- const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7535
+ const semantic = isJsonOriginalType(type, config) ? { edges: [], diagnostics: [] } : parseConfiguredRelations(type, file, raw, parsed.nodes, config);
5380
7536
  nodes.push(...parsed.nodes);
5381
7537
  edges.push(...parsed.edges, ...semantic.edges);
5382
7538
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
5383
7539
  }
5384
7540
  }
5385
- const absoluteRoot = (0, import_node_path11.isAbsolute)(root) ? root : (0, import_node_path11.resolve)(root);
7541
+ const absoluteRoot = (0, import_node_path14.isAbsolute)(root) ? root : (0, import_node_path14.resolve)(root);
5386
7542
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
5387
7543
  return resolveMatrixEdges(graph);
5388
7544
  }
@@ -5587,33 +7743,6 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5587
7743
  issues.push(issue("CYCLE_DETECTED", `depends_on cycle detected: ${cycle.join(" -> ")}`, "", 1, { node: cycle[0] }));
5588
7744
  }
5589
7745
  const defaultTypeKeys = new Set(Object.keys(DEFAULT_SCHEMA.types));
5590
- const specializedParserTypes = /* @__PURE__ */ new Set([
5591
- "feature",
5592
- "scenario",
5593
- "entity",
5594
- "decision",
5595
- "test",
5596
- "design",
5597
- "e2e_test",
5598
- "e2e_registry",
5599
- "rule-golden-cases",
5600
- "test-strategy",
5601
- "traceability-matrix-v2",
5602
- "traceability-version-lock",
5603
- "interface_contracts",
5604
- "data_contracts",
5605
- "application_state_machines",
5606
- "error_model",
5607
- "domain-glossary",
5608
- "bounded-context-map",
5609
- "domain-invariants",
5610
- "generation-packet-spec",
5611
- "report-contracts",
5612
- "verification-fixtures",
5613
- "ui-flow-contracts",
5614
- "non-functional-budgets",
5615
- "implementation-blueprint"
5616
- ]);
5617
7746
  const uidsWithEdges = /* @__PURE__ */ new Set();
5618
7747
  for (const edge2 of graph.edges) {
5619
7748
  uidsWithEdges.add(edge2.from);
@@ -5621,7 +7750,7 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5621
7750
  }
5622
7751
  for (const node of graph.nodes) {
5623
7752
  if (defaultTypeKeys.has(node.type)) continue;
5624
- if (specializedParserTypes.has(node.type)) continue;
7753
+ if (SPECIALIZED_PARSER_TYPES.has(node.type)) continue;
5625
7754
  if (!schema.types[node.type]) continue;
5626
7755
  if (!uidsWithEdges.has(node.uid)) {
5627
7756
  issues.push(issue(
@@ -5668,13 +7797,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
5668
7797
  const scenarioFeatureRefs = /* @__PURE__ */ new Map();
5669
7798
  const featureScenarioRefs = /* @__PURE__ */ new Map();
5670
7799
  for (const node of scenarioNodes) {
5671
- scenarioFeatureRefs.set(node.uid, relationOccurrences(node, "\u5173\u8054\u529F\u80FD", "feature"));
7800
+ scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
5672
7801
  if (!scenarioPattern.test(node.code)) {
5673
7802
  issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
5674
7803
  }
5675
7804
  }
5676
7805
  for (const node of featureNodes) {
5677
- featureScenarioRefs.set(node.uid, relationOccurrences(node, "scenarios", "scenario"));
7806
+ featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
5678
7807
  if (!featurePattern.test(node.code)) {
5679
7808
  issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
5680
7809
  }
@@ -5748,7 +7877,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5748
7877
  const indexPath = "artifacts/prd/feature-index.md";
5749
7878
  let raw = "";
5750
7879
  try {
5751
- raw = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, indexPath), "utf-8");
7880
+ raw = await (0, import_promises10.readFile)((0, import_node_path14.join)(root, indexPath), "utf-8");
5752
7881
  } catch (error) {
5753
7882
  if (error.code === "ENOENT") {
5754
7883
  return [];
@@ -5768,7 +7897,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5768
7897
  if (!feature) {
5769
7898
  return;
5770
7899
  }
5771
- const actualCount = relationOccurrences(feature, "scenarios", "scenario").length;
7900
+ const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
5772
7901
  if (actualCount !== expectedCount) {
5773
7902
  issues.push(issue(
5774
7903
  "INDEX_MISMATCH",
@@ -5996,12 +8125,12 @@ function nextId(graph, schema, type, rangeName) {
5996
8125
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
5997
8126
  }
5998
8127
  async function writeGraphCache(root, graph) {
5999
- const cacheDir = (0, import_node_path11.join)(root, ".artifact-graph");
6000
- await (0, import_promises7.mkdir)(cacheDir, { recursive: true });
6001
- await (0, import_promises7.writeFile)((0, import_node_path11.join)(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
8128
+ const cacheDir = (0, import_node_path14.join)(root, ".artifact-graph");
8129
+ await (0, import_promises10.mkdir)(cacheDir, { recursive: true });
8130
+ await (0, import_promises10.writeFile)((0, import_node_path14.join)(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
6002
8131
  `);
6003
8132
  const { default: Database } = await import("better-sqlite3");
6004
- const db = new Database((0, import_node_path11.join)(cacheDir, "graph.sqlite"));
8133
+ const db = new Database((0, import_node_path14.join)(cacheDir, "graph.sqlite"));
6005
8134
  try {
6006
8135
  db.exec(`
6007
8136
  DROP TABLE IF EXISTS nodes;
@@ -6042,7 +8171,13 @@ async function writeGraphCache(root, graph) {
6042
8171
  db.close();
6043
8172
  }
6044
8173
  }
8174
+ function isJsonOriginalType(type, schema) {
8175
+ return schema.types[type]?.format === "json" && !SPECIALIZED_PARSER_TYPES.has(type);
8176
+ }
6045
8177
  function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
8178
+ if (isJsonOriginalType(type, schema)) {
8179
+ return parseGenericJson(type, path, raw, schema);
8180
+ }
6046
8181
  if (type === "feature") {
6047
8182
  return { ...parseFeature(path, raw), diagnostics: [] };
6048
8183
  }
@@ -6111,9 +8246,187 @@ function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
6111
8246
  }
6112
8247
  return parseGenericMarkdown(type, path, raw, schema);
6113
8248
  }
8249
+ function isJsonObject(value) {
8250
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8251
+ }
8252
+ function jsonRootKind(value) {
8253
+ if (Array.isArray(value)) return "array";
8254
+ if (value === null) return "null";
8255
+ return typeof value;
8256
+ }
8257
+ function parseGenericJson(type, path, raw, schema) {
8258
+ const diagnostics = [];
8259
+ const idField = schema.types[type]?.idField;
8260
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
8261
+ diagnostics.push(issue(
8262
+ "INVALID_JSON",
8263
+ `types.${type}.idField must name one root property when format is json`,
8264
+ path,
8265
+ 1
8266
+ ));
8267
+ return { nodes: [], edges: [], diagnostics };
8268
+ }
8269
+ let parsed;
8270
+ try {
8271
+ parsed = JSON.parse(raw);
8272
+ } catch (error) {
8273
+ diagnostics.push(issue(
8274
+ "INVALID_JSON",
8275
+ `JSON artifact ${path} is not valid JSON: ${error.message}`,
8276
+ path,
8277
+ 1
8278
+ ));
8279
+ return { nodes: [], edges: [], diagnostics };
8280
+ }
8281
+ if (!isJsonObject(parsed)) {
8282
+ diagnostics.push(issue(
8283
+ "INVALID_JSON_ROOT",
8284
+ `JSON artifact ${path} must be one root object, got ${jsonRootKind(parsed)}`,
8285
+ path,
8286
+ 1
8287
+ ));
8288
+ return { nodes: [], edges: [], diagnostics };
8289
+ }
8290
+ if (!Object.prototype.hasOwnProperty.call(parsed, idField)) {
8291
+ diagnostics.push(issue(
8292
+ "ARTIFACT_ID_MISSING",
8293
+ `Artifact of type ${type} at ${path} has no root property ${idField}`,
8294
+ path,
8295
+ 1,
8296
+ { severity: "warning" }
8297
+ ));
8298
+ return { nodes: [], edges: [], diagnostics };
8299
+ }
8300
+ const idValue = parsed[idField];
8301
+ if (typeof idValue !== "string") {
8302
+ diagnostics.push(issue(
8303
+ "INVALID_ID",
8304
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8305
+ path,
8306
+ 1
8307
+ ));
8308
+ return { nodes: [], edges: [], diagnostics };
8309
+ }
8310
+ if (idValue.trim() === "") {
8311
+ diagnostics.push(issue(
8312
+ "ARTIFACT_ID_MISSING",
8313
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8314
+ path,
8315
+ 1,
8316
+ { severity: "warning" }
8317
+ ));
8318
+ return { nodes: [], edges: [], diagnostics };
8319
+ }
8320
+ const code = idValue;
8321
+ const idPattern = schema.idPatterns[type];
8322
+ if (idPattern && !new RegExp(idPattern).test(code)) {
8323
+ diagnostics.push(issue(
8324
+ "INVALID_ID",
8325
+ `Artifact ${type}:${code} field ${idField} does not match ${idPattern}`,
8326
+ path,
8327
+ 1,
8328
+ { node: toUid(type, code) }
8329
+ ));
8330
+ }
8331
+ const node = {
8332
+ type,
8333
+ code,
8334
+ title: code,
8335
+ path,
8336
+ line: 1
8337
+ };
8338
+ const relations = jsonConfiguredRelations(type, path, parsed, schema, toUid(type, code));
8339
+ diagnostics.push(...relations.diagnostics);
8340
+ return { nodes: [node], edges: relations.edges, diagnostics };
8341
+ }
8342
+ function readJsonRelation(record, field) {
8343
+ const segments = field.split(".");
8344
+ if (segments.some((segment) => segment.length === 0)) {
8345
+ return { status: "illegal-path" };
8346
+ }
8347
+ let current = record;
8348
+ for (let index = 0; index < segments.length; index += 1) {
8349
+ const key = segments[index] ?? "";
8350
+ if (!isJsonObject(current)) {
8351
+ return { status: "type-error", at: segments.slice(0, index).join(".") };
8352
+ }
8353
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
8354
+ return { status: "absent" };
8355
+ }
8356
+ const next = current[key];
8357
+ const last = index === segments.length - 1;
8358
+ if (!last && !isJsonObject(next)) {
8359
+ return { status: "type-error", at: segments.slice(0, index + 1).join(".") };
8360
+ }
8361
+ current = next;
8362
+ }
8363
+ return { status: "value", value: current };
8364
+ }
8365
+ function jsonRelationTerminal(value, field, path, sourceUid, diagnostics) {
8366
+ const message = `Relation field ${field} in ${path} must be a non-empty string or an array of non-empty strings`;
8367
+ if (typeof value === "string") {
8368
+ if (value.trim() === "") {
8369
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8370
+ return [];
8371
+ }
8372
+ return [value];
8373
+ }
8374
+ if (Array.isArray(value)) {
8375
+ const refs = [];
8376
+ for (const item of value) {
8377
+ if (typeof item !== "string" || item.trim() === "") {
8378
+ diagnostics.push(issue(
8379
+ "RELATION_VALUE_TYPE",
8380
+ `Relation field ${field} in ${path} must contain only non-empty strings`,
8381
+ path,
8382
+ 1,
8383
+ { node: sourceUid }
8384
+ ));
8385
+ continue;
8386
+ }
8387
+ refs.push(item);
8388
+ }
8389
+ return refs;
8390
+ }
8391
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8392
+ return [];
8393
+ }
8394
+ function jsonConfiguredRelations(type, path, record, schema, sourceUid) {
8395
+ const edges = [];
8396
+ const diagnostics = [];
8397
+ for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
8398
+ for (const field of spec.fields) {
8399
+ const read = readJsonRelation(record, field);
8400
+ if (read.status === "absent") continue;
8401
+ if (read.status === "illegal-path") {
8402
+ diagnostics.push(issue(
8403
+ "INVALID_RELATION_FIELD",
8404
+ `Relation field ${field} is not a fixed path of own properties`,
8405
+ path,
8406
+ 1,
8407
+ { node: sourceUid }
8408
+ ));
8409
+ continue;
8410
+ }
8411
+ if (read.status === "type-error") {
8412
+ diagnostics.push(issue(
8413
+ "RELATION_VALUE_TYPE",
8414
+ `Relation field ${field} in ${path} cannot be read at ${read.at}: expected an object`,
8415
+ path,
8416
+ 1,
8417
+ { node: sourceUid }
8418
+ ));
8419
+ continue;
8420
+ }
8421
+ const values = jsonRelationTerminal(read.value, field, path, sourceUid, diagnostics);
8422
+ appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, "json", edges, diagnostics);
8423
+ }
8424
+ }
8425
+ return { edges, diagnostics };
8426
+ }
6114
8427
  function parseGenericMarkdown(type, path, raw, schema) {
6115
8428
  const diagnostics = [];
6116
- const ext = (0, import_node_path11.extname)(path).toLowerCase();
8429
+ const ext = (0, import_node_path14.extname)(path).toLowerCase();
6117
8430
  if (ext !== ".md" && ext !== ".markdown") {
6118
8431
  diagnostics.push(issue(
6119
8432
  "UNSUPPORTED_FORMAT",
@@ -6229,38 +8542,18 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6229
8542
  const diagnostics = [];
6230
8543
  for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
6231
8544
  for (const field of spec.fields) {
6232
- for (const value of toArray(data[field])) {
6233
- const parsed = parseConfiguredRelationTarget(value, spec, schema);
6234
- if (!parsed?.code) continue;
6235
- const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
6236
- const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
6237
- if (!parsed.targetType && matchingTargetTypes.length > 1) {
6238
- diagnostics.push(issue(
6239
- "AMBIGUOUS_RELATION_TARGET",
6240
- `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
6241
- path,
6242
- 1,
6243
- { node: sourceUid }
6244
- ));
6245
- }
6246
- const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
6247
- if (targetType) {
6248
- const pattern = schema.idPatterns[targetType];
6249
- if (pattern && !new RegExp(pattern).test(parsed.code)) {
6250
- diagnostics.push(issue(
6251
- "FORMAT_ERROR",
6252
- `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
6253
- path,
6254
- 1,
6255
- { node: sourceUid }
6256
- ));
6257
- }
6258
- }
6259
- edges.push({
6260
- ...edge(sourceUid, targetUid, kind, "frontmatter", path, 1),
6261
- ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
6262
- });
6263
- }
8545
+ appendConfiguredRelationEdges(
8546
+ sourceUid,
8547
+ kind,
8548
+ field,
8549
+ toArray(data[field]),
8550
+ spec,
8551
+ schema,
8552
+ path,
8553
+ "frontmatter",
8554
+ edges,
8555
+ diagnostics
8556
+ );
6264
8557
  }
6265
8558
  }
6266
8559
  const external = getExternalEntryInfo({
@@ -6279,6 +8572,40 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6279
8572
  }
6280
8573
  return { edges, diagnostics };
6281
8574
  }
8575
+ function appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, edgeSource, edges, diagnostics) {
8576
+ for (const value of values) {
8577
+ const parsed = parseConfiguredRelationTarget(value, spec, schema);
8578
+ if (!parsed?.code) continue;
8579
+ const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
8580
+ const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
8581
+ if (!parsed.targetType && matchingTargetTypes.length > 1) {
8582
+ diagnostics.push(issue(
8583
+ "AMBIGUOUS_RELATION_TARGET",
8584
+ `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
8585
+ path,
8586
+ 1,
8587
+ { node: sourceUid }
8588
+ ));
8589
+ }
8590
+ const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
8591
+ if (targetType) {
8592
+ const pattern = schema.idPatterns[targetType];
8593
+ if (pattern && !new RegExp(pattern).test(parsed.code)) {
8594
+ diagnostics.push(issue(
8595
+ "FORMAT_ERROR",
8596
+ `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
8597
+ path,
8598
+ 1,
8599
+ { node: sourceUid }
8600
+ ));
8601
+ }
8602
+ }
8603
+ edges.push({
8604
+ ...edge(sourceUid, targetUid, kind, edgeSource, path, 1),
8605
+ ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
8606
+ });
8607
+ }
8608
+ }
6282
8609
  function parseConfiguredRelationTarget(value, spec, schema) {
6283
8610
  if (typeof value === "string" || typeof value === "number") {
6284
8611
  const raw = String(value).trim();
@@ -6363,7 +8690,7 @@ function parseFeature(path, raw) {
6363
8690
  }
6364
8691
  function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
6365
8692
  const lines = raw.split(/\r?\n/);
6366
- const codeLines = markdownCodeLineMask(lines);
8693
+ const codeLines = markdownCodeLineMask2(lines);
6367
8694
  const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
6368
8695
  const starts = [];
6369
8696
  lines.forEach((line, index) => {
@@ -6469,7 +8796,7 @@ function parseDecisions(path, raw) {
6469
8796
  }
6470
8797
  function isTestFile(filePath) {
6471
8798
  const normalized = filePath.replace(/\\/g, "/");
6472
- const name = (0, import_node_path11.basename)(normalized);
8799
+ const name = (0, import_node_path14.basename)(normalized);
6473
8800
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
6474
8801
  if (/(^|\/)(tests|test|__tests__)\//.test(normalized)) return true;
6475
8802
  if (/\w+Tests?\.java$/.test(name)) return true;
@@ -6781,41 +9108,15 @@ function parseE2eTest(path, raw) {
6781
9108
  const parsed = (0, import_gray_matter.default)(raw);
6782
9109
  const data = parsed.data;
6783
9110
  const lines = raw.split(/\r?\n/);
6784
- const starts = [];
6785
- lines.forEach((line, index) => {
6786
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
6787
- if (match) {
6788
- starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
6789
- }
6790
- });
9111
+ const starts = extractE2eTestCaseStarts(lines);
6791
9112
  const nodes = [];
6792
9113
  const edges = [];
6793
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(path, (0, import_node_path11.extname)(path))).trim();
9114
+ const batch = String(data.test_batch ?? (0, import_node_path14.basename)(path, (0, import_node_path14.extname)(path))).trim();
6794
9115
  const frontmatterScenarios = toArray(data.related_scenarios).map((value) => String(value).trim()).filter(Boolean);
6795
9116
  const scopeFeatures = extractCodes(String(data.scope ?? ""), "feature");
6796
- const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
9117
+ const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord2(data.ac_coverage)), ...scopeFeatures])];
6797
9118
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
6798
9119
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
6799
- if (starts.length === 0) {
6800
- const code = `${batch}:FILE`;
6801
- nodes.push({
6802
- type: "e2e_test",
6803
- code,
6804
- title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
6805
- path,
6806
- line: 1,
6807
- attrs: {
6808
- ...data,
6809
- testCaseId: "FILE",
6810
- fileLevelOnly: true,
6811
- tcFields: {},
6812
- blockText: raw,
6813
- coveredFeatures: [],
6814
- coveredScenarios: []
6815
- }
6816
- });
6817
- addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
6818
- }
6819
9120
  for (let index = 0; index < starts.length; index += 1) {
6820
9121
  const start = starts[index];
6821
9122
  const end = starts[index + 1]?.index ?? lines.length;
@@ -6841,6 +9142,16 @@ function parseE2eTest(path, raw) {
6841
9142
  }
6842
9143
  return { nodes, edges };
6843
9144
  }
9145
+ function extractE2eTestCaseStarts(lines) {
9146
+ const codeLines = markdownCodeLineMask2(lines);
9147
+ return lines.flatMap((line, index) => {
9148
+ if (codeLines[index]) {
9149
+ return [];
9150
+ }
9151
+ const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
9152
+ return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
9153
+ });
9154
+ }
6844
9155
  function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
6845
9156
  for (const scenario of scenarios) {
6846
9157
  edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
@@ -6863,7 +9174,7 @@ function parseE2eRegistry(path, raw) {
6863
9174
  data = { parseError: error.message };
6864
9175
  }
6865
9176
  return {
6866
- nodes: [{ type: "e2e_registry", code: (0, import_node_path11.basename)(path, (0, import_node_path11.extname)(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
9177
+ nodes: [{ type: "e2e_registry", code: (0, import_node_path14.basename)(path, (0, import_node_path14.extname)(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
6867
9178
  edges: []
6868
9179
  };
6869
9180
  }
@@ -7625,7 +9936,7 @@ function matchExplicitRelationFieldLine(line, label) {
7625
9936
  const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
7626
9937
  return match?.[1] ?? null;
7627
9938
  }
7628
- function markdownCodeLineMask(lines) {
9939
+ function markdownCodeLineMask2(lines) {
7629
9940
  const result = new Array(lines.length).fill(false);
7630
9941
  let fence;
7631
9942
  lines.forEach((line, index) => {
@@ -7670,14 +9981,14 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
7670
9981
  });
7671
9982
  return result;
7672
9983
  }
7673
- function relationOccurrences(node, field, targetType) {
7674
- const relationRecord = asRecord(node.attrs?.relationOccurrences);
9984
+ function relationOccurrences2(node, field, targetType) {
9985
+ const relationRecord = asRecord2(node.attrs?.relationOccurrences);
7675
9986
  const rawOccurrences = toArray(relationRecord[field]);
7676
9987
  return rawOccurrences.flatMap((value) => {
7677
9988
  if (typeof value === "string") {
7678
9989
  return [{ field, targetType, target: value, path: node.path, line: node.line }];
7679
9990
  }
7680
- const record = asRecord(value);
9991
+ const record = asRecord2(value);
7681
9992
  const target = String(record.target ?? "").trim();
7682
9993
  if (!target) {
7683
9994
  return [];
@@ -7784,7 +10095,7 @@ function validateE2eTests(graph) {
7784
10095
  issues.push(issue("E2E_REQUIRED_FRONTMATTER", `${node.uid} missing required frontmatter ${field}`, node.path, 1, { node: node.uid, severity: "warning" }));
7785
10096
  }
7786
10097
  }
7787
- const fields = asRecord(attrs.tcFields);
10098
+ const fields = asRecord2(attrs.tcFields);
7788
10099
  const requiredTcFields = [
7789
10100
  ["\u6807\u9898", node.title],
7790
10101
  ["\u524D\u7F6E\u6761\u4EF6", fields["\u524D\u7F6E\u6761\u4EF6"]],
@@ -7834,7 +10145,7 @@ function validateE2eTests(graph) {
7834
10145
  }
7835
10146
  for (const [path, nodes] of nodesByPath) {
7836
10147
  const first = nodes[0];
7837
- const declared = flattenAcCoverage(asRecord(first.attrs?.ac_coverage));
10148
+ const declared = flattenAcCoverage(asRecord2(first.attrs?.ac_coverage));
7838
10149
  const covered = new Set(nodes.flatMap((node) => toArray(node.attrs?.coveredFeatures).map((value) => {
7839
10150
  const ref = value;
7840
10151
  return `${String(ref.feature)}:${String(ref.ac)}`;
@@ -7869,13 +10180,16 @@ function validateE2eRegistry(graph) {
7869
10180
  }
7870
10181
  const actualNodes = byPath.get(file) ?? [];
7871
10182
  if (actualNodes.length === 0) {
10183
+ if (Number(batch.test_case_count ?? NaN) === 0) {
10184
+ continue;
10185
+ }
7872
10186
  issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? file)} file ${file || "<missing>"} does not match any E2E test file`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
7873
10187
  continue;
7874
10188
  }
7875
10189
  const first = actualNodes[0];
7876
10190
  compareRegistryValue(issues, registry, batch, "batch_id", first.attrs?.test_batch);
7877
10191
  compareRegistryValue(issues, registry, batch, "scope", first.attrs?.scope);
7878
- compareRegistryAcCoverage(issues, registry, batch, asRecord(first.attrs?.ac_coverage));
10192
+ compareRegistryAcCoverage(issues, registry, batch, asRecord2(first.attrs?.ac_coverage));
7879
10193
  compareRegistryArray(issues, registry, batch, "related_scenarios", toArray(first.attrs?.related_scenarios).map((value) => String(value)));
7880
10194
  compareRegistryValue(issues, registry, batch, "test_case_count", actualNodes.filter((node) => node.attrs?.fileLevelOnly !== true).length);
7881
10195
  }
@@ -7889,31 +10203,21 @@ function validateE2eRegistry(graph) {
7889
10203
  async function validateExecutableTraceability(root, config) {
7890
10204
  const issues = [];
7891
10205
  const schema = config ?? await loadConfig(root);
7892
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
7893
- let e2eFiles;
7894
- try {
7895
- e2eFiles = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => (0, import_node_path11.join)(e2eDir, name));
7896
- } catch {
10206
+ const e2eFiles = await findConfiguredE2eFiles(root, schema);
10207
+ if (e2eFiles.length === 0) {
7897
10208
  return [];
7898
10209
  }
7899
10210
  const mdToRef = /* @__PURE__ */ new Map();
7900
10211
  const allMdTcInfo = /* @__PURE__ */ new Map();
7901
10212
  const tcKeyToFields = /* @__PURE__ */ new Map();
7902
10213
  const mdBatches = /* @__PURE__ */ new Set();
7903
- for (const filePath of e2eFiles) {
7904
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
7905
- const relPath = (0, import_node_path11.relative)(root, filePath).split("\\").join("/");
10214
+ for (const relPath of e2eFiles) {
10215
+ const raw = await (0, import_promises10.readFile)((0, import_node_path14.join)(root, relPath), "utf-8");
7906
10216
  const parsed = (0, import_gray_matter.default)(raw);
7907
10217
  const data = parsed.data;
7908
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(filePath, (0, import_node_path11.extname)(filePath))).trim();
10218
+ const batch = String(data.test_batch ?? (0, import_node_path14.basename)(relPath, (0, import_node_path14.extname)(relPath))).trim();
7909
10219
  const lines = raw.split(/\r?\n/);
7910
- const tcStarts = [];
7911
- lines.forEach((line, index) => {
7912
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
7913
- if (match) {
7914
- tcStarts.push({ id: match[1], line: index + 1, index });
7915
- }
7916
- });
10220
+ const tcStarts = extractE2eTestCaseStarts(lines);
7917
10221
  for (let i = 0; i < tcStarts.length; i += 1) {
7918
10222
  const start = tcStarts[i];
7919
10223
  const end = tcStarts[i + 1]?.index ?? lines.length;
@@ -7950,10 +10254,10 @@ async function validateExecutableTraceability(root, config) {
7950
10254
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
7951
10255
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
7952
10256
  for (const specFile of specFiles) {
7953
- const fullSpecPath = (0, import_node_path11.join)(root, specFile);
10257
+ const fullSpecPath = (0, import_node_path14.join)(root, specFile);
7954
10258
  let content;
7955
10259
  try {
7956
- content = await (0, import_promises7.readFile)(fullSpecPath, "utf-8");
10260
+ content = await (0, import_promises10.readFile)(fullSpecPath, "utf-8");
7957
10261
  } catch {
7958
10262
  continue;
7959
10263
  }
@@ -8032,7 +10336,7 @@ async function validateExecutableTraceability(root, config) {
8032
10336
  if (entry.testId) {
8033
10337
  let content;
8034
10338
  try {
8035
- content = await (0, import_promises7.readFile)((0, import_node_path11.join)(root, normalizedRefFile), "utf-8");
10339
+ content = await (0, import_promises10.readFile)((0, import_node_path14.join)(root, normalizedRefFile), "utf-8");
8036
10340
  } catch {
8037
10341
  continue;
8038
10342
  }
@@ -8060,7 +10364,7 @@ async function validateExecutableTraceability(root, config) {
8060
10364
  }
8061
10365
  continue;
8062
10366
  }
8063
- if (!mdToRef.has(tcKey) && !await hasMarkdownTc(tcKey, e2eDir)) {
10367
+ if (!allMdTcInfo.has(tcKey)) {
8064
10368
  for (const ann of annotations) {
8065
10369
  issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
8066
10370
  }
@@ -8209,37 +10513,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8209
10513
  let withExecutableRef = 0;
8210
10514
  const statusBreakdown = {};
8211
10515
  const chainTypeBreakdown = {};
8212
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
8213
- const tcFieldsMap = /* @__PURE__ */ new Map();
8214
- let e2eFiles;
8215
- try {
8216
- e2eFiles = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => (0, import_node_path11.join)(e2eDir, name));
8217
- } catch {
8218
- e2eFiles = [];
8219
- }
8220
- for (const filePath of e2eFiles) {
8221
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
8222
- const lines = raw.split(/\r?\n/);
8223
- const tcStarts = [];
8224
- lines.forEach((line, index) => {
8225
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8226
- if (match) {
8227
- tcStarts.push({ id: match[1], index });
8228
- }
8229
- });
8230
- const parsed = (0, import_gray_matter.default)(raw);
8231
- const batch = String(parsed.data.test_batch ?? (0, import_node_path11.basename)(filePath, (0, import_node_path11.extname)(filePath))).trim();
8232
- for (let i = 0; i < tcStarts.length; i++) {
8233
- const start = tcStarts[i];
8234
- const end = tcStarts[i + 1]?.index ?? lines.length;
8235
- const block = lines.slice(start.index, end);
8236
- const fields = extractE2eTcFields(block);
8237
- tcFieldsMap.set(`${batch}:${start.id}`, fields);
8238
- }
8239
- }
10516
+ const tcFieldsMap = new Map(e2eNodes.map((node) => [
10517
+ node.code,
10518
+ asRecord2(node.attrs?.tcFields)
10519
+ ]));
8240
10520
  for (const node of e2eNodes) {
8241
10521
  const tcKey = node.code;
8242
- const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
10522
+ const fields = tcFieldsMap.get(tcKey) ?? asRecord2(node.attrs?.tcFields);
8243
10523
  const execRef = String(fields["executable_ref"] ?? "").trim();
8244
10524
  if (execRef && !isPendingExecutableRef(execRef)) {
8245
10525
  withExecutableRef++;
@@ -8269,8 +10549,8 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8269
10549
  }
8270
10550
  }
8271
10551
  for (const node of e2eNodes) {
8272
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8273
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10552
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10553
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8274
10554
  for (const feature of Object.keys(acCoverage)) {
8275
10555
  acCoveredFeatures.add(feature);
8276
10556
  }
@@ -8282,7 +10562,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8282
10562
  const runners = (await loadConfig(root)).e2e?.runners ?? [];
8283
10563
  const allProjectFiles = await walkFiles(root);
8284
10564
  for (const node of e2eNodes) {
8285
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
10565
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
8286
10566
  const status = String(fields["status"] ?? "").trim().toLowerCase();
8287
10567
  const execRef = String(fields["executable_ref"] ?? "").trim();
8288
10568
  if (status !== "verified") continue;
@@ -8291,7 +10571,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8291
10571
  let hasActiveE2eRef = false;
8292
10572
  for (const entry of parseExecutableRefLines(execRef)) {
8293
10573
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
8294
- if (!normalized || !(0, import_node_fs5.existsSync)((0, import_node_path11.join)(root, normalized))) continue;
10574
+ if (!normalized || !(0, import_node_fs5.existsSync)((0, import_node_path14.join)(root, normalized))) continue;
8295
10575
  const accepting = await getAcceptingRunners(root, normalized, runners);
8296
10576
  if (accepting.some((runner) => runner.kind === "e2e")) {
8297
10577
  hasActiveE2eRef = true;
@@ -8303,7 +10583,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8303
10583
  for (const scenario of relatedScenarios) {
8304
10584
  verifiedScenarios.add(scenario);
8305
10585
  }
8306
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10586
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8307
10587
  for (const feature of Object.keys(acCoverage)) {
8308
10588
  verifiedFeatures.add(feature);
8309
10589
  }
@@ -8350,13 +10630,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8350
10630
  const acCoverageRateByFeature = {};
8351
10631
  const featureAcMap = /* @__PURE__ */ new Map();
8352
10632
  for (const node of featureNodes) {
8353
- const acs = parseAcceptanceCriteria(await (0, import_promises7.readFile)((0, import_node_path11.join)(root, node.path), "utf-8"));
10633
+ const acs = parseAcceptanceCriteria(await (0, import_promises10.readFile)((0, import_node_path14.join)(root, node.path), "utf-8"));
8354
10634
  featureAcMap.set(node.code, new Set(acs));
8355
10635
  }
8356
10636
  const coveredAcByFeature = /* @__PURE__ */ new Map();
8357
10637
  for (const node of e2eNodes) {
8358
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8359
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10638
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10639
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8360
10640
  for (const [feature, acs] of Object.entries(acCoverage)) {
8361
10641
  const existing = coveredAcByFeature.get(feature) ?? /* @__PURE__ */ new Set();
8362
10642
  for (const ac of toArray(acs)) {
@@ -8392,39 +10672,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8392
10672
  };
8393
10673
  }
8394
10674
  async function generateE2eRegistry(root, opts) {
8395
- const e2eDir = (0, import_node_path11.join)(root, "artifacts", "tests", "e2e");
8396
- let files;
8397
- try {
8398
- files = (await (0, import_promises7.readdir)(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
8399
- } catch {
8400
- return {
8401
- registry_version: "1.0",
8402
- generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8403
- total_batches: 0,
8404
- total_test_cases: 0,
8405
- batches: []
8406
- };
8407
- }
10675
+ const schema = await loadConfig(root);
10676
+ const files = await findConfiguredE2eFiles(root, schema);
8408
10677
  const batches = [];
10678
+ const batchIds = /* @__PURE__ */ new Set();
8409
10679
  let totalTestCases = 0;
8410
10680
  for (const file of files) {
8411
- const filePath = (0, import_node_path11.join)(e2eDir, file);
8412
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
10681
+ const filePath = (0, import_node_path14.join)(root, file);
10682
+ const raw = await (0, import_promises10.readFile)(filePath, "utf-8");
8413
10683
  const parsed = (0, import_gray_matter.default)(raw);
8414
10684
  const data = parsed.data;
8415
- const batch = String(data.test_batch ?? (0, import_node_path11.basename)(file, (0, import_node_path11.extname)(file))).trim();
8416
- const relPath = `artifacts/tests/e2e/${file}`;
10685
+ const batch = String(data.test_batch ?? (0, import_node_path14.basename)(file, (0, import_node_path14.extname)(file))).trim();
10686
+ const relPath = file;
8417
10687
  const scope = String(data.scope ?? "").trim();
8418
10688
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
8419
10689
  const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
8420
10690
  const lines = raw.split(/\r?\n/);
8421
- const tcStarts = [];
8422
- lines.forEach((line, index) => {
8423
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8424
- if (match) {
8425
- tcStarts.push({ id: match[1], index });
8426
- }
8427
- });
10691
+ const tcStarts = extractE2eTestCaseStarts(lines);
10692
+ if (tcStarts.length > 0) {
10693
+ batchIds.add(batch);
10694
+ }
8428
10695
  const statusSummary = {};
8429
10696
  const blockingReasons = {};
8430
10697
  const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
@@ -8433,8 +10700,9 @@ async function generateE2eRegistry(root, opts) {
8433
10700
  blockingReasons[tc.id] = frontmatterFixesBlock;
8434
10701
  }
8435
10702
  }
8436
- for (const start of tcStarts) {
8437
- const end = tcStarts[tcStarts.indexOf(start) + 1]?.index ?? lines.length;
10703
+ for (let index = 0; index < tcStarts.length; index += 1) {
10704
+ const start = tcStarts[index];
10705
+ const end = tcStarts[index + 1]?.index ?? lines.length;
8438
10706
  const block = lines.slice(start.index, end);
8439
10707
  const fields = extractE2eTcFields(block);
8440
10708
  const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
@@ -8467,7 +10735,7 @@ async function generateE2eRegistry(root, opts) {
8467
10735
  return {
8468
10736
  registry_version: "1.0",
8469
10737
  generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8470
- total_batches: batches.length,
10738
+ total_batches: batchIds.size,
8471
10739
  total_test_cases: totalTestCases,
8472
10740
  batches
8473
10741
  };
@@ -8536,10 +10804,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
8536
10804
  if (!normalizedPath) {
8537
10805
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8538
10806
  }
8539
- const fullPath = (0, import_node_path11.join)(root, normalizedPath);
10807
+ const fullPath = (0, import_node_path14.join)(root, normalizedPath);
8540
10808
  let content;
8541
10809
  try {
8542
- content = await (0, import_promises7.readFile)(fullPath, "utf-8");
10810
+ content = await (0, import_promises10.readFile)(fullPath, "utf-8");
8543
10811
  } catch {
8544
10812
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8545
10813
  }
@@ -8573,7 +10841,7 @@ function detectTestLevel(specFile, content) {
8573
10841
  }
8574
10842
  function resolveExecutableRefFile(refFile, allFiles) {
8575
10843
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
8576
- if (!normalized || (0, import_node_path11.isAbsolute)(refFile) || normalized.split("/").includes("..")) {
10844
+ if (!normalized || (0, import_node_path14.isAbsolute)(refFile) || normalized.split("/").includes("..")) {
8577
10845
  return void 0;
8578
10846
  }
8579
10847
  if (allFiles.includes(normalized)) {
@@ -8646,17 +10914,6 @@ function splitMarkdownCells(line) {
8646
10914
  function escapeRegExp(value) {
8647
10915
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8648
10916
  }
8649
- async function hasMarkdownTc(tcKey, e2eDir) {
8650
- const [batch, tcId] = tcKey.split(":");
8651
- const filePath = (0, import_node_path11.join)(e2eDir, `${batch}.md`);
8652
- try {
8653
- const raw = await (0, import_promises7.readFile)(filePath, "utf-8");
8654
- const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
8655
- return tcRegex.test(raw);
8656
- } catch {
8657
- return false;
8658
- }
8659
- }
8660
10917
  async function findFiles(root, patterns) {
8661
10918
  const all = await walkFiles(root);
8662
10919
  const matched = /* @__PURE__ */ new Set();
@@ -8669,6 +10926,10 @@ async function findFiles(root, patterns) {
8669
10926
  }
8670
10927
  return [...matched].sort();
8671
10928
  }
10929
+ async function findConfiguredE2eFiles(root, schema) {
10930
+ const patterns = schema.types.e2e_test?.paths ?? [];
10931
+ return findFiles(root, patterns);
10932
+ }
8672
10933
  function matchesConfiguredArtifactPath(path, schema) {
8673
10934
  const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
8674
10935
  return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
@@ -8697,8 +10958,13 @@ function extractCodes(text, type, schema) {
8697
10958
  }
8698
10959
  function extractE2eTcFields(block) {
8699
10960
  const fields = {};
10961
+ const codeLines = markdownCodeLineMask2(block);
8700
10962
  let current = "";
8701
- for (const line of block) {
10963
+ for (let index = 0; index < block.length; index += 1) {
10964
+ if (codeLines[index]) {
10965
+ continue;
10966
+ }
10967
+ const line = block[index];
8702
10968
  const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
8703
10969
  if (match) {
8704
10970
  current = match[1].trim();
@@ -8750,7 +11016,7 @@ function flattenAcCoverage(value) {
8750
11016
  return Object.entries(value).flatMap(([feature, refs]) => toArray(refs).map((ac) => ({ feature, ac: String(ac).replace(/^AC[-\s]?(\d+)$/i, (_match, digits) => `AC${Number(digits)}`) })));
8751
11017
  }
8752
11018
  function needsDesktopChainWarning(node) {
8753
- const tcFields = asRecord(node.attrs?.tcFields);
11019
+ const tcFields = asRecord2(node.attrs?.tcFields);
8754
11020
  const chainType = String(tcFields["chain_type"] ?? "").trim().toLowerCase();
8755
11021
  if (chainType && VALID_CHAIN_TYPES.has(chainType) && chainType !== "desktop_chain" || chainType in DEPRECATED_CHAIN_TYPE_ALIASES) {
8756
11022
  return false;
@@ -8807,7 +11073,7 @@ function compareRegistryAcCoverage(issues, registry, batch, actual) {
8807
11073
  issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? "")} ac_coverage cannot be determined`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
8808
11074
  return;
8809
11075
  }
8810
- if (normalizeAcCoverage(asRecord(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
11076
+ if (normalizeAcCoverage(asRecord2(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
8811
11077
  issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? "")} ac_coverage does not match actual file`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
8812
11078
  }
8813
11079
  }
@@ -8822,7 +11088,7 @@ function groupBy(values, key) {
8822
11088
  }
8823
11089
  return result;
8824
11090
  }
8825
- function asRecord(value) {
11091
+ function asRecord2(value) {
8826
11092
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
8827
11093
  }
8828
11094
  function isEmptyValue(value) {
@@ -8881,7 +11147,7 @@ function normalizeDesignCode(value) {
8881
11147
  if (!raw) {
8882
11148
  return "";
8883
11149
  }
8884
- return (0, import_node_path11.basename)(raw, (0, import_node_path11.extname)(raw));
11150
+ return (0, import_node_path14.basename)(raw, (0, import_node_path14.extname)(raw));
8885
11151
  }
8886
11152
  function toUid(type, code) {
8887
11153
  return `${type}:${code}`;
@@ -9157,14 +11423,14 @@ function resolveArtifactContext(graph, opts) {
9157
11423
  }
9158
11424
  if (root) {
9159
11425
  for (const ap of ALWAYS_PRESENT_ITEMS) {
9160
- const fullPath = (0, import_node_path11.join)(root, ap.path);
9161
- let stat;
11426
+ const fullPath = (0, import_node_path14.join)(root, ap.path);
11427
+ let stat2;
9162
11428
  try {
9163
- stat = (0, import_node_fs5.statSync)(fullPath);
11429
+ stat2 = (0, import_node_fs5.statSync)(fullPath);
9164
11430
  } catch {
9165
- stat = null;
11431
+ stat2 = null;
9166
11432
  }
9167
- if (!stat) {
11433
+ if (!stat2) {
9168
11434
  const msg = `Required baseline artifact not found: ${ap.path}`;
9169
11435
  if (!missing.includes(msg)) {
9170
11436
  missing.push(msg);
@@ -9176,7 +11442,7 @@ function resolveArtifactContext(graph, opts) {
9176
11442
  suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
9177
11443
  });
9178
11444
  }
9179
- } else if (!stat.isFile()) {
11445
+ } else if (!stat2.isFile()) {
9180
11446
  const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
9181
11447
  if (!missing.includes(msg)) {
9182
11448
  missing.push(msg);
@@ -9399,14 +11665,14 @@ function formatContextMarkdown(manifest) {
9399
11665
  }
9400
11666
  return lines.join("\n");
9401
11667
  }
9402
- var import_gray_matter, import_js_yaml, import_node_fs5, import_promises7, import_node_path11, TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
11668
+ var import_gray_matter, import_js_yaml, import_node_fs5, import_promises10, import_node_path14, TARGET_ARTIFACT_TYPES, NON_TARGET_ROLES, DEFAULT_SCHEMA, SPECIALIZED_PARSER_TYPES, EMPTY_RELATION_FIELD_VALUES, VALID_TC_STATUSES, VALID_CHAIN_TYPES, DEPRECATED_CHAIN_TYPE_ALIASES, CONTEXT_CATEGORIES, TIER_ORDER;
9403
11669
  var init_index = __esm({
9404
11670
  "src/index.ts"() {
9405
11671
  import_gray_matter = __toESM(require("gray-matter"), 1);
9406
11672
  import_js_yaml = __toESM(require("js-yaml"), 1);
9407
11673
  import_node_fs5 = require("fs");
9408
- import_promises7 = require("fs/promises");
9409
- import_node_path11 = require("path");
11674
+ import_promises10 = require("fs/promises");
11675
+ import_node_path14 = require("path");
9410
11676
  init_packet_constants();
9411
11677
  init_packet_validator();
9412
11678
  init_glob_matcher();
@@ -9425,8 +11691,12 @@ var init_index = __esm({
9425
11691
  init_git_changes();
9426
11692
  init_git_hook_path();
9427
11693
  init_hook_installer();
11694
+ init_professional_conclusion();
9428
11695
  init_review_result_validator();
9429
11696
  init_contract_kernel();
11697
+ init_restructure();
11698
+ init_restructure_file_set();
11699
+ init_restructure_software();
9430
11700
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
9431
11701
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
9432
11702
  DEFAULT_SCHEMA = {
@@ -9474,6 +11744,33 @@ var init_index = __esm({
9474
11744
  runners: []
9475
11745
  }
9476
11746
  };
11747
+ SPECIALIZED_PARSER_TYPES = /* @__PURE__ */ new Set([
11748
+ "feature",
11749
+ "scenario",
11750
+ "entity",
11751
+ "decision",
11752
+ "test",
11753
+ "design",
11754
+ "e2e_test",
11755
+ "e2e_registry",
11756
+ "rule-golden-cases",
11757
+ "test-strategy",
11758
+ "traceability-matrix-v2",
11759
+ "traceability-version-lock",
11760
+ "interface_contracts",
11761
+ "data_contracts",
11762
+ "application_state_machines",
11763
+ "error_model",
11764
+ "domain-glossary",
11765
+ "bounded-context-map",
11766
+ "domain-invariants",
11767
+ "generation-packet-spec",
11768
+ "report-contracts",
11769
+ "verification-fixtures",
11770
+ "ui-flow-contracts",
11771
+ "non-functional-budgets",
11772
+ "implementation-blueprint"
11773
+ ]);
9477
11774
  EMPTY_RELATION_FIELD_VALUES = /* @__PURE__ */ new Set(["\u65E0", "none", "n/a", "-"]);
9478
11775
  VALID_TC_STATUSES = /* @__PURE__ */ new Set(["created", "automated", "verified", "waived"]);
9479
11776
  VALID_CHAIN_TYPES = /* @__PURE__ */ new Set([
@@ -9522,6 +11819,7 @@ init_index();
9522
11819
  BASELINE_CONSTRAINTS,
9523
11820
  BASELINE_CONSTRAINTS_COUNT,
9524
11821
  BASELINE_ITEMS_COUNT,
11822
+ CONTRACTS_PACKAGE_NAME,
9525
11823
  CONTRACT_ERROR_CODES,
9526
11824
  ContractCatalog,
9527
11825
  ContractError,
@@ -9529,35 +11827,62 @@ init_index();
9529
11827
  DEFAULT_MAX_CHARS,
9530
11828
  DEFAULT_SCHEMA,
9531
11829
  E2E_NORMALIZER_CONFIG,
11830
+ FILE_SET_RESULT_OBJECT,
11831
+ FOUNDATION_PACKAGE_NAME,
11832
+ GRAPH_DOMAIN_CODES,
11833
+ GRAPH_PROVIDER_ENTRY,
11834
+ GRAPH_PROVIDER_ID,
9532
11835
  MIN_PROMPT_CHARS,
11836
+ PROFESSIONAL_CONCLUSION_OBJECT,
11837
+ RESTRUCTURE_MAX_OPERATIONS,
11838
+ RESTRUCTURE_MAX_TOTAL_BYTES,
11839
+ RESTRUCTURE_PLAN_SCHEMA_VERSION,
11840
+ RESTRUCTURE_QUALIFIED_ARCH,
11841
+ RESTRUCTURE_QUALIFIED_FILESYSTEM,
11842
+ RESTRUCTURE_QUALIFIED_PLATFORM,
11843
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
11844
+ RESTRUCTURE_RECOVERY_REL_PATH,
11845
+ RESTRUCTURE_RECOVERY_ROOT_MODE,
11846
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS,
9533
11847
  TARGET_ARTIFACT_TYPES,
9534
11848
  VALID_PACKET_TARGET_TYPES,
9535
11849
  VERSION_INDEX_SCHEMA_VERSION,
9536
11850
  VERSION_LOCK_PATH,
9537
11851
  VERSION_LOCK_SCHEMA_VERSION,
9538
11852
  applyPreparedManagedHookBlocks,
11853
+ applyRestructure,
11854
+ applyRestructureFileSet,
9539
11855
  assemblePacket,
9540
11856
  auditPackets,
9541
11857
  auditVersionLock,
9542
11858
  bootstrapVersionLock,
11859
+ buildFileSetApplyRequest,
9543
11860
  buildGraph,
9544
11861
  buildVersionIndex,
11862
+ candidateByteDigest,
9545
11863
  collectChangedPaths,
9546
11864
  computeCoverageBoundary,
9547
11865
  computeE2eCoverageStats,
9548
11866
  computeImpact,
9549
11867
  computeRevisionDigest,
11868
+ createModeForUmask,
11869
+ createRestructureRootBinding,
11870
+ createRestructureValidationCallback,
11871
+ digestRestructureValue,
9550
11872
  dirname,
9551
11873
  discoverAndAuditPackets,
9552
11874
  discoverTargets,
9553
11875
  doctorArtifactChain,
11876
+ ensureRestructureMechanismRoot,
9554
11877
  extname,
9555
11878
  filterGraphByView,
9556
11879
  formatContextMarkdown,
11880
+ gateRestructureOperationPlan,
9557
11881
  generateE2eRegistry,
9558
11882
  getArtifactTypeMetadata,
9559
11883
  getExternalEntryInfo,
9560
11884
  getTargetArtifactTypes,
11885
+ inspectRestructure,
9561
11886
  installManagedHookBlock,
9562
11887
  isOfficialNamespace,
9563
11888
  isPacketTargetType,
@@ -9568,14 +11893,26 @@ init_index();
9568
11893
  loadContract,
9569
11894
  loadContractCatalog,
9570
11895
  loadContractsFromDirectory,
11896
+ loadFoundationModule,
11897
+ locateSoftwareRecord,
11898
+ markdownRecordHeadings,
9571
11899
  matchesConfiguredArtifactPath,
9572
11900
  nextId,
9573
11901
  normalizeE2eLegacyArtifact,
9574
11902
  normalizeToCanonical,
11903
+ observeRestructureJournal,
9575
11904
  parseTargetSelector,
9576
11905
  parseTargetsFile,
11906
+ planRestructure,
11907
+ planningUmask,
9577
11908
  prepareManagedHookBlock,
11909
+ projectRestructureFileSetResult,
11910
+ pruneRestructureFileSet,
11911
+ pruneRestructureRecovery,
11912
+ qualifyRestructureMechanism,
9578
11913
  queryGraph,
11914
+ recoverRestructure,
11915
+ recoverRestructureFileSet,
9579
11916
  refreshVersionLock,
9580
11917
  renderCoverageBoundaryMarkdown,
9581
11918
  renderDoctorMarkdown,
@@ -9586,6 +11923,7 @@ init_index();
9586
11923
  renderTraceVersionMarkdown,
9587
11924
  renderVersionLockAuditMarkdown,
9588
11925
  renderVersionLockRefreshMarkdown,
11926
+ replaceSoftwareHeader,
9589
11927
  resolveArtifactContext,
9590
11928
  resolveArtifactGraphCli,
9591
11929
  resolveArtifactTypeName,
@@ -9593,6 +11931,10 @@ init_index();
9593
11931
  resolveGitHookPath,
9594
11932
  resolveMatrixEdges,
9595
11933
  resolveNodeTimeView,
11934
+ resolveRealRoot,
11935
+ restructureBoundaryFindings,
11936
+ runCheckProfessional,
11937
+ runReadProof,
9596
11938
  scanArtifacts,
9597
11939
  traceVersion,
9598
11940
  updateVersionLock,
@@ -9608,6 +11950,7 @@ init_index();
9608
11950
  validateScenarioPrdLinkIndex,
9609
11951
  validateScenarioPrdLinks,
9610
11952
  verifyDigest,
11953
+ verifyMechanismResult,
9611
11954
  versionLockIssueSeverity,
9612
11955
  writeGraphCache
9613
11956
  });