archctx-contracts 0.17.1 → 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 (112) hide show
  1. package/fixtures/valid/archctx-capabilities.json +2 -2
  2. package/fixtures/valid/product-version-manifest.json +4 -10
  3. package/package.json +4 -1
  4. package/schemas/repo/refactor-decision.schema.json +283 -37
  5. package/schemas/runtime/archctx-capabilities.schema.json +144 -20
  6. package/schemas/runtime/architecture-debt-delta.schema.json +58 -19
  7. package/schemas/runtime/architecture-debt.schema.json +42 -42
  8. package/schemas/runtime/architecture-event.schema.json +1 -1
  9. package/schemas/runtime/architecture-history.schema.json +354 -0
  10. package/schemas/runtime/capability-dependencies.schema.json +266 -59
  11. package/schemas/runtime/cli-check.schema.json +197 -0
  12. package/schemas/runtime/cli-help.schema.json +28 -0
  13. package/schemas/runtime/dependency-constraint-evaluation.schema.json +67 -68
  14. package/schemas/runtime/docs-anchors.schema.json +250 -67
  15. package/schemas/runtime/doctor-code-facts.schema.json +49 -0
  16. package/schemas/runtime/evidence-binding.schema.json +1 -1
  17. package/schemas/runtime/flow-selector-check.schema.json +179 -46
  18. package/schemas/runtime/hook-debt-checkpoint.schema.json +12 -12
  19. package/schemas/runtime/index-seed.schema.json +56 -0
  20. package/schemas/runtime/path-context.schema.json +108 -0
  21. package/schemas/runtime/product-version-manifest.schema.json +142 -54
  22. package/schemas/runtime/projection-slice.schema.json +34 -34
  23. package/schemas/runtime/recommendation-v3.schema.json +372 -1
  24. package/schemas/runtime/ref-impact-batch-request.schema.json +20 -7
  25. package/schemas/runtime/ref-impact-batch.schema.json +83 -13
  26. package/schemas/runtime/ref-impact.schema.json +68 -61
  27. package/schemas/runtime/refactor-scan-v2.schema.json +434 -0
  28. package/schemas/runtime/refactor-simulate.schema.json +505 -0
  29. package/schemas/runtime/refactor-verify-v2.schema.json +172 -0
  30. package/schemas/runtime/resolve-path.schema.json +69 -0
  31. package/schemas/runtime/runtime-recommendation-show.schema.json +531 -2
  32. package/schemas/runtime/runtime-refactor-scan.schema.json +498 -2
  33. package/schemas/runtime/runtime-verify.schema.json +274 -56
  34. package/schemas/runtime/state-machine-check.schema.json +357 -89
  35. package/schemas/runtime/structural-observation-payload.schema.json +372 -1
  36. package/schemas/runtime/sync-check.schema.json +65 -0
  37. package/src/architecture-debt.ts +125 -38
  38. package/src/architecture-history.ts +168 -42
  39. package/src/architecture.ts +100 -0
  40. package/src/cli-read.ts +228 -0
  41. package/src/docs-anchors.ts +105 -50
  42. package/src/explorer-occurrence-ports.ts +175 -0
  43. package/src/explorer-query-ports.ts +270 -0
  44. package/src/failure.ts +3 -0
  45. package/src/index-seed.ts +42 -0
  46. package/src/index.ts +5 -0
  47. package/src/ledger-records.ts +262 -0
  48. package/src/ledger.ts +27 -566
  49. package/src/ownership-dependencies.ts +115 -5
  50. package/src/ports.ts +6 -541
  51. package/src/product-version.ts +74 -55
  52. package/src/projection-apply-types.ts +216 -0
  53. package/src/projection-apply-validators.ts +355 -0
  54. package/src/projection-capabilities.ts +181 -0
  55. package/src/projection-constants.ts +317 -0
  56. package/src/projection-manifest-types.ts +298 -0
  57. package/src/projection-manifest.ts +12 -299
  58. package/src/projection-recovery-validators.ts +229 -0
  59. package/src/projection-request-validators.ts +326 -0
  60. package/src/projection-types.ts +365 -0
  61. package/src/projection-validation-helpers.ts +15 -0
  62. package/src/projection.ts +7 -1689
  63. package/src/ref-impact.ts +225 -33
  64. package/src/refactor-constants.ts +213 -0
  65. package/src/refactor-decision-validators.ts +350 -0
  66. package/src/refactor-evidence-types.ts +286 -0
  67. package/src/refactor-observation-validators.ts +359 -0
  68. package/src/refactor-resolution-validators.ts +229 -0
  69. package/src/refactor-snapshot-validators.ts +368 -0
  70. package/src/refactor-types.ts +270 -0
  71. package/src/refactor-v2.ts +389 -0
  72. package/src/refactor-validation-helpers.ts +195 -0
  73. package/src/refactor.ts +7 -1849
  74. package/src/review-guards.ts +3 -23
  75. package/src/runtime-verify.ts +87 -0
  76. package/src/schema-kit.ts +183 -0
  77. package/src/schema-registry.ts +73 -0
  78. package/src/schema.ts +0 -4
  79. package/src/state-machine-schemas.ts +192 -0
  80. package/src/state-machine-types.ts +188 -0
  81. package/src/state-machine.ts +9 -189
  82. package/fixtures/boundary/agent-job-expired.json +0 -33
  83. package/fixtures/invalid/adapter-fidelity-reverse-sync.json +0 -9
  84. package/fixtures/invalid/agent-job-direct-mutation.json +0 -32
  85. package/fixtures/invalid/cloud-egress-envelope-private-field.json +0 -12
  86. package/fixtures/invalid/investigation-report-direct-mutation.json +0 -38
  87. package/fixtures/invalid/investigation-report-missing-proposed-delta.json +0 -19
  88. package/fixtures/invalid/notification-event-code-field.json +0 -11
  89. package/fixtures/valid/adapter-fidelity.json +0 -9
  90. package/fixtures/valid/agent-job.json +0 -33
  91. package/fixtures/valid/architecture-candidate-delta-policy.json +0 -45
  92. package/fixtures/valid/architecture-candidate-delta.json +0 -188
  93. package/fixtures/valid/chatgpt-ga-tool.json +0 -9
  94. package/fixtures/valid/cloud-egress-envelope.json +0 -11
  95. package/fixtures/valid/entitlement.json +0 -12
  96. package/fixtures/valid/investigation-report.json +0 -38
  97. package/fixtures/valid/likec4-mapping.json +0 -14
  98. package/fixtures/valid/notification-event.json +0 -10
  99. package/fixtures/valid/notification-provider.json +0 -12
  100. package/fixtures/valid/structurizr-mapping.json +0 -15
  101. package/schemas/cloud/cloud-egress-envelope.schema.json +0 -19
  102. package/schemas/cloud/entitlement.schema.json +0 -24
  103. package/schemas/integrations/adapter-fidelity.schema.json +0 -21
  104. package/schemas/integrations/chatgpt-ga-tool.schema.json +0 -25
  105. package/schemas/integrations/likec4-mapping.schema.json +0 -32
  106. package/schemas/integrations/structurizr-mapping.schema.json +0 -33
  107. package/schemas/runtime/agent-job.schema.json +0 -63
  108. package/schemas/runtime/architecture-candidate-delta-policy.schema.json +0 -129
  109. package/schemas/runtime/architecture-candidate-delta.schema.json +0 -386
  110. package/schemas/runtime/investigation-report.schema.json +0 -119
  111. package/schemas/runtime/notification-event.schema.json +0 -18
  112. package/schemas/runtime/notification-provider.schema.json +0 -26
