archctx-contracts 0.17.0 → 0.18.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.
Files changed (119) hide show
  1. package/fixtures/invalid/projection-result-applied-incomplete-coverage.json +3 -3
  2. package/fixtures/valid/archctx-capabilities.json +2 -2
  3. package/fixtures/valid/flow-selector-check.json +1 -1
  4. package/fixtures/valid/product-version-manifest.json +5 -11
  5. package/fixtures/valid/projection-manifest.json +1 -1
  6. package/fixtures/valid/projection-result.json +3 -3
  7. package/package.json +4 -1
  8. package/schemas/repo/refactor-decision.schema.json +283 -37
  9. package/schemas/runtime/archctx-capabilities.schema.json +144 -20
  10. package/schemas/runtime/architecture-debt-delta.schema.json +58 -19
  11. package/schemas/runtime/architecture-debt.schema.json +42 -42
  12. package/schemas/runtime/architecture-event.schema.json +1 -1
  13. package/schemas/runtime/architecture-history.schema.json +354 -0
  14. package/schemas/runtime/capability-dependencies.schema.json +266 -59
  15. package/schemas/runtime/cli-check.schema.json +197 -0
  16. package/schemas/runtime/cli-help.schema.json +28 -0
  17. package/schemas/runtime/dependency-constraint-evaluation.schema.json +67 -68
  18. package/schemas/runtime/docs-anchors.schema.json +250 -67
  19. package/schemas/runtime/doctor-code-facts.schema.json +49 -0
  20. package/schemas/runtime/evidence-binding.schema.json +1 -1
  21. package/schemas/runtime/flow-selector-check.schema.json +179 -46
  22. package/schemas/runtime/hook-debt-checkpoint.schema.json +12 -12
  23. package/schemas/runtime/index-seed.schema.json +56 -0
  24. package/schemas/runtime/path-context.schema.json +108 -0
  25. package/schemas/runtime/product-version-manifest.schema.json +142 -54
  26. package/schemas/runtime/projection-apply-readback.schema.json +2 -2
  27. package/schemas/runtime/projection-apply-recovery.schema.json +1 -1
  28. package/schemas/runtime/projection-result.schema.json +1 -1
  29. package/schemas/runtime/projection-slice.schema.json +34 -34
  30. package/schemas/runtime/recommendation-v3.schema.json +372 -1
  31. package/schemas/runtime/ref-impact-batch-request.schema.json +20 -7
  32. package/schemas/runtime/ref-impact-batch.schema.json +83 -13
  33. package/schemas/runtime/ref-impact.schema.json +68 -61
  34. package/schemas/runtime/refactor-scan-v2.schema.json +434 -0
  35. package/schemas/runtime/refactor-simulate.schema.json +505 -0
  36. package/schemas/runtime/refactor-verify-v2.schema.json +172 -0
  37. package/schemas/runtime/resolve-path.schema.json +69 -0
  38. package/schemas/runtime/runtime-recommendation-show.schema.json +531 -2
  39. package/schemas/runtime/runtime-refactor-scan.schema.json +498 -2
  40. package/schemas/runtime/runtime-verify.schema.json +274 -56
  41. package/schemas/runtime/state-machine-check.schema.json +357 -89
  42. package/schemas/runtime/structural-observation-payload.schema.json +372 -1
  43. package/schemas/runtime/sync-check.schema.json +65 -0
  44. package/src/architecture-debt.ts +125 -38
  45. package/src/architecture-history.ts +168 -42
  46. package/src/architecture.ts +100 -0
  47. package/src/cli-read.ts +228 -0
  48. package/src/docs-anchors.ts +105 -50
  49. package/src/explorer-occurrence-ports.ts +175 -0
  50. package/src/explorer-query-ports.ts +270 -0
  51. package/src/failure.ts +3 -0
  52. package/src/index-seed.ts +42 -0
  53. package/src/index.ts +5 -0
  54. package/src/ledger-records.ts +262 -0
  55. package/src/ledger.ts +27 -566
  56. package/src/ownership-dependencies.ts +115 -5
  57. package/src/ports.ts +12 -543
  58. package/src/product-version.ts +75 -56
  59. package/src/projection-apply-types.ts +216 -0
  60. package/src/projection-apply-validators.ts +355 -0
  61. package/src/projection-capabilities.ts +181 -0
  62. package/src/projection-constants.ts +317 -0
  63. package/src/projection-manifest-types.ts +298 -0
  64. package/src/projection-manifest.ts +12 -299
  65. package/src/projection-recovery-validators.ts +229 -0
  66. package/src/projection-request-validators.ts +326 -0
  67. package/src/projection-types.ts +365 -0
  68. package/src/projection-validation-helpers.ts +15 -0
  69. package/src/projection.ts +7 -1689
  70. package/src/ref-impact.ts +225 -33
  71. package/src/refactor-constants.ts +213 -0
  72. package/src/refactor-decision-validators.ts +350 -0
  73. package/src/refactor-evidence-types.ts +286 -0
  74. package/src/refactor-observation-validators.ts +359 -0
  75. package/src/refactor-resolution-validators.ts +229 -0
  76. package/src/refactor-snapshot-validators.ts +368 -0
  77. package/src/refactor-types.ts +270 -0
  78. package/src/refactor-v2.ts +389 -0
  79. package/src/refactor-validation-helpers.ts +195 -0
  80. package/src/refactor.ts +7 -1849
  81. package/src/review-guards.ts +3 -23
  82. package/src/runtime-verify.ts +87 -0
  83. package/src/schema-kit.ts +183 -0
  84. package/src/schema-registry.ts +73 -0
  85. package/src/schema.ts +0 -4
  86. package/src/state-machine-schemas.ts +192 -0
  87. package/src/state-machine-types.ts +188 -0
  88. package/src/state-machine.ts +9 -189
  89. package/fixtures/boundary/agent-job-expired.json +0 -33
  90. package/fixtures/invalid/adapter-fidelity-reverse-sync.json +0 -9
  91. package/fixtures/invalid/agent-job-direct-mutation.json +0 -32
  92. package/fixtures/invalid/cloud-egress-envelope-private-field.json +0 -12
  93. package/fixtures/invalid/investigation-report-direct-mutation.json +0 -38
  94. package/fixtures/invalid/investigation-report-missing-proposed-delta.json +0 -19
  95. package/fixtures/invalid/notification-event-code-field.json +0 -11
  96. package/fixtures/valid/adapter-fidelity.json +0 -9
  97. package/fixtures/valid/agent-job.json +0 -33
  98. package/fixtures/valid/architecture-candidate-delta-policy.json +0 -45
  99. package/fixtures/valid/architecture-candidate-delta.json +0 -188
  100. package/fixtures/valid/chatgpt-ga-tool.json +0 -9
  101. package/fixtures/valid/cloud-egress-envelope.json +0 -11
  102. package/fixtures/valid/entitlement.json +0 -12
  103. package/fixtures/valid/investigation-report.json +0 -38
  104. package/fixtures/valid/likec4-mapping.json +0 -14
  105. package/fixtures/valid/notification-event.json +0 -10
  106. package/fixtures/valid/notification-provider.json +0 -12
  107. package/fixtures/valid/structurizr-mapping.json +0 -15
  108. package/schemas/cloud/cloud-egress-envelope.schema.json +0 -19
  109. package/schemas/cloud/entitlement.schema.json +0 -24
  110. package/schemas/integrations/adapter-fidelity.schema.json +0 -21
  111. package/schemas/integrations/chatgpt-ga-tool.schema.json +0 -25
  112. package/schemas/integrations/likec4-mapping.schema.json +0 -32
  113. package/schemas/integrations/structurizr-mapping.schema.json +0 -33
  114. package/schemas/runtime/agent-job.schema.json +0 -63
  115. package/schemas/runtime/architecture-candidate-delta-policy.schema.json +0 -129
  116. package/schemas/runtime/architecture-candidate-delta.schema.json +0 -386
  117. package/schemas/runtime/investigation-report.schema.json +0 -119
  118. package/schemas/runtime/notification-event.schema.json +0 -18
  119. package/schemas/runtime/notification-provider.schema.json +0 -26
