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.js CHANGED
@@ -963,9 +963,13 @@ async function bootstrapVersionLock(root, options = {}) {
963
963
  async function refreshVersionLock(root, options = {}) {
964
964
  const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
965
965
  const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
966
+ const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
966
967
  const all = options.all === true || options.changedOnly !== true;
967
968
  const mode = all ? "all" : "changed-only";
968
969
  const warnings = [];
970
+ if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
971
+ throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
972
+ }
969
973
  if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
970
974
  throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
971
975
  }
@@ -975,9 +979,16 @@ async function refreshVersionLock(root, options = {}) {
975
979
  const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
976
980
  const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
977
981
  const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
982
+ const currentArtifactRelationEdgeList = artifactRelationEdges(index);
978
983
  const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
979
984
  const currentEntries = /* @__PURE__ */ new Map();
980
985
  const changedPathSet = new Set(changedPaths);
986
+ validatePreciseOrphanRemoval(
987
+ removeOrphanEdges,
988
+ lock,
989
+ new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
990
+ new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
991
+ );
981
992
  const affectedEdges = /* @__PURE__ */ new Set();
982
993
  const addedLocks = [];
983
994
  const updatedLocks = [];
@@ -1004,12 +1015,13 @@ async function refreshVersionLock(root, options = {}) {
1004
1015
  }
1005
1016
  for (const existing of lock.locks) {
1006
1017
  const current = currentEntries.get(existing.edgeId);
1007
- const affected = all || lockEntryTouchesAnyPath(existing, changedPathSet);
1018
+ const removePrecisely = removeOrphanEdges.has(existing.edgeId);
1019
+ const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
1008
1020
  if (affected) {
1009
1021
  affectedEdges.add(existing.edgeId);
1010
1022
  }
1011
1023
  if (!current) {
1012
- if (affected && options.removeOrphans === true) {
1024
+ if (removePrecisely || affected && options.removeOrphans === true) {
1013
1025
  removedOrphans.push(existing.edgeId);
1014
1026
  } else {
1015
1027
  if (affected) {
@@ -1044,7 +1056,6 @@ async function refreshVersionLock(root, options = {}) {
1044
1056
  if (mode === "changed-only" && changedPaths.length === 0) {
1045
1057
  warnings.push("No changed paths were provided; no locks were refreshed.");
1046
1058
  }
1047
- const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1048
1059
  const existingArtifactRelationLocks = lock.artifactRelations ?? [];
1049
1060
  const addedArtifactRelationLocks = [];
1050
1061
  const updatedArtifactRelationLocks = [];
@@ -1088,10 +1099,11 @@ async function refreshVersionLock(root, options = {}) {
1088
1099
  if (processedRelationEdgeIds.has(relEdgeId)) {
1089
1100
  continue;
1090
1101
  }
1091
- const affected = all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1102
+ const removePrecisely = removeOrphanEdges.has(relEdgeId);
1103
+ const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1092
1104
  if (affected) {
1093
1105
  affectedEdges.add(relEdgeId);
1094
- if (options.removeOrphans === true) {
1106
+ if (removePrecisely || options.removeOrphans === true) {
1095
1107
  removedArtifactRelationLocks.push(relEdgeId);
1096
1108
  } else {
1097
1109
  retainedArtifactRelationOrphans.push(relEdgeId);
@@ -1127,6 +1139,20 @@ async function refreshVersionLock(root, options = {}) {
1127
1139
  warnings
1128
1140
  };
1129
1141
  }
1142
+ function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
1143
+ for (const edgeId of requestedEdgeIds) {
1144
+ const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
1145
+ if (matches === 0) {
1146
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
1147
+ }
1148
+ if (matches !== 1) {
1149
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
1150
+ }
1151
+ if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
1152
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
1153
+ }
1154
+ }
1155
+ }
1130
1156
  async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
1131
1157
  const index = await buildVersionIndex(root);
1132
1158
  const safeLockPath = normalizeRelativePath(root, lockPath);
@@ -3101,16 +3127,16 @@ function probeNativeBinding(context = {}) {
3101
3127
  }
3102
3128
  return { ok: true };
3103
3129
  }
3104
- function buildNativeBindingDiagnostic(failure, probeContext) {
3130
+ function buildNativeBindingDiagnostic(failure2, probeContext) {
3105
3131
  return {
3106
3132
  selectedCli: probeContext.selectedCli,
3107
3133
  runtime: `${process.execPath} (v${process.versions.node})`,
3108
- abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure.detail)}`,
3134
+ abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
3109
3135
  installSource: probeContext.installSource,
3110
3136
  probedFrom: probeContext.probedFrom,
3111
- failedStage: failure.failedStage,
3112
- cause: failure.cause,
3113
- suggestion: failure.suggestion
3137
+ failedStage: failure2.failedStage,
3138
+ cause: failure2.cause,
3139
+ suggestion: failure2.suggestion
3114
3140
  };
3115
3141
  }
3116
3142
  function buildNativeBindingSuccessDiagnostic(probeContext) {
@@ -3231,7 +3257,7 @@ async function doctorArtifactChain(root, options = {}) {
3231
3257
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3232
3258
  const warnings = [
3233
3259
  ...cli.warnings,
3234
- ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy >=22.0.0.`],
3260
+ ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3235
3261
  ...probe.ok ? [] : [
3236
3262
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3237
3263
  ]
@@ -3243,7 +3269,7 @@ async function doctorArtifactChain(root, options = {}) {
3243
3269
  node: {
3244
3270
  version: process.versions.node,
3245
3271
  compatible: nodeCompatible,
3246
- required: ">=22.0.0"
3272
+ required: REQUIRED_NODE_VERSION
3247
3273
  },
3248
3274
  config: {
3249
3275
  path: configPath,
@@ -3347,8 +3373,10 @@ function resolveCandidatePath(root, candidatePath) {
3347
3373
  return isAbsolute2(candidatePath) ? candidatePath : resolve3(root, candidatePath);
3348
3374
  }
3349
3375
  function isNodeCompatible(version) {
3350
- const major = Number(version.split(".")[0]);
3351
- return Number.isFinite(major) && major >= 22;
3376
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
3377
+ if (!match) return false;
3378
+ const [, major, minor, patch] = match.map(Number);
3379
+ return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
3352
3380
  }
3353
3381
  async function detectPnpmVersion() {
3354
3382
  try {
@@ -3409,13 +3437,14 @@ function safeRealpath(path) {
3409
3437
  return path;
3410
3438
  }
3411
3439
  }
3412
- var execFileAsync2, KNOWN_COMMANDS;
3440
+ var execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
3413
3441
  var init_cli_resolver = __esm({
3414
3442
  "src/cli-resolver.ts"() {
3415
3443
  "use strict";
3416
3444
  init_versioned_traceability();
3417
3445
  init_native_binding_diagnostics();
3418
3446
  execFileAsync2 = promisify2(execFile2);
3447
+ REQUIRED_NODE_VERSION = ">=22.22.2 <23";
3419
3448
  KNOWN_COMMANDS = [
3420
3449
  "init",
3421
3450
  "scan",
@@ -3897,6 +3926,378 @@ var init_hook_installer = __esm({
3897
3926
  }
3898
3927
  });
3899
3928
 
3929
+ // src/professional-conclusion.ts
3930
+ import { access as access2 } from "fs/promises";
3931
+ import { createRequire as createRequire2 } from "module";
3932
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute4, join as join7, resolve as resolve5 } from "path";
3933
+ import { pathToFileURL } from "url";
3934
+ async function loadContracts() {
3935
+ return await import(CONTRACTS_PACKAGE_NAME);
3936
+ }
3937
+ async function loadHarness() {
3938
+ return await import("skill-family-harness-node");
3939
+ }
3940
+ function providerVersion() {
3941
+ const anchor = typeof __filename === "string" ? __filename : import.meta.url;
3942
+ const parsed = createRequire2(anchor)("../package.json");
3943
+ if (typeof parsed.version !== "string" || parsed.version.length === 0) {
3944
+ throw new Error("artifact-graph package.json is missing version");
3945
+ }
3946
+ return parsed.version;
3947
+ }
3948
+ function errorMessage(error) {
3949
+ return error instanceof Error ? error.message : String(error);
3950
+ }
3951
+ function harnessKind(error) {
3952
+ if (error === null || typeof error !== "object" || !("details" in error)) {
3953
+ return void 0;
3954
+ }
3955
+ const details = error.details;
3956
+ return typeof details?.kind === "string" ? details.kind : void 0;
3957
+ }
3958
+ async function missingRequiredConfig(root) {
3959
+ const configPath = join7(root, "artifact-graph.config.yaml");
3960
+ try {
3961
+ await access2(configPath);
3962
+ return void 0;
3963
+ } catch (error) {
3964
+ if (error.code === "ENOENT") {
3965
+ return `required configuration is missing: ${configPath}`;
3966
+ }
3967
+ return errorMessage(error);
3968
+ }
3969
+ }
3970
+ async function runValidate(root) {
3971
+ const config = await loadConfig(root);
3972
+ const graph = await scanArtifacts(root, config);
3973
+ const issues = validateGraph(graph, config);
3974
+ issues.push(...await validateScenarioPrdLinkIndex(root, graph));
3975
+ issues.push(...await validateExecutableTraceability(root, config));
3976
+ const includeCoverage = config.e2e?.executable_ref_warning !== void 0 || config.e2e?.executable_ref_error !== void 0;
3977
+ if (includeCoverage) {
3978
+ const e2eConfig = config.e2e ?? {};
3979
+ const coverageStats = await computeE2eCoverageStats(graph, root, {
3980
+ executableRefWarning: e2eConfig.executable_ref_warning,
3981
+ executableRefError: e2eConfig.executable_ref_error,
3982
+ reportUncoveredScenarios: e2eConfig.report_uncovered_scenarios,
3983
+ reportUncoveredFeatures: e2eConfig.report_uncovered_features,
3984
+ scenarioWaivers: e2eConfig.scenario_waivers,
3985
+ featureWaivers: e2eConfig.feature_waivers
3986
+ });
3987
+ for (const msg of coverageStats.thresholdWarnings) {
3988
+ issues.push({
3989
+ code: "E2E_COVERAGE_WARNING",
3990
+ severity: "warning",
3991
+ message: msg,
3992
+ path: "e2e-coverage",
3993
+ line: 1
3994
+ });
3995
+ }
3996
+ for (const msg of coverageStats.thresholdErrors) {
3997
+ issues.push({
3998
+ code: "E2E_COVERAGE_ERROR",
3999
+ severity: "error",
4000
+ message: msg,
4001
+ path: "e2e-coverage",
4002
+ line: 1
4003
+ });
4004
+ }
4005
+ }
4006
+ return { name: CHECK_VALIDATE, status: "completed", issues };
4007
+ }
4008
+ async function runLockAudit(root) {
4009
+ const result = await auditVersionLock(root);
4010
+ return { name: CHECK_LOCK, status: "completed", issues: result.issues };
4011
+ }
4012
+ async function runCoverage(root) {
4013
+ const report = await computeCoverageBoundary(root);
4014
+ return {
4015
+ name: CHECK_COVERAGE,
4016
+ status: "completed",
4017
+ issues: [],
4018
+ coverage: {
4019
+ assessment: report.graphHealth.assessment,
4020
+ changedPathScope: report.scanCoverage.changedPathScope,
4021
+ behaviorStatus: report.behaviorVerification.status
4022
+ }
4023
+ };
4024
+ }
4025
+ async function settleCheck(name, run) {
4026
+ try {
4027
+ return await run();
4028
+ } catch (error) {
4029
+ return { name, status: "not-performed", issues: [], reason: errorMessage(error) };
4030
+ }
4031
+ }
4032
+ function mapDomain(checks) {
4033
+ const completed = checks.filter((check) => check.status === "completed");
4034
+ const missing = checks.filter((check) => check.status === "not-performed");
4035
+ const hasFindings = completed.some((check) => check.issues.length > 0);
4036
+ if (completed.length === 0) {
4037
+ return {
4038
+ code: GRAPH_DOMAIN_CODES.UNAVAILABLE,
4039
+ completion: "not-performed",
4040
+ summary: "Graph checks did not start because configuration, runtime, or inputs were unavailable."
4041
+ };
4042
+ }
4043
+ if (hasFindings) {
4044
+ return {
4045
+ code: GRAPH_DOMAIN_CODES.FINDINGS,
4046
+ completion: missing.length > 0 ? "partial" : "complete",
4047
+ summary: "At least one completed graph check reported issues. Original issues are preserved."
4048
+ };
4049
+ }
4050
+ if (missing.length > 0) {
4051
+ return {
4052
+ code: GRAPH_DOMAIN_CODES.INCOMPLETE,
4053
+ completion: "partial",
4054
+ summary: "Some declared graph checks completed without findings; others lacked input or could not finish."
4055
+ };
4056
+ }
4057
+ return {
4058
+ code: GRAPH_DOMAIN_CODES.CLEAR,
4059
+ completion: "complete",
4060
+ summary: "Declared graph checks completed without issues. This does not prove unregistered relations or content correctness."
4061
+ };
4062
+ }
4063
+ function buildLimitations(checks) {
4064
+ const limitations = [STANDING_LIMITATION];
4065
+ for (const check of checks) {
4066
+ if (check.status === "not-performed") {
4067
+ limitations.push(`${check.name} did not complete: ${check.reason ?? "unknown error"}`);
4068
+ }
4069
+ if (check.coverage?.behaviorStatus === "not-evaluated") {
4070
+ limitations.push("coverage does not evaluate whether declared verification actually ran.");
4071
+ }
4072
+ if (check.coverage?.changedPathScope === "unavailable") {
4073
+ limitations.push("coverage could not observe Git worktree changes.");
4074
+ }
4075
+ }
4076
+ return [...new Set(limitations)];
4077
+ }
4078
+ function buildConclusion(root, checks) {
4079
+ const absoluteRoot = resolve5(root);
4080
+ const mapped = mapDomain(checks);
4081
+ const checked = checks.filter((check) => check.status === "completed").map((check) => check.name);
4082
+ const limitations = buildLimitations(checks);
4083
+ const issues = checks.flatMap((check) => check.issues);
4084
+ return {
4085
+ schemaVersion: 1,
4086
+ kind: "skill-family.professional-conclusion",
4087
+ provider: {
4088
+ id: GRAPH_PROVIDER_ID,
4089
+ version: providerVersion(),
4090
+ entry: GRAPH_PROVIDER_ENTRY
4091
+ },
4092
+ subject: {
4093
+ ref: pathToFileURL(absoluteRoot).href
4094
+ },
4095
+ scope: {
4096
+ checked: mapped.completion === "not-performed" ? [] : checked,
4097
+ limitations
4098
+ },
4099
+ outcome: {
4100
+ completion: mapped.completion,
4101
+ code: mapped.code,
4102
+ summary: mapped.summary
4103
+ },
4104
+ details: {
4105
+ checks: checks.map((check) => ({
4106
+ name: check.name,
4107
+ status: check.status,
4108
+ issueCount: check.issues.length,
4109
+ ...check.reason ? { reason: check.reason } : {},
4110
+ ...check.coverage ? { coverage: check.coverage } : {}
4111
+ })),
4112
+ issues
4113
+ }
4114
+ };
4115
+ }
4116
+ async function assertConclusionShape(conclusion) {
4117
+ const contracts = await loadContracts();
4118
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4119
+ if (registration === null) {
4120
+ throw new Error("skill-family-contracts 0.22.0 does not register professional-conclusion");
4121
+ }
4122
+ const verdict = contracts.validateDocument(conclusion, {
4123
+ schemaId: registration.$id,
4124
+ dialect: registration.dialect,
4125
+ policy: "strict"
4126
+ });
4127
+ if (!verdict.valid) {
4128
+ throw new Error(`constructed professional conclusion failed public schema validation (${verdict.errorCode ?? "invalid"})`);
4129
+ }
4130
+ }
4131
+ async function publishConclusion(absoluteOutput, conclusion) {
4132
+ if (!isAbsolute4(absoluteOutput)) {
4133
+ return "--conclusion-output must be an absolute path";
4134
+ }
4135
+ const outputRoot = dirname5(absoluteOutput);
4136
+ const relPath = basename3(absoluteOutput);
4137
+ if (relPath.length === 0 || relPath === "." || relPath === "..") {
4138
+ return "--conclusion-output must name a file";
4139
+ }
4140
+ try {
4141
+ const harness = await loadHarness();
4142
+ await harness.publishFileExclusive(outputRoot, relPath, `${JSON.stringify(conclusion, null, 2)}
4143
+ `);
4144
+ return void 0;
4145
+ } catch (error) {
4146
+ const kind = harnessKind(error);
4147
+ if (kind === "exclusive-publish-conflict") {
4148
+ return `exclusive publication target already exists: ${absoluteOutput}`;
4149
+ }
4150
+ return errorMessage(error);
4151
+ }
4152
+ }
4153
+ async function runCheckProfessional(options) {
4154
+ const root = resolve5(options.root);
4155
+ const configGap = await missingRequiredConfig(root);
4156
+ const checks = configGap === void 0 ? await Promise.all([
4157
+ settleCheck(CHECK_VALIDATE, () => runValidate(root)),
4158
+ settleCheck(CHECK_LOCK, () => runLockAudit(root)),
4159
+ settleCheck(CHECK_COVERAGE, () => runCoverage(root))
4160
+ ]) : [
4161
+ { name: CHECK_VALIDATE, status: "not-performed", issues: [], reason: configGap },
4162
+ { name: CHECK_LOCK, status: "not-performed", issues: [], reason: configGap },
4163
+ { name: CHECK_COVERAGE, status: "not-performed", issues: [], reason: configGap }
4164
+ ];
4165
+ const conclusion = buildConclusion(root, checks);
4166
+ await assertConclusionShape(conclusion);
4167
+ if (options.conclusionOutput === void 0) {
4168
+ return { conclusion };
4169
+ }
4170
+ if (!isAbsolute4(options.conclusionOutput)) {
4171
+ return { conclusion, writeError: "--conclusion-output must be an absolute path" };
4172
+ }
4173
+ const writeError = await publishConclusion(resolve5(options.conclusionOutput), conclusion);
4174
+ return { conclusion, ...writeError ? { writeError } : {} };
4175
+ }
4176
+ function asRecord(value) {
4177
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
4178
+ return null;
4179
+ }
4180
+ return value;
4181
+ }
4182
+ function readProvider(value) {
4183
+ const record = asRecord(value);
4184
+ if (record === null) {
4185
+ return null;
4186
+ }
4187
+ const provider = {};
4188
+ if (typeof record.id === "string") provider.id = record.id;
4189
+ if (typeof record.version === "string") provider.version = record.version;
4190
+ if (typeof record.entry === "string") provider.entry = record.entry;
4191
+ return Object.keys(provider).length > 0 ? provider : null;
4192
+ }
4193
+ function interpretConclusion(conclusion) {
4194
+ const provider = conclusion.provider;
4195
+ if (provider.id !== GRAPH_PROVIDER_ID) {
4196
+ return {
4197
+ status: "unavailable",
4198
+ reason: `proof provider ${provider.id} is not ${GRAPH_PROVIDER_ID}`,
4199
+ provider,
4200
+ conclusion
4201
+ };
4202
+ }
4203
+ if (!KNOWN_DOMAIN_CODES.has(conclusion.outcome.code)) {
4204
+ return {
4205
+ status: "unavailable",
4206
+ reason: `unknown same-version domain code: ${conclusion.outcome.code}`,
4207
+ provider,
4208
+ conclusion
4209
+ };
4210
+ }
4211
+ if (conclusion.outcome.code === GRAPH_DOMAIN_CODES.CLEAR && conclusion.outcome.completion === "complete") {
4212
+ return {
4213
+ status: "pass",
4214
+ reason: "GRAPH_CLEAR with complete scope is acceptable for this provider version.",
4215
+ provider,
4216
+ conclusion
4217
+ };
4218
+ }
4219
+ return {
4220
+ status: "not_pass",
4221
+ reason: `proof records ${conclusion.outcome.code} (${conclusion.outcome.completion}); complete does not mean pass.`,
4222
+ provider,
4223
+ conclusion
4224
+ };
4225
+ }
4226
+ async function runReadProof(options) {
4227
+ const unavailable = (reason, provider = null, conclusion = null) => ({
4228
+ result: { status: "unavailable", reason, provider, conclusion },
4229
+ exitCode: 2
4230
+ });
4231
+ let receipt;
4232
+ try {
4233
+ const harness = await loadHarness();
4234
+ receipt = await harness.readFileStrict(options.proofRoot, options.proof, { encoding: "utf8" });
4235
+ } catch (error) {
4236
+ const kind = harnessKind(error);
4237
+ if (kind === "missing-resource") {
4238
+ return unavailable(`proof file does not exist: ${options.proof}`, null, null);
4239
+ }
4240
+ return unavailable(errorMessage(error), null, null);
4241
+ }
4242
+ const raw = typeof receipt.content === "string" ? receipt.content : receipt.content.toString("utf8");
4243
+ let parsed;
4244
+ try {
4245
+ parsed = JSON.parse(raw);
4246
+ } catch (error) {
4247
+ return unavailable(`proof is not valid JSON: ${errorMessage(error)}`, null, null);
4248
+ }
4249
+ const previewProvider = readProvider(asRecord(parsed)?.provider);
4250
+ let contracts;
4251
+ try {
4252
+ contracts = await loadContracts();
4253
+ } catch (error) {
4254
+ return unavailable(`cannot load skill-family-contracts: ${errorMessage(error)}`, previewProvider, null);
4255
+ }
4256
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4257
+ if (registration === null) {
4258
+ return unavailable("professional-conclusion schema is not registered", previewProvider, null);
4259
+ }
4260
+ const verdict = contracts.validateDocument(parsed, {
4261
+ schemaId: registration.$id,
4262
+ dialect: registration.dialect,
4263
+ policy: "strict"
4264
+ });
4265
+ if (!verdict.valid) {
4266
+ return unavailable(
4267
+ `proof failed professional-conclusion schema validation (${verdict.errorCode ?? "invalid"})`,
4268
+ previewProvider,
4269
+ null
4270
+ );
4271
+ }
4272
+ const interpreted = interpretConclusion(parsed);
4273
+ const exitCode = interpreted.status === "pass" ? 0 : interpreted.status === "not_pass" ? 1 : 2;
4274
+ return { result: interpreted, exitCode };
4275
+ }
4276
+ var 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;
4277
+ var init_professional_conclusion = __esm({
4278
+ "src/professional-conclusion.ts"() {
4279
+ "use strict";
4280
+ init_coverage();
4281
+ init_index();
4282
+ init_versioned_traceability();
4283
+ GRAPH_PROVIDER_ID = "artifact-graph";
4284
+ GRAPH_PROVIDER_ENTRY = "check-professional";
4285
+ PROFESSIONAL_CONCLUSION_OBJECT = "professional-conclusion";
4286
+ GRAPH_DOMAIN_CODES = Object.freeze({
4287
+ CLEAR: "GRAPH_CLEAR",
4288
+ FINDINGS: "GRAPH_FINDINGS",
4289
+ INCOMPLETE: "GRAPH_CHECK_INCOMPLETE",
4290
+ UNAVAILABLE: "GRAPH_CHECK_UNAVAILABLE"
4291
+ });
4292
+ KNOWN_DOMAIN_CODES = new Set(Object.values(GRAPH_DOMAIN_CODES));
4293
+ CHECK_VALIDATE = "validate";
4294
+ CHECK_LOCK = "version-lock-audit";
4295
+ CHECK_COVERAGE = "coverage";
4296
+ STANDING_LIMITATION = "Graph checks do not prove content semantics, method execution, or publication facts.";
4297
+ CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
4298
+ }
4299
+ });
4300
+
3900
4301
  // src/review-result-validator.ts
3901
4302
  function validateReviewResult(input) {
3902
4303
  const errors = [];
@@ -3974,8 +4375,8 @@ function validateReviewResult(input) {
3974
4375
  validateReviewData(obj.review, "$.review", errors);
3975
4376
  if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
3976
4377
  const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
3977
- findings.forEach((finding, index) => {
3978
- if (isPlainObject(finding) && finding.severity === "block" && (finding.status === void 0 || finding.status === "open")) {
4378
+ findings.forEach((finding2, index) => {
4379
+ if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
3979
4380
  errors.push({
3980
4381
  path: `$.review.findings[${index}]`,
3981
4382
  message: `${obj.decision} cannot contain an open block finding`
@@ -4221,7 +4622,7 @@ var init_review_result_validator = __esm({
4221
4622
  // src/contract-kernel.ts
4222
4623
  import { createHash as createHash2 } from "crypto";
4223
4624
  import { readFile as readFile2, readdir as readdir2 } from "fs/promises";
4224
- import { join as join7 } from "path";
4625
+ import { join as join8 } from "path";
4225
4626
  import _AjvModule from "ajv";
4226
4627
  function isOfficialNamespace(namespace) {
4227
4628
  return OFFICIAL_NAMESPACE_PATTERN.test(namespace);
@@ -4553,7 +4954,7 @@ async function loadContractsFromDirectory(contractsDir, options) {
4553
4954
  const entries = await readdir2(contractsDir, { withFileTypes: true });
4554
4955
  for (const entry of entries) {
4555
4956
  if (entry.isDirectory()) {
4556
- const schemaPath = join7(contractsDir, entry.name, "schema.json");
4957
+ const schemaPath = join8(contractsDir, entry.name, "schema.json");
4557
4958
  const contract = await loadContract(schemaPath, options);
4558
4959
  contracts.push(contract);
4559
4960
  }
@@ -4993,12 +5394,1691 @@ var init_contract_kernel = __esm({
4993
5394
  }
4994
5395
  });
4995
5396
 
5397
+ // src/restructure-software.ts
5398
+ function lineStarts(raw) {
5399
+ const starts = [0];
5400
+ const buffer = Buffer.from(raw, "utf8");
5401
+ for (let index = 0; index < buffer.length; index += 1) {
5402
+ if (buffer[index] === 10) starts.push(index + 1);
5403
+ }
5404
+ return starts;
5405
+ }
5406
+ function markdownCodeLineMask(lines) {
5407
+ const result = new Array(lines.length).fill(false);
5408
+ let fence;
5409
+ lines.forEach((line, index) => {
5410
+ if (fence) {
5411
+ result[index] = true;
5412
+ const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
5413
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
5414
+ return;
5415
+ }
5416
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
5417
+ if (opening) {
5418
+ result[index] = true;
5419
+ fence = { marker: opening[1][0], length: opening[1].length };
5420
+ return;
5421
+ }
5422
+ if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
5423
+ });
5424
+ return result;
5425
+ }
5426
+ function markdownRecordHeadings(raw, type) {
5427
+ const lines = raw.split("\n");
5428
+ const masked = markdownCodeLineMask(lines);
5429
+ 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;
5430
+ if (!pattern) return [];
5431
+ return lines.flatMap((line, index) => {
5432
+ if (masked[index]) return [];
5433
+ const match = pattern.exec(line.replace(/\r$/, ""));
5434
+ return match ? [{ id: match[1], line: index + 1 }] : [];
5435
+ });
5436
+ }
5437
+ function locateSoftwareRecord(raw, node, nodesInFile) {
5438
+ const byteLength = Buffer.byteLength(raw, "utf8");
5439
+ if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
5440
+ if (node.type !== "scenario" && node.type !== "e2e_test") {
5441
+ return {
5442
+ blockers: [{
5443
+ code: "UNSUPPORTED_RECORD_BOUNDARY",
5444
+ message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
5445
+ path: node.path,
5446
+ line: node.line
5447
+ }]
5448
+ };
5449
+ }
5450
+ const headings = markdownRecordHeadings(raw, node.type);
5451
+ const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
5452
+ const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
5453
+ const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
5454
+ const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
5455
+ const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
5456
+ const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
5457
+ if (inconsistent) {
5458
+ return {
5459
+ blockers: [{
5460
+ code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
5461
+ 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",
5462
+ path: node.path,
5463
+ line: node.line
5464
+ }]
5465
+ };
5466
+ }
5467
+ if (!heading) {
5468
+ return {
5469
+ blockers: [{
5470
+ code: "RECORD_BOUNDARY_MISSING",
5471
+ message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
5472
+ path: node.path,
5473
+ line: node.line
5474
+ }]
5475
+ };
5476
+ }
5477
+ const starts = lineStarts(raw);
5478
+ const nextLine = headings.find((item) => item.line > heading.line)?.line;
5479
+ return {
5480
+ range: {
5481
+ startByte: starts[heading.line - 1] ?? 0,
5482
+ endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
5483
+ },
5484
+ blockers: []
5485
+ };
5486
+ }
5487
+ function replaceSoftwareHeader(raw, header) {
5488
+ const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
5489
+ const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
5490
+ ` : header;
5491
+ return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
5492
+ }
5493
+ var init_restructure_software = __esm({
5494
+ "src/restructure-software.ts"() {
5495
+ "use strict";
5496
+ }
5497
+ });
5498
+
5499
+ // src/restructure-file-set.ts
5500
+ import { createHash as createHash3 } from "crypto";
5501
+ import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
5502
+ import { join as join9, resolve as resolve6 } from "path";
5503
+ async function loadFoundationModule() {
5504
+ return await import(FOUNDATION_PACKAGE_NAME);
5505
+ }
5506
+ async function loadContractsModule() {
5507
+ return await import(CONTRACTS_PACKAGE_NAME2);
5508
+ }
5509
+ async function verifyMechanismResult(result) {
5510
+ if (typeof result !== "object" || result === null || Array.isArray(result)) {
5511
+ return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
5512
+ }
5513
+ let contracts;
5514
+ let registration;
5515
+ try {
5516
+ contracts = await loadContractsModule();
5517
+ registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
5518
+ } catch (cause) {
5519
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
5520
+ }
5521
+ if (registration === null) {
5522
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
5523
+ }
5524
+ const verdict = contracts.validateDocument(result, {
5525
+ schemaId: registration.$id,
5526
+ dialect: registration.dialect,
5527
+ policy: "strict"
5528
+ });
5529
+ if (!verdict.valid) {
5530
+ return failure(
5531
+ "MECHANISM_RESULT_INVALID",
5532
+ `The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
5533
+ { schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
5534
+ );
5535
+ }
5536
+ return { ok: true, data: result };
5537
+ }
5538
+ function failure(code, message, details) {
5539
+ return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
5540
+ }
5541
+ function candidateBytes(content) {
5542
+ return Buffer.from(content ?? "", "utf8");
5543
+ }
5544
+ function candidateByteDigest(content) {
5545
+ return createHash3("sha256").update(candidateBytes(content)).digest("hex");
5546
+ }
5547
+ function rawDigest(value, path) {
5548
+ if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
5549
+ throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
5550
+ }
5551
+ const raw = value.slice(DIGEST_PREFIX.length);
5552
+ if (!RAW_SHA256_PATTERN.test(raw)) {
5553
+ throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
5554
+ }
5555
+ return raw;
5556
+ }
5557
+ async function resolveRealRoot(root) {
5558
+ let canonical;
5559
+ try {
5560
+ canonical = await realpath(resolve6(root));
5561
+ } catch (cause) {
5562
+ return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5563
+ }
5564
+ let info;
5565
+ try {
5566
+ info = await lstat2(canonical);
5567
+ } catch (cause) {
5568
+ return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
5569
+ }
5570
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5571
+ return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
5572
+ }
5573
+ return { ok: true, data: canonical };
5574
+ }
5575
+ async function qualifyRestructureMechanism(root) {
5576
+ if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
5577
+ return failure(
5578
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5579
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
5580
+ );
5581
+ }
5582
+ const canonical = await resolveRealRoot(root);
5583
+ if (!canonical.ok) return canonical;
5584
+ let type;
5585
+ try {
5586
+ type = (await statfs(canonical.data)).type;
5587
+ } catch (cause) {
5588
+ return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
5589
+ }
5590
+ if (type !== APFS_STATFS_TYPE) {
5591
+ return failure(
5592
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5593
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
5594
+ );
5595
+ }
5596
+ return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5597
+ }
5598
+ async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5599
+ const target = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5600
+ const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5601
+ let info = await current();
5602
+ if (info === null) {
5603
+ if (!options.create) {
5604
+ return failure(
5605
+ "RECOVERY_MATERIALS_MISSING",
5606
+ `No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
5607
+ );
5608
+ }
5609
+ let created = false;
5610
+ try {
5611
+ await mkdir4(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
5612
+ created = true;
5613
+ } catch (cause) {
5614
+ if (cause.code !== "EEXIST") {
5615
+ return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
5616
+ }
5617
+ }
5618
+ info = await current();
5619
+ if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
5620
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5621
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5622
+ }
5623
+ if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5624
+ await chmod(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
5625
+ info = await current();
5626
+ if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
5627
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5628
+ }
5629
+ }
5630
+ }
5631
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5632
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5633
+ }
5634
+ if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5635
+ return failure(
5636
+ "MECHANISM_ROOT_UNSAFE",
5637
+ `${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
5638
+ );
5639
+ }
5640
+ return { ok: true, data: target };
5641
+ }
5642
+ async function createRestructureRootBinding(canonicalRoot) {
5643
+ try {
5644
+ const module = await loadFoundationModule();
5645
+ return { ok: true, data: await module.createFilesystemRootBinding(canonicalRoot) };
5646
+ } catch (cause) {
5647
+ return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
5648
+ }
5649
+ }
5650
+ function toOperation(candidate) {
5651
+ const expected = candidate.original.exists ? {
5652
+ exists: true,
5653
+ sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
5654
+ size: candidate.original.size,
5655
+ mode: candidate.original.mode
5656
+ } : { exists: false };
5657
+ if (candidate.action === "delete") {
5658
+ return { path: candidate.path, action: "delete", expected, next: null };
5659
+ }
5660
+ const bytes = candidateBytes(candidate.content);
5661
+ const declared = rawDigest(candidate.sha256, candidate.path);
5662
+ if (declared !== candidateByteDigest(candidate.content)) {
5663
+ throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
5664
+ }
5665
+ return {
5666
+ path: candidate.path,
5667
+ action: candidate.action,
5668
+ expected,
5669
+ next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
5670
+ };
5671
+ }
5672
+ async function buildFileSetApplyRequest(canonicalRoot, plan) {
5673
+ if (plan.candidates.length === 0) {
5674
+ return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
5675
+ }
5676
+ const binding = await createRestructureRootBinding(canonicalRoot);
5677
+ if (!binding.ok) return binding;
5678
+ let operations;
5679
+ try {
5680
+ operations = plan.candidates.map(toOperation);
5681
+ } catch (cause) {
5682
+ return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
5683
+ }
5684
+ return {
5685
+ ok: true,
5686
+ data: {
5687
+ schemaVersion: 1,
5688
+ kind: "skill-family.file-set-apply-request",
5689
+ operationId: plan.operation_id,
5690
+ root: canonicalRoot,
5691
+ rootBinding: binding.data,
5692
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5693
+ allowAdjacentStaging: true,
5694
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5695
+ validationTimeoutMs: plan.validation_timeout_ms,
5696
+ operations
5697
+ }
5698
+ };
5699
+ }
5700
+ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5701
+ const request = await buildFileSetApplyRequest(canonicalRoot, plan);
5702
+ if (!request.ok) return request;
5703
+ const module = await loadFoundationModule();
5704
+ let raw;
5705
+ try {
5706
+ raw = await module.applyFileSet(request.data, { validate: options.validate });
5707
+ } catch (cause) {
5708
+ return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
5709
+ }
5710
+ return await verifyMechanismResult(raw);
5711
+ }
5712
+ async function observeRestructureJournal(canonicalRoot) {
5713
+ const journalRoot = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5714
+ const module = await loadFoundationModule();
5715
+ try {
5716
+ return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
5717
+ } catch (cause) {
5718
+ return failure(
5719
+ "MAINTENANCE_OBSERVATION_FAILED",
5720
+ `The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
5721
+ );
5722
+ }
5723
+ }
5724
+ async function recoverRestructureFileSet(canonicalRoot, plan, options) {
5725
+ if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
5726
+ return failure(
5727
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
5728
+ "restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
5729
+ );
5730
+ }
5731
+ const binding = await createRestructureRootBinding(canonicalRoot);
5732
+ if (!binding.ok) return binding;
5733
+ const observation = await observeRestructureJournal(canonicalRoot);
5734
+ if (!observation.ok) return observation;
5735
+ const maintenance = {
5736
+ observation: observation.data,
5737
+ confirmAllParticipantsStopped: true,
5738
+ confirmExclusiveMaintenance: true
5739
+ };
5740
+ const request = {
5741
+ schemaVersion: 1,
5742
+ kind: "skill-family.file-set-recovery-request",
5743
+ operationId: plan.operation_id,
5744
+ root: canonicalRoot,
5745
+ rootBinding: binding.data,
5746
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5747
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5748
+ allowAdjacentStaging: true,
5749
+ maintenance
5750
+ };
5751
+ const module = await loadFoundationModule();
5752
+ let raw;
5753
+ try {
5754
+ raw = await module.recoverFileSet(request);
5755
+ } catch (cause) {
5756
+ return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
5757
+ }
5758
+ return await verifyMechanismResult(raw);
5759
+ }
5760
+ async function pruneRestructureFileSet(canonicalRoot, plan, options) {
5761
+ const binding = await createRestructureRootBinding(canonicalRoot);
5762
+ if (!binding.ok) return binding;
5763
+ const request = {
5764
+ schemaVersion: 1,
5765
+ kind: "skill-family.file-set-prune-request",
5766
+ operationId: plan.operation_id,
5767
+ root: canonicalRoot,
5768
+ rootBinding: binding.data,
5769
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5770
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
5771
+ };
5772
+ if (options.allParticipantsStopped && options.exclusiveMaintenance) {
5773
+ const observation = await observeRestructureJournal(canonicalRoot);
5774
+ if (!observation.ok) return observation;
5775
+ request.maintenance = {
5776
+ observation: observation.data,
5777
+ confirmAllParticipantsStopped: true,
5778
+ confirmExclusiveMaintenance: true
5779
+ };
5780
+ }
5781
+ const module = await loadFoundationModule();
5782
+ let raw;
5783
+ try {
5784
+ raw = await module.pruneFileSetRecovery(request);
5785
+ } catch (cause) {
5786
+ return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
5787
+ }
5788
+ return await verifyMechanismResult(raw);
5789
+ }
5790
+ function validationState(validation) {
5791
+ return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
5792
+ }
5793
+ function errorKinds(result) {
5794
+ return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
5795
+ }
5796
+ function applyProjection(result) {
5797
+ const kinds = errorKinds(result);
5798
+ if (result.outcome === "committed") {
5799
+ if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
5800
+ return {
5801
+ code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
5802
+ 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.",
5803
+ ok: false,
5804
+ rerunApplyPermitted: false
5805
+ };
5806
+ }
5807
+ const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
5808
+ return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
5809
+ code: "APPLY_INCOMPLETE",
5810
+ message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
5811
+ ok: false,
5812
+ rerunApplyPermitted: false
5813
+ };
5814
+ }
5815
+ const codes = {
5816
+ "commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
5817
+ "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."],
5818
+ "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."]
5819
+ };
5820
+ const mapped = codes[result.outcome];
5821
+ if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
5822
+ if (result.outcome === "rejected") {
5823
+ const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
5824
+ return {
5825
+ code: "APPLY_REJECTED",
5826
+ 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.",
5827
+ ok: false,
5828
+ rerunApplyPermitted: !identityTaken
5829
+ };
5830
+ }
5831
+ return {
5832
+ code: "APPLY_UNEXPECTED_OUTCOME",
5833
+ message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
5834
+ ok: false,
5835
+ rerunApplyPermitted: false
5836
+ };
5837
+ }
5838
+ function recoverProjection(result) {
5839
+ const reading = (() => {
5840
+ switch (result.outcome) {
5841
+ case "already-committed":
5842
+ return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
5843
+ case "already-rolled-back":
5844
+ return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
5845
+ case "rolled-back":
5846
+ return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
5847
+ case "pruned":
5848
+ return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
5849
+ case "already-pruned":
5850
+ return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
5851
+ case "commit-unconfirmed":
5852
+ 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 };
5853
+ case "recovery-required":
5854
+ return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
5855
+ case "rejected":
5856
+ return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
5857
+ default:
5858
+ return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
5859
+ }
5860
+ })();
5861
+ return { ...reading, rerunApplyPermitted: false };
5862
+ }
5863
+ function pruneProjection(result) {
5864
+ const reading = (() => {
5865
+ switch (result.outcome) {
5866
+ case "pruned":
5867
+ return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
5868
+ case "already-pruned":
5869
+ return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
5870
+ case "rejected":
5871
+ return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
5872
+ case "recovery-required":
5873
+ 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 };
5874
+ default:
5875
+ return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
5876
+ }
5877
+ })();
5878
+ return { ...reading, rerunApplyPermitted: false };
5879
+ }
5880
+ function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
5881
+ const base = {
5882
+ foundation: result,
5883
+ planPath,
5884
+ planDigest,
5885
+ operation: result.operation,
5886
+ outcome: result.outcome,
5887
+ preflight: result.preflight,
5888
+ businessWrite: result.businessWrite,
5889
+ validation: result.validation,
5890
+ validationState: validationState(result.validation),
5891
+ recovery: result.recovery,
5892
+ paths: result.paths,
5893
+ errors: result.errors,
5894
+ materialPath: result.materials.relPath,
5895
+ errorKinds: errorKinds(result)
5896
+ };
5897
+ const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
5898
+ return { ...base, ...reading };
5899
+ }
5900
+ var RESTRUCTURE_RECOVERY_REL_PATH, RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH, RESTRUCTURE_RECOVERY_ROOT_MODE, RESTRUCTURE_QUALIFIED_PLATFORM, RESTRUCTURE_QUALIFIED_ARCH, RESTRUCTURE_QUALIFIED_FILESYSTEM, APFS_STATFS_TYPE, DIGEST_PREFIX, RAW_SHA256_PATTERN, FOUNDATION_PACKAGE_NAME, CONTRACTS_PACKAGE_NAME2, FILE_SET_RESULT_OBJECT, APPLY_MAINTENANCE_ERROR_KINDS;
5901
+ var init_restructure_file_set = __esm({
5902
+ "src/restructure-file-set.ts"() {
5903
+ "use strict";
5904
+ RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
5905
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
5906
+ RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
5907
+ RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
5908
+ RESTRUCTURE_QUALIFIED_ARCH = "arm64";
5909
+ RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
5910
+ APFS_STATFS_TYPE = 26;
5911
+ DIGEST_PREFIX = "sha256:";
5912
+ RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5913
+ FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
5914
+ CONTRACTS_PACKAGE_NAME2 = "skill-family-contracts";
5915
+ FILE_SET_RESULT_OBJECT = "file-set-result";
5916
+ APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
5917
+ }
5918
+ });
5919
+
5920
+ // src/restructure.ts
5921
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
5922
+ import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
5923
+ import { dirname as dirname6, isAbsolute as isAbsolute5, join as join10, posix, relative as relative4, resolve as resolve7 } from "path";
5924
+ import { fileURLToPath as fileURLToPath2 } from "url";
5925
+ function digestBytes(value) {
5926
+ return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
5927
+ }
5928
+ function canonicalJson(value) {
5929
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
5930
+ if (value && typeof value === "object") {
5931
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
5932
+ }
5933
+ return JSON.stringify(value);
5934
+ }
5935
+ function digestRestructureValue(value) {
5936
+ return digestBytes(canonicalJson(value));
5937
+ }
5938
+ function normalizeRelativePath2(value) {
5939
+ if (!value || value.includes("\0") || isAbsolute5(value)) return void 0;
5940
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5941
+ if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5942
+ return normalized;
5943
+ }
5944
+ function isPathAllowed(path, allowed) {
5945
+ return allowed.some((entry) => {
5946
+ const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
5947
+ return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
5948
+ });
5949
+ }
5950
+ async function readContainedFileWithMode(root, path) {
5951
+ const normalized = normalizeRelativePath2(path);
5952
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5953
+ const absoluteRoot = resolve7(root);
5954
+ const absolutePath = resolve7(absoluteRoot, normalized);
5955
+ if (relative4(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
5956
+ try {
5957
+ const info = await lstat3(absolutePath);
5958
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
5959
+ return { buffer: await readFile3(absolutePath), mode: info.mode & MAX_POSIX_MODE };
5960
+ } catch (error) {
5961
+ if (error.code === "ENOENT") return void 0;
5962
+ throw error;
5963
+ }
5964
+ }
5965
+ async function readContainedFile(root, path) {
5966
+ return (await readContainedFileWithMode(root, path))?.buffer;
5967
+ }
5968
+ async function snapshotFile(root, path) {
5969
+ const normalized = normalizeRelativePath2(path);
5970
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5971
+ const contained = await readContainedFileWithMode(root, normalized);
5972
+ return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
5973
+ path: normalized,
5974
+ exists: true,
5975
+ sha256: digestBytes(contained.buffer),
5976
+ size: contained.buffer.byteLength,
5977
+ mode: contained.mode
5978
+ };
5979
+ }
5980
+ function sameSnapshot(left, right) {
5981
+ return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
5982
+ }
5983
+ async function configSnapshot(root) {
5984
+ return snapshotFile(root, "artifact-graph.config.yaml");
5985
+ }
5986
+ async function loadRestructureContract(name) {
5987
+ return loadContract(join10(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
5988
+ }
5989
+ async function validateDomainContract(name, value) {
5990
+ const contract = await loadRestructureContract(name);
5991
+ return validateContractAgainstSchema(value, contract).errors;
5992
+ }
5993
+ function occurrenceKey(edge2) {
5994
+ return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
5995
+ }
5996
+ function relationOccurrences(graph) {
5997
+ const counts = /* @__PURE__ */ new Map();
5998
+ return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
5999
+ const key = occurrenceKey(edge2);
6000
+ const occurrence = (counts.get(key) ?? 0) + 1;
6001
+ counts.set(key, occurrence);
6002
+ return {
6003
+ from: edge2.from,
6004
+ to: edge2.to,
6005
+ kind: edge2.kind,
6006
+ source: edge2.source,
6007
+ source_path: edge2.sourcePath,
6008
+ source_line: edge2.sourceLine,
6009
+ occurrence
6010
+ };
6011
+ });
6012
+ }
6013
+ function relationKey(value) {
6014
+ return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
6015
+ }
6016
+ function acceptanceCriteria(node) {
6017
+ const raw = node.attrs?.acceptanceCriteria;
6018
+ if (!Array.isArray(raw)) return [];
6019
+ return raw.flatMap((item, index) => {
6020
+ if (typeof item === "string") {
6021
+ const match = /\b(AC\d+)\b/.exec(item);
6022
+ return [match?.[1] ?? `AC${index + 1}`];
6023
+ }
6024
+ if (item && typeof item === "object") {
6025
+ const record = item;
6026
+ const value = String(record.id ?? record.code ?? "").trim();
6027
+ return value ? [value] : [`AC${index + 1}`];
6028
+ }
6029
+ return [`AC${index + 1}`];
6030
+ });
6031
+ }
6032
+ function spanFor(buffer, path, range) {
6033
+ return {
6034
+ path,
6035
+ start_byte: range.startByte,
6036
+ end_byte: range.endByte,
6037
+ sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
6038
+ };
6039
+ }
6040
+ function mappingTemplate(request, requestDigest, config, sources, unresolved) {
6041
+ return {
6042
+ schema_version: "1.0",
6043
+ request,
6044
+ request_digest: requestDigest,
6045
+ config_snapshot: config,
6046
+ sources: sources.map((source) => ({
6047
+ type: source.type,
6048
+ id: source.id,
6049
+ path: source.path,
6050
+ snapshot: source.snapshot,
6051
+ disposition: "preserved"
6052
+ })),
6053
+ targets: [],
6054
+ content_moves: [],
6055
+ identity_map: [],
6056
+ criterion_map: [],
6057
+ relation_map: [],
6058
+ prose_edits: [],
6059
+ file_headers: [],
6060
+ unresolved
6061
+ };
6062
+ }
6063
+ async function inspectRestructure(root, input) {
6064
+ const schemaErrors = await validateDomainContract("request", input);
6065
+ if (schemaErrors.length > 0) {
6066
+ return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
6067
+ }
6068
+ const request = input;
6069
+ const requestDigest = digestRestructureValue(request);
6070
+ const schema = await loadConfig(root);
6071
+ const graph = await scanArtifacts(root, schema);
6072
+ const allOccurrences = relationOccurrences(graph);
6073
+ const blockers = [];
6074
+ const unresolved = [];
6075
+ const inspected = [];
6076
+ for (const requested of request.sources) {
6077
+ const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
6078
+ if (candidates.length !== 1) {
6079
+ blockers.push({
6080
+ code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
6081
+ 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`,
6082
+ ...requested.path ? { path: requested.path } : {}
6083
+ });
6084
+ continue;
6085
+ }
6086
+ const node = candidates[0];
6087
+ const raw = await readContainedFile(root, node.path);
6088
+ if (!raw) {
6089
+ blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
6090
+ continue;
6091
+ }
6092
+ const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
6093
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
6094
+ blockers.push(...boundary.blockers);
6095
+ const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
6096
+ const uid = `${node.type}:${node.code}`;
6097
+ inspected.push({
6098
+ type: node.type,
6099
+ id: node.code,
6100
+ uid,
6101
+ path: node.path,
6102
+ title: node.title,
6103
+ snapshot: await snapshotFile(root, node.path),
6104
+ ...recordSpan ? {
6105
+ record_span: recordSpan,
6106
+ content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
6107
+ } : {},
6108
+ surrounding_spans: recordSpan ? [
6109
+ ...recordSpan.start_byte > 0 ? [{
6110
+ ...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
6111
+ content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
6112
+ }] : [],
6113
+ ...recordSpan.end_byte < raw.byteLength ? [{
6114
+ ...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
6115
+ content: raw.subarray(recordSpan.end_byte).toString("utf8")
6116
+ }] : []
6117
+ ] : [],
6118
+ acceptance_criteria: acceptanceCriteria(node),
6119
+ incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
6120
+ outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
6121
+ });
6122
+ }
6123
+ if (request.numbering_policy?.mode === "configured-next-available") {
6124
+ unresolved.push({
6125
+ code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
6126
+ message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
6127
+ });
6128
+ }
6129
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6130
+ root,
6131
+ [...new Set(inspected.map((item) => item.path))],
6132
+ []
6133
+ ));
6134
+ const config = await configSnapshot(root);
6135
+ const affectedPaths = new Set(inspected.map((item) => item.path));
6136
+ for (const source of inspected) {
6137
+ for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
6138
+ }
6139
+ const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
6140
+ const inspection = {
6141
+ schema_version: "1.0",
6142
+ request,
6143
+ request_digest: requestDigest,
6144
+ config_snapshot: config,
6145
+ sources: inspected,
6146
+ affected_files: affectedFiles,
6147
+ relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
6148
+ blockers,
6149
+ unresolved,
6150
+ mapping_template: {}
6151
+ };
6152
+ inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
6153
+ return { ok: true, data: inspection };
6154
+ }
6155
+ function finding(code, message, path, line) {
6156
+ return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
6157
+ }
6158
+ async function verifySnapshot(root, expected, blockers) {
6159
+ const normalized = normalizeRelativePath2(expected.path);
6160
+ if (!normalized) {
6161
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6162
+ return void 0;
6163
+ }
6164
+ const actual = await snapshotFile(root, normalized);
6165
+ if (!sameSnapshot(actual, { ...expected, path: normalized })) {
6166
+ blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
6167
+ }
6168
+ return actual;
6169
+ }
6170
+ function validateSpan(buffer, span, blockers) {
6171
+ if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
6172
+ blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
6173
+ return void 0;
6174
+ }
6175
+ const fragment = buffer.subarray(span.start_byte, span.end_byte);
6176
+ if (digestBytes(fragment) !== span.sha256) {
6177
+ blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
6178
+ return void 0;
6179
+ }
6180
+ return fragment;
6181
+ }
6182
+ function rangesCover(range, moves) {
6183
+ 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);
6184
+ let cursor = range.startByte;
6185
+ for (const interval of intervals) {
6186
+ if (interval.start > cursor) return false;
6187
+ cursor = Math.max(cursor, interval.end);
6188
+ }
6189
+ return cursor >= range.endByte;
6190
+ }
6191
+ function edgeDisplay(edge2) {
6192
+ return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
6193
+ }
6194
+ function graphDiff(before, after) {
6195
+ const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6196
+ const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6197
+ const beforeEdges = new Set(before.edges.map(edgeDisplay));
6198
+ const afterEdges = new Set(after.edges.map(edgeDisplay));
6199
+ return {
6200
+ added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
6201
+ removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
6202
+ added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
6203
+ removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
6204
+ };
6205
+ }
6206
+ function issueIdentity(issue2) {
6207
+ const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
6208
+ return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
6209
+ }
6210
+ function readableDiff(path, oldContent, newContent) {
6211
+ const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
6212
+ const newLines = newContent?.split(/(?<=\n)/) ?? [];
6213
+ if (oldContent === newContent) return "";
6214
+ return [
6215
+ `--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
6216
+ `+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
6217
+ ...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
6218
+ ...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
6219
+ ].join("\n");
6220
+ }
6221
+ function findRelativeLinks(fragment) {
6222
+ const found = /* @__PURE__ */ new Set();
6223
+ const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
6224
+ let match;
6225
+ while ((match = pattern.exec(fragment)) !== null) {
6226
+ const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
6227
+ if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
6228
+ }
6229
+ return [...found].sort();
6230
+ }
6231
+ function footnoteReferenceLabels(text) {
6232
+ const labels = /* @__PURE__ */ new Set();
6233
+ const pattern = /\[\^([^\]\s]+)\](?!:)/g;
6234
+ let match;
6235
+ while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
6236
+ return [...labels].sort();
6237
+ }
6238
+ function footnoteDefinition(label) {
6239
+ return `[^${label}]:`;
6240
+ }
6241
+ function splitMarkdownTarget(target) {
6242
+ const cleaned = target.trim().replace(/^<|>$/g, "");
6243
+ const hash = cleaned.indexOf("#");
6244
+ return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
6245
+ }
6246
+ async function pathExists2(absolutePath) {
6247
+ try {
6248
+ await lstat3(absolutePath);
6249
+ return true;
6250
+ } catch {
6251
+ return false;
6252
+ }
6253
+ }
6254
+ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6255
+ const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
6256
+ const migrationNames = new Set(migrationPaths.map((path) => posix.basename(path)));
6257
+ const directories = new Set(migrationPaths.map((path) => posix.dirname(path)));
6258
+ const findings = [];
6259
+ async function visit(directory) {
6260
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6261
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6262
+ const absolute = join10(directory, entry.name);
6263
+ if (entry.isDirectory()) {
6264
+ await visit(absolute);
6265
+ continue;
6266
+ }
6267
+ if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
6268
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6269
+ const raw = await readFile3(absolute, "utf8");
6270
+ const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
6271
+ const lines = raw.split(/\r?\n/);
6272
+ for (const [index, line] of lines.entries()) {
6273
+ const lineNumber = index + 1;
6274
+ if (MARKDOWN_FILE_SUFFIX.test(path)) {
6275
+ const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
6276
+ let match;
6277
+ while ((match = pattern.exec(line)) !== null) {
6278
+ const literal = match[0];
6279
+ const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
6280
+ if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
6281
+ if (!migrationNames.has(posix.basename(linkPath))) continue;
6282
+ const resolved = normalizeRelativePath2(posix.join(posix.dirname(path), linkPath));
6283
+ if (!resolved || targetPaths.includes(resolved)) continue;
6284
+ if (anchor) {
6285
+ findings.push(finding(
6286
+ "ANCHOR_REFERENCE_UNRESOLVED",
6287
+ `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`,
6288
+ path,
6289
+ lineNumber
6290
+ ));
6291
+ } else if (!await pathExists2(resolve7(root, resolved))) {
6292
+ findings.push(finding(
6293
+ "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
6294
+ `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`,
6295
+ path,
6296
+ lineNumber
6297
+ ));
6298
+ }
6299
+ }
6300
+ }
6301
+ if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
6302
+ const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
6303
+ const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
6304
+ if (directoryLiteral) {
6305
+ findings.push(finding(
6306
+ "RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
6307
+ `A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
6308
+ path,
6309
+ lineNumber
6310
+ ));
6311
+ }
6312
+ }
6313
+ }
6314
+ }
6315
+ }
6316
+ await visit(resolve7(root));
6317
+ const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
6318
+ return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
6319
+ }
6320
+ function mergeFindings(target, additions) {
6321
+ const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
6322
+ for (const item of additions) {
6323
+ const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
6324
+ if (seen.has(key)) continue;
6325
+ seen.add(key);
6326
+ target.push(item);
6327
+ }
6328
+ }
6329
+ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
6330
+ const results = [];
6331
+ async function visit(directory) {
6332
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6333
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6334
+ const absolute = join10(directory, entry.name);
6335
+ if (entry.isDirectory()) {
6336
+ await visit(absolute);
6337
+ } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
6338
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6339
+ if (excludedPaths.has(path)) continue;
6340
+ const raw = await readFile3(absolute, "utf8");
6341
+ raw.split(/\r?\n/).forEach((line, index) => {
6342
+ for (const reference of references) {
6343
+ if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
6344
+ }
6345
+ });
6346
+ }
6347
+ }
6348
+ }
6349
+ await visit(resolve7(root));
6350
+ return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6351
+ }
6352
+ function expectedRelationTargets(mapping) {
6353
+ return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
6354
+ }
6355
+ function relationTriples(graph) {
6356
+ return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
6357
+ }
6358
+ function formatMode(value) {
6359
+ return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
6360
+ }
6361
+ function isPosixFileMode(value) {
6362
+ return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
6363
+ }
6364
+ function modeIsUsableAtApply(mode, umask) {
6365
+ return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
6366
+ }
6367
+ function createModeForUmask(umask) {
6368
+ return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
6369
+ }
6370
+ function planningUmask() {
6371
+ return process.umask() & MAX_POSIX_MODE;
6372
+ }
6373
+ function restructureBoundaryFindings(operations, limits) {
6374
+ const findings = [];
6375
+ if (operations.length === 0) {
6376
+ findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
6377
+ return findings;
6378
+ }
6379
+ if (operations.length > limits.max_operations) {
6380
+ findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
6381
+ }
6382
+ const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
6383
+ if (totalBytes > limits.max_total_bytes) {
6384
+ findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
6385
+ }
6386
+ const expectedCreateMode = createModeForUmask(limits.umask);
6387
+ const applyModeContract = limits.mode_contract === "apply";
6388
+ for (const operation of operations) {
6389
+ const parent = dirname6(operation.path) || ".";
6390
+ if (!operation.parent_exists) {
6391
+ findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6392
+ } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
6393
+ findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
6394
+ }
6395
+ if (!isPosixFileMode(operation.mode)) {
6396
+ findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
6397
+ }
6398
+ if (!isPosixFileMode(operation.original_mode)) {
6399
+ findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
6400
+ }
6401
+ if (operation.original_exists && operation.original_mode === null) {
6402
+ findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
6403
+ }
6404
+ if (!operation.original_exists && operation.original_mode !== null) {
6405
+ findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
6406
+ }
6407
+ if (applyModeContract) {
6408
+ for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
6409
+ if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
6410
+ findings.push(finding(
6411
+ "MODE_NOT_USABLE",
6412
+ `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}`,
6413
+ operation.path
6414
+ ));
6415
+ }
6416
+ }
6417
+ if (operation.action === "create") {
6418
+ if (operation.original_exists) {
6419
+ findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
6420
+ }
6421
+ if (!applyModeContract && operation.mode !== expectedCreateMode) {
6422
+ findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
6423
+ }
6424
+ } else if (operation.action === "replace") {
6425
+ if (!operation.original_exists) {
6426
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
6427
+ } else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
6428
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
6429
+ }
6430
+ } else if (operation.mode !== null) {
6431
+ findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
6432
+ }
6433
+ }
6434
+ return findings;
6435
+ }
6436
+ async function probeDirectory(absolutePath) {
6437
+ try {
6438
+ const info = await stat(absolutePath);
6439
+ return { exists: info.isDirectory(), device: info.dev };
6440
+ } catch (error) {
6441
+ const code = error.code;
6442
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
6443
+ throw error;
6444
+ }
6445
+ }
6446
+ async function planRestructure(root, input) {
6447
+ const schemaErrors = await validateDomainContract("mapping", input);
6448
+ if (schemaErrors.length > 0) {
6449
+ return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
6450
+ }
6451
+ const mapping = input;
6452
+ const blockers = [];
6453
+ const unresolved = [...mapping.unresolved];
6454
+ const requestErrors = await validateDomainContract("request", mapping.request);
6455
+ if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
6456
+ if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
6457
+ const currentConfig = await configSnapshot(root);
6458
+ if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
6459
+ const schema = await loadConfig(root);
6460
+ const beforeGraph = await scanArtifacts(root, schema);
6461
+ const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
6462
+ const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
6463
+ const seenSourceUids = /* @__PURE__ */ new Set();
6464
+ for (const source of mapping.sources) {
6465
+ const uid = `${source.type}:${source.id}`;
6466
+ if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
6467
+ seenSourceUids.add(uid);
6468
+ 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));
6469
+ }
6470
+ for (const requested of mapping.request.sources) {
6471
+ const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
6472
+ const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
6473
+ if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
6474
+ }
6475
+ for (const source of mapping.sources) {
6476
+ if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
6477
+ blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
6478
+ }
6479
+ }
6480
+ const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
6481
+ const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
6482
+ for (const occurrence of requiredOccurrences) {
6483
+ if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
6484
+ }
6485
+ for (const entry of mapping.relation_map) {
6486
+ 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));
6487
+ }
6488
+ const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
6489
+ const targetKeys = /* @__PURE__ */ new Set();
6490
+ const targetUids = /* @__PURE__ */ new Set();
6491
+ for (const target of mapping.targets) {
6492
+ const path = normalizeRelativePath2(target.path);
6493
+ if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
6494
+ if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
6495
+ targetKeys.add(target.key);
6496
+ 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));
6497
+ const uid = `${target.type}:${target.id}`;
6498
+ if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
6499
+ targetUids.add(uid);
6500
+ if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
6501
+ blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
6502
+ }
6503
+ 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));
6504
+ if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
6505
+ }
6506
+ for (const identity of mapping.identity_map) {
6507
+ 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}`));
6508
+ }
6509
+ for (const source of mapping.sources) {
6510
+ const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
6511
+ 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));
6512
+ 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));
6513
+ }
6514
+ const snapshots = /* @__PURE__ */ new Map();
6515
+ const buffers = /* @__PURE__ */ new Map();
6516
+ for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
6517
+ const normalized = normalizeRelativePath2(expected.path);
6518
+ if (!normalized) {
6519
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6520
+ continue;
6521
+ }
6522
+ if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
6523
+ blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
6524
+ continue;
6525
+ }
6526
+ const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
6527
+ if (actual) snapshots.set(normalized, actual);
6528
+ const raw = await readContainedFile(root, normalized);
6529
+ if (raw) buffers.set(normalized, raw);
6530
+ }
6531
+ snapshots.set(currentConfig.path, currentConfig);
6532
+ const declaredSnapshots = [
6533
+ mapping.config_snapshot,
6534
+ ...mapping.sources.map((source) => source.snapshot),
6535
+ ...mapping.targets.map((target) => target.snapshot)
6536
+ ];
6537
+ const checkedDeclaredModes = /* @__PURE__ */ new Set();
6538
+ for (const declared of declaredSnapshots) {
6539
+ const declaredMode = declared.mode ?? null;
6540
+ const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
6541
+ const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
6542
+ if (checkedDeclaredModes.has(key)) continue;
6543
+ checkedDeclaredModes.add(key);
6544
+ if (!isPosixFileMode(declaredMode)) {
6545
+ blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
6546
+ } else if (declared.exists && declaredMode === null) {
6547
+ blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
6548
+ } else if (!declared.exists && declaredMode !== null) {
6549
+ blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
6550
+ }
6551
+ }
6552
+ const moveIds = /* @__PURE__ */ new Set();
6553
+ const rangesByPath = /* @__PURE__ */ new Map();
6554
+ const fragments = /* @__PURE__ */ new Map();
6555
+ for (const move of mapping.content_moves) {
6556
+ if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
6557
+ moveIds.add(move.id);
6558
+ const sourcePath = normalizeRelativePath2(move.source.path);
6559
+ const targetPath = normalizeRelativePath2(move.target.path);
6560
+ if (!sourcePath || !buffers.has(sourcePath)) {
6561
+ blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
6562
+ continue;
6563
+ }
6564
+ if (!targetPath || !isPathAllowed(targetPath, allowed)) {
6565
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
6566
+ continue;
6567
+ }
6568
+ const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
6569
+ if (!fragment) continue;
6570
+ fragments.set(move.id, fragment);
6571
+ const pathMoves = rangesByPath.get(sourcePath) ?? [];
6572
+ for (const existing of pathMoves) {
6573
+ if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
6574
+ 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;
6575
+ if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
6576
+ }
6577
+ }
6578
+ pathMoves.push(move);
6579
+ rangesByPath.set(sourcePath, pathMoves);
6580
+ if (dirname6(sourcePath) !== dirname6(targetPath)) {
6581
+ for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6582
+ const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6583
+ if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
6584
+ }
6585
+ }
6586
+ }
6587
+ for (const source of mapping.sources) {
6588
+ const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
6589
+ const raw = buffers.get(source.path);
6590
+ if (!node || !raw) continue;
6591
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
6592
+ blockers.push(...boundary.blockers);
6593
+ 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));
6594
+ if (source.type === "feature" && source.disposition === "retired") {
6595
+ const criteria = acceptanceCriteria(node);
6596
+ const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
6597
+ 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));
6598
+ }
6599
+ }
6600
+ const candidateBuffers = /* @__PURE__ */ new Map();
6601
+ const touched = /* @__PURE__ */ new Set();
6602
+ for (const [sourcePath, moves] of rangesByPath) {
6603
+ const original = buffers.get(sourcePath);
6604
+ const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
6605
+ const chunks = [];
6606
+ let cursor = 0;
6607
+ for (const move of removals) {
6608
+ chunks.push(original.subarray(cursor, move.source.start_byte));
6609
+ cursor = move.source.end_byte;
6610
+ }
6611
+ chunks.push(original.subarray(cursor));
6612
+ candidateBuffers.set(sourcePath, Buffer.concat(chunks));
6613
+ touched.add(sourcePath);
6614
+ }
6615
+ const movesByTarget = /* @__PURE__ */ new Map();
6616
+ for (const move of mapping.content_moves) {
6617
+ const targetPath = normalizeRelativePath2(move.target.path);
6618
+ if (!targetPath || !fragments.has(move.id)) continue;
6619
+ const list = movesByTarget.get(targetPath) ?? [];
6620
+ list.push(move);
6621
+ movesByTarget.set(targetPath, list);
6622
+ }
6623
+ for (const [targetPath, moves] of movesByTarget) {
6624
+ const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
6625
+ const appended = [base];
6626
+ for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
6627
+ const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
6628
+ appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
6629
+ }
6630
+ candidateBuffers.set(targetPath, Buffer.concat(appended));
6631
+ touched.add(targetPath);
6632
+ if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
6633
+ }
6634
+ for (const header of mapping.file_headers) {
6635
+ const path = normalizeRelativePath2(header.path);
6636
+ if (!path || !isPathAllowed(path, allowed)) {
6637
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
6638
+ continue;
6639
+ }
6640
+ if (header.affected_records.length === 0 && header.content === "") {
6641
+ const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
6642
+ if (unselected.length > 0) {
6643
+ blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
6644
+ } else {
6645
+ candidateBuffers.set(path, Buffer.alloc(0));
6646
+ touched.add(path);
6647
+ }
6648
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6649
+ continue;
6650
+ }
6651
+ const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6652
+ candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
6653
+ touched.add(path);
6654
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6655
+ }
6656
+ for (const edit of mapping.prose_edits) {
6657
+ const path = normalizeRelativePath2(edit.target_path);
6658
+ const sourcePath = normalizeRelativePath2(edit.source.path);
6659
+ if (!path || !sourcePath || !buffers.has(sourcePath)) {
6660
+ blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
6661
+ continue;
6662
+ }
6663
+ if (!isPathAllowed(path, allowed)) {
6664
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
6665
+ continue;
6666
+ }
6667
+ if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
6668
+ const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6669
+ const occurrences = current.split(edit.old_text).length - 1;
6670
+ if (!edit.old_text || occurrences !== 1) {
6671
+ blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
6672
+ continue;
6673
+ }
6674
+ candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
6675
+ touched.add(path);
6676
+ }
6677
+ const candidates = [];
6678
+ const umask = planningUmask();
6679
+ for (const path of [...touched].sort()) {
6680
+ if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
6681
+ const original = buffers.get(path);
6682
+ const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
6683
+ if (original && original.equals(candidate)) continue;
6684
+ const deleteFile = candidate.byteLength === 0;
6685
+ const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
6686
+ const action = deleteFile ? "delete" : original ? "replace" : "create";
6687
+ candidates.push({
6688
+ path,
6689
+ action,
6690
+ content: deleteFile ? null : candidate.toString("utf8"),
6691
+ sha256: deleteFile ? null : digestBytes(candidate),
6692
+ mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
6693
+ original: snapshot,
6694
+ diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6695
+ });
6696
+ }
6697
+ const rootDirectory = await probeDirectory(resolve7(root));
6698
+ const parentProbes = /* @__PURE__ */ new Map();
6699
+ for (const candidate of candidates) {
6700
+ const parent = dirname6(candidate.path);
6701
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve7(root, parent)));
6702
+ }
6703
+ blockers.push(...restructureBoundaryFindings(
6704
+ candidates.map((candidate) => {
6705
+ const parent = parentProbes.get(dirname6(candidate.path));
6706
+ return {
6707
+ path: candidate.path,
6708
+ action: candidate.action,
6709
+ original_exists: candidate.original.exists,
6710
+ original_mode: candidate.original.mode,
6711
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6712
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6713
+ mode: candidate.mode,
6714
+ parent_exists: parent.exists,
6715
+ parent_device: parent.device,
6716
+ root_device: rootDirectory.device ?? -1
6717
+ };
6718
+ }),
6719
+ {
6720
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6721
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6722
+ umask
6723
+ }
6724
+ ));
6725
+ const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
6726
+ const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
6727
+ const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
6728
+ const candidateIssues = validateGraph(afterGraph, schema);
6729
+ for (const issue2 of candidateIssues) {
6730
+ if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
6731
+ }
6732
+ const afterTriples = relationTriples(afterGraph);
6733
+ for (const expected of expectedRelationTargets(mapping)) {
6734
+ if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
6735
+ }
6736
+ for (const source of mapping.sources) {
6737
+ const uid = `${source.type}:${source.id}`;
6738
+ const present = afterGraph.nodes.some((node) => node.uid === uid);
6739
+ if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
6740
+ if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
6741
+ }
6742
+ for (const criterion of mapping.criterion_map) {
6743
+ const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
6744
+ 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));
6745
+ for (const target of criterion.targets) {
6746
+ const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
6747
+ 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));
6748
+ }
6749
+ }
6750
+ for (const header of mapping.file_headers) {
6751
+ const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
6752
+ const declaredRecords = [...header.affected_records].sort();
6753
+ 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));
6754
+ }
6755
+ const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
6756
+ for (const move of mapping.content_moves) {
6757
+ if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
6758
+ for (const path of [move.source.path, move.target.path]) {
6759
+ 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));
6760
+ }
6761
+ }
6762
+ for (const target of mapping.targets) {
6763
+ 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));
6764
+ }
6765
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6766
+ root,
6767
+ [...new Set(mapping.sources.map((source) => source.path))],
6768
+ [...new Set([
6769
+ ...mapping.targets.map((target) => target.path),
6770
+ ...mapping.content_moves.map((move) => move.target.path),
6771
+ ...mapping.file_headers.map((header) => header.path)
6772
+ ].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
6773
+ ));
6774
+ for (const move of mapping.content_moves) {
6775
+ const fragment = fragments.get(move.id);
6776
+ const sourcePath = normalizeRelativePath2(move.source.path);
6777
+ const targetPath = normalizeRelativePath2(move.target.path);
6778
+ if (!fragment || !sourcePath || !targetPath) continue;
6779
+ const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
6780
+ const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
6781
+ for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
6782
+ if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
6783
+ blockers.push(finding(
6784
+ "FOOTNOTE_DEFINITION_UNMAPPED",
6785
+ `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`,
6786
+ sourcePath
6787
+ ));
6788
+ }
6789
+ }
6790
+ const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
6791
+ const plan = {
6792
+ schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
6793
+ operation_id: randomUUID2(),
6794
+ validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6795
+ request_digest: mapping.request_digest,
6796
+ mapping_digest: digestRestructureValue(mapping),
6797
+ config_snapshot: currentConfig,
6798
+ input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
6799
+ candidates,
6800
+ graph_diff: graphDiff(beforeGraph, afterGraph),
6801
+ validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
6802
+ applicable: blockers.length === 0 && unresolved.length === 0
6803
+ };
6804
+ const planErrors = await validateDomainContract("plan", plan);
6805
+ if (planErrors.length > 0) {
6806
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
6807
+ }
6808
+ return { ok: true, data: plan };
6809
+ }
6810
+ async function gateRestructureOperationPlan(operation, plan) {
6811
+ const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
6812
+ if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
6813
+ return {
6814
+ ok: false,
6815
+ error: {
6816
+ code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
6817
+ message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
6818
+ }
6819
+ };
6820
+ }
6821
+ const errors = await validateDomainContract("plan", plan);
6822
+ if (errors.length > 0) {
6823
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
6824
+ }
6825
+ return { ok: true, data: plan };
6826
+ }
6827
+ function refusal(code, message, findings = []) {
6828
+ return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
6829
+ }
6830
+ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6831
+ const absolute = resolve7(planPath);
6832
+ let info;
6833
+ try {
6834
+ info = await lstat3(absolute);
6835
+ } catch (cause) {
6836
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6837
+ }
6838
+ if (info.isSymbolicLink() || !info.isFile()) {
6839
+ return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
6840
+ }
6841
+ let bytes;
6842
+ try {
6843
+ bytes = await readFile3(absolute);
6844
+ } catch (cause) {
6845
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
6846
+ }
6847
+ let parsed;
6848
+ try {
6849
+ parsed = JSON.parse(bytes.toString("utf8"));
6850
+ } catch (cause) {
6851
+ return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
6852
+ }
6853
+ const gate = await gateRestructureOperationPlan(operation, parsed);
6854
+ if (!gate.ok) return gate;
6855
+ return { ok: true, data: { path: absolute, realPath: await realpath2(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
6856
+ }
6857
+ function planRootIdentityFindings(document) {
6858
+ const findings = [];
6859
+ const record = (path, label) => {
6860
+ const normalized = normalizeRelativePath2(path);
6861
+ if (!normalized || normalized !== path) {
6862
+ findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
6863
+ }
6864
+ };
6865
+ record(document.plan.config_snapshot.path, "config_snapshot");
6866
+ for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
6867
+ for (const candidate of document.plan.candidates) {
6868
+ record(candidate.path, "candidate");
6869
+ record(candidate.original.path, "candidate original");
6870
+ }
6871
+ if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
6872
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6873
+ }
6874
+ const relativePlan = relative4(document.root, document.realPath);
6875
+ if (!relativePlan || relativePlan.startsWith("..") || isAbsolute5(relativePlan)) {
6876
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6877
+ }
6878
+ return findings;
6879
+ }
6880
+ async function operationBoundaries(root, plan) {
6881
+ const rootDirectory = await probeDirectory(resolve7(root));
6882
+ const parents = /* @__PURE__ */ new Map();
6883
+ const boundaries = [];
6884
+ for (const candidate of plan.candidates) {
6885
+ const parent = dirname6(candidate.path) || ".";
6886
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve7(root, parent)));
6887
+ const probe = parents.get(parent);
6888
+ boundaries.push({
6889
+ path: candidate.path,
6890
+ action: candidate.action,
6891
+ original_exists: candidate.original.exists,
6892
+ original_mode: candidate.original.mode,
6893
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6894
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6895
+ mode: candidate.mode,
6896
+ parent_exists: probe.exists,
6897
+ parent_device: probe.device,
6898
+ root_device: rootDirectory.device ?? -1
6899
+ });
6900
+ }
6901
+ return boundaries;
6902
+ }
6903
+ async function applyPreconditionFindings(root, document) {
6904
+ const findings = [];
6905
+ const plan = document.plan;
6906
+ const currentConfig = await configSnapshot(root);
6907
+ if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
6908
+ findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
6909
+ }
6910
+ for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
6911
+ const relativePlan = relative4(root, document.realPath).replace(/\\/g, "/");
6912
+ for (const candidate of plan.candidates) {
6913
+ if (candidate.path === relativePlan) {
6914
+ findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
6915
+ }
6916
+ if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
6917
+ findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
6918
+ }
6919
+ let original;
6920
+ try {
6921
+ original = await snapshotFile(root, candidate.path);
6922
+ } catch (cause) {
6923
+ findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
6924
+ continue;
6925
+ }
6926
+ if (!sameSnapshot(original, candidate.original)) {
6927
+ findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
6928
+ }
6929
+ if (candidate.action === "delete") continue;
6930
+ if (candidate.mode === null) {
6931
+ findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
6932
+ }
6933
+ if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
6934
+ findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
6935
+ }
6936
+ }
6937
+ findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
6938
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6939
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6940
+ umask: planningUmask(),
6941
+ mode_contract: "apply"
6942
+ }));
6943
+ return findings;
6944
+ }
6945
+ function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
6946
+ const excludedConsumers = new Set(excludedConsumerPaths);
6947
+ const addedNodes = plan.graph_diff.added_nodes;
6948
+ const removedNodes = new Set(plan.graph_diff.removed_nodes);
6949
+ const addedEdges = plan.graph_diff.added_edges;
6950
+ const removedEdges = new Set(plan.graph_diff.removed_edges);
6951
+ const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
6952
+ const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
6953
+ const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
6954
+ return async function validateCandidateState(input) {
6955
+ const schema = await loadConfig(input.root);
6956
+ const graph = await scanArtifacts(input.root, schema);
6957
+ if (input.signal.aborted) return { passed: false };
6958
+ const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6959
+ const edges = new Set(graph.edges.map(edgeDisplay));
6960
+ const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
6961
+ const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
6962
+ const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
6963
+ const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
6964
+ const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
6965
+ const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
6966
+ return { passed };
6967
+ };
6968
+ }
6969
+ async function applyRestructure(input) {
6970
+ if (input.confirmCooperativeWriters !== true) {
6971
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
6972
+ }
6973
+ const qualification = await qualifyRestructureMechanism(input.root);
6974
+ if (!qualification.ok) return qualification;
6975
+ const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
6976
+ if (!document.ok) return document;
6977
+ const plan = document.data.plan;
6978
+ if (plan.candidates.length === 0) {
6979
+ return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
6980
+ }
6981
+ if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
6982
+ return refusal(
6983
+ "PLAN_NOT_APPLICABLE",
6984
+ "The plan is not applicable: it still carries blockers or unresolved findings",
6985
+ [...plan.validation.blockers, ...plan.validation.unresolved]
6986
+ );
6987
+ }
6988
+ const identity = planRootIdentityFindings(document.data);
6989
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
6990
+ const drift = await applyPreconditionFindings(qualification.data.root, document.data);
6991
+ if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
6992
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
6993
+ if (!mechanismRoot.ok) return mechanismRoot;
6994
+ const planRelPath = relative4(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
6995
+ const applied = await applyRestructureFileSet(qualification.data.root, plan, {
6996
+ validate: createRestructureValidationCallback(plan, [planRelPath])
6997
+ });
6998
+ if (!applied.ok) return applied;
6999
+ const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
7000
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7001
+ }
7002
+ async function recoverRestructure(input) {
7003
+ if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
7004
+ return refusal(
7005
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7006
+ "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
7007
+ );
7008
+ }
7009
+ const qualification = await qualifyRestructureMechanism(input.root);
7010
+ if (!qualification.ok) return qualification;
7011
+ const document = await loadRestructurePlanDocument("recover", qualification.data.root, input.planPath);
7012
+ if (!document.ok) return document;
7013
+ const identity = planRootIdentityFindings(document.data);
7014
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7015
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7016
+ if (!mechanismRoot.ok) return mechanismRoot;
7017
+ const recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
7018
+ allParticipantsStopped: true,
7019
+ exclusiveMaintenance: true
7020
+ });
7021
+ if (!recovered.ok) return recovered;
7022
+ const projection = projectRestructureFileSetResult(recovered.data, document.data.realPath, document.data.digest);
7023
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7024
+ }
7025
+ async function pruneRestructureRecovery(input) {
7026
+ if (input.confirmCooperativeWriters !== true) {
7027
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
7028
+ }
7029
+ if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
7030
+ return refusal(
7031
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7032
+ "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
7033
+ );
7034
+ }
7035
+ const qualification = await qualifyRestructureMechanism(input.root);
7036
+ if (!qualification.ok) return qualification;
7037
+ const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
7038
+ if (!document.ok) return document;
7039
+ const identity = planRootIdentityFindings(document.data);
7040
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7041
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7042
+ if (!mechanismRoot.ok) return mechanismRoot;
7043
+ const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
7044
+ allParticipantsStopped: input.allParticipantsStopped,
7045
+ exclusiveMaintenance: input.exclusiveMaintenance
7046
+ });
7047
+ if (!pruned.ok) return pruned;
7048
+ const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
7049
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7050
+ }
7051
+ var RESTRUCTURE_PLAN_SCHEMA_VERSION, RESTRUCTURE_VALIDATION_TIMEOUT_MS, RESTRUCTURE_MAX_OPERATIONS, RESTRUCTURE_MAX_TOTAL_BYTES, MAX_POSIX_MODE, CREATE_MODE_BASE, MODULE_DIRECTORY, CONTRACT_ROOT, SKIPPED_SCAN_DIRS, TEXT_EXTENSIONS, MARKDOWN_LINK_PATTERN, RUNTIME_PATH_MARKER, MARKDOWN_FILE_SUFFIX, SCRIPT_FILE_SUFFIX;
7052
+ var init_restructure = __esm({
7053
+ "src/restructure.ts"() {
7054
+ "use strict";
7055
+ init_index();
7056
+ init_contract_kernel();
7057
+ init_restructure_software();
7058
+ init_restructure_file_set();
7059
+ RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
7060
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
7061
+ RESTRUCTURE_MAX_OPERATIONS = 1024;
7062
+ RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
7063
+ MAX_POSIX_MODE = 511;
7064
+ CREATE_MODE_BASE = 438;
7065
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname6(fileURLToPath2(import.meta.url));
7066
+ CONTRACT_ROOT = join10(MODULE_DIRECTORY, "..", "contracts");
7067
+ SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
7068
+ TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
7069
+ MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
7070
+ RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
7071
+ MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
7072
+ SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
7073
+ }
7074
+ });
7075
+
4996
7076
  // src/index.ts