@@ -0,0 +1,355 @@
1
+ import {
2
+ ARCHITECTURE_MAJOR_CHANGE_REASON_CODES,
3
+ ARCHITECTURE_PROOF_P1_STATUSES,
4
+ ARCHITECTURE_PROOF_P2_STATUSES,
5
+ ARCHITECTURE_SEMANTIC_FACETS,
6
+ PROJECTION_APPLY_IDENTITY_SCHEMA_VERSION,
7
+ PROJECTION_FILE_PREVIEW_MAX_BYTES,
8
+ PROJECTION_HUMAN_ACTION_REASON_CODES,
9
+ PROJECTION_PARTIAL_RESULT_STATUSES,
10
+ PROJECTION_PREVIEW_TOTAL_MAX_BYTES,
11
+ PROJECTION_REQUEST_SCHEMA_VERSION,
12
+ PROJECTION_TARGETS,
13
+ type ProjectionFilePreviewFormat,
14
+ type Sha256Digest
15
+ } from "./projection-constants";
16
+ import type {
17
+ AcceptedArchitectureChangeReferenceV1,
18
+ ArchitectureCapabilityChangeV1,
19
+ ArchitectureCapabilityProofStatusV1,
20
+ ArchitectureRefreshSignalV2,
21
+ ProjectionApplyIdentityV1,
22
+ ProjectionExpectedSnapshotV1,
23
+ ProjectionFileResultV1,
24
+ ProjectionRequestV1
25
+ } from "./projection-types";
26
+ import type { ProjectionApplyAbsenceV1, ProjectionApplyReceiptV1, ProjectionResultV3 } from "./projection-apply-types";
27
+ import {
28
+ projectionArchitectureDebtIssues,
29
+ projectionCoverageIssues,
30
+ projectionFreshnessIssues,
31
+ projectionPriorCommittedAppliesIssues,
32
+ projectionRequestInvariantIssues,
33
+ projectionResultReceiptDigest,
34
+ projectionTargetChangesIssues
35
+ } from "./projection-request-validators";
36
+ import { SHA256_DIGEST, sortedUniqueIssues, utf8ByteLength } from "./projection-validation-helpers";
37
+ import { digestJson, isRepoRelativePosixPath, type Json } from "./schema";
38
+
39
+ export function projectionResultInvariantIssues(input: ProjectionResultV3): string[] {
40
+ const issues = [
41
+ ...sortedUniqueIssues("affectedNodeIds", input.affectedNodeIds),
42
+ ...sortedUniqueIssues("files.path", input.files.map((file) => file.path)),
43
+ ...sortedUniqueIssues("refreshSignals.signalId", input.refreshSignals.map((signal) => signal.signalId)),
44
+ ...input.humanActions.flatMap((action, index) => sortedUniqueIssues(`humanActions[${index}].affectedNodeIds`, action.affectedNodeIds)),
45
+ ...input.refreshSignals.flatMap((signal, index) => architectureRefreshSignalInvariantIssues(signal, `refreshSignals[${index}]`))
46
+ ];
47
+ if (!/^[a-zA-Z0-9_.:-]+$/.test(input.requestId)) issues.push("requestId must use the stable identifier character set");
48
+ if (input.inputSnapshot.repositoryId !== input.outputSnapshot.repositoryId) issues.push("outputSnapshot.repositoryId must match inputSnapshot.repositoryId");
49
+ if (input.inputSnapshot.workspaceId !== input.outputSnapshot.workspaceId) issues.push("outputSnapshot.workspaceId must match inputSnapshot.workspaceId");
50
+ if (input.inputSnapshot.baseHeadSha !== input.outputSnapshot.baseHeadSha) issues.push("outputSnapshot.baseHeadSha must match inputSnapshot.baseHeadSha");
51
+ const statusRequiresHumanAction = input.status === "adoption-required" || input.status === "human-action-required";
52
+ if (statusRequiresHumanAction && input.humanActions.length === 0) issues.push(`${input.status} status requires at least one human action`);
53
+ if (!statusRequiresHumanAction && input.humanActions.length > 0) issues.push(`human actions are not allowed when status=${input.status}`);
54
+ if (input.status === "applied-reconcile-required") {
55
+ if (!input.applyReceipt) issues.push("applied-reconcile-required status requires applyReceipt");
56
+ if (input.refreshSignals.length > 0) issues.push("applied-reconcile-required status cannot deliver refreshSignals");
57
+ }
58
+ const partial = (PROJECTION_PARTIAL_RESULT_STATUSES as readonly string[]).includes(input.status);
59
+ if (partial !== (input.coverage !== undefined)) issues.push("coverage must be present exactly when status is planned-partial or applied-partial");
60
+ if (input.coverage !== undefined) issues.push(...projectionCoverageIssues(input.coverage, input.files));
61
+ if (partial) {
62
+ // An incomplete projection is never an acceptance: it records no apply and signals no refresh.
63
+ if (input.applyReceipt !== undefined) issues.push(`${input.status} status never carries applyReceipt`);
64
+ if (input.refreshSignals.length > 0) issues.push(`${input.status} status carries no refreshSignals`);
65
+ }
66
+ const committedApply = input.applyReceipt !== undefined || input.status === "applied" || input.status === "applied-partial" || input.status === "applied-reconcile-required";
67
+ for (const [index, action] of input.humanActions.entries()) {
68
+ const prefix = `humanActions[${index}]`;
69
+ if (!(PROJECTION_HUMAN_ACTION_REASON_CODES as readonly string[]).includes(action.reasonCode)) issues.push(`${prefix}.reasonCode is unsupported`);
70
+ if ((action.reasonCode === "orphaned-document-review") !== (action.path !== undefined)) {
71
+ issues.push(`${prefix}.path must be present exactly when reasonCode=orphaned-document-review`);
72
+ }
73
+ if (action.path !== undefined && !isRepoRelativePosixPath(action.path)) issues.push(`${prefix}.path must be a repository-relative POSIX path`);
74
+ }
75
+ const orphanReviewPaths = input.humanActions.flatMap((action) => action.reasonCode === "orphaned-document-review" && action.path !== undefined ? [action.path] : []);
76
+ issues.push(...sortedUniqueIssues("humanActions[orphaned-document-review].path", orphanReviewPaths));
77
+ if (orphanReviewPaths.some((path) => input.files.some((file) => file.path === path))) {
78
+ issues.push("an orphaned-document-review path must not also be a files[] entry");
79
+ }
80
+ for (const [index, file] of input.files.entries()) {
81
+ const prefix = `files[${index}]`;
82
+ if (file.action === "create" && (file.preimageDigest !== null || file.outputDigest === null)) {
83
+ issues.push(`${prefix} create requires null preimageDigest and non-null outputDigest`);
84
+ }
85
+ if (file.action === "delete" && (file.preimageDigest === null || file.outputDigest !== null)) {
86
+ issues.push(`${prefix} delete requires non-null preimageDigest and null outputDigest`);
87
+ }
88
+ if (file.action === "update" && (file.preimageDigest === null || file.outputDigest === null || file.preimageDigest === file.outputDigest)) {
89
+ issues.push(`${prefix} update requires two different non-null digests`);
90
+ }
91
+ if (file.action === "unchanged" && (file.preimageDigest === null || file.outputDigest === null || file.preimageDigest !== file.outputDigest)) {
92
+ issues.push(`${prefix} unchanged requires equal non-null digests`);
93
+ }
94
+ if (file.preview !== undefined) issues.push(...projectionFilePreviewIssues(file, prefix));
95
+ }
96
+ const previewBytes = input.files.reduce((total, file) => total + (file.preview ? utf8ByteLength(file.preview.content) : 0), 0);
97
+ if (previewBytes > PROJECTION_PREVIEW_TOTAL_MAX_BYTES) {
98
+ issues.push(`files[].preview.content must not exceed ${PROJECTION_PREVIEW_TOTAL_MAX_BYTES} UTF-8 bytes in total`);
99
+ }
100
+ // The result does not carry its request mode; projectionResultRequestModeIssues binds a preview
101
+ // to mode=plan. On the result alone, a committed apply (and so a persisted receipt) never carries one.
102
+ if (input.files.some((file) => file.preview !== undefined) && committedApply) {
103
+ issues.push("files[].preview is only allowed on a plan result, never on a committed apply");
104
+ }
105
+ if (input.priorCommittedApplies) {
106
+ issues.push(...projectionPriorCommittedAppliesIssues(input.priorCommittedApplies, input.requestId));
107
+ }
108
+ if (input.freshness) issues.push(...projectionFreshnessIssues(input.freshness));
109
+ if (input.architectureDebt) {
110
+ issues.push(...projectionArchitectureDebtIssues(input.architectureDebt));
111
+ if (committedApply) {
112
+ issues.push("architectureDebt is only allowed on a check or plan result, never on a committed apply");
113
+ }
114
+ }
115
+ if (input.changes) {
116
+ issues.push(...projectionTargetChangesIssues(input.changes, input.files));
117
+ if (committedApply) issues.push("changes is only allowed on a check or plan result, never on a committed apply");
118
+ // A carried-forward target is blocked, by the same reasons its coverage entry names.
119
+ for (const target of input.coverage?.blockedTargets ?? []) {
120
+ const entry = input.changes.find((candidate) => candidate.targetId === target.targetId);
121
+ if (!entry || entry.classification !== "blocked" || target.reasonCodes.some((code) => !entry.reasonCodes.includes(code))) {
122
+ issues.push(`changes must classify the carried-forward target ${target.path} as blocked with its coverage reason codes`);
123
+ }
124
+ }
125
+ }
126
+ if (input.majorChangeAcceptance !== undefined) {
127
+ if (input.majorChangeAcceptance !== "declined-unprovable-proof") issues.push("majorChangeAcceptance is unsupported");
128
+ if (input.status !== "human-action-required"
129
+ || !input.humanActions.some((action) => action.reasonCode === "unprovable-required-flow")
130
+ || input.humanActions.some((action) => action.reasonCode === "unresolved-major-change")) {
131
+ issues.push("majorChangeAcceptance requires human-action-required with unprovable-required-flow in place of unresolved-major-change");
132
+ }
133
+ }
134
+ if (input.replayed !== undefined) {
135
+ if (input.replayed !== true) issues.push("replayed must be true when present");
136
+ if (!input.applyReceipt || (input.status !== "applied" && input.status !== "applied-reconcile-required")) {
137
+ issues.push("replayed is only allowed on a committed apply result with applyReceipt");
138
+ }
139
+ }
140
+ if ((input.replayed !== undefined) !== (input.written !== undefined)) issues.push("written must be present exactly when replayed is present");
141
+ if (input.written !== undefined && typeof input.written !== "boolean") issues.push("written must be a boolean when present");
142
+ const { receiptDigest, ...receiptPayload } = input;
143
+ if (projectionResultReceiptDigest(receiptPayload) !== receiptDigest) issues.push("receiptDigest must match the canonical projection result payload");
144
+ for (const [index, signal] of input.refreshSignals.entries()) {
145
+ const prefix = `refreshSignals[${index}]`;
146
+ if (signal.projectionReceiptDigest !== receiptDigest) issues.push(`${prefix}.projectionReceiptDigest must match receiptDigest`);
147
+ if (signal.repository.repositoryId !== input.outputSnapshot.repositoryId) issues.push(`${prefix}.repositoryId must match outputSnapshot.repositoryId`);
148
+ if (signal.worktree.workspaceId !== input.outputSnapshot.workspaceId) issues.push(`${prefix}.workspaceId must match outputSnapshot.workspaceId`);
149
+ if (signal.worktree.headSha !== input.outputSnapshot.headSha) issues.push(`${prefix}.headSha must match outputSnapshot.headSha`);
150
+ if (signal.worktree.worktreeDigest !== input.outputSnapshot.worktreeDigest) issues.push(`${prefix}.worktreeDigest must match outputSnapshot.worktreeDigest`);
151
+ }
152
+ return issues;
153
+ }
154
+
155
+ function projectionFilePreviewIssues(file: ProjectionFileResultV1, prefix: string): string[] {
156
+ const preview = file.preview!;
157
+ const issues: string[] = [];
158
+ const expectedFormat: ProjectionFilePreviewFormat | undefined = file.action === "create"
159
+ ? "body"
160
+ : file.action === "update" || file.action === "delete" ? "unified-diff" : undefined;
161
+ if (expectedFormat === undefined) issues.push(`${prefix}.preview is not allowed when action=${file.action}`);
162
+ else if (preview.format !== expectedFormat) issues.push(`${prefix}.preview.format must be ${expectedFormat} when action=${file.action}`);
163
+ if (typeof preview.content !== "string" || typeof preview.truncated !== "boolean"
164
+ || !Number.isSafeInteger(preview.byteLength) || preview.byteLength < 0) {
165
+ issues.push(`${prefix}.preview must carry string content, a boolean truncated flag and a non-negative integer byteLength`);
166
+ return issues;
167
+ }
168
+ const contentBytes = utf8ByteLength(preview.content);
169
+ if (contentBytes > PROJECTION_FILE_PREVIEW_MAX_BYTES) issues.push(`${prefix}.preview.content must not exceed ${PROJECTION_FILE_PREVIEW_MAX_BYTES} UTF-8 bytes`);
170
+ if (preview.truncated ? contentBytes >= preview.byteLength : contentBytes !== preview.byteLength) {
171
+ issues.push(`${prefix}.preview.truncated must be true exactly when content is shorter than byteLength`);
172
+ }
173
+ return issues;
174
+ }
175
+
176
+ export function projectionApplyLookupKey(input: {
177
+ repositoryId: string;
178
+ workspaceId: string;
179
+ acceptedChange: AcceptedArchitectureChangeReferenceV1;
180
+ }): Sha256Digest {
181
+ return digestJson({
182
+ schemaVersion: "archcontext.projection-apply-lookup/v1",
183
+ repositoryId: input.repositoryId,
184
+ workspaceId: input.workspaceId,
185
+ acceptedChange: input.acceptedChange
186
+ } as unknown as Json) as Sha256Digest;
187
+ }
188
+
189
+ export function createProjectionApplyIdentity(input: {
190
+ repositoryId: string;
191
+ workspaceId: string;
192
+ acceptedChange: AcceptedArchitectureChangeReferenceV1;
193
+ changeSetId: string;
194
+ idempotencyKey: string;
195
+ files: ProjectionFileResultV1[];
196
+ refreshSignals: ArchitectureRefreshSignalV2[];
197
+ }): ProjectionApplyIdentityV1 {
198
+ const lookupKey = projectionApplyLookupKey(input);
199
+ const ownedFilesDigest = digestJson(input.files as unknown as Json) as Sha256Digest;
200
+ const refreshSignals = input.refreshSignals.map(({ projectionReceiptDigest: _receipt, ...signal }) => signal);
201
+ const refreshSignalsDigest = digestJson(refreshSignals as unknown as Json) as Sha256Digest;
202
+ const withoutApplyId = {
203
+ schemaVersion: PROJECTION_APPLY_IDENTITY_SCHEMA_VERSION,
204
+ lookupKey,
205
+ repositoryId: input.repositoryId,
206
+ workspaceId: input.workspaceId,
207
+ acceptedChange: input.acceptedChange,
208
+ semanticCommit: { changeSetId: input.changeSetId, idempotencyKey: input.idempotencyKey },
209
+ ownedFilesDigest,
210
+ refreshSignalsDigest
211
+ };
212
+ return {
213
+ ...withoutApplyId,
214
+ applyId: digestJson(withoutApplyId as unknown as Json) as Sha256Digest
215
+ };
216
+ }
217
+
218
+ /** Readback carries the original accepted apply request, never caller-authored receipt data. */
219
+ export function projectionApplyReadbackRequestInvariantIssues(request: ProjectionRequestV1): string[] {
220
+ const issues = projectionRequestInvariantIssues(request);
221
+ const allowed = new Set(["schemaVersion", "requestId", "profile", "mode", "targets", "changedPaths", "expected", "acceptedChange"]);
222
+ if (Object.keys(request).some((key) => !allowed.has(key))) issues.push("readback request contains unsupported fields");
223
+ if (request.mode !== "apply" || !request.acceptedChange) issues.push("readback requires an accepted apply request");
224
+ if (request.schemaVersion !== PROJECTION_REQUEST_SCHEMA_VERSION || request.profile !== "repo-harness/v1") issues.push("readback request protocol is invalid");
225
+ if (typeof request.requestId !== "string"
226
+ || request.targets.some((target) => !(PROJECTION_TARGETS as readonly string[]).includes(target))
227
+ || request.changedPaths.some((path) => typeof path !== "string" || !isRepoRelativePosixPath(path))) issues.push("readback request fields are invalid");
228
+ const expectedKeys = ["repositoryId", "workspaceId", "headSha", "worktreeDigest"];
229
+ if (Object.keys(request.expected).some((key) => !expectedKeys.includes(key))
230
+ || expectedKeys.some((key) => typeof request.expected[key as keyof ProjectionExpectedSnapshotV1] !== "string")
231
+ || !request.expected.repositoryId || !request.expected.workspaceId
232
+ || !/^[a-f0-9]{40}$/.test(request.expected.headSha)
233
+ || !SHA256_DIGEST.test(request.expected.worktreeDigest)) issues.push("readback expected snapshot is invalid");
234
+ if (request.acceptedChange && Object.keys(request.acceptedChange).some((key) => !["changeSetId", "eventId", "reasonCodes", "affectedNodeIds"].includes(key))) {
235
+ issues.push("readback accepted change contains unsupported fields");
236
+ }
237
+ return issues;
238
+ }
239
+
240
+ /**
241
+ * The readback request for a committed apply receipt, built only from what the receipt recorded:
242
+ * its requestId, the recovery binding's targets, changedPaths and original expected snapshot, and
243
+ * the identity's accepted change. Readback always takes `mode: "apply"`, also for an adopt receipt,
244
+ * because the binding never records the mode. A caller that held only `acceptObservedMajorChange`
245
+ * never had the accepted change, so `AC_PROJECTION_APPLY_COMMITTED` hands it this request (#278).
246
+ * Undefined for a receipt without a recovery binding, which readback cannot prove.
247
+ */
248
+ export function projectionApplyReadbackRequestFromReceipt(receipt: ProjectionApplyReceiptV1): ProjectionRequestV1 | undefined {
249
+ const binding = receipt.recovery;
250
+ if (!binding) return undefined;
251
+ return {
252
+ schemaVersion: PROJECTION_REQUEST_SCHEMA_VERSION,
253
+ requestId: receipt.result.requestId,
254
+ profile: "repo-harness/v1",
255
+ mode: "apply",
256
+ targets: [...binding.targets],
257
+ changedPaths: [...binding.changedPaths],
258
+ expected: { ...binding.originalExpectedSnapshot },
259
+ acceptedChange: {
260
+ ...receipt.identity.acceptedChange,
261
+ reasonCodes: [...receipt.identity.acceptedChange.reasonCodes],
262
+ affectedNodeIds: [...receipt.identity.acceptedChange.affectedNodeIds]
263
+ }
264
+ };
265
+ }
266
+
267
+ export function projectionApplyAbsenceInvariantIssues(input: ProjectionApplyAbsenceV1, request: ProjectionRequestV1): string[] {
268
+ const issues = projectionApplyReadbackRequestInvariantIssues(request);
269
+ if (input.schemaVersion !== "archcontext.projection-apply-absence/v1") issues.push("absence schemaVersion is invalid");
270
+ if (Object.keys(input).some((key) => !["schemaVersion", "requestId", "requestDigest", "lookupKey", "current", "absenceDigest"].includes(key))) issues.push("absence contains unsupported fields");
271
+ const { absenceDigest, ...body } = input;
272
+ if (absenceDigest !== digestJson(body as unknown as Json)) issues.push("absenceDigest must bind the complete absence result");
273
+ if (input.requestId !== request.requestId || input.requestDigest !== digestJson(request as unknown as Json)) issues.push("absence request identity mismatch");
274
+ if (digestJson(input.current as unknown as Json) !== digestJson(request.expected as unknown as Json)) issues.push("absence current snapshot differs from request");
275
+ if (!request.acceptedChange || input.lookupKey !== projectionApplyLookupKey({
276
+ repositoryId: request.expected.repositoryId, workspaceId: request.expected.workspaceId, acceptedChange: request.acceptedChange
277
+ })) issues.push("absence lookup identity mismatch");
278
+ return issues;
279
+ }
280
+
281
+ export function architectureRefreshSignalInvariantIssues(input: ArchitectureRefreshSignalV2, prefix = "signal"): string[] {
282
+ const issues = [
283
+ ...sortedUniqueIssues(`${prefix}.reasonCodes`, input.reasonCodes),
284
+ ...sortedUniqueIssues(`${prefix}.affectedNodeIds`, input.affectedNodeIds),
285
+ ...sortedUniqueIssues(`${prefix}.refreshTargets`, input.refreshTargets)
286
+ ];
287
+ if (input.acceptedChange) {
288
+ issues.push(
289
+ ...sortedUniqueIssues(`${prefix}.acceptedChange.reasonCodes`, input.acceptedChange.reasonCodes),
290
+ ...sortedUniqueIssues(`${prefix}.acceptedChange.affectedNodeIds`, input.acceptedChange.affectedNodeIds)
291
+ );
292
+ if (input.acceptedChange.changeSetId.trim() === "") issues.push(`${prefix}.acceptedChange.changeSetId must not be empty`);
293
+ if (input.acceptedChange.eventId.trim() === "") issues.push(`${prefix}.acceptedChange.eventId must not be empty`);
294
+ if (input.acceptedChange.reasonCodes.join("\u0000") !== input.reasonCodes.join("\u0000")) {
295
+ issues.push(`${prefix}.acceptedChange.reasonCodes must match signal reasonCodes`);
296
+ }
297
+ if (input.acceptedChange.affectedNodeIds.join("\u0000") !== input.affectedNodeIds.join("\u0000")) {
298
+ issues.push(`${prefix}.acceptedChange.affectedNodeIds must match signal affectedNodeIds`);
299
+ }
300
+ }
301
+ if (input.capabilities !== undefined) issues.push(...architectureCapabilityChangesIssues(input.capabilities, `${prefix}.capabilities`));
302
+ if (input.reasonCodes.length === 0) issues.push(`${prefix}.reasonCodes must contain at least one reason`);
303
+ if (input.affectedNodeIds.length === 0) issues.push(`${prefix}.affectedNodeIds must contain at least one node`);
304
+ if (input.refreshTargets.length === 0) issues.push(`${prefix}.refreshTargets must contain at least one target`);
305
+ if (input.cause === "unresolved-major-candidate" && input.mode !== "human-action-required") {
306
+ issues.push(`${prefix}.unresolved-major-candidate requires human-action-required mode`);
307
+ }
308
+ if (input.cause !== "unresolved-major-candidate" && input.mode !== "refresh-required") {
309
+ issues.push(`${prefix}.${input.cause} requires refresh-required mode`);
310
+ }
311
+ if (input.mode === "refresh-required" && !input.acceptedChange) {
312
+ issues.push(`${prefix}.refresh-required requires acceptedChange`);
313
+ }
314
+ if (input.mode === "human-action-required" && input.acceptedChange) {
315
+ issues.push(`${prefix}.human-action-required forbids acceptedChange`);
316
+ }
317
+ return issues;
318
+ }
319
+
320
+ /** Shape and canonical order of a per-capability major-change breakdown (#264). */
321
+ export function architectureCapabilityChangesIssues(input: readonly ArchitectureCapabilityChangeV1[], prefix = "capabilities"): string[] {
322
+ const issues = sortedUniqueIssues(`${prefix}.capabilityId`, input.map((entry) => entry.capabilityId));
323
+ if (input.length === 0) issues.push(`${prefix} must name at least one capability`);
324
+ const reasons = new Set<string>(ARCHITECTURE_MAJOR_CHANGE_REASON_CODES);
325
+ const facets = new Set<string>(ARCHITECTURE_SEMANTIC_FACETS);
326
+ for (const [index, entry] of input.entries()) {
327
+ const entryPrefix = `${prefix}[${index}]`;
328
+ if (typeof entry.capabilityId !== "string" || entry.capabilityId.trim() === "") issues.push(`${entryPrefix}.capabilityId must not be empty`);
329
+ issues.push(
330
+ ...sortedUniqueIssues(`${entryPrefix}.reasonCodes`, entry.reasonCodes),
331
+ ...sortedUniqueIssues(`${entryPrefix}.changedFacets`, entry.changedFacets)
332
+ );
333
+ const reason = entry.reasonCodes.find((code) => !reasons.has(code));
334
+ if (reason !== undefined) issues.push(`${entryPrefix}.reasonCodes contains unsupported reason: ${reason}`);
335
+ const facet = entry.changedFacets.find((name) => !facets.has(name));
336
+ if (facet !== undefined) issues.push(`${entryPrefix}.changedFacets contains unsupported facet: ${facet}`);
337
+ for (const field of ["proofStatusBefore", "proofStatusAfter"] as const) {
338
+ const status = entry[field];
339
+ if (status !== null && !isArchitectureCapabilityProofStatus(status)) issues.push(`${entryPrefix}.${field} must be null or a P1/P2 proof status`);
340
+ }
341
+ if (entry.proofStatusBefore === null && entry.proofStatusAfter === null) issues.push(`${entryPrefix} must exist before or after the change`);
342
+ if ((entry.proofStatusBefore === null || entry.proofStatusAfter === null) && entry.changedFacets.length > 0) {
343
+ issues.push(`${entryPrefix}.changedFacets must be empty for a capability present on one side only`);
344
+ }
345
+ }
346
+ return issues;
347
+ }
348
+
349
+ export function isArchitectureCapabilityProofStatus(value: unknown): value is ArchitectureCapabilityProofStatusV1 {
350
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
351
+ const record = value as Record<string, unknown>;
352
+ return Object.keys(record).length === 2
353
+ && (ARCHITECTURE_PROOF_P1_STATUSES as readonly unknown[]).includes(record.p1)
354
+ && (ARCHITECTURE_PROOF_P2_STATUSES as readonly unknown[]).includes(record.p2);
355
+ }
@@ -0,0 +1,181 @@
1
+ import { buildCapabilitiesSchemaDocument } from "./cli-read";
2
+ import {
3
+ AGENT_CONTEXT_RENDERER_VERSION,
4
+ ARCHCTX_CAPABILITIES_SCHEMA_VERSION,
5
+ ARCHCTX_FEATURES,
6
+ ARCHITECTURE_DOCS_RENDERER_VERSION,
7
+ ARCHITECTURE_FLOW_SELECTOR_CHECK_SCHEMA_VERSION,
8
+ ARCHITECTURE_FLOW_SELECTOR_PROOF_STATUSES,
9
+ ARCHITECTURE_PROOF_P2_STATUSES,
10
+ ARCHITECTURE_REFRESH_SIGNAL_SCHEMA_VERSION,
11
+ PROJECTION_REQUEST_SCHEMA_VERSION,
12
+ PROJECTION_RESULT_SCHEMA_VERSION,
13
+ PROJECTION_SLICE_SCHEMA_VERSION,
14
+ type ArchitectureFlowSelectorSiteV1
15
+ } from "./projection-constants";
16
+ import type { ProjectionSliceCapabilityV1, ProjectionSliceEntrypointV1 } from "./projection-types";
17
+ import type { ArchctxCapabilitiesV1 } from "./projection-apply-types";
18
+ import {
19
+ Const,
20
+ CountSchema,
21
+ GitOidSchema,
22
+ NonEmptyStringSchema,
23
+ NullableType,
24
+ PositiveIntSchema,
25
+ RawEnum,
26
+ Ref,
27
+ SchemaDocument,
28
+ StrictObject,
29
+ Type
30
+ } from "./schema-kit";
31
+
32
+ export function archctxCapabilities(packageVersion: string): ArchctxCapabilitiesV1 {
33
+ return {
34
+ schemaVersion: ARCHCTX_CAPABILITIES_SCHEMA_VERSION,
35
+ package: { name: "archctx", version: packageVersion },
36
+ protocols: {
37
+ projectionRequest: PROJECTION_REQUEST_SCHEMA_VERSION,
38
+ projectionResult: PROJECTION_RESULT_SCHEMA_VERSION,
39
+ architectureRefreshSignal: ARCHITECTURE_REFRESH_SIGNAL_SCHEMA_VERSION
40
+ },
41
+ renderers: {
42
+ architectureDocs: ARCHITECTURE_DOCS_RENDERER_VERSION,
43
+ agentContext: AGENT_CONTEXT_RENDERER_VERSION
44
+ },
45
+ features: [...ARCHCTX_FEATURES]
46
+ };
47
+ }
48
+
49
+ export const ArchctxCapabilitiesSchema = buildCapabilitiesSchemaDocument({
50
+ projectionRequest: PROJECTION_REQUEST_SCHEMA_VERSION,
51
+ projectionResult: PROJECTION_RESULT_SCHEMA_VERSION,
52
+ architectureRefreshSignal: ARCHITECTURE_REFRESH_SIGNAL_SCHEMA_VERSION,
53
+ architectureDocsRenderer: ARCHITECTURE_DOCS_RENDERER_VERSION,
54
+ agentContextRenderer: AGENT_CONTEXT_RENDERER_VERSION,
55
+ featureExamples: ARCHCTX_FEATURES
56
+ });
57
+
58
+ const FlowSelectorSitesDefSchema = Type.Array(
59
+ StrictObject({
60
+ path: NonEmptyStringSchema,
61
+ line: Type.Optional(PositiveIntSchema)
62
+ })
63
+ );
64
+
65
+ export const ArchitectureFlowSelectorCheckSchema = SchemaDocument({
66
+ $id: "https://archcontext.dev/schemas/runtime/flow-selector-check.schema.json",
67
+ title: "ArchitectureFlowSelectorCheckV1",
68
+ description:
69
+ "The data of `archctx flows check`: the P2 flow proof of every capability that declares a flow, and the proof status of every declared entrypoint-to-sink selector, computed without rendering. Consumers detect it through the flow-selector-check-v1 capability.",
70
+ schema: StrictObject({
71
+ schemaVersion: Const(ARCHITECTURE_FLOW_SELECTOR_CHECK_SCHEMA_VERSION),
72
+ ok: Type.Boolean({
73
+ description: "True when no capability that declares a flow has an unprovable P2 proof."
74
+ }),
75
+ codeGraph: StrictObject({
76
+ availability: RawEnum(["ready", "unavailable"] as const),
77
+ version: NonEmptyStringSchema
78
+ }),
79
+ summary: StrictObject({
80
+ selectors: CountSchema,
81
+ proven: CountSchema,
82
+ unproven: CountSchema,
83
+ usedUnproven: Type.Integer({
84
+ minimum: 0,
85
+ description: "Unproven selectors that a required-flow step names."
86
+ })
87
+ }),
88
+ selectors: Type.Array(
89
+ StrictObject({
90
+ nodeId: NonEmptyStringSchema,
91
+ entrypointId: NonEmptyStringSchema,
92
+ sourcePath: NonEmptyStringSchema,
93
+ sourceSymbol: NonEmptyStringSchema,
94
+ sinkId: NonEmptyStringSchema,
95
+ sinkPath: NonEmptyStringSchema,
96
+ sinkSymbol: NonEmptyStringSchema,
97
+ status: RawEnum(ARCHITECTURE_FLOW_SELECTOR_PROOF_STATUSES, {
98
+ description: "Only proven binds a flow step."
99
+ }),
100
+ callSites: Ref<ArchitectureFlowSelectorSiteV1[]>("#/$defs/sites"),
101
+ referenceSites: Ref<ArchitectureFlowSelectorSiteV1[]>("#/$defs/sites"),
102
+ rejectedBuiltinCallSites: Ref<ArchitectureFlowSelectorSiteV1[]>("#/$defs/sites"),
103
+ flowSteps: Type.Array(
104
+ StrictObject({
105
+ flowId: NonEmptyStringSchema,
106
+ stepId: NonEmptyStringSchema
107
+ })
108
+ )
109
+ })
110
+ ),
111
+ capabilities: Type.Array(
112
+ StrictObject({
113
+ capabilityId: NonEmptyStringSchema,
114
+ p2Status: RawEnum(ARCHITECTURE_PROOF_P2_STATUSES),
115
+ diagnostics: Type.Array(
116
+ StrictObject({
117
+ code: NonEmptyStringSchema,
118
+ flowId: Type.Optional(NonEmptyStringSchema),
119
+ stepId: Type.Optional(NonEmptyStringSchema),
120
+ detail: Type.String()
121
+ })
122
+ )
123
+ })
124
+ )
125
+ }),
126
+ $defs: {
127
+ sites: FlowSelectorSitesDefSchema
128
+ }
129
+ });
130
+
131
+ const ProjectionSliceEntrypointDefSchema = StrictObject({
132
+ nodeId: Ref<string>("#/$defs/nonEmpty"),
133
+ entrypointId: Ref<string>("#/$defs/nonEmpty"),
134
+ path: Ref<string>("#/$defs/nonEmpty"),
135
+ symbol: Ref<string>("#/$defs/nonEmpty")
136
+ });
137
+
138
+ const ProjectionSliceCapabilityDefSchema = StrictObject({
139
+ capabilityId: Ref<string>("#/$defs/nonEmpty"),
140
+ modulePath: Ref<string>("#/$defs/nonEmpty"),
141
+ diagramMermaid: NullableType("string", {
142
+ minLength: 1,
143
+ description: "Unfenced Mermaid or null when the capability was removed or its P1 diagram is unprovable."
144
+ }),
145
+ entrypoints: Type.Array(Ref<ProjectionSliceEntrypointV1>("#/$defs/entrypoint")),
146
+ markdown: Ref<string>("#/$defs/nonEmpty")
147
+ });
148
+
149
+ export const ProjectionSliceSchema = SchemaDocument({
150
+ $id: "https://archcontext.dev/schemas/runtime/projection-slice.schema.json",
151
+ title: "ProjectionSliceV1",
152
+ description:
153
+ "Read-only pull request projection of capability diagrams and entrypoint anchors from the same merge base and HEAD used to select changed paths.",
154
+ schema: StrictObject(
155
+ {
156
+ schemaVersion: Const(PROJECTION_SLICE_SCHEMA_VERSION),
157
+ base: Ref<string>("#/$defs/nonEmpty"),
158
+ baseSha: Ref<string>("#/$defs/sha"),
159
+ mergeBase: Ref<string>("#/$defs/sha"),
160
+ headSha: Ref<string>("#/$defs/sha"),
161
+ changedPaths: Type.Array(Ref<string>("#/$defs/nonEmpty"), {
162
+ uniqueItems: true,
163
+ description: "Sorted union of paths changed between the merge base and HEAD and explicit changed path overrides."
164
+ }),
165
+ changed: Type.Boolean(),
166
+ affectedCapabilities: Type.Array(Ref<ProjectionSliceCapabilityV1>("#/$defs/capability")),
167
+ markdown: Ref<string>("#/$defs/nonEmpty")
168
+ },
169
+ {
170
+ if: { properties: { changed: { const: true } } },
171
+ then: { properties: { affectedCapabilities: { minItems: 1 } } },
172
+ else: { properties: { affectedCapabilities: { maxItems: 0 } } }
173
+ }
174
+ ),
175
+ $defs: {
176
+ sha: GitOidSchema,
177
+ nonEmpty: NonEmptyStringSchema,
178
+ capability: ProjectionSliceCapabilityDefSchema,
179
+ entrypoint: ProjectionSliceEntrypointDefSchema
180
+ }
181
+ });