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/cli.js CHANGED
@@ -944,9 +944,13 @@ async function bootstrapVersionLock(root, options = {}) {
944
944
  async function refreshVersionLock(root, options = {}) {
945
945
  const lockPath = normalizeRelativePath(root, options.lockPath ?? VERSION_LOCK_PATH);
946
946
  const changedPaths = sortUnique2((options.changedPaths ?? []).map((path) => normalizeRelativePath(root, path)));
947
+ const removeOrphanEdges = new Set(sortUnique2(options.removeOrphanEdges ?? []));
947
948
  const all = options.all === true || options.changedOnly !== true;
948
949
  const mode = all ? "all" : "changed-only";
949
950
  const warnings = [];
951
+ if (options.removeOrphans === true && removeOrphanEdges.size > 0) {
952
+ throw new Error("--remove-orphans and --remove-orphan-edge are mutually exclusive");
953
+ }
950
954
  if (!all && changedPaths.includes("artifact-graph.config.yaml")) {
951
955
  throw new Error("Changed-only version-lock refresh includes artifact-graph.config.yaml and requires --all");
952
956
  }
@@ -956,9 +960,16 @@ async function refreshVersionLock(root, options = {}) {
956
960
  const nodeByUid = new Map(index.nodes.map((node) => [node.uid, node]));
957
961
  const nodeByPath = new Map(index.nodes.map((node) => [node.path, node]));
958
962
  const currentImplementationEdges = await lockableImplementationEdges(root, index, config);
963
+ const currentArtifactRelationEdgeList = artifactRelationEdges(index);
959
964
  const currentEdgePairs = new Set(currentImplementationEdges.map((edge2) => `${edge2.from} ${edge2.to}`));
960
965
  const currentEntries = /* @__PURE__ */ new Map();
961
966
  const changedPathSet = new Set(changedPaths);
967
+ validatePreciseOrphanRemoval(
968
+ removeOrphanEdges,
969
+ lock,
970
+ new Set(currentImplementationEdges.map((edge2) => edge2.edgeId)),
971
+ new Set(currentArtifactRelationEdgeList.map((edge2) => edge2.edgeId))
972
+ );
962
973
  const affectedEdges = /* @__PURE__ */ new Set();
963
974
  const addedLocks = [];
964
975
  const updatedLocks = [];
@@ -985,12 +996,13 @@ async function refreshVersionLock(root, options = {}) {
985
996
  }
986
997
  for (const existing of lock.locks) {
987
998
  const current = currentEntries.get(existing.edgeId);
988
- const affected = all || lockEntryTouchesAnyPath(existing, changedPathSet);
999
+ const removePrecisely = removeOrphanEdges.has(existing.edgeId);
1000
+ const affected = removePrecisely || all || lockEntryTouchesAnyPath(existing, changedPathSet);
989
1001
  if (affected) {
990
1002
  affectedEdges.add(existing.edgeId);
991
1003
  }
992
1004
  if (!current) {
993
- if (affected && options.removeOrphans === true) {
1005
+ if (removePrecisely || affected && options.removeOrphans === true) {
994
1006
  removedOrphans.push(existing.edgeId);
995
1007
  } else {
996
1008
  if (affected) {
@@ -1025,7 +1037,6 @@ async function refreshVersionLock(root, options = {}) {
1025
1037
  if (mode === "changed-only" && changedPaths.length === 0) {
1026
1038
  warnings.push("No changed paths were provided; no locks were refreshed.");
1027
1039
  }
1028
- const currentArtifactRelationEdgeList = artifactRelationEdges(index);
1029
1040
  const existingArtifactRelationLocks = lock.artifactRelations ?? [];
1030
1041
  const addedArtifactRelationLocks = [];
1031
1042
  const updatedArtifactRelationLocks = [];
@@ -1069,10 +1080,11 @@ async function refreshVersionLock(root, options = {}) {
1069
1080
  if (processedRelationEdgeIds.has(relEdgeId)) {
1070
1081
  continue;
1071
1082
  }
1072
- const affected = all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1083
+ const removePrecisely = removeOrphanEdges.has(relEdgeId);
1084
+ const affected = removePrecisely || all || artifactRelationLockTouchesPaths(existingLock, changedPathSet);
1073
1085
  if (affected) {
1074
1086
  affectedEdges.add(relEdgeId);
1075
- if (options.removeOrphans === true) {
1087
+ if (removePrecisely || options.removeOrphans === true) {
1076
1088
  removedArtifactRelationLocks.push(relEdgeId);
1077
1089
  } else {
1078
1090
  retainedArtifactRelationOrphans.push(relEdgeId);
@@ -1108,6 +1120,20 @@ async function refreshVersionLock(root, options = {}) {
1108
1120
  warnings
1109
1121
  };
1110
1122
  }
1123
+ function validatePreciseOrphanRemoval(requestedEdgeIds, lock, currentImplementationEdgeIds, currentArtifactRelationEdgeIds) {
1124
+ for (const edgeId of requestedEdgeIds) {
1125
+ const matches = lock.locks.filter((entry) => entry.edgeId === edgeId).length + (lock.artifactRelations ?? []).filter((entry) => entry.edgeId === edgeId).length;
1126
+ if (matches === 0) {
1127
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not exist in the version lock`);
1128
+ }
1129
+ if (matches !== 1) {
1130
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edgeId does not match exactly one version lock entry`);
1131
+ }
1132
+ if (currentImplementationEdgeIds.has(edgeId) || currentArtifactRelationEdgeIds.has(edgeId)) {
1133
+ throw new Error(`Cannot remove orphan edge ${edgeId}: edge is currently active`);
1134
+ }
1135
+ }
1136
+ }
1111
1137
  async function traceVersion(root, target, lockPath = VERSION_LOCK_PATH) {
1112
1138
  const index = await buildVersionIndex(root);
1113
1139
  const safeLockPath = normalizeRelativePath(root, lockPath);
@@ -3082,16 +3108,16 @@ function probeNativeBinding(context = {}) {
3082
3108
  }
3083
3109
  return { ok: true };
3084
3110
  }
3085
- function buildNativeBindingDiagnostic(failure, probeContext) {
3111
+ function buildNativeBindingDiagnostic(failure2, probeContext) {
3086
3112
  return {
3087
3113
  selectedCli: probeContext.selectedCli,
3088
3114
  runtime: `${process.execPath} (v${process.versions.node})`,
3089
- abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure.detail)}`,
3115
+ abi: `process.versions.modules=${process.versions.modules}${abiPrebuiltHint(failure2.detail)}`,
3090
3116
  installSource: probeContext.installSource,
3091
3117
  probedFrom: probeContext.probedFrom,
3092
- failedStage: failure.failedStage,
3093
- cause: failure.cause,
3094
- suggestion: failure.suggestion
3118
+ failedStage: failure2.failedStage,
3119
+ cause: failure2.cause,
3120
+ suggestion: failure2.suggestion
3095
3121
  };
3096
3122
  }
3097
3123
  function buildNativeBindingSuccessDiagnostic(probeContext) {
@@ -3115,21 +3141,21 @@ function runningArtifactGraphInstallRoot() {
3115
3141
  const anchor = typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url);
3116
3142
  return findPackageRoot(anchor);
3117
3143
  }
3118
- function structuredNativeBindingError(failure, context = {}) {
3144
+ function structuredNativeBindingError(failure2, context = {}) {
3119
3145
  return {
3120
3146
  error: "native_binding_unavailable",
3121
- stage: failure.failedStage,
3122
- cause: failure.cause,
3123
- detail: failure.detail,
3124
- suggestion: failure.suggestion,
3147
+ stage: failure2.failedStage,
3148
+ cause: failure2.cause,
3149
+ detail: failure2.detail,
3150
+ suggestion: failure2.suggestion,
3125
3151
  doctorHint: "artifact-graph doctor --format json",
3126
3152
  // F-10-P01/F-10-P03:机器读取错误包络也暴露实际探测来源,使 scan/query
3127
3153
  // 与 doctor 的分类依据(同一运行安装根)可被自动测试断言。
3128
3154
  probedFrom: context.probedFrom ?? "(current artifact-graph package)"
3129
3155
  };
3130
3156
  }
3131
- function renderStructuredNativeBindingError(failure, context = {}) {
3132
- return `${JSON.stringify(structuredNativeBindingError(failure, context), null, 2)}
3157
+ function renderStructuredNativeBindingError(failure2, context = {}) {
3158
+ return `${JSON.stringify(structuredNativeBindingError(failure2, context), null, 2)}
3133
3159
  `;
3134
3160
  }
3135
3161
  function safeClose(db) {
@@ -3233,7 +3259,7 @@ async function doctorArtifactChain(root, options = {}) {
3233
3259
  const nativeBinding = probe.ok ? { ok: true, ...buildNativeBindingSuccessDiagnostic(probeContext) } : { ok: false, ...buildNativeBindingDiagnostic(probe, probeContext) };
3234
3260
  const warnings = [
3235
3261
  ...cli.warnings,
3236
- ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy >=22.0.0.`],
3262
+ ...nodeCompatible ? [] : [`Node.js ${process.versions.node} does not satisfy ${REQUIRED_NODE_VERSION}.`],
3237
3263
  ...probe.ok ? [] : [
3238
3264
  `better-sqlite3 binding probe FAILED at stage "${probe.failedStage}" (cause ${probe.cause}): ${probe.suggestion}`
3239
3265
  ]
@@ -3245,7 +3271,7 @@ async function doctorArtifactChain(root, options = {}) {
3245
3271
  node: {
3246
3272
  version: process.versions.node,
3247
3273
  compatible: nodeCompatible,
3248
- required: ">=22.0.0"
3274
+ required: REQUIRED_NODE_VERSION
3249
3275
  },
3250
3276
  config: {
3251
3277
  path: configPath,
@@ -3349,8 +3375,10 @@ function resolveCandidatePath(root, candidatePath) {
3349
3375
  return isAbsolute2(candidatePath) ? candidatePath : resolve3(root, candidatePath);
3350
3376
  }
3351
3377
  function isNodeCompatible(version) {
3352
- const major = Number(version.split(".")[0]);
3353
- return Number.isFinite(major) && major >= 22;
3378
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
3379
+ if (!match) return false;
3380
+ const [, major, minor, patch] = match.map(Number);
3381
+ return major === 22 && (minor > 22 || minor === 22 && patch >= 2);
3354
3382
  }
3355
3383
  async function detectPnpmVersion() {
3356
3384
  try {
@@ -3411,13 +3439,14 @@ function safeRealpath(path) {
3411
3439
  return path;
3412
3440
  }
3413
3441
  }
3414
- var execFileAsync2, KNOWN_COMMANDS;
3442
+ var execFileAsync2, REQUIRED_NODE_VERSION, KNOWN_COMMANDS;
3415
3443
  var init_cli_resolver = __esm({
3416
3444
  "src/cli-resolver.ts"() {
3417
3445
  "use strict";
3418
3446
  init_versioned_traceability();
3419
3447
  init_native_binding_diagnostics();
3420
3448
  execFileAsync2 = promisify2(execFile2);
3449
+ REQUIRED_NODE_VERSION = ">=22.22.2 <23";
3421
3450
  KNOWN_COMMANDS = [
3422
3451
  "init",
3423
3452
  "scan",
@@ -3895,6 +3924,378 @@ var init_hook_installer = __esm({
3895
3924
  }
3896
3925
  });
3897
3926
 
3927
+ // src/professional-conclusion.ts
3928
+ import { access as access2 } from "fs/promises";
3929
+ import { createRequire as createRequire2 } from "module";
3930
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute4, join as join7, resolve as resolve5 } from "path";
3931
+ import { pathToFileURL } from "url";
3932
+ async function loadContracts() {
3933
+ return await import(CONTRACTS_PACKAGE_NAME);
3934
+ }
3935
+ async function loadHarness() {
3936
+ return await import("skill-family-harness-node");
3937
+ }
3938
+ function providerVersion() {
3939
+ const anchor = typeof __filename === "string" ? __filename : import.meta.url;
3940
+ const parsed = createRequire2(anchor)("../package.json");
3941
+ if (typeof parsed.version !== "string" || parsed.version.length === 0) {
3942
+ throw new Error("artifact-graph package.json is missing version");
3943
+ }
3944
+ return parsed.version;
3945
+ }
3946
+ function errorMessage(error) {
3947
+ return error instanceof Error ? error.message : String(error);
3948
+ }
3949
+ function harnessKind(error) {
3950
+ if (error === null || typeof error !== "object" || !("details" in error)) {
3951
+ return void 0;
3952
+ }
3953
+ const details = error.details;
3954
+ return typeof details?.kind === "string" ? details.kind : void 0;
3955
+ }
3956
+ async function missingRequiredConfig(root) {
3957
+ const configPath = join7(root, "artifact-graph.config.yaml");
3958
+ try {
3959
+ await access2(configPath);
3960
+ return void 0;
3961
+ } catch (error) {
3962
+ if (error.code === "ENOENT") {
3963
+ return `required configuration is missing: ${configPath}`;
3964
+ }
3965
+ return errorMessage(error);
3966
+ }
3967
+ }
3968
+ async function runValidate(root) {
3969
+ const config = await loadConfig(root);
3970
+ const graph = await scanArtifacts(root, config);
3971
+ const issues = validateGraph(graph, config);
3972
+ issues.push(...await validateScenarioPrdLinkIndex(root, graph));
3973
+ issues.push(...await validateExecutableTraceability(root, config));
3974
+ const includeCoverage = config.e2e?.executable_ref_warning !== void 0 || config.e2e?.executable_ref_error !== void 0;
3975
+ if (includeCoverage) {
3976
+ const e2eConfig = config.e2e ?? {};
3977
+ const coverageStats = await computeE2eCoverageStats(graph, root, {
3978
+ executableRefWarning: e2eConfig.executable_ref_warning,
3979
+ executableRefError: e2eConfig.executable_ref_error,
3980
+ reportUncoveredScenarios: e2eConfig.report_uncovered_scenarios,
3981
+ reportUncoveredFeatures: e2eConfig.report_uncovered_features,
3982
+ scenarioWaivers: e2eConfig.scenario_waivers,
3983
+ featureWaivers: e2eConfig.feature_waivers
3984
+ });
3985
+ for (const msg of coverageStats.thresholdWarnings) {
3986
+ issues.push({
3987
+ code: "E2E_COVERAGE_WARNING",
3988
+ severity: "warning",
3989
+ message: msg,
3990
+ path: "e2e-coverage",
3991
+ line: 1
3992
+ });
3993
+ }
3994
+ for (const msg of coverageStats.thresholdErrors) {
3995
+ issues.push({
3996
+ code: "E2E_COVERAGE_ERROR",
3997
+ severity: "error",
3998
+ message: msg,
3999
+ path: "e2e-coverage",
4000
+ line: 1
4001
+ });
4002
+ }
4003
+ }
4004
+ return { name: CHECK_VALIDATE, status: "completed", issues };
4005
+ }
4006
+ async function runLockAudit(root) {
4007
+ const result = await auditVersionLock(root);
4008
+ return { name: CHECK_LOCK, status: "completed", issues: result.issues };
4009
+ }
4010
+ async function runCoverage(root) {
4011
+ const report = await computeCoverageBoundary(root);
4012
+ return {
4013
+ name: CHECK_COVERAGE,
4014
+ status: "completed",
4015
+ issues: [],
4016
+ coverage: {
4017
+ assessment: report.graphHealth.assessment,
4018
+ changedPathScope: report.scanCoverage.changedPathScope,
4019
+ behaviorStatus: report.behaviorVerification.status
4020
+ }
4021
+ };
4022
+ }
4023
+ async function settleCheck(name, run) {
4024
+ try {
4025
+ return await run();
4026
+ } catch (error) {
4027
+ return { name, status: "not-performed", issues: [], reason: errorMessage(error) };
4028
+ }
4029
+ }
4030
+ function mapDomain(checks) {
4031
+ const completed = checks.filter((check) => check.status === "completed");
4032
+ const missing = checks.filter((check) => check.status === "not-performed");
4033
+ const hasFindings = completed.some((check) => check.issues.length > 0);
4034
+ if (completed.length === 0) {
4035
+ return {
4036
+ code: GRAPH_DOMAIN_CODES.UNAVAILABLE,
4037
+ completion: "not-performed",
4038
+ summary: "Graph checks did not start because configuration, runtime, or inputs were unavailable."
4039
+ };
4040
+ }
4041
+ if (hasFindings) {
4042
+ return {
4043
+ code: GRAPH_DOMAIN_CODES.FINDINGS,
4044
+ completion: missing.length > 0 ? "partial" : "complete",
4045
+ summary: "At least one completed graph check reported issues. Original issues are preserved."
4046
+ };
4047
+ }
4048
+ if (missing.length > 0) {
4049
+ return {
4050
+ code: GRAPH_DOMAIN_CODES.INCOMPLETE,
4051
+ completion: "partial",
4052
+ summary: "Some declared graph checks completed without findings; others lacked input or could not finish."
4053
+ };
4054
+ }
4055
+ return {
4056
+ code: GRAPH_DOMAIN_CODES.CLEAR,
4057
+ completion: "complete",
4058
+ summary: "Declared graph checks completed without issues. This does not prove unregistered relations or content correctness."
4059
+ };
4060
+ }
4061
+ function buildLimitations(checks) {
4062
+ const limitations = [STANDING_LIMITATION];
4063
+ for (const check of checks) {
4064
+ if (check.status === "not-performed") {
4065
+ limitations.push(`${check.name} did not complete: ${check.reason ?? "unknown error"}`);
4066
+ }
4067
+ if (check.coverage?.behaviorStatus === "not-evaluated") {
4068
+ limitations.push("coverage does not evaluate whether declared verification actually ran.");
4069
+ }
4070
+ if (check.coverage?.changedPathScope === "unavailable") {
4071
+ limitations.push("coverage could not observe Git worktree changes.");
4072
+ }
4073
+ }
4074
+ return [...new Set(limitations)];
4075
+ }
4076
+ function buildConclusion(root, checks) {
4077
+ const absoluteRoot = resolve5(root);
4078
+ const mapped = mapDomain(checks);
4079
+ const checked = checks.filter((check) => check.status === "completed").map((check) => check.name);
4080
+ const limitations = buildLimitations(checks);
4081
+ const issues = checks.flatMap((check) => check.issues);
4082
+ return {
4083
+ schemaVersion: 1,
4084
+ kind: "skill-family.professional-conclusion",
4085
+ provider: {
4086
+ id: GRAPH_PROVIDER_ID,
4087
+ version: providerVersion(),
4088
+ entry: GRAPH_PROVIDER_ENTRY
4089
+ },
4090
+ subject: {
4091
+ ref: pathToFileURL(absoluteRoot).href
4092
+ },
4093
+ scope: {
4094
+ checked: mapped.completion === "not-performed" ? [] : checked,
4095
+ limitations
4096
+ },
4097
+ outcome: {
4098
+ completion: mapped.completion,
4099
+ code: mapped.code,
4100
+ summary: mapped.summary
4101
+ },
4102
+ details: {
4103
+ checks: checks.map((check) => ({
4104
+ name: check.name,
4105
+ status: check.status,
4106
+ issueCount: check.issues.length,
4107
+ ...check.reason ? { reason: check.reason } : {},
4108
+ ...check.coverage ? { coverage: check.coverage } : {}
4109
+ })),
4110
+ issues
4111
+ }
4112
+ };
4113
+ }
4114
+ async function assertConclusionShape(conclusion) {
4115
+ const contracts = await loadContracts();
4116
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4117
+ if (registration === null) {
4118
+ throw new Error("skill-family-contracts 0.22.0 does not register professional-conclusion");
4119
+ }
4120
+ const verdict = contracts.validateDocument(conclusion, {
4121
+ schemaId: registration.$id,
4122
+ dialect: registration.dialect,
4123
+ policy: "strict"
4124
+ });
4125
+ if (!verdict.valid) {
4126
+ throw new Error(`constructed professional conclusion failed public schema validation (${verdict.errorCode ?? "invalid"})`);
4127
+ }
4128
+ }
4129
+ async function publishConclusion(absoluteOutput, conclusion) {
4130
+ if (!isAbsolute4(absoluteOutput)) {
4131
+ return "--conclusion-output must be an absolute path";
4132
+ }
4133
+ const outputRoot = dirname5(absoluteOutput);
4134
+ const relPath = basename3(absoluteOutput);
4135
+ if (relPath.length === 0 || relPath === "." || relPath === "..") {
4136
+ return "--conclusion-output must name a file";
4137
+ }
4138
+ try {
4139
+ const harness = await loadHarness();
4140
+ await harness.publishFileExclusive(outputRoot, relPath, `${JSON.stringify(conclusion, null, 2)}
4141
+ `);
4142
+ return void 0;
4143
+ } catch (error) {
4144
+ const kind = harnessKind(error);
4145
+ if (kind === "exclusive-publish-conflict") {
4146
+ return `exclusive publication target already exists: ${absoluteOutput}`;
4147
+ }
4148
+ return errorMessage(error);
4149
+ }
4150
+ }
4151
+ async function runCheckProfessional(options) {
4152
+ const root = resolve5(options.root);
4153
+ const configGap = await missingRequiredConfig(root);
4154
+ const checks = configGap === void 0 ? await Promise.all([
4155
+ settleCheck(CHECK_VALIDATE, () => runValidate(root)),
4156
+ settleCheck(CHECK_LOCK, () => runLockAudit(root)),
4157
+ settleCheck(CHECK_COVERAGE, () => runCoverage(root))
4158
+ ]) : [
4159
+ { name: CHECK_VALIDATE, status: "not-performed", issues: [], reason: configGap },
4160
+ { name: CHECK_LOCK, status: "not-performed", issues: [], reason: configGap },
4161
+ { name: CHECK_COVERAGE, status: "not-performed", issues: [], reason: configGap }
4162
+ ];
4163
+ const conclusion = buildConclusion(root, checks);
4164
+ await assertConclusionShape(conclusion);
4165
+ if (options.conclusionOutput === void 0) {
4166
+ return { conclusion };
4167
+ }
4168
+ if (!isAbsolute4(options.conclusionOutput)) {
4169
+ return { conclusion, writeError: "--conclusion-output must be an absolute path" };
4170
+ }
4171
+ const writeError = await publishConclusion(resolve5(options.conclusionOutput), conclusion);
4172
+ return { conclusion, ...writeError ? { writeError } : {} };
4173
+ }
4174
+ function asRecord(value) {
4175
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
4176
+ return null;
4177
+ }
4178
+ return value;
4179
+ }
4180
+ function readProvider(value) {
4181
+ const record = asRecord(value);
4182
+ if (record === null) {
4183
+ return null;
4184
+ }
4185
+ const provider = {};
4186
+ if (typeof record.id === "string") provider.id = record.id;
4187
+ if (typeof record.version === "string") provider.version = record.version;
4188
+ if (typeof record.entry === "string") provider.entry = record.entry;
4189
+ return Object.keys(provider).length > 0 ? provider : null;
4190
+ }
4191
+ function interpretConclusion(conclusion) {
4192
+ const provider = conclusion.provider;
4193
+ if (provider.id !== GRAPH_PROVIDER_ID) {
4194
+ return {
4195
+ status: "unavailable",
4196
+ reason: `proof provider ${provider.id} is not ${GRAPH_PROVIDER_ID}`,
4197
+ provider,
4198
+ conclusion
4199
+ };
4200
+ }
4201
+ if (!KNOWN_DOMAIN_CODES.has(conclusion.outcome.code)) {
4202
+ return {
4203
+ status: "unavailable",
4204
+ reason: `unknown same-version domain code: ${conclusion.outcome.code}`,
4205
+ provider,
4206
+ conclusion
4207
+ };
4208
+ }
4209
+ if (conclusion.outcome.code === GRAPH_DOMAIN_CODES.CLEAR && conclusion.outcome.completion === "complete") {
4210
+ return {
4211
+ status: "pass",
4212
+ reason: "GRAPH_CLEAR with complete scope is acceptable for this provider version.",
4213
+ provider,
4214
+ conclusion
4215
+ };
4216
+ }
4217
+ return {
4218
+ status: "not_pass",
4219
+ reason: `proof records ${conclusion.outcome.code} (${conclusion.outcome.completion}); complete does not mean pass.`,
4220
+ provider,
4221
+ conclusion
4222
+ };
4223
+ }
4224
+ async function runReadProof(options) {
4225
+ const unavailable = (reason, provider = null, conclusion = null) => ({
4226
+ result: { status: "unavailable", reason, provider, conclusion },
4227
+ exitCode: 2
4228
+ });
4229
+ let receipt;
4230
+ try {
4231
+ const harness = await loadHarness();
4232
+ receipt = await harness.readFileStrict(options.proofRoot, options.proof, { encoding: "utf8" });
4233
+ } catch (error) {
4234
+ const kind = harnessKind(error);
4235
+ if (kind === "missing-resource") {
4236
+ return unavailable(`proof file does not exist: ${options.proof}`, null, null);
4237
+ }
4238
+ return unavailable(errorMessage(error), null, null);
4239
+ }
4240
+ const raw = typeof receipt.content === "string" ? receipt.content : receipt.content.toString("utf8");
4241
+ let parsed;
4242
+ try {
4243
+ parsed = JSON.parse(raw);
4244
+ } catch (error) {
4245
+ return unavailable(`proof is not valid JSON: ${errorMessage(error)}`, null, null);
4246
+ }
4247
+ const previewProvider = readProvider(asRecord(parsed)?.provider);
4248
+ let contracts;
4249
+ try {
4250
+ contracts = await loadContracts();
4251
+ } catch (error) {
4252
+ return unavailable(`cannot load skill-family-contracts: ${errorMessage(error)}`, previewProvider, null);
4253
+ }
4254
+ const registration = contracts.findSchemaByObject(PROFESSIONAL_CONCLUSION_OBJECT);
4255
+ if (registration === null) {
4256
+ return unavailable("professional-conclusion schema is not registered", previewProvider, null);
4257
+ }
4258
+ const verdict = contracts.validateDocument(parsed, {
4259
+ schemaId: registration.$id,
4260
+ dialect: registration.dialect,
4261
+ policy: "strict"
4262
+ });
4263
+ if (!verdict.valid) {
4264
+ return unavailable(
4265
+ `proof failed professional-conclusion schema validation (${verdict.errorCode ?? "invalid"})`,
4266
+ previewProvider,
4267
+ null
4268
+ );
4269
+ }
4270
+ const interpreted = interpretConclusion(parsed);
4271
+ const exitCode = interpreted.status === "pass" ? 0 : interpreted.status === "not_pass" ? 1 : 2;
4272
+ return { result: interpreted, exitCode };
4273
+ }
4274
+ 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;
4275
+ var init_professional_conclusion = __esm({
4276
+ "src/professional-conclusion.ts"() {
4277
+ "use strict";
4278
+ init_coverage();
4279
+ init_index();
4280
+ init_versioned_traceability();
4281
+ GRAPH_PROVIDER_ID = "artifact-graph";
4282
+ GRAPH_PROVIDER_ENTRY = "check-professional";
4283
+ PROFESSIONAL_CONCLUSION_OBJECT = "professional-conclusion";
4284
+ GRAPH_DOMAIN_CODES = Object.freeze({
4285
+ CLEAR: "GRAPH_CLEAR",
4286
+ FINDINGS: "GRAPH_FINDINGS",
4287
+ INCOMPLETE: "GRAPH_CHECK_INCOMPLETE",
4288
+ UNAVAILABLE: "GRAPH_CHECK_UNAVAILABLE"
4289
+ });
4290
+ KNOWN_DOMAIN_CODES = new Set(Object.values(GRAPH_DOMAIN_CODES));
4291
+ CHECK_VALIDATE = "validate";
4292
+ CHECK_LOCK = "version-lock-audit";
4293
+ CHECK_COVERAGE = "coverage";
4294
+ STANDING_LIMITATION = "Graph checks do not prove content semantics, method execution, or publication facts.";
4295
+ CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
4296
+ }
4297
+ });
4298
+
3898
4299
  // src/review-result-validator.ts
3899
4300
  function validateReviewResult(input) {
3900
4301
  const errors = [];
@@ -3972,8 +4373,8 @@ function validateReviewResult(input) {
3972
4373
  validateReviewData(obj.review, "$.review", errors);
3973
4374
  if (obj.decision === "PASS" || obj.decision === "PASS_WITH_RESIDUAL_MINOR") {
3974
4375
  const findings = isPlainObject(obj.review) && Array.isArray(obj.review.findings) ? obj.review.findings : [];
3975
- findings.forEach((finding, index) => {
3976
- if (isPlainObject(finding) && finding.severity === "block" && (finding.status === void 0 || finding.status === "open")) {
4376
+ findings.forEach((finding2, index) => {
4377
+ if (isPlainObject(finding2) && finding2.severity === "block" && (finding2.status === void 0 || finding2.status === "open")) {
3977
4378
  errors.push({
3978
4379
  path: `$.review.findings[${index}]`,
3979
4380
  message: `${obj.decision} cannot contain an open block finding`
@@ -4246,7 +4647,7 @@ __export(contract_kernel_exports, {
4246
4647
  });
4247
4648
  import { createHash as createHash2 } from "crypto";
4248
4649
  import { readFile as readFile2, readdir as readdir2 } from "fs/promises";
4249
- import { join as join7 } from "path";
4650
+ import { join as join8 } from "path";
4250
4651
  import _AjvModule from "ajv";
4251
4652
  function isOfficialNamespace(namespace) {
4252
4653
  return OFFICIAL_NAMESPACE_PATTERN.test(namespace);
@@ -4659,7 +5060,7 @@ async function loadContractsFromDirectory(contractsDir, options) {
4659
5060
  const entries = await readdir2(contractsDir, { withFileTypes: true });
4660
5061
  for (const entry of entries) {
4661
5062
  if (entry.isDirectory()) {
4662
- const schemaPath = join7(contractsDir, entry.name, "schema.json");
5063
+ const schemaPath = join8(contractsDir, entry.name, "schema.json");
4663
5064
  const contract = await loadContract(schemaPath, options);
4664
5065
  contracts.push(contract);
4665
5066
  }
@@ -5146,107 +5547,1827 @@ var init_contract_kernel = __esm({
5146
5547
  }
5147
5548
  });
5148
5549
 
5149
- // src/index.ts
5150
- import matter from "gray-matter";
5151
- import yaml from "js-yaml";
5152
- import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
5153
- import { mkdir as mkdir4, readFile as readFile3, readdir as readdir3, writeFile as writeFile3 } from "fs/promises";
5154
- import { basename as basename4, dirname as dirname5, extname, isAbsolute as isAbsolute4, join as join8, relative as relative4, resolve as resolve5 } from "path";
5155
- function isTargetArtifactType(type) {
5156
- return isPacketTargetType(type);
5157
- }
5158
- function normalizeArtifactTypeRole(role) {
5159
- if (typeof role === "string") {
5160
- if (isTargetArtifactType(role)) return role;
5161
- if (NON_TARGET_ROLES.includes(role)) return role;
5550
+ // src/restructure-software.ts
5551
+ function lineStarts(raw) {
5552
+ const starts = [0];
5553
+ const buffer = Buffer.from(raw, "utf8");
5554
+ for (let index = 0; index < buffer.length; index += 1) {
5555
+ if (buffer[index] === 10) starts.push(index + 1);
5162
5556
  }
5163
- return "context";
5557
+ return starts;
5164
5558
  }
5165
- function getArtifactTypeMetadata(schema, type) {
5166
- const definition = schema.types[type];
5167
- const role = normalizeArtifactTypeRole(definition?.role);
5168
- const aliases = Array.isArray(definition?.aliases) ? definition.aliases.filter((alias) => typeof alias === "string" && alias.trim().length > 0) : [];
5169
- const legacyCoreRoleMatch = isTargetArtifactType(type) && role === type;
5170
- const targetCapable = definition?.target === true || legacyCoreRoleMatch;
5559
+ function markdownCodeLineMask(lines) {
5560
+ const result = new Array(lines.length).fill(false);
5561
+ let fence;
5562
+ lines.forEach((line, index) => {
5563
+ if (fence) {
5564
+ result[index] = true;
5565
+ const closing = /^ {0,3}(`+|~+)[ \t]*\r?$/.exec(line);
5566
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) fence = void 0;
5567
+ return;
5568
+ }
5569
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)\r?$/.exec(line);
5570
+ if (opening) {
5571
+ result[index] = true;
5572
+ fence = { marker: opening[1][0], length: opening[1].length };
5573
+ return;
5574
+ }
5575
+ if (/^(?: {4,}| {0,3}\t)/.test(line)) result[index] = true;
5576
+ });
5577
+ return result;
5578
+ }
5579
+ function markdownRecordHeadings(raw, type) {
5580
+ const lines = raw.split("\n");
5581
+ const masked = markdownCodeLineMask(lines);
5582
+ 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;
5583
+ if (!pattern) return [];
5584
+ return lines.flatMap((line, index) => {
5585
+ if (masked[index]) return [];
5586
+ const match = pattern.exec(line.replace(/\r$/, ""));
5587
+ return match ? [{ id: match[1], line: index + 1 }] : [];
5588
+ });
5589
+ }
5590
+ function locateSoftwareRecord(raw, node, nodesInFile) {
5591
+ const byteLength = Buffer.byteLength(raw, "utf8");
5592
+ if (node.type === "feature") return { range: { startByte: 0, endByte: byteLength }, blockers: [] };
5593
+ if (node.type !== "scenario" && node.type !== "e2e_test") {
5594
+ return {
5595
+ blockers: [{
5596
+ code: "UNSUPPORTED_RECORD_BOUNDARY",
5597
+ message: `\u9996\u8F6E\u4E0D\u652F\u6301 ${node.type} \u7684\u8BB0\u5F55\u8FB9\u754C\u7F16\u8BD1`,
5598
+ path: node.path,
5599
+ line: node.line
5600
+ }]
5601
+ };
5602
+ }
5603
+ const headings = markdownRecordHeadings(raw, node.type);
5604
+ const expectedId = node.type === "e2e_test" ? String(node.attrs?.testCaseId ?? "") : node.code;
5605
+ const heading = headings.find((item) => item.id === expectedId && item.line === node.line);
5606
+ const graphRecords = nodesInFile.filter((item) => item.type === node.type && item.attrs?.fileLevelOnly !== true);
5607
+ const graphLocations = new Set(graphRecords.map((item) => `${item.type === "e2e_test" ? String(item.attrs?.testCaseId ?? "") : item.code}:${item.line}`));
5608
+ const headingLocations = new Set(headings.map((item) => `${item.id}:${item.line}`));
5609
+ const inconsistent = graphLocations.size !== headingLocations.size || [...graphLocations].some((item) => !headingLocations.has(item));
5610
+ if (inconsistent) {
5611
+ return {
5612
+ blockers: [{
5613
+ code: node.type === "e2e_test" ? "E2E_BOUNDARY_INCONSISTENT" : "RECORD_BOUNDARY_INCONSISTENT",
5614
+ 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",
5615
+ path: node.path,
5616
+ line: node.line
5617
+ }]
5618
+ };
5619
+ }
5620
+ if (!heading) {
5621
+ return {
5622
+ blockers: [{
5623
+ code: "RECORD_BOUNDARY_MISSING",
5624
+ message: `\u65E0\u6CD5\u5B9A\u4F4D ${node.uid} \u7684\u6B63\u6587\u8FB9\u754C`,
5625
+ path: node.path,
5626
+ line: node.line
5627
+ }]
5628
+ };
5629
+ }
5630
+ const starts = lineStarts(raw);
5631
+ const nextLine = headings.find((item) => item.line > heading.line)?.line;
5171
5632
  return {
5172
- type,
5173
- displayName: definition?.displayName?.trim() || type,
5174
- role,
5175
- layer: definition?.layer?.trim() || "context",
5176
- aliases,
5177
- targetCapable
5633
+ range: {
5634
+ startByte: starts[heading.line - 1] ?? 0,
5635
+ endByte: nextLine ? starts[nextLine - 1] ?? byteLength : byteLength
5636
+ },
5637
+ blockers: []
5178
5638
  };
5179
5639
  }
5180
- function getTargetArtifactTypes(schema = DEFAULT_SCHEMA) {
5181
- const legacy = TARGET_ARTIFACT_TYPES.filter((type) => getArtifactTypeMetadata(schema, type).targetCapable);
5182
- const extras = Object.keys(schema.types).filter(
5183
- (type) => getArtifactTypeMetadata(schema, type).targetCapable && !legacy.includes(type)
5184
- );
5185
- return [...legacy, ...extras];
5640
+ function replaceSoftwareHeader(raw, header) {
5641
+ const match = /^---(?:\r?\n)[\s\S]*?(?:\r?\n)---(?:\r?\n)?/.exec(raw);
5642
+ const normalized = header.length > 0 && !/\r?\n$/.test(header) ? `${header}
5643
+ ` : header;
5644
+ return match ? `${normalized}${raw.slice(match[0].length)}` : `${normalized}${raw}`;
5186
5645
  }
5187
- function resolveArtifactTypeName(schema, token) {
5188
- if (!token) return void 0;
5189
- if (schema.types[token]) return token;
5190
- for (const [type, definition] of Object.entries(schema.types)) {
5191
- if (definition.aliases?.includes(token)) return type;
5646
+ var init_restructure_software = __esm({
5647
+ "src/restructure-software.ts"() {
5648
+ "use strict";
5192
5649
  }
5193
- return void 0;
5650
+ });
5651
+
5652
+ // src/restructure-file-set.ts
5653
+ import { createHash as createHash3 } from "crypto";
5654
+ import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
5655
+ import { join as join9, resolve as resolve6 } from "path";
5656
+ async function loadFoundationModule() {
5657
+ return await import(FOUNDATION_PACKAGE_NAME);
5658
+ }
5659
+ async function loadContractsModule() {
5660
+ return await import(CONTRACTS_PACKAGE_NAME2);
5661
+ }
5662
+ async function verifyMechanismResult(result) {
5663
+ if (typeof result !== "object" || result === null || Array.isArray(result)) {
5664
+ return failure("MECHANISM_RESULT_INVALID", "applyFileSet returned no concrete result object");
5665
+ }
5666
+ let contracts;
5667
+ let registration;
5668
+ try {
5669
+ contracts = await loadContractsModule();
5670
+ registration = contracts.findSchemaByObject(FILE_SET_RESULT_OBJECT);
5671
+ } catch (cause) {
5672
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published ${FILE_SET_RESULT_OBJECT} schema cannot be loaded: ${cause.message}`);
5673
+ }
5674
+ if (registration === null) {
5675
+ return failure("MECHANISM_RESULT_UNVERIFIABLE", `The published contracts package no longer registers ${FILE_SET_RESULT_OBJECT}`);
5676
+ }
5677
+ const verdict = contracts.validateDocument(result, {
5678
+ schemaId: registration.$id,
5679
+ dialect: registration.dialect,
5680
+ policy: "strict"
5681
+ });
5682
+ if (!verdict.valid) {
5683
+ return failure(
5684
+ "MECHANISM_RESULT_INVALID",
5685
+ `The mechanism result is not a valid ${FILE_SET_RESULT_OBJECT} document (${verdict.errorCode ?? "invalid"})`,
5686
+ { schemaId: registration.$id, errorCode: verdict.errorCode ?? null, errors: verdict.errors ?? [] }
5687
+ );
5688
+ }
5689
+ return { ok: true, data: result };
5194
5690
  }
5195
- async function loadConfig(root) {
5196
- const configPath = join8(root, "artifact-graph.config.yaml");
5197
- let parsed = {};
5691
+ function failure(code, message, details) {
5692
+ return { ok: false, error: { code, message, ...details === void 0 ? {} : { details } } };
5693
+ }
5694
+ function candidateBytes(content) {
5695
+ return Buffer.from(content ?? "", "utf8");
5696
+ }
5697
+ function candidateByteDigest(content) {
5698
+ return createHash3("sha256").update(candidateBytes(content)).digest("hex");
5699
+ }
5700
+ function rawDigest(value, path) {
5701
+ if (typeof value !== "string" || !value.startsWith(DIGEST_PREFIX)) {
5702
+ throw new Error(`${path} does not carry a ${DIGEST_PREFIX}<hex> digest`);
5703
+ }
5704
+ const raw = value.slice(DIGEST_PREFIX.length);
5705
+ if (!RAW_SHA256_PATTERN.test(raw)) {
5706
+ throw new Error(`${path} digest is not 64 lowercase hexadecimal characters`);
5707
+ }
5708
+ return raw;
5709
+ }
5710
+ async function resolveRealRoot(root) {
5711
+ let canonical;
5198
5712
  try {
5199
- const raw = await readFile3(configPath, "utf-8");
5200
- parsed = yaml.load(raw) ?? {};
5201
- } catch (error) {
5202
- if (error.code !== "ENOENT") {
5203
- throw error;
5204
- }
5713
+ canonical = await realpath(resolve6(root));
5714
+ } catch (cause) {
5715
+ return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5205
5716
  }
5206
- const ub = parsed.context?.universal_baseline;
5207
- if (ub !== void 0 && typeof ub !== "boolean") {
5208
- throw new Error(
5209
- `Invalid context.universal_baseline: ${JSON.stringify(ub)}. Must be boolean (true or false).`
5210
- );
5717
+ let info;
5718
+ try {
5719
+ info = await lstat2(canonical);
5720
+ } catch (cause) {
5721
+ return failure("ROOT_INVALID", `Project root cannot be inspected: ${cause.message}`);
5211
5722
  }
5212
- if (parsed.e2e !== void 0) {
5213
- if (typeof parsed.e2e !== "object" || parsed.e2e === null || Array.isArray(parsed.e2e)) {
5214
- throw new Error("Invalid e2e: must be an object.");
5215
- }
5216
- validateE2eConfig(parsed.e2e);
5723
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5724
+ return failure("ROOT_INVALID", `Project root must be one real directory: ${canonical}`);
5217
5725
  }
5218
- validateRelationSemanticsConfig(parsed.relationSemantics);
5219
- validateStatusViewsConfig(parsed.statusViews);
5220
- const mergedE2e = parsed.e2e === void 0 ? DEFAULT_SCHEMA.e2e : {
5221
- ...DEFAULT_SCHEMA.e2e,
5222
- ...parsed.e2e,
5223
- runners: (parsed.e2e.runners ?? DEFAULT_SCHEMA.e2e?.runners ?? []).map((runner) => ({
5224
- kind: "e2e",
5225
- ...runner
5226
- }))
5227
- };
5228
- const merged = {
5229
- ...DEFAULT_SCHEMA,
5230
- ...parsed,
5231
- types: mergeArtifactTypes(DEFAULT_SCHEMA.types, parsed.types),
5232
- idPatterns: mergeRecord(DEFAULT_SCHEMA.idPatterns, parsed.idPatterns),
5233
- relationFields: mergeRecord(DEFAULT_SCHEMA.relationFields, parsed.relationFields),
5234
- allowedEdges: parsed.allowedEdges ?? DEFAULT_SCHEMA.allowedEdges,
5235
- forbiddenEdges: parsed.forbiddenEdges ?? DEFAULT_SCHEMA.forbiddenEdges,
5236
- statuses: parsed.statuses ?? DEFAULT_SCHEMA.statuses,
5237
- idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
5238
- e2e: mergedE2e
5239
- };
5240
- return merged;
5726
+ return { ok: true, data: canonical };
5241
5727
  }
5242
- function validateRelationSemanticsConfig(value) {
5243
- if (value === void 0) return;
5244
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
5245
- throw new Error("Invalid relationSemantics: must be an object keyed by relation kind.");
5728
+ async function qualifyRestructureMechanism(root) {
5729
+ if (process.platform !== RESTRUCTURE_QUALIFIED_PLATFORM || process.arch !== RESTRUCTURE_QUALIFIED_ARCH) {
5730
+ return failure(
5731
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5732
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_PLATFORM}/${RESTRUCTURE_QUALIFIED_ARCH}; this runtime is ${process.platform}/${process.arch}`
5733
+ );
5246
5734
  }
5247
- for (const [kind, spec] of Object.entries(value)) {
5248
- if (!kind.trim() || typeof spec !== "object" || spec === null || Array.isArray(spec)) {
5249
- throw new Error(`Invalid relationSemantics.${kind}: must be an object.`);
5735
+ const canonical = await resolveRealRoot(root);
5736
+ if (!canonical.ok) return canonical;
5737
+ let type;
5738
+ try {
5739
+ type = (await statfs(canonical.data)).type;
5740
+ } catch (cause) {
5741
+ return failure("APPLY_ENVIRONMENT_UNSUPPORTED", `Project root filesystem cannot be inspected: ${cause.message}`);
5742
+ }
5743
+ if (type !== APFS_STATFS_TYPE) {
5744
+ return failure(
5745
+ "APPLY_ENVIRONMENT_UNSUPPORTED",
5746
+ `Real apply is qualified only on ${RESTRUCTURE_QUALIFIED_FILESYSTEM}; the project root reports filesystem type ${type}`
5747
+ );
5748
+ }
5749
+ return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5750
+ }
5751
+ async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5752
+ const target = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5753
+ const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5754
+ let info = await current();
5755
+ if (info === null) {
5756
+ if (!options.create) {
5757
+ return failure(
5758
+ "RECOVERY_MATERIALS_MISSING",
5759
+ `No ${RESTRUCTURE_RECOVERY_REL_PATH} mechanism directory exists under ${canonicalRoot}`
5760
+ );
5761
+ }
5762
+ let created = false;
5763
+ try {
5764
+ await mkdir4(target, { mode: RESTRUCTURE_RECOVERY_ROOT_MODE });
5765
+ created = true;
5766
+ } catch (cause) {
5767
+ if (cause.code !== "EEXIST") {
5768
+ return failure("MECHANISM_ROOT_UNSAFE", `Cannot create ${target}: ${cause.message}`);
5769
+ }
5770
+ }
5771
+ info = await current();
5772
+ if (info === null) return failure("MECHANISM_ROOT_UNSAFE", `${target} disappeared while it was being created`);
5773
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5774
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5775
+ }
5776
+ if (created && (info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5777
+ await chmod(target, RESTRUCTURE_RECOVERY_ROOT_MODE);
5778
+ info = await current();
5779
+ if (info === null || info.isSymbolicLink() || !info.isDirectory()) {
5780
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5781
+ }
5782
+ }
5783
+ }
5784
+ if (info.isSymbolicLink() || !info.isDirectory()) {
5785
+ return failure("MECHANISM_ROOT_UNSAFE", `${target} must be one real directory, not a link or special entry`);
5786
+ }
5787
+ if ((info.mode & 4095) !== RESTRUCTURE_RECOVERY_ROOT_MODE) {
5788
+ return failure(
5789
+ "MECHANISM_ROOT_UNSAFE",
5790
+ `${target} must have mode 0${RESTRUCTURE_RECOVERY_ROOT_MODE.toString(8)}; it has 0${(info.mode & 4095).toString(8)}`
5791
+ );
5792
+ }
5793
+ return { ok: true, data: target };
5794
+ }
5795
+ async function createRestructureRootBinding(canonicalRoot) {
5796
+ try {
5797
+ const module = await loadFoundationModule();
5798
+ return { ok: true, data: await module.createFilesystemRootBinding(canonicalRoot) };
5799
+ } catch (cause) {
5800
+ return failure("MECHANISM_CALL_FAILED", `The adopted mechanism refused the project root binding: ${cause.message}`);
5801
+ }
5802
+ }
5803
+ function toOperation(candidate) {
5804
+ const expected = candidate.original.exists ? {
5805
+ exists: true,
5806
+ sha256: rawDigest(candidate.original.sha256, `${candidate.path} original`),
5807
+ size: candidate.original.size,
5808
+ mode: candidate.original.mode
5809
+ } : { exists: false };
5810
+ if (candidate.action === "delete") {
5811
+ return { path: candidate.path, action: "delete", expected, next: null };
5812
+ }
5813
+ const bytes = candidateBytes(candidate.content);
5814
+ const declared = rawDigest(candidate.sha256, candidate.path);
5815
+ if (declared !== candidateByteDigest(candidate.content)) {
5816
+ throw new Error(`${candidate.path} candidate bytes do not match their frozen digest`);
5817
+ }
5818
+ return {
5819
+ path: candidate.path,
5820
+ action: candidate.action,
5821
+ expected,
5822
+ next: { sha256: declared, size: bytes.byteLength, mode: candidate.mode, bytes }
5823
+ };
5824
+ }
5825
+ async function buildFileSetApplyRequest(canonicalRoot, plan) {
5826
+ if (plan.candidates.length === 0) {
5827
+ return failure("PLAN_ZERO_OPERATIONS", "A plan with no file operations has nothing to apply");
5828
+ }
5829
+ const binding = await createRestructureRootBinding(canonicalRoot);
5830
+ if (!binding.ok) return binding;
5831
+ let operations;
5832
+ try {
5833
+ operations = plan.candidates.map(toOperation);
5834
+ } catch (cause) {
5835
+ return failure("CANDIDATE_BYTES_MISMATCH", cause.message);
5836
+ }
5837
+ return {
5838
+ ok: true,
5839
+ data: {
5840
+ schemaVersion: 1,
5841
+ kind: "skill-family.file-set-apply-request",
5842
+ operationId: plan.operation_id,
5843
+ root: canonicalRoot,
5844
+ rootBinding: binding.data,
5845
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5846
+ allowAdjacentStaging: true,
5847
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5848
+ validationTimeoutMs: plan.validation_timeout_ms,
5849
+ operations
5850
+ }
5851
+ };
5852
+ }
5853
+ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5854
+ const request = await buildFileSetApplyRequest(canonicalRoot, plan);
5855
+ if (!request.ok) return request;
5856
+ const module = await loadFoundationModule();
5857
+ let raw;
5858
+ try {
5859
+ raw = await module.applyFileSet(request.data, { validate: options.validate });
5860
+ } catch (cause) {
5861
+ return failure("MECHANISM_CALL_FAILED", `applyFileSet did not return a mechanism result: ${cause.message}`);
5862
+ }
5863
+ return await verifyMechanismResult(raw);
5864
+ }
5865
+ async function observeRestructureJournal(canonicalRoot) {
5866
+ const journalRoot = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5867
+ const module = await loadFoundationModule();
5868
+ try {
5869
+ return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
5870
+ } catch (cause) {
5871
+ return failure(
5872
+ "MAINTENANCE_OBSERVATION_FAILED",
5873
+ `The ${RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH} journal cannot be observed: ${cause.message}`
5874
+ );
5875
+ }
5876
+ }
5877
+ async function recoverRestructureFileSet(canonicalRoot, plan, options) {
5878
+ if (!options.allParticipantsStopped || !options.exclusiveMaintenance) {
5879
+ return failure(
5880
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
5881
+ "restructure recover requires --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
5882
+ );
5883
+ }
5884
+ const binding = await createRestructureRootBinding(canonicalRoot);
5885
+ if (!binding.ok) return binding;
5886
+ const observation = await observeRestructureJournal(canonicalRoot);
5887
+ if (!observation.ok) return observation;
5888
+ const maintenance = {
5889
+ observation: observation.data,
5890
+ confirmAllParticipantsStopped: true,
5891
+ confirmExclusiveMaintenance: true
5892
+ };
5893
+ const request = {
5894
+ schemaVersion: 1,
5895
+ kind: "skill-family.file-set-recovery-request",
5896
+ operationId: plan.operation_id,
5897
+ root: canonicalRoot,
5898
+ rootBinding: binding.data,
5899
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5900
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true },
5901
+ allowAdjacentStaging: true,
5902
+ maintenance
5903
+ };
5904
+ const module = await loadFoundationModule();
5905
+ let raw;
5906
+ try {
5907
+ raw = await module.recoverFileSet(request);
5908
+ } catch (cause) {
5909
+ return failure("MECHANISM_CALL_FAILED", `recoverFileSet did not return a mechanism result: ${cause.message}`);
5910
+ }
5911
+ return await verifyMechanismResult(raw);
5912
+ }
5913
+ async function pruneRestructureFileSet(canonicalRoot, plan, options) {
5914
+ const binding = await createRestructureRootBinding(canonicalRoot);
5915
+ if (!binding.ok) return binding;
5916
+ const request = {
5917
+ schemaVersion: 1,
5918
+ kind: "skill-family.file-set-prune-request",
5919
+ operationId: plan.operation_id,
5920
+ root: canonicalRoot,
5921
+ rootBinding: binding.data,
5922
+ recoveryRelPath: RESTRUCTURE_RECOVERY_REL_PATH,
5923
+ environment: { filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM, cooperativeWriters: true }
5924
+ };
5925
+ if (options.allParticipantsStopped && options.exclusiveMaintenance) {
5926
+ const observation = await observeRestructureJournal(canonicalRoot);
5927
+ if (!observation.ok) return observation;
5928
+ request.maintenance = {
5929
+ observation: observation.data,
5930
+ confirmAllParticipantsStopped: true,
5931
+ confirmExclusiveMaintenance: true
5932
+ };
5933
+ }
5934
+ const module = await loadFoundationModule();
5935
+ let raw;
5936
+ try {
5937
+ raw = await module.pruneFileSetRecovery(request);
5938
+ } catch (cause) {
5939
+ return failure("MECHANISM_CALL_FAILED", `pruneFileSetRecovery did not return a mechanism result: ${cause.message}`);
5940
+ }
5941
+ return await verifyMechanismResult(raw);
5942
+ }
5943
+ function validationState(validation) {
5944
+ return validation.reason === null ? `validation.${validation.status}` : `validation.${validation.status}/${validation.reason}`;
5945
+ }
5946
+ function errorKinds(result) {
5947
+ return [...new Set(result.errors.map((entry) => entry.details.kind))].sort();
5948
+ }
5949
+ function applyProjection(result) {
5950
+ const kinds = errorKinds(result);
5951
+ if (result.outcome === "committed") {
5952
+ if (kinds.some((kind) => APPLY_MAINTENANCE_ERROR_KINDS.includes(kind))) {
5953
+ return {
5954
+ code: "APPLY_COMMITTED_MAINTENANCE_REQUIRED",
5955
+ 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.",
5956
+ ok: false,
5957
+ rerunApplyPermitted: false
5958
+ };
5959
+ }
5960
+ const unconditional = result.validation.status === "passed" && result.errors.length === 0 && result.paths.length > 0 && result.paths.every((entry) => entry.current === "expected-new");
5961
+ return unconditional ? { code: "APPLIED", message: `Applied ${result.paths.length} file operation(s); every path is at its frozen new state.`, ok: true, rerunApplyPermitted: false } : {
5962
+ code: "APPLY_INCOMPLETE",
5963
+ message: "The mechanism reported a commit but the per-path facts or validation do not support unconditional success.",
5964
+ ok: false,
5965
+ rerunApplyPermitted: false
5966
+ };
5967
+ }
5968
+ const codes = {
5969
+ "commit-unconfirmed": ["APPLY_COMMIT_UNCONFIRMED", "The commit decision is durable but its confirmation is incomplete; the file set is never rolled back automatically."],
5970
+ "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."],
5971
+ "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."]
5972
+ };
5973
+ const mapped = codes[result.outcome];
5974
+ if (mapped) return { code: mapped[0], message: mapped[1], ok: false, rerunApplyPermitted: false };
5975
+ if (result.outcome === "rejected") {
5976
+ const identityTaken = kinds.some((kind) => kind === "operation-id-reused" || kind === "unfinished-operation");
5977
+ return {
5978
+ code: "APPLY_REJECTED",
5979
+ 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.",
5980
+ ok: false,
5981
+ rerunApplyPermitted: !identityTaken
5982
+ };
5983
+ }
5984
+ return {
5985
+ code: "APPLY_UNEXPECTED_OUTCOME",
5986
+ message: `The mechanism returned outcome ${result.outcome} for an apply call.`,
5987
+ ok: false,
5988
+ rerunApplyPermitted: false
5989
+ };
5990
+ }
5991
+ function recoverProjection(result) {
5992
+ const reading = (() => {
5993
+ switch (result.outcome) {
5994
+ case "already-committed":
5995
+ return { code: "RECOVER_COMMITTED_CONFIRMED", message: "The recorded commit decision is confirmed as the terminal state; no path was rewritten.", ok: true };
5996
+ case "already-rolled-back":
5997
+ return { code: "RECOVER_ROLLED_BACK_CONFIRMED", message: "The recorded rollback is confirmed as the terminal state.", ok: true };
5998
+ case "rolled-back":
5999
+ return { code: "RECOVER_ROLLED_BACK", message: "The interrupted file set was restored to its original bytes and modes.", ok: true };
6000
+ case "pruned":
6001
+ return { code: "RECOVER_PRUNE_COMPLETED", message: "The interrupted material cleanup of a terminal operation was resumed and finished.", ok: true };
6002
+ case "already-pruned":
6003
+ return { code: "RECOVER_ALREADY_PRUNED", message: "The terminal materials of this operation were already cleaned; the journal is retained.", ok: true };
6004
+ case "commit-unconfirmed":
6005
+ 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 };
6006
+ case "recovery-required":
6007
+ return { code: "RECOVER_REQUIRED", message: "Recovery could not reach a proven terminal state; materials and facts are retained.", ok: false };
6008
+ case "rejected":
6009
+ return { code: "RECOVER_REJECTED", message: "The mechanism refused the recovery request before any business write.", ok: false };
6010
+ default:
6011
+ return { code: "RECOVER_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a recover call.`, ok: false };
6012
+ }
6013
+ })();
6014
+ return { ...reading, rerunApplyPermitted: false };
6015
+ }
6016
+ function pruneProjection(result) {
6017
+ const reading = (() => {
6018
+ switch (result.outcome) {
6019
+ case "pruned":
6020
+ return { code: "PRUNED", message: "The terminal materials of this operation were removed; the journal is retained.", ok: true };
6021
+ case "already-pruned":
6022
+ return { code: "ALREADY_PRUNED", message: "The terminal materials of this operation were already removed.", ok: true };
6023
+ case "rejected":
6024
+ return { code: "PRUNE_REJECTED", message: "The mechanism refused the cleanup before touching any material.", ok: false };
6025
+ case "recovery-required":
6026
+ 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 };
6027
+ default:
6028
+ return { code: "PRUNE_UNEXPECTED_OUTCOME", message: `The mechanism returned outcome ${result.outcome} for a prune call.`, ok: false };
6029
+ }
6030
+ })();
6031
+ return { ...reading, rerunApplyPermitted: false };
6032
+ }
6033
+ function projectRestructureFileSetResult(result, planPath = "", planDigest = "") {
6034
+ const base = {
6035
+ foundation: result,
6036
+ planPath,
6037
+ planDigest,
6038
+ operation: result.operation,
6039
+ outcome: result.outcome,
6040
+ preflight: result.preflight,
6041
+ businessWrite: result.businessWrite,
6042
+ validation: result.validation,
6043
+ validationState: validationState(result.validation),
6044
+ recovery: result.recovery,
6045
+ paths: result.paths,
6046
+ errors: result.errors,
6047
+ materialPath: result.materials.relPath,
6048
+ errorKinds: errorKinds(result)
6049
+ };
6050
+ const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
6051
+ return { ...base, ...reading };
6052
+ }
6053
+ 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;
6054
+ var init_restructure_file_set = __esm({
6055
+ "src/restructure-file-set.ts"() {
6056
+ "use strict";
6057
+ RESTRUCTURE_RECOVERY_REL_PATH = ".foundation-file-apply";
6058
+ RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH = `${RESTRUCTURE_RECOVERY_REL_PATH}/journal`;
6059
+ RESTRUCTURE_RECOVERY_ROOT_MODE = 448;
6060
+ RESTRUCTURE_QUALIFIED_PLATFORM = "darwin";
6061
+ RESTRUCTURE_QUALIFIED_ARCH = "arm64";
6062
+ RESTRUCTURE_QUALIFIED_FILESYSTEM = "apfs";
6063
+ APFS_STATFS_TYPE = 26;
6064
+ DIGEST_PREFIX = "sha256:";
6065
+ RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
6066
+ FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
6067
+ CONTRACTS_PACKAGE_NAME2 = "skill-family-contracts";
6068
+ FILE_SET_RESULT_OBJECT = "file-set-result";
6069
+ APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
6070
+ }
6071
+ });
6072
+
6073
+ // src/restructure.ts
6074
+ var restructure_exports = {};
6075
+ __export(restructure_exports, {
6076
+ RESTRUCTURE_MAX_OPERATIONS: () => RESTRUCTURE_MAX_OPERATIONS,
6077
+ RESTRUCTURE_MAX_TOTAL_BYTES: () => RESTRUCTURE_MAX_TOTAL_BYTES,
6078
+ RESTRUCTURE_PLAN_SCHEMA_VERSION: () => RESTRUCTURE_PLAN_SCHEMA_VERSION,
6079
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS: () => RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6080
+ applyRestructure: () => applyRestructure,
6081
+ createModeForUmask: () => createModeForUmask,
6082
+ createRestructureValidationCallback: () => createRestructureValidationCallback,
6083
+ digestRestructureValue: () => digestRestructureValue,
6084
+ gateRestructureOperationPlan: () => gateRestructureOperationPlan,
6085
+ inspectRestructure: () => inspectRestructure,
6086
+ planRestructure: () => planRestructure,
6087
+ planningUmask: () => planningUmask,
6088
+ pruneRestructureRecovery: () => pruneRestructureRecovery,
6089
+ recoverRestructure: () => recoverRestructure,
6090
+ restructureBoundaryFindings: () => restructureBoundaryFindings
6091
+ });
6092
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
6093
+ import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
6094
+ import { dirname as dirname6, isAbsolute as isAbsolute5, join as join10, posix, relative as relative4, resolve as resolve7 } from "path";
6095
+ import { fileURLToPath as fileURLToPath2 } from "url";
6096
+ function digestBytes(value) {
6097
+ return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
6098
+ }
6099
+ function canonicalJson(value) {
6100
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
6101
+ if (value && typeof value === "object") {
6102
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
6103
+ }
6104
+ return JSON.stringify(value);
6105
+ }
6106
+ function digestRestructureValue(value) {
6107
+ return digestBytes(canonicalJson(value));
6108
+ }
6109
+ function normalizeRelativePath2(value) {
6110
+ if (!value || value.includes("\0") || isAbsolute5(value)) return void 0;
6111
+ const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
6112
+ if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
6113
+ return normalized;
6114
+ }
6115
+ function isPathAllowed(path, allowed) {
6116
+ return allowed.some((entry) => {
6117
+ const normalized = normalizeRelativePath2(entry.replace(/\/$/, ""));
6118
+ return normalized !== void 0 && (path === normalized || path.startsWith(`${normalized}/`));
6119
+ });
6120
+ }
6121
+ async function readContainedFileWithMode(root, path) {
6122
+ const normalized = normalizeRelativePath2(path);
6123
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
6124
+ const absoluteRoot = resolve7(root);
6125
+ const absolutePath = resolve7(absoluteRoot, normalized);
6126
+ if (relative4(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
6127
+ try {
6128
+ const info = await lstat3(absolutePath);
6129
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Path is not a regular file: ${path}`);
6130
+ return { buffer: await readFile3(absolutePath), mode: info.mode & MAX_POSIX_MODE };
6131
+ } catch (error) {
6132
+ if (error.code === "ENOENT") return void 0;
6133
+ throw error;
6134
+ }
6135
+ }
6136
+ async function readContainedFile(root, path) {
6137
+ return (await readContainedFileWithMode(root, path))?.buffer;
6138
+ }
6139
+ async function snapshotFile(root, path) {
6140
+ const normalized = normalizeRelativePath2(path);
6141
+ if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
6142
+ const contained = await readContainedFileWithMode(root, normalized);
6143
+ return contained === void 0 ? { path: normalized, exists: false, sha256: null, size: 0, mode: null } : {
6144
+ path: normalized,
6145
+ exists: true,
6146
+ sha256: digestBytes(contained.buffer),
6147
+ size: contained.buffer.byteLength,
6148
+ mode: contained.mode
6149
+ };
6150
+ }
6151
+ function sameSnapshot(left, right) {
6152
+ return left.path === right.path && left.exists === right.exists && left.sha256 === right.sha256 && left.size === right.size && left.mode === right.mode;
6153
+ }
6154
+ async function configSnapshot(root) {
6155
+ return snapshotFile(root, "artifact-graph.config.yaml");
6156
+ }
6157
+ async function loadRestructureContract(name) {
6158
+ return loadContract(join10(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
6159
+ }
6160
+ async function validateDomainContract(name, value) {
6161
+ const contract = await loadRestructureContract(name);
6162
+ return validateContractAgainstSchema(value, contract).errors;
6163
+ }
6164
+ function occurrenceKey(edge2) {
6165
+ return [edge2.from, edge2.to, edge2.kind, edge2.source, edge2.sourcePath, edge2.sourceLine].join(" ");
6166
+ }
6167
+ function relationOccurrences(graph) {
6168
+ const counts = /* @__PURE__ */ new Map();
6169
+ return [...graph.edges].sort((left, right) => occurrenceKey(left).localeCompare(occurrenceKey(right))).map((edge2) => {
6170
+ const key = occurrenceKey(edge2);
6171
+ const occurrence = (counts.get(key) ?? 0) + 1;
6172
+ counts.set(key, occurrence);
6173
+ return {
6174
+ from: edge2.from,
6175
+ to: edge2.to,
6176
+ kind: edge2.kind,
6177
+ source: edge2.source,
6178
+ source_path: edge2.sourcePath,
6179
+ source_line: edge2.sourceLine,
6180
+ occurrence
6181
+ };
6182
+ });
6183
+ }
6184
+ function relationKey(value) {
6185
+ return [value.from, value.to, value.kind, value.source, value.source_path, value.source_line, value.occurrence].join(" ");
6186
+ }
6187
+ function acceptanceCriteria(node) {
6188
+ const raw = node.attrs?.acceptanceCriteria;
6189
+ if (!Array.isArray(raw)) return [];
6190
+ return raw.flatMap((item, index) => {
6191
+ if (typeof item === "string") {
6192
+ const match = /\b(AC\d+)\b/.exec(item);
6193
+ return [match?.[1] ?? `AC${index + 1}`];
6194
+ }
6195
+ if (item && typeof item === "object") {
6196
+ const record = item;
6197
+ const value = String(record.id ?? record.code ?? "").trim();
6198
+ return value ? [value] : [`AC${index + 1}`];
6199
+ }
6200
+ return [`AC${index + 1}`];
6201
+ });
6202
+ }
6203
+ function spanFor(buffer, path, range) {
6204
+ return {
6205
+ path,
6206
+ start_byte: range.startByte,
6207
+ end_byte: range.endByte,
6208
+ sha256: digestBytes(buffer.subarray(range.startByte, range.endByte))
6209
+ };
6210
+ }
6211
+ function mappingTemplate(request, requestDigest, config, sources, unresolved) {
6212
+ return {
6213
+ schema_version: "1.0",
6214
+ request,
6215
+ request_digest: requestDigest,
6216
+ config_snapshot: config,
6217
+ sources: sources.map((source) => ({
6218
+ type: source.type,
6219
+ id: source.id,
6220
+ path: source.path,
6221
+ snapshot: source.snapshot,
6222
+ disposition: "preserved"
6223
+ })),
6224
+ targets: [],
6225
+ content_moves: [],
6226
+ identity_map: [],
6227
+ criterion_map: [],
6228
+ relation_map: [],
6229
+ prose_edits: [],
6230
+ file_headers: [],
6231
+ unresolved
6232
+ };
6233
+ }
6234
+ async function inspectRestructure(root, input) {
6235
+ const schemaErrors = await validateDomainContract("request", input);
6236
+ if (schemaErrors.length > 0) {
6237
+ return { ok: false, error: { code: "REQUEST_SCHEMA_INVALID", message: "Restructure request does not match its contract", details: schemaErrors } };
6238
+ }
6239
+ const request = input;
6240
+ const requestDigest = digestRestructureValue(request);
6241
+ const schema = await loadConfig(root);
6242
+ const graph = await scanArtifacts(root, schema);
6243
+ const allOccurrences = relationOccurrences(graph);
6244
+ const blockers = [];
6245
+ const unresolved = [];
6246
+ const inspected = [];
6247
+ for (const requested of request.sources) {
6248
+ const candidates = graph.nodes.filter((node2) => node2.type === requested.type && node2.code === requested.id && (!requested.path || node2.path === normalizeRelativePath2(requested.path)));
6249
+ if (candidates.length !== 1) {
6250
+ blockers.push({
6251
+ code: candidates.length === 0 ? "SOURCE_NOT_FOUND" : "SOURCE_AMBIGUOUS",
6252
+ 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`,
6253
+ ...requested.path ? { path: requested.path } : {}
6254
+ });
6255
+ continue;
6256
+ }
6257
+ const node = candidates[0];
6258
+ const raw = await readContainedFile(root, node.path);
6259
+ if (!raw) {
6260
+ blockers.push({ code: "SOURCE_NOT_FOUND", message: `Source file is missing: ${node.path}`, path: node.path, line: node.line });
6261
+ continue;
6262
+ }
6263
+ const nodesInFile = graph.nodes.filter((candidate) => candidate.path === node.path);
6264
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, nodesInFile);
6265
+ blockers.push(...boundary.blockers);
6266
+ const recordSpan = boundary.range ? spanFor(raw, node.path, boundary.range) : void 0;
6267
+ const uid = `${node.type}:${node.code}`;
6268
+ inspected.push({
6269
+ type: node.type,
6270
+ id: node.code,
6271
+ uid,
6272
+ path: node.path,
6273
+ title: node.title,
6274
+ snapshot: await snapshotFile(root, node.path),
6275
+ ...recordSpan ? {
6276
+ record_span: recordSpan,
6277
+ content: raw.subarray(recordSpan.start_byte, recordSpan.end_byte).toString("utf8")
6278
+ } : {},
6279
+ surrounding_spans: recordSpan ? [
6280
+ ...recordSpan.start_byte > 0 ? [{
6281
+ ...spanFor(raw, node.path, { startByte: 0, endByte: recordSpan.start_byte }),
6282
+ content: raw.subarray(0, recordSpan.start_byte).toString("utf8")
6283
+ }] : [],
6284
+ ...recordSpan.end_byte < raw.byteLength ? [{
6285
+ ...spanFor(raw, node.path, { startByte: recordSpan.end_byte, endByte: raw.byteLength }),
6286
+ content: raw.subarray(recordSpan.end_byte).toString("utf8")
6287
+ }] : []
6288
+ ] : [],
6289
+ acceptance_criteria: acceptanceCriteria(node),
6290
+ incoming_relations: allOccurrences.filter((edge2) => edge2.to === uid),
6291
+ outgoing_relations: allOccurrences.filter((edge2) => edge2.from === uid)
6292
+ });
6293
+ }
6294
+ if (request.numbering_policy?.mode === "configured-next-available") {
6295
+ unresolved.push({
6296
+ code: "NUMBER_ALLOCATION_REQUIRES_MAPPING",
6297
+ message: "The deterministic allocation result must be fixed in the mapping before plan compilation"
6298
+ });
6299
+ }
6300
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6301
+ root,
6302
+ [...new Set(inspected.map((item) => item.path))],
6303
+ []
6304
+ ));
6305
+ const config = await configSnapshot(root);
6306
+ const affectedPaths = new Set(inspected.map((item) => item.path));
6307
+ for (const source of inspected) {
6308
+ for (const edge2 of [...source.incoming_relations, ...source.outgoing_relations]) affectedPaths.add(edge2.source_path);
6309
+ }
6310
+ const affectedFiles = await Promise.all([...affectedPaths].sort().map((path) => snapshotFile(root, path)));
6311
+ const inspection = {
6312
+ schema_version: "1.0",
6313
+ request,
6314
+ request_digest: requestDigest,
6315
+ config_snapshot: config,
6316
+ sources: inspected,
6317
+ affected_files: affectedFiles,
6318
+ relation_occurrences: allOccurrences.filter((edge2) => inspected.some((source) => edge2.from === source.uid || edge2.to === source.uid)),
6319
+ blockers,
6320
+ unresolved,
6321
+ mapping_template: {}
6322
+ };
6323
+ inspection.mapping_template = mappingTemplate(request, requestDigest, config, inspected, unresolved);
6324
+ return { ok: true, data: inspection };
6325
+ }
6326
+ function finding(code, message, path, line) {
6327
+ return { code, message, ...path ? { path } : {}, ...line ? { line } : {} };
6328
+ }
6329
+ async function verifySnapshot(root, expected, blockers) {
6330
+ const normalized = normalizeRelativePath2(expected.path);
6331
+ if (!normalized) {
6332
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6333
+ return void 0;
6334
+ }
6335
+ const actual = await snapshotFile(root, normalized);
6336
+ if (!sameSnapshot(actual, { ...expected, path: normalized })) {
6337
+ blockers.push(finding("INPUT_CHANGED", `Input snapshot changed for ${normalized}`, normalized));
6338
+ }
6339
+ return actual;
6340
+ }
6341
+ function validateSpan(buffer, span, blockers) {
6342
+ if (span.start_byte > span.end_byte || span.end_byte > buffer.byteLength) {
6343
+ blockers.push(finding("SPAN_OUT_OF_RANGE", `Invalid half-open byte range [${span.start_byte}, ${span.end_byte})`, span.path));
6344
+ return void 0;
6345
+ }
6346
+ const fragment = buffer.subarray(span.start_byte, span.end_byte);
6347
+ if (digestBytes(fragment) !== span.sha256) {
6348
+ blockers.push(finding("SOURCE_FRAGMENT_CHANGED", `Source fragment digest does not match ${span.path}`, span.path));
6349
+ return void 0;
6350
+ }
6351
+ return fragment;
6352
+ }
6353
+ function rangesCover(range, moves) {
6354
+ 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);
6355
+ let cursor = range.startByte;
6356
+ for (const interval of intervals) {
6357
+ if (interval.start > cursor) return false;
6358
+ cursor = Math.max(cursor, interval.end);
6359
+ }
6360
+ return cursor >= range.endByte;
6361
+ }
6362
+ function edgeDisplay(edge2) {
6363
+ return `${edge2.from} --${edge2.kind}--> ${edge2.to} @ ${edge2.sourcePath}:${edge2.sourceLine} [${edge2.source}]${edge2.attrs ? ` ${canonicalJson(edge2.attrs)}` : ""}`;
6364
+ }
6365
+ function graphDiff(before, after) {
6366
+ const beforeNodes = new Set(before.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6367
+ const afterNodes = new Set(after.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
6368
+ const beforeEdges = new Set(before.edges.map(edgeDisplay));
6369
+ const afterEdges = new Set(after.edges.map(edgeDisplay));
6370
+ return {
6371
+ added_nodes: [...afterNodes].filter((item) => !beforeNodes.has(item)).sort(),
6372
+ removed_nodes: [...beforeNodes].filter((item) => !afterNodes.has(item)).sort(),
6373
+ added_edges: [...afterEdges].filter((item) => !beforeEdges.has(item)).sort(),
6374
+ removed_edges: [...beforeEdges].filter((item) => !afterEdges.has(item)).sort()
6375
+ };
6376
+ }
6377
+ function issueIdentity(issue2) {
6378
+ const edge2 = issue2.edge ? `${issue2.edge.from} ${issue2.edge.to} ${issue2.edge.kind} ${issue2.edge.source} ${canonicalJson(issue2.edge.attrs ?? {})}` : "";
6379
+ return `${issue2.code} ${issue2.message} ${issue2.node ?? ""} ${edge2}`;
6380
+ }
6381
+ function readableDiff(path, oldContent, newContent) {
6382
+ const oldLines = oldContent?.split(/(?<=\n)/) ?? [];
6383
+ const newLines = newContent?.split(/(?<=\n)/) ?? [];
6384
+ if (oldContent === newContent) return "";
6385
+ return [
6386
+ `--- ${oldContent === void 0 ? "/dev/null" : `a/${path}`}`,
6387
+ `+++ ${newContent === void 0 ? "/dev/null" : `b/${path}`}`,
6388
+ ...oldLines.map((line) => `-${line.replace(/\n$/, "")}`),
6389
+ ...newLines.map((line) => `+${line.replace(/\n$/, "")}`)
6390
+ ].join("\n");
6391
+ }
6392
+ function findRelativeLinks(fragment) {
6393
+ const found = /* @__PURE__ */ new Set();
6394
+ const pattern = /!?\[[^\]]*\]\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)/gm;
6395
+ let match;
6396
+ while ((match = pattern.exec(fragment)) !== null) {
6397
+ const target = String(match[1] ?? match[2] ?? "").trim().replace(/^<|>$/g, "");
6398
+ if (target && !target.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("/")) found.add(target);
6399
+ }
6400
+ return [...found].sort();
6401
+ }
6402
+ function footnoteReferenceLabels(text) {
6403
+ const labels = /* @__PURE__ */ new Set();
6404
+ const pattern = /\[\^([^\]\s]+)\](?!:)/g;
6405
+ let match;
6406
+ while ((match = pattern.exec(text)) !== null) labels.add(match[1]);
6407
+ return [...labels].sort();
6408
+ }
6409
+ function footnoteDefinition(label) {
6410
+ return `[^${label}]:`;
6411
+ }
6412
+ function splitMarkdownTarget(target) {
6413
+ const cleaned = target.trim().replace(/^<|>$/g, "");
6414
+ const hash = cleaned.indexOf("#");
6415
+ return hash < 0 ? { path: cleaned, anchor: null } : { path: cleaned.slice(0, hash), anchor: cleaned.slice(hash) };
6416
+ }
6417
+ async function pathExists2(absolutePath) {
6418
+ try {
6419
+ await lstat3(absolutePath);
6420
+ return true;
6421
+ } catch {
6422
+ return false;
6423
+ }
6424
+ }
6425
+ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6426
+ const migrationPaths = [.../* @__PURE__ */ new Set([...sourcePaths, ...targetPaths])];
6427
+ const migrationNames = new Set(migrationPaths.map((path) => posix.basename(path)));
6428
+ const directories = new Set(migrationPaths.map((path) => posix.dirname(path)));
6429
+ const findings = [];
6430
+ async function visit(directory) {
6431
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6432
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6433
+ const absolute = join10(directory, entry.name);
6434
+ if (entry.isDirectory()) {
6435
+ await visit(absolute);
6436
+ continue;
6437
+ }
6438
+ if (!entry.isFile() || !TEXT_EXTENSIONS.test(entry.name)) continue;
6439
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6440
+ const raw = await readFile3(absolute, "utf8");
6441
+ const namesTheMigration = migrationPaths.some((reference) => raw.includes(reference));
6442
+ const lines = raw.split(/\r?\n/);
6443
+ for (const [index, line] of lines.entries()) {
6444
+ const lineNumber = index + 1;
6445
+ if (MARKDOWN_FILE_SUFFIX.test(path)) {
6446
+ const pattern = new RegExp(MARKDOWN_LINK_PATTERN.source, "g");
6447
+ let match;
6448
+ while ((match = pattern.exec(line)) !== null) {
6449
+ const literal = match[0];
6450
+ const { path: linkPath, anchor } = splitMarkdownTarget(match[2]);
6451
+ if (!linkPath || linkPath.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(linkPath)) continue;
6452
+ if (!migrationNames.has(posix.basename(linkPath))) continue;
6453
+ const resolved = normalizeRelativePath2(posix.join(posix.dirname(path), linkPath));
6454
+ if (!resolved || targetPaths.includes(resolved)) continue;
6455
+ if (anchor) {
6456
+ findings.push(finding(
6457
+ "ANCHOR_REFERENCE_UNRESOLVED",
6458
+ `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`,
6459
+ path,
6460
+ lineNumber
6461
+ ));
6462
+ } else if (!await pathExists2(resolve7(root, resolved))) {
6463
+ findings.push(finding(
6464
+ "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
6465
+ `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`,
6466
+ path,
6467
+ lineNumber
6468
+ ));
6469
+ }
6470
+ }
6471
+ }
6472
+ if (SCRIPT_FILE_SUFFIX.test(path) && namesTheMigration && RUNTIME_PATH_MARKER.test(line)) {
6473
+ const literals = [...line.matchAll(/['"`]([^'"`\n]*)['"`]/g)].map((item) => item[1]);
6474
+ const directoryLiteral = literals.find((literal) => directories.has(literal) || migrationPaths.some((reference) => reference.startsWith(`${literal}/`)));
6475
+ if (directoryLiteral) {
6476
+ findings.push(finding(
6477
+ "RUNTIME_PATH_ASSEMBLY_UNRESOLVED",
6478
+ `A path assembled at runtime from ${JSON.stringify(directoryLiteral)} cannot be resolved statically: ${line.trim()}`,
6479
+ path,
6480
+ lineNumber
6481
+ ));
6482
+ }
6483
+ }
6484
+ }
6485
+ }
6486
+ }
6487
+ await visit(resolve7(root));
6488
+ const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
6489
+ return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
6490
+ }
6491
+ function mergeFindings(target, additions) {
6492
+ const seen = new Set(target.map((item) => `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`));
6493
+ for (const item of additions) {
6494
+ const key = `${item.code} ${item.path ?? ""} ${item.line ?? 0} ${item.message}`;
6495
+ if (seen.has(key)) continue;
6496
+ seen.add(key);
6497
+ target.push(item);
6498
+ }
6499
+ }
6500
+ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PURE__ */ new Set()) {
6501
+ const results = [];
6502
+ async function visit(directory) {
6503
+ for (const entry of await readdir3(directory, { withFileTypes: true })) {
6504
+ if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6505
+ const absolute = join10(directory, entry.name);
6506
+ if (entry.isDirectory()) {
6507
+ await visit(absolute);
6508
+ } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
6509
+ const path = relative4(root, absolute).replace(/\\/g, "/");
6510
+ if (excludedPaths.has(path)) continue;
6511
+ const raw = await readFile3(absolute, "utf8");
6512
+ raw.split(/\r?\n/).forEach((line, index) => {
6513
+ for (const reference of references) {
6514
+ if (path !== reference && line.includes(reference)) results.push({ path, line: index + 1, reference });
6515
+ }
6516
+ });
6517
+ }
6518
+ }
6519
+ }
6520
+ await visit(resolve7(root));
6521
+ return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6522
+ }
6523
+ function expectedRelationTargets(mapping) {
6524
+ return new Set(mapping.relation_map.flatMap((entry) => entry.targets.map((target) => `${target.from} ${target.to} ${target.kind}`)));
6525
+ }
6526
+ function relationTriples(graph) {
6527
+ return new Set(graph.edges.map((edge2) => `${edge2.from} ${edge2.to} ${edge2.kind}`));
6528
+ }
6529
+ function formatMode(value) {
6530
+ return value === null ? "null" : `0o${value.toString(8).padStart(3, "0")}`;
6531
+ }
6532
+ function isPosixFileMode(value) {
6533
+ return value === null || Number.isInteger(value) && value >= 0 && value <= MAX_POSIX_MODE;
6534
+ }
6535
+ function modeIsUsableAtApply(mode, umask) {
6536
+ return Number.isInteger(mode) && mode >= 0 && mode <= MAX_POSIX_MODE && (mode & 256) !== 0 && (mode & 3584) === 0 && (mode & umask) === 0;
6537
+ }
6538
+ function createModeForUmask(umask) {
6539
+ return CREATE_MODE_BASE & ~umask & MAX_POSIX_MODE;
6540
+ }
6541
+ function planningUmask() {
6542
+ return process.umask() & MAX_POSIX_MODE;
6543
+ }
6544
+ function restructureBoundaryFindings(operations, limits) {
6545
+ const findings = [];
6546
+ if (operations.length === 0) {
6547
+ findings.push(finding("NO_OPERATIONS", "The plan contains no file operations; a no-op plan has nothing to apply"));
6548
+ return findings;
6549
+ }
6550
+ if (operations.length > limits.max_operations) {
6551
+ findings.push(finding("TOO_MANY_OPERATIONS", `The plan contains ${operations.length} operations; at most ${limits.max_operations} are supported`));
6552
+ }
6553
+ const totalBytes = operations.reduce((total, operation) => total + operation.original_bytes + operation.new_bytes, 0);
6554
+ if (totalBytes > limits.max_total_bytes) {
6555
+ findings.push(finding("CAPACITY_EXCEEDED", `Planned original and new bytes total ${totalBytes}; the limit is ${limits.max_total_bytes}`));
6556
+ }
6557
+ const expectedCreateMode = createModeForUmask(limits.umask);
6558
+ const applyModeContract = limits.mode_contract === "apply";
6559
+ for (const operation of operations) {
6560
+ const parent = dirname6(operation.path) || ".";
6561
+ if (!operation.parent_exists) {
6562
+ findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6563
+ } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
6564
+ findings.push(finding("CROSS_FILESYSTEM", `Parent directory is on another filesystem than the project root: ${parent}`, operation.path));
6565
+ }
6566
+ if (!isPosixFileMode(operation.mode)) {
6567
+ findings.push(finding("MODE_OUT_OF_RANGE", `Candidate mode is not a POSIX permission value: ${formatMode(operation.mode)}`, operation.path));
6568
+ }
6569
+ if (!isPosixFileMode(operation.original_mode)) {
6570
+ findings.push(finding("MODE_OUT_OF_RANGE", `Original mode is not a POSIX permission value: ${formatMode(operation.original_mode)}`, operation.path));
6571
+ }
6572
+ if (operation.original_exists && operation.original_mode === null) {
6573
+ findings.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `The existing file has no frozen POSIX mode: ${operation.path}`, operation.path));
6574
+ }
6575
+ if (!operation.original_exists && operation.original_mode !== null) {
6576
+ findings.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${operation.path}`, operation.path));
6577
+ }
6578
+ if (applyModeContract) {
6579
+ for (const [label, value] of [["candidate mode", operation.mode], ["original mode", operation.original_mode]]) {
6580
+ if (value === null || modeIsUsableAtApply(value, limits.umask)) continue;
6581
+ findings.push(finding(
6582
+ "MODE_NOT_USABLE",
6583
+ `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}`,
6584
+ operation.path
6585
+ ));
6586
+ }
6587
+ }
6588
+ if (operation.action === "create") {
6589
+ if (operation.original_exists) {
6590
+ findings.push(finding("MODE_NOT_APPLICABLE", `create must target a path that does not exist yet: ${operation.path}`, operation.path));
6591
+ }
6592
+ if (!applyModeContract && operation.mode !== expectedCreateMode) {
6593
+ findings.push(finding("MODE_NOT_APPLICABLE", `create mode ${formatMode(operation.mode)} is not the planning umask mode ${formatMode(expectedCreateMode)}: ${operation.path}`, operation.path));
6594
+ }
6595
+ } else if (operation.action === "replace") {
6596
+ if (!operation.original_exists) {
6597
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must target an existing file: ${operation.path}`, operation.path));
6598
+ } else if (operation.original_mode !== null && operation.mode !== operation.original_mode) {
6599
+ findings.push(finding("MODE_NOT_APPLICABLE", `replace must preserve the original mode ${formatMode(operation.original_mode)}: ${operation.path}`, operation.path));
6600
+ }
6601
+ } else if (operation.mode !== null) {
6602
+ findings.push(finding("MODE_NOT_APPLICABLE", `delete must not carry a mode: ${operation.path}`, operation.path));
6603
+ }
6604
+ }
6605
+ return findings;
6606
+ }
6607
+ async function probeDirectory(absolutePath) {
6608
+ try {
6609
+ const info = await stat(absolutePath);
6610
+ return { exists: info.isDirectory(), device: info.dev };
6611
+ } catch (error) {
6612
+ const code = error.code;
6613
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, device: null };
6614
+ throw error;
6615
+ }
6616
+ }
6617
+ async function planRestructure(root, input) {
6618
+ const schemaErrors = await validateDomainContract("mapping", input);
6619
+ if (schemaErrors.length > 0) {
6620
+ return { ok: false, error: { code: "MAPPING_SCHEMA_INVALID", message: "Restructure mapping does not match its contract", details: schemaErrors } };
6621
+ }
6622
+ const mapping = input;
6623
+ const blockers = [];
6624
+ const unresolved = [...mapping.unresolved];
6625
+ const requestErrors = await validateDomainContract("request", mapping.request);
6626
+ if (requestErrors.length > 0) blockers.push(finding("REQUEST_SCHEMA_INVALID", requestErrors.join("; ")));
6627
+ if (digestRestructureValue(mapping.request) !== mapping.request_digest) blockers.push(finding("REQUEST_DIGEST_MISMATCH", "request_digest does not bind the embedded request"));
6628
+ const currentConfig = await configSnapshot(root);
6629
+ if (!sameSnapshot(currentConfig, mapping.config_snapshot)) blockers.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after inspection", currentConfig.path));
6630
+ const schema = await loadConfig(root);
6631
+ const beforeGraph = await scanArtifacts(root, schema);
6632
+ const beforeOccurrences = new Map(relationOccurrences(beforeGraph).map((entry) => [relationKey(entry), entry]));
6633
+ const sourceUids = new Set(mapping.sources.map((source) => `${source.type}:${source.id}`));
6634
+ const seenSourceUids = /* @__PURE__ */ new Set();
6635
+ for (const source of mapping.sources) {
6636
+ const uid = `${source.type}:${source.id}`;
6637
+ if (seenSourceUids.has(uid)) blockers.push(finding("DUPLICATE_SOURCE", `Duplicate mapping source: ${uid}`, source.path));
6638
+ seenSourceUids.add(uid);
6639
+ 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));
6640
+ }
6641
+ for (const requested of mapping.request.sources) {
6642
+ const requestedPath = requested.path ? normalizeRelativePath2(requested.path) : void 0;
6643
+ const matches = mapping.sources.filter((source) => source.type === requested.type && source.id === requested.id && (!requested.path || source.path === requestedPath));
6644
+ if (matches.length !== 1) blockers.push(finding("REQUEST_SOURCE_MISMATCH", `Request source ${requested.type}:${requested.id} must resolve to exactly one mapping source`));
6645
+ }
6646
+ for (const source of mapping.sources) {
6647
+ if (!mapping.request.sources.some((requested) => requested.type === source.type && requested.id === source.id && (!requested.path || normalizeRelativePath2(requested.path) === source.path))) {
6648
+ blockers.push(finding("UNREQUESTED_SOURCE", `Mapping source is not declared by the bound request: ${source.type}:${source.id}`, source.path));
6649
+ }
6650
+ }
6651
+ const requiredOccurrences = [...beforeOccurrences.values()].filter((entry) => sourceUids.has(entry.from) || sourceUids.has(entry.to));
6652
+ const mappedOccurrenceKeys = new Set(mapping.relation_map.map((entry) => relationKey(entry.occurrence)));
6653
+ for (const occurrence of requiredOccurrences) {
6654
+ if (!mappedOccurrenceKeys.has(relationKey(occurrence))) blockers.push(finding("RELATION_UNMAPPED", `Relation occurrence is not mapped: ${relationKey(occurrence)}`, occurrence.source_path, occurrence.source_line));
6655
+ }
6656
+ for (const entry of mapping.relation_map) {
6657
+ 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));
6658
+ }
6659
+ const allowed = mapping.request.allowed_output_paths.map((path) => normalizeRelativePath2(path.replace(/\/$/, ""))).filter((path) => Boolean(path));
6660
+ const targetKeys = /* @__PURE__ */ new Set();
6661
+ const targetUids = /* @__PURE__ */ new Set();
6662
+ for (const target of mapping.targets) {
6663
+ const path = normalizeRelativePath2(target.path);
6664
+ if (!path || !isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Target path is outside allowed_output_paths: ${target.path}`, target.path));
6665
+ if (targetKeys.has(target.key)) blockers.push(finding("DUPLICATE_TARGET_KEY", `Duplicate target key: ${target.key}`, target.path));
6666
+ targetKeys.add(target.key);
6667
+ 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));
6668
+ const uid = `${target.type}:${target.id}`;
6669
+ if (targetUids.has(uid)) blockers.push(finding("TARGET_ID_CONFLICT", `Duplicate target identity: ${uid}`, target.path));
6670
+ targetUids.add(uid);
6671
+ if (beforeGraph.nodes.some((node) => node.uid === uid) && !sourceUids.has(uid)) {
6672
+ blockers.push(finding("TARGET_ID_CONFLICT", `Target identity already exists outside this migration: ${uid}`, target.path));
6673
+ }
6674
+ 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));
6675
+ if (path && !matchesConfiguredArtifactPath(path, schema)) blockers.push(finding("TARGET_PATH_NOT_SCANNED", `Target path is not covered by the active artifact configuration: ${path}`, path));
6676
+ }
6677
+ for (const identity of mapping.identity_map) {
6678
+ 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}`));
6679
+ }
6680
+ for (const source of mapping.sources) {
6681
+ const identities = mapping.identity_map.filter((entry) => entry.source_type === source.type && entry.source_id === source.id);
6682
+ 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));
6683
+ 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));
6684
+ }
6685
+ const snapshots = /* @__PURE__ */ new Map();
6686
+ const buffers = /* @__PURE__ */ new Map();
6687
+ for (const expected of [...mapping.sources.map((item) => item.snapshot), ...mapping.targets.map((item) => item.snapshot)]) {
6688
+ const normalized = normalizeRelativePath2(expected.path);
6689
+ if (!normalized) {
6690
+ blockers.push(finding("PATH_OUTSIDE_ROOT", `Invalid project-relative path: ${expected.path}`, expected.path));
6691
+ continue;
6692
+ }
6693
+ if (snapshots.has(normalized) && !sameSnapshot(snapshots.get(normalized), { ...expected, path: normalized })) {
6694
+ blockers.push(finding("SNAPSHOT_CONFLICT", `Multiple incompatible snapshots were supplied for ${normalized}`, normalized));
6695
+ continue;
6696
+ }
6697
+ const actual = await verifySnapshot(root, { ...expected, path: normalized }, blockers);
6698
+ if (actual) snapshots.set(normalized, actual);
6699
+ const raw = await readContainedFile(root, normalized);
6700
+ if (raw) buffers.set(normalized, raw);
6701
+ }
6702
+ snapshots.set(currentConfig.path, currentConfig);
6703
+ const declaredSnapshots = [
6704
+ mapping.config_snapshot,
6705
+ ...mapping.sources.map((source) => source.snapshot),
6706
+ ...mapping.targets.map((target) => target.snapshot)
6707
+ ];
6708
+ const checkedDeclaredModes = /* @__PURE__ */ new Set();
6709
+ for (const declared of declaredSnapshots) {
6710
+ const declaredMode = declared.mode ?? null;
6711
+ const declaredPath = normalizeRelativePath2(declared.path) ?? declared.path;
6712
+ const key = `${declaredPath} ${declared.exists} ${declaredMode}`;
6713
+ if (checkedDeclaredModes.has(key)) continue;
6714
+ checkedDeclaredModes.add(key);
6715
+ if (!isPosixFileMode(declaredMode)) {
6716
+ blockers.push(finding("MODE_OUT_OF_RANGE", `Frozen mode is not a POSIX permission value: ${formatMode(declaredMode)}`, declaredPath));
6717
+ } else if (declared.exists && declaredMode === null) {
6718
+ blockers.push(finding("MODE_MISSING_FOR_EXISTING_FILE", `Existing file must freeze its POSIX mode: ${declaredPath}`, declaredPath));
6719
+ } else if (!declared.exists && declaredMode !== null) {
6720
+ blockers.push(finding("MODE_NOT_APPLICABLE", `A POSIX mode was frozen for a path that does not exist: ${declaredPath}`, declaredPath));
6721
+ }
6722
+ }
6723
+ const moveIds = /* @__PURE__ */ new Set();
6724
+ const rangesByPath = /* @__PURE__ */ new Map();
6725
+ const fragments = /* @__PURE__ */ new Map();
6726
+ for (const move of mapping.content_moves) {
6727
+ if (moveIds.has(move.id)) blockers.push(finding("DUPLICATE_CONTENT_MOVE", `Duplicate content move id: ${move.id}`));
6728
+ moveIds.add(move.id);
6729
+ const sourcePath = normalizeRelativePath2(move.source.path);
6730
+ const targetPath = normalizeRelativePath2(move.target.path);
6731
+ if (!sourcePath || !buffers.has(sourcePath)) {
6732
+ blockers.push(finding("SOURCE_NOT_FOUND", `Content move source is unavailable: ${move.source.path}`, move.source.path));
6733
+ continue;
6734
+ }
6735
+ if (!targetPath || !isPathAllowed(targetPath, allowed)) {
6736
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Content move target is outside allowed_output_paths: ${move.target.path}`, move.target.path));
6737
+ continue;
6738
+ }
6739
+ const fragment = validateSpan(buffers.get(sourcePath), { ...move.source, path: sourcePath }, blockers);
6740
+ if (!fragment) continue;
6741
+ fragments.set(move.id, fragment);
6742
+ const pathMoves = rangesByPath.get(sourcePath) ?? [];
6743
+ for (const existing of pathMoves) {
6744
+ if (Math.max(existing.source.start_byte, move.source.start_byte) < Math.min(existing.source.end_byte, move.source.end_byte)) {
6745
+ 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;
6746
+ if (!exactExplicitCopy) blockers.push(finding("SOURCE_SPAN_OVERLAP", `Content moves ${existing.id} and ${move.id} overlap without an exact explicit copy`, sourcePath));
6747
+ }
6748
+ }
6749
+ pathMoves.push(move);
6750
+ rangesByPath.set(sourcePath, pathMoves);
6751
+ if (dirname6(sourcePath) !== dirname6(targetPath)) {
6752
+ for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6753
+ const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6754
+ if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
6755
+ }
6756
+ }
6757
+ }
6758
+ for (const source of mapping.sources) {
6759
+ const node = beforeGraph.nodes.find((candidate) => candidate.type === source.type && candidate.code === source.id && candidate.path === source.path);
6760
+ const raw = buffers.get(source.path);
6761
+ if (!node || !raw) continue;
6762
+ const boundary = locateSoftwareRecord(raw.toString("utf8"), node, beforeGraph.nodes.filter((candidate) => candidate.path === source.path));
6763
+ blockers.push(...boundary.blockers);
6764
+ 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));
6765
+ if (source.type === "feature" && source.disposition === "retired") {
6766
+ const criteria = acceptanceCriteria(node);
6767
+ const mapped = new Set(mapping.criterion_map.filter((entry) => entry.source_feature === source.id && entry.targets.length > 0).map((entry) => entry.source_criterion));
6768
+ 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));
6769
+ }
6770
+ }
6771
+ const candidateBuffers = /* @__PURE__ */ new Map();
6772
+ const touched = /* @__PURE__ */ new Set();
6773
+ for (const [sourcePath, moves] of rangesByPath) {
6774
+ const original = buffers.get(sourcePath);
6775
+ const removals = moves.filter((move) => move.target.mode === "move").sort((left, right) => left.source.start_byte - right.source.start_byte);
6776
+ const chunks = [];
6777
+ let cursor = 0;
6778
+ for (const move of removals) {
6779
+ chunks.push(original.subarray(cursor, move.source.start_byte));
6780
+ cursor = move.source.end_byte;
6781
+ }
6782
+ chunks.push(original.subarray(cursor));
6783
+ candidateBuffers.set(sourcePath, Buffer.concat(chunks));
6784
+ touched.add(sourcePath);
6785
+ }
6786
+ const movesByTarget = /* @__PURE__ */ new Map();
6787
+ for (const move of mapping.content_moves) {
6788
+ const targetPath = normalizeRelativePath2(move.target.path);
6789
+ if (!targetPath || !fragments.has(move.id)) continue;
6790
+ const list = movesByTarget.get(targetPath) ?? [];
6791
+ list.push(move);
6792
+ movesByTarget.set(targetPath, list);
6793
+ }
6794
+ for (const [targetPath, moves] of movesByTarget) {
6795
+ const base = candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0);
6796
+ const appended = [base];
6797
+ for (const move of [...moves].sort((left, right) => left.target.order - right.target.order || left.id.localeCompare(right.id))) {
6798
+ const separator = move.target.separator ?? (appended.some((item) => item.byteLength > 0) ? "\n" : "");
6799
+ appended.push(Buffer.from(separator, "utf8"), fragments.get(move.id));
6800
+ }
6801
+ candidateBuffers.set(targetPath, Buffer.concat(appended));
6802
+ touched.add(targetPath);
6803
+ if (!snapshots.has(targetPath)) snapshots.set(targetPath, await snapshotFile(root, targetPath));
6804
+ }
6805
+ for (const header of mapping.file_headers) {
6806
+ const path = normalizeRelativePath2(header.path);
6807
+ if (!path || !isPathAllowed(path, allowed)) {
6808
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `File header path is outside allowed_output_paths: ${header.path}`, header.path));
6809
+ continue;
6810
+ }
6811
+ if (header.affected_records.length === 0 && header.content === "") {
6812
+ const unselected = beforeGraph.nodes.filter((node) => node.path === path && !sourceUids.has(node.uid));
6813
+ if (unselected.length > 0) {
6814
+ blockers.push(finding("FILE_DELETE_HAS_UNSELECTED_RECORDS", `Cannot delete ${path}; it still contains unselected records: ${unselected.map((node) => node.uid).join(", ")}`, path));
6815
+ } else {
6816
+ candidateBuffers.set(path, Buffer.alloc(0));
6817
+ touched.add(path);
6818
+ }
6819
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6820
+ continue;
6821
+ }
6822
+ const raw = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6823
+ candidateBuffers.set(path, Buffer.from(replaceSoftwareHeader(raw, header.content), "utf8"));
6824
+ touched.add(path);
6825
+ if (!snapshots.has(path)) snapshots.set(path, await snapshotFile(root, path));
6826
+ }
6827
+ for (const edit of mapping.prose_edits) {
6828
+ const path = normalizeRelativePath2(edit.target_path);
6829
+ const sourcePath = normalizeRelativePath2(edit.source.path);
6830
+ if (!path || !sourcePath || !buffers.has(sourcePath)) {
6831
+ blockers.push(finding("PROSE_EDIT_SOURCE_MISSING", `Prose edit source is unavailable: ${edit.source.path}`, edit.source.path));
6832
+ continue;
6833
+ }
6834
+ if (!isPathAllowed(path, allowed)) {
6835
+ blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Prose edit target is outside allowed_output_paths: ${edit.target_path}`, edit.target_path));
6836
+ continue;
6837
+ }
6838
+ if (!validateSpan(buffers.get(sourcePath), { ...edit.source, path: sourcePath }, blockers)) continue;
6839
+ const current = (candidateBuffers.get(path) ?? buffers.get(path) ?? Buffer.alloc(0)).toString("utf8");
6840
+ const occurrences = current.split(edit.old_text).length - 1;
6841
+ if (!edit.old_text || occurrences !== 1) {
6842
+ blockers.push(finding("PROSE_EDIT_AMBIGUOUS", `Expected exactly one prose edit match in ${path}, found ${occurrences}`, path));
6843
+ continue;
6844
+ }
6845
+ candidateBuffers.set(path, Buffer.from(current.replace(edit.old_text, edit.new_text), "utf8"));
6846
+ touched.add(path);
6847
+ }
6848
+ const candidates = [];
6849
+ const umask = planningUmask();
6850
+ for (const path of [...touched].sort()) {
6851
+ if (!isPathAllowed(path, allowed)) blockers.push(finding("OUTPUT_PATH_NOT_ALLOWED", `Candidate path is outside allowed_output_paths: ${path}`, path));
6852
+ const original = buffers.get(path);
6853
+ const candidate = candidateBuffers.get(path) ?? Buffer.alloc(0);
6854
+ if (original && original.equals(candidate)) continue;
6855
+ const deleteFile = candidate.byteLength === 0;
6856
+ const snapshot = snapshots.get(path) ?? await snapshotFile(root, path);
6857
+ const action = deleteFile ? "delete" : original ? "replace" : "create";
6858
+ candidates.push({
6859
+ path,
6860
+ action,
6861
+ content: deleteFile ? null : candidate.toString("utf8"),
6862
+ sha256: deleteFile ? null : digestBytes(candidate),
6863
+ mode: action === "delete" ? null : action === "replace" ? snapshot.mode : createModeForUmask(umask),
6864
+ original: snapshot,
6865
+ diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6866
+ });
6867
+ }
6868
+ const rootDirectory = await probeDirectory(resolve7(root));
6869
+ const parentProbes = /* @__PURE__ */ new Map();
6870
+ for (const candidate of candidates) {
6871
+ const parent = dirname6(candidate.path);
6872
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve7(root, parent)));
6873
+ }
6874
+ blockers.push(...restructureBoundaryFindings(
6875
+ candidates.map((candidate) => {
6876
+ const parent = parentProbes.get(dirname6(candidate.path));
6877
+ return {
6878
+ path: candidate.path,
6879
+ action: candidate.action,
6880
+ original_exists: candidate.original.exists,
6881
+ original_mode: candidate.original.mode,
6882
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
6883
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
6884
+ mode: candidate.mode,
6885
+ parent_exists: parent.exists,
6886
+ parent_device: parent.device,
6887
+ root_device: rootDirectory.device ?? -1
6888
+ };
6889
+ }),
6890
+ {
6891
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
6892
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
6893
+ umask
6894
+ }
6895
+ ));
6896
+ const overrides = new Map(candidates.map((candidate) => [candidate.path, candidate.content]));
6897
+ const afterGraph = await scanArtifacts(root, schema, { contents: overrides });
6898
+ const beforeIssues = new Set(validateGraph(beforeGraph, schema).map(issueIdentity));
6899
+ const candidateIssues = validateGraph(afterGraph, schema);
6900
+ for (const issue2 of candidateIssues) {
6901
+ if (issue2.severity === "error" && !beforeIssues.has(issueIdentity(issue2))) blockers.push(finding("CANDIDATE_GRAPH_INVALID", `${issue2.code}: ${issue2.message}`, issue2.path, issue2.line));
6902
+ }
6903
+ const afterTriples = relationTriples(afterGraph);
6904
+ for (const expected of expectedRelationTargets(mapping)) {
6905
+ if (!afterTriples.has(expected)) blockers.push(finding("MAPPED_RELATION_MISSING", `Mapped relation is absent from the candidate graph: ${expected}`));
6906
+ }
6907
+ for (const source of mapping.sources) {
6908
+ const uid = `${source.type}:${source.id}`;
6909
+ const present = afterGraph.nodes.some((node) => node.uid === uid);
6910
+ if (source.disposition === "retired" && present && !targetUids.has(uid)) blockers.push(finding("RETIRED_ID_STILL_PRESENT", `Retired identity remains in candidate graph: ${uid}`, source.path));
6911
+ if (source.disposition === "preserved" && !present) blockers.push(finding("PRESERVED_ID_MISSING", `Preserved identity is missing from candidate graph: ${uid}`, source.path));
6912
+ }
6913
+ for (const criterion of mapping.criterion_map) {
6914
+ const sourceNode = beforeGraph.nodes.find((node) => node.type === "feature" && node.code === criterion.source_feature);
6915
+ 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));
6916
+ for (const target of criterion.targets) {
6917
+ const targetNode = afterGraph.nodes.find((node) => node.type === "feature" && node.code === target.feature);
6918
+ 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));
6919
+ }
6920
+ }
6921
+ for (const header of mapping.file_headers) {
6922
+ const actualRecords = afterGraph.nodes.filter((node) => node.path === header.path).map((node) => node.uid).sort();
6923
+ const declaredRecords = [...header.affected_records].sort();
6924
+ 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));
6925
+ }
6926
+ const e2ePaths = new Set(mapping.sources.filter((source) => source.type === "e2e_test").map((source) => source.path));
6927
+ for (const move of mapping.content_moves) {
6928
+ if (!e2ePaths.has(move.source.path) || move.source.path === move.target.path) continue;
6929
+ for (const path of [move.source.path, move.target.path]) {
6930
+ 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));
6931
+ }
6932
+ }
6933
+ for (const target of mapping.targets) {
6934
+ 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));
6935
+ }
6936
+ mergeFindings(unresolved, await scanUnsupportedReferences(
6937
+ root,
6938
+ [...new Set(mapping.sources.map((source) => source.path))],
6939
+ [...new Set([
6940
+ ...mapping.targets.map((target) => target.path),
6941
+ ...mapping.content_moves.map((move) => move.target.path),
6942
+ ...mapping.file_headers.map((header) => header.path)
6943
+ ].map((path) => normalizeRelativePath2(path)).filter((path) => path !== void 0))]
6944
+ ));
6945
+ for (const move of mapping.content_moves) {
6946
+ const fragment = fragments.get(move.id);
6947
+ const sourcePath = normalizeRelativePath2(move.source.path);
6948
+ const targetPath = normalizeRelativePath2(move.target.path);
6949
+ if (!fragment || !sourcePath || !targetPath) continue;
6950
+ const sourceText = (buffers.get(sourcePath) ?? Buffer.alloc(0)).toString("utf8");
6951
+ const targetText = (candidateBuffers.get(targetPath) ?? buffers.get(targetPath) ?? Buffer.alloc(0)).toString("utf8");
6952
+ for (const label of footnoteReferenceLabels(fragment.toString("utf8"))) {
6953
+ if (!sourceText.includes(footnoteDefinition(label)) || targetText.includes(footnoteDefinition(label))) continue;
6954
+ blockers.push(finding(
6955
+ "FOOTNOTE_DEFINITION_UNMAPPED",
6956
+ `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`,
6957
+ sourcePath
6958
+ ));
6959
+ }
6960
+ }
6961
+ const consumerCandidates = await scanConsumerCandidates(root, [...new Set(mapping.sources.map((source) => source.path))]);
6962
+ const plan = {
6963
+ schema_version: RESTRUCTURE_PLAN_SCHEMA_VERSION,
6964
+ operation_id: randomUUID2(),
6965
+ validation_timeout_ms: RESTRUCTURE_VALIDATION_TIMEOUT_MS,
6966
+ request_digest: mapping.request_digest,
6967
+ mapping_digest: digestRestructureValue(mapping),
6968
+ config_snapshot: currentConfig,
6969
+ input_snapshots: [...snapshots.values()].sort((left, right) => left.path.localeCompare(right.path)),
6970
+ candidates,
6971
+ graph_diff: graphDiff(beforeGraph, afterGraph),
6972
+ validation: { blockers, unresolved, candidate_issues: candidateIssues, consumer_candidates: consumerCandidates },
6973
+ applicable: blockers.length === 0 && unresolved.length === 0
6974
+ };
6975
+ const planErrors = await validateDomainContract("plan", plan);
6976
+ if (planErrors.length > 0) {
6977
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: "Compiled plan does not match its contract", details: planErrors } };
6978
+ }
6979
+ return { ok: true, data: plan };
6980
+ }
6981
+ async function gateRestructureOperationPlan(operation, plan) {
6982
+ const declaredVersion = plan && typeof plan === "object" ? plan.schema_version : void 0;
6983
+ if (declaredVersion !== RESTRUCTURE_PLAN_SCHEMA_VERSION) {
6984
+ return {
6985
+ ok: false,
6986
+ error: {
6987
+ code: "PLAN_SCHEMA_VERSION_UNSUPPORTED",
6988
+ message: `${operation} requires a restructure plan ${RESTRUCTURE_PLAN_SCHEMA_VERSION} document, received ${JSON.stringify(declaredVersion)}`
6989
+ }
6990
+ };
6991
+ }
6992
+ const errors = await validateDomainContract("plan", plan);
6993
+ if (errors.length > 0) {
6994
+ return { ok: false, error: { code: "PLAN_SCHEMA_INVALID", message: `Restructure plan does not match its ${RESTRUCTURE_PLAN_SCHEMA_VERSION} contract`, details: errors } };
6995
+ }
6996
+ return { ok: true, data: plan };
6997
+ }
6998
+ function refusal(code, message, findings = []) {
6999
+ return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
7000
+ }
7001
+ async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
7002
+ const absolute = resolve7(planPath);
7003
+ let info;
7004
+ try {
7005
+ info = await lstat3(absolute);
7006
+ } catch (cause) {
7007
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
7008
+ }
7009
+ if (info.isSymbolicLink() || !info.isFile()) {
7010
+ return refusal("PLAN_FILE_UNSAFE", `Plan document must be the one regular file the operator persisted: ${absolute}`);
7011
+ }
7012
+ let bytes;
7013
+ try {
7014
+ bytes = await readFile3(absolute);
7015
+ } catch (cause) {
7016
+ return refusal("PLAN_FILE_UNREADABLE", `Plan document cannot be read: ${absolute} (${cause.message})`);
7017
+ }
7018
+ let parsed;
7019
+ try {
7020
+ parsed = JSON.parse(bytes.toString("utf8"));
7021
+ } catch (cause) {
7022
+ return refusal("PLAN_FILE_INVALID_JSON", `Plan document is not JSON: ${absolute} (${cause.message})`);
7023
+ }
7024
+ const gate = await gateRestructureOperationPlan(operation, parsed);
7025
+ if (!gate.ok) return gate;
7026
+ return { ok: true, data: { path: absolute, realPath: await realpath2(absolute), digest: digestBytes(bytes), root: canonicalRoot, plan: gate.data } };
7027
+ }
7028
+ function planRootIdentityFindings(document) {
7029
+ const findings = [];
7030
+ const record = (path, label) => {
7031
+ const normalized = normalizeRelativePath2(path);
7032
+ if (!normalized || normalized !== path) {
7033
+ findings.push(finding("PLAN_PATH_INVALID", `${label} is not a normalized project-relative path: ${JSON.stringify(path)}`, path));
7034
+ }
7035
+ };
7036
+ record(document.plan.config_snapshot.path, "config_snapshot");
7037
+ for (const snapshot of document.plan.input_snapshots) record(snapshot.path, "input_snapshot");
7038
+ for (const candidate of document.plan.candidates) {
7039
+ record(candidate.path, "candidate");
7040
+ record(candidate.original.path, "candidate original");
7041
+ }
7042
+ if (document.plan.config_snapshot.path !== "artifact-graph.config.yaml") {
7043
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
7044
+ }
7045
+ const relativePlan = relative4(document.root, document.realPath);
7046
+ if (!relativePlan || relativePlan.startsWith("..") || isAbsolute5(relativePlan)) {
7047
+ findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
7048
+ }
7049
+ return findings;
7050
+ }
7051
+ async function operationBoundaries(root, plan) {
7052
+ const rootDirectory = await probeDirectory(resolve7(root));
7053
+ const parents = /* @__PURE__ */ new Map();
7054
+ const boundaries = [];
7055
+ for (const candidate of plan.candidates) {
7056
+ const parent = dirname6(candidate.path) || ".";
7057
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve7(root, parent)));
7058
+ const probe = parents.get(parent);
7059
+ boundaries.push({
7060
+ path: candidate.path,
7061
+ action: candidate.action,
7062
+ original_exists: candidate.original.exists,
7063
+ original_mode: candidate.original.mode,
7064
+ original_bytes: candidate.action === "create" ? 0 : candidate.original.size,
7065
+ new_bytes: candidate.action === "delete" ? 0 : Buffer.byteLength(candidate.content ?? "", "utf8"),
7066
+ mode: candidate.mode,
7067
+ parent_exists: probe.exists,
7068
+ parent_device: probe.device,
7069
+ root_device: rootDirectory.device ?? -1
7070
+ });
7071
+ }
7072
+ return boundaries;
7073
+ }
7074
+ async function applyPreconditionFindings(root, document) {
7075
+ const findings = [];
7076
+ const plan = document.plan;
7077
+ const currentConfig = await configSnapshot(root);
7078
+ if (!sameSnapshot(currentConfig, plan.config_snapshot)) {
7079
+ findings.push(finding("CONFIG_CHANGED", "artifact-graph configuration changed after planning", currentConfig.path));
7080
+ }
7081
+ for (const snapshot of plan.input_snapshots) await verifySnapshot(root, snapshot, findings);
7082
+ const relativePlan = relative4(root, document.realPath).replace(/\\/g, "/");
7083
+ for (const candidate of plan.candidates) {
7084
+ if (candidate.path === relativePlan) {
7085
+ findings.push(finding("PLAN_IN_WRITE_SET", `The plan document is inside its own candidate write set: ${candidate.path}`, candidate.path));
7086
+ }
7087
+ if (candidate.path === RESTRUCTURE_RECOVERY_REL_PATH || candidate.path.startsWith(`${RESTRUCTURE_RECOVERY_REL_PATH}/`)) {
7088
+ findings.push(finding("MECHANISM_PATH_IN_WRITE_SET", `A candidate writes inside the mechanism directory: ${candidate.path}`, candidate.path));
7089
+ }
7090
+ let original;
7091
+ try {
7092
+ original = await snapshotFile(root, candidate.path);
7093
+ } catch (cause) {
7094
+ findings.push(finding("CANDIDATE_PATH_UNSAFE", cause.message, candidate.path));
7095
+ continue;
7096
+ }
7097
+ if (!sameSnapshot(original, candidate.original)) {
7098
+ findings.push(finding("INPUT_CHANGED", `The candidate path no longer holds its frozen original state: ${candidate.path}`, candidate.path));
7099
+ }
7100
+ if (candidate.action === "delete") continue;
7101
+ if (candidate.mode === null) {
7102
+ findings.push(finding("MODE_MISSING", `The candidate has no frozen POSIX mode to apply: ${candidate.path}`, candidate.path));
7103
+ }
7104
+ if (candidate.sha256 !== digestBytes(Buffer.from(candidate.content ?? "", "utf8"))) {
7105
+ findings.push(finding("CANDIDATE_CONTENT_CHANGED", `Candidate bytes no longer match their frozen digest: ${candidate.path}`, candidate.path));
7106
+ }
7107
+ }
7108
+ findings.push(...restructureBoundaryFindings(await operationBoundaries(root, plan), {
7109
+ max_operations: RESTRUCTURE_MAX_OPERATIONS,
7110
+ max_total_bytes: RESTRUCTURE_MAX_TOTAL_BYTES,
7111
+ umask: planningUmask(),
7112
+ mode_contract: "apply"
7113
+ }));
7114
+ return findings;
7115
+ }
7116
+ function createRestructureValidationCallback(plan, excludedConsumerPaths = []) {
7117
+ const excludedConsumers = new Set(excludedConsumerPaths);
7118
+ const addedNodes = plan.graph_diff.added_nodes;
7119
+ const removedNodes = new Set(plan.graph_diff.removed_nodes);
7120
+ const addedEdges = plan.graph_diff.added_edges;
7121
+ const removedEdges = new Set(plan.graph_diff.removed_edges);
7122
+ const knownErrors = new Set(plan.validation.candidate_issues.filter((issue2) => issue2.severity === "error").map(issueIdentity));
7123
+ const relevantConsumers = new Set(plan.validation.consumer_candidates.map((candidate) => `${candidate.path} ${candidate.line} ${candidate.reference}`));
7124
+ const referencePaths = [...new Set(plan.validation.consumer_candidates.map((candidate) => candidate.reference))];
7125
+ return async function validateCandidateState(input) {
7126
+ const schema = await loadConfig(input.root);
7127
+ const graph = await scanArtifacts(input.root, schema);
7128
+ if (input.signal.aborted) return { passed: false };
7129
+ const nodes = new Set(graph.nodes.map((node) => `${node.uid} @ ${node.path}:${node.line}`));
7130
+ const edges = new Set(graph.edges.map(edgeDisplay));
7131
+ const nodeIdentityComplete = addedNodes.every((item) => nodes.has(item)) && [...removedNodes].every((item) => !nodes.has(item));
7132
+ const edgeIdentityComplete = addedEdges.every((item) => edges.has(item)) && [...removedEdges].every((item) => !edges.has(item));
7133
+ const newErrors = validateGraph(graph, schema).filter((issue2) => issue2.severity === "error" && !knownErrors.has(issueIdentity(issue2)));
7134
+ const consumers = await scanConsumerCandidates(input.root, referencePaths, excludedConsumers);
7135
+ const unplannedConsumers = consumers.filter((candidate) => !relevantConsumers.has(`${candidate.path} ${candidate.line} ${candidate.reference}`));
7136
+ const passed = nodeIdentityComplete && edgeIdentityComplete && newErrors.length === 0 && unplannedConsumers.length === 0;
7137
+ return { passed };
7138
+ };
7139
+ }
7140
+ async function applyRestructure(input) {
7141
+ if (input.confirmCooperativeWriters !== true) {
7142
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure apply requires the explicit --confirm-cooperative-writers premise and never assumes it");
7143
+ }
7144
+ const qualification = await qualifyRestructureMechanism(input.root);
7145
+ if (!qualification.ok) return qualification;
7146
+ const document = await loadRestructurePlanDocument("apply", qualification.data.root, input.planPath);
7147
+ if (!document.ok) return document;
7148
+ const plan = document.data.plan;
7149
+ if (plan.candidates.length === 0) {
7150
+ return refusal("PLAN_NO_OPERATIONS", "A plan with no file operations must not be applied and must not reach the mechanism");
7151
+ }
7152
+ if (!plan.applicable || plan.validation.blockers.length > 0 || plan.validation.unresolved.length > 0) {
7153
+ return refusal(
7154
+ "PLAN_NOT_APPLICABLE",
7155
+ "The plan is not applicable: it still carries blockers or unresolved findings",
7156
+ [...plan.validation.blockers, ...plan.validation.unresolved]
7157
+ );
7158
+ }
7159
+ const identity = planRootIdentityFindings(document.data);
7160
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7161
+ const drift = await applyPreconditionFindings(qualification.data.root, document.data);
7162
+ if (drift.length > 0) return refusal("APPLY_PRECONDITION_FAILED", "The project drifted after planning; nothing was written", drift);
7163
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: true });
7164
+ if (!mechanismRoot.ok) return mechanismRoot;
7165
+ const planRelPath = relative4(qualification.data.root, document.data.realPath).replace(/\\/g, "/");
7166
+ const applied = await applyRestructureFileSet(qualification.data.root, plan, {
7167
+ validate: createRestructureValidationCallback(plan, [planRelPath])
7168
+ });
7169
+ if (!applied.ok) return applied;
7170
+ const projection = projectRestructureFileSetResult(applied.data, document.data.realPath, document.data.digest);
7171
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7172
+ }
7173
+ async function recoverRestructure(input) {
7174
+ if (input.allParticipantsStopped !== true || input.exclusiveMaintenance !== true) {
7175
+ return refusal(
7176
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7177
+ "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance"
7178
+ );
7179
+ }
7180
+ const qualification = await qualifyRestructureMechanism(input.root);
7181
+ if (!qualification.ok) return qualification;
7182
+ const document = await loadRestructurePlanDocument("recover", qualification.data.root, input.planPath);
7183
+ if (!document.ok) return document;
7184
+ const identity = planRootIdentityFindings(document.data);
7185
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7186
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7187
+ if (!mechanismRoot.ok) return mechanismRoot;
7188
+ const recovered = await recoverRestructureFileSet(qualification.data.root, document.data.plan, {
7189
+ allParticipantsStopped: true,
7190
+ exclusiveMaintenance: true
7191
+ });
7192
+ if (!recovered.ok) return recovered;
7193
+ const projection = projectRestructureFileSetResult(recovered.data, document.data.realPath, document.data.digest);
7194
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7195
+ }
7196
+ async function pruneRestructureRecovery(input) {
7197
+ if (input.confirmCooperativeWriters !== true) {
7198
+ return refusal("COOPERATIVE_WRITERS_UNCONFIRMED", "restructure prune-recovery requires the explicit --confirm-cooperative-writers premise and never assumes it");
7199
+ }
7200
+ if (input.allParticipantsStopped !== input.exclusiveMaintenance) {
7201
+ return refusal(
7202
+ "MAINTENANCE_CONFIRMATION_REQUIRED",
7203
+ "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone"
7204
+ );
7205
+ }
7206
+ const qualification = await qualifyRestructureMechanism(input.root);
7207
+ if (!qualification.ok) return qualification;
7208
+ const document = await loadRestructurePlanDocument("prune-recovery", qualification.data.root, input.planPath);
7209
+ if (!document.ok) return document;
7210
+ const identity = planRootIdentityFindings(document.data);
7211
+ if (identity.length > 0) return refusal("PLAN_BINDING_INVALID", "The plan document does not bind to this project root", identity);
7212
+ const mechanismRoot = await ensureRestructureMechanismRoot(qualification.data.root, { create: false });
7213
+ if (!mechanismRoot.ok) return mechanismRoot;
7214
+ const pruned = await pruneRestructureFileSet(qualification.data.root, document.data.plan, {
7215
+ allParticipantsStopped: input.allParticipantsStopped,
7216
+ exclusiveMaintenance: input.exclusiveMaintenance
7217
+ });
7218
+ if (!pruned.ok) return pruned;
7219
+ const projection = projectRestructureFileSetResult(pruned.data, document.data.realPath, document.data.digest);
7220
+ return projection.ok ? { ok: true, data: projection } : { ok: false, error: { code: projection.code, message: projection.message, details: projection } };
7221
+ }
7222
+ 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;
7223
+ var init_restructure = __esm({
7224
+ "src/restructure.ts"() {
7225
+ "use strict";
7226
+ init_index();
7227
+ init_contract_kernel();
7228
+ init_restructure_software();
7229
+ init_restructure_file_set();
7230
+ RESTRUCTURE_PLAN_SCHEMA_VERSION = "1.1";
7231
+ RESTRUCTURE_VALIDATION_TIMEOUT_MS = 3e4;
7232
+ RESTRUCTURE_MAX_OPERATIONS = 1024;
7233
+ RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
7234
+ MAX_POSIX_MODE = 511;
7235
+ CREATE_MODE_BASE = 438;
7236
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname6(fileURLToPath2(import.meta.url));
7237
+ CONTRACT_ROOT = join10(MODULE_DIRECTORY, "..", "contracts");
7238
+ SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
7239
+ TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
7240
+ MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
7241
+ RUNTIME_PATH_MARKER = /\.join\s*\(|\$\{[^}]*\}|["'`]\s*\+|\+\s*["'`]/;
7242
+ MARKDOWN_FILE_SUFFIX = /\.(?:md|markdown)$/i;
7243
+ SCRIPT_FILE_SUFFIX = /\.(?:[cm]?[jt]sx?)$/i;
7244
+ }
7245
+ });
7246
+
7247
+ // src/index.ts
7248
+ import matter from "gray-matter";
7249
+ import yaml from "js-yaml";
7250
+ import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
7251
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
7252
+ import { basename as basename5, dirname as dirname7, extname, isAbsolute as isAbsolute6, join as join11, resolve as resolve8 } from "path";
7253
+ function isTargetArtifactType(type) {
7254
+ return isPacketTargetType(type);
7255
+ }
7256
+ function normalizeArtifactTypeRole(role) {
7257
+ if (typeof role === "string") {
7258
+ if (isTargetArtifactType(role)) return role;
7259
+ if (NON_TARGET_ROLES.includes(role)) return role;
7260
+ }
7261
+ return "context";
7262
+ }
7263
+ function getArtifactTypeMetadata(schema, type) {
7264
+ const definition = schema.types[type];
7265
+ const role = normalizeArtifactTypeRole(definition?.role);
7266
+ const aliases = Array.isArray(definition?.aliases) ? definition.aliases.filter((alias) => typeof alias === "string" && alias.trim().length > 0) : [];
7267
+ const legacyCoreRoleMatch = isTargetArtifactType(type) && role === type;
7268
+ const targetCapable = definition?.target === true || legacyCoreRoleMatch;
7269
+ return {
7270
+ type,
7271
+ displayName: definition?.displayName?.trim() || type,
7272
+ role,
7273
+ layer: definition?.layer?.trim() || "context",
7274
+ aliases,
7275
+ targetCapable
7276
+ };
7277
+ }
7278
+ function getTargetArtifactTypes(schema = DEFAULT_SCHEMA) {
7279
+ const legacy = TARGET_ARTIFACT_TYPES.filter((type) => getArtifactTypeMetadata(schema, type).targetCapable);
7280
+ const extras = Object.keys(schema.types).filter(
7281
+ (type) => getArtifactTypeMetadata(schema, type).targetCapable && !legacy.includes(type)
7282
+ );
7283
+ return [...legacy, ...extras];
7284
+ }
7285
+ function resolveArtifactTypeName(schema, token) {
7286
+ if (!token) return void 0;
7287
+ if (schema.types[token]) return token;
7288
+ for (const [type, definition] of Object.entries(schema.types)) {
7289
+ if (definition.aliases?.includes(token)) return type;
7290
+ }
7291
+ return void 0;
7292
+ }
7293
+ async function loadConfig(root) {
7294
+ const configPath = join11(root, "artifact-graph.config.yaml");
7295
+ let parsed = {};
7296
+ try {
7297
+ const raw = await readFile4(configPath, "utf-8");
7298
+ parsed = yaml.load(raw) ?? {};
7299
+ } catch (error) {
7300
+ if (error.code !== "ENOENT") {
7301
+ throw error;
7302
+ }
7303
+ }
7304
+ const ub = parsed.context?.universal_baseline;
7305
+ if (ub !== void 0 && typeof ub !== "boolean") {
7306
+ throw new Error(
7307
+ `Invalid context.universal_baseline: ${JSON.stringify(ub)}. Must be boolean (true or false).`
7308
+ );
7309
+ }
7310
+ if (parsed.e2e !== void 0) {
7311
+ if (typeof parsed.e2e !== "object" || parsed.e2e === null || Array.isArray(parsed.e2e)) {
7312
+ throw new Error("Invalid e2e: must be an object.");
7313
+ }
7314
+ validateE2eConfig(parsed.e2e);
7315
+ }
7316
+ validateRelationSemanticsConfig(parsed.relationSemantics);
7317
+ validateStatusViewsConfig(parsed.statusViews);
7318
+ const mergedE2e = parsed.e2e === void 0 ? DEFAULT_SCHEMA.e2e : {
7319
+ ...DEFAULT_SCHEMA.e2e,
7320
+ ...parsed.e2e,
7321
+ runners: (parsed.e2e.runners ?? DEFAULT_SCHEMA.e2e?.runners ?? []).map((runner) => ({
7322
+ kind: "e2e",
7323
+ ...runner
7324
+ }))
7325
+ };
7326
+ const merged = {
7327
+ ...DEFAULT_SCHEMA,
7328
+ ...parsed,
7329
+ types: mergeArtifactTypes(DEFAULT_SCHEMA.types, parsed.types),
7330
+ idPatterns: mergeRecord(DEFAULT_SCHEMA.idPatterns, parsed.idPatterns),
7331
+ relationFields: mergeRecord(DEFAULT_SCHEMA.relationFields, parsed.relationFields),
7332
+ allowedEdges: parsed.allowedEdges ?? DEFAULT_SCHEMA.allowedEdges,
7333
+ forbiddenEdges: parsed.forbiddenEdges ?? DEFAULT_SCHEMA.forbiddenEdges,
7334
+ statuses: parsed.statuses ?? DEFAULT_SCHEMA.statuses,
7335
+ idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
7336
+ e2e: mergedE2e
7337
+ };
7338
+ validateJsonArtifactTypes(merged.types);
7339
+ return merged;
7340
+ }
7341
+ function validateJsonArtifactTypes(types) {
7342
+ for (const [type, definition] of Object.entries(types)) {
7343
+ const raw = definition;
7344
+ const format = raw.format;
7345
+ const idField = raw.idField;
7346
+ if (format === void 0) {
7347
+ if (idField !== void 0) {
7348
+ throw new Error(`Invalid types.${type}.idField: idField requires format json.`);
7349
+ }
7350
+ continue;
7351
+ }
7352
+ if (format !== "json") {
7353
+ throw new Error(`Invalid types.${type}.format: only json is supported. Omit format to keep Markdown parsing.`);
7354
+ }
7355
+ if (SPECIALIZED_PARSER_TYPES.has(type)) {
7356
+ throw new Error(`Invalid types.${type}.format: JSON format applies only to custom types. ${type} keeps its dedicated parser.`);
7357
+ }
7358
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
7359
+ throw new Error(`Invalid types.${type}.idField: format json requires the name of one root property.`);
7360
+ }
7361
+ }
7362
+ }
7363
+ function validateRelationSemanticsConfig(value) {
7364
+ if (value === void 0) return;
7365
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
7366
+ throw new Error("Invalid relationSemantics: must be an object keyed by relation kind.");
7367
+ }
7368
+ for (const [kind, spec] of Object.entries(value)) {
7369
+ if (!kind.trim() || typeof spec !== "object" || spec === null || Array.isArray(spec)) {
7370
+ throw new Error(`Invalid relationSemantics.${kind}: must be an object.`);
5250
7371
  }
5251
7372
  if (typeof spec.label !== "string" || !spec.label.trim()) {
5252
7373
  throw new Error(`Invalid relationSemantics.${kind}.label: must be a non-empty string.`);
@@ -5322,7 +7443,7 @@ function validateE2eConfig(e2e) {
5322
7443
  if (typeof runner.root !== "string" || !runner.root.trim()) {
5323
7444
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
5324
7445
  }
5325
- if (isAbsolute4(runner.root)) {
7446
+ if (isAbsolute6(runner.root)) {
5326
7447
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
5327
7448
  }
5328
7449
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -5385,14 +7506,19 @@ function buildGraph(nodes, edges, diagnostics = [], root) {
5385
7506
  diagnostics: diagnostics.sort((left, right) => left.code.localeCompare(right.code) || left.path.localeCompare(right.path) || left.line - right.line)
5386
7507
  };
5387
7508
  }
5388
- async function scanArtifacts(root, schema) {
7509
+ async function scanArtifacts(root, schema, options = {}) {
5389
7510
  const config = schema ?? await loadConfig(root);
5390
7511
  const nodes = [];
5391
7512
  const edges = [];
5392
7513
  const scanDiagnostics = [];
5393
7514
  const scannedFiles = /* @__PURE__ */ new Map();
7515
+ const contentOverrides = options.contents instanceof Map ? options.contents : new Map(Object.entries(options.contents ?? {}));
5394
7516
  for (const [type, definition] of artifactTypeEntriesBySpecificity(config)) {
5395
- const files = await findFiles(root, definition.paths);
7517
+ const diskFiles = await findFiles(root, definition.paths);
7518
+ const files = [.../* @__PURE__ */ new Set([
7519
+ ...diskFiles.filter((file) => contentOverrides.get(file) !== null),
7520
+ ...[...contentOverrides.keys()].filter((file) => contentOverrides.get(file) !== null && definition.paths.some((pattern) => matchesPattern(file, pattern)))
7521
+ ])].sort();
5396
7522
  for (const file of files) {
5397
7523
  if (scannedFiles.has(file)) {
5398
7524
  const existingType = scannedFiles.get(file);
@@ -5406,15 +7532,15 @@ async function scanArtifacts(root, schema) {
5406
7532
  continue;
5407
7533
  }
5408
7534
  scannedFiles.set(file, type);
5409
- const raw = await readFile3(join8(root, file), "utf-8");
7535
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join11(root, file), "utf-8");
5410
7536
  const parsed = parseFile(type, file, raw, config);
5411
- const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7537
+ const semantic = isJsonOriginalType(type, config) ? { edges: [], diagnostics: [] } : parseConfiguredRelations(type, file, raw, parsed.nodes, config);
5412
7538
  nodes.push(...parsed.nodes);
5413
7539
  edges.push(...parsed.edges, ...semantic.edges);
5414
7540
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
5415
7541
  }
5416
7542
  }
5417
- const absoluteRoot = isAbsolute4(root) ? root : resolve5(root);
7543
+ const absoluteRoot = isAbsolute6(root) ? root : resolve8(root);
5418
7544
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
5419
7545
  return resolveMatrixEdges(graph);
5420
7546
  }
@@ -5619,33 +7745,6 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5619
7745
  issues.push(issue("CYCLE_DETECTED", `depends_on cycle detected: ${cycle.join(" -> ")}`, "", 1, { node: cycle[0] }));
5620
7746
  }
5621
7747
  const defaultTypeKeys = new Set(Object.keys(DEFAULT_SCHEMA.types));
5622
- const specializedParserTypes = /* @__PURE__ */ new Set([
5623
- "feature",
5624
- "scenario",
5625
- "entity",
5626
- "decision",
5627
- "test",
5628
- "design",
5629
- "e2e_test",
5630
- "e2e_registry",
5631
- "rule-golden-cases",
5632
- "test-strategy",
5633
- "traceability-matrix-v2",
5634
- "traceability-version-lock",
5635
- "interface_contracts",
5636
- "data_contracts",
5637
- "application_state_machines",
5638
- "error_model",
5639
- "domain-glossary",
5640
- "bounded-context-map",
5641
- "domain-invariants",
5642
- "generation-packet-spec",
5643
- "report-contracts",
5644
- "verification-fixtures",
5645
- "ui-flow-contracts",
5646
- "non-functional-budgets",
5647
- "implementation-blueprint"
5648
- ]);
5649
7748
  const uidsWithEdges = /* @__PURE__ */ new Set();
5650
7749
  for (const edge2 of graph.edges) {
5651
7750
  uidsWithEdges.add(edge2.from);
@@ -5653,7 +7752,7 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
5653
7752
  }
5654
7753
  for (const node of graph.nodes) {
5655
7754
  if (defaultTypeKeys.has(node.type)) continue;
5656
- if (specializedParserTypes.has(node.type)) continue;
7755
+ if (SPECIALIZED_PARSER_TYPES.has(node.type)) continue;
5657
7756
  if (!schema.types[node.type]) continue;
5658
7757
  if (!uidsWithEdges.has(node.uid)) {
5659
7758
  issues.push(issue(
@@ -5697,13 +7796,13 @@ function validateScenarioPrdLinksInternal(graph, schema, includeScanDiagnosedInv
5697
7796
  const scenarioFeatureRefs = /* @__PURE__ */ new Map();
5698
7797
  const featureScenarioRefs = /* @__PURE__ */ new Map();
5699
7798
  for (const node of scenarioNodes) {
5700
- scenarioFeatureRefs.set(node.uid, relationOccurrences(node, "\u5173\u8054\u529F\u80FD", "feature"));
7799
+ scenarioFeatureRefs.set(node.uid, relationOccurrences2(node, "\u5173\u8054\u529F\u80FD", "feature"));
5701
7800
  if (!scenarioPattern.test(node.code)) {
5702
7801
  issues.push(issue("FORMAT_ERROR", `scenario ID ${node.code} does not match ${schema.idPatterns.scenario}`, node.path, node.line, { node: node.uid }));
5703
7802
  }
5704
7803
  }
5705
7804
  for (const node of featureNodes) {
5706
- featureScenarioRefs.set(node.uid, relationOccurrences(node, "scenarios", "scenario"));
7805
+ featureScenarioRefs.set(node.uid, relationOccurrences2(node, "scenarios", "scenario"));
5707
7806
  if (!featurePattern.test(node.code)) {
5708
7807
  issues.push(issue("FORMAT_ERROR", `feature ID ${node.code} does not match ${schema.idPatterns.feature}`, node.path, node.line, { node: node.uid }));
5709
7808
  }
@@ -5777,7 +7876,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5777
7876
  const indexPath = "artifacts/prd/feature-index.md";
5778
7877
  let raw = "";
5779
7878
  try {
5780
- raw = await readFile3(join8(root, indexPath), "utf-8");
7879
+ raw = await readFile4(join11(root, indexPath), "utf-8");
5781
7880
  } catch (error) {
5782
7881
  if (error.code === "ENOENT") {
5783
7882
  return [];
@@ -5797,7 +7896,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
5797
7896
  if (!feature) {
5798
7897
  return;
5799
7898
  }
5800
- const actualCount = relationOccurrences(feature, "scenarios", "scenario").length;
7899
+ const actualCount = relationOccurrences2(feature, "scenarios", "scenario").length;
5801
7900
  if (actualCount !== expectedCount) {
5802
7901
  issues.push(issue(
5803
7902
  "INDEX_MISMATCH",
@@ -6025,12 +8124,12 @@ function nextId(graph, schema, type, rangeName) {
6025
8124
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
6026
8125
  }
6027
8126
  async function writeGraphCache(root, graph) {
6028
- const cacheDir = join8(root, ".artifact-graph");
6029
- await mkdir4(cacheDir, { recursive: true });
6030
- await writeFile3(join8(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
8127
+ const cacheDir = join11(root, ".artifact-graph");
8128
+ await mkdir5(cacheDir, { recursive: true });
8129
+ await writeFile3(join11(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
6031
8130
  `);
6032
8131
  const { default: Database } = await import("better-sqlite3");
6033
- const db = new Database(join8(cacheDir, "graph.sqlite"));
8132
+ const db = new Database(join11(cacheDir, "graph.sqlite"));
6034
8133
  try {
6035
8134
  db.exec(`
6036
8135
  DROP TABLE IF EXISTS nodes;
@@ -6071,7 +8170,13 @@ async function writeGraphCache(root, graph) {
6071
8170
  db.close();
6072
8171
  }
6073
8172
  }
8173
+ function isJsonOriginalType(type, schema) {
8174
+ return schema.types[type]?.format === "json" && !SPECIALIZED_PARSER_TYPES.has(type);
8175
+ }
6074
8176
  function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
8177
+ if (isJsonOriginalType(type, schema)) {
8178
+ return parseGenericJson(type, path, raw, schema);
8179
+ }
6075
8180
  if (type === "feature") {
6076
8181
  return { ...parseFeature(path, raw), diagnostics: [] };
6077
8182
  }
@@ -6114,31 +8219,209 @@ function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
6114
8219
  if (type === "rule-golden-cases") {
6115
8220
  return { ...parseRuleGoldenCases(path, raw), diagnostics: [] };
6116
8221
  }
6117
- if (type === "test-strategy") {
6118
- return { ...parseTestStrategy(path, raw), diagnostics: [] };
8222
+ if (type === "test-strategy") {
8223
+ return { ...parseTestStrategy(path, raw), diagnostics: [] };
8224
+ }
8225
+ if (type === "traceability-matrix-v2") {
8226
+ return { ...parseTraceabilityMatrixV2(path, raw), diagnostics: [] };
8227
+ }
8228
+ if (type === "traceability-version-lock") {
8229
+ return { ...parseTraceabilityVersionLock(path, raw), diagnostics: [] };
8230
+ }
8231
+ if (type === "report-contracts") {
8232
+ return { ...parseReportContracts(path, raw), diagnostics: [] };
8233
+ }
8234
+ if (type === "verification-fixtures") {
8235
+ return { ...parseVerificationFixtures(path, raw), diagnostics: [] };
8236
+ }
8237
+ if (type === "ui-flow-contracts") {
8238
+ return { ...parseUIFlowContracts(path, raw), diagnostics: [] };
8239
+ }
8240
+ if (type === "non-functional-budgets") {
8241
+ return { ...parseNonFunctionalBudgets(path, raw), diagnostics: [] };
8242
+ }
8243
+ if (type === "implementation-blueprint") {
8244
+ return { ...parseImplementationBlueprint(path, raw), diagnostics: [] };
8245
+ }
8246
+ return parseGenericMarkdown(type, path, raw, schema);
8247
+ }
8248
+ function isJsonObject(value) {
8249
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8250
+ }
8251
+ function jsonRootKind(value) {
8252
+ if (Array.isArray(value)) return "array";
8253
+ if (value === null) return "null";
8254
+ return typeof value;
8255
+ }
8256
+ function parseGenericJson(type, path, raw, schema) {
8257
+ const diagnostics = [];
8258
+ const idField = schema.types[type]?.idField;
8259
+ if (typeof idField !== "string" || idField.length === 0 || idField.trim() !== idField) {
8260
+ diagnostics.push(issue(
8261
+ "INVALID_JSON",
8262
+ `types.${type}.idField must name one root property when format is json`,
8263
+ path,
8264
+ 1
8265
+ ));
8266
+ return { nodes: [], edges: [], diagnostics };
8267
+ }
8268
+ let parsed;
8269
+ try {
8270
+ parsed = JSON.parse(raw);
8271
+ } catch (error) {
8272
+ diagnostics.push(issue(
8273
+ "INVALID_JSON",
8274
+ `JSON artifact ${path} is not valid JSON: ${error.message}`,
8275
+ path,
8276
+ 1
8277
+ ));
8278
+ return { nodes: [], edges: [], diagnostics };
8279
+ }
8280
+ if (!isJsonObject(parsed)) {
8281
+ diagnostics.push(issue(
8282
+ "INVALID_JSON_ROOT",
8283
+ `JSON artifact ${path} must be one root object, got ${jsonRootKind(parsed)}`,
8284
+ path,
8285
+ 1
8286
+ ));
8287
+ return { nodes: [], edges: [], diagnostics };
8288
+ }
8289
+ if (!Object.prototype.hasOwnProperty.call(parsed, idField)) {
8290
+ diagnostics.push(issue(
8291
+ "ARTIFACT_ID_MISSING",
8292
+ `Artifact of type ${type} at ${path} has no root property ${idField}`,
8293
+ path,
8294
+ 1,
8295
+ { severity: "warning" }
8296
+ ));
8297
+ return { nodes: [], edges: [], diagnostics };
8298
+ }
8299
+ const idValue = parsed[idField];
8300
+ if (typeof idValue !== "string") {
8301
+ diagnostics.push(issue(
8302
+ "INVALID_ID",
8303
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8304
+ path,
8305
+ 1
8306
+ ));
8307
+ return { nodes: [], edges: [], diagnostics };
6119
8308
  }
6120
- if (type === "traceability-matrix-v2") {
6121
- return { ...parseTraceabilityMatrixV2(path, raw), diagnostics: [] };
8309
+ if (idValue.trim() === "") {
8310
+ diagnostics.push(issue(
8311
+ "ARTIFACT_ID_MISSING",
8312
+ `Artifact of type ${type} at ${path} field ${idField} must be a non-empty string`,
8313
+ path,
8314
+ 1,
8315
+ { severity: "warning" }
8316
+ ));
8317
+ return { nodes: [], edges: [], diagnostics };
6122
8318
  }
6123
- if (type === "traceability-version-lock") {
6124
- return { ...parseTraceabilityVersionLock(path, raw), diagnostics: [] };
8319
+ const code = idValue;
8320
+ const idPattern = schema.idPatterns[type];
8321
+ if (idPattern && !new RegExp(idPattern).test(code)) {
8322
+ diagnostics.push(issue(
8323
+ "INVALID_ID",
8324
+ `Artifact ${type}:${code} field ${idField} does not match ${idPattern}`,
8325
+ path,
8326
+ 1,
8327
+ { node: toUid(type, code) }
8328
+ ));
6125
8329
  }
6126
- if (type === "report-contracts") {
6127
- return { ...parseReportContracts(path, raw), diagnostics: [] };
8330
+ const node = {
8331
+ type,
8332
+ code,
8333
+ title: code,
8334
+ path,
8335
+ line: 1
8336
+ };
8337
+ const relations = jsonConfiguredRelations(type, path, parsed, schema, toUid(type, code));
8338
+ diagnostics.push(...relations.diagnostics);
8339
+ return { nodes: [node], edges: relations.edges, diagnostics };
8340
+ }
8341
+ function readJsonRelation(record, field) {
8342
+ const segments = field.split(".");
8343
+ if (segments.some((segment) => segment.length === 0)) {
8344
+ return { status: "illegal-path" };
6128
8345
  }
6129
- if (type === "verification-fixtures") {
6130
- return { ...parseVerificationFixtures(path, raw), diagnostics: [] };
8346
+ let current = record;
8347
+ for (let index = 0; index < segments.length; index += 1) {
8348
+ const key = segments[index] ?? "";
8349
+ if (!isJsonObject(current)) {
8350
+ return { status: "type-error", at: segments.slice(0, index).join(".") };
8351
+ }
8352
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
8353
+ return { status: "absent" };
8354
+ }
8355
+ const next = current[key];
8356
+ const last = index === segments.length - 1;
8357
+ if (!last && !isJsonObject(next)) {
8358
+ return { status: "type-error", at: segments.slice(0, index + 1).join(".") };
8359
+ }
8360
+ current = next;
6131
8361
  }
6132
- if (type === "ui-flow-contracts") {
6133
- return { ...parseUIFlowContracts(path, raw), diagnostics: [] };
8362
+ return { status: "value", value: current };
8363
+ }
8364
+ function jsonRelationTerminal(value, field, path, sourceUid, diagnostics) {
8365
+ const message = `Relation field ${field} in ${path} must be a non-empty string or an array of non-empty strings`;
8366
+ if (typeof value === "string") {
8367
+ if (value.trim() === "") {
8368
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8369
+ return [];
8370
+ }
8371
+ return [value];
6134
8372
  }
6135
- if (type === "non-functional-budgets") {
6136
- return { ...parseNonFunctionalBudgets(path, raw), diagnostics: [] };
8373
+ if (Array.isArray(value)) {
8374
+ const refs = [];
8375
+ for (const item of value) {
8376
+ if (typeof item !== "string" || item.trim() === "") {
8377
+ diagnostics.push(issue(
8378
+ "RELATION_VALUE_TYPE",
8379
+ `Relation field ${field} in ${path} must contain only non-empty strings`,
8380
+ path,
8381
+ 1,
8382
+ { node: sourceUid }
8383
+ ));
8384
+ continue;
8385
+ }
8386
+ refs.push(item);
8387
+ }
8388
+ return refs;
6137
8389
  }
6138
- if (type === "implementation-blueprint") {
6139
- return { ...parseImplementationBlueprint(path, raw), diagnostics: [] };
8390
+ diagnostics.push(issue("RELATION_VALUE_TYPE", message, path, 1, { node: sourceUid }));
8391
+ return [];
8392
+ }
8393
+ function jsonConfiguredRelations(type, path, record, schema, sourceUid) {
8394
+ const edges = [];
8395
+ const diagnostics = [];
8396
+ for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
8397
+ for (const field of spec.fields) {
8398
+ const read = readJsonRelation(record, field);
8399
+ if (read.status === "absent") continue;
8400
+ if (read.status === "illegal-path") {
8401
+ diagnostics.push(issue(
8402
+ "INVALID_RELATION_FIELD",
8403
+ `Relation field ${field} is not a fixed path of own properties`,
8404
+ path,
8405
+ 1,
8406
+ { node: sourceUid }
8407
+ ));
8408
+ continue;
8409
+ }
8410
+ if (read.status === "type-error") {
8411
+ diagnostics.push(issue(
8412
+ "RELATION_VALUE_TYPE",
8413
+ `Relation field ${field} in ${path} cannot be read at ${read.at}: expected an object`,
8414
+ path,
8415
+ 1,
8416
+ { node: sourceUid }
8417
+ ));
8418
+ continue;
8419
+ }
8420
+ const values = jsonRelationTerminal(read.value, field, path, sourceUid, diagnostics);
8421
+ appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, "json", edges, diagnostics);
8422
+ }
6140
8423
  }
6141
- return parseGenericMarkdown(type, path, raw, schema);
8424
+ return { edges, diagnostics };
6142
8425
  }
6143
8426
  function parseGenericMarkdown(type, path, raw, schema) {
6144
8427
  const diagnostics = [];
@@ -6258,38 +8541,18 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6258
8541
  const diagnostics = [];
6259
8542
  for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
6260
8543
  for (const field of spec.fields) {
6261
- for (const value of toArray(data[field])) {
6262
- const parsed = parseConfiguredRelationTarget(value, spec, schema);
6263
- if (!parsed?.code) continue;
6264
- const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
6265
- const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
6266
- if (!parsed.targetType && matchingTargetTypes.length > 1) {
6267
- diagnostics.push(issue(
6268
- "AMBIGUOUS_RELATION_TARGET",
6269
- `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
6270
- path,
6271
- 1,
6272
- { node: sourceUid }
6273
- ));
6274
- }
6275
- const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
6276
- if (targetType) {
6277
- const pattern = schema.idPatterns[targetType];
6278
- if (pattern && !new RegExp(pattern).test(parsed.code)) {
6279
- diagnostics.push(issue(
6280
- "FORMAT_ERROR",
6281
- `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
6282
- path,
6283
- 1,
6284
- { node: sourceUid }
6285
- ));
6286
- }
6287
- }
6288
- edges.push({
6289
- ...edge(sourceUid, targetUid, kind, "frontmatter", path, 1),
6290
- ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
6291
- });
6292
- }
8544
+ appendConfiguredRelationEdges(
8545
+ sourceUid,
8546
+ kind,
8547
+ field,
8548
+ toArray(data[field]),
8549
+ spec,
8550
+ schema,
8551
+ path,
8552
+ "frontmatter",
8553
+ edges,
8554
+ diagnostics
8555
+ );
6293
8556
  }
6294
8557
  }
6295
8558
  const external = getExternalEntryInfo({
@@ -6308,6 +8571,40 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
6308
8571
  }
6309
8572
  return { edges, diagnostics };
6310
8573
  }
8574
+ function appendConfiguredRelationEdges(sourceUid, kind, field, values, spec, schema, path, edgeSource, edges, diagnostics) {
8575
+ for (const value of values) {
8576
+ const parsed = parseConfiguredRelationTarget(value, spec, schema);
8577
+ if (!parsed?.code) continue;
8578
+ const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
8579
+ const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
8580
+ if (!parsed.targetType && matchingTargetTypes.length > 1) {
8581
+ diagnostics.push(issue(
8582
+ "AMBIGUOUS_RELATION_TARGET",
8583
+ `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
8584
+ path,
8585
+ 1,
8586
+ { node: sourceUid }
8587
+ ));
8588
+ }
8589
+ const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
8590
+ if (targetType) {
8591
+ const pattern = schema.idPatterns[targetType];
8592
+ if (pattern && !new RegExp(pattern).test(parsed.code)) {
8593
+ diagnostics.push(issue(
8594
+ "FORMAT_ERROR",
8595
+ `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
8596
+ path,
8597
+ 1,
8598
+ { node: sourceUid }
8599
+ ));
8600
+ }
8601
+ }
8602
+ edges.push({
8603
+ ...edge(sourceUid, targetUid, kind, edgeSource, path, 1),
8604
+ ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
8605
+ });
8606
+ }
8607
+ }
6311
8608
  function parseConfiguredRelationTarget(value, spec, schema) {
6312
8609
  if (typeof value === "string" || typeof value === "number") {
6313
8610
  const raw = String(value).trim();
@@ -6392,7 +8689,7 @@ function parseFeature(path, raw) {
6392
8689
  }
6393
8690
  function parseScenarios(path, raw, schema = DEFAULT_SCHEMA) {
6394
8691
  const lines = raw.split(/\r?\n/);
6395
- const codeLines = markdownCodeLineMask(lines);
8692
+ const codeLines = markdownCodeLineMask2(lines);
6396
8693
  const scenarioIdPattern = new RegExp(schema.idPatterns.scenario ?? DEFAULT_SCHEMA.idPatterns.scenario);
6397
8694
  const starts = [];
6398
8695
  lines.forEach((line, index) => {
@@ -6498,7 +8795,7 @@ function parseDecisions(path, raw) {
6498
8795
  }
6499
8796
  function isTestFile(filePath) {
6500
8797
  const normalized = filePath.replace(/\\/g, "/");
6501
- const name = basename4(normalized);
8798
+ const name = basename5(normalized);
6502
8799
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
6503
8800
  if (/(^|\/)(tests|test|__tests__)\//.test(normalized)) return true;
6504
8801
  if (/\w+Tests?\.java$/.test(name)) return true;
@@ -6810,41 +9107,15 @@ function parseE2eTest(path, raw) {
6810
9107
  const parsed = matter(raw);
6811
9108
  const data = parsed.data;
6812
9109
  const lines = raw.split(/\r?\n/);
6813
- const starts = [];
6814
- lines.forEach((line, index) => {
6815
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
6816
- if (match) {
6817
- starts.push({ id: match[1], title: match[2].trim(), line: index + 1, index });
6818
- }
6819
- });
9110
+ const starts = extractE2eTestCaseStarts(lines);
6820
9111
  const nodes = [];
6821
9112
  const edges = [];
6822
- const batch = String(data.test_batch ?? basename4(path, extname(path))).trim();
9113
+ const batch = String(data.test_batch ?? basename5(path, extname(path))).trim();
6823
9114
  const frontmatterScenarios = toArray(data.related_scenarios).map((value) => String(value).trim()).filter(Boolean);
6824
9115
  const scopeFeatures = extractCodes(String(data.scope ?? ""), "feature");
6825
- const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord(data.ac_coverage)), ...scopeFeatures])];
9116
+ const frontmatterFeatures = [.../* @__PURE__ */ new Set([...Object.keys(asRecord2(data.ac_coverage)), ...scopeFeatures])];
6826
9117
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
6827
9118
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
6828
- if (starts.length === 0) {
6829
- const code = `${batch}:FILE`;
6830
- nodes.push({
6831
- type: "e2e_test",
6832
- code,
6833
- title: raw.match(/^#\s+(.+)$/m)?.[1] ?? batch,
6834
- path,
6835
- line: 1,
6836
- attrs: {
6837
- ...data,
6838
- testCaseId: "FILE",
6839
- fileLevelOnly: true,
6840
- tcFields: {},
6841
- blockText: raw,
6842
- coveredFeatures: [],
6843
- coveredScenarios: []
6844
- }
6845
- });
6846
- addE2eFrontmatterEdges(edges, code, path, frontmatterScenarios, frontmatterFeatures, frontmatterDecisions, frontmatterEntities);
6847
- }
6848
9119
  for (let index = 0; index < starts.length; index += 1) {
6849
9120
  const start = starts[index];
6850
9121
  const end = starts[index + 1]?.index ?? lines.length;
@@ -6870,6 +9141,16 @@ function parseE2eTest(path, raw) {
6870
9141
  }
6871
9142
  return { nodes, edges };
6872
9143
  }
9144
+ function extractE2eTestCaseStarts(lines) {
9145
+ const codeLines = markdownCodeLineMask2(lines);
9146
+ return lines.flatMap((line, index) => {
9147
+ if (codeLines[index]) {
9148
+ return [];
9149
+ }
9150
+ const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*(.*?)\s*$/.exec(line);
9151
+ return match ? [{ id: match[1], title: match[2].trim(), line: index + 1, index }] : [];
9152
+ });
9153
+ }
6873
9154
  function addE2eFrontmatterEdges(edges, code, path, scenarios, features, decisions, entities) {
6874
9155
  for (const scenario of scenarios) {
6875
9156
  edges.push(edge(toUid("e2e_test", code), toUid("scenario", scenario), "verifies", "frontmatter", path, 1));
@@ -6892,7 +9173,7 @@ function parseE2eRegistry(path, raw) {
6892
9173
  data = { parseError: error.message };
6893
9174
  }
6894
9175
  return {
6895
- nodes: [{ type: "e2e_registry", code: basename4(path, extname(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
9176
+ nodes: [{ type: "e2e_registry", code: basename5(path, extname(path)), title: "E2E Test Registry", path, line: 1, attrs: data }],
6896
9177
  edges: []
6897
9178
  };
6898
9179
  }
@@ -7654,7 +9935,7 @@ function matchExplicitRelationFieldLine(line, label) {
7654
9935
  const match = new RegExp(`^ {0,3}(?:\\*\\*${escaped}\\*\\*|${escaped})[:\uFF1A]\\s*(.*?)\\s*$`).exec(line);
7655
9936
  return match?.[1] ?? null;
7656
9937
  }
7657
- function markdownCodeLineMask(lines) {
9938
+ function markdownCodeLineMask2(lines) {
7658
9939
  const result = new Array(lines.length).fill(false);
7659
9940
  let fence;
7660
9941
  lines.forEach((line, index) => {
@@ -7699,14 +9980,14 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
7699
9980
  });
7700
9981
  return result;
7701
9982
  }
7702
- function relationOccurrences(node, field, targetType) {
7703
- const relationRecord = asRecord(node.attrs?.relationOccurrences);
9983
+ function relationOccurrences2(node, field, targetType) {
9984
+ const relationRecord = asRecord2(node.attrs?.relationOccurrences);
7704
9985
  const rawOccurrences = toArray(relationRecord[field]);
7705
9986
  return rawOccurrences.flatMap((value) => {
7706
9987
  if (typeof value === "string") {
7707
9988
  return [{ field, targetType, target: value, path: node.path, line: node.line }];
7708
9989
  }
7709
- const record = asRecord(value);
9990
+ const record = asRecord2(value);
7710
9991
  const target = String(record.target ?? "").trim();
7711
9992
  if (!target) {
7712
9993
  return [];
@@ -7813,7 +10094,7 @@ function validateE2eTests(graph) {
7813
10094
  issues.push(issue("E2E_REQUIRED_FRONTMATTER", `${node.uid} missing required frontmatter ${field}`, node.path, 1, { node: node.uid, severity: "warning" }));
7814
10095
  }
7815
10096
  }
7816
- const fields = asRecord(attrs.tcFields);
10097
+ const fields = asRecord2(attrs.tcFields);
7817
10098
  const requiredTcFields = [
7818
10099
  ["\u6807\u9898", node.title],
7819
10100
  ["\u524D\u7F6E\u6761\u4EF6", fields["\u524D\u7F6E\u6761\u4EF6"]],
@@ -7863,7 +10144,7 @@ function validateE2eTests(graph) {
7863
10144
  }
7864
10145
  for (const [path, nodes] of nodesByPath) {
7865
10146
  const first = nodes[0];
7866
- const declared = flattenAcCoverage(asRecord(first.attrs?.ac_coverage));
10147
+ const declared = flattenAcCoverage(asRecord2(first.attrs?.ac_coverage));
7867
10148
  const covered = new Set(nodes.flatMap((node) => toArray(node.attrs?.coveredFeatures).map((value) => {
7868
10149
  const ref = value;
7869
10150
  return `${String(ref.feature)}:${String(ref.ac)}`;
@@ -7898,13 +10179,16 @@ function validateE2eRegistry(graph) {
7898
10179
  }
7899
10180
  const actualNodes = byPath.get(file) ?? [];
7900
10181
  if (actualNodes.length === 0) {
10182
+ if (Number(batch.test_case_count ?? NaN) === 0) {
10183
+ continue;
10184
+ }
7901
10185
  issues.push(issue("E2E_REGISTRY_MISMATCH", `registry batch ${String(batch.batch_id ?? file)} file ${file || "<missing>"} does not match any E2E test file`, registry.path, registry.line, { node: registry.uid, severity: "warning" }));
7902
10186
  continue;
7903
10187
  }
7904
10188
  const first = actualNodes[0];
7905
10189
  compareRegistryValue(issues, registry, batch, "batch_id", first.attrs?.test_batch);
7906
10190
  compareRegistryValue(issues, registry, batch, "scope", first.attrs?.scope);
7907
- compareRegistryAcCoverage(issues, registry, batch, asRecord(first.attrs?.ac_coverage));
10191
+ compareRegistryAcCoverage(issues, registry, batch, asRecord2(first.attrs?.ac_coverage));
7908
10192
  compareRegistryArray(issues, registry, batch, "related_scenarios", toArray(first.attrs?.related_scenarios).map((value) => String(value)));
7909
10193
  compareRegistryValue(issues, registry, batch, "test_case_count", actualNodes.filter((node) => node.attrs?.fileLevelOnly !== true).length);
7910
10194
  }
@@ -7918,31 +10202,21 @@ function validateE2eRegistry(graph) {
7918
10202
  async function validateExecutableTraceability(root, config) {
7919
10203
  const issues = [];
7920
10204
  const schema = config ?? await loadConfig(root);
7921
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
7922
- let e2eFiles;
7923
- try {
7924
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
7925
- } catch {
10205
+ const e2eFiles = await findConfiguredE2eFiles(root, schema);
10206
+ if (e2eFiles.length === 0) {
7926
10207
  return [];
7927
10208
  }
7928
10209
  const mdToRef = /* @__PURE__ */ new Map();
7929
10210
  const allMdTcInfo = /* @__PURE__ */ new Map();
7930
10211
  const tcKeyToFields = /* @__PURE__ */ new Map();
7931
10212
  const mdBatches = /* @__PURE__ */ new Set();
7932
- for (const filePath of e2eFiles) {
7933
- const raw = await readFile3(filePath, "utf-8");
7934
- const relPath = relative4(root, filePath).split("\\").join("/");
10213
+ for (const relPath of e2eFiles) {
10214
+ const raw = await readFile4(join11(root, relPath), "utf-8");
7935
10215
  const parsed = matter(raw);
7936
10216
  const data = parsed.data;
7937
- const batch = String(data.test_batch ?? basename4(filePath, extname(filePath))).trim();
10217
+ const batch = String(data.test_batch ?? basename5(relPath, extname(relPath))).trim();
7938
10218
  const lines = raw.split(/\r?\n/);
7939
- const tcStarts = [];
7940
- lines.forEach((line, index) => {
7941
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
7942
- if (match) {
7943
- tcStarts.push({ id: match[1], line: index + 1, index });
7944
- }
7945
- });
10219
+ const tcStarts = extractE2eTestCaseStarts(lines);
7946
10220
  for (let i = 0; i < tcStarts.length; i += 1) {
7947
10221
  const start = tcStarts[i];
7948
10222
  const end = tcStarts[i + 1]?.index ?? lines.length;
@@ -7979,10 +10253,10 @@ async function validateExecutableTraceability(root, config) {
7979
10253
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
7980
10254
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
7981
10255
  for (const specFile of specFiles) {
7982
- const fullSpecPath = join8(root, specFile);
10256
+ const fullSpecPath = join11(root, specFile);
7983
10257
  let content;
7984
10258
  try {
7985
- content = await readFile3(fullSpecPath, "utf-8");
10259
+ content = await readFile4(fullSpecPath, "utf-8");
7986
10260
  } catch {
7987
10261
  continue;
7988
10262
  }
@@ -8061,7 +10335,7 @@ async function validateExecutableTraceability(root, config) {
8061
10335
  if (entry.testId) {
8062
10336
  let content;
8063
10337
  try {
8064
- content = await readFile3(join8(root, normalizedRefFile), "utf-8");
10338
+ content = await readFile4(join11(root, normalizedRefFile), "utf-8");
8065
10339
  } catch {
8066
10340
  continue;
8067
10341
  }
@@ -8089,7 +10363,7 @@ async function validateExecutableTraceability(root, config) {
8089
10363
  }
8090
10364
  continue;
8091
10365
  }
8092
- if (!mdToRef.has(tcKey) && !await hasMarkdownTc(tcKey, e2eDir)) {
10366
+ if (!allMdTcInfo.has(tcKey)) {
8093
10367
  for (const ann of annotations) {
8094
10368
  issues.push(issue("E2E-TRACE-002", `E2E trace annotation ${tcKey} references non-existent Markdown TC`, ann.file, ann.line, { node: tcKey, severity: "warning" }));
8095
10369
  }
@@ -8238,37 +10512,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8238
10512
  let withExecutableRef = 0;
8239
10513
  const statusBreakdown = {};
8240
10514
  const chainTypeBreakdown = {};
8241
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8242
- const tcFieldsMap = /* @__PURE__ */ new Map();
8243
- let e2eFiles;
8244
- try {
8245
- e2eFiles = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).map((name) => join8(e2eDir, name));
8246
- } catch {
8247
- e2eFiles = [];
8248
- }
8249
- for (const filePath of e2eFiles) {
8250
- const raw = await readFile3(filePath, "utf-8");
8251
- const lines = raw.split(/\r?\n/);
8252
- const tcStarts = [];
8253
- lines.forEach((line, index) => {
8254
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8255
- if (match) {
8256
- tcStarts.push({ id: match[1], index });
8257
- }
8258
- });
8259
- const parsed = matter(raw);
8260
- const batch = String(parsed.data.test_batch ?? basename4(filePath, extname(filePath))).trim();
8261
- for (let i = 0; i < tcStarts.length; i++) {
8262
- const start = tcStarts[i];
8263
- const end = tcStarts[i + 1]?.index ?? lines.length;
8264
- const block = lines.slice(start.index, end);
8265
- const fields = extractE2eTcFields(block);
8266
- tcFieldsMap.set(`${batch}:${start.id}`, fields);
8267
- }
8268
- }
10515
+ const tcFieldsMap = new Map(e2eNodes.map((node) => [
10516
+ node.code,
10517
+ asRecord2(node.attrs?.tcFields)
10518
+ ]));
8269
10519
  for (const node of e2eNodes) {
8270
10520
  const tcKey = node.code;
8271
- const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
10521
+ const fields = tcFieldsMap.get(tcKey) ?? asRecord2(node.attrs?.tcFields);
8272
10522
  const execRef = String(fields["executable_ref"] ?? "").trim();
8273
10523
  if (execRef && !isPendingExecutableRef(execRef)) {
8274
10524
  withExecutableRef++;
@@ -8298,8 +10548,8 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8298
10548
  }
8299
10549
  }
8300
10550
  for (const node of e2eNodes) {
8301
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8302
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10551
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10552
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8303
10553
  for (const feature of Object.keys(acCoverage)) {
8304
10554
  acCoveredFeatures.add(feature);
8305
10555
  }
@@ -8311,7 +10561,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8311
10561
  const runners = (await loadConfig(root)).e2e?.runners ?? [];
8312
10562
  const allProjectFiles = await walkFiles(root);
8313
10563
  for (const node of e2eNodes) {
8314
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
10564
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
8315
10565
  const status = String(fields["status"] ?? "").trim().toLowerCase();
8316
10566
  const execRef = String(fields["executable_ref"] ?? "").trim();
8317
10567
  if (status !== "verified") continue;
@@ -8320,7 +10570,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8320
10570
  let hasActiveE2eRef = false;
8321
10571
  for (const entry of parseExecutableRefLines(execRef)) {
8322
10572
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
8323
- if (!normalized || !existsSync3(join8(root, normalized))) continue;
10573
+ if (!normalized || !existsSync3(join11(root, normalized))) continue;
8324
10574
  const accepting = await getAcceptingRunners(root, normalized, runners);
8325
10575
  if (accepting.some((runner) => runner.kind === "e2e")) {
8326
10576
  hasActiveE2eRef = true;
@@ -8332,7 +10582,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8332
10582
  for (const scenario of relatedScenarios) {
8333
10583
  verifiedScenarios.add(scenario);
8334
10584
  }
8335
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10585
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8336
10586
  for (const feature of Object.keys(acCoverage)) {
8337
10587
  verifiedFeatures.add(feature);
8338
10588
  }
@@ -8379,13 +10629,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8379
10629
  const acCoverageRateByFeature = {};
8380
10630
  const featureAcMap = /* @__PURE__ */ new Map();
8381
10631
  for (const node of featureNodes) {
8382
- const acs = parseAcceptanceCriteria(await readFile3(join8(root, node.path), "utf-8"));
10632
+ const acs = parseAcceptanceCriteria(await readFile4(join11(root, node.path), "utf-8"));
8383
10633
  featureAcMap.set(node.code, new Set(acs));
8384
10634
  }
8385
10635
  const coveredAcByFeature = /* @__PURE__ */ new Map();
8386
10636
  for (const node of e2eNodes) {
8387
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
8388
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10637
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
10638
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
8389
10639
  for (const [feature, acs] of Object.entries(acCoverage)) {
8390
10640
  const existing = coveredAcByFeature.get(feature) ?? /* @__PURE__ */ new Set();
8391
10641
  for (const ac of toArray(acs)) {
@@ -8421,39 +10671,26 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
8421
10671
  };
8422
10672
  }
8423
10673
  async function generateE2eRegistry(root, opts) {
8424
- const e2eDir = join8(root, "artifacts", "tests", "e2e");
8425
- let files;
8426
- try {
8427
- files = (await readdir3(e2eDir)).filter((name) => /^test-.*\.md$/.test(name)).sort();
8428
- } catch {
8429
- return {
8430
- registry_version: "1.0",
8431
- generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8432
- total_batches: 0,
8433
- total_test_cases: 0,
8434
- batches: []
8435
- };
8436
- }
10674
+ const schema = await loadConfig(root);
10675
+ const files = await findConfiguredE2eFiles(root, schema);
8437
10676
  const batches = [];
10677
+ const batchIds = /* @__PURE__ */ new Set();
8438
10678
  let totalTestCases = 0;
8439
10679
  for (const file of files) {
8440
- const filePath = join8(e2eDir, file);
8441
- const raw = await readFile3(filePath, "utf-8");
10680
+ const filePath = join11(root, file);
10681
+ const raw = await readFile4(filePath, "utf-8");
8442
10682
  const parsed = matter(raw);
8443
10683
  const data = parsed.data;
8444
- const batch = String(data.test_batch ?? basename4(file, extname(file))).trim();
8445
- const relPath = `artifacts/tests/e2e/${file}`;
10684
+ const batch = String(data.test_batch ?? basename5(file, extname(file))).trim();
10685
+ const relPath = file;
8446
10686
  const scope = String(data.scope ?? "").trim();
8447
10687
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
8448
10688
  const relatedScenarios = toArray(data.related_scenarios).map(String).filter(Boolean);
8449
10689
  const lines = raw.split(/\r?\n/);
8450
- const tcStarts = [];
8451
- lines.forEach((line, index) => {
8452
- const match = /^#{2,3}\s+(TC-\d+[a-z]?)\s*[::]?\s*.*$/.exec(line);
8453
- if (match) {
8454
- tcStarts.push({ id: match[1], index });
8455
- }
8456
- });
10690
+ const tcStarts = extractE2eTestCaseStarts(lines);
10691
+ if (tcStarts.length > 0) {
10692
+ batchIds.add(batch);
10693
+ }
8457
10694
  const statusSummary = {};
8458
10695
  const blockingReasons = {};
8459
10696
  const frontmatterFixesBlock = String(data.fixes_block ?? "").trim();
@@ -8462,8 +10699,9 @@ async function generateE2eRegistry(root, opts) {
8462
10699
  blockingReasons[tc.id] = frontmatterFixesBlock;
8463
10700
  }
8464
10701
  }
8465
- for (const start of tcStarts) {
8466
- const end = tcStarts[tcStarts.indexOf(start) + 1]?.index ?? lines.length;
10702
+ for (let index = 0; index < tcStarts.length; index += 1) {
10703
+ const start = tcStarts[index];
10704
+ const end = tcStarts[index + 1]?.index ?? lines.length;
8467
10705
  const block = lines.slice(start.index, end);
8468
10706
  const fields = extractE2eTcFields(block);
8469
10707
  const status = String(fields["status"] ?? "created").trim().toLowerCase() || "created";
@@ -8496,7 +10734,7 @@ async function generateE2eRegistry(root, opts) {
8496
10734
  return {
8497
10735
  registry_version: "1.0",
8498
10736
  generated_at: opts?.deterministic ? "1970-01-01T00:00:00.000Z" : (/* @__PURE__ */ new Date()).toISOString(),
8499
- total_batches: batches.length,
10737
+ total_batches: batchIds.size,
8500
10738
  total_test_cases: totalTestCases,
8501
10739
  batches
8502
10740
  };
@@ -8565,10 +10803,10 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
8565
10803
  if (!normalizedPath) {
8566
10804
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8567
10805
  }
8568
- const fullPath = join8(root, normalizedPath);
10806
+ const fullPath = join11(root, normalizedPath);
8569
10807
  let content;
8570
10808
  try {
8571
- content = await readFile3(fullPath, "utf-8");
10809
+ content = await readFile4(fullPath, "utf-8");
8572
10810
  } catch {
8573
10811
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
8574
10812
  }
@@ -8602,7 +10840,7 @@ function detectTestLevel(specFile, content) {
8602
10840
  }
8603
10841
  function resolveExecutableRefFile(refFile, allFiles) {
8604
10842
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
8605
- if (!normalized || isAbsolute4(refFile) || normalized.split("/").includes("..")) {
10843
+ if (!normalized || isAbsolute6(refFile) || normalized.split("/").includes("..")) {
8606
10844
  return void 0;
8607
10845
  }
8608
10846
  if (allFiles.includes(normalized)) {
@@ -8675,17 +10913,6 @@ function splitMarkdownCells(line) {
8675
10913
  function escapeRegExp(value) {
8676
10914
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8677
10915
  }
8678
- async function hasMarkdownTc(tcKey, e2eDir) {
8679
- const [batch, tcId] = tcKey.split(":");
8680
- const filePath = join8(e2eDir, `${batch}.md`);
8681
- try {
8682
- const raw = await readFile3(filePath, "utf-8");
8683
- const tcRegex = new RegExp(`^#{2,3}\\s+${escapeRegExp(tcId)}\\s*[:\uFF1A]?`, "m");
8684
- return tcRegex.test(raw);
8685
- } catch {
8686
- return false;
8687
- }
8688
- }
8689
10916
  async function findFiles(root, patterns) {
8690
10917
  const all = await walkFiles(root);
8691
10918
  const matched = /* @__PURE__ */ new Set();
@@ -8698,6 +10925,10 @@ async function findFiles(root, patterns) {
8698
10925
  }
8699
10926
  return [...matched].sort();
8700
10927
  }
10928
+ async function findConfiguredE2eFiles(root, schema) {
10929
+ const patterns = schema.types.e2e_test?.paths ?? [];
10930
+ return findFiles(root, patterns);
10931
+ }
8701
10932
  function matchesConfiguredArtifactPath(path, schema) {
8702
10933
  const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
8703
10934
  return Object.values(schema.types).some((definition) => definition.paths.some((pattern) => matchesPattern(normalizedPath, pattern)));
@@ -8726,8 +10957,13 @@ function extractCodes(text, type, schema) {
8726
10957
  }
8727
10958
  function extractE2eTcFields(block) {
8728
10959
  const fields = {};
10960
+ const codeLines = markdownCodeLineMask2(block);
8729
10961
  let current = "";
8730
- for (const line of block) {
10962
+ for (let index = 0; index < block.length; index += 1) {
10963
+ if (codeLines[index]) {
10964
+ continue;
10965
+ }
10966
+ const line = block[index];
8731
10967
  const match = /^\*\*([^*]+?)\*\*\s*[::]\s*(.*)$/.exec(line);
8732
10968
  if (match) {
8733
10969
  current = match[1].trim();
@@ -8779,7 +11015,7 @@ function flattenAcCoverage(value) {
8779
11015
  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)}`) })));
8780
11016
  }
8781
11017
  function needsDesktopChainWarning(node) {
8782
- const tcFields = asRecord(node.attrs?.tcFields);
11018
+ const tcFields = asRecord2(node.attrs?.tcFields);
8783
11019
  const chainType = String(tcFields["chain_type"] ?? "").trim().toLowerCase();
8784
11020
  if (chainType && VALID_CHAIN_TYPES.has(chainType) && chainType !== "desktop_chain" || chainType in DEPRECATED_CHAIN_TYPE_ALIASES) {
8785
11021
  return false;
@@ -8836,7 +11072,7 @@ function compareRegistryAcCoverage(issues, registry, batch, actual) {
8836
11072
  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" }));
8837
11073
  return;
8838
11074
  }
8839
- if (normalizeAcCoverage(asRecord(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
11075
+ if (normalizeAcCoverage(asRecord2(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
8840
11076
  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" }));
8841
11077
  }
8842
11078
  }
@@ -8851,7 +11087,7 @@ function groupBy(values, key) {
8851
11087
  }
8852
11088
  return result;
8853
11089
  }
8854
- function asRecord(value) {
11090
+ function asRecord2(value) {
8855
11091
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
8856
11092
  }
8857
11093
  function isEmptyValue(value) {
@@ -8910,7 +11146,7 @@ function normalizeDesignCode(value) {
8910
11146
  if (!raw) {
8911
11147
  return "";
8912
11148
  }
8913
- return basename4(raw, extname(raw));
11149
+ return basename5(raw, extname(raw));
8914
11150
  }
8915
11151
  function toUid(type, code) {
8916
11152
  return `${type}:${code}`;
@@ -9186,14 +11422,14 @@ function resolveArtifactContext(graph, opts) {
9186
11422
  }
9187
11423
  if (root) {
9188
11424
  for (const ap of ALWAYS_PRESENT_ITEMS) {
9189
- const fullPath = join8(root, ap.path);
9190
- let stat2;
11425
+ const fullPath = join11(root, ap.path);
11426
+ let stat3;
9191
11427
  try {
9192
- stat2 = statSync(fullPath);
11428
+ stat3 = statSync(fullPath);
9193
11429
  } catch {
9194
- stat2 = null;
11430
+ stat3 = null;
9195
11431
  }
9196
- if (!stat2) {
11432
+ if (!stat3) {
9197
11433
  const msg = `Required baseline artifact not found: ${ap.path}`;
9198
11434
  if (!missing.includes(msg)) {
9199
11435
  missing.push(msg);
@@ -9205,7 +11441,7 @@ function resolveArtifactContext(graph, opts) {
9205
11441
  suggestedAction: `\u521B\u5EFA\u6587\u4EF6 ${ap.path} \u6216\u914D\u7F6E\u8DF3\u8FC7 universal baseline`
9206
11442
  });
9207
11443
  }
9208
- } else if (!stat2.isFile()) {
11444
+ } else if (!stat3.isFile()) {
9209
11445
  const msg = `Required baseline artifact is not a regular file: ${ap.path}`;
9210
11446
  if (!missing.includes(msg)) {
9211
11447
  missing.push(msg);
@@ -9428,7 +11664,7 @@ function formatContextMarkdown(manifest) {
9428
11664
  }
9429
11665
  return lines.join("\n");
9430
11666
  }
9431
- 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;
11667
+ 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;
9432
11668
  var init_index = __esm({
9433
11669
  "src/index.ts"() {
9434
11670
  "use strict";
@@ -9450,8 +11686,12 @@ var init_index = __esm({
9450
11686
  init_git_changes();
9451
11687
  init_git_hook_path();
9452
11688
  init_hook_installer();
11689
+ init_professional_conclusion();
9453
11690
  init_review_result_validator();
9454
11691
  init_contract_kernel();
11692
+ init_restructure();
11693
+ init_restructure_file_set();
11694
+ init_restructure_software();
9455
11695
  TARGET_ARTIFACT_TYPES = VALID_PACKET_TARGET_TYPES;
9456
11696
  NON_TARGET_ROLES = ["context", "candidate", "not-recommended"];
9457
11697
  DEFAULT_SCHEMA = {
@@ -9499,6 +11739,33 @@ var init_index = __esm({
9499
11739
  runners: []
9500
11740
  }
9501
11741
  };
11742
+ SPECIALIZED_PARSER_TYPES = /* @__PURE__ */ new Set([
11743
+ "feature",
11744
+ "scenario",
11745
+ "entity",
11746
+ "decision",
11747
+ "test",
11748
+ "design",
11749
+ "e2e_test",
11750
+ "e2e_registry",
11751
+ "rule-golden-cases",
11752
+ "test-strategy",
11753
+ "traceability-matrix-v2",
11754
+ "traceability-version-lock",
11755
+ "interface_contracts",
11756
+ "data_contracts",
11757
+ "application_state_machines",
11758
+ "error_model",
11759
+ "domain-glossary",
11760
+ "bounded-context-map",
11761
+ "domain-invariants",
11762
+ "generation-packet-spec",
11763
+ "report-contracts",
11764
+ "verification-fixtures",
11765
+ "ui-flow-contracts",
11766
+ "non-functional-budgets",
11767
+ "implementation-blueprint"
11768
+ ]);
9502
11769
  EMPTY_RELATION_FIELD_VALUES = /* @__PURE__ */ new Set(["\u65E0", "none", "n/a", "-"]);
9503
11770
  VALID_TC_STATUSES = /* @__PURE__ */ new Set(["created", "automated", "verified", "waived"]);
9504
11771
  VALID_CHAIN_TYPES = /* @__PURE__ */ new Set([
@@ -9542,8 +11809,8 @@ var init_index = __esm({
9542
11809
  });
9543
11810
 
9544
11811
  // src/packet-prompt-audit.ts
9545
- import { mkdir as mkdir5, writeFile as writeFile4 } from "fs/promises";
9546
- import { join as join9 } from "path";
11812
+ import { mkdir as mkdir6, writeFile as writeFile4 } from "fs/promises";
11813
+ import { join as join12 } from "path";
9547
11814
  function promptFilename(target) {
9548
11815
  return `prompt-${target.type}-${target.id}.md`;
9549
11816
  }
@@ -9595,7 +11862,7 @@ async function auditSinglePromptTarget(target, graph, options) {
9595
11862
  }
9596
11863
  if (options.outDir) {
9597
11864
  const filename = promptFilename(target);
9598
- const outPath = join9(options.outDir, filename);
11865
+ const outPath = join12(options.outDir, filename);
9599
11866
  await writeFile4(outPath, prompt, "utf-8");
9600
11867
  entry.outputPath = outPath;
9601
11868
  }
@@ -9671,7 +11938,7 @@ function computeCountsByType(entries) {
9671
11938
  async function auditPromptBatch(root, targets, options, graph) {
9672
11939
  const resolvedGraph = graph ?? await scanArtifacts(root);
9673
11940
  if (options.outDir) {
9674
- await mkdir5(options.outDir, { recursive: true });
11941
+ await mkdir6(options.outDir, { recursive: true });
9675
11942
  }
9676
11943
  const entries = [];
9677
11944
  for (const target of targets) {
@@ -9700,10 +11967,10 @@ async function auditPromptBatch(root, targets, options, graph) {
9700
11967
  targets: summaryTargets
9701
11968
  };
9702
11969
  if (options.outDir) {
9703
- await mkdir5(options.outDir, { recursive: true });
9704
- const jsonPath = join9(options.outDir, "prompt-audit-summary.json");
11970
+ await mkdir6(options.outDir, { recursive: true });
11971
+ const jsonPath = join12(options.outDir, "prompt-audit-summary.json");
9705
11972
  await writeFile4(jsonPath, JSON.stringify(summary, null, 2) + "\n", "utf-8");
9706
- const mdPath = join9(options.outDir, "prompt-audit-summary.md");
11973
+ const mdPath = join12(options.outDir, "prompt-audit-summary.md");
9707
11974
  await writeFile4(mdPath, renderPromptAuditSummaryMarkdown(summary), "utf-8");
9708
11975
  }
9709
11976
  return summary;
@@ -9743,9 +12010,9 @@ __export(refactor_id_exports, {
9743
12010
  refactorId: () => refactorId,
9744
12011
  renderRefactorIdMarkdown: () => renderRefactorIdMarkdown
9745
12012
  });
9746
- import { chmod, readFile as readFile4, rename as rename2, rm, readdir as readdir4, stat, writeFile as writeFile5 } from "fs/promises";
12013
+ import { chmod as chmod2, readFile as readFile5, rename as rename2, rm, readdir as readdir4, stat as stat2, writeFile as writeFile5 } from "fs/promises";
9747
12014
  import { randomBytes } from "crypto";
9748
- import { basename as basename5, dirname as dirname6, join as join10, relative as relative5 } from "path";
12015
+ import { basename as basename6, dirname as dirname8, join as join13, relative as relative5 } from "path";
9749
12016
  import yaml2 from "js-yaml";
9750
12017
  function escapeRegExp2(value) {
9751
12018
  return value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
@@ -9923,12 +12190,12 @@ async function walkTextFiles(root) {
9923
12190
  for (const entry of entries) {
9924
12191
  if (entry.name.startsWith(".") && PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
9925
12192
  if (PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
9926
- const full = join10(dir, entry.name);
12193
+ const full = join13(dir, entry.name);
9927
12194
  if (entry.isDirectory()) {
9928
12195
  await visit(full);
9929
12196
  } else if (entry.isFile()) {
9930
12197
  const ext = entry.name.includes(".") ? `.${entry.name.split(".").slice(-1)[0]}` : "";
9931
- if (TEXT_EXTENSIONS.has(ext.toLowerCase())) {
12198
+ if (TEXT_EXTENSIONS2.has(ext.toLowerCase())) {
9932
12199
  found.push(relative5(root, full).replace(/\\/g, "/"));
9933
12200
  }
9934
12201
  }
@@ -9938,7 +12205,7 @@ async function walkTextFiles(root) {
9938
12205
  return found.sort();
9939
12206
  }
9940
12207
  async function computeLockImpact(root, type, oldId) {
9941
- const lockPath = join10(root, VERSION_LOCK_PATH);
12208
+ const lockPath = join13(root, VERSION_LOCK_PATH);
9942
12209
  const impact = {
9943
12210
  lockPath: VERSION_LOCK_PATH,
9944
12211
  affectedImplementationLocks: [],
@@ -9947,7 +12214,7 @@ async function computeLockImpact(root, type, oldId) {
9947
12214
  };
9948
12215
  let raw;
9949
12216
  try {
9950
- raw = await readFile4(lockPath, "utf-8");
12217
+ raw = await readFile5(lockPath, "utf-8");
9951
12218
  } catch {
9952
12219
  return impact;
9953
12220
  }
@@ -10030,7 +12297,7 @@ async function refactorId(options) {
10030
12297
  const fileContents = /* @__PURE__ */ new Map();
10031
12298
  const readArtifactFile = async (path) => {
10032
12299
  if (!fileContents.has(path)) {
10033
- fileContents.set(path, await readFile4(join10(root, path), "utf-8"));
12300
+ fileContents.set(path, await readFile5(join13(root, path), "utf-8"));
10034
12301
  }
10035
12302
  return fileContents.get(path);
10036
12303
  };
@@ -10106,7 +12373,7 @@ async function refactorId(options) {
10106
12373
  for (const relativePath of await walkTextFiles(root)) {
10107
12374
  if (relativePath === VERSION_LOCK_PATH) continue;
10108
12375
  if (relativePath === "artifact-graph.config.yaml") continue;
10109
- const raw = await readFile4(join10(root, relativePath), "utf-8");
12376
+ const raw = await readFile5(join13(root, relativePath), "utf-8");
10110
12377
  if (!containsIdToken(raw, oldId)) continue;
10111
12378
  const lines = raw.split(/\r?\n/);
10112
12379
  lines.forEach((line, index) => {
@@ -10182,7 +12449,7 @@ async function refactorId(options) {
10182
12449
  }
10183
12450
  if (options.__beforeWriteVerify) await options.__beforeWriteVerify();
10184
12451
  for (const path of targetFiles) {
10185
- const disk = await readFile4(join10(root, path), "utf-8");
12452
+ const disk = await readFile5(join13(root, path), "utf-8");
10186
12453
  if (disk !== fileContents.get(path)) {
10187
12454
  return fail("PLAN_DRIFT", `\u8BA1\u5212\u4E0E\u5199\u5165\u4E4B\u95F4\u76EE\u6807\u6587\u4EF6\u53D1\u751F\u53D8\u5316\uFF08apply \u4E2D\u6B62\uFF0C\u96F6\u5199\u5165\uFF09\uFF1A${path}`, { path });
10188
12455
  }
@@ -10193,7 +12460,7 @@ async function refactorId(options) {
10193
12460
  const tempPathFor = options.__tempPathFor ?? ((targetPath) => {
10194
12461
  tempSequence += 1;
10195
12462
  const suffix = randomBytes(4).toString("hex");
10196
- return join10(dirname6(targetPath), `.${basename5(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
12463
+ return join13(dirname8(targetPath), `.${basename6(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
10197
12464
  });
10198
12465
  let stage = "write";
10199
12466
  try {
@@ -10202,13 +12469,13 @@ async function refactorId(options) {
10202
12469
  if (options.__injectWriteFailure?.(path)) {
10203
12470
  throw Object.assign(new Error(`injected write failure: ${path}`), { code: "EINJECTED" });
10204
12471
  }
10205
- const original = fileContents.has(path) ? fileContents.get(path) : await readFile4(join10(root, path), "utf-8");
10206
- const targetPath = join10(root, path);
10207
- const originalMode = (await stat(targetPath)).mode & 4095;
12472
+ const original = fileContents.has(path) ? fileContents.get(path) : await readFile5(join13(root, path), "utf-8");
12473
+ const targetPath = join13(root, path);
12474
+ const originalMode = (await stat2(targetPath)).mode & 4095;
10208
12475
  const tempPath = tempPathFor(targetPath);
10209
12476
  await writeFile5(tempPath, newContents.get(path), { encoding: "utf-8", flag: "wx" });
10210
12477
  createdTempPaths.push(tempPath);
10211
- await chmod(tempPath, originalMode);
12478
+ await chmod2(tempPath, originalMode);
10212
12479
  stage = "rename";
10213
12480
  if (options.__injectRenameFailure?.(tempPath, targetPath)) {
10214
12481
  throw Object.assign(new Error(`injected rename failure: ${tempPath} -> ${targetPath}`), { code: "ERENAMEINJECTED" });
@@ -10226,21 +12493,21 @@ async function refactorId(options) {
10226
12493
  if (options.__injectRollbackFailure?.(entry.path)) {
10227
12494
  throw Object.assign(new Error(`injected rollback failure: ${entry.path}`), { code: "EROLLBACKINJECTED" });
10228
12495
  }
10229
- await writeFile5(join10(root, entry.path), entry.original, "utf-8");
10230
- await chmod(join10(root, entry.path), entry.originalMode);
12496
+ await writeFile5(join13(root, entry.path), entry.original, "utf-8");
12497
+ await chmod2(join13(root, entry.path), entry.originalMode);
10231
12498
  } catch (rollbackError) {
10232
12499
  rollbackErrors.push({ path: entry.path, message: rollbackError.message });
10233
12500
  }
10234
12501
  }
10235
- const failure = error;
10236
- const writeCode = failure.code === "EEXIST" ? "TEMP_FILE_COLLISION" : stage === "rename" || failure.code === "ERENAMEINJECTED" ? "RENAME_FAILED" : "WRITE_FAILED";
12502
+ const failure2 = error;
12503
+ const writeCode = failure2.code === "EEXIST" ? "TEMP_FILE_COLLISION" : stage === "rename" || failure2.code === "ERENAMEINJECTED" ? "RENAME_FAILED" : "WRITE_FAILED";
10237
12504
  if (rollbackErrors.length > 0) {
10238
12505
  return {
10239
12506
  ok: false,
10240
12507
  error: {
10241
12508
  code: "ROLLBACK_FAILED",
10242
- message: `apply \u5199\u5165\u5931\u8D25\uFF08${writeCode}\uFF09\u4E14\u56DE\u6EDA\u672A\u5B8C\u5168\u6210\u529F\uFF0C\u9700\u4EBA\u5DE5\u590D\u6838\uFF1A${failure.message}`,
10243
- details: { writeError: { code: writeCode, message: failure.message }, rollbackErrors }
12509
+ message: `apply \u5199\u5165\u5931\u8D25\uFF08${writeCode}\uFF09\u4E14\u56DE\u6EDA\u672A\u5B8C\u5168\u6210\u529F\uFF0C\u9700\u4EBA\u5DE5\u590D\u6838\uFF1A${failure2.message}`,
12510
+ details: { writeError: { code: writeCode, message: failure2.message }, rollbackErrors }
10244
12511
  }
10245
12512
  };
10246
12513
  }
@@ -10248,7 +12515,7 @@ async function refactorId(options) {
10248
12515
  ok: false,
10249
12516
  error: {
10250
12517
  code: writeCode,
10251
- message: `apply \u5199\u5165\u5931\u8D25\u5E76\u5DF2\u56DE\u6EDA\uFF1A${failure.message}`,
12518
+ message: `apply \u5199\u5165\u5931\u8D25\u5E76\u5DF2\u56DE\u6EDA\uFF1A${failure2.message}`,
10252
12519
  details: { stage }
10253
12520
  }
10254
12521
  };
@@ -10343,12 +12610,12 @@ function renderRefactorIdMarkdown(result) {
10343
12610
  lines.push("");
10344
12611
  return lines.join("\n");
10345
12612
  }
10346
- var TEXT_EXTENSIONS, PROSE_SCAN_SKIP_DIRS;
12613
+ var TEXT_EXTENSIONS2, PROSE_SCAN_SKIP_DIRS;
10347
12614
  var init_refactor_id = __esm({
10348
12615
  "src/refactor-id.ts"() {
10349
12616
  "use strict";
10350
12617
  init_index();
10351
- TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".ts", ".tsx", ".mts", ".mjs", ".js", ".yaml", ".yml", ".json"]);
12618
+ TEXT_EXTENSIONS2 = /* @__PURE__ */ new Set([".md", ".markdown", ".ts", ".tsx", ".mts", ".mjs", ".js", ".yaml", ".yml", ".json"]);
10352
12619
  PROSE_SCAN_SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".qoder", ".agents"]);
10353
12620
  }
10354
12621
  });
@@ -10360,9 +12627,9 @@ __export(cli_exports, {
10360
12627
  });
10361
12628
  import yaml3 from "js-yaml";
10362
12629
  import { realpathSync as realpathSync2 } from "fs";
10363
- import { access as access2, mkdir as mkdir6, readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
10364
- import { dirname as dirname7, isAbsolute as isAbsolute5, join as join11 } from "path";
10365
- import { fileURLToPath as fileURLToPath2 } from "url";
12630
+ import { access as access3, mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
12631
+ import { dirname as dirname9, isAbsolute as isAbsolute7, join as join14 } from "path";
12632
+ import { fileURLToPath as fileURLToPath3 } from "url";
10366
12633
  async function runCli(argv, io = {}) {
10367
12634
  const parsed = parseArgs(argv);
10368
12635
  const cwd = io.cwd ?? process.cwd();
@@ -10389,7 +12656,7 @@ async function runCli(argv, io = {}) {
10389
12656
  switch (parsed.command) {
10390
12657
  case "init": {
10391
12658
  await initConfig(root);
10392
- out(`Created ${join11(root, "artifact-graph.config.yaml")}
12659
+ out(`Created ${join14(root, "artifact-graph.config.yaml")}
10393
12660
  `);
10394
12661
  return 0;
10395
12662
  }
@@ -10402,6 +12669,53 @@ async function runCli(argv, io = {}) {
10402
12669
  `);
10403
12670
  return 0;
10404
12671
  }
12672
+ case "check-professional": {
12673
+ const format = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
12674
+ if (format !== "json") {
12675
+ err(`Invalid --format: "${String(parsed.flags.format)}". Allowed values: json
12676
+ `);
12677
+ return 2;
12678
+ }
12679
+ const conclusionOutput = parsed.flags["conclusion-output"];
12680
+ if (conclusionOutput === true || conclusionOutput !== void 0 && typeof conclusionOutput !== "string") {
12681
+ err("Usage: artifact-graph check-professional --root <target> --format json [--conclusion-output <absolute-path>]\n");
12682
+ return 1;
12683
+ }
12684
+ if (typeof conclusionOutput === "string" && !isAbsolute7(conclusionOutput)) {
12685
+ err("--conclusion-output must be an absolute path\n");
12686
+ return 1;
12687
+ }
12688
+ const { conclusion, writeError } = await runCheckProfessional({
12689
+ root,
12690
+ conclusionOutput: typeof conclusionOutput === "string" ? conclusionOutput : void 0
12691
+ });
12692
+ out(`${JSON.stringify(conclusion, null, 2)}
12693
+ `);
12694
+ if (writeError) {
12695
+ err(`${writeError}
12696
+ `);
12697
+ return 1;
12698
+ }
12699
+ return 0;
12700
+ }
12701
+ case "read-proof": {
12702
+ const format = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
12703
+ if (format !== "json") {
12704
+ err(`Invalid --format: "${String(parsed.flags.format)}". Allowed values: json
12705
+ `);
12706
+ return 2;
12707
+ }
12708
+ const proofRoot = parsed.flags["proof-root"];
12709
+ const proof = parsed.flags.proof;
12710
+ if (typeof proofRoot !== "string" || typeof proof !== "string") {
12711
+ err("Usage: artifact-graph read-proof --proof-root <root> --proof <relative> --format json\n");
12712
+ return 1;
12713
+ }
12714
+ const { result, exitCode } = await runReadProof({ proofRoot, proof });
12715
+ out(`${JSON.stringify(result, null, 2)}
12716
+ `);
12717
+ return exitCode;
12718
+ }
10405
12719
  case "validate": {
10406
12720
  const includes = new Set(
10407
12721
  typeof parsed.flags.include === "string" ? parsed.flags.include.split(",") : []
@@ -10780,7 +13094,7 @@ async function runCli(argv, io = {}) {
10780
13094
  if (packetJsonPath) {
10781
13095
  let rawJson;
10782
13096
  try {
10783
- rawJson = await readFile5(packetJsonPath, "utf-8");
13097
+ rawJson = await readFile6(packetJsonPath, "utf-8");
10784
13098
  } catch (readErr) {
10785
13099
  err(`\u9519\u8BEF\uFF1A\u65E0\u6CD5\u8BFB\u53D6 packet \u6587\u4EF6: "${packetJsonPath}" \u2014 ${readErr.message}
10786
13100
  `);
@@ -10981,7 +13295,7 @@ async function runCli(argv, io = {}) {
10981
13295
  universalBaseline: discoverConfig.context?.universal_baseline
10982
13296
  });
10983
13297
  } else {
10984
- const targetsContent = await readFile5(targetsFile, "utf-8");
13298
+ const targetsContent = await readFile6(targetsFile, "utf-8");
10985
13299
  const auditConfig2 = await loadConfig(root);
10986
13300
  const parseResult = parseTargetsFile(targetsContent, auditConfig2);
10987
13301
  if (parseResult.errors.length > 0) {
@@ -11106,7 +13420,7 @@ async function runCli(argv, io = {}) {
11106
13420
  } else {
11107
13421
  let ppaTargetsContent;
11108
13422
  try {
11109
- ppaTargetsContent = await readFile5(ppaTargetsFile, "utf-8");
13423
+ ppaTargetsContent = await readFile6(ppaTargetsFile, "utf-8");
11110
13424
  } catch (readErr) {
11111
13425
  err(`\u9519\u8BEF\uFF1A\u65E0\u6CD5\u8BFB\u53D6 targets \u6587\u4EF6: "${ppaTargetsFile}" \u2014 ${readErr.message}
11112
13426
  `);
@@ -11249,18 +13563,27 @@ async function runCli(argv, io = {}) {
11249
13563
  }
11250
13564
  const refreshAll = parsed.flags.all === true;
11251
13565
  const refreshChangedOnly = parsed.flags["changed-only"] === true;
13566
+ const removeOrphanEdges = parsed.multiFlags["remove-orphan-edge"] ?? [];
11252
13567
  if (!refreshAll && !refreshChangedOnly) {
11253
- err("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
13568
+ err("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11254
13569
  return 1;
11255
13570
  }
11256
13571
  if (parsed.flags.help === true) {
11257
- out("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
13572
+ out("Usage: artifact-graph version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11258
13573
  return 0;
11259
13574
  }
11260
13575
  if (refreshAll && refreshChangedOnly) {
11261
13576
  err("Error: --all and --changed-only are mutually exclusive\n");
11262
13577
  return 1;
11263
13578
  }
13579
+ if (parsed.flags["remove-orphan-edge"] === true) {
13580
+ err("Error: --remove-orphan-edge requires an edgeId\n");
13581
+ return 1;
13582
+ }
13583
+ if (parsed.flags["remove-orphans"] === true && removeOrphanEdges.length > 0) {
13584
+ err("Error: --remove-orphans and --remove-orphan-edge are mutually exclusive\n");
13585
+ return 1;
13586
+ }
11264
13587
  let changedPaths = [];
11265
13588
  if (refreshChangedOnly) {
11266
13589
  const changeModeFlags = [
@@ -11269,7 +13592,7 @@ async function runCli(argv, io = {}) {
11269
13592
  typeof parsed.flags.base === "string" ? "base" : null
11270
13593
  ].filter(Boolean);
11271
13594
  if (changeModeFlags.length !== 1) {
11272
- err("Usage: artifact-graph version-lock refresh --changed-only (--staged | --worktree | --base <ref>) [--remove-orphans] [--format json|markdown] [--lock-path <path>]\n");
13595
+ err("Usage: artifact-graph version-lock refresh --changed-only (--staged | --worktree | --base <ref>) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]\n");
11273
13596
  return 1;
11274
13597
  }
11275
13598
  const changeResult = await collectChangedPaths(root, {
@@ -11303,7 +13626,8 @@ async function runCli(argv, io = {}) {
11303
13626
  changedOnly: refreshChangedOnly,
11304
13627
  changedPaths,
11305
13628
  all: refreshAll,
11306
- removeOrphans: parsed.flags["remove-orphans"] === true
13629
+ removeOrphans: parsed.flags["remove-orphans"] === true,
13630
+ removeOrphanEdges
11307
13631
  });
11308
13632
  if (refreshFormat === "json") {
11309
13633
  out(`${JSON.stringify(result, null, 2)}
@@ -11353,8 +13677,8 @@ async function runCli(argv, io = {}) {
11353
13677
  const hooks = hookFlag === "all" ? ["pre-commit", "pre-push"] : [hookFlag];
11354
13678
  const prepared = [];
11355
13679
  for (const hookName of hooks) {
11356
- const templatePath = fileURLToPath2(new URL(`../templates/git-hooks/${hookName}.sh`, import.meta.url));
11357
- const block = await readFile5(templatePath, "utf-8");
13680
+ const templatePath = fileURLToPath3(new URL(`../templates/git-hooks/${hookName}.sh`, import.meta.url));
13681
+ const block = await readFile6(templatePath, "utf-8");
11358
13682
  prepared.push(await prepareManagedHookBlock({
11359
13683
  hookPath: await resolveGitHookPath(root, hookName),
11360
13684
  block,
@@ -11398,10 +13722,10 @@ async function runCli(argv, io = {}) {
11398
13722
  err("Usage: artifact-graph validate-review-result --file <path> [--format json]\n");
11399
13723
  return 1;
11400
13724
  }
11401
- const resolvedPath = isAbsolute5(filePath) ? filePath : join11(root, filePath);
13725
+ const resolvedPath = isAbsolute7(filePath) ? filePath : join14(root, filePath);
11402
13726
  let content;
11403
13727
  try {
11404
- content = await readFile5(resolvedPath, "utf-8");
13728
+ content = await readFile6(resolvedPath, "utf-8");
11405
13729
  } catch (readErr) {
11406
13730
  err(`Error: Cannot read file: "${resolvedPath}" \u2014 ${readErr.message}
11407
13731
  `);
@@ -11436,11 +13760,11 @@ async function runCli(argv, io = {}) {
11436
13760
  const deterministic = checkMode || parsed.flags.deterministic === true;
11437
13761
  const registry = await generateE2eRegistry(root, { deterministic });
11438
13762
  const output = JSON.stringify(registry, null, 2) + "\n";
11439
- const outPath = typeof parsed.flags.out === "string" ? parsed.flags.out : join11(root, "artifacts/tests/e2e/e2e-test-registry.json");
13763
+ const outPath = typeof parsed.flags.out === "string" ? parsed.flags.out : join14(root, "artifacts/tests/e2e/e2e-test-registry.json");
11440
13764
  if (checkMode) {
11441
13765
  let existing = "";
11442
13766
  try {
11443
- existing = await readFile5(outPath, "utf-8");
13767
+ existing = await readFile6(outPath, "utf-8");
11444
13768
  } catch {
11445
13769
  err(`Check failed: ${outPath} does not exist or is not readable
11446
13770
  `);
@@ -11464,6 +13788,117 @@ async function runCli(argv, io = {}) {
11464
13788
  }
11465
13789
  return 0;
11466
13790
  }
13791
+ case "restructure": {
13792
+ const action = parsed.positional[0];
13793
+ const format = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
13794
+ const {
13795
+ applyRestructure: applyRestructure2,
13796
+ gateRestructureOperationPlan: gateRestructureOperationPlan2,
13797
+ inspectRestructure: inspectRestructure2,
13798
+ planRestructure: planRestructure2,
13799
+ pruneRestructureRecovery: pruneRestructureRecovery2,
13800
+ recoverRestructure: recoverRestructure2
13801
+ } = await Promise.resolve().then(() => (init_restructure(), restructure_exports));
13802
+ if (format !== "json") {
13803
+ out(`${JSON.stringify({ ok: false, error: { code: "INVALID_FORMAT", message: `Invalid --format: "${format}". Allowed values: json` } }, null, 2)}
13804
+ `);
13805
+ return 1;
13806
+ }
13807
+ const mechanismOperation = action === "apply" || action === "recover" || action === "prune-recovery" ? action : void 0;
13808
+ if (mechanismOperation) {
13809
+ const planFlag = typeof parsed.flags.plan === "string" ? parsed.flags.plan : void 0;
13810
+ if (!planFlag) {
13811
+ out(`${JSON.stringify({ ok: false, error: { code: "PLAN_REQUIRED", message: `restructure ${mechanismOperation} requires --plan <plan.json>` } }, null, 2)}
13812
+ `);
13813
+ return 1;
13814
+ }
13815
+ const planPath = isAbsolute7(planFlag) ? planFlag : join14(cwd, planFlag);
13816
+ let planDocument;
13817
+ try {
13818
+ planDocument = JSON.parse(await readFile6(planPath, "utf8"));
13819
+ } catch (planError) {
13820
+ out(`${JSON.stringify({ ok: false, error: { code: "PLAN_UNREADABLE", message: `Cannot read a plan document from ${planPath}: ${planError.message}` } }, null, 2)}
13821
+ `);
13822
+ return 1;
13823
+ }
13824
+ const gate = await gateRestructureOperationPlan2(mechanismOperation, planDocument);
13825
+ if (!gate.ok) {
13826
+ out(`${JSON.stringify(gate, null, 2)}
13827
+ `);
13828
+ return 1;
13829
+ }
13830
+ const confirmCooperativeWriters = parsed.flags["confirm-cooperative-writers"] === true;
13831
+ const confirmAllParticipantsStopped = parsed.flags["confirm-all-participants-stopped"] === true;
13832
+ const confirmExclusiveMaintenance = parsed.flags["confirm-exclusive-maintenance"] === true;
13833
+ if (mechanismOperation === "apply" && !confirmCooperativeWriters) {
13834
+ out(`${JSON.stringify({ ok: false, error: { code: "COOPERATIVE_WRITERS_UNCONFIRMED", message: "restructure apply requires --confirm-cooperative-writers" } }, null, 2)}
13835
+ `);
13836
+ return 1;
13837
+ }
13838
+ if (mechanismOperation === "recover" && !(confirmAllParticipantsStopped && confirmExclusiveMaintenance)) {
13839
+ out(`${JSON.stringify({ ok: false, error: { code: "MAINTENANCE_CONFIRMATION_REQUIRED", message: "restructure recover requires both --confirm-all-participants-stopped and --confirm-exclusive-maintenance" } }, null, 2)}
13840
+ `);
13841
+ return 1;
13842
+ }
13843
+ if (mechanismOperation === "prune-recovery") {
13844
+ if (!confirmCooperativeWriters) {
13845
+ out(`${JSON.stringify({ ok: false, error: { code: "COOPERATIVE_WRITERS_UNCONFIRMED", message: "restructure prune-recovery requires --confirm-cooperative-writers" } }, null, 2)}
13846
+ `);
13847
+ return 1;
13848
+ }
13849
+ if (confirmAllParticipantsStopped !== confirmExclusiveMaintenance) {
13850
+ out(`${JSON.stringify({ ok: false, error: { code: "MAINTENANCE_CONFIRMATION_REQUIRED", message: "A fault takeover needs --confirm-all-participants-stopped and --confirm-exclusive-maintenance together; neither is accepted alone" } }, null, 2)}
13851
+ `);
13852
+ return 1;
13853
+ }
13854
+ }
13855
+ const result2 = mechanismOperation === "apply" ? await applyRestructure2({ root, planPath, confirmCooperativeWriters }) : mechanismOperation === "recover" ? await recoverRestructure2({
13856
+ root,
13857
+ planPath,
13858
+ allParticipantsStopped: confirmAllParticipantsStopped,
13859
+ exclusiveMaintenance: confirmExclusiveMaintenance
13860
+ }) : await pruneRestructureRecovery2({
13861
+ root,
13862
+ planPath,
13863
+ confirmCooperativeWriters,
13864
+ allParticipantsStopped: confirmAllParticipantsStopped,
13865
+ exclusiveMaintenance: confirmExclusiveMaintenance
13866
+ });
13867
+ out(`${JSON.stringify(result2, null, 2)}
13868
+ `);
13869
+ return result2.ok ? 0 : 1;
13870
+ }
13871
+ if (action !== "inspect" && action !== "plan") {
13872
+ out(`${JSON.stringify({ ok: false, error: { code: "INVALID_COMMAND", message: "Usage: artifact-graph restructure inspect|plan --root <project> --input <file> --format json; restructure apply|recover|prune-recovery --root <project> --plan <plan.json> [--format json]" } }, null, 2)}
13873
+ `);
13874
+ return 1;
13875
+ }
13876
+ const inputPath = typeof parsed.flags.input === "string" ? parsed.flags.input : void 0;
13877
+ if (!inputPath) {
13878
+ out(`${JSON.stringify({ ok: false, error: { code: "INPUT_REQUIRED", message: "--input is required" } }, null, 2)}
13879
+ `);
13880
+ return 1;
13881
+ }
13882
+ const resolvedInput = isAbsolute7(inputPath) ? inputPath : join14(cwd, inputPath);
13883
+ let input;
13884
+ try {
13885
+ input = JSON.parse(await readFile6(resolvedInput, "utf8"));
13886
+ } catch (inputError) {
13887
+ out(`${JSON.stringify({ ok: false, error: { code: "INPUT_INVALID", message: `Cannot read valid JSON from ${inputPath}: ${inputError.message}` } }, null, 2)}
13888
+ `);
13889
+ return 1;
13890
+ }
13891
+ if (action === "inspect") {
13892
+ const result2 = await inspectRestructure2(root, input);
13893
+ out(`${JSON.stringify(result2, null, 2)}
13894
+ `);
13895
+ return result2.ok ? 0 : 1;
13896
+ }
13897
+ const result = await planRestructure2(root, input);
13898
+ out(`${JSON.stringify(result, null, 2)}
13899
+ `);
13900
+ return result.ok && result.data.applicable ? 0 : 1;
13901
+ }
11467
13902
  case "contract": {
11468
13903
  const contractAction = parsed.positional[0];
11469
13904
  const contractFormat = typeof parsed.flags.format === "string" ? parsed.flags.format : "json";
@@ -11472,8 +13907,8 @@ async function runCli(argv, io = {}) {
11472
13907
  `);
11473
13908
  return 1;
11474
13909
  }
11475
- const packageDir = dirname7(fileURLToPath2(import.meta.url));
11476
- const contractsDir = typeof parsed.flags["contracts-dir"] === "string" ? parsed.flags["contracts-dir"] : join11(packageDir, "..", "contracts");
13910
+ const packageDir = dirname9(fileURLToPath3(import.meta.url));
13911
+ const contractsDir = typeof parsed.flags["contracts-dir"] === "string" ? parsed.flags["contracts-dir"] : join14(packageDir, "..", "contracts");
11477
13912
  const revisionDigest = typeof parsed.flags["revision-digest"] === "string" ? parsed.flags["revision-digest"] : void 0;
11478
13913
  async function resolveContract(contractId) {
11479
13914
  const catalog = await loadContractCatalog(contractsDir);
@@ -11687,7 +14122,7 @@ async function runCli(argv, io = {}) {
11687
14122
  }
11688
14123
  let markdownContent;
11689
14124
  try {
11690
- markdownContent = await readFile5(markdownPath, "utf-8");
14125
+ markdownContent = await readFile6(markdownPath, "utf-8");
11691
14126
  } catch {
11692
14127
  out(`${JSON.stringify({ ok: false, error: { code: "SCHEMA_VALIDATION_FAILED", path: "/markdown", message: `Could not read markdown file "${markdownPath}"` } }, null, 2)}
11693
14128
  `);
@@ -11786,21 +14221,22 @@ function isGraphRelevantPath(path, schema) {
11786
14221
  return path === "artifact-graph.config.yaml" || path === VERSION_LOCK_PATH || matchesConfiguredArtifactPath(path, schema);
11787
14222
  }
11788
14223
  async function initConfig(root) {
11789
- const configPath = join11(root, "artifact-graph.config.yaml");
14224
+ const configPath = join14(root, "artifact-graph.config.yaml");
11790
14225
  try {
11791
- await access2(configPath);
14226
+ await access3(configPath);
11792
14227
  throw new Error(`Config already exists: ${configPath}`);
11793
14228
  } catch (error) {
11794
14229
  if (error.code !== "ENOENT") {
11795
14230
  throw error;
11796
14231
  }
11797
14232
  }
11798
- await mkdir6(root, { recursive: true });
14233
+ await mkdir7(root, { recursive: true });
11799
14234
  await writeFile6(configPath, yaml3.dump(DEFAULT_SCHEMA, { lineWidth: 120 }));
11800
14235
  }
11801
14236
  function parseArgs(argv) {
11802
14237
  const [command, ...rest] = argv;
11803
14238
  const flags = {};
14239
+ const multiFlags = {};
11804
14240
  const positional = [];
11805
14241
  for (let index = 0; index < rest.length; index += 1) {
11806
14242
  const token = rest[index];
@@ -11810,6 +14246,9 @@ function parseArgs(argv) {
11810
14246
  const nextLooksLikeFlag = next && next.startsWith("-") && next.length > 1 && !/\d/.test(next[1]);
11811
14247
  if (next && !nextLooksLikeFlag) {
11812
14248
  flags[key] = next;
14249
+ const values = multiFlags[key] ?? [];
14250
+ values.push(next);
14251
+ multiFlags[key] = values;
11813
14252
  index += 1;
11814
14253
  } else {
11815
14254
  flags[key] = true;
@@ -11823,7 +14262,7 @@ function parseArgs(argv) {
11823
14262
  positional.push(token);
11824
14263
  }
11825
14264
  }
11826
- return { command, positional, flags };
14265
+ return { command, positional, flags, multiFlags };
11827
14266
  }
11828
14267
  function parseTimeViewFlag(value, err) {
11829
14268
  if (value === void 0) return void 0;
@@ -11836,13 +14275,13 @@ function parseTimeViewFlag(value, err) {
11836
14275
  }
11837
14276
  async function readReleaseInput(root, value) {
11838
14277
  if (value.includes(",")) return value.split(",");
11839
- const candidate = isAbsolute5(value) ? value : join11(root, value);
14278
+ const candidate = isAbsolute7(value) ? value : join14(root, value);
11840
14279
  try {
11841
- await access2(candidate);
14280
+ await access3(candidate);
11842
14281
  } catch {
11843
14282
  return [value];
11844
14283
  }
11845
- const raw = await readFile5(candidate, "utf-8");
14284
+ const raw = await readFile6(candidate, "utf-8");
11846
14285
  try {
11847
14286
  const parsed = JSON.parse(raw);
11848
14287
  if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) return parsed;
@@ -11857,6 +14296,12 @@ Commands:
11857
14296
  init
11858
14297
  scan
11859
14298
  validate [--format json] [--warning-only] [--include scenario-prd-links,e2e-coverage]
14299
+ check-professional --root <target> --format json [--conclusion-output <absolute-path>]
14300
+ Read-only composition of validate, version-lock audit, and coverage. Does not write graph cache.
14301
+ Absent artifact-graph.config.yaml is GRAPH_CHECK_UNAVAILABLE / not-performed; default loadConfig is not used here.
14302
+ Optional proof file is created exclusively and never overwrites an existing proof.
14303
+ read-proof --proof-root <root> --proof <relative> --format json
14304
+ Read one artifact-graph professional proof. Does not rescan the target or treat review-result as this contract.
11860
14305
  query [<target> | --from <code>] [--to <code>] [--depth <n>] [--view current|planned|history|all] [--format json]
11861
14306
  context (--target <type>:<id> | --feature <id> | --scenario <id> | --decision <id> | --design <id> | --e2e-test <id>) [--mode full|implementation] [--max-per-category <n>] [--view current|planned|history|all] [--format json]
11862
14307
  packet (--target <type>:<id> | --feature <id> | --scenario <id> | --decision <id> | --design <id> | --e2e-test <id>) [--mode full|implementation] [--max-per-category <n>] [--view current|planned|history|all] [--format json|markdown] [--out <path>] [--no-validate]
@@ -11874,13 +14319,16 @@ Commands:
11874
14319
  configure types.test.paths. See INSTALL.md: Code Traceability And Coverage Boundaries.
11875
14320
  version-lock update --target <type:id> --source <path> [--verified-by <path,path>] [--lock-path <path>]
11876
14321
  version-lock bootstrap [--force] [--lock-path <path>]
11877
- version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans] [--format json|markdown] [--lock-path <path>]
14322
+ version-lock refresh (--all | --changed-only (--staged | --worktree | --base <ref>)) [--remove-orphans | --remove-orphan-edge <edgeId>...] [--format json|markdown] [--lock-path <path>]
11878
14323
  --remove-orphans delete locks whose artifact, source, or traceability edge no longer
11879
14324
  exists (default: retain them). Typical cleanup after deleting or
11880
14325
  splitting artifacts:
11881
14326
  artifact-graph version-lock refresh --all --remove-orphans --format markdown
11882
14327
  git diff artifacts/traceability-version-lock.json # review
11883
14328
  git add artifacts/traceability-version-lock.json # stage, then commit
14329
+ --remove-orphan-edge <edgeId>
14330
+ delete only the named edge when it is still orphaned; repeat for
14331
+ multiple edges. Mutually exclusive with --remove-orphans.
11884
14332
  trace-version --target <type:id> [--format json|markdown] [--warning-only] [--strict-missing-lock] [--lock-path <path>]
11885
14333
  hooks install-git [--hook pre-commit|pre-push|all] [--uninstall]
11886
14334
  next-id <type> --range <name>
@@ -11890,6 +14338,18 @@ Commands:
11890
14338
  \u5B89\u5168\u5236\u54C1\u6807\u8BC6\u4E00\u5BF9\u4E00\u91CD\u6784\uFF1A\u7F3A\u7701 dry-run \u53EA\u8F93\u51FA\u8BA1\u5212\uFF1B--apply \u4EE5\u5355\u4E00\u4E8B\u52A1\u6539\u5199\u7ED3\u6784\u5316
11891
14339
  \u767D\u540D\u5355\u4F4D\u7F6E\u5E76\u81EA\u52A8 rescan \u8BC1\u660E\u3002\u9501\u4E0D\u81EA\u52A8\u5237\u65B0\uFF0Capply \u540E\u6309\u63D0\u793A\u8FD0\u884C
11892
14340
  version-lock refresh --changed-only --worktree\u3002
14341
+ restructure inspect --root <project> --input <request.json> [--format json]
14342
+ restructure plan --root <project> --input <mapping.json> [--format json]
14343
+ restructure apply --root <project> --plan <plan.json> --confirm-cooperative-writers [--format json]
14344
+ restructure recover --root <project> --plan <plan.json> --confirm-all-participants-stopped --confirm-exclusive-maintenance [--format json]
14345
+ restructure prune-recovery --root <project> --plan <plan.json> --confirm-cooperative-writers [--confirm-all-participants-stopped --confirm-exclusive-maintenance] [--format json]
14346
+ apply \u5DF2\u5F00\u653E\u5E76\u5728\u5408\u683C\u73AF\u5883\u771F\u5B9E\u5199\u5165\uFF1A\u5E73\u53F0\u8D44\u683C\u4EC5 Darwin/arm64/APFS\uFF0C\u5176\u4ED6\u5E73\u53F0\u4ECD\u53EF\u7528 inspect/plan\uFF0C
14347
+ apply \u4EE5 APPLY_ENVIRONMENT_UNSUPPORTED \u62D2\u7EDD\uFF0C\u4E0D\u4F1A\u964D\u7EA7\u6210\u65E0\u4E8B\u52A1\u5199\u5165\u3002\u6587\u4EF6\u96C6\u5408\u5199\u5165\u80FD\u529B\u7684\u6210\u719F\u5EA6\u4E3A
14348
+ candidate\uFF1A\u4EE5\u5408\u4F5C\u5F0F\u5199\u8005\u4E3A\u524D\u63D0\u4E14\u4E0D\u81EA\u8BC1\u8BE5\u524D\u63D0\uFF0Capply \u4E0E prune-recovery \u5FC5\u987B\u7ED9\u51FA
14349
+ --confirm-cooperative-writers\uFF0C\u7F3A\u5931\u5373\u62D2\u7EDD\u5199\u5165\uFF1Brecover \u5FC5\u987B\u540C\u65F6\u7ED9\u51FA
14350
+ --confirm-all-participants-stopped \u4E0E --confirm-exclusive-maintenance\u3002\u6062\u590D\u6750\u6599\u9ED8\u8BA4\u4FDD\u7559\uFF0C
14351
+ \u53EA\u6709\u663E\u5F0F prune-recovery \u624D\u6E05\u7406\u3002\u8BA1\u5212\u6587\u6863\u4FDD\u5B58\u5728\u5199\u96C6\u4E4B\u5916\u7684\u666E\u901A\u76EE\u5F55\uFF1A\u6062\u590D\u53EA\u4F9D\u8D56\u8BE5\u6587\u6863\uFF0C
14352
+ \u4E0D\u4F9D\u8D56\u8FDB\u7A0B\u72B6\u6001\u3002
11893
14353
  validate-review-result --file <path> [--format json]
11894
14354
  generate-e2e-registry [--deterministic] [--out <path>] [--check]
11895
14355
  contract list [--contracts-dir <path>] [--format json]
@@ -11905,7 +14365,7 @@ function isCliEntrypoint(argvPath) {
11905
14365
  return false;
11906
14366
  }
11907
14367
  try {
11908
- return realpathSync2(argvPath) === realpathSync2(fileURLToPath2(import.meta.url));
14368
+ return realpathSync2(argvPath) === realpathSync2(fileURLToPath3(import.meta.url));
11909
14369
  } catch {
11910
14370
  return false;
11911
14371
  }
@@ -11929,6 +14389,7 @@ var init_cli = __esm({
11929
14389
  init_git_hook_path();
11930
14390
  init_hook_installer();
11931
14391
  init_versioned_traceability();
14392
+ init_professional_conclusion();
11932
14393
  if (isCliEntrypoint(process.argv[1])) {
11933
14394
  void runCli(process.argv.slice(2)).then((code) => {
11934
14395
  process.exitCode = code;