artifact-graph 0.13.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
@@ -3924,6 +3924,378 @@ var init_hook_installer = __esm({
3924
3924
  }
3925
3925
  });
3926
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
+
3927
4299
  // src/review-result-validator.ts
3928
4300
  function validateReviewResult(input) {
3929
4301
  const errors = [];
@@ -4275,7 +4647,7 @@ __export(contract_kernel_exports, {
4275
4647
  });
4276
4648
  import { createHash as createHash2 } from "crypto";
4277
4649
  import { readFile as readFile2, readdir as readdir2 } from "fs/promises";
4278
- import { join as join7 } from "path";
4650
+ import { join as join8 } from "path";
4279
4651
  import _AjvModule from "ajv";
4280
4652
  function isOfficialNamespace(namespace) {
4281
4653
  return OFFICIAL_NAMESPACE_PATTERN.test(namespace);
@@ -4688,7 +5060,7 @@ async function loadContractsFromDirectory(contractsDir, options) {
4688
5060
  const entries = await readdir2(contractsDir, { withFileTypes: true });
4689
5061
  for (const entry of entries) {
4690
5062
  if (entry.isDirectory()) {
4691
- const schemaPath = join7(contractsDir, entry.name, "schema.json");
5063
+ const schemaPath = join8(contractsDir, entry.name, "schema.json");
4692
5064
  const contract = await loadContract(schemaPath, options);
4693
5065
  contracts.push(contract);
4694
5066
  }
@@ -5280,12 +5652,12 @@ var init_restructure_software = __esm({
5280
5652
  // src/restructure-file-set.ts
5281
5653
  import { createHash as createHash3 } from "crypto";
5282
5654
  import { chmod, lstat as lstat2, mkdir as mkdir4, realpath, statfs } from "fs/promises";
5283
- import { join as join8, resolve as resolve5 } from "path";
5655
+ import { join as join9, resolve as resolve6 } from "path";
5284
5656
  async function loadFoundationModule() {
5285
5657
  return await import(FOUNDATION_PACKAGE_NAME);
5286
5658
  }
5287
5659
  async function loadContractsModule() {
5288
- return await import(CONTRACTS_PACKAGE_NAME);
5660
+ return await import(CONTRACTS_PACKAGE_NAME2);
5289
5661
  }
5290
5662
  async function verifyMechanismResult(result) {
5291
5663
  if (typeof result !== "object" || result === null || Array.isArray(result)) {
@@ -5338,7 +5710,7 @@ function rawDigest(value, path) {
5338
5710
  async function resolveRealRoot(root) {
5339
5711
  let canonical;
5340
5712
  try {
5341
- canonical = await realpath(resolve5(root));
5713
+ canonical = await realpath(resolve6(root));
5342
5714
  } catch (cause) {
5343
5715
  return failure("ROOT_INVALID", `Project root cannot be resolved: ${cause.message}`);
5344
5716
  }
@@ -5377,7 +5749,7 @@ async function qualifyRestructureMechanism(root) {
5377
5749
  return { ok: true, data: { root: canonical.data, filesystem: RESTRUCTURE_QUALIFIED_FILESYSTEM } };
5378
5750
  }
5379
5751
  async function ensureRestructureMechanismRoot(canonicalRoot, options) {
5380
- const target = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5752
+ const target = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH);
5381
5753
  const current = async () => lstat2(target).catch((cause) => cause.code === "ENOENT" ? null : Promise.reject(cause));
5382
5754
  let info = await current();
5383
5755
  if (info === null) {
@@ -5491,7 +5863,7 @@ async function applyRestructureFileSet(canonicalRoot, plan, options) {
5491
5863
  return await verifyMechanismResult(raw);
5492
5864
  }
5493
5865
  async function observeRestructureJournal(canonicalRoot) {
5494
- const journalRoot = join8(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5866
+ const journalRoot = join9(canonicalRoot, RESTRUCTURE_RECOVERY_REL_PATH, "journal");
5495
5867
  const module = await loadFoundationModule();
5496
5868
  try {
5497
5869
  return { ok: true, data: await module.inspectStateStoreLock(journalRoot, { recoveryObservation: true }) };
@@ -5678,7 +6050,7 @@ function projectRestructureFileSetResult(result, planPath = "", planDigest = "")
5678
6050
  const reading = result.operation === "apply" ? applyProjection(result) : result.operation === "recover" ? recoverProjection(result) : pruneProjection(result);
5679
6051
  return { ...base, ...reading };
5680
6052
  }
5681
- var RESTRUCTURE_RECOVERY_REL_PATH, RESTRUCTURE_RECOVERY_JOURNAL_REL_PATH, RESTRUCTURE_RECOVERY_ROOT_MODE, RESTRUCTURE_QUALIFIED_PLATFORM, RESTRUCTURE_QUALIFIED_ARCH, RESTRUCTURE_QUALIFIED_FILESYSTEM, APFS_STATFS_TYPE, DIGEST_PREFIX, RAW_SHA256_PATTERN, FOUNDATION_PACKAGE_NAME, CONTRACTS_PACKAGE_NAME, FILE_SET_RESULT_OBJECT, APPLY_MAINTENANCE_ERROR_KINDS;
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;
5682
6054
  var init_restructure_file_set = __esm({
5683
6055
  "src/restructure-file-set.ts"() {
5684
6056
  "use strict";
@@ -5692,7 +6064,7 @@ var init_restructure_file_set = __esm({
5692
6064
  DIGEST_PREFIX = "sha256:";
5693
6065
  RAW_SHA256_PATTERN = /^[a-f0-9]{64}$/;
5694
6066
  FOUNDATION_PACKAGE_NAME = "skill-family-harness-node";
5695
- CONTRACTS_PACKAGE_NAME = "skill-family-contracts";
6067
+ CONTRACTS_PACKAGE_NAME2 = "skill-family-contracts";
5696
6068
  FILE_SET_RESULT_OBJECT = "file-set-result";
5697
6069
  APPLY_MAINTENANCE_ERROR_KINDS = ["lock-release-failed"];
5698
6070
  }
@@ -5719,7 +6091,7 @@ __export(restructure_exports, {
5719
6091
  });
5720
6092
  import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
5721
6093
  import { lstat as lstat3, readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "fs/promises";
5722
- import { dirname as dirname5, isAbsolute as isAbsolute4, join as join9, posix, relative as relative4, resolve as resolve6 } from "path";
6094
+ import { dirname as dirname6, isAbsolute as isAbsolute5, join as join10, posix, relative as relative4, resolve as resolve7 } from "path";
5723
6095
  import { fileURLToPath as fileURLToPath2 } from "url";
5724
6096
  function digestBytes(value) {
5725
6097
  return `sha256:${createHash4("sha256").update(value).digest("hex")}`;
@@ -5735,7 +6107,7 @@ function digestRestructureValue(value) {
5735
6107
  return digestBytes(canonicalJson(value));
5736
6108
  }
5737
6109
  function normalizeRelativePath2(value) {
5738
- if (!value || value.includes("\0") || isAbsolute4(value)) return void 0;
6110
+ if (!value || value.includes("\0") || isAbsolute5(value)) return void 0;
5739
6111
  const normalized = value.replace(/\\/g, "/").replace(/^\.\//, "");
5740
6112
  if (!normalized || normalized === "." || normalized.split("/").some((part) => part === ".." || part === "")) return void 0;
5741
6113
  return normalized;
@@ -5749,8 +6121,8 @@ function isPathAllowed(path, allowed) {
5749
6121
  async function readContainedFileWithMode(root, path) {
5750
6122
  const normalized = normalizeRelativePath2(path);
5751
6123
  if (!normalized) throw new Error(`Path must be a project-relative path without traversal: ${path}`);
5752
- const absoluteRoot = resolve6(root);
5753
- const absolutePath = resolve6(absoluteRoot, normalized);
6124
+ const absoluteRoot = resolve7(root);
6125
+ const absolutePath = resolve7(absoluteRoot, normalized);
5754
6126
  if (relative4(absoluteRoot, absolutePath).startsWith("..")) throw new Error(`Path escapes project root: ${path}`);
5755
6127
  try {
5756
6128
  const info = await lstat3(absolutePath);
@@ -5783,7 +6155,7 @@ async function configSnapshot(root) {
5783
6155
  return snapshotFile(root, "artifact-graph.config.yaml");
5784
6156
  }
5785
6157
  async function loadRestructureContract(name) {
5786
- return loadContract(join9(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
6158
+ return loadContract(join10(CONTRACT_ROOT, `restructure-${name}`, "schema.json"), { expectedAuthority: "artifact" });
5787
6159
  }
5788
6160
  async function validateDomainContract(name, value) {
5789
6161
  const contract = await loadRestructureContract(name);
@@ -6058,7 +6430,7 @@ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6058
6430
  async function visit(directory) {
6059
6431
  for (const entry of await readdir3(directory, { withFileTypes: true })) {
6060
6432
  if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6061
- const absolute = join9(directory, entry.name);
6433
+ const absolute = join10(directory, entry.name);
6062
6434
  if (entry.isDirectory()) {
6063
6435
  await visit(absolute);
6064
6436
  continue;
@@ -6087,7 +6459,7 @@ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6087
6459
  path,
6088
6460
  lineNumber
6089
6461
  ));
6090
- } else if (!await pathExists2(resolve6(root, resolved))) {
6462
+ } else if (!await pathExists2(resolve7(root, resolved))) {
6091
6463
  findings.push(finding(
6092
6464
  "SIBLING_RELATIVE_REFERENCE_UNRESOLVED",
6093
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`,
@@ -6112,7 +6484,7 @@ async function scanUnsupportedReferences(root, sourcePaths, targetPaths) {
6112
6484
  }
6113
6485
  }
6114
6486
  }
6115
- await visit(resolve6(root));
6487
+ await visit(resolve7(root));
6116
6488
  const unique = new Map(findings.map((item) => [`${item.code} ${item.path} ${item.line} ${item.message}`, item]));
6117
6489
  return [...unique.values()].sort((left, right) => (left.path ?? "").localeCompare(right.path ?? "") || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
6118
6490
  }
@@ -6130,7 +6502,7 @@ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PU
6130
6502
  async function visit(directory) {
6131
6503
  for (const entry of await readdir3(directory, { withFileTypes: true })) {
6132
6504
  if (entry.isDirectory() && SKIPPED_SCAN_DIRS.has(entry.name)) continue;
6133
- const absolute = join9(directory, entry.name);
6505
+ const absolute = join10(directory, entry.name);
6134
6506
  if (entry.isDirectory()) {
6135
6507
  await visit(absolute);
6136
6508
  } else if (entry.isFile() && TEXT_EXTENSIONS.test(entry.name)) {
@@ -6145,7 +6517,7 @@ async function scanConsumerCandidates(root, references, excludedPaths = /* @__PU
6145
6517
  }
6146
6518
  }
6147
6519
  }
6148
- await visit(resolve6(root));
6520
+ await visit(resolve7(root));
6149
6521
  return results.sort((left, right) => left.path.localeCompare(right.path) || left.line - right.line || left.reference.localeCompare(right.reference));
6150
6522
  }
6151
6523
  function expectedRelationTargets(mapping) {
@@ -6185,7 +6557,7 @@ function restructureBoundaryFindings(operations, limits) {
6185
6557
  const expectedCreateMode = createModeForUmask(limits.umask);
6186
6558
  const applyModeContract = limits.mode_contract === "apply";
6187
6559
  for (const operation of operations) {
6188
- const parent = dirname5(operation.path) || ".";
6560
+ const parent = dirname6(operation.path) || ".";
6189
6561
  if (!operation.parent_exists) {
6190
6562
  findings.push(finding("PARENT_DIRECTORY_MISSING", `Parent directory does not exist or is not a directory: ${parent}`, operation.path));
6191
6563
  } else if (operation.parent_device !== null && operation.parent_device !== operation.root_device) {
@@ -6376,7 +6748,7 @@ async function planRestructure(root, input) {
6376
6748
  }
6377
6749
  pathMoves.push(move);
6378
6750
  rangesByPath.set(sourcePath, pathMoves);
6379
- if (dirname5(sourcePath) !== dirname5(targetPath)) {
6751
+ if (dirname6(sourcePath) !== dirname6(targetPath)) {
6380
6752
  for (const link of findRelativeLinks(fragment.toString("utf8"))) {
6381
6753
  const explicitlyEdited = mapping.prose_edits.some((edit) => edit.target_path === targetPath && edit.old_text.includes(link));
6382
6754
  if (!explicitlyEdited) blockers.push(finding("RELATIVE_LINK_REQUIRES_MAPPING", `Relative reference "${link}" changes base directory when moved to ${targetPath}`, sourcePath));
@@ -6493,15 +6865,15 @@ async function planRestructure(root, input) {
6493
6865
  diff: readableDiff(path, original?.toString("utf8"), deleteFile ? void 0 : candidate.toString("utf8"))
6494
6866
  });
6495
6867
  }
6496
- const rootDirectory = await probeDirectory(resolve6(root));
6868
+ const rootDirectory = await probeDirectory(resolve7(root));
6497
6869
  const parentProbes = /* @__PURE__ */ new Map();
6498
6870
  for (const candidate of candidates) {
6499
- const parent = dirname5(candidate.path);
6500
- if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve6(root, parent)));
6871
+ const parent = dirname6(candidate.path);
6872
+ if (!parentProbes.has(parent)) parentProbes.set(parent, await probeDirectory(resolve7(root, parent)));
6501
6873
  }
6502
6874
  blockers.push(...restructureBoundaryFindings(
6503
6875
  candidates.map((candidate) => {
6504
- const parent = parentProbes.get(dirname5(candidate.path));
6876
+ const parent = parentProbes.get(dirname6(candidate.path));
6505
6877
  return {
6506
6878
  path: candidate.path,
6507
6879
  action: candidate.action,
@@ -6627,7 +6999,7 @@ function refusal(code, message, findings = []) {
6627
6999
  return { ok: false, error: { code, message, ...findings.length === 0 ? {} : { details: findings } } };
6628
7000
  }
6629
7001
  async function loadRestructurePlanDocument(operation, canonicalRoot, planPath) {
6630
- const absolute = resolve6(planPath);
7002
+ const absolute = resolve7(planPath);
6631
7003
  let info;
6632
7004
  try {
6633
7005
  info = await lstat3(absolute);
@@ -6671,18 +7043,18 @@ function planRootIdentityFindings(document) {
6671
7043
  findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan does not record this project's configuration file: ${document.plan.config_snapshot.path}`));
6672
7044
  }
6673
7045
  const relativePlan = relative4(document.root, document.realPath);
6674
- if (!relativePlan || relativePlan.startsWith("..") || isAbsolute4(relativePlan)) {
7046
+ if (!relativePlan || relativePlan.startsWith("..") || isAbsolute5(relativePlan)) {
6675
7047
  findings.push(finding("ROOT_IDENTITY_MISMATCH", `The plan document is outside the project root: ${document.realPath}`, document.realPath));
6676
7048
  }
6677
7049
  return findings;
6678
7050
  }
6679
7051
  async function operationBoundaries(root, plan) {
6680
- const rootDirectory = await probeDirectory(resolve6(root));
7052
+ const rootDirectory = await probeDirectory(resolve7(root));
6681
7053
  const parents = /* @__PURE__ */ new Map();
6682
7054
  const boundaries = [];
6683
7055
  for (const candidate of plan.candidates) {
6684
- const parent = dirname5(candidate.path) || ".";
6685
- if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve6(root, parent)));
7056
+ const parent = dirname6(candidate.path) || ".";
7057
+ if (!parents.has(parent)) parents.set(parent, await probeDirectory(resolve7(root, parent)));
6686
7058
  const probe = parents.get(parent);
6687
7059
  boundaries.push({
6688
7060
  path: candidate.path,
@@ -6861,8 +7233,8 @@ var init_restructure = __esm({
6861
7233
  RESTRUCTURE_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
6862
7234
  MAX_POSIX_MODE = 511;
6863
7235
  CREATE_MODE_BASE = 438;
6864
- MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname5(fileURLToPath2(import.meta.url));
6865
- CONTRACT_ROOT = join9(MODULE_DIRECTORY, "..", "contracts");
7236
+ MODULE_DIRECTORY = typeof __dirname === "string" ? __dirname : dirname6(fileURLToPath2(import.meta.url));
7237
+ CONTRACT_ROOT = join10(MODULE_DIRECTORY, "..", "contracts");
6866
7238
  SKIPPED_SCAN_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "coverage", ".tmp", ".codex", ".worktrees", ".foundation-file-apply", ".artifact-graph"]);
6867
7239
  TEXT_EXTENSIONS = /\.(?:md|markdown|json|ya?ml|[cm]?[jt]sx?)$/i;
6868
7240
  MARKDOWN_LINK_PATTERN = /!?\[([^\]\n]*)\]\(([^)\n]+)\)/g;
@@ -6877,7 +7249,7 @@ import matter from "gray-matter";
6877
7249
  import yaml from "js-yaml";
6878
7250
  import { accessSync, constants as fsConstants, existsSync as existsSync3, statSync } from "fs";
6879
7251
  import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
6880
- import { basename as basename4, dirname as dirname6, extname, isAbsolute as isAbsolute5, join as join10, resolve as resolve7 } from "path";
7252
+ import { basename as basename5, dirname as dirname7, extname, isAbsolute as isAbsolute6, join as join11, resolve as resolve8 } from "path";
6881
7253
  function isTargetArtifactType(type) {
6882
7254
  return isPacketTargetType(type);
6883
7255
  }
@@ -6919,7 +7291,7 @@ function resolveArtifactTypeName(schema, token) {
6919
7291
  return void 0;
6920
7292
  }
6921
7293
  async function loadConfig(root) {
6922
- const configPath = join10(root, "artifact-graph.config.yaml");
7294
+ const configPath = join11(root, "artifact-graph.config.yaml");
6923
7295
  let parsed = {};
6924
7296
  try {
6925
7297
  const raw = await readFile4(configPath, "utf-8");
@@ -6963,8 +7335,31 @@ async function loadConfig(root) {
6963
7335
  idRanges: mergeRecord(DEFAULT_SCHEMA.idRanges, parsed.idRanges),
6964
7336
  e2e: mergedE2e
6965
7337
  };
7338
+ validateJsonArtifactTypes(merged.types);
6966
7339
  return merged;
6967
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
+ }
6968
7363
  function validateRelationSemanticsConfig(value) {
6969
7364
  if (value === void 0) return;
6970
7365
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -7048,7 +7443,7 @@ function validateE2eConfig(e2e) {
7048
7443
  if (typeof runner.root !== "string" || !runner.root.trim()) {
7049
7444
  throw new Error(`Invalid e2e.runners[${runner.name}].root: must be a non-empty string.`);
7050
7445
  }
7051
- if (isAbsolute5(runner.root)) {
7446
+ if (isAbsolute6(runner.root)) {
7052
7447
  throw new Error(`Invalid e2e.runners[${runner.name}].root: "${runner.root}" must not be an absolute path.`);
7053
7448
  }
7054
7449
  if (runner.root.replace(/\\/g, "/").split("/").includes("..")) {
@@ -7137,15 +7532,15 @@ async function scanArtifacts(root, schema, options = {}) {
7137
7532
  continue;
7138
7533
  }
7139
7534
  scannedFiles.set(file, type);
7140
- const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join10(root, file), "utf-8");
7535
+ const raw = contentOverrides.has(file) ? contentOverrides.get(file) : await readFile4(join11(root, file), "utf-8");
7141
7536
  const parsed = parseFile(type, file, raw, config);
7142
- const semantic = parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7537
+ const semantic = isJsonOriginalType(type, config) ? { edges: [], diagnostics: [] } : parseConfiguredRelations(type, file, raw, parsed.nodes, config);
7143
7538
  nodes.push(...parsed.nodes);
7144
7539
  edges.push(...parsed.edges, ...semantic.edges);
7145
7540
  scanDiagnostics.push(...parsed.diagnostics, ...semantic.diagnostics);
7146
7541
  }
7147
7542
  }
7148
- const absoluteRoot = isAbsolute5(root) ? root : resolve7(root);
7543
+ const absoluteRoot = isAbsolute6(root) ? root : resolve8(root);
7149
7544
  const graph = buildGraph(nodes, edges, scanDiagnostics, absoluteRoot);
7150
7545
  return resolveMatrixEdges(graph);
7151
7546
  }
@@ -7350,33 +7745,6 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
7350
7745
  issues.push(issue("CYCLE_DETECTED", `depends_on cycle detected: ${cycle.join(" -> ")}`, "", 1, { node: cycle[0] }));
7351
7746
  }
7352
7747
  const defaultTypeKeys = new Set(Object.keys(DEFAULT_SCHEMA.types));
7353
- const specializedParserTypes = /* @__PURE__ */ new Set([
7354
- "feature",
7355
- "scenario",
7356
- "entity",
7357
- "decision",
7358
- "test",
7359
- "design",
7360
- "e2e_test",
7361
- "e2e_registry",
7362
- "rule-golden-cases",
7363
- "test-strategy",
7364
- "traceability-matrix-v2",
7365
- "traceability-version-lock",
7366
- "interface_contracts",
7367
- "data_contracts",
7368
- "application_state_machines",
7369
- "error_model",
7370
- "domain-glossary",
7371
- "bounded-context-map",
7372
- "domain-invariants",
7373
- "generation-packet-spec",
7374
- "report-contracts",
7375
- "verification-fixtures",
7376
- "ui-flow-contracts",
7377
- "non-functional-budgets",
7378
- "implementation-blueprint"
7379
- ]);
7380
7748
  const uidsWithEdges = /* @__PURE__ */ new Set();
7381
7749
  for (const edge2 of graph.edges) {
7382
7750
  uidsWithEdges.add(edge2.from);
@@ -7384,7 +7752,7 @@ function validateGraph(graph, schema = DEFAULT_SCHEMA) {
7384
7752
  }
7385
7753
  for (const node of graph.nodes) {
7386
7754
  if (defaultTypeKeys.has(node.type)) continue;
7387
- if (specializedParserTypes.has(node.type)) continue;
7755
+ if (SPECIALIZED_PARSER_TYPES.has(node.type)) continue;
7388
7756
  if (!schema.types[node.type]) continue;
7389
7757
  if (!uidsWithEdges.has(node.uid)) {
7390
7758
  issues.push(issue(
@@ -7508,7 +7876,7 @@ async function validateScenarioPrdLinkIndex(root, graph) {
7508
7876
  const indexPath = "artifacts/prd/feature-index.md";
7509
7877
  let raw = "";
7510
7878
  try {
7511
- raw = await readFile4(join10(root, indexPath), "utf-8");
7879
+ raw = await readFile4(join11(root, indexPath), "utf-8");
7512
7880
  } catch (error) {
7513
7881
  if (error.code === "ENOENT") {
7514
7882
  return [];
@@ -7756,12 +8124,12 @@ function nextId(graph, schema, type, rangeName) {
7756
8124
  throw new Error(`ID range ${type}.${rangeName} is exhausted`);
7757
8125
  }
7758
8126
  async function writeGraphCache(root, graph) {
7759
- const cacheDir = join10(root, ".artifact-graph");
8127
+ const cacheDir = join11(root, ".artifact-graph");
7760
8128
  await mkdir5(cacheDir, { recursive: true });
7761
- await writeFile3(join10(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
8129
+ await writeFile3(join11(cacheDir, "index.json"), `${JSON.stringify(graph, null, 2)}
7762
8130
  `);
7763
8131
  const { default: Database } = await import("better-sqlite3");
7764
- const db = new Database(join10(cacheDir, "graph.sqlite"));
8132
+ const db = new Database(join11(cacheDir, "graph.sqlite"));
7765
8133
  try {
7766
8134
  db.exec(`
7767
8135
  DROP TABLE IF EXISTS nodes;
@@ -7802,7 +8170,13 @@ async function writeGraphCache(root, graph) {
7802
8170
  db.close();
7803
8171
  }
7804
8172
  }
8173
+ function isJsonOriginalType(type, schema) {
8174
+ return schema.types[type]?.format === "json" && !SPECIALIZED_PARSER_TYPES.has(type);
8175
+ }
7805
8176
  function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
8177
+ if (isJsonOriginalType(type, schema)) {
8178
+ return parseGenericJson(type, path, raw, schema);
8179
+ }
7806
8180
  if (type === "feature") {
7807
8181
  return { ...parseFeature(path, raw), diagnostics: [] };
7808
8182
  }
@@ -7871,6 +8245,184 @@ function parseFile(type, path, raw, schema = DEFAULT_SCHEMA) {
7871
8245
  }
7872
8246
  return parseGenericMarkdown(type, path, raw, schema);
7873
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 };
8308
+ }
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 };
8318
+ }
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
+ ));
8329
+ }
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" };
8345
+ }
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;
8361
+ }
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];
8372
+ }
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;
8389
+ }
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
+ }
8423
+ }
8424
+ return { edges, diagnostics };
8425
+ }
7874
8426
  function parseGenericMarkdown(type, path, raw, schema) {
7875
8427
  const diagnostics = [];
7876
8428
  const ext = extname(path).toLowerCase();
@@ -7989,38 +8541,18 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
7989
8541
  const diagnostics = [];
7990
8542
  for (const [kind, spec] of Object.entries(schema.relationSemantics ?? {})) {
7991
8543
  for (const field of spec.fields) {
7992
- for (const value of toArray(data[field])) {
7993
- const parsed = parseConfiguredRelationTarget(value, spec, schema);
7994
- if (!parsed?.code) continue;
7995
- const matchingTargetTypes = parsed.targetType ? [] : relationTargetTypeMatches(parsed.code, spec.targetTypes, schema);
7996
- const targetType = parsed.targetType ?? inferRelationTargetType(parsed.code, spec.targetTypes, schema);
7997
- if (!parsed.targetType && matchingTargetTypes.length > 1) {
7998
- diagnostics.push(issue(
7999
- "AMBIGUOUS_RELATION_TARGET",
8000
- `${sourceUid} relation ${kind} target "${parsed.code}" matches ${matchingTargetTypes.join(", ")}; use a qualified type:id reference`,
8001
- path,
8002
- 1,
8003
- { node: sourceUid }
8004
- ));
8005
- }
8006
- const targetUid = targetType ? toUid(targetType, parsed.code) : `resolve:${parsed.code}`;
8007
- if (targetType) {
8008
- const pattern = schema.idPatterns[targetType];
8009
- if (pattern && !new RegExp(pattern).test(parsed.code)) {
8010
- diagnostics.push(issue(
8011
- "FORMAT_ERROR",
8012
- `${sourceUid} has invalid ${targetType} reference "${parsed.code}" in field ${field} (expected ${pattern})`,
8013
- path,
8014
- 1,
8015
- { node: sourceUid }
8016
- ));
8017
- }
8018
- }
8019
- edges.push({
8020
- ...edge(sourceUid, targetUid, kind, "frontmatter", path, 1),
8021
- ...parsed.sections.length > 0 ? { attrs: { sections: parsed.sections } } : {}
8022
- });
8023
- }
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
+ );
8024
8556
  }
8025
8557
  }
8026
8558
  const external = getExternalEntryInfo({
@@ -8039,6 +8571,40 @@ function parseConfiguredRelations(type, path, raw, nodes, schema) {
8039
8571
  }
8040
8572
  return { edges, diagnostics };
8041
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
+ }
8042
8608
  function parseConfiguredRelationTarget(value, spec, schema) {
8043
8609
  if (typeof value === "string" || typeof value === "number") {
8044
8610
  const raw = String(value).trim();
@@ -8229,7 +8795,7 @@ function parseDecisions(path, raw) {
8229
8795
  }
8230
8796
  function isTestFile(filePath) {
8231
8797
  const normalized = filePath.replace(/\\/g, "/");
8232
- const name = basename4(normalized);
8798
+ const name = basename5(normalized);
8233
8799
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
8234
8800
  if (/(^|\/)(tests|test|__tests__)\//.test(normalized)) return true;
8235
8801
  if (/\w+Tests?\.java$/.test(name)) return true;
@@ -8544,10 +9110,10 @@ function parseE2eTest(path, raw) {
8544
9110
  const starts = extractE2eTestCaseStarts(lines);
8545
9111
  const nodes = [];
8546
9112
  const edges = [];
8547
- const batch = String(data.test_batch ?? basename4(path, extname(path))).trim();
9113
+ const batch = String(data.test_batch ?? basename5(path, extname(path))).trim();
8548
9114
  const frontmatterScenarios = toArray(data.related_scenarios).map((value) => String(value).trim()).filter(Boolean);
8549
9115
  const scopeFeatures = extractCodes(String(data.scope ?? ""), "feature");
8550
- 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])];
8551
9117
  const frontmatterDecisions = toArray(data.related_decisions).map((value) => String(value).trim()).filter(Boolean);
8552
9118
  const frontmatterEntities = toArray(data.related_entities).map((value) => String(value).trim()).filter(Boolean);
8553
9119
  for (let index = 0; index < starts.length; index += 1) {
@@ -8607,7 +9173,7 @@ function parseE2eRegistry(path, raw) {
8607
9173
  data = { parseError: error.message };
8608
9174
  }
8609
9175
  return {
8610
- 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 }],
8611
9177
  edges: []
8612
9178
  };
8613
9179
  }
@@ -9415,13 +9981,13 @@ function markdownRelationOccurrences(path, scenario, block, codeLines, label, ta
9415
9981
  return result;
9416
9982
  }
9417
9983
  function relationOccurrences2(node, field, targetType) {
9418
- const relationRecord = asRecord(node.attrs?.relationOccurrences);
9984
+ const relationRecord = asRecord2(node.attrs?.relationOccurrences);
9419
9985
  const rawOccurrences = toArray(relationRecord[field]);
9420
9986
  return rawOccurrences.flatMap((value) => {
9421
9987
  if (typeof value === "string") {
9422
9988
  return [{ field, targetType, target: value, path: node.path, line: node.line }];
9423
9989
  }
9424
- const record = asRecord(value);
9990
+ const record = asRecord2(value);
9425
9991
  const target = String(record.target ?? "").trim();
9426
9992
  if (!target) {
9427
9993
  return [];
@@ -9528,7 +10094,7 @@ function validateE2eTests(graph) {
9528
10094
  issues.push(issue("E2E_REQUIRED_FRONTMATTER", `${node.uid} missing required frontmatter ${field}`, node.path, 1, { node: node.uid, severity: "warning" }));
9529
10095
  }
9530
10096
  }
9531
- const fields = asRecord(attrs.tcFields);
10097
+ const fields = asRecord2(attrs.tcFields);
9532
10098
  const requiredTcFields = [
9533
10099
  ["\u6807\u9898", node.title],
9534
10100
  ["\u524D\u7F6E\u6761\u4EF6", fields["\u524D\u7F6E\u6761\u4EF6"]],
@@ -9578,7 +10144,7 @@ function validateE2eTests(graph) {
9578
10144
  }
9579
10145
  for (const [path, nodes] of nodesByPath) {
9580
10146
  const first = nodes[0];
9581
- const declared = flattenAcCoverage(asRecord(first.attrs?.ac_coverage));
10147
+ const declared = flattenAcCoverage(asRecord2(first.attrs?.ac_coverage));
9582
10148
  const covered = new Set(nodes.flatMap((node) => toArray(node.attrs?.coveredFeatures).map((value) => {
9583
10149
  const ref = value;
9584
10150
  return `${String(ref.feature)}:${String(ref.ac)}`;
@@ -9622,7 +10188,7 @@ function validateE2eRegistry(graph) {
9622
10188
  const first = actualNodes[0];
9623
10189
  compareRegistryValue(issues, registry, batch, "batch_id", first.attrs?.test_batch);
9624
10190
  compareRegistryValue(issues, registry, batch, "scope", first.attrs?.scope);
9625
- compareRegistryAcCoverage(issues, registry, batch, asRecord(first.attrs?.ac_coverage));
10191
+ compareRegistryAcCoverage(issues, registry, batch, asRecord2(first.attrs?.ac_coverage));
9626
10192
  compareRegistryArray(issues, registry, batch, "related_scenarios", toArray(first.attrs?.related_scenarios).map((value) => String(value)));
9627
10193
  compareRegistryValue(issues, registry, batch, "test_case_count", actualNodes.filter((node) => node.attrs?.fileLevelOnly !== true).length);
9628
10194
  }
@@ -9645,10 +10211,10 @@ async function validateExecutableTraceability(root, config) {
9645
10211
  const tcKeyToFields = /* @__PURE__ */ new Map();
9646
10212
  const mdBatches = /* @__PURE__ */ new Set();
9647
10213
  for (const relPath of e2eFiles) {
9648
- const raw = await readFile4(join10(root, relPath), "utf-8");
10214
+ const raw = await readFile4(join11(root, relPath), "utf-8");
9649
10215
  const parsed = matter(raw);
9650
10216
  const data = parsed.data;
9651
- const batch = String(data.test_batch ?? basename4(relPath, extname(relPath))).trim();
10217
+ const batch = String(data.test_batch ?? basename5(relPath, extname(relPath))).trim();
9652
10218
  const lines = raw.split(/\r?\n/);
9653
10219
  const tcStarts = extractE2eTestCaseStarts(lines);
9654
10220
  for (let i = 0; i < tcStarts.length; i += 1) {
@@ -9687,7 +10253,7 @@ async function validateExecutableTraceability(root, config) {
9687
10253
  const tcAnnotationRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+?)\s+\[(\w+)\]/;
9688
10254
  const tcAnnotationNoLevelRegex = /\/\/!?\s*@(?:e2e_test|tc)\s+(\S+)/;
9689
10255
  for (const specFile of specFiles) {
9690
- const fullSpecPath = join10(root, specFile);
10256
+ const fullSpecPath = join11(root, specFile);
9691
10257
  let content;
9692
10258
  try {
9693
10259
  content = await readFile4(fullSpecPath, "utf-8");
@@ -9769,7 +10335,7 @@ async function validateExecutableTraceability(root, config) {
9769
10335
  if (entry.testId) {
9770
10336
  let content;
9771
10337
  try {
9772
- content = await readFile4(join10(root, normalizedRefFile), "utf-8");
10338
+ content = await readFile4(join11(root, normalizedRefFile), "utf-8");
9773
10339
  } catch {
9774
10340
  continue;
9775
10341
  }
@@ -9948,11 +10514,11 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
9948
10514
  const chainTypeBreakdown = {};
9949
10515
  const tcFieldsMap = new Map(e2eNodes.map((node) => [
9950
10516
  node.code,
9951
- asRecord(node.attrs?.tcFields)
10517
+ asRecord2(node.attrs?.tcFields)
9952
10518
  ]));
9953
10519
  for (const node of e2eNodes) {
9954
10520
  const tcKey = node.code;
9955
- const fields = tcFieldsMap.get(tcKey) ?? asRecord(node.attrs?.tcFields);
10521
+ const fields = tcFieldsMap.get(tcKey) ?? asRecord2(node.attrs?.tcFields);
9956
10522
  const execRef = String(fields["executable_ref"] ?? "").trim();
9957
10523
  if (execRef && !isPendingExecutableRef(execRef)) {
9958
10524
  withExecutableRef++;
@@ -9982,8 +10548,8 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
9982
10548
  }
9983
10549
  }
9984
10550
  for (const node of e2eNodes) {
9985
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
9986
- 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);
9987
10553
  for (const feature of Object.keys(acCoverage)) {
9988
10554
  acCoveredFeatures.add(feature);
9989
10555
  }
@@ -9995,7 +10561,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
9995
10561
  const runners = (await loadConfig(root)).e2e?.runners ?? [];
9996
10562
  const allProjectFiles = await walkFiles(root);
9997
10563
  for (const node of e2eNodes) {
9998
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
10564
+ const fields = tcFieldsMap.get(node.code) ?? asRecord2(node.attrs?.tcFields);
9999
10565
  const status = String(fields["status"] ?? "").trim().toLowerCase();
10000
10566
  const execRef = String(fields["executable_ref"] ?? "").trim();
10001
10567
  if (status !== "verified") continue;
@@ -10004,7 +10570,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
10004
10570
  let hasActiveE2eRef = false;
10005
10571
  for (const entry of parseExecutableRefLines(execRef)) {
10006
10572
  const normalized = resolveExecutableRefFile(entry.file, allProjectFiles);
10007
- if (!normalized || !existsSync3(join10(root, normalized))) continue;
10573
+ if (!normalized || !existsSync3(join11(root, normalized))) continue;
10008
10574
  const accepting = await getAcceptingRunners(root, normalized, runners);
10009
10575
  if (accepting.some((runner) => runner.kind === "e2e")) {
10010
10576
  hasActiveE2eRef = true;
@@ -10016,7 +10582,7 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
10016
10582
  for (const scenario of relatedScenarios) {
10017
10583
  verifiedScenarios.add(scenario);
10018
10584
  }
10019
- const acCoverage = asRecord(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10585
+ const acCoverage = asRecord2(fields["ac_coverage"] ?? node.attrs?.ac_coverage);
10020
10586
  for (const feature of Object.keys(acCoverage)) {
10021
10587
  verifiedFeatures.add(feature);
10022
10588
  }
@@ -10063,13 +10629,13 @@ async function computeE2eCoverageStats(graph, root, thresholds = {}) {
10063
10629
  const acCoverageRateByFeature = {};
10064
10630
  const featureAcMap = /* @__PURE__ */ new Map();
10065
10631
  for (const node of featureNodes) {
10066
- const acs = parseAcceptanceCriteria(await readFile4(join10(root, node.path), "utf-8"));
10632
+ const acs = parseAcceptanceCriteria(await readFile4(join11(root, node.path), "utf-8"));
10067
10633
  featureAcMap.set(node.code, new Set(acs));
10068
10634
  }
10069
10635
  const coveredAcByFeature = /* @__PURE__ */ new Map();
10070
10636
  for (const node of e2eNodes) {
10071
- const fields = tcFieldsMap.get(node.code) ?? asRecord(node.attrs?.tcFields);
10072
- 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);
10073
10639
  for (const [feature, acs] of Object.entries(acCoverage)) {
10074
10640
  const existing = coveredAcByFeature.get(feature) ?? /* @__PURE__ */ new Set();
10075
10641
  for (const ac of toArray(acs)) {
@@ -10111,11 +10677,11 @@ async function generateE2eRegistry(root, opts) {
10111
10677
  const batchIds = /* @__PURE__ */ new Set();
10112
10678
  let totalTestCases = 0;
10113
10679
  for (const file of files) {
10114
- const filePath = join10(root, file);
10680
+ const filePath = join11(root, file);
10115
10681
  const raw = await readFile4(filePath, "utf-8");
10116
10682
  const parsed = matter(raw);
10117
10683
  const data = parsed.data;
10118
- const batch = String(data.test_batch ?? basename4(file, extname(file))).trim();
10684
+ const batch = String(data.test_batch ?? basename5(file, extname(file))).trim();
10119
10685
  const relPath = file;
10120
10686
  const scope = String(data.scope ?? "").trim();
10121
10687
  const acCoverage = normalizeAcCoverageForRegistry(data.ac_coverage);
@@ -10237,7 +10803,7 @@ async function validatePartialRustEvidence(tcFields, tcKey, root, allFiles) {
10237
10803
  if (!normalizedPath) {
10238
10804
  return { hasValidPartialRust: false, detail: `partial_rust file not found: ${ref.file}` };
10239
10805
  }
10240
- const fullPath = join10(root, normalizedPath);
10806
+ const fullPath = join11(root, normalizedPath);
10241
10807
  let content;
10242
10808
  try {
10243
10809
  content = await readFile4(fullPath, "utf-8");
@@ -10274,7 +10840,7 @@ function detectTestLevel(specFile, content) {
10274
10840
  }
10275
10841
  function resolveExecutableRefFile(refFile, allFiles) {
10276
10842
  const normalized = refFile.replace(/\\/g, "/").replace(/^\.\//, "");
10277
- if (!normalized || isAbsolute5(refFile) || normalized.split("/").includes("..")) {
10843
+ if (!normalized || isAbsolute6(refFile) || normalized.split("/").includes("..")) {
10278
10844
  return void 0;
10279
10845
  }
10280
10846
  if (allFiles.includes(normalized)) {
@@ -10449,7 +11015,7 @@ function flattenAcCoverage(value) {
10449
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)}`) })));
10450
11016
  }
10451
11017
  function needsDesktopChainWarning(node) {
10452
- const tcFields = asRecord(node.attrs?.tcFields);
11018
+ const tcFields = asRecord2(node.attrs?.tcFields);
10453
11019
  const chainType = String(tcFields["chain_type"] ?? "").trim().toLowerCase();
10454
11020
  if (chainType && VALID_CHAIN_TYPES.has(chainType) && chainType !== "desktop_chain" || chainType in DEPRECATED_CHAIN_TYPE_ALIASES) {
10455
11021
  return false;
@@ -10506,7 +11072,7 @@ function compareRegistryAcCoverage(issues, registry, batch, actual) {
10506
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" }));
10507
11073
  return;
10508
11074
  }
10509
- if (normalizeAcCoverage(asRecord(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
11075
+ if (normalizeAcCoverage(asRecord2(batch.ac_coverage)) !== normalizeAcCoverage(actual)) {
10510
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" }));
10511
11077
  }
10512
11078
  }
@@ -10521,7 +11087,7 @@ function groupBy(values, key) {
10521
11087
  }
10522
11088
  return result;
10523
11089
  }
10524
- function asRecord(value) {
11090
+ function asRecord2(value) {
10525
11091
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
10526
11092
  }
10527
11093
  function isEmptyValue(value) {
@@ -10580,7 +11146,7 @@ function normalizeDesignCode(value) {
10580
11146
  if (!raw) {
10581
11147
  return "";
10582
11148
  }
10583
- return basename4(raw, extname(raw));
11149
+ return basename5(raw, extname(raw));
10584
11150
  }
10585
11151
  function toUid(type, code) {
10586
11152
  return `${type}:${code}`;
@@ -10856,7 +11422,7 @@ function resolveArtifactContext(graph, opts) {
10856
11422
  }
10857
11423
  if (root) {
10858
11424
  for (const ap of ALWAYS_PRESENT_ITEMS) {
10859
- const fullPath = join10(root, ap.path);
11425
+ const fullPath = join11(root, ap.path);
10860
11426
  let stat3;
10861
11427
  try {
10862
11428
  stat3 = statSync(fullPath);
@@ -11098,7 +11664,7 @@ function formatContextMarkdown(manifest) {
11098
11664
  }
11099
11665
  return lines.join("\n");
11100
11666
  }
11101
- 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;
11102
11668
  var init_index = __esm({
11103
11669
  "src/index.ts"() {
11104
11670
  "use strict";
@@ -11120,6 +11686,7 @@ var init_index = __esm({
11120
11686
  init_git_changes();
11121
11687
  init_git_hook_path();
11122
11688
  init_hook_installer();
11689
+ init_professional_conclusion();
11123
11690
  init_review_result_validator();
11124
11691
  init_contract_kernel();
11125
11692
  init_restructure();
@@ -11172,6 +11739,33 @@ var init_index = __esm({
11172
11739
  runners: []
11173
11740
  }
11174
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
+ ]);
11175
11769
  EMPTY_RELATION_FIELD_VALUES = /* @__PURE__ */ new Set(["\u65E0", "none", "n/a", "-"]);
11176
11770
  VALID_TC_STATUSES = /* @__PURE__ */ new Set(["created", "automated", "verified", "waived"]);
11177
11771
  VALID_CHAIN_TYPES = /* @__PURE__ */ new Set([
@@ -11216,7 +11810,7 @@ var init_index = __esm({
11216
11810
 
11217
11811
  // src/packet-prompt-audit.ts
11218
11812
  import { mkdir as mkdir6, writeFile as writeFile4 } from "fs/promises";
11219
- import { join as join11 } from "path";
11813
+ import { join as join12 } from "path";
11220
11814
  function promptFilename(target) {
11221
11815
  return `prompt-${target.type}-${target.id}.md`;
11222
11816
  }
@@ -11268,7 +11862,7 @@ async function auditSinglePromptTarget(target, graph, options) {
11268
11862
  }
11269
11863
  if (options.outDir) {
11270
11864
  const filename = promptFilename(target);
11271
- const outPath = join11(options.outDir, filename);
11865
+ const outPath = join12(options.outDir, filename);
11272
11866
  await writeFile4(outPath, prompt, "utf-8");
11273
11867
  entry.outputPath = outPath;
11274
11868
  }
@@ -11374,9 +11968,9 @@ async function auditPromptBatch(root, targets, options, graph) {
11374
11968
  };
11375
11969
  if (options.outDir) {
11376
11970
  await mkdir6(options.outDir, { recursive: true });
11377
- const jsonPath = join11(options.outDir, "prompt-audit-summary.json");
11971
+ const jsonPath = join12(options.outDir, "prompt-audit-summary.json");
11378
11972
  await writeFile4(jsonPath, JSON.stringify(summary, null, 2) + "\n", "utf-8");
11379
- const mdPath = join11(options.outDir, "prompt-audit-summary.md");
11973
+ const mdPath = join12(options.outDir, "prompt-audit-summary.md");
11380
11974
  await writeFile4(mdPath, renderPromptAuditSummaryMarkdown(summary), "utf-8");
11381
11975
  }
11382
11976
  return summary;
@@ -11418,7 +12012,7 @@ __export(refactor_id_exports, {
11418
12012
  });
11419
12013
  import { chmod as chmod2, readFile as readFile5, rename as rename2, rm, readdir as readdir4, stat as stat2, writeFile as writeFile5 } from "fs/promises";
11420
12014
  import { randomBytes } from "crypto";
11421
- import { basename as basename5, dirname as dirname7, join as join12, relative as relative5 } from "path";
12015
+ import { basename as basename6, dirname as dirname8, join as join13, relative as relative5 } from "path";
11422
12016
  import yaml2 from "js-yaml";
11423
12017
  function escapeRegExp2(value) {
11424
12018
  return value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
@@ -11596,7 +12190,7 @@ async function walkTextFiles(root) {
11596
12190
  for (const entry of entries) {
11597
12191
  if (entry.name.startsWith(".") && PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
11598
12192
  if (PROSE_SCAN_SKIP_DIRS.has(entry.name)) continue;
11599
- const full = join12(dir, entry.name);
12193
+ const full = join13(dir, entry.name);
11600
12194
  if (entry.isDirectory()) {
11601
12195
  await visit(full);
11602
12196
  } else if (entry.isFile()) {
@@ -11611,7 +12205,7 @@ async function walkTextFiles(root) {
11611
12205
  return found.sort();
11612
12206
  }
11613
12207
  async function computeLockImpact(root, type, oldId) {
11614
- const lockPath = join12(root, VERSION_LOCK_PATH);
12208
+ const lockPath = join13(root, VERSION_LOCK_PATH);
11615
12209
  const impact = {
11616
12210
  lockPath: VERSION_LOCK_PATH,
11617
12211
  affectedImplementationLocks: [],
@@ -11703,7 +12297,7 @@ async function refactorId(options) {
11703
12297
  const fileContents = /* @__PURE__ */ new Map();
11704
12298
  const readArtifactFile = async (path) => {
11705
12299
  if (!fileContents.has(path)) {
11706
- fileContents.set(path, await readFile5(join12(root, path), "utf-8"));
12300
+ fileContents.set(path, await readFile5(join13(root, path), "utf-8"));
11707
12301
  }
11708
12302
  return fileContents.get(path);
11709
12303
  };
@@ -11779,7 +12373,7 @@ async function refactorId(options) {
11779
12373
  for (const relativePath of await walkTextFiles(root)) {
11780
12374
  if (relativePath === VERSION_LOCK_PATH) continue;
11781
12375
  if (relativePath === "artifact-graph.config.yaml") continue;
11782
- const raw = await readFile5(join12(root, relativePath), "utf-8");
12376
+ const raw = await readFile5(join13(root, relativePath), "utf-8");
11783
12377
  if (!containsIdToken(raw, oldId)) continue;
11784
12378
  const lines = raw.split(/\r?\n/);
11785
12379
  lines.forEach((line, index) => {
@@ -11855,7 +12449,7 @@ async function refactorId(options) {
11855
12449
  }
11856
12450
  if (options.__beforeWriteVerify) await options.__beforeWriteVerify();
11857
12451
  for (const path of targetFiles) {
11858
- const disk = await readFile5(join12(root, path), "utf-8");
12452
+ const disk = await readFile5(join13(root, path), "utf-8");
11859
12453
  if (disk !== fileContents.get(path)) {
11860
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 });
11861
12455
  }
@@ -11866,7 +12460,7 @@ async function refactorId(options) {
11866
12460
  const tempPathFor = options.__tempPathFor ?? ((targetPath) => {
11867
12461
  tempSequence += 1;
11868
12462
  const suffix = randomBytes(4).toString("hex");
11869
- return join12(dirname7(targetPath), `.${basename5(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
12463
+ return join13(dirname8(targetPath), `.${basename6(targetPath)}.${process.pid}.${tempSequence}.${suffix}.refactor-id.tmp`);
11870
12464
  });
11871
12465
  let stage = "write";
11872
12466
  try {
@@ -11875,8 +12469,8 @@ async function refactorId(options) {
11875
12469
  if (options.__injectWriteFailure?.(path)) {
11876
12470
  throw Object.assign(new Error(`injected write failure: ${path}`), { code: "EINJECTED" });
11877
12471
  }
11878
- const original = fileContents.has(path) ? fileContents.get(path) : await readFile5(join12(root, path), "utf-8");
11879
- const targetPath = join12(root, path);
12472
+ const original = fileContents.has(path) ? fileContents.get(path) : await readFile5(join13(root, path), "utf-8");
12473
+ const targetPath = join13(root, path);
11880
12474
  const originalMode = (await stat2(targetPath)).mode & 4095;
11881
12475
  const tempPath = tempPathFor(targetPath);
11882
12476
  await writeFile5(tempPath, newContents.get(path), { encoding: "utf-8", flag: "wx" });
@@ -11899,8 +12493,8 @@ async function refactorId(options) {
11899
12493
  if (options.__injectRollbackFailure?.(entry.path)) {
11900
12494
  throw Object.assign(new Error(`injected rollback failure: ${entry.path}`), { code: "EROLLBACKINJECTED" });
11901
12495
  }
11902
- await writeFile5(join12(root, entry.path), entry.original, "utf-8");
11903
- await chmod2(join12(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);
11904
12498
  } catch (rollbackError) {
11905
12499
  rollbackErrors.push({ path: entry.path, message: rollbackError.message });
11906
12500
  }
@@ -12033,8 +12627,8 @@ __export(cli_exports, {
12033
12627
  });
12034
12628
  import yaml3 from "js-yaml";
12035
12629
  import { realpathSync as realpathSync2 } from "fs";
12036
- import { access as access2, mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
12037
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join13 } from "path";
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";
12038
12632
  import { fileURLToPath as fileURLToPath3 } from "url";
12039
12633
  async function runCli(argv, io = {}) {
12040
12634
  const parsed = parseArgs(argv);
@@ -12062,7 +12656,7 @@ async function runCli(argv, io = {}) {
12062
12656
  switch (parsed.command) {
12063
12657
  case "init": {
12064
12658
  await initConfig(root);
12065
- out(`Created ${join13(root, "artifact-graph.config.yaml")}
12659
+ out(`Created ${join14(root, "artifact-graph.config.yaml")}
12066
12660
  `);
12067
12661
  return 0;
12068
12662
  }
@@ -12075,6 +12669,53 @@ async function runCli(argv, io = {}) {
12075
12669
  `);
12076
12670
  return 0;
12077
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
+ }
12078
12719
  case "validate": {
12079
12720
  const includes = new Set(
12080
12721
  typeof parsed.flags.include === "string" ? parsed.flags.include.split(",") : []
@@ -13081,7 +13722,7 @@ async function runCli(argv, io = {}) {
13081
13722
  err("Usage: artifact-graph validate-review-result --file <path> [--format json]\n");
13082
13723
  return 1;
13083
13724
  }
13084
- const resolvedPath = isAbsolute6(filePath) ? filePath : join13(root, filePath);
13725
+ const resolvedPath = isAbsolute7(filePath) ? filePath : join14(root, filePath);
13085
13726
  let content;
13086
13727
  try {
13087
13728
  content = await readFile6(resolvedPath, "utf-8");
@@ -13119,7 +13760,7 @@ async function runCli(argv, io = {}) {
13119
13760
  const deterministic = checkMode || parsed.flags.deterministic === true;
13120
13761
  const registry = await generateE2eRegistry(root, { deterministic });
13121
13762
  const output = JSON.stringify(registry, null, 2) + "\n";
13122
- const outPath = typeof parsed.flags.out === "string" ? parsed.flags.out : join13(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");
13123
13764
  if (checkMode) {
13124
13765
  let existing = "";
13125
13766
  try {
@@ -13171,7 +13812,7 @@ async function runCli(argv, io = {}) {
13171
13812
  `);
13172
13813
  return 1;
13173
13814
  }
13174
- const planPath = isAbsolute6(planFlag) ? planFlag : join13(cwd, planFlag);
13815
+ const planPath = isAbsolute7(planFlag) ? planFlag : join14(cwd, planFlag);
13175
13816
  let planDocument;
13176
13817
  try {
13177
13818
  planDocument = JSON.parse(await readFile6(planPath, "utf8"));
@@ -13238,7 +13879,7 @@ async function runCli(argv, io = {}) {
13238
13879
  `);
13239
13880
  return 1;
13240
13881
  }
13241
- const resolvedInput = isAbsolute6(inputPath) ? inputPath : join13(cwd, inputPath);
13882
+ const resolvedInput = isAbsolute7(inputPath) ? inputPath : join14(cwd, inputPath);
13242
13883
  let input;
13243
13884
  try {
13244
13885
  input = JSON.parse(await readFile6(resolvedInput, "utf8"));
@@ -13266,8 +13907,8 @@ async function runCli(argv, io = {}) {
13266
13907
  `);
13267
13908
  return 1;
13268
13909
  }
13269
- const packageDir = dirname8(fileURLToPath3(import.meta.url));
13270
- const contractsDir = typeof parsed.flags["contracts-dir"] === "string" ? parsed.flags["contracts-dir"] : join13(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");
13271
13912
  const revisionDigest = typeof parsed.flags["revision-digest"] === "string" ? parsed.flags["revision-digest"] : void 0;
13272
13913
  async function resolveContract(contractId) {
13273
13914
  const catalog = await loadContractCatalog(contractsDir);
@@ -13580,9 +14221,9 @@ function isGraphRelevantPath(path, schema) {
13580
14221
  return path === "artifact-graph.config.yaml" || path === VERSION_LOCK_PATH || matchesConfiguredArtifactPath(path, schema);
13581
14222
  }
13582
14223
  async function initConfig(root) {
13583
- const configPath = join13(root, "artifact-graph.config.yaml");
14224
+ const configPath = join14(root, "artifact-graph.config.yaml");
13584
14225
  try {
13585
- await access2(configPath);
14226
+ await access3(configPath);
13586
14227
  throw new Error(`Config already exists: ${configPath}`);
13587
14228
  } catch (error) {
13588
14229
  if (error.code !== "ENOENT") {
@@ -13634,9 +14275,9 @@ function parseTimeViewFlag(value, err) {
13634
14275
  }
13635
14276
  async function readReleaseInput(root, value) {
13636
14277
  if (value.includes(",")) return value.split(",");
13637
- const candidate = isAbsolute6(value) ? value : join13(root, value);
14278
+ const candidate = isAbsolute7(value) ? value : join14(root, value);
13638
14279
  try {
13639
- await access2(candidate);
14280
+ await access3(candidate);
13640
14281
  } catch {
13641
14282
  return [value];
13642
14283
  }
@@ -13655,6 +14296,12 @@ Commands:
13655
14296
  init
13656
14297
  scan
13657
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.
13658
14305
  query [<target> | --from <code>] [--to <code>] [--depth <n>] [--view current|planned|history|all] [--format json]
13659
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]
13660
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]
@@ -13742,6 +14389,7 @@ var init_cli = __esm({
13742
14389
  init_git_hook_path();
13743
14390
  init_hook_installer();
13744
14391
  init_versioned_traceability();
14392
+ init_professional_conclusion();
13745
14393
  if (isCliEntrypoint(process.argv[1])) {
13746
14394
  void runCli(process.argv.slice(2)).then((code) => {
13747
14395
  process.exitCode = code;