4997
7077
  import matter from "gray-matter";
4998
7078
  import yaml from "js-yaml";
4999
7079
  import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
5000
- import { mkdir as mkdir4, readFile as readFile3, readdir as readdir3, writeFile as writeFile3 } from "fs/promises";
5001
- import { basename as basename4, dirname as dirname5, extname, isAbsolute as isAbsolute4, join as join8, relative as relative4, resolve as resolve5 } from "path";
7080
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
7081
+ import { basename as basename5, dirname as dirname7, extname, isAbsolute as isAbsolute6, join as join11, resolve as resolve8 } from "path";
5002
7082
  function isTargetArtifactType(type) {
5003
7083
  return isPacketTargetType(type);
5004
7084
  }
@@ -5040,10 +7120,10 @@ function resolveArtifactTypeName(schema, token) {
5040
7120
  return void 0;
5041
7121
  }
5042
7122
  async function loadConfig(root) {
5043
- const configPath = join8(root, "artifact-graph.config.yaml");
7123
+ const configPath = join11(root, "artifact-graph.config.yaml");
5044
7124
  let parsed = {};
5045
7125
  try {
5046
- const raw = await readFile3(configPath, "utf-8");
7126
+ const raw = await readFile4(configPath, "utf-8");
5047
7127
  parsed = yaml.load(raw) ?? {};
5048
7128
  } catch (error) {
5049
7129
  if (error.code !== "ENOENT") {
@@ -5084,8 +7164,31 @@ async function loadConfig(root) {
5084
7164
  idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
5085
7165
  e2e: mergedE2e
5086
7166
  };
7167
+ validateJsonArtifactTypes(merged.types);
5087
7168
  return merged;
5088
7169
  }
7170
+ function validateJsonArtifactTypes(types) {
7171
+ for (const [type, definition] of Object.entries(types)) {
7172
+ const raw = definition;
7173
+ const format = raw.format;
7174
+ const idField = raw.idField;
7175
+ if (format === void 0) {
7176
+ if (idField !== void 0) {
7177
+ throw new Error(`Invalid types.${type}.idField: idField requires format json.`);
7178
+ }
7179
+ continue;
7180
+ }
7181
+ if (format !== "json") {
7182
+ throw new Error(`Invalid types.${type}.format: only json is supported. Omit format to keep Markdown parsing.`);
7183
+ }
7184
+ if (SPECIALIZED_PARSER_TYPES.has(type)) {
7185
+ throw new Error(`Invalid types.${type}.format: JSON format applies only to custom types. ${type} keeps its dedicated parser.`);
7186
+ }
7187
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
7188
+ throw new Error(`Invalid types.${type}.idField: format json requires the name of one root property.`);
7189
+ }
7190
+ }
7191
+ }
5089
7192
  function validateRelationSemanticsConfig(value) {
5090
7193
  if (value === void 0) return;
5091
7194
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -5169,7 +7272,7 @@ function validateE2eConfig(e2e) {
5169
7272
  if (typeof runner.root !== "string" || !runner.root.trim()) {
5170
7273
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
5171
7274
  }
5172
- if (isAbsolute4(runner.root)) {
7275
+ if (isAbsolute6(runner.root)) {
5173
7276
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
5174
7277
  }
5175
7278
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -5232,14 +7335,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
5232
7335
  diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
5233
7336
  };
5234
7337
  }
5235
- async function scanArtifacts(root, schema) {
7338
+ async function scanArtifacts(root, schema, options = {}) {
5236
7339
  const config = schema ?? await loadConfig(root);
5237
7340
  const nodes = [];
5238
7341
  const edges = [];
5239
7342
  const scanDiagnostics = [];
5240
7343
  const scannedFiles = /* @__PURE__ */ new Map();
7344
+ const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
5241
7345
  for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
5242
- const files = await findFiles(root, definition.paths);
7346
+ const diskFiles = await findFiles(root, definition.paths);
7347
+ const files = [.../* @__PURE__ */ new Set([
7348
+ ...diskFiles.filter((file) => contentOverrides.get(file) !== null),
7349
+ ...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
7350
+ ])].sort();
5243
7351
  for (const file of files) {
5244
7352
  if (scannedFiles.has(file)) {
5245
7353
  const existingType = scannedFiles.get(file);
@@ -5253,15 +7361,15 @@ async function scanArtifacts(root, schema) {
5253
7361
  continue;
5254
7362
  }
5255
7363
  scannedFiles.set(file, type);
5256
- const raw = await readFile3(join8(root, file), "utf-8");
7364
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join11(root, file), "utf-8");
5257
7365
  const parsed = parseFile(type, file, raw, config);
5258
- const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7366
+ const semantic = isJsonOriginalType(type, config) ? { edges: [], diagnostics: [] } : parseConfiguredRelations(type, file, raw, parsed.nodes, config);
5259
7367
  nodes.push(...parsed.nodes);
5260
7368
  edges.push(...parsed.edges, ...semantic.edges);
5261
7369
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
5262
7370
  }
5263
7371
  }
5264
- const absoluteRoot = isAbsolute4(root) ? root : resolve5(root);
7372
+ const absoluteRoot = isAbsolute6(root) ? root : resolve8(root);
5265
7373
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
5266
7374
  return resolveMatrixEdges(graph);
5267
7375
  }
@@ -5466,33 +7574,6 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5466
7574
  issues.push(issue("CYCLE_DETECTED", `depends_on cycle detected: ${cycle.join(" -> ")}`, "", 1, { node: cycle[0] }));
5467
7575
  }
5468
7576
  const defaultTypeKeys = new Set(Object.keys(DEFAULT_SCHEMA.types));
5469
- const specializedParserTypes = /* @__PURE__ */ new Set([
5470
- "feature",
5471
- "scenario",
5472
- "entity",
5473
- "decision",
5474
- "test",
5475
- "design",
5476
- "e2e_test",
5477
- "e2e_registry",
5478
- "rule-golden-cases",
5479
- "test-strategy",
5480
- "traceability-matrix-v2",
5481
- "traceability-version-lock",
5482
- "interface_contracts",
5483
- "data_contracts",
5484
- "application_state_machines",
5485
- "error_model",
5486
- "domain-glossary",
5487
- "bounded-context-map",
5488
- "domain-invariants",
5489
- "generation-packet-spec",
5490
- "report-contracts",
5491
- "verification-fixtures",
5492
- "ui-flow-contracts",
5493
- "non-functional-budgets",
5494
- "implementation-blueprint"
5495
- ]);
5496
7577
  const uidsWithEdges = /* @__PURE__ */ new Set();
5497
7578
  for (const edge2 of graph.edges) {
5498
7579
  uidsWithEdges.add(edge2.from);
@@ -5500,7 +7581,7 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5500
7581
  }
5501
7582
  for (const node of graph.nodes) {
5502
7583
  if (defaultTypeKeys.has(node.type)) continue;
5503
- if (specializedParserTypes.has(node.type)) continue;
7584
+ if (SPECIALIZED_PARSER_TYPES.has(node.type)) continue;
5504
7585
  if (!schema.types[node.type]) continue;
5505
7586
  if (!uidsWithEdges.has(node.uid)) {
5506
7587
  issues.push(issue(
@@ -5547,13 +7628,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
5547
7628
  const scenarioFeatureRefs = /* @__PURE__ */ new Map();
5548
7629
  const featureScenarioRefs = /* @__PURE__ */ new Map();
5549
7630
  for (const node of scenarioNodes) {
5550
- scenarioFeatureRefs.set(node.uid, relationOccurrences(node, "\u5173\u8054\u529F\u80FD", "feature"));
7631
+ scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
5551
7632
  if (!scenarioPattern.test(node.code)) {
5552
7633
  issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
5553
7634
  }
5554
7635
  }
5555
7636
  for (const node of featureNodes) {
5556
- featureScenarioRefs.set(node.uid, relationOccurrences(node, "scenarios", "scenario"));
7637
+ featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
5557
7638
  if (!featurePattern.test(node.code)) {
5558
7639
  issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
5559
7640
  }
@@ -5627,7 +7708,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5627
7708
  const indexPath = "artifacts/prd/feature-index.md";
5628
7709
  let raw = "";
5629
7710
  try {
5630
- raw = await readFile3(join8(root, indexPath), "utf-8");
7711
+ raw = await readFile4(join11(root, indexPath), "utf-8");
5631
7712
  } catch (error) {
5632
7713
  if (error.code === "ENOENT") {
5633
7714
  return [];
@@ -5647,7 +7728,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5647
7728
  if (!feature) {
5648
7729
  return;
5649
7730
  }
5650
- const actualCount = relationOccurrences(feature, "scenarios", "scenario").length;
7731
+ const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
5651
7732
  if (actualCount !== expectedCount) {
5652
7733
  issues.push(issue(
5653
7734
  "INDEX_MISMATCH",
@@ -5875,12 +7956,12 @@ function nextId(graph, schema, type, rangeName) {
5875
7956
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
5876
7957
  }
5877
7958
  async function writeGraphCache(root, graph) {
5878
- const cacheDir = join8(root, ".artifact-graph");
5879
- await mkdir4(cacheDir, { recursive: true });
5880
- await writeFile3(join8(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
7959
+ const cacheDir = join11(root, ".artifact-graph");
7960
+ await mkdir5(cacheDir, { recursive: true });
7961
+ await writeFile3(join11(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
5881
7962
  `);
5882
7963
  const { default: Database } = await import("better-sqlite3");
5883
- const db = new Database(join8(cacheDir, "graph.sqlite"));
7964
+ const db = new Database(join11(cacheDir, "graph.sqlite"));
5884
7965
  try {
5885
7966
  db.exec(`
5886
7967
  DROP TABLE IF EXISTS nodes;
@@ -5921,7 +8002,13 @@ async function writeGraphCache(root, graph) {
5921
8002
  db.close();
5922
8003
  }
5923
8004
  }
8005
+ function isJsonOriginalType(type, schema) {
8006
+ return schema.types[type]?.format === "json" && !SPECIALIZED_PARSER_TYPES.has(type);
8007
+ }
5924
8008
  function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
8009
+ if (isJsonOriginalType(type, schema)) {
8010
+ return parseGenericJson(type, path, raw, schema);
8011
+ }
5925
8012
  if (type === "feature") {
5926
8013
  return { ...parseFeature(path, raw), diagnostics: [] };
5927
8014
  }
@@ -5990,6 +8077,184 @@ function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
5990
8077
  }
5991
8078
  return parseGenericMarkdown(type, path, raw, schema);
5992
8079
  }
8080
+ function isJsonObject(value) {
8081
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8082
+ }
8083
+ function jsonRootKind(value) {
8084
+ if (Array.isArray(value)) return "array";
8085
+ if (value === null) return "null";
8086
+ return typeof value;
8087
+ }
8088
+ function parseGenericJson(type, path, raw, schema) {
8089
+ const diagnostics = [];
8090
+ const idField = schema.types[type]?.idField;
8091
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
8092
+ diagnostics.push(issue(
8093
+ "INVALID_JSON",
8094
+ `types.${type}.idField must name one root property when format is json`,
8095
+ path,
8096
+ 1
8097
+ ));
8098
+ return { nodes: [], edges: [], diagnostics };
8099
+ }
8100
+ let parsed;
8101
+ try {
8102
+ parsed = JSON.parse(raw);
8103
+ } catch (error) {
8104
+ diagnostics.push(issue(
8105
+ "INVALID_JSON",
8106
+ `JSON artifact ${path} is not valid JSON: ${error.message}`,
8107
+ path,
8108
+ 1
8109
+ ));
8110
+ return { nodes: [], edges: [], diagnostics };
8111
+ }
8112
+ if (!isJsonObject(parsed)) {
8113
+ diagnostics.push(issue(
8114
+ "INVALID_JSON_ROOT",
8115
+ `JSON artifact ${path} must be one root object, got ${jsonRootKind(parsed)}`,
8116
+ path,
8117
+ 1
8118
+ ));
8119
+ return { nodes: [], edges: [], diagnostics };
8120
+ }
8121
+ if (!Object.prototype.hasOwnProperty.call(parsed, idField)) {
8122
+ diagnostics.push(issue(
8123
+ "ARTIFACT_ID_MISSING",
8124
+ `Artifact of type ${type} at ${path} has no root property ${idField}`,
8125
+ path,
8126
+ 1,
8127
+ { severity: "warning" }
8128
+ ));
8129
+ return { nodes: [], edges: [], diagnostics };
8130
+ }
8131
+ const idValue = parsed[idField];
8132
+ if (typeof idValue !== "string") {
8133
+ diagnostics.push(issue(
8134
+ "INVALID_ID",
8135
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8136
+ path,
8137
+ 1
8138
+ ));
8139
+ return { nodes: [], edges: [], diagnostics };
8140
+ }
8141
+ if (idValue.trim() === "") {
8142
+ diagnostics.push(issue(
8143
+ "ARTIFACT_ID_MISSING",
8144
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8145
+ path,
8146
+ 1,
8147
+ { severity: "warning" }
8148
+ ));
8149
+ return { nodes: [], edges: [], diagnostics };
8150
+ }
8151
+ const code = idValue;
8152
+ const idPattern = schema.idPatterns[type];
8153
+ if (idPattern && !new RegExp(idPattern).test(code)) {
8154
+ diagnostics.push(issue(
8155
+ "INVALID_ID",
8156
+ `Artifact ${type}:${code} field ${idField} does not match ${idPattern}`,
8157
+ path,
8158
+ 1,
8159
+ { node: toUid(type, code) }
8160
+ ));
8161
+ }
8162
+ const node = {
8163
+ type,
8164
+ code,
8165
+ title: code,
8166
+ path,
8167
+ line: 1
8168
+ };
8169
+ const relations = jsonConfiguredRelations(type, path, parsed, schema, toUid(type, code));
8170
+ diagnostics.push(...relations.diagnostics);
8171
+ return { nodes: [node], edges: relations.edges, diagnostics };
8172
+ }
8173
+ function readJsonRelation(record, field) {
8174
+ const segments = field.split(".");
8175
+ if (segments.some((segment) => segment.length === 0)) {
8176
+ return { status: "illegal-path" };
8177
+ }
8178
+ let current = record;
8179
+ for (let index = 0; index < segments.length; index += 1) {
8180
+ const key = segments[index] ?? "";
8181
+ if (!isJsonObject(current)) {
8182
+ return { status: "type-error", at: segments.slice(0, index).join(".") };
8183
+ }
8184
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
8185
+ return { status: "absent" };
8186
+ }
8187
+ const next = current[key];
8188
+ const last = index === segments.length - 1;
8189
+ if (!last && !isJsonObject(next)) {
8190
+ return { status: "type-error", at: segments.slice(0, index + 1).join(".") };
8191
+ }
8192
+ current = next;
8193
+ }
8194
+ return { status: "value", value: current };
8195
+ }
8196
+ function jsonRelationTerminal(value, field, path, sourceUid, diagnostics) {
8197
+ const message = `Relation field ${field} in ${path} must be a non-empty string or an array of non-empty strings`;
8198
+ if (typeof value === "string") {
8199
+ if (value.trim() === "") {
8200
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8201
+ return [];
8202
+ }
8203
+ return [value];
8204
+ }
8205
+ if (Array.isArray(value)) {
8206
+ const refs = [];
8207
+ for (const item of value) {
8208
+ if (typeof item !== "string" || item.trim() === "") {
8209
+ diagnostics.push(issue(
8210
+ "RELATION_VALUE_TYPE",
8211
+ `Relation field ${field} in ${path} must contain only non-empty strings`,
8212
+ path,
8213
+ 1,
8214
+ { node: sourceUid }
8215
+ ));
8216
+ continue;
8217
+ }
8218
+ refs.push(item);
8219
+ }
8220
+ return refs;
8221
+ }
8222
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8223
+ return [];
8224
+ }
8225
+ function jsonConfiguredRelations(type, path, record, schema, sourceUid) {
8226
+ const edges = [];
8227
+ const diagnostics = [];
8228
+ for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
8229
+ for (const field of spec.fields) {
8230
+ const read = readJsonRelation(record, field);
8231
+ if (read.status === "absent") continue;
8232
+ if (read.status === "illegal-path") {
8233
+ diagnostics.push(issue(
8234
+ "INVALID_RELATION_FIELD",
8235
+ `Relation field ${field} is not a fixed path of own properties`,
8236
+ path,
8237
+ 1,
8238
+ { node: sourceUid }
8239
+ ));
8240
+ continue;
8241
+ }
8242
+ if (read.status === "type-error") {
8243
+ diagnostics.push(issue(
8244
+ "RELATION_VALUE_TYPE",
8245
+ `Relation field ${field} in ${path} cannot be read at ${read.at}: expected an object`,
8246
+ path,
8247
+ 1,
8248
+ { node: sourceUid }
8249
+ ));
8250
+ continue;
8251
+ }
8252
+ const values = jsonRelationTerminal(read.value, field, path, sourceUid, diagnostics);
8253
+ appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, "json", edges, diagnostics);
8254
+ }
8255
+ }
8256
+ return { edges, diagnostics };
8257
+ }
5993
8258
  function parseGenericMarkdown(type, path, raw, schema) {
5994
8259
  const diagnostics = [];
5995
8260
  const ext = extname(path).toLowerCase();
@@ -6108,38 +8373,18 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6108
8373
  const diagnostics = [];
6109
8374
  for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
6110
8375
  for (const field of spec.fields) {
6111
- for (const value of toArray(data[field])) {
6112
- const parsed = parseConfiguredRelationTarget(value, spec, schema);
6113
- if (!parsed?.code) continue;
6114
- const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
6115
- const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
6116
- if (!parsed.targetType && matchingTargetTypes.length > 1) {
6117
- diagnostics.push(issue(
6118
- "AMBIGUOUS_RELATION_TARGET",
6119
- `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
6120
- path,
6121
- 1,
6122
- { node: sourceUid }
6123
- ));
6124
- }
6125
- const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
6126
- if (targetType) {
6127
- const pattern = schema.idPatterns[targetType];
6128
- if (pattern && !new RegExp(pattern).test(parsed.code)) {
6129
- diagnostics.push(issue(
6130
- "FORMAT_ERROR",
6131
- `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
6132
- path,
6133
- 1,
6134
- { node: sourceUid }
6135
- ));
6136
- }
6137
- }
6138
- edges.push({
6139
- ...edge(sourceUid, targetUid, kind, "frontmatter", path, 1),
6140
- ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
6141
- });
6142
- }
8376
+ appendConfiguredRelationEdges(
8377
+ sourceUid,
8378
+ kind,
8379
+ field,
8380
+ toArray(data[field]),
8381
+ spec,
8382
+ schema,
8383
+ path,
8384
+ "frontmatter",
8385
+ edges,
8386
+ diagnostics
8387
+ );
6143
8388
  }
6144
8389
  }
6145
8390
  const external = getExternalEntryInfo({
@@ -6158,6 +8403,40 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6158
8403
  }
6159
8404
  return { edges, diagnostics };
6160
8405
  }
8406
+ function appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, edgeSource, edges, diagnostics) {
8407
+ for (const value of values) {
8408
+ const parsed = parseConfiguredRelationTarget(value, spec, schema);
8409
+ if (!parsed?.code) continue;
8410
+ const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
8411
+ const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
8412
+ if (!parsed.targetType && matchingTargetTypes.length > 1) {
8413
+ diagnostics.push(issue(
8414
+ "AMBIGUOUS_RELATION_TARGET",
8415
+ `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
8416
+ path,
8417
+ 1,
8418
+ { node: sourceUid }
8419
+ ));
8420
+ }
8421
+ const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
8422
+ if (targetType) {
8423
+ const pattern = schema.idPatterns[targetType];
8424
+ if (pattern && !new RegExp(pattern).test(parsed.code)) {
8425
+ diagnostics.push(issue(
8426
+ "FORMAT_ERROR",
8427
+ `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
8428
+ path,
8429
+ 1,
8430
+ { node: sourceUid }
8431
+ ));
8432
+ }
8433
+ }
8434
+ edges.push({
8435
+ ...edge(sourceUid, targetUid, kind, edgeSource, path, 1),
8436
+ ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
8437
+ });
8438
+ }
8439
+ }
6161
8440
  function parseConfiguredRelationTarget(value, spec, schema) {
6162
8441
  if (typeof value === "string" || typeof value === "number") {
6163
8442
  const raw = String(value).trim();
@@ -6242,7 +8521,7 @@ function parseFeature(path, raw) {
6242
8521
  }
6243
8522
  function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
6244
8523
  const lines = raw.split(/\r?\n/);
6245
- const codeLines = markdownCodeLineMask(lines);
8524
+ const codeLines = markdownCodeLineMask2(lines);
6246
8525
  const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
6247
8526
  const starts = [];
6248
8527
  lines.forEach((line, index) => {
@@ -6348,7 +8627,7 @@ function parseDecisions(path, raw) {
6348
8627
  }
6349
8628
  function isTestFile(filePath) {
6350
8629
  const normalized = filePath.replace(/\\/g, "/");
6351
- const name = basename4(normalized);
8630
+ const name = basename5(normalized);
6352
8631
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
6353
8632
  if (/(^|\/)(tests|test|__tests__)\//.test(normalized)) return true;
6354
8633
  if (/\w+Tests?\.java$/.test(name)) return true;
@@ -6660,41 +8939,15 @@ function parseE2eTest(path, raw) {
6660
8939
  const parsed = matter(raw);
6661
8940
  const data = parsed.data;
6662
8941
  const lines = raw.split(/\r?\n/);
6663
- const starts = [];
6664
- lines.forEach((line, index) => {
6665
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
6666
- if (match) {
6667
- starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
6668
- }
6669
- });
8942
+ const starts = extractE2eTestCaseStarts(lines);
6670
8943
  const nodes = [];
6671
8944
  const edges = [];
6672
- const batch = String(data.test_batch ?? basename4(path, extname(path))).trim();
8945
+ const batch = String(data.test_batch ?? basename5(path, extname(path))).trim();
6673
8946
  const frontmatterScenarios = toArray(data.related_scenarios).map((value) => String(value).trim()).filter(Boolean);
6674
8947
  const scopeFeatures = extractCodes(String(data.scope ?? ""), "feature");
6675
- const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
8948
+ const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord2(data.ac_coverage)), ...scopeFeatures])];
6676
8949
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
6677
8950
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
6678
- if (starts.length === 0) {
6679
- const code = `${batch}:FILE`;
6680
- nodes.push({
6681
- type: "e2e_test",
6682
- code,
6683
- title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
6684
- path,
6685
- line: 1,
6686
- attrs: {
6687
- ...data,
6688
- testCaseId: "FILE",
6689
- fileLevelOnly: true,
6690
- tcFields: {},
6691
- blockText: raw,
6692
- coveredFeatures: [],
6693
- coveredScenarios: []
6694
- }
6695
- });
6696
- addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
6697
- }
6698
8951
  for (let index = 0; index < starts.length; index += 1) {
6699
8952
  const start = starts[index];
6700
8953
  const end = starts[index + 1]?.index ?? lines.length;
@@ -6720,6 +8973,16 @@ function parseE2eTest(path, raw) {
6720
8973
  }
6721
8974
  return { nodes, edges };
6722
8975
  }
8976
+ function extractE2eTestCaseStarts(lines) {
8977
+ const codeLines = markdownCodeLineMask2(lines);
8978
+ return lines.flatMap((line, index) => {
8979
+ if (codeLines[index]) {
8980
+ return [];
8981
+ }
8982
+ const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
8983
+ return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
8984
+ });
8985
+ }
6723
8986
  function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
6724
8987
  for (const scenario of scenarios) {
6725
8988
  edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
@@ -6742,7 +9005,7 @@ function parseE2eRegistry(path, raw) {
6742
9005
  data = { parseError: error.message };
6743
9006
  }
6744
9007
  return {
6745
- nodes: [{ type: "e2e_registry", code: basename4(path, extname(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
9008
+ nodes: [{ type: "e2e_registry", code: basename5(path, extname(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
6746
9009
  edges: []
6747
9010
  };
6748
9011
  }
@@ -7504,7 +9767,7 @@ function matchExplicitRelationFieldLine(line, label) {
7504
9767
  const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
7505
9768
  return match?.[1] ?? null;
7506
9769
  }
7507
- function markdownCodeLineMask(lines) {
9770
+ function markdownCodeLineMask2(lines) {
7508
9771
  const result = new Array(lines.length).fill(false);
7509
9772
  let fence;
7510
9773
  lines.forEach((line, index) => {
@@ -7549,14 +9812,14 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
7549
9812
  });
7550
9813
  return result;
7551
9814
  }
7552
- function relationOccurrences(node, field, targetType) {
7553
- const relationRecord = asRecord(node.attrs?.relationOccurrences);
9815
+ function relationOccurrences2(node, field, targetType) {
9816
+ const relationRecord = asRecord2(node.attrs?.relationOccurrences);
7554
9817
  const rawOccurrences = toArray(relationRecord[field]);
7555
9818
  return rawOccurrences.flatMap((value) => {
7556
9819
  if (typeof value === "string") {
7557
9820
  return [{ field, targetType, target: value, path: node.path, line: node.line }];
7558
9821
  }
7559
- const record = asRecord(value);
9822
+ const record = asRecord2(value);
7560
9823
  const target = String(record.target ?? "").trim();
7561
9824
  if (!target) {
7562
9825
  return [];
@@ -7663,7 +9926,7 @@ function validateE2eTests(graph) {
7663
9926
  issues.push(issue("E2E_REQUIRED_FRONTMATTER", `${node.uid} missing required frontmatter ${field}`, node.path, 1, { node: node.uid, severity: "warning" }));
7664
9927
  }
7665
9928
  }
7666
- const fields = asRecord(attrs.tcFields);
9929
+ const fields = asRecord2(attrs.tcFields);
7667
9930
  const requiredTcFields = [
7668
9931
  ["\u6807\u9898", node.title],
7669
9932
  ["\u524D\u7F6E\u6761\u4EF6", fields["\u524D\u7F6E\u6761\u4EF6"]],
@@ -7713,7 +9976,7 @@ function validateE2eTests(graph) {
7713
9976
  }
7714
9977
  for (const [path, nodes] of nodesByPath) {
7715
9978
  const first = nodes[0];
7716
- const declared = flattenAcCoverage(asRecord(first.attrs?.ac_coverage));
9979
+ const declared = flattenAcCoverage(asRecord2(first.attrs?.ac_coverage));
7717
9980
  const covered = new Set(nodes.flatMap((node) => toArray(node.attrs?.coveredFeatures).map((value) => {
7718
9981
  const ref = value;
7719
9982
  return `${String(ref.feature)}:${String(ref.ac)}`;
@@ -7748,13 +10011,16 @@ function validateE2eRegistry(graph) {
7748
10011
  }
7749
10012
  const actualNodes = byPath.get(file) ?? [];
7750
10013
  if (actualNodes.length === 0) {
10014
+ if (Number(batch.test_case_count ?? NaN) === 0) {
10015
+ continue;
10016
+ }
7751
10017
  issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? file)} file ${file || "<missing>"} does not match any E2E test file`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
7752
10018
  continue;
7753
10019
  }
7754
10020
  const first = actualNodes[0];
7755
10021
  compareRegistryValue(issues, registry, batch, "batch_id", first.attrs?.test_batch);
7756
10022
  compareRegistryValue(issues, registry, batch, "scope", first.attrs?.scope);
7757
- compareRegistryAcCoverage(issues, registry, batch, asRecord(first.attrs?.ac_coverage));
10023
+ compareRegistryAcCoverage(issues, registry, batch, asRecord2(first.attrs?.ac_coverage));
7758
10024
  compareRegistryArray(issues, registry, batch, "related_scenarios", toArray(first.attrs?.related_scenarios).map((value) => String(value)));
7759
10025
  compareRegistryValue(issues, registry, batch, "test_case_count", actualNodes.filter((node) => node.attrs?.fileLevelOnly !== true).length);
7760
10026
  }
@@ -7768,31 +10034,21 @@ function validateE2eRegistry(graph) {
7768
10034
  async function validateExecutableTraceability(root, config) {
7769
10035
  const issues = [];
7770
10036
  const schema = config ?? await loadConfig(root);
7771
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
7772
- let e2eFiles;
7773
- try {
7774
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
7775
- } catch {
10037
+ const e2eFiles = await findConfiguredE2eFiles(root, schema);
10038
+ if (e2eFiles.length === 0) {
7776
10039
  return [];
7777
10040
  }
7778
10041
  const mdToRef = /* @__PURE__ */ new Map();
7779
10042
  const allMdTcInfo = /* @__PURE__ */ new Map();
7780
10043
  const tcKeyToFields = /* @__PURE__ */ new Map();
7781
10044
  const mdBatches = /* @__PURE__ */ new Set();
7782
- for (const filePath of e2eFiles) {
7783
- const raw = await readFile3(filePath, "utf-8");
7784
- const relPath = relative4(root, filePath).split("\\").join("/");
10045
+ for (const relPath of e2eFiles) {
10046
+ const raw = await readFile4(join11(root, relPath), "utf-8");
7785
10047
  const parsed = matter(raw);
7786
10048
  const data = parsed.data;
7787
- const batch = String(data.test_batch ?? basename4(filePath, extname(filePath))).trim();
10049
+ const batch = String(data.test_batch ?? basename5(relPath, extname(relPath))).trim();
7788
10050
  const lines = raw.split(/\r?\n/);
7789
- const tcStarts = [];
7790
- lines.forEach((line, index) => {
7791
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
7792
- if (match) {
7793
- tcStarts.push({ id: match[1], line: index + 1, index });
7794
- }
7795
- });
10051
+ const tcStarts = extractE2eTestCaseStarts(lines);
7796
10052
  for (let i = 0; i < tcStarts.length; i += 1) {
7797
10053
  const start = tcStarts[i];
7798
10054
  const end = tcStarts[i + 1]?.index ?? lines.length;
@@ -7829,10 +10085,10 @@ async function validateExecutableTraceability(root, config) {
7829
10085
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
7830
10086
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
7831
10087
  for (const specFile of specFiles) {
7832
- const fullSpecPath = join8(root, specFile);
10088
+ const fullSpecPath = join11(root, specFile);
7833
10089
  let content;
7834
10090
  try {
7835
- content = await readFile3(fullSpecPath, "utf-8");
10091
+ content = await readFile4(fullSpecPath, "utf-8");
7836
10092
  } catch {
7837
10093
  continue;
7838
10094
  }
@@ -7911,7 +10167,7 @@ async function validateExecutableTraceability(root, config) {
7911
10167
  if (entry.testId) {
7912
10168
  let content;
7913
10169
  try {
7914
- content = await readFile3(join8(root, normalizedRefFile), "utf-8");
10170
+ content = await readFile4(join11(root, normalizedRefFile), "utf-8");
7915
10171
  } catch {
7916
10172
  continue;
7917
10173
  }
@@ -7939,7 +10195,7 @@ async function validateExecutableTraceability(root, config) {
7939
10195
  }
7940
10196
  continue;
7941
10197
  }
7942
- if (!mdToRef.has(tcKey) && !await hasMarkdownTc(tcKey, e2eDir)) {
10198
+ if (!allMdTcInfo.has(tcKey)) {
7943
10199
  for (const ann of annotations) {
7944
10200
  issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
7945
10201
  }
@@ -8088,37 +10344,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8088
10344
  let withExecutableRef = 0;
8089
10345
  const statusBreakdown = {};
8090
10346
  const chainTypeBreakdown = {};
8091
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8092
- const tcFieldsMap = /* @__PURE__ */ new Map();
8093
- let e2eFiles;
8094
- try {
8095
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
8096
- } catch {
8097
- e2eFiles = [];
8098
- }
8099
- for (const filePath of e2eFiles) {
8100
- const raw = await readFile3(filePath, "utf-8");
8101
- const lines = raw.split(/\r?\n/);
8102
- const tcStarts = [];
8103
- lines.forEach((line, index) => {
8104
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8105
- if (match) {
8106
- tcStarts.push({ id: match[1], index });
8107
- }
8108
- });
8109
- const parsed = matter(raw);
8110
- const batch = String(parsed.data.test_batch ?? basename4(filePath, extname(filePath))).trim();
8111
- for (let i = 0; i < tcStarts.length; i++) {
8112
- const start = tcStarts[i];
8113
- const end = tcStarts[i + 1]?.index ?? lines.length;
8114
- const block = lines.slice(start.index, end);
8115
- const fields = extractE2eTcFields(block);
8116
- tcFieldsMap.set(`${batch}:${start.id}`, fields);
8117
- }
8118
- }
10347
+ const tcFieldsMap = new Map(e2eNodes.map((node) => [
10348
+ node.code,
10349
+ asRecord2(node.attrs?.tcFields)
10350
+ ]));
8119
10351
  for (const node of e2eNodes) {
8120
10352
  const tcKey = node.code;
8121
- const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
10353
+ const fields = tcFieldsMap.get(tcKey) ?? asRecord2(node.attrs?.tcFields);
8122
10354
  const execRef = String(fields["executable_ref"] ?? "").trim();
8123
10355
  if (execRef && !isPendingExecutableRef(execRef)) {
8124
10356
  withExecutableRef++;
@@ -8148,8 +10380,8 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8148
10380
  }
8149
10381
  }
8150
10382
  for (const node of e2eNodes) {
8151
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8152
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10383
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10384
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8153
10385
  for (const feature of Object.keys(acCoverage)) {
8154
10386
  acCoveredFeatures.add(feature);
8155
10387
  }
@@ -8161,7 +10393,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8161
10393
  const runners = (await loadConfig(root)).e2e?.runners ?? [];
8162
10394
  const allProjectFiles = await walkFiles(root);
8163
10395
  for (const node of e2eNodes) {
8164
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
10396
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
8165
10397
  const status = String(fields["status"] ?? "").trim().toLowerCase();
8166
10398
  const execRef = String(fields["executable_ref"] ?? "").trim();
8167
10399
  if (status !== "verified") continue;
@@ -8170,7 +10402,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8170
10402
  let hasActiveE2eRef = false;
8171
10403
  for (const entry of parseExecutableRefLines(execRef)) {
8172
10404
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
8173
- if (!normalized || !existsSync3(join8(root, normalized))) continue;
10405
+ if (!normalized || !existsSync3(join11(root, normalized))) continue;
8174
10406
  const accepting = await getAcceptingRunners(root, normalized, runners);
8175
10407
  if (accepting.some((runner) => runner.kind === "e2e")) {
8176
10408
  hasActiveE2eRef = true;
@@ -8182,7 +10414,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8182
10414
  for (const scenario of relatedScenarios) {
8183
10415
  verifiedScenarios.add(scenario);
8184
10416
  }
8185
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10417
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8186
10418
  for (const feature of Object.keys(acCoverage)) {
8187
10419
  verifiedFeatures.add(feature);
8188
10420
  }
@@ -8229,13 +10461,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8229
10461
  const acCoverageRateByFeature = {};
8230
10462
  const featureAcMap = /* @__PURE__ */ new Map();
8231
10463
  for (const node of featureNodes) {
8232
- const acs = parseAcceptanceCriteria(await readFile3(join8(root, node.path), "utf-8"));
10464
+ const acs = parseAcceptanceCriteria(await readFile4(join11(root, node.path), "utf-8"));
8233
10465
  featureAcMap.set(node.code, new Set(acs));
8234
10466
  }
8235
10467
  const coveredAcByFeature = /* @__PURE__ */ new Map();
8236
10468
  for (const node of e2eNodes) {
8237
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8238
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10469
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10470
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8239
10471
  for (const [feature, acs] of Object.entries(acCoverage)) {
8240
10472
  const existing = coveredAcByFeature.get(feature) ?? /* @__PURE__ */ new Set();
8241
10473
  for (const ac of toArray(acs)) {
@@ -8271,39 +10503,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8271
10503
  };
8272
10504
  }
8273
10505
  async function generateE2eRegistry(root, opts) {
8274
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8275
- let files;
8276
- try {
8277
- files = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
8278
- } catch {
8279
- return {
8280
- registry_version: "1.0",
8281
- generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8282
- total_batches: 0,
8283
- total_test_cases: 0,
8284
- batches: []
8285
- };
8286
- }
10506
+ const schema = await loadConfig(root);
10507
+ const files = await findConfiguredE2eFiles(root, schema);
8287
10508
  const batches = [];
10509
+ const batchIds = /* @__PURE__ */ new Set();
8288
10510
  let totalTestCases = 0;
8289
10511
  for (const file of files) {
8290
- const filePath = join8(e2eDir, file);
8291
- const raw = await readFile3(filePath, "utf-8");
10512
+ const filePath = join11(root, file);
10513
+ const raw = await readFile4(filePath, "utf-8");
8292
10514
  const parsed = matter(raw);
8293
10515
  const data = parsed.data;
8294
- const batch = String(data.test_batch ?? basename4(file, extname(file))).trim();
8295
- const relPath = `artifacts/tests/e2e/${file}`;
10516
+ const batch = String(data.test_batch ?? basename5(file, extname(file))).trim();
10517
+ const relPath = file;
8296
10518
  const scope = String(data.scope ?? "").trim();
8297
10519
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
8298
10520
  const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
8299
10521
  const lines = raw.split(/\r?\n/);
8300
- const tcStarts = [];
8301
- lines.forEach((line, index) => {
8302
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8303
- if (match) {
8304
- tcStarts.push({ id: match[1], index });
8305
- }
8306
- });
10522
+ const tcStarts = extractE2eTestCaseStarts(lines);
10523
+ if (tcStarts.length > 0) {
10524
+ batchIds.add(batch);
10525
+ }
8307
10526
  const statusSummary = {};
8308
10527
  const blockingReasons = {};
8309
10528
  const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
@@ -8312,8 +10531,9 @@ async function generateE2eRegistry(root, opts) {
8312
10531
  blockingReasons[tc.id] = frontmatterFixesBlock;
8313
10532
  }
8314
10533
  }
8315
- for (const start of tcStarts) {
8316
- const end = tcStarts[tcStarts.indexOf(start) + 1]?.index ?? lines.length;
10534
+ for (let index = 0; index < tcStarts.length; index += 1) {
10535
+ const start = tcStarts[index];
10536
+ const end = tcStarts[index + 1]?.index ?? lines.length;
8317
10537
  const block = lines.slice(start.index, end);
8318
10538
  const fields = extractE2eTcFields(block);
8319
10539
  const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
@@ -8346,7 +10566,7 @@ async function generateE2eRegistry(root, opts) {
8346
10566
  return {
8347
10567
  registry_version: "1.0",
8348
10568
  generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8349
- total_batches: batches.length,
10569
+ total_batches: batchIds.size,
8350
10570
  total_test_cases: totalTestCases,
8351
10571
  batches
8352
10572
  };
@@ -8415,10 +10635,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
8415
10635
  if (!normalizedPath) {
8416
10636
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8417
10637
  }
8418
- const fullPath = join8(root, normalizedPath);
10638
+ const fullPath = join11(root, normalizedPath);
8419
10639
  let content;
8420
10640
  try {
8421
- content = await readFile3(fullPath, "utf-8");
10641
+ content = await readFile4(fullPath, "utf-8");
8422
10642
  } catch {
8423
10643
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8424
10644
  }
@@ -8452,7 +10672,7 @@ function detectTestLevel(specFile, content) {
8452
10672
  }
8453
10673
  function resolveExecutableRefFile(refFile, allFiles) {
8454
10674
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
8455
- if (!normalized || isAbsolute4(refFile) || normalized.split("/").includes("..")) {
10675
+ if (!normalized || isAbsolute6(refFile) || normalized.split("/").includes("..")) {
8456
10676
  return void 0;
8457
10677
  }
8458
10678
  if (allFiles.includes(normalized)) {
@@ -8525,17 +10745,6 @@ function splitMarkdownCells(line) {
8525
10745
  function escapeRegExp(value) {
8526
10746
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8527
10747
  }
8528
- async function hasMarkdownTc(tcKey, e2eDir) {
8529
- const [batch, tcId] = tcKey.split(":");
8530
- const filePath = join8(e2eDir, `${batch}.md`);
8531
- try {
8532
- const raw = await readFile3(filePath, "utf-8");
8533
- const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
8534
- return tcRegex.test(raw);
8535
- } catch {
8536
- return false;
8537
- }
8538
- }
8539
10748
  async function findFiles(root, patterns) {
8540
10749
  const all = await walkFiles(root);
8541
10750
  const matched = /* @__PURE__ */ new Set();
@@ -8548,6 +10757,10 @@ async function findFiles(root, patterns) {
8548
10757
  }
8549
10758
  return [...matched].sort();
8550
10759
  }
10760
+ async function findConfiguredE2eFiles(root, schema) {
10761
+ const patterns = schema.types.e2e_test?.paths ?? [];
10762
+ return findFiles(root, patterns);
10763
+ }
8551
10764
  function matchesConfiguredArtifactPath(path, schema) {
8552
10765
  const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
8553
10766
  return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
@@ -8576,8 +10789,13 @@ function extractCodes(text, type, schema) {
8576
10789
  }
8577
10790
  function extractE2eTcFields(block) {
8578
10791
  const fields = {};
10792
+ const codeLines = markdownCodeLineMask2(block);
8579
10793
  let current = "";
8580
- for (const line of block) {
10794
+ for (let index = 0; index < block.length; index += 1) {
10795
+ if (codeLines[index]) {
10796
+ continue;
10797
+ }
10798
+ const line = block[index];
8581
10799
  const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
8582
10800
  if (match) {
8583
10801
  current = match[1].trim();
@@ -8629,7 +10847,7 @@ function flattenAcCoverage(value) {
8629
10847
  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)}`) })));
8630
10848
  }
8631
10849
  function needsDesktopChainWarning(node) {
8632
- const tcFields = asRecord(node.attrs?.tcFields);
10850
+ const tcFields = asRecord2(node.attrs?.tcFields);
8633
10851
  const chainType = String(tcFields["chain_type"] ?? "").trim().toLowerCase();
8634
10852
  if (chainType && VALID_CHAIN_TYPES.has(chainType) && chainType !== "desktop_chain" || chainType in DEPRECATED_CHAIN_TYPE_ALIASES) {
8635
10853
  return false;
@@ -8686,7 +10904,7 @@ function compareRegistryAcCoverage(issues, registry, batch, actual) {
8686
10904
  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" }));
8687
10905
  return;
8688
10906
  }
8689
- if (normalizeAcCoverage(asRecord(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
10907
+ if (normalizeAcCoverage(asRecord2(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
8690
10908
  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" }));
8691
10909
  }
8692
10910
  }
@@ -8701,7 +10919,7 @@ function groupBy(values, key) {
8701
10919
  }
8702
10920
  return result;
8703
10921
  }
8704
- function asRecord(value) {
10922
+ function asRecord2(value) {
8705
10923
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
8706
10924
  }
8707
10925
  function isEmptyValue(value) {
@@ -8760,7 +10978,7 @@ function normalizeDesignCode(value) {
8760
10978
  if (!raw) {
8761
10979
  return "";
8762
10980
  }
8763
- return basename4(raw, extname(raw));
10981
+ return basename5(raw, extname(raw));
8764
10982
  }
8765
10983
  function toUid(type, code) {
8766
10984
  return `${type}:${code}`;
@@ -9036,14 +11254,14 @@ function resolveArtifactContext(graph, opts) {
9036
11254
  }
9037
11255
  if (root) {
9038
11256
  for (const ap of ALWAYS_PRESENT_ITEMS) {
9039
- const fullPath = join8(root, ap.path);
9040
- let stat;
11257
+ const fullPath = join11(root, ap.path);
11258
+ let stat2;
9041
11259
  try {
9042
- stat = statSync(fullPath);
11260
+ stat2 = statSync(fullPath);
9043
11261
  } catch {
9044
- stat = null;
11262
+ stat2 = null;
9045
11263
  }
9046
- if (!stat) {
11264
+ if (!stat2) {
9047
11265
  const msg = `Required baseline artifact not found: ${ap.path}`;
9048
11266
  if (!missing.includes(msg)) {
9049
11267
  missing.push(msg);
@@ -9055,7 +11273,7 @@ function resolveArtifactContext(graph, opts) {
9055
11273
  suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
9056
11274
  });
9057
11275
  }
9058
- } else if (!stat.isFile()) {
11276
+ } else if (!stat2.isFile()) {
9059
11277
  const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
9060
11278
  if (!missing.includes(msg)) {
9061
11279
  missing.push(msg);
@@ -9278,7 +11496,7 @@ function formatContextMarkdown(manifest) {
9278
11496
  }
9279
11497
  return lines.join("\n");
9280
11498
  }
9281
- var 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;
11499
+ var 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;
9282
11500
  var init_index = __esm({
9283
11501
  "src/index.ts"() {
9284
11502
  init_packet_constants();
@@ -9299,8 +11517,12 @@ var init_index = __esm({
9299
11517
  init_git_changes();
9300
11518
  init_git_hook_path();
9301
11519
  init_hook_installer();
11520
+ init_professional_conclusion();
9302
11521
  init_review_result_validator();
9303
11522
  init_contract_kernel();
11523
+ init_restructure();
11524
+ init_restructure_file_set();
11525
+ init_restructure_software();
9304
11526
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
9305
11527
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
9306
11528
  DEFAULT_SCHEMA = {
@@ -9348,6 +11570,33 @@ var init_index = __esm({
9348
11570
  runners: []
9349
11571
  }
9350
11572
  };
11573
+ SPECIALIZED_PARSER_TYPES = /* @__PURE__ */ new Set([
11574
+ "feature",
11575
+ "scenario",
11576
+ "entity",
11577
+ "decision",
11578
+ "test",
11579
+ "design",
11580
+ "e2e_test",
11581
+ "e2e_registry",
11582
+ "rule-golden-cases",
11583
+ "test-strategy",
11584
+ "traceability-matrix-v2",
11585
+ "traceability-version-lock",
11586
+ "interface_contracts",
11587
+ "data_contracts",
11588
+ "application_state_machines",
11589
+ "error_model",
11590
+ "domain-glossary",
11591
+ "bounded-context-map",
11592
+ "domain-invariants",
11593
+ "generation-packet-spec",
11594
+ "report-contracts",
11595
+ "verification-fixtures",
11596
+ "ui-flow-contracts",
11597
+ "non-functional-budgets",
11598
+ "implementation-blueprint"
11599
+ ]);
9351
11600
  EMPTY_RELATION_FIELD_VALUES = /* @__PURE__ */ new Set(["\u65E0", "none", "n/a", "-"]);
9352
11601
  VALID_TC_STATUSES = /* @__PURE__ */ new Set(["created", "automated", "verified", "waived"]);
9353
11602
  VALID_CHAIN_TYPES = /* @__PURE__ */ new Set([
@@ -9395,6 +11644,7 @@ export {
9395
11644
  BASELINE_CONSTRAINTS,
9396
11645
  BASELINE_CONSTRAINTS_COUNT,
9397
11646
  BASELINE_ITEMS_COUNT,
11647
+ CONTRACTS_PACKAGE_NAME2 as CONTRACTS_PACKAGE_NAME,
9398
11648
  CONTRACT_ERROR_CODES,
9399
11649
  ContractCatalog,
9400
11650
  ContractError,
@@ -9402,35 +11652,62 @@ export {
9402
11652
  DEFAULT_MAX_CHARS,
9403
11653
  DEFAULT_SCHEMA,
9404
11654
  E2E_NORMALIZER_CONFIG,
11655
+ FILE_SET_RESULT_OBJECT,
11656
+ FOUNDATION_PACKAGE_NAME,
11657
+ GRAPH_DOMAIN_CODES,
11658
+ GRAPH_PROVIDER_ENTRY,
11659
+ GRAPH_PROVIDER_ID,
9405
11660
  MIN_PROMPT_CHARS,
11661
+ PROFESSIONAL_CONCLUSION_OBJECT,
11662
+ RESTRUCTURE_MAX_OPERATIONS,
11663
+ RESTRUCTURE_MAX_TOTAL_BYTES,
11664
+ RESTRUCTURE_PLAN_SCHEMA_VERSION,
11665
+ RESTRUCTURE_QUALIFIED_ARCH,
11666
+ RESTRUCTURE_QUALIFIED_FILESYSTEM,
11667
+ RESTRUCTURE_QUALIFIED_PLATFORM,
11668
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH,
11669
+ RESTRUCTURE_RECOVERY_REL_PATH,
11670
+ RESTRUCTURE_RECOVERY_ROOT_MODE,
11671
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS,
9406
11672
  TARGET_ARTIFACT_TYPES,
9407
11673
  VALID_PACKET_TARGET_TYPES,
9408
11674
  VERSION_INDEX_SCHEMA_VERSION,
9409
11675
  VERSION_LOCK_PATH,
9410
11676
  VERSION_LOCK_SCHEMA_VERSION,
9411
11677
  applyPreparedManagedHookBlocks,
11678
+ applyRestructure,
11679
+ applyRestructureFileSet,
9412
11680
  assemblePacket,
9413
11681
  auditPackets,
9414
11682
  auditVersionLock,
9415
11683
  bootstrapVersionLock,
11684
+ buildFileSetApplyRequest,
9416
11685
  buildGraph,
9417
11686
  buildVersionIndex,
11687
+ candidateByteDigest,
9418
11688
  collectChangedPaths,
9419
11689
  computeCoverageBoundary,
9420
11690
  computeE2eCoverageStats,
9421
11691
  computeImpact,
9422
11692
  computeRevisionDigest,
9423
- dirname5 as dirname,
11693
+ createModeForUmask,
11694
+ createRestructureRootBinding,
11695
+ createRestructureValidationCallback,
11696
+ digestRestructureValue,
11697
+ dirname7 as dirname,
9424
11698
  discoverAndAuditPackets,
9425
11699
  discoverTargets,
9426
11700
  doctorArtifactChain,
11701
+ ensureRestructureMechanismRoot,
9427
11702
  extname,
9428
11703
  filterGraphByView,
9429
11704
  formatContextMarkdown,
11705
+ gateRestructureOperationPlan,
9430
11706
  generateE2eRegistry,
9431
11707
  getArtifactTypeMetadata,
9432
11708
  getExternalEntryInfo,
9433
11709
  getTargetArtifactTypes,
11710
+ inspectRestructure,
9434
11711
  installManagedHookBlock,
9435
11712
  isOfficialNamespace,
9436
11713
  isPacketTargetType,
@@ -9441,14 +11718,26 @@ export {
9441
11718
  loadContract,
9442
11719
  loadContractCatalog,
9443
11720
  loadContractsFromDirectory,
11721
+ loadFoundationModule,
11722
+ locateSoftwareRecord,
11723
+ markdownRecordHeadings,
9444
11724
  matchesConfiguredArtifactPath,
9445
11725
  nextId,
9446
11726
  normalizeE2eLegacyArtifact,
9447
11727
  normalizeToCanonical,
11728
+ observeRestructureJournal,
9448
11729
  parseTargetSelector,
9449
11730
  parseTargetsFile,
11731
+ planRestructure,
11732
+ planningUmask,
9450
11733
  prepareManagedHookBlock,
11734
+ projectRestructureFileSetResult,
11735
+ pruneRestructureFileSet,
11736
+ pruneRestructureRecovery,
11737
+ qualifyRestructureMechanism,
9451
11738
  queryGraph,
11739
+ recoverRestructure,
11740
+ recoverRestructureFileSet,
9452
11741
  refreshVersionLock,
9453
11742
  renderCoverageBoundaryMarkdown,
9454
11743
  renderDoctorMarkdown,
@@ -9459,6 +11748,7 @@ export {
9459
11748
  renderTraceVersionMarkdown,
9460
11749
  renderVersionLockAuditMarkdown,
9461
11750
  renderVersionLockRefreshMarkdown,
11751
+ replaceSoftwareHeader,
9462
11752
  resolveArtifactContext,
9463
11753
  resolveArtifactGraphCli,
9464
11754
  resolveArtifactTypeName,
@@ -9466,6 +11756,10 @@ export {
9466
11756
  resolveGitHookPath,
9467
11757
  resolveMatrixEdges,
9468
11758
  resolveNodeTimeView,
11759
+ resolveRealRoot,
11760
+ restructureBoundaryFindings,
11761
+ runCheckProfessional,
11762
+ runReadProof,
9469
11763
  scanArtifacts,
9470
11764
  traceVersion,
9471
11765
  updateVersionLock,
@@ -9481,6 +11775,7 @@ export {
9481
11775
  validateScenarioPrdLinkIndex,
9482
11776
  validateScenarioPrdLinks,
9483
11777
  verifyDigest,
11778
+ verifyMechanismResult,
9484
11779
  versionLockIssueSeverity,
9485
11780
  writeGraphCache
9486
11781
  };