@@ -0,0 +1,326 @@
1
+ import {
2
+ ARCHITECTURE_DOCS_PROJECTION_MANIFEST_PATH,
3
+ ARCHITECTURE_MAJOR_CHANGE_REASON_CODES,
4
+ PROJECTION_ARCHITECTURE_DEBT_COVERAGE_REASON_CODES,
5
+ PROJECTION_ARCHITECTURE_DEBT_REASON_CODES,
6
+ PROJECTION_COVERAGE_REASON_CODES,
7
+ PROJECTION_FRESHNESS_REASON_CODES,
8
+ PROJECTION_PRIOR_COMMITTED_APPLY_OPERATIONS,
9
+ PROJECTION_TARGET_CHANGE_BLOCKING_REASON_CODES,
10
+ PROJECTION_TARGET_CHANGE_PLANNED_ACTIONS,
11
+ PROJECTION_TARGET_CHANGE_REASON_CODES,
12
+ type ProjectionMode,
13
+ type ProjectionTargetChangeClassification,
14
+ type ProjectionTargetChangeReasonCode,
15
+ type Sha256Digest
16
+ } from "./projection-constants";
17
+ import type {
18
+ ProjectionArchitectureDebtV1,
19
+ ProjectionCoverageV1,
20
+ ProjectionFileResultV1,
21
+ ProjectionFreshnessV2,
22
+ ProjectionPriorCommittedApplyV1,
23
+ ProjectionRequestV1,
24
+ ProjectionTargetChangeV2
25
+ } from "./projection-types";
26
+ import type { ProjectionResultV3 } from "./projection-apply-types";
27
+ import { ISO_INSTANT, SHA256_DIGEST, sortedUniqueIssues } from "./projection-validation-helpers";
28
+ import { digestJson, isRepoRelativePosixPath, type Json } from "./schema";
29
+
30
+ export function projectionRequestInvariantIssues(input: ProjectionRequestV1): string[] {
31
+ const issues = [
32
+ ...sortedUniqueIssues("targets", input.targets),
33
+ ...sortedUniqueIssues("changedPaths", input.changedPaths),
34
+ ...(input.acceptedChange
35
+ ? [
36
+ ...sortedUniqueIssues("acceptedChange.reasonCodes", input.acceptedChange.reasonCodes),
37
+ ...sortedUniqueIssues("acceptedChange.affectedNodeIds", input.acceptedChange.affectedNodeIds)
38
+ ]
39
+ : [])
40
+ ];
41
+ if (input.targets.length === 0) issues.push("targets must contain at least one projection target");
42
+ if (!/^[a-zA-Z0-9_.:-]+$/.test(input.requestId)) issues.push("requestId must use the stable identifier character set");
43
+ if (input.mode === "adopt" && !input.adoptionPlanId) issues.push("adoptionPlanId is required when mode=adopt");
44
+ if (input.mode !== "adopt" && input.adoptionPlanId !== undefined) issues.push("adoptionPlanId is only allowed when mode=adopt");
45
+ if (input.acceptObservedMajorChange !== undefined) {
46
+ if (input.acceptObservedMajorChange !== true) issues.push("acceptObservedMajorChange must be true when present");
47
+ if (input.mode !== "apply" && input.mode !== "adopt") issues.push("acceptObservedMajorChange is only allowed when mode=apply or mode=adopt");
48
+ if (input.acceptedChange !== undefined) issues.push("acceptObservedMajorChange and acceptedChange are mutually exclusive");
49
+ }
50
+ if (input.acceptedChange) {
51
+ if (input.acceptedChange.changeSetId.trim() === "") issues.push("acceptedChange.changeSetId must not be empty");
52
+ if (input.acceptedChange.eventId.trim() === "") issues.push("acceptedChange.eventId must not be empty");
53
+ if (input.acceptedChange.reasonCodes.length === 0) issues.push("acceptedChange.reasonCodes must contain at least one reason");
54
+ if (input.acceptedChange.affectedNodeIds.length === 0) issues.push("acceptedChange.affectedNodeIds must contain at least one node");
55
+ const allowedReasons = new Set<string>(ARCHITECTURE_MAJOR_CHANGE_REASON_CODES);
56
+ for (const reason of input.acceptedChange.reasonCodes) {
57
+ if (!allowedReasons.has(reason)) issues.push(`acceptedChange.reasonCodes contains unsupported reason: ${reason}`);
58
+ }
59
+ for (const nodeId of input.acceptedChange.affectedNodeIds) {
60
+ if (nodeId.trim() === "") issues.push("acceptedChange.affectedNodeIds must not contain empty node ids");
61
+ }
62
+ }
63
+ return issues;
64
+ }
65
+
66
+ /**
67
+ * Invariants that bind a result to the request mode that produced it, which the result itself does
68
+ * not carry: only a `plan` result previews what it would write (#264); `check`, `apply` and
69
+ * `adopt` results never carry `files[].preview`, whatever their status.
70
+ */
71
+ export function projectionResultRequestModeIssues(input: ProjectionResultV3, mode: ProjectionMode): string[] {
72
+ const issues: string[] = [];
73
+ if (mode !== "plan" && input.files.some((file) => file.preview !== undefined)) {
74
+ issues.push(`files[].preview is only allowed on a plan result, never when mode=${mode}`);
75
+ }
76
+ if (mode !== "check" && mode !== "plan" && input.architectureDebt !== undefined) {
77
+ issues.push(`architectureDebt is only allowed on a check or plan result, never when mode=${mode}`);
78
+ }
79
+ if (mode !== "check" && mode !== "plan" && input.changes !== undefined) {
80
+ issues.push(`changes is only allowed on a check or plan result, never when mode=${mode}`);
81
+ }
82
+ // The schema cannot condition on the request mode, so the presence promise is checked here.
83
+ if ((mode === "check" || mode === "plan") && input.changes === undefined) {
84
+ issues.push(`changes is required on every check or plan result, also when mode=${mode}`);
85
+ }
86
+ if (input.status === "planned-partial" && mode !== "check" && mode !== "plan") {
87
+ issues.push(`planned-partial is only allowed on a check or plan result, never when mode=${mode}`);
88
+ }
89
+ if (input.status === "applied-partial" && mode !== "apply") {
90
+ issues.push(`applied-partial is only allowed on an apply result, never when mode=${mode}`);
91
+ }
92
+ return issues;
93
+ }
94
+
95
+ /**
96
+ * Shape and canonical order of a partial result's `coverage`, and its binding to the result's
97
+ * files: a carried-forward target is never also a written file.
98
+ */
99
+ export function projectionCoverageIssues(input: ProjectionCoverageV1, files: readonly ProjectionFileResultV1[] = []): string[] {
100
+ const issues = [
101
+ ...sortedUniqueIssues("coverage.blockedCapabilityIds", input.blockedCapabilityIds),
102
+ ...sortedUniqueIssues("coverage.blockedTargets.targetId", input.blockedTargets.map((target) => target.targetId)),
103
+ ...sortedUniqueIssues("coverage.appliedTargetIds", input.appliedTargetIds)
104
+ ];
105
+ if (input.complete !== false) issues.push("coverage.complete must be false; a result that covers every target omits coverage");
106
+ if (input.blockedCapabilityIds.length === 0) issues.push("coverage.blockedCapabilityIds must name at least one capability");
107
+ if (input.blockedTargets.length === 0) issues.push("coverage.blockedTargets must name at least one target");
108
+ if (input.blockedCapabilityIds.some((id) => typeof id !== "string" || id.trim() === "")) issues.push("coverage.blockedCapabilityIds must not contain empty ids");
109
+ if (input.appliedTargetIds.some((id) => typeof id !== "string" || id.trim() === "")) issues.push("coverage.appliedTargetIds must not contain empty ids");
110
+ const blockedCapabilities = new Set(input.blockedCapabilityIds);
111
+ const blockingCapabilities = new Set<string>();
112
+ const blockedPaths = new Set<string>();
113
+ const reasons = new Set<string>(PROJECTION_COVERAGE_REASON_CODES);
114
+ for (const [index, target] of input.blockedTargets.entries()) {
115
+ const prefix = `coverage.blockedTargets[${index}]`;
116
+ if (typeof target.targetId !== "string" || target.targetId.trim() === "") issues.push(`${prefix}.targetId must not be empty`);
117
+ if (!isRepoRelativePosixPath(target.path)) issues.push(`${prefix}.path must be a repository-relative POSIX path`);
118
+ else if (blockedPaths.has(target.path)) issues.push(`${prefix}.path is named by another blocked target`);
119
+ blockedPaths.add(target.path);
120
+ issues.push(...sortedUniqueIssues(`${prefix}.capabilityIds`, target.capabilityIds), ...sortedUniqueIssues(`${prefix}.reasonCodes`, target.reasonCodes));
121
+ if (target.capabilityIds.length === 0) issues.push(`${prefix}.capabilityIds must name at least one capability`);
122
+ if (target.reasonCodes.length === 0) issues.push(`${prefix}.reasonCodes must name at least one reason`);
123
+ for (const capabilityId of target.capabilityIds) {
124
+ if (!blockedCapabilities.has(capabilityId)) issues.push(`${prefix}.capabilityIds names ${capabilityId}, which is not a blocked capability`);
125
+ blockingCapabilities.add(capabilityId);
126
+ }
127
+ const reason = target.reasonCodes.find((code) => !reasons.has(code));
128
+ if (reason !== undefined) issues.push(`${prefix}.reasonCodes contains unsupported reason: ${reason}`);
129
+ if (input.appliedTargetIds.includes(target.targetId)) issues.push(`${prefix}.targetId must not also be an applied target`);
130
+ }
131
+ for (const capabilityId of input.blockedCapabilityIds) {
132
+ if (!blockingCapabilities.has(capabilityId)) issues.push(`coverage.blockedCapabilityIds names ${capabilityId}, which blocks no target`);
133
+ }
134
+ for (const file of files) {
135
+ if (blockedPaths.has(file.path)) issues.push(`files[] must not write the carried-forward target path ${file.path}`);
136
+ }
137
+ return issues;
138
+ }
139
+
140
+ const TARGET_CHANGE_BLOCKING_REASONS = new Set<string>(PROJECTION_TARGET_CHANGE_BLOCKING_REASON_CODES);
141
+ const TARGET_CHANGE_UNKNOWN_REASONS = ["baseline-missing", "target-row-missing"] as const;
142
+ const TARGET_CHANGE_OUTPUT_REASONS = ["file-bytes-changed", "rendered-output-changed", "target-added", "target-removed"] as const;
143
+ const TARGET_CHANGE_PROOF_REASONS = ["flow-proof-changed", "selector-evidence-changed"] as const;
144
+ const TARGET_CHANGE_SEMANTIC_REASONS = ["model-digest-changed", "semantic-fingerprint-changed"] as const;
145
+
146
+ /**
147
+ * The one precedence rule of a target change: blocked > proof-change (`proofChanged === true`) >
148
+ * baseline-missing > semantic-change > output-change > unchanged. A known proof change is never
149
+ * hidden by an unknown comparison (a target without a committed row can still carry a moved flow
150
+ * proof); an unknown comparison outranks everything below the proof change and is never `unchanged`.
151
+ */
152
+ export function projectionTargetChangeClassification(
153
+ input: Pick<ProjectionTargetChangeV2, "reasonCodes" | "outputChanged" | "semanticChanged" | "proofChanged">
154
+ ): ProjectionTargetChangeClassification {
155
+ if (input.reasonCodes.some((code) => TARGET_CHANGE_BLOCKING_REASONS.has(code))) return "blocked";
156
+ if (input.proofChanged === true) return "proof-change";
157
+ if (input.semanticChanged === null || input.proofChanged === null) return "baseline-missing";
158
+ if (input.semanticChanged) return "semantic-change";
159
+ if (input.outputChanged) return "output-change";
160
+ return "unchanged";
161
+ }
162
+
163
+ /**
164
+ * Shape, canonical order and internal consistency of a result's `changes`, and their binding to its
165
+ * `files`: a change with a planned action names the `files[]` entry of its path with that action; a
166
+ * `files[]` entry a change names but does not plan is a path rejected for adoption or ownership
167
+ * repair, so that change is blocked by that rejection, and still reports the bytes that entry
168
+ * changes (`outputChanged`). Every `files[]` entry that changes a file has a change of its path,
169
+ * except the projection manifest, which is never a target.
170
+ *
171
+ * One entry per target: `targetId` is unique, and entries are ordered by path, then targetId. Only
172
+ * agent-context targets share a path, because several nodes' regions live in one contract file
173
+ * (ADR-0056 §9).
174
+ */
175
+ export function projectionTargetChangesIssues(input: readonly ProjectionTargetChangeV2[], files: readonly ProjectionFileResultV1[] = []): string[] {
176
+ const issues: string[] = new Set(input.map((entry) => entry.targetId)).size === input.length ? [] : ["changes.targetId must be unique"];
177
+ const order = (entry: ProjectionTargetChangeV2) => `${entry.path}\u0000${entry.targetId}`;
178
+ if (input.some((entry, index) => index > 0 && order(input[index - 1]!) >= order(entry))) issues.push("changes must be ordered by path, then targetId");
179
+ const targetIdsByPath = new Map<string, string[]>();
180
+ for (const entry of input) targetIdsByPath.set(entry.path, [...(targetIdsByPath.get(entry.path) ?? []), entry.targetId]);
181
+ for (const [path, targetIds] of targetIdsByPath) {
182
+ if (targetIds.length > 1 && targetIds.some((targetId) => !isAgentContextTargetId(targetId))) issues.push(`changes.path ${path} is shared by targets that are not all agent-context targets`);
183
+ }
184
+ const fileByPath = new Map(files.map((file) => [file.path, file]));
185
+ const reasons = new Set<string>(PROJECTION_TARGET_CHANGE_REASON_CODES);
186
+ for (const [index, entry] of input.entries()) {
187
+ const prefix = `changes[${index}]`;
188
+ const has = (codes: readonly string[]) => codes.some((code) => entry.reasonCodes.includes(code as ProjectionTargetChangeReasonCode));
189
+ if (typeof entry.targetId !== "string" || entry.targetId.trim() === "") issues.push(`${prefix}.targetId must not be empty`);
190
+ if (!isRepoRelativePosixPath(entry.path)) issues.push(`${prefix}.path must be a repository-relative POSIX path`);
191
+ issues.push(...sortedUniqueIssues(`${prefix}.affectedCapabilityIds`, entry.affectedCapabilityIds), ...sortedUniqueIssues(`${prefix}.reasonCodes`, entry.reasonCodes));
192
+ if (entry.affectedCapabilityIds.some((id) => typeof id !== "string" || id.trim() === "")) issues.push(`${prefix}.affectedCapabilityIds must not contain empty ids`);
193
+ const unsupported = entry.reasonCodes.find((code) => !reasons.has(code));
194
+ if (unsupported !== undefined) issues.push(`${prefix}.reasonCodes contains an unsupported code: ${unsupported}`);
195
+ for (const field of ["semanticChanged", "proofChanged"] as const) {
196
+ if (entry[field] !== null && typeof entry[field] !== "boolean") issues.push(`${prefix}.${field} must be a boolean or null`);
197
+ }
198
+ if (typeof entry.outputChanged !== "boolean") issues.push(`${prefix}.outputChanged must be a boolean`);
199
+ if (!(PROJECTION_TARGET_CHANGE_PLANNED_ACTIONS as readonly string[]).includes(entry.plannedAction)) issues.push(`${prefix}.plannedAction is unsupported`);
200
+ if ((entry.semanticChanged === true) !== has(TARGET_CHANGE_SEMANTIC_REASONS)) issues.push(`${prefix}.semanticChanged must be true exactly when semantic-fingerprint-changed or model-digest-changed is reported`);
201
+ if ((entry.proofChanged === true) !== has(TARGET_CHANGE_PROOF_REASONS)) issues.push(`${prefix}.proofChanged must be true exactly when flow-proof-changed or selector-evidence-changed is reported`);
202
+ if (entry.outputChanged !== has(TARGET_CHANGE_OUTPUT_REASONS)) issues.push(`${prefix}.outputChanged must be true exactly when an output reason code is reported`);
203
+ if ((entry.semanticChanged === null || entry.proofChanged === null) !== has(TARGET_CHANGE_UNKNOWN_REASONS)) {
204
+ issues.push(`${prefix} must report baseline-missing or target-row-missing exactly when a comparison is unknown`);
205
+ }
206
+ const derived = projectionTargetChangeClassification(entry);
207
+ if (entry.classification !== derived) issues.push(`${prefix}.classification must be ${derived} for its comparisons and reason codes`);
208
+ if ((entry.classification === "unchanged") !== (entry.reasonCodes.length === 0)) issues.push(`${prefix}.reasonCodes must be empty exactly when classification is unchanged`);
209
+ if (entry.classification === "unchanged" && entry.affectedCapabilityIds.length > 0) issues.push(`${prefix} is unchanged, so affectedCapabilityIds must be empty`);
210
+ if (entry.classification === "blocked" && entry.plannedAction !== "none") issues.push(`${prefix} is blocked, so plannedAction must be none`);
211
+ if (entry.plannedAction !== "none" && entry.outputChanged !== true) issues.push(`${prefix} writes its file, so outputChanged must be true`);
212
+ if (entry.path === ARCHITECTURE_DOCS_PROJECTION_MANIFEST_PATH) issues.push(`${prefix} names the projection manifest, which is not a target`);
213
+ const file = fileByPath.get(entry.path);
214
+ const fileAction = file === undefined || file.action === "unchanged" ? "none" : file.action;
215
+ const rejected = has(["adoption-required", "ambiguous-ownership"]);
216
+ if (entry.plannedAction !== fileAction && !(rejected && entry.plannedAction === "none" && fileAction === "update")) {
217
+ issues.push(`${prefix}.plannedAction must be ${fileAction}, the files[] action for ${entry.path}`);
218
+ }
219
+ // The file result proves the bytes change, whether or not this run may write them.
220
+ if (fileAction !== "none" && entry.outputChanged !== true) issues.push(`${prefix}.outputChanged must be true, the files[] entry for ${entry.path} changes its bytes`);
221
+ }
222
+ const changedPaths = new Set(input.map((entry) => entry.path));
223
+ for (const file of files) {
224
+ if (file.action === "unchanged" || file.path === ARCHITECTURE_DOCS_PROJECTION_MANIFEST_PATH || changedPaths.has(file.path)) continue;
225
+ issues.push(`changes must name the files[] ${file.action} of ${file.path}; only the projection manifest has none`);
226
+ }
227
+ return issues;
228
+ }
229
+
230
+ /** The targetId shape of an agent-context target: `projection_target.agent-context.<agents|claude>.<node>`. */
231
+ function isAgentContextTargetId(targetId: unknown): boolean {
232
+ return typeof targetId === "string" && /^projection_target\.agent-context\.(agents|claude)\.[^.]+$/.test(targetId);
233
+ }
234
+
235
+ export function projectionFreshnessIssues(input: ProjectionFreshnessV2): string[] {
236
+ const issues = [
237
+ ...sortedUniqueIssues("freshness.reasonCodes", input.reasonCodes),
238
+ ...sortedUniqueIssues("freshness.staleTargets.targetId", input.staleTargets.map((target) => target.targetId))
239
+ ];
240
+ const unsupported = input.reasonCodes.find((code) => !(PROJECTION_FRESHNESS_REASON_CODES as readonly string[]).includes(code));
241
+ if (unsupported) issues.push(`freshness.reasonCodes contains an unsupported code: ${unsupported}`);
242
+ if (input.ok !== (input.reasonCodes.length === 0)) issues.push("freshness.ok must be true exactly when reasonCodes is empty");
243
+ if ((input.staleTargets.length > 0) !== input.reasonCodes.includes("projection-output-changed")) {
244
+ issues.push("freshness.staleTargets must be non-empty exactly when projection-output-changed is reported");
245
+ }
246
+ for (const [index, target] of input.staleTargets.entries()) {
247
+ const prefix = `freshness.staleTargets[${index}]`;
248
+ if (target.targetId.trim() === "") issues.push(`${prefix}.targetId must not be empty`);
249
+ if (!isRepoRelativePosixPath(target.path)) issues.push(`${prefix}.path must be a repository-relative POSIX path`);
250
+ const digests = [target.committedOutputDigest, target.renderedOutputDigest];
251
+ if (digests.every((digest) => digest === null)) issues.push(`${prefix} must name at least one digest`);
252
+ else if (digests.some((digest) => digest !== null && !SHA256_DIGEST.test(digest))) issues.push(`${prefix} digests must be SHA-256 digests or null`);
253
+ else if (target.committedOutputDigest === target.renderedOutputDigest) issues.push(`${prefix} must name two different digests`);
254
+ }
255
+ return issues;
256
+ }
257
+
258
+ export function projectionArchitectureDebtIssues(input: ProjectionArchitectureDebtV1): string[] {
259
+ const issues = [
260
+ ...sortedUniqueIssues("architectureDebt.coverageReasonCodes", input.coverageReasonCodes),
261
+ ...sortedUniqueIssues("architectureDebt.items", input.items.map((item) => JSON.stringify([item.fromCapabilityId, item.toCapabilityId])))
262
+ ];
263
+ if (!(["complete", "partial", "unknown"] as const).includes(input.coverage)) issues.push("architectureDebt.coverage is unsupported");
264
+ const unsupported = input.coverageReasonCodes.find((code) => !(PROJECTION_ARCHITECTURE_DEBT_COVERAGE_REASON_CODES as readonly string[]).includes(code));
265
+ if (unsupported) issues.push(`architectureDebt.coverageReasonCodes contains an unsupported code: ${unsupported}`);
266
+ if ((input.coverage === "complete") !== (input.coverageReasonCodes.length === 0)) {
267
+ issues.push("architectureDebt.coverageReasonCodes must be empty exactly when coverage is complete");
268
+ }
269
+ if ((input.coverage === "unknown") !== input.coverageReasonCodes.includes("code-facts-unavailable")) {
270
+ issues.push("architectureDebt.coverage must be unknown exactly when code-facts-unavailable is reported");
271
+ }
272
+ if (input.coverage === "unknown" && input.items.length > 0) issues.push("architectureDebt.items must be empty when coverage is unknown");
273
+ for (const [index, item] of input.items.entries()) {
274
+ const prefix = `architectureDebt.items[${index}]`;
275
+ if (!(PROJECTION_ARCHITECTURE_DEBT_REASON_CODES as readonly string[]).includes(item.reasonCode)) issues.push(`${prefix}.reasonCode is unsupported`);
276
+ if (item.fromCapabilityId.trim() === "" || item.toCapabilityId.trim() === "") issues.push(`${prefix} must name two capabilities`);
277
+ else if (item.fromCapabilityId === item.toCapabilityId) issues.push(`${prefix} must name two different capabilities`);
278
+ if (!Number.isSafeInteger(item.importEdgeCount) || item.importEdgeCount < 1) issues.push(`${prefix}.importEdgeCount must be a positive integer`);
279
+ }
280
+ return issues;
281
+ }
282
+
283
+ export function projectionPriorCommittedAppliesIssues(
284
+ input: readonly ProjectionPriorCommittedApplyV1[],
285
+ requestId: string
286
+ ): string[] {
287
+ const issues = sortedUniqueIssues("priorCommittedApplies.changeSetId", input.map((entry) => entry.changeSetId));
288
+ if (input.length === 0) issues.push("priorCommittedApplies must be omitted instead of empty");
289
+ for (const [index, entry] of input.entries()) {
290
+ const prefix = `priorCommittedApplies[${index}]`;
291
+ issues.push(...sortedUniqueIssues(`${prefix}.files.path`, entry.files.map((file) => file.path)));
292
+ if (entry.requestId !== requestId) issues.push(`${prefix}.requestId must match the projection result requestId`);
293
+ if (entry.changeSetId.trim() === "") issues.push(`${prefix}.changeSetId must not be empty`);
294
+ if (!ISO_INSTANT.test(entry.committedAt)) issues.push(`${prefix}.committedAt must be an ISO-8601 UTC instant`);
295
+ if (entry.files.length === 0) issues.push(`${prefix}.files must name at least one committed file`);
296
+ if ((entry.applyId === undefined) !== (entry.lookupKey === undefined)) {
297
+ issues.push(`${prefix}.applyId and lookupKey must be present together or both absent`);
298
+ }
299
+ for (const field of ["applyId", "lookupKey"] as const) {
300
+ const value = entry[field];
301
+ if (value !== undefined && !SHA256_DIGEST.test(value)) issues.push(`${prefix}.${field} must be a SHA-256 digest`);
302
+ }
303
+ for (const [fileIndex, file] of entry.files.entries()) {
304
+ const filePrefix = `${prefix}.files[${fileIndex}]`;
305
+ if (!isRepoRelativePosixPath(file.path)) issues.push(`${filePrefix}.path must be a repository-relative POSIX path`);
306
+ if (!(PROJECTION_PRIOR_COMMITTED_APPLY_OPERATIONS as readonly string[]).includes(file.operation)) {
307
+ issues.push(`${filePrefix}.operation must be a supported committed operation`);
308
+ }
309
+ const expectsMissing = file.operation === "delete";
310
+ if (expectsMissing && file.hash !== "missing") issues.push(`${filePrefix}.hash must be "missing" for a delete`);
311
+ if (!expectsMissing && !SHA256_DIGEST.test(file.hash)) issues.push(`${filePrefix}.hash must be a SHA-256 body digest`);
312
+ }
313
+ }
314
+ return issues;
315
+ }
316
+
317
+ /**
318
+ * Computes the accepted projection receipt. Signal back-references are omitted from the
319
+ * receipt payload to avoid a circular hash; every signal must then bind that receipt via
320
+ * projectionReceiptDigest, which projectionResultInvariantIssues verifies.
321
+ */
322
+ export function projectionResultReceiptDigest(input: Omit<ProjectionResultV3, "receiptDigest">): Sha256Digest {
323
+ const { replayed: _replayed, written: _written, ...payload } = input;
324
+ const refreshSignals = payload.refreshSignals.map(({ projectionReceiptDigest: _projectionReceiptDigest, ...signal }) => signal);
325
+ return digestJson({ ...payload, refreshSignals } as unknown as Json) as Sha256Digest;
326
+ }